From 42d740eb7e18cf93adbefe930700e4a86851b111 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20=C5=A0pa=C4=8Dek?= Date: Tue, 5 Nov 2024 04:23:11 +0100 Subject: [PATCH] Update OpenPGP.js to 6.0.0 https://github.com/openpgpjs/openpgpjs/releases/tag/v6.0.0 --- app/node_modules/.package-lock.json | 50 +- app/node_modules/asn1.js/.eslintrc.js | 27 - app/node_modules/asn1.js/LICENSE | 21 - app/node_modules/asn1.js/README.md | 100 - app/node_modules/asn1.js/lib/asn1.js | 11 - app/node_modules/asn1.js/lib/asn1/api.js | 57 - .../asn1.js/lib/asn1/base/buffer.js | 153 - .../asn1.js/lib/asn1/base/index.js | 8 - .../asn1.js/lib/asn1/base/node.js | 638 - .../asn1.js/lib/asn1/base/reporter.js | 123 - .../asn1.js/lib/asn1/constants/der.js | 58 - .../asn1.js/lib/asn1/constants/index.js | 21 - .../asn1.js/lib/asn1/decoders/der.js | 335 - .../asn1.js/lib/asn1/decoders/index.js | 6 - .../asn1.js/lib/asn1/decoders/pem.js | 51 - .../asn1.js/lib/asn1/encoders/der.js | 295 - .../asn1.js/lib/asn1/encoders/index.js | 6 - .../asn1.js/lib/asn1/encoders/pem.js | 23 - app/node_modules/asn1.js/package.json | 36 - app/node_modules/bn.js/LICENSE | 19 - app/node_modules/bn.js/README.md | 200 - app/node_modules/bn.js/lib/bn.js | 3446 - app/node_modules/bn.js/package.json | 36 - app/node_modules/inherits/LICENSE | 16 - app/node_modules/inherits/README.md | 42 - app/node_modules/inherits/inherits.js | 9 - app/node_modules/inherits/inherits_browser.js | 27 - app/node_modules/inherits/package.json | 29 - app/node_modules/minimalistic-assert/LICENSE | 13 - app/node_modules/minimalistic-assert/index.js | 11 - .../minimalistic-assert/package.json | 19 - .../minimalistic-assert/readme.md | 4 - app/node_modules/openpgp/README.md | 108 +- .../openpgp/dist/lightweight/argon2id.min.mjs | 3 + .../dist/lightweight/argon2id.min.mjs.map | 1 + .../openpgp/dist/lightweight/argon2id.mjs | 683 + .../dist/lightweight/bn.interface.min.mjs | 3 - .../dist/lightweight/bn.interface.min.mjs.map | 1 - .../openpgp/dist/lightweight/bn.interface.mjs | 340 - .../openpgp/dist/lightweight/bn.min.mjs | 3 - .../openpgp/dist/lightweight/bn.min.mjs.map | 1 - .../openpgp/dist/lightweight/bn.mjs | 3434 - .../openpgp/dist/lightweight/elliptic.min.mjs | 3 - .../dist/lightweight/elliptic.min.mjs.map | 1 - .../openpgp/dist/lightweight/elliptic.mjs | 4313 -- .../dist/lightweight/legacy_ciphers.min.mjs | 3 + .../lightweight/legacy_ciphers.min.mjs.map | 1 + .../dist/lightweight/legacy_ciphers.mjs | 1784 + .../dist/lightweight/noble_curves.min.mjs | 14 + .../dist/lightweight/noble_curves.min.mjs.map | 1 + .../openpgp/dist/lightweight/noble_curves.mjs | 2994 + .../dist/lightweight/noble_hashes.min.mjs | 3 + .../dist/lightweight/noble_hashes.min.mjs.map | 1 + .../openpgp/dist/lightweight/noble_hashes.mjs | 207 + .../openpgp/dist/lightweight/openpgp.min.mjs | 5 +- .../dist/lightweight/openpgp.min.mjs.map | 2 +- .../openpgp/dist/lightweight/openpgp.mjs | 33423 +++----- .../dist/lightweight/ponyfill.es6.min.mjs | 3 - .../dist/lightweight/ponyfill.es6.min.mjs.map | 1 - .../openpgp/dist/lightweight/ponyfill.es6.mjs | 3831 - .../dist/lightweight/seek-bzip.min.mjs | 3 + .../dist/lightweight/seek-bzip.min.mjs.map | 1 + .../openpgp/dist/lightweight/seek-bzip.mjs | 866 + .../openpgp/dist/lightweight/sha3.min.mjs | 4 + .../openpgp/dist/lightweight/sha3.min.mjs.map | 1 + .../openpgp/dist/lightweight/sha3.mjs | 830 + .../lightweight/web-streams-adapter.min.mjs | 17 - .../web-streams-adapter.min.mjs.map | 1 - .../dist/lightweight/web-streams-adapter.mjs | 561 - .../openpgp/dist/node/openpgp.cjs | 28651 +++++++ app/node_modules/openpgp/dist/node/openpgp.js | 44142 ----------- .../openpgp/dist/node/openpgp.min.cjs | 16 + .../openpgp/dist/node/openpgp.min.cjs.map | 1 + .../openpgp/dist/node/openpgp.min.js | 17 - .../openpgp/dist/node/openpgp.min.js.map | 1 - .../openpgp/dist/node/openpgp.min.mjs | 31 +- .../openpgp/dist/node/openpgp.min.mjs.map | 2 +- .../openpgp/dist/node/openpgp.mjs | 63854 ++++++---------- app/node_modules/openpgp/dist/openpgp.js | 63639 ++++++--------- app/node_modules/openpgp/dist/openpgp.min.js | 31 +- .../openpgp/dist/openpgp.min.js.map | 2 +- app/node_modules/openpgp/dist/openpgp.min.mjs | 31 +- .../openpgp/dist/openpgp.min.mjs.map | 2 +- app/node_modules/openpgp/dist/openpgp.mjs | 63628 ++++++--------- .../openpgp/lightweight/package.json | 2 +- app/node_modules/openpgp/openpgp.d.ts | 253 +- app/node_modules/openpgp/package.json | 125 +- app/node_modules/safer-buffer/LICENSE | 21 - .../safer-buffer/Porting-Buffer.md | 268 - app/node_modules/safer-buffer/Readme.md | 156 - app/node_modules/safer-buffer/dangerous.js | 58 - app/node_modules/safer-buffer/package.json | 34 - app/node_modules/safer-buffer/safer.js | 77 - app/node_modules/safer-buffer/tests.js | 406 - app/package-lock.json | 52 +- app/package.json | 2 +- 96 files changed, 120236 insertions(+), 204607 deletions(-) delete mode 100644 app/node_modules/asn1.js/.eslintrc.js delete mode 100644 app/node_modules/asn1.js/LICENSE delete mode 100644 app/node_modules/asn1.js/README.md delete mode 100644 app/node_modules/asn1.js/lib/asn1.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/api.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/base/buffer.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/base/index.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/base/node.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/base/reporter.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/constants/der.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/constants/index.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/decoders/der.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/decoders/index.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/decoders/pem.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/encoders/der.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/encoders/index.js delete mode 100644 app/node_modules/asn1.js/lib/asn1/encoders/pem.js delete mode 100644 app/node_modules/asn1.js/package.json delete mode 100644 app/node_modules/bn.js/LICENSE delete mode 100644 app/node_modules/bn.js/README.md delete mode 100644 app/node_modules/bn.js/lib/bn.js delete mode 100644 app/node_modules/bn.js/package.json delete mode 100644 app/node_modules/inherits/LICENSE delete mode 100644 app/node_modules/inherits/README.md delete mode 100644 app/node_modules/inherits/inherits.js delete mode 100644 app/node_modules/inherits/inherits_browser.js delete mode 100644 app/node_modules/inherits/package.json delete mode 100644 app/node_modules/minimalistic-assert/LICENSE delete mode 100644 app/node_modules/minimalistic-assert/index.js delete mode 100644 app/node_modules/minimalistic-assert/package.json delete mode 100644 app/node_modules/minimalistic-assert/readme.md create mode 100644 app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/argon2id.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs.map delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.interface.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.min.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.min.mjs.map delete mode 100644 app/node_modules/openpgp/dist/lightweight/bn.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/elliptic.min.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/elliptic.min.mjs.map delete mode 100644 app/node_modules/openpgp/dist/lightweight/elliptic.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/legacy_ciphers.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/legacy_ciphers.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/legacy_ciphers.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_curves.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/noble_hashes.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs.map delete mode 100644 app/node_modules/openpgp/dist/lightweight/ponyfill.es6.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/seek-bzip.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/sha3.min.mjs create mode 100644 app/node_modules/openpgp/dist/lightweight/sha3.min.mjs.map create mode 100644 app/node_modules/openpgp/dist/lightweight/sha3.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs delete mode 100644 app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs.map delete mode 100644 app/node_modules/openpgp/dist/lightweight/web-streams-adapter.mjs create mode 100644 app/node_modules/openpgp/dist/node/openpgp.cjs delete mode 100644 app/node_modules/openpgp/dist/node/openpgp.js create mode 100644 app/node_modules/openpgp/dist/node/openpgp.min.cjs create mode 100644 app/node_modules/openpgp/dist/node/openpgp.min.cjs.map delete mode 100644 app/node_modules/openpgp/dist/node/openpgp.min.js delete mode 100644 app/node_modules/openpgp/dist/node/openpgp.min.js.map delete mode 100644 app/node_modules/safer-buffer/LICENSE delete mode 100644 app/node_modules/safer-buffer/Porting-Buffer.md delete mode 100644 app/node_modules/safer-buffer/Readme.md delete mode 100644 app/node_modules/safer-buffer/dangerous.js delete mode 100644 app/node_modules/safer-buffer/package.json delete mode 100644 app/node_modules/safer-buffer/safer.js delete mode 100644 app/node_modules/safer-buffer/tests.js diff --git a/app/node_modules/.package-lock.json b/app/node_modules/.package-lock.json index fa37d66f7..166724919 100644 --- a/app/node_modules/.package-lock.json +++ b/app/node_modules/.package-lock.json @@ -1,61 +1,23 @@ { - "name": "site", + "name": "app", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "license": "MIT", - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "license": "MIT" - }, "node_modules/humbleicons": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/humbleicons/-/humbleicons-1.10.0.tgz", "integrity": "sha512-+9kIQEa5+aJz+0Aw5gm2hShu59ov9gzT1+x0MZGsDdSlsMeabZ91VBav/zogHA6DywvUDUvXRLn0FOeTnfHyeQ==", "license": "MIT" }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "license": "ISC" - }, "node_modules/openpgp": { - "version": "5.11.2", - "resolved": "https://registry.npmjs.org/openpgp/-/openpgp-5.11.2.tgz", - "integrity": "sha512-f8dJFVLwdkvPvW3VPFs6q9Vs2+HNhdvwls7a/MIFcQUB+XiQzRe7alfa3RtwfGJU7oUDDMAWPZ0nYsHa23Az+A==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/openpgp/-/openpgp-6.0.0.tgz", + "integrity": "sha512-8YMuhOV6bP8+J4bCHltvRwol1sBJhxAcJXvwEKpcK65lKpQ0VUbymQR/EuGrzxYnatNSyMyrMgip4j/F0vhZvg==", "license": "LGPL-3.0+", - "dependencies": { - "asn1.js": "^5.0.0" - }, "engines": { - "node": ">= 8.0.0" + "node": ">= 18.0.0" } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" } } } diff --git a/app/node_modules/asn1.js/.eslintrc.js b/app/node_modules/asn1.js/.eslintrc.js deleted file mode 100644 index 6b5dc4460..000000000 --- a/app/node_modules/asn1.js/.eslintrc.js +++ /dev/null @@ -1,27 +0,0 @@ -module.exports = { - 'env': { - 'browser': false, - 'commonjs': true, - 'es6': true, - 'node': true - }, - 'extends': 'eslint:recommended', - 'rules': { - 'indent': [ - 'error', - 2 - ], - 'linebreak-style': [ - 'error', - 'unix' - ], - 'quotes': [ - 'error', - 'single' - ], - 'semi': [ - 'error', - 'always' - ] - } -}; diff --git a/app/node_modules/asn1.js/LICENSE b/app/node_modules/asn1.js/LICENSE deleted file mode 100644 index caaf4f211..000000000 --- a/app/node_modules/asn1.js/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Fedor Indutny - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/app/node_modules/asn1.js/README.md b/app/node_modules/asn1.js/README.md deleted file mode 100644 index 9f04af7e7..000000000 --- a/app/node_modules/asn1.js/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# ASN1.js - -ASN.1 DER Encoder/Decoder and DSL. - -## Example - -Define model: - -```javascript -var asn = require('asn1.js'); - -var Human = asn.define('Human', function() { - this.seq().obj( - this.key('firstName').octstr(), - this.key('lastName').octstr(), - this.key('age').int(), - this.key('gender').enum({ 0: 'male', 1: 'female' }), - this.key('bio').seqof(Bio) - ); -}); - -var Bio = asn.define('Bio', function() { - this.seq().obj( - this.key('time').gentime(), - this.key('description').octstr() - ); -}); -``` - -Encode data: - -```javascript -var output = Human.encode({ - firstName: 'Thomas', - lastName: 'Anderson', - age: 28, - gender: 'male', - bio: [ - { - time: +new Date('31 March 1999'), - description: 'freedom of mind' - } - ] -}, 'der'); -``` - -Decode data: - -```javascript -var human = Human.decode(output, 'der'); -console.log(human); -/* -{ firstName: , - lastName: , - age: 28, - gender: 'male', - bio: - [ { time: 922820400000, - description: } ] } -*/ -``` - -### Partial decode - -Its possible to parse data without stopping on first error. In order to do it, -you should call: - -```javascript -var human = Human.decode(output, 'der', { partial: true }); -console.log(human); -/* -{ result: { ... }, - errors: [ ... ] } -*/ -``` - -#### LICENSE - -This software is licensed under the MIT License. - -Copyright Fedor Indutny, 2017. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/app/node_modules/asn1.js/lib/asn1.js b/app/node_modules/asn1.js/lib/asn1.js deleted file mode 100644 index c7d70b8e3..000000000 --- a/app/node_modules/asn1.js/lib/asn1.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -const asn1 = exports; - -asn1.bignum = require('bn.js'); - -asn1.define = require('./asn1/api').define; -asn1.base = require('./asn1/base'); -asn1.constants = require('./asn1/constants'); -asn1.decoders = require('./asn1/decoders'); -asn1.encoders = require('./asn1/encoders'); diff --git a/app/node_modules/asn1.js/lib/asn1/api.js b/app/node_modules/asn1.js/lib/asn1/api.js deleted file mode 100644 index 61e3eb270..000000000 --- a/app/node_modules/asn1.js/lib/asn1/api.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const encoders = require('./encoders'); -const decoders = require('./decoders'); -const inherits = require('inherits'); - -const api = exports; - -api.define = function define(name, body) { - return new Entity(name, body); -}; - -function Entity(name, body) { - this.name = name; - this.body = body; - - this.decoders = {}; - this.encoders = {}; -} - -Entity.prototype._createNamed = function createNamed(Base) { - const name = this.name; - - function Generated(entity) { - this._initNamed(entity, name); - } - inherits(Generated, Base); - Generated.prototype._initNamed = function _initNamed(entity, name) { - Base.call(this, entity, name); - }; - - return new Generated(this); -}; - -Entity.prototype._getDecoder = function _getDecoder(enc) { - enc = enc || 'der'; - // Lazily create decoder - if (!this.decoders.hasOwnProperty(enc)) - this.decoders[enc] = this._createNamed(decoders[enc]); - return this.decoders[enc]; -}; - -Entity.prototype.decode = function decode(data, enc, options) { - return this._getDecoder(enc).decode(data, options); -}; - -Entity.prototype._getEncoder = function _getEncoder(enc) { - enc = enc || 'der'; - // Lazily create encoder - if (!this.encoders.hasOwnProperty(enc)) - this.encoders[enc] = this._createNamed(encoders[enc]); - return this.encoders[enc]; -}; - -Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { - return this._getEncoder(enc).encode(data, reporter); -}; diff --git a/app/node_modules/asn1.js/lib/asn1/base/buffer.js b/app/node_modules/asn1.js/lib/asn1/base/buffer.js deleted file mode 100644 index bb5bc06e5..000000000 --- a/app/node_modules/asn1.js/lib/asn1/base/buffer.js +++ /dev/null @@ -1,153 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); -const Reporter = require('../base/reporter').Reporter; -const Buffer = require('safer-buffer').Buffer; - -function DecoderBuffer(base, options) { - Reporter.call(this, options); - if (!Buffer.isBuffer(base)) { - this.error('Input not Buffer'); - return; - } - - this.base = base; - this.offset = 0; - this.length = base.length; -} -inherits(DecoderBuffer, Reporter); -exports.DecoderBuffer = DecoderBuffer; - -DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { - if (data instanceof DecoderBuffer) { - return true; - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - Buffer.isBuffer(data.base) && - data.constructor.name === 'DecoderBuffer' && - typeof data.offset === 'number' && - typeof data.length === 'number' && - typeof data.save === 'function' && - typeof data.restore === 'function' && - typeof data.isEmpty === 'function' && - typeof data.readUInt8 === 'function' && - typeof data.skip === 'function' && - typeof data.raw === 'function'; - - return isCompatible; -}; - -DecoderBuffer.prototype.save = function save() { - return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; -}; - -DecoderBuffer.prototype.restore = function restore(save) { - // Return skipped data - const res = new DecoderBuffer(this.base); - res.offset = save.offset; - res.length = this.offset; - - this.offset = save.offset; - Reporter.prototype.restore.call(this, save.reporter); - - return res; -}; - -DecoderBuffer.prototype.isEmpty = function isEmpty() { - return this.offset === this.length; -}; - -DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { - if (this.offset + 1 <= this.length) - return this.base.readUInt8(this.offset++, true); - else - return this.error(fail || 'DecoderBuffer overrun'); -}; - -DecoderBuffer.prototype.skip = function skip(bytes, fail) { - if (!(this.offset + bytes <= this.length)) - return this.error(fail || 'DecoderBuffer overrun'); - - const res = new DecoderBuffer(this.base); - - // Share reporter state - res._reporterState = this._reporterState; - - res.offset = this.offset; - res.length = this.offset + bytes; - this.offset += bytes; - return res; -}; - -DecoderBuffer.prototype.raw = function raw(save) { - return this.base.slice(save ? save.offset : this.offset, this.length); -}; - -function EncoderBuffer(value, reporter) { - if (Array.isArray(value)) { - this.length = 0; - this.value = value.map(function(item) { - if (!EncoderBuffer.isEncoderBuffer(item)) - item = new EncoderBuffer(item, reporter); - this.length += item.length; - return item; - }, this); - } else if (typeof value === 'number') { - if (!(0 <= value && value <= 0xff)) - return reporter.error('non-byte EncoderBuffer value'); - this.value = value; - this.length = 1; - } else if (typeof value === 'string') { - this.value = value; - this.length = Buffer.byteLength(value); - } else if (Buffer.isBuffer(value)) { - this.value = value; - this.length = value.length; - } else { - return reporter.error('Unsupported type: ' + typeof value); - } -} -exports.EncoderBuffer = EncoderBuffer; - -EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { - if (data instanceof EncoderBuffer) { - return true; - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - data.constructor.name === 'EncoderBuffer' && - typeof data.length === 'number' && - typeof data.join === 'function'; - - return isCompatible; -}; - -EncoderBuffer.prototype.join = function join(out, offset) { - if (!out) - out = Buffer.alloc(this.length); - if (!offset) - offset = 0; - - if (this.length === 0) - return out; - - if (Array.isArray(this.value)) { - this.value.forEach(function(item) { - item.join(out, offset); - offset += item.length; - }); - } else { - if (typeof this.value === 'number') - out[offset] = this.value; - else if (typeof this.value === 'string') - out.write(this.value, offset); - else if (Buffer.isBuffer(this.value)) - this.value.copy(out, offset); - offset += this.length; - } - - return out; -}; diff --git a/app/node_modules/asn1.js/lib/asn1/base/index.js b/app/node_modules/asn1.js/lib/asn1/base/index.js deleted file mode 100644 index 8b92f206a..000000000 --- a/app/node_modules/asn1.js/lib/asn1/base/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -const base = exports; - -base.Reporter = require('./reporter').Reporter; -base.DecoderBuffer = require('./buffer').DecoderBuffer; -base.EncoderBuffer = require('./buffer').EncoderBuffer; -base.Node = require('./node'); diff --git a/app/node_modules/asn1.js/lib/asn1/base/node.js b/app/node_modules/asn1.js/lib/asn1/base/node.js deleted file mode 100644 index d676d2137..000000000 --- a/app/node_modules/asn1.js/lib/asn1/base/node.js +++ /dev/null @@ -1,638 +0,0 @@ -'use strict'; - -const Reporter = require('../base/reporter').Reporter; -const EncoderBuffer = require('../base/buffer').EncoderBuffer; -const DecoderBuffer = require('../base/buffer').DecoderBuffer; -const assert = require('minimalistic-assert'); - -// Supported tags -const tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -]; - -// Public methods list -const methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags); - -// Overrided methods list -const overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -]; - -function Node(enc, parent, name) { - const state = {}; - this._baseState = state; - - state.name = name; - state.enc = enc; - - state.parent = parent || null; - state.children = null; - - // State - state.tag = null; - state.args = null; - state.reverseArgs = null; - state.choice = null; - state.optional = false; - state.any = false; - state.obj = false; - state.use = null; - state.useDecoder = null; - state.key = null; - state['default'] = null; - state.explicit = null; - state.implicit = null; - state.contains = null; - - // Should create new instance on each method - if (!state.parent) { - state.children = []; - this._wrap(); - } -} -module.exports = Node; - -const stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -]; - -Node.prototype.clone = function clone() { - const state = this._baseState; - const cstate = {}; - stateProps.forEach(function(prop) { - cstate[prop] = state[prop]; - }); - const res = new this.constructor(cstate.parent); - res._baseState = cstate; - return res; -}; - -Node.prototype._wrap = function wrap() { - const state = this._baseState; - methods.forEach(function(method) { - this[method] = function _wrappedMethod() { - const clone = new this.constructor(this); - state.children.push(clone); - return clone[method].apply(clone, arguments); - }; - }, this); -}; - -Node.prototype._init = function init(body) { - const state = this._baseState; - - assert(state.parent === null); - body.call(this); - - // Filter children - state.children = state.children.filter(function(child) { - return child._baseState.parent === this; - }, this); - assert.equal(state.children.length, 1, 'Root node can have only one child'); -}; - -Node.prototype._useArgs = function useArgs(args) { - const state = this._baseState; - - // Filter children and args - const children = args.filter(function(arg) { - return arg instanceof this.constructor; - }, this); - args = args.filter(function(arg) { - return !(arg instanceof this.constructor); - }, this); - - if (children.length !== 0) { - assert(state.children === null); - state.children = children; - - // Replace parent to maintain backward link - children.forEach(function(child) { - child._baseState.parent = this; - }, this); - } - if (args.length !== 0) { - assert(state.args === null); - state.args = args; - state.reverseArgs = args.map(function(arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) - return arg; - - const res = {}; - Object.keys(arg).forEach(function(key) { - if (key == (key | 0)) - key |= 0; - const value = arg[key]; - res[value] = key; - }); - return res; - }); - } -}; - -// -// Overrided methods -// - -overrided.forEach(function(method) { - Node.prototype[method] = function _overrided() { - const state = this._baseState; - throw new Error(method + ' not implemented for encoding: ' + state.enc); - }; -}); - -// -// Public methods -// - -tags.forEach(function(tag) { - Node.prototype[tag] = function _tagMethod() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); - - assert(state.tag === null); - state.tag = tag; - - this._useArgs(args); - - return this; - }; -}); - -Node.prototype.use = function use(item) { - assert(item); - const state = this._baseState; - - assert(state.use === null); - state.use = item; - - return this; -}; - -Node.prototype.optional = function optional() { - const state = this._baseState; - - state.optional = true; - - return this; -}; - -Node.prototype.def = function def(val) { - const state = this._baseState; - - assert(state['default'] === null); - state['default'] = val; - state.optional = true; - - return this; -}; - -Node.prototype.explicit = function explicit(num) { - const state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.explicit = num; - - return this; -}; - -Node.prototype.implicit = function implicit(num) { - const state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.implicit = num; - - return this; -}; - -Node.prototype.obj = function obj() { - const state = this._baseState; - const args = Array.prototype.slice.call(arguments); - - state.obj = true; - - if (args.length !== 0) - this._useArgs(args); - - return this; -}; - -Node.prototype.key = function key(newKey) { - const state = this._baseState; - - assert(state.key === null); - state.key = newKey; - - return this; -}; - -Node.prototype.any = function any() { - const state = this._baseState; - - state.any = true; - - return this; -}; - -Node.prototype.choice = function choice(obj) { - const state = this._baseState; - - assert(state.choice === null); - state.choice = obj; - this._useArgs(Object.keys(obj).map(function(key) { - return obj[key]; - })); - - return this; -}; - -Node.prototype.contains = function contains(item) { - const state = this._baseState; - - assert(state.use === null); - state.contains = item; - - return this; -}; - -// -// Decoding -// - -Node.prototype._decode = function decode(input, options) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return input.wrapResult(state.children[0]._decode(input, options)); - - let result = state['default']; - let present = true; - - let prevKey = null; - if (state.key !== null) - prevKey = input.enterKey(state.key); - - // Check if tag is there - if (state.optional) { - let tag = null; - if (state.explicit !== null) - tag = state.explicit; - else if (state.implicit !== null) - tag = state.implicit; - else if (state.tag !== null) - tag = state.tag; - - if (tag === null && !state.any) { - // Trial and Error - const save = input.save(); - try { - if (state.choice === null) - this._decodeGeneric(state.tag, input, options); - else - this._decodeChoice(input, options); - present = true; - } catch (e) { - present = false; - } - input.restore(save); - } else { - present = this._peekTag(input, tag, state.any); - - if (input.isError(present)) - return present; - } - } - - // Push object on stack - let prevObj; - if (state.obj && present) - prevObj = input.enterObject(); - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - const explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) - return explicit; - input = explicit; - } - - const start = input.offset; - - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - let save; - if (state.any) - save = input.save(); - const body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ); - if (input.isError(body)) - return body; - - if (state.any) - result = input.raw(save); - else - input = body; - } - - if (options && options.track && state.tag !== null) - options.track(input.path(), start, input.length, 'tagged'); - - if (options && options.track && state.tag !== null) - options.track(input.path(), input.offset, input.length, 'content'); - - // Select proper method for tag - if (state.any) { - // no-op - } else if (state.choice === null) { - result = this._decodeGeneric(state.tag, input, options); - } else { - result = this._decodeChoice(input, options); - } - - if (input.isError(result)) - return result; - - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren(child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options); - }); - } - - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - const data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options); - } - } - - // Pop object - if (state.obj && present) - result = input.leaveObject(prevObj); - - // Set key - if (state.key !== null && (result !== null || present === true)) - input.leaveKey(prevKey, state.key, result); - else if (prevKey !== null) - input.exitKey(prevKey); - - return result; -}; - -Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { - const state = this._baseState; - - if (tag === 'seq' || tag === 'set') - return null; - if (tag === 'seqof' || tag === 'setof') - return this._decodeList(input, tag, state.args[0], options); - else if (/str$/.test(tag)) - return this._decodeStr(input, tag, options); - else if (tag === 'objid' && state.args) - return this._decodeObjid(input, state.args[0], state.args[1], options); - else if (tag === 'objid') - return this._decodeObjid(input, null, null, options); - else if (tag === 'gentime' || tag === 'utctime') - return this._decodeTime(input, tag, options); - else if (tag === 'null_') - return this._decodeNull(input, options); - else if (tag === 'bool') - return this._decodeBool(input, options); - else if (tag === 'objDesc') - return this._decodeStr(input, tag, options); - else if (tag === 'int' || tag === 'enum') - return this._decodeInt(input, state.args && state.args[0], options); - - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options); - } else { - return input.error('unknown tag: ' + tag); - } -}; - -Node.prototype._getUse = function _getUse(entity, obj) { - - const state = this._baseState; - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj); - assert(state.useDecoder._baseState.parent === null); - state.useDecoder = state.useDecoder._baseState.children[0]; - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone(); - state.useDecoder._baseState.implicit = state.implicit; - } - return state.useDecoder; -}; - -Node.prototype._decodeChoice = function decodeChoice(input, options) { - const state = this._baseState; - let result = null; - let match = false; - - Object.keys(state.choice).some(function(key) { - const save = input.save(); - const node = state.choice[key]; - try { - const value = node._decode(input, options); - if (input.isError(value)) - return false; - - result = { type: key, value: value }; - match = true; - } catch (e) { - input.restore(save); - return false; - } - return true; - }, this); - - if (!match) - return input.error('Choice not matched'); - - return result; -}; - -// -// Encoding -// - -Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { - return new EncoderBuffer(data, this.reporter); -}; - -Node.prototype._encode = function encode(data, reporter, parent) { - const state = this._baseState; - if (state['default'] !== null && state['default'] === data) - return; - - const result = this._encodeValue(data, reporter, parent); - if (result === undefined) - return; - - if (this._skipDefault(result, reporter, parent)) - return; - - return result; -}; - -Node.prototype._encodeValue = function encode(data, reporter, parent) { - const state = this._baseState; - - // Decode root node - if (state.parent === null) - return state.children[0]._encode(data, reporter || new Reporter()); - - let result = null; - - // Set reporter to share it with a child class - this.reporter = reporter; - - // Check if data is there - if (state.optional && data === undefined) { - if (state['default'] !== null) - data = state['default']; - else - return; - } - - // Encode children first - let content = null; - let primitive = false; - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data); - } else if (state.choice) { - result = this._encodeChoice(data, reporter); - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter); - primitive = true; - } else if (state.children) { - content = state.children.map(function(child) { - if (child._baseState.tag === 'null_') - return child._encode(null, reporter, data); - - if (child._baseState.key === null) - return reporter.error('Child should have a key'); - const prevKey = reporter.enterKey(child._baseState.key); - - if (typeof data !== 'object') - return reporter.error('Child expected, but input is not object'); - - const res = child._encode(data[child._baseState.key], reporter, data); - reporter.leaveKey(prevKey); - - return res; - }, this).filter(function(child) { - return child; - }); - content = this._createEncoderBuffer(content); - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - // TODO(indutny): this should be thrown on DSL level - if (!(state.args && state.args.length === 1)) - return reporter.error('Too many args for : ' + state.tag); - - if (!Array.isArray(data)) - return reporter.error('seqof/setof, but data is not Array'); - - const child = this.clone(); - child._baseState.implicit = null; - content = this._createEncoderBuffer(data.map(function(item) { - const state = this._baseState; - - return this._getUse(state.args[0], data)._encode(item, reporter); - }, child)); - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter); - } else { - content = this._encodePrimitive(state.tag, data); - primitive = true; - } - } - - // Encode data itself - if (!state.any && state.choice === null) { - const tag = state.implicit !== null ? state.implicit : state.tag; - const cls = state.implicit === null ? 'universal' : 'context'; - - if (tag === null) { - if (state.use === null) - reporter.error('Tag could be omitted only for .use()'); - } else { - if (state.use === null) - result = this._encodeComposite(tag, primitive, cls, content); - } - } - - // Wrap in explicit - if (state.explicit !== null) - result = this._encodeComposite(state.explicit, false, 'context', result); - - return result; -}; - -Node.prototype._encodeChoice = function encodeChoice(data, reporter) { - const state = this._baseState; - - const node = state.choice[data.type]; - if (!node) { - assert( - false, - data.type + ' not found in ' + - JSON.stringify(Object.keys(state.choice))); - } - return node._encode(data.value, reporter); -}; - -Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { - const state = this._baseState; - - if (/str$/.test(tag)) - return this._encodeStr(data, tag); - else if (tag === 'objid' && state.args) - return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - else if (tag === 'objid') - return this._encodeObjid(data, null, null); - else if (tag === 'gentime' || tag === 'utctime') - return this._encodeTime(data, tag); - else if (tag === 'null_') - return this._encodeNull(); - else if (tag === 'int' || tag === 'enum') - return this._encodeInt(data, state.args && state.reverseArgs[0]); - else if (tag === 'bool') - return this._encodeBool(data); - else if (tag === 'objDesc') - return this._encodeStr(data, tag); - else - throw new Error('Unsupported tag: ' + tag); -}; - -Node.prototype._isNumstr = function isNumstr(str) { - return /^[0-9 ]*$/.test(str); -}; - -Node.prototype._isPrintstr = function isPrintstr(str) { - return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); -}; diff --git a/app/node_modules/asn1.js/lib/asn1/base/reporter.js b/app/node_modules/asn1.js/lib/asn1/base/reporter.js deleted file mode 100644 index d05fe12f3..000000000 --- a/app/node_modules/asn1.js/lib/asn1/base/reporter.js +++ /dev/null @@ -1,123 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); - -function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - }; -} -exports.Reporter = Reporter; - -Reporter.prototype.isError = function isError(obj) { - return obj instanceof ReporterError; -}; - -Reporter.prototype.save = function save() { - const state = this._reporterState; - - return { obj: state.obj, pathLen: state.path.length }; -}; - -Reporter.prototype.restore = function restore(data) { - const state = this._reporterState; - - state.obj = data.obj; - state.path = state.path.slice(0, data.pathLen); -}; - -Reporter.prototype.enterKey = function enterKey(key) { - return this._reporterState.path.push(key); -}; - -Reporter.prototype.exitKey = function exitKey(index) { - const state = this._reporterState; - - state.path = state.path.slice(0, index - 1); -}; - -Reporter.prototype.leaveKey = function leaveKey(index, key, value) { - const state = this._reporterState; - - this.exitKey(index); - if (state.obj !== null) - state.obj[key] = value; -}; - -Reporter.prototype.path = function path() { - return this._reporterState.path.join('/'); -}; - -Reporter.prototype.enterObject = function enterObject() { - const state = this._reporterState; - - const prev = state.obj; - state.obj = {}; - return prev; -}; - -Reporter.prototype.leaveObject = function leaveObject(prev) { - const state = this._reporterState; - - const now = state.obj; - state.obj = prev; - return now; -}; - -Reporter.prototype.error = function error(msg) { - let err; - const state = this._reporterState; - - const inherited = msg instanceof ReporterError; - if (inherited) { - err = msg; - } else { - err = new ReporterError(state.path.map(function(elem) { - return '[' + JSON.stringify(elem) + ']'; - }).join(''), msg.message || msg, msg.stack); - } - - if (!state.options.partial) - throw err; - - if (!inherited) - state.errors.push(err); - - return err; -}; - -Reporter.prototype.wrapResult = function wrapResult(result) { - const state = this._reporterState; - if (!state.options.partial) - return result; - - return { - result: this.isError(result) ? null : result, - errors: state.errors - }; -}; - -function ReporterError(path, msg) { - this.path = path; - this.rethrow(msg); -} -inherits(ReporterError, Error); - -ReporterError.prototype.rethrow = function rethrow(msg) { - this.message = msg + ' at: ' + (this.path || '(shallow)'); - if (Error.captureStackTrace) - Error.captureStackTrace(this, ReporterError); - - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; - } - } - return this; -}; diff --git a/app/node_modules/asn1.js/lib/asn1/constants/der.js b/app/node_modules/asn1.js/lib/asn1/constants/der.js deleted file mode 100644 index 2b678aaf3..000000000 --- a/app/node_modules/asn1.js/lib/asn1/constants/der.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -// Helper -function reverse(map) { - const res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - const value = map[key]; - res[value] = key; - }); - - return res; -} - -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -}; -exports.tagClassByName = reverse(exports.tagClass); - -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -}; -exports.tagByName = reverse(exports.tag); diff --git a/app/node_modules/asn1.js/lib/asn1/constants/index.js b/app/node_modules/asn1.js/lib/asn1/constants/index.js deleted file mode 100644 index 632cf3de5..000000000 --- a/app/node_modules/asn1.js/lib/asn1/constants/index.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -const constants = exports; - -// Helper -constants._reverse = function reverse(map) { - const res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - const value = map[key]; - res[value] = key; - }); - - return res; -}; - -constants.der = require('./der'); diff --git a/app/node_modules/asn1.js/lib/asn1/decoders/der.js b/app/node_modules/asn1.js/lib/asn1/decoders/der.js deleted file mode 100644 index c5b0515b7..000000000 --- a/app/node_modules/asn1.js/lib/asn1/decoders/der.js +++ /dev/null @@ -1,335 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); - -const bignum = require('bn.js'); -const DecoderBuffer = require('../base/buffer').DecoderBuffer; -const Node = require('../base/node'); - -// Import DER constants -const der = require('../constants/der'); - -function DERDecoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DERDecoder; - -DERDecoder.prototype.decode = function decode(data, options) { - if (!DecoderBuffer.isDecoderBuffer(data)) { - data = new DecoderBuffer(data, options); - } - - return this.tree._decode(data, options); -}; - -// Tree methods - -function DERNode(parent) { - Node.call(this, 'der', parent); -} -inherits(DERNode, Node); - -DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { - if (buffer.isEmpty()) - return false; - - const state = buffer.save(); - const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - buffer.restore(state); - - return decodedTag.tag === tag || decodedTag.tagStr === tag || - (decodedTag.tagStr + 'of') === tag || any; -}; - -DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { - const decodedTag = derDecodeTag(buffer, - 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - let len = derDecodeLen(buffer, - decodedTag.primitive, - 'Failed to get length of "' + tag + '"'); - - // Failure - if (buffer.isError(len)) - return len; - - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error('Failed to match tag: "' + tag + '"'); - } - - if (decodedTag.primitive || len !== null) - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - - // Indefinite length... find END tag - const state = buffer.save(); - const res = this._skipUntilEnd( - buffer, - 'Failed to skip indefinite length body: "' + this.tag + '"'); - if (buffer.isError(res)) - return res; - - len = buffer.offset - state.offset; - buffer.restore(state); - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); -}; - -DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { - for (;;) { - const tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) - return tag; - const len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) - return len; - - let res; - if (tag.primitive || len !== null) - res = buffer.skip(len); - else - res = this._skipUntilEnd(buffer, fail); - - // Failure - if (buffer.isError(res)) - return res; - - if (tag.tagStr === 'end') - break; - } -}; - -DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, - options) { - const result = []; - while (!buffer.isEmpty()) { - const possibleEnd = this._peekTag(buffer, 'end'); - if (buffer.isError(possibleEnd)) - return possibleEnd; - - const res = decoder.decode(buffer, 'der', options); - if (buffer.isError(res) && possibleEnd) - break; - result.push(res); - } - return result; -}; - -DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { - if (tag === 'bitstr') { - const unused = buffer.readUInt8(); - if (buffer.isError(unused)) - return unused; - return { unused: unused, data: buffer.raw() }; - } else if (tag === 'bmpstr') { - const raw = buffer.raw(); - if (raw.length % 2 === 1) - return buffer.error('Decoding of string type: bmpstr length mismatch'); - - let str = ''; - for (let i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)); - } - return str; - } else if (tag === 'numstr') { - const numstr = buffer.raw().toString('ascii'); - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: ' + - 'numstr unsupported characters'); - } - return numstr; - } else if (tag === 'octstr') { - return buffer.raw(); - } else if (tag === 'objDesc') { - return buffer.raw(); - } else if (tag === 'printstr') { - const printstr = buffer.raw().toString('ascii'); - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: ' + - 'printstr unsupported characters'); - } - return printstr; - } else if (/str$/.test(tag)) { - return buffer.raw().toString(); - } else { - return buffer.error('Decoding of string type: ' + tag + ' unsupported'); - } -}; - -DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { - let result; - const identifiers = []; - let ident = 0; - let subident = 0; - while (!buffer.isEmpty()) { - subident = buffer.readUInt8(); - ident <<= 7; - ident |= subident & 0x7f; - if ((subident & 0x80) === 0) { - identifiers.push(ident); - ident = 0; - } - } - if (subident & 0x80) - identifiers.push(ident); - - const first = (identifiers[0] / 40) | 0; - const second = identifiers[0] % 40; - - if (relative) - result = identifiers; - else - result = [first, second].concat(identifiers.slice(1)); - - if (values) { - let tmp = values[result.join(' ')]; - if (tmp === undefined) - tmp = values[result.join('.')]; - if (tmp !== undefined) - result = tmp; - } - - return result; -}; - -DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { - const str = buffer.raw().toString(); - - let year; - let mon; - let day; - let hour; - let min; - let sec; - if (tag === 'gentime') { - year = str.slice(0, 4) | 0; - mon = str.slice(4, 6) | 0; - day = str.slice(6, 8) | 0; - hour = str.slice(8, 10) | 0; - min = str.slice(10, 12) | 0; - sec = str.slice(12, 14) | 0; - } else if (tag === 'utctime') { - year = str.slice(0, 2) | 0; - mon = str.slice(2, 4) | 0; - day = str.slice(4, 6) | 0; - hour = str.slice(6, 8) | 0; - min = str.slice(8, 10) | 0; - sec = str.slice(10, 12) | 0; - if (year < 70) - year = 2000 + year; - else - year = 1900 + year; - } else { - return buffer.error('Decoding ' + tag + ' time is not supported yet'); - } - - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); -}; - -DERNode.prototype._decodeNull = function decodeNull() { - return null; -}; - -DERNode.prototype._decodeBool = function decodeBool(buffer) { - const res = buffer.readUInt8(); - if (buffer.isError(res)) - return res; - else - return res !== 0; -}; - -DERNode.prototype._decodeInt = function decodeInt(buffer, values) { - // Bigint, return as it is (assume big endian) - const raw = buffer.raw(); - let res = new bignum(raw); - - if (values) - res = values[res.toString(10)] || res; - - return res; -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getDecoder('der').tree; -}; - -// Utility methods - -function derDecodeTag(buf, fail) { - let tag = buf.readUInt8(fail); - if (buf.isError(tag)) - return tag; - - const cls = der.tagClass[tag >> 6]; - const primitive = (tag & 0x20) === 0; - - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - let oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; - - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; - } - const tagStr = der.tag[tag]; - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} - -function derDecodeLen(buf, primitive, fail) { - let len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; - - // Indefinite form - if (!primitive && len === 0x80) - return null; - - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } - - // Long form - const num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); - - len = 0; - for (let i = 0; i < num; i++) { - len <<= 8; - const j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; - } - - return len; -} diff --git a/app/node_modules/asn1.js/lib/asn1/decoders/index.js b/app/node_modules/asn1.js/lib/asn1/decoders/index.js deleted file mode 100644 index 14fb05aea..000000000 --- a/app/node_modules/asn1.js/lib/asn1/decoders/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const decoders = exports; - -decoders.der = require('./der'); -decoders.pem = require('./pem'); diff --git a/app/node_modules/asn1.js/lib/asn1/decoders/pem.js b/app/node_modules/asn1.js/lib/asn1/decoders/pem.js deleted file mode 100644 index 2b050ef6d..000000000 --- a/app/node_modules/asn1.js/lib/asn1/decoders/pem.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('safer-buffer').Buffer; - -const DERDecoder = require('./der'); - -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; - -PEMDecoder.prototype.decode = function decode(data, options) { - const lines = data.toString().split(/[\r\n]+/g); - - const label = options.label.toUpperCase(); - - const re = /^-----(BEGIN|END) ([^-]+)-----$/; - let start = -1; - let end = -1; - for (let i = 0; i < lines.length; i++) { - const match = lines[i].match(re); - if (match === null) - continue; - - if (match[2] !== label) - continue; - - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); - - const base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9+/=]+/gi, ''); - - const input = Buffer.from(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); -}; diff --git a/app/node_modules/asn1.js/lib/asn1/encoders/der.js b/app/node_modules/asn1.js/lib/asn1/encoders/der.js deleted file mode 100644 index 55eb43591..000000000 --- a/app/node_modules/asn1.js/lib/asn1/encoders/der.js +++ /dev/null @@ -1,295 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('safer-buffer').Buffer; -const Node = require('../base/node'); - -// Import DER constants -const der = require('../constants/der'); - -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DEREncoder; - -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; - -// Tree methods - -function DERNode(parent) { - Node.call(this, 'der', parent); -} -inherits(DERNode, Node); - -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - const encodedTag = encodeTag(tag, primitive, cls, this.reporter); - - // Short form - if (content.length < 0x80) { - const header = Buffer.alloc(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } - - // Long form - // Count octets required to store length - let lenOctets = 1; - for (let i = content.length; i >= 0x100; i >>= 8) - lenOctets++; - - const header = Buffer.alloc(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; - - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; - - return this._createEncoderBuffer([ header, content ]); -}; - -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - const buf = Buffer.alloc(str.length * 2); - for (let i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } -}; - -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s.]+/g); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } - - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } - - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } - - // Count number of octets - let size = 0; - for (let i = 0; i < id.length; i++) { - let ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } - - const objid = Buffer.alloc(size); - let offset = objid.length - 1; - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } - - return this._createEncoderBuffer(objid); -}; - -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} - -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - let str; - const date = new Date(time); - - if (tag === 'gentime') { - str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); -}; - -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - const numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = Buffer.from(numArray); - } - - if (Buffer.isBuffer(num)) { - let size = num.length; - if (num.length === 0) - size++; - - const out = Buffer.alloc(size); - num.copy(out); - if (num.length === 0) - out[0] = 0; - return this._createEncoderBuffer(out); - } - - if (num < 0x80) - return this._createEncoderBuffer(num); - - if (num < 0x100) - return this._createEncoderBuffer([0, num]); - - let size = 1; - for (let i = num; i >= 0x100; i >>= 8) - size++; - - const out = new Array(size); - for (let i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); - } - - return this._createEncoderBuffer(Buffer.from(out)); -}; - -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; - -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { - const state = this._baseState; - let i; - if (state['default'] === null) - return false; - - const data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - - if (data.length !== state.defaultBuffer.length) - return false; - - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; - - return true; -}; - -// Utility methods - -function encodeTag(tag, primitive, cls, reporter) { - let res; - - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; - - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); - - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); - - if (!primitive) - res |= 0x20; - - res |= (der.tagClassByName[cls || 'universal'] << 6); - - return res; -} diff --git a/app/node_modules/asn1.js/lib/asn1/encoders/index.js b/app/node_modules/asn1.js/lib/asn1/encoders/index.js deleted file mode 100644 index bb8ea34d5..000000000 --- a/app/node_modules/asn1.js/lib/asn1/encoders/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const encoders = exports; - -encoders.der = require('./der'); -encoders.pem = require('./pem'); diff --git a/app/node_modules/asn1.js/lib/asn1/encoders/pem.js b/app/node_modules/asn1.js/lib/asn1/encoders/pem.js deleted file mode 100644 index 77fbdb47b..000000000 --- a/app/node_modules/asn1.js/lib/asn1/encoders/pem.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const inherits = require('inherits'); - -const DEREncoder = require('./der'); - -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; - -PEMEncoder.prototype.encode = function encode(data, options) { - const buf = DEREncoder.prototype.encode.call(this, data); - - const p = buf.toString('base64'); - const out = [ '-----BEGIN ' + options.label + '-----' ]; - for (let i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); -}; diff --git a/app/node_modules/asn1.js/package.json b/app/node_modules/asn1.js/package.json deleted file mode 100644 index 7b7d0530e..000000000 --- a/app/node_modules/asn1.js/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "asn1.js", - "version": "5.4.1", - "description": "ASN.1 encoder and decoder", - "main": "lib/asn1.js", - "scripts": { - "lint-2560": "eslint --fix rfc/2560/*.js rfc/2560/test/*.js", - "lint-5280": "eslint --fix rfc/5280/*.js rfc/5280/test/*.js", - "lint": "eslint --fix lib/*.js lib/**/*.js lib/**/**/*.js && npm run lint-2560 && npm run lint-5280", - "test": "mocha --reporter spec test/*-test.js && cd rfc/2560 && npm i && npm test && cd ../../rfc/5280 && npm i && npm test && cd ../../ && npm run lint" - }, - "repository": { - "type": "git", - "url": "git@github.com:indutny/asn1.js" - }, - "keywords": [ - "asn.1", - "der" - ], - "author": "Fedor Indutny", - "license": "MIT", - "bugs": { - "url": "https://github.com/indutny/asn1.js/issues" - }, - "homepage": "https://github.com/indutny/asn1.js", - "devDependencies": { - "eslint": "^4.10.0", - "mocha": "^7.0.0" - }, - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } -} diff --git a/app/node_modules/bn.js/LICENSE b/app/node_modules/bn.js/LICENSE deleted file mode 100644 index c328f0401..000000000 --- a/app/node_modules/bn.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Fedor Indutny, 2015. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/app/node_modules/bn.js/README.md b/app/node_modules/bn.js/README.md deleted file mode 100644 index aecc3ba0f..000000000 --- a/app/node_modules/bn.js/README.md +++ /dev/null @@ -1,200 +0,0 @@ -# bn.js - -> BigNum in pure javascript - -[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) - -## Install -`npm install --save bn.js` - -## Usage - -```js -const BN = require('bn.js'); - -var a = new BN('dead', 16); -var b = new BN('101010', 2); - -var res = a.add(b); -console.log(res.toString(10)); // 57047 -``` - -**Note**: decimals are not supported in this library. - -## Notation - -### Prefixes - -There are several prefixes to instructions that affect the way the work. Here -is the list of them in the order of appearance in the function name: - -* `i` - perform operation in-place, storing the result in the host object (on - which the method was invoked). Might be used to avoid number allocation costs -* `u` - unsigned, ignore the sign of operands when performing operation, or - always return positive value. Second case applies to reduction operations - like `mod()`. In such cases if the result will be negative - modulo will be - added to the result to make it positive - -### Postfixes - -The only available postfix at the moment is: - -* `n` - which means that the argument of the function must be a plain JavaScript - Number. Decimals are not supported. - -### Examples - -* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` -* `a.umod(b)` - reduce `a` modulo `b`, returning positive value -* `a.iushln(13)` - shift bits of `a` left by 13 - -## Instructions - -Prefixes/postfixes are put in parens at the of the line. `endian` - could be -either `le` (little-endian) or `be` (big-endian). - -### Utilities - -* `a.clone()` - clone number -* `a.toString(base, length)` - convert to base-string and pad with zeroes -* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) -* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) -* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero - pad to length, throwing if already exceeding -* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, - which must behave like an `Array` -* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For - compatibility with browserify and similar tools, use this instead: - `a.toArrayLike(Buffer, endian, length)` -* `a.bitLength()` - get number of bits occupied -* `a.zeroBits()` - return number of less-significant consequent zero bits - (example: `1010000` has 4 zero bits) -* `a.byteLength()` - return number of bytes occupied -* `a.isNeg()` - true if the number is negative -* `a.isEven()` - no comments -* `a.isOdd()` - no comments -* `a.isZero()` - no comments -* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) - depending on the comparison result (`ucmp`, `cmpn`) -* `a.lt(b)` - `a` less than `b` (`n`) -* `a.lte(b)` - `a` less than or equals `b` (`n`) -* `a.gt(b)` - `a` greater than `b` (`n`) -* `a.gte(b)` - `a` greater than or equals `b` (`n`) -* `a.eq(b)` - `a` equals `b` (`n`) -* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width -* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width -* `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance - -### Arithmetics - -* `a.neg()` - negate sign (`i`) -* `a.abs()` - absolute value (`i`) -* `a.add(b)` - addition (`i`, `n`, `in`) -* `a.sub(b)` - subtraction (`i`, `n`, `in`) -* `a.mul(b)` - multiply (`i`, `n`, `in`) -* `a.sqr()` - square (`i`) -* `a.pow(b)` - raise `a` to the power of `b` -* `a.div(b)` - divide (`divn`, `idivn`) -* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) -* `a.divRound(b)` - rounded division - -### Bit operations - -* `a.or(b)` - or (`i`, `u`, `iu`) -* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced - with `andn` in future) -* `a.xor(b)` - xor (`i`, `u`, `iu`) -* `a.setn(b)` - set specified bit to `1` -* `a.shln(b)` - shift left (`i`, `u`, `iu`) -* `a.shrn(b)` - shift right (`i`, `u`, `iu`) -* `a.testn(b)` - test if specified bit is set -* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) -* `a.bincn(b)` - add `1 << b` to the number -* `a.notn(w)` - not (for the width specified by `w`) (`i`) - -### Reduction - -* `a.gcd(b)` - GCD -* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) -* `a.invm(b)` - inverse `a` modulo `b` - -## Fast reduction - -When doing lots of reductions using the same modulo, it might be beneficial to -use some tricks: like [Montgomery multiplication][0], or using special algorithm -for [Mersenne Prime][1]. - -### Reduction context - -To enable this tricks one should create a reduction context: - -```js -var red = BN.red(num); -``` -where `num` is just a BN instance. - -Or: - -```js -var red = BN.red(primeName); -``` - -Where `primeName` is either of these [Mersenne Primes][1]: - -* `'k256'` -* `'p224'` -* `'p192'` -* `'p25519'` - -Or: - -```js -var red = BN.mont(num); -``` - -To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than -`.red(num)`, but slower than `BN.red(primeName)`. - -### Converting numbers - -Before performing anything in reduction context - numbers should be converted -to it. Usually, this means that one should: - -* Convert inputs to reducted ones -* Operate on them in reduction context -* Convert outputs back from the reduction context - -Here is how one may convert numbers to `red`: - -```js -var redA = a.toRed(red); -``` -Where `red` is a reduction context created using instructions above - -Here is how to convert them back: - -```js -var a = redA.fromRed(); -``` - -### Red instructions - -Most of the instructions from the very start of this readme have their -counterparts in red context: - -* `a.redAdd(b)`, `a.redIAdd(b)` -* `a.redSub(b)`, `a.redISub(b)` -* `a.redShl(num)` -* `a.redMul(b)`, `a.redIMul(b)` -* `a.redSqr()`, `a.redISqr()` -* `a.redSqrt()` - square root modulo reduction context's prime -* `a.redInvm()` - modular inverse of the number -* `a.redNeg()` -* `a.redPow(b)` - modular exponentiation - -## LICENSE - -This software is licensed under the MIT License. - -[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication -[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/app/node_modules/bn.js/lib/bn.js b/app/node_modules/bn.js/lib/bn.js deleted file mode 100644 index 3a4371ea2..000000000 --- a/app/node_modules/bn.js/lib/bn.js +++ /dev/null @@ -1,3446 +0,0 @@ -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require('buffer').Buffer; - } - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } - - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // 'A' - 'F' - if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - // '0' - '9' - } else { - return (c - 48) & 0xf; - } - } - - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - // 24-bits chunks - var off = 0; - var j = 0; - - var w; - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } - - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this.strip(); - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is BN v4 instance - r.strip(); - } else { - // r is BN v5 instance - r._strip(); - } - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(typeof module === 'undefined' || module, this); diff --git a/app/node_modules/bn.js/package.json b/app/node_modules/bn.js/package.json deleted file mode 100644 index 098b805f9..000000000 --- a/app/node_modules/bn.js/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "bn.js", - "version": "4.12.0", - "description": "Big number implementation in pure javascript", - "main": "lib/bn.js", - "scripts": { - "lint": "semistandard", - "unit": "mocha --reporter=spec test/*-test.js", - "test": "npm run lint && npm run unit" - }, - "repository": { - "type": "git", - "url": "git@github.com:indutny/bn.js" - }, - "keywords": [ - "BN", - "BigNum", - "Big number", - "Modulo", - "Montgomery" - ], - "author": "Fedor Indutny ", - "license": "MIT", - "bugs": { - "url": "https://github.com/indutny/bn.js/issues" - }, - "homepage": "https://github.com/indutny/bn.js", - "browser": { - "buffer": false - }, - "devDependencies": { - "istanbul": "^0.3.5", - "mocha": "^2.1.0", - "semistandard": "^7.0.4" - } -} diff --git a/app/node_modules/inherits/LICENSE b/app/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013d6..000000000 --- a/app/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/app/node_modules/inherits/README.md b/app/node_modules/inherits/README.md deleted file mode 100644 index b1c566585..000000000 --- a/app/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/app/node_modules/inherits/inherits.js b/app/node_modules/inherits/inherits.js deleted file mode 100644 index f71f2d932..000000000 --- a/app/node_modules/inherits/inherits.js +++ /dev/null @@ -1,9 +0,0 @@ -try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = require('./inherits_browser.js'); -} diff --git a/app/node_modules/inherits/inherits_browser.js b/app/node_modules/inherits/inherits_browser.js deleted file mode 100644 index 86bbb3dc2..000000000 --- a/app/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,27 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} diff --git a/app/node_modules/inherits/package.json b/app/node_modules/inherits/package.json deleted file mode 100644 index 37b4366b8..000000000 --- a/app/node_modules/inherits/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.4", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": "git://github.com/isaacs/inherits", - "license": "ISC", - "scripts": { - "test": "tap" - }, - "devDependencies": { - "tap": "^14.2.4" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ] -} diff --git a/app/node_modules/minimalistic-assert/LICENSE b/app/node_modules/minimalistic-assert/LICENSE deleted file mode 100644 index adca66b32..000000000 --- a/app/node_modules/minimalistic-assert/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 Calvin Metcalf - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted, provided that the above copyright notice -and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/app/node_modules/minimalistic-assert/index.js b/app/node_modules/minimalistic-assert/index.js deleted file mode 100644 index 70b4ea5bb..000000000 --- a/app/node_modules/minimalistic-assert/index.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; diff --git a/app/node_modules/minimalistic-assert/package.json b/app/node_modules/minimalistic-assert/package.json deleted file mode 100644 index f8de10d9d..000000000 --- a/app/node_modules/minimalistic-assert/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "minimalistic-assert", - "version": "1.0.1", - "description": "minimalistic-assert ===", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://github.com/calvinmetcalf/minimalistic-assert.git" - }, - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/calvinmetcalf/minimalistic-assert/issues" - }, - "homepage": "https://github.com/calvinmetcalf/minimalistic-assert" -} diff --git a/app/node_modules/minimalistic-assert/readme.md b/app/node_modules/minimalistic-assert/readme.md deleted file mode 100644 index 2ca0d256e..000000000 --- a/app/node_modules/minimalistic-assert/readme.md +++ /dev/null @@ -1,4 +0,0 @@ -minimalistic-assert -=== - -very minimalistic assert module. diff --git a/app/node_modules/openpgp/README.md b/app/node_modules/openpgp/README.md index 1f719ee4e..955300a4f 100644 --- a/app/node_modules/openpgp/README.md +++ b/app/node_modules/openpgp/README.md @@ -1,7 +1,7 @@ -OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3)](https://automate.browserstack.com/public-build/N1l2eHFOanVBMU9wYWxJM3ZnWERnc1lidkt5UkRqa3BralV3SWVhOGpGTT0tLVljSjE4Z3dzVmdiQjl6RWgxb2c3T2c9PQ==--5864052cd523f751b6b907d547ac9c4c5f88c8a3) [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +OpenPGP.js [![Join the chat on Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/openpgpjs/openpgpjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ========== -[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements [RFC4880](https://tools.ietf.org/html/rfc4880) and parts of [RFC4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10). +[OpenPGP.js](https://openpgpjs.org/) is a JavaScript implementation of the OpenPGP protocol. It implements [RFC 9580](https://datatracker.ietf.org/doc/rfc9580/) (superseding [RFC 4880](https://tools.ietf.org/html/rfc4880) and [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10)). **Table of Contents** @@ -33,61 +33,62 @@ OpenPGP.js [![BrowserStack Status](https://automate.browserstack.com/badge.svg?b ### Platform Support -* The `dist/openpgp.min.js` bundle works well with recent versions of Chrome, Firefox, Safari and Edge. +* The `dist/openpgp.min.js` (or `.mjs`) bundle works with recent versions of Chrome, Firefox, Edge and Safari 14+. -* The `dist/node/openpgp.min.js` bundle works well in Node.js. It is used by default when you `require('openpgp')` in Node.js. +* The `dist/node/openpgp.min.mjs` (or `.cjs`) bundle works in Node.js v18+: it is used by default when you `import ... from 'openpgp'` (or `require('openpgp')`, respectively). + +* Support for the [Web Cryptography API](https://w3c.github.io/webcrypto/)'s `SubtleCrypto` is required. + * In browsers, `SubtleCrypto` is only available in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts). + * In supported versions of Node.js, `SubtleCrypto` is always available. + +* Support for the [Web Streams API](https://streams.spec.whatwg.org/) is required. + * In browsers: the latest versions of Chrome, Firefox, Edge and Safari support Streams, including `TransformStream`s. + These are needed if you use the library with stream inputs. + In previous versions of OpenPGP.js, Web Streams were automatically polyfilled by the library, + but from v6 this task is left up to the library user, due to the more extensive browser support, and the + polyfilling side-effects. If you're working with [older browsers versions which do not implement e.g. TransformStreams](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility), you can manually + load the [Web Streams polyfill](https://github.com/MattiasBuelens/web-streams-polyfills). + Please note that when you load the polyfills, the global `ReadableStream` property (if it exists) gets overwritten with the polyfill version. + In some edge cases, you might need to use the native + `ReadableStream` (for example when using it to create a `Response` + object), in which case you should store a reference to it before loading + the polyfills. There is also the [web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter) + library to convert back and forth between them. + * In Node.js: OpenPGP.js v6 no longer supports native Node `Readable` streams in inputs, and instead expects (and outputs) [Node's Web Streams](https://nodejs.org/api/webstreams.html#class-readablestream). [Node v17+ includes utilities to convert from and to Web Streams](https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options). -* Currently, Chrome, Safari and Edge have partial implementations of the -[Streams specification](https://streams.spec.whatwg.org/), and Firefox -has a partial implementation behind feature flags. Chrome is the only -browser that implements `TransformStream`s, which we need, so we include -a [polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) for -all other browsers. Please note that in those browsers, the global -`ReadableStream` property gets overwritten with the polyfill version if -it exists. In some edge cases, you might need to use the native -`ReadableStream` (for example when using it to create a `Response` -object), in which case you should store a reference to it before loading -OpenPGP.js. There is also the -[web-streams-adapter](https://github.com/MattiasBuelens/web-streams-adapter) -library to convert back and forth between them. ### Performance -* Version 3.0.0 of the library introduces support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported: +* Version 3.0.0 of the library introduced support for public-key cryptography using [elliptic curves](https://wiki.gnupg.org/ECC). We use native implementations on browsers and Node.js when available. Compared to RSA, elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported: | Curve | Encryption | Signature | NodeCrypto | WebCrypto | Constant-Time | |:---------------:|:----------:|:---------:|:----------:|:---------:|:-----------------:| - | curve25519 | ECDH | N/A | No | No | Algorithmically** | - | ed25519 | N/A | EdDSA | No | No | Algorithmically** | - | p256 | ECDH | ECDSA | Yes* | Yes* | If native*** | - | p384 | ECDH | ECDSA | Yes* | Yes* | If native*** | - | p521 | ECDH | ECDSA | Yes* | Yes* | If native*** | - | brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native*** | - | brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native*** | - | brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native*** | - | secp256k1 | ECDH | ECDSA | Yes* | No | If native*** | + | curve25519 | ECDH | N/A | No | No | Algorithmically | + | ed25519 | N/A | EdDSA | No | Yes* | If native** | + | nistP256 | ECDH | ECDSA | Yes* | Yes* | If native** | + | nistP384 | ECDH | ECDSA | Yes* | Yes* | If native** | + | nistP521 | ECDH | ECDSA | Yes* | Yes* | If native** | + | brainpoolP256r1 | ECDH | ECDSA | Yes* | No | If native** | + | brainpoolP384r1 | ECDH | ECDSA | Yes* | No | If native** | + | brainpoolP512r1 | ECDH | ECDSA | Yes* | No | If native** | + | secp256k1 | ECDH | ECDSA | Yes* | No | If native** | \* when available - \** the curve25519 and ed25519 implementations are algorithmically constant-time, but may not be constant-time after optimizations of the JavaScript compiler - \*** these curves are only constant-time if the underlying native implementation is available and constant-time - -* Version 2.x of the library has been built from the ground up with Uint8Arrays. This allows for much better performance and memory usage than strings. + \** these curves are only constant-time if the underlying native implementation is available and constant-time -* If the user's browser supports [native WebCrypto](https://caniuse.com/#feat=cryptography) via the `window.crypto.subtle` API, this will be used. Under Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is used. +* The platform's [native Web Crypto API](https://w3c.github.io/webcrypto/) is used for performance. On Node.js the native [crypto module](https://nodejs.org/api/crypto.html#crypto_crypto) is also used, in cases where it offers additional functionality. -* The library implements the [RFC4880bis proposal](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10) for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database.** You can enable it by setting `openpgp.config.aeadProtect = true`. +* The library implements authenticated encryption (AEAD) as per [RFC 9580](https://datatracker.ietf.org/doc/rfc9580/) using AES-GCM, OCB, or EAX. This makes symmetric encryption faster on platforms with native implementations. However, since the specification is very recent and other OpenPGP implementations are in the process of adopting it, the feature is currently behind a flag. **Note: activating this setting can break compatibility with other OpenPGP implementations which have yet to implement the feature.** You can enable it by setting `openpgp.config.aeadProtect = true`. + Note that this setting has a different effect from the one in OpenPGP.js v5, which implemented support for a provisional version of AEAD from [RFC 4880bis](https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-10), which was modified in RFC 9580. You can change the AEAD mode by setting one of the following options: ``` - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax // Default, native - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb // Non-native - openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM // **Non-standard**, fastest + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // Default, native in WebCrypto and Node.js + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // Non-native, but supported across RFC 9580 implementations + openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax; // Native in Node.js ``` -* For environments that don't provide native crypto, the library falls back to [asm.js](https://caniuse.com/#feat=asmjs) implementations of AES, SHA-1, and SHA-256. - - ### Getting started #### Node.js @@ -98,16 +99,15 @@ Install OpenPGP.js using npm and save it in your dependencies: npm install --save openpgp ``` -And import it as a CommonJS module: - +And import it as an ES module, from a .mjs file: ```js -const openpgp = require('openpgp'); +import * as openpgp from 'openpgp'; ``` -Or as an ES6 module, from an .mjs file: +Or as a CommonJS module: ```js -import * as openpgp from 'openpgp'; +const openpgp = require('openpgp'); ``` #### Deno (experimental) @@ -174,17 +174,17 @@ To offload cryptographic operations off the main thread, you can implement a Web #### TypeScript -Since TS is not fully integrated in the library, TS-only dependencies are currently listed as `devDependencies`, so to compile the project you’ll need to add `@openpgp/web-stream-tools` manually (NB: only versions below v0.12 are compatible with OpenPGP.js v5): +Since TS is not fully integrated in the library, TS-only dependencies are currently listed as `devDependencies`, so to compile the project you’ll need to add `@openpgp/web-stream-tools` manually: ```sh -npm install --save-dev @openpgp/web-stream-tools@0.0.11-patch-0 +npm install --save-dev @openpgp/web-stream-tools ``` If you notice missing or incorrect type definitions, feel free to open a PR. ### Examples -Here are some examples of how to use OpenPGP.js v5. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/V5-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation). +Here are some examples of how to use OpenPGP.js v6. For more elaborate examples and working code, please check out the [public API unit tests](https://github.com/openpgpjs/openpgpjs/blob/main/test/general/openpgp.js). If you're upgrading from v4 it might help to check out the [changelog](https://github.com/openpgpjs/openpgpjs/wiki/v6-Changelog) and [documentation](https://github.com/openpgpjs/openpgpjs#documentation). #### Encrypt and decrypt *Uint8Array* data with a password @@ -389,14 +389,8 @@ Where the value can be any of: })(); ``` -For more information on using ReadableStreams, see [the MDN Documentation on the -Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API). - -You can also pass a [Node.js `Readable` -stream](https://nodejs.org/api/stream.html#stream_class_stream_readable), in -which case OpenPGP.js will return a Node.js `Readable` stream as well, which you -can `.pipe()` to a `Writable` stream, for example. - +For more information on using ReadableStreams (both in browsers and Node.js), see [the MDN Documentation on the +Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) . #### Streaming encrypt and decrypt *String* data with PGP keys @@ -453,7 +447,7 @@ can `.pipe()` to a `Writable` stream, for example. ECC keys (smaller and faster to generate): -Possible values for `curve` are: `curve25519`, `ed25519`, `p256`, `p384`, `p521`, +Possible values for `curve` are: `curve25519`, `ed25519`, `nistP256`, `nistP384`, `nistP521`, `brainpoolP256r1`, `brainpoolP384r1`, `brainpoolP512r1`, and `secp256k1`. Note that both the `curve25519` and `ed25519` options generate a primary key for signing using Ed25519 and a subkey for encryption using Curve25519. @@ -670,7 +664,7 @@ To create your own build of the library, just run the following command after cl npm install && npm test -For debugging browser errors, you can run `npm start` and open [`http://localhost:8080/test/unittests.html`](http://localhost:8080/test/unittests.html) in a browser, or run the following command: +For debugging browser errors, run the following command: npm run browsertest diff --git a/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs b/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs new file mode 100644 index 000000000..278134f88 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs @@ -0,0 +1,3 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const A="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function I(A,I,g,B){A[I]+=g[B],A[I+1]+=g[B+1]+(A[I]>>24^e<<8,A[C+1]=e>>>24^i<<8,I(A,B,A,C),I(A,B,g,t),i=A[E]^A[B],e=A[E+1]^A[B+1],A[E]=i>>>16^e<<16,A[E+1]=e>>>16^i<<16,I(A,Q,A,E),i=A[C]^A[Q],e=A[C+1]^A[Q+1],A[C]=e>>>31^i<<1,A[C+1]=i>>>31^e<<1}const C=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Q=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((A=>2*A)));function E(A,I){const g=new Uint32Array(32),E=new Uint32Array(A.b.buffer,A.b.byteOffset,32);for(let I=0;I<16;I++)g[I]=A.h[I],g[I+16]=C[I];g[24]^=A.t0[0],g[25]^=A.t0[1];const w=I?4294967295:0;g[28]^=w,g[29]^=w;for(let A=0;A<12;A++){const I=A<<4;B(g,E,0,8,16,24,Q[I+0],Q[I+1]),B(g,E,2,10,18,26,Q[I+2],Q[I+3]),B(g,E,4,12,20,28,Q[I+4],Q[I+5]),B(g,E,6,14,22,30,Q[I+6],Q[I+7]),B(g,E,0,10,20,30,Q[I+8],Q[I+9]),B(g,E,2,12,22,24,Q[I+10],Q[I+11]),B(g,E,4,14,16,26,Q[I+12],Q[I+13]),B(g,E,6,8,18,28,Q[I+14],Q[I+15])}for(let I=0;I<16;I++)A.h[I]^=g[I]^g[I+16]}class w{constructor(A,I,g,B){const Q=new Uint8Array(64);this.S={b:new Uint8Array(e),h:new Uint32Array(i/4),t0:new Uint32Array(2),c:0,outlen:A},Q[0]=A,I&&(Q[1]=I.length),Q[2]=1,Q[3]=1,g&&Q.set(g,32),B&&Q.set(B,48);const E=new Uint32Array(Q.buffer,Q.byteOffset,Q.length/Uint32Array.BYTES_PER_ELEMENT);for(let A=0;A<16;A++)this.S.h[A]=C[A]^E[A];if(I){const A=new Uint8Array(e);A.set(I),this.update(A)}}update(A){if(!(A instanceof Uint8Array))throw Error("Input must be Uint8Array or Buffer");let I=0;for(;I>2]>>8*(3&A);return this.S.h=null,I.buffer}}function t(A,I,g,B){if(A>i)throw Error(`outlen must be at most ${i} (given: ${A})`);return new w(A,I,g,B)}const i=64,e=128,n=2,D=19,s=4294967295,f=4,r=4294967295,o=8,c=4294967295,S=8,y=4294967295,a=4294967295,h=32,M=1024,U=64,R=205===new Uint8Array(new Uint16Array([43981]).buffer)[0];function N(A,I,g){return A[g+0]=I,A[g+1]=I>>8,A[g+2]=I>>16,A[g+3]=I>>24,A}function k(A,I,g){if(I>Number.MAX_SAFE_INTEGER)throw Error("LE64: large numbers unsupported");let B=I;for(let I=g;I{if(IB)throw Error(`${A} size should be between ${g} and ${B} bytes`)};if(A!==n||I!==D)throw Error("Unsupported type or version");return e("password",B,S,c),e("salt",C,o,r),e("tag",g,f,s),e("memory",t,8*w,y),Q&&e("associated data",Q,0,a),E&&e("secret",E,0,h),{type:A,version:I,tagLength:g,password:B,salt:C,ad:Q,secret:E,lanes:w,memorySize:t,passes:i}}({type:n,version:D,...A}),{G:C,G2:Q,xor:E,getLZ:w}=g.exports,i={},e={};e.G=C,e.G2=Q,e.XOR=E;const k=4*B.lanes*Math.floor(B.memorySize/(4*B.lanes)),F=k*M+10*J;if(I.buffer.byteLength{g.set(A,B),B+=A.length})),g}(C));const Q=I.digest();return new Uint8Array(Q)}(B),P=k/B.lanes,x=Array(B.lanes).fill(null).map((()=>Array(P))),m=(A,I)=>(x[A][I]=v.subarray(A*P*1024+1024*I,A*P*1024+1024*I+M),x[A][I]);for(let A=0;A0?x[C][t-1]:x[C][P-1],e=g?E.next().value:i;w(p.byteOffset,e.byteOffset,C,B.lanes,A,I,Q,4,O);const n=p[0],D=p[1];0===A&&m(C,t),G(d,i,x[n][D],A>0?b:x[C][t]),A>0&&l(d,x[C][t],b,x[C][t])}}}const V=x[0][P-1];for(let A=1;AK(A,{instance:B.instance,memory:g})}function b(I,g,B,C){var Q=null,E=A.atob(B),w=E.length;Q=new Uint8Array(new ArrayBuffer(w));for(var t=0;td((A=>b(0,0,"AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCA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WN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaik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tIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==",A)));export{v as default}; +//# sourceMappingURL=argon2id.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs.map new file mode 100644 index 000000000..eb96a3170 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/argon2id.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2id.min.mjs","sources":["../../node_modules/argon2id/lib/blake2b.js","../../node_modules/argon2id/lib/argon2id.js","../../node_modules/argon2id/lib/setup.js","../../node_modules/argon2id/index.js"],"sourcesContent":["// Adapted from the reference implementation in RFC7693\n// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes\n\n// Uint64 values are represented using two Uint32s, stored as little endian\n// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays\n// need to be manually handled\n\n// 64-bit unsigned addition (little endian, in place)\n// Sets a[i,i+1] += b[j,j+1]\n// `a` and `b` must be Uint32Array(2)\nfunction ADD64 (a, i, b, j) {\n a[i] += b[j];\n a[i+1] += b[j+1] + (a[i] < b[j]); // add carry\n}\n\n// Increment 64-bit little-endian unsigned value by `c` (in place)\n// `a` must be Uint32Array(2)\nfunction INC64 (a, c) {\n a[0] += c;\n a[1] += (a[0] < c);\n}\n\n// G Mixing function\n// The ROTRs are inlined for speed\nfunction G (v, m, a, b, c, d, ix, iy) {\n ADD64(v, a, v, b) // v[a,a+1] += v[b,b+1]\n ADD64(v, a, m, ix) // v[a, a+1] += x ... x0\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n let xor0 = v[d] ^ v[a]\n let xor1 = v[d + 1] ^ v[a + 1]\n v[d] = xor1\n v[d + 1] = xor0\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor0 >>> 24) ^ (xor1 << 8)\n v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)\n\n ADD64(v, a, v, b)\n ADD64(v, a, m, iy)\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = v[d] ^ v[a]\n xor1 = v[d + 1] ^ v[a + 1]\n v[d] = (xor0 >>> 16) ^ (xor1 << 16)\n v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor1 >>> 31) ^ (xor0 << 1)\n v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)\n}\n\n// Initialization Vector\nconst BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n])\n\n// These are offsets into a Uint64 buffer.\n// Multiply them all by 2 to make them offsets into a Uint32 buffer\nconst SIGMA = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n].map(x => x * 2))\n\n// Compression function. 'last' flag indicates last block.\n// Note: we're representing 16 uint64s as 32 uint32s\nfunction compress(S, last) {\n const v = new Uint32Array(32)\n const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32)\n\n // init work variables\n for (let i = 0; i < 16; i++) {\n v[i] = S.h[i]\n v[i + 16] = BLAKE2B_IV32[i]\n }\n\n // low 64 bits of offset\n v[24] ^= S.t0[0]\n v[25] ^= S.t0[1]\n // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1\n\n // if last block\n const f0 = last ? 0xFFFFFFFF : 0;\n v[28] ^= f0;\n v[29] ^= f0;\n\n // twelve rounds of mixing\n for (let i = 0; i < 12; i++) {\n // ROUND(r)\n const i16 = i << 4;\n G(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1])\n G(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3])\n G(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5])\n G(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7])\n G(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9])\n G(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11])\n G(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13])\n G(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15])\n }\n\n for (let i = 0; i < 16; i++) {\n S.h[i] ^= v[i] ^ v[i + 16]\n }\n}\n\n// Creates a BLAKE2b hashing context\n// Requires an output length between 1 and 64 bytes\n// Takes an optional Uint8Array key\nclass Blake2b {\n constructor(outlen, key, salt, personal) {\n const params = new Uint8Array(64)\n // 0: outlen, keylen, fanout, depth\n // 4: leaf length, sequential mode\n // 8: node offset\n // 12: node offset\n // 16: node depth, inner length, rfu\n // 20: rfu\n // 24: rfu\n // 28: rfu\n // 32: salt\n // 36: salt\n // 40: salt\n // 44: salt\n // 48: personal\n // 52: personal\n // 56: personal\n // 60: personal\n\n // init internal state\n this.S = {\n b: new Uint8Array(BLOCKBYTES),\n h: new Uint32Array(OUTBYTES_MAX / 4),\n t0: new Uint32Array(2), // input counter `t`, lower 64-bits only\n c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`\n outlen // output length in bytes\n }\n\n // init parameter block\n params[0] = outlen\n if (key) params[1] = key.length\n params[2] = 1 // fanout\n params[3] = 1 // depth\n if (salt) params.set(salt, 32)\n if (personal) params.set(personal, 48)\n const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];\n }\n\n // key the hash, if applicable\n if (key) {\n const block = new Uint8Array(BLOCKBYTES)\n block.set(key)\n this.update(block)\n }\n }\n\n // Updates a BLAKE2b streaming hash\n // Requires Uint8Array (byte array)\n update(input) {\n if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')\n // for (let i = 0; i < input.length; i++) {\n // if (this.S.c === BLOCKBYTES) { // buffer full\n // INC64(this.S.t0, this.S.c) // add counters\n // compress(this.S, false)\n // this.S.c = 0 // empty buffer\n // }\n // this.S.b[this.S.c++] = input[i]\n // }\n let i = 0\n while(i < input.length) {\n if (this.S.c === BLOCKBYTES) { // buffer full\n INC64(this.S.t0, this.S.c) // add counters\n compress(this.S, false)\n this.S.c = 0 // empty buffer\n }\n let left = BLOCKBYTES - this.S.c\n this.S.b.set(input.subarray(i, i + left), this.S.c) // end index can be out of bounds\n const fill = Math.min(left, input.length - i)\n this.S.c += fill\n i += fill\n }\n return this\n }\n\n /**\n * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one\n * @param {Uint8Array} [prealloc] - optional preallocated buffer\n * @returns {ArrayBuffer} message digest\n */\n digest(prealloc) {\n INC64(this.S.t0, this.S.c) // mark last block offset\n\n // final block, padded\n this.S.b.fill(0, this.S.c);\n this.S.c = BLOCKBYTES;\n compress(this.S, true)\n\n const out = prealloc || new Uint8Array(this.S.outlen);\n for (let i = 0; i < this.S.outlen; i++) {\n // must be loaded individually since default Uint32 endianness is platform dependant\n out[i] = this.S.h[i >> 2] >> (8 * (i & 3))\n }\n this.S.h = null; // prevent calling `update` after `digest`\n return out.buffer;\n }\n}\n\n\nexport default function createHash(outlen, key, salt, personal) {\n if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)\n if (key) {\n if (!(key instanceof Uint8Array)) throw new Error('key must be Uint8Array or Buffer')\n if (key.length > KEYBYTES_MAX) throw new Error(`key size must be at most ${KEYBYTES_MAX} (given: ${key.length})`)\n }\n if (salt) {\n if (!(salt instanceof Uint8Array)) throw new Error('salt must be Uint8Array or Buffer')\n if (salt.length !== SALTBYTES) throw new Error(`salt must be exactly ${SALTBYTES} (given: ${salt.length}`)\n }\n if (personal) {\n if (!(personal instanceof Uint8Array)) throw new Error('personal must be Uint8Array or Buffer')\n if (personal.length !== PERSONALBYTES) throw new Error(`salt must be exactly ${PERSONALBYTES} (given: ${personal.length}`)\n }\n\n return new Blake2b(outlen, key, salt, personal)\n}\n\nconst OUTBYTES_MAX = 64;\nconst KEYBYTES_MAX = 64;\nconst SALTBYTES = 16;\nconst PERSONALBYTES = 16;\nconst BLOCKBYTES = 128;\n\n","import blake2b from \"./blake2b.js\"\nconst TYPE = 2; // Argon2id\nconst VERSION = 0x13;\nconst TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MIN = 8;\nconst passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst passwordBYTES_MIN = 8;\nconst MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)\nconst SECRETBYTES_MAX = 32; // key (optional)\n\nconst ARGON2_BLOCK_SIZE = 1024;\nconst ARGON2_PREHASH_DIGEST_LENGTH = 64;\n\nconst isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;\n\n// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])\nfunction LE32(buf, n, i) {\n buf[i+0] = n;\n buf[i+1] = n >> 8;\n buf[i+2] = n >> 16;\n buf[i+3] = n >> 24;\n return buf;\n}\n\n/**\n * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])\n * @param {Uint8Array} buf\n * @param {Number} n\n * @param {Number} i\n */\nfunction LE64(buf, n, i) {\n if (n > Number.MAX_SAFE_INTEGER) throw new Error(\"LE64: large numbers unsupported\");\n // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations\n // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)\n // so we manually extract each byte\n let remainder = n;\n for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER\n buf[offset] = remainder; // implicit & 0xff\n remainder = (remainder - buf[offset]) / 256;\n }\n return buf;\n}\n\n/**\n * Variable-Length Hash Function H'\n * @param {Number} outlen - T\n * @param {Uint8Array} X - value to hash\n * @param {Uint8Array} res - output buffer, of length `outlength` or larger\n */\nfunction H_(outlen, X, res) {\n const V = new Uint8Array(64); // no need to keep around all V_i\n\n const V1_in = new Uint8Array(4 + X.length);\n LE32(V1_in, outlen, 0);\n V1_in.set(X, 4);\n if (outlen <= 64) {\n // H'^T(A) = H^T(LE32(T)||A)\n blake2b(outlen).update(V1_in).digest(res);\n return res\n }\n\n const r = Math.ceil(outlen / 32) - 2;\n\n // Let V_i be a 64-byte block and W_i be its first 32 bytes.\n // V_1 = H^(64)(LE32(T)||A)\n // V_2 = H^(64)(V_1)\n // ...\n // V_r = H^(64)(V_{r-1})\n // V_{r+1} = H^(T-32*r)(V_{r})\n // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}\n for (let i = 0; i < r; i++) {\n blake2b(64).update(i === 0 ? V1_in : V).digest(V);\n // store W_i in result buffer already\n res.set(V.subarray(0, 32), i*32)\n }\n // V_{r+1}\n const V_r1 = new Uint8Array(blake2b(outlen - 32*r).update(V).digest());\n res.set(V_r1, r*32);\n\n return res;\n}\n\n// compute buf = xs ^ ys\nfunction XOR(wasmContext, buf, xs, ys) {\n wasmContext.fn.XOR(\n buf.byteOffset,\n xs.byteOffset,\n ys.byteOffset,\n );\n return buf\n}\n\n/**\n * @param {Uint8Array} X (read-only)\n * @param {Uint8Array} Y (read-only)\n * @param {Uint8Array} R - output buffer\n * @returns\n */\nfunction G(wasmContext, X, Y, R) {\n wasmContext.fn.G(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\nfunction G2(wasmContext, X, Y, R) {\n wasmContext.fn.G2(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\n// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.\nfunction* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {\n // For each segment, we do the following. First, we compute the value Z as:\n // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )\n wasmContext.refs.prngTmp.fill(0);\n const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);\n LE64(Z, pass, 0);\n LE64(Z, lane, 8);\n LE64(Z, slice, 16);\n LE64(Z, m_, 24);\n LE64(Z, totalPasses, 32);\n LE64(Z, TYPE, 40);\n\n // Then we compute q/(128*SL) 1024-byte values\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),\n // ...,\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),\n for(let i = 1; i <= segmentLength; i++) {\n // tmp.set(Z); // no need to re-copy\n LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed\n const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );\n\n // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2\n // NB: the first generated pair must be used for the first block of the segment, and so on.\n // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.\n for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {\n yield g2.subarray(k, k+8);\n }\n }\n return [];\n}\n\nfunction validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {\n const assertLength = (name, value, min, max) => {\n if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }\n }\n\n if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');\n assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);\n assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);\n assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);\n assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);\n // optional fields\n ad && assertLength('associated data', ad, 0, ADBYTES_MAX);\n secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);\n\n return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };\n}\n\nconst KB = 1024;\nconst WASM_PAGE_SIZE = 64 * KB;\n\nexport default function argon2id(params, { memory, instance: wasmInstance }) {\n if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system\n\n const ctx = validateParams({ type: TYPE, version: VERSION, ...params });\n\n const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;\n const wasmRefs = {};\n const wasmFn = {};\n wasmFn.G = wasmG;\n wasmFn.G2 = wasmG2;\n wasmFn.XOR = wasmXOR;\n\n // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.\n const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));\n const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references\n if (memory.buffer.byteLength < requiredMemory) {\n const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE)\n // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.\n // Otherwise, the operation fails, and the original memory can still be used.\n memory.grow(missing)\n }\n\n let offset = 0;\n // Init wasm memory needed in other functions\n wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;\n wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;\n wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;\n wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;\n // Init wasm memory needed locally\n const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;\n const wasmContext = { fn: wasmFn, refs: wasmRefs };\n const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;\n const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);\n const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);\n\n // 1. Establish H_0\n const H0 = getH0(ctx);\n\n // 2. Allocate the memory as m' 1024-byte blocks\n // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.\n const q = m_ / ctx.lanes;\n const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));\n const initBlock = (i, j) => {\n B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);\n return B[i][j];\n }\n\n for (let i = 0; i < ctx.lanes; i++) {\n // const LEi = LE0; // since p = 1 for us\n const tmp = new Uint8Array(H0.length + 8);\n // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p\n // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))\n tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));\n // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p\n // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))\n LE32(tmp, 1, H0.length);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));\n }\n\n // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2\n // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes\n // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.\n const SL = 4; // vertical slices\n const segmentLength = q / SL;\n for (let pass = 0; pass < ctx.passes; pass++) {\n // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel\n for (let sl = 0; sl < SL; sl++) {\n const isDataIndependent = pass === 0 && sl <= 1;\n for (let i = 0; i < ctx.lanes; i++) { // lane\n // On the first slice of the first pass, blocks 0 and 1 are already filled\n let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;\n // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)\n const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;\n for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {\n const j = sl * segmentLength + segmentOffset;\n const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]\n\n // we can assume the PRNG is never done\n const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength)\n const l = lz[0]; const z = lz[1];\n // for (let i = 0; i < p; i++ )\n // B[i][j] = G(B[i][j-1], B[l][z])\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n if (pass === 0) initBlock(i, j);\n G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);\n\n // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one\n if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j])\n }\n }\n }\n }\n\n // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:\n // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]\n const C = B[0][q-1];\n for(let i = 1; i < ctx.lanes; i++) {\n XOR(wasmContext, C, C, B[i][q-1])\n }\n\n const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));\n // clear memory since the module might be cached\n allocatedMemory.fill(0) // clear sensitive contents\n memory.grow(0) // allow deallocation\n // 8. The output tag is computed as H'^T(C).\n return tag;\n\n}\n\nfunction getH0(ctx) {\n const H = blake2b(ARGON2_PREHASH_DIGEST_LENGTH);\n const ZERO32 = new Uint8Array(4);\n const params = new Uint8Array(24);\n LE32(params, ctx.lanes, 0);\n LE32(params, ctx.tagLength, 4);\n LE32(params, ctx.memorySize, 8);\n LE32(params, ctx.passes, 12);\n LE32(params, ctx.version, 16);\n LE32(params, ctx.type, 20);\n\n const toHash = [params];\n if (ctx.password) {\n toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0))\n toHash.push(ctx.password)\n } else {\n toHash.push(ZERO32) // context.password.length\n }\n\n if (ctx.salt) {\n toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0))\n toHash.push(ctx.salt)\n } else {\n toHash.push(ZERO32) // context.salt.length\n }\n\n if (ctx.secret) {\n toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0))\n toHash.push(ctx.secret)\n // todo clear secret?\n } else {\n toHash.push(ZERO32) // context.secret.length\n }\n\n if (ctx.ad) {\n toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0))\n toHash.push(ctx.ad)\n } else {\n toHash.push(ZERO32) // context.ad.length\n }\n H.update(concatArrays(toHash))\n\n const outputBuffer = H.digest();\n return new Uint8Array(outputBuffer);\n}\n\nfunction concatArrays(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!(arrays[i] instanceof Uint8Array)) {\n throw new Error('concatArrays: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach((element) => {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n","import argon2id from \"./argon2id.js\";\n\nlet isSIMDSupported;\nasync function wasmLoader(memory, getSIMD, getNonSIMD) {\n const importObject = { env: { memory } };\n if (isSIMDSupported === undefined) {\n try {\n const loaded = await getSIMD(importObject);\n isSIMDSupported = true;\n return loaded;\n } catch(e) {\n isSIMDSupported = false;\n }\n }\n\n const loader = isSIMDSupported ? getSIMD : getNonSIMD;\n return loader(importObject);\n}\n\nexport default async function setupWasm(getSIMD, getNonSIMD) {\n const memory = new WebAssembly.Memory({\n // in pages of 64KiB each\n // these values need to be compatible with those declared when building in `build-wasm`\n initial: 1040, // 65MB\n maximum: 65536, // 4GB\n });\n const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);\n\n /**\n * Argon2id hash function\n * @callback computeHash\n * @param {Object} params\n * @param {Uint8Array} params.password - password\n * @param {Uint8Array} params.salt - salt\n * @param {Integer} params.parallelism\n * @param {Integer} params.passes\n * @param {Integer} params.memorySize - in kibibytes\n * @param {Integer} params.tagLength - output tag length\n * @param {Uint8Array} [params.ad] - associated data (optional)\n * @param {Uint8Array} [params.secret] - secret data (optional)\n * @return {Uint8Array} argon2id hash\n */\n const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });\n\n return computeHash;\n}\n","import setupWasm from './lib/setup.js';\nimport wasmSIMD from './dist/simd.wasm';\nimport wasmNonSIMD from './dist/no-simd.wasm';\n\nconst loadWasm = async () => setupWasm(\n (instanceObject) => wasmSIMD(instanceObject),\n (instanceObject) => wasmNonSIMD(instanceObject),\n);\n\nexport default loadWasm;\n"],"names":["ADD64","a","i","b","j","INC64","c","G","v","m","d","ix","iy","xor0","xor1","BLAKE2B_IV32","Uint32Array","SIGMA","Uint8Array","map","x","compress","S","last","buffer","byteOffset","h","t0","f0","i16","Blake2b","constructor","outlen","key","salt","personal","params","this","BLOCKBYTES","OUTBYTES_MAX","length","set","params32","BYTES_PER_ELEMENT","block","update","input","Error","left","subarray","fill","Math","min","digest","prealloc","out","createHash","TYPE","VERSION","TAGBYTES_MAX","TAGBYTES_MIN","SALTBYTES_MAX","SALTBYTES_MIN","passwordBYTES_MAX","passwordBYTES_MIN","MEMBYTES_MAX","ADBYTES_MAX","SECRETBYTES_MAX","ARGON2_BLOCK_SIZE","ARGON2_PREHASH_DIGEST_LENGTH","isLittleEndian","Uint16Array","LE32","buf","n","LE64","Number","MAX_SAFE_INTEGER","remainder","offset","H_","X","res","V","V1_in","blake2b","r","ceil","V_r1","XOR","wasmContext","xs","ys","fn","Y","R","refs","gZ","G2","makePRNG","pass","lane","slice","m_","totalPasses","segmentLength","segmentOffset","prngTmp","Z","g2","ZERO1024","prngR","k","KB","WASM_PAGE_SIZE","argon2id","memory","instance","wasmInstance","ctx","type","version","tagLength","password","ad","secret","parallelism","memorySize","passes","assertLength","name","value","max","lanes","validateParams","wasmG","wasmG2","xor","wasmXOR","getLZ","wasmLZ","exports","wasmRefs","wasmFn","floor","requiredMemory","byteLength","missing","grow","lz","newBlock","blockMemory","allocatedMemory","H0","H","ZERO32","toHash","push","arrays","totalLength","result","pos","forEach","element","concatArrays","outputBuffer","getH0","q","B","Array","initBlock","tmp","sl","isDataIndependent","PRNG","prevBlock","J1J2","next","l","z","C","tag","isSIMDSupported","async","setupWasm","getSIMD","getNonSIMD","WebAssembly","Memory","initial","maximum","wasmModule","importObject","env","undefined","loaded","e","wasmLoader","loadWasm","instanceObject"],"mappings":";6GAUA,SAASA,EAAOC,EAAGC,EAAGC,EAAGC,GACvBH,EAAEC,IAAMC,EAAEC,GACVH,EAAEC,EAAE,IAAMC,EAAEC,EAAE,IAAMH,EAAEC,GAAKC,EAAEC,GAC/B,CAIA,SAASC,EAAOJ,EAAGK,GACjBL,EAAE,IAAMK,EACRL,EAAE,IAAOA,EAAE,GAAKK,CAClB,CAIA,SAASC,EAAGC,EAAGC,EAAGR,EAAGE,EAAGG,EAAGI,EAAGC,EAAIC,GAChCZ,EAAMQ,EAAGP,EAAGO,EAAGL,GACfH,EAAMQ,EAAGP,EAAGQ,EAAGE,GAGf,IAAIE,EAAOL,EAAEE,GAAKF,EAAEP,GAChBa,EAAON,EAAEE,EAAI,GAAKF,EAAEP,EAAI,GAC5BO,EAAEE,GAAKI,EACPN,EAAEE,EAAI,GAAKG,EAEXb,EAAMQ,EAAGF,EAAGE,EAAGE,GAGfG,EAAOL,EAAEL,GAAKK,EAAEF,GACh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ADeA,EAAkBG,EAAUC,GAC7BM,EAChB,CAS2BK,CAAWjF,EAAQqE,EAASC,GAkBrD,OAFqBtJ,GAAW+E,EAAS/E,EAAQ,CAAEiF,SAAU0E,EAAW1E,SAAUD,UAGpF,yOCzCK,MAACkF,EAAWf,SAAYC,GAC1Be,4wLAA4BA,KAC5BA,wyJAA+BA","x_google_ignoreList":[0,1,2,3]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/argon2id.mjs b/app/node_modules/openpgp/dist/lightweight/argon2id.mjs new file mode 100644 index 000000000..392aeccc6 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/argon2id.mjs @@ -0,0 +1,683 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +// Adapted from the reference implementation in RFC7693 +// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes + +// Uint64 values are represented using two Uint32s, stored as little endian +// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays +// need to be manually handled + +// 64-bit unsigned addition (little endian, in place) +// Sets a[i,i+1] += b[j,j+1] +// `a` and `b` must be Uint32Array(2) +function ADD64 (a, i, b, j) { + a[i] += b[j]; + a[i+1] += b[j+1] + (a[i] < b[j]); // add carry +} + +// Increment 64-bit little-endian unsigned value by `c` (in place) +// `a` must be Uint32Array(2) +function INC64 (a, c) { + a[0] += c; + a[1] += (a[0] < c); +} + +// G Mixing function +// The ROTRs are inlined for speed +function G$1 (v, m, a, b, c, d, ix, iy) { + ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1] + ADD64(v, a, m, ix); // v[a, a+1] += x ... x0 + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; + + ADD64(v, c, v, d); + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor0 >>> 24) ^ (xor1 << 8); + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); + + ADD64(v, a, v, b); + ADD64(v, a, m, iy); + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = (xor0 >>> 16) ^ (xor1 << 16); + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); + + ADD64(v, c, v, d); + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor1 >>> 31) ^ (xor0 << 1); + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); +} + +// Initialization Vector +const BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]); + +// These are offsets into a Uint64 buffer. +// Multiply them all by 2 to make them offsets into a Uint32 buffer +const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +].map(x => x * 2)); + +// Compression function. 'last' flag indicates last block. +// Note: we're representing 16 uint64s as 32 uint32s +function compress(S, last) { + const v = new Uint32Array(32); + const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32); + + // init work variables + for (let i = 0; i < 16; i++) { + v[i] = S.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + + // low 64 bits of offset + v[24] ^= S.t0[0]; + v[25] ^= S.t0[1]; + // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1 + + // if last block + const f0 = last ? 0xFFFFFFFF : 0; + v[28] ^= f0; + v[29] ^= f0; + + // twelve rounds of mixing + for (let i = 0; i < 12; i++) { + // ROUND(r) + const i16 = i << 4; + G$1(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1]); + G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]); + G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]); + G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]); + G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]); + G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]); + G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]); + G$1(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15]); + } + + for (let i = 0; i < 16; i++) { + S.h[i] ^= v[i] ^ v[i + 16]; + } +} + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +class Blake2b { + constructor(outlen, key, salt, personal) { + const params = new Uint8Array(64); + // 0: outlen, keylen, fanout, depth + // 4: leaf length, sequential mode + // 8: node offset + // 12: node offset + // 16: node depth, inner length, rfu + // 20: rfu + // 24: rfu + // 28: rfu + // 32: salt + // 36: salt + // 40: salt + // 44: salt + // 48: personal + // 52: personal + // 56: personal + // 60: personal + + // init internal state + this.S = { + b: new Uint8Array(BLOCKBYTES), + h: new Uint32Array(OUTBYTES_MAX / 4), + t0: new Uint32Array(2), // input counter `t`, lower 64-bits only + c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES` + outlen // output length in bytes + }; + + // init parameter block + params[0] = outlen; + if (key) params[1] = key.length; + params[2] = 1; // fanout + params[3] = 1; // depth + if (salt) params.set(salt, 32); + if (personal) params.set(personal, 48); + const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT); + + // initialize hash state + for (let i = 0; i < 16; i++) { + this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i]; + } + + // key the hash, if applicable + if (key) { + const block = new Uint8Array(BLOCKBYTES); + block.set(key); + this.update(block); + } + } + + // Updates a BLAKE2b streaming hash + // Requires Uint8Array (byte array) + update(input) { + if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer') + // for (let i = 0; i < input.length; i++) { + // if (this.S.c === BLOCKBYTES) { // buffer full + // INC64(this.S.t0, this.S.c) // add counters + // compress(this.S, false) + // this.S.c = 0 // empty buffer + // } + // this.S.b[this.S.c++] = input[i] + // } + let i = 0; + while(i < input.length) { + if (this.S.c === BLOCKBYTES) { // buffer full + INC64(this.S.t0, this.S.c); // add counters + compress(this.S, false); + this.S.c = 0; // empty buffer + } + let left = BLOCKBYTES - this.S.c; + this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds + const fill = Math.min(left, input.length - i); + this.S.c += fill; + i += fill; + } + return this + } + + /** + * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one + * @param {Uint8Array} [prealloc] - optional preallocated buffer + * @returns {ArrayBuffer} message digest + */ + digest(prealloc) { + INC64(this.S.t0, this.S.c); // mark last block offset + + // final block, padded + this.S.b.fill(0, this.S.c); + this.S.c = BLOCKBYTES; + compress(this.S, true); + + const out = prealloc || new Uint8Array(this.S.outlen); + for (let i = 0; i < this.S.outlen; i++) { + // must be loaded individually since default Uint32 endianness is platform dependant + out[i] = this.S.h[i >> 2] >> (8 * (i & 3)); + } + this.S.h = null; // prevent calling `update` after `digest` + return out.buffer; + } +} + + +function createHash(outlen, key, salt, personal) { + if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`) + + return new Blake2b(outlen, key, salt, personal) +} + +const OUTBYTES_MAX = 64; +const BLOCKBYTES = 128; + +const TYPE = 2; // Argon2id +const VERSION = 0x13; +const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1; +const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const SALTBYTES_MIN = 8; +const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const passwordBYTES_MIN = 8; +const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional) +const SECRETBYTES_MAX = 32; // key (optional) + +const ARGON2_BLOCK_SIZE = 1024; +const ARGON2_PREHASH_DIGEST_LENGTH = 64; + +const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd; + +// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3]) +function LE32(buf, n, i) { + buf[i+0] = n; + buf[i+1] = n >> 8; + buf[i+2] = n >> 16; + buf[i+3] = n >> 24; + return buf; +} + +/** + * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7]) + * @param {Uint8Array} buf + * @param {Number} n + * @param {Number} i + */ +function LE64(buf, n, i) { + if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported"); + // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations + // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps) + // so we manually extract each byte + let remainder = n; + for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER + buf[offset] = remainder; // implicit & 0xff + remainder = (remainder - buf[offset]) / 256; + } + return buf; +} + +/** + * Variable-Length Hash Function H' + * @param {Number} outlen - T + * @param {Uint8Array} X - value to hash + * @param {Uint8Array} res - output buffer, of length `outlength` or larger + */ +function H_(outlen, X, res) { + const V = new Uint8Array(64); // no need to keep around all V_i + + const V1_in = new Uint8Array(4 + X.length); + LE32(V1_in, outlen, 0); + V1_in.set(X, 4); + if (outlen <= 64) { + // H'^T(A) = H^T(LE32(T)||A) + createHash(outlen).update(V1_in).digest(res); + return res + } + + const r = Math.ceil(outlen / 32) - 2; + + // Let V_i be a 64-byte block and W_i be its first 32 bytes. + // V_1 = H^(64)(LE32(T)||A) + // V_2 = H^(64)(V_1) + // ... + // V_r = H^(64)(V_{r-1}) + // V_{r+1} = H^(T-32*r)(V_{r}) + // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1} + for (let i = 0; i < r; i++) { + createHash(64).update(i === 0 ? V1_in : V).digest(V); + // store W_i in result buffer already + res.set(V.subarray(0, 32), i*32); + } + // V_{r+1} + const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest()); + res.set(V_r1, r*32); + + return res; +} + +// compute buf = xs ^ ys +function XOR(wasmContext, buf, xs, ys) { + wasmContext.fn.XOR( + buf.byteOffset, + xs.byteOffset, + ys.byteOffset, + ); + return buf +} + +/** + * @param {Uint8Array} X (read-only) + * @param {Uint8Array} Y (read-only) + * @param {Uint8Array} R - output buffer + * @returns + */ +function G(wasmContext, X, Y, R) { + wasmContext.fn.G( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +function G2(wasmContext, X, Y, R) { + wasmContext.fn.G2( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values. +function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) { + // For each segment, we do the following. First, we compute the value Z as: + // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) ) + wasmContext.refs.prngTmp.fill(0); + const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8); + LE64(Z, pass, 0); + LE64(Z, lane, 8); + LE64(Z, slice, 16); + LE64(Z, m_, 24); + LE64(Z, totalPasses, 32); + LE64(Z, TYPE, 40); + + // Then we compute q/(128*SL) 1024-byte values + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ), + // ..., + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )), + for(let i = 1; i <= segmentLength; i++) { + // tmp.set(Z); // no need to re-copy + LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed + const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR ); + + // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2 + // NB: the first generated pair must be used for the first block of the segment, and so on. + // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset. + for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) { + yield g2.subarray(k, k+8); + } + } + return []; +} + +function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) { + const assertLength = (name, value, min, max) => { + if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); } + }; + + if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version'); + assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX); + assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX); + assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX); + assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX); + // optional fields + ad && assertLength('associated data', ad, 0, ADBYTES_MAX); + secret && assertLength('secret', secret, 0, SECRETBYTES_MAX); + + return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes }; +} + +const KB = 1024; +const WASM_PAGE_SIZE = 64 * KB; + +function argon2id(params, { memory, instance: wasmInstance }) { + if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system + + const ctx = validateParams({ type: TYPE, version: VERSION, ...params }); + + const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports; + const wasmRefs = {}; + const wasmFn = {}; + wasmFn.G = wasmG; + wasmFn.G2 = wasmG2; + wasmFn.XOR = wasmXOR; + + // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p. + const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes)); + const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references + if (memory.buffer.byteLength < requiredMemory) { + const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE); + // If enough memory is available, the `memory.buffer` is internally detached and the reference updated. + // Otherwise, the operation fails, and the original memory can still be used. + memory.grow(missing); + } + + let offset = 0; + // Init wasm memory needed in other functions + wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length; + wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length; + wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length; + wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length; + // Init wasm memory needed locally + const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT; + const wasmContext = { fn: wasmFn, refs: wasmRefs }; + const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length; + const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE); + const allocatedMemory = new Uint8Array(memory.buffer, 0, offset); + + // 1. Establish H_0 + const H0 = getH0(ctx); + + // 2. Allocate the memory as m' 1024-byte blocks + // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns. + const q = m_ / ctx.lanes; + const B = new Array(ctx.lanes).fill(null).map(() => new Array(q)); + const initBlock = (i, j) => { + B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE); + return B[i][j]; + }; + + for (let i = 0; i < ctx.lanes; i++) { + // const LEi = LE0; // since p = 1 for us + const tmp = new Uint8Array(H0.length + 8); + // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0)); + // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + LE32(tmp, 1, H0.length); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1)); + } + + // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2 + // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes + // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc. + const SL = 4; // vertical slices + const segmentLength = q / SL; + for (let pass = 0; pass < ctx.passes; pass++) { + // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel + for (let sl = 0; sl < SL; sl++) { + const isDataIndependent = pass === 0 && sl <= 1; + for (let i = 0; i < ctx.lanes; i++) { // lane + // On the first slice of the first pass, blocks 0 and 1 are already filled + let segmentOffset = sl === 0 && pass === 0 ? 2 : 0; + // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory) + const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null; + for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) { + const j = sl * segmentLength + segmentOffset; + const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q] + + // we can assume the PRNG is never done + const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength); + const l = lz[0]; const z = lz[1]; + // for (let i = 0; i < p; i++ ) + // B[i][j] = G(B[i][j-1], B[l][z]) + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + if (pass === 0) initBlock(i, j); + G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]); + + // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one + if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]); + } + } + } + } + + // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column: + // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1] + const C = B[0][q-1]; + for(let i = 1; i < ctx.lanes; i++) { + XOR(wasmContext, C, C, B[i][q-1]); + } + + const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength)); + // clear memory since the module might be cached + allocatedMemory.fill(0); // clear sensitive contents + memory.grow(0); // allow deallocation + // 8. The output tag is computed as H'^T(C). + return tag; + +} + +function getH0(ctx) { + const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH); + const ZERO32 = new Uint8Array(4); + const params = new Uint8Array(24); + LE32(params, ctx.lanes, 0); + LE32(params, ctx.tagLength, 4); + LE32(params, ctx.memorySize, 8); + LE32(params, ctx.passes, 12); + LE32(params, ctx.version, 16); + LE32(params, ctx.type, 20); + + const toHash = [params]; + if (ctx.password) { + toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0)); + toHash.push(ctx.password); + } else { + toHash.push(ZERO32); // context.password.length + } + + if (ctx.salt) { + toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0)); + toHash.push(ctx.salt); + } else { + toHash.push(ZERO32); // context.salt.length + } + + if (ctx.secret) { + toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0)); + toHash.push(ctx.secret); + // todo clear secret? + } else { + toHash.push(ZERO32); // context.secret.length + } + + if (ctx.ad) { + toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0)); + toHash.push(ctx.ad); + } else { + toHash.push(ZERO32); // context.ad.length + } + H.update(concatArrays(toHash)); + + const outputBuffer = H.digest(); + return new Uint8Array(outputBuffer); +} + +function concatArrays(arrays) { + if (arrays.length === 1) return arrays[0]; + + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!(arrays[i] instanceof Uint8Array)) { + throw new Error('concatArrays: Data must be in the form of a Uint8Array'); + } + + totalLength += arrays[i].length; + } + + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach((element) => { + result.set(element, pos); + pos += element.length; + }); + + return result; +} + +let isSIMDSupported; +async function wasmLoader(memory, getSIMD, getNonSIMD) { + const importObject = { env: { memory } }; + if (isSIMDSupported === undefined) { + try { + const loaded = await getSIMD(importObject); + isSIMDSupported = true; + return loaded; + } catch(e) { + isSIMDSupported = false; + } + } + + const loader = isSIMDSupported ? getSIMD : getNonSIMD; + return loader(importObject); +} + +async function setupWasm(getSIMD, getNonSIMD) { + const memory = new WebAssembly.Memory({ + // in pages of 64KiB each + // these values need to be compatible with those declared when building in `build-wasm` + initial: 1040, // 65MB + maximum: 65536, // 4GB + }); + const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD); + + /** + * Argon2id hash function + * @callback computeHash + * @param {Object} params + * @param {Uint8Array} params.password - password + * @param {Uint8Array} params.salt - salt + * @param {Integer} params.parallelism + * @param {Integer} params.passes + * @param {Integer} params.memorySize - in kibibytes + * @param {Integer} params.tagLength - output tag length + * @param {Uint8Array} [params.ad] - associated data (optional) + * @param {Uint8Array} [params.secret] - secret data (optional) + * @return {Uint8Array} argon2id hash + */ + const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory }); + + return computeHash; +} + +function _loadWasmModule (sync, filepath, src, imports) { + function _instantiateOrCompile(source, imports, stream) { + var instantiateFunc = WebAssembly.instantiate; + var compileFunc = WebAssembly.compile; + + if (imports) { + return instantiateFunc(source, imports) + } else { + return compileFunc(source) + } + } + + +var buf = null; + + +var raw = globalThis.atob(src); +var rawLength = raw.length; +buf = new Uint8Array(new ArrayBuffer(rawLength)); +for(var i = 0; i < rawLength; i++) { + buf[i] = raw.charCodeAt(i); +} + + + + { + return _instantiateOrCompile(buf, imports) + } +} + +function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoAB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ASAAIANq/QAEACAB/QAEAP1R/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)} + +function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTc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ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)} + +const loadWasm = async () => setupWasm( + (instanceObject) => wasmSIMD(instanceObject), + (instanceObject) => wasmNonSIMD(instanceObject), +); + +export { loadWasm as default }; diff --git a/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs b/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs deleted file mode 100644 index ded8ad20f..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs +++ /dev/null @@ -1,3 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import e from"./bn.min.mjs";import"./openpgp.min.mjs";class t{constructor(t){if(void 0===t)throw Error("Invalid BigInteger input");this.value=new e(t)}clone(){const e=new t(null);return this.value.copy(e.value),e}iinc(){return this.value.iadd(new e(1)),this}inc(){return this.clone().iinc()}idec(){return this.value.isub(new e(1)),this}dec(){return this.clone().idec()}iadd(e){return this.value.iadd(e.value),this}add(e){return this.clone().iadd(e)}isub(e){return this.value.isub(e.value),this}sub(e){return this.clone().isub(e)}imul(e){return this.value.imul(e.value),this}mul(e){return this.clone().imul(e)}imod(e){return this.value=this.value.umod(e.value),this}mod(e){return this.clone().imod(e)}modExp(t,i){const r=i.isEven()?e.red(i.value):e.mont(i.value),u=this.clone();return u.value=u.value.toRed(r).redPow(t.value).fromRed(),u}modInv(e){if(!this.gcd(e).isOne())throw Error("Inverse does not exist");return new t(this.value.invm(e.value))}gcd(e){return new t(this.value.gcd(e.value))}ileftShift(e){return this.value.ishln(e.value.toNumber()),this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value.ishrn(e.value.toNumber()),this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value.eq(e.value)}lt(e){return this.value.lt(e.value)}lte(e){return this.value.lte(e.value)}gt(e){return this.value.gt(e.value)}gte(e){return this.value.gte(e.value)}isZero(){return this.value.isZero()}isOne(){return this.value.eq(new e(1))}isNegative(){return this.value.isNeg()}isEven(){return this.value.isEven()}abs(){const e=this.clone();return e.value=e.value.abs(),e}toString(){return this.value.toString()}toNumber(){return this.value.toNumber()}getBit(e){return this.value.testn(e)?1:0}bitLength(){return this.value.bitLength()}byteLength(){return this.value.byteLength()}toUint8Array(e="be",t){return this.value.toArrayLike(Uint8Array,e,t)}}export default t; -//# sourceMappingURL=bn.interface.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs.map deleted file mode 100644 index 3f6b23580..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.interface.min.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bn.interface.min.mjs","sources":["../../src/biginteger/bn.interface.js"],"sourcesContent":["import BN from 'bn.js';\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)\n * @module biginteger/bn\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n this.value = new BN(n);\n }\n\n clone() {\n const clone = new BigInteger(null);\n this.value.copy(clone.value);\n return clone;\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value.iadd(new BN(1));\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value.isub(new BN(1));\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value.iadd(x.value);\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value.isub(x.value);\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value.imul(x.value);\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value = this.value.umod(m.value);\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation\n * Much faster than this.exp(e).mod(n)\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n // We use either Montgomery or normal reduction context\n // Montgomery requires coprime n and R (montogmery multiplier)\n // bn.js picks R as power of 2, so n must be odd\n const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);\n const x = this.clone();\n x.value = x.value.toRed(nred).redPow(e.value).fromRed();\n return x;\n }\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n // invm returns a wrong result if the inverse does not exist\n if (!this.gcd(n).isOne()) {\n throw new Error('Inverse does not exist');\n }\n return new BigInteger(this.value.invm(n.value));\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} n - Operand\n * @returns {BigInteger} gcd\n */\n gcd(n) {\n return new BigInteger(this.value.gcd(n.value));\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value.ishln(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value.ishrn(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value.eq(x.value);\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value.lt(x.value);\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value.lte(x.value);\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value.gt(x.value);\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value.gte(x.value);\n }\n\n isZero() {\n return this.value.isZero();\n }\n\n isOne() {\n return this.value.eq(new BN(1));\n }\n\n isNegative() {\n return this.value.isNeg();\n }\n\n isEven() {\n return this.value.isEven();\n }\n\n abs() {\n const res = this.clone();\n res.value = res.value.abs();\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n return this.value.toNumber();\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n return this.value.testn(i) ? 1 : 0;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n return this.value.bitLength();\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n return this.value.byteLength();\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n return this.value.toArrayLike(Uint8Array, endian, length);\n }\n}\n"],"names":["BigInteger","constructor","n","undefined","Error","this","value","BN","clone","copy","iinc","iadd","inc","idec","isub","dec","x","add","sub","imul","mul","imod","m","umod","mod","modExp","e","nred","isEven","red","mont","toRed","redPow","fromRed","modInv","gcd","isOne","invm","ileftShift","ishln","toNumber","leftShift","irightShift","ishrn","rightShift","equal","eq","lt","lte","gt","gte","isZero","isNegative","isNeg","abs","res","toString","getBit","i","testn","bitLength","byteLength","toUint8Array","endian","length","toArrayLike","Uint8Array"],"mappings":";yJAae,MAAMA,EAMnBC,YAAYC,GACV,QAAUC,IAAND,EACF,MAAUE,MAAM,4BAGlBC,KAAKC,MAAQ,IAAIC,EAAGL,GAGtBM,QACE,MAAMA,EAAQ,IAAIR,EAAW,MAE7B,OADAK,KAAKC,MAAMG,KAAKD,EAAMF,OACfE,EAMTE,OAEE,OADAL,KAAKC,MAAMK,KAAK,IAAIJ,EAAG,IAChBF,KAOTO,MACE,OAAOP,KAAKG,QAAQE,OAMtBG,OAEE,OADAR,KAAKC,MAAMQ,KAAK,IAAIP,EAAG,IAChBF,KAOTU,MACE,OAAOV,KAAKG,QAAQK,OAQtBF,KAAKK,GAEH,OADAX,KAAKC,MAAMK,KAAKK,EAAEV,OACXD,KAQTY,IAAID,GACF,OAAOX,KAAKG,QAAQG,KAAKK,GAO3BF,KAAKE,GAEH,OADAX,KAAKC,MAAMQ,KAAKE,EAAEV,OACXD,KAQTa,IAAIF,GACF,OAAOX,KAAKG,QAAQM,KAAKE,GAO3BG,KAAKH,GAEH,OADAX,KAAKC,MAAMa,KAAKH,EAAEV,OACXD,KAQTe,IAAIJ,GACF,OAAOX,KAAKG,QAAQW,KAAKH,GAO3BK,KAAKC,GAEH,OADAjB,KAAKC,MAAQD,KAAKC,MAAMiB,KAAKD,EAAEhB,OACxBD,KAQTmB,IAAIF,GACF,OAAOjB,KAAKG,QAAQa,KAAKC,GAU3BG,OAAOC,EAAGxB,GAIR,MAAMyB,EAAOzB,EAAE0B,SAAWrB,EAAGsB,IAAI3B,EAAEI,OAASC,EAAGuB,KAAK5B,EAAEI,OAChDU,EAAIX,KAAKG,QAEf,OADAQ,EAAEV,MAAQU,EAAEV,MAAMyB,MAAMJ,GAAMK,OAAON,EAAEpB,OAA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D,YAOpBC,aACE,OAAOxD,KAAKC,MAAMuD,aASpBC,aAAaC,EAAS,KAAMC,GAC1B,OAAO3D,KAAKC,MAAM2D,YAAYC,WAAYH,EAAQC"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/bn.interface.mjs b/app/node_modules/openpgp/dist/lightweight/bn.interface.mjs deleted file mode 100644 index 6fe2f8534..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.interface.mjs +++ /dev/null @@ -1,340 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -import bn from './bn.mjs'; -import './openpgp.mjs'; - -/** - * @fileoverview - * BigInteger implementation of basic operations - * Wrapper of bn.js library (wwww.github.com/indutny/bn.js) - * @module biginteger/bn - * @private - */ - -/** - * @private - */ -class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - - this.value = new bn(n); - } - - clone() { - const clone = new BigInteger(null); - this.value.copy(clone.value); - return clone; - } - - /** - * BigInteger increment in place - */ - iinc() { - this.value.iadd(new bn(1)); - return this; - } - - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - - /** - * BigInteger decrement in place - */ - idec() { - this.value.isub(new bn(1)); - return this; - } - - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } - - - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value.iadd(x.value); - return this; - } - - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } - - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value.isub(x.value); - return this; - } - - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } - - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value.imul(x.value); - return this; - } - - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); - } - - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value = this.value.umod(m.value); - return this; - } - - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } - - /** - * Compute modular exponentiation - * Much faster than this.exp(e).mod(n) - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - // We use either Montgomery or normal reduction context - // Montgomery requires coprime n and R (montogmery multiplier) - // bn.js picks R as power of 2, so n must be odd - const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value); - const x = this.clone(); - x.value = x.value.toRed(nred).redPow(e.value).fromRed(); - return x; - } - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - // invm returns a wrong result if the inverse does not exist - if (!this.gcd(n).isOne()) { - throw new Error('Inverse does not exist'); - } - return new BigInteger(this.value.invm(n.value)); - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} n - Operand - * @returns {BigInteger} gcd - */ - gcd(n) { - return new BigInteger(this.value.gcd(n.value)); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value.ishln(x.value.toNumber()); - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value.ishrn(x.value.toNumber()); - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value.eq(x.value); - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value.lt(x.value); - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value.lte(x.value); - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value.gt(x.value); - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value.gte(x.value); - } - - isZero() { - return this.value.isZero(); - } - - isOne() { - return this.value.eq(new bn(1)); - } - - isNegative() { - return this.value.isNeg(); - } - - isEven() { - return this.value.isEven(); - } - - abs() { - const res = this.clone(); - res.value = res.value.abs(); - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - return this.value.toNumber(); - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - return this.value.testn(i) ? 1 : 0; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - return this.value.bitLength(); - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - return this.value.byteLength(); - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - return this.value.toArrayLike(Uint8Array, endian, length); - } -} - -export default BigInteger; diff --git a/app/node_modules/openpgp/dist/lightweight/bn.min.mjs b/app/node_modules/openpgp/dist/lightweight/bn.min.mjs deleted file mode 100644 index 64f86c3e3..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.min.mjs +++ /dev/null @@ -1,3 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import{c as t,a as i}from"./openpgp.min.mjs";var r=t((function(t){!function(t,i){function r(t,i){if(!t)throw Error(i||"Assertion failed")}function h(t,i){t.super_=i;var r=function(){};r.prototype=i.prototype,t.prototype=new r,t.prototype.constructor=t}function n(t,i,r){if(n.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==i&&"be"!==i||(r=i,i=10),this._init(t||0,i||10,r||"be"))}var e;"object"==typeof t?t.exports=n:i.BN=n,n.BN=n,n.wordSize=26;try{e=void 0}catch(t){}function o(t,i,r){for(var h=0,n=Math.min(t.length,r),e=i;e=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return h}function s(t,i,r,h){for(var n=0,e=Math.min(t.length,r),o=i;o=49?s-49+10:s>=17?s-17+10:s}return n}n.isBN=function(t){return t instanceof n||null!==t&&"object"==typeof t&&t.constructor.wordSize===n.wordSize&&Array.isArray(t.words)},n.max=function(t,i){return t.cmp(i)>0?t:i},n.min=function(t,i){return t.cmp(i)<0?t:i},n.prototype._init=function(t,i,h){if("number"==typeof t)return this._initNumber(t,i,h);if("object"==typeof t)return this._initArray(t,i,h);"hex"===i&&(i=16),r(i===(0|i)&&i>=2&&i<=36);var n=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&n++,16===i?this._parseHex(t,n):this._parseBase(t,i,n),"-"===t[0]&&(this.negative=1),this.strip(),"le"===h&&this._initArray(this.toArray(),i,h)},n.prototype._initNumber=function(t,i,h){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===h&&this._initArray(this.toArray(),i,h)},n.prototype._initArray=function(t,i,h){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=Array(this.length);for(var n=0;n=0;n-=3)o=t[n]|t[n-1]<<8|t[n-2]<<16,this.words[e]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,e++);else if("le"===h)for(n=0,e=0;n>>26-s&67108863,(s+=24)>=26&&(s-=26,e++);return this.strip()},n.prototype._parseHex=function(t,i){this.length=Math.ceil((t.length-i)/6),this.words=Array(this.length);for(var r=0;r=i;r-=6)n=o(t,r,r+6),this.words[h]|=n<>>26-e&4194303,(e+=24)>=26&&(e-=26,h++);r+6!==i&&(n=o(t,i,r+6),this.words[h]|=n<>>26-e&4194303),this.strip()},n.prototype._parseBase=function(t,i,r){this.words=[0],this.length=1;for(var h=0,n=1;n<=67108863;n*=i)h++;h--,n=n/i|0;for(var e=t.length-r,o=e%h,u=Math.min(e,e-o)+r,a=0,l=r;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],a=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],l=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function m(t,i,r){r.negative=i.negative^t.negative;var h=t.length+i.length|0;r.length=h,h=h-1|0;var n=0|t.words[0],e=0|i.words[0],o=n*e,s=67108863&o,u=o/67108864|0;r.words[0]=s;for(var a=1;a>>26,m=67108863&u,f=Math.min(a,i.length-1),d=Math.max(0,a-t.length+1);d<=f;d++){var p=a-d|0;l+=(o=(n=0|t.words[p])*(e=0|i.words[d])+m)/67108864|0,m=67108863&o}r.words[a]=0|m,u=0|l}return 0!==u?r.words[a]=0|u:r.length--,r.strip()}n.prototype.toString=function(t,i){var h;if(i=0|i||1,16===(t=t||10)||"hex"===t){h="";for(var n=0,e=0,o=0;o>>24-n&16777215)||o!==this.length-1?u[6-m.length]+m+h:m+h,(n+=2)>=26&&(n-=26,o--)}for(0!==e&&(h=e.toString(16)+h);h.length%i!=0;)h="0"+h;return 0!==this.negative&&(h="-"+h),h}if(t===(0|t)&&t>=2&&t<=36){var f=a[t],d=l[t];h="";var p=this.clone();for(p.negative=0;!p.isZero();){var M=p.modn(d).toString(t);h=(p=p.idivn(d)).isZero()?M+h:u[f-M.length]+M+h}for(this.isZero()&&(h="0"+h);h.length%i!=0;)h="0"+h;return 0!==this.negative&&(h="-"+h),h}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(t,i){return r(void 0!==e),this.toArrayLike(e,t,i)},n.prototype.toArray=function(t,i){return this.toArrayLike(Array,t,i)},n.prototype.toArrayLike=function(t,i,h){var n=this.byteLength(),e=h||Math.max(1,n);r(n<=e,"byte array longer than desired length"),r(e>0,"Requested array length <= 0"),this.strip();var o,s,u="le"===i,a=new t(e),l=this.clone();if(u){for(s=0;!l.isZero();s++)o=l.andln(255),l.iushrn(8),a[s]=o;for(;s=4096&&(r+=13,i>>>=13),i>=64&&(r+=7,i>>>=7),i>=8&&(r+=4,i>>>=4),i>=2&&(r+=2,i>>>=2),r+i},n.prototype._zeroBits=function(t){if(0===t)return 26;var i=t,r=0;return 0==(8191&i)&&(r+=13,i>>>=13),0==(127&i)&&(r+=7,i>>>=7),0==(15&i)&&(r+=4,i>>>=4),0==(3&i)&&(r+=2,i>>>=2),0==(1&i)&&r++,r},n.prototype.bitLength=function(){var t=this.words[this.length-1],i=this._countBits(t);return 26*(this.length-1)+i},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,i=0;it.length?this.clone().ior(t):t.clone().ior(this)},n.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},n.prototype.iuand=function(t){var i;i=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},n.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},n.prototype.iuxor=function(t){var i,r;this.length>t.length?(i=this,r=t):(i=t,r=this);for(var h=0;ht.length?this.clone().ixor(t):t.clone().ixor(this)},n.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},n.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var i=0|Math.ceil(t/26),h=t%26;this._expand(i),h>0&&i--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-h),this.strip()},n.prototype.notn=function(t){return this.clone().inotn(t)},n.prototype.setn=function(t,i){r("number"==typeof t&&t>=0);var h=t/26|0,n=t%26;return this._expand(h+1),this.words[h]=i?this.words[h]|1<t.length?(r=this,h=t):(r=t,h=this);for(var n=0,e=0;e>>26;for(;0!==n&&e>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;et.length?this.clone().iadd(t):t.clone().iadd(this)},n.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var i=this.iadd(t);return t.negative=1,i._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,h,n=this.cmp(t);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,h=t):(r=t,h=this);for(var e=0,o=0;o>26,this.words[o]=67108863&i;for(;0!==e&&o>26,this.words[o]=67108863&i;if(0===e&&o>>13,d=0|o[1],p=8191&d,M=d>>>13,v=0|o[2],g=8191&v,c=v>>>13,w=0|o[3],y=8191&w,b=w>>>13,_=0|o[4],k=8191&_,A=_>>>13,x=0|o[5],S=8191&x,Z=x>>>13,R=0|o[6],q=8191&R,B=R>>>13,N=0|o[7],L=8191&N,I=N>>>13,z=0|o[8],E=8191&z,T=z>>>13,O=0|o[9],j=8191&O,K=O>>>13,P=0|s[0],F=8191&P,C=P>>>13,D=0|s[1],H=8191&D,J=D>>>13,U=0|s[2],G=8191&U,Q=U>>>13,V=0|s[3],W=8191&V,X=V>>>13,Y=0|s[4],$=8191&Y,tt=Y>>>13,it=0|s[5],rt=8191&it,ht=it>>>13,nt=0|s[6],et=8191&nt,ot=nt>>>13,st=0|s[7],ut=8191&st,at=st>>>13,lt=0|s[8],mt=8191<,ft=lt>>>13,dt=0|s[9],pt=8191&dt,Mt=dt>>>13;r.negative=t.negative^i.negative,r.length=19;var vt=(a+(h=Math.imul(m,F))|0)+((8191&(n=(n=Math.imul(m,C))+Math.imul(f,F)|0))<<13)|0;a=((e=Math.imul(f,C))+(n>>>13)|0)+(vt>>>26)|0,vt&=67108863,h=Math.imul(p,F),n=(n=Math.imul(p,C))+Math.imul(M,F)|0,e=Math.imul(M,C);var gt=(a+(h=h+Math.imul(m,H)|0)|0)+((8191&(n=(n=n+Math.imul(m,J)|0)+Math.imul(f,H)|0))<<13)|0;a=((e=e+Math.imul(f,J)|0)+(n>>>13)|0)+(gt>>>26)|0,gt&=67108863,h=Math.imul(g,F),n=(n=Math.imul(g,C))+Math.imul(c,F)|0,e=Math.imul(c,C),h=h+Math.imul(p,H)|0,n=(n=n+Math.imul(p,J)|0)+Math.imul(M,H)|0,e=e+Math.imul(M,J)|0;var ct=(a+(h=h+Math.imul(m,G)|0)|0)+((8191&(n=(n=n+Math.imul(m,Q)|0)+Math.imul(f,G)|0))<<13)|0;a=((e=e+Math.imul(f,Q)|0)+(n>>>13)|0)+(ct>>>26)|0,ct&=67108863,h=Math.imul(y,F),n=(n=Math.imul(y,C))+Math.imul(b,F)|0,e=Math.imul(b,C),h=h+Math.imul(g,H)|0,n=(n=n+Math.imul(g,J)|0)+Math.imul(c,H)|0,e=e+Math.imul(c,J)|0,h=h+Math.imul(p,G)|0,n=(n=n+Math.imul(p,Q)|0)+Math.imul(M,G)|0,e=e+Math.imul(M,Q)|0;var wt=(a+(h=h+Math.imul(m,W)|0)|0)+((8191&(n=(n=n+Math.imul(m,X)|0)+Math.imul(f,W)|0))<<13)|0;a=((e=e+Math.imul(f,X)|0)+(n>>>13)|0)+(wt>>>26)|0,wt&=67108863,h=Math.imul(k,F),n=(n=Math.imul(k,C))+Math.imul(A,F)|0,e=Math.imul(A,C),h=h+Math.imul(y,H)|0,n=(n=n+Math.imul(y,J)|0)+Math.imul(b,H)|0,e=e+Math.imul(b,J)|0,h=h+Math.imul(g,G)|0,n=(n=n+Math.imul(g,Q)|0)+Math.imul(c,G)|0,e=e+Math.imul(c,Q)|0,h=h+Math.imul(p,W)|0,n=(n=n+Math.imul(p,X)|0)+Math.imul(M,W)|0,e=e+Math.imul(M,X)|0;var yt=(a+(h=h+Math.imul(m,$)|0)|0)+((8191&(n=(n=n+Math.imul(m,tt)|0)+Math.imul(f,$)|0))<<13)|0;a=((e=e+Math.imul(f,tt)|0)+(n>>>13)|0)+(yt>>>26)|0,yt&=67108863,h=Math.imul(S,F),n=(n=Math.imul(S,C))+Math.imul(Z,F)|0,e=Math.imul(Z,C),h=h+Math.imul(k,H)|0,n=(n=n+Math.imul(k,J)|0)+Math.imul(A,H)|0,e=e+Math.imul(A,J)|0,h=h+Math.imul(y,G)|0,n=(n=n+Math.imul(y,Q)|0)+Math.imul(b,G)|0,e=e+Math.imul(b,Q)|0,h=h+Math.imul(g,W)|0,n=(n=n+Math.imul(g,X)|0)+Math.imul(c,W)|0,e=e+Math.imul(c,X)|0,h=h+Math.imul(p,$)|0,n=(n=n+Math.imul(p,tt)|0)+Math.imul(M,$)|0,e=e+Math.imul(M,tt)|0;var bt=(a+(h=h+Math.imul(m,rt)|0)|0)+((8191&(n=(n=n+Math.imul(m,ht)|0)+Math.imul(f,rt)|0))<<13)|0;a=((e=e+Math.imul(f,ht)|0)+(n>>>13)|0)+(bt>>>26)|0,bt&=67108863,h=Math.imul(q,F),n=(n=Math.imul(q,C))+Math.imul(B,F)|0,e=Math.imul(B,C),h=h+Math.imul(S,H)|0,n=(n=n+Math.imul(S,J)|0)+Math.imul(Z,H)|0,e=e+Math.imul(Z,J)|0,h=h+Math.imul(k,G)|0,n=(n=n+Math.imul(k,Q)|0)+Math.imul(A,G)|0,e=e+Math.imul(A,Q)|0,h=h+Math.imul(y,W)|0,n=(n=n+Math.imul(y,X)|0)+Math.imul(b,W)|0,e=e+Math.imul(b,X)|0,h=h+Math.imul(g,$)|0,n=(n=n+Math.imul(g,tt)|0)+Math.imul(c,$)|0,e=e+Math.imul(c,tt)|0,h=h+Math.imul(p,rt)|0,n=(n=n+Math.imul(p,ht)|0)+Math.imul(M,rt)|0,e=e+Math.imul(M,ht)|0;var _t=(a+(h=h+Math.imul(m,et)|0)|0)+((8191&(n=(n=n+Math.imul(m,ot)|0)+Math.imul(f,et)|0))<<13)|0;a=((e=e+Math.imul(f,ot)|0)+(n>>>13)|0)+(_t>>>26)|0,_t&=67108863,h=Math.imul(L,F),n=(n=Math.imul(L,C))+Math.imul(I,F)|0,e=Math.imul(I,C),h=h+Math.imul(q,H)|0,n=(n=n+Math.imul(q,J)|0)+Math.imul(B,H)|0,e=e+Math.imul(B,J)|0,h=h+Math.imul(S,G)|0,n=(n=n+Math.imul(S,Q)|0)+Math.imul(Z,G)|0,e=e+Math.imul(Z,Q)|0,h=h+Math.imul(k,W)|0,n=(n=n+Math.imul(k,X)|0)+Math.imul(A,W)|0,e=e+Math.imul(A,X)|0,h=h+Math.imul(y,$)|0,n=(n=n+Math.imul(y,tt)|0)+Math.imul(b,$)|0,e=e+Math.imul(b,tt)|0,h=h+Math.imul(g,rt)|0,n=(n=n+Math.imul(g,ht)|0)+Math.imul(c,rt)|0,e=e+Math.imul(c,ht)|0,h=h+Math.imul(p,et)|0,n=(n=n+Math.imul(p,ot)|0)+Math.imul(M,et)|0,e=e+Math.imul(M,ot)|0;var kt=(a+(h=h+Math.imul(m,ut)|0)|0)+((8191&(n=(n=n+Math.imul(m,at)|0)+Math.imul(f,ut)|0))<<13)|0;a=((e=e+Math.imul(f,at)|0)+(n>>>13)|0)+(kt>>>26)|0,kt&=67108863,h=Math.imul(E,F),n=(n=Math.imul(E,C))+Math.imul(T,F)|0,e=Math.imul(T,C),h=h+Math.imul(L,H)|0,n=(n=n+Math.imul(L,J)|0)+Math.imul(I,H)|0,e=e+Math.imul(I,J)|0,h=h+Math.imul(q,G)|0,n=(n=n+Math.imul(q,Q)|0)+Math.imul(B,G)|0,e=e+Math.imul(B,Q)|0,h=h+Math.imul(S,W)|0,n=(n=n+Math.imul(S,X)|0)+Math.imul(Z,W)|0,e=e+Math.imul(Z,X)|0,h=h+Math.imul(k,$)|0,n=(n=n+Math.imul(k,tt)|0)+Math.imul(A,$)|0,e=e+Math.imul(A,tt)|0,h=h+Math.imul(y,rt)|0,n=(n=n+Math.imul(y,ht)|0)+Math.imul(b,rt)|0,e=e+Math.imul(b,ht)|0,h=h+Math.imul(g,et)|0,n=(n=n+Math.imul(g,ot)|0)+Math.imul(c,et)|0,e=e+Math.imul(c,ot)|0,h=h+Math.imul(p,ut)|0,n=(n=n+Math.imul(p,at)|0)+Math.imul(M,ut)|0,e=e+Math.imul(M,at)|0;var At=(a+(h=h+Math.imul(m,mt)|0)|0)+((8191&(n=(n=n+Math.imul(m,ft)|0)+Math.imul(f,mt)|0))<<13)|0;a=((e=e+Math.imul(f,ft)|0)+(n>>>13)|0)+(At>>>26)|0,At&=67108863,h=Math.imul(j,F),n=(n=Math.imul(j,C))+Math.imul(K,F)|0,e=Math.imul(K,C),h=h+Math.imul(E,H)|0,n=(n=n+Math.imul(E,J)|0)+Math.imul(T,H)|0,e=e+Math.imul(T,J)|0,h=h+Math.imul(L,G)|0,n=(n=n+Math.imul(L,Q)|0)+Math.imul(I,G)|0,e=e+Math.imul(I,Q)|0,h=h+Math.imul(q,W)|0,n=(n=n+Math.imul(q,X)|0)+Math.imul(B,W)|0,e=e+Math.imul(B,X)|0,h=h+Math.imul(S,$)|0,n=(n=n+Math.imul(S,tt)|0)+Math.imul(Z,$)|0,e=e+Math.imul(Z,tt)|0,h=h+Math.imul(k,rt)|0,n=(n=n+Math.imul(k,ht)|0)+Math.imul(A,rt)|0,e=e+Math.imul(A,ht)|0,h=h+Math.imul(y,et)|0,n=(n=n+Math.imul(y,ot)|0)+Math.imul(b,et)|0,e=e+Math.imul(b,ot)|0,h=h+Math.imul(g,ut)|0,n=(n=n+Math.imul(g,at)|0)+Math.imul(c,ut)|0,e=e+Math.imul(c,at)|0,h=h+Math.imul(p,mt)|0,n=(n=n+Math.imul(p,ft)|0)+Math.imul(M,mt)|0,e=e+Math.imul(M,ft)|0;var xt=(a+(h=h+Math.imul(m,pt)|0)|0)+((8191&(n=(n=n+Math.imul(m,Mt)|0)+Math.imul(f,pt)|0))<<13)|0;a=((e=e+Math.imul(f,Mt)|0)+(n>>>13)|0)+(xt>>>26)|0,xt&=67108863,h=Math.imul(j,H),n=(n=Math.imul(j,J))+Math.imul(K,H)|0,e=Math.imul(K,J),h=h+Math.imul(E,G)|0,n=(n=n+Math.imul(E,Q)|0)+Math.imul(T,G)|0,e=e+Math.imul(T,Q)|0,h=h+Math.imul(L,W)|0,n=(n=n+Math.imul(L,X)|0)+Math.imul(I,W)|0,e=e+Math.imul(I,X)|0,h=h+Math.imul(q,$)|0,n=(n=n+Math.imul(q,tt)|0)+Math.imul(B,$)|0,e=e+Math.imul(B,tt)|0,h=h+Math.imul(S,rt)|0,n=(n=n+Math.imul(S,ht)|0)+Math.imul(Z,rt)|0,e=e+Math.imul(Z,ht)|0,h=h+Math.imul(k,et)|0,n=(n=n+Math.imul(k,ot)|0)+Math.imul(A,et)|0,e=e+Math.imul(A,ot)|0,h=h+Math.imul(y,ut)|0,n=(n=n+Math.imul(y,at)|0)+Math.imul(b,ut)|0,e=e+Math.imul(b,at)|0,h=h+Math.imul(g,mt)|0,n=(n=n+Math.imul(g,ft)|0)+Math.imul(c,mt)|0,e=e+Math.imul(c,ft)|0;var St=(a+(h=h+Math.imul(p,pt)|0)|0)+((8191&(n=(n=n+Math.imul(p,Mt)|0)+Math.imul(M,pt)|0))<<13)|0;a=((e=e+Math.imul(M,Mt)|0)+(n>>>13)|0)+(St>>>26)|0,St&=67108863,h=Math.imul(j,G),n=(n=Math.imul(j,Q))+Math.imul(K,G)|0,e=Math.imul(K,Q),h=h+Math.imul(E,W)|0,n=(n=n+Math.imul(E,X)|0)+Math.imul(T,W)|0,e=e+Math.imul(T,X)|0,h=h+Math.imul(L,$)|0,n=(n=n+Math.imul(L,tt)|0)+Math.imul(I,$)|0,e=e+Math.imul(I,tt)|0,h=h+Math.imul(q,rt)|0,n=(n=n+Math.imul(q,ht)|0)+Math.imul(B,rt)|0,e=e+Math.imul(B,ht)|0,h=h+Math.imul(S,et)|0,n=(n=n+Math.imul(S,ot)|0)+Math.imul(Z,et)|0,e=e+Math.imul(Z,ot)|0,h=h+Math.imul(k,ut)|0,n=(n=n+Math.imul(k,at)|0)+Math.imul(A,ut)|0,e=e+Math.imul(A,at)|0,h=h+Math.imul(y,mt)|0,n=(n=n+Math.imul(y,ft)|0)+Math.imul(b,mt)|0,e=e+Math.imul(b,ft)|0;var Zt=(a+(h=h+Math.imul(g,pt)|0)|0)+((8191&(n=(n=n+Math.imul(g,Mt)|0)+Math.imul(c,pt)|0))<<13)|0;a=((e=e+Math.imul(c,Mt)|0)+(n>>>13)|0)+(Zt>>>26)|0,Zt&=67108863,h=Math.imul(j,W),n=(n=Math.imul(j,X))+Math.imul(K,W)|0,e=Math.imul(K,X),h=h+Math.imul(E,$)|0,n=(n=n+Math.imul(E,tt)|0)+Math.imul(T,$)|0,e=e+Math.imul(T,tt)|0,h=h+Math.imul(L,rt)|0,n=(n=n+Math.imul(L,ht)|0)+Math.imul(I,rt)|0,e=e+Math.imul(I,ht)|0,h=h+Math.imul(q,et)|0,n=(n=n+Math.imul(q,ot)|0)+Math.imul(B,et)|0,e=e+Math.imul(B,ot)|0,h=h+Math.imul(S,ut)|0,n=(n=n+Math.imul(S,at)|0)+Math.imul(Z,ut)|0,e=e+Math.imul(Z,at)|0,h=h+Math.imul(k,mt)|0,n=(n=n+Math.imul(k,ft)|0)+Math.imul(A,mt)|0,e=e+Math.imul(A,ft)|0;var Rt=(a+(h=h+Math.imul(y,pt)|0)|0)+((8191&(n=(n=n+Math.imul(y,Mt)|0)+Math.imul(b,pt)|0))<<13)|0;a=((e=e+Math.imul(b,Mt)|0)+(n>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,h=Math.imul(j,$),n=(n=Math.imul(j,tt))+Math.imul(K,$)|0,e=Math.imul(K,tt),h=h+Math.imul(E,rt)|0,n=(n=n+Math.imul(E,ht)|0)+Math.imul(T,rt)|0,e=e+Math.imul(T,ht)|0,h=h+Math.imul(L,et)|0,n=(n=n+Math.imul(L,ot)|0)+Math.imul(I,et)|0,e=e+Math.imul(I,ot)|0,h=h+Math.imul(q,ut)|0,n=(n=n+Math.imul(q,at)|0)+Math.imul(B,ut)|0,e=e+Math.imul(B,at)|0,h=h+Math.imul(S,mt)|0,n=(n=n+Math.imul(S,ft)|0)+Math.imul(Z,mt)|0,e=e+Math.imul(Z,ft)|0;var qt=(a+(h=h+Math.imul(k,pt)|0)|0)+((8191&(n=(n=n+Math.imul(k,Mt)|0)+Math.imul(A,pt)|0))<<13)|0;a=((e=e+Math.imul(A,Mt)|0)+(n>>>13)|0)+(qt>>>26)|0,qt&=67108863,h=Math.imul(j,rt),n=(n=Math.imul(j,ht))+Math.imul(K,rt)|0,e=Math.imul(K,ht),h=h+Math.imul(E,et)|0,n=(n=n+Math.imul(E,ot)|0)+Math.imul(T,et)|0,e=e+Math.imul(T,ot)|0,h=h+Math.imul(L,ut)|0,n=(n=n+Math.imul(L,at)|0)+Math.imul(I,ut)|0,e=e+Math.imul(I,at)|0,h=h+Math.imul(q,mt)|0,n=(n=n+Math.imul(q,ft)|0)+Math.imul(B,mt)|0,e=e+Math.imul(B,ft)|0;var Bt=(a+(h=h+Math.imul(S,pt)|0)|0)+((8191&(n=(n=n+Math.imul(S,Mt)|0)+Math.imul(Z,pt)|0))<<13)|0;a=((e=e+Math.imul(Z,Mt)|0)+(n>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,h=Math.imul(j,et),n=(n=Math.imul(j,ot))+Math.imul(K,et)|0,e=Math.imul(K,ot),h=h+Math.imul(E,ut)|0,n=(n=n+Math.imul(E,at)|0)+Math.imul(T,ut)|0,e=e+Math.imul(T,at)|0,h=h+Math.imul(L,mt)|0,n=(n=n+Math.imul(L,ft)|0)+Math.imul(I,mt)|0,e=e+Math.imul(I,ft)|0;var Nt=(a+(h=h+Math.imul(q,pt)|0)|0)+((8191&(n=(n=n+Math.imul(q,Mt)|0)+Math.imul(B,pt)|0))<<13)|0;a=((e=e+Math.imul(B,Mt)|0)+(n>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,h=Math.imul(j,ut),n=(n=Math.imul(j,at))+Math.imul(K,ut)|0,e=Math.imul(K,at),h=h+Math.imul(E,mt)|0,n=(n=n+Math.imul(E,ft)|0)+Math.imul(T,mt)|0,e=e+Math.imul(T,ft)|0;var Lt=(a+(h=h+Math.imul(L,pt)|0)|0)+((8191&(n=(n=n+Math.imul(L,Mt)|0)+Math.imul(I,pt)|0))<<13)|0;a=((e=e+Math.imul(I,Mt)|0)+(n>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,h=Math.imul(j,mt),n=(n=Math.imul(j,ft))+Math.imul(K,mt)|0,e=Math.imul(K,ft);var It=(a+(h=h+Math.imul(E,pt)|0)|0)+((8191&(n=(n=n+Math.imul(E,Mt)|0)+Math.imul(T,pt)|0))<<13)|0;a=((e=e+Math.imul(T,Mt)|0)+(n>>>13)|0)+(It>>>26)|0,It&=67108863;var zt=(a+(h=Math.imul(j,pt))|0)+((8191&(n=(n=Math.imul(j,Mt))+Math.imul(K,pt)|0))<<13)|0;return a=((e=Math.imul(K,Mt))+(n>>>13)|0)+(zt>>>26)|0,zt&=67108863,u[0]=vt,u[1]=gt,u[2]=ct,u[3]=wt,u[4]=yt,u[5]=bt,u[6]=_t,u[7]=kt,u[8]=At,u[9]=xt,u[10]=St,u[11]=Zt,u[12]=Rt,u[13]=qt,u[14]=Bt,u[15]=Nt,u[16]=Lt,u[17]=It,u[18]=zt,0!==a&&(u[19]=a,r.length++),r};function d(t,i,r){return(new p).mulp(t,i,r)}function p(t,i){this.x=t,this.y=i}Math.imul||(f=m),n.prototype.mulTo=function(t,i){var r,h=this.length+t.length;return r=10===this.length&&10===t.length?f(this,t,i):h<63?m(this,t,i):h<1024?function(t,i,r){r.negative=i.negative^t.negative,r.length=t.length+i.length;for(var h=0,n=0,e=0;e>>26)|0)>>>26,o&=67108863}r.words[e]=s,h=o,o=n}return 0!==h?r.words[e]=h:r.length--,r.strip()}(this,t,i):d(this,t,i),r},p.prototype.makeRBT=function(t){for(var i=Array(t),r=n.prototype._countBits(t)-1,h=0;h>=1;return h},p.prototype.permute=function(t,i,r,h,n,e){for(var o=0;o>>=1)n++;return 1<>>=13,h[2*o+1]=8191&e,e>>>=13;for(o=2*i;o>=26,i+=n/67108864|0,i+=e>>>26,this.words[h]=67108863&e}return 0!==i&&(this.words[h]=i,this.length++),this},n.prototype.muln=function(t){return this.clone().imuln(t)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(t){var i=function(t){for(var i=Array(t.bitLength()),r=0;r>>n}return i}(t);if(0===i.length)return new n(1);for(var r=this,h=0;h=0);var i,h=t%26,n=(t-h)/26,e=67108863>>>26-h<<26-h;if(0!==h){var o=0;for(i=0;i>>26-h}o&&(this.words[i]=o,this.length++)}if(0!==n){for(i=this.length-1;i>=0;i--)this.words[i+n]=this.words[i];for(i=0;i=0),n=i?(i-i%26)/26:0;var e=t%26,o=Math.min((t-e)/26,this.length),s=67108863^67108863>>>e<o)for(this.length-=o,a=0;a=0&&(0!==l||a>=n);a--){var m=0|this.words[a];this.words[a]=l<<26-e|m>>>e,l=m&s}return u&&0!==l&&(u.words[u.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(t,i,h){return r(0===this.negative),this.iushrn(t,i,h)},n.prototype.shln=function(t){return this.clone().ishln(t)},n.prototype.ushln=function(t){return this.clone().iushln(t)},n.prototype.shrn=function(t){return this.clone().ishrn(t)},n.prototype.ushrn=function(t){return this.clone().iushrn(t)},n.prototype.testn=function(t){r("number"==typeof t&&t>=0);var i=t%26,h=(t-i)/26,n=1<=0);var i=t%26,h=(t-i)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=h)return this;if(0!==i&&h++,this.length=Math.min(h,this.length),0!==i){var n=67108863^67108863>>>i<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},n.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(u/67108864|0),this.words[n+h]=67108863&e}for(;n>26,this.words[n+h]=67108863&e;if(0===s)return this.strip();for(r(-1===s),s=0,n=0;n>26,this.words[n]=67108863&e;return this.negative=1,this.strip()},n.prototype._wordDiv=function(t,i){var r=(this.length,t.length),h=this.clone(),e=t,o=0|e.words[e.length-1];0!==(r=26-this._countBits(o))&&(e=e.ushln(r),h.iushln(r),o=0|e.words[e.length-1]);var s,u=h.length-e.length;if("mod"!==i){(s=new n(null)).length=u+1,s.words=Array(s.length);for(var a=0;a=0;m--){var f=67108864*(0|h.words[e.length+m])+(0|h.words[e.length+m-1]);for(f=Math.min(f/o|0,67108863),h._ishlnsubmul(e,f,m);0!==h.negative;)f--,h.negative=0,h._ishlnsubmul(e,1,m),h.isZero()||(h.negative^=1);s&&(s.words[m]=f)}return s&&s.strip(),h.strip(),"div"!==i&&0!==r&&h.iushrn(r),{div:s||null,mod:h}},n.prototype.divmod=function(t,i,h){return r(!t.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,i),"mod"!==i&&(e=s.div.neg()),"div"!==i&&(o=s.mod.neg(),h&&0!==o.negative&&o.iadd(t)),{div:e,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),i),"mod"!==i&&(e=s.div.neg()),{div:e,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),i),"div"!==i&&(o=s.mod.neg(),h&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new n(0),mod:this}:1===t.length?"div"===i?{div:this.divn(t.words[0]),mod:null}:"mod"===i?{div:null,mod:new n(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new n(this.modn(t.words[0]))}:this._wordDiv(t,i);var e,o,s},n.prototype.div=function(t){return this.divmod(t,"div",!1).div},n.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},n.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},n.prototype.divRound=function(t){var i=this.divmod(t);if(i.mod.isZero())return i.div;var r=0!==i.div.negative?i.mod.isub(t):i.mod,h=t.ushrn(1),n=t.andln(1),e=r.cmp(h);return e<0||1===n&&0===e?i.div:0!==i.div.negative?i.div.isubn(1):i.div.iaddn(1)},n.prototype.modn=function(t){r(t<=67108863);for(var i=(1<<26)%t,h=0,n=this.length-1;n>=0;n--)h=(i*h+(0|this.words[n]))%t;return h},n.prototype.idivn=function(t){r(t<=67108863);for(var i=0,h=this.length-1;h>=0;h--){var n=(0|this.words[h])+67108864*i;this.words[h]=n/t|0,i=n%t}return this.strip()},n.prototype.divn=function(t){return this.clone().idivn(t)},n.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var i=this,h=t.clone();i=0!==i.negative?i.umod(t):i.clone();for(var e=new n(1),o=new n(0),s=new n(0),u=new n(1),a=0;i.isEven()&&h.isEven();)i.iushrn(1),h.iushrn(1),++a;for(var l=h.clone(),m=i.clone();!i.isZero();){for(var f=0,d=1;0==(i.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(i.iushrn(f);f-- >0;)(e.isOdd()||o.isOdd())&&(e.iadd(l),o.isub(m)),e.iushrn(1),o.iushrn(1);for(var p=0,M=1;0==(h.words[0]&M)&&p<26;++p,M<<=1);if(p>0)for(h.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(l),u.isub(m)),s.iushrn(1),u.iushrn(1);i.cmp(h)>=0?(i.isub(h),e.isub(s),o.isub(u)):(h.isub(i),s.isub(e),u.isub(o))}return{a:s,b:u,gcd:h.iushln(a)}},n.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var i=this,h=t.clone();i=0!==i.negative?i.umod(t):i.clone();for(var e,o=new n(1),s=new n(0),u=h.clone();i.cmpn(1)>0&&h.cmpn(1)>0;){for(var a=0,l=1;0==(i.words[0]&l)&&a<26;++a,l<<=1);if(a>0)for(i.iushrn(a);a-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);for(var m=0,f=1;0==(h.words[0]&f)&&m<26;++m,f<<=1);if(m>0)for(h.iushrn(m);m-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);i.cmp(h)>=0?(i.isub(h),o.isub(s)):(h.isub(i),s.isub(o))}return(e=0===i.cmpn(1)?o:s).cmpn(0)<0&&e.iadd(t),e},n.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var i=this.clone(),r=t.clone();i.negative=0,r.negative=0;for(var h=0;i.isEven()&&r.isEven();h++)i.iushrn(1),r.iushrn(1);for(;;){for(;i.isEven();)i.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=i.cmp(r);if(n<0){var e=i;i=r,r=e}else if(0===n||0===r.cmpn(1))break;i.isub(r)}return r.iushln(h)},n.prototype.invm=function(t){return this.egcd(t).a.umod(t)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(t){return this.words[0]&t},n.prototype.bincn=function(t){r("number"==typeof t);var i=t%26,h=(t-i)/26,n=1<>>26,s&=67108863,this.words[o]=s}return 0!==e&&(this.words[o]=e,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(t){var i,h=t<0;if(0!==this.negative&&!h)return-1;if(0===this.negative&&h)return 1;if(this.strip(),this.length>1)i=1;else{h&&(t=-t),r(t<=67108863,"Number is too big");var n=0|this.words[0];i=n===t?0:nt.length)return 1;if(this.length=0;r--){var h=0|this.words[r],n=0|t.words[r];if(h!==n){hn&&(i=1);break}}return i},n.prototype.gtn=function(t){return 1===this.cmpn(t)},n.prototype.gt=function(t){return 1===this.cmp(t)},n.prototype.gten=function(t){return this.cmpn(t)>=0},n.prototype.gte=function(t){return this.cmp(t)>=0},n.prototype.ltn=function(t){return-1===this.cmpn(t)},n.prototype.lt=function(t){return-1===this.cmp(t)},n.prototype.lten=function(t){return this.cmpn(t)<=0},n.prototype.lte=function(t){return this.cmp(t)<=0},n.prototype.eqn=function(t){return 0===this.cmpn(t)},n.prototype.eq=function(t){return 0===this.cmp(t)},n.red=function(t){return new b(t)},n.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(t){return this.red=t,this},n.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},n.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},n.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},n.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},n.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},n.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},n.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},n.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var M={k256:null,p224:null,p192:null,p25519:null};function v(t,i){this.name=t,this.p=new n(i,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function c(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function y(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function b(t){if("string"==typeof t){var i=n._prime(t);this.m=i.p,this.prime=i}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function _(t){b.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v.prototype._tmp=function(){var t=new n(null);return t.words=Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var i,r=t;do{this.split(r,this.tmp),i=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(i>this.n);var h=i0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,i){t.iushrn(this.n,0,i)},v.prototype.imulK=function(t){return t.imul(this.k)},h(g,v),g.prototype.split=function(t,i){for(var r=4194303,h=Math.min(t.length,9),n=0;n>>22,e=o}e>>>=22,t.words[n-10]=e,0===e&&t.length>10?t.length-=10:t.length-=9},g.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var i=0,r=0;r>>=26,t.words[r]=n,i=h}return 0!==i&&(t.words[t.length++]=i),t},n._prime=function(t){if(M[t])return M[t];var i;if("k256"===t)i=new g;else if("p224"===t)i=new c;else if("p192"===t)i=new w;else{if("p25519"!==t)throw Error("Unknown prime "+t);i=new y}return M[t]=i,i},b.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},b.prototype._verify2=function(t,i){r(0==(t.negative|i.negative),"red works only with positives"),r(t.red&&t.red===i.red,"red works only with red numbers")},b.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},b.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},b.prototype.add=function(t,i){this._verify2(t,i);var r=t.add(i);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},b.prototype.iadd=function(t,i){this._verify2(t,i);var r=t.iadd(i);return r.cmp(this.m)>=0&&r.isub(this.m),r},b.prototype.sub=function(t,i){this._verify2(t,i);var r=t.sub(i);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},b.prototype.isub=function(t,i){this._verify2(t,i);var r=t.isub(i);return r.cmpn(0)<0&&r.iadd(this.m),r},b.prototype.shl=function(t,i){return this._verify1(t),this.imod(t.ushln(i))},b.prototype.imul=function(t,i){return this._verify2(t,i),this.imod(t.imul(i))},b.prototype.mul=function(t,i){return this._verify2(t,i),this.imod(t.mul(i))},b.prototype.isqr=function(t){return this.imul(t,t.clone())},b.prototype.sqr=function(t){return this.mul(t,t)},b.prototype.sqrt=function(t){if(t.isZero())return t.clone();var i=this.m.andln(3);if(r(i%2==1),3===i){var h=this.m.add(new n(1)).iushrn(2);return this.pow(t,h)}for(var e=this.m.subn(1),o=0;!e.isZero()&&0===e.andln(1);)o++,e.iushrn(1);r(!e.isZero());var s=new n(1).toRed(this),u=s.redNeg(),a=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new n(2*l*l).toRed(this);0!==this.pow(l,a).cmp(u);)l.redIAdd(u);for(var m=this.pow(l,e),f=this.pow(t,e.addn(1).iushrn(1)),d=this.pow(t,e),p=o;0!==d.cmp(s);){for(var M=d,v=0;0!==M.cmp(s);v++)M=M.redSqr();r(v=0;h--){for(var a=i.words[h],l=u-1;l>=0;l--){var m=a>>l&1;e!==r[0]&&(e=this.sqr(e)),0!==m||0!==o?(o<<=1,o|=m,(4===++s||0===h&&0===l)&&(e=this.mul(e,r[o]),s=0,o=0)):s=0}u=26}return e},b.prototype.convertTo=function(t){var i=t.umod(this.m);return i===t?i.clone():i},b.prototype.convertFrom=function(t){var i=t.clone();return i.red=null,i},n.mont=function(t){return new _(t)},h(_,b),_.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},_.prototype.convertFrom=function(t){var i=this.imod(t.mul(this.rinv));return i.red=null,i},_.prototype.imul=function(t,i){if(t.isZero()||i.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(i),h=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(h).iushrn(this.shift),e=n;return n.cmp(this.m)>=0?e=n.isub(this.m):n.cmpn(0)<0&&(e=n.iadd(this.m)),e._forceRed(this)},_.prototype.mul=function(t,i){if(t.isZero()||i.isZero())return new n(0)._forceRed(this);var r=t.mul(i),h=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),e=r.isub(h).iushrn(this.shift),o=e;return e.cmp(this.m)>=0?o=e.isub(this.m):e.cmpn(0)<0&&(o=e.iadd(this.m)),o._forceRed(this)},_.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,i)}));export default r;export{r as __moduleExports}; -//# sourceMappingURL=bn.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/bn.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/bn.min.mjs.map deleted file mode 100644 index 631314774..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.min.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bn.min.mjs","sources":["../../node_modules/bn.js/lib/bn.js"],"sourcesContent":["(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n r.strip();\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n"],"names":["module","exports","assert","val","msg","Error","inherits","ctor","superCtor","super_","TempCtor","prototype","constructor","BN","number","base","endian","isBN","this","negative","words","length","red","_init","Buffer","wordSize","e","parseHex","str","start","end","r","len","Math","min","i","c","charCodeAt","parseBase","mul","num","Array","isArray","max","left","right","cmp","_initNumber","_initArray","toString","replace","_parseHex","_parseBase","strip","toArray","ceil","j","w","off","limbLen","limbPow","total","mod","word","imuln","_iaddn","pow","copy","dest","clone","_expand","size","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","self","out","a","b","lo","carry","k","ncarry","rword","maxJ","padding","groupSize","groupBase","isZero","modn","idivn","toNumber","ret","toJSON","toBuffer","toArrayLike","ArrayType","byteLength","reqLength","littleEndian","res","q","andln","iushrn","_countBits","clz32","t","_zeroBits","bitLength","hi","zeroBits","toTwos","width","abs","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","xor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","add","sub","comb10MulTo","mid","o","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","b1","bl1","bh1","b2","bl2","bh2","b3","bl3","bh3","b4","bl4","bh4","b5","bl5","bh5","b6","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","b9","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","jumboMulTo","FFTM","mulp","x","y","mulTo","hncarry","bigMulTo","makeRBT","N","l","revBin","rb","permute","rbt","rws","iws","rtws","itws","transform","s","rtwdf","cos","PI","itwdf","sin","p","rtwdf_","itwdf_","re","ie","ro","io","rx","guessLen13b","n","m","odd","conjugate","normalize13b","ws","round","convert13b","stub","ph","_","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","bits","carryMask","newCarry","ishln","hint","extended","h","mask","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","shift","_wordDiv","mode","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","half","r2","acc","egcd","A","B","C","D","g","isEven","yp","xp","im","isOdd","jm","gcd","_invmp","x1","x2","delta","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","eq","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","name","tmp","_tmp","K256","call","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","split","imulK","input","output","outLen","prev","next","mod3","one","nOne","lpow","z","inv","wnd","current","currentLen","mont","u"],"mappings":";sKAAA,SAAWA,EAAQC,GAIjB,SAASC,EAAQC,EAAKC,GACpB,IAAKD,EAAK,MAAUE,MAAMD,GAAO,oBAKnC,SAASE,EAAUC,EAAMC,GACvBD,EAAKE,OAASD,EACd,IAAIE,EAAW,aACfA,EAASC,UAAYH,EAAUG,UAC/BJ,EAAKI,UAAY,IAAID,EACrBH,EAAKI,UAAUC,YAAcL,EAK/B,SAASM,EAAIC,EAAQC,EAAMC,GACzB,GAAIH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nBlK,EAAM4T,EAAEpR,KAAK7H,KAAKuP,GACT0J,EAAE9E,KAAK,GAAK,IACrB9O,EAAM4T,EAAErR,KAAK5H,KAAKuP,IAGblK,EAAIgQ,UAAUrV,OAGvB0X,EAAKjY,UAAU2U,KAAO,SAAetQ,GAGnC,OADU9D,KAAK2X,KAAK7T,EAAEiQ,OAAO/T,KAAKuP,GAAGlO,IAAIrB,KAAKgT,KACnCqC,UAAUrV,MAExB,CAl2GD,CAk2GoClB,EAAQkB"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/bn.mjs b/app/node_modules/openpgp/dist/lightweight/bn.mjs deleted file mode 100644 index afb79f3db..000000000 --- a/app/node_modules/openpgp/dist/lightweight/bn.mjs +++ /dev/null @@ -1,3434 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -import { c as createCommonjsModule, a as commonjsGlobal } from './openpgp.mjs'; - -var bn = createCommonjsModule(function (module) { -(function (module, exports) { - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = void('buffer').Buffer; - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) ; else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(module, commonjsGlobal); -}); - -export default bn; -export { bn as __moduleExports }; diff --git a/app/node_modules/openpgp/dist/lightweight/elliptic.min.mjs b/app/node_modules/openpgp/dist/lightweight/elliptic.min.mjs deleted file mode 100644 index 3a3ae755c..000000000 --- a/app/node_modules/openpgp/dist/lightweight/elliptic.min.mjs +++ /dev/null @@ -1,3 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import{c as e,m as f,i as d,u as t,b as a,d as c,_ as r,e as b,f as i,g as n,r as s}from"./openpgp.min.mjs";import o from"./bn.min.mjs";var h,u=e((function(e,f){var d=f;function t(e){return 1===e.length?"0"+e:e}function a(e){for(var f="",d=0;d>8,r=255&a;c?d.push(c,r):d.push(r)}return d},d.zero2=t,d.toHex=a,d.encode=function(e,f){return"hex"===f?a(e):e}})),p=e((function(e,d){var t=d;t.assert=f,t.toArray=u.toArray,t.zero2=u.zero2,t.toHex=u.toHex,t.encode=u.encode,t.getNAF=function(e,f){for(var d=[],t=1<=0;){var c;if(a.isOdd()){var r=a.andln(t-1);c=r>(t>>1)-1?(t>>1)-r:r,a.isubn(c)}else c=0;d.push(c);for(var b=0!==a.cmpn(0)&&0===a.andln(t-1)?f+1:1,i=1;i0||f.cmpn(-a)>0;){var c,r,b,i=e.andln(3)+t&3,n=f.andln(3)+a&3;if(3===i&&(i=-1),3===n&&(n=-1),0==(1&i))c=0;else c=3!==(b=e.andln(7)+t&7)&&5!==b||2!==n?i:-i;if(d[0].push(c),0==(1&n))r=0;else r=3!==(b=f.andln(7)+a&7)&&5!==b||2!==i?n:-n;d[1].push(r),2*t===c+1&&(t=1-t),2*a===r+1&&(a=1-a),e.iushrn(1),f.iushrn(1)}return d},t.cachedProperty=function(e,f,d){var t="_"+f;e.prototype[f]=function(){return void 0!==this[t]?this[t]:this[t]=d.call(this)}},t.parseBytes=function(e){return"string"==typeof e?t.toArray(e,"hex"):e},t.intFromLE=function(e){return new o(e,"hex","le")}})),l=function(e){return h||(h=new y(null)),h.generate(e)};function y(e){this.rand=e}var v=y;if(y.prototype.generate=function(e){return this._rand(e)},y.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var f=new Uint8Array(e),d=0;d0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var I=w;function E(e,f){this.curve=e,this.type=f,this.precomputed=null}w.prototype.point=function(){throw Error("Not implemented")},w.prototype.validate=function(){throw Error("Not implemented")},w.prototype._fixedNafMul=function(e,f){S(e.precomputed);var d=e._getDoubles(),t=A(f,1),a=(1<=r;f--)b=(b<<1)+t[f];c.push(b)}for(var i=this.jpoint(null,null,null),n=this.jpoint(null,null,null),s=a;s>0;s--){for(r=0;r=0;b--){for(f=0;b>=0&&0===c[b];b--)f++;if(b>=0&&f++,r=r.dblp(f),b<0)break;var i=c[b];S(0!==i),r="affine"===e.type?i>0?r.mixedAdd(a[i-1>>1]):r.mixedAdd(a[-i-1>>1].neg()):i>0?r.add(a[i-1>>1]):r.add(a[-i-1>>1].neg())}return"affine"===e.type?r.toP():r},w.prototype._wnafMulAdd=function(e,f,d,t,a){for(var c=this._wnafT1,r=this._wnafT2,b=this._wnafT3,i=0,n=0;n=1;n-=2){var o=n-1,h=n;if(1===c[o]&&1===c[h]){var u=[f[o],null,null,f[h]];0===f[o].y.cmp(f[h].y)?(u[1]=f[o].add(f[h]),u[2]=f[o].toJ().mixedAdd(f[h].neg())):0===f[o].y.cmp(f[h].y.redNeg())?(u[1]=f[o].toJ().mixedAdd(f[h]),u[2]=f[o].add(f[h].neg())):(u[1]=f[o].toJ().mixedAdd(f[h]),u[2]=f[o].toJ().mixedAdd(f[h].neg()));var p=[-3,-1,-5,-7,0,7,5,1,3],l=g(d[o],d[h]);i=Math.max(l[0].length,i),b[o]=Array(i),b[h]=Array(i);for(var y=0;y=0;n--){for(var I=0;n>=0;){var E=!0;for(y=0;y=0&&I++,S=S.dblp(I),n<0)break;for(y=0;y0?x=r[y][M-1>>1]:M<0&&(x=r[y][-M-1>>1].neg()),S="affine"===x.type?S.mixedAdd(x):S.add(x))}}for(n=0;n=Math.ceil((e.bitLength()+1)/f.step)},E.prototype._getDoubles=function(e,f){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var d=[this],t=this,a=0;a=0&&(c=f,r=d),t.negative&&(t=t.neg(),a=a.neg()),c.negative&&(c=c.neg(),r=r.neg()),[{a:t,b:a},{a:c,b:r}]},M.prototype._endoSplit=function(e){var f=this.endo.basis,d=f[0],t=f[1],a=t.b.mul(e).divRound(this.n),c=d.b.neg().mul(e).divRound(this.n),r=a.mul(d.a),b=c.mul(t.a),i=a.mul(d.b),n=c.mul(t.b);return{k1:e.sub(r).sub(b),k2:i.add(n).neg()}},M.prototype.pointFromX=function(e,f){(e=new o(e,16)).red||(e=e.toRed(this.red));var d=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),t=d.redSqrt();if(0!==t.redSqr().redSub(d).cmp(this.zero))throw Error("invalid point");var a=t.fromRed().isOdd();return(f&&!a||!f&&a)&&(t=t.redNeg()),this.point(e,t)},M.prototype.validate=function(e){if(e.inf)return!0;var f=e.x,d=e.y,t=this.a.redMul(f),a=f.redSqr().redMul(f).redIAdd(t).redIAdd(this.b);return 0===d.redSqr().redISub(a).cmpn(0)},M.prototype._endoWnafMulAdd=function(e,f,d){for(var t=this._endoWnafT1,a=this._endoWnafT2,c=0;c":""},C.prototype.isInfinity=function(){return this.inf},C.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var f=this.y.redSub(e.y);0!==f.cmpn(0)&&(f=f.redMul(this.x.redSub(e.x).redInvm()));var d=f.redSqr().redISub(this.x).redISub(e.x),t=f.redMul(this.x.redSub(d)).redISub(this.y);return this.curve.point(d,t)},C.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var f=this.curve.a,d=this.x.redSqr(),t=e.redInvm(),a=d.redAdd(d).redIAdd(d).redIAdd(f).redMul(t),c=a.redSqr().redISub(this.x.redAdd(this.x)),r=a.redMul(this.x.redSub(c)).redISub(this.y);return this.curve.point(c,r)},C.prototype.getX=function(){return this.x.fromRed()},C.prototype.getY=function(){return this.y.fromRed()},C.prototype.mul=function(e){return e=new o(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},C.prototype.mulAdd=function(e,f,d){var t=[this,f],a=[e,d];return this.curve.endo?this.curve._endoWnafMulAdd(t,a):this.curve._wnafMulAdd(1,t,a,2)},C.prototype.jmulAdd=function(e,f,d){var t=[this,f],a=[e,d];return this.curve.endo?this.curve._endoWnafMulAdd(t,a,!0):this.curve._wnafMulAdd(1,t,a,2,!0)},C.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},C.prototype.neg=function(e){if(this.inf)return this;var f=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var d=this.precomputed,t=function(e){return e.neg()};f.precomputed={naf:d.naf&&{wnd:d.naf.wnd,points:d.naf.points.map(t)},doubles:d.doubles&&{step:d.doubles.step,points:d.doubles.points.map(t)}}}return f},C.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},d(_,I.BasePoint),M.prototype.jpoint=function(e,f,d){return new _(this,e,f,d)},_.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),f=e.redSqr(),d=this.x.redMul(f),t=this.y.redMul(f).redMul(e);return this.curve.point(d,t)},_.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var f=e.z.redSqr(),d=this.z.redSqr(),t=this.x.redMul(f),a=e.x.redMul(d),c=this.y.redMul(f.redMul(e.z)),r=e.y.redMul(d.redMul(this.z)),b=t.redSub(a),i=c.redSub(r);if(0===b.cmpn(0))return 0!==i.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var n=b.redSqr(),s=n.redMul(b),o=t.redMul(n),h=i.redSqr().redIAdd(s).redISub(o).redISub(o),u=i.redMul(o.redISub(h)).redISub(c.redMul(s)),p=this.z.redMul(e.z).redMul(b);return this.curve.jpoint(h,u,p)},_.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var f=this.z.redSqr(),d=this.x,t=e.x.redMul(f),a=this.y,c=e.y.redMul(f).redMul(this.z),r=d.redSub(t),b=a.redSub(c);if(0===r.cmpn(0))return 0!==b.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var i=r.redSqr(),n=i.redMul(r),s=d.redMul(i),o=b.redSqr().redIAdd(n).redISub(s).redISub(s),h=b.redMul(s.redISub(o)).redISub(a.redMul(n)),u=this.z.redMul(r);return this.curve.jpoint(o,h,u)},_.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var f=this,d=0;d=0)return!1;if(d.redIAdd(a),0===this.x.cmp(d))return!0}},_.prototype.inspect=function(){return this.isInfinity()?"":""},_.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},d(D,I);var F=D;function z(e,f,d){I.BasePoint.call(this,e,"projective"),null===f&&null===d?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new o(f,16),this.z=new o(d,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}D.prototype.validate=function(e){var f=e.normalize().x,d=f.redSqr(),t=d.redMul(f).redAdd(d.redMul(this.a)).redAdd(f);return 0===t.redSqrt().redSqr().cmp(t)},d(z,I.BasePoint),D.prototype.decodePoint=function(e,f){if(33===(e=p.toArray(e,f)).length&&64===e[0]&&(e=e.slice(1,33).reverse()),32!==e.length)throw Error("Unknown point compression format");return this.point(e,1)},D.prototype.point=function(e,f){return new z(this,e,f)},D.prototype.pointFromJSON=function(e){return z.fromJSON(this,e)},z.prototype.precompute=function(){},z.prototype._encode=function(e){var f=this.curve.p.byteLength();return e?[64].concat(this.getX().toArray("le",f)):this.getX().toArray("be",f)},z.fromJSON=function(e,f){return new z(e,f[0],f[1]||e.one)},z.prototype.inspect=function(){return this.isInfinity()?"":""},z.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},z.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),f=this.x.redSub(this.z).redSqr(),d=e.redSub(f),t=e.redMul(f),a=d.redMul(f.redAdd(this.curve.a24.redMul(d)));return this.curve.point(t,a)},z.prototype.add=function(){throw Error("Not supported on Montgomery curve")},z.prototype.diffAdd=function(e,f){var d=this.x.redAdd(this.z),t=this.x.redSub(this.z),a=e.x.redAdd(e.z),c=e.x.redSub(e.z).redMul(d),r=a.redMul(t),b=f.z.redMul(c.redAdd(r).redSqr()),i=f.x.redMul(c.redISub(r).redSqr());return this.curve.point(b,i)},z.prototype.mul=function(e){for(var f=(e=new o(e,16)).clone(),d=this,t=this.curve.point(null,null),a=[];0!==f.cmpn(0);f.iushrn(1))a.push(f.andln(1));for(var c=a.length-1;c>=0;c--)0===a[c]?(d=d.diffAdd(t,this),t=t.dbl()):(t=d.diffAdd(t,this),d=d.dbl());return t},z.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},z.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},z.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},z.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},z.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var q=p.assert;function R(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,I.call(this,"edwards",e),this.a=new o(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new o(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new o(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),q(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}d(R,I);var P=R;function N(e,f,d,t,a){I.BasePoint.call(this,e,"projective"),null===f&&null===d&&null===t?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new o(f,16),this.y=new o(d,16),this.z=t?new o(t,16):this.curve.one,this.t=a&&new o(a,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}R.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},R.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},R.prototype.jpoint=function(e,f,d,t){return this.point(e,f,d,t)},R.prototype.pointFromX=function(e,f){(e=new o(e,16)).red||(e=e.toRed(this.red));var d=e.redSqr(),t=this.c2.redSub(this.a.redMul(d)),a=this.one.redSub(this.c2.redMul(this.d).redMul(d)),c=t.redMul(a.redInvm()),r=c.redSqrt();if(0!==r.redSqr().redSub(c).cmp(this.zero))throw Error("invalid point");var b=r.fromRed().isOdd();return(f&&!b||!f&&b)&&(r=r.redNeg()),this.point(e,r)},R.prototype.pointFromY=function(e,f){(e=new o(e,16)).red||(e=e.toRed(this.red));var d=e.redSqr(),t=d.redSub(this.c2),a=d.redMul(this.d).redMul(this.c2).redSub(this.a),c=t.redMul(a.redInvm());if(0===c.cmp(this.zero)){if(f)throw Error("invalid point");return this.point(this.zero,e)}var r=c.redSqrt();if(0!==r.redSqr().redSub(c).cmp(this.zero))throw Error("invalid point");return r.fromRed().isOdd()!==f&&(r=r.redNeg()),this.point(r,e)},R.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var f=e.x.redSqr(),d=e.y.redSqr(),t=f.redMul(this.a).redAdd(d),a=this.c2.redMul(this.one.redAdd(this.d.redMul(f).redMul(d)));return 0===t.cmp(a)},d(N,I.BasePoint),R.prototype.pointFromJSON=function(e){return N.fromJSON(this,e)},R.prototype.point=function(e,f,d,t){return new N(this,e,f,d,t)},N.fromJSON=function(e,f){return new N(e,f[0],f[1],f[2])},N.prototype.inspect=function(){return this.isInfinity()?"":""},N.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},N.prototype._extDbl=function(){var e=this.x.redSqr(),f=this.y.redSqr(),d=this.z.redSqr();d=d.redIAdd(d);var t=this.curve._mulA(e),a=this.x.redAdd(this.y).redSqr().redISub(e).redISub(f),c=t.redAdd(f),r=c.redSub(d),b=t.redSub(f),i=a.redMul(r),n=c.redMul(b),s=a.redMul(b),o=r.redMul(c);return this.curve.point(i,n,o,s)},N.prototype._projDbl=function(){var e,f,d,t=this.x.redAdd(this.y).redSqr(),a=this.x.redSqr(),c=this.y.redSqr();if(this.curve.twisted){var r=(n=this.curve._mulA(a)).redAdd(c);if(this.zOne)e=t.redSub(a).redSub(c).redMul(r.redSub(this.curve.two)),f=r.redMul(n.redSub(c)),d=r.redSqr().redSub(r).redSub(r);else{var b=this.z.redSqr(),i=r.redSub(b).redISub(b);e=t.redSub(a).redISub(c).redMul(i),f=r.redMul(n.redSub(c)),d=r.redMul(i)}}else{var n=a.redAdd(c);b=this.curve._mulC(this.z).redSqr(),i=n.redSub(b).redSub(b);e=this.curve._mulC(t.redISub(n)).redMul(i),f=this.curve._mulC(n).redMul(a.redISub(c)),d=n.redMul(i)}return this.curve.point(e,f,d)},N.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},N.prototype._extAdd=function(e){var f=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),d=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),t=this.t.redMul(this.curve.dd).redMul(e.t),a=this.z.redMul(e.z.redAdd(e.z)),c=d.redSub(f),r=a.redSub(t),b=a.redAdd(t),i=d.redAdd(f),n=c.redMul(r),s=b.redMul(i),o=c.redMul(i),h=r.redMul(b);return this.curve.point(n,s,h,o)},N.prototype._projAdd=function(e){var f,d,t=this.z.redMul(e.z),a=t.redSqr(),c=this.x.redMul(e.x),r=this.y.redMul(e.y),b=this.curve.d.redMul(c).redMul(r),i=a.redSub(b),n=a.redAdd(b),s=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(c).redISub(r),o=t.redMul(i).redMul(s);return this.curve.twisted?(f=t.redMul(n).redMul(r.redSub(this.curve._mulA(c))),d=i.redMul(n)):(f=t.redMul(n).redMul(r.redSub(c)),d=this.curve._mulC(i).redMul(n)),this.curve.point(o,f,d)},N.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},N.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},N.prototype.mulAdd=function(e,f,d){return this.curve._wnafMulAdd(1,[this,f],[e,d],2,!1)},N.prototype.jmulAdd=function(e,f,d){return this.curve._wnafMulAdd(1,[this,f],[e,d],2,!0)},N.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},N.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},N.prototype.getX=function(){return this.normalize(),this.x.fromRed()},N.prototype.getY=function(){return this.normalize(),this.y.fromRed()},N.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},N.prototype.eqXToP=function(e){var f=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(f))return!0;for(var d=e.clone(),t=this.curve.redN.redMul(this.z);;){if(d.iadd(this.curve.n),d.cmp(this.curve.p)>=0)return!1;if(f.redIAdd(t),0===this.x.cmp(f))return!0}},N.prototype.toP=N.prototype.normalize,N.prototype.mixedAdd=N.prototype.add;var k=e((function(e,f){var d=f;d.base=I,d.short=B,d.mont=F,d.edwards=P})),j=t.rotl32,O=t.sum32,L=t.sum32_5,T=a.ft_1,J=c.BlockHash,X=[1518500249,1859775393,2400959708,3395469782];function V(){if(!(this instanceof V))return new V;J.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}t.inherits(V,J);var K=V;V.blockSize=512,V.outSize=160,V.hmacStrength=80,V.padLength=64,V.prototype._update=function(e,f){for(var d=this.W,t=0;t<16;t++)d[t]=e[f+t];for(;tthis.blockSize&&(e=(new this.Hash).update(e).digest()),f(e.length<=this.blockSize);for(var d=e.length;d=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(d,t,a)}var $=Z;Z.prototype._init=function(e,f,d){var t=e.concat(f).concat(d);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var a=0;a=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(t||[])),this._reseed=1},Z.prototype.generate=function(e,f,d,t){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");"string"!=typeof f&&(t=d,d=f,f=null),d&&(d=u.toArray(d,t||"hex"),this._update(d));for(var a=[];a.length"};var te=p.assert;function ae(e,f){if(e instanceof ae)return e;this._importDER(e,f)||(te(e.r&&e.s,"Signature without r or s"),this.r=new o(e.r,16),this.s=new o(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var ce=ae;function re(){this.place=0}function be(e,f){var d=e[f.place++];if(!(128&d))return d;for(var t=15&d,a=0,c=0,r=f.place;c>>3);for(e.push(128|d);--d;)e.push(f>>>(d<<3)&255);e.push(f)}}ae.prototype._importDER=function(e,f){e=p.toArray(e,f);var d=new re;if(48!==e[d.place++])return!1;if(be(e,d)+d.place!==e.length)return!1;if(2!==e[d.place++])return!1;var t=be(e,d),a=e.slice(d.place,t+d.place);if(d.place+=t,2!==e[d.place++])return!1;var c=be(e,d);if(e.length!==c+d.place)return!1;var r=e.slice(d.place,c+d.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===r[0]&&128&r[1]&&(r=r.slice(1)),this.r=new o(a),this.s=new o(r),this.recoveryParam=null,!0},ae.prototype.toDER=function(e){var f=this.r.toArray(),d=this.s.toArray();for(128&f[0]&&(f=[0].concat(f)),128&d[0]&&(d=[0].concat(d)),f=ie(f),d=ie(d);!(d[0]||128&d[1]);)d=d.slice(1);var t=[2];ne(t,f.length),(t=t.concat(f)).push(2),ne(t,d.length);var a=t.concat(d),c=[48];return ne(c,a.length),c=c.concat(a),p.encode(c,e)};var se=p.assert;function oe(e){if(!(this instanceof oe))return new oe(e);"string"==typeof e&&(se(Q.hasOwnProperty(e),"Unknown curve "+e),e=Q[e]),e instanceof Q.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var he=oe;oe.prototype.keyPair=function(e){return new de(this,e)},oe.prototype.keyFromPrivate=function(e,f){return de.fromPrivate(this,e,f)},oe.prototype.keyFromPublic=function(e,f){return de.fromPublic(this,e,f)},oe.prototype.genKeyPair=function(e){e||(e={});var f=new $({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||l(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()});if("mont"===this.curve.type){var d=new o(f.generate(32));return this.keyFromPrivate(d)}for(var t=this.n.byteLength(),a=this.n.sub(new o(2));;){if(!((d=new o(f.generate(t))).cmp(a)>0))return d.iaddn(1),this.keyFromPrivate(d)}},oe.prototype._truncateToN=function(e,f,d){var t=(d=d||8*e.byteLength())-this.n.bitLength();return t>0&&(e=e.ushrn(t)),!f&&e.cmp(this.n)>=0?e.sub(this.n):e},oe.prototype.truncateMsg=function(e){var f;return e instanceof Uint8Array?(f=8*e.byteLength,e=this._truncateToN(new o(e,16),!1,f)):"string"==typeof e?(f=4*e.length,e=this._truncateToN(new o(e,16),!1,f)):e=this._truncateToN(new o(e,16)),e},oe.prototype.sign=function(e,f,d,t){"object"==typeof d&&(t=d,d=null),t||(t={}),f=this.keyFromPrivate(f,d),e=this.truncateMsg(e);for(var a=this.n.byteLength(),c=f.getPrivate().toArray("be",a),r=e.toArray("be",a),b=new $({hash:this.hash,entropy:c,nonce:r,pers:t.pers,persEnc:t.persEnc||"utf8"}),i=this.n.sub(new o(1)),n=0;;n++){var s=t.k?t.k(n):new o(b.generate(this.n.byteLength()));if(!((s=this._truncateToN(s,!0)).cmpn(1)<=0||s.cmp(i)>=0)){var h=this.g.mul(s);if(!h.isInfinity()){var u=h.getX(),p=u.umod(this.n);if(0!==p.cmpn(0)){var l=s.invm(this.n).mul(p.mul(f.getPrivate()).iadd(e));if(0!==(l=l.umod(this.n)).cmpn(0)){var y=(h.getY().isOdd()?1:0)|(0!==u.cmp(p)?2:0);return t.canonical&&l.cmp(this.nh)>0&&(l=this.n.sub(l),y^=1),new ce({r:p,s:l,recoveryParam:y})}}}}}},oe.prototype.verify=function(e,f,d,t){return d=this.keyFromPublic(d,t),f=new ce(f,"hex"),this._verify(this.truncateMsg(e),f,d)||this._verify(this._truncateToN(new o(e,16)),f,d)},oe.prototype._verify=function(e,f,d){var t=f.r,a=f.s;if(t.cmpn(1)<0||t.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var c,r=a.invm(this.n),b=r.mul(e).umod(this.n),i=r.mul(t).umod(this.n);return this.curve._maxwellTrick?!(c=this.g.jmulAdd(b,d.getPublic(),i)).isInfinity()&&c.eqXToP(t):!(c=this.g.mulAdd(b,d.getPublic(),i)).isInfinity()&&0===c.getX().umod(this.n).cmp(t)},oe.prototype.recoverPubKey=function(e,f,d,t){se((3&d)===d,"The recovery param is more than two bits"),f=new ce(f,t);var a=this.n,c=new o(e),r=f.r,b=f.s,i=1&d,n=d>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&n)throw Error("Unable to find sencond key candinate");r=n?this.curve.pointFromX(r.add(this.curve.n),i):this.curve.pointFromX(r,i);var s=f.r.invm(a),h=a.sub(c).mul(s).umod(a),u=b.mul(s).umod(a);return this.g.mulAdd(h,r,u)},oe.prototype.getKeyRecoveryParam=function(e,f,d,t){if(null!==(f=new ce(f,t)).recoveryParam)return f.recoveryParam;for(var a=0;a<4;a++){var c;try{c=this.recoverPubKey(e,f,a)}catch(e){continue}if(c.eq(d))return a}throw Error("Unable to find valid recovery factor")};var ue=p.assert,pe=p.parseBytes,le=p.cachedProperty;function ye(e,f){if(this.eddsa=e,f.hasOwnProperty("secret")&&(this._secret=pe(f.secret)),e.isPoint(f.pub))this._pub=f.pub;else if(this._pubBytes=pe(f.pub),this._pubBytes&&33===this._pubBytes.length&&64===this._pubBytes[0]&&(this._pubBytes=this._pubBytes.slice(1,33)),this._pubBytes&&32!==this._pubBytes.length)throw Error("Unknown point compression format")}ye.fromPublic=function(e,f){return f instanceof ye?f:new ye(e,{pub:f})},ye.fromSecret=function(e,f){return f instanceof ye?f:new ye(e,{secret:f})},ye.prototype.secret=function(){return this._secret},le(ye,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),le(ye,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),le(ye,"privBytes",(function(){var e=this.eddsa,f=this.hash(),d=e.encodingLength-1,t=f.slice(0,e.encodingLength);return t[0]&=248,t[d]&=127,t[d]|=64,t})),le(ye,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),le(ye,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),le(ye,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ye.prototype.sign=function(e){return ue(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},ye.prototype.verify=function(e,f){return this.eddsa.verify(e,f,this)},ye.prototype.getSecret=function(e){return ue(this._secret,"KeyPair is public only"),p.encode(this.secret(),e)},ye.prototype.getPublic=function(e,f){return p.encode((f?[64]:[]).concat(this.pubBytes()),e)};var ve=ye,me=p.assert,Ae=p.cachedProperty,ge=p.parseBytes;function Se(e,f){this.eddsa=e,"object"!=typeof f&&(f=ge(f)),Array.isArray(f)&&(f={R:f.slice(0,e.encodingLength),S:f.slice(e.encodingLength)}),me(f.R&&f.S,"Signature without R or S"),e.isPoint(f.R)&&(this._R=f.R),f.S instanceof o&&(this._S=f.S),this._Rencoded=Array.isArray(f.R)?f.R:f.Rencoded,this._Sencoded=Array.isArray(f.S)?f.S:f.Sencoded}Ae(Se,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),Ae(Se,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),Ae(Se,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),Ae(Se,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),Se.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Se.prototype.toHex=function(){return p.encode(this.toBytes(),"hex").toUpperCase()};var we=Se,Ie=p.assert,Ee=p.parseBytes;function xe(e){if(Ie("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof xe))return new xe(e);e=Q[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=Y.sha512}var Me=xe;xe.prototype.sign=function(e,f){e=Ee(e);var d=this.keyFromSecret(f),t=this.hashInt(d.messagePrefix(),e),a=this.g.mul(t),c=this.encodePoint(a),r=this.hashInt(c,d.pubBytes(),e).mul(d.priv()),b=t.add(r).umod(this.curve.n);return this.makeSignature({R:a,S:b,Rencoded:c})},xe.prototype.verify=function(e,f,d){e=Ee(e),f=this.makeSignature(f);var t=this.keyFromPublic(d),a=this.hashInt(f.Rencoded(),t.pubBytes(),e),c=this.g.mul(f.S());return f.R().add(t.pub().mul(a)).eq(c)},xe.prototype.hashInt=function(){for(var e=this.hash(),f=0;f> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w) {\n var naf = [];\n var ws = 1 << (w + 1);\n var k = num.clone();\n while (k.cmpn(1) >= 0) {\n var z;\n if (k.isOdd()) {\n var mod = k.andln(ws - 1);\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n naf.push(z);\n\n // Optimization, shift by word if possible\n var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;\n for (var i = 1; i < shift; i++)\n naf.push(0);\n k.iushrn(shift);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n []\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n var m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n var m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n for (var j = 0; j < naf.length; j += doubles.step) {\n var nafW = 0;\n for (var k = j + doubles.step - 1; k >= j; k--)\n nafW = (nafW << 1) + naf[k];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (var j = 0; j < repr.length; j++) {\n var nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var k = 0; i >= 0 && naf[i] === 0; i--)\n k++;\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n for (var i = 0; i < len; i++) {\n var p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (var i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a]);\n naf[b] = getNAF(coeffs[b], wndWidth[b]);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b] /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3 /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (var j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (var i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (var j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (var j = 0; j < len; j++) {\n var z = tmp[j];\n var p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (var i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16)\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n};\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point))\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point))\n }\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate)\n }\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (var i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (var i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n // Note: this implementation is according to the original paper\n // by P. Montgomery, NOT the one by D. J. Bernstein.\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n var bytes = utils.toArray(bytes, enc);\n\n // TODO Curve448\n // Montgomery curve points must be represented in the compressed format\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (bytes.length === 33 && bytes[0] === 0x40)\n bytes = bytes.slice(1, 33).reverse(); // point must be little-endian\n if (bytes.length !== 32)\n throw new Error('Unknown point compression format');\n return this.point(bytes, 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n\n // Note: the output should always be little-endian\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (compact) {\n return [ 0x40 ].concat(this.getX().toArray('le', len));\n } else {\n return this.getX().toArray('be', len);\n }\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n if (this.curve.twisted) {\n // E = a * C\n var e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n var h = this.z.redSqr();\n // J = F - 2 * H\n var j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n var e = c.redAdd(d);\n // H = (c * Z1)^2\n var h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n var j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else if (options.type === 'mont')\n this.curve = new curve.mont(options);\n else throw new Error('Unknown curve type.');\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve\n });\n return curve;\n }\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'\n ]\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'\n ]\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'\n ]\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'\n ]\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650'\n ]\n});\n\n// https://tools.ietf.org/html/rfc7748#section-4.1\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9'\n ]\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.4\ndefineCurve('brainpoolP256r1', {\n type: 'short',\n prime: null,\n p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',\n a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',\n b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',\n n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',\n hash: hash.sha256, // or 384, or 512\n gRed: false,\n g: [\n '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',\n '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.6\ndefineCurve('brainpoolP384r1', {\n type: 'short',\n prime: null,\n p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +\n 'ACD3A729 901D1A71 87470013 3107EC53',\n a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +\n '8AA5814A 503AD4EB 04A8C7DD 22CE2826',\n b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +\n '7CB43902 95DBC994 3AB78696 FA504C11',\n n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +\n 'CF3AB6AF 6B7FC310 3B883202 E9046565',\n hash: hash.sha384, // or 512\n gRed: false,\n g: [\n '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +\n 'E8E826E03436D646AAEF87B2E247D4AF1E',\n '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +\n '280E4646217791811142820341263C5315'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.7\ndefineCurve('brainpoolP512r1', {\n type: 'short',\n prime: null,\n p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +\n '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',\n a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +\n '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',\n b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +\n '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',\n n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +\n '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',\n hash: hash.sha512,\n gRed: false,\n g: [\n '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +\n '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',\n '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +\n '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'\n ]\n});\n\n// https://en.bitcoin.it/wiki/Secp256k1\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre\n ]\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc\n });\n};\n\n// TODO: should not validate for X25519\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // For Curve25519/Curve448 we have a specific procedure.\n // TODO Curve448\n if (this.ec.curve.type === 'mont') {\n var one = this.ec.curve.one;\n var mask = one.ushln(255 - 3).sub(one).ushln(3);\n this.priv = this.priv.or(one.ushln(255 - 1));\n this.priv = this.priv.and(mask);\n } else\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n }\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0 && (r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] === 0 && (s[1] & 0x80)) {\n s = s.slice(1);\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray()\n });\n\n // Key generation for curve25519 is simpler\n if (this.curve.type === 'mont') {\n var priv = new BN(drbg.generate(32));\n return this.keyFromPrivate(priv);\n }\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n do {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n } while (true);\n};\n\nEC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {\n bitSize = bitSize || msg.byteLength() * 8;\n var delta = bitSize - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.truncateMsg = function truncateMSG(msg) {\n // Bit size is only determined correctly for Uint8Arrays and hex strings\n var bitSize;\n if (msg instanceof Uint8Array) {\n bitSize = msg.byteLength * 8;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else if (typeof msg === 'string') {\n bitSize = msg.length * 4;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else {\n msg = this._truncateToN(new BN(msg, 16));\n }\n return msg;\n}\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this.truncateMsg(msg);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8'\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; true; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n // Fallback to the old code\n var ret = this._verify(this.truncateMsg(msg), signature, key) ||\n this._verify(this._truncateToN(new BN(msg, 16)), signature, key);\n return ret;\n};\n\nEC.prototype._verify = function _verify(msg, signature, key) {\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n\n if (!this.curve._maxwellTrick) {\n var p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n var p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n if (params.hasOwnProperty('secret'))\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else {\n this._pubBytes = parseBytes(params.pub);\n if (this._pubBytes && this._pubBytes.length === 33 &&\n this._pubBytes[0] === 0x40)\n this._pubBytes = this._pubBytes.slice(1, 33);\n if (this._pubBytes && this._pubBytes.length !== 32)\n throw new Error('Unknown point compression format');\n }\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n // https://tools.ietf.org/html/rfc8032#section-5.1.5\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength)\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar HmacDRBG = require('hmac-drbg');\nvar rand = require('brorand');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n var curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.curve.n.toArray()\n });\n\n return this.keyFromSecret(drbg.generate(32));\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n"],"names":["r","utils","exports","zero2","word","length","toHex","msg","res","i","toString","toArray","enc","Array","isArray","slice","replace","push","parseInt","c","charCodeAt","hi","lo","encode","arr","assert","minAssert","minUtils","getNAF","num","w","naf","ws","k","clone","cmpn","z","isOdd","mod","andln","isubn","shift","iushrn","getJSF","k1","k2","jsf","d1","d2","u1","u2","m8","m14","m24","cachedProperty","obj","name","computer","key","prototype","undefined","this","call","parseBytes","bytes","intFromLE","BN","len","Rand","generate","rand","_rand","n","getBytes","Uint8Array","getByte","self","crypto","getRandomValues","msCrypto","window","Error","randomBytes","e","BaseCurve","type","conf","p","red","prime","mont","zero","toRed","one","two","g","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","adjustCount","div","redN","_maxwellTrick","BasePoint","curve","precomputed","point","validate","_fixedNafMul","doubles","_getDoubles","I","step","repr","j","nafW","a","jpoint","b","mixedAdd","points","neg","add","toP","_wnafMul","nafPoints","_getNAFPoints","wnd","acc","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","max","comb","y","cmp","toJ","redNeg","index","Math","ja","jb","tmp","eq","decodePoint","byteLength","pointFromX","encodeCompressed","_encode","compact","x","getX","getY","isEven","concat","precompute","power","beta","_getBeta","_hasDoubles","ceil","bitLength","dbl","ShortCurve","Base","tinv","redInvm","zeroA","fromRed","threeA","sub","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","inherits","Point","isRed","inf","forceRed","JPoint","zOne","MontCurve","i4","a24","redMul","redAdd","modn","lambda","betas","_getEndoRoots","lambdas","mul","basis","map","vec","_getEndoBasis","ntinv","s","redSqrt","redSub","a0","b0","a1","b1","a2","b2","prevR","aprxSqrt","ushrn","floor","u","v","x1","y1","x2","y2","q","len1","sqr","negative","_endoSplit","v1","v2","c1","divRound","c2","p1","p2","q1","q2","odd","redSqr","redIAdd","ax","rhs","redISub","_endoWnafMulAdd","npoints","ncoeffs","split","ineg","fromJSON","pre","endoMul","toJSON","JSON","parse","obj2point","inspect","isInfinity","nx","ny","ys1","dyinv","mulAdd","jmulAdd","_precompute","negate","zinv","zinv2","ay","pz2","z2","s1","s2","h","h2","h3","nz","pow","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","t1","t2","dny","_zeroDbl","_threeDbl","_dbl","xx","yy","yyyy","m","t","yyyy8","d","f","c8","delta","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","z3","pz3","eqXToP","zs","rx","xc","iadd","normalize","reverse","aa","bb","diffAdd","diff","da","cb","bits","jumlAdd","other","EdwardsCurve","twisted","mOneA","extended","umod","dd","oneC","_mulA","_mulC","lhs","pointFromY","_extDbl","nt","_projDbl","_extAdd","_projAdd","zi","base","require$$0","short","require$$1","require$$2","edwards","require$$3","rotl32","sum32","sum32_5","ft_1","shaCommon","BlockHash","common","sha1_K","SHA1","W","blockSize","outSize","hmacStrength","padLength","_update","start","_digest","toHex32","split32","require$$4","Hmac","hash","Hash","inner","outer","_init","update","digest","sha","ripemd","hmac","sha1","sha256","sha224","sha384","sha512","ripemd160","curves","PresetCurve","options","defineCurve","Object","defineProperty","configurable","enumerable","get","value","cofactor","HmacDRBG","predResist","outLen","minEntropy","_reseed","reseedInterval","K","V","entropy","entropyEnc","nonce","nonceEnc","pers","persEnc","seed","_hmac","kmac","reseed","addEnc","temp","KeyPair","ec","priv","pub","_importPrivate","privEnc","_importPublic","pubEnc","fromPublic","fromPrivate","getPublic","result","reason","getPrivate","mask","ushln","or","and","derive","sign","verify","signature","Signature","_importDER","recoveryParam","Position","place","getLength","buf","initial","octetLen","val","off","rmPadding","constructLength","octets","log","LN2","data","rlen","slen","toDER","backHalf","EC","hasOwnProperty","nh","keyPair","keyFromPrivate","keyFromPublic","genKeyPair","drbg","ns2","iaddn","_truncateToN","truncOnly","bitSize","truncateMsg","bkey","ns1","iter","kp","kpX","invm","canonical","_verify","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Q","Qprime","eddsa","params","_secret","secret","isPoint","_pub","_pubBytes","fromSecret","encodePoint","lastIx","encodingLength","decodeInt","privBytes","message","sig","getSecret","pubBytes","R","S","_R","_S","_Rencoded","Rencoded","_Sencoded","Sencoded","encodeInt","toBytes","toUpperCase","EDDSA","pointClass","constructor","keyFromSecret","hashInt","messagePrefix","s_","makeSignature","SG","arguments","normed","xIsOdd","elliptic","require$$5"],"mappings":";+OAAIA,qBCEJ,IAAIC,EAAQC,EAkCZ,SAASC,EAAMC,GACb,OAAoB,IAAhBA,EAAKC,OACA,IAAMD,EAENA,CACX,CAGA,SAASE,EAAMC,GAEb,IADA,IAAIC,EAAM,GACDC,EAAI,EAAGA,EAAIF,EAAIF,OAAQI,IAC9BD,GAAOL,EAAMI,EAAIE,GAAGC,SAAS,KAC/B,OAAOF,CACT,CAfAP,EAAMU,QA9BN,SAAiBJ,EAAKK,GACpB,GAAIC,MAAMC,QAAQP,GAChB,OAAOA,EAAIQ,QACb,IAAKR,EACH,MAAO,GACT,IAAIC,EAAM,GACV,GAAmB,iBAARD,EAAkB,CAC3B,IAAK,IAAIE,EAAI,EAAGA,EAAIF,EAAIF,OAAQI,IAC9BD,EAAIC,GAAc,EAATF,EAAIE,GACf,OAAOD,EAET,GAAY,QAARI,EAAe,EACjBL,EAAMA,EAAIS,QAAQ,eAAgB,KAC1BX,OAAS,GAAM,IACrBE,EAAM,IAAMA,GACd,IAASE,EAAI,EAAGA,EAAIF,EAAIF,OAAQI,GAAK,EACnCD,EAAIS,KAAKC,SAASX,EAAIE,GAAKF,EAAIE,EAAI,GAAI,UAEzC,IAASA,EAAI,EAAGA,EAAIF,EAAIF,OAAQI,IAAK,CACnC,IAAIU,EAAIZ,EAAIa,WAAWX,GACnBY,EAAKF,GAAK,EACVG,EAAS,IAAJH,EACLE,E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AEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAIN5F,IAAK,CACHmG,IAAK,EACLP,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,C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,EAAIlB,QAAQ,KAAMkD,KAAK+b,eAChC,EAEAkB,GAAMnd,UAAUkc,UAAY,SAAmB7b,GAC7C,OAAO/D,EAAMgE,UAAUD,EACzB,EAEA8c,GAAMnd,UAAU2b,QAAU,SAAiB9C,GACzC,OAAOA,aAAe3Y,KAAKkd,UAC7B,0BC1IA,IAAIW,EAAWxhB,EAEfwhB,EAASzhB,MAAQ8V,EACjB2L,EAASpd,KAAO2R,EAChByL,EAAS/a,MAAQuP,EACjBwL,EAAShJ,OAAStC,EAGlBsL,EAAShH,GAAKlD,GACdkK,EAASxC,MAAQyC"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/elliptic.mjs b/app/node_modules/openpgp/dist/lightweight/elliptic.mjs deleted file mode 100644 index 1bcd8eb8d..000000000 --- a/app/node_modules/openpgp/dist/lightweight/elliptic.mjs +++ /dev/null @@ -1,4313 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -import { c as createCommonjsModule, m as minimalisticAssert, i as inherits_browser, u as utils, b as common, d as common$1, _ as _224, e as _256, f as _384, g as _512, r as ripemd } from './openpgp.mjs'; -import bn from './bn.mjs'; - -var utils_1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - return res; -} -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; -}); - -var utils_1$1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - - - - -utils.assert = minimalisticAssert; -utils.toArray = utils_1.toArray; -utils.zero2 = utils_1.zero2; -utils.toHex = utils_1.toHex; -utils.encode = utils_1.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new bn(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; -}); - -var r; - -var brorand = function rand(len) { - if (!r) - r = new Rand(null); - - return r.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -var Rand_1 = Rand; - -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; - -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); - - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; - -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; - - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto = void('crypto'); - if (typeof crypto.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto.randomBytes(n); - }; - } catch (e) { - } -} -brorand.Rand = Rand_1; - -var getNAF = utils_1$1.getNAF; -var getJSF = utils_1$1.getJSF; -var assert = utils_1$1.assert; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); - - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -var base = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); - - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -var assert$1 = utils_1$1.assert; - -function ShortCurve(conf) { - base.call(this, 'short', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits_browser(ShortCurve, base); -var short_1 = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert$1(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; - -function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits_browser(Point, base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits_browser(JPoint, base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -function MontCurve(conf) { - base.call(this, 'mont', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - // Note: this implementation is according to the original paper - // by P. Montgomery, NOT the one by D. J. Bernstein. - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits_browser(MontCurve, base); -var mont = MontCurve; - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point$1(curve, x, z) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits_browser(Point$1, base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - var bytes = utils_1$1.toArray(bytes, enc); - - // TODO Curve448 - // Montgomery curve points must be represented in the compressed format - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (bytes.length === 33 && bytes[0] === 0x40) - bytes = bytes.slice(1, 33).reverse(); // point must be little-endian - if (bytes.length !== 32) - throw new Error('Unknown point compression format'); - return this.point(bytes, 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); -}; - -Point$1.prototype.precompute = function precompute() { - // No-op -}; - -Point$1.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - - // Note: the output should always be little-endian - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (compact) { - return [ 0x40 ].concat(this.getX().toArray('le', len)); - } else { - return this.getX().toArray('be', len); - } -}; - -Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); -}; - -Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point$1.prototype.mul = function mul(k) { - k = new bn(k, 16); - - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -var assert$2 = utils_1$1.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - base.call(this, 'edwards', conf); - - this.a = new bn(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert$2(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits_browser(EdwardsCurve, base); -var edwards = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new bn(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } - - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point$2(curve, x, y, z, t) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits_browser(Point$2, base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$2.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point$2(this, x, y, z, t); -}; - -Point$2.fromJSON = function fromJSON(curve, obj) { - return new Point$2(curve, obj[0], obj[1], obj[2]); -}; - -Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point$2.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); -}; - -Point$2.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); - } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point$2.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point$2.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; - -Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; - -Point$2.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point$2.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point$2.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point$2.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -Point$2.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; - -Point$2.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -// Compatibility with BaseCurve -Point$2.prototype.toP = Point$2.prototype.normalize; -Point$2.prototype.mixedAdd = Point$2.prototype.add; - -var curve_1 = createCommonjsModule(function (module, exports) { - -var curve = exports; - -curve.base = base; -curve.short = short_1; -curve.mont = mont; -curve.edwards = edwards; -}); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_5 = utils.sum32_5; -var ft_1 = common.ft_1; -var BlockHash = common$1.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -var _1 = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; - -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - - for(; i < W.length; i++) - W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -var sha1 = _1; -var sha224 = _224; -var sha256 = _256; -var sha384 = _384; -var sha512 = _512; - -var sha = { - sha1: sha1, - sha224: sha224, - sha256: sha256, - sha384: sha384, - sha512: sha512 -}; - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -var hmac = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -var hash_1 = createCommonjsModule(function (module, exports) { -var hash = exports; - -hash.utils = utils; -hash.common = common$1; -hash.sha = sha; -hash.ripemd = ripemd; -hash.hmac = hmac; - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; -}); - -var secp256k1 = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; - -var curves_1 = createCommonjsModule(function (module, exports) { - -var curves = exports; - - - - - -var assert = utils_1$1.assert; - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve_1.short(options); - else if (options.type === 'edwards') - this.curve = new curve_1.edwards(options); - else if (options.type === 'mont') - this.curve = new curve_1.mont(options); - else throw new Error('Unknown curve type.'); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash_1.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash_1.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash_1.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); - -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash_1.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); - -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash_1.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); - -// https://tools.ietf.org/html/rfc7748#section-4.1 -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '9' - ] -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.4 -defineCurve('brainpoolP256r1', { - type: 'short', - prime: null, - p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377', - a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9', - b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6', - n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7', - hash: hash_1.sha256, // or 384, or 512 - gRed: false, - g: [ - '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262', - '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.6 -defineCurve('brainpoolP384r1', { - type: 'short', - prime: null, - p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' + - 'ACD3A729 901D1A71 87470013 3107EC53', - a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' + - '8AA5814A 503AD4EB 04A8C7DD 22CE2826', - b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' + - '7CB43902 95DBC994 3AB78696 FA504C11', - n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' + - 'CF3AB6AF 6B7FC310 3B883202 E9046565', - hash: hash_1.sha384, // or 512 - gRed: false, - g: [ - '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' + - 'E8E826E03436D646AAEF87B2E247D4AF1E', - '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' + - '280E4646217791811142820341263C5315' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.7 -defineCurve('brainpoolP512r1', { - type: 'short', - prime: null, - p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' + - '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3', - a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' + - '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA', - b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' + - '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723', - n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' + - '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069', - hash: hash_1.sha512, - gRed: false, - g: [ - '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' + - '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', - '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' + - '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892' - ] -}); - -// https://en.bitcoin.it/wiki/Secp256k1 -var pre; -try { - pre = secp256k1; -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash_1.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); -}); - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils_1.toArray(options.pers, options.persEnc || 'hex'); - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -var hmacDrbg = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); - - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils_1.encode(res, enc); -}; - -var assert$3 = utils_1$1.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); -} -var key = KeyPair; - -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; - -// TODO: should not validate for X25519 -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(enc, compact) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - if (!enc) - return this.pub; - - return this.pub.encode(enc, compact); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new bn(key, enc || 16); - - // For Curve25519/Curve448 we have a specific procedure. - // TODO Curve448 - if (this.ec.curve.type === 'mont') { - var one = this.ec.curve.one; - var mask = one.ushln(255 - 3).sub(one).ushln(3); - this.priv = this.priv.or(one.ushln(255 - 1)); - this.priv = this.priv.and(mask); - } else - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$3(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$3(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -var assert$4 = utils_1$1.assert; - -function Signature(options, enc) { - if (options instanceof Signature) - return options; - - if (this._importDER(options, enc)) - return; - - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; -} -var signature = Signature; - -function Position() { - this.place = 0; -} - -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} - -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); - } - - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); -}; - -var assert$5 = utils_1$1.assert; - - - - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$5(curves_1.hasOwnProperty(options), 'Unknown curve ' + options); - - options = curves_1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves_1.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash function for DRBG - this.hash = options.hash || options.curve.hash; -} -var ec = EC; - -EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); -}; - -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); -}; - -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); - - // Key generation for curve25519 is simpler - if (this.curve.type === 'mont') { - var priv = new bn(drbg.generate(32)); - return this.keyFromPrivate(priv); - } - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; - -EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) { - bitSize = bitSize || msg.byteLength() * 8; - var delta = bitSize - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.truncateMsg = function truncateMSG(msg) { - // Bit size is only determined correctly for Uint8Arrays and hex strings - var bitSize; - if (msg instanceof Uint8Array) { - bitSize = msg.byteLength * 8; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else if (typeof msg === 'string') { - bitSize = msg.length * 4; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else { - msg = this._truncateToN(new bn(msg, 16)); - } - return msg; -}; - -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this.truncateMsg(msg); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); - - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; - - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature$1, key, enc) { - key = this.keyFromPublic(key, enc); - signature$1 = new signature(signature$1, 'hex'); - // Fallback to the old code - var ret = this._verify(this.truncateMsg(msg), signature$1, key) || - this._verify(this._truncateToN(new bn(msg, 16)), signature$1, key); - return ret; -}; - -EC.prototype._verify = function _verify(msg, signature, key) { - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; - -EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) { - assert$5((3 & j) === j, 'The recovery param is more than two bits'); - signature$1 = new signature(signature$1, enc); - - var n = this.n; - var e = new bn(msg); - var r = signature$1.r; - var s = signature$1.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature$1.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; - -EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) { - signature$1 = new signature(signature$1, enc); - if (signature$1.recoveryParam !== null) - return signature$1.recoveryParam; - - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature$1, i); - } catch (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -var assert$6 = utils_1$1.assert; -var parseBytes = utils_1$1.parseBytes; -var cachedProperty = utils_1$1.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair$1(eddsa, params) { - this.eddsa = eddsa; - if (params.hasOwnProperty('secret')) - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else { - this._pubBytes = parseBytes(params.pub); - if (this._pubBytes && this._pubBytes.length === 33 && - this._pubBytes[0] === 0x40) - this._pubBytes = this._pubBytes.slice(1, 33); - if (this._pubBytes && this._pubBytes.length !== 32) - throw new Error('Unknown point compression format'); - } -} - -KeyPair$1.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$1) - return pub; - return new KeyPair$1(eddsa, { pub: pub }); -}; - -KeyPair$1.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$1) - return secret; - return new KeyPair$1(eddsa, { secret: secret }); -}; - -KeyPair$1.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair$1, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair$1, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair$1, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair$1, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair$1.prototype.sign = function sign(message) { - assert$6(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair$1.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair$1.prototype.getSecret = function getSecret(enc) { - assert$6(this._secret, 'KeyPair is public only'); - return utils_1$1.encode(this.secret(), enc); -}; - -KeyPair$1.prototype.getPublic = function getPublic(enc, compact) { - return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); -}; - -var key$1 = KeyPair$1; - -var assert$7 = utils_1$1.assert; -var cachedProperty$1 = utils_1$1.cachedProperty; -var parseBytes$1 = utils_1$1.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature$1(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; - } - - assert$7(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof bn) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty$1(Signature$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty$1(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty$1(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty$1(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature$1.prototype.toHex = function toHex() { - return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -var signature$1 = Signature$1; - -var assert$8 = utils_1$1.assert; -var parseBytes$2 = utils_1$1.parseBytes; - - - -function EDDSA(curve) { - assert$8(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = curves_1[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash_1.sha512; -} - -var eddsa = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes$2(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes$2(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n); -}; - -EDDSA.prototype.keyPair = function keyPair(options) { - return new key$1(this, options); -}; - -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return key$1.fromPublic(this, pub); -}; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return key$1.fromSecret(this, secret); -}; - -EDDSA.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.curve.n.toArray() - }); - - return this.keyFromSecret(drbg.generate(32)); -}; - -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof signature$1) - return sig; - return new signature$1(this, sig); -}; - -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; - -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils_1$1.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils_1$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; - -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; - -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils_1$1.intFromLE(bytes); -}; - -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; - -var elliptic_1 = createCommonjsModule(function (module, exports) { - -var elliptic = exports; - -elliptic.utils = utils_1$1; -elliptic.rand = brorand; -elliptic.curve = curve_1; -elliptic.curves = curves_1; - -// Protocols -elliptic.ec = ec; -elliptic.eddsa = eddsa; -}); - -export default elliptic_1; -export { elliptic_1 as __moduleExports }; diff --git a/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.min.mjs b/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.min.mjs new file mode 100644 index 000000000..e2dccbe09 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.min.mjs @@ -0,0 +1,3 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import{enums as t}from"./openpgp.min.mjs";function i(t,i,e,n,s,o){const r=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],h=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],a=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],f=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],u=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],y=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,k,g,m,S,b,z,d,w,A,B=0,N=i.length;const _=32===t.length?3:9;d=3===_?e?[0,32,2]:[30,-2,-2]:e?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],e&&(i=function(t){const i=8-t.length%8;let e;if(!(i<8)){if(8===i)return t;throw Error("des: invalid padding")}e=0;const n=new Uint8Array(t.length+i);for(let i=0;i>>4^z),z^=g,b^=g<<4,g=65535&(b>>>16^z),z^=g,b^=g<<16,g=858993459&(z>>>2^b),b^=g,z^=g<<2,g=16711935&(z>>>8^b),b^=g,z^=g<<8,g=1431655765&(b>>>1^z),z^=g,b^=g<<1,b=b<<1|b>>>31,z=z<<1|z>>>31,k=0;k<_;k+=3){for(w=d[k+1],A=d[k+2],p=d[k];p!==w;p+=A)m=z^t[p],S=(z>>>4|z<<28)^t[p+1],g=b,b=z,z=g^(h[m>>>24&63]|a[m>>>16&63]|l[m>>>8&63]|y[63&m]|r[S>>>24&63]|c[S>>>16&63]|f[S>>>8&63]|u[63&S]);g=b,b=z,z=g}b=b>>>1|b<<31,z=z>>>1|z<<31,g=1431655765&(b>>>1^z),z^=g,b^=g<<1,g=16711935&(z>>>8^b),b^=g,z^=g<<8,g=858993459&(z>>>2^b),b^=g,z^=g<<2,g=65535&(b>>>16^z),z^=g,b^=g<<16,g=252645135&(b>>>4^z),z^=g,b^=g<<4,x[E++]=b>>>24,x[E++]=b>>>16&255,x[E++]=b>>>8&255,x[E++]=255&b,x[E++]=z>>>24,x[E++]=z>>>16&255,x[E++]=z>>>8&255,x[E++]=255&z}return e||(x=function(t){let i,e=null;if(i=0,!e){for(e=1;t[t.length-e]===i;)e++;e--}return t.subarray(0,t.length-e)}(x)),x}function e(t){const i=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],e=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],r=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],h=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],a=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],f=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],u=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],y=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],k=t.length>8?3:1,g=Array(32*k),m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let S,b,z,d=0,w=0;for(let A=0;A>>4^A),A^=z,k^=z<<4,z=65535&(A>>>-16^k),k^=z,A^=z<<-16,z=858993459&(k>>>2^A),A^=z,k^=z<<2,z=65535&(A>>>-16^k),k^=z,A^=z<<-16,z=1431655765&(k>>>1^A),A^=z,k^=z<<1,z=16711935&(A>>>8^k),k^=z,A^=z<<8,z=1431655765&(k>>>1^A),A^=z,k^=z<<1,z=k<<8|A>>>20&240,k=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=z;for(let t=0;t<16;t++)m[t]?(k=k<<2|k>>>26,A=A<<2|A>>>26):(k=k<<1|k>>>27,A=A<<1|A>>>27),k&=-15,A&=-15,S=i[k>>>28]|e[k>>>24&15]|n[k>>>20&15]|s[k>>>16&15]|o[k>>>12&15]|r[k>>>8&15]|h[k>>>4&15],b=c[A>>>28]|a[A>>>24&15]|f[A>>>20&15]|l[A>>>16&15]|u[A>>>12&15]|y[A>>>8&15]|p[A>>>4&15],z=65535&(b>>>16^S),g[w++]=S^z,g[w++]=b^z<<16}return g}function n(t){this.key=[];for(let i=0;i<3;i++)this.key.push(new Uint8Array(t.subarray(8*i,8*i+8)));this.encrypt=function(t){return i(e(this.key[2]),i(e(this.key[1]),i(e(this.key[0]),t,!0),!1),!0)}}function s(){this.BlockSize=8,this.KeySize=16,this.setKey=function(t){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),t.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(t),!0},this.reset=function(){for(let t=0;t<16;t++)this.masking[t]=0,this.rotate[t]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(t){const i=Array(t.length);for(let o=0;o>>24&255,i[o+1]=c>>>16&255,i[o+2]=c>>>8&255,i[o+3]=255&c,i[o+4]=h>>>24&255,i[o+5]=h>>>16&255,i[o+6]=h>>>8&255,i[o+7]=255&h}return i},this.decrypt=function(t){const i=Array(t.length);for(let o=0;o>>24&255,i[o+1]=c>>>16&255,i[o+2]=c>>>8&255,i[o+3]=255&c,i[o+4]=h>>>24&255,i[o+5]=h>>16&255,i[o+6]=h>>8&255,i[o+7]=255&h}return i};const t=[,,,,];t[0]=[,,,,],t[0][0]=[4,0,13,15,12,14,8],t[0][1]=[5,2,16,18,17,19,10],t[0][2]=[6,3,23,22,21,20,9],t[0][3]=[7,1,26,25,27,24,11],t[1]=[,,,,],t[1][0]=[0,6,21,23,20,22,16],t[1][1]=[1,4,0,2,1,3,18],t[1][2]=[2,5,7,6,5,4,17],t[1][3]=[3,7,10,9,11,8,19],t[2]=[,,,,],t[2][0]=[4,0,13,15,12,14,8],t[2][1]=[5,2,16,18,17,19,10],t[2][2]=[6,3,23,22,21,20,9],t[2][3]=[7,1,26,25,27,24,11],t[3]=[,,,,],t[3][0]=[0,6,21,23,20,22,16],t[3][1]=[1,4,0,2,1,3,18],t[3][2]=[2,5,7,6,5,4,17],t[3][3]=[3,7,10,9,11,8,19];const i=[,,,,];function e(t,i,e){const n=i+t,s=n<>>32-e;return(o[0][s>>>24]^o[1][s>>>16&255])-o[2][s>>>8&255]+o[3][255&s]}function n(t,i,e){const n=i^t,s=n<>>32-e;return o[0][s>>>24]-o[1][s>>>16&255]+o[2][s>>>8&255]^o[3][255&s]}function s(t,i,e){const n=i-t,s=n<>>32-e;return(o[0][s>>>24]+o[1][s>>>16&255]^o[2][s>>>8&255])-o[3][255&s]}i[0]=[,,,,],i[0][0]=[24,25,23,22,18],i[0][1]=[26,27,21,20,22],i[0][2]=[28,29,19,18,25],i[0][3]=[30,31,17,16,28],i[1]=[,,,,],i[1][0]=[3,2,12,13,8],i[1][1]=[1,0,14,15,13],i[1][2]=[7,6,8,9,3],i[1][3]=[5,4,10,11,7],i[2]=[,,,,],i[2][0]=[19,18,28,29,25],i[2][1]=[17,16,30,31,28],i[2][2]=[23,22,24,25,18],i[2][3]=[21,20,26,27,22],i[3]=[,,,,],i[3][0]=[8,9,7,6,3],i[3][1]=[10,11,5,4,7],i[3][2]=[12,13,3,2,8],i[3][3]=[14,15,1,0,13],this.keySchedule=function(e){const n=[,,,,,,,,],s=Array(32);let r;for(let t=0;t<4;t++)r=4*t,n[t]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3];const h=[6,7,4,5];let c,a=0;for(let e=0;e<2;e++)for(let e=0;e<4;e++){for(r=0;r<4;r++){const i=t[e][r];c=n[i[1]],c^=o[4][n[i[2]>>>2]>>>24-8*(3&i[2])&255],c^=o[5][n[i[3]>>>2]>>>24-8*(3&i[3])&255],c^=o[6][n[i[4]>>>2]>>>24-8*(3&i[4])&255],c^=o[7][n[i[5]>>>2]>>>24-8*(3&i[5])&255],c^=o[h[r]][n[i[6]>>>2]>>>24-8*(3&i[6])&255],n[i[0]]=c}for(r=0;r<4;r++){const t=i[e][r];c=o[4][n[t[0]>>>2]>>>24-8*(3&t[0])&255],c^=o[5][n[t[1]>>>2]>>>24-8*(3&t[1])&255],c^=o[6][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=o[7][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=o[4+r][n[t[4]>>>2]>>>24-8*(3&t[4])&255],s[a]=c,a++}}for(let t=0;t<16;t++)this.masking[t]=s[t],this.rotate[t]=31&s[16+t]};const o=[,,,,,,,,];o[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],o[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],o[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],o[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],o[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],o[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],o[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],o[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function o(t){this.cast5=new s,this.cast5.setKey(t),this.encrypt=function(t){return this.cast5.encrypt(t)}}n.keySize=n.prototype.keySize=24,n.blockSize=n.prototype.blockSize=8,o.blockSize=o.prototype.blockSize=8,o.keySize=o.prototype.keySize=16;const r=4294967295;function h(t,i){return(t<>>32-i)&r}function c(t,i){return t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24}function a(t,i,e){t.splice(i,4,255&e,e>>>8&255,e>>>16&255,e>>>24&255)}function f(t,i){return t>>>8*i&255}function l(t){this.tf=function(){let t=null,i=null,e=-1,n=[],s=[[],[],[],[]];function o(t){return s[0][f(t,0)]^s[1][f(t,1)]^s[2][f(t,2)]^s[3][f(t,3)]}function l(t){return s[0][f(t,3)]^s[1][f(t,0)]^s[2][f(t,1)]^s[3][f(t,2)]}function u(t,i){let e=o(i[0]),s=l(i[1]);i[2]=h(i[2]^e+s+n[4*t+8]&r,31),i[3]=h(i[3],1)^e+2*s+n[4*t+9]&r,e=o(i[2]),s=l(i[3]),i[0]=h(i[0]^e+s+n[4*t+10]&r,31),i[1]=h(i[1],1)^e+2*s+n[4*t+11]&r}function y(t,i){let e=o(i[0]),s=l(i[1]);i[2]=h(i[2],1)^e+s+n[4*t+10]&r,i[3]=h(i[3]^e+2*s+n[4*t+11]&r,31),e=o(i[2]),s=l(i[3]),i[0]=h(i[0],1)^e+s+n[4*t+8]&r,i[1]=h(i[1]^e+2*s+n[4*t+9]&r,31)}return{name:"twofish",blocksize:16,open:function(i){let e,o,a,l,u;t=i;const y=[],p=[],k=[];let g;const m=[];let S,b,z;const d=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],A=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],B=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],N=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],_=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],x=[[],[]],E=[[],[],[],[]];function K(t){return t^t>>2^[0,90,180,238][3&t]}function O(t){return t^t>>1^t>>2^[0,238,180,90][3&t]}function C(t,i){let e,n,s;for(e=0;e<8;e++)n=i>>>24,i=i<<8&r|t>>>24,t=t<<8&r,s=n<<1,128&n&&(s^=333),i^=n^s<<16,s^=n>>>1,1&n&&(s^=166),i^=s<<24|s<<8;return i}function I(t,i){const e=i>>4,n=15&i,s=d[t][e^n],o=w[t][N[n]^_[e]];return B[t][N[o]^_[s]]<<4|A[t][s^o]}function L(t,i){let e=f(t,0),n=f(t,1),s=f(t,2),o=f(t,3);switch(g){case 4:e=x[1][e]^f(i[3],0),n=x[0][n]^f(i[3],1),s=x[0][s]^f(i[3],2),o=x[1][o]^f(i[3],3);case 3:e=x[1][e]^f(i[2],0),n=x[1][n]^f(i[2],1),s=x[0][s]^f(i[2],2),o=x[0][o]^f(i[2],3);case 2:e=x[0][x[0][e]^f(i[1],0)]^f(i[0],0),n=x[0][x[1][n]^f(i[1],1)]^f(i[0],1),s=x[1][x[0][s]^f(i[1],2)]^f(i[0],2),o=x[1][x[1][o]^f(i[1],3)]^f(i[0],3)}return E[0][e]^E[1][n]^E[2][s]^E[3][o]}for(t=t.slice(0,32),e=t.length;16!==e&&24!==e&&32!==e;)t[e++]=0;for(e=0;e>2]=c(t,e);for(e=0;e<256;e++)x[0][e]=I(0,e),x[1][e]=I(1,e);for(e=0;e<256;e++)S=x[1][e],b=K(S),z=O(S),E[0][e]=S+(b<<8)+(z<<16)+(z<<24),E[2][e]=b+(z<<8)+(S<<16)+(z<<24),S=x[0][e],b=K(S),z=O(S),E[1][e]=z+(z<<8)+(b<<16)+(S<<24),E[3][e]=b+(S<<8)+(z<<16)+(b<<24);for(g=k.length/2,e=0;e=0;t--)y(t,o);a(i,e,o[2]^n[0]),a(i,e+4,o[3]^n[1]),a(i,e+8,o[0]^n[2]),a(i,e+12,o[1]^n[3]),e+=16},finalize:function(){return i}}}(),this.tf.open(Array.from(t),0),this.encrypt=function(t){return this.tf.encrypt(Array.from(t),0)}}function u(){}function y(t){this.bf=new u,this.bf.init(t),this.encrypt=function(t){return this.bf.encryptBlock(t)}}l.keySize=l.prototype.keySize=32,l.blockSize=l.prototype.blockSize=16,u.prototype.BLOCKSIZE=8,u.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],u.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],u.prototype.NN=16,u.prototype._clean=function(t){if(t<0){t=(2147483647&t)+2147483648}return t},u.prototype._F=function(t){let i;const e=255&t,n=255&(t>>>=8),s=255&(t>>>=8),o=255&(t>>>=8);return i=this.sboxes[0][o]+this.sboxes[1][s],i^=this.sboxes[2][n],i+=this.sboxes[3][e],i},u.prototype._encryptBlock=function(t){let i,e=t[0],n=t[1];for(i=0;i>>24-8*i&255,s[i+n]=e[1]>>>24-8*i&255;return s},u.prototype._decryptBlock=function(t){let i,e=t[0],n=t[1];for(i=this.NN+1;i>1;--i){e^=this.parray[i],n=this._F(e)^n;const t=e;e=n,n=t}e^=this.parray[1],n^=this.parray[0],t[0]=this._clean(n),t[1]=this._clean(e)},u.prototype.init=function(t){let i,e=0;for(this.parray=[],i=0;i=t.length&&(e=0);this.parray[i]=this.PARRAY[i]^n}for(this.sboxes=[],i=0;i<4;++i)for(this.sboxes[i]=[],e=0;e<256;++e)this.sboxes[i][e]=this.SBOXES[i][e];const n=[0,0];for(i=0;i>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * This file is needed to dynamic import the legacy ciphers.\n * Separate dynamic imports are not convenient as they result in multiple chunks.\n */\n\nimport { TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TwoFish from './twofish';\nimport BlowFish from './blowfish';\nimport enums from '../../enums';\n\nexport const legacyCiphers = new Map([\n [enums.symmetric.tripledes, TripleDES],\n [enums.symmetric.cast5, CAST5],\n [enums.symmetric.blowfish, BlowFish],\n [enums.symmetric.twofish, TwoFish]\n]);\n"],"names":["des","keys","message","encrypt","mode","iv","padding","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","i","j","temp","right1","right2","left","right","looping","endloop","loopinc","m","len","length","iterations","padLength","pad","Error","paddedMessage","Uint8Array","desAddPadding","result","k","subarray","desRemovePadding","desCreateKeys","key","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","Array","shifts","lefttemp","righttemp","n","TripleDES","this","push","block","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","reset","keySchedule","getBlockSize","src","dst","t","l","r","f1","f2","f3","decrypt","scheduleA","scheduleB","d","I","sBox","inn","x","w","ki","half","round","a","b","CAST5","cast5","keySize","prototype","blockSize","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","name","blocksize","open","c","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","q","ffm5b","ffmEf","mdsRem","p","u","qp","hFun","slice","close","data","offset","finalize","createTwofish","from","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","tmp","vector","off","ret","_decryptBlock","jj","kk","legacyCiphers","Map","enums","symmetric","tripledes","blowfish","BlowFish","twofish","TwoFish"],"mappings":";6IAuBA,SAASA,EAAIC,EAAMC,EAASC,EAASC,EAAMC,EAAIC,GAE7C,MAAMC,EAAc,CAClB,SAAW,EAAG,MAAS,SAAW,SAAW,MAAS,EAAK,MAAS,KAAO,SAC3E,SAAW,KAAO,SAAW,SAAW,SAAW,EAAK,KAAO,SAAW,SA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,QAASC"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.mjs b/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.mjs new file mode 100644 index 000000000..c77388b30 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/legacy_ciphers.mjs @@ -0,0 +1,1784 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +import { enums } from './openpgp.mjs'; + +//Paul Tero, July 2001 +//http://www.tero.co.uk/des/ +// +//Optimised for performance with large blocks by Michael Hayworth, November 2001 +//http://www.netdealing.com +// +// Modified by Recurity Labs GmbH + +//THIS SOFTWARE IS PROVIDED "AS IS" AND +//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +//SUCH DAMAGE. + +//des +//this takes the key, the message, and whether to encrypt or decrypt + +function des(keys, message, encrypt, mode, iv, padding) { + //declaring this locally speeds things up a bit + const spfunction1 = [ + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, + 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, + 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, + 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ]; + const spfunction2 = [ + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, + -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, + -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, + -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, + 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, + -0x7fef7fe0, 0x108000 + ]; + const spfunction3 = [ + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, + 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, + 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, + 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ]; + const spfunction4 = [ + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, + 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, + 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ]; + const spfunction5 = [ + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, + 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, + 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, + 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, + 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, + 0x40080000, 0x2080100, 0x40000100 + ]; + const spfunction6 = [ + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, + 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, + 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, + 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ]; + const spfunction7 = [ + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, + 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, + 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, + 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ]; + const spfunction8 = [ + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, + 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, + 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, + 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ]; + + //create the 16 or 48 subkeys we will need + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let endloop; + let loopinc; + let len = message.length; + + //set up the loops for single and triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des + if (iterations === 3) { + looping = encrypt ? [0, 32, 2] : [30, -2, -2]; + } else { + looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; + } + + //pad the message depending on the padding parameter + //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt + if (encrypt) { + message = desAddPadding(message); + len = message.length; + } + + //store the result here + let result = new Uint8Array(len); + let k = 0; + + //loop through each 64 bit chunk of the message + while (m < len) { + left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + + //first each 64 but chunk of the message must be permuted according to IP + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + //do this either 1 or 3 times for each chunk of the message + for (j = 0; j < iterations; j += 3) { + endloop = looping[j + 1]; + loopinc = looping[j + 2]; + //now go through and perform the encryption or decryption + for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency + right1 = right ^ keys[i]; + right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + //the result is attained by passing these bytes through the S selection functions + temp = left; + left = right; + right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> + 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & + 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); + } + temp = left; + left = right; + right = temp; //unreverse left and right + } //for either 1 or 3 iterations + + //move then each one bit to the right + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + //now perform IP-1, which is IP in the opposite direction + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + + result[k++] = (left >>> 24); + result[k++] = ((left >>> 16) & 0xff); + result[k++] = ((left >>> 8) & 0xff); + result[k++] = (left & 0xff); + result[k++] = (right >>> 24); + result[k++] = ((right >>> 16) & 0xff); + result[k++] = ((right >>> 8) & 0xff); + result[k++] = (right & 0xff); + } //for every 8 characters, or 64 bits in the message + + //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt + if (!encrypt) { + result = desRemovePadding(result); + } + + return result; +} //end of des + + +//desCreateKeys +//this takes as input a 64 bit key (even though only 56 bits are used) +//as an array of 2 integers, and returns 16 48 bit keys + +function desCreateKeys(key) { + //declaring this locally speeds things up a bit + const pc2bytes0 = [ + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ]; + const pc2bytes1 = [ + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ]; + const pc2bytes2 = [ + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ]; + const pc2bytes3 = [ + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ]; + const pc2bytes4 = [ + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ]; + const pc2bytes5 = [ + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ]; + const pc2bytes6 = [ + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ]; + const pc2bytes7 = [ + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ]; + const pc2bytes8 = [ + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ]; + const pc2bytes9 = [ + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ]; + const pc2bytes10 = [ + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ]; + const pc2bytes11 = [ + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ]; + const pc2bytes12 = [ + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ]; + const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; + + //how many iterations (1 for des, 3 for triple des) + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + //stores the return keys + const keys = new Array(32 * iterations); + //now define the left shifts which need to be done + const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + //other variables + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; + + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 2) ^ right) & 0x33333333; + right ^= temp; + left ^= (temp << 2); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + + //the right side needs to be shifted and to get the last four bits of the left side + temp = (left << 8) | ((right >>> 20) & 0x000000f0); + //left needs to be put upside down + left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); + right = temp; + + //now go through and perform these shifts on the left and right keys + for (let i = 0; i < shifts.length; i++) { + //shift the keys either one or two bits to the left + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + //now apply PC-2, in such a way that E is easier when encrypting or decrypting + //this conversion will look like PC-2 except only the last 6 bits of each byte are used + //rather than 48 consecutive bits and the order of lines will be according to + //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 + lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( + left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & + 0xf]; + righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | + pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]; + temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; + keys[n++] = lefttemp ^ temp; + keys[n++] = righttemp ^ (temp << 16); + } + } //for each iterations + //return the keys we've created + return keys; +} //end of desCreateKeys + + +function desAddPadding(message, padding) { + const padLength = 8 - (message.length % 8); + + let pad; + if ((padLength < 8)) { //pad the message out with null bytes + pad = 0; + } else if (padLength === 8) { + return message; + } else { + throw new Error('des: invalid padding'); + } + + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { + paddedMessage[i] = message[i]; + } + for (let j = 0; j < padLength; j++) { + paddedMessage[message.length + j] = pad; + } + + return paddedMessage; +} + +function desRemovePadding(message, padding) { + let padLength = null; + let pad; + { // null padding + pad = 0; + } + + if (!padLength) { + padLength = 1; + while (message[message.length - padLength] === pad) { + padLength++; + } + padLength--; + } + + return message.subarray(0, message.length - padLength); +} + +// added by Recurity Labs + +function TripleDES(key) { + this.key = []; + + for (let i = 0; i < 3; i++) { + this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); + } + + this.encrypt = function(block) { + return des( + desCreateKeys(this.key[2]), + des( + desCreateKeys(this.key[1]), + des( + desCreateKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true); + }; +} + +TripleDES.keySize = TripleDES.prototype.keySize = 24; +TripleDES.blockSize = TripleDES.prototype.blockSize = 8; + +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Copyright 2010 pjacobs@xeekr.com . All rights reserved. + +// Modified by Recurity Labs GmbH + +// fixed/modified by Herbert Hanewinkel, www.haneWIN.de +// check www.haneWIN.de for the latest version + +// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. +// CAST-128 is a common OpenPGP cipher. + + +// CAST5 constructor + +function OpenPGPSymEncCAST5() { + this.BlockSize = 8; + this.KeySize = 16; + + this.setKey = function(key) { + this.masking = new Array(16); + this.rotate = new Array(16); + + this.reset(); + + if (key.length === this.KeySize) { + this.keySchedule(key); + } else { + throw new Error('CAST-128: keys must be 16 bytes'); + } + return true; + }; + + this.reset = function() { + for (let i = 0; i < 16; i++) { + this.masking[i] = 0; + this.rotate[i] = 0; + } + }; + + this.getBlockSize = function() { + return this.BlockSize; + }; + + this.encrypt = function(src) { + const dst = new Array(src.length); + + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; + + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >>> 16) & 255; + dst[i + 6] = (l >>> 8) & 255; + dst[i + 7] = l & 255; + } + + return dst; + }; + + this.decrypt = function(src) { + const dst = new Array(src.length); + + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; + + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >> 16) & 255; + dst[i + 6] = (l >> 8) & 255; + dst[i + 7] = l & 255; + } + + return dst; + }; + const scheduleA = new Array(4); + + scheduleA[0] = new Array(4); + scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; + scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + + scheduleA[1] = new Array(4); + scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + + scheduleA[2] = new Array(4); + scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; + scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + + + scheduleA[3] = new Array(4); + scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + + const scheduleB = new Array(4); + + scheduleB[0] = new Array(4); + scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; + scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; + scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; + scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; + + scheduleB[1] = new Array(4); + scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; + scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; + scheduleB[1][2] = [7, 6, 8, 9, 3]; + scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; + + + scheduleB[2] = new Array(4); + scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; + scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; + scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; + scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; + + + scheduleB[3] = new Array(4); + scheduleB[3][0] = [8, 9, 7, 6, 3]; + scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; + scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; + scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; + + // changed 'in' to 'inn' (in javascript 'in' is a reserved word) + this.keySchedule = function(inn) { + const t = new Array(8); + const k = new Array(32); + + let j; + + for (let i = 0; i < 4; i++) { + j = i * 4; + t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + } + + const x = [6, 7, 4, 5]; + let ki = 0; + let w; + + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { + for (j = 0; j < 4; j++) { + const a = scheduleA[round][j]; + w = t[a[1]]; + + w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; + w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; + w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; + w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; + w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; + t[a[0]] = w; + } + + for (j = 0; j < 4; j++) { + const b = scheduleB[round][j]; + w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; + + w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; + w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; + w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; + w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; + k[ki] = w; + ki++; + } + } + } + + for (let i = 0; i < 16; i++) { + this.masking[i] = k[i]; + this.rotate[i] = k[16 + i] & 0x1f; + } + }; + + // These are the three 'f' functions. See RFC 2144, section 2.2. + + function f1(d, m, r) { + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; + } + + function f2(d, m, r) { + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; + } + + function f3(d, m, r) { + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; + } + + const sBox = new Array(8); + sBox[0] = [ + 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, + 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, + 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, + 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, + 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, + 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, + 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, + 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, + 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, + 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, + 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, + 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, + 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, + 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, + 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, + 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, + 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, + 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, + 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, + 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, + 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, + 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, + 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, + 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, + 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, + 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, + 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, + 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, + 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, + 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, + 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ]; + + sBox[1] = [ + 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, + 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, + 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, + 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, + 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, + 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, + 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, + 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, + 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, + 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, + 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, + 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, + 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, + 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, + 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, + 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, + 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, + 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, + 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, + 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, + 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, + 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, + 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, + 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, + 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, + 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, + 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, + 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, + 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, + 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, + 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ]; + + sBox[2] = [ + 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, + 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, + 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, + 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, + 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, + 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, + 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, + 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, + 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, + 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, + 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, + 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, + 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, + 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, + 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, + 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, + 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, + 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, + 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, + 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, + 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, + 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, + 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, + 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, + 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, + 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, + 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, + 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, + 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, + 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, + 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ]; + + sBox[3] = [ + 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, + 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, + 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, + 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, + 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, + 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, + 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, + 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, + 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, + 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, + 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, + 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, + 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, + 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, + 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, + 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, + 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, + 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, + 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, + 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, + 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, + 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, + 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, + 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, + 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, + 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, + 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, + 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, + 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, + 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, + 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ]; + + sBox[4] = [ + 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, + 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, + 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, + 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, + 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, + 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, + 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, + 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, + 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, + 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, + 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, + 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, + 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, + 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, + 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, + 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, + 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, + 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, + 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, + 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, + 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, + 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, + 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, + 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, + 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, + 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, + 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, + 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, + 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, + 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, + 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ]; + + sBox[5] = [ + 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, + 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, + 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, + 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, + 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, + 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, + 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, + 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, + 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, + 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, + 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, + 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, + 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, + 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, + 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, + 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, + 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, + 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, + 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, + 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, + 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, + 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, + 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, + 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, + 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, + 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, + 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, + 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, + 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, + 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, + 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ]; + + sBox[6] = [ + 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, + 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, + 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, + 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, + 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, + 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, + 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, + 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, + 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, + 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, + 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, + 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, + 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, + 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, + 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, + 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, + 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, + 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, + 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, + 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, + 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, + 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, + 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, + 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, + 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, + 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, + 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, + 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, + 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, + 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, + 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ]; + + sBox[7] = [ + 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, + 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, + 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, + 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, + 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, + 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, + 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, + 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, + 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, + 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, + 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, + 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, + 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, + 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, + 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, + 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, + 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, + 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, + 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, + 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, + 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, + 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, + 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, + 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, + 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, + 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, + 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, + 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, + 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, + 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, + 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ]; +} + +function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); + this.cast5.setKey(key); + + this.encrypt = function(block) { + return this.cast5.encrypt(block); + }; +} + +CAST5.blockSize = CAST5.prototype.blockSize = 8; +CAST5.keySize = CAST5.prototype.keySize = 16; + +/* eslint-disable no-mixed-operators, no-fallthrough */ + + +/* Modified by Recurity Labs GmbH + * + * Cipher.js + * A block-cipher algorithm implementation on JavaScript + * See Cipher.readme.txt for further information. + * + * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] + * This script file is distributed under the LGPL + * + * ACKNOWLEDGMENT + * + * The main subroutines are written by Michiel van Everdingen. + * + * Michiel van Everdingen + * http://home.versatel.nl/MAvanEverdingen/index.html + * + * All rights for these routines are reserved to Michiel van Everdingen. + * + */ + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//Math +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +const MAXINT = 0xFFFFFFFF; + +function rotw(w, n) { + return (w << n | w >>> (32 - n)) & MAXINT; +} + +function getW(a, i) { + return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +} + +function setW(a, i, w) { + a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +} + +function getB(x, n) { + return (x >>> (n * 8)) & 0xFF; +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Twofish +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +function createTwofish() { + // + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; + // var dataLength = -1; + // var idx2 = -1; + // + + let tfsKey = []; + let tfsM = [ + [], + [], + [], + [] + ]; + + function tfsInit(key) { + keyBytes = key; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; + + const q0 = [ + [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], + [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] + ]; + const q1 = [ + [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], + [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] + ]; + const q2 = [ + [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], + [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] + ]; + const q3 = [ + [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], + [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] + ]; + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ + [], + [] + ]; + const m = [ + [], + [], + [], + [] + ]; + + function ffm5b(x) { + return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + } + + function ffmEf(x) { + return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + } + + function mdsRem(p, q) { + let i; + let t; + let u; + for (i = 0; i < 8; i++) { + t = q >>> 24; + q = ((q << 8) & MAXINT) | p >>> 24; + p = (p << 8) & MAXINT; + u = t << 1; + if (t & 128) { + u ^= 333; + } + q ^= t ^ (u << 16); + u ^= t >>> 1; + if (t & 1) { + u ^= 166; + } + q ^= u << 24 | u << 8; + } + return q; + } + + function qp(n, x) { + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; + return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; + } + + function hFun(x, key) { + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); + switch (kLen) { + case 4: + a = q[1][a] ^ getB(key[3], 0); + b = q[0][b] ^ getB(key[3], 1); + c = q[0][c] ^ getB(key[3], 2); + d = q[1][d] ^ getB(key[3], 3); + case 3: + a = q[1][a] ^ getB(key[2], 0); + b = q[1][b] ^ getB(key[2], 1); + c = q[0][c] ^ getB(key[2], 2); + d = q[0][d] ^ getB(key[2], 3); + case 2: + a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); + b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); + c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); + d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); + } + return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; + } + + keyBytes = keyBytes.slice(0, 32); + i = keyBytes.length; + while (i !== 16 && i !== 24 && i !== 32) { + keyBytes[i++] = 0; + } + + for (i = 0; i < keyBytes.length; i += 4) { + inKey[i >> 2] = getW(keyBytes, i); + } + for (i = 0; i < 256; i++) { + q[0][i] = qp(0, i); + q[1][i] = qp(1, i); + } + for (i = 0; i < 256; i++) { + f01 = q[1][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + f01 = q[0][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } + + kLen = inKey.length / 2; + for (i = 0; i < kLen; i++) { + a = inKey[i + i]; + meKey[i] = a; + b = inKey[i + i + 1]; + moKey[i] = b; + sKey[kLen - i - 1] = mdsRem(a, b); + } + for (i = 0; i < 40; i += 2) { + a = 0x1010101 * i; + b = a + 0x1010101; + a = hFun(a, meKey); + b = rotw(hFun(b, moKey), 8); + tfsKey[i] = (a + b) & MAXINT; + tfsKey[i + 1] = rotw(a + 2 * b, 9); + } + for (i = 0; i < 256; i++) { + a = b = c = d = i; + switch (kLen) { + case 4: + a = q[1][a] ^ getB(sKey[3], 0); + b = q[0][b] ^ getB(sKey[3], 1); + c = q[0][c] ^ getB(sKey[3], 2); + d = q[1][d] ^ getB(sKey[3], 3); + case 3: + a = q[1][a] ^ getB(sKey[2], 0); + b = q[1][b] ^ getB(sKey[2], 1); + c = q[0][c] ^ getB(sKey[2], 2); + d = q[0][d] ^ getB(sKey[2], 3); + case 2: + tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; + tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; + tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; + tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + } + } + } + + function tfsG0(x) { + return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; + } + + function tfsG1(x) { + return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; + } + + function tfsFrnd(r, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); + blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); + blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + } + + function tfsIrnd(i, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; + blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; + blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + } + + function tfsClose() { + tfsKey = []; + tfsM = [ + [], + [], + [], + [] + ]; + } + + function tfsEncrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { + tfsFrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); + dataOffset += 16; + return dataBytes; + } + + function tfsDecrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { + tfsIrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); + dataOffset += 16; + } + + // added by Recurity Labs + + function tfsFinal() { + return dataBytes; + } + + return { + name: 'twofish', + blocksize: 128 / 8, + open: tfsInit, + close: tfsClose, + encrypt: tfsEncrypt, + decrypt: tfsDecrypt, + // added by Recurity Labs + finalize: tfsFinal + }; +} + +// added by Recurity Labs + +function TF(key) { + this.tf = createTwofish(); + this.tf.open(Array.from(key), 0); + + this.encrypt = function(block) { + return this.tf.encrypt(Array.from(block), 0); + }; +} + +TF.keySize = TF.prototype.keySize = 32; +TF.blockSize = TF.prototype.blockSize = 16; + +/* Modified by Recurity Labs GmbH + * + * Originally written by nklein software (nklein.com) + */ + +/* + * Javascript implementation based on Bruce Schneier's reference implementation. + * + * + * The constructor doesn't do much of anything. It's just here + * so we can start defining properties and methods and such. + */ +function Blowfish() {} + +/* + * Declare the block size so that protocols know what size + * Initialization Vector (IV) they will need. + */ +Blowfish.prototype.BLOCKSIZE = 8; + +/* + * These are the default SBOXES. + */ +Blowfish.prototype.SBOXES = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] +]; + +//* +//* This is the default PARRAY +//* +Blowfish.prototype.PARRAY = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b +]; + +//* +//* This is the number of rounds the cipher will go +//* +Blowfish.prototype.NN = 16; + +//* +//* This function is needed to get rid of problems +//* with the high-bit getting set. If we don't do +//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not +//* equal to ( bb & 0x00FFFFFFFF ) even when they +//* agree bit-for-bit for the first 32 bits. +//* +Blowfish.prototype._clean = function(xx) { + if (xx < 0) { + const yy = xx & 0x7FFFFFFF; + xx = yy + 0x80000000; + } + return xx; +}; + +//* +//* This is the mixing function that uses the sboxes +//* +Blowfish.prototype._F = function(xx) { + let yy; + + const dd = xx & 0x00FF; + xx >>>= 8; + const cc = xx & 0x00FF; + xx >>>= 8; + const bb = xx & 0x00FF; + xx >>>= 8; + const aa = xx & 0x00FF; + + yy = this.sboxes[0][aa] + this.sboxes[1][bb]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; + + return yy; +}; + +//* +//* This method takes an array with two values, left and right +//* and does NN rounds of Blowfish on them. +//* +Blowfish.prototype._encryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; + + let ii; + + for (ii = 0; ii < this.NN; ++ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; + + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } + + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; + + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); +}; + +//* +//* This method takes a vector of numbers and turns them +//* into long words so that they can be processed by the +//* real algorithm. +//* +//* Maybe I should make the real algorithm above take a vector +//* instead. That will involve more looping, but it won't require +//* the F() method to deconstruct the vector. +//* +Blowfish.prototype.encryptBlock = function(vector) { + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); + vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); + } + + this._encryptBlock(vals); + + const ret = []; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); + ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); + // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); + // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + } + + return ret; +}; + +//* +//* This method takes an array with two values, left and right +//* and undoes NN rounds of Blowfish on them. +//* +Blowfish.prototype._decryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; + + let ii; + + for (ii = this.NN + 1; ii > 1; --ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; + + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } + + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; + + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); +}; + +//* +//* This method takes a key array and initializes the +//* sboxes and parray for this encryption. +//* +Blowfish.prototype.init = function(key) { + let ii; + let jj = 0; + + this.parray = []; + for (ii = 0; ii < this.NN + 2; ++ii) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { + data = (data << 8) | (key[jj] & 0x00FF); + if (++jj >= key.length) { + jj = 0; + } + } + this.parray[ii] = this.PARRAY[ii] ^ data; + } + + this.sboxes = []; + for (ii = 0; ii < 4; ++ii) { + this.sboxes[ii] = []; + for (jj = 0; jj < 256; ++jj) { + this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + } + } + + const vals = [0x00000000, 0x00000000]; + + for (ii = 0; ii < this.NN + 2; ii += 2) { + this._encryptBlock(vals); + this.parray[ii + 0] = vals[0]; + this.parray[ii + 1] = vals[1]; + } + + for (ii = 0; ii < 4; ++ii) { + for (jj = 0; jj < 256; jj += 2) { + this._encryptBlock(vals); + this.sboxes[ii][jj + 0] = vals[0]; + this.sboxes[ii][jj + 1] = vals[1]; + } + } +}; + +// added by Recurity Labs +function BF(key) { + this.bf = new Blowfish(); + this.bf.init(key); + + this.encrypt = function(block) { + return this.bf.encryptBlock(block); + }; +} + +BF.keySize = BF.prototype.keySize = 16; +BF.blockSize = BF.prototype.blockSize = 8; + +/** + * This file is needed to dynamic import the legacy ciphers. + * Separate dynamic imports are not convenient as they result in multiple chunks. + */ + + +const legacyCiphers = new Map([ + [enums.symmetric.tripledes, TripleDES], + [enums.symmetric.cast5, CAST5], + [enums.symmetric.blowfish, BF], + [enums.symmetric.twofish, TF] +]); + +export { legacyCiphers }; diff --git a/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs b/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs new file mode 100644 index 000000000..182bff42b --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs @@ -0,0 +1,14 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import{H as t,h as e,t as n,e as r,b as f,c as o,r as i,s,a,d as c,w as d,u,f as l}from"./sha3.min.mjs";class h extends t{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,e(t);const f=n(r);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,i=new Uint8Array(o);i.set(f.length>o?t.create().update(f).digest():f);for(let t=0;tnew h(t,e).update(n).digest();g.create=(t,e)=>new h(t,e) +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const b=/* @__PURE__ */BigInt(0),y=/* @__PURE__ */BigInt(1),p=/* @__PURE__ */BigInt(2);function m(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}function w(t){if(!m(t))throw Error("Uint8Array expected")}function B(t,e){if("boolean"!=typeof e)throw Error(`${t} must be valid boolean, got "${e}".`)}const E=/* @__PURE__ */Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function x(t){w(t);let e="";for(let n=0;n=S._0&&t<=S._9?t-S._0:t>=S._A&&t<=S._F?t-(S._A-10):t>=S._a&&t<=S._f?t-(S._a-10):void 0}function O(t){if("string"!=typeof t)throw Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw Error("padded hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,f=0;e"bigint"==typeof t&&b<=t;function T(t,e,n){return H(t)&&H(e)&&H(n)&&e<=t&&tb;t>>=y,e+=1);return e}const $=t=>(p<new Uint8Array(t),k=t=>Uint8Array.from(t);function G(t,e,n){if("number"!=typeof t||t<2)throw Error("hashLen must be a number");if("number"!=typeof e||e<2)throw Error("qByteLen must be a number");if("function"!=typeof n)throw Error("hmacFn must be a function");let r=_(t),f=_(t),o=0;const i=()=>{r.fill(1),f.fill(0),o=0},s=(...t)=>n(f,r,...t),a=(t=_())=>{f=s(k([0]),t),r=s(),0!==t.length&&(f=s(k([1]),t),r=s())},c=()=>{if(o++>=1e3)throw Error("drbg: tried 1000 values");let t=0;const n=[];for(;t{let n;for(i(),a(t);!(n=e(c()));)a();return i(),n}}const U={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||m(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function j(t,e,n={}){const r=(e,n,r)=>{const f=U[n];if("function"!=typeof f)throw Error(`Invalid validator "${n}", expected function`);const o=t[e];if(!(r&&void 0===o||f(o,t)))throw Error(`Invalid param ${e+""}=${o} (${typeof o}), expected ${n}`)};for(const[t,n]of Object.entries(e))r(t,n,!1);for(const[t,e]of Object.entries(n))r(t,e,!0);return t}function C(t){const e=new WeakMap;return(n,...r)=>{const f=e.get(n);if(void 0!==f)return f;const o=t(n,...r);return e.set(n,o),o}}var V=/*#__PURE__*/Object.freeze({__proto__:null,aInRange:F,abool:B,abytes:w,bitGet:function(t,e){return t>>BigInt(e)&y},bitLen:Z,bitMask:$,bitSet:function(t,e,n){return t|(n?y:b)<{throw Error("not implemented")},numberToBytesBE:z,numberToBytesLE:P,numberToHexUnpadded:I,numberToVarBytesBE:function(t){return O(I(t))},utf8ToBytes:function(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))},validateObject:j}); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const K=BigInt(0),Y=BigInt(1),M=BigInt(2),W=BigInt(3),D=BigInt(4),J=BigInt(5),Q=BigInt(8);function X(t,e){const n=t%e;return n>=K?n:e+n}function tt(t,e,n){if(n<=K||e 0");if(n===Y)return K;let r=Y;for(;e>K;)e&Y&&(r=r*t%n),t=t*t%n,e>>=Y;return r}function et(t,e,n){let r=t;for(;e-- >K;)r*=r,r%=n;return r}function nt(t,e){if(t===K||e<=K)throw Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=X(t,e),r=e,f=K,o=Y;for(;n!==K;){const t=r%n,e=f-o*(r/n);r=n,n=t,f=o,o=e}if(r!==Y)throw Error("invert: does not exist");return X(f,e)}function rt(t){if(t%D===W){const e=(t+Y)/D;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw Error("Cannot find square root");return r}}if(t%Q===J){const e=(t-J)/Q;return function(t,n){const r=t.mul(n,M),f=t.pow(r,e),o=t.mul(n,f),i=t.mul(t.mul(o,M),f),s=t.mul(o,t.sub(i,t.ONE));if(!t.eql(t.sqr(s),n))throw Error("Cannot find square root");return s}}return function(t){const e=(t-Y)/M;let n,r,f;for(n=t-Y,r=0;n%M===K;n/=M,r++);for(f=M;f 0, got "+t);const{nBitLength:f,nByteLength:o}=ot(t,e);if(o>2048)throw Error("Field lengths over 2048 bytes are not supported");const i=rt(t),s=Object.freeze({ORDER:t,BITS:f,BYTES:o,MASK:$(f),ZERO:K,ONE:Y,create:e=>X(e,t),isValid:e=>{if("bigint"!=typeof e)throw Error("Invalid field element: expected bigint, got "+typeof e);return K<=e&&et===K,isOdd:t=>(t&Y)===Y,neg:e=>X(-e,t),eql:(t,e)=>t===e,sqr:e=>X(e*e,t),add:(e,n)=>X(e+n,t),sub:(e,n)=>X(e-n,t),mul:(e,n)=>X(e*n,t),pow:(t,e)=>function(t,e,n){if(n 0");if(n===K)return t.ONE;if(n===Y)return e;let r=t.ONE,f=e;for(;n>K;)n&Y&&(r=t.mul(r,f)),f=t.sqr(f),n>>=Y;return r}(s,t,e),div:(e,n)=>X(e*nt(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>nt(e,t),sqrt:r.sqrt||(t=>i(s,t)),invertBatch:t=>function(t,e){const n=Array(e.length),r=e.reduce(((e,r,f)=>t.is0(r)?e:(n[f]=e,t.mul(e,r))),t.ONE),f=t.inv(r);return e.reduceRight(((e,r,f)=>t.is0(r)?e:(n[f]=t.mul(e,n[f]),t.mul(e,r))),f),n}(s,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?P(t,o):z(t,o),fromBytes:t=>{if(t.length!==o)throw Error(`Fp.fromBytes: expected ${o}, got ${t.length}`);return n?q(t):R(t)}});return Object.freeze(s)}function st(t){if("bigint"!=typeof t)throw Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function at(t){const e=st(t);return e+Math.ceil(e/2)} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const ct=BigInt(0),dt=BigInt(1),ut=new WeakMap,lt=new WeakMap;function ht(t,e){const n=(t,e)=>{const n=e.negate();return t?n:e},r=t=>{if(!Number.isSafeInteger(t)||t<=0||t>e)throw Error(`Wrong window size=${t}, should be [1..${e}]`)},f=t=>{r(t);return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1)}};return{constTimeNegate:n,unsafeLadder(e,n){let r=t.ZERO,f=e;for(;n>ct;)n&dt&&(r=r.add(f)),f=f.double(),n>>=dt;return r},precomputeWindow(t,e){const{windows:n,windowSize:r}=f(e),o=[];let i=t,s=i;for(let t=0;t>=l,f>s&&(f-=u,o+=dt);const i=e,h=e+Math.abs(f)-1,g=t%2!=0,b=f<0;0===f?c=c.add(n(g,r[i])):a=a.add(n(b,r[h]))}return{p:a,f:c}},wNAFCached(t,e,n){const r=lt.get(t)||1;let f=ut.get(t);return f||(f=this.precomputeWindow(t,r),1!==r&&ut.set(t,n(f))),this.wNAF(r,f,e)},setWindowSize(t,e){r(e),lt.set(t,e),ut.delete(t)}}}function gt(t,e,n,r){if(!Array.isArray(n)||!Array.isArray(r)||r.length!==n.length)throw Error("arrays of points and scalars must have equal length");r.forEach(((t,n)=>{if(!e.isValid(t))throw Error("wrong scalar at index "+n)})),n.forEach(((e,n)=>{if(!(e instanceof t))throw Error("wrong point at index "+n)}));const f=Z(BigInt(n.length)),o=f>12?f-3:f>4?f-2:f?2:1,i=(1<=0;e-=o){s.fill(t.ZERO);for(let t=0;t>BigInt(e)&BigInt(i));s[o]=s[o].add(n[t])}let f=t.ZERO;for(let e=s.length-1,n=t.ZERO;e>0;e--)n=n.add(s[e]),f=f.add(n);if(c=c.add(f),0!==e)for(let t=0;t(t[e]="function",t)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),j(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ot(t.n,t.nBitLength),...t,p:t.Fp.ORDER})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yt(t){void 0!==t.lowS&&B("lowS",t.lowS),void 0!==t.prehash&&B("prehash",t.prehash)}const{bytesToNumberBE:pt,hexToBytes:mt}=V,wt={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(t,e)=>{const{Err:n}=wt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(1&e.length)throw new n("tlv.encode: unpadded data");const r=e.length/2,f=I(r);if(f.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?I(f.length/2|128):"";return`${I(t)}${o}${f}${e}`},decode(t,e){const{Err:n}=wt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const f=e[r++];let o=0;if(!!(128&f)){const t=127&f;if(!t)throw new n("tlv.decode(long): indefinite length not supported");if(t>4)throw new n("tlv.decode(long): byte length is too big");const i=e.subarray(r,r+t);if(i.length!==t)throw new n("tlv.decode: length bytes not complete");if(0===i[0])throw new n("tlv.decode(long): zero leftmost byte");for(const t of i)o=o<<8|t;if(r+=t,o<128)throw new n("tlv.decode(long): not minimal encoding")}else o=f;const i=e.subarray(r,r+o);if(i.length!==o)throw new n("tlv.decode: wrong value length");return{v:i,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=wt;if(t{const f=e.toAffine();return N(Uint8Array.from([4]),n.toBytes(f.x),n.toBytes(f.y))}),o=e.fromBytes||(t=>{const e=t.subarray(1);return{x:n.fromBytes(e.subarray(0,n.BYTES)),y:n.fromBytes(e.subarray(n.BYTES,2*n.BYTES))}});function i(t){const{a:r,b:f}=e,o=n.sqr(t),i=n.mul(o,t);return n.add(n.add(i,n.mul(t,r)),f)}if(!n.eql(n.sqr(e.Gy),i(e.Gx)))throw Error("bad generator point: equation left != right");function s(t){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:f,n:o}=e;if(n&&"bigint"!=typeof t){if(m(t)&&(t=x(t)),"string"!=typeof t||!n.includes(t.length))throw Error("Invalid key");t=t.padStart(2*r,"0")}let i;try{i="bigint"==typeof t?t:R(L("private key",t,r))}catch(e){throw Error(`private key must be ${r} bytes, hex or bigint, not ${typeof t}`)}return f&&(i=X(i,o)),F("private key",i,Et,o),i}function a(t){if(!(t instanceof u))throw Error("ProjectivePoint expected")}const c=C(((t,e)=>{const{px:r,py:f,pz:o}=t;if(n.eql(o,n.ONE))return{x:r,y:f};const i=t.is0();null==e&&(e=i?n.ONE:n.inv(o));const s=n.mul(r,e),a=n.mul(f,e),c=n.mul(o,e);if(i)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw Error("invZ was invalid");return{x:s,y:a}})),d=C((t=>{if(t.is0()){if(e.allowInfinityPoint&&!n.is0(t.py))return;throw Error("bad point: ZERO")}const{x:r,y:f}=t.toAffine();if(!n.isValid(r)||!n.isValid(f))throw Error("bad point: x or y not FE");const o=n.sqr(f),s=i(r);if(!n.eql(o,s))throw Error("bad point: equation left != right");if(!t.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));class u{constructor(t,e,r){if(this.px=t,this.py=e,this.pz=r,null==t||!n.isValid(t))throw Error("x required");if(null==e||!n.isValid(e))throw Error("y required");if(null==r||!n.isValid(r))throw Error("z required");Object.freeze(this)}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw Error("invalid affine point");if(t instanceof u)throw Error("projective point not allowed");const f=t=>n.eql(t,n.ZERO);return f(e)&&f(r)?u.ZERO:new u(e,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(u.fromAffine)}static fromHex(t){const e=u.fromAffine(o(L("pointHex",t)));return e.assertValidity(),e}static fromPrivateKey(t){return u.BASE.multiply(s(t))}static msm(t,e){return gt(u,r,t,e)}_setWindowSize(t){h.setWindowSize(this,t)}assertValidity(){d(this)}hasEvenY(){const{y:t}=this.toAffine();if(n.isOdd)return!n.isOdd(t);throw Error("Field doesn't support isOdd")}equals(t){a(t);const{px:e,py:r,pz:f}=this,{px:o,py:i,pz:s}=t,c=n.eql(n.mul(e,s),n.mul(o,f)),d=n.eql(n.mul(r,s),n.mul(i,f));return c&&d}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:t,b:r}=e,f=n.mul(r,xt),{px:o,py:i,pz:s}=this;let a=n.ZERO,c=n.ZERO,d=n.ZERO,l=n.mul(o,o),h=n.mul(i,i),g=n.mul(s,s),b=n.mul(o,i);return b=n.add(b,b),d=n.mul(o,s),d=n.add(d,d),a=n.mul(t,d),c=n.mul(f,g),c=n.add(a,c),a=n.sub(h,c),c=n.add(h,c),c=n.mul(a,c),a=n.mul(b,a),d=n.mul(f,d),g=n.mul(t,g),b=n.sub(l,g),b=n.mul(t,b),b=n.add(b,d),d=n.add(l,l),l=n.add(d,l),l=n.add(l,g),l=n.mul(l,b),c=n.add(c,l),g=n.mul(i,s),g=n.add(g,g),l=n.mul(g,b),a=n.sub(a,l),d=n.mul(g,h),d=n.add(d,d),d=n.add(d,d),new u(a,c,d)}add(t){a(t);const{px:r,py:f,pz:o}=this,{px:i,py:s,pz:c}=t;let d=n.ZERO,l=n.ZERO,h=n.ZERO;const g=e.a,b=n.mul(e.b,xt);let y=n.mul(r,i),p=n.mul(f,s),m=n.mul(o,c),w=n.add(r,f),B=n.add(i,s);w=n.mul(w,B),B=n.add(y,p),w=n.sub(w,B),B=n.add(r,o);let E=n.add(i,c);return B=n.mul(B,E),E=n.add(y,m),B=n.sub(B,E),E=n.add(f,o),d=n.add(s,c),E=n.mul(E,d),d=n.add(p,m),E=n.sub(E,d),h=n.mul(g,B),d=n.mul(b,m),h=n.add(d,h),d=n.sub(p,h),h=n.add(p,h),l=n.mul(d,h),p=n.add(y,y),p=n.add(p,y),m=n.mul(g,m),B=n.mul(b,B),p=n.add(p,m),m=n.sub(y,m),m=n.mul(g,m),B=n.add(B,m),y=n.mul(p,B),l=n.add(l,y),y=n.mul(E,B),d=n.mul(w,d),d=n.sub(d,y),y=n.mul(w,p),h=n.mul(E,h),h=n.add(h,y),new u(d,l,h)}subtract(t){return this.add(t.negate())}is0(){return this.equals(u.ZERO)}wNAF(t){return h.wNAFCached(this,t,u.normalizeZ)}multiplyUnsafe(t){F("scalar",t,Bt,e.n);const r=u.ZERO;if(t===Bt)return r;if(t===Et)return this;const{endo:f}=e;if(!f)return h.unsafeLadder(this,t);let{k1neg:o,k1:i,k2neg:s,k2:a}=f.splitScalar(t),c=r,d=r,l=this;for(;i>Bt||a>Bt;)i&Et&&(c=c.add(l)),a&Et&&(d=d.add(l)),l=l.double(),i>>=Et,a>>=Et;return o&&(c=c.negate()),s&&(d=d.negate()),d=new u(n.mul(d.px,f.beta),d.py,d.pz),c.add(d)}multiply(t){const{endo:r,n:f}=e;let o,i;if(F("scalar",t,Et,f),r){const{k1neg:e,k1:f,k2neg:s,k2:a}=r.splitScalar(t);let{p:c,f:d}=this.wNAF(f),{p:l,f:g}=this.wNAF(a);c=h.constTimeNegate(e,c),l=h.constTimeNegate(s,l),l=new u(n.mul(l.px,r.beta),l.py,l.pz),o=c.add(l),i=d.add(g)}else{const{p:e,f:n}=this.wNAF(t);o=e,i=n}return u.normalizeZ([o,i])[0]}multiplyAndAddUnsafe(t,e,n){const r=u.BASE,f=(t,e)=>e!==Bt&&e!==Et&&t.equals(r)?t.multiply(e):t.multiplyUnsafe(e),o=f(this,e).add(f(t,n));return o.is0()?void 0:o}toAffine(t){return c(this,t)}isTorsionFree(){const{h:t,isTorsionFree:n}=e;if(t===Et)return!0;if(n)return n(u,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:t,clearCofactor:n}=e;return t===Et?this:n?n(u,this):this.multiplyUnsafe(e.h)}toRawBytes(t=!0){return B("isCompressed",t),this.assertValidity(),f(u,this,t)}toHex(t=!0){return B("isCompressed",t),x(this.toRawBytes(t))}}u.BASE=new u(e.Gx,e.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const l=e.nBitLength,h=ht(u,e.endo?Math.ceil(l/2):l);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:s,weierstrassEquation:i,isWithinCurveOrder:function(t){return T(t,Et,e.n)}}}function vt(t){const e=function(t){const e=bt(t);return j(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}(t),{Fp:n,n:r}=e,f=n.BYTES+1,o=2*n.BYTES+1;function i(t){return X(t,r)}function s(t){return nt(t,r)}const{ProjectivePoint:a,normPrivateKeyToScalar:c,weierstrassEquation:d,isWithinCurveOrder:u}=It({...e,toBytes(t,e,r){const f=e.toAffine(),o=n.toBytes(f.x),i=N;return B("isCompressed",r),r?i(Uint8Array.from([e.hasEvenY()?2:3]),o):i(Uint8Array.from([4]),o,n.toBytes(f.y))},fromBytes(t){const e=t.length,r=t[0],i=t.subarray(1);if(e!==f||2!==r&&3!==r){if(e===o&&4===r){return{x:n.fromBytes(i.subarray(0,n.BYTES)),y:n.fromBytes(i.subarray(n.BYTES,2*n.BYTES))}}throw Error(`Point of length ${e} was invalid. Expected ${f} compressed bytes or ${o} uncompressed bytes`)}{const t=R(i);if(!T(t,Et,n.ORDER))throw Error("Point is not on curve");const e=d(t);let f;try{f=n.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw Error("Point is not on curve"+e)}return!(1&~r)!==((f&Et)===Et)&&(f=n.neg(f)),{x:t,y:f}}}}),l=t=>x(z(t,e.nByteLength));function h(t){return t>r>>Et}const g=(t,e,n)=>R(t.slice(e,n));class b{constructor(t,e,n){this.r=t,this.s=e,this.recovery=n,this.assertValidity()}static fromCompact(t){const n=e.nByteLength;return t=L("compactSignature",t,2*n),new b(g(t,0,n),g(t,n,2*n))}static fromDER(t){const{r:e,s:n}=wt.toSig(L("DER",t));return new b(e,n)}assertValidity(){F("r",this.r,Et,r),F("s",this.s,Et,r)}addRecoveryBit(t){return new b(this.r,this.s,t)}recoverPublicKey(t){const{r,s:f,recovery:o}=this,c=E(L("msgHash",t));if(null==o||![0,1,2,3].includes(o))throw Error("recovery id invalid");const d=2===o||3===o?r+e.n:r;if(d>=n.ORDER)throw Error("recovery id 2 or 3 invalid");const u=1&o?"03":"02",h=a.fromHex(u+l(d)),g=s(d),b=i(-c*g),y=i(f*g),p=a.BASE.multiplyAndAddUnsafe(h,b,y);if(!p)throw Error("point at infinify");return p.assertValidity(),p}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return O(this.toDERHex())}toDERHex(){return wt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return O(this.toCompactHex())}toCompactHex(){return l(this.r)+l(this.s)}}const y={isValidPrivateKey(t){try{return c(t),!0}catch(t){return!1}},normPrivateKeyToScalar:c,randomPrivateKey:()=>{const t=at(e.n);return function(t,e,n=!1){const r=t.length,f=st(e),o=at(e);if(r<16||r1024)throw Error(`expected ${o}-1024 bytes of input, got ${r}`);const i=X(n?R(t):q(t),e-Y)+Y;return n?P(i,f):z(i,f)}(e.randomBytes(t),e.n)},precompute:(t=8,e=a.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)};function p(t){const e=m(t),n="string"==typeof t,r=(e||n)&&t.length;return e?r===f||r===o:n?r===2*f||r===2*o:t instanceof a}const w=e.bits2int||function(t){const n=R(t),r=8*t.length-e.nBitLength;return r>0?n>>BigInt(r):n},E=e.bits2int_modN||function(t){return i(w(t))},I=$(e.nBitLength);function v(t){return F("num < 2^"+e.nBitLength,t,Bt,I),z(t,e.nByteLength)}function S(t,r,f=A){if(["recovered","canonical"].some((t=>t in f)))throw Error("sign() legacy options not supported");const{hash:o,randomBytes:d}=e;let{lowS:l,prehash:g,extraEntropy:y}=f;null==l&&(l=!0),t=L("msgHash",t),yt(f),g&&(t=L("prehashed msgHash",o(t)));const p=E(t),m=c(r),B=[v(m),v(p)];if(null!=y&&!1!==y){const t=!0===y?d(n.BYTES):y;B.push(L("extraEntropy",t))}const x=N(...B),I=p;return{seed:x,k2sig:function(t){const e=w(t);if(!u(e))return;const n=s(e),r=a.BASE.multiply(e).toAffine(),f=i(r.x);if(f===Bt)return;const o=i(n*i(I+f*m));if(o===Bt)return;let c=(r.x===f?0:2)|Number(r.y&Et),d=o;return l&&h(o)&&(d=function(t){return h(t)?i(-t):t}(o),c^=1),new b(f,d,c)}}}const A={lowS:e.lowS,prehash:!1},H={lowS:e.lowS,prehash:!1};return a.BASE._setWindowSize(8),{CURVE:e,getPublicKey:function(t,e=!0){return a.fromPrivateKey(t).toRawBytes(e)},getSharedSecret:function(t,e,n=!0){if(p(t))throw Error("first arg must be private key");if(!p(e))throw Error("second arg must be public key");return a.fromHex(e).multiply(c(t)).toRawBytes(n)},sign:function(t,n,r=A){const{seed:f,k2sig:o}=S(t,n,r),i=e;return G(i.hash.outputLen,i.nByteLength,i.hmac)(f,o)},verify:function(t,n,r,f=H){const o=t;if(n=L("msgHash",n),r=L("publicKey",r),"strict"in f)throw Error("options.strict was renamed to lowS");yt(f);const{lowS:c,prehash:d}=f;let u,l;try{if("string"==typeof o||m(o))try{u=b.fromDER(o)}catch(t){if(!(t instanceof wt.Err))throw t;u=b.fromCompact(o)}else{if("object"!=typeof o||"bigint"!=typeof o.r||"bigint"!=typeof o.s)throw Error("PARSE");{const{r:t,s:e}=o;u=new b(t,e)}}l=a.fromHex(r)}catch(t){if("PARSE"===t.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(c&&u.hasHighS())return!1;d&&(n=e.hash(n));const{r:h,s:g}=u,y=E(n),p=s(g),w=i(y*p),B=i(h*p),x=a.BASE.multiplyAndAddUnsafe(l,w,B)?.toAffine();return!!x&&i(x.x)===h},ProjectivePoint:a,Signature:b,utils:y}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function St(t){return{hash:t,hmac:(e,...n)=>g(t,e,o(...n)),randomBytes:i}}function At(t,e){const n=e=>vt({...t,...St(e)});return Object.freeze({...n(e),create:n})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const Ot=it(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Rt=At({a:Ot.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:Ot,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},s),qt=it(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),zt=At({a:qt.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:qt,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},a),Pt=it(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),Lt={a:Pt.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:Pt,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1)},Nt=At({a:Lt.a,b:Lt.b,Fp:Pt,n:Lt.n,Gx:Lt.Gx,Gy:Lt.Gy,h:Lt.h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},c),Ht=BigInt(0),Tt=BigInt(1),Ft=BigInt(2),Zt=BigInt(8),$t={zip215:!0};function _t(t){const e=function(t){const e=bt(t);return j(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}(t),{Fp:n,n:r,prehash:f,hash:o,randomBytes:i,nByteLength:s,h:a}=e,c=Ft<{try{return{isValid:!0,value:n.sqrt(t*n.inv(e))}}catch(t){return{isValid:!1,value:Ht}}}),h=e.adjustScalarBytes||(t=>t),g=e.domain||((t,e,n)=>{if(B("phflag",n),e.length||n)throw Error("Contexts/pre-hash are not supported");return t});function b(t,e){F("coordinate "+t,e,Ht,c)}function y(t){if(!(t instanceof w))throw Error("ExtendedPoint expected")}const p=C(((t,e)=>{const{ex:r,ey:f,ez:o}=t,i=t.is0();null==e&&(e=i?Zt:n.inv(o));const s=d(r*e),a=d(f*e),c=d(o*e);if(i)return{x:Ht,y:Tt};if(c!==Tt)throw Error("invZ was invalid");return{x:s,y:a}})),m=C((t=>{const{a:n,d:r}=e;if(t.is0())throw Error("bad point: ZERO");const{ex:f,ey:o,ez:i,et:s}=t,a=d(f*f),c=d(o*o),u=d(i*i),l=d(u*u),h=d(a*n);if(d(u*d(h+c))!==d(l+d(r*d(a*c))))throw Error("bad point: equation left != right (1)");if(d(f*o)!==d(i*s))throw Error("bad point: equation left != right (2)");return!0}));class w{constructor(t,e,n,r){this.ex=t,this.ey=e,this.ez=n,this.et=r,b("x",t),b("y",e),b("z",n),b("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(t){if(t instanceof w)throw Error("extended point not allowed");const{x:e,y:n}=t||{};return b("x",e),b("y",n),new w(e,n,Tt,d(e*n))}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.ez)));return t.map(((t,n)=>t.toAffine(e[n]))).map(w.fromAffine)}static msm(t,e){return gt(w,u,t,e)}_setWindowSize(t){v.setWindowSize(this,t)}assertValidity(){m(this)}equals(t){y(t);const{ex:e,ey:n,ez:r}=this,{ex:f,ey:o,ez:i}=t,s=d(e*i),a=d(f*r),c=d(n*i),u=d(o*r);return s===a&&c===u}is0(){return this.equals(w.ZERO)}negate(){return new w(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){const{a:t}=e,{ex:n,ey:r,ez:f}=this,o=d(n*n),i=d(r*r),s=d(Ft*d(f*f)),a=d(t*o),c=n+r,u=d(d(c*c)-o-i),l=a+i,h=l-s,g=a-i,b=d(u*h),y=d(l*g),p=d(u*g),m=d(h*l);return new w(b,y,m,p)}add(t){y(t);const{a:n,d:r}=e,{ex:f,ey:o,ez:i,et:s}=this,{ex:a,ey:c,ez:u,et:l}=t;if(n===BigInt(-1)){const t=d((o-f)*(c+a)),e=d((o+f)*(c-a)),n=d(e-t);if(n===Ht)return this.double();const r=d(i*Ft*l),h=d(s*Ft*u),g=h+r,b=e+t,y=h-r,p=d(g*n),m=d(b*y),B=d(g*y),E=d(n*b);return new w(p,m,E,B)}const h=d(f*a),g=d(o*c),b=d(s*r*l),p=d(i*u),m=d((f+o)*(a+c)-h-g),B=p-b,E=p+b,x=d(g-n*h),I=d(m*B),v=d(E*x),S=d(m*x),A=d(B*E);return new w(I,v,A,S)}subtract(t){return this.add(t.negate())}wNAF(t){return v.wNAFCached(this,t,w.normalizeZ)}multiply(t){const e=t;F("scalar",e,Tt,r);const{p:n,f}=this.wNAF(e);return w.normalizeZ([n,f])[0]}multiplyUnsafe(t){const e=t;return F("scalar",e,Ht,r),e===Ht?I:this.equals(I)||e===Tt?this:this.equals(E)?this.wNAF(e).p:v.unsafeLadder(this,e)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return v.unsafeLadder(this,r).is0()}toAffine(t){return p(this,t)}clearCofactor(){const{h:t}=e;return t===Tt?this:this.multiplyUnsafe(t)}static fromHex(t,r=!1){const{d:f,a:o}=e,i=n.BYTES;t=L("pointHex",t,i),B("zip215",r);const s=t.slice(),a=t[i-1];s[i-1]=-129&a;const u=q(s),h=r?c:n.ORDER;F("pointHex.y",u,Ht,h);const g=d(u*u),b=d(g-Tt),y=d(f*g-o);let{isValid:p,value:m}=l(b,y);if(!p)throw Error("Point.fromHex: invalid y coordinate");const E=(m&Tt)===Tt,x=!!(128&a);if(!r&&m===Ht&&x)throw Error("Point.fromHex: x=0 and x_0=1");return x!==E&&(m=d(-m)),w.fromAffine({x:m,y:u})}static fromPrivateKey(t){return O(t).point}toRawBytes(){const{x:t,y:e}=this.toAffine(),r=P(e,n.BYTES);return r[r.length-1]|=t&Tt?128:0,r}toHex(){return x(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Tt,d(e.Gx*e.Gy)),w.ZERO=new w(Ht,Tt,Tt,Ht);const{BASE:E,ZERO:I}=w,v=ht(w,8*s);function S(t){return X(t,r)}function A(t){return S(q(t))}function O(t){const e=s;t=L("private key",t,e);const n=L("hashed private key",o(t),2*e),r=h(n.slice(0,e)),f=n.slice(e,2*e),i=A(r),a=E.multiply(i),c=a.toRawBytes();return{head:r,prefix:f,scalar:i,point:a,pointBytes:c}}function R(t=new Uint8Array,...e){const n=N(...e);return A(o(g(n,L("context",t),!!f)))}const z=$t;E._setWindowSize(8);return{CURVE:e,getPublicKey:function(t){return O(t).pointBytes},sign:function(t,e,o={}){t=L("message",t),f&&(t=f(t));const{prefix:i,scalar:a,pointBytes:c}=O(e),d=R(o.context,i,t),u=E.multiply(d).toRawBytes(),l=S(d+R(o.context,u,c,t)*a);return F("signature.s",l,Ht,r),L("result",N(u,P(l,n.BYTES)),2*s)},verify:function(t,e,r,o=z){const{context:i,zip215:s}=o,a=n.BYTES;t=L("signature",t,2*a),e=L("message",e),void 0!==s&&B("zip215",s),f&&(e=f(e));const c=q(t.slice(a,2*a));let d,u,l;try{d=w.fromHex(r,s),u=w.fromHex(t.slice(0,a),s),l=E.multiplyUnsafe(c)}catch(t){return!1}if(!s&&d.isSmallOrder())return!1;const h=R(i,u.toRawBytes(),d.toRawBytes(),e);return u.add(d.multiplyUnsafe(h)).subtract(l).clearCofactor().equals(w.ZERO)},ExtendedPoint:w,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>i(n.BYTES),precompute:(t=8,e=w.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)}}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kt=BigInt(0),Gt=BigInt(1);function Ut(t){const e=(j(n=t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...n}));var n;const{P:r}=e,f=t=>X(t,r),o=e.montgomeryBits,i=Math.ceil(o/8),s=e.nByteLength,a=e.adjustScalarBytes||(t=>t),c=e.powPminus2||(t=>tt(t,r-BigInt(2),r));function d(t,e,n){const r=f(t*(e-n));return[e=f(e-r),n=f(n+r)]}const u=(e.a-BigInt(2))/BigInt(4);function l(t){return P(f(t),i)}function h(t,e){const n=function(t){const e=L("u coordinate",t,i);return 32===s&&(e[31]&=127),q(e)}(e),h=function(t){const e=L("scalar",t),n=e.length;if(n!==i&&n!==s)throw Error(`Expected ${i} or ${s} bytes, got ${n}`);return q(a(e))}(t),g=function(t,e){F("u",t,kt,r),F("scalar",e,kt,r);const n=e,i=t;let s,a=Gt,l=kt,h=t,g=Gt,b=kt;for(let t=BigInt(o-1);t>=kt;t--){const e=n>>t≫b^=e,s=d(b,a,h),a=s[0],h=s[1],s=d(b,l,g),l=s[0],g=s[1],b=e;const r=a+l,o=f(r*r),c=a-l,y=f(c*c),p=o-y,m=h+g,w=f((h-g)*r),B=f(m*c),E=w+B,x=w-B;h=f(E*E),g=f(i*f(x*x)),a=f(o*y),l=f(p*(o+f(u*p)))}s=d(b,a,h),a=s[0],h=s[1],s=d(b,l,g),l=s[0],g=s[1];const y=c(l);return f(a*y)}(n,h);if(g===kt)throw Error("Invalid private or public key received");return l(g)}const g=l(e.Gu);function b(t){return h(t,g)}return{scalarMult:h,scalarMultBase:b,getSharedSecret:(t,e)=>h(t,e),getPublicKey:t=>b(t),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:g}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jt=d((()=>l.create({dkLen:114}))),Ct=(d((()=>l.create({dkLen:64}))),BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439")),Vt=BigInt(1),Kt=BigInt(2),Yt=BigInt(3);BigInt(4);const Mt=BigInt(11),Wt=BigInt(22),Dt=BigInt(44),Jt=BigInt(88),Qt=BigInt(223);function Xt(t){const e=Ct,n=t*t*t%e,r=n*n*t%e,f=et(r,Yt,e)*r%e,o=et(f,Yt,e)*r%e,i=et(o,Kt,e)*n%e,s=et(i,Mt,e)*i%e,a=et(s,Wt,e)*s%e,c=et(a,Dt,e)*a%e,d=et(c,Jt,e)*c%e,u=et(d,Dt,e)*a%e,l=et(u,Kt,e)*n%e,h=et(l,Vt,e)*t%e;return et(h,Qt,e)*l%e}function te(t){return t[0]&=252,t[55]|=128,t[56]=0,t}const ee=it(Ct,456,!0),ne={a:BigInt(1),d:BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"),Fp:ee,n:BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"),nBitLength:456,h:BigInt(4),Gx:BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"),Gy:BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"),hash:jt,randomBytes:i,adjustScalarBytes:te,domain:(t,e,n)=>{if(e.length>255)throw Error("Context is too big: "+e.length);return o(u("SigEd448"),new Uint8Array([n?1:0,e.length]),e,t)},uvRatio:function(t,e){const n=Ct,r=X(t*t*e,n),f=X(r*t,n),o=X(f*r*e,n),i=X(f*Xt(o),n),s=X(i*i,n);return{isValid:X(s*e,n)===t,value:i}}},re=/* @__PURE__ */_t(ne),fe=/* @__PURE__ */(()=>Ut({a:BigInt(156326),montgomeryBits:448,nByteLength:56,P:Ct,Gu:BigInt(5),powPminus2:t=>{const e=Ct;return X(et(Xt(t),BigInt(2),e)*t,e)},adjustScalarBytes:te,randomBytes:i}))();ee.ORDER,BigInt(3),BigInt(4),BigInt(156326),BigInt("39082"),BigInt("78163"),BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"),BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"),BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const oe=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ie=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),se=BigInt(1),ae=BigInt(2),ce=(t,e)=>(t+e/ae)/e;const de=it(oe,void 0,void 0,{sqrt:function(t){const e=oe,n=BigInt(3),r=BigInt(6),f=BigInt(11),o=BigInt(22),i=BigInt(23),s=BigInt(44),a=BigInt(88),c=t*t*t%e,d=c*c*t%e,u=et(d,n,e)*d%e,l=et(u,n,e)*d%e,h=et(l,ae,e)*c%e,g=et(h,f,e)*h%e,b=et(g,o,e)*g%e,y=et(b,s,e)*b%e,p=et(y,a,e)*y%e,m=et(p,s,e)*b%e,w=et(m,n,e)*d%e,B=et(w,i,e)*g%e,E=et(B,r,e)*c%e,x=et(E,ae,e);if(!de.eql(de.sqr(x),t))throw Error("Cannot find square root");return x}}),ue=At({a:BigInt(0),b:BigInt(7),Fp:de,n:ie,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=ie,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-se*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),f=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),s=ce(o*t,e),a=ce(-r*t,e);let c=X(t-s*n-a*f,e),d=X(-s*r-a*o,e);const u=c>i,l=d>i;if(u&&(c=e-c),l&&(d=e-d),c>i||d>i)throw Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:c,k2neg:l,k2:d}}}},s);BigInt(0),ue.ProjectivePoint;const le=it(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377")),he=At({a:le.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),b:BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),Fp:le,n:BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),Gx:BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),Gy:BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),h:BigInt(1),lowS:!1},s),ge=it(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53")),be=At({a:ge.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),b:BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),Fp:ge,n:BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),Gx:BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),Gy:BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),h:BigInt(1),lowS:!1},a),ye=it(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3")),pe=At({a:ye.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),b:BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),Fp:ye,n:BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),Gx:BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),Gy:BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),h:BigInt(1),lowS:!1},c),me=new Map(Object.entries({nistP256:Rt,nistP384:zt,nistP521:Nt,brainpoolP256r1:he,brainpoolP384r1:be,brainpoolP512r1:pe,secp256k1:ue,x448:fe,ed448:re}));export{me as nobleCurves}; +//# sourceMappingURL=noble_curves.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs.map new file mode 100644 index 000000000..c7d845370 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_curves.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"noble_curves.min.mjs","sources":["../../node_modules/@noble/hashes/esm/hmac.js","../../node_modules/@noble/curves/esm/abstract/utils.js","../../node_modules/@noble/curves/esm/abstract/modular.js","../../node_modules/@noble/curves/esm/abstract/curve.js","../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../node_modules/@noble/curves/esm/_shortw_utils.js","../../node_modules/@noble/curves/esm/p256.js","../../node_modules/@noble/curves/esm/p384.js","../../node_modules/@noble/curves/esm/p521.js","../../node_modules/@noble/curves/esm/abstract/edwards.js","../../node_modules/@noble/curves/esm/abstract/montgomery.js","../../node_modules/@noble/curves/esm/ed448.js","../../node_modules/@noble/curves/esm/secp256k1.js","../../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP256r1.ts","../../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP384r1.ts","../../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP512r1.ts","../../src/crypto/public_key/elliptic/noble_curves.js"],"sourcesContent":["import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n}, sha256);\nexport const secp256r1 = p256;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha384 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp384r1 aka p384\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');\nconst Fp = Field(P);\nconst CURVE_A = Fp.create(BigInt('-3'));\n// prettier-ignore\nconst CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n// prettier-ignore\nexport const p384 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\n // Curve order, total count of valid points in the field.\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n // Base (generator) point (x, y)\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n h: BigInt(1),\n lowS: false,\n}, sha384);\nexport const secp384r1 = p384;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-12')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p384.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp521r1 aka p521\n// Note that it's 521, which differs from 512 of its hash function.\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst Fp = Field(P);\nconst CURVE = {\n a: Fp.create(BigInt('-3')),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Fp,\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n h: BigInt(1),\n};\n// prettier-ignore\nexport const p521 = createCurve({\n a: CURVE.a, // Equation params: a, b\n b: CURVE.b,\n Fp, // Field: 2n**521n - 1n\n // Curve order, total count of valid points in the field\n n: CURVE.n,\n Gx: CURVE.Gx, // Base point (x, y) aka generator point\n Gy: CURVE.Gy,\n h: CURVE.h,\n lowS: false,\n allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\nexport const secp521r1 = p521;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE.a,\n B: CURVE.b,\n Z: Fp.create(BigInt('-4')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p521.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3';\nimport { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xof } from './abstract/hash-to-curve.js';\nimport { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * Edwards448 (not Ed448-Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n */\nconst shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));\nconst ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');\n// prettier-ignore\nconst _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);\n// prettier-ignore\nconst _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448P;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most\n // significant bit of the last byte to 1.\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.\n// Uses algo from RFC8032 5.1.3.\nfunction uvRatio(u, v) {\n const P = ed448P;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u²v\n const u3v = mod(u2v * u, P); // u³v\n const u5v3 = mod(u3v * u2v * v, P); // u⁵v³\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x²\n // If vx² = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\nconst Fp = Field(ed448P, 456, true);\nconst ED448_DEF = {\n // Param: a\n a: BigInt(1),\n // -39081. Negative number is P - number\n d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'),\n // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n\n Fp,\n // Subgroup order: how many points curve has;\n // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\n n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n nBitLength: 456,\n // Cofactor\n h: BigInt(4),\n // Base point (x, y) aka generator point\n Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'),\n Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'),\n // SHAKE256(dom4(phflag,context)||x, 114)\n hash: shake256_114,\n randomBytes,\n adjustScalarBytes,\n // dom4\n domain: (data, ctx, phflag) => {\n if (ctx.length > 255)\n throw new Error(`Context is too big: ${ctx.length}`);\n return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n },\n uvRatio,\n};\nexport const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF);\n// NOTE: there is no ed448ctx, since ed448 supports ctx by default\nexport const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 });\nexport const x448 = /* @__PURE__ */ (() => montgomery({\n a: BigInt(156326),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n montgomeryBits: 448,\n nByteLength: 56,\n P: ed448P,\n Gu: BigInt(5),\n powPminus2: (x) => {\n const P = ed448P;\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, BigInt(2), P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts edwards448 public key to x448 public key. Uses formula:\n * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n * @example\n * const aPub = ed448.getPublicKey(utils.randomPrivateKey());\n * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed448.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version\n// Hash To Curve Elligator2 Map\nconst ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic\nconst ELL2_J = BigInt(156326);\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\nfunction map_to_curve_elligator2_edwards448(u) {\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = Fp.invertBatch([xEd, yEd]); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertDcfPoint(other) {\n if (!(other instanceof DcfPoint))\n throw new Error('DecafPoint expected');\n}\n// 1-d\nconst ONE_MINUS_D = BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = BigInt('78163');\n// √(-d)\nconst SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / √(-d)\nconst INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B);\n// Computes Elligator map for Decaf\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const r = mod(-(r0 * r0)); // 1\n const u0 = mod(d * (r - _1n)); // 2\n const u1 = mod((u0 + _1n) * (u0 - r)); // 3\n const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = mod(r0 * v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = mod(-_1n);\n const s = mod(v_prime * (r + _1n)); // 7\n let s_abs = s;\n if (isNegativeLE(s, P))\n s_abs = mod(-s);\n const s2 = s * s;\n const W0 = mod(s_abs * _2n); // 8\n const W1 = mod(s2 + _1n); // 9\n const W2 = mod(s2 - _1n); // 10\n const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11\n return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed448/ExtendedPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass DcfPoint {\n // Private property to discourage combining ExtendedPoint + DecafPoint\n // Always use Decaf encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\n * @param hex 112-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('decafHash', hex, 112);\n const r1 = bytes448ToNumberLE(hex.slice(0, 56));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = bytes448ToNumberLE(hex.slice(56, 112));\n const R2 = calcElligatorDecafMap(r2);\n return new DcfPoint(R1.add(R2));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2\n * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('decafHex', hex, 56);\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint';\n const s = bytes448ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s); // 1\n const u1 = mod(_1n + s2); // 2\n const u1sq = mod(u1 * u1);\n const u2 = mod(u1sq - _4n * d * s2); // 3\n const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4\n let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5\n if (isNegativeLE(u3, P))\n u3 = mod(-u3);\n const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6\n const y = mod((_1n - s2) * invsqrt * u1); // 7\n const t = mod(x * y); // 8\n if (!isValid)\n throw new Error(emsg);\n return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2\n */\n toRawBytes() {\n let { ex: x, ey: _y, ez: z, et: t } = this.ep;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const u1 = mod(mod(x + t) * mod(x - t)); // 1\n const x2 = mod(x * x);\n const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2\n let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3\n if (isNegativeLE(ratio, P))\n ratio = mod(-ratio);\n const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4\n let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 56);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2\n equals(other) {\n assertDcfPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed448.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2)\n return mod(X1 * Y2) === mod(Y1 * X2);\n }\n add(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new DcfPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new DcfPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new DcfPoint(this.ep.double());\n }\n negate() {\n return new DcfPoint(this.ep.negate());\n }\n}\nexport const DecafPoint = /* @__PURE__ */ (() => {\n // decaf448 base point is ed448 base x 2\n // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699\n if (!DcfPoint.BASE)\n DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n);\n if (!DcfPoint.ZERO)\n DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO);\n return DcfPoint;\n})();\n// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C\nexport const hashToDecaf448 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256);\n const P = DcfPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_decaf448 = hashToDecaf448; // legacy\n//# sourceMappingURL=ed448.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));\nconst CURVE_A = Fp.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));\nconst CURVE_B = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');\n\n// prettier-ignore\nexport const brainpoolP256r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),\n Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),\n h: BigInt(1),\n lowS: false\n} as const, sha256);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha384 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));\nconst CURVE_A = Fp.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));\nconst CURVE_B = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');\n\n// prettier-ignore\nexport const brainpoolP384r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),\n Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),\n h: BigInt(1),\n lowS: false\n} as const, sha384);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));\nconst CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));\nconst CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');\n\n// prettier-ignore\nexport const brainpoolP512r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),\n Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),\n h: BigInt(1),\n lowS: false\n} as const, sha512);\n","/**\n * This file is needed to dynamic import the noble-curves.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { p256 as nistP256 } from '@noble/curves/p256';\nimport { p384 as nistP384 } from '@noble/curves/p384';\nimport { p521 as nistP521 } from '@noble/curves/p521';\nimport { x448, ed448 } from '@noble/curves/ed448';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { brainpoolP256r1 } from './brainpool/brainpoolP256r1';\nimport { brainpoolP384r1 } from './brainpool/brainpoolP384r1';\nimport { brainpoolP512r1 } from './brainpool/brainpoolP512r1';\n\nexport const nobleCurves = new Map(Object.entries({\n nistP256,\n nistP384,\n nistP521,\n brainpoolP256r1,\n brainpoolP384r1,\n brainpoolP512r1,\n secp256k1,\n x448,\n ed448\n}));\n\n"],"names":["HMAC","Hash","constructor","hash","_key","super","this","finished","destroyed","assertHash","key","toBytes","iHash","create","update","Error","blockLen","outputLen","pad","Uint8Array","set","length","digest","i","oHash","fill","buf","assertExists","digestInto","out","assertBytes","destroy","_cloneInto","to","Object","getPrototypeOf","hmac","message","_0n","BigInt","_1n","_2n","isBytes","a","name","abytes","item","abool","title","value","hexes","Array","from","_","toString","padStart","bytesToHex","bytes","hex","numberToHexUnpadded","num","hexToNumber","asciis","_0","_9","_A","_F","_a","_f","asciiToBase16","char","hexToBytes","hl","al","array","ai","hi","n1","charCodeAt","n2","undefined","bytesToNumberBE","bytesToNumberLE","reverse","numberToBytesBE","n","len","numberToBytesLE","ensureBytes","expectedLength","res","e","concatBytes","arrays","sum","isPosBig","inRange","min","max","aInRange","bitLen","bitMask","u8n","data","u8fr","arr","createHmacDrbg","hashLen","qByteLen","hmacFn","v","k","reset","h","b","reseed","seed","gen","sl","slice","push","pred","validatorFns","bigint","val","function","boolean","string","stringOrUint8Array","isSafeInteger","Number","isArray","field","object","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","type","isOptional","checkVal","String","entries","memoized","fn","map","WeakMap","arg","args","get","computed","pos","diff","str","TextEncoder","encode","_3n","_4n","_5n","_8n","mod","result","pow","power","modulo","pow2","x","invert","number","u","r","m","FpSqrt","P","p1div4","root","eql","sqr","c1","mul","nv","sub","ONE","legendreC","Q","S","Z","Q1div2","neg","g","ZERO","t2","ge","tonelliShanks","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Math","ceil","Field","ORDER","isLE","redef","BITS","BYTES","sqrtP","f","freeze","MASK","is0","isOdd","lhs","rhs","add","p","d","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","lst","nums","tmp","lastMultiplied","reduce","acc","inverted","reduceRight","FpInvertBatch","cmov","c","fromBytes","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","bits","constTimeNegate","condition","negate","validateW","W","opts","windows","windowSize","unsafeLadder","elm","double","precomputeWindow","points","base","window","precomputes","BASE","mask","maxNumber","shiftBy","offset","wbits","offset1","offset2","abs","cond1","cond2","wNAFCached","transform","comp","setWindowSize","delete","pippenger","scalars","forEach","s","buckets","lastBits","floor","j","scalar","resI","sumI","validateBasic","curve","Gx","Gy","validateSigVerOpts","lowS","prehash","b2n","h2b","ut","DER","Err","_tlv","tag","E","dataLen","ut.numberToHexUnpadded","lenLen","decode","first","lengthBytes","subarray","l","_int","parseInt","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","sig","seq","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","_c","point","_isCompressed","toAffine","ut.concatBytes","y","tail","weierstrassEquation","x2","x3","normPrivateKeyToScalar","lengths","N","ut.isBytes","ut.bytesToHex","includes","ut.bytesToNumberBE","error","mod.mod","ut.aInRange","assertPrjPoint","other","Point","toAffineMemo","iz","px","py","pz","z","ax","ay","zz","assertValidMemo","left","right","fromAffine","normalizeZ","toInv","fromHex","assertValidity","fromPrivateKey","privateKey","multiply","msm","_setWindowSize","wnaf","hasEvenY","equals","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t3","t4","t5","subtract","multiplyUnsafe","sc","I","k1neg","k1","k2neg","k2","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","G","cofactor","toRawBytes","isCompressed","toHex","_bits","ProjectivePoint","isWithinCurveOrder","ut.inRange","weierstrass","curveDef","randomBytes","bits2int","bits2int_modN","validateOpts","CURVE_ORDER","compressedLen","uncompressedLen","modN","invN","mod.invert","cat","head","y2","sqrtError","suffix","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","prefix","R","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","utils","isValidPrivateKey","randomPrivateKey","mod.getMinHashLength","fieldLen","minLen","reduced","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","some","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","q","normS","defaultVerOpts","getPublicKey","getSharedSecret","privateA","publicB","sign","privKey","C","ut.createHmacDrbg","drbg","verify","signature","publicKey","sg","_sig","derError","is","getHash","msgs","createCurve","defHash","p256","sha256","p384","sha384","p521","sha512","VERIFY_DEFAULT","zip215","twistedEdwards","adjustScalarBytes","domain","uvRatio","mapToCurve","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","X","Y","et","T","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","A","B","D","x1y1","F","H","T3","T1","T2","isSmallOrder","normed","lastByte","ut.bytesToNumberLE","isXOdd","isLastByteOdd","getExtendedPublicKey","ut.numberToBytesLE","modN_LE","hashed","pointBytes","hashDomainToScalar","context","msg","verifyOpts","options","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","cswap","swap","x_2","x_3","dummy","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","t","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","shake256_114","wrapConstructor","shake256","dkLen","ed448P","_11n","_22n","_44n","_88n","_223n","ed448_pow_Pminus3div4","b2","b6","b9","b11","b22","b44","b88","b176","b220","b222","b223","ED448_DEF","utf8ToBytes","u2v","u3v","u5v3","ed448","x448","secp256k1P","secp256k1N","divNearest","_6n","_23n","secp256k1","a1","b1","a2","POW_2_128","c2","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","nobleCurves","Map","nistP256","nistP384","nistP521"],"mappings":";2MAGO,MAAMA,UAAaC,EACtB,WAAAC,CAAYC,EAAMC,GACdC,QACAC,KAAKC,UAAW,EAChBD,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H,OAAO0B,OAAO,uEAM/B2E,EALc3E,OAAO,yEAMrB+F,GAEAjD,EAAG9C,OAAO,sEAEVgQ,GAAIhQ,OAAO,sEACXiQ,GAAIjQ,OAAO,sEACX0E,EAAG1E,OAAO,GACVmQ,MAAM,GACIiO,GChBNrY,GAAKsE,GAAMrK,OAAO,uGAKX0mB,GAAkBzI,GAAY,CACzC7d,EALc2F,GAAGzH,OAAO0B,OAAO,uGAM/B2E,EALc3E,OAAO,yGAMrB+F,GAEAjD,EAAG9C,OAAO,sGAEVgQ,GAAIhQ,OAAO,sGACXiQ,GAAIjQ,OAAO,sGACX0E,EAAG1E,OAAO,GACVmQ,MAAM,GACImO,GChBNvY,GAAKsE,GAAMrK,OAAO,uIAKX2mB,GAAkB1I,GAAY,CACzC7d,EALc2F,GAAGzH,OAAO0B,OAAO,uIAM/B2E,EALc3E,OAAO,sIAMrB+F,MAEAjD,EAAG9C,OAAO,sIAEVgQ,GAAIhQ,OAAO,sIACXiQ,GAAIjQ,OAAO,sIACX0E,EAAG1E,OAAO,GACVmQ,MAAM,GACIqO,GCRCoI,GAAc,IAAIC,IAAIlnB,OAAO+G,QAAQ,CAClDogB,SAAEA,GACFC,SAAEA,GACFC,SAAEA,GACAP,mBACAC,mBACAC,mBACAR,aACAN,QACAD","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/noble_curves.mjs b/app/node_modules/openpgp/dist/lightweight/noble_curves.mjs new file mode 100644 index 000000000..e54561c75 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_curves.mjs @@ -0,0 +1,2994 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +import { H as Hash, h as hash, t as toBytes, e as exists, b as bytes, c as concatBytes$1, r as randomBytes, s as sha256, a as sha384, d as sha512, w as wrapConstructor, u as utf8ToBytes$1, f as shake256 } from './sha3.mjs'; + +// HMAC (RFC 2104) +class HMAC extends Hash { + constructor(hash$1, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash$1.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + * @example + * import { hmac } from '@noble/hashes/hmac'; + * import { sha256 } from '@noble/hashes/sha2'; + * const mac1 = hmac(sha256, 'key', 'message'); + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n$5 = /* @__PURE__ */ BigInt(0); +const _1n$7 = /* @__PURE__ */ BigInt(1); +const _2n$4 = /* @__PURE__ */ BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Is positive bigint +const isPosBig = (n) => typeof n === 'bigint' && _0n$5 <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +/** + * Asserts min <= n < max. NOTE: It's < max and not <= max. + * @example + * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) + */ +function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n$5; n >>= _1n$7, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n$7; +} +/** + * Sets single bit at position. + */ +function bitSet(n, pos, value) { + return n | ((value ? _1n$7 : _0n$5) << BigInt(pos)); +} +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n$4 << BigInt(n - 1)) - _1n$7; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +/** + * throws not implemented error + */ +const notImplemented = () => { + throw new Error('not implemented'); +}; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +function memoized(fn) { + const map = new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} + +var ut = /*#__PURE__*/Object.freeze({ + __proto__: null, + aInRange: aInRange, + abool: abool, + abytes: abytes, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + inRange: inRange, + isBytes: isBytes, + memoized: memoized, + notImplemented: notImplemented, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject +}); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +// prettier-ignore +const _0n$4 = BigInt(0), _1n$6 = BigInt(1), _2n$3 = BigInt(2), _3n$2 = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n$1 = BigInt(8); +// prettier-ignore +BigInt(9); BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n$4 ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n$4 || power < _0n$4) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n$6) + return _0n$4; + let res = _1n$6; + while (power > _0n$4) { + if (power & _1n$6) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n$6; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$4) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n$4 || modulo <= _0n$4) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n$4, u = _1n$6; + while (a !== _0n$4) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + // prettier-ignore + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$6) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n$6) / _2n$3; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n$6, S = 0; Q % _2n$3 === _0n$4; Q /= _2n$3, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n$3; Z < P && pow(Z, legendreC, P) !== P - _1n$6; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n$6) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n$6) / _2n$3; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n$6 << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n$2) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n$6) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n$1 === _5n) { + const c1 = (P - _5n) / _8n$1; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$3); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$3), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n$4) + throw new Error('Expected power > 0'); + if (power === _0n$4) + return f.ONE; + if (power === _1n$6) + return num; + let p = f.ONE; + let d = num; + while (power > _0n$4) { + if (power & _1n$6) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$6; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * NOTE: operations don't check 'isValid' for all elements for performance reasons, + * it is caller responsibility to check this. + * This is low-level code, please make sure you know what you doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$4) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$4, + ONE: _1n$6, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$4 <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n$4, + isOdd: (num) => (num & _1n$6) === _1n$6, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n$6) + _1n$6; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const _0n$3 = BigInt(0); +const _1n$5 = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$3) { + if (n & _1n$5) + p = p.add(d); + d = d.double(); + n >>= _1n$5; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$5; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c Curve Point constructor + * @param field field over CURVE.N - important that it's not over CURVE.P + * @param points array of L curve points + * @param scalars array of L scalars (aka private keys / bigints) + */ +function pippenger(c, field, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.ZERO; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html + */ +const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 128) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 127; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n$2) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected assertion'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 128)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + abytes(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + return tlv.encode(0x30, seq); + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$2 = BigInt(0), _1n$4 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return inRange(num, _1n$4, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (isBytes(key)) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, N); // disabled by default, enabled for BLS + aInRange('private key', num, _1n$4, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // Memoized toAffine / validity check. They are heavy. Points are immutable. + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p) => { + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n$1); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + aInRange('scalar', sc, _0n$2, CURVE.n); + const I = Point.ZERO; + if (sc === _0n$2) + return I; + if (sc === _1n$4) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$2 || k2 > _0n$2) { + if (k1 & _1n$4) + k1p = k1p.add(d); + if (k2 & _1n$4) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$4; + k2 >>= _1n$4; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange('scalar', scalar, _1n$4, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n$2 || a === _1n$4 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$4) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$4) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts$2(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +function weierstrass(curveDef) { + const CURVE = validateOpts$2(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n$4, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n$4) === _1n$4; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$4; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange('r', this.r, _1n$4, CURVE_ORDER); // r in [1..N] + aInRange('s', this.s, _1n$4, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$2, ORDER_MASK); + // works with order, can have different size than numToField! + return numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n$2) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n$2) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$4); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), + randomBytes, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp$7 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A$4 = Fp$7.create(BigInt('-3')); +const CURVE_B$4 = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +const p256 = createCurve({ + a: CURVE_A$4, // Equation params: a, b + b: CURVE_B$4, + Fp: Fp$7, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp$6 = Field(P$1); +const CURVE_A$3 = Fp$6.create(BigInt('-3')); +// prettier-ignore +const CURVE_B$3 = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +const p384 = createCurve({ + a: CURVE_A$3, // Equation params: a, b + b: CURVE_B$3, + Fp: Fp$6, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp$5 = Field(P); +const CURVE = { + a: Fp$5.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp: Fp$5, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp: Fp$5, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts$1(curve) { + const opts = validateBasic(curve); + validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +function twistedEdwards(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n$1 }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + aInRange('coordinate ' + title, n, _0n$1, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n$1, y: _1n$3 }; + if (zz !== _1n$3) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n$3, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n$2 * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n$1) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n$2 * T2); + const D = modP(T1 * _2n$2 * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n$1) + return I; + if (this.equals(I) || n === _1n$3) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n$3) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('pointHex.y', y, _0n$1, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n$3); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n$3) === _1n$3; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n$1 && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n$1, _1n$3, _1n$3, _0n$1); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l + const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n = BigInt(0); +const _1n$2 = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n$2; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n$2; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n$2; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n$1, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n$1, P) * b2) % P; + const b223 = (pow2(b222, _1n$1, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp$4 = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp: Fp$4, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes$1(utf8ToBytes$1('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +/* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +(Fp$4.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +BigInt(156326); +// 1-d +BigInt('39082'); +// 1-2d +BigInt('78163'); +// √(-d) +BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp$3.eql(Fp$3.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp$3 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$3, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +BigInt(0); +secp256k1.ProjectivePoint; + +// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4 +// eslint-disable-next-line new-cap +const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377')); +const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9')); +const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'); +// prettier-ignore +const brainpoolP256r1 = createCurve({ + a: CURVE_A$2, // Equation params: a, b + b: CURVE_B$2, + Fp: Fp$2, + // Curve order (q), total count of valid points in the field + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + // Base (generator) point (x, y) + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), + lowS: false +}, sha256); + +// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6 +// eslint-disable-next-line new-cap +const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53')); +const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826')); +const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'); +// prettier-ignore +const brainpoolP384r1 = createCurve({ + a: CURVE_A$1, // Equation params: a, b + b: CURVE_B$1, + Fp: Fp$1, + // Curve order (q), total count of valid points in the field + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + // Base (generator) point (x, y) + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), + lowS: false +}, sha384); + +// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7 +// eslint-disable-next-line new-cap +const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3')); +const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca')); +const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'); +// prettier-ignore +const brainpoolP512r1 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, + // Curve order (q), total count of valid points in the field + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + // Base (generator) point (x, y) + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), + lowS: false +}, sha512); + +/** + * This file is needed to dynamic import the noble-curves. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleCurves = new Map(Object.entries({ + nistP256: p256, + nistP384: p384, + nistP521: p521, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, + secp256k1, + x448, + ed448 +})); + +export { nobleCurves }; diff --git a/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs b/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs new file mode 100644 index 000000000..6f929bb9a --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs @@ -0,0 +1,3 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;import{w as t,g as s,i as h,C as i,M as e,j as n,s as r,a,d as o,k as l,l as f}from"./sha3.min.mjs";const c=/* @__PURE__ */new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),p=/* @__PURE__ */new Uint32Array(80);class d extends s{constructor(){super(64,20,8,!1),this.A=0|c[0],this.B=0|c[1],this.C=0|c[2],this.D=0|c[3],this.E=0|c[4]}get(){const{A:t,B:s,C:h,D:i,E:e}=this;return[t,s,h,i,e]}set(t,s,h,i,e){this.A=0|t,this.B=0|s,this.C=0|h,this.D=0|i,this.E=0|e}process(t,s){for(let h=0;h<16;h++,s+=4)p[h]=t.getUint32(s,!1);for(let t=16;t<80;t++)p[t]=h(p[t-3]^p[t-8]^p[t-14]^p[t-16],1);let{A:n,B:r,C:a,D:o,E:l}=this;for(let t=0;t<80;t++){let s,f;t<20?(s=i(r,a,o),f=1518500249):t<40?(s=r^a^o,f=1859775393):t<60?(s=e(r,a,o),f=2400959708):(s=r^a^o,f=3395469782);const c=h(n,5)+s+l+f+p[t]|0;l=o,o=a,a=h(r,30),r=n,n=c}n=n+this.A|0,r=r+this.B|0,a=a+this.C|0,o=o+this.D|0,l=l+this.E|0,this.set(n,r,a,o,l)}roundClean(){p.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}const u=/* @__PURE__ */t((()=>new d)),w=/* @__PURE__ */new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),y=/* @__PURE__ */new Uint8Array(Array(16).fill(0).map(((t,s)=>s)));let A=[y],m=[/* @__PURE__ */y.map((t=>(9*t+5)%16))];for(let t=0;t<4;t++)for(let s of[A,m])s.push(s[t].map((t=>w[t])));const U=/* @__PURE__ */[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((t=>new Uint8Array(t))),C=/* @__PURE__ */A.map(((t,s)=>t.map((t=>U[s][t])))),g=/* @__PURE__ */m.map(((t,s)=>t.map((t=>U[s][t])))),b=/* @__PURE__ */new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),B=/* @__PURE__ */new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function D(t,s,h,i){return 0===t?s^h^i:1===t?s&h|~s&i:2===t?(s|~h)^i:3===t?s&i|h&~i:s^(h|~i)}const E=/* @__PURE__ */new Uint32Array(16);class j extends s{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:s,h2:h,h3:i,h4:e}=this;return[t,s,h,i,e]}set(t,s,h,i,e){this.h0=0|t,this.h1=0|s,this.h2=0|h,this.h3=0|i,this.h4=0|e}process(t,s){for(let h=0;h<16;h++,s+=4)E[h]=t.getUint32(s,!0);let i=0|this.h0,e=i,n=0|this.h1,r=n,a=0|this.h2,o=a,l=0|this.h3,f=l,c=0|this.h4,p=c;for(let t=0;t<5;t++){const s=4-t,d=b[t],u=B[t],w=A[t],y=m[t],U=C[t],j=g[t];for(let s=0;s<16;s++){const e=h(i+D(t,n,a,l)+E[w[s]]+d,U[s])+c|0;i=c,c=l,l=0|h(a,10),a=n,n=e}for(let t=0;t<16;t++){const i=h(e+D(s,r,o,f)+E[y[t]]+u,j[t])+p|0;e=p,p=f,f=0|h(o,10),o=r,r=i}}this.set(this.h1+a+f|0,this.h2+l+p|0,this.h3+c+e|0,this.h4+i+r|0,this.h0+n+o|0)}roundClean(){E.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const x=new Map(Object.entries({sha1:u,sha224:n,sha256:r,sha384:a,sha512:o,sha3_256:l,sha3_512:f,ripemd160:/* @__PURE__ */t((()=>new j))}));export{x as nobleHashes}; +//# sourceMappingURL=noble_hashes.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs.map new file mode 100644 index 000000000..5cdc9c985 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_hashes.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"noble_hashes.min.mjs","sources":["../../node_modules/@noble/hashes/esm/sha1.js","../../node_modules/@noble/hashes/esm/ripemd160.js","../../src/crypto/hash/noble_hashes.js"],"sourcesContent":["import { HashMD, Chi, Maj } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms.\n// Initial state\nconst SHA1_IV = /* @__PURE__ */ new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n SHA1_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * SHA1 (RFC 3174) hash function.\n * It was cryptographically broken: prefer newer algorithms.\n * @param message - data that would be hashed\n */\nexport const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());\n//# sourceMappingURL=sha1.js.map","import { HashMD } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n R_BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.js.map","/**\n * This file is needed to dynamic import the noble-hashes.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { sha1 } from '@noble/hashes/sha1';\nimport { sha224, sha256 } from '@noble/hashes/sha256';\nimport { sha384, sha512 } from '@noble/hashes/sha512';\nimport { sha3_256, sha3_512 } from '@noble/hashes/sha3';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\n\nexport const nobleHashes = new Map(Object.entries({\n sha1,\n sha224,\n sha256,\n sha384,\n sha512,\n sha3_256,\n sha3_512,\n ripemd160\n}));\n"],"names":["SHA1_IV","Uint32Array","SHA1_W","SHA1","HashMD","constructor","super","this","A","B","C","D","E","get","set","process","view","offset","i","getUint32","rotl","F","K","Chi","Maj","T","roundClean","fill","destroy","buffer","sha1","wrapConstructor","Rho","Uint8Array","Id","Array","map","_","idxL","idxR","j","push","k","shifts","shiftsL","idx","shiftsR","Kl","Kr","f","group","x","y","z","R_BUF","RIPEMD160","h0","h1","h2","h3","h4","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","tr","destroyed","nobleHashes","Map","Object","entries","sha224","sha256","sha384","sha512","sha3_256","sha3_512","ripemd160"],"mappings":";uMAIA,MAAMA,iBAA0B,IAAIC,YAAY,CAC5C,WAAY,WAAY,WAAY,UAAY,aAI9CC,iBAAyB,IAAID,YAAY,IACxC,MAAME,UAAaC,EACtB,WAAAC,GACIC,MAAM,GAAI,GAAI,GAAG,GACjBC,KAAKC,EAAiB,EAAbR,EAAQ,GACjBO,KAAKE,EAAiB,EAAbT,EAAQ,GACjBO,KAAKG,EAAiB,EAAbV,EAAQ,GACjBO,KAAKI,EAAiB,EAAbX,EAAQ,GACjBO,KAAKK,EAAiB,EAAbZ,EAAQ,EACzB,CACI,GAAAa,GACI,MAAML,EAAEA,EAACC,EAAEA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,GAAKU,EAAKP,EAAM,EAAIvD,KAAKqD,GAAKC,EAAKG,EAAM,EAAIzD,KAAKiD,GAAKO,EAAKG,EAAM,EAC3I,CACI,UAAAxC,GACI4B,EAAM3B,KAAK,EACnB,CACI,OAAAC,GACIrB,KAAKyE,WAAY,EACjBzE,KAAKsB,OAAOF,KAAK,GACjBpB,KAAKO,IAAI,EAAG,EAAG,EAAG,EAAG,EAC7B,EAMO,MCxFMmE,EAAc,IAAIC,IAAIC,OAAOC,QAAQ,CAChDtD,OACAuD,SACAC,SACAC,SACAC,SACAC,WACAC,WACAC,yBDgFuC5D,GAAgB,IAAM,IAAIwB","x_google_ignoreList":[0,1]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/noble_hashes.mjs b/app/node_modules/openpgp/dist/lightweight/noble_hashes.mjs new file mode 100644 index 000000000..c9060f8cb --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/noble_hashes.mjs @@ -0,0 +1,207 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +import { w as wrapConstructor, g as HashMD, i as rotl, C as Chi, M as Maj, j as sha224, s as sha256, a as sha384, d as sha512, k as sha3_256, l as sha3_512 } from './sha3.mjs'; + +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends HashMD { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + R_BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); + +/** + * This file is needed to dynamic import the noble-hashes. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleHashes = new Map(Object.entries({ + sha1, + sha224, + sha256, + sha384, + sha512, + sha3_256, + sha3_512, + ripemd160 +})); + +export { nobleHashes }; diff --git a/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs b/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs index 15b0809e1..4d39a8d9e 100644 --- a/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs +++ b/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs @@ -1,3 +1,4 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=Symbol("doneWritingPromise"),r=Symbol("doneWritingResolve"),n=Symbol("doneWritingReject"),i=Symbol("readingIndex");class a extends Array{constructor(){super(),this[t]=new Promise(((e,t)=>{this[r]=e,this[n]=t})),this[t].catch((()=>{}))}}function s(e){return e&&e.getReader&&Array.isArray(e)}function o(e){if(!s(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}a.prototype.getReader=function(){return void 0===this[i]&&(this[i]=0),{read:async()=>(await this[t],this[i]===this.length?{value:void 0,done:!0}:{value:this[this[i]++],done:!1})}},a.prototype.readToEnd=async function(e){await this[t];const r=e(this.slice(this[i]));return this.length=0,r},a.prototype.clone=function(){const e=new a;return e[t]=this[t].then((()=>{e.push(...this)})),e},o.prototype.write=async function(e){this.stream.push(e)},o.prototype.close=async function(){this.stream[r]()},o.prototype.abort=async function(e){return this.stream[n](e),e},o.prototype.releaseLock=function(){};const c="object"==typeof e.process&&"object"==typeof e.process.versions,h=c&&void 0;function u(t){return s(t)?"array":e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t)?"web":A&&A.prototype.isPrototypeOf(t)?"ponyfill":h&&h.prototype.isPrototypeOf(t)?"node":!(!t||!t.getReader)&&"web-like"}function l(e){return Uint8Array.prototype.isPrototypeOf(e)}function y(e){if(1===e.length)return e[0];let t=0;for(let r=0;r{t||(d.isBuffer(n)&&(n=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),r.enqueue(n),e.pause())})),e.on("end",(()=>{t||r.close()})),e.on("error",(e=>r.error(e)))},pull(){e.resume()},cancel(r){t=!0,e.destroy(r)}})};class e extends p{constructor(e,t){super(t),this._reader=D(e)}async _read(e){try{for(;;){const{done:e,value:t}=await this._reader.read();if(e){this.push(null);break}if(!this.push(t))break}}catch(e){this.destroy(e)}}async _destroy(e,t){this._reader.cancel(e).then(t,t)}}g=function(t,r){return new e(t,r)}}const m=new WeakSet,w=Symbol("externalBuffer");function b(e){if(this.stream=e,e[w]&&(this[w]=e[w].slice()),s(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=async()=>{})}let t=u(e);if("node"===t&&(e=f(e)),t){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let r=!1;this._read=async()=>r||m.has(e)?{value:void 0,done:!0}:(r=!0,{value:e,done:!1}),this._releaseLock=()=>{if(r)try{m.add(e)}catch(e){}}}b.prototype.read=async function(){if(this[w]&&this[w].length){return{done:!1,value:this[w].shift()}}return this._read()},b.prototype.releaseLock=function(){this[w]&&(this.stream[w]=this[w]),this._releaseLock()},b.prototype.cancel=function(e){return this._cancel(e)},b.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:n}=await this.read();if(n+="",r)return t.length?U(t):void 0;const i=n.indexOf("\n")+1;i&&(e=U(t.concat(n.substr(0,i))),t=[]),i!==n.length&&t.push(n.substr(i))}return this.unshift(...t),e},b.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(F(t,1)),r},b.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:n,value:i}=await this.read();if(n)return t.length?U(t):void 0;if(t.push(i),r+=i.length,r>=e){const r=U(t);return this.unshift(F(r,e)),F(r,0,e)}}},b.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},b.prototype.unshift=function(...e){this[w]||(this[w]=[]),1===e.length&&l(e[0])&&this[w].length&&e[0].length&&this[w][0].byteOffset>=e[0].length?this[w][0]=new Uint8Array(this[w][0].buffer,this[w][0].byteOffset-e[0].length,this[w][0].byteLength+e[0].length):this[w].unshift(...e.filter((e=>e&&e.length)))},b.prototype.readToEnd=async function(e=U){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};let k,v,{ReadableStream:A,WritableStream:_,TransformStream:E}=e;async function S(){if(E)return;const[t,r]=await Promise.all([import("./ponyfill.es6.min.mjs"),import("./web-streams-adapter.min.mjs")]);({ReadableStream:A,WritableStream:_,TransformStream:E}=t);const{createReadableStreamWrapper:n}=r;e.ReadableStream&&A!==e.ReadableStream&&(k=n(A),v=n(e.ReadableStream))}const K=c&&void 0;function x(e){let t=u(e);return"node"===t?f(e):"web"===t&&k?k(e):t?e:new A({start(t){t.enqueue(e),t.close()}})}function P(e){if(u(e))return e;const t=new a;return(async()=>{const r=C(t);await r.write(e),await r.close()})(),t}function U(e){return e.some((e=>u(e)&&!s(e)))?function(e){e=e.map(x);const t=B((async function(e){await Promise.all(n.map((t=>j(t,e))))}));let r=Promise.resolve();const n=e.map(((n,i)=>R(n,((n,a)=>(r=r.then((()=>I(n,t.writable,{preventClose:i!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>s(e)))?function(e){const t=new a;let r=Promise.resolve();return e.forEach(((n,i)=>(r=r.then((()=>I(n,t,{preventClose:i!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):K&&K.isBuffer(e[0])?K.concat(e):y(e)}function D(e){return new b(e)}function C(e){return new o(e)}async function I(e,t,{preventClose:r=!1,preventAbort:n=!1,preventCancel:i=!1}={}){if(u(e)&&!s(e)){e=x(e);try{if(e[w]){const r=C(t);for(let t=0;t{t=e,r=n})),t=null,r=null)},close:n.close.bind(n),abort:n.error.bind(n)})}}function z(e,t=(()=>{}),r=(()=>{})){if(s(e)){const n=new a;return(async()=>{const i=C(n);try{const n=await H(e),a=t(n),s=r();let o;o=void 0!==a&&void 0!==s?U([a,s]):void 0!==a?a:s,await i.write(o),await i.close()}catch(e){await i.abort(e)}})(),n}if(u(e))return T(e,{async transform(e,r){try{const n=await t(e);void 0!==n&&r.enqueue(n)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const n=t(e),i=r();return void 0!==n&&void 0!==i?U([n,i]):void 0!==n?n:i}function R(e,t){if(u(e)&&!s(e)){let r;const n=new E({start(e){r=e}}),i=I(e,n.writable),a=B((async function(e){r.error(e),await i,await new Promise(setTimeout)}));return t(n.readable,a.writable),a.readable}e=P(e);const r=new a;return t(e,r),r}function M(e,t){let r;const n=R(e,((e,i)=>{const a=D(e);a.remainder=()=>(a.releaseLock(),I(e,i),n),r=t(a)}));return r}function L(e){if(s(e))return e.clone();if(u(e)){const t=function(e){if(s(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(u(e)){const t=x(e).tee();return t[0][w]=t[1][w]=e[w],t}return[F(e),F(e)]}(e);return O(e,t[0]),t[1]}return F(e)}function N(e){return s(e)?L(e):u(e)?new A({start(t){const r=R(e,(async(e,r)=>{const n=D(e),i=C(r);try{for(;;){await i.ready;const{done:e,value:r}=await n.read();if(e){try{t.close()}catch(e){}return void await i.close()}try{t.enqueue(r)}catch(e){}await i.write(r)}}catch(e){t.error(e),await i.abort(e)}}));O(e,r)}}):F(e)}function O(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,n])=>{"constructor"!==r&&(n.value?n.value=n.value.bind(t):n.get=n.get.bind(t),Object.defineProperty(e,r,n))}))}function F(e,t=0,r=1/0){if(s(e))throw Error("Not implemented");if(u(e)){if(t>=0&&r>=0){let n=0;return T(e,{transform(e,i){n=t&&i.enqueue(F(e,Math.max(t-n,0),r-n)),n+=e.length):i.terminate()}})}if(t<0&&(r<0||r===1/0)){let n=[];return z(e,(e=>{e.length>=-t?n=[e]:n.push(e)}),(()=>F(U(n),t,r)))}if(0===t&&r<0){let n;return z(e,(e=>{const i=n?U([n,e]):e;if(i.length>=-r)return n=F(i,r),F(i,t,r);n=i}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),q((async()=>F(await H(e),t,r)))}return e[w]&&(e=U(e[w].concat([e]))),!l(e)||K&&K.isBuffer(e)?e.slice(t,r):(r===1/0&&(r=e.length),e.subarray(t,r))}async function H(e,t=U){return s(e)?e.readToEnd(t):u(e)?D(e).readToEnd(t):e}async function j(e,t){if(u(e)){if(e.cancel)return e.cancel(t);if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function q(e){const t=new a;return(async()=>{const r=C(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}class G{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");if(e instanceof Uint8Array){const t=e,r=Array(t.length);for(let e=0;eBigInt(0);){const e=r&BigInt(1);r>>=BigInt(1);const a=i*n%t.value;i=e?a:i,n=n*n%t.value}return new G(i)}modInv(e){const{gcd:t,x:r}=this._egcd(e);if(!t.isOne())throw Error("Inverse does not exist");return r.add(e).mod(e)}_egcd(e){let t=BigInt(0),r=BigInt(1),n=BigInt(1),i=BigInt(0),a=this.value;for(e=e.value;e!==BigInt(0);){const s=a/e;let o=t;t=n-s*t,n=o,o=r,r=i-s*r,i=o,o=e,e=a%e,a=o}return{x:new G(n),y:new G(i),gcd:new G(a)}}gcd(e){let t=this.value;for(e=e.value;e!==BigInt(0);){const r=e;e=t%e,t=r}return new G(t)}ileftShift(e){return this.value<<=e.value,this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value>>=e.value,this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value===e.value}lt(e){return this.valuee.value}gte(e){return this.value>=e.value}isZero(){return this.value===BigInt(0)}isOne(){return this.value===BigInt(1)}isNegative(){return this.valueNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return e}getBit(e){return(this.value>>BigInt(e)&BigInt(1))===BigInt(0)?0:1}bitLength(){const e=new G(0),t=new G(1),r=new G(-1),n=this.isNegative()?r:e;let i=1;const a=this.clone();for(;!a.irightShift(t).equal(n);)i++;return i}byteLength(){const e=new G(0),t=new G(-1),r=this.isNegative()?t:e,n=new G(8);let i=1;const a=this.clone();for(;!a.irightShift(n).equal(r);)i++;return i}toUint8Array(e="be",t){let r=this.value.toString(16);r.length%2==1&&(r="0"+r);const n=r.length/2,i=new Uint8Array(t||n),a=t?t-n:0;let s=0;for(;s"undefined"!=typeof BigInt;const W=Symbol("byValue");var $={curve:{p256:"p256","P-256":"p256",secp256r1:"p256",prime256v1:"p256","1.2.840.10045.3.1.7":"p256","2a8648ce3d030107":"p256","2A8648CE3D030107":"p256",p384:"p384","P-384":"p384",secp384r1:"p384","1.3.132.0.34":"p384","2b81040022":"p384","2B81040022":"p384",p521:"p521","P-521":"p521",secp521r1:"p521","1.3.132.0.35":"p521","2b81040023":"p521","2B81040023":"p521",secp256k1:"secp256k1","1.3.132.0.10":"secp256k1","2b8104000a":"secp256k1","2B8104000A":"secp256k1",ed25519Legacy:"ed25519",ED25519:"ed25519",ed25519:"ed25519",Ed25519:"ed25519","1.3.6.1.4.1.11591.15.1":"ed25519","2b06010401da470f01":"ed25519","2B06010401DA470F01":"ed25519",curve25519Legacy:"curve25519",X25519:"curve25519",cv25519:"curve25519",curve25519:"curve25519",Curve25519:"curve25519","1.3.6.1.4.1.3029.1.5.1":"curve25519","2b060104019755010501":"curve25519","2B060104019755010501":"curve25519",brainpoolP256r1:"brainpoolP256r1","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1","2b2403030208010107":"brainpoolP256r1","2B2403030208010107":"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1","2b240303020801010b":"brainpoolP384r1","2B240303020801010B":"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1","2b240303020801010d":"brainpoolP512r1","2B240303020801010D":"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,ed25519Legacy:22,eddsa:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuer:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[W]||(e[W]=[],Object.entries(e).forEach((([t,r])=>{e[W][r]=t}))),void 0!==e[W][t])return e[W][t];throw Error("Invalid enum value.")}};const Z=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),X={isString:function(e){return"string"==typeof e||e instanceof String},isArray:function(e){return e instanceof Array},isUint8Array:l,isStream:u,readNumber:function(e){let t=0;for(let r=0;r>8*(t-n-1)&255;return r},readDate:function(e){const t=X.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return X.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return e.subarray(2,2+t)},leftPad(e,t){const r=new Uint8Array(t),n=t-e.length;return r.set(e,n),r},uint8ArrayToMPI:function(e){const t=X.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),n=new Uint8Array([(65280&t)>>8,255&t]);return X.concatUint8Array([n,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t=[],r=e.length;let n,i=0;for(;i{if(!X.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return z(e,r,(()=>r(new Uint8Array,!0)))},concat:U,concatUint8Array:y,equalsUint8Array:function(e,t){if(!X.isUint8Array(e)||!X.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let n=0;n>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){return void 0!==e&&e.crypto&&e.crypto.subtle},getBigInteger:async function(){if(V())return G;{const{default:e}=await import("./bn.interface.min.mjs");return e}},getNodeCrypto:function(){},getNodeZlib:function(){},getNodeBuffer:function(){return{}.Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return(void 0).cpus().length},isEmailAddress:function(e){if(!X.isString(e))return!1;return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/.test(e)},canonicalizeEOL:function(e){let t=!1;return z(e,(e=>{let r;t&&(e=X.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const n=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&n.push(r);if(!n.length)return e;const i=new Uint8Array(e.length+n.length);let a=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return z(e,(e=>{let r;13===(e=t&&10!==e[0]?X.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let n=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const i=r-(10===e[r]?1:0);t&&e.copyWithin(n,t,i),n+=i-t}return e.subarray(0,n)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let n;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){n=e}}))),r(n)}))},selectUint8Array:function(e,t,r){const n=Math.max(t.length,r.length),i=new Uint8Array(n);let a=0;for(let n=0;n{t=X.concatUint8Array([t,e]);const r=[],n=Math.floor(t.length/45),i=45*n,a=Y(t.subarray(0,i));for(let e=0;et.length?Y(t)+"\n":""))}function te(e){let t="";return z(e,(e=>{t+=e;let r=0;const n=[" ","\t","\r","\n"];for(let e=0;e0&&(i-r)%4!=0;i--)n.includes(t[i])&&r--;const a=J(t.substr(0,i));return t=t.substr(i),a}),(()=>J(t)))}function re(e){return te(e.replace(/-/g,"+").replace(/_/g,"/"))}function ne(e,t){let r=ee(e).replace(/[\r\n]/g,"");return t&&(r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,"")),r}Q?(Y=e=>Q.from(e).toString("base64"),J=e=>{const t=Q.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(Y=e=>btoa(X.uint8ArrayToString(e)),J=e=>X.stringToUint8Array(atob(e)));var ie={preferredHashAlgorithm:$.hash.sha256,preferredSymmetricAlgorithm:$.symmetric.aes256,preferredCompressionAlgorithm:$.compression.uncompressed,deflateLevel:6,aeadProtect:!1,preferredAEADAlgorithm:$.aead.eax,aeadChunkSizeByte:12,v5Keys:!1,s2kIterationCountByte:224,allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,checksumRequired:!1,minRSABits:2047,passwordCollisionCheck:!1,revocationsExpire:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([$.symmetric.aes128,$.symmetric.aes192,$.symmetric.aes256]),minBytesForWebCrypto:1e3,ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 5.11.2",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],useIndutnyElliptic:!0,rejectHashAlgorithms:new Set([$.hash.md5,$.hash.ripemd]),rejectMessageHashAlgorithms:new Set([$.hash.md5,$.hash.ripemd,$.hash.sha1]),rejectPublicKeyAlgorithms:new Set([$.publicKey.elgamal,$.publicKey.dsa]),rejectCurves:new Set([$.curve.secp256k1])};function ae(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?$.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?$.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?$.armor.signed:/MESSAGE/.test(t[1])?$.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?$.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?$.armor.privateKey:/SIGNATURE/.test(t[1])?$.armor.signature:void 0}function se(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function oe(e){return ee(function(e){let t=13501623;return z(e,(e=>{const r=he?Math.floor(e.length/4):0,n=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^ce[1][t>>16&255]^ce[2][t>>8&255]^ce[3][t>>0&255];for(let n=4*r;n>8^ce[0][255&t^e[n]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e))}const ce=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(0!=(8388608&t)?8801531:0);ce[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)ce[1][e]=ce[0][e]>>8^ce[0][255&ce[0][e]];for(let e=0;e<=255;e++)ce[2][e]=ce[1][e]>>8^ce[0][255&ce[1][e]];for(let e=0;e<=255;e++)ce[3][e]=ce[2][e]>>8^ce[0][255&ce[2][e]];const he=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function ue(e){for(let t=0;t=0&&n!==e.length-1&&(t=e.slice(0,n),r=e.slice(n+1).substr(0,4)),{body:t,checksum:r}}function ye(e,t=ie){return new Promise((async(r,n)=>{try{const i=/^-----[^-]+-----$/m,a=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const o=[];let c,h,u,l=o,y=[],d=te(R(e,(async(e,t)=>{const p=D(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=X.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(c)h||2!==s||(i.test(e)?(y=y.join("\r\n"),h=!0,ue(l),l=[],c=!1):y.push(e.replace(/^- /,"")));else if(i.test(e)&&n(Error("Mandatory blank line missing between armor headers and armor data")),a.test(e)){if(ue(l),c=!0,h||2!==s){r({text:y,data:d,headers:o,type:s});break}}else l.push(e);else i.test(e)&&(s=ae(e))}}catch(e){return void n(e)}const f=C(t);try{for(;;){await f.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=X.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(i);if(1===t.length)throw Error("Misformed armored text");const n=le(t[0].slice(0,-1));u=n.checksum,await f.write(n.body);break}await f.write(r)}await f.ready,await f.close()}catch(e){await f.abort(e)}})));d=R(d,(async(e,r)=>{const n=H(oe(N(e)));n.catch((()=>{})),await I(e,r,{preventClose:!0});const i=C(r);try{const e=(await n).replace("\n","");if(u!==e&&(u||t.checksumRequired))throw Error("Ascii armor integrity check failed");await i.ready,await i.close()}catch(e){await i.abort(e)}}))}catch(e){n(e)}})).then((async e=>(s(e.data)&&(e.data=await H(e.data)),e)))}function de(e,t,r,n,i,a=ie){let s,o;e===$.armor.signed&&(s=t.text,o=t.hash,t=t.data);const c=N(t),h=[];switch(e){case $.armor.multipartSection:h.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+n+"-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP MESSAGE, PART "+r+"/"+n+"-----\n");break;case $.armor.multipartLast:h.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case $.armor.signed:h.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),h.push("Hash: "+o+"\n\n"),h.push(s.replace(/^-/gm,"- -")),h.push("\n-----BEGIN PGP SIGNATURE-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP SIGNATURE-----\n");break;case $.armor.message:h.push("-----BEGIN PGP MESSAGE-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP MESSAGE-----\n");break;case $.armor.publicKey:h.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case $.armor.privateKey:h.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case $.armor.signature:h.push("-----BEGIN PGP SIGNATURE-----\n"),h.push(se(i,a)),h.push(ee(t)),h.push("=",oe(c)),h.push("-----END PGP SIGNATURE-----\n")}return X.concat(h)}class pe{constructor(){this.bytes=""}read(e){return this.bytes=X.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return X.stringToUint8Array(this.bytes)}toHex(){return X.uint8ArrayToHex(X.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new pe;return t.read(X.hexToUint8Array(e)),t}static wildcard(){const e=new pe;return e.read(new Uint8Array(8)),e}}var fe=function(){var e,t,r=!1;function n(r,n){var i=e[(t[r]+t[n])%255];return 0!==r&&0!==n||(i=0),i}var i,a,s,o,c=!1;function h(){function h(r){var n,i,a;for(i=a=function(r){var n=e[255-t[r]];return 0===r&&(n=0),n}(r),n=0;n<4;n++)a^=i=255&(i<<1|i>>>7);return a^=99}r||function(){e=[],t=[];var n,i,a=1;for(n=0;n<255;n++)e[n]=a,i=128&a,a<<=1,a&=255,128===i&&(a^=27),a^=e[n],t[e[n]]=n;e[255]=e[0],t[0]=0,r=!0}(),i=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var u=0;u<256;u++){var l=h(u);i[u]=l,a[l]=u,s[0][u]=n(2,l)<<24|l<<16|l<<8|n(3,l),o[0][l]=n(14,u)<<24|n(9,u)<<16|n(13,u)<<8|n(11,u);for(var y=1;y<4;y++)s[y][u]=s[y-1][u]>>>8|s[y-1][u]<<24,o[y][l]=o[y-1][l]>>>8|o[y-1][l]<<24}c=!0}var u=function(e,t){c||h();var r=new Uint32Array(t);r.set(i,512),r.set(a,768);for(var n=0;n<4;n++)r.set(s[n],4096+1024*n>>2),r.set(o[n],8192+1024*n>>2);var u=function(e,t,r){"use asm";var n=0,i=0,a=0,s=0,o=0,c=0,h=0,u=0,l=0,y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0,k=0,v=0,A=0,_=0;var E=new e.Uint32Array(r),S=new e.Uint8Array(r);function K(e,t,r,o,c,h,u,l){e=e|0;t=t|0;r=r|0;o=o|0;c=c|0;h=h|0;u=u|0;l=l|0;var y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0;y=r|0x400,d=r|0x800,p=r|0xc00;c=c^E[(e|0)>>2],h=h^E[(e|4)>>2],u=u^E[(e|8)>>2],l=l^E[(e|12)>>2];for(b=16;(b|0)<=o<<4;b=b+16|0){f=E[(r|c>>22&1020)>>2]^E[(y|h>>14&1020)>>2]^E[(d|u>>6&1020)>>2]^E[(p|l<<2&1020)>>2]^E[(e|b|0)>>2],g=E[(r|h>>22&1020)>>2]^E[(y|u>>14&1020)>>2]^E[(d|l>>6&1020)>>2]^E[(p|c<<2&1020)>>2]^E[(e|b|4)>>2],m=E[(r|u>>22&1020)>>2]^E[(y|l>>14&1020)>>2]^E[(d|c>>6&1020)>>2]^E[(p|h<<2&1020)>>2]^E[(e|b|8)>>2],w=E[(r|l>>22&1020)>>2]^E[(y|c>>14&1020)>>2]^E[(d|h>>6&1020)>>2]^E[(p|u<<2&1020)>>2]^E[(e|b|12)>>2];c=f,h=g,u=m,l=w}n=E[(t|c>>22&1020)>>2]<<24^E[(t|h>>14&1020)>>2]<<16^E[(t|u>>6&1020)>>2]<<8^E[(t|l<<2&1020)>>2]^E[(e|b|0)>>2],i=E[(t|h>>22&1020)>>2]<<24^E[(t|u>>14&1020)>>2]<<16^E[(t|l>>6&1020)>>2]<<8^E[(t|c<<2&1020)>>2]^E[(e|b|4)>>2],a=E[(t|u>>22&1020)>>2]<<24^E[(t|l>>14&1020)>>2]<<16^E[(t|c>>6&1020)>>2]<<8^E[(t|h<<2&1020)>>2]^E[(e|b|8)>>2],s=E[(t|l>>22&1020)>>2]<<24^E[(t|c>>14&1020)>>2]<<16^E[(t|h>>6&1020)>>2]<<8^E[(t|u<<2&1020)>>2]^E[(e|b|12)>>2]}function x(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;K(0x0000,0x0800,0x1000,_,e,t,r,n)}function P(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var a=0;K(0x0400,0x0c00,0x2000,_,e,n,r,t);a=i,i=s,s=a}function U(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;K(0x0000,0x0800,0x1000,_,o^e,c^t,h^r,u^l);o=n,c=i,h=a,u=s}function D(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;var y=0;K(0x0400,0x0c00,0x2000,_,e,l,r,t);y=i,i=s,s=y;n=n^o,i=i^c,a=a^h,s=s^u;o=e,c=t,h=r,u=l}function C(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;K(0x0000,0x0800,0x1000,_,o,c,h,u);o=n=n^e,c=i=i^t,h=a=a^r,u=s=s^l}function I(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;K(0x0000,0x0800,0x1000,_,o,c,h,u);n=n^e,i=i^t,a=a^r,s=s^l;o=e,c=t,h=r,u=l}function T(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;K(0x0000,0x0800,0x1000,_,o,c,h,u);o=n,c=i,h=a,u=s;n=n^e,i=i^t,a=a^r,s=s^l}function B(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;K(0x0000,0x0800,0x1000,_,l,y,d,p);p=~w&p|w&p+1;d=~m&d|m&d+((p|0)==0);y=~g&y|g&y+((d|0)==0);l=~f&l|f&l+((y|0)==0);n=n^e;i=i^t;a=a^r;s=s^o}function z(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var i=0,a=0,s=0,l=0,y=0,d=0,p=0,f=0,g=0,m=0;e=e^o,t=t^c,r=r^h,n=n^u;i=b|0,a=k|0,s=v|0,l=A|0;for(;(g|0)<128;g=g+1|0){if(i>>>31){y=y^e,d=d^t,p=p^r,f=f^n}i=i<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|l>>>31,l=l<<1;m=n&1;n=n>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(m)e=e^0xe1000000}o=y,c=d,h=p,u=f}function R(e){e=e|0;_=e}function M(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;n=e,i=t,a=r,s=o}function L(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;o=e,c=t,h=r,u=n}function N(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;l=e,y=t,d=r,p=n}function O(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;f=e,g=t,m=r,w=n}function F(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;p=~w&p|w&n,d=~m&d|m&r,y=~g&y|g&t,l=~f&l|f&e}function H(e){e=e|0;if(e&15)return-1;S[e|0]=n>>>24,S[e|1]=n>>>16&255,S[e|2]=n>>>8&255,S[e|3]=n&255,S[e|4]=i>>>24,S[e|5]=i>>>16&255,S[e|6]=i>>>8&255,S[e|7]=i&255,S[e|8]=a>>>24,S[e|9]=a>>>16&255,S[e|10]=a>>>8&255,S[e|11]=a&255,S[e|12]=s>>>24,S[e|13]=s>>>16&255,S[e|14]=s>>>8&255,S[e|15]=s&255;return 16}function j(e){e=e|0;if(e&15)return-1;S[e|0]=o>>>24,S[e|1]=o>>>16&255,S[e|2]=o>>>8&255,S[e|3]=o&255,S[e|4]=c>>>24,S[e|5]=c>>>16&255,S[e|6]=c>>>8&255,S[e|7]=c&255,S[e|8]=h>>>24,S[e|9]=h>>>16&255,S[e|10]=h>>>8&255,S[e|11]=h&255,S[e|12]=u>>>24,S[e|13]=u>>>16&255,S[e|14]=u>>>8&255,S[e|15]=u&255;return 16}function q(){x(0,0,0,0);b=n,k=i,v=a,A=s}function G(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){W[e&7](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);S[t|0]=n>>>24,S[t|1]=n>>>16&255,S[t|2]=n>>>8&255,S[t|3]=n&255,S[t|4]=i>>>24,S[t|5]=i>>>16&255,S[t|6]=i>>>8&255,S[t|7]=i&255,S[t|8]=a>>>24,S[t|9]=a>>>16&255,S[t|10]=a>>>8&255,S[t|11]=a&255,S[t|12]=s>>>24,S[t|13]=s>>>16&255,S[t|14]=s>>>8&255,S[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function V(e,t,r){e=e|0;t=t|0;r=r|0;var n=0;if(t&15)return-1;while((r|0)>=16){$[e&1](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);n=n+16|0,t=t+16|0,r=r-16|0}return n|0}var W=[x,P,U,D,C,I,T,B];var $=[U,z];return{set_rounds:R,set_state:M,set_iv:L,set_nonce:N,set_mask:O,set_counter:F,get_state:H,get_iv:j,gcm_init:q,cipher:G,mac:V}}({Uint8Array,Uint32Array},e,t);return u.set_key=function(e,t,n,a,s,c,h,l,y){var d=r.subarray(0,60),p=r.subarray(256,316);d.set([t,n,a,s,c,h,l,y]);for(var f=e,g=1;f<4*e+28;f++){var m=d[f-1];(f%e==0||8===e&&f%e==4)&&(m=i[m>>>24]<<24^i[m>>>16&255]<<16^i[m>>>8&255]<<8^i[255&m]),f%e==0&&(m=m<<8^m>>>24^g<<24,g=g<<1^(128&g?27:0)),d[f]=d[f-e]^m}for(var w=0;w=f-4?m:o[0][i[m>>>24]]^o[1][i[m>>>16&255]]^o[2][i[m>>>8&255]]^o[3][i[255&m]]}u.set_rounds(e+5)},u};return u.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},u.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},u.MAC={CBC:0,GCM:1},u.HEAP_DATA=16384,u}();function ge(e){return e instanceof Uint8Array}function me(e,t){const r=e?e.byteLength:t||65536;if(4095&r||r<=0)throw Error("heap size must be a positive integer and a multiple of 4096");return e=e||new Uint8Array(new ArrayBuffer(r))}function we(e,t,r,n,i){const a=e.length-t,s=ae+t.length),0),r=new Uint8Array(t);let n=0;for(let t=0;t>2,i.getUint32(0),i.getUint32(4),i.getUint32(8),i.getUint32(12),n>16?i.getUint32(16):0,n>16?i.getUint32(20):0,n>24?i.getUint32(24):0,n>24?i.getUint32(28):0),void 0!==t){if(16!==t.length)throw new ve("illegal iv size");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);r.set_iv(e.getUint32(0),e.getUint32(4),e.getUint32(8),e.getUint32(12))}else r.set_iv(0,0,0,0)}AES_Encrypt_process(e){if(!ge(e))throw new TypeError("data isn't of expected type");let{heap:t,asm:r}=this.acquire_asm(),n=fe.ENC[this.mode],i=fe.HEAP_DATA,a=this.pos,s=this.len,o=0,c=e.length||0,h=0,u=0,l=new Uint8Array(s+c&-16);for(;c>0;)u=we(t,a+s,e,o,c),s+=u,o+=u,c-=u,u=r.cipher(n,i+a,s),u&&l.set(t.subarray(a,a+u),h),h+=u,u0;)y=we(t,a+s,e,o,c),s+=y,o+=y,c-=y,y=r.cipher(n,i+a,s-(c?0:l)),y&&d.set(t.subarray(a,a+y),h),h+=y,y0){if(a%16){if(this.hasOwnProperty("padding"))throw new ve("data length must be a multiple of the block size");a+=16-a%16}if(t.cipher(r,n+i,a),this.hasOwnProperty("padding")&&this.padding){let t=e[i+s-1];if(t<1||t>16||t>s)throw new Ae("bad padding");let r=0;for(let n=t;n>1;n--)r|=t^e[i+s-n];if(r)throw new Ae("bad padding");s-=t}}const o=new Uint8Array(s);return s>0&&o.set(e.subarray(i,i+s)),this.pos=0,this.len=0,this.release_asm(),o}}class Ke{static encrypt(e,t,r=!1){return new Ke(t,r).encrypt(e)}static decrypt(e,t,r=!1){return new Ke(t,r).decrypt(e)}constructor(e,t=!1,r){this.aes=r||new Se(e,void 0,t,"ECB")}encrypt(e){return be(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return be(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}function xe(e){const t=function(e){const t=new Ke(e);this.encrypt=function(e){return t.encrypt(e)},this.decrypt=function(e){return t.decrypt(e)}};return t.blockSize=t.prototype.blockSize=16,t.keySize=t.prototype.keySize=e/8,t}function Pe(e,t,r,n,i,a){const s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],h=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],y=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,f,g,m,w,b,k,v,A,_,E,S,K,x,P=0,U=t.length;const D=32===e.length?3:9;v=3===D?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e,t){const r=8-e.length%8;let n;if(2===t&&r<8)n=32;else if(1===t)n=r;else{if(t||!(r<8)){if(8===r)return e;throw Error("des: invalid padding")}n=0}const i=new Uint8Array(e.length+r);for(let t=0;t>>4^k),k^=g,b^=g<<4,g=65535&(b>>>16^k),k^=g,b^=g<<16,g=858993459&(k>>>2^b),b^=g,k^=g<<2,g=16711935&(k>>>8^b),b^=g,k^=g<<8,g=1431655765&(b>>>1^k),k^=g,b^=g<<1,b=b<<1|b>>>31,k=k<<1|k>>>31,f=0;f>>4|k<<28)^e[p+1],g=b,b=k,k=g^(o[m>>>24&63]|h[m>>>16&63]|l[m>>>8&63]|d[63&m]|s[w>>>24&63]|c[w>>>16&63]|u[w>>>8&63]|y[63&w]);g=b,b=k,k=g}b=b>>>1|b<<31,k=k>>>1|k<<31,g=1431655765&(b>>>1^k),k^=g,b^=g<<1,g=16711935&(k>>>8^b),b^=g,k^=g<<8,g=858993459&(k>>>2^b),b^=g,k^=g<<2,g=65535&(b>>>16^k),k^=g,b^=g<<16,g=252645135&(b>>>4^k),k^=g,b^=g<<4,1===n&&(r?(A=b,E=k):(b^=_,k^=S)),C[I++]=b>>>24,C[I++]=b>>>16&255,C[I++]=b>>>8&255,C[I++]=255&b,C[I++]=k>>>24,C[I++]=k>>>16&255,C[I++]=k>>>8&255,C[I++]=255&k}return r||(C=function(e,t){let r,n=null;if(2===t)r=32;else if(1===t)n=e[e.length-1];else{if(t)throw Error("des: invalid padding");r=0}if(!n){for(n=1;e[e.length-n]===r;)n++;n--}return e.subarray(0,e.length-n)}(C,a)),C}function Ue(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],h=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],f=e.length>8?3:1,g=Array(32*f),m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let w,b,k,v=0,A=0;for(let _=0;_>>4^_),_^=k,f^=k<<4,k=65535&(_>>>-16^f),f^=k,_^=k<<-16,k=858993459&(f>>>2^_),_^=k,f^=k<<2,k=65535&(_>>>-16^f),f^=k,_^=k<<-16,k=1431655765&(f>>>1^_),_^=k,f^=k<<1,k=16711935&(_>>>8^f),f^=k,_^=k<<8,k=1431655765&(f>>>1^_),_^=k,f^=k<<1,k=f<<8|_>>>20&240,f=_<<24|_<<8&16711680|_>>>8&65280|_>>>24&240,_=k;for(let e=0;e<16;e++)m[e]?(f=f<<2|f>>>26,_=_<<2|_>>>26):(f=f<<1|f>>>27,_=_<<1|_>>>27),f&=-15,_&=-15,w=t[f>>>28]|r[f>>>24&15]|n[f>>>20&15]|i[f>>>16&15]|a[f>>>12&15]|s[f>>>8&15]|o[f>>>4&15],b=c[_>>>28]|h[_>>>24&15]|u[_>>>20&15]|l[_>>>16&15]|y[_>>>12&15]|d[_>>>8&15]|p[_>>>4&15],k=65535&(b>>>16^w),g[A++]=w^k,g[A++]=b^k<<16}return g}function De(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Pe(Ue(this.key[2]),Pe(Ue(this.key[1]),Pe(Ue(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}function Ce(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>>16&255,t[a+6]=o>>>8&255,t[a+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>16&255,t[a+6]=o>>8&255,t[a+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const n=t+e,i=n<>>32-r;return(a[0][i>>>24]^a[1][i>>>16&255])-a[2][i>>>8&255]+a[3][255&i]}function n(e,t,r){const n=t^e,i=n<>>32-r;return a[0][i>>>24]-a[1][i>>>16&255]+a[2][i>>>8&255]^a[3][255&i]}function i(e,t,r){const n=t-e,i=n<>>32-r;return(a[0][i>>>24]+a[1][i>>>16&255]^a[2][i>>>8&255])-a[3][255&i]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const n=[,,,,,,,,],i=Array(32);let s;for(let e=0;e<4;e++)s=4*e,n[e]=r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3];const o=[6,7,4,5];let c,h=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(s=0;s<4;s++){const t=e[r][s];c=n[t[1]],c^=a[4][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=a[5][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=a[6][n[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=a[7][n[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=a[o[s]][n[t[6]>>>2]>>>24-8*(3&t[6])&255],n[t[0]]=c}for(s=0;s<4;s++){const e=t[r][s];c=a[4][n[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=a[5][n[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=a[6][n[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=a[7][n[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=a[4+s][n[e[4]>>>2]>>>24-8*(3&e[4])&255],i[h]=c,h++}}for(let e=0;e<16;e++)this.masking[e]=i[e],this.rotate[e]=31&i[16+e]};const a=[,,,,,,,,];a[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],a[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],a[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],a[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],a[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],a[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],a[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],a[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Ie(e){this.cast5=new Ce,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}De.keySize=De.prototype.keySize=24,De.blockSize=De.prototype.blockSize=8,Ie.blockSize=Ie.prototype.blockSize=8,Ie.keySize=Ie.prototype.keySize=16;const Te=4294967295;function Be(e,t){return(e<>>32-t)&Te}function ze(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Re(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function Me(e,t){return e>>>8*t&255}function Le(e){this.tf=function(){let e=null,t=null,r=-1,n=[],i=[[],[],[],[]];function a(e){return i[0][Me(e,0)]^i[1][Me(e,1)]^i[2][Me(e,2)]^i[3][Me(e,3)]}function s(e){return i[0][Me(e,3)]^i[1][Me(e,0)]^i[2][Me(e,1)]^i[3][Me(e,2)]}function o(e,t){let r=a(t[0]),i=s(t[1]);t[2]=Be(t[2]^r+i+n[4*e+8]&Te,31),t[3]=Be(t[3],1)^r+2*i+n[4*e+9]&Te,r=a(t[2]),i=s(t[3]),t[0]=Be(t[0]^r+i+n[4*e+10]&Te,31),t[1]=Be(t[1],1)^r+2*i+n[4*e+11]&Te}function c(e,t){let r=a(t[0]),i=s(t[1]);t[2]=Be(t[2],1)^r+i+n[4*e+10]&Te,t[3]=Be(t[3]^r+2*i+n[4*e+11]&Te,31),r=a(t[2]),i=s(t[3]),t[0]=Be(t[0],1)^r+i+n[4*e+8]&Te,t[1]=Be(t[1]^r+2*i+n[4*e+9]&Te,31)}return{name:"twofish",blocksize:16,open:function(t){let r,a,s,o,c;e=t;const h=[],u=[],l=[];let y;const d=[];let p,f,g;const m=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],b=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],k=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],v=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],A=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],_=[[],[]],E=[[],[],[],[]];function S(e){return e^e>>2^[0,90,180,238][3&e]}function K(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function x(e,t){let r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&Te|e>>>24,e=e<<8&Te,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function P(e,t){const r=t>>4,n=15&t,i=m[e][r^n],a=w[e][v[n]^A[r]];return k[e][v[a]^A[i]]<<4|b[e][i^a]}function U(e,t){let r=Me(e,0),n=Me(e,1),i=Me(e,2),a=Me(e,3);switch(y){case 4:r=_[1][r]^Me(t[3],0),n=_[0][n]^Me(t[3],1),i=_[0][i]^Me(t[3],2),a=_[1][a]^Me(t[3],3);case 3:r=_[1][r]^Me(t[2],0),n=_[1][n]^Me(t[2],1),i=_[0][i]^Me(t[2],2),a=_[0][a]^Me(t[2],3);case 2:r=_[0][_[0][r]^Me(t[1],0)]^Me(t[0],0),n=_[0][_[1][n]^Me(t[1],1)]^Me(t[0],1),i=_[1][_[0][i]^Me(t[1],2)]^Me(t[0],2),a=_[1][_[1][a]^Me(t[1],3)]^Me(t[0],3)}return E[0][r]^E[1][n]^E[2][i]^E[3][a]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=ze(e,r);for(r=0;r<256;r++)_[0][r]=P(0,r),_[1][r]=P(1,r);for(r=0;r<256;r++)p=_[1][r],f=S(p),g=K(p),E[0][r]=p+(f<<8)+(g<<16)+(g<<24),E[2][r]=f+(g<<8)+(p<<16)+(g<<24),p=_[0][r],f=S(p),g=K(p),E[1][r]=g+(g<<8)+(f<<16)+(p<<24),E[3][r]=f+(p<<8)+(g<<16)+(f<<24);for(y=l.length/2,r=0;r=0;e--)c(e,a);Re(t,r,a[2]^n[0]),Re(t,r+4,a[3]^n[1]),Re(t,r+8,a[0]^n[2]),Re(t,r+12,a[1]^n[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Ne(){}function Oe(e){this.bf=new Ne,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}Le.keySize=Le.prototype.keySize=32,Le.blockSize=Le.prototype.blockSize=16,Ne.prototype.BLOCKSIZE=8,Ne.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Ne.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Ne.prototype.NN=16,Ne.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Ne.prototype._F=function(e){let t;const r=255&e,n=255&(e>>>=8),i=255&(e>>>=8),a=255&(e>>>=8);return t=this.sboxes[0][a]+this.sboxes[1][i],t^=this.sboxes[2][n],t+=this.sboxes[3][r],t},Ne.prototype._encryptBlock=function(e){let t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},Ne.prototype._decryptBlock=function(e){let t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],n=this._F(r)^n;const e=r;r=n,n=e}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},Ne.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^n}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const n=[0,0];for(t=0;t>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=t+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=r+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=c+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=h+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=u+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=l+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=y+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=d+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=p+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=f+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=g+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=m+(v<<5|v>>>27)+S+(A&_|~A&E)+0x5a827999|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;x=w+(v<<5|v>>>27)+S+(A&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<1|K>>>31;x=Me+(v<<5|v>>>27)+S+(A^_^E)-0x359d3e2a|0;S=E;E=_;_=A<<30|A>>>2;A=v;v=x;n=n+v|0;i=i+A|0;a=a+_|0;s=s+E|0;o=o+S|0}function A(e){e=e|0;v(k[e|0]<<24|k[e|1]<<16|k[e|2]<<8|k[e|3],k[e|4]<<24|k[e|5]<<16|k[e|6]<<8|k[e|7],k[e|8]<<24|k[e|9]<<16|k[e|10]<<8|k[e|11],k[e|12]<<24|k[e|13]<<16|k[e|14]<<8|k[e|15],k[e|16]<<24|k[e|17]<<16|k[e|18]<<8|k[e|19],k[e|20]<<24|k[e|21]<<16|k[e|22]<<8|k[e|23],k[e|24]<<24|k[e|25]<<16|k[e|26]<<8|k[e|27],k[e|28]<<24|k[e|29]<<16|k[e|30]<<8|k[e|31],k[e|32]<<24|k[e|33]<<16|k[e|34]<<8|k[e|35],k[e|36]<<24|k[e|37]<<16|k[e|38]<<8|k[e|39],k[e|40]<<24|k[e|41]<<16|k[e|42]<<8|k[e|43],k[e|44]<<24|k[e|45]<<16|k[e|46]<<8|k[e|47],k[e|48]<<24|k[e|49]<<16|k[e|50]<<8|k[e|51],k[e|52]<<24|k[e|53]<<16|k[e|54]<<8|k[e|55],k[e|56]<<24|k[e|57]<<16|k[e|58]<<8|k[e|59],k[e|60]<<24|k[e|61]<<16|k[e|62]<<8|k[e|63])}function _(e){e=e|0;k[e|0]=n>>>24;k[e|1]=n>>>16&255;k[e|2]=n>>>8&255;k[e|3]=n&255;k[e|4]=i>>>24;k[e|5]=i>>>16&255;k[e|6]=i>>>8&255;k[e|7]=i&255;k[e|8]=a>>>24;k[e|9]=a>>>16&255;k[e|10]=a>>>8&255;k[e|11]=a&255;k[e|12]=s>>>24;k[e|13]=s>>>16&255;k[e|14]=s>>>8&255;k[e|15]=s&255;k[e|16]=o>>>24;k[e|17]=o>>>16&255;k[e|18]=o>>>8&255;k[e|19]=o&255}function E(){n=0x67452301;i=0xefcdab89;a=0x98badcfe;s=0x10325476;o=0xc3d2e1f0;c=h=0}function S(e,t,r,u,l,y,d){e=e|0;t=t|0;r=r|0;u=u|0;l=l|0;y=y|0;d=d|0;n=e;i=t;a=r;s=u;o=l;c=y;h=d}function K(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){A(e);e=e+64|0;t=t-64|0;r=r+64|0}c=c+r|0;if(c>>>0>>0)h=h+1|0;return r|0}function x(e,t,r){e=e|0;t=t|0;r=r|0;var n=0,i=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){n=K(e,t)|0;if((n|0)==-1)return-1;e=e+n|0;t=t-n|0}n=n+t|0;c=c+t|0;if(c>>>0>>0)h=h+1|0;k[e|t]=0x80;if((t|0)>=56){for(i=t+1|0;(i|0)<64;i=i+1|0)k[e|i]=0x00;A(e);t=0;k[e|0]=0}for(i=t+1|0;(i|0)<59;i=i+1|0)k[e|i]=0;k[e|56]=h>>>21&255;k[e|57]=h>>>13&255;k[e|58]=h>>>5&255;k[e|59]=h<<3&255|c>>>29;k[e|60]=c>>>21&255;k[e|61]=c>>>13&255;k[e|62]=c>>>5&255;k[e|63]=c<<3&255;A(e);if(~r)_(r);return n|0}function P(){n=u;i=l;a=y;s=d;o=p;c=64;h=0}function U(){n=f;i=g;a=m;s=w;o=b;c=64;h=0}function D(e,t,r,k,A,_,S,K,x,P,U,D,C,I,T,B){e=e|0;t=t|0;r=r|0;k=k|0;A=A|0;_=_|0;S=S|0;K=K|0;x=x|0;P=P|0;U=U|0;D=D|0;C=C|0;I=I|0;T=T|0;B=B|0;E();v(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,k^0x5c5c5c5c,A^0x5c5c5c5c,_^0x5c5c5c5c,S^0x5c5c5c5c,K^0x5c5c5c5c,x^0x5c5c5c5c,P^0x5c5c5c5c,U^0x5c5c5c5c,D^0x5c5c5c5c,C^0x5c5c5c5c,I^0x5c5c5c5c,T^0x5c5c5c5c,B^0x5c5c5c5c);f=n;g=i;m=a;w=s;b=o;E();v(e^0x36363636,t^0x36363636,r^0x36363636,k^0x36363636,A^0x36363636,_^0x36363636,S^0x36363636,K^0x36363636,x^0x36363636,P^0x36363636,U^0x36363636,D^0x36363636,C^0x36363636,I^0x36363636,T^0x36363636,B^0x36363636);u=n;l=i;y=a;d=s;p=o;c=64;h=0}function C(e,t,r){e=e|0;t=t|0;r=r|0;var c=0,h=0,u=0,l=0,y=0,d=0;if(e&63)return-1;if(~r)if(r&31)return-1;d=x(e,t,-1)|0;c=n,h=i,u=a,l=s,y=o;U();v(c,h,u,l,y,0x80000000,0,0,0,0,0,0,0,0,0,672);if(~r)_(r);return d|0}function I(e,t,r,c,h){e=e|0;t=t|0;r=r|0;c=c|0;h=h|0;var u=0,l=0,y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0;if(e&63)return-1;if(~h)if(h&31)return-1;k[e+t|0]=r>>>24;k[e+t+1|0]=r>>>16&255;k[e+t+2|0]=r>>>8&255;k[e+t+3|0]=r&255;C(e,t+4|0,-1)|0;u=f=n,l=g=i,y=m=a,d=w=s,p=b=o;c=c-1|0;while((c|0)>0){P();v(f,g,m,w,b,0x80000000,0,0,0,0,0,0,0,0,0,672);f=n,g=i,m=a,w=s,b=o;U();v(f,g,m,w,b,0x80000000,0,0,0,0,0,0,0,0,0,672);f=n,g=i,m=a,w=s,b=o;u=u^n;l=l^i;y=y^a;d=d^s;p=p^o;c=c-1|0}n=u;i=l;a=y;s=d;o=p;if(~h)_(h);return 0}return{reset:E,init:S,process:K,finish:x,hmac_reset:P,hmac_init:D,hmac_finish:C,pbkdf2_generate_block:I}};class Ve{constructor(){this.pos=0,this.len=0}reset(){const{asm:e}=this.acquire_asm();return this.result=null,this.pos=0,this.len=0,e.reset(),this}process(e){if(null!==this.result)throw new ke("state must be reset before processing new data");const{asm:t,heap:r}=this.acquire_asm();let n=this.pos,i=this.len,a=0,s=e.length,o=0;for(;s>0;)o=we(r,n+i,e,a,s),i+=o,a+=o,s-=o,o=t.process(n,i),n+=o,i-=o,i||(n=0);return this.pos=n,this.len=i,this}finish(){if(null!==this.result)throw new ke("state must be reset before processing new data");const{asm:e,heap:t}=this.acquire_asm();return e.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(t.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this.release_asm(),this}}const We=[],$e=[];class Ze extends Ve{constructor(){super(),this.NAME="sha1",this.BLOCK_SIZE=64,this.HASH_SIZE=20,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=We.pop()||me(),this.asm=$e.pop()||Ge({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(We.push(this.heap),$e.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new Ze).process(e).finish().result}}Ze.NAME="sha1",Ze.heap_pool=[],Ze.asm_pool=[],Ze.asm_function=Ge;const Xe=[],Qe=[];class Ye extends Ve{constructor(){super(),this.NAME="sha256",this.BLOCK_SIZE=64,this.HASH_SIZE=32,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=Xe.pop()||me(),this.asm=Qe.pop()||function(e,t,r){"use asm";var n=0,i=0,a=0,s=0,o=0,c=0,h=0,u=0,l=0,y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0,k=0,v=0,A=0,_=0,E=0,S=0,K=0,x=0,P=0,U=new e.Uint8Array(r);function D(e,t,r,l,y,d,p,f,g,m,w,b,k,v,A,_){e=e|0;t=t|0;r=r|0;l=l|0;y=y|0;d=d|0;p=p|0;f=f|0;g=g|0;m=m|0;w=w|0;b=b|0;k=k|0;v=v|0;A=A|0;_=_|0;var E=0,S=0,K=0,x=0,P=0,U=0,D=0,C=0;E=n;S=i;K=a;x=s;P=o;U=c;D=h;C=u;C=e+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0x428a2f98|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=t+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0x71374491|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;U=r+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0xb5c0fbcf|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=l+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0xe9b5dba5|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;x=y+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x3956c25b|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;K=d+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0x59f111f1|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;S=p+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x923f82a4|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;E=f+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0xab1c5ed5|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=g+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0xd807aa98|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=m+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0x12835b01|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;U=w+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0x243185be|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=b+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0x550c7dc3|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;x=k+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x72be5d74|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;K=v+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0x80deb1fe|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;S=A+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x9bdc06a7|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;E=_+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0xc19bf174|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;C=e+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0xe49b69c1|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+w|0;D=t+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0xefbe4786|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;r=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+b|0;U=r+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0x0fc19dc6|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;l=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+k|0;P=l+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0x240ca1cc|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;y=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+y+v|0;x=y+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x2de92c6f|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;d=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;K=d+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0x4a7484aa|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+p+_|0;S=p+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x5cb0a9dc|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+f+e|0;E=f+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0x76f988da|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;C=g+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0x983e5152|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+m+r|0;D=m+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0xa831c66d|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+l|0;U=w+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0xb00327c8|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+b+y|0;P=b+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0xbf597fc7|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;k=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+d|0;x=k+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0xc6e00bf3|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;v=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+v+p|0;K=v+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0xd5a79147|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;A=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+A+f|0;S=A+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x06ca6351|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;_=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+_+g|0;E=_+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0x14292967|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;C=e+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0x27b70a85|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+w|0;D=t+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0x2e1b2138|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;r=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+b|0;U=r+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0x4d2c6dfc|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;l=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+k|0;P=l+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0x53380d13|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;y=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+y+v|0;x=y+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x650a7354|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;d=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;K=d+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0x766a0abb|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+p+_|0;S=p+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x81c2c92e|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+f+e|0;E=f+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0x92722c85|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;C=g+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0xa2bfe8a1|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+m+r|0;D=m+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0xa81a664b|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+l|0;U=w+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0xc24b8b70|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+b+y|0;P=b+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0xc76c51a3|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;k=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+d|0;x=k+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0xd192e819|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;v=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+v+p|0;K=v+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0xd6990624|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;A=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+A+f|0;S=A+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0xf40e3585|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;_=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+_+g|0;E=_+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0x106aa070|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;C=e+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0x19a4c116|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+w|0;D=t+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0x1e376c08|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;r=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+b|0;U=r+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0x2748774c|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;l=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+k|0;P=l+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0x34b0bcb5|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;y=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+y+v|0;x=y+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x391c0cb3|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;d=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;K=d+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0x4ed8aa4a|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+p+_|0;S=p+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0x5b9cca4f|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+f+e|0;E=f+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0x682e6ff3|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;C=g+C+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(D^P&(U^D))+0x748f82ee|0;x=x+C|0;C=C+(E&S^K&(E^S))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+m+r|0;D=m+D+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(U^x&(P^U))+0x78a5636f|0;K=K+D|0;D=D+(C&E^S&(C^E))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+l|0;U=w+U+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(P^K&(x^P))+0x84c87814|0;S=S+U|0;U=U+(D&C^E&(D^C))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+b+y|0;P=b+P+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(x^S&(K^x))+0x8cc70208|0;E=E+P|0;P=P+(U&D^C&(U^D))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;k=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+d|0;x=k+x+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(K^E&(S^K))+0x90befffa|0;C=C+x|0;x=x+(P&U^D&(P^U))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;v=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+v+p|0;K=v+K+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(E^S))+0xa4506ceb|0;D=D+K|0;K=K+(x&P^U&(x^P))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;A=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+A+f|0;S=A+S+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(C^E))+0xbef9a3f7|0;U=U+S|0;S=S+(K&x^P&(K^x))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;_=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+_+g|0;E=_+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(C^U&(D^C))+0xc67178f2|0;P=P+E|0;E=E+(S&K^x&(S^K))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;n=n+E|0;i=i+S|0;a=a+K|0;s=s+x|0;o=o+P|0;c=c+U|0;h=h+D|0;u=u+C|0}function C(e){e=e|0;D(U[e|0]<<24|U[e|1]<<16|U[e|2]<<8|U[e|3],U[e|4]<<24|U[e|5]<<16|U[e|6]<<8|U[e|7],U[e|8]<<24|U[e|9]<<16|U[e|10]<<8|U[e|11],U[e|12]<<24|U[e|13]<<16|U[e|14]<<8|U[e|15],U[e|16]<<24|U[e|17]<<16|U[e|18]<<8|U[e|19],U[e|20]<<24|U[e|21]<<16|U[e|22]<<8|U[e|23],U[e|24]<<24|U[e|25]<<16|U[e|26]<<8|U[e|27],U[e|28]<<24|U[e|29]<<16|U[e|30]<<8|U[e|31],U[e|32]<<24|U[e|33]<<16|U[e|34]<<8|U[e|35],U[e|36]<<24|U[e|37]<<16|U[e|38]<<8|U[e|39],U[e|40]<<24|U[e|41]<<16|U[e|42]<<8|U[e|43],U[e|44]<<24|U[e|45]<<16|U[e|46]<<8|U[e|47],U[e|48]<<24|U[e|49]<<16|U[e|50]<<8|U[e|51],U[e|52]<<24|U[e|53]<<16|U[e|54]<<8|U[e|55],U[e|56]<<24|U[e|57]<<16|U[e|58]<<8|U[e|59],U[e|60]<<24|U[e|61]<<16|U[e|62]<<8|U[e|63])}function I(e){e=e|0;U[e|0]=n>>>24;U[e|1]=n>>>16&255;U[e|2]=n>>>8&255;U[e|3]=n&255;U[e|4]=i>>>24;U[e|5]=i>>>16&255;U[e|6]=i>>>8&255;U[e|7]=i&255;U[e|8]=a>>>24;U[e|9]=a>>>16&255;U[e|10]=a>>>8&255;U[e|11]=a&255;U[e|12]=s>>>24;U[e|13]=s>>>16&255;U[e|14]=s>>>8&255;U[e|15]=s&255;U[e|16]=o>>>24;U[e|17]=o>>>16&255;U[e|18]=o>>>8&255;U[e|19]=o&255;U[e|20]=c>>>24;U[e|21]=c>>>16&255;U[e|22]=c>>>8&255;U[e|23]=c&255;U[e|24]=h>>>24;U[e|25]=h>>>16&255;U[e|26]=h>>>8&255;U[e|27]=h&255;U[e|28]=u>>>24;U[e|29]=u>>>16&255;U[e|30]=u>>>8&255;U[e|31]=u&255}function T(){n=0x6a09e667;i=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;c=0x9b05688c;h=0x1f83d9ab;u=0x5be0cd19;l=y=0}function B(e,t,r,d,p,f,g,m,w,b){e=e|0;t=t|0;r=r|0;d=d|0;p=p|0;f=f|0;g=g|0;m=m|0;w=w|0;b=b|0;n=e;i=t;a=r;s=d;o=p;c=f;h=g;u=m;l=w;y=b}function z(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){C(e);e=e+64|0;t=t-64|0;r=r+64|0}l=l+r|0;if(l>>>0>>0)y=y+1|0;return r|0}function R(e,t,r){e=e|0;t=t|0;r=r|0;var n=0,i=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){n=z(e,t)|0;if((n|0)==-1)return-1;e=e+n|0;t=t-n|0}n=n+t|0;l=l+t|0;if(l>>>0>>0)y=y+1|0;U[e|t]=0x80;if((t|0)>=56){for(i=t+1|0;(i|0)<64;i=i+1|0)U[e|i]=0x00;C(e);t=0;U[e|0]=0}for(i=t+1|0;(i|0)<59;i=i+1|0)U[e|i]=0;U[e|56]=y>>>21&255;U[e|57]=y>>>13&255;U[e|58]=y>>>5&255;U[e|59]=y<<3&255|l>>>29;U[e|60]=l>>>21&255;U[e|61]=l>>>13&255;U[e|62]=l>>>5&255;U[e|63]=l<<3&255;C(e);if(~r)I(r);return n|0}function M(){n=d;i=p;a=f;s=g;o=m;c=w;h=b;u=k;l=64;y=0}function L(){n=v;i=A;a=_;s=E;o=S;c=K;h=x;u=P;l=64;y=0}function N(e,t,r,U,C,I,B,z,R,M,L,N,O,F,H,j){e=e|0;t=t|0;r=r|0;U=U|0;C=C|0;I=I|0;B=B|0;z=z|0;R=R|0;M=M|0;L=L|0;N=N|0;O=O|0;F=F|0;H=H|0;j=j|0;T();D(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,U^0x5c5c5c5c,C^0x5c5c5c5c,I^0x5c5c5c5c,B^0x5c5c5c5c,z^0x5c5c5c5c,R^0x5c5c5c5c,M^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,O^0x5c5c5c5c,F^0x5c5c5c5c,H^0x5c5c5c5c,j^0x5c5c5c5c);v=n;A=i;_=a;E=s;S=o;K=c;x=h;P=u;T();D(e^0x36363636,t^0x36363636,r^0x36363636,U^0x36363636,C^0x36363636,I^0x36363636,B^0x36363636,z^0x36363636,R^0x36363636,M^0x36363636,L^0x36363636,N^0x36363636,O^0x36363636,F^0x36363636,H^0x36363636,j^0x36363636);d=n;p=i;f=a;g=s;m=o;w=c;b=h;k=u;l=64;y=0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var l=0,y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0;if(e&63)return-1;if(~r)if(r&31)return-1;b=R(e,t,-1)|0;l=n,y=i,d=a,p=s,f=o,g=c,m=h,w=u;L();D(l,y,d,p,f,g,m,w,0x80000000,0,0,0,0,0,0,768);if(~r)I(r);return b|0}function F(e,t,r,l,y){e=e|0;t=t|0;r=r|0;l=l|0;y=y|0;var d=0,p=0,f=0,g=0,m=0,w=0,b=0,k=0,v=0,A=0,_=0,E=0,S=0,K=0,x=0,P=0;if(e&63)return-1;if(~y)if(y&31)return-1;U[e+t|0]=r>>>24;U[e+t+1|0]=r>>>16&255;U[e+t+2|0]=r>>>8&255;U[e+t+3|0]=r&255;O(e,t+4|0,-1)|0;d=v=n,p=A=i,f=_=a,g=E=s,m=S=o,w=K=c,b=x=h,k=P=u;l=l-1|0;while((l|0)>0){M();D(v,A,_,E,S,K,x,P,0x80000000,0,0,0,0,0,0,768);v=n,A=i,_=a,E=s,S=o,K=c,x=h,P=u;L();D(v,A,_,E,S,K,x,P,0x80000000,0,0,0,0,0,0,768);v=n,A=i,_=a,E=s,S=o,K=c,x=h,P=u;d=d^n;p=p^i;f=f^a;g=g^s;m=m^o;w=w^c;b=b^h;k=k^u;l=l-1|0}n=d;i=p;a=f;s=g;o=m;c=w;h=b;u=k;if(~y)I(y);return 0}return{reset:T,init:B,process:z,finish:R,hmac_reset:M,hmac_init:N,hmac_finish:O,pbkdf2_generate_block:F}}({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(Xe.push(this.heap),Qe.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new Ye).process(e).finish().result}}Ye.NAME="sha256";var Je=et;function et(e,t){if(!e)throw Error(t||"Assertion failed")}et.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)};var tt=void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function rt(e,t){return e(t={exports:{}},t.exports),t.exports}function nt(){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var it=rt((function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}));var at=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>8,s=255&i;a?r.push(a,s):r.push(s)}else for(n=0;n>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}var ct=function(e,t){for(var r="",n=0;n>>0}return a};var yt=function(e,t){for(var r=Array(4*e.length),n=0,i=0;n>>24,r[i+1]=a>>>16&255,r[i+2]=a>>>8&255,r[i+3]=255&a):(r[i+3]=a>>>24,r[i+2]=a>>>16&255,r[i+1]=a>>>8&255,r[i]=255&a)}return r};var dt={inherits:it,toArray:at,toHex:st,htonl:ot,toHex32:ct,zero2:ht,zero8:ut,join32:lt,split32:yt,rotr32:function(e,t){return e>>>t|e<<32-t},rotl32:function(e,t){return e<>>32-t},sum32:function(e,t){return e+t>>>0},sum32_3:function(e,t,r){return e+t+r>>>0},sum32_4:function(e,t,r,n){return e+t+r+n>>>0},sum32_5:function(e,t,r,n,i){return e+t+r+n+i>>>0},sum64:function(e,t,r,n){var i=e[t],a=n+e[t+1]>>>0,s=(a>>0,e[t+1]=a},sum64_hi:function(e,t,r,n){return(t+n>>>0>>0},sum64_lo:function(e,t,r,n){return t+n>>>0},sum64_4_hi:function(e,t,r,n,i,a,s,o){var c=0,h=t;return c+=(h=h+n>>>0)>>0)>>0)>>0},sum64_4_lo:function(e,t,r,n,i,a,s,o){return t+n+a+o>>>0},sum64_5_hi:function(e,t,r,n,i,a,s,o,c,h){var u=0,l=t;return u+=(l=l+n>>>0)>>0)>>0)>>0)>>0},sum64_5_lo:function(e,t,r,n,i,a,s,o,c,h){return t+n+a+o+h>>>0},rotr64_hi:function(e,t,r){return(t<<32-r|e>>>r)>>>0},rotr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0},shr64_hi:function(e,t,r){return e>>>r},shr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0}};function pt(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var ft=pt;pt.prototype.update=function(e,t){if(e=dt.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=dt.join32(e,0,e.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,a=8;a>>3},g1_256:function(e){return mt(e,17)^mt(e,19)^e>>>10}},_t=dt.sum32,Et=dt.sum32_4,St=dt.sum32_5,Kt=At.ch32,xt=At.maj32,Pt=At.s0_256,Ut=At.s1_256,Dt=At.g0_256,Ct=At.g1_256,It=gt.BlockHash,Tt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Bt(){if(!(this instanceof Bt))return new Bt;It.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=Tt,this.W=Array(64)}dt.inherits(Bt,It);var zt=Bt;function Rt(){if(!(this instanceof Rt))return new Rt;zt.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Bt.blockSize=512,Bt.outSize=256,Bt.hmacStrength=192,Bt.padLength=64,Bt.prototype._update=function(e,t){for(var r=this.W,n=0;n<16;n++)r[n]=e[t+n];for(;n>>32-i,r)}function Dr(e,t,r,n,i,a,s){return Ur(t&r|~t&n,e,t,i,a,s)}function Cr(e,t,r,n,i,a,s){return Ur(t&n|r&~n,e,t,i,a,s)}function Ir(e,t,r,n,i,a,s){return Ur(t^r^n,e,t,i,a,s)}function Tr(e,t,r,n,i,a,s){return Ur(r^(t|~n),e,t,i,a,s)}function Br(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const zr="0123456789abcdef".split("");function Rr(e){let t="",r=0;for(;r<4;r++)t+=zr[e>>8*r+4&15]+zr[e>>8*r&15];return t}function Mr(e,t){return e+t&4294967295}const Lr=X.getWebCrypto(),Nr=X.getNodeCrypto(),Or=Nr&&Nr.getHashes();function Fr(e){if(Nr&&Or.includes(e))return async function(t){const r=Nr.createHash(e);return z(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function Hr(e,t){return async function(r,n=ie){if(s(r)&&(r=await H(r)),!X.isStream(r)&&Lr&&t&&r.length>=n.minBytesForWebCrypto)return new Uint8Array(await Lr.digest(t,r));const i=e();return z(r,(e=>{i.update(e)}),(()=>new Uint8Array(i.digest())))}}function jr(e,t){return async function(r,n=ie){if(s(r)&&(r=await H(r)),X.isStream(r)){const t=new e;return z(r,(e=>{t.process(e)}),(()=>t.finish().result))}return Lr&&t&&r.length>=n.minBytesForWebCrypto?new Uint8Array(await Lr.digest(t,r)):e.bytes(r)}}const qr={md5:Fr("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let n;for(n=64;n<=e.length;n+=64)Pr(r,Br(e.substring(n-64,n)));e=e.substring(n-64);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(Pr(r,i),n=0;n<16;n++)i[n]=0;return i[14]=8*t,Pr(r,i),r}(X.uint8ArrayToString(e));return X.hexToUint8Array(function(e){for(let t=0;tnew Uint8Array(a.update(e))))}(e,t,r,n);if(X.isAES(e))return function(e,t,r,n,i){if(X.getWebCrypto()&&24!==t.length&&!X.isStream(r)&&r.length>=3e3*i.minBytesForWebCrypto)return async function(e,t,r,n){const i="AES-CBC",a=await $r.importKey("raw",t,{name:i},!1,["encrypt"]),{blockSize:s}=Wr(e),o=X.concatUint8Array([new Uint8Array(s),r]),c=new Uint8Array(await $r.encrypt({name:i,iv:n},a,o)).subarray(0,r.length);return function(e,t){for(let r=0;ra.aes.AES_Encrypt_process(e)),(()=>a.aes.AES_Encrypt_finish()))}(e,t,r,n,i);const s=new(Wr(e))(t),o=s.blockSize,c=n.slice();let h=new Uint8Array;const u=e=>{e&&(h=X.concatUint8Array([h,e]));const t=new Uint8Array(h.length);let r,n=0;for(;e?h.length>=o:h.length;){const e=s.encrypt(c);for(r=0;rnew Uint8Array(a.update(e))))}(e,t,r,n);if(X.isAES(e))return function(e,t,r,n){if(X.isStream(r)){const e=new Vr(t,n);return z(r,(t=>e.aes.AES_Decrypt_process(t)),(()=>e.aes.AES_Decrypt_finish()))}return Vr.decrypt(r,t,n)}(0,t,r,n);const a=new(Wr(e))(t),s=a.blockSize;let o=n,c=new Uint8Array;const h=e=>{e&&(c=X.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,n=0;for(;e?c.length>=s:c.length;){const e=a.encrypt(o);for(o=c.subarray(0,s),r=0;r48)throw new ve("illegal counter size");let e=Math.pow(2,r)-1;n.set_mask(0,0,e/4294967296|0,0|e)}else r=48,n.set_mask(0,0,65535,4294967295);if(void 0===e)throw Error("nonce is required");{let t=e.length;if(!t||t>16)throw new ve("illegal nonce size");let r=new DataView(new ArrayBuffer(16));new Uint8Array(r.buffer).set(e),n.set_nonce(r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12))}if(void 0!==t){if(t<0||t>=Math.pow(2,r))throw new ve("illegal counter value");n.set_counter(0,0,t/4294967296|0,0|t)}}}class en{static encrypt(e,t,r=!0,n){return new en(t,n,r).encrypt(e)}static decrypt(e,t,r=!0,n){return new en(t,n,r).decrypt(e)}constructor(e,t,r=!0,n){this.aes=n||new Se(e,t,r,"CBC")}encrypt(e){return be(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return be(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}const tn=X.getWebCrypto(),rn=X.getNodeCrypto(),nn=16;function an(e,t){const r=e.length-nn;for(let n=0;n>3),17+(h>>3)),8-(7&h)).subarray(1),d=new Uint8Array(kn),p=new Uint8Array(t.length+An);let f,g=0;for(f=0;f16)throw new ve("illegal tagSize value");const o=t.length||0,c=new Uint8Array(16);12!==o?(this._gcm_mac_process(t),s[0]=0,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=0,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=0,s[11]=o>>>29,s[12]=o>>>21&255,s[13]=o>>>13&255,s[14]=o>>>5&255,s[15]=o<<3&255,a.mac(fe.MAC.GCM,fe.HEAP_DATA,16),a.get_iv(fe.HEAP_DATA),a.set_iv(0,0,0,0),c.set(s.subarray(0,16))):(c.set(t),c[15]=1);const h=new DataView(c.buffer);if(this.gamma0=h.getUint32(12),a.set_nonce(h.getUint32(0),h.getUint32(4),h.getUint32(8),0),a.set_mask(0,0,0,4294967295),void 0!==r){if(r.length>Un)throw new ve("illegal adata length");r.length?(this.adata=r,this._gcm_mac_process(r)):this.adata=void 0}else this.adata=void 0;if(this.counter<1||this.counter>4294967295)throw new RangeError("counter must be a positive 32-bit integer");a.set_counter(0,0,0,this.gamma0+this.counter|0)}static encrypt(e,t,r,n,i){return new Dn(t,r,n,i).encrypt(e)}static decrypt(e,t,r,n,i){return new Dn(t,r,n,i).decrypt(e)}encrypt(e){return this.AES_GCM_encrypt(e)}decrypt(e){return this.AES_GCM_decrypt(e)}AES_GCM_Encrypt_process(e){let t=0,r=e.length||0,{asm:n,heap:i}=this.aes.acquire_asm(),a=this.counter,s=this.aes.pos,o=this.aes.len,c=0,h=o+r&-16,u=0;if((a-1<<4)+o+r>Un)throw new RangeError("counter overflow");const l=new Uint8Array(h);for(;r>0;)u=we(i,s+o,e,t,r),o+=u,t+=u,r-=u,u=n.cipher(fe.ENC.CTR,fe.HEAP_DATA+s,o),u=n.mac(fe.MAC.GCM,fe.HEAP_DATA+s,u),u&&l.set(i.subarray(s,s+u),c),a+=u>>>4,c+=u,u>>29,t[4]=h>>>21,t[5]=h>>>13&255,t[6]=h>>>5&255,t[7]=h<<3&255,t[8]=t[9]=t[10]=0,t[11]=u>>>29,t[12]=u>>>21&255,t[13]=u>>>13&255,t[14]=u>>>5&255,t[15]=u<<3&255,e.mac(fe.MAC.GCM,fe.HEAP_DATA,16),e.get_iv(fe.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(fe.ENC.CTR,fe.HEAP_DATA,16),o.set(t.subarray(0,n),s),this.counter=1,this.aes.pos=0,this.aes.len=0,o}AES_GCM_Decrypt_process(e){let t=0,r=e.length||0,{asm:n,heap:i}=this.aes.acquire_asm(),a=this.counter,s=this.tagSize,o=this.aes.pos,c=this.aes.len,h=0,u=c+r>s?c+r-s&-16:0,l=c+r-u,y=0;if((a-1<<4)+c+r>Un)throw new RangeError("counter overflow");const d=new Uint8Array(u);for(;r>l;)y=we(i,o+c,e,t,r-l),c+=y,t+=y,r-=y,y=n.mac(fe.MAC.GCM,fe.HEAP_DATA+o,y),y=n.cipher(fe.DEC.CTR,fe.HEAP_DATA+o,y),y&&d.set(i.subarray(o,o+y),h),a+=y>>>4,h+=y,o=0,c=0;return r>0&&(c+=we(i,0,e,t,r)),this.counter=a,this.aes.pos=o,this.aes.len=c,d}AES_GCM_Decrypt_finish(){let{asm:e,heap:t}=this.aes.acquire_asm(),r=this.tagSize,n=this.adata,i=this.counter,a=this.aes.pos,s=this.aes.len,o=s-r;if(s>>29,t[4]=l>>>21,t[5]=l>>>13&255,t[6]=l>>>5&255,t[7]=l<<3&255,t[8]=t[9]=t[10]=0,t[11]=y>>>29,t[12]=y>>>21&255,t[13]=y>>>13&255,t[14]=y>>>5&255,t[15]=y<<3&255,e.mac(fe.MAC.GCM,fe.HEAP_DATA,16),e.get_iv(fe.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(fe.ENC.CTR,fe.HEAP_DATA,16);let d=0;for(let e=0;e0;){for(a=we(r,0,e,n,i),n+=a,i-=a;15&a;)r[a++]=0;t.mac(fe.MAC.GCM,fe.HEAP_DATA,a)}}}const Cn=X.getWebCrypto(),In=X.getNodeCrypto(),Tn=X.getNodeBuffer(),Bn=16,zn="AES-GCM";async function Rn(e,t){if(e!==$.symmetric.aes128&&e!==$.symmetric.aes192&&e!==$.symmetric.aes256)throw Error("GCM mode supports only AES cipher");if(X.getNodeCrypto())return{encrypt:async function(e,r,n=new Uint8Array){const i=new In.createCipheriv("aes-"+8*t.length+"-gcm",t,r);i.setAAD(n);const a=Tn.concat([i.update(e),i.final(),i.getAuthTag()]);return new Uint8Array(a)},decrypt:async function(e,r,n=new Uint8Array){const i=new In.createDecipheriv("aes-"+8*t.length+"-gcm",t,r);i.setAAD(n),i.setAuthTag(e.slice(e.length-Bn,e.length));const a=Tn.concat([i.update(e.slice(0,e.length-Bn)),i.final()]);return new Uint8Array(a)}};if(X.getWebCrypto()&&24!==t.length){const e=await Cn.importKey("raw",t,{name:zn},!1,["encrypt","decrypt"]);return{encrypt:async function(r,n,i=new Uint8Array){if(!r.length)return Dn.encrypt(r,t,n,i);const a=await Cn.encrypt({name:zn,iv:n,additionalData:i,tagLength:8*Bn},e,r);return new Uint8Array(a)},decrypt:async function(r,n,i=new Uint8Array){if(r.length===Bn)return Dn.decrypt(r,t,n,i);const a=await Cn.decrypt({name:zn,iv:n,additionalData:i,tagLength:8*Bn},e,r);return new Uint8Array(a)}}}return{encrypt:async function(e,r,n){return Dn.encrypt(e,t,r,n)},decrypt:async function(e,r,n){return Dn.decrypt(e,t,r,n)}}}Rn.getNonce=function(e,t){const r=e.slice();for(let e=0;e>>8)-1}(e,t,r,n,32)}function d(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function p(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function f(e,t,r){for(var n,i=~(r-1),a=0;a<16;a++)n=i&(e[a]^t[a]),e[a]^=n,t[a]^=n}function g(e,r){var n,i,a,s=t(),o=t();for(n=0;n<16;n++)o[n]=r[n];for(p(o),p(o),p(o),i=0;i<2;i++){for(s[0]=o[0]-65517,n=1;n<15;n++)s[n]=o[n]-65535-(s[n-1]>>16&1),s[n-1]&=65535;s[15]=o[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,f(o,s,1-a)}for(n=0;n<16;n++)e[2*n]=255&o[n],e[2*n+1]=o[n]>>8}function m(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return g(r,e),g(n,t),y(r,0,n,0)}function w(e){var t=new Uint8Array(32);return g(t,e),1&t[0]}function b(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function k(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function v(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function A(e,t,r){var n,i,a=0,s=0,o=0,c=0,h=0,u=0,l=0,y=0,d=0,p=0,f=0,g=0,m=0,w=0,b=0,k=0,v=0,A=0,_=0,E=0,S=0,K=0,x=0,P=0,U=0,D=0,C=0,I=0,T=0,B=0,z=0,R=r[0],M=r[1],L=r[2],N=r[3],O=r[4],F=r[5],H=r[6],j=r[7],q=r[8],G=r[9],V=r[10],W=r[11],$=r[12],Z=r[13],X=r[14],Q=r[15];a+=(n=t[0])*R,s+=n*M,o+=n*L,c+=n*N,h+=n*O,u+=n*F,l+=n*H,y+=n*j,d+=n*q,p+=n*G,f+=n*V,g+=n*W,m+=n*$,w+=n*Z,b+=n*X,k+=n*Q,s+=(n=t[1])*R,o+=n*M,c+=n*L,h+=n*N,u+=n*O,l+=n*F,y+=n*H,d+=n*j,p+=n*q,f+=n*G,g+=n*V,m+=n*W,w+=n*$,b+=n*Z,k+=n*X,v+=n*Q,o+=(n=t[2])*R,c+=n*M,h+=n*L,u+=n*N,l+=n*O,y+=n*F,d+=n*H,p+=n*j,f+=n*q,g+=n*G,m+=n*V,w+=n*W,b+=n*$,k+=n*Z,v+=n*X,A+=n*Q,c+=(n=t[3])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G,K+=n*V,x+=n*W,P+=n*$,U+=n*Z,D+=n*X,C+=n*Q,m+=(n=t[12])*R,w+=n*M,b+=n*L,k+=n*N,v+=n*O,A+=n*F,_+=n*H,E+=n*j,S+=n*q,K+=n*G,x+=n*V,P+=n*W,U+=n*$,D+=n*Z,C+=n*X,I+=n*Q,w+=(n=t[13])*R,b+=n*M,k+=n*L,v+=n*N,A+=n*O,_+=n*F,E+=n*H,S+=n*j,K+=n*q,x+=n*G,P+=n*V,U+=n*W,D+=n*$,C+=n*Z,I+=n*X,T+=n*Q,b+=(n=t[14])*R,k+=n*M,v+=n*L,A+=n*N,_+=n*O,E+=n*F,S+=n*H,K+=n*j,x+=n*q,P+=n*G,U+=n*V,D+=n*W,C+=n*$,I+=n*Z,T+=n*X,B+=n*Q,k+=(n=t[15])*R,s+=38*(A+=n*L),o+=38*(_+=n*N),c+=38*(E+=n*O),h+=38*(S+=n*F),u+=38*(K+=n*H),l+=38*(x+=n*j),y+=38*(P+=n*q),d+=38*(U+=n*G),p+=38*(D+=n*V),f+=38*(C+=n*W),g+=38*(I+=n*$),m+=38*(T+=n*Z),w+=38*(B+=n*X),b+=38*(z+=n*Q),a=(n=(a+=38*(v+=n*M))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),k=(n=k+i+65535)-65536*(i=Math.floor(n/65536)),a=(n=(a+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),k=(n=k+i+65535)-65536*(i=Math.floor(n/65536)),a+=i-1+37*(i-1),e[0]=a,e[1]=s,e[2]=o,e[3]=c,e[4]=h,e[5]=u,e[6]=l,e[7]=y,e[8]=d,e[9]=p,e[10]=f,e[11]=g,e[12]=m,e[13]=w,e[14]=b,e[15]=k}function _(e,t){A(e,t,t)}function E(e,r){var n,i=t();for(n=0;n<16;n++)i[n]=r[n];for(n=253;n>=0;n--)_(i,i),2!==n&&4!==n&&A(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}function S(e,r,n){var i,a,o=new Uint8Array(32),c=new Float64Array(80),h=t(),u=t(),l=t(),y=t(),d=t(),p=t();for(a=0;a<31;a++)o[a]=r[a];for(o[31]=127&r[31]|64,o[0]&=248,b(c,n),a=0;a<16;a++)u[a]=c[a],y[a]=h[a]=l[a]=0;for(h[0]=y[0]=1,a=254;a>=0;--a)f(h,u,i=o[a>>>3]>>>(7&a)&1),f(l,y,i),k(d,h,l),v(h,h,l),k(l,u,y),v(u,u,y),_(y,d),_(p,h),A(h,l,h),A(l,u,d),k(d,h,l),v(h,h,l),_(u,h),v(l,y,p),A(h,l,s),k(h,h,y),A(l,l,h),A(h,y,p),A(y,u,c),_(u,d),f(h,u,i),f(l,y,i);for(a=0;a<16;a++)c[a+16]=h[a],c[a+32]=l[a],c[a+48]=u[a],c[a+64]=y[a];var m=c.subarray(32),w=c.subarray(16);return E(m,m),A(w,w,m),g(e,w),0}function K(e,t){return S(e,t,n)}function x(e,r){var n=t(),i=t(),a=t(),s=t(),o=t(),h=t(),u=t(),l=t(),y=t();v(n,e[1],e[0]),v(y,r[1],r[0]),A(n,n,y),k(i,e[0],e[1]),k(y,r[0],r[1]),A(i,i,y),A(a,e[3],r[3]),A(a,a,c),A(s,e[2],r[2]),k(s,s,s),v(o,i,n),v(h,s,a),k(u,s,a),k(l,i,n),A(e[0],o,h),A(e[1],l,u),A(e[2],u,h),A(e[3],o,l)}function P(e,t,r){var n;for(n=0;n<4;n++)f(e[n],t[n],r)}function U(e,r){var n=t(),i=t(),a=t();E(a,r[2]),A(n,r[0],a),A(i,r[1],a),g(e,i),e[31]^=w(n)<<7}function D(e,t,r){var n,s;for(d(e[0],i),d(e[1],a),d(e[2],a),d(e[3],i),s=255;s>=0;--s)P(e,t,n=r[s/8|0]>>(7&s)&1),x(t,e),x(e,e),P(e,t,n)}function C(e,r){var n=[t(),t(),t(),t()];d(n[0],h),d(n[1],u),d(n[2],a),A(n[3],h,u),D(e,n,r)}function I(n,i,a){var s,o,c=[t(),t(),t(),t()];for(a||r(i,32),(s=e.hash(i.subarray(0,32)))[0]&=248,s[31]&=127,s[31]|=64,C(c,s),U(n,c),o=0;o<32;o++)i[o+32]=n[o];return 0}var T=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function B(e,t){var r,n,i,a;for(n=63;n>=32;--n){for(r=0,i=n-32,a=n-12;i>4)*T[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*T[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function z(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;B(e,r)}function R(e,r){var n=t(),s=t(),c=t(),h=t(),u=t(),y=t(),p=t();return d(e[2],a),b(e[1],r),_(c,e[1]),A(h,c,o),v(c,c,e[2]),k(h,e[2],h),_(u,h),_(y,u),A(p,y,u),A(n,p,c),A(n,n,h),function(e,r){var n,i=t();for(n=0;n<16;n++)i[n]=r[n];for(n=250;n>=0;n--)_(i,i),1!==n&&A(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}(n,n),A(n,n,c),A(n,n,h),A(n,n,h),A(e[0],n,h),_(s,e[0]),A(s,s,h),m(s,c)&&A(e[0],e[0],l),_(s,e[0]),A(s,s,h),m(s,c)?-1:(w(e[0])===r[31]>>7&&v(e[0],i,e[0]),A(e[3],e[0],e[1]),0)}var M=64;function L(){for(var e=0;e=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return I(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(L(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;re&&(c.imod(a.leftShift(i)).iadd(a),h=c.mod(s).toNumber())}while(!await qn(c,t,r));return c}async function qn(e,t,r){return!(t&&!e.dec().gcd(t).isOne())&&(!!await async function(e){const t=await X.getBigInteger();return Gn.every((r=>0!==e.mod(new t(r))))}(e)&&(!!await async function(e,t){const r=await X.getBigInteger();return t=t||new r(2),t.modExp(e.dec(),e).isOne()}(e)&&!!await async function(e,t,r){const n=await X.getBigInteger(),i=e.bitLength();t||(t=Math.max(1,i/48|0));const a=e.dec();let s=0;for(;!a.getBit(s);)s++;const o=e.rightShift(new n(s));for(;t>0;t--){let t,i=(r?r():await Fn(new n(2),a)).modExp(o,e);if(!i.isOne()&&!i.equal(a)){for(t=1;tt-11)throw Error("Message too long");const n=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!n;if(t)return X.selectUint8Array(s,a,t);if(s)return a;throw Error("Decryption error")}async function Zn(e,t,r){let n;if(t.length!==Gr.getHashByteLength(e))throw Error("Invalid hash length");const i=new Uint8Array(Vn[e].length);for(n=0;n{Yn.generateKeyPair("rsa",r,((r,n,i)=>{r?t(r):e(ei.decode(i,"der"))}))}));return{n:n.modulus.toArrayLike(Uint8Array),e:n.publicExponent.toArrayLike(Uint8Array),d:n.privateExponent.toArrayLike(Uint8Array),p:n.prime2.toArrayLike(Uint8Array),q:n.prime1.toArrayLike(Uint8Array),u:n.coefficient.toArrayLike(Uint8Array)}}let r,n,i;do{n=await jn(e-(e>>1),t,40),r=await jn(e>>1,t,40),i=r.mul(n)}while(i.bitLength()!==e);const a=r.dec().imul(n.dec());return n.lt(r)&&([r,n]=[n,r]),{n:i.toUint8Array(),e:t.toUint8Array(),d:t.modInv(a).toUint8Array(),p:r.toUint8Array(),q:n.toUint8Array(),u:r.modInv(n).toUint8Array()}},validateParams:async function(e,t,r,n,i,a){const s=await X.getBigInteger();if(e=new s(e),n=new s(n),i=new s(i),!n.mul(i).equal(e))return!1;const o=new s(2);if(a=new s(a),!n.mul(a).mod(i).isOne())return!1;t=new s(t),r=new s(r);const c=new s(Math.floor(e.bitLength()/3)),h=await Fn(o,o.leftShift(c)),u=h.mul(r).mul(t);return!(!u.mod(n.dec()).equal(h)||!u.mod(i.dec()).equal(h))}});var ni=/*#__PURE__*/Object.freeze({__proto__:null,encrypt:async function(e,t,r,n){const i=await X.getBigInteger();t=new i(t),r=new i(r),n=new i(n);const a=new i(Wn(e,t.byteLength())),s=await Fn(new i(1),t.dec());return{c1:r.modExp(s,t).toUint8Array(),c2:n.modExp(s,t).imul(a).imod(t).toUint8Array()}},decrypt:async function(e,t,r,n,i){const a=await X.getBigInteger();return e=new a(e),t=new a(t),r=new a(r),n=new a(n),$n(e.modExp(n,r).modInv(r).imul(t).imod(r).toUint8Array("be",r.byteLength()),i)},validateParams:async function(e,t,r,n){const i=await X.getBigInteger();e=new i(e),t=new i(t),r=new i(r);const a=new i(1);if(t.lte(a)||t.gte(e))return!1;const s=new i(e.bitLength()),o=new i(1023);if(s.lt(o))return!1;if(!t.modExp(e.dec(),e).isOne())return!1;let c=t;const h=new i(1),u=new i(2).leftShift(new i(17));for(;h.lt(u);){if(c=c.mul(t).imod(e),c.isOne())return!1;h.iinc()}n=new i(n);const l=new i(2),y=await Fn(l.leftShift(s.dec()),l.leftShift(s)),d=e.dec().imul(y).iadd(n);return!!r.equal(t.modExp(d,e))}});class ii{constructor(e){if(e instanceof ii)this.oid=e.oid;else if(X.isArray(e)||X.isUint8Array(e)){if(6===(e=new Uint8Array(e))[0]){if(e[1]!==e.length-2)throw Error("Length mismatch in DER encoded oid");e=e.subarray(2)}this.oid=e}else this.oid=""}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return X.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return X.uint8ArrayToHex(this.oid)}getName(){const e=this.toHex();if($.curve[e])return $.write($.curve,e);throw Error("Unknown curve object identifier.")}}function ai(e,t){return e.keyPair({priv:t})}function si(e,t){const r=e.keyPair({pub:t});if(!0!==r.validate().result)throw Error("Invalid elliptic public key");return r}async function oi(e){if(!ie.useIndutnyElliptic)throw Error("This curve is only supported in the full build of OpenPGP.js");const{default:t}=await import("./elliptic.min.mjs");return new t.ec(e)}function ci(e){let t,r=0;const n=e[0];return n<192?([r]=e,t=1):n<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===n&&(r=X.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function hi(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):X.concatUint8Array([new Uint8Array([255]),X.writeNumber(e,4)])}function ui(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function li(e){return new Uint8Array([192|e])}function yi(e,t){return X.concatUint8Array([li(e),hi(t)])}function di(e){return[$.packet.literalData,$.packet.compressedData,$.packet.symmetricallyEncryptedData,$.packet.symEncryptedIntegrityProtectedData,$.packet.aeadEncryptedData].includes(e)}async function pi(e,t){const r=D(e);let n,i;try{const s=await r.peekBytes(2);if(!s||s.length<2||0==(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const o=await r.readByte();let c,h,u=-1,l=-1;l=0,0!=(64&o)&&(l=1),l?u=63&o:(u=(63&o)>>2,h=3&o);const y=di(u);let d,p=null;if(y){if("array"===X.isStream(e)){const e=new a;n=C(e),p=e}else{const e=new E;n=C(e.writable),p=e.readable}i=t({tag:u,packet:p})}else p=[];do{if(l){const e=await r.readByte();if(d=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),d=!0,!y)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(h){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){n&&await n.ready;const{done:t,value:i}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const a=c===1/0?i:i.subarray(0,c-e);if(n?await n.write(a):p.push(a),e+=i.length,e>=c){r.unshift(i.subarray(c-e+i.length));break}}}}while(d);const f=await r.peekBytes(y?1/0:2);return n?(await n.ready,await n.close()):(p=X.concatUint8Array(p),await t({tag:u,packet:p})),!f||!f.length}catch(e){if(n)return await n.abort(e),!0;throw e}finally{n&&await i,r.releaseLock()}}class fi extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,fi),this.name="UnsupportedError"}}class gi{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}const mi=X.getWebCrypto(),wi=X.getNodeCrypto(),bi={p256:"P-256",p384:"P-384",p521:"P-521"},ki=wi?wi.getCurves():[],vi=wi?{secp256k1:ki.includes("secp256k1")?"secp256k1":void 0,p256:ki.includes("prime256v1")?"prime256v1":void 0,p384:ki.includes("secp384r1")?"secp384r1":void 0,p521:ki.includes("secp521r1")?"secp521r1":void 0,ed25519:ki.includes("ED25519")?"ED25519":void 0,curve25519:ki.includes("X25519")?"X25519":void 0,brainpoolP256r1:ki.includes("brainpoolP256r1")?"brainpoolP256r1":void 0,brainpoolP384r1:ki.includes("brainpoolP384r1")?"brainpoolP384r1":void 0,brainpoolP512r1:ki.includes("brainpoolP512r1")?"brainpoolP512r1":void 0}:{},Ai={p256:{oid:[6,8,42,134,72,206,61,3,1,7],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:vi.p256,web:bi.p256,payloadSize:32,sharedSize:256},p384:{oid:[6,5,43,129,4,0,34],keyType:$.publicKey.ecdsa,hash:$.hash.sha384,cipher:$.symmetric.aes192,node:vi.p384,web:bi.p384,payloadSize:48,sharedSize:384},p521:{oid:[6,5,43,129,4,0,35],keyType:$.publicKey.ecdsa,hash:$.hash.sha512,cipher:$.symmetric.aes256,node:vi.p521,web:bi.p521,payloadSize:66,sharedSize:528},secp256k1:{oid:[6,5,43,129,4,0,10],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:vi.secp256k1,payloadSize:32},ed25519:{oid:[6,9,43,6,1,4,1,218,71,15,1],keyType:$.publicKey.eddsaLegacy,hash:$.hash.sha512,node:!1,payloadSize:32},curve25519:{oid:[6,10,43,6,1,4,1,151,85,1,5,1],keyType:$.publicKey.ecdh,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:!1,payloadSize:32},brainpoolP256r1:{oid:[6,9,43,36,3,3,2,8,1,1,7],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:vi.brainpoolP256r1,payloadSize:32},brainpoolP384r1:{oid:[6,9,43,36,3,3,2,8,1,1,11],keyType:$.publicKey.ecdsa,hash:$.hash.sha384,cipher:$.symmetric.aes192,node:vi.brainpoolP384r1,payloadSize:48},brainpoolP512r1:{oid:[6,9,43,36,3,3,2,8,1,1,13],keyType:$.publicKey.ecdsa,hash:$.hash.sha512,cipher:$.symmetric.aes256,node:vi.brainpoolP512r1,payloadSize:64}};class _i{constructor(e,t){try{(X.isArray(e)||X.isUint8Array(e))&&(e=new ii(e)),e instanceof ii&&(e=e.getName()),this.name=$.write($.curve,e)}catch(e){throw new fi("Unknown curve")}t=t||Ai[this.name],this.keyType=t.keyType,this.oid=t.oid,this.hash=t.hash,this.cipher=t.cipher,this.node=t.node&&Ai[this.name],this.web=t.web&&Ai[this.name],this.payloadSize=t.payloadSize,this.web&&X.getWebCrypto()?this.type="web":this.node&&X.getNodeCrypto()?this.type="node":"curve25519"===this.name?this.type="curve25519":"ed25519"===this.name&&(this.type="ed25519")}async genKeyPair(){let e;switch(this.type){case"web":try{return await async function(e){const t=await mi.generateKey({name:"ECDSA",namedCurve:bi[e]},!0,["sign","verify"]),r=await mi.exportKey("jwk",t.privateKey),n=await mi.exportKey("jwk",t.publicKey);return{publicKey:Si(n),privateKey:re(r.d)}}(this.name)}catch(e){X.printDebugError("Browser did not support generating ec key "+e.message);break}case"node":return async function(e){const t=wi.createECDH(vi[e]);return await t.generateKeys(),{publicKey:new Uint8Array(t.getPublicKey()),privateKey:new Uint8Array(t.getPrivateKey())}}(this.name);case"curve25519":{const t=On(32);t[0]=127&t[0]|64,t[31]&=248;const r=t.slice().reverse();e=Ln.box.keyPair.fromSecretKey(r);return{publicKey:X.concatUint8Array([new Uint8Array([64]),e.publicKey]),privateKey:t}}case"ed25519":{const e=On(32),t=Ln.sign.keyPair.fromSeed(e);return{publicKey:X.concatUint8Array([new Uint8Array([64]),t.publicKey]),privateKey:e}}}const t=await oi(this.name);return e=await t.genKeyPair({entropy:X.uint8ArrayToString(On(32))}),{publicKey:new Uint8Array(e.getPublic("array",!1)),privateKey:e.getPrivate().toArrayLike(Uint8Array)}}}async function Ei(e,t,r,n){const i={p256:!0,p384:!0,p521:!0,secp256k1:!0,curve25519:e===$.publicKey.ecdh,brainpoolP256r1:!0,brainpoolP384r1:!0,brainpoolP512r1:!0},a=t.getName();if(!i[a])return!1;if("curve25519"===a){n=n.slice().reverse();const{publicKey:e}=Ln.box.keyPair.fromSecretKey(n);r=new Uint8Array(r);const t=new Uint8Array([64,...e]);return!!X.equalsUint8Array(t,r)}const s=await oi(a);try{r=si(s,r).getPublic()}catch(e){return!1}return!!ai(s,n).getPublic().eq(r)}function Si(e){const t=re(e.x),r=re(e.y),n=new Uint8Array(t.length+r.length+1);return n[0]=4,n.set(t,1),n.set(r,t.length+1),n}function Ki(e,t,r){const n=e,i=r.slice(1,n+1),a=r.slice(n+1,2*n+1);return{kty:"EC",crv:t,x:ne(i,!0),y:ne(a,!0),ext:!0}}function xi(e,t,r,n){const i=Ki(e,t,r);return i.d=ne(n,!0),i}const Pi=X.getWebCrypto(),Ui=X.getNodeCrypto();async function Di(e,t,r,n,i,a){const s=new _i(e);if(r&&!X.isStream(r)){const e={publicKey:n,privateKey:i};switch(s.type){case"web":try{return await async function(e,t,r,n){const i=e.payloadSize,a=xi(e.payloadSize,bi[e.name],n.publicKey,n.privateKey),s=await Pi.importKey("jwk",a,{name:"ECDSA",namedCurve:bi[e.name],hash:{name:$.read($.webHash,e.hash)}},!1,["sign"]),o=new Uint8Array(await Pi.sign({name:"ECDSA",namedCurve:bi[e.name],hash:{name:$.read($.webHash,t)}},s,r));return{r:o.slice(0,i),s:o.slice(i,i<<1)}}(s,t,r,e)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;X.printDebugError("Browser did not support signing: "+e.message)}break;case"node":{const n=await async function(e,t,r,n){const i=Ui.createSign($.read($.hash,t));i.write(r),i.end();const a=Bi.encode({version:1,parameters:e.oid,privateKey:Array.from(n.privateKey),publicKey:{unused:0,data:Array.from(n.publicKey)}},"pem",{label:"EC PRIVATE KEY"});return Ti.decode(i.sign(a),"der")}(s,t,r,e);return{r:n.r.toArrayLike(Uint8Array),s:n.s.toArrayLike(Uint8Array)}}}}return async function(e,t,r){const n=await oi(e.name),i=ai(n,r),a=i.sign(t);return{r:a.r.toArrayLike(Uint8Array),s:a.s.toArrayLike(Uint8Array)}}(s,a,i)}async function Ci(e,t,r,n,i,a){const s=new _i(e);if(n&&!X.isStream(n))switch(s.type){case"web":try{return await async function(e,t,{r,s:n},i,a){const s=Ki(e.payloadSize,bi[e.name],a),o=await Pi.importKey("jwk",s,{name:"ECDSA",namedCurve:bi[e.name],hash:{name:$.read($.webHash,e.hash)}},!1,["verify"]),c=X.concatUint8Array([r,n]).buffer;return Pi.verify({name:"ECDSA",namedCurve:bi[e.name],hash:{name:$.read($.webHash,t)}},o,c,i)}(s,t,r,n,i)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;X.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":return async function(e,t,{r,s:n},i,a){const{default:s}=await import("./bn.min.mjs"),o=Ui.createVerify($.read($.hash,t));o.write(i),o.end();const c=Ri.encode({algorithm:{algorithm:[1,2,840,10045,2,1],parameters:e.oid},subjectPublicKey:{unused:0,data:Array.from(a)}},"pem",{label:"PUBLIC KEY"}),h=Ti.encode({r:new s(r),s:new s(n)},"der");try{return o.verify(c,h)}catch(e){return!1}}(s,t,r,n,i)}return async function(e,t,r,n){const i=await oi(e.name),a=si(i,n);return a.verify(r,t)}(s,r,void 0===t?n:a,i)}const Ii=void 0,Ti=Ui?Ii.define("ECDSASignature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())})):void 0,Bi=Ui?Ii.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().any(),this.key("publicKey").explicit(1).optional().bitstr())})):void 0,zi=Ui?Ii.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().any())})):void 0,Ri=Ui?Ii.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(zi),this.key("subjectPublicKey").bitstr())})):void 0;var Mi=/*#__PURE__*/Object.freeze({__proto__:null,sign:Di,verify:Ci,validateParams:async function(e,t,r){const n=new _i(e);if(n.keyType!==$.publicKey.ecdsa)return!1;switch(n.type){case"web":case"node":{const n=On(8),i=$.hash.sha256,a=await Gr.digest(i,n);try{const s=await Di(e,i,n,t,r,a);return await Ci(e,i,s,n,t,a)}catch(e){return!1}}default:return Ei($.publicKey.ecdsa,e,t,r)}}});Ln.hash=e=>new Uint8Array(Yt().update(e).digest());var Li=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,a){if(Gr.getHashByteLength(t)new Uint8Array(Yt().update(e).digest());var Oi=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===$.publicKey.ed25519){const e=On(32),{publicKey:t}=Ln.sign.keyPair.fromSeed(e);return{A:t,seed:e}}throw Error("Unsupported EdDSA algorithm")},sign:async function(e,t,r,n,i,a){if(Gr.getHashByteLength(t)=0;--e)for(let t=o-1;t>=0;--t)c[1]=o*e+(t+1),h[0]=a[0]^c[0],h[1]=a[1]^c[1],h[2]=s[2*t],h[3]=s[2*t+1],h=ji(r.decrypt(qi(h))),a=h.subarray(0,2),s[2*t]=h[2],s[2*t+1]=h[3];if(a[0]===n[0]&&a[1]===n[1])return qi(s);throw Error("Key Data Integrity failed")}function ji(e){const{length:t}=e,r=function(e){if(X.isString(e)){const{length:t}=e,r=new ArrayBuffer(t),n=new Uint8Array(r);for(let r=0;r0){const r=e[t-1];if(r>=1){const n=e.subarray(t-r),i=new Uint8Array(r).fill(r);if(X.equalsUint8Array(n,i))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var $i=/*#__PURE__*/Object.freeze({__proto__:null,encode:Vi,decode:Wi});const Zi=X.getWebCrypto(),Xi=X.getNodeCrypto();function Qi(e,t,r,n){return X.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),X.stringToUint8Array("Anonymous Sender "),n.subarray(0,20)])}async function Yi(e,t,r,n,i=!1,a=!1){let s;if(i){for(s=0;s=0&&0===t[s];s--);t=t.subarray(0,s+1)}return(await Gr.digest(e,X.concatUint8Array([new Uint8Array([0,0,0,1]),t,n]))).subarray(0,r)}async function Ji(e,t){switch(e.type){case"curve25519":{const r=On(32),{secretKey:n,sharedKey:i}=await ea(e,t,null,r);let{publicKey:a}=Ln.box.keyPair.fromSecretKey(n);return a=X.concatUint8Array([new Uint8Array([64]),a]),{publicKey:a,sharedKey:i}}case"web":if(e.web&&X.getWebCrypto())try{return await async function(e,t){const r=Ki(e.payloadSize,e.web.web,t);let n=Zi.generateKey({name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]),i=Zi.importKey("jwk",r,{name:"ECDH",namedCurve:e.web.web},!1,[]);[n,i]=await Promise.all([n,i]);let a=Zi.deriveBits({name:"ECDH",namedCurve:e.web.web,public:i},n.privateKey,e.web.sharedSize),s=Zi.exportKey("jwk",n.publicKey);[a,s]=await Promise.all([a,s]);const o=new Uint8Array(a),c=new Uint8Array(Si(s));return{publicKey:c,sharedKey:o}}(e,t)}catch(e){X.printDebugError(e)}break;case"node":return async function(e,t){const r=Xi.createECDH(e.node.node);r.generateKeys();const n=new Uint8Array(r.computeSecret(t)),i=new Uint8Array(r.getPublicKey());return{publicKey:i,sharedKey:n}}(e,t)}return async function(e,t){const r=await oi(e.name),n=await e.genKeyPair();t=si(r,t);const i=ai(r,n.privateKey),a=n.publicKey,s=i.derive(t.getPublic()),o=r.curve.p.byteLength(),c=s.toArrayLike(Uint8Array,"be",o);return{publicKey:a,sharedKey:c}}(e,t)}async function ea(e,t,r,n){if(n.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(n,e.payloadSize-n.length),n=t}switch(e.type){case"curve25519":{const e=n.slice().reverse();return{secretKey:e,sharedKey:Ln.scalarMult(e,t.subarray(1))}}case"web":if(e.web&&X.getWebCrypto())try{return await async function(e,t,r,n){const i=xi(e.payloadSize,e.web.web,r,n);let a=Zi.importKey("jwk",i,{name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]);const s=Ki(e.payloadSize,e.web.web,t);let o=Zi.importKey("jwk",s,{name:"ECDH",namedCurve:e.web.web},!0,[]);[a,o]=await Promise.all([a,o]);let c=Zi.deriveBits({name:"ECDH",namedCurve:e.web.web,public:o},a,e.web.sharedSize),h=Zi.exportKey("jwk",a);[c,h]=await Promise.all([c,h]);const u=new Uint8Array(c);return{secretKey:re(h.d),sharedKey:u}}(e,t,r,n)}catch(e){X.printDebugError(e)}break;case"node":return async function(e,t,r){const n=Xi.createECDH(e.node.node);n.setPrivateKey(r);const i=new Uint8Array(n.computeSecret(t));return{secretKey:new Uint8Array(n.getPrivateKey()),sharedKey:i}}(e,t,n)}return async function(e,t,r){const n=await oi(e.name);t=si(n,t),r=ai(n,r);const i=new Uint8Array(r.getPrivate()),a=r.derive(t.getPublic()),s=n.curve.p.byteLength(),o=a.toArrayLike(Uint8Array,"be",s);return{secretKey:i,sharedKey:o}}(e,t,n)}var ta=/*#__PURE__*/Object.freeze({__proto__:null,validateParams:async function(e,t,r){return Ei($.publicKey.ecdh,e,t,r)},encrypt:async function(e,t,r,n,i){const a=Vi(r),s=new _i(e),{publicKey:o,sharedKey:c}=await Ji(s,n),h=Qi($.publicKey.ecdh,e,t,i),{keySize:u}=Wr(t.cipher);return{publicKey:o,wrappedKey:Fi(await Yi(t.hash,c,u,h),a)}},decrypt:async function(e,t,r,n,i,a,s){const o=new _i(e),{sharedKey:c}=await ea(o,r,i,a),h=Qi($.publicKey.ecdh,e,t,s),{keySize:u}=Wr(t.cipher);let l;for(let e=0;e<3;e++)try{return Wi(Hi(await Yi(t.hash,c,u,h,1===e,2===e),n))}catch(e){l=e}throw l}});const ra=X.getWebCrypto(),na=X.getNodeCrypto(),ia=na&&na.webcrypto&&na.webcrypto.subtle;async function aa(e,t,r,n,i){const a=$.read($.webHash,e);if(!a)throw Error("Hash algo not supported with HKDF");if(ra||ia){const e=ra||ia,s=await e.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await e.deriveBits({name:"HKDF",hash:a,salt:r,info:n},s,8*i);return new Uint8Array(o)}if(na){const a=$.read($.hash,e),s=(e,t)=>na.createHmac(a,e).update(t).digest(),o=s(r,t),c=o.length,h=Math.ceil(i/c),u=new Uint8Array(h*c),l=new Uint8Array(c+n.length+1);l.set(n,c);for(let e=0;e0?l:l.subarray(c));l.set(t,0),u.set(t,e*c)}return u.subarray(0,i)}throw Error("No HKDF implementation available")}const sa={x25519:X.encodeUTF8("OpenPGP X25519")};var oa=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===$.publicKey.x25519){const e=On(32),{publicKey:t}=Ln.box.keyPair.fromSecretKey(e);return{A:t,k:e}}throw Error("Unsupported ECDH algorithm")},validateParams:async function(e,t,r){if(e===$.publicKey.x25519){const{publicKey:e}=Ln.box.keyPair.fromSecretKey(r);return X.equalsUint8Array(t,e)}return!1},encrypt:async function(e,t,r){if(e===$.publicKey.x25519){const e=On(32),n=Ln.scalarMult(e,r),{publicKey:i}=Ln.box.keyPair.fromSecretKey(e),a=X.concatUint8Array([i,r,n]),{keySize:s}=Wr($.symmetric.aes128);return{ephemeralPublicKey:i,wrappedKey:Fi(await aa($.hash.sha256,a,new Uint8Array,sa.x25519,s),t)}}throw Error("Unsupported ECDH algorithm")},decrypt:async function(e,t,r,n,i){if(e===$.publicKey.x25519){const e=Ln.scalarMult(i,t),a=X.concatUint8Array([t,n,e]),{keySize:s}=Wr($.symmetric.aes128);return Hi(await aa($.hash.sha256,a,new Uint8Array,sa.x25519,s),r)}throw Error("Unsupported ECDH algorithm")}}),ca=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:_i,ecdh:ta,ecdhX:oa,ecdsa:Mi,eddsaLegacy:Li,eddsa:Oi,generate:async function(e){const t=await X.getBigInteger();e=new _i(e);const r=await e.genKeyPair(),n=new t(r.publicKey).toUint8Array(),i=new t(r.privateKey).toUint8Array("be",e.payloadSize);return{oid:e.oid,Q:n,secret:i,hash:e.hash,cipher:e.cipher}},getPreferredHashAlgo:function(e){return Ai[$.write($.curve,e.toHex())].hash}});var ha=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,a){const s=await X.getBigInteger(),o=new s(1);let c,h,u,l;n=new s(n),i=new s(i),r=new s(r),a=new s(a),r=r.mod(n),a=a.mod(i);const y=new s(t.subarray(0,i.byteLength())).mod(i);for(;;){if(c=await Fn(o,i),h=r.modExp(c,n).imod(i),h.isZero())continue;const e=a.mul(h).imod(i);if(l=y.add(e).imod(i),u=c.modInv(i).imul(l).imod(i),!u.isZero())break}return{r:h.toUint8Array("be",i.byteLength()),s:u.toUint8Array("be",i.byteLength())}},verify:async function(e,t,r,n,i,a,s,o){const c=await X.getBigInteger(),h=new c(0);if(t=new c(t),r=new c(r),a=new c(a),s=new c(s),i=new c(i),o=new c(o),t.lte(h)||t.gte(s)||r.lte(h)||r.gte(s))return X.printDebug("invalid DSA Signature"),!1;const u=new c(n.subarray(0,s.byteLength())).imod(s),l=r.modInv(s);if(l.isZero())return X.printDebug("invalid DSA Signature"),!1;i=i.mod(a),o=o.mod(a);const y=u.mul(l).imod(s),d=t.mul(l).imod(s),p=i.modExp(y,a),f=o.modExp(d,a);return p.mul(f).imod(a).imod(s).equal(t)},validateParams:async function(e,t,r,n,i){const a=await X.getBigInteger();e=new a(e),t=new a(t),r=new a(r),n=new a(n);const s=new a(1);if(r.lte(s)||r.gte(e))return!1;if(!e.dec().mod(t).isZero())return!1;if(!r.modExp(t,e).isOne())return!1;const o=new a(t.bitLength()),c=new a(150);if(o.lt(c)||!await qn(t,null,32))return!1;i=new a(i);const h=new a(2),u=await Fn(h.leftShift(o.dec()),h.leftShift(o)),l=t.mul(u).add(i);return!!n.equal(r.modExp(l,e))}}),ua={rsa:ri,elgamal:ni,elliptic:ca,dsa:ha,nacl:Ln};var la=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:return{s:X.readMPI(t.subarray(r))};case $.publicKey.dsa:case $.publicKey.ecdsa:{const e=X.readMPI(t.subarray(r));r+=e.length+2;return{r:e,s:X.readMPI(t.subarray(r))}}case $.publicKey.eddsaLegacy:{let e=X.readMPI(t.subarray(r));r+=e.length+2,e=X.leftPad(e,32);let n=X.readMPI(t.subarray(r));return n=X.leftPad(n,32),{r:e,s:n}}case $.publicKey.ed25519:{const e=t.subarray(r,r+64);return r+=e.length,{RS:e}}default:throw new fi("Unknown signature algorithm.")}},verify:async function(e,t,r,n,i,a){switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:{const{n:e,e:s}=n,o=X.leftPad(r.s,e.length);return ua.rsa.verify(t,i,o,e,s,a)}case $.publicKey.dsa:{const{g:e,p:i,q:s,y:o}=n,{r:c,s:h}=r;return ua.dsa.verify(t,c,h,a,e,i,s,o)}case $.publicKey.ecdsa:{const{oid:e,Q:s}=n,o=new ua.elliptic.CurveWithOID(e).payloadSize,c=X.leftPad(r.r,o),h=X.leftPad(r.s,o);return ua.elliptic.ecdsa.verify(e,t,{r:c,s:h},i,s,a)}case $.publicKey.eddsaLegacy:{const{oid:e,Q:s}=n;return ua.elliptic.eddsaLegacy.verify(e,t,r,i,s,a)}case $.publicKey.ed25519:{const{A:s}=n;return ua.elliptic.eddsa.verify(e,t,r,i,s,a)}default:throw Error("Unknown signature algorithm.")}},sign:async function(e,t,r,n,i,a){if(!r||!n)throw Error("Missing key parameters");switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:{const{n:e,e:s}=r,{d:o,p:c,q:h,u}=n;return{s:await ua.rsa.sign(t,i,e,s,o,c,h,u,a)}}case $.publicKey.dsa:{const{g:e,p:i,q:s}=r,{x:o}=n;return ua.dsa.sign(t,a,e,i,s,o)}case $.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case $.publicKey.ecdsa:{const{oid:e,Q:s}=r,{d:o}=n;return ua.elliptic.ecdsa.sign(e,t,i,s,o,a)}case $.publicKey.eddsaLegacy:{const{oid:e,Q:s}=r,{seed:o}=n;return ua.elliptic.eddsaLegacy.sign(e,t,i,s,o,a)}case $.publicKey.ed25519:{const{A:s}=r,{seed:o}=n;return ua.elliptic.eddsa.sign(e,t,i,s,o,a)}default:throw Error("Unknown signature algorithm.")}}});class ya{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return X.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class da{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new fi("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class pa{static fromObject({wrappedKey:e,algorithm:t}){const r=new pa;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=e.subarray(t,t+r),t+=r}write(){return X.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function fa(e){try{e.getName()}catch(e){throw new fi("Unknown curve OID")}}var ga=/*#__PURE__*/Object.freeze({__proto__:null,publicKeyEncrypt:async function(e,t,r,n,i){switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await ua.rsa.encrypt(n,e,t)}}case $.publicKey.elgamal:{const{p:e,g:t,y:i}=r;return ua.elgamal.encrypt(n,e,t,i)}case $.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:a}=r,{publicKey:s,wrappedKey:o}=await ua.elliptic.ecdh.encrypt(e,a,n,t,i);return{V:s,C:new ya(o)}}case $.publicKey.x25519:{if(!X.isAES(t))throw Error("X25519 keys can only encrypt AES session keys");const{A:i}=r,{ephemeralPublicKey:a,wrappedKey:s}=await ua.elliptic.ecdhX.encrypt(e,n,i);return{ephemeralPublicKey:a,C:pa.fromObject({algorithm:t,wrappedKey:s})}}default:return[]}},publicKeyDecrypt:async function(e,t,r,n,i,a){switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:{const{c:e}=n,{n:i,e:s}=t,{d:o,p:c,q:h,u}=r;return ua.rsa.decrypt(e,i,s,o,c,h,u,a)}case $.publicKey.elgamal:{const{c1:e,c2:i}=n,s=t.p,o=r.x;return ua.elgamal.decrypt(e,i,s,o,a)}case $.publicKey.ecdh:{const{oid:e,Q:a,kdfParams:s}=t,{d:o}=r,{V:c,C:h}=n;return ua.elliptic.ecdh.decrypt(e,s,c,h.data,a,o,i)}case $.publicKey.x25519:{const{A:i}=t,{k:a}=r,{ephemeralPublicKey:s,C:o}=n;if(!X.isAES(o.algorithm))throw Error("AES session key expected");return ua.elliptic.ecdhX.decrypt(e,s,o.wrappedKey,i,a)}default:throw Error("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const n=X.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{n:e,e:n}}}case $.publicKey.dsa:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const n=X.readMPI(t.subarray(r));r+=n.length+2;const i=X.readMPI(t.subarray(r));r+=i.length+2;const a=X.readMPI(t.subarray(r));return r+=a.length+2,{read:r,publicParams:{p:e,q:n,g:i,y:a}}}case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const n=X.readMPI(t.subarray(r));r+=n.length+2;const i=X.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{p:e,g:n,y:i}}}case $.publicKey.ecdsa:{const e=new ii;r+=e.read(t),fa(e);const n=X.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{oid:e,Q:n}}}case $.publicKey.eddsaLegacy:{const e=new ii;r+=e.read(t),fa(e);let n=X.readMPI(t.subarray(r));return r+=n.length+2,n=X.leftPad(n,33),{read:r,publicParams:{oid:e,Q:n}}}case $.publicKey.ecdh:{const e=new ii;r+=e.read(t),fa(e);const n=X.readMPI(t.subarray(r));r+=n.length+2;const i=new da;return r+=i.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:n,kdfParams:i}}}case $.publicKey.ed25519:case $.publicKey.x25519:{const e=t.subarray(r,r+32);return r+=e.length,{read:r,publicParams:{A:e}}}default:throw new fi("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let n=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const e=X.readMPI(t.subarray(n));n+=e.length+2;const r=X.readMPI(t.subarray(n));n+=r.length+2;const i=X.readMPI(t.subarray(n));n+=i.length+2;const a=X.readMPI(t.subarray(n));return n+=a.length+2,{read:n,privateParams:{d:e,p:r,q:i,u:a}}}case $.publicKey.dsa:case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(n));return n+=e.length+2,{read:n,privateParams:{x:e}}}case $.publicKey.ecdsa:case $.publicKey.ecdh:{const e=new _i(r.oid);let i=X.readMPI(t.subarray(n));return n+=i.length+2,i=X.leftPad(i,e.payloadSize),{read:n,privateParams:{d:i}}}case $.publicKey.eddsaLegacy:{const e=new _i(r.oid);let i=X.readMPI(t.subarray(n));return n+=i.length+2,i=X.leftPad(i,e.payloadSize),{read:n,privateParams:{seed:i}}}case $.publicKey.ed25519:{const e=t.subarray(n,n+32);return n+=e.length,{read:n,privateParams:{seed:e}}}case $.publicKey.x25519:{const e=t.subarray(n,n+32);return n+=e.length,{read:n,privateParams:{k:e}}}default:throw new fi("Unknown public key encryption algorithm.")}},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:return{c:X.readMPI(t.subarray(r))};case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:X.readMPI(t.subarray(r))}}case $.publicKey.ecdh:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const n=new ya;return n.read(t.subarray(r)),{V:e,C:n}}case $.publicKey.x25519:{const e=t.subarray(r,r+32);r+=e.length;const n=new pa;return n.read(t.subarray(r)),{ephemeralPublicKey:e,C:n}}default:throw new fi("Unknown public key encryption algorithm.")}},serializeParams:function(e,t){const r=new Set([$.publicKey.ed25519,$.publicKey.x25519]),n=Object.keys(t).map((n=>{const i=t[n];return X.isUint8Array(i)?r.has(e)?i:X.uint8ArrayToMPI(i):i.write()}));return X.concatUint8Array(n)},generateParams:function(e,t,r){switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:return ua.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:n,q:i,u:a})=>({privateParams:{d:r,p:n,q:i,u:a},publicParams:{n:e,e:t}})));case $.publicKey.ecdsa:return ua.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new ii(e),Q:t}})));case $.publicKey.eddsaLegacy:return ua.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new ii(e),Q:t}})));case $.publicKey.ecdh:return ua.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:n,cipher:i})=>({privateParams:{d:r},publicParams:{oid:new ii(e),Q:t,kdfParams:new da({hash:n,cipher:i})}})));case $.publicKey.ed25519:return ua.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case $.publicKey.x25519:return ua.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case $.publicKey.dsa:case $.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const{n:e,e:n}=t,{d:i,p:a,q:s,u:o}=r;return ua.rsa.validateParams(e,n,i,a,s,o)}case $.publicKey.dsa:{const{p:e,q:n,g:i,y:a}=t,{x:s}=r;return ua.dsa.validateParams(e,n,i,a,s)}case $.publicKey.elgamal:{const{p:e,g:n,y:i}=t,{x:a}=r;return ua.elgamal.validateParams(e,n,i,a)}case $.publicKey.ecdsa:case $.publicKey.ecdh:{const n=ua.elliptic[$.read($.publicKey,e)],{oid:i,Q:a}=t,{d:s}=r;return n.validateParams(i,a,s)}case $.publicKey.eddsaLegacy:{const{Q:e,oid:n}=t,{seed:i}=r;return ua.elliptic.eddsaLegacy.validateParams(n,e,i)}case $.publicKey.ed25519:{const{A:n}=t,{seed:i}=r;return ua.elliptic.eddsa.validateParams(e,n,i)}case $.publicKey.x25519:{const{A:n}=t,{k:i}=r;return ua.elliptic.ecdhX.validateParams(e,n,i)}default:throw Error("Unknown public key algorithm.")}},getPrefixRandom:async function(e){const{blockSize:t}=Wr(e),r=await On(t),n=new Uint8Array([r[r.length-2],r[r.length-1]]);return X.concat([r,n])},generateSessionKey:function(e){const{keySize:t}=Wr(e);return On(t)},getAEADMode:function(e){const t=$.read($.aead,e);return Mn[t]},getCipher:Wr,getPreferredCurveHashAlgo:function(e,t){switch(e){case $.publicKey.ecdsa:case $.publicKey.eddsaLegacy:return ua.elliptic.getPreferredHashAlgo(t);case $.publicKey.ed25519:return ua.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}}});const ma={cipher:qe,hash:Gr,mode:Mn,publicKey:ua,signature:la,random:Hn,pkcs1:Xn,pkcs5:$i,aesKW:Gi};Object.assign(ma,ga);var wa="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function ba(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)}const ka={arraySet:function(e,t,r,n,i){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+n),i);else for(let a=0;a=0;)e[t]=0}const Xa=0,Qa=1,Ya=2,Ja=29,es=256,ts=es+1+Ja,rs=30,ns=19,is=2*ts+1,as=15,ss=16,os=7,cs=256,hs=16,us=17,ls=18,ys=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ds=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ps=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],fs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],gs=Array(2*(ts+2));Za(gs);const ms=Array(2*rs);Za(ms);const ws=Array(512);Za(ws);const bs=Array(256);Za(bs);const ks=Array(Ja);Za(ks);const vs=Array(rs);function As(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}let _s,Es,Ss;function Ks(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function xs(e){return e<256?ws[e]:ws[256+(e>>>7)]}function Ps(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Us(e,t,r){e.bi_valid>ss-r?(e.bi_buf|=t<>ss-e.bi_valid,e.bi_valid+=r-ss):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Is(e,t,r){const n=Array(as+1);let i,a,s=0;for(i=1;i<=as;i++)n[i]=s=s+r[i-1]<<1;for(a=0;a<=t;a++){const t=e[2*a+1];0!==t&&(e[2*a]=Cs(n[t]++,t))}}function Ts(e){let t;for(t=0;t8?Ps(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function zs(e,t,r,n){const i=2*t,a=2*r;return e[i]>1;s>=1;s--)Rs(e,r,s);c=a;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Rs(e,r,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,r[2*c]=r[2*s]+r[2*o],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,r[2*s+1]=r[2*o+1]=c,e.heap[1]=c++,Rs(e,r,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){const r=t.dyn_tree,n=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let h,u,l,y,d,p,f=0;for(y=0;y<=as;y++)e.bl_count[y]=0;for(r[2*e.heap[e.heap_max]+1]=0,h=e.heap_max+1;hc&&(y=c,f++),r[2*u+1]=y,u>n||(e.bl_count[y]++,d=0,u>=o&&(d=s[u-o]),p=r[2*u],e.opt_len+=p*(y+d),a&&(e.static_len+=p*(i[2*u+1]+d)));if(0!==f){do{for(y=c-1;0===e.bl_count[y];)y--;e.bl_count[y]--,e.bl_count[y+1]+=2,e.bl_count[c]--,f-=2}while(f>0);for(y=c;0!==y;y--)for(u=e.bl_count[y];0!==u;)l=e.heap[--h],l>n||(r[2*l+1]!==y&&(e.opt_len+=(y-r[2*l+1])*r[2*l],r[2*l+1]=y),u--)}}(e,t),Is(r,h,e.bl_count)}function Ns(e,t,r){let n,i,a=-1,s=t[1],o=0,c=7,h=4;for(0===s&&(c=138,h=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=s,s=t[2*(n+1)+1],++o>=7;n=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function Gs(e,t,r,n){let i,a,s=0;e.level>0?(e.strm.data_type===Wa&&(e.strm.data_type=function(e){let t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return Ga;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return Va;for(t=32;t=3&&0===e.bl_tree[2*fs[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=i&&(i=a)):i=a=r+5,r+4<=i&&-1!==t?js(e,t,r,n):e.strategy===qa||a===i?(Us(e,(Qa<<1)+(n?1:0),3),Ms(e,gs,ms)):(Us(e,(Ya<<1)+(n?1:0),3),function(e,t,r,n){let i;for(Us(e,t-257,5),Us(e,r-1,5),Us(e,n-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(bs[r]+es+1)]++,e.dyn_dtree[2*xs(t)]++),e.last_lit===e.lit_bufsize-1}function Ws(e,t,r,n){let i=65535&e|0,a=e>>>16&65535|0,s=0;for(;0!==r;){s=r>2e3?2e3:r,r-=s;do{i=i+t[n++]|0,a=a+i|0}while(--s);i%=65521,a%=65521}return i|a<<16|0}const $s=function(){let e;const t=[];for(let r=0;r<256;r++){e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function Zs(e,t,r,n){const i=$s,a=n+r;e^=-1;for(let r=n;r>>8^i[255&(e^t[r])];return-1^e}var Xs={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};const Qs=9,Ys=3,Js=258,eo=Js+Ys+1,to=32,ro=42,no=69,io=73,ao=91,so=103,oo=113,co=666,ho=1,uo=2,lo=3,yo=4,po=3;function fo(e,t){return e.msg=Xs[t],t}function go(e){return(e<<1)-(e>4?9:0)}function mo(e){let t=e.length;for(;--t>=0;)e[t]=0}function wo(e){const t=e.state;let r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(Ka(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function bo(e,t){Gs(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,wo(e.strm)}function ko(e,t){e.pending_buf[e.pending++]=t}function vo(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Ao(e,t,r,n){let i=e.avail_in;return i>n&&(i=n),0===i?0:(e.avail_in-=i,Ka(t,e.input,e.next_in,i,r),1===e.state.wrap?e.adler=Ws(e.adler,t,i,r):2===e.state.wrap&&(e.adler=Zs(e.adler,t,i,r)),e.next_in+=i,e.total_in+=i,i)}function _o(e,t){let r,n,i=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-eo?e.strstart-(e.w_size-eo):0,h=e.window,u=e.w_mask,l=e.prev,y=e.strstart+Js;let d=h[a+s-1],p=h[a+s];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do{if(r=t,h[r+s]===p&&h[r+s-1]===d&&h[r]===h[a]&&h[++r]===h[a+1]){a+=2,r++;do{}while(h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&h[++a]===h[++r]&&as){if(e.match_start=t,s=n,n>=o)break;d=h[a+s-1],p=h[a+s]}}}while((t=l[t&u])>c&&0!=--i);return s<=e.lookahead?s:e.lookahead}function Eo(e){const t=e.w_size;let r,n,i,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-eo)){Ka(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,r=n;do{i=e.head[--r],e.head[r]=i>=t?i-t:0}while(--n);n=t,r=n;do{i=e.prev[--r],e.prev[r]=i>=t?i-t:0}while(--n);a+=t}if(0===e.strm.avail_in)break;if(n=Ao(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=Ys)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=Ys&&(e.ins_h=(e.ins_h<=Ys)if(n=Vs(e,e.strstart-e.match_start,e.match_length-Ys),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=Ys){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=Ys&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=Ys-1)),e.prev_length>=Ys&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-Ys,n=Vs(e,e.strstart-1-e.prev_match,e.prev_length-Ys),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=i&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Eo(e),0===e.lookahead&&t===xa)return ho;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;const n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,bo(e,!1),0===e.strm.avail_out))return ho;if(e.strstart-e.block_start>=e.w_size-eo&&(bo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ca?(bo(e,!0),0===e.strm.avail_out?lo:yo):(e.strstart>e.block_start&&(bo(e,!1),e.strm.avail_out),ho)})),new xo(4,4,8,4,So),new xo(4,5,16,8,So),new xo(4,6,32,32,So),new xo(4,4,16,16,Ko),new xo(8,16,32,32,Ko),new xo(8,16,128,128,Ko),new xo(8,32,128,256,Ko),new xo(32,128,258,1024,Ko),new xo(32,258,258,4096,Ko)];class Uo{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$a,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new _a(1146),this.dyn_dtree=new _a(122),this.bl_tree=new _a(78),mo(this.dyn_ltree),mo(this.dyn_dtree),mo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new _a(16),this.heap=new _a(573),mo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new _a(573),mo(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}}function Do(e){const t=function(e){let t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=Wa,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?ro:oo,e.adler=2===t.wrap?0:1,t.last_flush=xa,Hs(t),Ba):fo(e,Ma)}(e);return t===Ba&&function(e){e.window_size=2*e.w_size,mo(e.head),e.max_lazy_match=Po[e.level].max_lazy,e.good_match=Po[e.level].good_length,e.nice_match=Po[e.level].nice_length,e.max_chain_length=Po[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=Ys-1,e.match_available=0,e.ins_h=0}(e.state),t}function Co(e,t){let r,n,i,a;if(!e||!e.state||t>Ia||t<0)return e?fo(e,Ma):Ma;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||n.status===co&&t!==Ca)return fo(e,0===e.avail_out?Na:Ma);if(n.strm=e,r=n.last_flush,n.last_flush=t,n.status===ro)if(2===n.wrap)e.adler=0,ko(n,31),ko(n,139),ko(n,8),n.gzhead?(ko(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),ko(n,255&n.gzhead.time),ko(n,n.gzhead.time>>8&255),ko(n,n.gzhead.time>>16&255),ko(n,n.gzhead.time>>24&255),ko(n,9===n.level?2:n.strategy>=Ha||n.level<2?4:0),ko(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(ko(n,255&n.gzhead.extra.length),ko(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=Zs(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=no):(ko(n,0),ko(n,0),ko(n,0),ko(n,0),ko(n,0),ko(n,9===n.level?2:n.strategy>=Ha||n.level<2?4:0),ko(n,po),n.status=oo);else{let t=$a+(n.w_bits-8<<4)<<8,r=-1;r=n.strategy>=Ha||n.level<2?0:n.level<6?1:6===n.level?2:3,t|=r<<6,0!==n.strstart&&(t|=to),t+=31-t%31,n.status=oo,vo(n,t),0!==n.strstart&&(vo(n,e.adler>>>16),vo(n,65535&e.adler)),e.adler=1}if(n.status===no)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending!==n.pending_buf_size));)ko(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=io)}else n.status=io;if(n.status===io)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindexi&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),0===a&&(n.gzindex=0,n.status=ao)}else n.status=ao;if(n.status===ao)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindexi&&(e.adler=Zs(e.adler,n.pending_buf,n.pending-i,i)),0===a&&(n.status=so)}else n.status=so;if(n.status===so&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&wo(e),n.pending+2<=n.pending_buf_size&&(ko(n,255&e.adler),ko(n,e.adler>>8&255),e.adler=0,n.status=oo)):n.status=oo),0!==n.pending){if(wo(e),0===e.avail_out)return n.last_flush=-1,Ba}else if(0===e.avail_in&&go(t)<=go(r)&&t!==Ca)return fo(e,Na);if(n.status===co&&0!==e.avail_in)return fo(e,Na);if(0!==e.avail_in||0!==n.lookahead||t!==xa&&n.status!==co){var s=n.strategy===Ha?function(e,t){let r;for(;;){if(0===e.lookahead&&(Eo(e),0===e.lookahead)){if(t===xa)return ho;break}if(e.match_length=0,r=Vs(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(bo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ca?(bo(e,!0),0===e.strm.avail_out?lo:yo):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?ho:uo}(n,t):n.strategy===ja?function(e,t){let r,n,i,a;const s=e.window;for(;;){if(e.lookahead<=Js){if(Eo(e),e.lookahead<=Js&&t===xa)return ho;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=Ys&&e.strstart>0&&(i=e.strstart-1,n=s[i],n===s[++i]&&n===s[++i]&&n===s[++i])){a=e.strstart+Js;do{}while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&ie.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=Ys?(r=Vs(e,1,e.match_length-Ys),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=Vs(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(bo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ca?(bo(e,!0),0===e.strm.avail_out?lo:yo):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?ho:uo}(n,t):Po[n.level].func(n,t);if(s!==lo&&s!==yo||(n.status=co),s===ho||s===lo)return 0===e.avail_out&&(n.last_flush=-1),Ba;if(s===uo&&(t===Pa?qs(n):t!==Ia&&(js(n,0,0,!1),t===Da&&(mo(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),wo(e),0===e.avail_out))return n.last_flush=-1,Ba}return t!==Ca?Ba:n.wrap<=0?za:(2===n.wrap?(ko(n,255&e.adler),ko(n,e.adler>>8&255),ko(n,e.adler>>16&255),ko(n,e.adler>>24&255),ko(n,255&e.total_in),ko(n,e.total_in>>8&255),ko(n,e.total_in>>16&255),ko(n,e.total_in>>24&255)):(vo(n,e.adler>>>16),vo(n,65535&e.adler)),wo(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Ba:za)}try{String.fromCharCode.call(null,0)}catch(e){}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}const Io=new Aa(256);for(let e=0;e<256;e++)Io[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;function To(e){let t,r,n,i,a=0;const s=e.length;for(n=0;n>>6,o[i++]=128|63&t):t<65536?(o[i++]=224|t>>>12,o[i++]=128|t>>>6&63,o[i++]=128|63&t):(o[i++]=240|t>>>18,o[i++]=128|t>>>12&63,o[i++]=128|t>>>6&63,o[i++]=128|63&t);return o}Io[254]=Io[254]=1;class Bo{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}class zo{constructor(e){this.options={level:Oa,method:$a,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,...e||{}};const t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Bo,this.strm.avail_out=0;var r,n,i=function(e,t,r,n,i,a){if(!e)return Ma;let s=1;if(t===Oa&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),i<1||i>Qs||r!==$a||n<8||n>15||t<0||t>9||a<0||a>qa)return fo(e,Ma);8===n&&(n=9);const o=new Uo;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=n,o.w_size=1<=r.w_size&&(0===a&&(mo(r.head),r.strstart=0,r.block_start=0,r.insert=0),h=new Aa(r.w_size),Ka(h,t,u-r.w_size,r.w_size,0),t=h,u=r.w_size),s=e.avail_in,o=e.next_in,c=e.input,e.avail_in=u,e.next_in=0,e.input=t,Eo(r);r.lookahead>=Ys;){n=r.strstart,i=r.lookahead-(Ys-1);do{r.ins_h=(r.ins_h<0||0===r.avail_out)&&i!==za);return a===Ca?(i=function(e){let t;return e&&e.state?(t=e.state.status,t!==ro&&t!==no&&t!==io&&t!==ao&&t!==so&&t!==oo&&t!==co?fo(e,Ma):(e.state=null,t===oo?fo(e,La):Ba)):Ma}(this.strm),this.onEnd(i),this.ended=!0,i===Ba):a!==Ua||(this.onEnd(Ba),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ba&&(this.result=Sa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}const Ro=30,Mo=12;function Lo(e,t){let r,n,i,a,s,o,c,h,u,l;const y=e.state;r=e.next_in;const d=e.input,p=r+(e.avail_in-5);n=e.next_out;const f=e.output,g=n-(t-e.avail_out),m=n+(e.avail_out-257),w=y.dmax,b=y.wsize,k=y.whave,v=y.wnext,A=y.window;i=y.hold,a=y.bits;const _=y.lencode,E=y.distcode,S=(1<>>24,i>>>=o,a-=o,o=s>>>16&255,0===o)f[n++]=65535&s;else{if(!(16&o)){if(0==(64&o)){s=_[(65535&s)+(i&(1<>>=o,a-=o),a<15&&(i+=d[r++]<>>24,i>>>=o,a-=o,o=s>>>16&255,!(16&o)){if(0==(64&o)){s=E[(65535&s)+(i&(1<w){e.msg="invalid distance too far back",y.mode=Ro;break e}if(i>>>=o,a-=o,o=n-g,h>o){if(o=h-o,o>k&&y.sane){e.msg="invalid distance too far back",y.mode=Ro;break e}if(u=0,l=A,0===v){if(u+=b-o,o2;)f[n++]=l[u++],f[n++]=l[u++],f[n++]=l[u++],c-=3;c&&(f[n++]=l[u++],c>1&&(f[n++]=l[u++]))}else{u=n-h;do{f[n++]=f[u++],f[n++]=f[u++],f[n++]=f[u++],c-=3}while(c>2);c&&(f[n++]=f[u++],c>1&&(f[n++]=f[u++]))}break}}break}}while(r>3,r-=c,a-=c<<3,i&=(1<=1&&0===K[m];m--);if(w>m&&(w=m),0===m)return i[a++]=20971520,i[a++]=20971520,o.bits=1,0;for(g=1;g0&&(e===Ho||1!==m))return-1;for(x[1]=0,p=1;pOo||e===qo&&A>Fo)return 1;for(;;){P=p-k,s[f]d?(U=C[I+s[f]],D=E[S+s[f]]):(U=96,D=0),h=1<>k)+u]=P<<24|U<<16|D|0}while(0!==u);for(h=1<>=1;if(0!==h?(_&=h-1,_+=h):_=0,f++,0==--K[p]){if(p===m)break;p=t[r+s[f]]}if(p>w&&(_&T)!==l){for(0===k&&(k=w),y+=g,b=p-k,v=1<Oo||e===qo&&A>Fo)return 1;l=_&T,i[l]=w<<24|b<<16|y-a|0}}return 0!==_&&(i[y+_]=p-k<<24|64<<16|0),o.bits=w,0}const Xo=0,Qo=1,Yo=2,Jo=1,ec=2,tc=3,rc=4,nc=5,ic=6,ac=7,sc=8,oc=9,cc=10,hc=11,uc=12,lc=13,yc=14,dc=15,pc=16,fc=17,gc=18,mc=19,wc=20,bc=21,kc=22,vc=23,Ac=24,_c=25,Ec=26,Sc=27,Kc=28,xc=29,Pc=30,Uc=852,Dc=592;function Cc(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}class Ic{constructor(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new _a(320),this.work=new _a(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}}function Tc(e){let t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,function(e){let t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Jo,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Ea(Uc),t.distcode=t.distdyn=new Ea(Dc),t.sane=1,t.back=-1,Ba):Ma}(e)):Ma}function Bc(e,t){let r,n;return e?(n=new Ic,e.state=n,n.window=null,r=function(e,t){let r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ma:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,Tc(e))):Ma}(e,t),r!==Ba&&(e.state=null),r):Ma}let zc,Rc,Mc=!0;function Lc(e){if(Mc){let t;for(zc=new Ea(512),Rc=new Ea(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Zo(Qo,e.lens,0,288,zc,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Zo(Yo,e.lens,0,32,Rc,0,e.work,{bits:5}),Mc=!1}e.lencode=zc,e.lenbits=9,e.distcode=Rc,e.distbits=5}function Nc(e,t,r,n){let i;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(Ka(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>n&&(i=n),Ka(a.window,t,r-n,i,a.wnext),(n-=i)?(Ka(a.window,t,r-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=Zs(r.check,x,2,0),h=0,u=0,r.mode=ec;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",r.mode=Pc;break}if((15&h)!==$a){e.msg="unknown compression method",r.mode=Pc;break}if(h>>>=4,u-=4,A=8+(15&h),0===r.wbits)r.wbits=A;else if(A>r.wbits){e.msg="invalid window size",r.mode=Pc;break}r.dmax=1<>8&1),512&r.flags&&(x[0]=255&h,x[1]=h>>>8&255,r.check=Zs(r.check,x,2,0)),h=0,u=0,r.mode=tc;case tc:for(;u<32;){if(0===o)break e;o--,h+=n[a++]<>>8&255,x[2]=h>>>16&255,x[3]=h>>>24&255,r.check=Zs(r.check,x,4,0)),h=0,u=0,r.mode=rc;case rc:for(;u<16;){if(0===o)break e;o--,h+=n[a++]<>8),512&r.flags&&(x[0]=255&h,x[1]=h>>>8&255,r.check=Zs(r.check,x,2,0)),h=0,u=0,r.mode=nc;case nc:if(1024&r.flags){for(;u<16;){if(0===o)break e;o--,h+=n[a++]<>>8&255,r.check=Zs(r.check,x,2,0)),h=0,u=0}else r.head&&(r.head.extra=null);r.mode=ic;case ic:if(1024&r.flags&&(d=r.length,d>o&&(d=o),d&&(r.head&&(A=r.head.extra_len-r.length,r.head.extra||(r.head.extra=Array(r.head.extra_len)),Ka(r.head.extra,n,a,d,A)),512&r.flags&&(r.check=Zs(r.check,n,d,a)),o-=d,a+=d,r.length-=d),r.length))break e;r.length=0,r.mode=ac;case ac:if(2048&r.flags){if(0===o)break e;d=0;do{A=n[a+d++],r.head&&A&&r.length<65536&&(r.head.name+=String.fromCharCode(A))}while(A&&d>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=uc;break;case cc:for(;u<32;){if(0===o)break e;o--,h+=n[a++]<>>=7&u,u-=7&u,r.mode=Sc;break}for(;u<3;){if(0===o)break e;o--,h+=n[a++]<>>=1,u-=1,3&h){case 0:r.mode=yc;break;case 1:if(Lc(r),r.mode=wc,t===Ta){h>>>=2,u-=2;break e}break;case 2:r.mode=fc;break;case 3:e.msg="invalid block type",r.mode=Pc}h>>>=2,u-=2;break;case yc:for(h>>>=7&u,u-=7&u;u<32;){if(0===o)break e;o--,h+=n[a++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=Pc;break}if(r.length=65535&h,h=0,u=0,r.mode=dc,t===Ta)break e;case dc:r.mode=pc;case pc:if(d=r.length,d){if(d>o&&(d=o),d>c&&(d=c),0===d)break e;Ka(i,n,a,d,s),o-=d,a+=d,c-=d,s+=d,r.length-=d;break}r.mode=uc;break;case fc:for(;u<14;){if(0===o)break e;o--,h+=n[a++]<>>=5,u-=5,r.ndist=1+(31&h),h>>>=5,u-=5,r.ncode=4+(15&h),h>>>=4,u-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Pc;break}r.have=0,r.mode=gc;case gc:for(;r.have>>=3,u-=3}for(;r.have<19;)r.lens[P[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,E={bits:r.lenbits},_=Zo(Xo,r.lens,0,19,r.lencode,0,r.work,E),r.lenbits=E.bits,_){e.msg="invalid code lengths set",r.mode=Pc;break}r.have=0,r.mode=mc;case mc:for(;r.have>>24,m=K>>>16&255,w=65535&K,!(g<=u);){if(0===o)break e;o--,h+=n[a++]<>>=g,u-=g,r.lens[r.have++]=w;else{if(16===w){for(S=g+2;u>>=g,u-=g,0===r.have){e.msg="invalid bit length repeat",r.mode=Pc;break}A=r.lens[r.have-1],d=3+(3&h),h>>>=2,u-=2}else if(17===w){for(S=g+3;u>>=g,u-=g,A=0,d=3+(7&h),h>>>=3,u-=3}else{for(S=g+7;u>>=g,u-=g,A=0,d=11+(127&h),h>>>=7,u-=7}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Pc;break}for(;d--;)r.lens[r.have++]=A}}if(r.mode===Pc)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=Pc;break}if(r.lenbits=9,E={bits:r.lenbits},_=Zo(Qo,r.lens,0,r.nlen,r.lencode,0,r.work,E),r.lenbits=E.bits,_){e.msg="invalid literal/lengths set",r.mode=Pc;break}if(r.distbits=6,r.distcode=r.distdyn,E={bits:r.distbits},_=Zo(Yo,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,E),r.distbits=E.bits,_){e.msg="invalid distances set",r.mode=Pc;break}if(r.mode=wc,t===Ta)break e;case wc:r.mode=bc;case bc:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,r.hold=h,r.bits=u,Lo(e,y),s=e.next_out,i=e.output,c=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,h=r.hold,u=r.bits,r.mode===uc&&(r.back=-1);break}for(r.back=0;K=r.lencode[h&(1<>>24,m=K>>>16&255,w=65535&K,!(g<=u);){if(0===o)break e;o--,h+=n[a++]<>b)],g=K>>>24,m=K>>>16&255,w=65535&K,!(b+g<=u);){if(0===o)break e;o--,h+=n[a++]<>>=b,u-=b,r.back+=b}if(h>>>=g,u-=g,r.back+=g,r.length=w,0===m){r.mode=Ec;break}if(32&m){r.back=-1,r.mode=uc;break}if(64&m){e.msg="invalid literal/length code",r.mode=Pc;break}r.extra=15&m,r.mode=kc;case kc:if(r.extra){for(S=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=vc;case vc:for(;K=r.distcode[h&(1<>>24,m=K>>>16&255,w=65535&K,!(g<=u);){if(0===o)break e;o--,h+=n[a++]<>b)],g=K>>>24,m=K>>>16&255,w=65535&K,!(b+g<=u);){if(0===o)break e;o--,h+=n[a++]<>>=b,u-=b,r.back+=b}if(h>>>=g,u-=g,r.back+=g,64&m){e.msg="invalid distance code",r.mode=Pc;break}r.offset=w,r.extra=15&m,r.mode=Ac;case Ac:if(r.extra){for(S=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Pc;break}r.mode=_c;case _c:if(0===c)break e;if(d=y-c,r.offset>d){if(d=r.offset-d,d>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Pc;break}d>r.wnext?(d-=r.wnext,p=r.wsize-d):p=r.wnext-d,d>r.length&&(d=r.length),f=r.window}else f=i,p=s-r.offset,d=r.length;d>c&&(d=c),c-=d,r.length-=d;do{i[s++]=f[p++]}while(--d);0===r.length&&(r.mode=bc);break;case Ec:if(0===c)break e;i[s++]=r.length,c--,r.mode=bc;break;case Sc:if(r.wrap){for(;u<32;){if(0===o)break e;o--,h|=n[a++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Bo,this.strm.avail_out=0;let r=Bc(this.strm,t.windowBits);if(r!==Ba)throw Error(Xs[r]);if(this.header=new Hc,function(e,t){let r;e&&e.state&&(r=e.state,0==(2&r.wrap)||(r.head=t,t.done=!1))}(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=To(t.dictionary):t.dictionary instanceof ArrayBuffer&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=Fc(this.strm,t.dictionary),r!==Ba)))throw Error(Xs[r])}push(e,t){const{strm:r,options:{chunkSize:n,dictionary:i}}=this;let a,s,o=!1;if(this.ended)return!1;s=t===~~t?t:!0===t?Ca:xa,"string"==typeof e?r.input=function(e){const t=new Aa(e.length);for(let r=0,n=t.length;r0||0===r.avail_out)&&a!==za);return a===za&&(s=Ca),s===Ca?(a=function(e){if(!e||!e.state)return Ma;const t=e.state;return t.window&&(t.window=null),e.state=null,Ba}(this.strm),this.onEnd(a),this.ended=!0,a===Ba):s!==Ua||(this.onEnd(Ba),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ba&&(this.result=Sa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}var qc=[0,1,3,7,15,31,63,127,255],Gc=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};Gc.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},Gc.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=qc[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var n=r-e;t|=(this.curByte&qc[e]<>n,this.bitOffset+=e,e=0}}return t},Gc.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},Gc.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var Vc=Gc,Wc=function(){};Wc.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},Wc.prototype.read=function(e,t,r){for(var n=0;n>>0},this.updateCRC=function(t){e=e<<8^$c[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^$c[255&(e>>>24^t)]}}),Qc=function(e,t){var r,n=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=n,n},Yc={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},Jc={};Jc[Yc.LAST_BLOCK]="Bad file checksum",Jc[Yc.NOT_BZIP_DATA]="Not bzip data",Jc[Yc.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",Jc[Yc.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",Jc[Yc.DATA_ERROR]="Data error",Jc[Yc.OUT_OF_MEMORY]="Out of memory",Jc[Yc.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var eh=function(e,t){var r=Jc[e]||"unknown error";t&&(r+=": "+t);var n=new TypeError(r);throw n.errorCode=e,n},th=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};th.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Xc,!0):(this.writeCount=-1,!1)},th.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||eh(Yc.NOT_BZIP_DATA,"bad magic");var n=r[3]-48;(n<1||n>9)&&eh(Yc.NOT_BZIP_DATA,"level out of range"),this.reader=new Vc(e),this.dbufSize=1e5*n,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},th.prototype._get_next_block=function(){var e,t,r,n=this.reader,i=n.pi();if("177245385090"===i)return!1;"314159265359"!==i&&eh(Yc.NOT_BZIP_DATA),this.targetBlockCRC=n.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,n.read(1)&&eh(Yc.OBSOLETE_INPUT);var a=n.read(24);a>this.dbufSize&&eh(Yc.DATA_ERROR,"initial position out of bounds");var s=n.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(s&1<<15-e){var h=16*e;for(r=n.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=h+t)}var u=n.read(3);(u<2||u>6)&&eh(Yc.DATA_ERROR);var l=n.read(15);0===l&&eh(Yc.DATA_ERROR);var y=new Uint8Array(256);for(e=0;e=u&&eh(Yc.DATA_ERROR);d[e]=Qc(y,t)}var p,f=c+2,g=[];for(t=0;t20)&&eh(Yc.DATA_ERROR),n.read(1);)n.read(1)?s--:s++;b[e]=s}for(m=w=b[0],e=1;ew?w=b[e]:b[e]=l&&eh(Yc.DATA_ERROR),p=g[d[K++]]),e=p.minLen,t=n.read(e);e>p.maxLen&&eh(Yc.DATA_ERROR),!(t<=p.limit[e]);e++)t=t<<1|n.read(1);((t-=p.base[e])<0||t>=258)&&eh(Yc.DATA_ERROR);var P=p.permute[t];if(0!==P&&1!==P){if(E)for(E=0,S+s>this.dbufSize&&eh(Yc.DATA_ERROR),A[_=o[y[0]]]+=s;s--;)x[S++]=_;if(P>c)break;S>=this.dbufSize&&eh(Yc.DATA_ERROR),A[_=o[_=Qc(y,e=P-1)]]++,x[S++]=_}else E||(E=1,s=0),s+=0===P?E:2*E,E<<=1}for((a<0||a>=S)&&eh(Yc.DATA_ERROR),t=0,e=0;e<256;e++)r=t+A[e],A[e]=t,t=r;for(e=0;e>=8,C=-1),this.writePos=U,this.writeCurrent=D,this.writeCount=S,this.writeRun=C,!0},th.prototype._read_bunzip=function(e,t){var r,n,i;if(this.writeCount<0)return 0;var a=this.dbuf,s=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var h=this.writeRun;c;){for(c--,n=o,o=255&(s=a[s]),s>>=8,3==h++?(r=o,i=n,o=-1):(r=1,i=o),this.blockCRC.updateCRCRun(i,r);r--;)this.outputStream.writeByte(i),this.nextoutput++;o!=n&&(h=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&eh(Yc.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var rh=function(e){if("readByte"in e)return e;var t=new Zc;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},nh=function(e){var t=new Zc,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var ih=function(e,t,r){for(var n=rh(e),i=nh(t),a=new th(n,i);!("eof"in n)||!n.eof();)if(a._init_block())a._read_bunzip();else{var s=a.reader.read(32)>>>0;if(s!==a.streamCRC&&eh(Yc.DATA_ERROR,"Bad stream CRC (got "+a.streamCRC.toString(16)+" expected "+s.toString(16)+")"),!r||!("eof"in n)||n.eof())break;a._start_bunzip(n,i)}if("getBuffer"in i)return i.getBuffer()};class ah{static get tag(){return $.packet.literalData}constructor(e=new Date){this.format=$.literal.utf8,this.date=X.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=$.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||X.isStream(this.text))&&(this.text=X.decodeUTF8(X.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=X.canonicalizeEOL(X.encodeUTF8(this.text))),e?N(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await M(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=X.decodeUTF8(await e.readBytes(r)),this.date=X.readDate(await e.readBytes(4));let n=e.remainder();s(n)&&(n=await H(n)),this.setBytes(n,t)}))}writeHeader(){const e=X.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),n=X.writeDate(this.date);return X.concatUint8Array([r,t,e,n])}write(){const e=this.writeHeader(),t=this.getBytes();return X.concat([e,t])}}const sh=Symbol("verified"),oh=new Set([$.signatureSubpacket.issuer,$.signatureSubpacket.issuerFingerprint,$.signatureSubpacket.embeddedSignature]);class ch{static get tag(){return $.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.signedHashValue=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new pe,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.revoked=null,this[sh]=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version)throw new fi(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[t++],this.publicKeyAlgorithm=e[t++],this.hashAlgorithm=e[t++],t+=this.readSubPackets(e.subarray(t,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");this.signatureData=e.subarray(0,t),t+=this.readSubPackets(e.subarray(t,e.length),!1),this.signedHashValue=e.subarray(t,t+2),t+=2,this.params=ma.signature.parseSignatureParams(this.publicKeyAlgorithm,e.subarray(t,e.length))}writeParams(){return this.params instanceof Promise?q((async()=>ma.serializeParams(this.publicKeyAlgorithm,await this.params))):ma.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),e.push(this.writeParams()),X.concat(e)}async sign(e,t,r=new Date,n=!1){5===e.version?this.version=5:this.version=4;const i=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];this.created=X.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID(),i.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=X.concat(i);const a=this.toHash(this.signatureType,t,n),s=await this.hash(this.signatureType,t,a,n);this.signedHashValue=F(L(s),0,2);const o=async()=>ma.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await H(s));X.isStream(s)?this.params=o():(this.params=await o(),this[sh]=!0)}writeHashedSubPackets(){const e=$.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(hh(e.signatureCreationTime,!0,X.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(hh(e.signatureExpirationTime,!0,X.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(hh(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(hh(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(hh(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(hh(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(hh(e.keyExpirationTime,!0,X.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(hh(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=X.concat([r,this.revocationKeyFingerprint]),t.push(hh(e.revocationKey,!1,r))),this.issuerKeyID.isNull()||5===this.issuerKeyVersion||t.push(hh(e.issuer,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:n,value:i,humanReadable:a,critical:s})=>{r=[new Uint8Array([a?128:0,0,0,0])];const o=X.encodeUTF8(n);r.push(X.writeNumber(o.length,2)),r.push(X.writeNumber(i.length,2)),r.push(o),r.push(i),r=X.concat(r),t.push(hh(e.notationData,s,r))})),null!==this.preferredHashAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(hh(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(hh(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.keyServerPreferences)),t.push(hh(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(hh(e.preferredKeyServer,!1,X.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(hh(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(hh(e.policyURI,!1,X.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.keyFlags)),t.push(hh(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(hh(e.signersUserID,!1,X.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=X.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(hh(e.reasonForRevocation,!0,r))),null!==this.features&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.features)),t.push(hh(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(X.stringToUint8Array(this.signatureTargetHash)),r=X.concat(r),t.push(hh(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(hh(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=X.concat(r),t.push(hh(e.issuerFingerprint,5===this.version,r))),null!==this.preferredAEADAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(hh(e.preferredAEADAlgorithms,!1,r)));const n=X.concat(t),i=X.writeNumber(n.length,2);return X.concat([i,n])}writeUnhashedSubPackets(){const e=[];this.unhashedSubpackets.forEach((t=>{e.push(hi(t.length)),e.push(t)}));const t=X.concat(e),r=X.writeNumber(t.length,2);return X.concat([r,t])}readSubPacket(e,t=!0){let r=0;const n=!!(128&e[r]),i=127&e[r];if(t||(this.unhashedSubpackets.push(e.subarray(r,e.length)),oh.has(i)))switch(r++,i){case $.signatureSubpacket.signatureCreationTime:this.created=X.readDate(e.subarray(r,e.length));break;case $.signatureSubpacket.signatureExpirationTime:{const t=X.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case $.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case $.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case $.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case $.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case $.signatureSubpacket.keyExpirationTime:{const t=X.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case $.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case $.signatureSubpacket.issuer:this.issuerKeyID.read(e.subarray(r,e.length));break;case $.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const i=X.readNumber(e.subarray(r,r+2));r+=2;const a=X.readNumber(e.subarray(r,r+2));r+=2;const s=X.decodeUTF8(e.subarray(r,r+i)),o=e.subarray(r+i,r+i+a);this.rawNotations.push({name:s,humanReadable:t,value:o,critical:n}),t&&(this.notations[s]=X.decodeUTF8(o));break}case $.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case $.signatureSubpacket.policyURI:this.policyURI=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.signersUserID:this.signersUserID=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=ma.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=X.uint8ArrayToString(e.subarray(r,r+t));break}case $.signatureSubpacket.embeddedSignature:this.embeddedSignature=new ch,this.embeddedSignature.read(e.subarray(r,e.length));break;case $.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),5===this.issuerKeyVersion?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case $.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;default:{const e=Error("Unknown signature subpacket type "+i);if(n)throw e;X.printDebug(e)}}}readSubPackets(e,t=!0,r){const n=X.readNumber(e.subarray(0,2));let i=2;for(;i<2+n;){const n=ci(e.subarray(i,e.length));i+=n.offset,this.readSubPacket(e.subarray(i,i+n.len),t,r),i+=n.len}return i}toSign(e,t){const r=$.signature;switch(e){case r.binary:return null!==t.text?X.encodeUTF8(t.getText(!0)):t.getBytes(!0);case r.text:{const e=t.getBytes(!0);return X.canonicalizeEOL(e)}case r.standalone:return new Uint8Array(0);case r.certGeneric:case r.certPersona:case r.certCasual:case r.certPositive:case r.certRevocation:{let e,n;if(t.userID)n=180,e=t.userID;else{if(!t.userAttribute)throw Error("Either a userID or userAttribute packet needs to be supplied for certification.");n=209,e=t.userAttribute}const i=e.write();return X.concat([this.toSign(r.key,t),new Uint8Array([n]),X.writeNumber(i.length,4),i])}case r.subkeyBinding:case r.subkeyRevocation:case r.keyBinding:return X.concat([this.toSign(r.key,t),this.toSign(r.key,{key:t.bind})]);case r.key:if(void 0===t.key)throw Error("Key packet is required for this signature.");return t.key.writeForHash(this.version);case r.keyRevocation:return this.toSign(r.key,t);case r.timestamp:return new Uint8Array(0);case r.thirdParty:throw Error("Not implemented");default:throw Error("Unknown signature type.")}}calculateTrailer(e,t){let r=0;return z(L(this.signatureData),(e=>{r+=e.length}),(()=>{const n=[];return 5!==this.version||this.signatureType!==$.signature.binary&&this.signatureType!==$.signature.text||(t?n.push(new Uint8Array(6)):n.push(e.writeHeader())),n.push(new Uint8Array([this.version,255])),5===this.version&&n.push(new Uint8Array(4)),n.push(X.writeNumber(r,4)),X.concat(n)}))}toHash(e,t,r=!1){const n=this.toSign(e,t);return X.concat([n,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,n=!1){return r||(r=this.toHash(e,t,n)),ma.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,n=new Date,i=!1,a=ie){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const s=t===$.signature.binary||t===$.signature.text;if(!(this[sh]&&!s)){let n,a;if(this.hashed?a=await this.hashed:(n=this.toHash(t,r,i),a=await this.hash(t,r,n)),a=await H(a),this.signedHashValue[0]!==a[0]||this.signedHashValue[1]!==a[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[sh]=await ma.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,n,a),!this[sh])throw Error("Signature verification failed")}const o=X.normalizeDate(n);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(a.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+$.read($.hash,this.hashAlgorithm).toUpperCase());if(a.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[$.signature.binary,$.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+$.read($.hash,this.hashAlgorithm).toUpperCase());if(this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&a.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=X.normalizeDate(e);return null!==t&&!(this.created<=t&&tch.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==$.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function lh(e,t){if(!t[e]){let t;try{t=$.read($.packet,e)}catch(t){throw new fi("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}uh.prototype.hash=ch.prototype.hash,uh.prototype.toHash=ch.prototype.toHash,uh.prototype.toSign=ch.prototype.toSign;class yh extends Array{static async fromBinary(e,t,r=ie){const n=new yh;return await n.read(e,t,r),n}async read(e,t,r=ie){r.additionalAllowedPackets.length&&(t={...t,...X.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=R(e,(async(e,n)=>{const i=C(n);try{for(;;){await i.ready;if(await pi(e,(async e=>{try{if(e.tag===$.packet.marker||e.tag===$.packet.trust)return;const n=lh(e.tag,t);n.packets=new yh,n.fromStream=X.isStream(e.packet),await n.read(e.packet,r),await i.write(n)}catch(t){const n=!r.ignoreUnsupportedPackets&&t instanceof fi,a=!(r.ignoreMalformedPackets||t instanceof fi);if(n||a||di(e.tag))await i.abort(t);else{const t=new gi(e.tag,e.packet);await i.write(t)}X.printDebugError(t)}})))return await i.ready,void await i.close()}}catch(e){await i.abort(e)}}));const n=D(this.stream);for(;;){const{done:e,value:t}=await n.read();if(e?this.stream=null:this.push(t),e||di(t.constructor.tag))break}n.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),i+=e.length,i>=a){const e=Math.min(Math.log(i)/Math.LN2|0,30),r=2**e,n=X.concat([ui(e)].concat(t));return t=[n.subarray(1+r)],i=t[0].length,n.subarray(0,1+r)}}),(()=>X.concat([hi(i)].concat(t)))))}else{if(X.isStream(n)){let t=0;e.push(z(L(n),(e=>{t+=e.length}),(()=>yi(r,t))))}else e.push(yi(r,n.length));e.push(n)}}return X.concat(e)}filterByTag(...e){const t=new yh,r=e=>t=>e===t;for(let n=0;nt.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,n=e=>t=>e===t;for(let i=0;i{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),X.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=ie){const t=$.read($.compression,this.algorithm),r=vh[t];if(!r)throw Error(t+" decompression not supported");this.packets=await yh.fromBinary(r(this.compressed),dh,e)}compress(){const e=$.read($.compression,this.algorithm),t=kh[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write(),this.deflateLevel)}}const fh=X.getNodeZlib();function gh(e){return e}function mh(e,t,r={}){return function(n){return!X.isStream(n)||s(n)?q((()=>H(n).then((t=>new Promise(((n,i)=>{e(t,r,((e,t)=>{if(e)return i(e);n(t)}))})))))):f(g(n).pipe(t(r)))}}function wh(e,t={}){return function(r){const n=new e(t);return z(r,(e=>{if(e.length)return n.push(e,Ua),n.result}),(()=>{if(e===zo)return n.push([],Ca),n.result}))}}function bh(e){return function(t){return q((async()=>e(await H(t))))}}const kh=fh?{zip:/*#__PURE__*/(e,t)=>mh(fh.deflateRaw,fh.createDeflateRaw,{level:t})(e),zlib:/*#__PURE__*/(e,t)=>mh(fh.deflate,fh.createDeflate,{level:t})(e)}:{zip:/*#__PURE__*/(e,t)=>wh(zo,{raw:!0,level:t})(e),zlib:/*#__PURE__*/(e,t)=>wh(zo,{level:t})(e)},vh=fh?{uncompressed:gh,zip:/*#__PURE__*/mh(fh.inflateRaw,fh.createInflateRaw),zlib:/*#__PURE__*/mh(fh.inflate,fh.createInflate),bzip2:/*#__PURE__*/bh(ih)}:{uncompressed:gh,zip:/*#__PURE__*/wh(jc,{raw:!0}),zlib:/*#__PURE__*/wh(jc),bzip2:/*#__PURE__*/bh(ih)},Ah=/*#__PURE__*/X.constructAllowedPackets([ah,ph,uh,ch]);class _h{static get tag(){return $.packet.symEncryptedIntegrityProtectedData}constructor(){this.version=1,this.encrypted=null,this.packets=null}async read(e){await M(e,(async e=>{const t=await e.readByte();if(1!==t)throw new fi(`Version ${t} of the SEIP packet is unsupported.`);this.encrypted=e.remainder()}))}write(){return X.concat([new Uint8Array([1]),this.encrypted])}async encrypt(e,t,r=ie){const{blockSize:n}=ma.getCipher(e);let i=this.packets.write();s(i)&&(i=await H(i));const a=await ma.getPrefixRandom(e),o=new Uint8Array([211,20]),c=X.concat([a,i,o]),h=await ma.hash.sha1(N(c)),u=X.concat([c,h]);return this.encrypted=await ma.mode.cfb.encrypt(e,t,u,new Uint8Array(n),r),!0}async decrypt(e,t,r=ie){const{blockSize:n}=ma.getCipher(e);let i=L(this.encrypted);s(i)&&(i=await H(i));const a=await ma.mode.cfb.decrypt(e,t,i,new Uint8Array(n)),o=F(N(a),-20),c=F(a,0,-20),h=Promise.all([H(await ma.hash.sha1(N(c))),H(o)]).then((([e,t])=>{if(!X.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=F(c,n+2);let l=F(u,0,-2);return l=U([l,q((()=>h))]),X.isStream(i)&&r.allowUnauthenticatedStream||(l=await H(l)),this.packets=await yh.fromBinary(l,Ah,r),!0}}const Eh=/*#__PURE__*/X.constructAllowedPackets([ah,ph,uh,ch]);class Sh{static get tag(){return $.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=$.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await M(e,(async e=>{const t=await e.readByte();if(1!==t)throw new fi(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=ma.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return X.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=ie){this.packets=await yh.fromBinary(await this.crypt("decrypt",t,L(this.encrypted)),Eh,r)}async encrypt(e,t,r=ie){this.cipherAlgorithm=e;const{ivLength:n}=ma.getAEADMode(this.aeadAlgorithm);this.iv=ma.random.getRandomBytes(n),this.chunkSizeByte=r.aeadChunkSizeByte;const i=this.packets.write();this.encrypted=await this.crypt("encrypt",t,i)}async crypt(e,t,r){const n=ma.getAEADMode(this.aeadAlgorithm),i=await n(this.cipherAlgorithm,t),a="decrypt"===e?n.tagLength:0,s="encrypt"===e?n.tagLength:0,o=2**(this.chunkSizeByte+6)+a,c=new ArrayBuffer(21),h=new Uint8Array(c,0,13),u=new Uint8Array(c),l=new DataView(c),y=new Uint8Array(c,5,8);h.set([192|Sh.tag,this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte],0);let d=0,p=Promise.resolve(),f=0,g=0;const m=this.iv;return R(r,(async(t,r)=>{if("array"!==X.isStream(t)){const e=new E({},{highWaterMark:X.getHardwareConcurrency()*2**(this.chunkSizeByte+6),size:e=>e.length});I(e.readable,r),r=e.writable}const c=D(t),w=C(r);try{for(;;){let t=await c.readBytes(o+a)||new Uint8Array;const r=t.subarray(t.length-a);let b,k;if(t=t.subarray(0,t.length-a),!d||t.length?(c.unshift(r),b=i[e](t,n.getNonce(m,y),h),g+=t.length-a+s):(l.setInt32(17,f),b=i[e](r,n.getNonce(m,y),u),g+=s,k=!0),f+=t.length-a,p=p.then((()=>b)).then((async e=>{await w.ready,await w.write(e),g-=e.length})).catch((e=>w.abort(e))),(k||g>w.desiredSize)&&await p,k){await w.close();break}l.setInt32(9,++d)}}catch(e){await w.abort(e)}}))}}class Kh{static get tag(){return $.packet.publicKeyEncryptedSessionKey}constructor(){this.version=3,this.publicKeyID=new pe,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}read(e){let t=0;if(this.version=e[t++],3!==this.version)throw new fi(`Version ${this.version} of the PKESK packet is unsupported.`);t+=this.publicKeyID.read(e.subarray(t)),this.publicKeyAlgorithm=e[t++],this.encrypted=ma.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t),this.version),this.publicKeyAlgorithm===$.publicKey.x25519&&(this.sessionKeyAlgorithm=$.write($.symmetric,this.encrypted.C.algorithm))}write(){const e=[new Uint8Array([this.version]),this.publicKeyID.write(),new Uint8Array([this.publicKeyAlgorithm]),ma.serializeParams(this.publicKeyAlgorithm,this.encrypted)];return X.concatUint8Array(e)}async encrypt(e){const t=$.write($.publicKey,this.publicKeyAlgorithm),r=xh(this.version,t,this.sessionKeyAlgorithm,this.sessionKey);this.encrypted=await ma.publicKeyEncrypt(t,this.sessionKeyAlgorithm,e.publicParams,r,e.getFingerprintBytes())}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?xh(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,n=await ma.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,e.getFingerprintBytes(),r),{sessionKey:i,sessionKeyAlgorithm:a}=function(e,t,r,n){switch(t){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.elgamal:case $.publicKey.ecdh:{const e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),i=X.writeChecksum(e.subarray(e.length%8)),a=i[0]===t[0]&i[1]===t[1],s={sessionKeyAlgorithm:e[0],sessionKey:e.subarray(1)};if(n){const e=a&s.sessionKeyAlgorithm===n.sessionKeyAlgorithm&s.sessionKey.length===n.sessionKey.length;return{sessionKey:X.selectUint8Array(e,s.sessionKey,n.sessionKey),sessionKeyAlgorithm:X.selectUint8(e,s.sessionKeyAlgorithm,n.sessionKeyAlgorithm)}}if(a&&$.read($.symmetric,s.sessionKeyAlgorithm))return s;throw Error("Decryption error")}case $.publicKey.x25519:return{sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,n,t);this.publicKeyAlgorithm!==$.publicKey.x25519&&(this.sessionKeyAlgorithm=a),this.sessionKey=i}}function xh(e,t,r,n){switch(t){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.elgamal:case $.publicKey.ecdh:return X.concatUint8Array([new Uint8Array([r]),n,X.writeChecksum(n.subarray(n.length%8))]);case $.publicKey.x25519:return n;default:throw Error("Unsupported public key algorithm")}}class Ph{constructor(e=ie){this.algorithm=$.hash.sha256,this.type="iterated",this.c=e.s2kIterationCountByte,this.salt=null}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;try{this.type=$.read($.s2k,e[t++])}catch(e){throw new fi("Unknown S2K type.")}switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==X.uint8ArrayToString(e.subarray(t,t+3)))throw new fi("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new fi("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new fi("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...X.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([$.write($.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return X.concatUint8Array(e)}async produceKey(e,t){e=X.encodeUTF8(e);const r=[];let n=0,i=0;for(;n{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function Mh(e,t,r){const{keySize:n}=ma.getCipher(r);return e.produceKey(t,n)}var Lh=rt((function(e){!function(t){function r(e){function t(){return _e0&&(t.semantic=" "),t}}function g(e,t){return function(){var n,a,o,h,u;for(h=r(),n=s("star"),o=0,u=void 0===t?0:t;null!==(a=e());)o+=1,c(n,a);return o>=u?n:(i(h),null)}}function m(e){return e.charCodeAt(0)>=128}function w(){return o("cr",u("\r")())}function b(){return o("crlf",l(w,A)())}function k(){return o("dquote",u('"')())}function v(){return o("htab",u("\t")())}function A(){return o("lf",u("\n")())}function _(){return o("sp",u(" ")())}function E(){return o("vchar",h((function(t){var r=t.charCodeAt(0),n=33<=r&&r<=126;return e.rfc6532&&(n=n||m(t)),n})))}function S(){return o("wsp",y(_,v)())}function K(){var e=o("quoted-pair",y(l(u("\\"),y(E,S)),ne)());return null===e?null:(e.semantic=e.semantic[1],e)}function x(){return o("fws",y(ae,l(d(l(g(S),p(b))),g(S,1)))())}function P(){return o("ctext",y((function(){return h((function(t){var r=t.charCodeAt(0),n=33<=r&&r<=39||42<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(n=n||m(t)),n}))}),te)())}function U(){return o("ccontent",y(P,K,D)())}function D(){return o("comment",l(u("("),g(l(d(x),U)),d(x),u(")"))())}function C(){return o("cfws",y(l(g(l(d(x),D),1),d(x)),x)())}function I(){return o("atext",h((function(t){var r="a"<=t&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||["!","#","$","%","&","'","*","+","-","/","=","?","^","_","`","{","|","}","~"].indexOf(t)>=0;return e.rfc6532&&(r=r||m(t)),r})))}function T(){return o("atom",l(f(d(C)),g(I,1),f(d(C)))())}function B(){var e,t;return null===(e=o("dot-atom-text",g(I,1)()))||null!==(t=g(l(u("."),g(I,1)))())&&c(e,t),e}function z(){return o("dot-atom",l(p(d(C)),B,p(d(C)))())}function R(){return o("qtext",y((function(){return h((function(t){var r=t.charCodeAt(0),n=33===r||35<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(n=n||m(t)),n}))}),re)())}function M(){return o("qcontent",y(R,K)())}function L(){return o("quoted-string",l(p(d(C)),p(k),g(l(d(f(x)),M)),d(p(x)),p(k),p(d(C)))())}function N(){return o("word",y(T,L)())}function O(){return o("address",y(F,q)())}function F(){return o("mailbox",y(H,J)())}function H(){return o("name-addr",l(d(G),j)())}function j(){return o("angle-addr",y(l(p(d(C)),u("<"),J,u(">"),p(d(C))),se)())}function q(){return o("group",l(G,u(":"),d($),u(";"),p(d(C)))())}function G(){return o("display-name",(null!==(e=o("phrase",y(ie,g(N,1))()))&&(e.semantic=function(e){return e.replace(/([ \t]|\r\n)+/g," ").replace(/^\s*/,"").replace(/\s*$/,"")}(e.semantic)),e));var e}function V(){return o("mailbox-list",y(l(F,g(l(u(","),F))),he)())}function W(){return o("address-list",y(l(O,g(l(u(","),O))),ue)())}function $(){return o("group-list",y(V,p(C),le)())}function Z(){return o("local-part",y(ye,z,L)())}function X(){return o("dtext",y((function(){return h((function(t){var r=t.charCodeAt(0),n=33<=r&&r<=90||94<=r&&r<=126;return e.rfc6532&&(n=n||m(t)),n}))}),pe)())}function Q(){return o("domain-literal",l(p(d(C)),u("["),g(l(d(x),X)),d(x),u("]"),p(d(C)))())}function Y(){return o("domain",(t=y(de,z,Q)(),e.rejectTLD&&t&&t.semantic&&t.semantic.indexOf(".")<0?null:(t&&(t.semantic=t.semantic.replace(/\s+/g,"")),t)));var t}function J(){return o("addr-spec",l(Z,u("@"),Y)())}function ee(){return e.strict?null:o("obs-NO-WS-CTL",h((function(e){var t=e.charCodeAt(0);return 1<=t&&t<=8||11===t||12===t||14<=t&&t<=31||127===t})))}function te(){return e.strict?null:o("obs-ctext",ee())}function re(){return e.strict?null:o("obs-qtext",ee())}function ne(){return e.strict?null:o("obs-qp",l(u("\\"),y(u("\0"),ee,A,w))())}function ie(){return e.strict?null:e.atInDisplayName?o("obs-phrase",l(N,g(y(N,u("."),u("@"),f(C))))()):o("obs-phrase",l(N,g(y(N,u("."),f(C))))())}function ae(){return e.strict?null:o("obs-FWS",g(l(p(d(b)),S),1)())}function se(){return e.strict?null:o("obs-angle-addr",l(p(d(C)),u("<"),oe,J,u(">"),p(d(C)))())}function oe(){return e.strict?null:o("obs-route",l(ce,u(":"))())}function ce(){return e.strict?null:o("obs-domain-list",l(g(y(p(C),u(","))),u("@"),Y,g(l(u(","),p(d(C)),d(l(u("@"),Y)))))())}function he(){return e.strict?null:o("obs-mbox-list",l(g(l(p(d(C)),u(","))),F,g(l(u(","),d(l(F,p(C))))))())}function ue(){return e.strict?null:o("obs-addr-list",l(g(l(p(d(C)),u(","))),O,g(l(u(","),d(l(O,p(C))))))())}function le(){return e.strict?null:o("obs-group-list",l(g(l(p(d(C)),u(",")),1),p(d(C)))())}function ye(){return e.strict?null:o("obs-local-part",l(N,g(l(u("."),N)))())}function de(){return e.strict?null:o("obs-domain",l(T,g(l(u("."),T)))())}function pe(){return e.strict?null:o("obs-dtext",y(ee,K)())}function fe(e,t){var r,n,i;if(null==t)return null;for(n=[t];n.length>0;){if((i=n.pop()).name===e)return i;for(r=i.children.length-1;r>=0;r-=1)n.push(i.children[r])}return null}function ge(e,t){var r,n,i,a,s;if(null==t)return null;for(n=[t],a=[],s={},r=0;r0;)if((i=n.pop()).name in s)a.push(i);else for(r=i.children.length-1;r>=0;r-=1)n.push(i.children[r]);return a}function me(t){var r,n,i,a,s;if(null===t)return null;for(r=[],n=ge(["group","mailbox"],t),i=0;i1)return null;return t.addresses&&t.addresses[0]}(s):e.simple?s&&s.addresses:s}function we(e){var t,r=fe("display-name",e),n=[],i=ge(["mailbox"],e);for(t=0;t0;)for((i=n.pop()).name===e&&a.push(i),r=i.children.length-1;r>=0;r-=1)n.push(i.children[r]);return a}("cfws",e),i=ge(["comment"],e),a=fe("local-part",r),s=fe("domain",r);return{node:e,parts:{name:t,address:r,local:a,domain:s,comments:n},type:e.name,name:ke(t),address:ke(r),local:ke(a),domain:ke(s),comments:ve(i),groupName:ke(e.groupName)}}function ke(e){return null!=e?e.semantic:null}function ve(e){var t="";if(e)for(var r=0;r`),t.userID=r.join(" "),t}read(e,t=ie){const r=X.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");try{const{name:e,address:t,comments:n}=Lh.parseOneAddress({input:r,atInDisplayName:!0});this.comment=n.replace(/^\(|\)$/g,""),this.name=e,this.email=t}catch(e){}this.userID=r}write(){return X.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Oh extends Rh{static get tag(){return $.packet.secretSubkey}constructor(e=new Date,t=ie){super(e,t)}}class Fh{static get tag(){return $.packet.trust}read(){throw new fi("Trust packets are not supported")}write(){throw new fi("Trust packets are not supported")}}const Hh=/*#__PURE__*/X.constructAllowedPackets([ch]);class jh{constructor(e){this.packets=e||new yh}write(){return this.packets.write()}armor(e=ie){return de($.armor.signature,this.write(),void 0,void 0,void 0,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function qh({armoredSignature:e,binarySignature:t,config:r,...n}){r={...ie,...r};let i=e||t;if(!i)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!X.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!X.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:e,data:t}=await ye(i,r);if(e!==$.armor.signature)throw Error("Armored text not of type signature");i=t}const s=await yh.fromBinary(i,Hh,r);return new jh(s)}async function Gh(e,t){const r=new Oh(e.date,t);return r.packets=null,r.algorithm=$.write($.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function Vh(e,t){const r=new Rh(e.date,t);return r.packets=null,r.algorithm=$.write($.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Wh(e,t,r,n,i=new Date,a){let s,o;for(let c=e.length-1;c>=0;c--)try{(!s||e[c].created>=s.created)&&(await e[c].verify(t,r,n,i,void 0,a),s=e[c])}catch(e){o=e}if(!s)throw X.wrapError(`Could not find valid ${$.read($.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return s}function $h(e,t,r=new Date){const n=X.normalizeDate(r);if(null!==n){const r=tu(e,t);return!(e.created<=n&&n0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1);return await Yh(i,null,t,a,r.date,void 0,void 0,void 0,n)}async function Xh(e,t,r=new Date,n={},i){let a=i.preferredHashAlgorithm,s=a;if(e){const t=await e.getPrimaryUser(r,n,i);t.selfCertification.preferredHashAlgorithms&&([s]=t.selfCertification.preferredHashAlgorithms,a=ma.hash.getHashByteLength(a)<=ma.hash.getHashByteLength(s)?s:a)}switch(t.algorithm){case $.publicKey.ecdsa:case $.publicKey.eddsaLegacy:case $.publicKey.ed25519:s=ma.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid)}return ma.hash.getHashByteLength(a)<=ma.hash.getHashByteLength(s)?s:a}async function Qh(e,t=[],r=new Date,n=[],i=ie){const a={symmetric:$.symmetric.aes128,aead:$.aead.eax,compression:$.compression.uncompressed}[e],s={symmetric:i.preferredSymmetricAlgorithm,aead:i.preferredAEADAlgorithm,compression:i.preferredCompressionAlgorithm}[e],o={symmetric:"preferredSymmetricAlgorithms",aead:"preferredAEADAlgorithms",compression:"preferredCompressionAlgorithms"}[e];return(await Promise.all(t.map((async function(e,t){const a=(await e.getPrimaryUser(r,n[t],i)).selfCertification[o];return!!a&&a.indexOf(s)>=0})))).every(Boolean)?s:a}async function Yh(e,t,r,n,i,a,s=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const h=new ch;return Object.assign(h,n),h.publicKeyAlgorithm=r.algorithm,h.hashAlgorithm=await Xh(t,r,i,a,c),h.rawNotations=s,await h.sign(r,e,i,o),h}async function Jh(e,t,r,n=new Date,i){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(n)||i&&!await i(e)||t[r].some((function(t){return X.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function eu(e,t,r,n,i,a,s=new Date,o){a=a||e;const c=[];return await Promise.all(n.map((async function(e){try{i&&!e.issuerKeyID.equals(i.issuerKeyID)||(await e.verify(a,t,r,o.revocationsExpire?s:null,!1,o),c.push(e.issuerKeyID))}catch(e){}}))),i?(i.revoked=!!c.some((e=>e.equals(i.issuerKeyID)))||(i.revoked||!1),i.revoked):c.length>0}function tu(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function ru(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=X.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=$.write($.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==$.curve.ed25519Legacy&&e.curve!==$.curve.curve25519Legacy||(e.curve=e.sign?$.curve.ed25519Legacy:$.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===$.curve.ed25519Legacy?$.publicKey.eddsaLegacy:$.publicKey.ecdsa:e.algorithm=$.publicKey.ecdh;break;case"rsa":e.algorithm=$.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function nu(e,t){const r=e.algorithm;return r!==$.publicKey.rsaEncrypt&&r!==$.publicKey.elgamal&&r!==$.publicKey.ecdh&&r!==$.publicKey.x25519&&(!t.keyFlags||0!=(t.keyFlags[0]&$.keyFlags.signData))}function iu(e,t){const r=e.algorithm;return r!==$.publicKey.dsa&&r!==$.publicKey.rsaSign&&r!==$.publicKey.ecdsa&&r!==$.publicKey.eddsaLegacy&&r!==$.publicKey.ed25519&&(!t.keyFlags||0!=(t.keyFlags[0]&$.keyFlags.encryptCommunication)||0!=(t.keyFlags[0]&$.keyFlags.encryptStorage))}function au(e,t){return!!t.allowInsecureDecryptionWithSigningKeys||(!e.keyFlags||0!=(e.keyFlags[0]&$.keyFlags.encryptCommunication)||0!=(e.keyFlags[0]&$.keyFlags.encryptStorage))}function su(e,t){const r=$.write($.publicKey,e.algorithm),n=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(n.algorithm+" keys are considered too weak.");switch(r){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:case $.publicKey.rsaEncrypt:if(n.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const a=await t.getSigningKey(o,e.created,void 0,n);if(e.revoked||await i.isRevoked(e,a.keyPacket,r,n))throw Error("User certificate is revoked");try{await e.verify(a.keyPacket,$.signature.certGeneric,s,r,void 0,n)}catch(e){throw X.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const n=this,i=this.selfCertifications.concat(this.otherCertifications);return Promise.all(i.map((async i=>({keyID:i.issuerKeyID,valid:await n.verifyCertificate(i,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};let a;for(let s=this.selfCertifications.length-1;s>=0;s--)try{const a=this.selfCertifications[s];if(a.revoked||await r.isRevoked(a,void 0,e,t))throw Error("Self-certification is revoked");try{await a.verify(n,$.signature.certGeneric,i,e,void 0,t)}catch(e){throw X.wrapError("Self-certification is invalid",e)}return!0}catch(e){a=e}throw a}async update(e,t,r){const n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};await Jh(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(n,$.signature.certGeneric,i,t,!1,r),!0}catch(e){return!1}})),await Jh(e,this,"otherCertifications",t),await Jh(e,this,"revocationSignatures",t,(function(e){return eu(n,$.signature.certRevocation,i,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=$.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=ie){const a={userID:this.userID,userAttribute:this.userAttribute,key:e},s=new ou(a.userID||a.userAttribute,this.mainKey);return s.revocationSignatures.push(await Yh(a,null,e,{signatureType:$.signature.certRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await s.update(this),s}}class cu{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new yh;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new cu(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,n=ie){const i=this.mainKey.keyPacket;return eu(i,$.signature.subkeyRevocation,{key:i,bind:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verify(e=new Date,t=ie){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket},i=await Wh(this.bindingSignatures,r,$.signature.subkeyBinding,n,e,t);if(i.revoked||await this.isRevoked(i,null,e,t))throw Error("Subkey is revoked");if($h(this.keyPacket,i,e))throw Error("Subkey is expired");return i}async getExpirationTime(e=new Date,t=ie){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket};let i;try{i=await Wh(this.bindingSignatures,r,$.signature.subkeyBinding,n,e,t)}catch(e){return null}const a=tu(this.keyPacket,i),s=i.getExpirationTime();return ai.bindingSignatures[t].created&&(i.bindingSignatures[t]=e),!1;try{return await e.verify(n,$.signature.subkeyBinding,a,t,void 0,r),!0}catch(e){return!1}})),await Jh(e,this,"revocationSignatures",t,(function(e){return eu(n,$.signature.subkeyRevocation,a,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=$.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=ie){const a={key:e,bind:this.keyPacket},s=new cu(this.keyPacket,this.mainKey);return s.revocationSignatures.push(await Yh(a,null,e,{signatureType:$.signature.subkeyRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await s.update(this),s}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{cu.prototype[e]=function(){return this.keyPacket[e]()}}));const hu=/*#__PURE__*/X.constructAllowedPackets([ch]),uu=new Set([$.packet.publicKey,$.packet.privateKey]),lu=new Set([$.packet.publicKey,$.packet.privateKey,$.packet.publicSubkey,$.packet.privateSubkey]);class yu{packetListToStructure(e,t=new Set){let r,n,i,a;for(const s of e){if(s instanceof gi){lu.has(s.tag)&&!a&&(a=uu.has(s.tag)?uu:lu);continue}const e=s.constructor.tag;if(a){if(!a.has(e))continue;a=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case $.packet.publicKey:case $.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=s,n=this.getKeyID(),!n)throw Error("Missing Key ID");break;case $.packet.userID:case $.packet.userAttribute:r=new ou(s,this),this.users.push(r);break;case $.packet.publicSubkey:case $.packet.secretSubkey:r=null,i=new cu(s,this),this.subkeys.push(i);break;case $.packet.signature:switch(s.signatureType){case $.signature.certGeneric:case $.signature.certPersona:case $.signature.certCasual:case $.signature.certPositive:if(!r){X.printDebug("Dropping certification signatures without preceding user packet");continue}s.issuerKeyID.equals(n)?r.selfCertifications.push(s):r.otherCertifications.push(s);break;case $.signature.certRevocation:r?r.revocationSignatures.push(s):this.directSignatures.push(s);break;case $.signature.key:this.directSignatures.push(s);break;case $.signature.subkeyBinding:if(!i){X.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}i.bindingSignatures.push(s);break;case $.signature.keyRevocation:this.revocationSignatures.push(s);break;case $.signature.subkeyRevocation:if(!i){X.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}i.revocationSignatures.push(s)}}}}toPacketList(){const e=new yh;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},n=ie){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},a=await Wh(r.bindingSignatures,i,$.signature.subkeyBinding,e,t,n);if(!nu(r.keyPacket,a))continue;if(!a.embeddedSignature)throw Error("Missing embedded signature");return await Wh([a.embeddedSignature],r.keyPacket,$.signature.keyBinding,e,t,n),su(r.keyPacket,n),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,n);if((!e||i.getKeyID().equals(e))&&nu(i,a.selfCertification))return su(i,n),this}catch(e){s=e}throw X.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),s)}async getEncryptionKey(e,t=new Date,r={},n=ie){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},a=await Wh(r.bindingSignatures,i,$.signature.subkeyBinding,e,t,n);if(iu(r.keyPacket,a))return su(r.keyPacket,n),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,n);if((!e||i.getKeyID().equals(e))&&iu(i,a.selfCertification))return su(i,n),this}catch(e){s=e}throw X.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),s)}async isRevoked(e,t,r=new Date,n=ie){return eu(this.keyPacket,$.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verifyPrimaryKey(e=new Date,t={},r=ie){const n=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");const{selfCertification:i}=await this.getPrimaryUser(e,t,r);if($h(n,i,e))throw Error("Primary key is expired");const a=await Wh(this.directSignatures,n,$.signature.key,{key:n},e,r).catch((()=>{}));if(a&&$h(n,a,e))throw Error("Primary key is expired")}async getExpirationTime(e,t=ie){let r;try{const{selfCertification:n}=await this.getPrimaryUser(null,e,t),i=tu(this.keyPacket,n),a=n.getExpirationTime(),s=await Wh(this.directSignatures,this.keyPacket,$.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(s){const e=tu(this.keyPacket,s);r=Math.min(i,a,e)}else r=ie.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const n=this.clone();return await Jh(e,n,"revocationSignatures",t,(i=>eu(n.keyPacket,$.signature.keyRevocation,n,[i],null,e.keyPacket,t,r))),await Jh(e,n,"directSignatures",t),await Promise.all(e.users.map((async e=>{const i=n.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const i=n.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.subkeys.push(t)}}))),n}async getRevocationCertificate(e=new Date,t=ie){const r={key:this.keyPacket},n=await Wh(this.revocationSignatures,this.keyPacket,$.signature.keyRevocation,r,e,t),i=new yh;return i.push(n),de($.armor.publicKey,i.write(),null,null,"This is a revocation certificate")}async applyRevocationCertificate(e,t=new Date,r=ie){const n=await ye(e,r),i=(await yh.fromBinary(n.data,hu,r)).findPacket($.packet.signature);if(!i||i.signatureType!==$.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!i.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await i.verify(this.keyPacket,$.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw X.wrapError("Could not verify revocation signature",e)}const a=this.clone();return a.revocationSignatures.push(i),a}async signPrimaryUser(e,t,r,n=ie){const{index:i,user:a}=await this.getPrimaryUser(t,r,n),s=await a.certify(e,t,n),o=this.clone();return o.users[i]=s,o}async signAllUsers(e,t=new Date,r=ie){const n=this.clone();return n.users=await Promise.all(this.users.map((function(n){return n.certify(e,t,r)}))),n}async verifyPrimaryUser(e,t=new Date,r,n=ie){const i=this.keyPacket,{user:a}=await this.getPrimaryUser(t,r,n);return e?await a.verifyAllCertifications(e,t,n):[{keyID:i.getKeyID(),valid:await a.verify(t,n).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=ie){const n=this.keyPacket,i=[];return await Promise.all(this.users.map((async a=>{const s=e?await a.verifyAllCertifications(e,t,r):[{keyID:n.getKeyID(),valid:await a.verify(t,r).catch((()=>!1))}];i.push(...s.map((e=>({userID:a.userID?a.userID.userID:null,userAttribute:a.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),i}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{yu.prototype[e]=cu.prototype[e]}));class du extends yu{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([$.packet.secretKey,$.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=ie){return de($.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,e)}}class pu extends du{constructor(e){if(super(),this.packetListToStructure(e,new Set([$.packet.publicKey,$.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new yh,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case $.packet.secretKey:{const t=Dh.fromSecretKeyPacket(r);e.push(t);break}case $.packet.secretSubkey:{const t=Bh.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new du(e)}armor(e=ie){return de($.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,e)}async getDecryptionKeys(e,t=new Date,r={},n=ie){const i=this.keyPacket,a=[];for(let r=0;re.isDecrypted()))}async validate(e=ie){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=$.reasonForRevocation.noReason,string:t=""}={},r=new Date,n=ie){if(!this.isPrivate())throw Error("Need private key for revoking");const i={key:this.keyPacket},a=this.clone();return a.revocationSignatures.push(await Yh(i,null,this.keyPacket,{signatureType:$.signature.keyRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,n)),a}async addSubkey(e={}){const t={...ie,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}const s=Nh.fromObject(t),o={};o.userID=s,o.key=e;const c={};c.signatureType=$.signature.certGeneric,c.keyFlags=[$.keyFlags.certifyKeys|$.keyFlags.signData],c.preferredSymmetricAlgorithms=a([$.symmetric.aes256,$.symmetric.aes128,$.symmetric.aes192],n.preferredSymmetricAlgorithm),n.aeadProtect&&(c.preferredAEADAlgorithms=a([$.aead.eax,$.aead.ocb],n.preferredAEADAlgorithm)),c.preferredHashAlgorithms=a([$.hash.sha256,$.hash.sha512],n.preferredHashAlgorithm),c.preferredCompressionAlgorithms=a([$.compression.zlib,$.compression.zip,$.compression.uncompressed],n.preferredCompressionAlgorithm),0===i&&(c.isPrimaryUserID=!0),c.features=[0],c.features[0]|=$.features.modificationDetection,n.aeadProtect&&(c.features[0]|=$.features.aead),n.v5Keys&&(c.features[0]|=$.features.v5Keys),r.keyExpirationTime>0&&(c.keyExpirationTime=r.keyExpirationTime,c.keyNeverExpires=!1);return{userIDPacket:s,signaturePacket:await Yh(o,null,e,c,r.date,void 0,void 0,void 0,n)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{i.push(e),i.push(t)}))})),await Promise.all(t.map((async function(t,i){const a=r.subkeys[i];return{secretSubkeyPacket:t,subkeySignaturePacket:await Zh(t,e,a,n)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{i.push(e),i.push(t)}))}));const a={key:e};return i.push(await Yh(a,null,e,{signatureType:$.signature.keyRevocation,reasonForRevocationFlag:$.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,n)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new pu(i)}async function wu({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...ie,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!X.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!X.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let a;if(e){const{type:t,data:n}=await ye(e,r);if(t!==$.armor.publicKey&&t!==$.armor.privateKey)throw Error("Armored text not of type key");a=n}else a=t;return gu(await yh.fromBinary(a,fu,r))}async function bu({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...ie,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!X.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!X.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let a;if(e){const{type:t,data:n}=await ye(e,r);if(t!==$.armor.privateKey)throw Error("Armored text not of type private key");a=n}else a=t;const s=await yh.fromBinary(a,fu,r);return new pu(s)}async function ku({armoredKeys:e,binaryKeys:t,config:r,...n}){r={...ie,...r};let i=e||t;if(!i)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!X.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!X.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:t,data:n}=await ye(e,r);if(t!==$.armor.publicKey&&t!==$.armor.privateKey)throw Error("Armored text not of type key");i=n}const s=[],o=await yh.fromBinary(i,fu,r),c=o.indexOfTag($.packet.publicKey,$.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag($.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,n=new Date,i=ie){const a=r||await this.decryptSessionKeys(e,t,n,i),s=this.packets.filterByTag($.packet.symmetricallyEncryptedData,$.packet.symEncryptedIntegrityProtectedData,$.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const o=s[0];let c=null;const h=Promise.all(a.map((async({algorithm:e,data:t})=>{if(!X.isUint8Array(t)||!X.isString(e))throw Error("Invalid session key for decryption.");try{const r=$.write($.symmetric,e);await o.decrypt(r,t,i)}catch(e){X.printDebugError(e),c=e}})));if(j(o.encrypted),o.encrypted=null,await h,!o.packets||!o.packets.length)throw c||Error("Decryption failed.");const u=new Su(o.packets);return o.packets=new yh,u}async decryptSessionKeys(e,t,r=new Date,n=ie){let i,a=[];if(t){const e=this.packets.filterByTag($.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let i;i=r?await yh.fromBinary(e.write(),_u,n):e,await Promise.all(i.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){X.printDebugError(e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag($.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let s=[$.symmetric.aes256,$.symmetric.aes128,$.symmetric.tripledes,$.symmetric.cast5];try{const t=await e.getPrimaryUser(r,void 0,n);t.selfCertification.preferredSymmetricAlgorithms&&(s=s.concat(t.selfCertification.preferredSymmetricAlgorithms))}catch(e){}const o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,n)).map((e=>e.keyPacket));await Promise.all(o.map((async function(e){if(!e||e.isDummy())return;if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(n.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===$.publicKey.rsaEncrypt||t.publicKeyAlgorithm===$.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===$.publicKey.rsaSign||t.publicKeyAlgorithm===$.publicKey.elgamal)){const r=t.write();await Promise.all(Array.from(n.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map((async t=>{const n=new Kh;n.read(r);const s={sessionKeyAlgorithm:t,sessionKey:ma.generateSessionKey(t)};try{await n.decrypt(e,s),a.push(n)}catch(e){X.printDebugError(e),i=e}})))}else try{if(await t.decrypt(e),!s.includes($.write($.symmetric,t.sessionKeyAlgorithm)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){X.printDebugError(e),i=e}})))}))),j(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+X.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:$.read($.symmetric,e.sessionKeyAlgorithm)})))}throw i||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],n=ie){const i=await Qh("symmetric",e,t,r,n),a=$.read($.symmetric,i),s=n.aeadProtect&&await async function(e,t=new Date,r=[],n=ie){let i=!0;return await Promise.all(e.map((async function(e,a){const s=await e.getPrimaryUser(t,r[a],n);s.selfCertification.features&&s.selfCertification.features[0]&$.features.aead||(i=!1)}))),i}(e,t,r,n)?$.read($.aead,await Qh("aead",e,t,r,n)):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&e.keyPacket.algorithm===$.publicKey.x25519&&!X.isAES(i))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:ma.generateSessionKey(i),algorithm:a,aeadAlgorithm:s}}async encrypt(e,t,r,n=!1,i=[],a=new Date,s=[],o=ie){if(r){if(!X.isUint8Array(r.data)||!X.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Su.generateSessionKey(e,a,s,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Su.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:h,aeadAlgorithm:u}=r,l=await Su.encryptSessionKey(c,h,u,e,t,n,i,a,s,o);let y;u?(y=new Sh,y.aeadAlgorithm=$.write($.aead,u)):y=new _h,y.packets=this.packets;const d=$.write($.symmetric,h);return await y.encrypt(d,c,o),l.packets.push(y),y.packets=new yh,l}static async encryptSessionKey(e,t,r,n,i,a=!1,s=[],o=new Date,c=[],h=ie){const u=new yh,l=$.write($.symmetric,t),y=r&&$.write($.aead,r);if(n){const t=await Promise.all(n.map((async function(t,r){const n=await t.getEncryptionKey(s[r],o,c,h),i=new Kh;return i.publicKeyID=a?pe.wildcard():n.getKeyID(),i.publicKeyAlgorithm=n.keyPacket.algorithm,i.sessionKey=e,i.sessionKeyAlgorithm=l,await i.encrypt(n.keyPacket),delete i.sessionKey,i})));u.push(...t)}if(i){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,n=async function(e,a,s,o){const c=new Uh(h);if(c.sessionKey=e,c.sessionKeyAlgorithm=a,s&&(c.aeadAlgorithm=s),await c.encrypt(o,h),h.passwordCollisionCheck){if(1!==(await Promise.all(i.map((e=>t(c,e))))).reduce(r))return n(e,a,o)}return delete c.sessionKey,c},a=await Promise.all(i.map((t=>n(e,l,y,t))));u.push(...a)}return new Su(u)}async sign(e=[],t=null,r=[],n=new Date,i=[],a=[],s=ie){const o=new yh,c=this.packets.findPacket($.packet.literalData);if(!c)throw Error("No literal data packet to sign.");let h,u;const l=null===c.text?$.signature.binary:$.signature.text;if(t)for(u=t.packets.filterByTag($.packet.signature),h=u.length-1;h>=0;h--){const t=u[h],r=new uh;r.signatureType=t.signatureType,r.hashAlgorithm=t.hashAlgorithm,r.publicKeyAlgorithm=t.publicKeyAlgorithm,r.issuerKeyID=t.issuerKeyID,e.length||0!==h||(r.flags=1),o.push(r)}return await Promise.all(Array.from(e).reverse().map((async function(t,a){if(!t.isPrivate())throw Error("Need private key for signing");const o=r[e.length-1-a],c=await t.getSigningKey(o,n,i,s),h=new uh;return h.signatureType=l,h.hashAlgorithm=await Xh(t,c.keyPacket,n,i,s),h.publicKeyAlgorithm=c.keyPacket.algorithm,h.issuerKeyID=c.getKeyID(),a===e.length-1&&(h.flags=1),h}))).then((e=>{e.forEach((e=>o.push(e)))})),o.push(c),o.push(...await Ku(c,e,t,r,n,i,a,!1,s)),new Su(o)}compress(e,t=ie){if(e===$.compression.uncompressed)return this;const r=new ph(t);r.algorithm=e,r.packets=this.packets;const n=new yh;return n.push(r),new Su(n)}async signDetached(e=[],t=null,r=[],n=new Date,i=[],a=[],s=ie){const o=this.packets.findPacket($.packet.literalData);if(!o)throw Error("No literal data packet to sign.");return new jh(await Ku(o,e,t,r,n,i,a,!0,s))}async verify(e,t=new Date,r=ie){const n=this.unwrapCompressed(),i=n.packets.filterByTag($.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");s(n.packets.stream)&&n.packets.push(...await H(n.packets.stream,(e=>e||[])));const a=n.packets.filterByTag($.packet.onePassSignature).reverse(),o=n.packets.filterByTag($.packet.signature);return a.length&&!o.length&&X.isStream(n.packets.stream)&&!s(n.packets.stream)?(await Promise.all(a.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=q((async()=>(await e.correspondingSig).signatureData)),e.hashed=H(await e.hash(e.signatureType,i[0],void 0,!1)),e.hashed.catch((()=>{}))}))),n.packets.stream=R(n.packets.stream,(async(e,t)=>{const r=D(e),n=C(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await n.abort(e)}})),xu(a,i,e,t,!1,r)):xu(o,i,e,t,!1,r)}verifyDetached(e,t,r=new Date,n=ie){const i=this.unwrapCompressed().packets.filterByTag($.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");return xu(e.packets.filterByTag($.packet.signature),i,t,r,!0,n)}unwrapCompressed(){const e=this.packets.filterByTag($.packet.compressedData);return e.length?new Su(e[0].packets):this}async appendSignature(e,t=ie){await this.packets.read(X.isUint8Array(e)?e:(await ye(e)).data,Eu,t)}write(){return this.packets.write()}armor(e=ie){return de($.armor.message,this.write(),null,null,null,e)}}async function Ku(e,t,r=null,n=[],i=new Date,a=[],s=[],o=!1,c=ie){const h=new yh,u=null===e.text?$.signature.binary:$.signature.text;if(await Promise.all(t.map((async(t,r)=>{const h=a[r];if(!t.isPrivate())throw Error("Need private key for signing");const l=await t.getSigningKey(n[r],i,h,c);return Yh(e,t,l.keyPacket,{signatureType:u},i,h,s,o,c)}))).then((e=>{h.push(...e)})),r){const e=r.packets.filterByTag($.packet.signature);h.push(...e)}return h}async function xu(e,t,r,n=new Date,i=!1,a=ie){return Promise.all(e.filter((function(e){return["text","binary"].includes($.read($.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,n=new Date,i=!1,a=ie){let s,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){s=t,o=r[0];break}}const c=e instanceof uh?e.correspondingSig:e,h={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],n,i,a);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await s.getSigningKey(o.getKeyID(),r.created,void 0,a)}catch(e){if(!a.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await s.getSigningKey(o.getKeyID(),n,void 0,a)}return!0})(),signature:(async()=>{const e=await c,t=new yh;return e&&t.push(e),new jh(t)})()};return h.signature.catch((()=>{})),h.verified.catch((()=>{})),h}(e,t,r,n,i,a)})))}async function Pu({armoredMessage:e,binaryMessage:t,config:r,...n}){r={...ie,...r};let i=e||t;if(!i)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!X.isString(e)&&!X.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!X.isUint8Array(t)&&!X.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));const s=X.isStream(i);if(s&&(await S(),i=x(i)),e){const{type:e,data:t}=await ye(i,r);if(e!==$.armor.message)throw Error("Armored text not of type message");i=t}const o=await yh.fromBinary(i,Au,r),c=new Su(o);return c.fromStream=s,c}async function Uu({text:e,binary:t,filename:r,date:n=new Date,format:i=(void 0!==e?"utf8":"binary"),...a}){let s=void 0!==e?e:t;if(void 0===s)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!X.isString(e)&&!X.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!X.isUint8Array(t)&&!X.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=X.isStream(s);c&&(await S(),s=x(s));const h=new ah(n);void 0!==e?h.setText(s,$.write($.literal,i)):h.setBytes(s,$.write($.literal,i)),void 0!==r&&h.setFilename(r);const u=new yh;u.push(h);const l=new Su(u);return l.fromStream=c,l}const Du=/*#__PURE__*/X.constructAllowedPackets([ch]);class Cu{constructor(e,t){if(this.text=X.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof jh))throw Error("Invalid signature input");this.signature=t||new jh(new yh)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=null,r=[],n=new Date,i=[],a=[],s=ie){const o=new ah;o.setText(this.text);const c=new jh(await Ku(o,e,t,r,n,i,a,!0,s));return new Cu(this.text,c)}verify(e,t=new Date,r=ie){const n=this.signature.packets.filterByTag($.packet.signature),i=new ah;return i.setText(this.text),xu(n,[i],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=ie){let t=this.signature.packets.map((function(e){return $.read($.hash,e.hashAlgorithm).toUpperCase()}));t=t.filter((function(e,t,r){return r.indexOf(e)===t}));const r={hash:t.join(),text:this.text,data:this.signature.packets.write()};return de($.armor.signed,r,void 0,void 0,void 0,e)}}async function Iu({cleartextMessage:e,config:t,...r}){if(t={...ie,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!X.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const n=Object.keys(r);if(n.length>0)throw Error("Unknown option: "+n.join(", "));const i=await ye(e);if(i.type!==$.armor.signed)throw Error("No cleartext signed message.");const a=await yh.fromBinary(i.data,Du,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let n=0;n0)throw Error("Unknown option: "+r.join(", "));return new Cu(e)}async function Bu({userIDs:e=[],passphrase:t,type:r="ecc",rsaBits:n=4096,curve:i="curve25519",keyExpirationTime:a=0,date:s=new Date,subkeys:o=[{}],format:c="armored",config:h,...u}){Xu(h={...ie,...h}),e=Qu(e);const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(0===e.length)throw Error("UserIDs are required for key generation");if("rsa"===r&&nru(e.subkeys[r],e)));let r=[Vh(e,t)];r=r.concat(e.subkeys.map((e=>Gh(e,t))));const n=await Promise.all(r),i=await mu(n[0],n.slice(1),e,t),a=await i.getRevocationCertificate(e.date,t);return i.revocationSignatures=[],{key:i,revocationCertificate:a}}(y,h);return e.getKeys().forEach((({keyPacket:e})=>su(e,h))),{privateKey:el(e,c,h),publicKey:el(e.toPublic(),c,h),revocationCertificate:t}}catch(e){throw X.wrapError("Error generating keypair",e)}}async function zu({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:n=0,date:i,format:a="armored",config:s,...o}){Xu(s={...ie,...s}),t=Qu(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length)throw Error("UserIDs are required for key reformat");const h={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:n,date:i};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const n=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,i={key:n,bind:r},a=await Wh(e.bindingSignatures,n,$.signature.subkeyBinding,i,null,t).catch((()=>({})));return{sign:a.keyFlags&&a.keyFlags[0]&$.keyFlags.signData}}))));const i=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==i.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const a=await mu(n,i,e,t),s=await a.getRevocationCertificate(e.date,t);return a.revocationSignatures=[],{key:a,revocationCertificate:s};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=X.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(h,s);return{privateKey:el(e,a,s),publicKey:el(e.toPublic(),a,s),revocationCertificate:t}}catch(e){throw X.wrapError("Error reformatting keypair",e)}}async function Ru({key:e,revocationCertificate:t,reasonForRevocation:r,date:n=new Date,format:i="armored",config:a,...s}){Xu(a={...ie,...a});const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const s=t?await e.applyRevocationCertificate(t,n,a):await e.revoke(r,n,a);return s.isPrivate()?{privateKey:el(s,i,a),publicKey:el(s.toPublic(),i,a)}:{privateKey:null,publicKey:el(s,i,a)}}catch(e){throw X.wrapError("Error revoking key",e)}}async function Mu({privateKey:e,passphrase:t,config:r,...n}){Xu(r={...ie,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const a=e.clone(!0),s=X.isArray(t)?t:[t];try{return await Promise.all(a.getKeys().map((e=>X.anyPromise(s.map((t=>e.keyPacket.decrypt(t))))))),await a.validate(r),a}catch(e){throw a.clearPrivateParams(),X.wrapError("Error decrypting private key",e)}}async function Lu({privateKey:e,passphrase:t,config:r,...n}){Xu(r={...ie,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const a=e.clone(!0),s=a.getKeys(),o=X.isArray(t)?t:Array(s.length).fill(t);if(o.length!==s.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(s.map((async(e,t)=>{const{keyPacket:n}=e;await n.encrypt(o[t],r),n.clearPrivateParams()}))),a}catch(e){throw a.clearPrivateParams(),X.wrapError("Error encrypting private key",e)}}async function Nu({message:e,encryptionKeys:t,signingKeys:r,passwords:n,sessionKey:i,format:a="armored",signature:s=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:h=[],date:u=new Date,signingUserIDs:l=[],encryptionUserIDs:y=[],signatureNotations:d=[],config:p,...f}){if(Xu(p={...ie,...p}),Vu(e),$u(a),t=Qu(t),r=Qu(r),n=Qu(n),c=Qu(c),h=Qu(h),l=Qu(l),y=Qu(y),d=Qu(d),f.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(f.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(f.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==f.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const g=Object.keys(f);if(g.length>0)throw Error("Unknown option: "+g.join(", "));r||(r=[]);const m=e.fromStream;try{if((r.length||s)&&(e=await e.sign(r,s,c,u,l,d,p)),e=e.compress(await Qh("compression",t,u,y,p),p),e=await e.encrypt(t,n,i,o,h,u,y,p),"object"===a)return e;const f="armored"===a;return Yu(f?e.armor(p):e.write(),m,f?"utf8":"binary")}catch(e){throw X.wrapError("Error encrypting message",e)}}async function Ou({message:e,decryptionKeys:t,passwords:r,sessionKeys:n,verificationKeys:i,expectSigned:a=!1,format:s="utf8",signature:o=null,date:c=new Date,config:h,...u}){if(Xu(h={...ie,...h}),Vu(e),i=Qu(i),t=Qu(t),r=Qu(r),n=Qu(n),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(u.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));try{const u=await e.decrypt(t,r,n,c,h);i||(i=[]);const l={};if(l.signatures=o?await u.verifyDetached(o,i,c,h):await u.verify(i,c,h),l.data="binary"===s?u.getLiteralData():u.getText(),l.filename=u.getFilename(),Ju(l,e),a){if(0===i.length)throw Error("Verification keys are required to verify message signatures");if(0===l.signatures.length)throw Error("Message is not signed");l.data=U([l.data,q((async()=>{await X.anyPromise(l.signatures.map((e=>e.verified)))}))])}return l.data=await Yu(l.data,e.fromStream,s),l}catch(e){throw X.wrapError("Error decrypting message",e)}}async function Fu({message:e,signingKeys:t,format:r="armored",detached:n=!1,signingKeyIDs:i=[],date:a=new Date,signingUserIDs:s=[],signatureNotations:o=[],config:c,...h}){if(Xu(c={...ie,...c}),Wu(e),$u(r),t=Qu(t),i=Qu(i),s=Qu(s),o=Qu(o),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==h.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const u=Object.keys(h);if(u.length>0)throw Error("Unknown option: "+u.join(", "));if(e instanceof Cu&&"binary"===r)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Cu&&n)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let h;if(h=n?await e.signDetached(t,void 0,i,a,s,o,c):await e.sign(t,void 0,i,a,s,o,c),"object"===r)return h;const u="armored"===r;return h=u?h.armor(c):h.write(),n&&(h=R(e.packets.write(),(async(e,t)=>{await Promise.all([I(h,t),H(e).catch((()=>{}))])}))),Yu(h,e.fromStream,u?"utf8":"binary")}catch(e){throw X.wrapError("Error signing message",e)}}async function Hu({message:e,verificationKeys:t,expectSigned:r=!1,format:n="utf8",signature:i=null,date:a=new Date,config:s,...o}){if(Xu(s={...ie,...s}),Wu(e),t=Qu(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Cu&&"binary"===n)throw Error("Can't return cleartext message data as binary");if(e instanceof Cu&&i)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=i?await e.verifyDetached(i,t,a,s):await e.verify(t,a,s),o.data="binary"===n?e.getLiteralData():e.getText(),e.fromStream&&!i&&Ju(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=U([o.data,q((async()=>{await X.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Yu(o.data,e.fromStream,n),o}catch(e){throw X.wrapError("Error verifying signed message",e)}}async function ju({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:n,...i}){if(Xu(n={...ie,...n}),e=Qu(e),r=Qu(r),i.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await Su.generateSessionKey(e,t,r,n)}catch(e){throw X.wrapError("Error generating session key",e)}}async function qu({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:n,passwords:i,format:a="armored",wildcard:s=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:h=[],config:u,...l}){if(Xu(u={...ie,...u}),function(e,t){if(!X.isUint8Array(e))throw Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(e),function(e,t){if(!X.isString(e))throw Error("Parameter ["+(t||"data")+"] must be of type String")}(t,"algorithm"),$u(a),n=Qu(n),i=Qu(i),o=Qu(o),h=Qu(h),l.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(!(n&&0!==n.length||i&&0!==i.length))throw Error("No encryption keys or passwords provided.");try{return el(await Su.encryptSessionKey(e,t,r,n,i,s,o,c,h,u),a,u)}catch(e){throw X.wrapError("Error encrypting session key",e)}}async function Gu({message:e,decryptionKeys:t,passwords:r,date:n=new Date,config:i,...a}){if(Xu(i={...ie,...i}),Vu(e),t=Qu(t),r=Qu(r),a.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const s=Object.keys(a);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await e.decryptSessionKeys(t,r,n,i)}catch(e){throw X.wrapError("Error decrypting session keys",e)}}function Vu(e){if(!(e instanceof Su))throw Error("Parameter [message] needs to be of type Message")}function Wu(e){if(!(e instanceof Cu||e instanceof Su))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function $u(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Zu=Object.keys(ie).length;function Xu(e){const t=Object.keys(e);if(t.length!==Zu)for(const e of t)if(void 0===ie[e])throw Error("Unknown config property: "+e)}function Qu(e){return e&&!X.isArray(e)&&(e=[e]),e}async function Yu(e,t,r="utf8"){const n=X.isStream(e);return"array"===n?H(e):"node"===t?(e=g(e),"binary"!==r&&e.setEncoding(r),e):"web"===t&&"ponyfill"===n?v(e):e}function Ju(e,t){e.data=R(t.packets.stream,(async(t,r)=>{await I(e.data,r,{preventClose:!0});const n=C(r);try{await H(t,(e=>e)),await n.close()}catch(e){await n.abort(e)}}))}function el(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}export{Sh as AEADEncryptedDataPacket,Cu as CleartextMessage,ph as CompressedDataPacket,ah as LiteralDataPacket,Th as MarkerPacket,Su as Message,uh as OnePassSignaturePacket,yh as PacketList,pu as PrivateKey,du as PublicKey,Kh as PublicKeyEncryptedSessionKeyPacket,Dh as PublicKeyPacket,Bh as PublicSubkeyPacket,Rh as SecretKeyPacket,Oh as SecretSubkeyPacket,jh as Signature,ch as SignaturePacket,cu as Subkey,_h as SymEncryptedIntegrityProtectedDataPacket,Uh as SymEncryptedSessionKeyPacket,Ih as SymmetricallyEncryptedDataPacket,Fh as TrustPacket,gi as UnparseablePacket,zh as UserAttributePacket,Nh as UserIDPacket,Mt as _,tt as a,de as armor,At as b,rt as c,ie as config,Tu as createCleartextMessage,Uu as createMessage,gt as d,Ou as decrypt,Mu as decryptKey,Gu as decryptSessionKeys,zt as e,Nu as encrypt,Lu as encryptKey,qu as encryptSessionKey,$ as enums,yr as f,Yt as g,Bu as generateKey,ju as generateSessionKey,it as i,Je as m,xr as r,Iu as readCleartextMessage,wu as readKey,ku as readKeys,Pu as readMessage,bu as readPrivateKey,vu as readPrivateKeys,qh as readSignature,zu as reformatKey,Ru as revokeKey,Fu as sign,dt as u,ye as unarmor,Hu as verify}; +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=Symbol("doneWritingPromise"),r=Symbol("doneWritingResolve"),i=Symbol("doneWritingReject"),n=Symbol("readingIndex");class s extends Array{constructor(){super(),Object.setPrototypeOf(this,s.prototype),this[t]=new Promise(((e,t)=>{this[r]=e,this[i]=t})),this[t].catch((()=>{}))}}function a(e){return e&&e.getReader&&Array.isArray(e)}function o(e){if(!a(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}function c(t){if(a(t))return"array";if(e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t))return"web";if(t&&!(e.ReadableStream&&t instanceof e.ReadableStream)&&"function"==typeof t._read&&"object"==typeof t._readableState)throw Error("Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`");return!(!t||!t.getReader)&&"web-like"}function u(e){return Uint8Array.prototype.isPrototypeOf(e)}function h(e){if(1===e.length)return e[0];let t=0;for(let r=0;r(await this[t],this[n]===this.length?{value:void 0,done:!0}:{value:this[this[n]++],done:!1})}},s.prototype.readToEnd=async function(e){await this[t];const r=e(this.slice(this[n]));return this.length=0,r},s.prototype.clone=function(){const e=new s;return e[t]=this[t].then((()=>{e.push(...this)})),e},o.prototype.write=async function(e){this.stream.push(e)},o.prototype.close=async function(){this.stream[r]()},o.prototype.abort=async function(e){return this.stream[i](e),e},o.prototype.releaseLock=function(){},"object"==typeof e.process&&e.process.versions;const y=new WeakSet,l=Symbol("externalBuffer");function p(e){if(this.stream=e,e[l]&&(this[l]=e[l].slice()),a(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=()=>{})}if(c(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let t=!1;this._read=async()=>t||y.has(e)?{value:void 0,done:!0}:(t=!0,{value:e,done:!1}),this._releaseLock=()=>{if(t)try{y.add(e)}catch(e){}}}function g(e){return c(e)?e:new ReadableStream({start(t){t.enqueue(e),t.close()}})}function d(e){if(c(e))return e;const t=new s;return(async()=>{const r=C(t);await r.write(e),await r.close()})(),t}function f(e){return e.some((e=>c(e)&&!a(e)))?function(e){e=e.map(g);const t=b((async function(e){await Promise.all(i.map((t=>D(t,e))))}));let r=Promise.resolve();const i=e.map(((i,n)=>v(i,((i,s)=>(r=r.then((()=>m(i,t.writable,{preventClose:n!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>a(e)))?function(e){const t=new s;let r=Promise.resolve();return e.forEach(((i,n)=>(r=r.then((()=>m(i,t,{preventClose:n!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):h(e)}async function m(e,t,{preventClose:r=!1,preventAbort:i=!1,preventCancel:n=!1}={}){if(c(e)&&!a(e)){e=g(e);try{if(e[l]){const r=C(t);for(let t=0;t{t=e,r=i})),t=null,r=null)},close:i.close.bind(i),abort:i.error.bind(i)})}}function k(e,t=()=>{},r=()=>{}){if(a(e)){const i=new s;return(async()=>{const n=C(i);try{const i=await U(e),s=t(i),a=r();let o;o=void 0!==s&&void 0!==a?f([s,a]):void 0!==s?s:a,await n.write(o),await n.close()}catch(e){await n.abort(e)}})(),i}if(c(e))return w(e,{async transform(e,r){try{const i=await t(e);void 0!==i&&r.enqueue(i)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const i=t(e),n=r();return void 0!==i&&void 0!==n?f([i,n]):void 0!==i?i:n}function v(e,t){if(c(e)&&!a(e)){let r;const i=new TransformStream({start(e){r=e}}),n=m(e,i.writable),s=b((async function(e){r.error(e),await n,await new Promise(setTimeout)}));return t(i.readable,s.writable),s.readable}e=d(e);const r=new s;return t(e,r),r}function A(e,t){let r;const i=v(e,((e,n)=>{const s=I(e);s.remainder=()=>(s.releaseLock(),m(e,n),i),r=t(s)}));return r}function K(e){if(a(e))return e.clone();if(c(e)){const t=function(e){if(a(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(c(e)){const t=g(e).tee();return t[0][l]=t[1][l]=e[l],t}return[P(e),P(e)]}(e);return S(e,t[0]),t[1]}return P(e)}function E(e){return a(e)?K(e):c(e)?new ReadableStream({start(t){const r=v(e,(async(e,r)=>{const i=I(e),n=C(r);try{for(;;){await n.ready;const{done:e,value:r}=await i.read();if(e){try{t.close()}catch(e){}return void await n.close()}try{t.enqueue(r)}catch(e){}await n.write(r)}}catch(e){t.error(e),await n.abort(e)}}));S(e,r)}}):P(e)}function S(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,i])=>{"constructor"!==r&&(i.value?i.value=i.value.bind(t):i.get=i.get.bind(t),Object.defineProperty(e,r,i))}))}function P(e,t=0,r=1/0){if(a(e))throw Error("Not implemented");if(c(e)){if(t>=0&&r>=0){let i=0;return w(e,{transform(e,n){i=t&&n.enqueue(P(e,Math.max(t-i,0),r-i)),i+=e.length):n.terminate()}})}if(t<0&&(r<0||r===1/0)){let i=[];return k(e,(e=>{e.length>=-t?i=[e]:i.push(e)}),(()=>P(f(i),t,r)))}if(0===t&&r<0){let i;return k(e,(e=>{const n=i?f([i,e]):e;if(n.length>=-r)return i=P(n,r),P(n,t,r);i=n}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),x((async()=>P(await U(e),t,r)))}return e[l]&&(e=f(e[l].concat([e]))),u(e)?e.subarray(t,r===1/0?e.length:r):e.slice(t,r)}async function U(e,t=f){return a(e)?e.readToEnd(t):c(e)?I(e).readToEnd(t):e}async function D(e,t){if(c(e)){if(e.cancel){const r=await e.cancel(t);return await new Promise(setTimeout),r}if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function x(e){const t=new s;return(async()=>{const r=C(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}function I(e){return new p(e)}function C(e){return new o(e)}p.prototype.read=async function(){if(this[l]&&this[l].length){return{done:!1,value:this[l].shift()}}return this._read()},p.prototype.releaseLock=function(){this[l]&&(this.stream[l]=this[l]),this._releaseLock()},p.prototype.cancel=function(e){return this._cancel(e)},p.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:i}=await this.read();if(i+="",r)return t.length?f(t):void 0;const n=i.indexOf("\n")+1;n&&(e=f(t.concat(i.substr(0,n))),t=[]),n!==i.length&&t.push(i.substr(n))}return this.unshift(...t),e},p.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(P(t,1)),r},p.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:i,value:n}=await this.read();if(i)return t.length?f(t):void 0;if(t.push(n),r+=n.length,r>=e){const r=f(t);return this.unshift(P(r,e)),P(r,0,e)}}},p.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},p.prototype.unshift=function(...e){this[l]||(this[l]=[]),1===e.length&&u(e[0])&&this[l].length&&e[0].length&&this[l][0].byteOffset>=e[0].length?this[l][0]=new Uint8Array(this[l][0].buffer,this[l][0].byteOffset-e[0].length,this[l][0].byteLength+e[0].length):this[l].unshift(...e.filter((e=>e&&e.length)))},p.prototype.readToEnd=async function(e=f){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};const B=Symbol("byValue");var T={curve:{nistP256:"nistP256",p256:"nistP256",nistP384:"nistP384",p384:"nistP384",nistP521:"nistP521",p521:"nistP521",secp256k1:"secp256k1",ed25519Legacy:"ed25519Legacy",ed25519:"ed25519Legacy",curve25519Legacy:"curve25519Legacy",curve25519:"curve25519Legacy",brainpoolP256r1:"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,argon2:4,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11,sha3_256:12,sha3_512:14},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,gcm:3,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20,padding:21},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuerKeyID:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34,preferredCipherSuites:39},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4,seipdv2:8},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[B]||(e[B]=[],Object.entries(e).forEach((([t,r])=>{e[B][r]=t}))),void 0!==e[B][t])return e[B][t];throw Error("Invalid enum value.")}},M={preferredHashAlgorithm:T.hash.sha512,preferredSymmetricAlgorithm:T.symmetric.aes256,preferredCompressionAlgorithm:T.compression.uncompressed,aeadProtect:!1,parseAEADEncryptedV4KeysAsLegacy:!1,preferredAEADAlgorithm:T.aead.gcm,aeadChunkSizeByte:12,v6Keys:!1,enableParsingV5Entities:!1,s2kType:T.s2k.iterated,s2kIterationCountByte:224,s2kArgon2Params:{passes:3,parallelism:4,memoryExponent:16},allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,minRSABits:2047,passwordCollisionCheck:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,allowMissingKeyFlags:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([T.symmetric.aes128,T.symmetric.aes192,T.symmetric.aes256]),ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 6.0.0",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],nonDeterministicSignaturesViaNotation:!0,useEllipticFallback:!0,rejectHashAlgorithms:new Set([T.hash.md5,T.hash.ripemd]),rejectMessageHashAlgorithms:new Set([T.hash.md5,T.hash.ripemd,T.hash.sha1]),rejectPublicKeyAlgorithms:new Set([T.publicKey.elgamal,T.publicKey.dsa]),rejectCurves:new Set([T.curve.secp256k1])};const L=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),F={isString:function(e){return"string"==typeof e||e instanceof String},nodeRequire:()=>{},isArray:function(e){return e instanceof Array},isUint8Array:u,isStream:c,getNobleCurve:async(e,t)=>{if(!M.useEllipticFallback)throw Error("This curve is only supported in the full build of OpenPGP.js");const{nobleCurves:r}=await import("./noble_curves.min.mjs");switch(e){case T.publicKey.ecdh:case T.publicKey.ecdsa:{const e=r.get(t);if(!e)throw Error("Unsupported curve");return e}case T.publicKey.x448:return r.get("x448");case T.publicKey.ed448:return r.get("ed448");default:throw Error("Unsupported curve")}},readNumber:function(e){let t=0;for(let r=0;r>8*(t-i-1)&255;return r},readDate:function(e){const t=F.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return F.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return F.readExactSubarray(e,2,2+t)},readExactSubarray:function(e,t,r){if(e.lengtht)throw Error("Input array too long");const r=new Uint8Array(t),i=t-e.length;return r.set(e,i),r},uint8ArrayToMPI:function(e){const t=F.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),i=new Uint8Array([(65280&t)>>8,255&t]);return F.concatUint8Array([i,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t="0123456789abcdef";let r="";return e.forEach((e=>{r+=t[e>>4]+t[15&e]})),r},stringToUint8Array:function(e){return k(e,(e=>{if(!F.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return k(e,r,(()=>r(new Uint8Array,!0)))},concat:f,concatUint8Array:h,equalsUint8Array:function(e,t){if(!F.isUint8Array(e)||!F.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let i=0;i>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){const t=void 0!==e&&e.crypto&&e.crypto.subtle||this.getNodeCrypto()?.webcrypto.subtle;if(!t)throw Error("The WebCrypto API is not available");return t},getNodeCrypto:function(){return this.nodeRequire("crypto")},getNodeZlib:function(){return this.nodeRequire("zlib")},getNodeBuffer:function(){return(this.nodeRequire("buffer")||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return this.nodeRequire("os").cpus().length},isEmailAddress:function(e){if(!F.isString(e))return!1;return/^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u.test(e)},canonicalizeEOL:function(e){let t=!1;return k(e,(e=>{let r;t&&(e=F.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const i=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&i.push(r);if(!i.length)return e;const n=new Uint8Array(e.length+i.length);let s=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return k(e,(e=>{let r;13===(e=t&&10!==e[0]?F.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let i=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const n=r-(10===e[r]?1:0);t&&e.copyWithin(i,t,n),i+=n-t}return e.subarray(0,i)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let i;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){i=e}}))),r(i)}))},selectUint8Array:function(e,t,r){const i=Math.max(t.length,r.length),n=new Uint8Array(i);let s=0;for(let i=0;i{t=F.concatUint8Array([t,e]);const r=[],i=Math.floor(t.length/45),n=45*i,s=N(t.subarray(0,n));for(let e=0;et.length?N(t)+"\n":""))}function O(e){let t="";return k(e,(e=>{t+=e;let r=0;const i=[" ","\t","\r","\n"];for(let e=0;e0&&(n-r)%4!=0;n--)i.includes(t[n])&&r--;const s=z(t.substr(0,n));return t=t.substr(n),s}),(()=>z(t)))}function H(e){return O(e.replace(/-/g,"+").replace(/_/g,"/"))}function _(e,t){let r=j(e).replace(/[\r\n]/g,"");return r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,""),r}function G(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?T.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?T.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?T.armor.signed:/MESSAGE/.test(t[1])?T.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?T.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?T.armor.privateKey:/SIGNATURE/.test(t[1])?T.armor.signature:void 0}function q(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function V(e){const t=function(e){let t=13501623;return k(e,(e=>{const r=$?Math.floor(e.length/4):0,i=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^W[1][t>>16&255]^W[2][t>>8&255]^W[3][255&t];for(let i=4*r;i>8^W[0][255&t^e[i]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e);return j(t)}R?(N=e=>R.from(e).toString("base64"),z=e=>{const t=R.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(N=e=>btoa(F.uint8ArrayToString(e)),z=e=>F.stringToUint8Array(atob(e)));const W=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(8388608&t?8801531:0);W[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)W[1][e]=W[0][e]>>8^W[0][255&W[0][e]];for(let e=0;e<=255;e++)W[2][e]=W[1][e]>>8^W[0][255&W[1][e]];for(let e=0;e<=255;e++)W[3][e]=W[2][e]>>8^W[0][255&W[2][e]];const $=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function Q(e){for(let t=0;t=0&&r!==e.length-1&&(t=e.slice(0,r)),t}function Y(e){return new Promise((async(t,r)=>{try{const i=/^-----[^-]+-----$/m,n=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const a=[];let o,c,u=a,h=[];const y=O(v(e,(async(e,l)=>{const p=I(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=F.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(o)c||s!==T.armor.signed||(i.test(e)?(h=h.join("\r\n"),c=!0,Q(u),u=[],o=!1):h.push(e.replace(/^- /,"")));else if(i.test(e)&&r(Error("Mandatory blank line missing between armor headers and armor data")),n.test(e)){if(Q(u),o=!0,c||s!==T.armor.signed){t({text:h,data:y,headers:a,type:s});break}}else u.push(e);else i.test(e)&&(s=G(e))}}catch(e){return void r(e)}const g=C(l);try{for(;;){await g.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=F.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(i);if(1===t.length)throw Error("Misformed armored text");const n=X(t[0].slice(0,-1));await g.write(n);break}await g.write(r)}await g.ready,await g.close()}catch(e){await g.abort(e)}})))}catch(e){r(e)}})).then((async e=>(a(e.data)&&(e.data=await U(e.data)),e)))}function Z(e,t,r,i,n,s=!1,a=M){let o,c;e===T.armor.signed&&(o=t.text,c=t.hash,t=t.data);const u=s&&E(t),h=[];switch(e){case T.armor.multipartSection:h.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+i+"-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP MESSAGE, PART "+r+"/"+i+"-----\n");break;case T.armor.multipartLast:h.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case T.armor.signed:h.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),h.push(c?`Hash: ${c}\n\n`:"\n"),h.push(o.replace(/^-/gm,"- -")),h.push("\n-----BEGIN PGP SIGNATURE-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP SIGNATURE-----\n");break;case T.armor.message:h.push("-----BEGIN PGP MESSAGE-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP MESSAGE-----\n");break;case T.armor.publicKey:h.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case T.armor.privateKey:h.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case T.armor.signature:h.push("-----BEGIN PGP SIGNATURE-----\n"),h.push(q(n,a)),h.push(j(t)),u&&h.push("=",V(u)),h.push("-----END PGP SIGNATURE-----\n")}return F.concat(h)}async function J(e){switch(e){case T.symmetric.aes128:case T.symmetric.aes192:case T.symmetric.aes256:throw Error("Not a legacy cipher");case T.symmetric.cast5:case T.symmetric.blowfish:case T.symmetric.twofish:case T.symmetric.tripledes:{const{legacyCiphers:t}=await import("./legacy_ciphers.min.mjs"),r=t.get(e);if(!r)throw Error("Unsupported cipher algorithm");return r}default:throw Error("Unsupported cipher algorithm")}}function ee(e){switch(e){case T.symmetric.aes128:case T.symmetric.aes192:case T.symmetric.aes256:case T.symmetric.twofish:return 16;case T.symmetric.blowfish:case T.symmetric.cast5:case T.symmetric.tripledes:return 8;default:throw Error("Unsupported cipher")}}function te(e){switch(e){case T.symmetric.aes128:case T.symmetric.blowfish:case T.symmetric.cast5:return 16;case T.symmetric.aes192:case T.symmetric.tripledes:return 24;case T.symmetric.aes256:case T.symmetric.twofish:return 32;default:throw Error("Unsupported cipher")}}function re(e){return{keySize:te(e),blockSize:ee(e)}}var ie=/*#__PURE__*/Object.freeze({__proto__:null,getCipherParams:re,getLegacyCipher:J});function ne(e,t){let r=e[0],i=e[1],n=e[2],s=e[3];r=ae(r,i,n,s,t[0],7,-680876936),s=ae(s,r,i,n,t[1],12,-389564586),n=ae(n,s,r,i,t[2],17,606105819),i=ae(i,n,s,r,t[3],22,-1044525330),r=ae(r,i,n,s,t[4],7,-176418897),s=ae(s,r,i,n,t[5],12,1200080426),n=ae(n,s,r,i,t[6],17,-1473231341),i=ae(i,n,s,r,t[7],22,-45705983),r=ae(r,i,n,s,t[8],7,1770035416),s=ae(s,r,i,n,t[9],12,-1958414417),n=ae(n,s,r,i,t[10],17,-42063),i=ae(i,n,s,r,t[11],22,-1990404162),r=ae(r,i,n,s,t[12],7,1804603682),s=ae(s,r,i,n,t[13],12,-40341101),n=ae(n,s,r,i,t[14],17,-1502002290),i=ae(i,n,s,r,t[15],22,1236535329),r=oe(r,i,n,s,t[1],5,-165796510),s=oe(s,r,i,n,t[6],9,-1069501632),n=oe(n,s,r,i,t[11],14,643717713),i=oe(i,n,s,r,t[0],20,-373897302),r=oe(r,i,n,s,t[5],5,-701558691),s=oe(s,r,i,n,t[10],9,38016083),n=oe(n,s,r,i,t[15],14,-660478335),i=oe(i,n,s,r,t[4],20,-405537848),r=oe(r,i,n,s,t[9],5,568446438),s=oe(s,r,i,n,t[14],9,-1019803690),n=oe(n,s,r,i,t[3],14,-187363961),i=oe(i,n,s,r,t[8],20,1163531501),r=oe(r,i,n,s,t[13],5,-1444681467),s=oe(s,r,i,n,t[2],9,-51403784),n=oe(n,s,r,i,t[7],14,1735328473),i=oe(i,n,s,r,t[12],20,-1926607734),r=ce(r,i,n,s,t[5],4,-378558),s=ce(s,r,i,n,t[8],11,-2022574463),n=ce(n,s,r,i,t[11],16,1839030562),i=ce(i,n,s,r,t[14],23,-35309556),r=ce(r,i,n,s,t[1],4,-1530992060),s=ce(s,r,i,n,t[4],11,1272893353),n=ce(n,s,r,i,t[7],16,-155497632),i=ce(i,n,s,r,t[10],23,-1094730640),r=ce(r,i,n,s,t[13],4,681279174),s=ce(s,r,i,n,t[0],11,-358537222),n=ce(n,s,r,i,t[3],16,-722521979),i=ce(i,n,s,r,t[6],23,76029189),r=ce(r,i,n,s,t[9],4,-640364487),s=ce(s,r,i,n,t[12],11,-421815835),n=ce(n,s,r,i,t[15],16,530742520),i=ce(i,n,s,r,t[2],23,-995338651),r=ue(r,i,n,s,t[0],6,-198630844),s=ue(s,r,i,n,t[7],10,1126891415),n=ue(n,s,r,i,t[14],15,-1416354905),i=ue(i,n,s,r,t[5],21,-57434055),r=ue(r,i,n,s,t[12],6,1700485571),s=ue(s,r,i,n,t[3],10,-1894986606),n=ue(n,s,r,i,t[10],15,-1051523),i=ue(i,n,s,r,t[1],21,-2054922799),r=ue(r,i,n,s,t[8],6,1873313359),s=ue(s,r,i,n,t[15],10,-30611744),n=ue(n,s,r,i,t[6],15,-1560198380),i=ue(i,n,s,r,t[13],21,1309151649),r=ue(r,i,n,s,t[4],6,-145523070),s=ue(s,r,i,n,t[11],10,-1120210379),n=ue(n,s,r,i,t[2],15,718787259),i=ue(i,n,s,r,t[9],21,-343485551),e[0]=pe(r,e[0]),e[1]=pe(i,e[1]),e[2]=pe(n,e[2]),e[3]=pe(s,e[3])}function se(e,t,r,i,n,s){return t=pe(pe(t,e),pe(i,s)),pe(t<>>32-n,r)}function ae(e,t,r,i,n,s,a){return se(t&r|~t&i,e,t,n,s,a)}function oe(e,t,r,i,n,s,a){return se(t&i|r&~i,e,t,n,s,a)}function ce(e,t,r,i,n,s,a){return se(t^r^i,e,t,n,s,a)}function ue(e,t,r,i,n,s,a){return se(r^(t|~i),e,t,n,s,a)}function he(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const ye="0123456789abcdef".split("");function le(e){let t="",r=0;for(;r<4;r++)t+=ye[e>>8*r+4&15]+ye[e>>8*r&15];return t}function pe(e,t){return e+t&4294967295}const ge=F.getWebCrypto(),de=F.getNodeCrypto(),fe=de&&de.getHashes();function me(e){if(de&&fe.includes(e))return async function(t){const r=de.createHash(e);return k(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function we(e,t){const r=async()=>{const{nobleHashes:t}=await import("./noble_hashes.min.mjs"),r=t.get(e);if(!r)throw Error("Unsupported hash");return r};return async function(e){if(a(e)&&(e=await U(e)),F.isStream(e)){const t=(await r()).create();return k(e,(e=>{t.update(e)}),(()=>t.digest()))}if(ge&&t)return new Uint8Array(await ge.digest(t,e));return(await r())(e)}}var be={md5:me("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let i;for(i=64;i<=e.length;i+=64)ne(r,he(e.substring(i-64,i)));e=e.substring(i-64);const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i>2]|=e.charCodeAt(i)<<(i%4<<3);if(n[i>>2]|=128<<(i%4<<3),i>55)for(ne(r,n),i=0;i<16;i++)n[i]=0;return n[14]=8*t,ne(r,n),r}(F.uint8ArrayToString(e));return F.hexToUint8Array(function(e){for(let t=0;t0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ae(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Ke(e,t){ve(e);const r=t.outputLen;if(e.lengthnew Uint8Array(e.buffer,e.byteOffset,e.byteLength),Se=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Pe=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw Error("Non little-endian hardware is not supported");function Ue(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!ke(e))throw Error("Uint8Array expected, got "+typeof e);e=Be(e)}return e}function De(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i(Object.assign(t,e),t);function Ie(e,t,r,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,i);const n=BigInt(32),s=BigInt(4294967295),a=Number(r>>n&s),o=Number(r&s);e.setUint32(t+0,a,i),e.setUint32(t+4,o,i)}function Ce(e){return e.byteOffset%4==0}function Be(e){return Uint8Array.from(e)}function Te(...e){for(let t=0;t(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Ne{constructor(e,t){this.blockLen=Me,this.outputLen=Me,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,ve(e=Ue(e),16);const r=Pe(e);let i=r.getUint32(0,!1),n=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:Re(i),s1:Re(n),s2:Re(s),s3:Re(a)}),({s0:i,s1:n,s2:s,s3:a}={s3:(h=s)<<31|(y=a)>>>1,s2:(u=n)<<31|h>>>1,s1:(c=i)<<31|u>>>1,s0:c>>>1^225<<24&-(1&y)});var c,u,h,y;const l=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(l))throw Error(`ghash: wrong window size=${l}, should be 2, 4 or 8`);this.W=l;const p=128/l,g=this.windowSize=2**l,d=[];for(let e=0;e>>l-a-1&1))continue;const{s0:c,s1:u,s2:h,s3:y}=o[l*e+a];r^=c,i^=u,n^=h,s^=y}d.push({s0:r,s1:i,s2:n,s3:s})}this.t=d}_updateBlock(e,t,r,i){e^=this.s0,t^=this.s1,r^=this.s2,i^=this.s3;const{W:n,t:s,windowSize:a}=this;let o=0,c=0,u=0,h=0;const y=(1<>>8*e&255;for(let e=8/n-1;e>=0;e--){const r=t>>>n*e&y,{s0:i,s1:p,s2:g,s3:d}=s[l*a+r];o^=i,c^=p,u^=g,h^=d,l+=1}}this.s0=o,this.s1=c,this.s2=u,this.s3=h}update(e){e=Ue(e),Ae(this);const t=Se(e),r=Math.floor(e.length/Me),i=e.length%Me;for(let e=0;e>>1|r,r=(1&i)<<7}return e[0]^=225&-t,e}(Be(e=Ue(e)));super(r,t),Te(r)}update(e){e=Ue(e),Ae(this);const t=Se(e),r=e.length%Me,i=Math.floor(e.length/Me);for(let e=0;ee(r,t.length).update(Ue(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const Oe=je(((e,t)=>new Ne(e,t)));je(((e,t)=>new ze(e,t)));const He=16,_e=new Uint8Array(He),Ge=283;function qe(e){return e<<1^Ge&-(e>>7)}function Ve(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=qe(e);return r}const We=/* @__PURE__ */(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=qe(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let i=e[255-r];i|=i<<8,t[e[r]]=255&(i^i>>4^i>>5^i>>6^i>>7^99)}return Te(e),t})(),$e=/* @__PURE__ */We.map(((e,t)=>We.indexOf(t))),Qe=e=>e<<24|e>>>8,Xe=e=>e<<8|e>>>24,Ye=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function Ze(e,t){if(256!==e.length)throw Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,i)=>t(e[i]))),i=r.map(Xe),n=i.map(Xe),s=n.map(Xe),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let u=0;u<256;u++){const h=256*t+u;a[h]=r[t]^i[u],o[h]=n[t]^s[u],c[h]=e[t]<<8|e[u]}return{sbox:e,sbox2:c,T0:r,T1:i,T2:n,T3:s,T01:a,T23:o}}const Je=/* @__PURE__ */Ze(We,(e=>Ve(e,3)<<24|e<<16|e<<8|Ve(e,2))),et=/* @__PURE__ */Ze($e,(e=>Ve(e,11)<<24|Ve(e,13)<<16|Ve(e,9)<<8|Ve(e,14))),tt=/* @__PURE__ */(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=qe(r))e[t]=r;return e})();function rt(e){ve(e);const t=e.length;if(![16,24,32].includes(t))throw Error("aes: wrong key size: should be 16, 24 or 32, got: "+t);const{sbox2:r}=Je,i=[];Ce(e)||i.push(e=Be(e));const n=Se(e),s=n.length,a=e=>st(r,e,e,e,e),o=new Uint32Array(t+28);o.set(n);for(let e=s;e6&&e%s==4&&(t=a(t)),o[e]=o[e-s]^t}return Te(...i),o}function it(e){const t=rt(e),r=t.slice(),i=t.length,{sbox2:n}=Je,{T0:s,T1:a,T2:o,T3:c}=et;for(let e=0;e>>8&255]^o[i>>>16&255]^c[i>>>24]}return r}function nt(e,t,r,i,n,s){return e[r<<8&65280|i>>>8&255]^t[n>>>8&65280|s>>>24&255]}function st(e,t,r,i,n){return e[255&t|65280&r]|e[i>>>16&255|n>>>16&65280]<<16}function at(e,t,r,i,n){const{sbox2:s,T01:a,T23:o}=Je;let c=0;t^=e[c++],r^=e[c++],i^=e[c++],n^=e[c++];const u=e.length/4-2;for(let s=0;s=0;e--)r=r+(255&s[e])|0,s[e]=255&r,r>>>=8;({s0:o,s1:c,s2:u,s3:h}=at(e,a[0],a[1],a[2],a[3]))}const p=He*Math.floor(y.length/4);if(p>>0,o.setUint32(h,l,t),({s0:p,s1:g,s2:d,s3:f}=at(e,a[0],a[1],a[2],a[3]));const m=He*Math.floor(c.length/4);if(mr(e,t),decrypt:(e,t)=>r(e,t)}}));const lt=xe({blockSize:16,nonceLength:16},(function(e,t,r={}){ve(e),ve(t,16);const i=!r.disablePadding;return{encrypt(r,n){const s=rt(e),{b:a,o,out:c}=function(e,t,r){ve(e);let i=e.length;const n=i%He;if(!t&&0!==n)throw Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Ce(e)||(e=Be(e));const s=Se(e);if(t){let e=He-n;e||(e=He),i+=e}const a=ct(i,r);return{b:s,o:Se(a),out:a}}(r,i,n);let u=t;const h=[s];Ce(u)||h.push(u=Be(u));const y=Se(u);let l=y[0],p=y[1],g=y[2],d=y[3],f=0;for(;f+4<=a.length;)l^=a[f+0],p^=a[f+1],g^=a[f+2],d^=a[f+3],({s0:l,s1:p,s2:g,s3:d}=at(s,l,p,g,d)),o[f++]=l,o[f++]=p,o[f++]=g,o[f++]=d;if(i){const e=function(e){const t=new Uint8Array(16),r=Se(t);t.set(e);const i=He-e.length;for(let e=He-i;e16)throw Error("aes/pcks5: wrong padding");const n=e.subarray(0,-i);for(let t=0;tr(e,!0,t),decrypt:(e,t)=>r(e,!1,t)}}));const gt=xe({blockSize:16,nonceLength:12,tagLength:16},(function(e,t,r){if(ve(e),ve(t),void 0!==r&&ve(r),t.length<8)throw Error("aes/gcm: invalid nonce length");const i=16;function n(e,t,i){const n=function(e,t,r,i,n){const s=null==n?0:n.length,a=e.create(r,i.length+s);n&&a.update(n),a.update(i);const o=new Uint8Array(16),c=Pe(o);n&&Ie(c,0,BigInt(8*s),t),Ie(c,8,BigInt(8*i.length),t),a.update(o);const u=a.digest();return Te(o),u}(Oe,!1,e,i,r);for(let e=0;e=2**32)throw Error("plaintext should be less than 4gb");const r=rt(e);if(16===t.length)ft(r,t);else{const e=Se(t);let i=e[0],n=e[1];for(let t=0,s=1;t<6;t++)for(let t=2;t=2**32)throw Error("ciphertext should be less than 4gb");const r=it(e),i=t.length/8-1;if(1===i)mt(r,t);else{const e=Se(t);let n=e[0],s=e[1];for(let t=0,a=6*i;t<6;t++)for(let t=2*i;t>=1;t-=2,a--){s^=Ye(a);const{s0:i,s1:o,s2:c,s3:u}=ot(r,n,s,e[t],e[t+1]);n=i,s=o,e[t]=c,e[t+1]=u}e[0]=n,e[1]=s}r.fill(0)}},bt=new Uint8Array(8).fill(166),kt=xe({blockSize:8},(e=>({encrypt(t){if(ve(t),!t.length||t.length%8!=0)throw Error("invalid plaintext length");if(8===t.length)throw Error("8-byte keys not allowed in AESKW, use AESKWP instead");const r=function(...e){let t=0;for(let r=0;r!0),(()=>!1))}async _runCBC(e,t){const r="AES-CBC";this.keyRef=this.keyRef||await At.importKey("raw",this.key,r,!1,["encrypt"]);const i=await At.encrypt({name:r,iv:t||this.zeroBlock},this.keyRef,e);return new Uint8Array(i).subarray(0,e.length)}async encryptChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,i=F.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),n=F.concatUint8Array([this.prevBlock,i.subarray(0,i.length-this.blockSize)]),s=await this._runCBC(n);return Dt(s,i),this.prevBlock=s.slice(-this.blockSize),r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,s}let i;if(this.i+=r.length,this.i===this.nextBlock.length){const t=this.nextBlock;i=await this._runCBC(this.prevBlock),Dt(i,t),this.prevBlock=i.slice(),this.i=0;const n=e.subarray(r.length);this.nextBlock.set(n,this.i),this.i+=n.length}else i=new Uint8Array;return i}async finish(){let e;if(0===this.i)e=new Uint8Array;else{this.nextBlock=this.nextBlock.subarray(0,this.i);const t=this.nextBlock,r=await this._runCBC(this.prevBlock);Dt(r,t),e=r.subarray(0,t.length)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.keyRef=null,this.key=null}async encrypt(e){const t=(await this._runCBC(F.concatUint8Array([new Uint8Array(this.blockSize),e]),this.iv)).subarray(0,e.length);return Dt(t,e),this.clearSensitiveData(),t}}class Ut{constructor(e,t,r,i){this.forEncryption=e;const{blockSize:n}=re(t);this.key=vt.expandKeyLE(r),i.byteOffset%4!=0&&(i=i.slice()),this.prevBlock=xt(i),this.nextBlock=new Uint8Array(n),this.i=0,this.blockSize=n}_runCFB(e){const t=xt(e),r=new Uint8Array(e.length),i=xt(r);for(let e=0;e+4<=i.length;e+=4){const{s0:r,s1:n,s2:s,s3:a}=vt.encrypt(this.key,this.prevBlock[0],this.prevBlock[1],this.prevBlock[2],this.prevBlock[3]);i[e+0]=t[e+0]^r,i[e+1]=t[e+1]^n,i[e+2]=t[e+2]^s,i[e+3]=t[e+3]^a,this.prevBlock=(this.forEncryption?i:t).slice(e,e+4)}return r}async processChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,i=F.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),n=this._runCFB(i);return r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,n}let i;if(this.i+=r.length,this.i===this.nextBlock.length){i=this._runCFB(this.nextBlock),this.i=0;const t=e.subarray(r.length);this.nextBlock.set(t,this.i),this.i+=t.length}else i=new Uint8Array;return i}async finish(){let e;if(0===this.i)e=new Uint8Array;else{e=this._runCFB(this.nextBlock).subarray(0,this.i)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.key.fill(0)}}function Dt(e,t){const r=Math.min(e.length,t.length);for(let i=0;inew Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));var It=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,i){const n=T.read(T.symmetric,e);if(Kt&&St[n])return function(e,t,r,i){const n=T.read(T.symmetric,e),s=new Kt.createDecipheriv(St[n],t,i);return k(r,(e=>new Uint8Array(s.update(e))))}(e,t,r,i);if(F.isAES(e))return async function(e,t,r,i){if(F.isStream(r)){const n=new Ut(!1,e,t,i);return k(r,(e=>n.processChunk(e)),(()=>n.finish()))}return pt(t,i).decrypt(r)}(e,t,r,i);const s=new(await J(e))(t),a=s.blockSize;let o=i,c=new Uint8Array;const u=e=>{e&&(c=F.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,i=0;for(;e?c.length>=a:c.length;){const e=s.encrypt(o);for(o=c.subarray(0,a),r=0;rnew Uint8Array(s.update(e))))}(e,t,r,i);if(F.isAES(e))return async function(e,t,r,i){if(At&&await Pt.isSupported(e)){const n=new Pt(e,t,i);return F.isStream(r)?k(r,(e=>n.encryptChunk(e)),(()=>n.finish())):n.encrypt(r)}if(F.isStream(r)){const n=new Ut(!0,e,t,i);return k(r,(e=>n.processChunk(e)),(()=>n.finish()))}return pt(t,i).encrypt(r)}(e,t,r,i);const a=new(await J(e))(t),o=a.blockSize,c=i.slice();let u=new Uint8Array;const h=e=>{e&&(u=F.concatUint8Array([u,e]));const t=new Uint8Array(u.length);let r,i=0;for(;e?u.length>=o:u.length;){const e=a.encrypt(c);for(r=0;rn.encrypt(e),a=e=>n.decrypt(e);let o;function c(e,t,r,n){const a=t.length/Xt|0;!function(e,t){const r=F.nbits(Math.max(e.length,t.length)/Xt|0)-1;for(let e=i+1;e<=r;e++)o[e]=F.double(o[e-1]);i=r}(t,n);const c=F.concatUint8Array([tr.subarray(0,15-r.length),rr,r]),u=63&c[15];c[15]&=192;const h=s(c),y=F.concatUint8Array([h,er(h.subarray(0,8),h.subarray(1,9))]),l=F.shiftRight(y.subarray(0+(u>>3),17+(u>>3)),8-(7&u)).subarray(1),p=new Uint8Array(Xt),g=new Uint8Array(t.length+Yt);let d,f=0;for(d=0;d{r+=t[e>>4]+t[15&e]})),BigInt("0x0"+r)}function gr(e,t){const r=e%t;return ryr;){const e=i&lr;i>>=lr;s=e?s*n%r:s,n=n*n%r}return s}function fr(e){return e>=yr?e:-e}function mr(e,t){const{gcd:r,x:i}=function(e,t){let r=BigInt(0),i=BigInt(1),n=BigInt(1),s=BigInt(0),a=fr(e),o=fr(t);const c=eNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return t}function br(e,t){return(e>>BigInt(t)&lr)===yr?0:1}function kr(e){const t=e>=lr)!==t;)r++;return r}function vr(e){const t=e>=r)!==t;)i++;return i}function Ar(e,t="be",r){let i=e.toString(16);i.length%2==1&&(i="0"+i);const n=i.length/2,s=new Uint8Array(r||n),a=r?r-n:0;let o=0;for(;oe&&(a=gr(a,n<gr(e,r)!==t))}(e)&&(!!function(e,t=BigInt(2)){return dr(t,e-Ur,e)===Ur}(e)&&!!function(e,t){const r=kr(e);t||(t=Math.max(1,r/48|0));const i=e-Ur;let n=0;for(;!br(i,n);)n++;const s=e>>BigInt(n);for(;t>0;t--){let t,r=dr(Sr(BigInt(2),i),s,e);if(r!==Ur&&r!==i){for(t=1;tBigInt(e)));const Cr=[];function Br(e,t){const r=e.length;if(r>t-11)throw Error("Message too long");const i=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!i;if(t)return F.selectUint8Array(a,s,t);if(a)return s;throw Error("Decryption error")}function Mr(e,t,r){let i;if(t.length!==be.getHashByteLength(e))throw Error("Invalid hash length");const n=new Uint8Array(Cr[e].length);for(i=0;i=t)throw Error("Data too large.");const c=gr(i,s-Nr),u=gr(i,n-Nr),h=Sr(BigInt(2),t),y=dr(mr(h,t),r,t);e=gr(e*y,t);const l=dr(e,u,n),p=dr(e,c,s),g=gr(a*(p-l),s);let d=g*n+l;return d=gr(d*h,t),Tr(Ar(d,"be",vr(t)),o)}(e,t,r,i,n,s,a,o)},encrypt:async function(e,t,r){return F.getNodeCrypto()?async function(e,t,r){const i=jr(t,r),n={key:i,format:"jwk",type:"pkcs1",padding:Rr.constants.RSA_PKCS1_PADDING};return new Uint8Array(Rr.publicEncrypt(n,e))}(e,t,r):async function(e,t,r){if(t=pr(t),e=pr(Br(e,vr(t))),r=pr(r),e>=t)throw Error("Message size cannot exceed modulus size");return Ar(dr(e,r,t),"be",vr(t))}(e,t,r)},generate:async function(e,t){if(t=BigInt(t),F.getWebCrypto()){const r={name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ar(t),hash:{name:"SHA-1"}},i=await Fr.generateKey(r,!0,["sign","verify"]);return Or(await Fr.exportKey("jwk",i.privateKey),t)}if(F.getNodeCrypto()){const r={modulusLength:e,publicExponent:wr(t),publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}},i=await new Promise(((e,t)=>{Rr.generateKeyPair("rsa",r,((r,i,n)=>{r?t(r):e(n)}))}));return Or(i,t)}let r,i,n;do{i=Dr(e-(e>>1),t,40),r=Dr(e>>1,t,40),n=r*i}while(kr(n)!==e);const s=(r-Nr)*(i-Nr);return i=r.length)throw Error("Digest size cannot exceed key modulus size");if(t&&!F.isStream(t))if(F.getWebCrypto())try{return await async function(e,t,r,i,n,s,a,o){const c=await zr(r,i,n,s,a,o),u={name:"RSASSA-PKCS1-v1_5",hash:{name:e}},h=await Fr.importKey("jwk",c,u,!1,["sign"]);return new Uint8Array(await Fr.sign("RSASSA-PKCS1-v1_5",h,t))}(T.read(T.webHash,e),t,r,i,n,s,a,o)}catch(e){F.printDebugError(e)}else if(F.getNodeCrypto())return async function(e,t,r,i,n,s,a,o){const c=Rr.createSign(T.read(T.hash,e));c.write(t),c.end();const u=await zr(r,i,n,s,a,o);return new Uint8Array(c.sign({key:u,format:"jwk",type:"pkcs1"}))}(e,t,r,i,n,s,a,o);return async function(e,t,r,i){t=pr(t);const n=pr(Mr(e,i,vr(t)));return r=pr(r),Ar(dr(n,r,t),"be",vr(t))}(e,r,n,c)},validateParams:async function(e,t,r,i,n,s){if(e=pr(e),(i=pr(i))*(n=pr(n))!==e)return!1;const a=BigInt(2);if(gr(i*(s=pr(s)),n)!==BigInt(1))return!1;t=pr(t),r=pr(r);const o=Sr(a,a<=r)throw Error("Signature size cannot exceed modulus size");const s=Ar(dr(t,i,r),"be",vr(r)),a=Mr(e,n,vr(r));return F.equalsUint8Array(s,a)}(e,r,i,n,s)}});const _r=BigInt(1);var Gr=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,i,n){return e=pr(e),t=pr(t),r=pr(r),Tr(Ar(gr(mr(dr(e,i=pr(i),r),r)*t,r),"be",vr(r)),n)},encrypt:async function(e,t,r,i){t=pr(t),r=pr(r),i=pr(i);const n=pr(Br(e,vr(t))),s=Sr(_r,t-_r);return{c1:Ar(dr(r,s,t)),c2:Ar(gr(dr(i,s,t)*n,t))}},validateParams:async function(e,t,r,i){if(e=pr(e),t=pr(t),r=pr(r),t<=_r||t>=e)return!1;const n=BigInt(kr(e));if(n>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=i>>24&255,e[t+5]=i>>16&255,e[t+6]=i>>8&255,e[t+7]=255&i}function si(e,t,r,i){return function(e,t,r,i,n){var s,a=0;for(s=0;s>>8)-1}(e,t,r,i,32)}function ai(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function oi(e){var t,r,i=1;for(t=0;t<16;t++)r=e[t]+i+65535,i=Math.floor(r/65536),e[t]=r-65536*i;e[0]+=i-1+37*(i-1)}function ci(e,t,r){for(var i,n=~(r-1),s=0;s<16;s++)i=n&(e[s]^t[s]),e[s]^=i,t[s]^=i}function ui(e,t){var r,i,n,s=Wr(),a=Wr();for(r=0;r<16;r++)a[r]=t[r];for(oi(a),oi(a),oi(a),i=0;i<2;i++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),n=s[15]>>16&1,s[14]&=65535,ci(a,s,1-n)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function hi(e,t){var r=new Uint8Array(32),i=new Uint8Array(32);return ui(r,e),ui(i,t),si(r,0,i,0)}function yi(e){var t=new Uint8Array(32);return ui(t,e),1&t[0]}function li(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function pi(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]+r[i]}function gi(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]-r[i]}function di(e,t,r){var i,n,s=0,a=0,o=0,c=0,u=0,h=0,y=0,l=0,p=0,g=0,d=0,f=0,m=0,w=0,b=0,k=0,v=0,A=0,K=0,E=0,S=0,P=0,U=0,D=0,x=0,I=0,C=0,B=0,T=0,M=0,L=0,F=r[0],R=r[1],N=r[2],z=r[3],j=r[4],O=r[5],H=r[6],_=r[7],G=r[8],q=r[9],V=r[10],W=r[11],$=r[12],Q=r[13],X=r[14],Y=r[15];s+=(i=t[0])*F,a+=i*R,o+=i*N,c+=i*z,u+=i*j,h+=i*O,y+=i*H,l+=i*_,p+=i*G,g+=i*q,d+=i*V,f+=i*W,m+=i*$,w+=i*Q,b+=i*X,k+=i*Y,a+=(i=t[1])*F,o+=i*R,c+=i*N,u+=i*z,h+=i*j,y+=i*O,l+=i*H,p+=i*_,g+=i*G,d+=i*q,f+=i*V,m+=i*W,w+=i*$,b+=i*Q,k+=i*X,v+=i*Y,o+=(i=t[2])*F,c+=i*R,u+=i*N,h+=i*z,y+=i*j,l+=i*O,p+=i*H,g+=i*_,d+=i*G,f+=i*q,m+=i*V,w+=i*W,b+=i*$,k+=i*Q,v+=i*X,A+=i*Y,c+=(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,S+=i*q,P+=i*V,U+=i*W,D+=i*$,x+=i*Q,I+=i*X,C+=i*Y,m+=(i=t[12])*F,w+=i*R,b+=i*N,k+=i*z,v+=i*j,A+=i*O,K+=i*H,E+=i*_,S+=i*G,P+=i*q,U+=i*V,D+=i*W,x+=i*$,I+=i*Q,C+=i*X,B+=i*Y,w+=(i=t[13])*F,b+=i*R,k+=i*N,v+=i*z,A+=i*j,K+=i*O,E+=i*H,S+=i*_,P+=i*G,U+=i*q,D+=i*V,x+=i*W,I+=i*$,C+=i*Q,B+=i*X,T+=i*Y,b+=(i=t[14])*F,k+=i*R,v+=i*N,A+=i*z,K+=i*j,E+=i*O,S+=i*H,P+=i*_,U+=i*G,D+=i*q,x+=i*V,I+=i*W,C+=i*$,B+=i*Q,T+=i*X,M+=i*Y,k+=(i=t[15])*F,a+=38*(A+=i*N),o+=38*(K+=i*z),c+=38*(E+=i*j),u+=38*(S+=i*O),h+=38*(P+=i*H),y+=38*(U+=i*_),l+=38*(D+=i*G),p+=38*(x+=i*q),g+=38*(I+=i*V),d+=38*(C+=i*W),f+=38*(B+=i*$),m+=38*(T+=i*Q),w+=38*(M+=i*X),b+=38*(L+=i*Y),s=(i=(s+=38*(v+=i*R))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),a=(i=a+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),k=(i=k+n+65535)-65536*(n=Math.floor(i/65536)),s=(i=(s+=n-1+37*(n-1))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),a=(i=a+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),k=(i=k+n+65535)-65536*(n=Math.floor(i/65536)),s+=n-1+37*(n-1),e[0]=s,e[1]=a,e[2]=o,e[3]=c,e[4]=u,e[5]=h,e[6]=y,e[7]=l,e[8]=p,e[9]=g,e[10]=d,e[11]=f,e[12]=m,e[13]=w,e[14]=b,e[15]=k}function fi(e,t){di(e,t,t)}function mi(e,t){var r,i=Wr();for(r=0;r<16;r++)i[r]=t[r];for(r=253;r>=0;r--)fi(i,i),2!==r&&4!==r&&di(i,i,t);for(r=0;r<16;r++)e[r]=i[r]}function wi(e,t,r){var i,n,s=new Uint8Array(32),a=new Float64Array(80),o=Wr(),c=Wr(),u=Wr(),h=Wr(),y=Wr(),l=Wr();for(n=0;n<31;n++)s[n]=t[n];for(s[31]=127&t[31]|64,s[0]&=248,li(a,r),n=0;n<16;n++)c[n]=a[n],h[n]=o[n]=u[n]=0;for(o[0]=h[0]=1,n=254;n>=0;--n)ci(o,c,i=s[n>>>3]>>>(7&n)&1),ci(u,h,i),pi(y,o,u),gi(o,o,u),pi(u,c,h),gi(c,c,h),fi(h,y),fi(l,o),di(o,u,o),di(u,c,y),pi(y,o,u),gi(o,o,u),fi(c,o),gi(u,h,l),di(o,u,Zr),pi(o,o,h),di(u,u,o),di(o,h,l),di(h,c,a),fi(c,y),ci(o,c,i),ci(u,h,i);for(n=0;n<16;n++)a[n+16]=o[n],a[n+32]=u[n],a[n+48]=c[n],a[n+64]=h[n];var p=a.subarray(32),g=a.subarray(16);return mi(p,p),di(g,g,p),ui(e,g),0}function bi(e,t){return wi(e,t,Qr)}var ki=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function vi(e,t,r,i){for(var n,s,a,o,c,u,h,y,l,p,g,d,f,m,w,b,k,v,A,K,E,S,P,U,D,x,I=new Int32Array(16),C=new Int32Array(16),B=e[0],T=e[1],M=e[2],L=e[3],F=e[4],R=e[5],N=e[6],z=e[7],j=t[0],O=t[1],H=t[2],_=t[3],G=t[4],q=t[5],V=t[6],W=t[7],$=0;i>=128;){for(A=0;A<16;A++)K=8*A+$,I[A]=r[K+0]<<24|r[K+1]<<16|r[K+2]<<8|r[K+3],C[A]=r[K+4]<<24|r[K+5]<<16|r[K+6]<<8|r[K+7];for(A=0;A<80;A++)if(n=B,s=T,a=M,o=L,c=F,u=R,h=N,z,l=j,p=O,g=H,d=_,f=G,m=q,w=V,W,P=65535&(S=W),U=S>>>16,D=65535&(E=z),x=E>>>16,P+=65535&(S=(G>>>14|F<<18)^(G>>>18|F<<14)^(F>>>9|G<<23)),U+=S>>>16,D+=65535&(E=(F>>>14|G<<18)^(F>>>18|G<<14)^(G>>>9|F<<23)),x+=E>>>16,P+=65535&(S=G&q^~G&V),U+=S>>>16,D+=65535&(E=F&R^~F&N),x+=E>>>16,E=ki[2*A],P+=65535&(S=ki[2*A+1]),U+=S>>>16,D+=65535&E,x+=E>>>16,E=I[A%16],U+=(S=C[A%16])>>>16,D+=65535&E,x+=E>>>16,D+=(U+=(P+=65535&S)>>>16)>>>16,P=65535&(S=v=65535&P|U<<16),U=S>>>16,D=65535&(E=k=65535&D|(x+=D>>>16)<<16),x=E>>>16,P+=65535&(S=(j>>>28|B<<4)^(B>>>2|j<<30)^(B>>>7|j<<25)),U+=S>>>16,D+=65535&(E=(B>>>28|j<<4)^(j>>>2|B<<30)^(j>>>7|B<<25)),x+=E>>>16,U+=(S=j&O^j&H^O&H)>>>16,D+=65535&(E=B&T^B&M^T&M),x+=E>>>16,y=65535&(D+=(U+=(P+=65535&S)>>>16)>>>16)|(x+=D>>>16)<<16,b=65535&P|U<<16,P=65535&(S=d),U=S>>>16,D=65535&(E=o),x=E>>>16,U+=(S=v)>>>16,D+=65535&(E=k),x+=E>>>16,T=n,M=s,L=a,F=o=65535&(D+=(U+=(P+=65535&S)>>>16)>>>16)|(x+=D>>>16)<<16,R=c,N=u,z=h,B=y,O=l,H=p,_=g,G=d=65535&P|U<<16,q=f,V=m,W=w,j=b,A%16==15)for(K=0;K<16;K++)E=I[K],P=65535&(S=C[K]),U=S>>>16,D=65535&E,x=E>>>16,E=I[(K+9)%16],P+=65535&(S=C[(K+9)%16]),U+=S>>>16,D+=65535&E,x+=E>>>16,k=I[(K+1)%16],P+=65535&(S=((v=C[(K+1)%16])>>>1|k<<31)^(v>>>8|k<<24)^(v>>>7|k<<25)),U+=S>>>16,D+=65535&(E=(k>>>1|v<<31)^(k>>>8|v<<24)^k>>>7),x+=E>>>16,k=I[(K+14)%16],U+=(S=((v=C[(K+14)%16])>>>19|k<<13)^(k>>>29|v<<3)^(v>>>6|k<<26))>>>16,D+=65535&(E=(k>>>19|v<<13)^(v>>>29|k<<3)^k>>>6),x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,I[K]=65535&D|x<<16,C[K]=65535&P|U<<16;P=65535&(S=j),U=S>>>16,D=65535&(E=B),x=E>>>16,E=e[0],U+=(S=t[0])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[0]=B=65535&D|x<<16,t[0]=j=65535&P|U<<16,P=65535&(S=O),U=S>>>16,D=65535&(E=T),x=E>>>16,E=e[1],U+=(S=t[1])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[1]=T=65535&D|x<<16,t[1]=O=65535&P|U<<16,P=65535&(S=H),U=S>>>16,D=65535&(E=M),x=E>>>16,E=e[2],U+=(S=t[2])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[2]=M=65535&D|x<<16,t[2]=H=65535&P|U<<16,P=65535&(S=_),U=S>>>16,D=65535&(E=L),x=E>>>16,E=e[3],U+=(S=t[3])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[3]=L=65535&D|x<<16,t[3]=_=65535&P|U<<16,P=65535&(S=G),U=S>>>16,D=65535&(E=F),x=E>>>16,E=e[4],U+=(S=t[4])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[4]=F=65535&D|x<<16,t[4]=G=65535&P|U<<16,P=65535&(S=q),U=S>>>16,D=65535&(E=R),x=E>>>16,E=e[5],U+=(S=t[5])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[5]=R=65535&D|x<<16,t[5]=q=65535&P|U<<16,P=65535&(S=V),U=S>>>16,D=65535&(E=N),x=E>>>16,E=e[6],U+=(S=t[6])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[6]=N=65535&D|x<<16,t[6]=V=65535&P|U<<16,P=65535&(S=W),U=S>>>16,D=65535&(E=z),x=E>>>16,E=e[7],U+=(S=t[7])>>>16,D+=65535&E,x+=E>>>16,x+=(D+=(U+=(P+=65535&S)>>>16)>>>16)>>>16,e[7]=z=65535&D|x<<16,t[7]=W=65535&P|U<<16,$+=128,i-=128}return i}function Ai(e,t,r){var i,n=new Int32Array(8),s=new Int32Array(8),a=new Uint8Array(256),o=r;for(n[0]=1779033703,n[1]=3144134277,n[2]=1013904242,n[3]=2773480762,n[4]=1359893119,n[5]=2600822924,n[6]=528734635,n[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,vi(n,s,t,r),r%=128,i=0;i=0;--n)Ei(e,t,i=r[n/8|0]>>(7&n)&1),Ki(t,e),Ki(e,e),Ei(e,t,i)}function Ui(e,t){var r=[Wr(),Wr(),Wr(),Wr()];ai(r[0],ti),ai(r[1],ri),ai(r[2],Yr),di(r[3],ti,ri),Pi(e,r,t)}function Di(e,t,r){var i,n=new Uint8Array(64),s=[Wr(),Wr(),Wr(),Wr()];for(r||$r(t,32),Ai(n,t,32),n[0]&=248,n[31]&=127,n[31]|=64,Ui(s,n),Si(e,s),i=0;i<32;i++)t[i+32]=e[i];return 0}var xi=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ii(e,t){var r,i,n,s;for(i=63;i>=32;--i){for(r=0,n=i-32,s=i-12;n>4)*xi[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*xi[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function Ci(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;Ii(e,r)}function Bi(e,t){var r=Wr(),i=Wr(),n=Wr(),s=Wr(),a=Wr(),o=Wr(),c=Wr();return ai(e[2],Yr),li(e[1],t),fi(n,e[1]),di(s,n,Jr),gi(n,n,e[2]),pi(s,e[2],s),fi(a,s),fi(o,a),di(c,o,a),di(r,c,n),di(r,r,s),function(e,t){var r,i=Wr();for(r=0;r<16;r++)i[r]=t[r];for(r=250;r>=0;r--)fi(i,i),1!==r&&di(i,i,t);for(r=0;r<16;r++)e[r]=i[r]}(r,r),di(r,r,n),di(r,r,s),di(r,r,s),di(e[0],r,s),fi(i,e[0]),di(i,i,s),hi(i,n)&&di(e[0],e[0],ii),fi(i,e[0]),di(i,i,s),hi(i,n)?-1:(yi(e[0])===t[31]>>7&&gi(e[0],Xr,e[0]),di(e[3],e[0],e[1]),0)}var Ti=64;function Mi(){for(var e=0;e=0},Vr.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return Di(e,t),{publicKey:e,secretKey:t}},Vr.sign.keyPair.fromSecretKey=function(e){if(Mi(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;r=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return F.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return F.uint8ArrayToHex(this.oid)}getName(){const e=Li[this.toHex()];if(!e)throw Error("Unknown curve object identifier.");return e}}function Ri(e){let t,r=0;const i=e[0];return i<192?([r]=e,t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=F.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function Ni(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):F.concatUint8Array([new Uint8Array([255]),F.writeNumber(e,4)])}function zi(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function ji(e){return new Uint8Array([192|e])}function Oi(e,t){return F.concatUint8Array([ji(e),Ni(t)])}function Hi(e){return[T.packet.literalData,T.packet.compressedData,T.packet.symmetricallyEncryptedData,T.packet.symEncryptedIntegrityProtectedData,T.packet.aeadEncryptedData].includes(e)}async function _i(e,t){const r=I(e);let i,n;try{const a=await r.peekBytes(2);if(!a||a.length<2||!(128&a[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const o=await r.readByte();let c,u,h=-1,y=-1;y=0,64&o&&(y=1),y?h=63&o:(h=(63&o)>>2,u=3&o);const l=Hi(h);let p,g=null;if(l){if("array"===F.isStream(e)){const e=new s;i=C(e),g=e}else{const e=new TransformStream;i=C(e.writable),g=e.readable}n=t({tag:h,packet:g})}else g=[];do{if(y){const e=await r.readByte();if(p=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),p=!0,!l)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(u){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){i&&await i.ready;const{done:t,value:n}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const s=c===1/0?n:n.subarray(0,c-e);if(i?await i.write(s):g.push(s),e+=n.length,e>=c){r.unshift(n.subarray(c-e+n.length));break}}}}while(p);const d=await r.peekBytes(l?1/0:2);return i?(await i.ready,await i.close()):(g=F.concatUint8Array(g),await t({tag:h,packet:g})),!d||!d.length}catch(e){if(i)return await i.abort(e),!0;throw e}finally{i&&await n,r.releaseLock()}}class Gi extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Gi),this.name="UnsupportedError"}}class qi extends Gi{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Gi),this.name="UnknownPacketError"}}class Vi{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}async function Wi(e){switch(e){case T.publicKey.ed25519:try{const e=F.getWebCrypto(),t=await e.generateKey("Ed25519",!0,["sign","verify"]),r=await e.exportKey("jwk",t.privateKey),i=await e.exportKey("jwk",t.publicKey);return{A:new Uint8Array(H(i.x)),seed:H(r.d)}}catch(t){if("NotSupportedError"!==t.name&&"OperationError"!==t.name)throw t;const r=Er(Xi(e)),{publicKey:i}=Vr.sign.keyPair.fromSeed(r);return{A:i,seed:r}}case T.publicKey.ed448:{const e=await F.getNobleCurve(T.publicKey.ed448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),seed:t}}default:throw Error("Unsupported EdDSA algorithm")}}async function $i(e,t,r,i,n,s){if(be.getHashByteLength(t){if(e===T.publicKey.ed25519){return{kty:"OKP",crv:"Ed25519",x:_(t),ext:!0}}throw Error("Unsupported EdDSA algorithm")},Ji=(e,t,r)=>{if(e===T.publicKey.ed25519){const i=Zi(e,t);return i.d=_(r),i}throw Error("Unsupported EdDSA algorithm")};var en=/*#__PURE__*/Object.freeze({__proto__:null,generate:Wi,getPayloadSize:Xi,getPreferredHashAlgo:Yi,sign:$i,validateParams:async function(e,t,r){switch(e){case T.publicKey.ed25519:{const{publicKey:e}=Vr.sign.keyPair.fromSeed(r);return F.equalsUint8Array(t,e)}case T.publicKey.ed448:{const e=(await F.getNobleCurve(T.publicKey.ed448)).getPublicKey(r);return F.equalsUint8Array(t,e)}default:return!1}},verify:Qi});const tn=F.getWebCrypto();async function rn(e,t,r){const{keySize:i}=re(e);if(!F.isAES(e)||t.length!==i)throw Error("Unexpected algorithm or key size");try{const e=await tn.importKey("raw",t,{name:"AES-KW"},!1,["wrapKey"]),i=await tn.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!0,["sign"]),n=await tn.wrapKey("raw",i,e,{name:"AES-KW"});return new Uint8Array(n)}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;F.printDebugError("Browser did not support operation: "+e.message)}return kt(t).encrypt(r)}async function nn(e,t,r){const{keySize:i}=re(e);if(!F.isAES(e)||t.length!==i)throw Error("Unexpected algorithm or key size");let n;try{n=await tn.importKey("raw",t,{name:"AES-KW"},!1,["unwrapKey"])}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;return F.printDebugError("Browser did not support operation: "+e.message),kt(t).decrypt(r)}try{const e=await tn.unwrapKey("raw",r,n,{name:"AES-KW"},{name:"HMAC",hash:"SHA-256"},!0,["sign"]);return new Uint8Array(await tn.exportKey("raw",e))}catch(e){if("OperationError"===e.name)throw Error("Key Data Integrity failed");throw e}}var sn=/*#__PURE__*/Object.freeze({__proto__:null,unwrap:nn,wrap:rn});const an=F.getWebCrypto();async function on(e,t,r,i,n){const s=T.read(T.webHash,e);if(!s)throw Error("Hash algo not supported with HKDF");const a=await an.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await an.deriveBits({name:"HKDF",hash:s,salt:r,info:i},a,8*n);return new Uint8Array(o)}const cn={x25519:F.encodeUTF8("OpenPGP X25519"),x448:F.encodeUTF8("OpenPGP X448")};async function un(e){switch(e){case T.publicKey.x25519:{const e=Er(32),{publicKey:t}=Vr.box.keyPair.fromSecretKey(e);return{A:t,k:e}}case T.publicKey.x448:{const e=await F.getNobleCurve(T.publicKey.x448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),k:t}}default:throw Error("Unsupported ECDH algorithm")}}function hn(e){switch(e){case T.publicKey.x25519:return 32;case T.publicKey.x448:return 56;default:throw Error("Unsupported ECDH algorithm")}}async function yn(e,t){switch(e){case T.publicKey.x25519:{const r=Er(hn(e)),i=Vr.scalarMult(r,t);pn(i);const{publicKey:n}=Vr.box.keyPair.fromSecretKey(r);return{ephemeralPublicKey:n,sharedSecret:i}}case T.publicKey.x448:{const e=await F.getNobleCurve(T.publicKey.x448),r=e.utils.randomPrivateKey(),i=e.getSharedSecret(r,t);pn(i);return{ephemeralPublicKey:e.getPublicKey(r),sharedSecret:i}}default:throw Error("Unsupported ECDH algorithm")}}async function ln(e,t,r,i){switch(e){case T.publicKey.x25519:{const e=Vr.scalarMult(i,t);return pn(e),e}case T.publicKey.x448:{const e=(await F.getNobleCurve(T.publicKey.x448)).getSharedSecret(i,t);return pn(e),e}default:throw Error("Unsupported ECDH algorithm")}}function pn(e){let t=0;for(let r=0;r0===s[0]&&Bn(a,r,s.subarray(1),n);if(i&&!F.isStream(i))switch(a.type){case"web":try{const e=await async function(e,t,{r,s:i},n,s){const a=Pn(e.payloadSize,mn[e.name],s),o=await Dn.importKey("jwk",a,{name:"ECDSA",namedCurve:mn[e.name],hash:{name:T.read(T.webHash,e.hash)}},!1,["verify"]),c=F.concatUint8Array([r,i]).buffer;return Dn.verify({name:"ECDSA",namedCurve:mn[e.name],hash:{name:T.read(T.webHash,t)}},o,c,n)}(a,t,r,i,n);return e||o()}catch(e){if("nistP521"!==a.name&&("DataError"===e.name||"OperationError"===e.name))throw e;F.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":{const e=await async function(e,t,{r,s:i},n,s){const a=F.nodeRequire("eckey-utils"),o=F.getNodeBuffer(),{publicKey:c}=a.generateDer({curveName:bn[e.name],publicKey:o.from(s)}),u=xn.createVerify(T.read(T.hash,t));u.write(n),u.end();const h=F.concatUint8Array([r,i]);try{return u.verify({key:c,format:"der",type:"spki",dsaEncoding:"ieee-p1363"},h)}catch(e){return!1}}(a,t,r,i,n);return e||o()}}return await Bn(a,r,s,n)||o()}async function Bn(e,t,r,i){return(await F.getNobleCurve(T.publicKey.ecdsa,e.name)).verify(F.concatUint8Array([t.r,t.s]),r,i,{lowS:!1})}var Tn=/*#__PURE__*/Object.freeze({__proto__:null,sign:In,validateParams:async function(e,t,r){const i=new vn(e);if(i.keyType!==T.publicKey.ecdsa)return!1;switch(i.type){case"web":case"node":{const i=Er(8),n=T.hash.sha256,s=await be.digest(n,i);try{const a=await In(e,n,i,t,r,s);return await Cn(e,n,a,i,t,s)}catch(e){return!1}}default:return An(T.publicKey.ecdsa,e,t,r)}},verify:Cn});var Mn=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,s){if(Kn(new vn(e),i),be.getHashByteLength(t)0){const r=e[t-1];if(r>=1){const i=e.subarray(t-r),n=new Uint8Array(r).fill(r);if(F.equalsUint8Array(i,n))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Rn=/*#__PURE__*/Object.freeze({__proto__:null,decode:Fn,encode:Ln});const Nn=F.getWebCrypto(),zn=F.getNodeCrypto();function jn(e,t,r,i){return F.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),F.stringToUint8Array("Anonymous Sender "),i])}async function On(e,t,r,i,n=!1,s=!1){let a;if(n){for(a=0;a=0&&0===t[a];a--);t=t.subarray(0,a+1)}return(await be.digest(e,F.concatUint8Array([new Uint8Array([0,0,0,1]),t,i]))).subarray(0,r)}async function Hn(e,t){switch(e.type){case"curve25519Legacy":{const{sharedSecret:r,ephemeralPublicKey:i}=await yn(T.publicKey.x25519,t.subarray(1));return{publicKey:F.concatUint8Array([new Uint8Array([e.wireFormatLeadingByte]),i]),sharedKey:r}}case"web":if(e.web&&F.getWebCrypto())try{return await async function(e,t){const r=Pn(e.payloadSize,e.web,t);let i=Nn.generateKey({name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]),n=Nn.importKey("jwk",r,{name:"ECDH",namedCurve:e.web},!1,[]);[i,n]=await Promise.all([i,n]);let s=Nn.deriveBits({name:"ECDH",namedCurve:e.web,public:n},i.privateKey,e.sharedSize),a=Nn.exportKey("jwk",i.publicKey);[s,a]=await Promise.all([s,a]);const o=new Uint8Array(s),c=new Uint8Array(Sn(a,e.wireFormatLeadingByte));return{publicKey:c,sharedKey:o}}(e,t)}catch(r){return F.printDebugError(r),qn(e,t)}break;case"node":return async function(e,t){const r=zn.createECDH(e.node);r.generateKeys();const i=new Uint8Array(r.computeSecret(t)),n=new Uint8Array(r.getPublicKey());return{publicKey:n,sharedKey:i}}(e,t);default:return qn(e,t)}}async function _n(e,t,r,i){if(i.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(i,e.payloadSize-i.length),i=t}switch(e.type){case"curve25519Legacy":{const e=i.slice().reverse();return{secretKey:e,sharedKey:await ln(T.publicKey.x25519,t.subarray(1),r.subarray(1),e)}}case"web":if(e.web&&F.getWebCrypto())try{return await async function(e,t,r,i){const n=Un(e.payloadSize,e.web,r,i);let s=Nn.importKey("jwk",n,{name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]);const a=Pn(e.payloadSize,e.web,t);let o=Nn.importKey("jwk",a,{name:"ECDH",namedCurve:e.web},!0,[]);[s,o]=await Promise.all([s,o]);let c=Nn.deriveBits({name:"ECDH",namedCurve:e.web,public:o},s,e.sharedSize),u=Nn.exportKey("jwk",s);[c,u]=await Promise.all([c,u]);const h=new Uint8Array(c);return{secretKey:H(u.d),sharedKey:h}}(e,t,r,i)}catch(r){return F.printDebugError(r),Gn(e,t,i)}break;case"node":return async function(e,t,r){const i=zn.createECDH(e.node);i.setPrivateKey(r);const n=new Uint8Array(i.computeSecret(t));return{secretKey:new Uint8Array(i.getPrivateKey()),sharedKey:n}}(e,t,i);default:return Gn(e,t,i)}}async function Gn(e,t,r){return{secretKey:r,sharedKey:(await F.getNobleCurve(T.publicKey.ecdh,e.name)).getSharedSecret(r,t).subarray(1)}}async function qn(e,t){const r=await F.getNobleCurve(T.publicKey.ecdh,e.name),{publicKey:i,privateKey:n}=await e.genKeyPair();return{publicKey:i,sharedKey:r.getSharedSecret(n,t).subarray(1)}}var Vn=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,i,n,s,a){const o=new vn(e);Kn(o,n),Kn(o,r);const{sharedKey:c}=await _n(o,r,n,s),u=jn(T.publicKey.ecdh,e,t,a),{keySize:h}=re(t.cipher);let y;for(let e=0;e<3;e++)try{const r=await On(t.hash,c,h,u,1===e,2===e);return Fn(await nn(t.cipher,r,i))}catch(e){y=e}throw y},encrypt:async function(e,t,r,i,n){const s=Ln(r),a=new vn(e);Kn(a,i);const{publicKey:o,sharedKey:c}=await Hn(a,i),u=jn(T.publicKey.ecdh,e,t,n),{keySize:h}=re(t.cipher),y=await On(t.hash,c,h,u);return{publicKey:o,wrappedKey:await rn(t.cipher,y,s)}},validateParams:async function(e,t,r){return An(T.publicKey.ecdh,e,t,r)}}),Wn=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:vn,ecdh:Vn,ecdhX:gn,ecdsa:Tn,eddsa:en,eddsaLegacy:Mn,generate:async function(e){const t=new vn(e),{oid:r,hash:i,cipher:n}=t,s=await t.genKeyPair();return{oid:r,Q:s.publicKey,secret:F.leftPad(s.privateKey,t.payloadSize),hash:i,cipher:n}},getPreferredHashAlgo:function(e){return kn[e.getName()].hash}});const $n=BigInt(0),Qn=BigInt(1);var Xn=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,s){const a=BigInt(0);let o,c,u,h;i=pr(i),n=pr(n),r=pr(r),s=pr(s),r=gr(r,i),s=gr(s,n);const y=gr(pr(t.subarray(0,vr(n))),n);for(;;){if(o=Sr(Qn,n),c=gr(dr(r,o,i),n),c===a)continue;const e=gr(s*c,n);if(h=gr(y+e,n),u=gr(mr(o,n)*h,n),u!==a)break}return{r:Ar(c,"be",vr(i)),s:Ar(u,"be",vr(i))}},validateParams:async function(e,t,r,i,n){if(e=pr(e),t=pr(t),r=pr(r),i=pr(i),r<=Qn||r>=e)return!1;if(gr(e-Qn,t)!==$n)return!1;if(dr(r,t,e)!==Qn)return!1;const s=BigInt(kr(t));if(s=a||r<=$n||r>=a)return F.printDebug("invalid DSA Signature"),!1;const c=gr(pr(i.subarray(0,vr(a))),a),u=mr(r,a);if(u===$n)return F.printDebug("invalid DSA Signature"),!1;n=gr(n,s),o=gr(o,s);const h=gr(c*u,a),y=gr(t*u,a);return gr(gr(dr(n,h,s)*dr(o,y,s),s),a)===t}}),Yn={rsa:Hr,elgamal:Gr,elliptic:Wn,dsa:Xn};var Zn=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(r));return r+=e.length+2,{read:r,signatureParams:{s:e}}}case T.publicKey.dsa:case T.publicKey.ecdsa:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=F.readMPI(t.subarray(r));return r+=i.length+2,{read:r,signatureParams:{r:e,s:i}}}case T.publicKey.eddsaLegacy:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=F.readMPI(t.subarray(r));return r+=i.length+2,{read:r,signatureParams:{r:e,s:i}}}case T.publicKey.ed25519:case T.publicKey.ed448:{const i=2*Yn.elliptic.eddsa.getPayloadSize(e),n=F.readExactSubarray(t,r,r+i);return r+=n.length,{read:r,signatureParams:{RS:n}}}default:throw new Gi("Unknown signature algorithm.")}},sign:async function(e,t,r,i,n,s){if(!r||!i)throw Error("Missing key parameters");switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const{n:e,e:a}=r,{d:o,p:c,q:u,u:h}=i;return{s:await Yn.rsa.sign(t,n,e,a,o,c,u,h,s)}}case T.publicKey.dsa:{const{g:e,p:n,q:a}=r,{x:o}=i;return Yn.dsa.sign(t,s,e,n,a,o)}case T.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case T.publicKey.ecdsa:{const{oid:e,Q:a}=r,{d:o}=i;return Yn.elliptic.ecdsa.sign(e,t,n,a,o,s)}case T.publicKey.eddsaLegacy:{const{oid:e,Q:a}=r,{seed:o}=i;return Yn.elliptic.eddsaLegacy.sign(e,t,n,a,o,s)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:a}=r,{seed:o}=i;return Yn.elliptic.eddsa.sign(e,t,n,a,o,s)}default:throw Error("Unknown signature algorithm.")}},verify:async function(e,t,r,i,n,s){switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const{n:e,e:a}=i,o=F.leftPad(r.s,e.length);return Yn.rsa.verify(t,n,o,e,a,s)}case T.publicKey.dsa:{const{g:e,p:n,q:a,y:o}=i,{r:c,s:u}=r;return Yn.dsa.verify(t,c,u,s,e,n,a,o)}case T.publicKey.ecdsa:{const{oid:e,Q:a}=i,o=new Yn.elliptic.CurveWithOID(e).payloadSize,c=F.leftPad(r.r,o),u=F.leftPad(r.s,o);return Yn.elliptic.ecdsa.verify(e,t,{r:c,s:u},n,a,s)}case T.publicKey.eddsaLegacy:{const{oid:e,Q:a}=i,o=new Yn.elliptic.CurveWithOID(e).payloadSize,c=F.leftPad(r.r,o),u=F.leftPad(r.s,o);return Yn.elliptic.eddsaLegacy.verify(e,t,{r:c,s:u},n,a,s)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:a}=i;return Yn.elliptic.eddsa.verify(e,t,r,n,a,s)}default:throw Error("Unknown signature algorithm.")}}});class Jn{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return F.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class es{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Gi("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class ts{static fromObject({wrappedKey:e,algorithm:t}){const r=new ts;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=F.readExactSubarray(e,t,t+r),t+=r}write(){return F.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function rs(e){try{e.getName()}catch(e){throw new Gi("Unknown curve OID")}}function is(e,t){switch(e){case T.publicKey.ecdsa:case T.publicKey.ecdh:case T.publicKey.eddsaLegacy:return new Yn.elliptic.CurveWithOID(t).payloadSize;case T.publicKey.ed25519:case T.publicKey.ed448:return Yn.elliptic.eddsa.getPayloadSize(e);case T.publicKey.x25519:case T.publicKey.x448:return Yn.elliptic.ecdhX.getPayloadSize(e);default:throw Error("Unknown elliptic algo")}}var ns=/*#__PURE__*/Object.freeze({__proto__:null,generateParams:function(e,t,r){switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:return Yn.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:i,q:n,u:s})=>({privateParams:{d:r,p:i,q:n,u:s},publicParams:{n:e,e:t}})));case T.publicKey.ecdsa:return Yn.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new Fi(e),Q:t}})));case T.publicKey.eddsaLegacy:return Yn.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new Fi(e),Q:t}})));case T.publicKey.ecdh:return Yn.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:i,cipher:n})=>({privateParams:{d:r},publicParams:{oid:new Fi(e),Q:t,kdfParams:new es({hash:i,cipher:n})}})));case T.publicKey.ed25519:case T.publicKey.ed448:return Yn.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case T.publicKey.x25519:case T.publicKey.x448:return Yn.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case T.publicKey.dsa:case T.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},generateSessionKey:function(e){const{keySize:t}=re(e);return Er(t)},getAEADMode:function(e){const t=T.read(T.aead,e);return hr[t]},getCipherParams:re,getCurvePayloadSize:is,getPreferredCurveHashAlgo:function(e,t){switch(e){case T.publicKey.ecdsa:case T.publicKey.eddsaLegacy:return Yn.elliptic.getPreferredHashAlgo(t);case T.publicKey.ed25519:case T.publicKey.ed448:return Yn.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}},getPrefixRandom:async function(e){const{blockSize:t}=re(e),r=await Er(t),i=new Uint8Array([r[r.length-2],r[r.length-1]]);return F.concat([r,i])},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:return{c:F.readMPI(t.subarray(r))};case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:F.readMPI(t.subarray(r))}}case T.publicKey.ecdh:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=new Jn;return i.read(t.subarray(r)),{V:e,C:i}}case T.publicKey.x25519:case T.publicKey.x448:{const i=is(e),n=F.readExactSubarray(t,r,r+i);r+=n.length;const s=new ts;return s.read(t.subarray(r)),{ephemeralPublicKey:n,C:s}}default:throw new Gi("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let i=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(i));i+=e.length+2;const r=F.readMPI(t.subarray(i));i+=r.length+2;const n=F.readMPI(t.subarray(i));i+=n.length+2;const s=F.readMPI(t.subarray(i));return i+=s.length+2,{read:i,privateParams:{d:e,p:r,q:n,u:s}}}case T.publicKey.dsa:case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(i));return i+=e.length+2,{read:i,privateParams:{x:e}}}case T.publicKey.ecdsa:case T.publicKey.ecdh:{const n=is(e,r.oid);let s=F.readMPI(t.subarray(i));return i+=s.length+2,s=F.leftPad(s,n),{read:i,privateParams:{d:s}}}case T.publicKey.eddsaLegacy:{const n=is(e,r.oid);if(r.oid.getName()!==T.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let s=F.readMPI(t.subarray(i));return i+=s.length+2,s=F.leftPad(s,n),{read:i,privateParams:{seed:s}}}case T.publicKey.ed25519:case T.publicKey.ed448:{const r=is(e),n=F.readExactSubarray(t,i,i+r);return i+=n.length,{read:i,privateParams:{seed:n}}}case T.publicKey.x25519:case T.publicKey.x448:{const r=is(e),n=F.readExactSubarray(t,i,i+r);return i+=n.length,{read:i,privateParams:{k:n}}}default:throw new Gi("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=F.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{n:e,e:i}}}case T.publicKey.dsa:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=F.readMPI(t.subarray(r));r+=i.length+2;const n=F.readMPI(t.subarray(r));r+=n.length+2;const s=F.readMPI(t.subarray(r));return r+=s.length+2,{read:r,publicParams:{p:e,q:i,g:n,y:s}}}case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const i=F.readMPI(t.subarray(r));r+=i.length+2;const n=F.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{p:e,g:i,y:n}}}case T.publicKey.ecdsa:{const e=new Fi;r+=e.read(t),rs(e);const i=F.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{oid:e,Q:i}}}case T.publicKey.eddsaLegacy:{const e=new Fi;if(r+=e.read(t),rs(e),e.getName()!==T.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let i=F.readMPI(t.subarray(r));return r+=i.length+2,i=F.leftPad(i,33),{read:r,publicParams:{oid:e,Q:i}}}case T.publicKey.ecdh:{const e=new Fi;r+=e.read(t),rs(e);const i=F.readMPI(t.subarray(r));r+=i.length+2;const n=new es;return r+=n.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:i,kdfParams:n}}}case T.publicKey.ed25519:case T.publicKey.ed448:case T.publicKey.x25519:case T.publicKey.x448:{const i=F.readExactSubarray(t,r,r+is(e));return r+=i.length,{read:r,publicParams:{A:i}}}default:throw new Gi("Unknown public key encryption algorithm.")}},publicKeyDecrypt:async function(e,t,r,i,n,s){switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:{const{c:e}=i,{n,e:a}=t,{d:o,p:c,q:u,u:h}=r;return Yn.rsa.decrypt(e,n,a,o,c,u,h,s)}case T.publicKey.elgamal:{const{c1:e,c2:n}=i,a=t.p,o=r.x;return Yn.elgamal.decrypt(e,n,a,o,s)}case T.publicKey.ecdh:{const{oid:e,Q:s,kdfParams:a}=t,{d:o}=r,{V:c,C:u}=i;return Yn.elliptic.ecdh.decrypt(e,a,c,u.data,s,o,n)}case T.publicKey.x25519:case T.publicKey.x448:{const{A:n}=t,{k:s}=r,{ephemeralPublicKey:a,C:o}=i;if(null!==o.algorithm&&!F.isAES(o.algorithm))throw Error("AES session key expected");return Yn.elliptic.ecdhX.decrypt(e,a,o.wrappedKey,n,s)}default:throw Error("Unknown public key encryption algorithm.")}},publicKeyEncrypt:async function(e,t,r,i,n){switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await Yn.rsa.encrypt(i,e,t)}}case T.publicKey.elgamal:{const{p:e,g:t,y:n}=r;return Yn.elgamal.encrypt(i,e,t,n)}case T.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:s}=r,{publicKey:a,wrappedKey:o}=await Yn.elliptic.ecdh.encrypt(e,s,i,t,n);return{V:a,C:new Jn(o)}}case T.publicKey.x25519:case T.publicKey.x448:{if(t&&!F.isAES(t))throw Error("X25519 and X448 keys can only encrypt AES session keys");const{A:n}=r,{ephemeralPublicKey:s,wrappedKey:a}=await Yn.elliptic.ecdhX.encrypt(e,i,n);return{ephemeralPublicKey:s,C:ts.fromObject({algorithm:t,wrappedKey:a})}}default:return[]}},serializeParams:function(e,t){const r=new Set([T.publicKey.ed25519,T.publicKey.x25519,T.publicKey.ed448,T.publicKey.x448]),i=Object.keys(t).map((i=>{const n=t[i];return F.isUint8Array(n)?r.has(e)?n:F.uint8ArrayToMPI(n):n.write()}));return F.concatUint8Array(i)},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const{n:e,e:i}=t,{d:n,p:s,q:a,u:o}=r;return Yn.rsa.validateParams(e,i,n,s,a,o)}case T.publicKey.dsa:{const{p:e,q:i,g:n,y:s}=t,{x:a}=r;return Yn.dsa.validateParams(e,i,n,s,a)}case T.publicKey.elgamal:{const{p:e,g:i,y:n}=t,{x:s}=r;return Yn.elgamal.validateParams(e,i,n,s)}case T.publicKey.ecdsa:case T.publicKey.ecdh:{const i=Yn.elliptic[T.read(T.publicKey,e)],{oid:n,Q:s}=t,{d:a}=r;return i.validateParams(n,s,a)}case T.publicKey.eddsaLegacy:{const{Q:e,oid:i}=t,{seed:n}=r;return Yn.elliptic.eddsaLegacy.validateParams(i,e,n)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:i}=t,{seed:n}=r;return Yn.elliptic.eddsa.validateParams(e,i,n)}case T.publicKey.x25519:case T.publicKey.x448:{const{A:i}=t,{k:n}=r;return Yn.elliptic.ecdhX.validateParams(e,i,n)}default:throw Error("Unknown public key algorithm.")}}});const ss={cipher:ie,hash:be,mode:hr,publicKey:Yn,signature:Zn,random:Pr,pkcs1:Lr,pkcs5:Rn,aesKW:sn};Object.assign(ss,ns);class as extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,as),this.name="Argon2OutOfMemoryError"}}let os,cs;class us{constructor(e=M){const{passes:t,parallelism:r,memoryExponent:i}=e.s2kArgon2Params;this.type="argon2",this.salt=null,this.t=t,this.p=r,this.encodedM=i}generateSalt(){this.salt=ss.random.getRandomBytes(16)}read(e){let t=0;return this.salt=e.subarray(t,t+16),t+=16,this.t=e[t++],this.p=e[t++],this.encodedM=e[t++],t}write(){const e=[new Uint8Array([T.write(T.s2k,this.type)]),this.salt,new Uint8Array([this.t,this.p,this.encodedM])];return F.concatUint8Array(e)}async produceKey(e,t){const r=2<1048576&&(cs=os(),cs.catch((()=>{}))),n}catch(e){throw e.message&&(e.message.includes("Unable to grow instance memory")||e.message.includes("failed to grow memory")||e.message.includes("WebAssembly.Memory.grow")||e.message.includes("Out of memory"))?new as("Could not allocate required memory for Argon2"):e}}}class hs{constructor(e,t=M){this.algorithm=T.hash.sha256,this.type=T.read(T.s2k,e),this.c=t.s2kIterationCountByte,this.salt=null}generateSalt(){switch(this.type){case"salted":case"iterated":this.salt=ss.random.getRandomBytes(8)}}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==F.uint8ArrayToString(e.subarray(t,t+3)))throw new Gi("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Gi("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Gi("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...F.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([T.write(T.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return F.concatUint8Array(e)}async produceKey(e,t){e=F.encodeUTF8(e);const r=[];let i=0,n=0;for(;i>>1|(21845&Ds)<<1;xs=(61680&(xs=(52428&xs)>>>2|(13107&xs)<<2))>>>4|(3855&xs)<<4,Us[Ds]=((65280&xs)>>>8|(255&xs)<<8)>>>1}var Is=function(e,t,r){for(var i=e.length,n=0,s=new ds(t);n>>c]=u}else for(a=new ds(i),n=0;n>>15-e[n]);return a},Cs=new gs(288);for(Ds=0;Ds<144;++Ds)Cs[Ds]=8;for(Ds=144;Ds<256;++Ds)Cs[Ds]=9;for(Ds=256;Ds<280;++Ds)Cs[Ds]=7;for(Ds=280;Ds<288;++Ds)Cs[Ds]=8;var Bs=new gs(32);for(Ds=0;Ds<32;++Ds)Bs[Ds]=5;var Ts=/*#__PURE__*/Is(Cs,9,0),Ms=/*#__PURE__*/Is(Cs,9,1),Ls=/*#__PURE__*/Is(Bs,5,0),Fs=/*#__PURE__*/Is(Bs,5,1),Rs=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},Ns=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},zs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},js=function(e){return(e+7)/8|0},Os=function(e,t,r){(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length);var i=new(2==e.BYTES_PER_ELEMENT?ds:4==e.BYTES_PER_ELEMENT?fs:gs)(r-t);return i.set(e.subarray(t,r)),i},Hs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],_s=function(e,t,r){var i=Error(t||Hs[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,_s),!r)throw i;return i},Gs=function(e,t,r){r<<=7&t;var i=t/8|0;e[i]|=r,e[i+1]|=r>>>8},qs=function(e,t,r){r<<=7&t;var i=t/8|0;e[i]|=r,e[i+1]|=r>>>8,e[i+2]|=r>>>16},Vs=function(e,t){for(var r=[],i=0;il&&(l=s[i].s);var p=new ds(l+1),g=Ws(r[h-1],p,0);if(g>t){i=0;var d=0,f=g-t,m=1<t))break;d+=m-(1<>>=f;d>0;){var b=s[i].s;p[b]=0&&d;--i){var k=s[i].s;p[k]==t&&(--p[k],++d)}g=t}return[new gs(p),g]},Ws=function(e,t,r){return-1==e.s?Math.max(Ws(e.l,t,r+1),Ws(e.r,t,r+1)):t[e.s]=r},$s=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new ds(++t),i=0,n=e[0],s=1,a=function(e){r[i++]=e},o=1;o<=t;++o)if(e[o]==n&&o!=t)++s;else{if(!n&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(n),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(n);s=1,n=e[o]}return[r.subarray(0,i),t]},Qs=function(e,t){for(var r=0,i=0;i>>8,e[n+2]=255^e[n],e[n+3]=255^e[n+1];for(var s=0;s4&&!P[bs[D-1]];--D);var x,I,C,B,T=u+5<<3,M=Qs(n,Cs)+Qs(s,Bs)+a,L=Qs(n,l)+Qs(s,d)+a+14+3*D+Qs(K,P)+(2*K[16]+3*K[17]+7*K[18]);if(T<=M&&T<=L)return Xs(t,h,e.subarray(c,c+u));if(Gs(t,h,1+(L15&&(Gs(t,h,z[E]>>>5&127),h+=z[E]>>>12)}}}else x=Ts,I=Cs,C=Ls,B=Bs;for(E=0;E255){j=i[E]>>>18&31;qs(t,h,x[j+257]),h+=I[j+257],j>7&&(Gs(t,h,i[E]>>>23&31),h+=ms[j]);var O=31&i[E];qs(t,h,C[O]),h+=B[O],O>3&&(qs(t,h,i[E]>>>5&8191),h+=ws[O])}else qs(t,h,x[i[E]]),h+=I[i[E]];return qs(t,h,x[256]),h+I[256]},Zs=/*#__PURE__*/new fs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Js=/*#__PURE__*/new gs(0),ea=function(e,t,r,i,n){return function(e,t,r,i,n,s){var a=e.length,o=new gs(i+a+5*(1+Math.ceil(a/7e3))+n),c=o.subarray(i,o.length-n),u=0;if(!t||a<8)for(var h=0;h<=a;h+=65535){var y=h+65535;y>=a&&(c[u>>3]=s),u=Xs(c,u+1,e.subarray(h,y))}else{for(var l=Zs[t-1],p=l>>>13,g=8191&l,d=(1<7e3||P>24576)&&B>423){u=Ys(e,c,0,v,A,K,S,P,D,h-D,u),P=E=S=0,D=h;for(var T=0;T<286;++T)A[T]=0;for(T=0;T<30;++T)K[T]=0}var M=2,L=0,F=g,R=I-C&32767;if(B>2&&x==k(h-R))for(var N=Math.min(p,B)-1,z=Math.min(32767,h),j=Math.min(258,B);R<=z&&--F&&I!=C;){if(e[h+M]==e[h+M-R]){for(var O=0;OM){if(M=O,L=R,O>N)break;var H=Math.min(R,O-2),_=0;for(T=0;T_&&(_=q,C=G)}}}R+=(I=C)-(C=f[I])+32768&32767}if(L){v[P++]=268435456|Ks[M]<<18|Ps[L];var V=31&Ks[M],W=31&Ps[L];S+=ms[V]+ws[W],++A[257+V],++K[W],U=h+M,++E}else v[P++]=e[h],++A[e[h]]}}u=Ys(e,c,s,v,A,K,S,P,D,h-D,u),!s&&7&u&&(u=Xs(c,u+1,Js))}return Os(o,0,i+js(u)+n)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,r,i,!n)},ta=/*#__PURE__*/function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(ea(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||_s(5),this.d&&_s(4),this.d=t,this.p(e,t||!1)},e}(),ra=/*#__PURE__*/function(){function e(e){this.s={},this.p=new gs(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||_s(5),this.d&&_s(4);var t=this.p.length,r=new gs(t+e.length);r.set(this.p),r.set(e,t),this.p=r},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,r=function(e,t,r){var i=e.length;if(!i||r&&r.f&&!r.l)return t||new gs(0);var n=!t||r,s=!r||r.i;r||(r={}),t||(t=new gs(3*i));var a=function(e){var r=t.length;if(e>r){var i=new gs(Math.max(2*r,e));i.set(t),t=i}},o=r.f||0,c=r.p||0,u=r.b||0,h=r.l,y=r.d,l=r.m,p=r.n,g=8*i;do{if(!h){o=Ns(e,c,1);var d=Ns(e,c+1,3);if(c+=3,!d){var f=e[(U=js(c)+4)-4]|e[U-3]<<8,m=U+f;if(m>i){s&&_s(0);break}n&&a(u+f),t.set(e.subarray(U,m),u),r.b=u+=f,r.p=c=8*m,r.f=o;continue}if(1==d)h=Ms,y=Fs,l=9,p=5;else if(2==d){var w=Ns(e,c,31)+257,b=Ns(e,c+10,15)+4,k=w+Ns(e,c+5,31)+1;c+=14;for(var v=new gs(k),A=new gs(19),K=0;K>>4)<16)v[K++]=U;else{var x=0,I=0;for(16==U?(I=3+Ns(e,c,3),c+=2,x=v[K-1]):17==U?(I=3+Ns(e,c,7),c+=3):18==U&&(I=11+Ns(e,c,127),c+=7);I--;)v[K++]=x}}var C=v.subarray(0,w),B=v.subarray(w);l=Rs(C),p=Rs(B),h=Is(C,l,1),y=Is(B,p,1)}else _s(1);if(c>g){s&&_s(0);break}}n&&a(u+131072);for(var T=(1<>>4;if((c+=15&x)>g){s&&_s(0);break}if(x||_s(2),F<256)t[u++]=F;else{if(256==F){L=c,h=null;break}var R=F-254;if(F>264){var N=ms[K=F-257];R=Ns(e,c,(1<>>4;if(z||_s(3),c+=15&z,B=Ss[j],j>3&&(N=ws[j],B+=zs(e,c)&(1<g){s&&_s(0);break}n&&a(u+131072);for(var O=u+R;u>16),n=(65535&n)+15*(n>>16)}r=t,i=n},d:function(){return(255&(r%=65521))<<24|r>>>8<<16|(255&(i%=65521))<<8|i>>>8}}),this.v=1,ta.call(this,e,t)}return e.prototype.push=function(e,t){ta.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var r=ea(e,this.o,this.v&&2,t&&4,!t);this.v&&(function(e,t){var r=t.level,i=0==r?0:r<6?1:9==r?3:2;e[0]=120,e[1]=i<<6|(i?32-2*i:1)}(r,this.o),this.v=0),t&&function(e,t,r){for(;r;++t)e[t]=r,r>>>=8}(r,r.length-4,this.c.d()),this.ondata(r,t)},e}(),na=/*#__PURE__*/function(){function e(e){this.v=1,ra.call(this,e)}return e.prototype.push=function(e,t){if(ra.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&_s(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),ra.prototype.c.call(this,t)},e}(),sa="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{sa.decode(Js,{stream:!0}),1}catch(e){}class aa{static get tag(){return T.packet.literalData}constructor(e=new Date){this.format=T.literal.utf8,this.date=F.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=T.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||F.isStream(this.text))&&(this.text=F.decodeUTF8(F.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=F.canonicalizeEOL(F.encodeUTF8(this.text))),e?E(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await A(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=F.decodeUTF8(await e.readBytes(r)),this.date=F.readDate(await e.readBytes(4));let i=e.remainder();a(i)&&(i=await U(i)),this.setBytes(i,t)}))}writeHeader(){const e=F.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),i=F.writeDate(this.date);return F.concatUint8Array([r,t,e,i])}write(){const e=this.writeHeader(),t=this.getBytes();return F.concat([e,t])}}class oa{constructor(){this.bytes=""}read(e){return this.bytes=F.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return F.stringToUint8Array(this.bytes)}toHex(){return F.uint8ArrayToHex(F.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new oa;return t.read(F.hexToUint8Array(e)),t}static wildcard(){const e=new oa;return e.read(new Uint8Array(8)),e}}const ca=Symbol("verified"),ua="salt@notations.openpgpjs.org",ha=new Set([T.signatureSubpacket.issuerKeyID,T.signatureSubpacket.issuerFingerprint,T.signatureSubpacket.embeddedSignature]);class ya{static get tag(){return T.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.unknownSubpackets=[],this.signedHashValue=null,this.salt=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new oa,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.preferredCipherSuites=null,this.revoked=null,this[ca]=null}read(e,t=M){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Gi("Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4!==this.version&&5!==this.version&&6!==this.version)throw new Gi(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[r++],this.publicKeyAlgorithm=e[r++],this.hashAlgorithm=e[r++],r+=this.readSubPackets(e.subarray(r,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");if(this.signatureData=e.subarray(0,r),r+=this.readSubPackets(e.subarray(r,e.length),!1),this.signedHashValue=e.subarray(r,r+2),r+=2,6===this.version){const t=e[r++];this.salt=e.subarray(r,r+t),r+=t}const i=e.subarray(r,e.length),{read:n,signatureParams:s}=ss.signature.parseSignatureParams(this.publicKeyAlgorithm,i);if(nss.serializeParams(this.publicKeyAlgorithm,await this.params))):ss.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),6===this.version&&(e.push(new Uint8Array([this.salt.length])),e.push(this.salt)),e.push(this.writeParams()),F.concat(e)}async sign(e,t,r=new Date,i=!1,n){this.version=e.version,this.created=F.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID();const s=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];if(6===this.version){const e=pa(this.hashAlgorithm);if(null===this.salt)this.salt=ss.random.getRandomBytes(e);else if(e!==this.salt.length)throw Error("Provided salt does not have the required length")}else if(n.nonDeterministicSignaturesViaNotation){if(0!==this.rawNotations.filter((({name:e})=>e===ua)).length)throw Error("Unexpected existing salt notation");{const e=ss.random.getRandomBytes(pa(this.hashAlgorithm));this.rawNotations.push({name:ua,value:e,humanReadable:!1,critical:!1})}}s.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=F.concat(s);const a=this.toHash(this.signatureType,t,i),o=await this.hash(this.signatureType,t,a,i);this.signedHashValue=P(K(o),0,2);const c=async()=>ss.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await U(o));F.isStream(o)?this.params=c():(this.params=await c(),this[ca]=!0)}writeHashedSubPackets(){const e=T.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(la(e.signatureCreationTime,!0,F.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(la(e.signatureExpirationTime,!0,F.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(la(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(la(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(la(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(la(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(la(e.keyExpirationTime,!0,F.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(la(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=F.concat([r,this.revocationKeyFingerprint]),t.push(la(e.revocationKey,!1,r))),!this.issuerKeyID.isNull()&&this.issuerKeyVersion<5&&t.push(la(e.issuerKeyID,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:i,value:n,humanReadable:s,critical:a})=>{r=[new Uint8Array([s?128:0,0,0,0])];const o=F.encodeUTF8(i);r.push(F.writeNumber(o.length,2)),r.push(F.writeNumber(n.length,2)),r.push(o),r.push(n),r=F.concat(r),t.push(la(e.notationData,a,r))})),null!==this.preferredHashAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(la(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(la(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.keyServerPreferences)),t.push(la(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(la(e.preferredKeyServer,!1,F.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(la(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(la(e.policyURI,!1,F.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.keyFlags)),t.push(la(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(la(e.signersUserID,!1,F.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=F.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(la(e.reasonForRevocation,!0,r))),null!==this.features&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.features)),t.push(la(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(F.stringToUint8Array(this.signatureTargetHash)),r=F.concat(r),t.push(la(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(la(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=F.concat(r),t.push(la(e.issuerFingerprint,this.version>=5,r))),null!==this.preferredAEADAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(la(e.preferredAEADAlgorithms,!1,r))),null!==this.preferredCipherSuites&&(r=new Uint8Array([].concat(...this.preferredCipherSuites)),t.push(la(e.preferredCipherSuites,!1,r)));const i=F.concat(t),n=F.writeNumber(i.length,6===this.version?4:2);return F.concat([n,i])}writeUnhashedSubPackets(){const e=this.unhashedSubpackets.map((({type:e,critical:t,body:r})=>la(e,t,r))),t=F.concat(e),r=F.writeNumber(t.length,6===this.version?4:2);return F.concat([r,t])}readSubPacket(e,t=!0){let r=0;const i=!!(128&e[r]),n=127&e[r];if(r++,t||(this.unhashedSubpackets.push({type:n,critical:i,body:e.subarray(r,e.length)}),ha.has(n)))switch(n){case T.signatureSubpacket.signatureCreationTime:this.created=F.readDate(e.subarray(r,e.length));break;case T.signatureSubpacket.signatureExpirationTime:{const t=F.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case T.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case T.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case T.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case T.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case T.signatureSubpacket.keyExpirationTime:{const t=F.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case T.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case T.signatureSubpacket.issuerKeyID:if(4===this.version)this.issuerKeyID.read(e.subarray(r,e.length));else if(t)throw Error("Unexpected Issuer Key ID subpacket");break;case T.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const n=F.readNumber(e.subarray(r,r+2));r+=2;const s=F.readNumber(e.subarray(r,r+2));r+=2;const a=F.decodeUTF8(e.subarray(r,r+n)),o=e.subarray(r+n,r+n+s);this.rawNotations.push({name:a,humanReadable:t,value:o,critical:i}),t&&(this.notations[a]=F.decodeUTF8(o));break}case T.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case T.signatureSubpacket.policyURI:this.policyURI=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.signersUserID:this.signersUserID=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=ss.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=F.uint8ArrayToString(e.subarray(r,r+t));break}case T.signatureSubpacket.embeddedSignature:this.embeddedSignature=new ya,this.embeddedSignature.read(e.subarray(r,e.length));break;case T.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),this.issuerKeyVersion>=5?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case T.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredCipherSuites:this.preferredCipherSuites=[];for(let t=r;t{r+=e.length}),(()=>{const i=[];return 5!==this.version||this.signatureType!==T.signature.binary&&this.signatureType!==T.signature.text||(t?i.push(new Uint8Array(6)):i.push(e.writeHeader())),i.push(new Uint8Array([this.version,255])),5===this.version&&i.push(new Uint8Array(4)),i.push(F.writeNumber(r,4)),F.concat(i)}))}toHash(e,t,r=!1){const i=this.toSign(e,t);return F.concat([this.salt||new Uint8Array,i,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,i=!1){if(6===this.version&&this.salt.length!==pa(this.hashAlgorithm))throw Error("Signature salt does not have the expected length");return r||(r=this.toHash(e,t,i)),ss.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,i=new Date,n=!1,s=M){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const a=t===T.signature.binary||t===T.signature.text;if(!(this[ca]&&!a)){let i,s;if(this.hashed?s=await this.hashed:(i=this.toHash(t,r,n),s=await this.hash(t,r,i)),s=await U(s),this.signedHashValue[0]!==s[0]||this.signedHashValue[1]!==s[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[ca]=await ss.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,i,s),!this[ca])throw Error("Signature verification failed")}const o=F.normalizeDate(i);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(s.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+T.read(T.hash,this.hashAlgorithm).toUpperCase());if(s.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[T.signature.binary,T.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+T.read(T.hash,this.hashAlgorithm).toUpperCase());if(this.unknownSubpackets.forEach((({type:e,critical:t})=>{if(t)throw Error("Unknown critical signature subpacket type "+e)})),this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&s.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=F.normalizeDate(e);return null!==t&&!(this.created<=t&&tya.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==T.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID)||3===this.version&&6===e.version||6===this.version&&6!==e.version||6===this.version&&!F.equalsUint8Array(e.issuerFingerprint,this.issuerFingerprint)||6===this.version&&!F.equalsUint8Array(e.salt,this.salt))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function da(e,t){if(!t[e]){let t;try{t=T.read(T.packet,e)}catch(t){throw new qi("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}ga.prototype.hash=ya.prototype.hash,ga.prototype.toHash=ya.prototype.toHash,ga.prototype.toSign=ya.prototype.toSign;class fa extends Array{static async fromBinary(e,t,r=M){const i=new fa;return await i.read(e,t,r),i}async read(e,t,r=M){r.additionalAllowedPackets.length&&(t={...t,...F.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=v(e,(async(e,i)=>{const n=C(i);try{for(;;){await n.ready;if(await _i(e,(async e=>{try{if(e.tag===T.packet.marker||e.tag===T.packet.trust||e.tag===T.packet.padding)return;const i=da(e.tag,t);i.packets=new fa,i.fromStream=F.isStream(e.packet),await i.read(e.packet,r),await n.write(i)}catch(t){if(t instanceof qi){if(!(e.tag<=39))return;await n.abort(t)}const i=!r.ignoreUnsupportedPackets&&t instanceof Gi,s=!(r.ignoreMalformedPackets||t instanceof Gi);if(i||s||Hi(e.tag))await n.abort(t);else{const t=new Vi(e.tag,e.packet);await n.write(t)}F.printDebugError(t)}})))return await n.ready,void await n.close()}}catch(e){await n.abort(e)}}));const i=I(this.stream);for(;;){const{done:e,value:t}=await i.read();if(e?this.stream=null:this.push(t),e||Hi(t.constructor.tag))break}i.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),n+=e.length,n>=s){const e=Math.min(Math.log(n)/Math.LN2|0,30),r=2**e,i=F.concat([zi(e)].concat(t));return t=[i.subarray(1+r)],n=t[0].length,i.subarray(0,1+r)}}),(()=>F.concat([Ni(n)].concat(t)))))}else{if(F.isStream(i)){let t=0;e.push(k(K(i),(e=>{t+=e.length}),(()=>Oi(r,t))))}else e.push(Oi(r,i.length));e.push(i)}}return F.concat(e)}filterByTag(...e){const t=new fa,r=e=>t=>e===t;for(let i=0;it.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,i=e=>t=>e===t;for(let n=0;n{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),F.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=M){const t=T.read(T.compression,this.algorithm),r=Ka[t];if(!r)throw Error(t+" decompression not supported");this.packets=await fa.fromBinary(await r(this.compressed),ma,e)}compress(){const e=T.read(T.compression,this.algorithm),t=Aa[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write())}}function ba(e,t){return r=>{if(!F.isStream(r)||a(r))return x((()=>U(r).then((e=>new Promise(((r,i)=>{const n=new t;n.ondata=e=>{r(e)};try{n.push(e,!0)}catch(e){i(e)}}))))));if(e)try{const t=e();return r.pipeThrough(t)}catch(e){if("TypeError"!==e.name)throw e}const i=r.getReader(),n=new t;return new ReadableStream({async start(e){for(n.ondata=async(t,r)=>{e.enqueue(t),r&&e.close()};;){const{done:e,value:t}=await i.read();if(e)return void n.push(new Uint8Array,!0);t.length&&n.push(t)}}})}}function ka(){return async function(e){const{decode:t}=await import("./seek-bzip.min.mjs").then((function(e){return e.i}));return x((async()=>t(await U(e))))}}const va=e=>({compressor:"undefined"!=typeof CompressionStream&&(()=>new CompressionStream(e)),decompressor:"undefined"!=typeof DecompressionStream&&(()=>new DecompressionStream(e))}),Aa={zip:/*#__PURE__*/ba(va("deflate-raw").compressor,ta),zlib:/*#__PURE__*/ba(va("deflate").compressor,ia)},Ka={uncompressed:e=>e,zip:/*#__PURE__*/ba(va("deflate-raw").decompressor,ra),zlib:/*#__PURE__*/ba(va("deflate").decompressor,na),bzip2:/*#__PURE__*/ka()},Ea=/*#__PURE__*/F.constructAllowedPackets([aa,wa,ga,ya]);class Sa{static get tag(){return T.packet.symEncryptedIntegrityProtectedData}static fromObject({version:e,aeadAlgorithm:t}){if(1!==e&&2!==e)throw Error("Unsupported SEIPD version");const r=new Sa;return r.version=e,2===e&&(r.aeadAlgorithm=t),r}constructor(){this.version=null,this.cipherAlgorithm=null,this.aeadAlgorithm=null,this.chunkSizeByte=null,this.salt=null,this.encrypted=null,this.packets=null}async read(e){await A(e,(async e=>{if(this.version=await e.readByte(),1!==this.version&&2!==this.version)throw new Gi(`Version ${this.version} of the SEIP packet is unsupported.`);2===this.version&&(this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte(),this.salt=await e.readBytes(32)),this.encrypted=e.remainder()}))}write(){return 2===this.version?F.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.salt,this.encrypted]):F.concat([new Uint8Array([this.version]),this.encrypted])}async encrypt(e,t,r=M){const{blockSize:i,keySize:n}=ss.getCipherParams(e);if(t.length!==n)throw Error("Unexpected session key size");let s=this.packets.write();if(a(s)&&(s=await U(s)),2===this.version)this.cipherAlgorithm=e,this.salt=ss.random.getRandomBytes(32),this.chunkSizeByte=r.aeadChunkSizeByte,this.encrypted=await Pa(this,"encrypt",t,s);else{const n=await ss.getPrefixRandom(e),a=new Uint8Array([211,20]),o=F.concat([n,s,a]),c=await ss.hash.sha1(E(o)),u=F.concat([o,c]);this.encrypted=await ss.mode.cfb.encrypt(e,t,u,new Uint8Array(i),r)}return!0}async decrypt(e,t,r=M){if(t.length!==ss.getCipherParams(e).keySize)throw Error("Unexpected session key size");let i,n=K(this.encrypted);if(a(n)&&(n=await U(n)),2===this.version){if(this.cipherAlgorithm!==e)throw Error("Unexpected session key algorithm");i=await Pa(this,"decrypt",t,n)}else{const{blockSize:s}=ss.getCipherParams(e),a=await ss.mode.cfb.decrypt(e,t,n,new Uint8Array(s)),o=P(E(a),-20),c=P(a,0,-20),u=Promise.all([U(await ss.hash.sha1(E(c))),U(o)]).then((([e,t])=>{if(!F.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),h=P(c,s+2);i=P(h,0,-2),i=f([i,x((()=>u))]),F.isStream(n)&&r.allowUnauthenticatedStream||(i=await U(i))}return this.packets=await fa.fromBinary(i,Ea,r),!0}}async function Pa(e,t,r,i){const n=e instanceof Sa&&2===e.version,s=!n&&e.constructor.tag===T.packet.aeadEncryptedData;if(!n&&!s)throw Error("Unexpected packet type");const a=ss.getAEADMode(e.aeadAlgorithm),o="decrypt"===t?a.tagLength:0,c="encrypt"===t?a.tagLength:0,u=2**(e.chunkSizeByte+6)+o,h=s?8:0,y=new ArrayBuffer(13+h),l=new Uint8Array(y,0,5+h),p=new Uint8Array(y),g=new DataView(y),d=new Uint8Array(y,5,8);l.set([192|e.constructor.tag,e.version,e.cipherAlgorithm,e.aeadAlgorithm,e.chunkSizeByte],0);let f,w,b=0,k=Promise.resolve(),A=0,K=0;if(n){const{keySize:t}=ss.getCipherParams(e.cipherAlgorithm),{ivLength:i}=a,n=new Uint8Array(y,0,5),s=await on(T.hash.sha256,r,e.salt,n,t+i);r=s.subarray(0,t),f=s.subarray(t),f.fill(0,f.length-8),w=new DataView(f.buffer,f.byteOffset,f.byteLength)}else f=e.iv;const E=await a(e.cipherAlgorithm,r);return v(i,(async(r,i)=>{if("array"!==F.isStream(r)){const t=new TransformStream({},{highWaterMark:F.getHardwareConcurrency()*2**(e.chunkSizeByte+6),size:e=>e.length});m(t.readable,i),i=t.writable}const s=I(r),a=C(i);try{for(;;){let e=await s.readBytes(u+o)||new Uint8Array;const r=e.subarray(e.length-o);let i,y,m;if(e=e.subarray(0,e.length-o),n)m=f;else{m=f.slice();for(let e=0;e<8;e++)m[f.length-8+e]^=d[e]}if(!b||e.length?(s.unshift(r),i=E[t](e,m,l),i.catch((()=>{})),K+=e.length-o+c):(g.setInt32(5+h+4,A),i=E[t](r,m,p),i.catch((()=>{})),K+=c,y=!0),A+=e.length-o,k=k.then((()=>i)).then((async e=>{await a.ready,await a.write(e),K-=e.length})).catch((e=>a.abort(e))),(y||K>a.desiredSize)&&await k,y){await a.close();break}n?w.setInt32(f.length-4,++b):g.setInt32(9,++b)}}catch(e){await a.ready.catch((()=>{})),await a.abort(e)}}))}const Ua=/*#__PURE__*/F.constructAllowedPackets([aa,wa,ga,ya]);class Da{static get tag(){return T.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=T.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await A(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Gi(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=ss.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return F.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=M){this.packets=await fa.fromBinary(await Pa(this,"decrypt",t,K(this.encrypted)),Ua,r)}async encrypt(e,t,r=M){this.cipherAlgorithm=e;const{ivLength:i}=ss.getAEADMode(this.aeadAlgorithm);this.iv=ss.random.getRandomBytes(i),this.chunkSizeByte=r.aeadChunkSizeByte;const n=this.packets.write();this.encrypted=await Pa(this,"encrypt",t,n)}}class xa{static get tag(){return T.packet.publicKeyEncryptedSessionKey}constructor(){this.version=null,this.publicKeyID=new oa,this.publicKeyVersion=null,this.publicKeyFingerprint=null,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}static fromObject({version:e,encryptionKeyPacket:t,anonymousRecipient:r,sessionKey:i,sessionKeyAlgorithm:n}){const s=new xa;if(3!==e&&6!==e)throw Error("Unsupported PKESK version");return s.version=e,6===e&&(s.publicKeyVersion=r?null:t.version,s.publicKeyFingerprint=r?null:t.getFingerprintBytes()),s.publicKeyID=r?oa.wildcard():t.getKeyID(),s.publicKeyAlgorithm=t.algorithm,s.sessionKey=i,s.sessionKeyAlgorithm=n,s}read(e){let t=0;if(this.version=e[t++],3!==this.version&&6!==this.version)throw new Gi(`Version ${this.version} of the PKESK packet is unsupported.`);if(6===this.version){const r=e[t++];if(r){this.publicKeyVersion=e[t++];const i=r-1;this.publicKeyFingerprint=e.subarray(t,t+i),t+=i,this.publicKeyVersion>=5?this.publicKeyID.read(this.publicKeyFingerprint):this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8))}else this.publicKeyID=oa.wildcard()}else t+=this.publicKeyID.read(e.subarray(t,t+8));if(this.publicKeyAlgorithm=e[t++],this.encrypted=ss.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t)),this.publicKeyAlgorithm===T.publicKey.x25519||this.publicKeyAlgorithm===T.publicKey.x448)if(3===this.version)this.sessionKeyAlgorithm=T.write(T.symmetric,this.encrypted.C.algorithm);else if(null!==this.encrypted.C.algorithm)throw Error("Unexpected cleartext symmetric algorithm")}write(){const e=[new Uint8Array([this.version])];return 6===this.version?null!==this.publicKeyFingerprint?(e.push(new Uint8Array([this.publicKeyFingerprint.length+1,this.publicKeyVersion])),e.push(this.publicKeyFingerprint)):e.push(new Uint8Array([0])):e.push(this.publicKeyID.write()),e.push(new Uint8Array([this.publicKeyAlgorithm]),ss.serializeParams(this.publicKeyAlgorithm,this.encrypted)),F.concatUint8Array(e)}async encrypt(e){const t=T.write(T.publicKey,this.publicKeyAlgorithm),r=3===this.version?this.sessionKeyAlgorithm:null,i=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),n=Ia(this.version,t,r,this.sessionKey);this.encrypted=await ss.publicKeyEncrypt(t,r,e.publicParams,n,i)}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Ia(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,i=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),n=await ss.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,i,r),{sessionKey:s,sessionKeyAlgorithm:a}=function(e,t,r,i){switch(t){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.elgamal:case T.publicKey.ecdh:{const t=r.subarray(0,r.length-2),n=r.subarray(r.length-2),s=F.writeChecksum(t.subarray(t.length%8)),a=s[0]===n[0]&s[1]===n[1],o=6===e?{sessionKeyAlgorithm:null,sessionKey:t}:{sessionKeyAlgorithm:t[0],sessionKey:t.subarray(1)};if(i){const t=a&o.sessionKeyAlgorithm===i.sessionKeyAlgorithm&o.sessionKey.length===i.sessionKey.length;return{sessionKey:F.selectUint8Array(t,o.sessionKey,i.sessionKey),sessionKeyAlgorithm:6===e?null:F.selectUint8(t,o.sessionKeyAlgorithm,i.sessionKeyAlgorithm)}}if(a&&(6===e||T.read(T.symmetric,o.sessionKeyAlgorithm)))return o;throw Error("Decryption error")}case T.publicKey.x25519:case T.publicKey.x448:return{sessionKeyAlgorithm:null,sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,n,t);if(3===this.version){const e=this.publicKeyAlgorithm!==T.publicKey.x25519&&this.publicKeyAlgorithm!==T.publicKey.x448;if(this.sessionKeyAlgorithm=e?a:this.sessionKeyAlgorithm,s.length!==ss.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}this.sessionKey=s}}function Ia(e,t,r,i){switch(t){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.elgamal:case T.publicKey.ecdh:return F.concatUint8Array([new Uint8Array(6===e?[]:[r]),i,F.writeChecksum(i.subarray(i.length%8))]);case T.publicKey.x25519:case T.publicKey.x448:return i;default:throw Error("Unsupported public key algorithm")}}class Ca{static get tag(){return T.packet.symEncryptedSessionKey}constructor(e=M){this.version=e.aeadProtect?6:4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm=null,this.aeadAlgorithm=T.write(T.aead,e.preferredAEADAlgorithm),this.encrypted=null,this.s2k=null,this.iv=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version&&6!==this.version)throw new Gi(`Version ${this.version} of the SKESK packet is unsupported.`);6===this.version&&t++;const r=e[t++];this.version>=5&&(this.aeadAlgorithm=e[t++],6===this.version&&t++);const i=e[t++];if(this.s2k=ls(i),t+=this.s2k.read(e.subarray(t,e.length)),this.version>=5){const r=ss.getAEADMode(this.aeadAlgorithm);this.iv=e.subarray(t,t+=r.ivLength)}this.version>=5||t=5){const e=ss.getAEADMode(this.aeadAlgorithm),r=new Uint8Array([192|Ca.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),s=6===this.version?await on(T.hash.sha256,n,new Uint8Array,r,i):n,a=await e(t,s);this.sessionKey=await a.decrypt(this.encrypted,this.iv,r)}else if(null!==this.encrypted){const e=await ss.mode.cfb.decrypt(t,n,this.encrypted,new Uint8Array(r));if(this.sessionKeyAlgorithm=T.write(T.symmetric,e[0]),this.sessionKey=e.subarray(1,e.length),this.sessionKey.length!==ss.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}else this.sessionKey=n}async encrypt(e,t=M){const r=null!==this.sessionKeyEncryptionAlgorithm?this.sessionKeyEncryptionAlgorithm:this.sessionKeyAlgorithm;this.sessionKeyEncryptionAlgorithm=r,this.s2k=ps(t),this.s2k.generateSalt();const{blockSize:i,keySize:n}=ss.getCipherParams(r),s=await this.s2k.produceKey(e,n);if(null===this.sessionKey&&(this.sessionKey=ss.generateSessionKey(this.sessionKeyAlgorithm)),this.version>=5){const e=ss.getAEADMode(this.aeadAlgorithm);this.iv=ss.random.getRandomBytes(e.ivLength);const t=new Uint8Array([192|Ca.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),i=6===this.version?await on(T.hash.sha256,s,new Uint8Array,t,n):s,a=await e(r,i);this.encrypted=await a.encrypt(this.sessionKey,this.iv,t)}else{const e=F.concatUint8Array([new Uint8Array([this.sessionKeyAlgorithm]),this.sessionKey]);this.encrypted=await ss.mode.cfb.encrypt(r,s,e,new Uint8Array(i),t)}}}class Ba{static get tag(){return T.packet.publicKey}constructor(e=new Date,t=M){this.version=t.v6Keys?6:4,this.created=F.normalizeDate(e),this.algorithm=null,this.publicParams=null,this.expirationTimeV3=0,this.fingerprint=null,this.keyID=null}static fromSecretKeyPacket(e){const t=new Ba,{version:r,created:i,algorithm:n,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=i,t.algorithm=n,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}async read(e,t=M){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Gi("Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4===this.version||5===this.version||6===this.version){this.created=F.readDate(e.subarray(r,r+4)),r+=4,this.algorithm=e[r++],this.version>=5&&(r+=4);const{read:t,publicParams:i}=ss.parsePublicKeyParams(this.algorithm,e.subarray(r));if(6===this.version&&i.oid&&(i.oid.getName()===T.curve.curve25519Legacy||i.oid.getName()===T.curve.ed25519Legacy))throw Error("Legacy curve25519 cannot be used with v6 keys");return this.publicParams=i,r+=t,await this.computeFingerprintAndKeyID(),r}throw new Gi(`Version ${this.version} of the key packet is unsupported.`)}write(){const e=[];e.push(new Uint8Array([this.version])),e.push(F.writeDate(this.created)),e.push(new Uint8Array([this.algorithm]));const t=ss.serializeParams(this.algorithm,this.publicParams);return this.version>=5&&e.push(F.writeNumber(t.length,4)),e.push(t),F.concatUint8Array(e)}writeForHash(e){const t=this.writePublicKey(),r=149+e,i=e>=5?4:2;return F.concatUint8Array([new Uint8Array([r]),F.writeNumber(t.length,i),t])}isDecrypted(){return null}getCreationTime(){return this.created}getKeyID(){return this.keyID}async computeFingerprintAndKeyID(){if(await this.computeFingerprint(),this.keyID=new oa,this.version>=5)this.keyID.read(this.fingerprint.subarray(0,8));else{if(4!==this.version)throw Error("Unsupported key version");this.keyID.read(this.fingerprint.subarray(12,20))}}async computeFingerprint(){const e=this.writeForHash(this.version);if(this.version>=5)this.fingerprint=await ss.hash.sha256(e);else{if(4!==this.version)throw Error("Unsupported key version");this.fingerprint=await ss.hash.sha1(e)}}getFingerprintBytes(){return this.fingerprint}getFingerprint(){return F.uint8ArrayToHex(this.getFingerprintBytes())}hasSameFingerprintAs(e){return this.version===e.version&&F.equalsUint8Array(this.writePublicKey(),e.writePublicKey())}getAlgorithmInfo(){const e={};e.algorithm=T.read(T.publicKey,this.algorithm);const t=this.publicParams.n||this.publicParams.p;return t?e.bits=F.uint8ArrayBitLength(t):this.publicParams.oid&&(e.curve=this.publicParams.oid.getName()),e}}Ba.prototype.readPublicKey=Ba.prototype.read,Ba.prototype.writePublicKey=Ba.prototype.write;const Ta=/*#__PURE__*/F.constructAllowedPackets([aa,wa,ga,ya]);class Ma{static get tag(){return T.packet.symmetricallyEncryptedData}constructor(){this.encrypted=null,this.packets=null}read(e){this.encrypted=e}write(){return this.encrypted}async decrypt(e,t,r=M){if(!r.allowUnauthenticatedMessages)throw Error("Message is not authenticated.");const{blockSize:i}=ss.getCipherParams(e),n=await U(K(this.encrypted)),s=await ss.mode.cfb.decrypt(e,t,n.subarray(i+2),n.subarray(2,i+2));this.packets=await fa.fromBinary(s,Ta,r)}async encrypt(e,t,r=M){const i=this.packets.write(),{blockSize:n}=ss.getCipherParams(e),s=await ss.getPrefixRandom(e),a=await ss.mode.cfb.encrypt(e,t,s,new Uint8Array(n),r),o=await ss.mode.cfb.encrypt(e,t,i,a.subarray(2),r);this.encrypted=F.concat([a,o])}}class La{static get tag(){return T.packet.marker}read(e){return 80===e[0]&&71===e[1]&&80===e[2]}write(){return new Uint8Array([80,71,80])}}class Fa extends Ba{static get tag(){return T.packet.publicSubkey}constructor(e,t){super(e,t)}static fromSecretSubkeyPacket(e){const t=new Fa,{version:r,created:i,algorithm:n,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=i,t.algorithm=n,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}}class Ra{static get tag(){return T.packet.userAttribute}constructor(){this.attributes=[]}read(e){let t=0;for(;t{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function za(e,t,r,i,n,s,a){if("argon2"===t.type&&!n)throw Error("Using Argon2 S2K without AEAD is not allowed");if("simple"===t.type&&6===e)throw Error("Using Simple S2K with version 6 keys is not allowed");const{keySize:o}=ss.getCipherParams(i),c=await t.produceKey(r,o);if(!n||5===e||a)return c;const u=F.concatUint8Array([s,new Uint8Array([e,i,n])]);return on(T.hash.sha256,c,new Uint8Array,u,o)}class ja{static get tag(){return T.packet.userID}constructor(){this.userID="",this.name="",this.email="",this.comment=""}static fromObject(e){if(F.isString(e)||e.name&&!F.isString(e.name)||e.email&&!F.isEmailAddress(e.email)||e.comment&&!F.isString(e.comment))throw Error("Invalid user ID format");const t=new ja;Object.assign(t,e);const r=[];return t.name&&r.push(t.name),t.comment&&r.push(`(${t.comment})`),t.email&&r.push(`<${t.email}>`),t.userID=r.join(" "),t}read(e,t=M){const r=F.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");const i=/^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/.exec(r);if(null!==i){const{name:e,comment:t,email:r}=i.groups;this.comment=t?.replace(/^\(|\)|\s$/g,"").trim()||"",this.name=e?.trim()||"",this.email=r.substring(1,r.length-1)}else/^[^\s@]+@[^\s@]+$/.test(r)&&(this.email=r);this.userID=r}write(){return F.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Oa extends Na{static get tag(){return T.packet.secretSubkey}constructor(e=new Date,t=M){super(e,t)}}class Ha{static get tag(){return T.packet.trust}read(){throw new Gi("Trust packets are not supported")}write(){throw new Gi("Trust packets are not supported")}}class _a{static get tag(){return T.packet.padding}constructor(){this.padding=null}read(e){}write(){return this.padding}async createPadding(e){this.padding=await ss.random.getRandomBytes(e)}}const Ga=/*#__PURE__*/F.constructAllowedPackets([ya]);class qa{constructor(e){this.packets=e||new fa}write(){return this.packets.write()}armor(e=M){const t=this.packets.some((e=>e.constructor.tag===ya.tag&&6!==e.version));return Z(T.armor.signature,this.write(),void 0,void 0,void 0,t,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Va({armoredSignature:e,binarySignature:t,config:r,...i}){r={...M,...r};let n=e||t;if(!n)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!F.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!F.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:e,data:t}=await Y(n);if(e!==T.armor.signature)throw Error("Armored text not of type signature");n=t}const a=await fa.fromBinary(n,Ga,r);return new qa(a)}async function Wa(e,t){const r=new Oa(e.date,t);return r.packets=null,r.algorithm=T.write(T.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function $a(e,t){const r=new Na(e.date,t);return r.packets=null,r.algorithm=T.write(T.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Qa(e,t,r,i,n=new Date,s){let a,o;for(let c=e.length-1;c>=0;c--)try{(!a||e[c].created>=a.created)&&(await e[c].verify(t,r,i,n,void 0,s),a=e[c])}catch(e){o=e}if(!a)throw F.wrapError(`Could not find valid ${T.read(T.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return a}function Xa(e,t,r=new Date){const i=F.normalizeDate(r);if(null!==i){const r=to(e,t);return!(e.created<=i&&i0&&(s.keyExpirationTime=r.keyExpirationTime,s.keyNeverExpires=!1);return await Za(n,[],t,s,r.date,void 0,void 0,void 0,i)}async function Za(e,t,r,i,n,s,a=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const u=new ya;return Object.assign(u,i),u.publicKeyAlgorithm=r.algorithm,u.hashAlgorithm=await async function(e,t,r=new Date,i=[],n){const s=T.hash.sha256,a=n.preferredHashAlgorithm,o=await Promise.all(e.map((async(e,t)=>(await e.getPrimarySelfSignature(r,i[t],n)).preferredHashAlgorithms))),c=new Map;for(const e of o)for(const t of e)try{const e=T.write(T.hash,t);c.set(e,c.has(e)?c.get(e)+1:1)}catch{}const u=t=>0===e.length||c.get(t)===e.length||t===s,h=()=>{if(0===c.size)return s;const e=Array.from(c.keys()).filter((e=>u(e))).sort(((e,t)=>ss.hash.getHashByteLength(e)-ss.hash.getHashByteLength(t)))[0];return ss.hash.getHashByteLength(e)>=ss.hash.getHashByteLength(s)?e:s};if(new Set([T.publicKey.ecdsa,T.publicKey.eddsaLegacy,T.publicKey.ed25519,T.publicKey.ed448]).has(t.algorithm)){const e=ss.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid),r=u(a),i=ss.hash.getHashByteLength(a)>=ss.hash.getHashByteLength(e);if(r&&i)return a;{const t=h();return ss.hash.getHashByteLength(t)>=ss.hash.getHashByteLength(e)?t:e}}return u(a)?a:h()}(t,r,n,s,c),u.rawNotations=[...a],await u.sign(r,e,n,o,c),u}async function Ja(e,t,r,i=new Date,n){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(i)||n&&!await n(e)||t[r].some((function(t){return F.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function eo(e,t,r,i,n,s,a=new Date,o){s=s||e;const c=[];return await Promise.all(i.map((async function(e){try{if(!n||e.issuerKeyID.equals(n.issuerKeyID)){const i=![T.reasonForRevocation.keyRetired,T.reasonForRevocation.keySuperseded,T.reasonForRevocation.userIDInvalid].includes(e.reasonForRevocationFlag);await e.verify(s,t,r,i?null:a,!1,o),c.push(e.issuerKeyID)}}catch(e){}}))),n?(n.revoked=!!c.some((e=>e.equals(n.issuerKeyID)))||(n.revoked||!1),n.revoked):c.length>0}function to(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function ro(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=F.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=T.write(T.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==T.curve.ed25519Legacy&&e.curve!==T.curve.curve25519Legacy&&"ed25519"!==e.curve&&"curve25519"!==e.curve||(e.curve=e.sign?T.curve.ed25519Legacy:T.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===T.curve.ed25519Legacy?T.publicKey.eddsaLegacy:T.publicKey.ecdsa:e.algorithm=T.publicKey.ecdh;break;case"curve25519":e.algorithm=e.sign?T.publicKey.ed25519:T.publicKey.x25519;break;case"curve448":e.algorithm=e.sign?T.publicKey.ed448:T.publicKey.x448;break;case"rsa":e.algorithm=T.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function io(e,t,r){switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:case T.publicKey.dsa:case T.publicKey.ecdsa:case T.publicKey.eddsaLegacy:case T.publicKey.ed25519:case T.publicKey.ed448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.signData);default:return!1}}function no(e,t,r){switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.elgamal:case T.publicKey.ecdh:case T.publicKey.x25519:case T.publicKey.x448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&T.keyFlags.encryptStorage);default:return!1}}function so(e,t,r){if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.elgamal:case T.publicKey.ecdh:case T.publicKey.x25519:case T.publicKey.x448:return!(!(!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.signData))||!r.allowInsecureDecryptionWithSigningKeys)||(!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&T.keyFlags.encryptStorage));default:return!1}}function ao(e,t){const r=T.write(T.publicKey,e.algorithm),i=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(i.algorithm+" keys are considered too weak.");switch(r){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:case T.publicKey.rsaEncrypt:if(i.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const s=await t.getSigningKey(o,e.created,void 0,i);if(e.revoked||await n.isRevoked(e,s.keyPacket,r,i))throw Error("User certificate is revoked");try{await e.verify(s.keyPacket,T.signature.certGeneric,a,r,void 0,i)}catch(e){throw F.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const i=this,n=this.selfCertifications.concat(this.otherCertifications);return Promise.all(n.map((async n=>({keyID:n.issuerKeyID,valid:await i.verifyCertificate(n,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};let s;for(let a=this.selfCertifications.length-1;a>=0;a--)try{const s=this.selfCertifications[a];if(s.revoked||await r.isRevoked(s,void 0,e,t))throw Error("Self-certification is revoked");try{await s.verify(i,T.signature.certGeneric,n,e,void 0,t)}catch(e){throw F.wrapError("Self-certification is invalid",e)}return!0}catch(e){s=e}throw s}async update(e,t,r){const i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};await Ja(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(i,T.signature.certGeneric,n,t,!1,r),!0}catch(e){return!1}})),await Ja(e,this,"otherCertifications",t),await Ja(e,this,"revocationSignatures",t,(function(e){return eo(i,T.signature.certRevocation,n,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=T.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=M){const s={userID:this.userID,userAttribute:this.userAttribute,key:e},a=new oo(s.userID||s.userAttribute,this.mainKey);return a.revocationSignatures.push(await Za(s,[],e,{signatureType:T.signature.certRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await a.update(this),a}}class co{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new fa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new co(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,i=M){const n=this.mainKey.keyPacket;return eo(n,T.signature.subkeyRevocation,{key:n,bind:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verify(e=new Date,t=M){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket},n=await Qa(this.bindingSignatures,r,T.signature.subkeyBinding,i,e,t);if(n.revoked||await this.isRevoked(n,null,e,t))throw Error("Subkey is revoked");if(Xa(this.keyPacket,n,e))throw Error("Subkey is expired");return n}async getExpirationTime(e=new Date,t=M){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket};let n;try{n=await Qa(this.bindingSignatures,r,T.signature.subkeyBinding,i,e,t)}catch(e){return null}const s=to(this.keyPacket,n),a=n.getExpirationTime();return sn.bindingSignatures[t].created&&(n.bindingSignatures[t]=e),!1;try{return await e.verify(i,T.signature.subkeyBinding,s,t,void 0,r),!0}catch(e){return!1}})),await Ja(e,this,"revocationSignatures",t,(function(e){return eo(i,T.signature.subkeyRevocation,s,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=T.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=M){const s={key:e,bind:this.keyPacket},a=new co(this.keyPacket,this.mainKey);return a.revocationSignatures.push(await Za(s,[],e,{signatureType:T.signature.subkeyRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await a.update(this),a}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{co.prototype[e]=function(){return this.keyPacket[e]()}}));const uo=/*#__PURE__*/F.constructAllowedPackets([ya]),ho=new Set([T.packet.publicKey,T.packet.privateKey]),yo=new Set([T.packet.publicKey,T.packet.privateKey,T.packet.publicSubkey,T.packet.privateSubkey]);class lo{packetListToStructure(e,t=new Set){let r,i,n,s;for(const a of e){if(a instanceof Vi){yo.has(a.tag)&&!s&&(s=ho.has(a.tag)?ho:yo);continue}const e=a.constructor.tag;if(s){if(!s.has(e))continue;s=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case T.packet.publicKey:case T.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=a,i=this.getKeyID(),!i)throw Error("Missing Key ID");break;case T.packet.userID:case T.packet.userAttribute:r=new oo(a,this),this.users.push(r);break;case T.packet.publicSubkey:case T.packet.secretSubkey:r=null,n=new co(a,this),this.subkeys.push(n);break;case T.packet.signature:switch(a.signatureType){case T.signature.certGeneric:case T.signature.certPersona:case T.signature.certCasual:case T.signature.certPositive:if(!r){F.printDebug("Dropping certification signatures without preceding user packet");continue}a.issuerKeyID.equals(i)?r.selfCertifications.push(a):r.otherCertifications.push(a);break;case T.signature.certRevocation:r?r.revocationSignatures.push(a):this.directSignatures.push(a);break;case T.signature.key:this.directSignatures.push(a);break;case T.signature.subkeyBinding:if(!n){F.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}n.bindingSignatures.push(a);break;case T.signature.keyRevocation:this.revocationSignatures.push(a);break;case T.signature.subkeyRevocation:if(!n){F.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}n.revocationSignatures.push(a)}}}}toPacketList(){const e=new fa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},i=M){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket;try{ao(n,i)}catch(e){throw F.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},s=await Qa(r.bindingSignatures,n,T.signature.subkeyBinding,e,t,i);if(!io(r.keyPacket,s,i))continue;if(!s.embeddedSignature)throw Error("Missing embedded signature");return await Qa([s.embeddedSignature],r.keyPacket,T.signature.keyBinding,e,t,i),ao(r.keyPacket,i),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,i);if((!e||n.getKeyID().equals(e))&&io(n,s,i))return ao(n,i),this}catch(e){a=e}throw F.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),a)}async getEncryptionKey(e,t=new Date,r={},i=M){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket;try{ao(n,i)}catch(e){throw F.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},s=await Qa(r.bindingSignatures,n,T.signature.subkeyBinding,e,t,i);if(no(r.keyPacket,s,i))return ao(r.keyPacket,i),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,i);if((!e||n.getKeyID().equals(e))&&no(n,s,i))return ao(n,i),this}catch(e){a=e}throw F.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),a)}async isRevoked(e,t,r=new Date,i=M){return eo(this.keyPacket,T.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verifyPrimaryKey(e=new Date,t={},r=M){const i=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");if(Xa(i,await this.getPrimarySelfSignature(e,t,r),e))throw Error("Primary key is expired");if(6!==i.version){const t=await Qa(this.directSignatures,i,T.signature.key,{key:i},e,r).catch((()=>{}));if(t&&Xa(i,t,e))throw Error("Primary key is expired")}}async getExpirationTime(e,t=M){let r;try{const i=await this.getPrimarySelfSignature(null,e,t),n=to(this.keyPacket,i),s=i.getExpirationTime(),a=6!==this.keyPacket.version&&await Qa(this.directSignatures,this.keyPacket,T.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(a){const e=to(this.keyPacket,a);r=Math.min(n,s,e)}else r=ne.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const i=this.clone();return await Ja(e,i,"revocationSignatures",t,(n=>eo(i.keyPacket,T.signature.keyRevocation,i,[n],null,e.keyPacket,t,r))),await Ja(e,i,"directSignatures",t),await Promise.all(e.users.map((async e=>{const n=i.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const n=i.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.subkeys.push(t)}}))),i}async getRevocationCertificate(e=new Date,t=M){const r={key:this.keyPacket},i=await Qa(this.revocationSignatures,this.keyPacket,T.signature.keyRevocation,r,e,t),n=new fa;n.push(i);const s=6!==this.keyPacket.version;return Z(T.armor.publicKey,n.write(),null,null,"This is a revocation certificate",s,t)}async applyRevocationCertificate(e,t=new Date,r=M){const i=await Y(e),n=(await fa.fromBinary(i.data,uo,r)).findPacket(T.packet.signature);if(!n||n.signatureType!==T.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!n.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await n.verify(this.keyPacket,T.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw F.wrapError("Could not verify revocation signature",e)}const s=this.clone();return s.revocationSignatures.push(n),s}async signPrimaryUser(e,t,r,i=M){const{index:n,user:s}=await this.getPrimaryUser(t,r,i),a=await s.certify(e,t,i),o=this.clone();return o.users[n]=a,o}async signAllUsers(e,t=new Date,r=M){const i=this.clone();return i.users=await Promise.all(this.users.map((function(i){return i.certify(e,t,r)}))),i}async verifyPrimaryUser(e,t=new Date,r,i=M){const n=this.keyPacket,{user:s}=await this.getPrimaryUser(t,r,i);return e?await s.verifyAllCertifications(e,t,i):[{keyID:n.getKeyID(),valid:await s.verify(t,i).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=M){const i=this.keyPacket,n=[];return await Promise.all(this.users.map((async s=>{const a=e?await s.verifyAllCertifications(e,t,r):[{keyID:i.getKeyID(),valid:await s.verify(t,r).catch((()=>!1))}];n.push(...a.map((e=>({userID:s.userID?s.userID.userID:null,userAttribute:s.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),n}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{lo.prototype[e]=co.prototype[e]}));class po extends lo{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([T.packet.secretKey,T.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=M){const t=6!==this.keyPacket.version;return Z(T.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}}class go extends po{constructor(e){if(super(),this.packetListToStructure(e,new Set([T.packet.publicKey,T.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new fa,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case T.packet.secretKey:{const t=Ba.fromSecretKeyPacket(r);e.push(t);break}case T.packet.secretSubkey:{const t=Fa.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new po(e)}armor(e=M){const t=6!==this.keyPacket.version;return Z(T.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}async getDecryptionKeys(e,t=new Date,r={},i=M){const n=this.keyPacket,s=[];let a=null;for(let r=0;re.isDecrypted()))}async validate(e=M){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=T.reasonForRevocation.noReason,string:t=""}={},r=new Date,i=M){if(!this.isPrivate())throw Error("Need private key for revoking");const n={key:this.keyPacket},s=this.clone();return s.revocationSignatures.push(await Za(n,[],this.keyPacket,{signatureType:T.signature.keyRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,i)),s}async addSubkey(e={}){const t={...M,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}function a(){const e={};e.keyFlags=[T.keyFlags.certifyKeys|T.keyFlags.signData];const t=s([T.symmetric.aes256,T.symmetric.aes128],i.preferredSymmetricAlgorithm);if(e.preferredSymmetricAlgorithms=t,i.aeadProtect){const r=s([T.aead.gcm,T.aead.eax,T.aead.ocb],i.preferredAEADAlgorithm);e.preferredCipherSuites=r.flatMap((e=>t.map((t=>[t,e]))))}return e.preferredHashAlgorithms=s([T.hash.sha256,T.hash.sha512,T.hash.sha3_256,T.hash.sha3_512],i.preferredHashAlgorithm),e.preferredCompressionAlgorithms=s([T.compression.uncompressed,T.compression.zlib,T.compression.zip],i.preferredCompressionAlgorithm),e.features=[0],e.features[0]|=T.features.modificationDetection,i.aeadProtect&&(e.features[0]|=T.features.seipdv2),r.keyExpirationTime>0&&(e.keyExpirationTime=r.keyExpirationTime,e.keyNeverExpires=!1),e}if(n.push(e),6===e.version){const t={key:e},s=a();s.signatureType=T.signature.key;const o=await Za(t,[],e,s,r.date,void 0,void 0,void 0,i);n.push(o)}await Promise.all(r.userIDs.map((async function(t,n){const s=ja.fromObject(t),o={userID:s,key:e},c=6!==e.version?a():{};c.signatureType=T.signature.certPositive,0===n&&(c.isPrimaryUserID=!0);return{userIDPacket:s,signaturePacket:await Za(o,[],e,c,r.date,void 0,void 0,void 0,i)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{n.push(e),n.push(t)}))})),await Promise.all(t.map((async function(t,n){const s=r.subkeys[n];return{secretSubkeyPacket:t,subkeySignaturePacket:await Ya(t,e,s,i)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{n.push(e),n.push(t)}))}));const o={key:e};return n.push(await Za(o,[],e,{signatureType:T.signature.keyRevocation,reasonForRevocationFlag:T.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,i)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new go(n)}async function bo({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...M,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!F.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!F.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let s;if(e){const{type:t,data:r}=await Y(e);if(t!==T.armor.publicKey&&t!==T.armor.privateKey)throw Error("Armored text not of type key");s=r}else s=t;const a=await fa.fromBinary(s,fo,r),o=a.indexOfTag(T.packet.publicKey,T.packet.secretKey);if(0===o.length)throw Error("No key packet found");return mo(a.slice(o[0],o[1]))}async function ko({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...M,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!F.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!F.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let s;if(e){const{type:t,data:r}=await Y(e);if(t!==T.armor.privateKey)throw Error("Armored text not of type private key");s=r}else s=t;const a=await fa.fromBinary(s,fo,r),o=a.indexOfTag(T.packet.publicKey,T.packet.secretKey);for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:t,data:r}=await Y(e);if(t!==T.armor.publicKey&&t!==T.armor.privateKey)throw Error("Armored text not of type key");n=r}const a=[],o=await fa.fromBinary(n,fo,r),c=o.indexOfTag(T.packet.publicKey,T.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(T.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,i=new Date,n=M){const s=this.packets.filterByTag(T.packet.symmetricallyEncryptedData,T.packet.symEncryptedIntegrityProtectedData,T.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const a=s[0],o=a.cipherAlgorithm,c=r||await this.decryptSessionKeys(e,t,o,i,n);let u=null;const h=Promise.all(c.map((async({algorithm:e,data:t})=>{if(!F.isUint8Array(t)||!a.cipherAlgorithm&&!F.isString(e))throw Error("Invalid session key for decryption.");try{const r=a.cipherAlgorithm||T.write(T.symmetric,e);await a.decrypt(r,t,n)}catch(e){F.printDebugError(e),u=e}})));if(D(a.encrypted),a.encrypted=null,await h,!a.packets||!a.packets.length)throw u||Error("Decryption failed.");const y=new Po(a.packets);return a.packets=new fa,y}async decryptSessionKeys(e,t,r,i=new Date,n=M){let s,a=[];if(t){const e=this.packets.filterByTag(T.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let i;i=r?await fa.fromBinary(e.write(),Eo,n):e,await Promise.all(i.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){F.printDebugError(e),e instanceof as&&(s=e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(T.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let o;try{o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,n)).map((e=>e.keyPacket))}catch(e){return void(s=e)}let c=[T.symmetric.aes256,T.symmetric.aes128,T.symmetric.tripledes,T.symmetric.cast5];try{const t=await e.getPrimarySelfSignature(i,void 0,n);t.preferredSymmetricAlgorithms&&(c=c.concat(t.preferredSymmetricAlgorithms))}catch(e){}await Promise.all(o.map((async function(e){if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(n.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===T.publicKey.rsaEncrypt||t.publicKeyAlgorithm===T.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===T.publicKey.rsaSign||t.publicKeyAlgorithm===T.publicKey.elgamal)){const i=t.write();await Promise.all((r?[r]:Array.from(n.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map((async t=>{const r=new xa;r.read(i);const n={sessionKeyAlgorithm:t,sessionKey:ss.generateSessionKey(t)};try{await r.decrypt(e,n),a.push(r)}catch(e){F.printDebugError(e),s=e}})))}else try{await t.decrypt(e);const i=r||t.sessionKeyAlgorithm;if(i&&!c.includes(T.write(T.symmetric,i)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){F.printDebugError(e),s=e}})))}))),D(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+F.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:e.sessionKeyAlgorithm&&T.read(T.symmetric,e.sessionKeyAlgorithm)})))}throw s||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],i=M){const{symmetricAlgo:n,aeadAlgo:s}=await async function(e=[],t=new Date,r=[],i=M){const n=await Promise.all(e.map(((e,n)=>e.getPrimarySelfSignature(t,r[n],i))));if(e.length?n.every((e=>e.features&&e.features[0]&T.features.seipdv2)):i.aeadProtect){const e={symmetricAlgo:T.symmetric.aes128,aeadAlgo:T.aead.ocb},t=[{symmetricAlgo:i.preferredSymmetricAlgorithm,aeadAlgo:i.preferredAEADAlgorithm},{symmetricAlgo:i.preferredSymmetricAlgorithm,aeadAlgo:T.aead.ocb},{symmetricAlgo:T.symmetric.aes128,aeadAlgo:i.preferredAEADAlgorithm}];for(const e of t)if(n.every((t=>t.preferredCipherSuites&&t.preferredCipherSuites.some((t=>t[0]===e.symmetricAlgo&&t[1]===e.aeadAlgo)))))return e;return e}const s=T.symmetric.aes128,a=i.preferredSymmetricAlgorithm;return{symmetricAlgo:n.every((e=>e.preferredSymmetricAlgorithms&&e.preferredSymmetricAlgorithms.includes(a)))?a:s,aeadAlgo:void 0}}(e,t,r,i),a=T.read(T.symmetric,n),o=s?T.read(T.aead,s):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&(e.keyPacket.algorithm===T.publicKey.x25519||e.keyPacket.algorithm===T.publicKey.x448)&&!o&&!F.isAES(n))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:ss.generateSessionKey(n),algorithm:a,aeadAlgorithm:o}}async encrypt(e,t,r,i=!1,n=[],s=new Date,a=[],o=M){if(r){if(!F.isUint8Array(r.data)||!F.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Po.generateSessionKey(e,s,a,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Po.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:u,aeadAlgorithm:h}=r,y=await Po.encryptSessionKey(c,u,h,e,t,i,n,s,a,o),l=Sa.fromObject({version:h?2:1,aeadAlgorithm:h?T.write(T.aead,h):null});l.packets=this.packets;const p=T.write(T.symmetric,u);return await l.encrypt(p,c,o),y.packets.push(l),l.packets=new fa,y}static async encryptSessionKey(e,t,r,i,n,s=!1,a=[],o=new Date,c=[],u=M){const h=new fa,y=T.write(T.symmetric,t),l=r&&T.write(T.aead,r);if(i){const t=await Promise.all(i.map((async function(t,r){const i=await t.getEncryptionKey(a[r],o,c,u),n=xa.fromObject({version:l?6:3,encryptionKeyPacket:i.keyPacket,anonymousRecipient:s,sessionKey:e,sessionKeyAlgorithm:y});return await n.encrypt(i.keyPacket),delete n.sessionKey,n})));h.push(...t)}if(n){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,i=async function(e,s,a,o){const c=new Ca(u);if(c.sessionKey=e,c.sessionKeyAlgorithm=s,a&&(c.aeadAlgorithm=a),await c.encrypt(o,u),u.passwordCollisionCheck){if(1!==(await Promise.all(n.map((e=>t(c,e))))).reduce(r))return i(e,s,o)}return delete c.sessionKey,c},s=await Promise.all(n.map((t=>i(e,y,l,t))));h.push(...s)}return new Po(h)}async sign(e=[],t=[],r=null,i=[],n=new Date,s=[],a=[],o=[],c=M){const u=new fa,h=this.packets.findPacket(T.packet.literalData);if(!h)throw Error("No literal data packet to sign.");const y=await Uo(h,e,t,r,i,n,s,a,o,!1,c),l=y.map(((e,t)=>ga.fromSignaturePacket(e,0===t))).reverse();return u.push(...l),u.push(h),u.push(...y),new Po(u)}compress(e,t=M){if(e===T.compression.uncompressed)return this;const r=new wa(t);r.algorithm=e,r.packets=this.packets;const i=new fa;return i.push(r),new Po(i)}async signDetached(e=[],t=[],r=null,i=[],n=[],s=new Date,a=[],o=[],c=M){const u=this.packets.findPacket(T.packet.literalData);if(!u)throw Error("No literal data packet to sign.");return new qa(await Uo(u,e,t,r,i,n,s,a,o,!0,c))}async verify(e,t=new Date,r=M){const i=this.unwrapCompressed(),n=i.packets.filterByTag(T.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");a(i.packets.stream)&&i.packets.push(...await U(i.packets.stream,(e=>e||[])));const s=i.packets.filterByTag(T.packet.onePassSignature).reverse(),o=i.packets.filterByTag(T.packet.signature);return s.length&&!o.length&&F.isStream(i.packets.stream)&&!a(i.packets.stream)?(await Promise.all(s.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=x((async()=>(await e.correspondingSig).signatureData)),e.hashed=U(await e.hash(e.signatureType,n[0],void 0,!1)),e.hashed.catch((()=>{}))}))),i.packets.stream=v(i.packets.stream,(async(e,t)=>{const r=I(e),i=C(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await i.abort(e)}})),Do(s,n,e,t,!1,r)):Do(o,n,e,t,!1,r)}verifyDetached(e,t,r=new Date,i=M){const n=this.unwrapCompressed().packets.filterByTag(T.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");return Do(e.packets.filterByTag(T.packet.signature),n,t,r,!0,i)}unwrapCompressed(){const e=this.packets.filterByTag(T.packet.compressedData);return e.length?new Po(e[0].packets):this}async appendSignature(e,t=M){await this.packets.read(F.isUint8Array(e)?e:(await Y(e)).data,So,t)}write(){return this.packets.write()}armor(e=M){const t=this.packets[this.packets.length-1],r=t.constructor.tag===Sa.tag?2!==t.version:this.packets.some((e=>e.constructor.tag===ya.tag&&6!==e.version));return Z(T.armor.message,this.write(),null,null,null,r,e)}}async function Uo(e,t,r=[],i=null,n=[],s=new Date,a=[],o=[],c=[],u=!1,h=M){const y=new fa,l=null===e.text?T.signature.binary:T.signature.text;if(await Promise.all(t.map((async(t,i)=>{const y=a[i];if(!t.isPrivate())throw Error("Need private key for signing");const p=await t.getSigningKey(n[i],s,y,h);return Za(e,r.length?r:[t],p.keyPacket,{signatureType:l},s,o,c,u,h)}))).then((e=>{y.push(...e)})),i){const e=i.packets.filterByTag(T.packet.signature);y.push(...e)}return y}async function Do(e,t,r,i=new Date,n=!1,s=M){return Promise.all(e.filter((function(e){return["text","binary"].includes(T.read(T.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,i=new Date,n=!1,s=M){let a,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){a=t,o=r[0];break}}const c=e instanceof ga?e.correspondingSig:e,u={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],i,n,s);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await a.getSigningKey(o.getKeyID(),r.created,void 0,s)}catch(e){if(!s.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await a.getSigningKey(o.getKeyID(),i,void 0,s)}return!0})(),signature:(async()=>{const e=await c,t=new fa;return e&&t.push(e),new qa(t)})()};return u.signature.catch((()=>{})),u.verified.catch((()=>{})),u}(e,t,r,i,n,s)})))}async function xo({armoredMessage:e,binaryMessage:t,config:r,...i}){r={...M,...r};let n=e||t;if(!n)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!F.isString(e)&&!F.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!F.isUint8Array(t)&&!F.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));const a=F.isStream(n);if(e){const{type:e,data:t}=await Y(n);if(e!==T.armor.message)throw Error("Armored text not of type message");n=t}const o=await fa.fromBinary(n,Ko,r),c=new Po(o);return c.fromStream=a,c}async function Io({text:e,binary:t,filename:r,date:i=new Date,format:n=(void 0!==e?"utf8":"binary"),...s}){const a=void 0!==e?e:t;if(void 0===a)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!F.isString(e)&&!F.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!F.isUint8Array(t)&&!F.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=F.isStream(a),u=new aa(i);void 0!==e?u.setText(a,T.write(T.literal,n)):u.setBytes(a,T.write(T.literal,n)),void 0!==r&&u.setFilename(r);const h=new fa;h.push(u);const y=new Po(h);return y.fromStream=c,y}const Co=/*#__PURE__*/F.constructAllowedPackets([ya]);class Bo{constructor(e,t){if(this.text=F.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof qa))throw Error("Invalid signature input");this.signature=t||new qa(new fa)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=[],r=null,i=[],n=new Date,s=[],a=[],o=[],c=M){const u=new aa;u.setText(this.text);const h=new qa(await Uo(u,e,t,r,i,n,s,a,o,!0,c));return new Bo(this.text,h)}verify(e,t=new Date,r=M){const i=this.signature.packets.filterByTag(T.packet.signature),n=new aa;return n.setText(this.text),Do(i,[n],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=M){const t=this.signature.packets.some((e=>6!==e.version)),r={hash:t?Array.from(new Set(this.signature.packets.map((e=>T.read(T.hash,e.hashAlgorithm).toUpperCase())))).join():null,text:this.text,data:this.signature.packets.write()};return Z(T.armor.signed,r,void 0,void 0,void 0,t,e)}}async function To({cleartextMessage:e,config:t,...r}){if(t={...M,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!F.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const i=Object.keys(r);if(i.length>0)throw Error("Unknown option: "+i.join(", "));const n=await Y(e);if(n.type!==T.armor.signed)throw Error("No cleartext signed message.");const s=await fa.fromBinary(n.data,Co,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let i=0;i{const t=e.match(/^Hash: (.+)$/);if(!t)throw Error('Only "Hash" header allowed in cleartext signed message');{const e=t[1].replace(/\s/g,"").split(",").map((e=>{try{return T.write(T.hash,e.toLowerCase())}catch(t){throw Error("Unknown hash algorithm in armor header: "+e.toLowerCase())}}));i.push(...e)}})),i.length&&!r(i))throw Error("Hash algorithm mismatch in armor header and signature")}(n.headers,s);const a=new qa(s);return new Bo(n.text,a)}async function Mo({text:e,...t}){if(!e)throw Error("createCleartextMessage: must pass options object containing `text`");if(!F.isString(e))throw Error("createCleartextMessage: options.text must be a string");const r=Object.keys(t);if(r.length>0)throw Error("Unknown option: "+r.join(", "));return new Bo(e)}async function Lo({userIDs:e=[],passphrase:t,type:r,curve:i,rsaBits:n=4096,keyExpirationTime:s=0,date:a=new Date,subkeys:o=[{}],format:c="armored",config:u,...h}){Yo(u={...M,...u}),r||i?(r=r||"ecc",i=i||"curve25519Legacy"):(r=u.v6Keys?"curve25519":"ecc",i="curve25519Legacy"),e=Zo(e);const y=Object.keys(h);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(0===e.length&&!u.v6Keys)throw Error("UserIDs are required for V4 keys");if("rsa"===r&&nro(e.subkeys[r],e)));let r=[$a(e,t)];r=r.concat(e.subkeys.map((e=>Wa(e,t))));const i=await Promise.all(r),n=await wo(i[0],i.slice(1),e,t),s=await n.getRevocationCertificate(e.date,t);return n.revocationSignatures=[],{key:n,revocationCertificate:s}}(l,u);return e.getKeys().forEach((({keyPacket:e})=>ao(e,u))),{privateKey:tc(e,c,u),publicKey:tc(e.toPublic(),c,u),revocationCertificate:t}}catch(e){throw F.wrapError("Error generating keypair",e)}}async function Fo({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:i=0,date:n,format:s="armored",config:a,...o}){Yo(a={...M,...a}),t=Zo(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length&&6!==e.keyPacket.version)throw Error("UserIDs are required for V4 keys");const u={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:i,date:n};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const i=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,n={key:i,bind:r},s=await Qa(e.bindingSignatures,i,T.signature.subkeyBinding,n,null,t).catch((()=>({})));return{sign:s.keyFlags&&s.keyFlags[0]&T.keyFlags.signData}}))));const n=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==n.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const s=await wo(i,n,e,t),a=await s.getRevocationCertificate(e.date,t);return s.revocationSignatures=[],{key:s,revocationCertificate:a};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=F.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(u,a);return{privateKey:tc(e,s,a),publicKey:tc(e.toPublic(),s,a),revocationCertificate:t}}catch(e){throw F.wrapError("Error reformatting keypair",e)}}async function Ro({key:e,revocationCertificate:t,reasonForRevocation:r,date:i=new Date,format:n="armored",config:s,...a}){Yo(s={...M,...s});const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const a=t?await e.applyRevocationCertificate(t,i,s):await e.revoke(r,i,s);return a.isPrivate()?{privateKey:tc(a,n,s),publicKey:tc(a.toPublic(),n,s)}:{privateKey:null,publicKey:tc(a,n,s)}}catch(e){throw F.wrapError("Error revoking key",e)}}async function No({privateKey:e,passphrase:t,config:r,...i}){Yo(r={...M,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const s=e.clone(!0),a=F.isArray(t)?t:[t];try{return await Promise.all(s.getKeys().map((e=>F.anyPromise(a.map((t=>e.keyPacket.decrypt(t))))))),await s.validate(r),s}catch(e){throw s.clearPrivateParams(),F.wrapError("Error decrypting private key",e)}}async function zo({privateKey:e,passphrase:t,config:r,...i}){Yo(r={...M,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const s=e.clone(!0),a=s.getKeys(),o=F.isArray(t)?t:Array(a.length).fill(t);if(o.length!==a.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(a.map((async(e,t)=>{const{keyPacket:i}=e;await i.encrypt(o[t],r),i.clearPrivateParams()}))),s}catch(e){throw s.clearPrivateParams(),F.wrapError("Error encrypting private key",e)}}async function jo({message:e,encryptionKeys:t,signingKeys:r,passwords:i,sessionKey:n,format:s="armored",signature:a=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:u=[],date:h=new Date,signingUserIDs:y=[],encryptionUserIDs:l=[],signatureNotations:p=[],config:g,...d}){if(Yo(g={...M,...g}),Wo(e),Qo(s),t=Zo(t),r=Zo(r),i=Zo(i),c=Zo(c),u=Zo(u),y=Zo(y),l=Zo(l),p=Zo(p),d.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(d.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(d.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==d.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const f=Object.keys(d);if(f.length>0)throw Error("Unknown option: "+f.join(", "));r||(r=[]);try{if((r.length||a)&&(e=await e.sign(r,t,a,c,h,y,u,p,g)),e=e.compress(await async function(e=[],t=new Date,r=[],i=M){const n=T.compression.uncompressed,s=i.preferredCompressionAlgorithm,a=await Promise.all(e.map((async function(e,n){const a=(await e.getPrimarySelfSignature(t,r[n],i)).preferredCompressionAlgorithms;return!!a&&a.indexOf(s)>=0})));return a.every(Boolean)?s:n}(t,h,l,g),g),e=await e.encrypt(t,i,n,o,u,h,l,g),"object"===s)return e;const d="armored"===s?e.armor(g):e.write();return await Jo(d)}catch(e){throw F.wrapError("Error encrypting message",e)}}async function Oo({message:e,decryptionKeys:t,passwords:r,sessionKeys:i,verificationKeys:n,expectSigned:s=!1,format:a="utf8",signature:o=null,date:c=new Date,config:u,...h}){if(Yo(u={...M,...u}),Wo(e),n=Zo(n),t=Zo(t),r=Zo(r),i=Zo(i),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(h.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const y=Object.keys(h);if(y.length>0)throw Error("Unknown option: "+y.join(", "));try{const h=await e.decrypt(t,r,i,c,u);n||(n=[]);const y={};if(y.signatures=o?await h.verifyDetached(o,n,c,u):await h.verify(n,c,u),y.data="binary"===a?h.getLiteralData():h.getText(),y.filename=h.getFilename(),ec(y,e),s){if(0===n.length)throw Error("Verification keys are required to verify message signatures");if(0===y.signatures.length)throw Error("Message is not signed");y.data=f([y.data,x((async()=>{await F.anyPromise(y.signatures.map((e=>e.verified)))}))])}return y.data=await Jo(y.data),y}catch(e){throw F.wrapError("Error decrypting message",e)}}async function Ho({message:e,signingKeys:t,recipientKeys:r=[],format:i="armored",detached:n=!1,signingKeyIDs:s=[],date:a=new Date,signingUserIDs:o=[],recipientUserIDs:c=[],signatureNotations:u=[],config:h,...y}){if(Yo(h={...M,...h}),$o(e),Qo(i),t=Zo(t),s=Zo(s),o=Zo(o),r=Zo(r),c=Zo(c),u=Zo(u),y.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==y.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const l=Object.keys(y);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(e instanceof Bo&&"binary"===i)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Bo&&n)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let y;if(y=n?await e.signDetached(t,r,void 0,s,a,o,c,u,h):await e.sign(t,r,void 0,s,a,o,c,u,h),"object"===i)return y;return y="armored"===i?y.armor(h):y.write(),n&&(y=v(e.packets.write(),(async(e,t)=>{await Promise.all([m(y,t),U(e).catch((()=>{}))])}))),await Jo(y)}catch(e){throw F.wrapError("Error signing message",e)}}async function _o({message:e,verificationKeys:t,expectSigned:r=!1,format:i="utf8",signature:n=null,date:s=new Date,config:a,...o}){if(Yo(a={...M,...a}),$o(e),t=Zo(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Bo&&"binary"===i)throw Error("Can't return cleartext message data as binary");if(e instanceof Bo&&n)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=n?await e.verifyDetached(n,t,s,a):await e.verify(t,s,a),o.data="binary"===i?e.getLiteralData():e.getText(),e.fromStream&&!n&&ec(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=f([o.data,x((async()=>{await F.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Jo(o.data),o}catch(e){throw F.wrapError("Error verifying signed message",e)}}async function Go({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:i,...n}){if(Yo(i={...M,...i}),e=Zo(e),r=Zo(r),n.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await Po.generateSessionKey(e,t,r,i)}catch(e){throw F.wrapError("Error generating session key",e)}}async function qo({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:i,passwords:n,format:s="armored",wildcard:a=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:u=[],config:h,...y}){if(Yo(h={...M,...h}),function(e){if(!F.isUint8Array(e))throw Error("Parameter [data] must be of type Uint8Array")}(e),function(e,t){if(!F.isString(e))throw Error("Parameter ["+t+"] must be of type String")}(t,"algorithm"),Qo(s),i=Zo(i),n=Zo(n),o=Zo(o),u=Zo(u),y.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const l=Object.keys(y);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(!(i&&0!==i.length||n&&0!==n.length))throw Error("No encryption keys or passwords provided.");try{return tc(await Po.encryptSessionKey(e,t,r,i,n,a,o,c,u,h),s,h)}catch(e){throw F.wrapError("Error encrypting session key",e)}}async function Vo({message:e,decryptionKeys:t,passwords:r,date:i=new Date,config:n,...s}){if(Yo(n={...M,...n}),Wo(e),t=Zo(t),r=Zo(r),s.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const a=Object.keys(s);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await e.decryptSessionKeys(t,r,void 0,i,n)}catch(e){throw F.wrapError("Error decrypting session keys",e)}}function Wo(e){if(!(e instanceof Po))throw Error("Parameter [message] needs to be of type Message")}function $o(e){if(!(e instanceof Bo||e instanceof Po))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Qo(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Xo=Object.keys(M).length;function Yo(e){const t=Object.keys(e);if(t.length!==Xo)for(const e of t)if(void 0===M[e])throw Error("Unknown config property: "+e)}function Zo(e){return e&&!F.isArray(e)&&(e=[e]),e}async function Jo(e){return"array"===F.isStream(e)?U(e):e}function ec(e,t){e.data=v(t.packets.stream,(async(t,r)=>{await m(e.data,r,{preventClose:!0});const i=C(r);try{await U(t,(e=>e)),await i.close()}catch(e){await i.abort(e)}}))}function tc(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}export{Da as AEADEncryptedDataPacket,Bo as CleartextMessage,wa as CompressedDataPacket,aa as LiteralDataPacket,La as MarkerPacket,Po as Message,ga as OnePassSignaturePacket,fa as PacketList,_a as PaddingPacket,go as PrivateKey,po as PublicKey,xa as PublicKeyEncryptedSessionKeyPacket,Ba as PublicKeyPacket,Fa as PublicSubkeyPacket,Na as SecretKeyPacket,Oa as SecretSubkeyPacket,qa as Signature,ya as SignaturePacket,co as Subkey,Sa as SymEncryptedIntegrityProtectedDataPacket,Ca as SymEncryptedSessionKeyPacket,Ma as SymmetricallyEncryptedDataPacket,Ha as TrustPacket,Vi as UnparseablePacket,Ra as UserAttributePacket,ja as UserIDPacket,Z as armor,M as config,Mo as createCleartextMessage,Io as createMessage,Oo as decrypt,No as decryptKey,Vo as decryptSessionKeys,jo as encrypt,zo as encryptKey,qo as encryptSessionKey,T as enums,Lo as generateKey,Go as generateSessionKey,To as readCleartextMessage,bo as readKey,vo as readKeys,xo as readMessage,ko as readPrivateKey,Ao as readPrivateKeys,Va as readSignature,Fo as reformatKey,Ro as revokeKey,Ho as sign,Y as unarmor,_o as verify}; //# sourceMappingURL=openpgp.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs.map index 9ae210e9f..426a35f1a 100644 --- a/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs.map +++ b/app/node_modules/openpgp/dist/lightweight/openpgp.min.mjs.map @@ -1 +1 @@ -{"version":3,"file":"openpgp.min.mjs","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/node-conversions.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/biginteger/native.interface.js","../../src/biginteger/index.js","../../src/enums.js","../../src/util.js","../../src/encoding/base64.js","../../src/config/config.js","../../src/encoding/armor.js","../../src/type/keyid.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/utils.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/errors.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ecb.js","../../src/crypto/cipher/aes.js","../../src/crypto/cipher/des.js","../../src/crypto/cipher/cast5.js","../../src/crypto/cipher/twofish.js","../../src/crypto/cipher/blowfish.js","../../src/crypto/cipher/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/hash.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.asm.js","../../node_modules/minimalistic-assert/index.js","../../node_modules/inherits/inherits_browser.js","../../node_modules/hash.js/lib/hash/utils.js","../../node_modules/hash.js/lib/hash/common.js","../../node_modules/hash.js/lib/hash/sha/common.js","../../node_modules/hash.js/lib/hash/sha/256.js","../../node_modules/hash.js/lib/hash/sha/224.js","../../node_modules/hash.js/lib/hash/sha/512.js","../../node_modules/hash.js/lib/hash/sha/384.js","../../node_modules/hash.js/lib/hash/ripemd.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cfb.js","../../src/crypto/cipher/getCipher.js","../../src/crypto/mode/cfb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ctr.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cbc.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/gcm.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../node_modules/@openpgp/tweetnacl/nacl-fast-light.js","../../src/crypto/random.js","../../src/crypto/public_key/prime.js","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../src/type/oid.js","../../src/crypto/public_key/elliptic/indutnyKey.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../node_modules/@openpgp/pako/lib/utils/common.js","../../node_modules/@openpgp/pako/lib/zlib/constants.js","../../node_modules/@openpgp/pako/lib/zlib/trees.js","../../node_modules/@openpgp/pako/lib/zlib/adler32.js","../../node_modules/@openpgp/pako/lib/zlib/crc32.js","../../node_modules/@openpgp/pako/lib/zlib/messages.js","../../node_modules/@openpgp/pako/lib/zlib/deflate.js","../../node_modules/@openpgp/pako/lib/utils/strings.js","../../node_modules/@openpgp/pako/lib/zlib/zstream.js","../../node_modules/@openpgp/pako/lib/deflate.js","../../node_modules/@openpgp/pako/lib/zlib/inffast.js","../../node_modules/@openpgp/pako/lib/zlib/inftrees.js","../../node_modules/@openpgp/pako/lib/zlib/inflate.js","../../node_modules/@openpgp/pako/lib/zlib/gzheader.js","../../node_modules/@openpgp/pako/lib/inflate.js","../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js","../../src/packet/literal_data.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/type/s2k.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/marker.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../node_modules/email-addresses/lib/email-addresses.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/packet/trust.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","import * as streams from './streams';\nimport { isArrayStream } from './writer';\n\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n if (streams.ReadableStream && streams.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'ponyfill';\n }\n if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {\n return 'node';\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isNode } from './util';\nimport * as streams from './streams';\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Web / node stream conversion functions\n * From https://github.com/gwicke/node-web-streams\n */\n\nlet nodeToWeb;\nlet webToNode;\n\nif (NodeReadableStream) {\n\n /**\n * Convert a Node Readable Stream to a Web ReadableStream\n * @param {Readable} nodeStream\n * @returns {ReadableStream}\n */\n nodeToWeb = function(nodeStream) {\n let canceled = false;\n return new streams.ReadableStream({\n start(controller) {\n nodeStream.pause();\n nodeStream.on('data', chunk => {\n if (canceled) {\n return;\n }\n if (NodeBuffer.isBuffer(chunk)) {\n chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n controller.enqueue(chunk);\n nodeStream.pause();\n });\n nodeStream.on('end', () => {\n if (canceled) {\n return;\n }\n controller.close();\n });\n nodeStream.on('error', e => controller.error(e));\n },\n pull() {\n nodeStream.resume();\n },\n cancel(reason) {\n canceled = true;\n nodeStream.destroy(reason);\n }\n });\n };\n\n\n class NodeReadable extends NodeReadableStream {\n constructor(webStream, options) {\n super(options);\n this._reader = streams.getReader(webStream);\n }\n\n async _read(size) {\n try {\n while (true) {\n const { done, value } = await this._reader.read();\n if (done) {\n this.push(null);\n break;\n }\n if (!this.push(value)) {\n break;\n }\n }\n } catch (e) {\n this.destroy(e);\n }\n }\n\n async _destroy(error, callback) {\n this._reader.cancel(error).then(callback, callback);\n }\n }\n\n /**\n * Convert a Web ReadableStream to a Node Readable Stream\n * @param {ReadableStream} webStream\n * @param {Object} options\n * @returns {Readable}\n */\n webToNode = function(webStream, options) {\n return new NodeReadable(webStream, options);\n };\n\n}\n\nexport { nodeToWeb, webToNode };\n","import * as streams from './streams';\nimport { isUint8Array } from './util';\n\nconst doneReadingSet = new WeakSet();\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (streams.isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = async () => {};\n return;\n }\n let streamType = streams.isStream(input);\n if (streamType === 'node') {\n input = streams.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array } from './util';\nimport { nodeToWeb, webToNode } from './node-conversions';\nimport { Reader, externalBuffer } from './reader';\nimport { ArrayStream, Writer } from './writer';\n\nlet { ReadableStream, WritableStream, TransformStream } = globalThis;\n\nlet toPonyfillReadable, toNativeReadable;\n\nasync function loadStreamsPonyfill() {\n if (TransformStream) {\n return;\n }\n\n const [ponyfill, adapter] = await Promise.all([\n import('web-streams-polyfill/ponyfill/es6'),\n import('@mattiasbuelens/web-streams-adapter')\n ]);\n\n ({ ReadableStream, WritableStream, TransformStream } = ponyfill);\n\n const { createReadableStreamWrapper } = adapter;\n\n if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {\n toPonyfillReadable = createReadableStreamWrapper(ReadableStream);\n toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);\n }\n}\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType === 'node') {\n return nodeToWeb(input);\n }\n if (streamType === 'web' && toPonyfillReadable) {\n return toPonyfillReadable(input);\n }\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert data to ArrayStream\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {\n return NodeBuffer.concat(list);\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n } else {\n lastBytes = returnValue;\n }\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {\n if (end === Infinity) end = input.length;\n return input.subarray(begin, end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n return input.cancel(reason);\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n\nexport { ReadableStream, WritableStream, TransformStream, ArrayStream, loadStreamsPonyfill, isStream, isArrayStream, isUint8Array, toStream, toPonyfillReadable, toNativeReadable, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };\n","/* eslint-disable new-cap */\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * that wraps the native BigInt library.\n * Operations are not constant time,\n * but we try and limit timing leakage where we can\n * @module biginteger/native\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on null or undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n if (n instanceof Uint8Array) {\n const bytes = n;\n const hex = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n const hexByte = bytes[i].toString(16);\n hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;\n }\n this.value = BigInt('0x0' + hex.join(''));\n } else {\n this.value = BigInt(n);\n }\n }\n\n clone() {\n return new BigInteger(this.value);\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value++;\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value--;\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value += x.value;\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value -= x.value;\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value *= x.value;\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value %= m.value;\n if (this.isNegative()) {\n this.iadd(m);\n }\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation using square and multiply\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n if (n.isZero()) throw Error('Modulo cannot be zero');\n if (n.isOne()) return new BigInteger(0);\n if (e.isNegative()) throw Error('Unsopported negative exponent');\n\n let exp = e.value;\n let x = this.value;\n\n x %= n.value;\n let r = BigInt(1);\n while (exp > BigInt(0)) {\n const lsb = exp & BigInt(1);\n exp >>= BigInt(1); // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n.value;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n.value; // Square\n }\n return new BigInteger(r);\n }\n\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n const { gcd, x } = this._egcd(n);\n if (!gcd.isOne()) {\n throw new Error('Inverse does not exist');\n }\n return x.add(n).mod(n);\n }\n\n /**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)\n * @param {BigInteger} b - Second operand\n * @returns {{ gcd, x, y: BigInteger }}\n */\n _egcd(b) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n let a = this.value;\n b = b.value;\n\n while (b !== BigInt(0)) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: new BigInteger(xPrev),\n y: new BigInteger(yPrev),\n gcd: new BigInteger(a)\n };\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} b - Operand\n * @returns {BigInteger} gcd\n */\n gcd(b) {\n let a = this.value;\n b = b.value;\n while (b !== BigInt(0)) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return new BigInteger(a);\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value <<= x.value;\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value >>= x.value;\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value === x.value;\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value < x.value;\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value <= x.value;\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value > x.value;\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value >= x.value;\n }\n\n isZero() {\n return this.value === BigInt(0);\n }\n\n isOne() {\n return this.value === BigInt(1);\n }\n\n isNegative() {\n return this.value < BigInt(0);\n }\n\n isEven() {\n return !(this.value & BigInt(1));\n }\n\n abs() {\n const res = this.clone();\n if (this.isNegative()) {\n res.value = -res.value;\n }\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n const number = Number(this.value);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n const bit = (this.value >> BigInt(i)) & BigInt(1);\n return (bit === BigInt(0)) ? 0 : 1;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n const zero = new BigInteger(0);\n const one = new BigInteger(1);\n const negOne = new BigInteger(-1);\n\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = this.isNegative() ? negOne : zero;\n let bitlen = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(one).equal(target)) {\n bitlen++;\n }\n return bitlen;\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n const zero = new BigInteger(0);\n const negOne = new BigInteger(-1);\n\n const target = this.isNegative() ? negOne : zero;\n const eight = new BigInteger(8);\n let len = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(eight).equal(target)) {\n len++;\n }\n return len;\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = this.value.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? (length - rawLength) : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n }\n}\n","import BigInteger from './native.interface';\n\nconst detectBigInt = () => typeof BigInt !== 'undefined';\n\nasync function getBigInteger() {\n if (detectBigInt()) {\n return BigInteger;\n } else {\n const { default: BigInteger } = await import('./bn.interface');\n return BigInteger;\n }\n}\n\nexport { getBigInteger };\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'p256': 'p256',\n 'P-256': 'p256',\n 'secp256r1': 'p256',\n 'prime256v1': 'p256',\n '1.2.840.10045.3.1.7': 'p256',\n '2a8648ce3d030107': 'p256',\n '2A8648CE3D030107': 'p256',\n\n /** NIST P-384 Curve */\n 'p384': 'p384',\n 'P-384': 'p384',\n 'secp384r1': 'p384',\n '1.3.132.0.34': 'p384',\n '2b81040022': 'p384',\n '2B81040022': 'p384',\n\n /** NIST P-521 Curve */\n 'p521': 'p521',\n 'P-521': 'p521',\n 'secp521r1': 'p521',\n '1.3.132.0.35': 'p521',\n '2b81040023': 'p521',\n '2B81040023': 'p521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n '1.3.132.0.10': 'secp256k1',\n '2b8104000a': 'secp256k1',\n '2B8104000A': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519',\n 'ED25519': 'ed25519',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519',\n 'Ed25519': 'ed25519',\n '1.3.6.1.4.1.11591.15.1': 'ed25519',\n '2b06010401da470f01': 'ed25519',\n '2B06010401DA470F01': 'ed25519',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519',\n 'X25519': 'curve25519',\n 'cv25519': 'curve25519',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519',\n 'Curve25519': 'curve25519',\n '1.3.6.1.4.1.3029.1.5.1': 'curve25519',\n '2b060104019755010501': 'curve25519',\n '2B060104019755010501': 'curve25519',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',\n '2b2403030208010107': 'brainpoolP256r1',\n '2B2403030208010107': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',\n '2b240303020801010b': 'brainpoolP384r1',\n '2B240303020801010B': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1',\n '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',\n '2b240303020801010d': 'brainpoolP512r1',\n '2B240303020801010D': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility\n /** @deprecated use `eddsaLegacy` instead */\n ed25519Legacy: 22,\n /** @deprecated use `eddsaLegacy` instead */\n eddsa: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n plaintext: 0,\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuer: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { getBigInteger } from './biginteger';\nimport enums from './enums';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n return bytes.subarray(2, 2 + bytelen);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const r = [];\n const e = bytes.length;\n let c = 0;\n let h;\n while (c < e) {\n h = bytes[c++].toString(16);\n while (h.length < 2) {\n h = '0' + h;\n }\n r.push('' + h);\n }\n return r.join('');\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography api, only the current version of the spec.\n * @returns {Object} The SubtleCrypto api or 'undefined'.\n */\n getWebCrypto: function() {\n return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n },\n\n /**\n * Get BigInteger class\n * It wraps the native BigInt type if it's available\n * Otherwise it relies on bn.js\n * @returns {BigInteger}\n * @async\n */\n getBigInteger,\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return require('crypto');\n },\n\n getNodeZlib: function() {\n return require('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (require('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = require('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\\-0-9]+)))$/;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha256,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * @memberof module:config\n * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9\n */\n deflateLevel: 6,\n\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.eax,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use V5 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v5Keys\n */\n v5Keys: false,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:\n * Iteration Count Byte for S2K (String to Key)\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * @memberof module:config\n * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum\n */\n checksumRequired: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * @memberof module:config\n * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored\n */\n revocationsExpire: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n\n /**\n * @memberof module:config\n * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available\n */\n minBytesForWebCrypto: 1000,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * Note: the indutny/elliptic curve library is not designed to be constant time.\n * @memberof module:config\n * @property {Boolean} useIndutnyElliptic\n */\n useIndutnyElliptic: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n } else\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n } else\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n } else\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n } else\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n } else\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n } else\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Splits a message into two parts, the body and the checksum. This is an internal function\n * @param {String} text - OpenPGP armored message part\n * @returns {Object} An object with attribute \"body\" containing the body.\n * and an attribute \"checksum\" containing the checksum.\n * @private\n */\nfunction splitChecksum(text) {\n let body = text;\n let checksum = '';\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n checksum = text.slice(lastEquals + 1).substr(0, 4);\n }\n\n return { body: body, checksum: checksum };\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input, config = defaultConfig) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n let checksum;\n let data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== 2) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === 2) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const split = splitChecksum(parts[0].slice(0, -1));\n checksum = split.checksum;\n await writer.write(split.body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n data = stream.transformPair(data, async (readable, writable) => {\n const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));\n checksumVerified.catch(() => {});\n await stream.pipe(readable, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n const checksumVerifiedString = (await checksumVerified).replace('\\n', '');\n if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {\n throw new Error('Ascii armor integrity check failed');\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n const bodyClone = stream.passiveClone(body);\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push('Hash: ' + hash + '\\n\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n * @private\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","/**\n * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.\n * @author Artem S Vybornov \n * @license MIT\n */\nexport var AES_asm = function () {\n \"use strict\";\n\n /**\n * Galois Field stuff init flag\n */\n var ginit_done = false;\n\n /**\n * Galois Field exponentiation and logarithm tables for 3 (the generator)\n */\n var gexp3, glog3;\n\n /**\n * Init Galois Field tables\n */\n function ginit() {\n gexp3 = [],\n glog3 = [];\n\n var a = 1, c, d;\n for (c = 0; c < 255; c++) {\n gexp3[c] = a;\n\n // Multiply by three\n d = a & 0x80, a <<= 1, a &= 255;\n if (d === 0x80) a ^= 0x1b;\n a ^= gexp3[c];\n\n // Set the log table value\n glog3[gexp3[c]] = c;\n }\n gexp3[255] = gexp3[0];\n glog3[0] = 0;\n\n ginit_done = true;\n }\n\n /**\n * Galois Field multiplication\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\n function gmul(a, b) {\n var c = gexp3[(glog3[a] + glog3[b]) % 255];\n if (a === 0 || b === 0) c = 0;\n return c;\n }\n\n /**\n * Galois Field reciprocal\n * @param {number} a\n * @return {number}\n */\n function ginv(a) {\n var i = gexp3[255 - glog3[a]];\n if (a === 0) i = 0;\n return i;\n }\n\n /**\n * AES stuff init flag\n */\n var aes_init_done = false;\n\n /**\n * Encryption, Decryption, S-Box and KeyTransform tables\n *\n * @type {number[]}\n */\n var aes_sbox;\n\n /**\n * @type {number[]}\n */\n var aes_sinv;\n\n /**\n * @type {number[][]}\n */\n var aes_enc;\n\n /**\n * @type {number[][]}\n */\n var aes_dec;\n\n /**\n * Init AES tables\n */\n function aes_init() {\n if (!ginit_done) ginit();\n\n // Calculates AES S-Box value\n function _s(a) {\n var c, s, x;\n s = x = ginv(a);\n for (c = 0; c < 4; c++) {\n s = ((s << 1) | (s >>> 7)) & 255;\n x ^= s;\n }\n x ^= 99;\n return x;\n }\n\n // Tables\n aes_sbox = [],\n aes_sinv = [],\n aes_enc = [[], [], [], []],\n aes_dec = [[], [], [], []];\n\n for (var i = 0; i < 256; i++) {\n var s = _s(i);\n\n // S-Box and its inverse\n aes_sbox[i] = s;\n aes_sinv[s] = i;\n\n // Ecryption and Decryption tables\n aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);\n aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);\n // Rotate tables\n for (var t = 1; t < 4; t++) {\n aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);\n aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);\n }\n }\n\n aes_init_done = true;\n }\n\n /**\n * Asm.js module constructor.\n *\n *

\n * Heap buffer layout by offset:\n *

\n   * 0x0000   encryption key schedule\n   * 0x0400   decryption key schedule\n   * 0x0800   sbox\n   * 0x0c00   inv sbox\n   * 0x1000   encryption tables\n   * 0x2000   decryption tables\n   * 0x3000   reserved (future GCM multiplication lookup table)\n   * 0x4000   data\n   * 
\n * Don't touch anything before 0x400.\n *

\n *\n * @alias AES_asm\n * @class\n * @param foreign - ignored\n * @param buffer - heap buffer to link with\n */\n var wrapper = function (foreign, buffer) {\n // Init AES stuff for the first time\n if (!aes_init_done) aes_init();\n\n // Fill up AES tables\n var heap = new Uint32Array(buffer);\n heap.set(aes_sbox, 0x0800 >> 2);\n heap.set(aes_sinv, 0x0c00 >> 2);\n for (var i = 0; i < 4; i++) {\n heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);\n heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);\n }\n\n /**\n * Calculate AES key schedules.\n * @instance\n * @memberof AES_asm\n * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)\n * @param {number} k0 - key vector components\n * @param {number} k1 - key vector components\n * @param {number} k2 - key vector components\n * @param {number} k3 - key vector components\n * @param {number} k4 - key vector components\n * @param {number} k5 - key vector components\n * @param {number} k6 - key vector components\n * @param {number} k7 - key vector components\n */\n function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {\n var ekeys = heap.subarray(0x000, 60),\n dkeys = heap.subarray(0x100, 0x100 + 60);\n\n // Encryption key schedule\n ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);\n for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {\n var k = ekeys[i - 1];\n if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {\n k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];\n }\n if (i % ks === 0) {\n k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);\n }\n ekeys[i] = ekeys[i - ks] ^ k;\n }\n\n // Decryption key schedule\n for (var j = 0; j < i; j += 4) {\n for (var jj = 0; jj < 4; jj++) {\n var k = ekeys[i - (4 + j) + (4 - jj) % 4];\n if (j < 4 || j >= i - 4) {\n dkeys[j + jj] = k;\n } else {\n dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]\n ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]\n ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]\n ^ aes_dec[3][aes_sbox[k & 255]];\n }\n }\n }\n\n // Set rounds number\n asm.set_rounds(ks + 5);\n }\n\n // create library object with necessary properties\n var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};\n\n var asm = function (stdlib, foreign, buffer) {\n \"use asm\";\n\n var S0 = 0, S1 = 0, S2 = 0, S3 = 0,\n I0 = 0, I1 = 0, I2 = 0, I3 = 0,\n N0 = 0, N1 = 0, N2 = 0, N3 = 0,\n M0 = 0, M1 = 0, M2 = 0, M3 = 0,\n H0 = 0, H1 = 0, H2 = 0, H3 = 0,\n R = 0;\n\n var HEAP = new stdlib.Uint32Array(buffer),\n DATA = new stdlib.Uint8Array(buffer);\n\n /**\n * AES core\n * @param {number} k - precomputed key schedule offset\n * @param {number} s - precomputed sbox table offset\n * @param {number} t - precomputed round table offset\n * @param {number} r - number of inner rounds to perform\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _core(k, s, t, r, x0, x1, x2, x3) {\n k = k | 0;\n s = s | 0;\n t = t | 0;\n r = r | 0;\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t1 = 0, t2 = 0, t3 = 0,\n y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n i = 0;\n\n t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;\n\n // round 0\n x0 = x0 ^ HEAP[(k | 0) >> 2],\n x1 = x1 ^ HEAP[(k | 4) >> 2],\n x2 = x2 ^ HEAP[(k | 8) >> 2],\n x3 = x3 ^ HEAP[(k | 12) >> 2];\n\n // round 1..r\n for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {\n y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n x0 = y0, x1 = y1, x2 = y2, x3 = y3;\n }\n\n // final round\n S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n }\n\n /**\n * ECB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n x0,\n x1,\n x2,\n x3\n );\n }\n\n /**\n * ECB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n }\n\n\n /**\n * CBC mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0 ^ x0,\n I1 ^ x1,\n I2 ^ x2,\n I3 ^ x3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n }\n\n /**\n * CBC mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n\n S0 = S0 ^ I0,\n S1 = S1 ^ I1,\n S2 = S2 ^ I2,\n S3 = S3 ^ I3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * CFB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0 = S0 ^ x0,\n I1 = S1 = S1 ^ x1,\n I2 = S2 = S2 ^ x2,\n I3 = S3 = S3 ^ x3;\n }\n\n\n /**\n * CFB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * OFB mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ofb(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n }\n\n /**\n * CTR mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ctr(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n N0,\n N1,\n N2,\n N3\n );\n\n N3 = (~M3 & N3) | M3 & (N3 + 1);\n N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));\n N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));\n N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));\n\n S0 = S0 ^ x0;\n S1 = S1 ^ x1;\n S2 = S2 ^ x2;\n S3 = S3 ^ x3;\n }\n\n /**\n * GCM mode MAC calculation\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _gcm_mac(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n z0 = 0, z1 = 0, z2 = 0, z3 = 0,\n i = 0, c = 0;\n\n x0 = x0 ^ I0,\n x1 = x1 ^ I1,\n x2 = x2 ^ I2,\n x3 = x3 ^ I3;\n\n y0 = H0 | 0,\n y1 = H1 | 0,\n y2 = H2 | 0,\n y3 = H3 | 0;\n\n for (; (i | 0) < 128; i = (i + 1) | 0) {\n if (y0 >>> 31) {\n z0 = z0 ^ x0,\n z1 = z1 ^ x1,\n z2 = z2 ^ x2,\n z3 = z3 ^ x3;\n }\n\n y0 = (y0 << 1) | (y1 >>> 31),\n y1 = (y1 << 1) | (y2 >>> 31),\n y2 = (y2 << 1) | (y3 >>> 31),\n y3 = (y3 << 1);\n\n c = x3 & 1;\n\n x3 = (x3 >>> 1) | (x2 << 31),\n x2 = (x2 >>> 1) | (x1 << 31),\n x1 = (x1 >>> 1) | (x0 << 31),\n x0 = (x0 >>> 1);\n\n if (c) x0 = x0 ^ 0xe1000000;\n }\n\n I0 = z0,\n I1 = z1,\n I2 = z2,\n I3 = z3;\n }\n\n /**\n * Set the internal rounds number.\n * @instance\n * @memberof AES_asm\n * @param {number} r - number if inner AES rounds\n */\n function set_rounds(r) {\n r = r | 0;\n R = r;\n }\n\n /**\n * Populate the internal state of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} s0 - state vector\n * @param {number} s1 - state vector\n * @param {number} s2 - state vector\n * @param {number} s3 - state vector\n */\n function set_state(s0, s1, s2, s3) {\n s0 = s0 | 0;\n s1 = s1 | 0;\n s2 = s2 | 0;\n s3 = s3 | 0;\n\n S0 = s0,\n S1 = s1,\n S2 = s2,\n S3 = s3;\n }\n\n /**\n * Populate the internal iv of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} i0 - iv vector\n * @param {number} i1 - iv vector\n * @param {number} i2 - iv vector\n * @param {number} i3 - iv vector\n */\n function set_iv(i0, i1, i2, i3) {\n i0 = i0 | 0;\n i1 = i1 | 0;\n i2 = i2 | 0;\n i3 = i3 | 0;\n\n I0 = i0,\n I1 = i1,\n I2 = i2,\n I3 = i3;\n }\n\n /**\n * Set nonce for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} n0 - nonce vector\n * @param {number} n1 - nonce vector\n * @param {number} n2 - nonce vector\n * @param {number} n3 - nonce vector\n */\n function set_nonce(n0, n1, n2, n3) {\n n0 = n0 | 0;\n n1 = n1 | 0;\n n2 = n2 | 0;\n n3 = n3 | 0;\n\n N0 = n0,\n N1 = n1,\n N2 = n2,\n N3 = n3;\n }\n\n /**\n * Set counter mask for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} m0 - counter mask vector\n * @param {number} m1 - counter mask vector\n * @param {number} m2 - counter mask vector\n * @param {number} m3 - counter mask vector\n */\n function set_mask(m0, m1, m2, m3) {\n m0 = m0 | 0;\n m1 = m1 | 0;\n m2 = m2 | 0;\n m3 = m3 | 0;\n\n M0 = m0,\n M1 = m1,\n M2 = m2,\n M3 = m3;\n }\n\n /**\n * Set counter for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} c0 - counter vector\n * @param {number} c1 - counter vector\n * @param {number} c2 - counter vector\n * @param {number} c3 - counter vector\n */\n function set_counter(c0, c1, c2, c3) {\n c0 = c0 | 0;\n c1 = c1 | 0;\n c2 = c2 | 0;\n c3 = c3 | 0;\n\n N3 = (~M3 & N3) | M3 & c3,\n N2 = (~M2 & N2) | M2 & c2,\n N1 = (~M1 & N1) | M1 & c1,\n N0 = (~M0 & N0) | M0 & c0;\n }\n\n /**\n * Store the internal state vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_state(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n return 16;\n }\n\n /**\n * Store the internal iv vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_iv(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = I0 >>> 24,\n DATA[pos | 1] = I0 >>> 16 & 255,\n DATA[pos | 2] = I0 >>> 8 & 255,\n DATA[pos | 3] = I0 & 255,\n DATA[pos | 4] = I1 >>> 24,\n DATA[pos | 5] = I1 >>> 16 & 255,\n DATA[pos | 6] = I1 >>> 8 & 255,\n DATA[pos | 7] = I1 & 255,\n DATA[pos | 8] = I2 >>> 24,\n DATA[pos | 9] = I2 >>> 16 & 255,\n DATA[pos | 10] = I2 >>> 8 & 255,\n DATA[pos | 11] = I2 & 255,\n DATA[pos | 12] = I3 >>> 24,\n DATA[pos | 13] = I3 >>> 16 & 255,\n DATA[pos | 14] = I3 >>> 8 & 255,\n DATA[pos | 15] = I3 & 255;\n\n return 16;\n }\n\n /**\n * GCM initialization.\n * @instance\n * @memberof AES_asm\n */\n function gcm_init() {\n _ecb_enc(0, 0, 0, 0);\n H0 = S0,\n H1 = S1,\n H2 = S2,\n H3 = S3;\n }\n\n /**\n * Perform ciphering operation on the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function cipher(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _cipher_modes[mode & 7](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * Calculates MAC of the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function mac(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _mac_modes[mode & 1](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * AES cipher modes table (virual methods)\n */\n var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];\n\n /**\n * AES MAC modes table (virual methods)\n */\n var _mac_modes = [_cbc_enc, _gcm_mac];\n\n /**\n * Asm.js module exports\n */\n return {\n set_rounds: set_rounds,\n set_state: set_state,\n set_iv: set_iv,\n set_nonce: set_nonce,\n set_mask: set_mask,\n set_counter: set_counter,\n get_state: get_state,\n get_iv: get_iv,\n gcm_init: gcm_init,\n cipher: cipher,\n mac: mac,\n };\n }(stdlib, foreign, buffer);\n\n asm.set_key = set_key;\n\n return asm;\n };\n\n /**\n * AES enciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.ENC = {\n ECB: 0,\n CBC: 2,\n CFB: 4,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES deciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.DEC = {\n ECB: 1,\n CBC: 3,\n CFB: 5,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES MAC mode constants\n * @enum {number}\n * @const\n */\n wrapper.MAC = {\n CBC: 0,\n GCM: 1,\n };\n\n /**\n * Heap data offset\n * @type {number}\n * @const\n */\n wrapper.HEAP_DATA = 0x4000;\n\n return wrapper;\n}();\n","const local_atob = typeof atob === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'base64').toString('binary') : atob;\nconst local_btoa = typeof btoa === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'binary').toString('base64') : btoa;\nexport function string_to_bytes(str, utf8 = false) {\n var len = str.length, bytes = new Uint8Array(utf8 ? 4 * len : len);\n for (var i = 0, j = 0; i < len; i++) {\n var c = str.charCodeAt(i);\n if (utf8 && 0xd800 <= c && c <= 0xdbff) {\n if (++i >= len)\n throw new Error('Malformed string, low surrogate expected at position ' + i);\n c = ((c ^ 0xd800) << 10) | 0x10000 | (str.charCodeAt(i) ^ 0xdc00);\n }\n else if (!utf8 && c >>> 8) {\n throw new Error('Wide characters are not allowed.');\n }\n if (!utf8 || c <= 0x7f) {\n bytes[j++] = c;\n }\n else if (c <= 0x7ff) {\n bytes[j++] = 0xc0 | (c >> 6);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else if (c <= 0xffff) {\n bytes[j++] = 0xe0 | (c >> 12);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else {\n bytes[j++] = 0xf0 | (c >> 18);\n bytes[j++] = 0x80 | ((c >> 12) & 0x3f);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n }\n return bytes.subarray(0, j);\n}\nexport function hex_to_bytes(str) {\n var len = str.length;\n if (len & 1) {\n str = '0' + str;\n len++;\n }\n var bytes = new Uint8Array(len >> 1);\n for (var i = 0; i < len; i += 2) {\n bytes[i >> 1] = parseInt(str.substr(i, 2), 16);\n }\n return bytes;\n}\nexport function base64_to_bytes(str) {\n return string_to_bytes(local_atob(str));\n}\nexport function bytes_to_string(bytes, utf8 = false) {\n var len = bytes.length, chars = new Array(len);\n for (var i = 0, j = 0; i < len; i++) {\n var b = bytes[i];\n if (!utf8 || b < 128) {\n chars[j++] = b;\n }\n else if (b >= 192 && b < 224 && i + 1 < len) {\n chars[j++] = ((b & 0x1f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 224 && b < 240 && i + 2 < len) {\n chars[j++] = ((b & 0xf) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 240 && b < 248 && i + 3 < len) {\n var c = ((b & 7) << 18) | ((bytes[++i] & 0x3f) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n if (c <= 0xffff) {\n chars[j++] = c;\n }\n else {\n c ^= 0x10000;\n chars[j++] = 0xd800 | (c >> 10);\n chars[j++] = 0xdc00 | (c & 0x3ff);\n }\n }\n else {\n throw new Error('Malformed UTF8 character at byte offset ' + i);\n }\n }\n var str = '', bs = 16384;\n for (var i = 0; i < j; i += bs) {\n str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));\n }\n return str;\n}\nexport function bytes_to_hex(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var h = (arr[i] & 0xff).toString(16);\n if (h.length < 2)\n str += '0';\n str += h;\n }\n return str;\n}\nexport function bytes_to_base64(arr) {\n return local_btoa(bytes_to_string(arr));\n}\nexport function pow2_ceil(a) {\n a -= 1;\n a |= a >>> 1;\n a |= a >>> 2;\n a |= a >>> 4;\n a |= a >>> 8;\n a |= a >>> 16;\n a += 1;\n return a;\n}\nexport function is_number(a) {\n return typeof a === 'number';\n}\nexport function is_string(a) {\n return typeof a === 'string';\n}\nexport function is_buffer(a) {\n return a instanceof ArrayBuffer;\n}\nexport function is_bytes(a) {\n return a instanceof Uint8Array;\n}\nexport function is_typed_array(a) {\n return (a instanceof Int8Array ||\n a instanceof Uint8Array ||\n a instanceof Int16Array ||\n a instanceof Uint16Array ||\n a instanceof Int32Array ||\n a instanceof Uint32Array ||\n a instanceof Float32Array ||\n a instanceof Float64Array);\n}\nexport function _heap_init(heap, heapSize) {\n const size = heap ? heap.byteLength : heapSize || 65536;\n if (size & 0xfff || size <= 0)\n throw new Error('heap size must be a positive integer and a multiple of 4096');\n heap = heap || new Uint8Array(new ArrayBuffer(size));\n return heap;\n}\nexport function _heap_write(heap, hpos, data, dpos, dlen) {\n const hlen = heap.length - hpos;\n const wlen = hlen < dlen ? hlen : dlen;\n heap.set(data.subarray(dpos, dpos + wlen), hpos);\n return wlen;\n}\nexport function joinBytes(...arg) {\n const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);\n const ret = new Uint8Array(totalLenght);\n let cursor = 0;\n for (let i = 0; i < arg.length; i++) {\n ret.set(arg[i], cursor);\n cursor += arg[i].length;\n }\n return ret;\n}\n","export class IllegalStateError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });\n }\n}\nexport class IllegalArgumentError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });\n }\n}\nexport class SecurityError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'SecurityError' } });\n }\n}\n","import { AES_asm } from './aes.asm';\nimport { _heap_init, _heap_write, is_bytes } from '../other/utils';\nimport { IllegalArgumentError, SecurityError } from '../other/errors';\nconst heap_pool = [];\nconst asm_pool = [];\nexport class AES {\n constructor(key, iv, padding = true, mode, heap, asm) {\n this.pos = 0;\n this.len = 0;\n this.mode = mode;\n // The AES object state\n this.pos = 0;\n this.len = 0;\n this.key = key;\n this.iv = iv;\n this.padding = padding;\n // The AES \"worker\"\n this.acquire_asm(heap, asm);\n }\n acquire_asm(heap, asm) {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);\n this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);\n this.reset(this.key, this.iv);\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n reset(key, iv) {\n const { asm } = this.acquire_asm();\n // Key\n const keylen = key.length;\n if (keylen !== 16 && keylen !== 24 && keylen !== 32)\n throw new IllegalArgumentError('illegal key size');\n const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);\n asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);\n // IV\n if (iv !== undefined) {\n if (iv.length !== 16)\n throw new IllegalArgumentError('illegal iv size');\n let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));\n }\n else {\n asm.set_iv(0, 0, 0, 0);\n }\n }\n AES_Encrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n let result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Encrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let plen = 16 - (len % 16);\n let rlen = len;\n if (this.hasOwnProperty('padding')) {\n if (this.padding) {\n for (let p = 0; p < plen; ++p) {\n heap[pos + len + p] = plen;\n }\n len += plen;\n rlen = len;\n }\n else if (len % 16) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n }\n else {\n len += plen;\n }\n const result = new Uint8Array(rlen);\n if (len)\n asm.cipher(amode, hpos + pos, len);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n AES_Decrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let plen = 0;\n let wlen = 0;\n if (this.padding) {\n plen = len + dlen - rlen || 16;\n rlen -= plen;\n }\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Decrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let rlen = len;\n if (len > 0) {\n if (len % 16) {\n if (this.hasOwnProperty('padding')) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n else {\n len += 16 - (len % 16);\n }\n }\n asm.cipher(amode, hpos + pos, len);\n if (this.hasOwnProperty('padding') && this.padding) {\n let pad = heap[pos + rlen - 1];\n if (pad < 1 || pad > 16 || pad > rlen)\n throw new SecurityError('bad padding');\n let pcheck = 0;\n for (let i = pad; i > 1; i--)\n pcheck |= pad ^ heap[pos + rlen - i];\n if (pcheck)\n throw new SecurityError('bad padding');\n rlen -= pad;\n }\n }\n const result = new Uint8Array(rlen);\n if (rlen > 0) {\n result.set(heap.subarray(pos, pos + rlen));\n }\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_ECB {\n static encrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).encrypt(data);\n }\n static decrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).decrypt(data);\n }\n constructor(key, padding = false, aes) {\n this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';\n\n/**\n * Javascript AES implementation.\n * This is used as fallback if the native Crypto APIs are not available.\n */\nfunction aes(length) {\n const C = function(key) {\n const aesECB = new AES_ECB(key);\n\n this.encrypt = function(block) {\n return aesECB.encrypt(block);\n };\n\n this.decrypt = function(block) {\n return aesECB.decrypt(block);\n };\n };\n\n C.blockSize = C.prototype.blockSize = 16;\n C.keySize = C.prototype.keySize = length / 8;\n\n return C;\n}\n\nexport default aes;\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * @fileoverview Symmetric cryptography functions\n * @module crypto/cipher\n * @private\n */\n\nimport aes from './aes';\nimport { DES, TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TF from './twofish';\nimport BF from './blowfish';\n\n/**\n * AES-128 encryption and decryption (ID 7)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes128 = aes(128);\n/**\n * AES-128 Block Cipher (ID 8)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes192 = aes(192);\n/**\n * AES-128 Block Cipher (ID 9)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes256 = aes(256);\n// Not in OpenPGP specifications\nexport const des = DES;\n/**\n * Triple DES Block Cipher (ID 2)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}\n * @returns {Object}\n */\nexport const tripledes = TripleDES;\n/**\n * CAST-128 Block Cipher (ID 3)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}\n * @returns {Object}\n */\nexport const cast5 = CAST5;\n/**\n * Twofish Block Cipher (ID 10)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}\n * @returns {Object}\n */\nexport const twofish = TF;\n/**\n * Blowfish Block Cipher (ID 4)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}\n * @returns {Object}\n */\nexport const blowfish = BF;\n/**\n * Not implemented\n * @function\n * @throws {Error}\n */\nexport const idea = function() {\n throw new Error('IDEA symmetric-key algorithm not implemented');\n};\n","export var sha1_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,\n w16 = 0, w17 = 0, w18 = 0, w19 = 0,\n w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,\n w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,\n w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,\n w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,\n w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,\n w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n\n // 0\n t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 1\n t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 2\n t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 3\n t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 4\n t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 5\n t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 6\n t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 7\n t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 8\n t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 9\n t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 10\n t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 11\n t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 12\n t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 13\n t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 14\n t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 15\n t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 16\n n = w13 ^ w8 ^ w2 ^ w0;\n w16 = (n << 1) | (n >>> 31);\n t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 17\n n = w14 ^ w9 ^ w3 ^ w1;\n w17 = (n << 1) | (n >>> 31);\n t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 18\n n = w15 ^ w10 ^ w4 ^ w2;\n w18 = (n << 1) | (n >>> 31);\n t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 19\n n = w16 ^ w11 ^ w5 ^ w3;\n w19 = (n << 1) | (n >>> 31);\n t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 20\n n = w17 ^ w12 ^ w6 ^ w4;\n w20 = (n << 1) | (n >>> 31);\n t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 21\n n = w18 ^ w13 ^ w7 ^ w5;\n w21 = (n << 1) | (n >>> 31);\n t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 22\n n = w19 ^ w14 ^ w8 ^ w6;\n w22 = (n << 1) | (n >>> 31);\n t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 23\n n = w20 ^ w15 ^ w9 ^ w7;\n w23 = (n << 1) | (n >>> 31);\n t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 24\n n = w21 ^ w16 ^ w10 ^ w8;\n w24 = (n << 1) | (n >>> 31);\n t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 25\n n = w22 ^ w17 ^ w11 ^ w9;\n w25 = (n << 1) | (n >>> 31);\n t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 26\n n = w23 ^ w18 ^ w12 ^ w10;\n w26 = (n << 1) | (n >>> 31);\n t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 27\n n = w24 ^ w19 ^ w13 ^ w11;\n w27 = (n << 1) | (n >>> 31);\n t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 28\n n = w25 ^ w20 ^ w14 ^ w12;\n w28 = (n << 1) | (n >>> 31);\n t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 29\n n = w26 ^ w21 ^ w15 ^ w13;\n w29 = (n << 1) | (n >>> 31);\n t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 30\n n = w27 ^ w22 ^ w16 ^ w14;\n w30 = (n << 1) | (n >>> 31);\n t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 31\n n = w28 ^ w23 ^ w17 ^ w15;\n w31 = (n << 1) | (n >>> 31);\n t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 32\n n = w29 ^ w24 ^ w18 ^ w16;\n w32 = (n << 1) | (n >>> 31);\n t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 33\n n = w30 ^ w25 ^ w19 ^ w17;\n w33 = (n << 1) | (n >>> 31);\n t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 34\n n = w31 ^ w26 ^ w20 ^ w18;\n w34 = (n << 1) | (n >>> 31);\n t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 35\n n = w32 ^ w27 ^ w21 ^ w19;\n w35 = (n << 1) | (n >>> 31);\n t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 36\n n = w33 ^ w28 ^ w22 ^ w20;\n w36 = (n << 1) | (n >>> 31);\n t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 37\n n = w34 ^ w29 ^ w23 ^ w21;\n w37 = (n << 1) | (n >>> 31);\n t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 38\n n = w35 ^ w30 ^ w24 ^ w22;\n w38 = (n << 1) | (n >>> 31);\n t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 39\n n = w36 ^ w31 ^ w25 ^ w23;\n w39 = (n << 1) | (n >>> 31);\n t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 40\n n = w37 ^ w32 ^ w26 ^ w24;\n w40 = (n << 1) | (n >>> 31);\n t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 41\n n = w38 ^ w33 ^ w27 ^ w25;\n w41 = (n << 1) | (n >>> 31);\n t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 42\n n = w39 ^ w34 ^ w28 ^ w26;\n w42 = (n << 1) | (n >>> 31);\n t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 43\n n = w40 ^ w35 ^ w29 ^ w27;\n w43 = (n << 1) | (n >>> 31);\n t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 44\n n = w41 ^ w36 ^ w30 ^ w28;\n w44 = (n << 1) | (n >>> 31);\n t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 45\n n = w42 ^ w37 ^ w31 ^ w29;\n w45 = (n << 1) | (n >>> 31);\n t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 46\n n = w43 ^ w38 ^ w32 ^ w30;\n w46 = (n << 1) | (n >>> 31);\n t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 47\n n = w44 ^ w39 ^ w33 ^ w31;\n w47 = (n << 1) | (n >>> 31);\n t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 48\n n = w45 ^ w40 ^ w34 ^ w32;\n w48 = (n << 1) | (n >>> 31);\n t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 49\n n = w46 ^ w41 ^ w35 ^ w33;\n w49 = (n << 1) | (n >>> 31);\n t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 50\n n = w47 ^ w42 ^ w36 ^ w34;\n w50 = (n << 1) | (n >>> 31);\n t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 51\n n = w48 ^ w43 ^ w37 ^ w35;\n w51 = (n << 1) | (n >>> 31);\n t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 52\n n = w49 ^ w44 ^ w38 ^ w36;\n w52 = (n << 1) | (n >>> 31);\n t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 53\n n = w50 ^ w45 ^ w39 ^ w37;\n w53 = (n << 1) | (n >>> 31);\n t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 54\n n = w51 ^ w46 ^ w40 ^ w38;\n w54 = (n << 1) | (n >>> 31);\n t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 55\n n = w52 ^ w47 ^ w41 ^ w39;\n w55 = (n << 1) | (n >>> 31);\n t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 56\n n = w53 ^ w48 ^ w42 ^ w40;\n w56 = (n << 1) | (n >>> 31);\n t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 57\n n = w54 ^ w49 ^ w43 ^ w41;\n w57 = (n << 1) | (n >>> 31);\n t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 58\n n = w55 ^ w50 ^ w44 ^ w42;\n w58 = (n << 1) | (n >>> 31);\n t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 59\n n = w56 ^ w51 ^ w45 ^ w43;\n w59 = (n << 1) | (n >>> 31);\n t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 60\n n = w57 ^ w52 ^ w46 ^ w44;\n w60 = (n << 1) | (n >>> 31);\n t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 61\n n = w58 ^ w53 ^ w47 ^ w45;\n w61 = (n << 1) | (n >>> 31);\n t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 62\n n = w59 ^ w54 ^ w48 ^ w46;\n w62 = (n << 1) | (n >>> 31);\n t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 63\n n = w60 ^ w55 ^ w49 ^ w47;\n w63 = (n << 1) | (n >>> 31);\n t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 64\n n = w61 ^ w56 ^ w50 ^ w48;\n w64 = (n << 1) | (n >>> 31);\n t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 65\n n = w62 ^ w57 ^ w51 ^ w49;\n w65 = (n << 1) | (n >>> 31);\n t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 66\n n = w63 ^ w58 ^ w52 ^ w50;\n w66 = (n << 1) | (n >>> 31);\n t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 67\n n = w64 ^ w59 ^ w53 ^ w51;\n w67 = (n << 1) | (n >>> 31);\n t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 68\n n = w65 ^ w60 ^ w54 ^ w52;\n w68 = (n << 1) | (n >>> 31);\n t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 69\n n = w66 ^ w61 ^ w55 ^ w53;\n w69 = (n << 1) | (n >>> 31);\n t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 70\n n = w67 ^ w62 ^ w56 ^ w54;\n w70 = (n << 1) | (n >>> 31);\n t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 71\n n = w68 ^ w63 ^ w57 ^ w55;\n w71 = (n << 1) | (n >>> 31);\n t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 72\n n = w69 ^ w64 ^ w58 ^ w56;\n w72 = (n << 1) | (n >>> 31);\n t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 73\n n = w70 ^ w65 ^ w59 ^ w57;\n w73 = (n << 1) | (n >>> 31);\n t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 74\n n = w71 ^ w66 ^ w60 ^ w58;\n w74 = (n << 1) | (n >>> 31);\n t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 75\n n = w72 ^ w67 ^ w61 ^ w59;\n w75 = (n << 1) | (n >>> 31);\n t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 76\n n = w73 ^ w68 ^ w62 ^ w60;\n w76 = (n << 1) | (n >>> 31);\n t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 77\n n = w74 ^ w69 ^ w63 ^ w61;\n w77 = (n << 1) | (n >>> 31);\n t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 78\n n = w75 ^ w70 ^ w64 ^ w62;\n w78 = (n << 1) | (n >>> 31);\n t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 79\n n = w76 ^ w71 ^ w65 ^ w63;\n w79 = (n << 1) | (n >>> 31);\n t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n }\n\n function reset () {\n H0 = 0x67452301;\n H1 = 0xefcdab89;\n H2 = 0x98badcfe;\n H3 = 0x10325476;\n H4 = 0xc3d2e1f0;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA1\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA1\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA1\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","import { _heap_write } from '../other/utils';\nimport { IllegalStateError } from '../other/errors';\nexport class Hash {\n constructor() {\n this.pos = 0;\n this.len = 0;\n }\n reset() {\n const { asm } = this.acquire_asm();\n this.result = null;\n this.pos = 0;\n this.len = 0;\n asm.reset();\n return this;\n }\n process(data) {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n let hpos = this.pos;\n let hlen = this.len;\n let dpos = 0;\n let dlen = data.length;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);\n hlen += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.process(hpos, hlen);\n hpos += wlen;\n hlen -= wlen;\n if (!hlen)\n hpos = 0;\n }\n this.pos = hpos;\n this.len = hlen;\n return this;\n }\n finish() {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n asm.finish(this.pos, this.len, 0);\n this.result = new Uint8Array(this.HASH_SIZE);\n this.result.set(heap.subarray(0, this.HASH_SIZE));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return this;\n }\n}\n","import { sha1_asm } from './sha1.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha1_block_size = 64;\nexport const _sha1_hash_size = 20;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha1 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha1';\n this.BLOCK_SIZE = _sha1_block_size;\n this.HASH_SIZE = _sha1_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha1().process(data).finish().result;\n }\n}\nSha1.NAME = 'sha1';\nSha1.heap_pool = [];\nSha1.asm_pool = [];\nSha1.asm_function = sha1_asm;\n","import { sha256_asm } from './sha256.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha256_block_size = 64;\nexport const _sha256_hash_size = 32;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha256 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha256';\n this.BLOCK_SIZE = _sha256_block_size;\n this.HASH_SIZE = _sha256_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha256().process(data).finish().result;\n }\n}\nSha256.NAME = 'sha256';\n","export var sha256_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n f = H5;\n g = H6;\n h = H7;\n \n // 0\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 1\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 2\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 3\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 4\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 5\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 6\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 7\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 8\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 9\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 10\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 11\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 12\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 13\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 14\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 15\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 16\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 17\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 18\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 19\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 20\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 21\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 22\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 23\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 24\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 25\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 26\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 27\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 28\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 29\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 30\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 31\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 32\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 33\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 34\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 35\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 36\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 37\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 38\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 39\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 40\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 41\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 42\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 43\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 44\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 45\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 46\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 47\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 48\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 49\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 50\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 51\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 52\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 53\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 54\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 55\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 56\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 57\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 58\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 59\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 60\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 61\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 62\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 63\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n H5 = ( H5 + f )|0;\n H6 = ( H6 + g )|0;\n H7 = ( H7 + h )|0;\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n HEAP[output|20] = H5>>>24;\n HEAP[output|21] = H5>>>16&255;\n HEAP[output|22] = H5>>>8&255;\n HEAP[output|23] = H5&255;\n HEAP[output|24] = H6>>>24;\n HEAP[output|25] = H6>>>16&255;\n HEAP[output|26] = H6>>>8&255;\n HEAP[output|27] = H6&255;\n HEAP[output|28] = H7>>>24;\n HEAP[output|29] = H7>>>16&255;\n HEAP[output|30] = H7>>>8&255;\n HEAP[output|31] = H7&255;\n }\n\n function reset () {\n H0 = 0x6a09e667;\n H1 = 0xbb67ae85;\n H2 = 0x3c6ef372;\n H3 = 0xa54ff53a;\n H4 = 0x510e527f;\n H5 = 0x9b05688c;\n H6 = 0x1f83d9ab;\n H7 = 0x5be0cd19;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n h5 = h5|0;\n h6 = h6|0;\n h7 = h7|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n H5 = I5;\n H6 = I6;\n H7 = I7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n H5 = O5;\n H6 = O6;\n H7 = O7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n O5 = H5;\n O6 = H6;\n O7 = H7;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n I5 = H5;\n I6 = H6;\n I7 = H7;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n h5 = h5 ^ H5;\n h6 = h6 ^ H6;\n h7 = h7 ^ H7;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA256\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA256\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA256\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n * @private\n */\n\nimport { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1';\nimport { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256';\nimport sha224 from 'hash.js/lib/hash/sha/224';\nimport sha384 from 'hash.js/lib/hash/sha/384';\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport { ripemd160 } from 'hash.js/lib/hash/ripemd';\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport defaultConfig from '../../config';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction hashjsHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n }\n const hashInstance = hash();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => new Uint8Array(hashInstance.digest()));\n };\n}\n\nfunction asmcryptoHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hashInstance = new hash();\n return stream.transform(data, value => {\n hashInstance.process(value);\n }, () => hashInstance.finish().result);\n } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n } else {\n return hash.bytes(data);\n }\n };\n}\n\nconst hashFunctions = {\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),\n sha224: nodeHash('sha224') || hashjsHash(sha224),\n sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),\n sha384: nodeHash('sha384') || hashjsHash(sha384, 'SHA-384'),\n sha512: nodeHash('sha512') || hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge.\n ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)\n};\n\nexport default {\n\n /** @see module:md5 */\n md5: hashFunctions.md5,\n /** @see asmCrypto */\n sha1: hashFunctions.sha1,\n /** @see hash.js */\n sha224: hashFunctions.sha224,\n /** @see asmCrypto */\n sha256: hashFunctions.sha256,\n /** @see hash.js */\n sha384: hashFunctions.sha384,\n /** @see asmCrypto */\n sha512: hashFunctions.sha512,\n /** @see hash.js */\n ripemd: hashFunctions.ripemd,\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n default:\n throw new Error('Invalid hash function.');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CFB {\n static encrypt(data, key, iv) {\n return new AES_CFB(key, iv).encrypt(data);\n }\n static decrypt(data, key, iv) {\n return new AES_CFB(key, iv).decrypt(data);\n }\n constructor(key, iv, aes) {\n this.aes = aes ? aes : new AES(key, iv, true, 'CFB');\n delete this.aes.padding;\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import * as cipher from '.';\nimport enums from '../../enums';\n\n/**\n * Get implementation of the given cipher\n * @param {enums.symmetric} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport default function getCipher(algo) {\n const algoName = enums.read(enums.symmetric, algo);\n return cipher[algoName];\n}\n","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n * @private\n */\n\nimport { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb';\nimport * as stream from '@openpgp/web-stream-tools';\nimport getCipher from '../cipher/getCipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nfunction aesEncrypt(algo, key, pt, iv, config) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support\n !util.isStream(pt) &&\n pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2\n ) { // Web Crypto\n return webEncrypt(algo, key, pt, iv);\n }\n // asm.js fallback\n const cfb = new AES_CFB(key, iv);\n return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());\n}\n\nfunction aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new AES_CFB(key, iv);\n return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());\n }\n return AES_CFB.decrypt(ct, key, iv);\n}\n\nfunction xorMut(a, b) {\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nasync function webEncrypt(algo, key, pt, iv) {\n const ALGO = 'AES-CBC';\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);\n const { blockSize } = getCipher(algo);\n const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);\n const ct = new Uint8Array(await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);\n xorMut(ct, pt);\n return ct;\n}\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","import { AES } from './aes';\nimport { IllegalArgumentError } from '../other/errors';\nimport { joinBytes } from '../other/utils';\nexport class AES_CTR {\n static encrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n static decrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n constructor(key, nonce, aes) {\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n delete this.aes.padding;\n this.AES_CTR_set_options(nonce);\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n AES_CTR_set_options(nonce, counter, size) {\n let { asm } = this.aes.acquire_asm();\n if (size !== undefined) {\n if (size < 8 || size > 48)\n throw new IllegalArgumentError('illegal counter size');\n let mask = Math.pow(2, size) - 1;\n asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);\n }\n else {\n size = 48;\n asm.set_mask(0, 0, 0xffff, 0xffffffff);\n }\n if (nonce !== undefined) {\n let len = nonce.length;\n if (!len || len > 16)\n throw new IllegalArgumentError('illegal nonce size');\n let view = new DataView(new ArrayBuffer(16));\n new Uint8Array(view.buffer).set(nonce);\n asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));\n }\n else {\n throw new Error('nonce is required');\n }\n if (counter !== undefined) {\n if (counter < 0 || counter >= Math.pow(2, size))\n throw new IllegalArgumentError('illegal counter value');\n asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);\n }\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CBC {\n static encrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).encrypt(data);\n }\n static decrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).decrypt(data);\n }\n constructor(key, iv, padding = true, aes) {\n this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n * @private\n */\n\nimport { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt) {\n return AES_CBC.encrypt(pt, key, false, zeroBlock);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n * @private\n */\n\nimport { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n ) {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt, iv) {\n return AES_CTR.encrypt(pt, key, iv);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n * @private\n */\n\nimport * as ciphers from '../cipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n\n let maxNtz = 0;\n let encipher;\n let decipher;\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables(cipher, key) {\n const cipherName = enums.read(enums.symmetric, cipher);\n const aes = new ciphers[cipherName](key);\n encipher = aes.encrypt.bind(aes);\n decipher = aes.decrypt.bind(aes);\n\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors';\nimport { _heap_write } from '../other/utils';\nimport { AES } from './aes';\nimport { AES_asm } from './aes.asm';\nconst _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5\nexport class AES_GCM {\n constructor(key, nonce, adata, tagSize = 16, aes) {\n this.tagSize = tagSize;\n this.gamma0 = 0;\n this.counter = 1;\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n let { asm, heap } = this.aes.acquire_asm();\n // Init GCM\n asm.gcm_init();\n // Tag size\n if (this.tagSize < 4 || this.tagSize > 16)\n throw new IllegalArgumentError('illegal tagSize value');\n // Nonce\n const noncelen = nonce.length || 0;\n const noncebuf = new Uint8Array(16);\n if (noncelen !== 12) {\n this._gcm_mac_process(nonce);\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = 0;\n heap[4] = 0;\n heap[5] = 0;\n heap[6] = 0;\n heap[7] = 0;\n heap[8] = 0;\n heap[9] = 0;\n heap[10] = 0;\n heap[11] = noncelen >>> 29;\n heap[12] = (noncelen >>> 21) & 255;\n heap[13] = (noncelen >>> 13) & 255;\n heap[14] = (noncelen >>> 5) & 255;\n heap[15] = (noncelen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_iv(0, 0, 0, 0);\n noncebuf.set(heap.subarray(0, 16));\n }\n else {\n noncebuf.set(nonce);\n noncebuf[15] = 1;\n }\n const nonceview = new DataView(noncebuf.buffer);\n this.gamma0 = nonceview.getUint32(12);\n asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);\n asm.set_mask(0, 0, 0, 0xffffffff);\n // Associated data\n if (adata !== undefined) {\n if (adata.length > _AES_GCM_data_maxLength)\n throw new IllegalArgumentError('illegal adata length');\n if (adata.length) {\n this.adata = adata;\n this._gcm_mac_process(adata);\n }\n else {\n this.adata = undefined;\n }\n }\n else {\n this.adata = undefined;\n }\n // Counter\n if (this.counter < 1 || this.counter > 0xffffffff)\n throw new RangeError('counter must be a positive 32-bit integer');\n asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);\n }\n static encrypt(cleartext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);\n }\n static decrypt(ciphertext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);\n }\n encrypt(data) {\n return this.AES_GCM_encrypt(data);\n }\n decrypt(data) {\n return this.AES_GCM_decrypt(data);\n }\n AES_GCM_Encrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Encrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let adata = this.adata;\n let pos = this.aes.pos;\n let len = this.aes.len;\n const result = new Uint8Array(len + tagSize);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);\n if (len)\n result.set(heap.subarray(pos, pos + len));\n let i = len;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n result.set(heap.subarray(0, tagSize), len);\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_Decrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;\n let tlen = len + dlen - rlen;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > tlen) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n pos = 0;\n len = 0;\n }\n if (dlen > 0) {\n len += _heap_write(heap, 0, data, dpos, dlen);\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Decrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let tagSize = this.tagSize;\n let adata = this.adata;\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rlen = len - tagSize;\n if (len < tagSize)\n throw new IllegalStateError('authentication tag not found');\n const result = new Uint8Array(rlen);\n const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));\n let i = rlen;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len - tagSize;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n let acheck = 0;\n for (let i = 0; i < tagSize; ++i)\n acheck |= atag[i] ^ heap[i];\n if (acheck)\n throw new SecurityError('data integrity check failed');\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_decrypt(data) {\n const result1 = this.AES_GCM_Decrypt_process(data);\n const result2 = this.AES_GCM_Decrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n AES_GCM_encrypt(data) {\n const result1 = this.AES_GCM_Encrypt_process(data);\n const result2 = this.AES_GCM_Encrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n _gcm_mac_process(data) {\n let { asm, heap } = this.aes.acquire_asm();\n let dpos = 0;\n let dlen = data.length || 0;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, 0, data, dpos, dlen);\n dpos += wlen;\n dlen -= wlen;\n while (wlen & 15)\n heap[wlen++] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);\n }\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n * @private\n */\n\nimport { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.encrypt(pt, key, iv, adata);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (ct.length === tagLength) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n }\n };\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return AES_GCM.encrypt(pt, key, iv, adata);\n },\n\n decrypt: async function(ct, iv, adata) {\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n * @private\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","/*jshint bitwise: false*/\n\n(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d;\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d, h, r;\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n r = nacl.hash(sm.subarray(32, smlen));\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n h = nacl.hash(sm.subarray(0, smlen));\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h;\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n h = nacl.hash(m.subarray(0, n));\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n * @private\n */\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const buf = new Uint8Array(length);\n if (nodeCrypto) {\n const bytes = nodeCrypto.randomBytes(buf.length);\n buf.set(bytes);\n } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n return buf;\n}\n\n/**\n * Create a secure random BigInteger that is greater than or equal to min and less than max.\n * @param {module:BigInteger} min - Lower bound, included\n * @param {module:BigInteger} max - Upper bound, excluded\n * @returns {Promise} Random BigInteger.\n * @async\n */\nexport async function getRandomBigInteger(min, max) {\n const BigInteger = await util.getBigInteger();\n\n if (max.lt(min)) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max.sub(min);\n const bytes = modulus.byteLength();\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = new BigInteger(await getRandomBytes(bytes + 8));\n return r.mod(modulus).add(min);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\n\n/**\n * Generate a probably prime random number\n * @param {Integer} bits - Bit length of the prime\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns BigInteger\n * @async\n */\nexport async function randomProbablePrime(bits, e, k) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n const min = one.leftShift(new BigInteger(bits - 1));\n const thirty = new BigInteger(30);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n const n = await getRandomBigInteger(min, min.leftShift(one));\n let i = n.mod(thirty).toNumber();\n\n do {\n n.iadd(new BigInteger(adds[i]));\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (n.bitLength() > bits) {\n n.imod(min.leftShift(one)).iadd(min);\n i = n.mod(thirty).toNumber();\n }\n } while (!await isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns {boolean}\n * @async\n */\nexport async function isProbablePrime(n, e, k) {\n if (e && !n.dec().gcd(e).isOne()) {\n return false;\n }\n if (!await divisionTest(n)) {\n return false;\n }\n if (!await fermat(n)) {\n return false;\n }\n if (!await millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} b - Optional Fermat test base\n * @returns {boolean}\n */\nexport async function fermat(n, b) {\n const BigInteger = await util.getBigInteger();\n b = b || new BigInteger(2);\n return b.modExp(n.dec(), n).isOne();\n}\n\nexport async function divisionTest(n) {\n const BigInteger = await util.getBigInteger();\n return smallPrimes.every(m => {\n return n.mod(new BigInteger(m)) !== 0;\n });\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n];\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param {BigInteger} n - Number to test\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @param {Function} rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport async function millerRabin(n, k, rand) {\n const BigInteger = await util.getBigInteger();\n const len = n.bitLength();\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n.dec(); // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!n1.getBit(s)) { s++; }\n const d = n.rightShift(new BigInteger(s));\n\n for (; k > 0; k--) {\n const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);\n\n let x = a.modExp(d, n);\n if (x.isOne() || x.equal(n1)) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = x.mul(x).mod(n);\n\n if (x.isOne()) {\n return false;\n }\n if (x.equal(n1)) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n * @private\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport async function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n * @private\n */\n\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\n/* eslint-disable no-invalid-this */\nconst RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('version').int(), // 0\n this.key('modulus').int(), // n\n this.key('publicExponent').int(), // e\n this.key('privateExponent').int(), // d\n this.key('prime1').int(), // p\n this.key('prime2').int(), // q\n this.key('exponent1').int(), // dp\n this.key('exponent2').int(), // dq\n this.key('coefficient').int() // u\n );\n}) : undefined;\n\nconst RSAPublicKey = nodeCrypto ? asn1.define('RSAPubliceKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('modulus').int(), // n\n this.key('publicExponent').int() // e\n );\n}) : undefined;\n/* eslint-enable no-invalid-this */\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n const BigInteger = await util.getBigInteger();\n\n e = new BigInteger(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return {\n n: b64ToUint8Array(jwk.n),\n e: e.toUint8Array(),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {\n const opts = {\n modulusLength: bits,\n publicExponent: e.toNumber(),\n publicKeyEncoding: { type: 'pkcs1', format: 'der' },\n privateKeyEncoding: { type: 'pkcs1', format: 'der' }\n };\n const prv = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {\n if (err) {\n reject(err);\n } else {\n resolve(RSAPrivateKey.decode(der, 'der'));\n }\n });\n });\n /**\n * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.\n * @link https://tools.ietf.org/html/rfc3447#section-3.2\n * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1\n */\n return {\n n: prv.modulus.toArrayLike(Uint8Array),\n e: prv.publicExponent.toArrayLike(Uint8Array),\n d: prv.privateExponent.toArrayLike(Uint8Array),\n // switch p and q\n p: prv.prime2.toArrayLike(Uint8Array),\n q: prv.prime1.toArrayLike(Uint8Array),\n // Since p and q are switched in places, we can keep u as defined by DER\n u: prv.coefficient.toArrayLike(Uint8Array)\n };\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = await randomProbablePrime(bits - (bits >> 1), e, 40);\n p = await randomProbablePrime(bits >> 1, e, 40);\n n = p.mul(q);\n } while (n.bitLength() !== bits);\n\n const phi = p.dec().imul(q.dec());\n\n if (q.lt(p)) {\n [p, q] = [q, p];\n }\n\n return {\n n: n.toUint8Array(),\n e: e.toUint8Array(),\n d: e.modInv(phi).toUint8Array(),\n p: p.toUint8Array(),\n q: q.toUint8Array(),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: p.modInv(q).toUint8Array()\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n p = new BigInteger(p);\n q = new BigInteger(q);\n\n // expect pq = n\n if (!p.mul(q).equal(n)) {\n return false;\n }\n\n const two = new BigInteger(2);\n // expect p*u = 1 mod q\n u = new BigInteger(u);\n if (!p.mul(u).mod(q).isOne()) {\n return false;\n }\n\n e = new BigInteger(e);\n d = new BigInteger(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));\n const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r.mul(d).mul(e);\n\n const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));\n d = new BigInteger(d);\n if (m.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return m.modExp(d, n).toUint8Array('be', n.byteLength());\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPrivateKey.encode(keyObject, 'der');\n return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));\n }\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n return new Uint8Array(sign.sign(pem));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n s = new BigInteger(s);\n e = new BigInteger(e);\n if (s.gte(n)) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());\n const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1' };\n } else {\n key = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n }\n try {\n return await verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const { default: BN } = await import('bn.js');\n\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n data = new BigInteger(emeEncode(data, n.byteLength()));\n e = new BigInteger(e);\n if (data.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return data.modExp(e, n).toUint8Array('be', n.byteLength());\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPrivateKey.encode(keyObject, 'der');\n key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n const BigInteger = await util.getBigInteger();\n data = new BigInteger(data);\n n = new BigInteger(n);\n e = new BigInteger(e);\n d = new BigInteger(d);\n p = new BigInteger(p);\n q = new BigInteger(q);\n u = new BigInteger(u);\n if (data.gte(n)) {\n throw new Error('Data too large.');\n }\n const dq = d.mod(q.dec()); // d mod (q-1)\n const dp = d.mod(p.dec()); // d mod (p-1)\n\n const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);\n const blinder = unblinder.modInv(n).modExp(e, n);\n data = data.mul(blinder).mod(n);\n\n\n const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p\n const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q\n const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h.mul(p).add(mp); // result < n due to relations above\n\n result = result.mul(unblinder).mod(n);\n\n\n return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n const pNum = new BigInteger(p);\n const qNum = new BigInteger(q);\n const dNum = new BigInteger(d);\n\n let dq = dNum.mod(qNum.dec()); // d mod (q-1)\n let dp = dNum.mod(pNum.dec()); // d mod (p-1)\n dp = dp.toUint8Array();\n dq = dq.toUint8Array();\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const padded = emeEncode(data, p.byteLength());\n const m = new BigInteger(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = await getRandomBigInteger(new BigInteger(1), p.dec());\n return {\n c1: g.modExp(k, p).toUint8Array(),\n c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n const BigInteger = await util.getBigInteger();\n c1 = new BigInteger(c1);\n c2 = new BigInteger(c2);\n p = new BigInteger(p);\n x = new BigInteger(x);\n\n const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);\n return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = new BigInteger(p.bitLength());\n const n1023 = new BigInteger(1023);\n if (pSize.lt(n1023)) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (!g.modExp(p.dec(), p).isOne()) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n const i = new BigInteger(1);\n const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold\n while (i.lt(threshold)) {\n res = res.mul(g).imod(p);\n if (res.isOne()) {\n return false;\n }\n i.iinc();\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1\n const rqx = p.dec().imul(r).iadd(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n * @private\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {string} String with the canonical name of the curve.\n */\n getName() {\n const hex = this.toHex();\n if (enums.curve[hex]) {\n return enums.write(enums.curve, hex);\n } else {\n throw new Error('Unknown curve object identifier.');\n }\n }\n}\n\nexport default OID;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library\n * @module crypto/public_key/elliptic/indutnyKey\n * @private\n */\n\nimport config from '../../../config';\n\nexport function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}\n\nexport function keyFromPublic(indutnyCurve, pub) {\n const keyPair = indutnyCurve.keyPair({ pub: pub });\n if (keyPair.validate().result !== true) {\n throw new Error('Invalid elliptic public key');\n }\n return keyPair;\n}\n\nexport async function getIndutnyCurve(name) {\n if (!config.useIndutnyElliptic) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n const { default: elliptic } = await import('@openpgp/elliptic');\n return new elliptic.ec(name);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new stream.TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { getRandomBytes } from '../../random';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport { UnsupportedError } from '../../../packet/packet';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n 'p256': 'P-256',\n 'p384': 'P-384',\n 'p521': 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,\n brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n p256: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.p256,\n web: webCurves.p256,\n payloadSize: 32,\n sharedSize: 256\n },\n p384: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.p384,\n web: webCurves.p384,\n payloadSize: 48,\n sharedSize: 384\n },\n p521: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.p521,\n web: webCurves.p521,\n payloadSize: 66,\n sharedSize: 528\n },\n secp256k1: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.secp256k1,\n payloadSize: 32\n },\n ed25519: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32\n },\n curve25519: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32\n },\n brainpoolP256r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.brainpoolP256r1,\n payloadSize: 32\n },\n brainpoolP384r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.brainpoolP384r1,\n payloadSize: 48\n },\n brainpoolP512r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.brainpoolP512r1,\n payloadSize: 64\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName, params) {\n try {\n if (util.isArray(oidOrName) ||\n util.isUint8Array(oidOrName)) {\n // by oid byte array\n oidOrName = new OID(oidOrName);\n }\n if (oidOrName instanceof OID) {\n // by curve OID\n oidOrName = oidOrName.getName();\n }\n // by curve name or oid string\n this.name = enums.write(enums.curve, oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n params = params || curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node && curves[this.name];\n this.web = params.web && curves[this.name];\n this.payloadSize = params.payloadSize;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === 'curve25519') {\n this.type = 'curve25519';\n } else if (this.name === 'ed25519') {\n this.type = 'ed25519';\n }\n }\n\n async genKeyPair() {\n let keyPair;\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n break;\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519': {\n const privateKey = getRandomBytes(32);\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const secretKey = privateKey.slice().reverse();\n keyPair = nacl.box.keyPair.fromSecretKey(secretKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n case 'ed25519': {\n const privateKey = getRandomBytes(32);\n const keyPair = nacl.sign.keyPair.fromSeed(privateKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n }\n const indutnyCurve = await getIndutnyCurve(this.name);\n keyPair = await indutnyCurve.genKeyPair({\n entropy: util.uint8ArrayToString(getRandomBytes(32))\n });\n return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };\n }\n}\n\nasync function generate(curve) {\n const BigInteger = await util.getBigInteger();\n\n curve = new CurveWithOID(curve);\n const keyPair = await curve.genKeyPair();\n const Q = new BigInteger(keyPair.publicKey).toUint8Array();\n const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);\n return {\n oid: curve.oid,\n Q,\n secret,\n hash: curve.hash,\n cipher: curve.cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[enums.write(enums.curve, oid.toHex())].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n p256: true,\n p384: true,\n p521: true,\n secp256k1: true,\n curve25519: algo === enums.publicKey.ecdh,\n brainpoolP256r1: true,\n brainpoolP384r1: true,\n brainpoolP512r1: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === 'curve25519') {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const curve = await getIndutnyCurve(curveName);\n try {\n // Parse Q and check that it is on the curve but not at infinity\n Q = keyFromPublic(curve, Q).getPublic();\n } catch (validationErrors) {\n return false;\n }\n\n /**\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = keyFromPrivate(curve, d).getPublic();\n if (!dG.eq(Q)) {\n return false;\n }\n\n return true;\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nasync function webGenKeyPair(name) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = 0x04;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n * @private\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './oid_curves';\nimport { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web': {\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n }\n case 'node': {\n const signature = await nodeSign(curve, hashAlgo, message, keyPair);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n }\n }\n }\n return ellipticSign(curve, hashed, privateKey);\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n return await webVerify(curve, hashAlgo, signature, message, publicKey);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node':\n return nodeVerify(curve, hashAlgo, signature, message, publicKey);\n }\n }\n const digest = (typeof hashAlgo === 'undefined') ? message : hashed;\n return ellipticVerify(curve, signature, digest, publicKey);\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\nasync function ellipticSign(curve, hashed, privateKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPrivate(indutnyCurve, privateKey);\n const signature = key.sign(hashed);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n}\n\nasync function ellipticVerify(curve, signature, digest, publicKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPublic(indutnyCurve, publicKey);\n return key.verify(digest, signature);\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, keyPair) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n const key = ECPrivateKey.encode({\n version: 1,\n parameters: curve.oid,\n privateKey: Array.from(keyPair.privateKey),\n publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }\n }, 'pem', {\n label: 'EC PRIVATE KEY'\n });\n\n return ECDSASignature.decode(sign.sign(key), 'der');\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n const key = SubjectPublicKeyInfo.encode({\n algorithm: {\n algorithm: [1, 2, 840, 10045, 2, 1],\n parameters: curve.oid\n },\n subjectPublicKey: { unused: 0, data: Array.from(publicKey) }\n }, 'pem', {\n label: 'PUBLIC KEY'\n });\n const signature = ECDSASignature.encode({\n r: new BN(r), s: new BN(s)\n }, 'der');\n\n try {\n return verify.verify(key, signature);\n } catch (err) {\n return false;\n }\n}\n\n// Originally written by Owen Smith https://github.com/omsmith\n// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/\n\n/* eslint-disable no-invalid-this */\n\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\nconst ECDSASignature = nodeCrypto ?\n asn1.define('ECDSASignature', function() {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n );\n }) : undefined;\n\nconst ECPrivateKey = nodeCrypto ?\n asn1.define('ECPrivateKey', function() {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').explicit(0).optional().any(),\n this.key('publicKey').explicit(1).optional().bitstr()\n );\n }) : undefined;\n\nconst AlgorithmIdentifier = nodeCrypto ?\n asn1.define('AlgorithmIdentifier', function() {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional().any()\n );\n }) : undefined;\n\nconst SubjectPublicKeyInfo = nodeCrypto ?\n asn1.define('SubjectPublicKeyInfo', function() {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n );\n }) : undefined;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);\n const signature = nacl.sign.detached(hashed, secretKey);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const signature = util.concatUint8Array([r, s]);\n return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1));\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== 'ed25519') {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const seed = getRandomBytes(32);\n const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = nacl.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n return nacl.sign.detached.verify(hashed, RS, publicKey);\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: // unsupported\n default:\n return false;\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n * @private\n */\n\nimport * as cipher from './cipher';\nimport util from '../util';\n\n/**\n * AES key wrap\n * @function\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nexport function wrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const P = unpack(data);\n let A = IV;\n const R = P;\n const n = P.length / 2;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 0; j <= 5; ++j) {\n for (let i = 0; i < n; ++i) {\n t[1] = n * j + (1 + i);\n // B = A\n B[0] = A[0];\n B[1] = A[1];\n // B = A || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES(K, B)\n B = unpack(aes.encrypt(pack(B)));\n // A = MSB(64, B) ^ t\n A = B.subarray(0, 2);\n A[0] ^= t[0];\n A[1] ^= t[1];\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n return pack(A, R);\n}\n\n/**\n * AES key unwrap\n * @function\n * @param {String} key\n * @param {String} data\n * @returns {Uint8Array}\n * @throws {Error}\n */\nexport function unwrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const C = unpack(data);\n let A = C.subarray(0, 2);\n const R = C.subarray(2);\n const n = C.length / 2 - 1;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 5; j >= 0; --j) {\n for (let i = n - 1; i >= 0; --i) {\n t[1] = n * j + (i + 1);\n // B = A ^ t\n B[0] = A[0] ^ t[0];\n B[1] = A[1] ^ t[1];\n // B = (A ^ t) || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES-1(B)\n B = unpack(aes.decrypt(pack(B)));\n // A = MSB(64, B)\n A = B.subarray(0, 2);\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n if (A[0] === IV[0] && A[1] === IV[1]) {\n return pack(R);\n }\n throw new Error('Key Data Integrity failed');\n}\n\nfunction createArrayBuffer(data) {\n if (util.isString(data)) {\n const { length } = data;\n const buffer = new ArrayBuffer(length);\n const view = new Uint8Array(buffer);\n for (let j = 0; j < length; ++j) {\n view[j] = data.charCodeAt(j);\n }\n return buffer;\n }\n return new Uint8Array(data).buffer;\n}\n\nfunction unpack(data) {\n const { length } = data;\n const buffer = createArrayBuffer(data);\n const view = new DataView(buffer);\n const arr = new Uint32Array(length / 4);\n for (let i = 0; i < length / 4; ++i) {\n arr[i] = view.getUint32(4 * i);\n }\n return arr;\n}\n\nfunction pack() {\n let length = 0;\n for (let k = 0; k < arguments.length; ++k) {\n length += 4 * arguments[k].length;\n }\n const buffer = new ArrayBuffer(length);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < arguments.length; ++i) {\n for (let j = 0; j < arguments[i].length; ++j) {\n view.setUint32(offset + 4 * j, arguments[i][j]);\n }\n offset += 4 * arguments[i].length;\n }\n return new Uint8Array(buffer);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport getCipher from '../../cipher/getCipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint.subarray(0, 20)\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519': {\n const d = getRandomBytes(32);\n const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);\n let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);\n publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n }\n return ellipticPublicEphemeralKey(curve, Q);\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = aesKW.wrap(Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519': {\n const secretKey = d.slice().reverse();\n const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n }\n return ellipticPrivateEphemeralKey(curve, V, d);\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(aesKW.unwrap(Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: sender\n },\n privateKey,\n curve.web.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.web.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPrivateEphemeralKey(curve, V, d) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n V = keyFromPublic(indutnyCurve, V);\n d = keyFromPrivate(indutnyCurve, d);\n const secretKey = new Uint8Array(d.getPrivate());\n const S = d.derive(V.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPublicEphemeralKey(curve, Q) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const v = await curve.genKeyPair();\n Q = keyFromPublic(indutnyCurve, Q);\n const V = keyFromPrivate(indutnyCurve, v.privateKey);\n const publicKey = v.publicKey;\n const S = V.derive(Q.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeSubtleCrypto = nodeCrypto && nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle;\n\nexport default async function HKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n if (webCrypto || nodeSubtleCrypto) {\n const crypto = webCrypto || nodeSubtleCrypto;\n const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n }\n\n if (nodeCrypto) {\n const hashAlgoName = enums.read(enums.hash, hashAlgo);\n // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869\n\n const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();\n // Step 1: Extract\n // PRK = HMAC-Hash(salt, IKM)\n const pseudoRandomKey = computeHMAC(salt, inputKey);\n\n const hashLen = pseudoRandomKey.length;\n\n // Step 2: Expand\n // HKDF-Expand(PRK, info, L) -> OKM\n const n = Math.ceil(outLen / hashLen);\n const outputKeyingMaterial = new Uint8Array(n * hashLen);\n\n // HMAC input buffer updated at each iteration\n const roundInput = new Uint8Array(hashLen + info.length + 1);\n // T_i and last byte are updated at each iteration, but `info` remains constant\n roundInput.set(info, hashLen);\n\n for (let i = 0; i < n; i++) {\n // T(0) = empty string (zero length)\n // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)\n roundInput[roundInput.length - 1] = i + 1;\n // t = T(i+1)\n const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));\n roundInput.set(t, 0);\n\n outputKeyingMaterial.set(t, i * hashLen);\n }\n\n return outputKeyingMaterial.subarray(0, outLen);\n }\n\n throw new Error('No HKDF implementation available');\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport getCipher from '../../cipher/getCipher';\nimport computeHKDF from '../../hkdf';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(32);\n const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA);\n const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = aesKW.wrap(encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n * @private\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n x = new BigInteger(x);\n\n let k;\n let r;\n let s;\n let t;\n g = g.mod(p);\n x = x.mod(q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = await getRandomBigInteger(one, q); // returns in [1, q-1]\n r = g.modExp(k, p).imod(q); // (g**k mod p) mod q\n if (r.isZero()) {\n continue;\n }\n const xr = x.mul(r).imod(q);\n t = h.add(xr).imod(q); // H(m) + x*r mod q\n s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q\n if (s.isZero()) {\n continue;\n }\n break;\n }\n return {\n r: r.toUint8Array('be', q.byteLength()),\n s: s.toUint8Array('be', q.byteLength())\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n const BigInteger = await util.getBigInteger();\n const zero = new BigInteger(0);\n r = new BigInteger(r);\n s = new BigInteger(s);\n\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n if (r.lte(zero) || r.gte(q) ||\n s.lte(zero) || s.gte(q)) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);\n const w = s.modInv(q); // s**-1 mod q\n if (w.isZero()) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = g.mod(p);\n y = y.mod(p);\n const u1 = h.mul(w).imod(q); // H(m) * w mod q\n const u2 = r.mul(w).imod(q); // r * w mod q\n const t1 = g.modExp(u1, p); // g**u1 mod p\n const t2 = y.modExp(u2, p); // y**u2 mod p\n const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q\n return v.equal(r);\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (!p.dec().mod(q).isZero()) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (!g.modExp(q, p).isOne()) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = new BigInteger(q.bitLength());\n const n150 = new BigInteger(150);\n if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q\n const rqx = q.mul(r).add(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa,\n /** @see tweetnacl */\n nacl: nacl\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n * @private\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read));\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { s };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read));\n return { r, s };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n let r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n r = util.leftPad(r, 32);\n let s = util.readMPI(signature.subarray(read));\n s = util.leftPad(s, 32);\n return { r, s };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n case enums.publicKey.ed25519: {\n const RS = signature.subarray(read, read + 64); read += RS.length;\n return { RS };\n }\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n // signature already padded on parsing\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal: {\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n * @private\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n * @private\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport getCipher from './cipher/getCipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { CurveWithOID } from './public_key/elliptic/oid_curves';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519: {\n if (!util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (!util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.x25519: {\n const A = bytes.subarray(read, read + 32); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const curve = new CurveWithOID(publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, curve.payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const curve = new CurveWithOID(publicParams.oid);\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, curve.payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519: {\n const seed = bytes.subarray(read, read + 32); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519: {\n const k = bytes.subarray(read, read + 32); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key.\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519: {\n const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n }\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipher(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipher(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\nexport { getCipher };\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get preferred hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n * @private\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","\n\n\nvar TYPED_OK = typeof Uint8Array !== \"undefined\" &&\n typeof Uint16Array !== \"undefined\" &&\n typeof Int32Array !== \"undefined\";\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function assign(obj /*...args obj, from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue; \n }\n\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n //return Object.assign(...args);\n}\n\n\n// reduce buffer size, avoiding mem copy\nexport function shrinkBuf(buf, size) {\n if (buf.length === size) {\n return buf; \n }\n if (buf.subarray) {\n return buf.subarray(0, size); \n }\n buf.length = size;\n return buf;\n}\n\n\nconst fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n let i, l, len, pos, chunk;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nconst fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\n\nexport let Buf8 = TYPED_OK ? Uint8Array : Array;\nexport let Buf16 = TYPED_OK ? Uint16Array : Array;\nexport let Buf32 = TYPED_OK ? Int32Array : Array;\nexport let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;\nexport let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;\nexport function setTyped(on) {\n if (on) {\n Buf8 = Uint8Array;\n Buf16 = Uint16Array;\n Buf32 = Int32Array;\n ({ flattenChunks, arraySet } = fnTyped);\n } else {\n Buf8 = Array;\n Buf16 = Array;\n Buf32 = Array;\n ({ flattenChunks, arraySet } = fnUntyped);\n }\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nexport const Z_NO_FLUSH = 0;\nexport const Z_PARTIAL_FLUSH = 1;\nexport const Z_SYNC_FLUSH = 2;\nexport const Z_FULL_FLUSH = 3;\nexport const Z_FINISH = 4;\nexport const Z_BLOCK = 5;\nexport const Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nexport const Z_OK = 0;\nexport const Z_STREAM_END = 1;\nexport const Z_NEED_DICT = 2;\nexport const Z_ERRNO = -1;\nexport const Z_STREAM_ERROR = -2;\nexport const Z_DATA_ERROR = -3;\n//export const Z_MEM_ERROR = -4;\nexport const Z_BUF_ERROR = -5;\n//export const Z_VERSION_ERROR = -6;\n\n /* compression levels */\nexport const Z_NO_COMPRESSION = 0;\nexport const Z_BEST_SPEED = 1;\nexport const Z_BEST_COMPRESSION = 9;\nexport const Z_DEFAULT_COMPRESSION = -1;\n\n\nexport const Z_FILTERED = 1;\nexport const Z_HUFFMAN_ONLY = 2;\nexport const Z_RLE = 3;\nexport const Z_FIXED = 4;\nexport const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nexport const Z_BINARY = 0;\nexport const Z_TEXT = 1;\n//export const Z_ASCII = 1; // = Z_TEXT (deprecated)\nexport const Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nexport const Z_DEFLATED = 8;\n//export const Z_NULL = null // Use -1 or null inline, depending on var type\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nimport * as utils from \"../utils/common.js\";\nimport {\n Z_FIXED,\n Z_BINARY,\n Z_TEXT,\n Z_UNKNOWN\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nfunction zero(buf) {\n let len = buf.length; while (--len >= 0) {\n buf[len] = 0; \n } \n}\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nconst extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nconst extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nconst bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = w & 0xff;\n s.pending_buf[s.pending++] = w >>> 8 & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) {\n continue; \n } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) {\n return; \n }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--; \n }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue; \n }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2]/*.Freq*/ = 0; \n }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n // while (len--) {\n // put_byte(s, *buf++);\n // }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n const _n2 = n * 2;\n const _m2 = m * 2;\n return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break; \n }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {\n pqdownheap(s, tree, n); \n }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]/*.Freq*/++; \n }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree); \n } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb; \n }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n\n //#ifdef TRUNCATE_BLOCK\n // /* Try to guess if it is profitable to stop the current block here */\n // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n // /* Compute an upper bound for the compressed length */\n // out_length = s.last_lit*8;\n // in_length = s.strstart - s.block_start;\n //\n // for (dcode = 0; dcode < D_CODES; dcode++) {\n // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n // }\n // out_length >>>= 3;\n // //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n // // s->last_lit, in_length, out_length,\n // // 100L - out_length*100L/in_length));\n // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n // return true;\n // }\n // }\n //#endif\n\n return s.last_lit === s.lit_bufsize - 1;\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexport {\n _tr_init,\n _tr_stored_block,\n _tr_flush_block,\n _tr_tally,\n _tr_align\n};","\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default function adler32(adler, buf, len, pos) {\n let s1 = adler & 0xffff |0,\n s2 = adler >>> 16 & 0xffff |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = s1 + buf[pos++] |0;\n s2 = s2 + s1 |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return s1 | s2 << 16 |0;\n}\n","\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n let c;\n const table = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = makeTable();\n\n\nexport default function crc32(crc, buf, len, pos) {\n const t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return crc ^ -1; // >>> 0;\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default {\n 2: \"need dictionary\", /* Z_NEED_DICT 2 */\n 1: \"stream end\", /* Z_STREAM_END 1 */\n 0: \"\", /* Z_OK 0 */\n \"-1\": \"file error\", /* Z_ERRNO (-1) */\n \"-2\": \"stream error\", /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\", /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\", /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\", /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\" /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport * as trees from \"./trees.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport msg from \"./messages.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_NO_FLUSH,\n Z_PARTIAL_FLUSH,\n Z_FULL_FLUSH,\n Z_FINISH,\n Z_BLOCK,\n Z_OK,\n Z_STREAM_END,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED,\n Z_HUFFMAN_ONLY,\n Z_RLE,\n Z_FIXED,\n Z_DEFAULT_STRATEGY,\n Z_UNKNOWN,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n // put_byte(s, (Byte)(b >> 8));\n // put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n //#if MIN_MATCH != 3\n // Call update_hash() MIN_MATCH-3 more times\n //#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n // if (s.high_water < s.window_size) {\n // var curr = s.strstart + s.lookahead;\n // var init = 0;\n //\n // if (s.high_water < curr) {\n // /* Previous high water mark below current data -- zero WIN_INIT\n // * bytes or up to end of window, whichever is less.\n // */\n // init = s.window_size - curr;\n // if (init > WIN_INIT)\n // init = WIN_INIT;\n // zmemzero(s->window + curr, (unsigned)init);\n // s->high_water = curr + init;\n // }\n // else if (s->high_water < (ulg)curr + WIN_INIT) {\n // /* High water mark at or above current data, but below current data\n // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n // * to end of window, whichever is less.\n // */\n // init = (ulg)curr + WIN_INIT - s->high_water;\n // if (init > s->window_size - s->high_water)\n // init = s->window_size - s->high_water;\n // zmemzero(s->window + s->high_water, (unsigned)init);\n // s->high_water += init;\n // }\n // }\n //\n // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n // \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (; ;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n // s.block_start >= s.w_size)) {\n // throw new Error(\"slide too late\");\n // }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n // if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n //#if MIN_MATCH != 3\n // Call UPDATE_HASH() MIN_MATCH-3 more times\n //#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nclass Config {\n constructor(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n};\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\nclass DeflateState {\n constructor() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n }\n}\n\nfunction deflateResetKeep(strm) {\n let s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n let old_flush, s;\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n //#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n //#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n let status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n let dictLength = dictionary.length;\n\n let s;\n let str, n;\n let wrap;\n let avail;\n let next;\n let input;\n let tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\nconst deflateInfo = 'pako deflate (from Nodeca project)';\nexport {\n deflateInit,\n deflateInit2,\n deflateReset,\n deflateResetKeep,\n deflateSetHeader,\n deflate,\n deflateEnd,\n deflateSetDictionary,\n deflateInfo\n};\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n\n\n\nimport * as utils from \"./common.js\";\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_OK = true;\nlet STR_APPLY_UIA_OK = true;\n\ntry {\n String.fromCharCode.apply(null, [ 0 ]); \n} catch (__) {\n STR_APPLY_OK = false; \n}\ntry {\n String.fromCharCode.apply(null, new Uint8Array(1)); \n} catch (__) {\n STR_APPLY_UIA_OK = false; \n}\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new utils.Buf8(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexport function string2buf (str) {\n let c, c2, m_pos, i, buf_len = 0;\n const str_len = str.length;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n const buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | c >>> 6;\n buf[i++] = 0x80 | c & 0x3f;\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | c >>> 12;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | c >>> 18;\n buf[i++] = 0x80 | c >>> 12 & 0x3f;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n let result = \"\";\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexport function buf2binstring (buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nexport function binstring2buf (str) {\n const buf = new utils.Buf8(str.length);\n for (let i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nexport function buf2string (buf, max) {\n let i, out, c, c_len;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n // var utf16buf = new Array(len * 2);\n // try Uint16Array\n const utf16buf = new Uint16Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) {\n utf16buf[out++] = c; continue; \n }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) {\n utf16buf[out++] = 0xfffd; i += c_len - 1; continue; \n }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 0x3f;\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) {\n utf16buf[out++] = 0xfffd; continue; \n }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;\n utf16buf[out++] = 0xdc00 | c & 0x3ff;\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexport function utf8border (buf, max) {\n let pos;\n\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length; \n }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {\n pos--; \n }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) {\n return max; \n }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) {\n return max; \n }\n\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class ZStream {\n constructor() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n }\n}","'use strict';\n\nimport * as zlib_deflate from \"./zlib/deflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\nimport { Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED } from \"./zlib/constants.js\"\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\n\nclass Deflate {\n constructor(options) {\n this.options = {\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n ...(options || {})\n };\n\n const opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n }\n\n /**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize } } = this;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n /**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n /**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw new Error(deflator.msg || msg[deflator.err]); }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\nexport { Deflate, deflate, deflateRaw, gzip };\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nexport default function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let _out; /* local strm.output */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n const input = strm.input;\n const last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n const output = strm.output;\n const beg = _out - (start - strm.avail_out);\n const end = _out + (strm.avail_out - 257);\n //#ifdef INFLATE_STRICT\n const dmax = state.dmax;\n //#endif\n const wsize = state.wsize;\n const whave = state.whave;\n const wnext = state.wnext;\n const s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n const lcode = state.lencode;\n const dcode = state.distcode;\n const lmask = (1 << state.lenbits) - 1;\n const dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n } else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n //#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n //#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n // if (len <= op - whave) {\n // do {\n // output[_out++] = 0;\n // } while (--len);\n // continue top;\n // }\n // len -= op - whave;\n // do {\n // output[_out++] = 0;\n // } while (--op > whave);\n // if (op === 0) {\n // from = _out - dist;\n // do {\n // output[_out++] = output[from++];\n // } while (--len);\n // continue top;\n // }\n //#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n } else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n } else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nconst lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nconst dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nconst dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nexport default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n // var shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break; \n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break; \n }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n const mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break; \n }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break; \n }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = root << 24 | curr << 16 | next - table_index |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = len - drop << 24 | 64 << 16 |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport inflate_fast from \"./inffast.js\";\nimport inflate_table from \"./inftrees.js\";\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_FINISH,\n Z_BLOCK,\n Z_TREES,\n Z_OK,\n Z_STREAM_END,\n Z_NEED_DICT,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\n//const MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nclass InflateState {\n constructor() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n }\n}\n\nfunction inflateResetKeep(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n let wrap;\n let state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n let ret;\n let state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n let sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n let hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary var for NEED_BITS\n\n const order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n // case MEM:\n // return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n const state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n let state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n // if (ret) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n // }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nconst inflateInfo = 'pako inflate (from Nodeca project)';\n\nexport {\n inflateReset,\n inflateReset2,\n inflateResetKeep,\n inflateInit,\n inflateInit2,\n inflate,\n inflateEnd,\n inflateGetHeader,\n inflateSetDictionary,\n inflateInfo\n};\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class GZheader {\n constructor() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n }\n}","'use strict';\n\nimport * as zlib_inflate from \"./zlib/inflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport * as c from \"./zlib/constants.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\nimport GZheader from \"./zlib/gzheader.js\";\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nclass Inflate {\n constructor(options) {\n this.options = {\n chunkSize: 16384,\n windowBits: 0,\n ...(options || {})\n };\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n let status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n }\n /**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize, dictionary } } = this;\n let status, _mode;\n let next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n let allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n\n /**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n\n\n /**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === c.Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw new Error(inflator.msg || msg[inflator.err]); }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\nexport { Inflate, inflate, inflateRaw, inflate as ungzip };\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuer,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.signedHashValue = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n this.params = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false) {\n if (key.version === 5) {\n this.version = 5;\n } else {\n this.version = 4;\n }\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = [];\n this.unhashedSubpackets.forEach(data => {\n arr.push(writeSimpleLength(data.length));\n arr.push(data);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n // V4 signature sub packets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n if (!hashed) {\n this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n mypos++;\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuer:\n // Issuer\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion === 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n default: {\n const err = new Error(`Unknown signature subpacket type ${type}`);\n if (critical) {\n throw err;\n } else {\n util.printDebug(err);\n }\n }\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, 2));\n\n let i = 2;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n constructor() {\n /** A one-octet version number. The current version is 3. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** An eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current version is 3.\n this.version = bytes[mypos++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n // An eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);\n\n const end = new Uint8Array([this.flags]);\n\n return util.concatUint8Array([start, this.issuerKeyID.write(), end]);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID)\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Deflate } from '@openpgp/pako/lib/deflate';\nimport { Inflate } from '@openpgp/pako/lib/inflate';\nimport { Z_SYNC_FLUSH, Z_FINISH } from '@openpgp/pako/lib/zlib/constants';\nimport { decode as BunzipDecode } from '@openpgp/seek-bzip';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n\n /**\n * zip/zlib compression level, between 1 and 9\n */\n this.deflateLevel = config.deflateLevel;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName];\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write(), this.deflateLevel);\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nconst nodeZlib = util.getNodeZlib();\n\nfunction uncompressed(data) {\n return data;\n}\n\nfunction node_zlib(func, create, options = {}) {\n return function (data) {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(data => {\n return new Promise((resolve, reject) => {\n func(data, options, (err, result) => {\n if (err) return reject(err);\n resolve(result);\n });\n });\n }));\n }\n return stream.nodeToWeb(stream.webToNode(data).pipe(create(options)));\n };\n}\n\nfunction pako_zlib(constructor, options = {}) {\n return function(data) {\n const obj = new constructor(options);\n return stream.transform(data, value => {\n if (value.length) {\n obj.push(value, Z_SYNC_FLUSH);\n return obj.result;\n }\n }, () => {\n if (constructor === Deflate) {\n obj.push([], Z_FINISH);\n return obj.result;\n }\n });\n };\n}\n\nfunction bzip2(func) {\n return function(data) {\n return stream.fromAsync(async () => func(await stream.readToEnd(data)));\n };\n}\n\nconst compress_fns = nodeZlib ? {\n zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)\n} : {\n zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)\n};\n\nconst decompress_fns = nodeZlib ? {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),\n zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n} : {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),\n zlib: /*#__PURE__*/ pako_zlib(Inflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n constructor() {\n this.version = VERSION;\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n // - A one-octet version number. The only currently defined value is 1.\n if (version !== VERSION) {\n throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);\n }\n\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n return util.concat([new Uint8Array([VERSION]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await this.crypt('decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await this.crypt('encrypt', key, data);\n }\n\n /**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\n async crypt(fn, key, data) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const modeInstance = await mode(this.cipherAlgorithm, key);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const adataBuffer = new ArrayBuffer(21);\n const adataArray = new Uint8Array(adataBuffer, 0, 13);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n const iv = this.iv;\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new stream.TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)\n cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = 3;\n\n this.publicKeyID = new KeyID();\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n i += this.publicKeyID.read(bytes.subarray(i));\n this.publicKeyAlgorithm = bytes[i++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);\n if (this.publicKeyAlgorithm === enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version]),\n this.publicKeyID.write(),\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n // v3 Montgomery curves have cleartext cipher algo\n if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = sessionKeyAlgorithm;\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // add checksum\n return util.concatUint8Array([\n new Uint8Array([cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n }\n case enums.publicKey.x25519:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n return {\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n * @private\n */\n\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport { UnsupportedError } from '../packet/packet';\nimport util from '../util';\n\nclass S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = 'iterated';\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n try {\n this.type = enums.read(enums.s2k, bytes[i++]);\n } catch (err) {\n throw new UnsupportedError('Unknown S2K type.');\n }\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport S2K from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 5 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = enums.symmetric.aes256;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number. The only currently defined version is 4.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version === 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n this.s2k = new S2K();\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version === 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, key);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n } else {\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const encryptionKey = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v5Keys ? 5 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes) {\n let pos = 0;\n // A one-octet version number (3, 4 or 5).\n this.version = bytes[pos++];\n\n if (this.version === 4 || this.version === 5) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version === 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version === 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n if (version === 5) {\n return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);\n }\n return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version === 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version === 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport S2K from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n this.s2k = new S2K();\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipher(this.symmetric).blockSize\n );\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n const cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...this.s2k.write());\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = new S2K(config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n\n const { blockSize } = crypto.getCipher(this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = enums.aead.eax;\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } else {\n this.s2kUsage = 254;\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\nasync function produceEncryptionKey(s2k, passphrase, algorithm) {\n const { keySize } = crypto.getCipher(algorithm);\n return s2k.produceKey(passphrase, keySize);\n}\n\nexport default SecretKeyPacket;\n","\n// email-addresses.js - RFC 5322 email address parser\n// v 3.1.0\n//\n// http://tools.ietf.org/html/rfc5322\n//\n// This library does not validate email addresses.\n// emailAddresses attempts to parse addresses using the (fairly liberal)\n// grammar specified in RFC 5322.\n//\n// email-addresses returns {\n// ast: ,\n// addresses: [{\n// node: ,\n// name: ,\n// address: ,\n// local: ,\n// domain: \n// }, ...]\n// }\n//\n// emailAddresses.parseOneAddress and emailAddresses.parseAddressList\n// work as you might expect. Try it out.\n//\n// Many thanks to Dominic Sayers and his documentation on the is_email function,\n// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.\n\n(function (global) {\n\"use strict\";\n\nfunction parse5322(opts) {\n\n // tokenizing functions\n\n function inStr() { return pos < len; }\n function curTok() { return parseString[pos]; }\n function getPos() { return pos; }\n function setPos(i) { pos = i; }\n function nextTok() { pos += 1; }\n function initialize() {\n pos = 0;\n len = parseString.length;\n }\n\n // parser helper functions\n\n function o(name, value) {\n return {\n name: name,\n tokens: value || \"\",\n semantic: value || \"\",\n children: []\n };\n }\n\n function wrap(name, ast) {\n var n;\n if (ast === null) { return null; }\n n = o(name);\n n.tokens = ast.tokens;\n n.semantic = ast.semantic;\n n.children.push(ast);\n return n;\n }\n\n function add(parent, child) {\n if (child !== null) {\n parent.tokens += child.tokens;\n parent.semantic += child.semantic;\n }\n parent.children.push(child);\n return parent;\n }\n\n function compareToken(fxnCompare) {\n var tok;\n if (!inStr()) { return null; }\n tok = curTok();\n if (fxnCompare(tok)) {\n nextTok();\n return o('token', tok);\n }\n return null;\n }\n\n function literal(lit) {\n return function literalFunc() {\n return wrap('literal', compareToken(function (tok) {\n return tok === lit;\n }));\n };\n }\n\n function and() {\n var args = arguments;\n return function andFunc() {\n var i, s, result, start;\n start = getPos();\n s = o('and');\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result === null) {\n setPos(start);\n return null;\n }\n add(s, result);\n }\n return s;\n };\n }\n\n function or() {\n var args = arguments;\n return function orFunc() {\n var i, result, start;\n start = getPos();\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result !== null) {\n return result;\n }\n setPos(start);\n }\n return null;\n };\n }\n\n function opt(prod) {\n return function optFunc() {\n var result, start;\n start = getPos();\n result = prod();\n if (result !== null) {\n return result;\n }\n else {\n setPos(start);\n return o('opt');\n }\n };\n }\n\n function invis(prod) {\n return function invisFunc() {\n var result = prod();\n if (result !== null) {\n result.semantic = \"\";\n }\n return result;\n };\n }\n\n function colwsp(prod) {\n return function collapseSemanticWhitespace() {\n var result = prod();\n if (result !== null && result.semantic.length > 0) {\n result.semantic = \" \";\n }\n return result;\n };\n }\n\n function star(prod, minimum) {\n return function starFunc() {\n var s, result, count, start, min;\n start = getPos();\n s = o('star');\n count = 0;\n min = minimum === undefined ? 0 : minimum;\n while ((result = prod()) !== null) {\n count = count + 1;\n add(s, result);\n }\n if (count >= min) {\n return s;\n }\n else {\n setPos(start);\n return null;\n }\n };\n }\n\n // One expects names to get normalized like this:\n // \" First Last \" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n function collapseWhitespace(s) {\n return s.replace(/([ \\t]|\\r\\n)+/g, ' ').replace(/^\\s*/, '').replace(/\\s*$/, '');\n }\n\n // UTF-8 pseudo-production (RFC 6532)\n // RFC 6532 extends RFC 5322 productions to include UTF-8\n // using the following productions:\n // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4\n // UTF8-2 = \n // UTF8-3 = \n // UTF8-4 = \n //\n // For reference, the extended RFC 5322 productions are:\n // VCHAR =/ UTF8-non-ascii\n // ctext =/ UTF8-non-ascii\n // atext =/ UTF8-non-ascii\n // qtext =/ UTF8-non-ascii\n // dtext =/ UTF8-non-ascii\n function isUTF8NonAscii(tok) {\n // In JavaScript, we just deal directly with Unicode code points,\n // so we aren't checking individual bytes for UTF-8 encoding.\n // Just check that the character is non-ascii.\n return tok.charCodeAt(0) >= 128;\n }\n\n\n // common productions (RFC 5234)\n // http://tools.ietf.org/html/rfc5234\n // B.1. Core Rules\n\n // CR = %x0D\n // ; carriage return\n function cr() { return wrap('cr', literal('\\r')()); }\n\n // CRLF = CR LF\n // ; Internet standard newline\n function crlf() { return wrap('crlf', and(cr, lf)()); }\n\n // DQUOTE = %x22\n // ; \" (Double Quote)\n function dquote() { return wrap('dquote', literal('\"')()); }\n\n // HTAB = %x09\n // ; horizontal tab\n function htab() { return wrap('htab', literal('\\t')()); }\n\n // LF = %x0A\n // ; linefeed\n function lf() { return wrap('lf', literal('\\n')()); }\n\n // SP = %x20\n function sp() { return wrap('sp', literal(' ')()); }\n\n // VCHAR = %x21-7E\n // ; visible (printing) characters\n function vchar() {\n return wrap('vchar', compareToken(function vcharFunc(tok) {\n var code = tok.charCodeAt(0);\n var accept = (0x21 <= code && code <= 0x7E);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // WSP = SP / HTAB\n // ; white space\n function wsp() { return wrap('wsp', or(sp, htab)()); }\n\n\n // email productions (RFC 5322)\n // http://tools.ietf.org/html/rfc5322\n // 3.2.1. Quoted characters\n\n // quoted-pair = (\"\\\" (VCHAR / WSP)) / obs-qp\n function quotedPair() {\n var qp = wrap('quoted-pair',\n or(\n and(literal('\\\\'), or(vchar, wsp)),\n obsQP\n )());\n if (qp === null) { return null; }\n // a quoted pair will be two characters, and the \"\\\" character\n // should be semantically \"invisible\" (RFC 5322 3.2.1)\n qp.semantic = qp.semantic[1];\n return qp;\n }\n\n // 3.2.2. Folding White Space and Comments\n\n // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS\n function fws() {\n return wrap('fws', or(\n obsFws,\n and(\n opt(and(\n star(wsp),\n invis(crlf)\n )),\n star(wsp, 1)\n )\n )());\n }\n\n // ctext = %d33-39 / ; Printable US-ASCII\n // %d42-91 / ; characters not including\n // %d93-126 / ; \"(\", \")\", or \"\\\"\n // obs-ctext\n function ctext() {\n return wrap('ctext', or(\n function ctextFunc1() {\n return compareToken(function ctextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 39) ||\n (42 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsCtext\n )());\n }\n\n // ccontent = ctext / quoted-pair / comment\n function ccontent() {\n return wrap('ccontent', or(ctext, quotedPair, comment)());\n }\n\n // comment = \"(\" *([FWS] ccontent) [FWS] \")\"\n function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }\n\n // CFWS = (1*([FWS] comment) [FWS]) / FWS\n function cfws() {\n return wrap('cfws', or(\n and(\n star(\n and(opt(fws), comment),\n 1\n ),\n opt(fws)\n ),\n fws\n )());\n }\n\n // 3.2.3. Atom\n\n //atext = ALPHA / DIGIT / ; Printable US-ASCII\n // \"!\" / \"#\" / ; characters not including\n // \"$\" / \"%\" / ; specials. Used for atoms.\n // \"&\" / \"'\" /\n // \"*\" / \"+\" /\n // \"-\" / \"/\" /\n // \"=\" / \"?\" /\n // \"^\" / \"_\" /\n // \"`\" / \"{\" /\n // \"|\" / \"}\" /\n // \"~\"\n function atext() {\n return wrap('atext', compareToken(function atextFunc(tok) {\n var accept =\n ('a' <= tok && tok <= 'z') ||\n ('A' <= tok && tok <= 'Z') ||\n ('0' <= tok && tok <= '9') ||\n (['!', '#', '$', '%', '&', '\\'', '*', '+', '-', '/',\n '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // atom = [CFWS] 1*atext [CFWS]\n function atom() {\n return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());\n }\n\n // dot-atom-text = 1*atext *(\".\" 1*atext)\n function dotAtomText() {\n var s, maybeText;\n s = wrap('dot-atom-text', star(atext, 1)());\n if (s === null) { return s; }\n maybeText = star(and(literal('.'), star(atext, 1)))();\n if (maybeText !== null) {\n add(s, maybeText);\n }\n return s;\n }\n\n // dot-atom = [CFWS] dot-atom-text [CFWS]\n function dotAtom() {\n return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());\n }\n\n // 3.2.4. Quoted Strings\n\n // qtext = %d33 / ; Printable US-ASCII\n // %d35-91 / ; characters not including\n // %d93-126 / ; \"\\\" or the quote character\n // obs-qtext\n function qtext() {\n return wrap('qtext', or(\n function qtextFunc1() {\n return compareToken(function qtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 === code) ||\n (35 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsQtext\n )());\n }\n\n // qcontent = qtext / quoted-pair\n function qcontent() {\n return wrap('qcontent', or(qtext, quotedPair)());\n }\n\n // quoted-string = [CFWS]\n // DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n // [CFWS]\n function quotedString() {\n return wrap('quoted-string', and(\n invis(opt(cfws)),\n invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),\n invis(opt(cfws))\n )());\n }\n\n // 3.2.5 Miscellaneous Tokens\n\n // word = atom / quoted-string\n function word() {\n return wrap('word', or(atom, quotedString)());\n }\n\n // phrase = 1*word / obs-phrase\n function phrase() {\n return wrap('phrase', or(obsPhrase, star(word, 1))());\n }\n\n // 3.4. Address Specification\n // address = mailbox / group\n function address() {\n return wrap('address', or(mailbox, group)());\n }\n\n // mailbox = name-addr / addr-spec\n function mailbox() {\n return wrap('mailbox', or(nameAddr, addrSpec)());\n }\n\n // name-addr = [display-name] angle-addr\n function nameAddr() {\n return wrap('name-addr', and(opt(displayName), angleAddr)());\n }\n\n // angle-addr = [CFWS] \"<\" addr-spec \">\" [CFWS] /\n // obs-angle-addr\n function angleAddr() {\n return wrap('angle-addr', or(\n and(\n invis(opt(cfws)),\n literal('<'),\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n ),\n obsAngleAddr\n )());\n }\n\n // group = display-name \":\" [group-list] \";\" [CFWS]\n function group() {\n return wrap('group', and(\n displayName,\n literal(':'),\n opt(groupList),\n literal(';'),\n invis(opt(cfws))\n )());\n }\n\n // display-name = phrase\n function displayName() {\n return wrap('display-name', function phraseFixedSemantic() {\n var result = phrase();\n if (result !== null) {\n result.semantic = collapseWhitespace(result.semantic);\n }\n return result;\n }());\n }\n\n // mailbox-list = (mailbox *(\",\" mailbox)) / obs-mbox-list\n function mailboxList() {\n return wrap('mailbox-list', or(\n and(\n mailbox,\n star(and(literal(','), mailbox))\n ),\n obsMboxList\n )());\n }\n\n // address-list = (address *(\",\" address)) / obs-addr-list\n function addressList() {\n return wrap('address-list', or(\n and(\n address,\n star(and(literal(','), address))\n ),\n obsAddrList\n )());\n }\n\n // group-list = mailbox-list / CFWS / obs-group-list\n function groupList() {\n return wrap('group-list', or(\n mailboxList,\n invis(cfws),\n obsGroupList\n )());\n }\n\n // 3.4.1 Addr-Spec Specification\n\n // local-part = dot-atom / quoted-string / obs-local-part\n function localPart() {\n // note: quoted-string, dotAtom are proper subsets of obs-local-part\n // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree\n return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());\n }\n\n // dtext = %d33-90 / ; Printable US-ASCII\n // %d94-126 / ; characters not including\n // obs-dtext ; \"[\", \"]\", or \"\\\"\n function dtext() {\n return wrap('dtext', or(\n function dtextFunc1() {\n return compareToken(function dtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 90) ||\n (94 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsDtext\n )()\n );\n }\n\n // domain-literal = [CFWS] \"[\" *([FWS] dtext) [FWS] \"]\" [CFWS]\n function domainLiteral() {\n return wrap('domain-literal', and(\n invis(opt(cfws)),\n literal('['),\n star(and(opt(fws), dtext)),\n opt(fws),\n literal(']'),\n invis(opt(cfws))\n )());\n }\n\n // domain = dot-atom / domain-literal / obs-domain\n function domain() {\n return wrap('domain', function domainCheckTLD() {\n var result = or(obsDomain, dotAtom, domainLiteral)();\n if (opts.rejectTLD) {\n if (result && result.semantic && result.semantic.indexOf('.') < 0) {\n return null;\n }\n }\n // strip all whitespace from domains\n if (result) {\n result.semantic = result.semantic.replace(/\\s+/g, '');\n }\n return result;\n }());\n }\n\n // addr-spec = local-part \"@\" domain\n function addrSpec() {\n return wrap('addr-spec', and(\n localPart, literal('@'), domain\n )());\n }\n\n // 3.6.2 Originator Fields\n // Below we only parse the field body, not the name of the field\n // like \"From:\", \"Sender:\", or \"Reply-To:\". Other libraries that\n // parse email headers can parse those and defer to these productions\n // for the \"RFC 5322\" part.\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // from = \"From:\" (mailbox-list / address-list) CRLF\n function fromSpec() {\n return wrap('from', or(\n mailboxList,\n addressList\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // sender = \"Sender:\" (mailbox / address) CRLF\n function senderSpec() {\n return wrap('sender', or(\n mailbox,\n address\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // reply-to = \"Reply-To:\" address-list CRLF\n function replyToSpec() {\n return wrap('reply-to', addressList());\n }\n\n // 4.1. Miscellaneous Obsolete Tokens\n\n // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control\n // %d11 / ; characters that do not\n // %d12 / ; include the carriage\n // %d14-31 / ; return, line feed, and\n // %d127 ; white space characters\n function obsNoWsCtl() {\n return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {\n var code = tok.charCodeAt(0);\n return ((1 <= code && code <= 8) ||\n (11 === code || 12 === code) ||\n (14 <= code && code <= 31) ||\n (127 === code));\n }));\n }\n\n // obs-ctext = obs-NO-WS-CTL\n function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }\n\n // obs-qtext = obs-NO-WS-CTL\n function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }\n\n // obs-qp = \"\\\" (%d0 / obs-NO-WS-CTL / LF / CR)\n function obsQP() {\n return opts.strict ? null : wrap('obs-qp', and(\n literal('\\\\'),\n or(literal('\\0'), obsNoWsCtl, lf, cr)\n )());\n }\n\n // obs-phrase = word *(word / \".\" / CFWS)\n function obsPhrase() {\n if (opts.strict ) return null;\n return opts.atInDisplayName ? wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), literal('@'), colwsp(cfws)))\n )()) :\n wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), colwsp(cfws)))\n )());\n }\n\n // 4.2. Obsolete Folding White Space\n\n // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908\n // obs-FWS = 1*([CRLF] WSP)\n function obsFws() {\n return opts.strict ? null : wrap('obs-FWS', star(\n and(invis(opt(crlf)), wsp),\n 1\n )());\n }\n\n // 4.4. Obsolete Addressing\n\n // obs-angle-addr = [CFWS] \"<\" obs-route addr-spec \">\" [CFWS]\n function obsAngleAddr() {\n return opts.strict ? null : wrap('obs-angle-addr', and(\n invis(opt(cfws)),\n literal('<'),\n obsRoute,\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n )());\n }\n\n // obs-route = obs-domain-list \":\"\n function obsRoute() {\n return opts.strict ? null : wrap('obs-route', and(\n obsDomainList,\n literal(':')\n )());\n }\n\n // obs-domain-list = *(CFWS / \",\") \"@\" domain\n // *(\",\" [CFWS] [\"@\" domain])\n function obsDomainList() {\n return opts.strict ? null : wrap('obs-domain-list', and(\n star(or(invis(cfws), literal(','))),\n literal('@'),\n domain,\n star(and(\n literal(','),\n invis(opt(cfws)),\n opt(and(literal('@'), domain))\n ))\n )());\n }\n\n // obs-mbox-list = *([CFWS] \",\") mailbox *(\",\" [mailbox / CFWS])\n function obsMboxList() {\n return opts.strict ? null : wrap('obs-mbox-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n mailbox,\n star(and(\n literal(','),\n opt(and(\n mailbox,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-addr-list = *([CFWS] \",\") address *(\",\" [address / CFWS])\n function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n address,\n star(and(\n literal(','),\n opt(and(\n address,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-group-list = 1*([CFWS] \",\") [CFWS]\n function obsGroupList() {\n return opts.strict ? null : wrap('obs-group-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n ), 1),\n invis(opt(cfws))\n )());\n }\n\n // obs-local-part = word *(\".\" word)\n function obsLocalPart() {\n return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());\n }\n\n // obs-domain = atom *(\".\" atom)\n function obsDomain() {\n return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());\n }\n\n // obs-dtext = obs-NO-WS-CTL / quoted-pair\n function obsDtext() {\n return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());\n }\n\n /////////////////////////////////////////////////////\n\n // ast analysis\n\n function findNode(name, root) {\n var i, stack, node;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n return node;\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return null;\n }\n\n function findAllNodes(name, root) {\n var i, stack, node, result;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n result.push(node);\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return result;\n }\n\n function findAllNodesNoChildren(names, root) {\n var i, stack, node, result, namesLookup;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n namesLookup = {};\n for (i = 0; i < names.length; i += 1) {\n namesLookup[names[i]] = true;\n }\n\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name in namesLookup) {\n result.push(node);\n // don't look at children (hence findAllNodesNoChildren)\n } else {\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n }\n return result;\n }\n\n function giveResult(ast) {\n var addresses, groupsAndMailboxes, i, groupOrMailbox, result;\n if (ast === null) {\n return null;\n }\n addresses = [];\n\n // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.\n groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);\n for (i = 0; i < groupsAndMailboxes.length; i += 1) {\n groupOrMailbox = groupsAndMailboxes[i];\n if (groupOrMailbox.name === 'group') {\n addresses.push(giveResultGroup(groupOrMailbox));\n } else if (groupOrMailbox.name === 'mailbox') {\n addresses.push(giveResultMailbox(groupOrMailbox));\n }\n }\n\n result = {\n ast: ast,\n addresses: addresses,\n };\n if (opts.simple) {\n result = simplifyResult(result);\n }\n if (opts.oneResult) {\n return oneResult(result);\n }\n if (opts.simple) {\n return result && result.addresses;\n } else {\n return result;\n }\n }\n\n function giveResultGroup(group) {\n var i;\n var groupName = findNode('display-name', group);\n var groupResultMailboxes = [];\n var mailboxes = findAllNodesNoChildren(['mailbox'], group);\n for (i = 0; i < mailboxes.length; i += 1) {\n groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));\n }\n return {\n node: group,\n parts: {\n name: groupName,\n },\n type: group.name, // 'group'\n name: grabSemantic(groupName),\n addresses: groupResultMailboxes,\n };\n }\n\n function giveResultMailbox(mailbox) {\n var name = findNode('display-name', mailbox);\n var aspec = findNode('addr-spec', mailbox);\n var cfws = findAllNodes('cfws', mailbox);\n var comments = findAllNodesNoChildren(['comment'], mailbox);\n\n\n var local = findNode('local-part', aspec);\n var domain = findNode('domain', aspec);\n return {\n node: mailbox,\n parts: {\n name: name,\n address: aspec,\n local: local,\n domain: domain,\n comments: cfws\n },\n type: mailbox.name, // 'mailbox'\n name: grabSemantic(name),\n address: grabSemantic(aspec),\n local: grabSemantic(local),\n domain: grabSemantic(domain),\n comments: concatComments(comments),\n groupName: grabSemantic(mailbox.groupName),\n };\n }\n\n function grabSemantic(n) {\n return n !== null && n !== undefined ? n.semantic : null;\n }\n\n function simplifyResult(result) {\n var i;\n if (result && result.addresses) {\n for (i = 0; i < result.addresses.length; i += 1) {\n delete result.addresses[i].node;\n }\n }\n return result;\n }\n\n function concatComments(comments) {\n var result = '';\n if (comments) {\n for (var i = 0; i < comments.length; i += 1) {\n result += grabSemantic(comments[i]);\n }\n }\n return result;\n }\n\n function oneResult(result) {\n if (!result) { return null; }\n if (!opts.partial && result.addresses.length > 1) { return null; }\n return result.addresses && result.addresses[0];\n }\n\n /////////////////////////////////////////////////////\n\n var parseString, pos, len, parsed, startProduction;\n\n opts = handleOpts(opts, {});\n if (opts === null) { return null; }\n\n parseString = opts.input;\n\n startProduction = {\n 'address': address,\n 'address-list': addressList,\n 'angle-addr': angleAddr,\n 'from': fromSpec,\n 'group': group,\n 'mailbox': mailbox,\n 'mailbox-list': mailboxList,\n 'reply-to': replyToSpec,\n 'sender': senderSpec,\n }[opts.startAt] || addressList;\n\n if (!opts.strict) {\n initialize();\n opts.strict = true;\n parsed = startProduction(parseString);\n if (opts.partial || !inStr()) {\n return giveResult(parsed);\n }\n opts.strict = false;\n }\n\n initialize();\n parsed = startProduction(parseString);\n if (!opts.partial && inStr()) { return null; }\n return giveResult(parsed);\n}\n\nfunction parseOneAddressSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseAddressListSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseFromSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'from',\n }));\n}\n\nfunction parseSenderSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'sender',\n }));\n}\n\nfunction parseReplyToSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'reply-to',\n }));\n}\n\nfunction handleOpts(opts, defs) {\n function isString(str) {\n return Object.prototype.toString.call(str) === '[object String]';\n }\n\n function isObject(o) {\n return o === Object(o);\n }\n\n function isNullUndef(o) {\n return o === null || o === undefined;\n }\n\n var defaults, o;\n\n if (isString(opts)) {\n opts = { input: opts };\n } else if (!isObject(opts)) {\n return null;\n }\n\n if (!isString(opts.input)) { return null; }\n if (!defs) { return null; }\n\n defaults = {\n oneResult: false,\n partial: false,\n rejectTLD: false,\n rfc6532: false,\n simple: false,\n startAt: 'address-list',\n strict: false,\n atInDisplayName: false\n };\n\n for (o in defaults) {\n if (isNullUndef(opts[o])) {\n opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];\n }\n }\n return opts;\n}\n\nparse5322.parseOneAddress = parseOneAddressSimple;\nparse5322.parseAddressList = parseAddressListSimple;\nparse5322.parseFrom = parseFromSimple;\nparse5322.parseSender = parseSenderSimple;\nparse5322.parseReplyTo = parseReplyToSimple;\n\nif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = parse5322;\n} else {\n global.emailAddresses = parse5322;\n}\n\n}(this));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport emailAddresses from 'email-addresses';\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n try {\n const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });\n this.comment = comments.replace(/^\\(|\\)$/g, '');\n this.name = name;\n this.email = email;\n } catch (e) {}\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n * @private\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm of a key\n * @param {Key} [key] - The key to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) {\n let hashAlgo = config.preferredHashAlgorithm;\n let prefAlgo = hashAlgo;\n if (key) {\n const primaryUser = await key.getPrimaryUser(date, userID, config);\n if (primaryUser.selfCertification.preferredHashAlgorithms) {\n [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;\n hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n }\n }\n switch (keyPacket.algorithm) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n prefAlgo = crypto.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);\n }\n return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n}\n\n/**\n * Returns the preferred symmetric/aead/compression algorithm for a set of keys\n * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred algorithm\n * @async\n */\nexport async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = { // these are all must-implement in rfc4880bis\n 'symmetric': enums.symmetric.aes128,\n 'aead': enums.aead.eax,\n 'compression': enums.compression.uncompressed\n }[type];\n const preferredSenderAlgo = {\n 'symmetric': config.preferredSymmetricAlgorithm,\n 'aead': config.preferredAEADAlgorithm,\n 'compression': config.preferredCompressionAlgorithm\n }[type];\n const prefPropertyName = {\n 'symmetric': 'preferredSymmetricAlgorithms',\n 'aead': 'preferredAEADAlgorithms',\n 'compression': 'preferredCompressionAlgorithms'\n }[type];\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n const recipientPrefs = primaryUser.selfCertification[prefPropertyName];\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {PrivateKey} privateKey - key to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config);\n signaturePacket.rawNotations = notations;\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n await revocationSignature.verify(\n key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\n/**\n * Returns whether aead is supported by all keys in the set\n * @param {Array} keys - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {\n let supported = true;\n // TODO replace when Promise.some or Promise.any are implemented\n await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n if (!primaryUser.selfCertification.features ||\n !(primaryUser.selfCertification.features[0] & enums.features.aead)) {\n supported = false;\n }\n }));\n return supported;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc':\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function isValidSigningKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.rsaEncrypt &&\n keyAlgo !== enums.publicKey.elgamal &&\n keyAlgo !== enums.publicKey.ecdh &&\n keyAlgo !== enums.publicKey.x25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);\n}\n\nexport function isValidEncryptionKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.dsa &&\n keyAlgo !== enums.publicKey.rsaSign &&\n keyAlgo !== enums.publicKey.ecdsa &&\n keyAlgo !== enums.publicKey.eddsaLegacy &&\n keyAlgo !== enums.publicKey.ed25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);\n}\n\nexport function isValidDecryptionKeyPacket(signature, config) {\n if (config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n * @private\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n // check for expiration time in direct signatures\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const { selfCertification } = await this.getPrimaryUser(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidDecryptionKeyPacket(bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {}\n }\n }\n\n // evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&\n helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {\n keys.push(this);\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n const keyPacket = await helper.generateSecretSubkey(options);\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {};\n dataToSign.userID = userIDPacket;\n dataToSign.key = secretKeyPacket;\n\n const signatureProperties = {};\n signatureProperties.signatureType = enums.signature.certGeneric;\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128,\n enums.symmetric.aes192\n ], config.preferredSymmetricAlgorithm);\n if (config.aeadProtect) {\n signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.zlib,\n enums.compression.zip,\n enums.compression.uncompressed\n ], config.preferredCompressionAlgorithm);\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.aead;\n }\n if (config.v5Keys) {\n signatureProperties.features[0] |= enums.features.v5Keys;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return createKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No secret key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport KeyID from './type/keyid';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);\n\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || !util.isString(algorithmName)) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.\n if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n // do not check key expiration to allow decryption of old messages\n const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {\n return;\n }\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);\n const algorithmName = enums.read(enums.symmetric, algo);\n const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?\n enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :\n undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(algo);\n return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n let symEncryptedPacket;\n if (aeadAlgorithmName) {\n symEncryptedPacket = new AEADEncryptedDataPacket();\n symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);\n } else {\n symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();\n }\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const algorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();\n pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();\n pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;\n pkESKeyPacket.sessionKey = sessionKey;\n pkESKeyPacket.sessionKeyAlgorithm = algorithm;\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n let i;\n let existingSigPacketlist;\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n if (signature) {\n existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n for (i = existingSigPacketlist.length - 1; i >= 0; i--) {\n const signaturePacket = existingSigPacketlist[i];\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n if (!signingKeys.length && i === 0) {\n onePassSig.flags = 1;\n }\n packetlist.push(onePassSig);\n }\n }\n\n await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];\n const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signatureType;\n onePassSig.hashAlgorithm = await getPreferredHashAlgo(primaryKey, signingKey.keyPacket, date, userIDs, config);\n onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;\n onePassSig.issuerKeyID = signingKey.getKeyID();\n if (i === signingKeys.length - 1) {\n onePassSig.flags = 1;\n }\n return onePassSig;\n })).then(onePassSignatureList => {\n onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));\n });\n\n packetlist.push(literalDataPacket);\n packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config)));\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.message, this.write(), null, null, null, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const userID = userIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);\n return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n let input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} privateKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n let hashes = this.signature.packets.map(function(packet) {\n return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();\n });\n hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });\n const body = {\n hash: hashes.join(),\n text: this.text,\n data: this.signature.packets.write()\n };\n return armor(enums.armor.signed, body, undefined, undefined, undefined, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n let oneHeader = null;\n let hashAlgos = [];\n headers.forEach(function(header) {\n oneHeader = header.match(/^Hash: (.+)$/); // get header value\n if (oneHeader) {\n oneHeader = oneHeader[1].replace(/\\s/g, ''); // remove whitespace\n oneHeader = oneHeader.split(',');\n oneHeader = oneHeader.map(function(hash) {\n hash = hash.toLowerCase();\n try {\n return enums.write(enums.hash, hash);\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hash);\n }\n });\n hashAlgos = hashAlgos.concat(oneHeader);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {\n throw new Error('If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed');\n } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:\n * curve25519 (default), p256, p384, p521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key generation');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key reformat');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n const streaming = message.fromStream;\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return convertStream(data, streaming, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type\n * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data, streaming, encoding = 'utf8') {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n if (streaming === 'node') {\n data = stream.webToNode(data);\n if (encoding !== 'binary') data.setEncoding(encoding);\n return data;\n }\n if (streaming === 'web' && streamType === 'ponyfill') {\n return stream.toNativeReadable(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","this","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","prototype","undefined","read","async","length","value","done","readToEnd","join","result","slice","clone","then","push","write","chunk","close","abort","reason","isNode","globalThis","process","versions","NodeReadableStream","isStream","ReadableStream","isPrototypeOf","streams.ReadableStream","isUint8Array","Uint8Array","concatUint8Array","arrays","totalLength","i","Error","pos","forEach","element","set","NodeBuffer","nodeToWeb","webToNode","nodeStream","canceled","start","controller","pause","on","isBuffer","buffer","byteOffset","byteLength","enqueue","e","error","pull","resume","cancel","destroy","NodeReadable","webStream","options","_reader","streams.getReader","size","callback","doneReadingSet","WeakSet","externalBuffer","Reader","streams.isArrayStream","reader","_read","bind","_releaseLock","_cancel","streamType","streams.isStream","streams.nodeToWeb","doneReading","has","add","shift","readLine","returnVal","streams.concat","lineEndIndex","indexOf","concat","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","filter","toPonyfillReadable","toNativeReadable","WritableStream","TransformStream","loadStreamsPonyfill","ponyfill","adapter","all","import","createReadableStreamWrapper","toStream","toArrayStream","list","some","map","transform","transformWithCancel","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","transformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","highWaterMark","finish","output","data","result1","result2","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","Object","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","arrayStream","BigInteger","n","hex","hexByte","toString","BigInt","iinc","inc","idec","dec","iadd","x","isub","sub","imul","mul","imod","m","isNegative","mod","modExp","isZero","isOne","exp","r","lsb","rx","modInv","gcd","_egcd","b","y","xPrev","yPrev","a","q","tmp","ileftShift","leftShift","irightShift","rightShift","equal","lt","lte","gt","gte","isEven","abs","res","toNumber","number","Number","MAX_SAFE_INTEGER","getBit","bitLength","zero","one","negOne","bitlen","eight","len","toUint8Array","endian","rawLength","offset","parseInt","reverse","detectBigInt","byValue","curve","p256","secp256r1","prime256v1","p384","secp384r1","p521","secp521r1","secp256k1","ed25519Legacy","ED25519","ed25519","Ed25519","curve25519Legacy","X25519","cv25519","curve25519","Curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","eddsa","aedh","aedsa","x25519","x448","ed448","symmetric","plaintext","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","webHash","aead","eax","ocb","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuer","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","type","debugMode","env","NODE_ENV","util","isString","String","stream.isUint8Array","stream.isStream","readNumber","writeNumber","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","leftPad","padded","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","k","uint8ArrayToHex","h","c","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","s","printDebug","log","printDebugError","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","crypto","subtle","getBigInteger","default","getNodeCrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","selectUint8","isAES","cipherAlgo","enums","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","from","btoa","atob","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","deflateLevel","aeadProtect","preferredAEADAlgorithm","aeadChunkSizeByte","s2kIterationCountByte","allowUnauthenticatedMessages","allowUnauthenticatedStream","checksumRequired","minRSABits","passwordCollisionCheck","revocationsExpire","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","minBytesForWebCrypto","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","useIndutnyElliptic","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","getType","header","match","addheader","customComment","config","getCheckSum","base64.encode","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","splitChecksum","body","checksum","lastEquals","lastIndexOf","unarmor","defaultConfig","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","checksumVerified","stream.readToEnd","stream.passiveClone","stream.pipe","checksumVerifiedString","stream.isArrayStream","messageType","partIndex","partTotal","bodyClone","KeyID","toHex","equals","keyID","matchWildcard","isWildcard","isNull","static","AES_asm","gexp3","glog3","ginit_done","gmul","aes_sbox","aes_sinv","aes_enc","aes_dec","aes_init_done","aes_init","_s","ginv","d","ginit","wrapper","foreign","heap","asm","stdlib","S0","S1","S2","S3","I0","I1","I2","I3","N0","N1","N2","N3","M0","M1","M2","M3","H0","H1","H2","H3","R","HEAP","DATA","_core","x0","x1","x2","x3","t1","t2","t3","y0","y1","y2","y3","_ecb_enc","_ecb_dec","_cbc_enc","_cbc_dec","_cfb_enc","_cfb_dec","_ofb","_ctr","_gcm_mac","z0","z1","z2","z3","set_rounds","set_state","s0","s1","s2","s3","set_iv","i0","i1","i2","i3","set_nonce","n0","n1","n2","n3","set_mask","m0","m1","m2","m3","set_counter","c0","c1","c2","c3","get_state","get_iv","gcm_init","cipher","mode","ret","_cipher_modes","mac","_mac_modes","set_key","ks","k0","k1","k2","k3","k4","k5","k6","k7","ekeys","dkeys","rcon","jj","ENC","ECB","CBC","CFB","OFB","CTR","DEC","MAC","GCM","HEAP_DATA","is_bytes","_heap_init","heapSize","_heap_write","hpos","dpos","dlen","hlen","wlen","joinBytes","arg","totalLenght","reduce","sum","curr","cursor","IllegalStateError","args","IllegalArgumentError","SecurityError","heap_pool","asm_pool","AES","iv","padding","acquire_asm","pop","reset","release_asm","keylen","keyview","getUint32","ivview","AES_Encrypt_process","TypeError","amode","rpos","AES_Encrypt_finish","plen","rlen","hasOwnProperty","p","AES_Decrypt_process","AES_Decrypt_finish","pad","pcheck","AES_ECB","encrypt","decrypt","aes","C","aesECB","block","blockSize","keySize","des","keys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","left","right","looping","cbcleft","cbcleft2","cbcright","cbcright2","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","src","dst","l","f1","f2","f3","scheduleA","scheduleB","I","sBox","inn","w","ki","half","round","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","u","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","vector","off","_decryptBlock","kk","sha1_asm","H4","TOTAL0","TOTAL1","I4","O0","O1","O2","O3","O4","w0","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32","w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61","w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","_core_heap","_state_to_heap","h0","h1","h2","h3","h4","total0","total1","hashed","hmac_reset","_hmac_opad","hmac_init","p0","p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","hmac_finish","t0","t4","pbkdf2_generate_block","count","Hash","HASH_SIZE","Sha1","NAME","BLOCK_SIZE","asm_function","Sha256","H5","H6","H7","I5","I6","I7","O5","O6","O7","f","g","h5","h6","h7","t5","t6","t7","sha256_asm","assert","val","msg","module","create","ctor","superCtor","super_","enumerable","configurable","TempCtor","enc","hi","lo","zero2","htonl","zero8","word","inherits","ah","al","bh","bl","ch","cl","dh","dl","carry","eh","el","num","BlockHash","pending","pendingTotal","outSize","hmacStrength","_delta8","_delta32","update","utils","toArray","join32","_update","digest","_pad","_digest","rotr32","z","ch32","p32","maj32","sum32","sum32_4","sum32_5","shaCommon","s0_256","s1_256","g0_256","g1_256","common","sha256_K","SHA256","W","SHA224","T1","T2","toHex32","split32","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","SHA512","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","SHA384","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotl32","sum32_3","RIPEMD160","K","Kh","A","B","D","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","md5cycle","ff","gg","add32","cmn","md5blk","md5blks","hex_chr","rhex","webCrypto","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","hashjsHash","webCryptoHash","hashInstance","asmcryptoHash","hashFunctions","entree","state","substring","tail","md51","ripemd160","algo","getHashByteLength","AES_CFB","getCipher","algoName","knownAlgos","getCiphers","nodeAlgos","pt","cipherObj","createCipheriv","nodeEncrypt","ALGO","_key","importKey","cbc_pt","ct","xorMut","webEncrypt","cfb","aesEncrypt","cipherfn","block_size","blockc","ciphertext","encblock","decipherObj","createDecipheriv","nodeDecrypt","aesDecrypt","blockp","decblock","AES_CTR","nonce","AES_CTR_set_options","counter","mask","pow","view","AES_CBC","blockLength","rightXORMut","zeroBlock","CMAC","cbc","padding2","ivLength","tagLength","two","OMAC","cmac","en","final","EAX","omac","ctr","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","xor","OCB","encipher","decipher","maxNtz","crypt","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","xorInput","$","cipherInput","cipherName","ciphers","mask_x","mask_$","constructKeyVariables","crypted","_AES_GCM_data_maxLength","AES_GCM","tagSize","gamma0","noncelen","noncebuf","_gcm_mac_process","nonceview","RangeError","cleartext","tagsize","AES_GCM_encrypt","AES_GCM_decrypt","AES_GCM_Encrypt_process","AES_GCM_Encrypt_finish","alen","clen","AES_GCM_Decrypt_process","tlen","AES_GCM_Decrypt_finish","atag","acheck","setAAD","getAuthTag","de","setAuthTag","additionalData","gcm","nacl","gf","Float64Array","randombytes","_9","gf0","gf1","_121665","D2","X","Y","crypto_verify_32","xi","yi","vn","set25519","car25519","o","v","sel25519","pack25519","neq25519","par25519","unpack25519","Z","M","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","x32","x16","crypto_scalarmult_base","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","cleanup","arr","scalarMult","box","keyPair","fromSecretKey","sign","signedMsg","sm","smlen","crypto_sign","detached","sig","verify","crypto_sign_open","fromSeed","seed","setPRNG","self","msCrypto","getRandomValues","min","require","randomBytes","exports","getRandomBytes","getRandomBigInteger","modulus","randomProbablePrime","thirty","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","rand","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","emLen","hashPrefix","tLen","fill","EM","asn1","RSAPrivateKey","define","seq","obj","int","RSAPublicKey","hashAlgo","hashName","jwk","pNum","qNum","dNum","dq","dp","kty","qi","ext","privateToJWK","webSign","err","BN","pBNum","qBNum","dBNum","subn","createSign","keyObject","version","publicExponent","privateExponent","prime1","prime2","exponent1","exponent2","coefficient","createPrivateKey","der","format","pem","label","nodeSign","bnSign","publicToJWK","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","constants","RSA_PKCS1_PADDING","publicEncrypt","bnEncrypt","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","keyGenOpt","modulusLength","generateKey","exportKey","generateKeyPair","opts","publicKeyEncoding","privateKeyEncoding","prv","_","toArrayLike","phi","nSizeOver3","rde","pSize","n1023","threshold","rqx","OID","oid","getName","keyFromPrivate","indutnyCurve","priv","keyFromPublic","pub","validate","getIndutnyCurve","elliptic","ec","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","stream.TransformStream","lengthByte","nextPacket","UnsupportedError","params","captureStackTrace","UnparseablePacket","rawContent","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","CurveWithOID","oidOrName","webCryptoKey","namedCurve","jwkToRawPublic","webGenKeyPair","createECDH","generateKeys","getPublicKey","getPrivateKey","nodeGenKeyPair","genKeyPair","entropy","getPublic","getPrivate","validateStandardParams","Q","supportedCurves","curveName","dG","validationErrors","eq","bufX","bufY","rawPublicToJWK","crv","ECPrivateKey","parameters","unused","ECDSASignature","ellipticSign","SubjectPublicKeyInfo","algorithm","subjectPublicKey","ellipticVerify","octstr","explicit","optional","any","bitstr","AlgorithmIdentifier","objid","use","getPreferredHashAlgo","RS","wrap","IV","P","unpack","unwrap","createArrayBuffer","setUint32","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","genPrivateEphemeralKey","recipient","deriveBits","public","webPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","V","derive","ellipticPublicEphemeralKey","secret","webPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","ellipticPrivateEphemeralKey","pkcs5.encode","wrappedKey","aesKW.wrap","pkcs5.decode","aesKW.unwrap","nodeSubtleCrypto","webcrypto","HKDF","inputKey","salt","info","outLen","importedKey","hashAlgoName","computeHMAC","hmacKey","hmacMessage","createHmac","pseudoRandomKey","hashLen","outputKeyingMaterial","roundInput","HKDF_INFO","recipientA","ephemeralSecretKey","sharedSecret","ephemeralPublicKey","hkdfInput","computeHKDF","xr","u1","u2","qSize","n150","rsa","publicParams","curveSize","publicKeyParams","privateKeyParams","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","instance","followLength","checkSupportedCurve","keyAlgo","symmetricAlgo","ECDHSymkey","ecdhX","fromObject","sessionKeyParams","privateParams","algosWithNativeRepresentation","orderedParams","generate","validateParams","algoModule","prefixrandom","repeat","random","pkcs1","pkcs5","aesKW","assign","TYPED_OK","Uint16Array","Int32Array","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","fnUntyped","Buf8","Buf16","Buf32","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","STORED_BLOCK","STATIC_TREES","DYN_TREES","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","MAX_MATCH","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","max_code","d_code","dist","put_short","pending_buf","send_bits","bi_valid","bi_buf","send_code","tree","bi_reverse","code","gen_codes","bl_count","next_code","init_block","dyn_ltree","dyn_dtree","bl_tree","opt_len","static_len","last_lit","matches","bi_windup","smaller","depth","_n2","_m2","pqdownheap","heap_len","compress_block","ltree","dtree","lc","extra","lx","d_buf","l_buf","build_tree","desc","stree","heap_max","base","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","_tr_init","tr_static_init","l_desc","d_desc","bl_desc","_tr_stored_block","stored_len","utils.arraySet","window","copy_block","_tr_align","bi_flush","_tr_flush_block","opt_lenb","static_lenb","max_blindex","level","strm","data_type","black_mask","detect_data_type","build_bl_tree","strategy","lcodes","dcodes","blcodes","rank","send_all_trees","_tr_tally","lit_bufsize","adler32","adler","crcTable","table","makeTable","crc32","MAX_MEM_LEVEL","MIN_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","errorCode","flush_pending","avail_out","pending_out","next_out","total_out","flush_block_only","trees._tr_flush_block","block_start","strstart","put_byte","putShortMSB","read_buf","avail_in","next_in","total_in","longest_match","cur_match","chain_length","max_chain_length","scan","best_len","prev_length","nice_match","limit","w_size","_win","wmask","w_mask","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","_w_size","more","window_size","hash_size","head","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","trees._tr_tally","max_lazy_match","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","max_block_size","pending_buf_size","max_start","DeflateState","status","gzhead","gzindex","method","last_flush","w_bits","hash_bits","utils.Buf16","deflateReset","trees._tr_init","deflateResetKeep","lm_init","deflate","old_flush","beg","hcrc","comment","os","level_flags","bstate","deflate_huff","deflate_rle","trees._tr_align","trees._tr_stored_block","__","_utf8len","utils.Buf8","string2buf","m_pos","buf_len","str_len","ZStream","Deflate","chunkSize","windowBits","memLevel","opt","raw","gzip","ended","zlib_deflate.deflateInit2","dictionary","dict","strings.string2buf","avail","next","tmpDict","dictLength","zlib_deflate.deflateSetDictionary","_dict_set","_mode","zlib_deflate.deflate","onEnd","onData","utils.shrinkBuf","zlib_deflate.deflateEnd","utils.flattenChunks","BAD","TYPE","inflate_fast","_in","_out","hold","here","op","from_source","dmax","wsize","whave","wnext","s_window","lcode","lencode","dcode","distcode","lmask","lenbits","dmask","distbits","top","dolen","dodist","sane","MAXBITS","ENOUGH_LENS","ENOUGH_DISTS","CODES","LENS","DISTS","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","incr","low","sym","root","drop","used","huff","base_index","offs","here_bits","here_op","here_val","extra_index","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","zswap32","InflateState","havedict","flags","check","total","wbits","ncode","nlen","ndist","have","lendyn","distdyn","back","was","inflateReset","utils.Buf32","inflateResetKeep","inflateInit2","inflateReset2","lenfix","distfix","virgin","fixedtables","updatewindow","copy","inflate","put","last_bits","last_op","last_val","hbuf","order","inf_leave","xflags","extra_len","inflateSetDictionary","dictid","GZheader","Inflate","zlib_inflate.inflateInit2","c.Z_OK","zlib_inflate.inflateGetHeader","zlib_inflate.inflateSetDictionary","allowBufError","c.Z_FINISH","c.Z_NO_FLUSH","strings.binstring2buf","zlib_inflate.inflate","c.Z_NEED_DICT","c.Z_BUF_ERROR","c.Z_STREAM_END","c.Z_SYNC_FLUSH","zlib_inflate.inflateEnd","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","remaining","seek","n_bit","n_byte","pi","bufToHex","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","getCRC","updateCRC","updateCRCRun","mtf","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","optDetail","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","CRC32","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","MAX_HUFCODE_BITS","permute","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","multistream","bz","targetStreamCRC","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","verified","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","issuerKeyID","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","writeHashedSubPackets","toHash","stream.slice","stream.clone","writeSubPacket","humanReadable","critical","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","fromBinary","compressionFn","compress_fns","nodeZlib","node_zlib","stream.nodeToWeb","stream.webToNode","pako_zlib","deflateRaw","createDeflateRaw","createDeflate","inflateRaw","createInflateRaw","createInflate","BunzipDecode","SymEncryptedIntegrityProtectedDataPacket","encrypted","sessionKeyAlgorithm","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","AEADEncryptedDataPacket","cipherAlgorithm","aeadAlgorithm","chunkSizeByte","getAEADMode","modeInstance","tagLengthIfDecrypting","tagLengthIfEncrypting","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","latestPromise","cryptedBytes","queuedBytes","finalChunk","cryptedPromise","setInt32","desiredSize","PublicKeyEncryptedSessionKeyPacket","publicKeyID","sessionKey","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","sessionKeyData","S2K","getCount","passphrase","numBytes","rlength","prefixlen","datalen","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","produceKey","encryptionKey","generateSessionKey","associatedData","toEncrypt","PublicKeyPacket","expirationTimeV3","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","startOfSecretKeyData","unparseableKeyMaterial","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","produceEncryptionKey","cleartextWithHash","validParams","generateParams","global","parse5322","inStr","getPos","setPos","initialize","parseString","tokens","semantic","children","ast","parent","child","compareToken","fxnCompare","tok","lit","and","or","prod","invis","colwsp","star","minimum","isUTF8NonAscii","cr","crlf","lf","dquote","htab","sp","vchar","accept","rfc6532","wsp","quotedPair","obsQP","fws","obsFws","ctext","obsCtext","ccontent","cfws","atext","atom","dotAtomText","maybeText","dotAtom","qtext","obsQtext","qcontent","quotedString","address","mailbox","group","nameAddr","addrSpec","displayName","angleAddr","obsAngleAddr","groupList","obsPhrase","collapseWhitespace","mailboxList","obsMboxList","addressList","obsAddrList","obsGroupList","localPart","obsLocalPart","dtext","obsDtext","domainLiteral","domain","obsDomain","rejectTLD","obsNoWsCtl","strict","atInDisplayName","obsRoute","obsDomainList","findNode","stack","findAllNodesNoChildren","names","namesLookup","giveResult","addresses","groupsAndMailboxes","groupOrMailbox","giveResultGroup","giveResultMailbox","simplifyResult","oneResult","partial","groupName","groupResultMailboxes","mailboxes","grabSemantic","aspec","findAllNodes","comments","local","concatComments","startProduction","handleOpts","startAt","defs","isNullUndef","defaults","isObject","parseOneAddress","parseAddressList","parseFrom","parseSender","parseReplyTo","UserIDPacket","email","components","emailAddresses","otherUserID","SecretSubkeyPacket","TrustPacket","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","prefAlgo","primaryUser","getPrimaryUser","selfCertification","getPreferredCurveHashAlgo","getPreferredAlgo","userIDs","defaultAlgo","preferredSenderAlgo","prefPropertyName","recipientPrefs","Boolean","signingKeyPacket","signaturePacket","mergeSignatures","source","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","sanitizeKeyOptions","subkeyDefaults","isValidSigningKeyPacket","isValidEncryptionKeyPacket","isValidDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","signingKeys","isPrivate","signingKey","getSigningKey","certificate","verificationKeys","issuerKeys","getKeys","isRevoked","certifications","certification","valid","verifyCertificate","sourceUser","srcSelfSig","srcRevSig","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","sort","helper.isValidSigningKeyPacket","helper.checkKeyRequirements","helper.isValidEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","revocationCertificate","privateKeys","userSign","certify","verifyAllCertifications","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","fromSecretKeyPacket","pubSubkeyPacket","fromSecretSubkeyPacket","helper.isValidDecryptionKeyPacket","defaultOptions","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","readPrivateKey","readKeys","armoredKeys","binaryKeys","keyIndex","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","sessionKeyObjects","decryptSessionKeys","symEncryptedPacketlist","symEncryptedPacket","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","password","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","getDecryptionKeys","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgorithmName","supported","isAEADSupported","getEncryptionKey","maybeKey","wildcard","encryptionKeyIDs","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","literalDataPacket","existingSigPacketlist","onePassSig","signingKeyID","onePassSignatureList","createSignaturePackets","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","detachedSignature","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","stream.loadStreamsPonyfill","stream.toStream","createMessage","literalDataPacketlist","CleartextMessage","newSignature","hashes","ar","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","oneHeader","createCleartextMessage","checkConfig","helper.generateSecretKey","getRevocationCertificate","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","applyRevocationCertificate","revoke","decryptKey","clonedPrivateKey","passphrases","encryptKey","signingUserIDs","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","streaming","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","signDetached","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","encoding","setEncoding","stream.toNativeReadable","object"],"mappings":";6GAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxBC,cACEC,QACAC,KAAKT,GAAsB,IAAIU,SAAQ,CAACC,EAASC,KAC/CH,KAAKP,GAAsBS,EAC3BF,KAAKN,GAAqBS,CAAM,IAElCH,KAAKT,GAAoBa,OAAM,UAuCnC,SAASC,EAAcC,GACrB,OAAOA,GAASA,EAAMC,WAAaV,MAAMW,QAAQF,EACnD,CAOA,SAASG,EAAOH,GACd,IAAKD,EAAcC,GAAQ,CACzB,MAAMI,EAASJ,EAAMK,YACfC,EAAcF,EAAOE,YAK3B,OAJAF,EAAOE,YAAc,KACnBF,EAAOG,OAAOT,OAAM,eACpBQ,EAAYE,KAAKJ,EAAO,EAEnBA,EAETV,KAAKe,OAAST,CAChB,CAvDAV,EAAYoB,UAAUT,UAAY,WAIhC,YAH2BU,IAAvBjB,KAAKL,KACPK,KAAKL,GAAgB,GAEhB,CACLuB,KAAMC,gBACEnB,KAAKT,GACPS,KAAKL,KAAkBK,KAAKoB,OACvB,CAAEC,WAAOJ,EAAWK,MAAM,GAE5B,CAAED,MAAOrB,KAAKA,KAAKL,MAAkB2B,MAAM,IAGxD,EAEA1B,EAAYoB,UAAUO,UAAYJ,eAAeK,SACzCxB,KAAKT,GACX,MAAMkC,EAASD,EAAKxB,KAAK0B,MAAM1B,KAAKL,KAEpC,OADAK,KAAKoB,OAAS,EACPK,CACT,EAEA7B,EAAYoB,UAAUW,MAAQ,WAC5B,MAAMA,EAAQ,IAAI/B,EAIlB,OAHA+B,EAAMpC,GAAsBS,KAAKT,GAAoBqC,MAAK,KACxDD,EAAME,QAAQ7B,KAAK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ghB,EAAiB7c,GAER,SAAdyvF,GACFzvF,EAAOmvE,EAAiBnvE,GACP,WAAbowF,GAAuBpwF,EAAKqwF,YAAYD,GACrCpwF,GAES,QAAdyvF,GAAsC,aAAf5zF,EAClBy0F,EAAwBtwF,GAE1BA,CACT,CAUA,SAAS4vF,GAAYl4F,EAAQ+X,GAC3B/X,EAAOsI,KAAOwc,EAAqB/M,EAAQ09D,QAAQn2E,QAAQI,MAAOsH,EAAUC,WACpEoe,EAAYrlB,EAAOsI,KAAMrB,EAAU,CACvCE,cAAc,IAEhB,MAAMlI,EAAS+lB,EAAiB/d,GAChC,UAEQke,EAAiBne,GAAU67C,GAAKA,UAChC5jD,EAAOsB,QACb,MAAOqC,SACD3D,EAAOuB,MAAMoC,MAGzB,CASA,SAASg0F,GAAaiC,EAAQ/3C,EAAQ79B,GACpC,OAAQ69B,GACN,IAAK,SACH,OAAO+3C,EACT,IAAK,UACH,OAAOA,EAAOlhF,MAAMsL,GACtB,IAAK,SACH,OAAO41E,EAAOx4F,QAChB,QACE,MAAUoB,MAAM,sBAAsBq/C,GAE5C"} \ No newline at end of file +{"version":3,"file":"openpgp.min.mjs","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/enums.js","../../src/config/config.js","../../src/util.js","../../src/encoding/base64.js","../../src/encoding/armor.js","../../src/crypto/cipher/index.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@noble/ciphers/esm/_assert.js","../../node_modules/@noble/ciphers/esm/utils.js","../../node_modules/@noble/ciphers/esm/_polyval.js","../../node_modules/@noble/ciphers/esm/aes.js","../../src/crypto/mode/cfb.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../../../../src/crypto/biginteger.ts","../../src/crypto/random.js","../../../../../src/crypto/public_key/prime.ts","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../node_modules/@openpgp/tweetnacl/cryptoBrowser.js","../../node_modules/@openpgp/tweetnacl/nacl-fast.js","../../src/type/oid.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../src/type/s2k/argon2.js","../../src/type/s2k/generic.js","../../src/type/s2k/index.js","../../node_modules/fflate/esm/browser.js","../../src/packet/literal_data.js","../../src/type/keyid.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/marker.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/packet/trust.js","../../src/packet/padding.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n Object.setPrototypeOf(this, ArrayStream.prototype);\n\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","/* eslint-disable no-prototype-builtins */\nimport { isArrayStream } from './writer.js';\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n // try and detect a node native stream without having to import its class\n if (input &&\n !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&\n typeof input._read === 'function' && typeof input._readableState === 'object') {\n throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isUint8Array, isStream, isArrayStream } from './util.js';\nimport * as streams from './streams.js';\n\nconst doneReadingSet = new WeakSet();\n/**\n * The external buffer is used to store values that have been peeked or unshifted from the original stream.\n * Because of how streams are implemented, such values cannot be \"put back\" in the original stream,\n * but they need to be returned first when reading from the input again.\n */\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = () => {};\n return;\n }\n let streamType = isStream(input);\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isStream, isArrayStream, isUint8Array, concatUint8Array } from './util.js';\nimport { Reader, externalBuffer } from './reader.js';\nimport { ArrayStream, Writer } from './writer.js';\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n }\n lastBytes = returnValue;\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input)) {\n return input.subarray(begin, end === Infinity ? input.length : end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n const cancelled = await input.cancel(reason);\n // the stream is not always cancelled at this point, so we wait some more\n await new Promise(setTimeout);\n return cancelled;\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n\nexport {\n ArrayStream,\n toStream,\n concatStream,\n concat,\n getReader,\n getWriter,\n pipe,\n transformRaw,\n transform,\n transformPair,\n parse,\n clone,\n passiveClone,\n slice,\n readToEnd,\n cancel,\n fromAsync\n};\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'nistP256': 'nistP256',\n /** @deprecated use `nistP256` instead */\n 'p256': 'nistP256',\n\n /** NIST P-384 Curve */\n 'nistP384': 'nistP384',\n /** @deprecated use `nistP384` instead */\n 'p384': 'nistP384',\n\n /** NIST P-521 Curve */\n 'nistP521': 'nistP521',\n /** @deprecated use `nistP521` instead */\n 'p521': 'nistP521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519Legacy',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519Legacy',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519Legacy',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519Legacy',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n argon2: 4,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11,\n sha3_256: 12,\n sha3_512: 14\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n gcm: 3,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n padding: 21\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuerKeyID: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34,\n preferredCipherSuites: 39\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4,\n seipdv2: 8\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha512,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * This option is applicable to:\n * - key generation (encryption key preferences),\n * - password-based message encryption, and\n * - private key encryption.\n * In the case of message encryption using public keys, the encryption key preferences are respected instead.\n * Note: not all OpenPGP implementations are compatible with this option.\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)\n * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,\n * this option must be set, otherwise key parsing and/or key decryption will fail.\n * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys\n * will be processed incorrectly.\n */\n parseAEADEncryptedV4KeysAsLegacy: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.gcm,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use v6 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v6Keys\n */\n v6Keys: false,\n /**\n * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).\n * These are non-standard entities, which in the crypto-refresh have been superseded\n * by v6 keys and v6 signatures, respectively.\n * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,\n * hence parsing them might be necessary in some cases.\n */\n enableParsingV5Entities: false,\n /**\n * S2K (String to Key) type, used for key derivation in the context of secret key encryption\n * and password-encrypted data. Weaker s2k options are not allowed.\n * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it\n * (pending standardisation).\n * @memberof module:config\n * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}\n */\n s2kType: enums.s2k.iterated,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:\n * Iteration Count Byte for Iterated and Salted S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.\n * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:\n * Argon2 parameters for S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.\n * Default settings correspond to the second recommendation from RFC9106 (\"uniformly safe option\"),\n * to ensure compatibility with memory-constrained environments.\n * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.\n * @memberof module:config\n * @property {Object} params\n * @property {Integer} params.passes - number of iterations t\n * @property {Integer} params.parallelism - degree of parallelism p\n * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.\n */\n s2kArgon2Params: {\n passes: 3,\n parallelism: 4, // lanes\n memoryExponent: 16 // 64 MiB of RAM\n },\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:\n * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL\n * (see https://efail.de/).\n * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.\n *\n * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n /**\n * Allow using keys that do not have any key flags set.\n * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages\n * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).\n * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.\n * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.\n */\n allowMissingKeyFlags: false,\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).\n * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur\n * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of\n * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.\n * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.\n */\n nonDeterministicSignaturesViaNotation: true,\n /**\n * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * @memberof module:config\n * @property {Boolean} useEllipticFallback\n */\n useEllipticFallback: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { createRequire } from 'module'; // Must be stripped in browser built\nimport enums from './enums';\nimport defaultConfig from './config';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n nodeRequire: createRequire(import.meta.url),\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n /**\n * Load noble-curves lib on demand and return the requested curve function\n * @param {enums.publicKey} publicKeyAlgo\n * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)\n * @returns curve implementation\n * @throws on unrecognized curve, or curve not implemented by noble-curve\n */\n getNobleCurve: async (publicKeyAlgo, curveName) => {\n if (!defaultConfig.useEllipticFallback) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n\n const { nobleCurves } = await import('./crypto/public_key/elliptic/noble_curves');\n switch (publicKeyAlgo) {\n case enums.publicKey.ecdh:\n case enums.publicKey.ecdsa: {\n const curve = nobleCurves.get(curveName);\n if (!curve) throw new Error('Unsupported curve');\n return curve;\n }\n case enums.publicKey.x448:\n return nobleCurves.get('x448');\n case enums.publicKey.ed448:\n return nobleCurves.get('ed448');\n default:\n throw new Error('Unsupported curve');\n }\n },\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,\n // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed\n // has not been authenticated (yet).\n // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.\n // Also, AEAD is also not affected.\n return util.readExactSubarray(bytes, 2, 2 + bytelen);\n },\n\n /**\n * Read exactly `end - start` bytes from input.\n * This is a stricter version of `.subarray`.\n * @param {Uint8Array} input - Input data to parse\n * @returns {Uint8Array} subarray of size always equal to `end - start`\n * @throws if the input array is too short.\n */\n readExactSubarray: function (input, start, end) {\n if (input.length < (end - start)) {\n throw new Error('Input array too short');\n }\n return input.subarray(start, end);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n if (bytes.length > length) {\n throw new Error('Input array too long');\n }\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const hexAlphabet = '0123456789abcdef';\n let s = '';\n bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });\n return s;\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography API.\n * @returns {Object} The SubtleCrypto API\n * @throws if the API is not available\n */\n getWebCrypto: function() {\n const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n // Fallback for Node 16, which does not expose WebCrypto as a global\n const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;\n if (!webCrypto) {\n throw new Error('The WebCrypto API is not available');\n }\n return webCrypto;\n },\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return this.nodeRequire('crypto');\n },\n\n getNodeZlib: function() {\n return this.nodeRequire('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (this.nodeRequire('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = this.nodeRequire('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n /**\n * Test email format to ensure basic compliance:\n * - must include a single @\n * - no control or space unicode chars allowed\n * - no backslash and square brackets (as the latter can mess with the userID parsing)\n * - cannot end with a punctuation char\n * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,\n * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).\n */\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^[^\\p{C}\\p{Z}@<>\\\\]+@[^\\p{C}\\p{Z}@<>\\\\]+[^\\p{C}\\p{Z}\\p{P}]$/u;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n }\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n }\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n }\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n }\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n }\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n }\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Remove the (optional) checksum from an armored message.\n * @param {String} text - OpenPGP armored message\n * @returns {String} The body of the armored message.\n * @private\n */\nfunction removeChecksum(text) {\n let body = text;\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n }\n\n return body;\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n const data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== enums.armor.signed) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === enums.armor.signed) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const body = removeChecksum(parts[0].slice(0, -1));\n await writer.write(body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum\n * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug\n // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)\n const maybeBodyClone = emitChecksum && stream.passiveClone(body);\n\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push(hash ? `Hash: ${hash}\\n\\n` : '\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","import enums from '../../enums';\n\nexport async function getLegacyCipher(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n throw new Error('Not a legacy cipher');\n case enums.symmetric.cast5:\n case enums.symmetric.blowfish:\n case enums.symmetric.twofish:\n case enums.symmetric.tripledes: {\n const { legacyCiphers } = await import('./legacy_ciphers');\n const cipher = legacyCiphers.get(algo);\n if (!cipher) {\n throw new Error('Unsupported cipher algorithm');\n }\n return cipher;\n }\n default:\n throw new Error('Unsupported cipher algorithm');\n }\n}\n\n/**\n * Get block size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherBlockSize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 16;\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n case enums.symmetric.tripledes:\n return 8;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherKeySize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n return 16;\n case enums.symmetric.aes192:\n case enums.symmetric.tripledes:\n return 24;\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 32;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get block and key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nexport function getCipherParams(algo) {\n return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };\n}\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction nobleHash(nobleHashName, webCryptoHashName) {\n const getNobleHash = async () => {\n const { nobleHashes } = await import('./noble_hashes');\n const hash = nobleHashes.get(nobleHashName);\n if (!hash) throw new Error('Unsupported hash');\n return hash;\n };\n\n return async function(data) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hash = await getNobleHash();\n\n const hashInstance = hash.create();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => hashInstance.digest());\n } else if (webCrypto && webCryptoHashName) {\n return new Uint8Array(await webCrypto.digest(webCryptoHashName, data));\n } else {\n const hash = await getNobleHash();\n\n return hash(data);\n }\n };\n}\n\nexport default {\n\n /** @see module:md5 */\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'),\n sha224: nodeHash('sha224') || nobleHash('sha224'),\n sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'),\n sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'),\n sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'),\n ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'),\n sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'),\n sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'),\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n case enums.hash.sha3_256:\n return this.sha3_256(data);\n case enums.hash.sha3_512:\n return this.sha3_512(data);\n default:\n throw new Error('Unsupported hash function');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n case enums.hash.sha3_256:\n return 32;\n case enums.hash.sha3_512:\n return 64;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, copyBytes, createView, toBytes, u32 } from './utils.js';\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\nclass GHASH {\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n this.blockLen = BLOCK_SIZE;\n this.outputLen = BLOCK_SIZE;\n this.s0 = 0;\n this.s1 = 0;\n this.s2 = 0;\n this.s3 = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\nclass Polyval extends GHASH {\n constructor(key, expectedLength) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\nfunction wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key, expectedLength) => hashCons(key, expectedLength);\n return hashC;\n}\nexport const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));\nexport const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));\n//# sourceMappingURL=_polyval.js.map","// prettier-ignore\nimport { bytes as abytes } from './_assert.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { clean, concatBytes, copyBytes, createView, equalBytes, isAligned32, setBigUint64, u32, u8, wrapCipher, } from './utils.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (dst === undefined)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n if (!isAligned32(dst))\n throw new Error('unaligned dst');\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n const out = getDst(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD == null ? 0 : AAD.length;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(aadLength * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(key);\n abytes(nonce);\n if (AAD !== undefined)\n abytes(AAD);\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\n// Private, unsafe low-level methods. Can change at any time.\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n */\n\nimport { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../../util';\nimport enums from '../../enums';\nimport { getLegacyCipher, getCipherParams } from '../cipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (nodeCrypto && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nclass WebCryptoEncryptor {\n constructor(algo, key, iv) {\n const { blockSize } = getCipherParams(algo);\n this.key = key;\n this.prevBlock = iv;\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n this.zeroBlock = new Uint8Array(this.blockSize);\n }\n\n static async isSupported(algo) {\n const { keySize } = getCipherParams(algo);\n return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])\n .then(() => true, () => false);\n }\n\n async _runCBC(plaintext, nonZeroIV) {\n const mode = 'AES-CBC';\n this.keyRef = this.keyRef || await webCrypto.importKey('raw', this.key, mode, false, ['encrypt']);\n const ciphertext = await webCrypto.encrypt(\n { name: mode, iv: nonZeroIV || this.zeroBlock },\n this.keyRef,\n plaintext\n );\n return new Uint8Array(ciphertext).subarray(0, plaintext.length);\n }\n\n async encryptChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const plaintext = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n const toEncrypt = util.concatUint8Array([\n this.prevBlock,\n plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block \"early\", since we only need to xor the plaintext and pass it over as prevBlock\n ]);\n\n const encryptedBlocks = await this._runCBC(toEncrypt);\n xorMut(encryptedBlocks, plaintext);\n this.prevBlock = encryptedBlocks.slice(-this.blockSize);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return encryptedBlocks;\n }\n\n this.i += added.length;\n let encryptedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n const curBlock = this.nextBlock;\n encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n this.prevBlock = encryptedBlock.slice();\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n encryptedBlock = new Uint8Array();\n }\n\n return encryptedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n this.nextBlock = this.nextBlock.subarray(0, this.i);\n const curBlock = this.nextBlock;\n const encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n result = encryptedBlock.subarray(0, curBlock.length);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.keyRef = null;\n this.key = null;\n }\n\n async encrypt(plaintext) {\n // plaintext is internally padded to block length before encryption\n const encryptedWithPadding = await this._runCBC(\n util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]),\n this.iv\n );\n // drop encrypted padding\n const ct = encryptedWithPadding.subarray(0, plaintext.length);\n xorMut(ct, plaintext);\n this.clearSensitiveData();\n return ct;\n }\n}\n\nclass NobleStreamProcessor {\n constructor(forEncryption, algo, key, iv) {\n this.forEncryption = forEncryption;\n const { blockSize } = getCipherParams(algo);\n this.key = nobleAesHelpers.expandKeyLE(key);\n\n if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers\n this.prevBlock = getUint32Array(iv);\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n }\n\n _runCFB(src) {\n const src32 = getUint32Array(src);\n const dst = new Uint8Array(src.length);\n const dst32 = getUint32Array(dst);\n for (let i = 0; i + 4 <= dst32.length; i += 4) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);\n }\n return dst;\n }\n\n async processChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const toProcess = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n\n const processedBlocks = this._runCFB(toProcess);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return processedBlocks;\n }\n\n this.i += added.length;\n\n let processedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n processedBlock = this._runCFB(this.nextBlock);\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n processedBlock = new Uint8Array();\n }\n\n return processedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n const processedBlock = this._runCFB(this.nextBlock);\n\n result = processedBlock.subarray(0, this.i);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.key.fill(0);\n }\n}\n\n\nasync function aesEncrypt(algo, key, pt, iv) {\n if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys\n const cfb = new WebCryptoEncryptor(algo, key, iv);\n return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);\n } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream\n const cfb = new NobleStreamProcessor(true, algo, key, iv);\n return stream.transform(pt, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).encrypt(pt);\n}\n\nasync function aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new NobleStreamProcessor(false, algo, key, iv);\n return stream.transform(ct, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).decrypt(ct);\n}\n\nfunction xorMut(a, b) {\n const aLength = Math.min(a.length, b.length);\n for (let i = 0; i < aLength; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nconst getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt) {\n return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n */\n\nimport { ctr as nobleAesCtr } from '@noble/ciphers/aes';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const keyRef = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, keyRef, pt);\n return new Uint8Array(ct);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt, iv) {\n return nobleAesCtr(key, iv).encrypt(pt);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport { getCipherParams } from '../cipher';\nimport util from '../../util';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n const { keySize } = getCipherParams(cipher);\n // sanity checks\n if (!util.isAES(cipher) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let maxNtz = 0;\n\n // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,\n // hence its execution cannot be broken up.\n // As a result, WebCrypto cannot currently be used for `encipher`.\n const aes = nobleAesCbc(key, zeroBlock, { disablePadding: true });\n const encipher = block => aes.encrypt(block);\n const decipher = block => aes.decrypt(block);\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables() {\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n */\n\nimport { gcm as nobleAesGcm } from '@noble/ciphers/aes';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages\n const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\\/13\\.\\d(\\.\\d)* Safari/) ||\n navigator.userAgent.match(/Version\\/(13|14)\\.\\d(\\.\\d)* Mobile\\/\\S* Safari/);\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && !pt.length) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n try {\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n } catch (e) {\n if (e.name === 'OperationError') {\n throw new Error('Authentication tag mismatch');\n }\n }\n }\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n },\n\n decrypt: async function(ct, iv, adata) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","// Operations are not constant time, but we try and limit timing leakage where we can\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport function uint8ArrayToBigInt(bytes: Uint8Array) {\n const hexAlphabet = '0123456789ABCDEF';\n let s = '';\n bytes.forEach(v => {\n s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];\n });\n return BigInt('0x0' + s);\n}\n\nexport function mod(a: bigint, m: bigint) {\n const reduced = a % m;\n return reduced < _0n ? reduced + m : reduced;\n}\n\n/**\n * Compute modular exponentiation using square and multiply\n * @param {BigInt} a - Base\n * @param {BigInt} e - Exponent\n * @param {BigInt} n - Modulo\n * @returns {BigInt} b ** e mod n.\n */\nexport function modExp(b: bigint, e: bigint, n: bigint) {\n if (n === _0n) throw Error('Modulo cannot be zero');\n if (n === _1n) return BigInt(0);\n if (e < _0n) throw Error('Unsopported negative exponent');\n\n let exp = e;\n let x = b;\n\n x %= n;\n let r = BigInt(1);\n while (exp > _0n) {\n const lsb = exp & _1n;\n exp >>= _1n; // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n; // Square\n }\n return r;\n}\n\n\nfunction abs(x: bigint) {\n return x >= _0n ? x : -x;\n}\n\n/**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a and b, compute (x, y) such that ax + by = gdc(a, b).\n * Negative numbers are also supported.\n * @param {BigInt} a - First operand\n * @param {BigInt} b - Second operand\n * @returns {{ gcd, x, y: bigint }}\n */\nfunction _egcd(aInput: bigint, bInput: bigint) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n // Deal with negative numbers: run algo over absolute values,\n // and \"move\" the sign to the returned x and/or y.\n // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers\n let a = abs(aInput);\n let b = abs(bInput);\n const aNegated = aInput < _0n;\n const bNegated = bInput < _0n;\n\n while (b !== _0n) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: aNegated ? -xPrev : xPrev,\n y: bNegated ? -yPrev : yPrev,\n gcd: a\n };\n}\n\n/**\n * Compute the inverse of `a` modulo `n`\n * Note: `a` and and `n` must be relatively prime\n * @param {BigInt} a\n * @param {BigInt} n - Modulo\n * @returns {BigInt} x such that a*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\nexport function modInv(a: bigint, n: bigint) {\n const { gcd, x } = _egcd(a, n);\n if (gcd !== _1n) {\n throw new Error('Inverse does not exist');\n }\n return mod(x + n, n);\n}\n\n/**\n * Compute greatest common divisor between this and n\n * @param {BigInt} aInput - Operand\n * @param {BigInt} bInput - Operand\n * @returns {BigInt} gcd\n */\nexport function gcd(aInput: bigint, bInput: bigint) {\n let a = aInput;\n let b = bInput;\n while (b !== _0n) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\n/**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\nexport function bigIntToNumber(x: bigint) {\n const number = Number(x);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n}\n\n/**\n * Get value of i-th bit\n * @param {BigInt} x\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\nexport function getBit(x:bigint, i: number) {\n const bit = (x >> BigInt(i)) & _1n;\n return bit === _0n ? 0 : 1;\n}\n\n/**\n * Compute bit length\n */\nexport function bitLength(x: bigint) {\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = x < _0n ? BigInt(-1) : _0n;\n let bitlen = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _1n) !== target) {\n bitlen++;\n }\n return bitlen;\n}\n\n/**\n * Compute byte length\n */\nexport function byteLength(x: bigint) {\n const target = x < _0n ? BigInt(-1) : _0n;\n const _8n = BigInt(8);\n let len = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _8n) !== target) {\n len++;\n }\n return len;\n}\n\n/**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\nexport function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = x.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? length - rawLength : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n */\nimport { byteLength, mod, uint8ArrayToBigInt } from './biginteger';\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto?.webcrypto;\n if (webcrypto?.getRandomValues) {\n const buf = new Uint8Array(length);\n return webcrypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n}\n\n/**\n * Create a secure random BigInt that is greater than or equal to min and less than max.\n * @param {bigint} min - Lower bound, included\n * @param {bigint} max - Upper bound, excluded\n * @returns {bigint} Random BigInt.\n * @async\n */\nexport function getRandomBigInteger(min, max) {\n if (max < min) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max - min;\n const bytes = byteLength(modulus);\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));\n return mod(r, modulus) + min;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n */\nimport { bigIntToNumber, bitLength, gcd, getBit, mod, modExp } from '../biginteger';\nimport { getRandomBigInteger } from '../random';\n\nconst _1n = BigInt(1);\n\n/**\n * Generate a probably prime random number\n * @param bits - Bit length of the prime\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function randomProbablePrime(bits: number, e: bigint, k: number) {\n const _30n = BigInt(30);\n const min = _1n << BigInt(bits - 1);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n let n = getRandomBigInteger(min, min << _1n);\n let i = bigIntToNumber(mod(n, _30n));\n\n do {\n n += BigInt(adds[i]);\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (bitLength(n) > bits) {\n n = mod(n, min << _1n); n += min;\n i = bigIntToNumber(mod(n, _30n));\n }\n } while (!isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param n - Number to test\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function isProbablePrime(n: bigint, e: bigint, k: number) {\n if (e && gcd(n - _1n, e) !== _1n) {\n return false;\n }\n if (!divisionTest(n)) {\n return false;\n }\n if (!fermat(n)) {\n return false;\n }\n if (!millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param n - Number to test\n * @param b - Optional Fermat test base\n */\nexport function fermat(n: bigint, b = BigInt(2)) {\n return modExp(b, n - _1n, n) === _1n;\n}\n\nexport function divisionTest(n: bigint) {\n const _0n = BigInt(0);\n return smallPrimes.every(m => mod(n, m) !== _0n);\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n].map(n => BigInt(n));\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param n - Number to test\n * @param k - Optional number of iterations of Miller-Rabin test\n * @param rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport function millerRabin(n: bigint, k: number, rand?: () => bigint) {\n const len = bitLength(n);\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n - _1n; // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!getBit(n1, s)) { s++; }\n const d = n >> BigInt(s);\n\n for (; k > 0; k--) {\n const a = rand ? rand() : getRandomBigInteger(BigInt(2), n1);\n\n let x = modExp(a, d, n);\n if (x === _1n || x === n1) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = mod(x * x, n);\n\n if (x === _1n) {\n return false;\n }\n if (x === n1) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n */\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\nimport { bigIntToNumber, bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\nimport hash from '../hash';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst _1n = BigInt(1);\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (hash.getHashByteLength(hashAlgo) >= n.length) {\n // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error\n // e.g. if a 512-bit RSA key is used with a SHA-512 digest.\n // The size limit is actually slightly different but here we only care about throwing\n // on common key sizes.\n throw new Error('Digest size cannot exceed key modulus size');\n }\n\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n e = BigInt(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return jwkToPrivate(jwk, e);\n } else if (util.getNodeCrypto()) {\n const opts = {\n modulusLength: bits,\n publicExponent: bigIntToNumber(e),\n publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },\n privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }\n };\n const jwk = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {\n if (err) {\n reject(err);\n } else {\n resolve(jwkPrivateKey);\n }\n });\n });\n return jwkToPrivate(jwk, e);\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = randomProbablePrime(bits - (bits >> 1), e, 40);\n p = randomProbablePrime(bits >> 1, e, 40);\n n = p * q;\n } while (bitLength(n) !== bits);\n\n const phi = (p - _1n) * (q - _1n);\n\n if (q < p) {\n [p, q] = [q, p];\n }\n\n return {\n n: bigIntToUint8Array(n),\n e: bigIntToUint8Array(e),\n d: bigIntToUint8Array(modInv(e, phi)),\n p: bigIntToUint8Array(p),\n q: bigIntToUint8Array(q),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: bigIntToUint8Array(modInv(p, q))\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n n = uint8ArrayToBigInt(n);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n\n // expect pq = n\n if ((p * q) !== n) {\n return false;\n }\n\n const _2n = BigInt(2);\n // expect p*u = 1 mod q\n u = uint8ArrayToBigInt(u);\n if (mod(p * u, q) !== BigInt(1)) {\n return false;\n }\n\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));\n const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r * d * e;\n\n const areInverses = mod(rde, p - _1n) === r && mod(rde, q - _1n) === r;\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n n = uint8ArrayToBigInt(n);\n const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));\n d = uint8ArrayToBigInt(d);\n return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n\n const jwk = await privateToJWK(n, e, d, p, q, u);\n return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n n = uint8ArrayToBigInt(n);\n s = uint8ArrayToBigInt(s);\n e = uint8ArrayToBigInt(e);\n if (s >= n) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));\n const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1' };\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n\n try {\n return verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n n = uint8ArrayToBigInt(n);\n data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));\n e = uint8ArrayToBigInt(e);\n if (data >= n) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n data = uint8ArrayToBigInt(data);\n n = uint8ArrayToBigInt(n);\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n u = uint8ArrayToBigInt(u);\n if (data >= n) {\n throw new Error('Data too large.');\n }\n const dq = mod(d, q - _1n); // d mod (q-1)\n const dp = mod(d, p - _1n); // d mod (p-1)\n\n const unblinder = getRandomBigInteger(BigInt(2), n);\n const blinder = modExp(modInv(unblinder, n), e, n);\n data = mod(data * blinder, n);\n\n const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p\n const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q\n const h = mod(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h * p + mp; // result < n due to relations above\n\n result = mod(result * unblinder, n);\n\n return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const pNum = uint8ArrayToBigInt(p);\n const qNum = uint8ArrayToBigInt(q);\n const dNum = uint8ArrayToBigInt(d);\n\n let dq = mod(dNum, qNum - _1n); // d mod (q-1)\n let dp = mod(dNum, pNum - _1n); // d mod (p-1)\n dp = bigIntToUint8Array(dp);\n dq = bigIntToUint8Array(dq);\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n\n/** Convert JWK private key to OpenPGP private key params */\nfunction jwkToPrivate(jwk, e) {\n return {\n n: b64ToUint8Array(jwk.n),\n e: bigIntToUint8Array(e),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n */\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\nconst _1n = BigInt(1);\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n const padded = emeEncode(data, byteLength(p));\n const m = uint8ArrayToBigInt(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = getRandomBigInteger(_1n, p - _1n);\n return {\n c1: bigIntToUint8Array(modExp(g, k, p)),\n c2: bigIntToUint8Array(mod(modExp(y, k, p) * m, p))\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n c1 = uint8ArrayToBigInt(c1);\n c2 = uint8ArrayToBigInt(c2);\n p = uint8ArrayToBigInt(p);\n x = uint8ArrayToBigInt(x);\n\n const padded = mod(modInv(modExp(c1, x, p), p) * c2, p);\n return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = BigInt(bitLength(p));\n const _1023n = BigInt(1023);\n if (pSize < _1023n) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (modExp(g, p - _1n, p) !== _1n) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n let i = BigInt(1);\n const _2n = BigInt(2);\n const threshold = _2n << BigInt(17); // we want order > threshold\n while (i < threshold) {\n res = mod(res * g, p);\n if (res === _1n) {\n return false;\n }\n i++;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const r = getRandomBigInteger(_2n << (pSize - _1n), _2n << pSize); // draw r of same size as p-1\n const rqx = (p - _1n) * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","// declare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import { crypto } from './crypto.js';\n\n'use strict';\nconst nacl = {};\nexport default nacl;\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n if (crypto && crypto.getRandomValues) {\n // Browsers and Node v16+\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n})();\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nconst knownOIDs = {\n '2a8648ce3d030107': enums.curve.nistP256,\n '2b81040022': enums.curve.nistP384,\n '2b81040023': enums.curve.nistP521,\n '2b8104000a': enums.curve.secp256k1,\n '2b06010401da470f01': enums.curve.ed25519Legacy,\n '2b060104019755010501': enums.curve.curve25519Legacy,\n '2b2403030208010107': enums.curve.brainpoolP256r1,\n '2b240303020801010b': enums.curve.brainpoolP384r1,\n '2b240303020801010d': enums.curve.brainpoolP512r1\n};\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {enums.curve} String with the canonical name of the curve\n * @throws if unknown\n */\n getName() {\n const name = knownOIDs[this.toHex()];\n if (!name) {\n throw new Error('Unknown curve object identifier.');\n }\n\n return name;\n }\n}\n\nexport default OID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\n// unknown packet types are handled differently depending on the packet criticality\nexport class UnknownPacketError extends UnsupportedError {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnknownPacketError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n */\n\nimport ed25519 from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\nimport { b64ToUint8Array, uint8ArrayToB64 } from '../../../encoding/base64';\n\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n A: new Uint8Array(b64ToUint8Array(publicKey.x)),\n seed: b64ToUint8Array(privateKey.d, true)\n };\n } catch (err) {\n if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux\n throw err;\n }\n const seed = getRandomBytes(getPayloadSize(algo));\n const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const seed = ed448.utils.randomPrivateKey();\n const A = ed448.getPublicKey(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = privateKeyToJWK(algo, publicKey, privateKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);\n\n const signature = new Uint8Array(\n await webCrypto.sign('Ed25519', key, hashed)\n );\n\n return { RS: signature };\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = ed25519.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const signature = ed448.sign(hashed, privateKey);\n return { RS: signature };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = publicKeyToJWK(algo, publicKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);\n const verified = await webCrypto.verify('Ed25519', key, RS, hashed);\n return verified;\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n return ed25519.sign.detached.verify(hashed, RS, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n return ed448.verify(RS, hashed, publicKey);\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented\n */\n const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n\n const publicKey = ed448.getPublicKey(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n default:\n return false;\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return 32;\n\n case enums.publicKey.ed448:\n return 57;\n\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n case enums.publicKey.ed448:\n return enums.hash.sha512;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n\nconst publicKeyToJWK = (algo, publicKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = {\n kty: 'OKP',\n crv: 'Ed25519',\n x: uint8ArrayToB64(publicKey, true),\n ext: true\n };\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n\nconst privateKeyToJWK = (algo, publicKey, privateKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = publicKeyToJWK(algo, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n */\n\nimport { aeskw as nobleAesKW } from '@noble/ciphers/aes';\nimport { getCipherParams } from './cipher';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n/**\n * AES key wrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} dataToWrap\n * @returns {Uint8Array} wrapped key\n */\nexport async function wrap(algo, key, dataToWrap) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n try {\n const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);\n // Import data as HMAC key, as it has no key length requirements\n const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });\n return new Uint8Array(wrapped);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n\n return nobleAesKW(key).encrypt(dataToWrap);\n}\n\n/**\n * AES key unwrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} wrappedData\n * @returns {Uint8Array} unwrapped data\n */\nexport async function unwrap(algo, key, wrappedData) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let wrappingKey;\n try {\n wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n return nobleAesKW(key).decrypt(wrappedData);\n }\n\n try {\n const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));\n } catch (err) {\n if (err.name === 'OperationError') {\n throw new Error('Key Data Integrity failed');\n }\n throw err;\n }\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n\nexport default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport x25519 from '@openpgp/tweetnacl';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport computeHKDF from '../../hkdf';\nimport { getCipherParams } from '../../cipher';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519'),\n x448: util.encodeUTF8('OpenPGP X448')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = x25519.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const k = x448.utils.randomPrivateKey();\n const A = x448.getPublicKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = x25519.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const publicKey = x448.getPublicKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.x25519:\n return 32;\n\n case enums.publicKey.x448:\n return 56;\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Generate shared secret and ephemeral public key for encryption\n * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret\n * @async\n */\nexport async function generateEphemeralEncryptionMaterial(algo, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo));\n const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const { publicKey: ephemeralPublicKey } = x25519.box.keyPair.fromSecretKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const ephemeralSecretKey = x448.utils.randomPrivateKey();\n const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * x25519 and x448 produce an all-zero value when given as input a point with small order.\n * This does not lead to a security issue in the context of ECDH, but it is still unexpected,\n * hence we throw.\n * @param {Uint8Array} sharedSecret\n */\nfunction assertNonZeroArray(sharedSecret) {\n let acc = 0;\n for (let i = 0; i < sharedSecret.length; i++) {\n acc |= sharedSecret[i];\n }\n if (acc === 0) {\n throw new Error('Unexpected low order point');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n */\nimport nacl from '@openpgp/tweetnacl';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { UnsupportedError } from '../../../packet/packet';\nimport { generate as eddsaGenerate } from './eddsa';\nimport { generate as ecdhXGenerate } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n [enums.curve.nistP256]: 'P-256',\n [enums.curve.nistP384]: 'P-384',\n [enums.curve.nistP521]: 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,\n [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n [enums.curve.nistP256]: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.nistP256],\n web: webCurves[enums.curve.nistP256],\n payloadSize: 32,\n sharedSize: 256,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP384]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.nistP384],\n web: webCurves[enums.curve.nistP384],\n payloadSize: 48,\n sharedSize: 384,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP521]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.nistP521],\n web: webCurves[enums.curve.nistP521],\n payloadSize: 66,\n sharedSize: 528,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.secp256k1]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.secp256k1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.ed25519Legacy]: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.curve25519Legacy]: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.brainpoolP256r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.brainpoolP256r1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP384r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.brainpoolP384r1],\n payloadSize: 48,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP512r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.brainpoolP512r1],\n payloadSize: 64,\n wireFormatLeadingByte: 0x04\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName) {\n try {\n this.name = oidOrName instanceof OID ?\n oidOrName.getName() :\n enums.write(enums.curve,oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n const params = curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node;\n this.web = params.web;\n this.payloadSize = params.payloadSize;\n this.sharedSize = params.sharedSize;\n this.wireFormatLeadingByte = params.wireFormatLeadingByte;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === enums.curve.curve25519Legacy) {\n this.type = 'curve25519Legacy';\n } else if (this.name === enums.curve.ed25519Legacy) {\n this.type = 'ed25519Legacy';\n }\n }\n\n async genKeyPair() {\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name, this.wireFormatLeadingByte);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n return jsGenKeyPair(this.name);\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519Legacy': {\n // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3\n const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);\n const privateKey = k.slice().reverse();\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n case 'ed25519Legacy': {\n const { seed: privateKey, A } = await eddsaGenerate(enums.publicKey.ed25519);\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n default:\n return jsGenKeyPair(this.name);\n }\n }\n}\n\nasync function generate(curveName) {\n const curve = new CurveWithOID(curveName);\n const { oid, hash, cipher } = curve;\n const keyPair = await curve.genKeyPair();\n return {\n oid,\n Q: keyPair.publicKey,\n secret: util.leftPad(keyPair.privateKey, curve.payloadSize),\n hash,\n cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[oid.getName()].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n [enums.curve.nistP256]: true,\n [enums.curve.nistP384]: true,\n [enums.curve.nistP521]: true,\n [enums.curve.secp256k1]: true,\n [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,\n [enums.curve.brainpoolP256r1]: true,\n [enums.curve.brainpoolP384r1]: true,\n [enums.curve.brainpoolP512r1]: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === enums.curve.curve25519Legacy) {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n /*\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = nobleCurve.getPublicKey(d, false);\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check whether the public point has a valid encoding.\n * NB: this function does not check e.g. whether the point belongs to the curve.\n */\nfunction checkPublicPointEnconding(curve, V) {\n const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;\n\n const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;\n\n if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {\n throw new Error('Invalid point encoding');\n }\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\nasync function jsGenKeyPair(name) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n const privateKey = nobleCurve.utils.randomPrivateKey();\n const publicKey = nobleCurve.getPublicKey(privateKey, false);\n return { publicKey, privateKey };\n}\n\nasync function webGenKeyPair(name, wireFormatLeadingByte) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk, wireFormatLeadingByte) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = wireFormatLeadingByte;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams, nodeCurves, checkPublicPointEnconding } from './oid_curves';\nimport { bigIntToUint8Array } from '../../biginteger';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web':\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n case 'node':\n return nodeSign(curve, hashAlgo, message, privateKey);\n }\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });\n return {\n r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),\n s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)\n };\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n // See https://github.com/openpgpjs/openpgpjs/pull/948.\n // NB: the impact was more likely limited to Brainpool curves, since thanks\n // to WebCrypto availability, NIST curve should not have been affected.\n // Similarly, secp256k1 should have been used rarely enough.\n // However, we implement the fix for all curves, since it's only needed in case of\n // verification failure, which is unexpected, hence a minor slowdown is acceptable.\n const tryFallbackVerificationForOldBug = async () => (\n hashed[0] === 0 ?\n jsVerify(curve, signature, hashed.subarray(1), publicKey) :\n false\n );\n\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node': {\n const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n }\n }\n }\n\n const verified = await jsVerify(curve, signature, hashed, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n // eslint-disable-next-line @typescript-eslint/return-await\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Fallback javascript implementation of ECDSA verification.\n * To be used if no native implementation is available for the given curve/operation.\n */\nasync function jsVerify(curve, signature, hashed, publicKey) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, privateKey) {\n // JWT encoding cannot be used for now, as Brainpool curves are not supported\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n privateKey: nodeBuffer.from(privateKey)\n });\n\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n\n const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));\n const len = curve.payloadSize;\n\n return {\n r: signature.subarray(0, len),\n s: signature.subarray(len, len << 1)\n };\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { publicKey: derPublicKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n publicKey: nodeBuffer.from(publicKey)\n });\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n\n const signature = util.concatUint8Array([r, s]);\n\n try {\n return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);\n } catch (err) {\n return false;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n */\n\nimport nacl from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { CurveWithOID, checkPublicPointEnconding } from './oid_curves';\nimport { sign as eddsaSign, verify as eddsaVerify } from './eddsa';\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const { RS: signature } = await eddsaSign(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const RS = util.concatUint8Array([r, s]);\n return eddsaVerify(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { getCipherParams } from '../../cipher';\nimport { generateEphemeralEncryptionMaterial as ecdhXGenerateEphemeralEncryptionMaterial, recomputeSharedSecret as ecdhXRecomputeSharedSecret } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519Legacy': {\n const { sharedSecret: sharedKey, ephemeralPublicKey } = await ecdhXGenerateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));\n const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n return jsPublicEphemeralKey(curve, Q);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n default:\n return jsPublicEphemeralKey(curve, Q);\n\n }\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = await aesKW.wrap(kdfParams.cipher, Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519Legacy': {\n const secretKey = d.slice().reverse();\n const sharedKey = await ecdhXRecomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n return jsPrivateEphemeralKey(curve, V, d);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n default:\n return jsPrivateEphemeralKey(curve, V, d);\n }\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n checkPublicPointEnconding(curve, V);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(await aesKW.unwrap(kdfParams.cipher, Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\nasync function jsPrivateEphemeralKey(curve, V, d) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { secretKey: d, sharedKey };\n}\n\nasync function jsPublicEphemeralKey(curve, Q) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n const { publicKey: V, privateKey: v } = await curve.genKeyPair();\n\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { publicKey: V, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: sender\n },\n privateKey,\n curve.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const _0n = BigInt(0);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n x = uint8ArrayToBigInt(x);\n\n let k;\n let r;\n let s;\n let t;\n g = mod(g, p);\n x = mod(x, q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = getRandomBigInteger(_1n, q); // returns in [1, q-1]\n r = mod(modExp(g, k, p), q); // (g**k mod p) mod q\n if (r === _0n) {\n continue;\n }\n const xr = mod(x * r, q);\n t = mod(h + xr, q); // H(m) + x*r mod q\n s = mod(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q\n if (s === _0n) {\n continue;\n }\n break;\n }\n return {\n r: bigIntToUint8Array(r, 'be', byteLength(p)),\n s: bigIntToUint8Array(s, 'be', byteLength(p))\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n r = uint8ArrayToBigInt(r);\n s = uint8ArrayToBigInt(s);\n\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n if (r <= _0n || r >= q ||\n s <= _0n || s >= q) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n const w = modInv(s, q); // s**-1 mod q\n if (w === _0n) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = mod(g, p);\n y = mod(y, p);\n const u1 = mod(h * w, q); // H(m) * w mod q\n const u2 = mod(r * w, q); // r * w mod q\n const t1 = modExp(g, u1, p); // g**u1 mod p\n const t2 = modExp(y, u2, p); // y**u2 mod p\n const v = mod(mod(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q\n return v === r;\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (mod(p - _1n, q) !== _0n) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (modExp(g, q, p) !== _1n) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = BigInt(bitLength(q));\n const _150n = BigInt(150);\n if (qSize < _150n || !isProbablePrime(q, null, 32)) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const _2n = BigInt(2);\n const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q\n const rqx = q * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n */\n\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { read, signatureParams: { s } };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n // If the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature\n // verification: if the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n // Algorithm-Specific Fields for Ed448 signatures:\n // - 114 octets of the native signature\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo);\n const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length;\n return { read, signatureParams: { RS } };\n }\n\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal:\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport { getCipherParams } from './cipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n if (symmetricAlgo && !util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 and X448 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (C.algorithm !== null && !util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const payloadSize = getCurvePayloadSize(algo);\n const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const payloadSize = getCurvePayloadSize(algo);\n const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 or X448 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const pointSize = getCurvePayloadSize(algo);\n const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([\n enums.publicKey.ed25519,\n enums.publicKey.x25519,\n enums.publicKey.ed448,\n enums.publicKey.x448\n ]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipherParams(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipherParams(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get encoded secret size for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getCurvePayloadSize(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh:\n case enums.publicKey.eddsaLegacy:\n return new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPayloadSize(algo);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.getPayloadSize(algo);\n default:\n throw new Error('Unknown elliptic algo');\n }\n}\n\n/**\n * Get preferred signing hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n\n\nexport { getCipherParams };\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","import defaultConfig from '../../config';\nimport enums from '../../enums';\nimport util from '../../util';\nimport crypto from '../../crypto';\n\nconst ARGON2_TYPE = 0x02; // id\nconst ARGON2_VERSION = 0x13;\nconst ARGON2_SALT_SIZE = 16;\n\nexport class Argon2OutOfMemoryError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Argon2OutOfMemoryError);\n }\n\n this.name = 'Argon2OutOfMemoryError';\n }\n}\n\n// cache argon wasm module\nlet loadArgonWasmModule;\nlet argon2Promise;\n// reload wasm module above this treshold, to deallocated used memory\nconst ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;\n\nclass Argon2S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n const { passes, parallelism, memoryExponent } = config.s2kArgon2Params;\n\n this.type = 'argon2';\n /**\n * 16 bytes of salt\n * @type {Uint8Array}\n */\n this.salt = null;\n /**\n * number of passes\n * @type {Integer}\n */\n this.t = passes;\n /**\n * degree of parallelism (lanes)\n * @type {Integer}\n */\n this.p = parallelism;\n /**\n * exponent indicating memory size\n * @type {Integer}\n */\n this.encodedM = memoryExponent;\n }\n\n generateSalt() {\n this.salt = crypto.random.getRandomBytes(ARGON2_SALT_SIZE);\n }\n\n /**\n * Parsing function for argon2 string-to-key specifier.\n * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n\n this.salt = bytes.subarray(i, i + 16);\n i += 16;\n\n this.t = bytes[i++];\n this.p = bytes[i++];\n this.encodedM = bytes[i++]; // memory size exponent, one-octect\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n const arr = [\n new Uint8Array([enums.write(enums.s2k, this.type)]),\n this.salt,\n new Uint8Array([this.t, this.p, this.encodedM])\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to `keySize`\n * @throws {Argon2OutOfMemoryError|Errors}\n * @async\n */\n async produceKey(passphrase, keySize) {\n const decodedM = 2 << (this.encodedM - 1);\n\n try {\n // on first load, the argon2 lib is imported and the WASM module is initialized.\n // the two steps need to be atomic to avoid race conditions causing multiple wasm modules\n // being loaded when `argon2Promise` is not initialized.\n loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;\n argon2Promise = argon2Promise || loadArgonWasmModule();\n\n // important to keep local ref to argon2 in case the module is reloaded by another instance\n const argon2 = await argon2Promise;\n\n const passwordBytes = util.encodeUTF8(passphrase);\n const hash = argon2({\n version: ARGON2_VERSION,\n type: ARGON2_TYPE,\n password: passwordBytes,\n salt: this.salt,\n tagLength: keySize,\n memorySize: decodedM,\n parallelism: this.p,\n passes: this.t\n });\n\n // a lot of memory was used, reload to deallocate\n if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {\n // it will be awaited if needed at the next `produceKey` invocation\n argon2Promise = loadArgonWasmModule();\n argon2Promise.catch(() => {});\n }\n return hash;\n } catch (e) {\n if (e.message && (\n e.message.includes('Unable to grow instance memory') || // Chrome\n e.message.includes('failed to grow memory') || // Firefox\n e.message.includes('WebAssembly.Memory.grow') || // Safari\n e.message.includes('Out of memory') // Safari iOS\n )) {\n throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');\n } else {\n throw e;\n }\n }\n }\n}\n\nexport default Argon2S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n */\n\nimport defaultConfig from '../../config';\nimport crypto from '../../crypto';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\nimport util from '../../util';\n\nclass GenericS2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(s2kType, config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = enums.read(enums.s2k, s2kType);\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n generateSalt() {\n switch (this.type) {\n case 'salted':\n case 'iterated':\n this.salt = crypto.random.getRandomBytes(8);\n }\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default GenericS2K;\n","import defaultConfig from '../../config';\nimport Argon2S2K, { Argon2OutOfMemoryError } from './argon2';\nimport GenericS2K from './generic';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\n\nconst allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);\n\n/**\n * Instantiate a new S2K instance of the given type\n * @param {module:enums.s2k} type\n * @oaram {Object} [config]\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromType(type, config = defaultConfig) {\n switch (type) {\n case enums.s2k.argon2:\n return new Argon2S2K(config);\n case enums.s2k.iterated:\n case enums.s2k.gnu:\n case enums.s2k.salted:\n case enums.s2k.simple:\n return new GenericS2K(type, config);\n default:\n throw new UnsupportedError('Unsupported S2K type');\n }\n}\n\n/**\n * Instantiate a new S2K instance based on the config settings\n * @oaram {Object} config\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromConfig(config) {\n const { s2kType } = config;\n\n if (!allowedS2KTypesForEncryption.has(s2kType)) {\n throw new Error('The provided `config.s2kType` value is not allowed');\n }\n\n return newS2KFromType(s2kType, config);\n}\n\nexport { Argon2OutOfMemoryError };\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n ], { type: 'text/javascript' }))));\n w.onmessage = function (e) {\n var d = e.data, ed = d.$e$;\n if (ed) {\n var err = new Error(ed[0]);\n err['code'] = ed[1];\n err.stack = ed[2];\n cb(err, null);\n }\n else\n cb(null, d);\n };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n ,\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && st.f && !st.l))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[pos >> 3] = lst;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if (d[1] & 32)\n err(6, 'invalid zlib data: preset dictionaries not supported');\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n err(6, 'invalid gzip data');\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (val instanceof u8)\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n err(8);\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n err(8);\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this_1.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this_1.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_3 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// A salt notation is used to randomize signatures.\n// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks\n// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).\n// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.\n// some chosen-prefix attacks.\n// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.\nconst SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuerKeyID,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.unknownSubpackets = [];\n this.signedHashValue = null;\n this.salt = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n this.preferredCipherSuites = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes, config = defaultConfig) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n // Only for v6 signatures, a variable-length field containing:\n if (this.version === 6) {\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[i++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(i, i + saltLength);\n i += saltLength;\n }\n\n const signatureMaterial = bytes.subarray(i, bytes.length);\n const { read, signatureParams } = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);\n if (read < signatureMaterial.length) {\n throw new Error('Error reading MPIs');\n }\n this.params = signatureParams;\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n if (this.version === 6) {\n arr.push(new Uint8Array([this.salt.length]));\n arr.push(this.salt);\n }\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false, config) {\n this.version = key.version;\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n // add randomness to the signature\n if (this.version === 6) {\n const saltLength = saltLengthForHash(this.hashAlgorithm);\n if (this.salt === null) {\n this.salt = crypto.random.getRandomBytes(saltLength);\n } else if (saltLength !== this.salt.length) {\n throw new Error('Provided salt does not have the required length');\n }\n } else if (config.nonDeterministicSignaturesViaNotation) {\n const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));\n // since re-signing the same object is not supported, it's not expected to have multiple salt notations,\n // but we guard against it as a sanity check\n if (saltNotations.length === 0) {\n const saltValue = crypto.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm));\n this.rawNotations.push({\n name: SALT_NOTATION_NAME,\n value: saltValue,\n humanReadable: false,\n critical: false\n });\n } else {\n throw new Error('Unexpected existing salt notation');\n }\n }\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n if (this.preferredCipherSuites !== null) {\n bytes = new Uint8Array([].concat(...this.preferredCipherSuites));\n arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {\n return writeSubPacket(type, critical, body);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n // Signature subpackets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n mypos++;\n\n if (!hashed) {\n this.unhashedSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuerKeyID:\n // Issuer\n if (this.version === 4) {\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n } else if (hashed) {\n // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,\n // since the Issuer Fingerprint subpacket is to be used instead.\n // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.\n // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,\n // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)\n // issuerFingerprint.\n // If the packet is hashed, then we reject the signature, to avoid verifying data different from\n // what was parsed.\n throw new Error('Unexpected Issuer Key ID subpacket');\n }\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion >= 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCipherSuites:\n // Preferred AEAD Cipher Suites\n this.preferredCipherSuites = [];\n for (let i = mypos; i < bytes.length; i += 2) {\n this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);\n }\n break;\n default:\n this.unknownSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n break;\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n const subpacketLengthBytes = this.version === 6 ? 4 : 2;\n\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));\n\n let i = subpacketLengthBytes;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {\n // avoid hashing unexpected salt size\n throw new Error('Signature salt does not have the expected length');\n }\n\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.unknownSubpackets.forEach(({ type, critical }) => {\n if (critical) {\n throw new Error(`Unknown critical signature subpacket type ${type}`);\n }\n });\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n\n/**\n * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}\n * @param {enums.hash} hashAlgorithm - Hash algorithm.\n * @returns {Integer} Salt length.\n * @private\n */\nfunction saltLengthForHash(hashAlgorithm) {\n switch (hashAlgorithm) {\n case enums.hash.sha256: return 16;\n case enums.hash.sha384: return 24;\n case enums.hash.sha512: return 32;\n case enums.hash.sha224: return 16;\n case enums.hash.sha3_256: return 16;\n case enums.hash.sha3_512: return 32;\n default: throw new Error('Unsupported hash function');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n static fromSignaturePacket(signaturePacket, isLast) {\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.version = signaturePacket.version === 6 ? 6 : 3;\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n onePassSig.salt = signaturePacket.salt; // v6 only\n onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only\n\n onePassSig.flags = isLast ? 1 : 0;\n return onePassSig;\n }\n\n constructor() {\n /** A one-octet version number. The current versions are 3 and 6. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** Only for v6, a variable-length field containing the salt. */\n this.salt = null;\n /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */\n this.issuerFingerprint = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current versions are 3 or 6.\n this.version = bytes[mypos++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n if (this.version === 6) {\n // Only for v6 signatures, a variable-length field containing:\n\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[mypos++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(mypos, mypos + saltLength);\n mypos += saltLength;\n\n // Only for v6 packets, 32 octets of the fingerprint of the signing key.\n this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);\n mypos += 32;\n this.issuerKeyID = new KeyID();\n // For v6 the Key ID is the high-order 64 bits of the fingerprint.\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n }\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const arr = [new Uint8Array([\n this.version,\n this.signatureType,\n this.hashAlgorithm,\n this.publicKeyAlgorithm\n ])];\n if (this.version === 6) {\n arr.push(\n new Uint8Array([this.salt.length]),\n this.salt,\n this.issuerFingerprint\n );\n } else {\n arr.push(this.issuerKeyID.write());\n }\n arr.push(new Uint8Array([this.flags]));\n return util.concatUint8Array(arr);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||\n (this.version === 3 && correspondingSig.version === 6) ||\n (this.version === 6 && correspondingSig.version !== 6) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError,\n UnknownPacketError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,\n // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.\n // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.\n if (e instanceof UnknownPacketError) {\n if (parsed.tag <= 39) {\n await writer.abort(e);\n } else {\n return;\n }\n }\n\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Inflate, Deflate, Zlib, Unzlib } from 'fflate';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write());\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.\n * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator\n * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor\n * @returns {ReadableStream} compressed or decompressed data\n */\nfunction zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {\n return data => {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(inputData => {\n return new Promise((resolve, reject) => {\n const zlibStream = new ZlibStreamedConstructor();\n zlibStream.ondata = processedData => {\n resolve(processedData);\n };\n try {\n zlibStream.push(inputData, true); // only one chunk to push\n } catch (err) {\n reject(err);\n }\n });\n }));\n }\n\n // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)\n if (compressionStreamInstantiator) {\n try {\n const compressorOrDecompressor = compressionStreamInstantiator();\n return data.pipeThrough(compressorOrDecompressor);\n } catch (err) {\n // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate.\n if (err.name !== 'TypeError') {\n throw err;\n }\n }\n }\n\n // JS fallback\n const inputReader = data.getReader();\n const zlibStream = new ZlibStreamedConstructor();\n\n return new ReadableStream({\n async start(controller) {\n zlibStream.ondata = async (value, isLast) => {\n controller.enqueue(value);\n if (isLast) {\n controller.close();\n }\n };\n\n while (true) {\n const { done, value } = await inputReader.read();\n if (done) {\n zlibStream.push(new Uint8Array(), true);\n return;\n } else if (value.length) {\n zlibStream.push(value);\n }\n }\n }\n });\n };\n}\n\nfunction bzip2Decompress() {\n return async function(data) {\n const { decode: bunzipDecode } = await import('@openpgp/seek-bzip');\n return stream.fromAsync(async () => bunzipDecode(await stream.readToEnd(data)));\n };\n}\n\n/**\n * Get Compression Stream API instatiators if the constructors are implemented.\n * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported\n * (supported formats cannot be determined in advance).\n * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat\n * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}\n */\nconst getCompressionStreamInstantiators = compressionFormat => ({\n compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),\n decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))\n});\n\nconst compress_fns = {\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)\n};\n\nconst decompress_fns = {\n uncompressed: data => data,\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),\n bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n static fromObject({ version, aeadAlgorithm }) {\n if (version !== 1 && version !== 2) {\n throw new Error('Unsupported SEIPD version');\n }\n\n const seip = new SymEncryptedIntegrityProtectedDataPacket();\n seip.version = version;\n if (version === 2) {\n seip.aeadAlgorithm = aeadAlgorithm;\n }\n\n return seip;\n }\n\n constructor() {\n this.version = null;\n\n // The following 4 fields are for V2 only.\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = null;\n this.chunkSizeByte = null;\n this.salt = null;\n\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n this.version = await reader.readByte();\n // - A one-octet version number with value 1 or 2.\n if (this.version !== 1 && this.version !== 2) {\n throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);\n }\n\n if (this.version === 2) {\n // - A one-octet cipher algorithm.\n this.cipherAlgorithm = await reader.readByte();\n // - A one-octet AEAD algorithm.\n this.aeadAlgorithm = await reader.readByte();\n // - A one-octet chunk size.\n this.chunkSizeByte = await reader.readByte();\n // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.\n this.salt = await reader.readBytes(32);\n }\n\n // For V1:\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n // For V2:\n // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.\n // - A final, summary authentication tag for the AEAD mode.\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n if (this.version === 2) {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);\n }\n return util.concat([new Uint8Array([this.version]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n const { blockSize, keySize } = crypto.getCipherParams(sessionKeyAlgorithm);\n if (key.length !== keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n\n if (this.version === 2) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n this.salt = crypto.random.getRandomBytes(32);\n this.chunkSizeByte = config.aeadChunkSizeByte;\n this.encrypted = await runAEAD(this, 'encrypt', key, bytes);\n } else {\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n }\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n if (key.length !== crypto.getCipherParams(sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n\n let packetbytes;\n if (this.version === 2) {\n if (this.cipherAlgorithm !== sessionKeyAlgorithm) {\n // sanity check\n throw new Error('Unexpected session key algorithm');\n }\n packetbytes = await runAEAD(this, 'decrypt', key, encrypted);\n } else {\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n }\n\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n\n/**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\nexport async function runAEAD(packet, fn, key, data) {\n const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;\n const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)\n if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type');\n\n const mode = crypto.getAEADMode(packet.aeadAlgorithm);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;\n const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);\n const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n let iv;\n let ivView;\n if (isSEIPDv2) {\n const { keySize } = crypto.getCipherParams(packet.cipherAlgorithm);\n const { ivLength } = mode;\n const info = new Uint8Array(adataBuffer, 0, 5);\n const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);\n key = derived.subarray(0, keySize);\n iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.\n iv.fill(0, iv.length - 8);\n ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n } else { // AEADEncryptedDataPacket\n iv = packet.iv;\n // ivView is unused in this case\n }\n const modeInstance = await mode(packet.cipherAlgorithm, key);\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n let nonce;\n if (isSEIPDv2) { // SEIPD V2\n nonce = iv;\n } else { // AEADEncryptedDataPacket\n nonce = iv.slice();\n for (let i = 0; i < 8; i++) {\n nonce[iv.length - 8 + i] ^= chunkIndexArray[i];\n }\n }\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);\n cryptedPromise.catch(() => {});\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...)\n cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);\n cryptedPromise.catch(() => {});\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n if (isSEIPDv2) { // SEIPD V2\n ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...)\n } else { // AEADEncryptedDataPacket\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n }\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.ready.catch(() => {});\n await writer.abort(e);\n }\n });\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\nimport { runAEAD } from './sym_encrypted_integrity_protected_data';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await runAEAD(this, 'decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await runAEAD(this, 'encrypt', key, data);\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = null;\n\n // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`\n this.publicKeyID = new KeyID();\n\n // For version 6:\n this.publicKeyVersion = null;\n this.publicKeyFingerprint = null;\n\n // For all versions:\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n static fromObject({\n version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm\n }) {\n const pkesk = new PublicKeyEncryptedSessionKeyPacket();\n\n if (version !== 3 && version !== 6) {\n throw new Error('Unsupported PKESK version');\n }\n\n pkesk.version = version;\n\n if (version === 6) {\n pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;\n pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();\n }\n\n pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();\n pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;\n pkesk.sessionKey = sessionKey;\n pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;\n\n return pkesk;\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let offset = 0;\n this.version = bytes[offset++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n if (this.version === 6) {\n // A one-octet size of the following two fields:\n // - A one octet key version number.\n // - The fingerprint of the public key or subkey to which the session key is encrypted.\n // The size may also be zero.\n const versionAndFingerprintLength = bytes[offset++];\n if (versionAndFingerprintLength) {\n this.publicKeyVersion = bytes[offset++];\n const fingerprintLength = versionAndFingerprintLength - 1;\n this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength;\n if (this.publicKeyVersion >= 5) {\n // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint);\n } else {\n // For v4 The Key ID is the low-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));\n }\n } else {\n // The size may also be zero, and the key version and\n // fingerprint omitted for an \"anonymous recipient\"\n this.publicKeyID = KeyID.wildcard();\n }\n } else {\n offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));\n }\n this.publicKeyAlgorithm = bytes[offset++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));\n if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {\n if (this.version === 3) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n } else if (this.encrypted.C.algorithm !== null) {\n throw new Error('Unexpected cleartext symmetric algorithm');\n }\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version])\n ];\n\n if (this.version === 6) {\n if (this.publicKeyFingerprint !== null) {\n arr.push(new Uint8Array([\n this.publicKeyFingerprint.length + 1,\n this.publicKeyVersion]\n ));\n arr.push(this.publicKeyFingerprint);\n } else {\n arr.push(new Uint8Array([0]));\n }\n } else {\n arr.push(this.publicKeyID.write());\n }\n\n arr.push(\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n );\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a\n // v6 PKESK packet, as it is included in the v2 SEIPD packet.\n const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n if (this.version === 3) {\n // v3 Montgomery curves have cleartext cipher algo\n const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;\n this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;\n\n if (sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n // add checksum\n return util.concatUint8Array([\n new Uint8Array(version === 6 ? [] : [cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = version === 6 ?\n { sessionKeyAlgorithm: null, sessionKey: result } :\n { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && (\n version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return {\n sessionKeyAlgorithm: null,\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 6 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number with value 4, 5 or 6.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following 5 fields.\n offset++;\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version >= 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following field.\n offset++;\n }\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n const s2kType = bytes[offset++];\n this.s2k = newS2KFromType(s2kType);\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version >= 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n const s2k = this.s2k.write();\n if (this.version === 6) {\n const s2kLen = s2k.length;\n const fieldsLen = 3 + s2kLen + this.iv.length;\n bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);\n } else if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n if (this.sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n } else {\n // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v6Keys ? 6 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes, config = defaultConfig) {\n let pos = 0;\n // A one-octet version number (4, 5 or 6).\n this.version = bytes[pos++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version === 4 || this.version === 5 || this.version === 6) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version >= 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (\n this.version === 6 &&\n publicParams.oid && (\n publicParams.oid.getName() === enums.curve.curve25519Legacy ||\n publicParams.oid.getName() === enums.curve.ed25519Legacy\n )\n ) {\n throw new Error('Legacy curve25519 cannot be used with v6 keys');\n }\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version >= 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n const versionOctet = 0x95 + version;\n const lengthOctets = version >= 5 ? 4 : 2;\n return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version >= 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version >= 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError, writeTag } from './packet';\nimport computeHKDF from '../crypto/hkdf';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis\n * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).\n * This value is only relevant to know how to decrypt the key:\n * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.\n * @type {Boolean}\n * @private\n */\n this.isLegacyAEAD = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n /**\n * `true` for keys whose integrity is already confirmed, based on\n * the AEAD encryption mechanism\n * @type {Boolean}\n * @private\n */\n this.usedModernAEAD = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes, config = defaultConfig) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes, config);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n // - Only for a version 6 packet where the secret key material is\n // encrypted (that is, where the previous octet is not zero), a one-\n // octet scalar octet count of the cumulative length of all the\n // following optional string-to-key parameter fields.\n if (this.version === 6 && this.s2kUsage) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n i++;\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n const s2kType = bytes[i++];\n this.s2k = newS2KFromType(s2kType);\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n\n if (this.s2kUsage) {\n // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).\n // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).\n // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always\n // fail if the key was parsed according to the wrong format, since the keys are processed differently.\n // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.\n this.isLegacyAEAD = this.s2kUsage === 253 && (\n this.version === 5 || (this.version === 4 && config.parseAEADEncryptedV4KeysAsLegacy));\n // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)\n // of the same length as the cipher's block size.\n // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the\n // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.\n // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero\n if (this.s2kUsage !== 253 || this.isLegacyAEAD) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipherParams(this.symmetric).blockSize\n );\n this.usedModernAEAD = false;\n } else {\n // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),\n // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which\n // is used as the nonce for the AEAD algorithm.\n this.iv = bytes.subarray(\n i,\n i + crypto.getAEADMode(this.aead).ivLength\n );\n // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.\n this.usedModernAEAD = true;\n }\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n let cleartext;\n if (this.version === 6) {\n cleartext = this.keyMaterial;\n } else {\n cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n }\n try {\n const { read, privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n if (read < cleartext.length) {\n throw new Error('Error reading MPIs');\n }\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n const s2k = this.s2k.write();\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n optionalFieldsArr.push(s2k.length);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...s2k);\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage && this.version !== 6) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = newS2KFromType(enums.s2k.gnu, config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n this.isLegacyAEAD = null;\n this.usedModernAEAD = null;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n\n const { blockSize } = crypto.getCipherParams(this.symmetric);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = config.preferredAEADAlgorithm;\n const mode = crypto.getAEADMode(this.aead);\n this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.\n this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material\n\n const serializedPacketTag = writeTag(this.constructor.tag);\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n\n const modeInstance = await mode(this.symmetric, key);\n this.iv = this.isLegacyAEAD ? crypto.random.getRandomBytes(blockSize) : crypto.random.getRandomBytes(mode.ivLength);\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);\n } else {\n this.s2kUsage = 254;\n this.usedModernAEAD = false;\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(\n this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n this.aead = null;\n this.symmetric = null;\n this.isLegacyAEAD = null;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n if (this.usedModernAEAD) {\n // key integrity confirmed by successful AEAD decryption\n return;\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (this.version === 6 && (\n (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||\n this.algorithm === enums.publicKey.eddsaLegacy\n )) {\n throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);\n }\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\n/**\n * Derive encryption key\n * @param {Number} keyVersion - key derivation differs for v5 keys\n * @param {module:type/s2k} s2k\n * @param {String} passphrase\n * @param {module:enums.symmetric} cipherAlgo\n * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)\n * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)\n * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)\n * @returns encryption key\n */\nasync function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) {\n if (s2k.type === 'argon2' && !aeadMode) {\n throw new Error('Using Argon2 S2K without AEAD is not allowed');\n }\n if (s2k.type === 'simple' && keyVersion === 6) {\n throw new Error('Using Simple S2K with version 6 keys is not allowed');\n }\n const { keySize } = crypto.getCipherParams(cipherAlgo);\n const derivedKey = await s2k.produceKey(passphrase, keySize);\n if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {\n return derivedKey;\n }\n const info = util.concatUint8Array([\n serializedPacketTag,\n new Uint8Array([keyVersion, cipherAlgo, aeadMode])\n ]);\n return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);\n}\n\nexport default SecretKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n\n /**\n * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,\n * as well comments placed between the name (if present) and the bracketed email address:\n * - name (comment) \n * - email\n * In the first case, the `email` is the only required part, and it must contain the `@` symbol.\n * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,\n * since they interfere with `comment` parsing.\n */\n const re = /^(?[^()]+\\s+)?(?\\([^()]+\\)\\s+)?(?<\\S+@\\S+>)$/;\n const matches = re.exec(userID);\n if (matches !== null) {\n const { name, comment, email } = matches.groups;\n this.comment = comment?.replace(/^\\(|\\)|\\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace\n this.name = name?.trim() || '';\n this.email = email.substring(1, email.length - 1); // remove brackets\n } else if (/^[^\\s@]+@[^\\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace\n this.email = userID;\n }\n\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2022 Proton AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport crypto from '../crypto';\nimport enums from '../enums';\n\n/**\n * Implementation of the Padding Packet\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:\n * Padding Packet\n */\nclass PaddingPacket {\n static get tag() {\n return enums.packet.padding;\n }\n\n constructor() {\n this.padding = null;\n }\n\n /**\n * Read a padding packet\n * @param {Uint8Array | ReadableStream} bytes\n */\n read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars\n // Padding packets are ignored, so this function is never called.\n }\n\n /**\n * Write the padding packet\n * @returns {Uint8Array} The padding packet.\n */\n write() {\n return this.padding;\n }\n\n /**\n * Create random padding.\n * @param {Number} length - The length of padding to be generated.\n * @throws {Error} if padding generation was not successful\n * @async\n */\n async createPadding(length) {\n this.padding = await crypto.random.getRandomBytes(length);\n }\n}\n\nexport default PaddingPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,\n * `enums.signatures.certGeneric` should be given regardless of the actual trust level)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm for a set of keys.\n * @param {Array} [targetKeys] - The keys to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {\n /**\n * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the\n * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).\n * if no keys are available, `preferredSenderAlgo` is returned.\n * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).\n */\n const defaultAlgo = enums.hash.sha256; // MUST implement\n const preferredSenderAlgo = config.preferredHashAlgorithm;\n\n const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {\n const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);\n const targetPrefs = selfCertification.preferredHashAlgorithms;\n return targetPrefs;\n }));\n const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys\n for (const supportedAlgos of supportedAlgosPerTarget) {\n for (const hashAlgo of supportedAlgos) {\n try {\n // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on\n const supportedAlgo = enums.write(enums.hash, hashAlgo);\n supportedAlgosMap.set(\n supportedAlgo,\n supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1\n );\n } catch {}\n }\n }\n const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;\n const getStrongestSupportedHashAlgo = () => {\n if (supportedAlgosMap.size === 0) {\n return defaultAlgo;\n }\n const sortedHashAlgos = Array.from(supportedAlgosMap.keys())\n .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))\n .sort((algoA, algoB) => crypto.hash.getHashByteLength(algoA) - crypto.hash.getHashByteLength(algoB));\n const strongestHashAlgo = sortedHashAlgos[0];\n // defaultAlgo is always implicilty supported, and might be stronger than the rest\n return crypto.hash.getHashByteLength(strongestHashAlgo) >= crypto.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;\n };\n\n const eccAlgos = new Set([\n enums.publicKey.ecdsa,\n enums.publicKey.eddsaLegacy,\n enums.publicKey.ed25519,\n enums.publicKey.ed448\n ]);\n\n if (eccAlgos.has(signingKeyPacket.algorithm)) {\n // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:\n // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5\n // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;\n // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve\n // preferred algo, even if not supported by all targets.\n const preferredCurveAlgo = crypto.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);\n\n const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);\n const preferredSenderAlgoStrongerThanCurveAlgo = crypto.hash.getHashByteLength(preferredSenderAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo);\n\n if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {\n return preferredSenderAlgo;\n } else {\n const strongestSupportedAlgo = getStrongestSupportedHashAlgo();\n return crypto.hash.getHashByteLength(strongestSupportedAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo) ?\n strongestSupportedAlgo :\n preferredCurveAlgo;\n }\n }\n\n // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,\n // since it was manually set by the sender.\n return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();\n}\n\n/**\n * Returns the preferred compression algorithm for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred compression algorithm\n * @async\n */\nexport async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = enums.compression.uncompressed;\n const preferredSenderAlgo = config.preferredCompressionAlgorithm;\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config);\n const recipientPrefs = selfCertification.preferredCompressionAlgorithms;\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred\n * @async\n */\nexport async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config)));\n const withAEAD = keys.length ?\n selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :\n config.aeadProtect;\n\n if (withAEAD) {\n const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };\n const desiredCipherSuites = [\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: config.preferredAEADAlgorithm },\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },\n { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config.preferredAEADAlgorithm }\n ];\n for (const desiredCipherSuite of desiredCipherSuites) {\n if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(\n cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo\n ))) {\n return desiredCipherSuite;\n }\n }\n return defaultCipherSuite;\n }\n const defaultSymAlgo = enums.symmetric.aes128;\n const desiredSymAlgo = config.preferredSymmetricAlgorithm;\n return {\n symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?\n desiredSymAlgo :\n defaultSymAlgo,\n aeadAlgo: undefined\n };\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {Array} recipientKeys - keys to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);\n signaturePacket.rawNotations = [...notations];\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n const isHardRevocation = ![\n enums.reasonForRevocation.keyRetired,\n enums.reasonForRevocation.keySuperseded,\n enums.reasonForRevocation.userIDInvalid\n ].includes(revocationSignature.reasonForRevocationFlag);\n\n await revocationSignature.verify(\n key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||\n options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'curve25519':\n options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;\n break;\n case 'curve448':\n options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function validateSigningKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateEncryptionKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateDecryptionKeyPacket(keyPacket, signature, config) {\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateSigningKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateEncryptionKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n if (primaryKey.version !== 6) {\n // check for expiration time in direct signatures (for V6 keys, the above already did so)\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const selfCertification = await this.getPrimarySelfSignature(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.\n await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * For V4 keys, returns the self-signature of the primary user.\n * For V5 keys, returns the latest valid direct-key self-signature.\n * This self-signature is to be used to check the key expiration,\n * algorithm preferences, and so on.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} The primary self-signature\n * @async\n */\n async getPrimarySelfSignature(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n if (primaryKey.version === 6) {\n return helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n );\n }\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n return selfCertification;\n }\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config);\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @throws {Error} if no decryption key is found\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n let exception = null;\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n if (this.subkeys[i].keyPacket.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n continue;\n }\n\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n // evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.validateDecryptionKeyPacket(primaryKey, selfCertification, config)) {\n if (primaryKey.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n } else {\n keys.push(this);\n }\n }\n\n if (keys.length === 0) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('No decryption key packets found');\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.\n * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).\n * Note: Curve448 and Curve25519 are not widely supported yet.\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n // Every subkey for a v4 primary key MUST be a v4 subkey.\n // Every subkey for a v6 primary key MUST be a v6 subkey.\n // For v5 keys, since we dropped generation support, a v4 subkey is added.\n // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.\n const keyPacket = await helper.generateSecretSubkey(options, { ...config, v6Keys: this.keyPacket.version === 6 });\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nfunction getDefaultSubkeyType(algoName) {\n const algo = enums.write(enums.publicKey, algoName);\n // NB: no encryption-only algos, since they cannot be in primary keys\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n return 'rsa';\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return 'ecc';\n case enums.publicKey.ed25519:\n return 'curve25519';\n case enums.publicKey.ed448:\n return 'curve448';\n default:\n throw new Error('Unsupported algorithm');\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n function getKeySignatureProperties() {\n const signatureProperties = {};\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n const symmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128\n ], config.preferredSymmetricAlgorithm);\n signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;\n if (config.aeadProtect) {\n const aeadAlgorithms = createPreferredAlgos([\n enums.aead.gcm,\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {\n return symmetricAlgorithms.map(symmetricAlgorithm => {\n return [symmetricAlgorithm, aeadAlgorithm];\n });\n });\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512,\n enums.hash.sha3_256,\n enums.hash.sha3_512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.uncompressed,\n enums.compression.zlib,\n enums.compression.zip\n ], config.preferredCompressionAlgorithm);\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.seipdv2;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n return signatureProperties;\n }\n\n if (secretKeyPacket.version === 6) { // add direct key signature with key prefs\n const dataToSign = {\n key: secretKeyPacket\n };\n\n const signatureProperties = getKeySignatureProperties();\n signatureProperties.signatureType = enums.signature.key;\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n packetlist.push(signaturePacket);\n }\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {\n userID: userIDPacket,\n key: secretKeyPacket\n };\n const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};\n signatureProperties.signatureType = enums.signature.certPositive;\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);\n return createKey(firstKeyPacketList);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n return new PrivateKey(firstPrivateKeyList);\n }\n throw new Error('No secret key packet found');\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n if (keys.length === 0) {\n throw new Error('No secret key packet found');\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport { Argon2OutOfMemoryError } from './type/s2k';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredCipherSuite, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;\n\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config);\n\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n if (err instanceof Argon2OutOfMemoryError) {\n exception = err;\n }\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let decryptionKeyPackets;\n try {\n // do not check key expiration to allow decryption of old messages\n decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n } catch (err) {\n exception = err;\n return;\n }\n\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config); // TODO: Pass userID from somewhere.\n if (selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all((\n expectedSymmetricAlgorithm ?\n [expectedSymmetricAlgorithm] :\n Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)\n ).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;\n if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config);\n const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);\n const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&\n !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(symmetricAlgo);\n return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({\n version: aeadAlgorithmName ? 2 : 1,\n aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null\n });\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n\n const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({\n version: aeadAlgorithm ? 6 : 3,\n encryptionKeyPacket: encryptionKey.keyPacket,\n anonymousRecipient: wildcard,\n sessionKey,\n sessionKeyAlgorithm: symmetricAlgorithm\n });\n\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config); // this returns the existing signature packets as well\n const onePassSignaturePackets = signaturePackets.map(\n (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))\n .reverse(); // innermost OPS refers to the first signature packet\n\n packetlist.push(...onePassSignaturePackets);\n packetlist.push(literalDataPacket);\n packetlist.push(...signaturePackets);\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n const trailingPacket = this.packets[this.packets.length - 1];\n // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?\n trailingPacket.version !== 2 :\n this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const signingUserID = signingUserIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config);\n return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n const input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // emit header and checksum if one of the signatures has a version not 6\n const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);\n const hash = emitHeaderAndChecksum ?\n Array.from(new Set(this.signature.packets.map(\n packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()\n ))).join() :\n null;\n\n const body = {\n hash,\n text: this.text,\n data: this.signature.packets.write()\n };\n\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n const hashAlgos = [];\n headers.forEach(header => {\n const hashHeader = header.match(/^Hash: (.+)$/); // get header value\n if (hashHeader) {\n const parsedHashIDs = hashHeader[1]\n .replace(/\\s/g, '') // remove whitespace\n .split(',')\n .map(hashName => {\n try {\n return enums.write(enums.hash, hashName.toLowerCase());\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());\n }\n });\n hashAlgos.push(...parsedHashIDs);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredCompressionAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).\n * Note: Curve448 and Curve25519 (new format) are not widely supported yet.\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:\n * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n if (!type && !curve) {\n type = config.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)\n curve = 'curve25519Legacy'; // unused with type != 'ecc'\n } else {\n type = type || 'ecc';\n curve = curve || 'curve25519Legacy';\n }\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && !config.v6Keys) {\n throw new Error('UserIDs are required for V4 keys');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {\n throw new Error('UserIDs are required for V4 keys');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return await convertStream(data);\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return await convertStream(signature);\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data) {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","Object","setPrototypeOf","this","prototype","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","isStream","globalThis","ReadableStream","isPrototypeOf","_read","_readableState","Error","isUint8Array","Uint8Array","concatUint8Array","arrays","length","totalLength","i","result","pos","forEach","element","set","undefined","read","async","value","done","readToEnd","join","slice","clone","then","push","write","chunk","close","abort","reason","process","versions","doneReadingSet","WeakSet","externalBuffer","Reader","reader","bind","_releaseLock","_cancel","cancel","doneReading","has","add","e","toStream","start","controller","enqueue","toArrayStream","concat","list","some","map","transform","transformWithCancel","all","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","options","transformStream","TransformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","pull","highWaterMark","WritableStream","error","finish","output","data","result1","result2","flush","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","destroy","arrayStream","shift","readLine","returnVal","buffer","streams.concat","lineEndIndex","indexOf","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","byteOffset","byteLength","filter","byValue","enums","curve","nistP256","p256","nistP384","p384","nistP521","p521","secp256k1","ed25519Legacy","ed25519","curve25519Legacy","curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","argon2","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","aedh","aedsa","x25519","x448","ed448","symmetric","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","sha3_256","sha3_512","webHash","aead","eax","ocb","gcm","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","padding","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuerKeyID","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","preferredCipherSuites","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","seipdv2","type","config","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","aeadProtect","parseAEADEncryptedV4KeysAsLegacy","preferredAEADAlgorithm","aeadChunkSizeByte","v6Keys","enableParsingV5Entities","s2kType","s2kIterationCountByte","s2kArgon2Params","passes","parallelism","memoryExponent","allowUnauthenticatedMessages","allowUnauthenticatedStream","minRSABits","passwordCollisionCheck","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","allowMissingKeyFlags","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","nonDeterministicSignaturesViaNotation","useEllipticFallback","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","debugMode","env","NODE_ENV","util","isString","String","nodeRequire","stream.isUint8Array","stream.isStream","getNobleCurve","publicKeyAlgo","curveName","defaultConfig","nobleCurves","import","readNumber","n","writeNumber","b","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","readExactSubarray","leftPad","padded","offset","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","hex","k","parseInt","uint8ArrayToHex","hexAlphabet","s","v","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","printDebug","log","printDebugError","x","r","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","webCrypto","crypto","subtle","getNodeCrypto","webcrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","sub","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","a","selectUint8","isAES","cipherAlgo","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","getType","header","match","addheader","customComment","getCheckSum","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","base64.encode","from","toString","btoa","atob","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","removeChecksum","body","lastEquals","lastIndexOf","unarmor","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","stream.isArrayStream","stream.readToEnd","messageType","partIndex","partTotal","emitChecksum","maybeBodyClone","stream.passiveClone","getLegacyCipher","algo","legacyCiphers","cipher","getCipherBlockSize","getCipherKeySize","getCipherParams","keySize","blockSize","md5cycle","c","d","ff","gg","hh","ii","add32","cmn","q","md5blk","md5blks","hex_chr","rhex","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","update","digest","nobleHash","nobleHashName","webCryptoHashName","getNobleHash","nobleHashes","hashInstance","create","entree","state","substring","tail","md51","getHashByteLength","isBytes","lengths","exists","instance","checkFinished","destroyed","finished","out","min","outputLen","u8","arr","u32","createView","toBytes","utf8ToBytes","copyBytes","equalBytes","diff","wrapCipher","params","assign","setBigUint64","view","isLE","_32n","BigInt","_u32_max","wh","Number","wl","setUint32","isAligned32","clean","fill","BLOCK_SIZE","ZEROS16","ZEROS32","swapLE","GHASH","expectedLength","blockLen","s0","s1","s2","s3","abytes","kView","k0","getUint32","k1","k2","k3","doubles","W","estimateWindow","windows","windowSize","items","w","d0","d1","d2","d3","_updateBlock","o0","o1","o2","o3","mask","num","bytePos","bitPos","bit","e0","e1","e2","e3","aexists","b32","blocks","left","elm","digestInto","aoutput","o32","res","Polyval","ghKey","reverse","hiBit","carry","_toGHASHKey","wrapConstructorWithKey","hashCons","hashC","msg","tmp","ghash","EMPTY_BLOCK","POLY","mul2","mul","sbox","box","invSbox","_","rotr32_8","rotl32_8","byteSwap","word","genTtable","T0","T1","T2","T3","T01","T23","sbox2","Uint16Array","idx","tableEncoding","tableDecoding","xPowers","p","expandKeyLE","len","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","encrypt","rounds","t0","t1","t2","t3","decrypt","getDst","dst","ctrCounter","nonce","src","srcLen","ctr","c32","src32","dst32","ctr32","ctrPos","ctrNum","nonceLength","processCtr","plaintext","ciphertext","cbc","iv","opts","pcks5","disablePadding","o","_out","outLen","remaining","validateBlockEncrypt","_iv","n32","tmp32","paddingByte","padPCKS","validateBlockDecrypt","ps0","ps1","ps2","ps3","lastByte","validatePCKS","cfb","processCfb","isEncrypt","next32","tagLength","AAD","_computeTag","authKey","tagMask","aadLength","h","computeTag","deriveKeys","counter","nonceLen","g","passedTag","isBytes32","encryptBlock","block","decryptBlock","AESW","kek","a0","a1","chunks","AESKW_IV","aeskw","sum","pad","concatBytes","unsafe","knownAlgos","getCiphers","nodeAlgos","WebCryptoEncryptor","prevBlock","nextBlock","zeroBlock","isSupported","importKey","_runCBC","nonZeroIV","mode","keyRef","encryptChunk","missing","added","leftover","toEncrypt","encryptedBlocks","xorMut","encryptedBlock","curBlock","clearSensitiveData","ct","NobleStreamProcessor","forEncryption","nobleAesHelpers","getUint32Array","_runCFB","processChunk","toProcess","processedBlocks","processedBlock","aLength","algoName","decipherObj","createDecipheriv","nodeDecrypt","nobleAesCfb","aesDecrypt","cipherfn","block_size","blockp","decblock","pt","cipherObj","createCipheriv","nodeEncrypt","aesEncrypt","blockc","encblock","blockLength","rightXORMut","CMAC","CBC","padding2","err","nobleAesCbc","ivLength","zero","one","two","OMAC","cmac","CTR","en","final","nobleAesCtr","EAX","omac","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","T","xor","OCB","maxNtz","aes","encipher","decipher","crypt","m","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","checksum","xorInput","$","cipherInput","mask_x","mask_$","constructKeyVariables","crypted","ALGO","GCM","setAAD","getAuthTag","de","setAuthTag","_key","webcryptoEmptyMessagesUnsupported","userAgent","nobleAesGcm","additionalData","_0n","_1n","uint8ArrayToBigInt","mod","reduced","modExp","exp","lsb","abs","modInv","gcd","aInput","bInput","y","xPrev","yPrev","aNegated","bNegated","_egcd","bigIntToNumber","number","MAX_SAFE_INTEGER","getBit","bitLength","bitlen","_8n","bigIntToUint8Array","endian","rawLength","getRandomBytes","getRandomValues","getRandomBigInteger","modulus","randomProbablePrime","_30n","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","n1","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","count","randomBytes","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","hashed","emLen","hashPrefix","tLen","EM","privateToJWK","u","pNum","qNum","dNum","dq","dp","kty","qi","ext","publicToJWK","jwkToPrivate","jwk","format","constants","RSA_PKCS1_PADDING","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","publicEncrypt","bnEncrypt","keyGenOpt","modulusLength","publicExponent","keyPair","generateKey","exportKey","publicKeyEncoding","privateKeyEncoding","generateKeyPair","jwkPrivateKey","phi","hashAlgo","hashName","sign","webSign","createSign","nodeSign","bnSign","_2n","rde","verify","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","c1","c2","pSize","threshold","nacl","gf","init","Float64Array","randombytes","_9","gf0","gf1","_121665","D","D2","X","Y","I","ts64","l","crypto_verify_32","xi","yi","vn","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","A","Z","M","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","z","f","x32","x16","crypto_scalarmult_base","K","crypto_hashblocks_hl","hl","bh0","bh1","bh2","bh3","bh4","bh5","bh6","bh7","bl0","bl1","bl2","bl3","bl4","bl5","bl6","bl7","th","tl","Int32Array","ah0","ah1","ah2","ah3","ah4","ah5","ah6","ah7","al0","al1","al2","al3","al4","al5","al6","al7","crypto_hash","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","reduce","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","TypeError","scalarMult","crypto_box_keypair","fromSecretKey","signedMsg","sm","smlen","crypto_sign","detached","sig","crypto_sign_open","fromSeed","seed","setPRNG","cleanup","knownOIDs","OID","oid","toHex","getName","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callback","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","lengthByte","nextPacket","UnsupportedError","captureStackTrace","UnknownPacketError","UnparseablePacket","rawContent","generate","webCryptoKey","getPayloadSize","utils","randomPrivateKey","getPublicKey","getPreferredHashAlgo","privateKeyToJWK","RS","publicKeyToJWK","crv","wrap","dataToWrap","wrappingKey","keyToWrap","wrapped","wrapKey","nobleAesKW","unwrap","wrappedData","unwrapped","unwrapKey","computeHKDF","inputKey","salt","info","importedKey","deriveBits","HKDF_INFO","generateEphemeralEncryptionMaterial","recipientA","ephemeralSecretKey","sharedSecret","assertNonZeroArray","ephemeralPublicKey","getSharedSecret","recomputeSharedSecret","acc","wrappedKey","hkdfInput","aesKW.unwrap","encryptionKey","aesKW.wrap","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","wireFormatLeadingByte","CurveWithOID","oidOrName","genKeyPair","namedCurve","jwkToRawPublic","webGenKeyPair","jsGenKeyPair","createECDH","generateKeys","getPrivateKey","nodeGenKeyPair","ecdhXGenerate","eddsaGenerate","validateStandardParams","Q","supportedCurves","dG","checkPublicPointEnconding","V","pointSize","nobleCurve","bufX","bufY","rawPublicToJWK","ecKeyUtils","nodeBuffer","derPrivateKey","generateDer","dsaEncoding","lowS","tryFallbackVerificationForOldBug","jsVerify","verified","derPublicKey","eddsaSign","eddsaVerify","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","ecdhXGenerateEphemeralEncryptionMaterial","recipient","public","webPublicEphemeralKey","jsPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","genPrivateEphemeralKey","ecdhXRecomputeSharedSecret","secret","webPrivateEphemeralKey","jsPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","C","pkcs5.decode","pkcs5.encode","xr","qSize","u1","u2","rsa","elliptic","signatureParams","rsSize","eddsa","publicKeyParams","privateKeyParams","publicParams","curveSize","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","fromObject","algorithm","followLength","checkSupportedCurve","getCurvePayloadSize","ecdhX","privateParams","prefixrandom","repeat","ECDHSymkey","sessionKeyParams","keyAlgo","symmetricAlgo","algosWithNativeRepresentation","orderedParams","keys","validateParams","algoModule","random","pkcs1","pkcs5","aesKW","Argon2OutOfMemoryError","loadArgonWasmModule","argon2Promise","Argon2S2K","encodedM","generateSalt","produceKey","passphrase","decodedM","default","version","password","memorySize","GenericS2K","getCount","numBytes","rlength","prefixlen","toHash","datalen","allowedS2KTypesForEncryption","newS2KFromType","newS2KFromConfig","u16","fleb","fdeb","clim","freb","eb","_a","fl","revfl","_b","fd","revfd","rev","hMap","cd","mb","co","le","rvb","sv","r_1","flt","fdt","flm","flrm","fdm","fdrm","bits16","shft","slc","BYTES_PER_ELEMENT","ec","ind","nt","code","wbits","wbits16","hTree","et","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","cl","cli","cln","cls","clen","cf","wfblk","dat","wblk","syms","lf","df","li","bl","dlt","mlb","ddt","mdb","_c","lclt","nlc","_d","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","deo","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","head","bs1_1","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","level","mem","Deflate","cb","ondata","Inflate","bts","sl","noBuf","noSt","cbuf","nbuf","bt","lbt","dbt","tbts","hLit","hcLen","ldt","clt","clb","clbmsk","clm","lt","lms","dms","lpos","sym","dsym","inflt","Zlib","raw","lv","zlh","wbytes","Unzlib","td","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","KeyID","equals","keyID","matchWildcard","isWildcard","isNull","mapToHex","fromID","wildcard","SALT_NOTATION_NAME","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","unknownSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","saltLength","signatureMaterial","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","saltLengthForHash","saltValue","humanReadable","critical","writeHashedSubPackets","stream.slice","stream.clone","writeSubPacket","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLengthBytes","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","fromSignaturePacket","signaturePacket","isLast","onePassSig","flags","args","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","fromBinary","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","chunkSize","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","compressionFn","compress_fns","compressionStreamInstantiator","ZlibStreamedConstructor","inputData","zlibStream","processedData","compressorOrDecompressor","pipeThrough","inputReader","bzip2Decompress","bunzipDecode","getCompressionStreamInstantiators","compressionFormat","compressor","CompressionStream","decompressor","DecompressionStream","SymEncryptedIntegrityProtectedDataPacket","aeadAlgorithm","seip","cipherAlgorithm","chunkSizeByte","encrypted","sessionKeyAlgorithm","runAEAD","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","isSEIPDv2","isAEADP","getAEADMode","tagLengthIfDecrypting","tagLengthIfEncrypting","chunkIndexSizeIfAEADEP","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","ivView","latestPromise","cryptedBytes","queuedBytes","derived","modeInstance","size","stream.pipe","finalChunk","cryptedPromise","setInt32","desiredSize","AEADEncryptedDataPacket","PublicKeyEncryptedSessionKeyPacket","publicKeyID","publicKeyVersion","publicKeyFingerprint","sessionKey","encryptionKeyPacket","anonymousRecipient","pkesk","versionAndFingerprintLength","fingerprintLength","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","hasEncryptedAlgo","sessionKeyData","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","s2kLen","fieldsLen","generateSessionKey","PublicKeyPacket","expirationTimeV3","fromSecretKeyPacket","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","versionOctet","lengthOctets","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","fromSecretSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","isLegacyAEAD","usedModernAEAD","startOfSecretKeyData","unparseableKeyMaterial","cleartext","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","serializedPacketTag","produceEncryptionKey","associateData","cleartextWithHash","validate","validParams","generateParams","keyVersion","aeadMode","derivedKey","UserIDPacket","email","comment","components","matches","exec","groups","trim","otherUserID","SecretSubkeyPacket","TrustPacket","PaddingPacket","createPadding","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","recipientKeys","signingKeyPacket","recipientUserIDs","targetKeys","targetUserIDs","defaultAlgo","preferredSenderAlgo","supportedAlgosPerTarget","getPrimarySelfSignature","supportedAlgosMap","Map","supportedAlgos","supportedAlgo","isSupportedHashAlgo","getStrongestSupportedHashAlgo","strongestHashAlgo","algoA","algoB","preferredCurveAlgo","getPreferredCurveHashAlgo","preferredSenderAlgoIsSupported","preferredSenderAlgoStrongerThanCurveAlgo","strongestSupportedAlgo","mergeSignatures","source","dest","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","isHardRevocation","sanitizeKeyOptions","subkeyDefaults","validateSigningKeyPacket","validateEncryptionKeyPacket","validateDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","certify","signingKeys","isPrivate","signingKey","getSigningKey","isRevoked","certificate","verifyCertificate","verificationKeys","issuerKeys","getKeys","verifyAllCertifications","certifications","certification","valid","selfCertification","sourceUser","srcSelfSig","srcRevSig","revoke","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","helper.checkKeyRequirements","helper.validateSigningKeyPacket","getEncryptionKey","helper.validateEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","getPrimaryUser","primaryUser","B","pop","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","getRevocationCertificate","applyRevocationCertificate","revocationCertificate","signPrimaryUser","privateKeys","userSign","signAllUsers","verifyPrimaryUser","verifyAllUsers","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","pubSubkeyPacket","getDecryptionKeys","helper.validateDecryptionKeyPacket","Boolean","addSubkey","defaultOptions","getDefaultSubkeyType","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","getKeySignatureProperties","symmetricAlgorithms","aeadAlgorithms","flatMap","symmetricAlgorithm","userIDs","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","keyIndex","readPrivateKey","firstPrivateKeyList","readKeys","armoredKeys","binaryKeys","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","symEncryptedPacketlist","symEncryptedPacket","expectedSymmetricAlgorithm","sessionKeyObjects","decryptSessionKeys","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgo","selfSigs","selfSig","defaultCipherSuite","desiredCipherSuites","desiredCipherSuite","cipherSuite","defaultSymAlgo","desiredSymAlgo","getPreferredCipherSuite","symmetricAlgoName","aeadAlgoName","maybeKey","encryptionKeyIDs","aeadAlgorithmName","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","signingUserIDs","literalDataPacket","signaturePackets","createSignaturePackets","onePassSignaturePackets","signDetached","recipientKeyIDs","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","appendSignature","detachedSignature","trailingPacket","signingUserID","existingSigPacketlist","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","streamType","createMessage","literalDataPacketlist","CleartextMessage","newSignature","emitHeaderAndChecksum","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","check","hashHeader","parsedHashIDs","createCleartextMessage","checkConfig","toArray","helper.generateSecretKey","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","decryptKey","clonedPrivateKey","passphrases","encryptKey","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","senderAlgoSupport","recipientPrefs","getPreferredCompressionAlgo","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","object"],"mappings":";6GAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxB,WAAAC,GACEC,QAEAC,OAAOC,eAAeC,KAAMN,EAAYO,WAExCD,KAAKX,GAAsB,IAAIa,SAAQ,CAACC,EAASC,KAC/CJ,KAAKT,GAAsBY,EAC3BH,KAAKR,GAAqBY,CAAM,IAElCJ,KAAKX,GAAoBgB,OAAM,QACnC,EAsCA,SAASC,EAAcC,GACrB,OAAOA,GAASA,EAAMC,WAAab,MAAMc,QAAQF,EACnD,CAOA,SAASG,EAAOH,GACd,IAAKD,EAAcC,GAAQ,CACzB,MAAMI,EAASJ,EAAMK,YACfC,EAAcF,EAAOE,YAK3B,OAJAF,EAAOE,YAAc,KACnBF,EAAOG,OAAOT,OAAM,eACpBQ,EAAYE,KAAKJ,EAAO,EAEnBA,CACX,CACEX,KAAKgB,OAAST,CAChB,CCjEA,SAASU,EAASV,GAChB,GAAID,EAAcC,GAChB,MAAO,QAET,GAAIW,EAAWC,gBAAkBD,EAAWC,eAAelB,UAAUmB,cAAcb,GACjF,MAAO,M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BmV,EAAcoxD,GAChB,MAAUpnE,MAAM,4BAA4BonE,EAIpD,CAQA,SAAS7B,GAAQ/zB,GAIf,OAHIA,IAAUj8B,EAAKrW,QAAQsyC,KACzBA,EAAQ,CAACA,IAEJA,CACT,CASAzwC,eAAe6lE,GAActhE,GAE3B,MAAmB,UADAiQ,EAAK7V,SAAS4F,GAExBob,EAAiBpb,GAEnBA,CACT,CAUA,SAASwhE,GAAYtmE,EAAQwR,GAC3BxR,EAAO8E,KAAO+a,EAAqBrO,EAAQ+0C,QAAQtnD,QAAQsB,MAAO4C,EAAUC,WACpEgoD,EAAYprD,EAAO8E,KAAM1B,EAAU,CACvCE,cAAc,IAEhB,MAAM1E,EAASmhB,EAAiB3c,GAChC,UAEQ8c,EAAiB/c,GAAU4mB,GAAKA,UAChCnrB,EAAOsC,OACd,CAAC,MAAOiB,SACDvD,EAAOuC,MAAMgB,EACzB,IAEA,CASA,SAAS8iE,GAAa4B,EAAQpqC,EAAQtqB,GACpC,OAAQsqB,GACN,IAAK,SACH,OAAOoqC,EACT,IAAK,UACH,OAAOA,EAAOz1D,MAAMe,GACtB,IAAK,SACH,OAAO00D,EAAO7lE,QAChB,QACE,MAAUxB,MAAM,sBAAsBi9B,GAE5C","x_google_ignoreList":[0,1,2,3,12,13,14,15,28,29,52]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/openpgp.mjs b/app/node_modules/openpgp/dist/lightweight/openpgp.mjs index a6eb5717e..57dfd97ca 100644 --- a/app/node_modules/openpgp/dist/lightweight/openpgp.mjs +++ b/app/node_modules/openpgp/dist/lightweight/openpgp.mjs @@ -1,4 +1,4 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; const doneWritingPromise = Symbol('doneWritingPromise'); @@ -10,6 +10,9 @@ const readingIndex = Symbol('readingIndex'); class ArrayStream extends Array { constructor() { super(); + // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work + Object.setPrototypeOf(this, ArrayStream.prototype); + this[doneWritingPromise] = new Promise((resolve, reject) => { this[doneWritingResolve] = resolve; this[doneWritingReject] = reject; @@ -110,15 +113,14 @@ Writer.prototype.abort = async function(reason) { */ Writer.prototype.releaseLock = function() {}; -const isNode = typeof globalThis.process === 'object' && +/* eslint-disable no-prototype-builtins */ +typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; -const NodeReadableStream = isNode && void('stream').Readable; - /** * Check whether data is a Stream, and if so of which type * @param {Any} input data to check - * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false} + * @returns {'web'|'node'|'array'|'web-like'|false} */ function isStream(input) { if (isArrayStream(input)) { @@ -127,11 +129,11 @@ function isStream(input) { if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { return 'web'; } - if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) { - return 'ponyfill'; - } - if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) { - return 'node'; + // try and detect a node native stream without having to import its class + if (input && + !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) && + typeof input._read === 'function' && typeof input._readableState === 'object') { + throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`'); } if (input && input.getReader) { return 'web-like'; @@ -175,99 +177,12 @@ function concatUint8Array(arrays) { return result; } -const NodeBuffer = isNode && void('buffer').Buffer; -const NodeReadableStream$1 = isNode && void('stream').Readable; - +const doneReadingSet = new WeakSet(); /** - * Web / node stream conversion functions - * From https://github.com/gwicke/node-web-streams + * The external buffer is used to store values that have been peeked or unshifted from the original stream. + * Because of how streams are implemented, such values cannot be "put back" in the original stream, + * but they need to be returned first when reading from the input again. */ - -let nodeToWeb; -let webToNode; - -if (NodeReadableStream$1) { - - /** - * Convert a Node Readable Stream to a Web ReadableStream - * @param {Readable} nodeStream - * @returns {ReadableStream} - */ - nodeToWeb = function(nodeStream) { - let canceled = false; - return new ReadableStream({ - start(controller) { - nodeStream.pause(); - nodeStream.on('data', chunk => { - if (canceled) { - return; - } - if (NodeBuffer.isBuffer(chunk)) { - chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - controller.enqueue(chunk); - nodeStream.pause(); - }); - nodeStream.on('end', () => { - if (canceled) { - return; - } - controller.close(); - }); - nodeStream.on('error', e => controller.error(e)); - }, - pull() { - nodeStream.resume(); - }, - cancel(reason) { - canceled = true; - nodeStream.destroy(reason); - } - }); - }; - - - class NodeReadable extends NodeReadableStream$1 { - constructor(webStream, options) { - super(options); - this._reader = getReader(webStream); - } - - async _read(size) { - try { - while (true) { - const { done, value } = await this._reader.read(); - if (done) { - this.push(null); - break; - } - if (!this.push(value)) { - break; - } - } - } catch (e) { - this.destroy(e); - } - } - - async _destroy(error, callback) { - this._reader.cancel(error).then(callback, callback); - } - } - - /** - * Convert a Web ReadableStream to a Node Readable Stream - * @param {ReadableStream} webStream - * @param {Object} options - * @returns {Readable} - */ - webToNode = function(webStream, options) { - return new NodeReadable(webStream, options); - }; - -} - -const doneReadingSet = new WeakSet(); const externalBuffer = Symbol('externalBuffer'); /** @@ -286,13 +201,10 @@ function Reader(input) { const reader = input.getReader(); this._read = reader.read.bind(reader); this._releaseLock = () => {}; - this._cancel = async () => {}; + this._cancel = () => {}; return; } let streamType = isStream(input); - if (streamType === 'node') { - input = nodeToWeb(input); - } if (streamType) { const reader = input.getReader(); this._read = reader.read.bind(reader); @@ -399,6 +311,7 @@ Reader.prototype.readByte = async function() { Reader.prototype.readBytes = async function(length) { const buffer = []; let bufferLength = 0; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) { @@ -458,6 +371,7 @@ Reader.prototype.unshift = function(...values) { */ Reader.prototype.readToEnd = async function(join=concat) { const result = []; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) break; @@ -466,32 +380,6 @@ Reader.prototype.readToEnd = async function(join=concat) { return join(result); }; -let { ReadableStream, WritableStream, TransformStream } = globalThis; - -let toPonyfillReadable, toNativeReadable; - -async function loadStreamsPonyfill() { - if (TransformStream) { - return; - } - - const [ponyfill, adapter] = await Promise.all([ - import('./ponyfill.es6.mjs'), - import('./web-streams-adapter.mjs') - ]); - - ({ ReadableStream, WritableStream, TransformStream } = ponyfill); - - const { createReadableStreamWrapper } = adapter; - - if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) { - toPonyfillReadable = createReadableStreamWrapper(ReadableStream); - toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream); - } -} - -const NodeBuffer$1 = isNode && void('buffer').Buffer; - /** * Convert data to Stream * @param {ReadableStream|Uint8array|String} input data to convert @@ -499,12 +387,6 @@ const NodeBuffer$1 = isNode && void('buffer').Buffer; */ function toStream(input) { let streamType = isStream(input); - if (streamType === 'node') { - return nodeToWeb(input); - } - if (streamType === 'web' && toPonyfillReadable) { - return toPonyfillReadable(input); - } if (streamType) { return input; } @@ -517,7 +399,7 @@ function toStream(input) { } /** - * Convert data to ArrayStream + * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream. * @param {Object} input data to convert * @returns {ArrayStream} Converted data */ @@ -550,9 +432,6 @@ function concat(list) { if (typeof list[0] === 'string') { return list.join(''); } - if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) { - return NodeBuffer$1.concat(list); - } return concatUint8Array(list); } @@ -593,24 +472,6 @@ function concatArrayStream(list) { return result; } -/** - * Get a Reader - * @param {ReadableStream|Uint8array|String} input - * @returns {Reader} - */ -function getReader(input) { - return new Reader(input); -} - -/** - * Get a Writer - * @param {WritableStream} input - * @returns {Writer} - */ -function getWriter(input) { - return new Writer(input); -} - /** * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. * @param {ReadableStream|Uint8array|String} input @@ -647,6 +508,7 @@ async function pipe(input, target, { const reader = getReader(input); const writer = getWriter(target); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -898,6 +760,7 @@ function passiveClone(input) { const reader = getReader(readable); const writer = getWriter(writable); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -981,9 +844,8 @@ function slice(input, begin=0, end=Infinity) { if (returnValue.length >= -end) { lastBytes = slice(returnValue, end); return slice(returnValue, begin, end); - } else { - lastBytes = returnValue; } + lastBytes = returnValue; }); } console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); @@ -992,9 +854,8 @@ function slice(input, begin=0, end=Infinity) { if (input[externalBuffer]) { input = concat(input[externalBuffer].concat([input])); } - if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) { - if (end === Infinity) end = input.length; - return input.subarray(begin, end); + if (isUint8Array(input)) { + return input.subarray(begin, end === Infinity ? input.length : end); } return input.slice(begin, end); } @@ -1026,7 +887,10 @@ async function readToEnd(input, join=concat) { async function cancel(input, reason) { if (isStream(input)) { if (input.cancel) { - return input.cancel(reason); + const cancelled = await input.cancel(reason); + // the stream is not always cancelled at this point, so we wait some more + await new Promise(setTimeout); + return cancelled; } if (input.destroy) { input.destroy(reason); @@ -1055,640 +919,156 @@ function fromAsync(fn) { return arrayStream; } -/* eslint-disable new-cap */ +/** + * Get a Reader + * @param {ReadableStream|Uint8array|String} input + * @returns {Reader} + */ +function getReader(input) { + return new Reader(input); +} /** - * @fileoverview - * BigInteger implementation of basic operations - * that wraps the native BigInt library. - * Operations are not constant time, - * but we try and limit timing leakage where we can - * @module biginteger/native - * @private + * Get a Writer + * @param {WritableStream} input + * @returns {Writer} */ +function getWriter(input) { + return new Writer(input); +} /** - * @private + * @module enums */ -class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on null or undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - if (n instanceof Uint8Array) { - const bytes = n; - const hex = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - const hexByte = bytes[i].toString(16); - hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte; - } - this.value = BigInt('0x0' + hex.join('')); - } else { - this.value = BigInt(n); - } - } +const byValue = Symbol('byValue'); - clone() { - return new BigInteger(this.value); - } +var enums = { - /** - * BigInteger increment in place + /** Maps curve names under various standards to one + * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} + * @enum {String} + * @readonly */ - iinc() { - this.value++; - return this; - } + curve: { + /** NIST P-256 Curve */ + 'nistP256': 'nistP256', + /** @deprecated use `nistP256` instead */ + 'p256': 'nistP256', - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } + /** NIST P-384 Curve */ + 'nistP384': 'nistP384', + /** @deprecated use `nistP384` instead */ + 'p384': 'nistP384', - /** - * BigInteger decrement in place - */ - idec() { - this.value--; - return this; - } + /** NIST P-521 Curve */ + 'nistP521': 'nistP521', + /** @deprecated use `nistP521` instead */ + 'p521': 'nistP521', - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + /** SECG SECP256k1 Curve */ + 'secp256k1': 'secp256k1', - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value += x.value; - return this; - } + /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ + 'ed25519Legacy': 'ed25519Legacy', + /** @deprecated use `ed25519Legacy` instead */ + 'ed25519': 'ed25519Legacy', - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ + 'curve25519Legacy': 'curve25519Legacy', + /** @deprecated use `curve25519Legacy` instead */ + 'curve25519': 'curve25519Legacy', - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value -= x.value; - return this; - } + /** BrainpoolP256r1 Curve */ + 'brainpoolP256r1': 'brainpoolP256r1', - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } + /** BrainpoolP384r1 Curve */ + 'brainpoolP384r1': 'brainpoolP384r1', - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value *= x.value; - return this; - } + /** BrainpoolP512r1 Curve */ + 'brainpoolP512r1': 'brainpoolP512r1' + }, - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. + /** A string to key specifier type + * @enum {Integer} + * @readonly */ - mul(x) { - return this.clone().imul(x); - } + s2k: { + simple: 0, + salted: 1, + iterated: 3, + argon2: 4, + gnu: 101 + }, - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} + * @enum {Integer} + * @readonly */ - imod(m) { - this.value %= m.value; - if (this.isNegative()) { - this.iadd(m); - } - return this; - } + publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ + rsaEncryptSign: 1, + /** RSA (Encrypt only) [HAC] */ + rsaEncrypt: 2, + /** RSA (Sign only) [HAC] */ + rsaSign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ + elgamal: 16, + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsaLegacy: 22, + /** Reserved for AEDH */ + aedh: 23, + /** Reserved for AEDSA */ + aedsa: 24, + /** X25519 (Encrypt only) */ + x25519: 25, + /** X448 (Encrypt only) */ + x448: 26, + /** Ed25519 (Sign only) */ + ed25519: 27, + /** Ed448 (Sign only) */ + ed448: 28 + }, - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + * @enum {Integer} + * @readonly */ - mod(m) { - return this.clone().imod(m); - } + symmetric: { + /** Not implemented! */ + idea: 1, + tripledes: 2, + cast5: 3, + blowfish: 4, + aes128: 7, + aes192: 8, + aes256: 9, + twofish: 10 + }, - /** - * Compute modular exponentiation using square and multiply - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + * @enum {Integer} + * @readonly */ - modExp(e, n) { - if (n.isZero()) throw Error('Modulo cannot be zero'); - if (n.isOne()) return new BigInteger(0); - if (e.isNegative()) throw Error('Unsopported negative exponent'); - - let exp = e.value; - let x = this.value; - - x %= n.value; - let r = BigInt(1); - while (exp > BigInt(0)) { - const lsb = exp & BigInt(1); - exp >>= BigInt(1); // e / 2 - // Always compute multiplication step, to reduce timing leakage - const rx = (r * x) % n.value; - // Update r only if lsb is 1 (odd exponent) - r = lsb ? rx : r; - x = (x * x) % n.value; // Square - } - return new BigInteger(r); - } - + compression: { + uncompressed: 0, + /** RFC1951 */ + zip: 1, + /** RFC1950 */ + zlib: 2, + bzip2: 3 + }, - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - const { gcd, x } = this._egcd(n); - if (!gcd.isOne()) { - throw new Error('Inverse does not exist'); - } - return x.add(n).mod(n); - } - - /** - * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) - * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b) - * @param {BigInteger} b - Second operand - * @returns {{ gcd, x, y: BigInteger }} - */ - _egcd(b) { - let x = BigInt(0); - let y = BigInt(1); - let xPrev = BigInt(1); - let yPrev = BigInt(0); - - let a = this.value; - b = b.value; - - while (b !== BigInt(0)) { - const q = a / b; - let tmp = x; - x = xPrev - q * x; - xPrev = tmp; - - tmp = y; - y = yPrev - q * y; - yPrev = tmp; - - tmp = b; - b = a % b; - a = tmp; - } - - return { - x: new BigInteger(xPrev), - y: new BigInteger(yPrev), - gcd: new BigInteger(a) - }; - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} b - Operand - * @returns {BigInteger} gcd - */ - gcd(b) { - let a = this.value; - b = b.value; - while (b !== BigInt(0)) { - const tmp = b; - b = a % b; - a = tmp; - } - return new BigInteger(a); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value <<= x.value; - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value >>= x.value; - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value === x.value; - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value < x.value; - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value <= x.value; - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value > x.value; - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value >= x.value; - } - - isZero() { - return this.value === BigInt(0); - } - - isOne() { - return this.value === BigInt(1); - } - - isNegative() { - return this.value < BigInt(0); - } - - isEven() { - return !(this.value & BigInt(1)); - } - - abs() { - const res = this.clone(); - if (this.isNegative()) { - res.value = -res.value; - } - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - const number = Number(this.value); - if (number > Number.MAX_SAFE_INTEGER) { - // We throw and error to conform with the bn.js implementation - throw new Error('Number can only safely store up to 53 bits'); - } - return number; - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - const bit = (this.value >> BigInt(i)) & BigInt(1); - return (bit === BigInt(0)) ? 0 : 1; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - const zero = new BigInteger(0); - const one = new BigInteger(1); - const negOne = new BigInteger(-1); - - // -1n >> -1n is -1n - // 1n >> 1n is 0n - const target = this.isNegative() ? negOne : zero; - let bitlen = 1; - const tmp = this.clone(); - while (!tmp.irightShift(one).equal(target)) { - bitlen++; - } - return bitlen; - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - const zero = new BigInteger(0); - const negOne = new BigInteger(-1); - - const target = this.isNegative() ? negOne : zero; - const eight = new BigInteger(8); - let len = 1; - const tmp = this.clone(); - while (!tmp.irightShift(eight).equal(target)) { - len++; - } - return len; - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) - // this is faster than shift+mod iterations - let hex = this.value.toString(16); - if (hex.length % 2 === 1) { - hex = '0' + hex; - } - - const rawLength = hex.length / 2; - const bytes = new Uint8Array(length || rawLength); - // parse hex - const offset = length ? (length - rawLength) : 0; - let i = 0; - while (i < rawLength) { - bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); - i++; - } - - if (endian !== 'be') { - bytes.reverse(); - } - - return bytes; - } -} - -const detectBigInt = () => typeof BigInt !== 'undefined'; - -async function getBigInteger() { - if (detectBigInt()) { - return BigInteger; - } else { - const { default: BigInteger } = await import('./bn.interface.mjs'); - return BigInteger; - } -} - -/** - * @module enums - */ - -const byValue = Symbol('byValue'); - -var enums = { - - /** Maps curve names under various standards to one - * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} - * @enum {String} - * @readonly - */ - curve: { - /** NIST P-256 Curve */ - 'p256': 'p256', - 'P-256': 'p256', - 'secp256r1': 'p256', - 'prime256v1': 'p256', - '1.2.840.10045.3.1.7': 'p256', - '2a8648ce3d030107': 'p256', - '2A8648CE3D030107': 'p256', - - /** NIST P-384 Curve */ - 'p384': 'p384', - 'P-384': 'p384', - 'secp384r1': 'p384', - '1.3.132.0.34': 'p384', - '2b81040022': 'p384', - '2B81040022': 'p384', - - /** NIST P-521 Curve */ - 'p521': 'p521', - 'P-521': 'p521', - 'secp521r1': 'p521', - '1.3.132.0.35': 'p521', - '2b81040023': 'p521', - '2B81040023': 'p521', - - /** SECG SECP256k1 Curve */ - 'secp256k1': 'secp256k1', - '1.3.132.0.10': 'secp256k1', - '2b8104000a': 'secp256k1', - '2B8104000A': 'secp256k1', - - /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ - 'ed25519Legacy': 'ed25519', - 'ED25519': 'ed25519', - /** @deprecated use `ed25519Legacy` instead */ - 'ed25519': 'ed25519', - 'Ed25519': 'ed25519', - '1.3.6.1.4.1.11591.15.1': 'ed25519', - '2b06010401da470f01': 'ed25519', - '2B06010401DA470F01': 'ed25519', - - /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ - 'curve25519Legacy': 'curve25519', - 'X25519': 'curve25519', - 'cv25519': 'curve25519', - /** @deprecated use `curve25519Legacy` instead */ - 'curve25519': 'curve25519', - 'Curve25519': 'curve25519', - '1.3.6.1.4.1.3029.1.5.1': 'curve25519', - '2b060104019755010501': 'curve25519', - '2B060104019755010501': 'curve25519', - - /** BrainpoolP256r1 Curve */ - 'brainpoolP256r1': 'brainpoolP256r1', - '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1', - '2b2403030208010107': 'brainpoolP256r1', - '2B2403030208010107': 'brainpoolP256r1', - - /** BrainpoolP384r1 Curve */ - 'brainpoolP384r1': 'brainpoolP384r1', - '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1', - '2b240303020801010b': 'brainpoolP384r1', - '2B240303020801010B': 'brainpoolP384r1', - - /** BrainpoolP512r1 Curve */ - 'brainpoolP512r1': 'brainpoolP512r1', - '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1', - '2b240303020801010d': 'brainpoolP512r1', - '2B240303020801010D': 'brainpoolP512r1' - }, - - /** A string to key specifier type - * @enum {Integer} - * @readonly - */ - s2k: { - simple: 0, - salted: 1, - iterated: 3, - gnu: 101 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} - * @enum {Integer} - * @readonly - */ - publicKey: { - /** RSA (Encrypt or Sign) [HAC] */ - rsaEncryptSign: 1, - /** RSA (Encrypt only) [HAC] */ - rsaEncrypt: 2, - /** RSA (Sign only) [HAC] */ - rsaSign: 3, - /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ - elgamal: 16, - /** DSA (Sign only) [FIPS186] [HAC] */ - dsa: 17, - /** ECDH (Encrypt only) [RFC6637] */ - ecdh: 18, - /** ECDSA (Sign only) [RFC6637] */ - ecdsa: 19, - /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) - * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ - eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility - /** @deprecated use `eddsaLegacy` instead */ - ed25519Legacy: 22, - /** @deprecated use `eddsaLegacy` instead */ - eddsa: 22, - /** Reserved for AEDH */ - aedh: 23, - /** Reserved for AEDSA */ - aedsa: 24, - /** X25519 (Encrypt only) */ - x25519: 25, - /** X448 (Encrypt only) */ - x448: 26, - /** Ed25519 (Sign only) */ - ed25519: 27, - /** Ed448 (Sign only) */ - ed448: 28 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - * @enum {Integer} - * @readonly - */ - symmetric: { - plaintext: 0, - /** Not implemented! */ - idea: 1, - tripledes: 2, - cast5: 3, - blowfish: 4, - aes128: 7, - aes192: 8, - aes256: 9, - twofish: 10 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - * @enum {Integer} - * @readonly - */ - compression: { - uncompressed: 0, - /** RFC1951 */ - zip: 1, - /** RFC1950 */ - zlib: 2, - bzip2: 3 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} - * @enum {Integer} - * @readonly + /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + * @enum {Integer} + * @readonly */ hash: { md5: 1, @@ -1697,7 +1077,9 @@ var enums = { sha256: 8, sha384: 9, sha512: 10, - sha224: 11 + sha224: 11, + sha3_256: 12, + sha3_512: 14 }, /** A list of hash names as accepted by webCrypto functions. @@ -1718,6 +1100,7 @@ var enums = { aead: { eax: 1, ocb: 2, + gcm: 3, experimentalGCM: 100 // Private algorithm }, @@ -1743,7 +1126,8 @@ var enums = { userAttribute: 17, symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + padding: 21 }, /** Data types in the literal packet @@ -1899,7 +1283,7 @@ var enums = { placeholderBackwardsCompatibility: 10, preferredSymmetricAlgorithms: 11, revocationKey: 12, - issuer: 16, + issuerKeyID: 16, notationData: 20, preferredHashAlgorithms: 21, preferredCompressionAlgorithms: 22, @@ -1914,7 +1298,8 @@ var enums = { signatureTarget: 31, embeddedSignature: 32, issuerFingerprint: 33, - preferredAEADAlgorithms: 34 + preferredAEADAlgorithms: 34, + preferredCipherSuites: 39 }, /** Key flags @@ -1983,7 +1368,8 @@ var enums = { aead: 2, /** 0x04 - Version 5 Public-Key Packet format and corresponding new * fingerprint format */ - v5Keys: 4 + v5Keys: 4, + seipdv2: 8 }, /** @@ -2029,9 +1415,322 @@ var enums = { }; // GPG4Browsers - An OpenPGP implementation in javascript - -const debugMode = (() => { - try { +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +var config = { + /** + * @memberof module:config + * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} + */ + preferredHashAlgorithm: enums.hash.sha512, + /** + * @memberof module:config + * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} + */ + preferredSymmetricAlgorithm: enums.symmetric.aes256, + /** + * @memberof module:config + * @property {Integer} compression Default compression algorithm {@link module:enums.compression} + */ + preferredCompressionAlgorithm: enums.compression.uncompressed, + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * This option is applicable to: + * - key generation (encryption key preferences), + * - password-based message encryption, and + * - private key encryption. + * In the case of message encryption using public keys, the encryption key preferences are respected instead. + * Note: not all OpenPGP implementations are compatible with this option. + * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10} + * @memberof module:config + * @property {Boolean} aeadProtect + */ + aeadProtect: false, + /** + * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`) + * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`, + * this option must be set, otherwise key parsing and/or key decryption will fail. + * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys + * will be processed incorrectly. + */ + parseAEADEncryptedV4KeysAsLegacy: false, + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aeadProtect is set to true. + * @memberof module:config + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} + */ + preferredAEADAlgorithm: enums.aead.gcm, + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aeadProtect is set to true. + * Must be an integer value from 0 to 56. + * @memberof module:config + * @property {Integer} aeadChunkSizeByte + */ + aeadChunkSizeByte: 12, + /** + * Use v6 keys. + * Note: not all OpenPGP implementations are compatible with this option. + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + * @memberof module:config + * @property {Boolean} v6Keys + */ + v6Keys: false, + /** + * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet). + * These are non-standard entities, which in the crypto-refresh have been superseded + * by v6 keys and v6 signatures, respectively. + * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries, + * hence parsing them might be necessary in some cases. + */ + enableParsingV5Entities: false, + /** + * S2K (String to Key) type, used for key derivation in the context of secret key encryption + * and password-encrypted data. Weaker s2k options are not allowed. + * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it + * (pending standardisation). + * @memberof module:config + * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k} + */ + s2kType: enums.s2k.iterated, + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}: + * Iteration Count Byte for Iterated and Salted S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`. + * Note: this is the exponent value, not the final number of iterations (refer to specs for more details). + * @memberof module:config + * @property {Integer} s2kIterationCountByte + */ + s2kIterationCountByte: 224, + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}: + * Argon2 parameters for S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`. + * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"), + * to ensure compatibility with memory-constrained environments. + * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4. + * @memberof module:config + * @property {Object} params + * @property {Integer} params.passes - number of iterations t + * @property {Integer} params.parallelism - degree of parallelism p + * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes. + */ + s2kArgon2Params: { + passes: 3, + parallelism: 4, // lanes + memoryExponent: 16 // 64 MiB of RAM + }, + /** + * Allow decryption of messages without integrity protection. + * This is an **insecure** setting: + * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. + * - it enables downgrade attacks against integrity-protected messages. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedMessages + */ + allowUnauthenticatedMessages: false, + /** + * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to + * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible + * and deferring checking their integrity until the decrypted stream has been read in full. + * + * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity: + * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL + * (see https://efail.de/). + * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data. + * + * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedStream + */ + allowUnauthenticatedStream: false, + /** + * Minimum RSA key size allowed for key generation and message signing, verification and encryption. + * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. + * @memberof module:config + * @property {Number} minRSABits + */ + minRSABits: 2047, + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + * @memberof module:config + * @property {Boolean} passwordCollisionCheck + */ + passwordCollisionCheck: false, + /** + * Allow decryption using RSA keys without `encrypt` flag. + * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug + * where key flags were ignored when selecting a key for encryption. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureDecryptionWithSigningKeys: false, + /** + * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. + * Instead, a verification key will also be consider valid as long as it is valid at the current time. + * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, + * and have self-signature's creation date that does not match the primary key creation date. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureVerificationWithReformattedKeys: false, + /** + * Allow using keys that do not have any key flags set. + * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages + * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29). + * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation. + * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm. + */ + allowMissingKeyFlags: false, + /** + * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). + * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: + * - new/incoming messages are automatically decrypted (without user interaction); + * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). + * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. + * @memberof module:config + * @property {Boolean} constantTimePKCS1Decryption + */ + constantTimePKCS1Decryption: false, + /** + * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. + * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. + * However, the more algorithms are added, the slower the decryption procedure becomes. + * @memberof module:config + * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} + */ + constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), + /** + * @memberof module:config + * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error + */ + ignoreUnsupportedPackets: true, + /** + * @memberof module:config + * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error + */ + ignoreMalformedPackets: false, + /** + * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only + * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable + * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). + * @memberof module:config + * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] + */ + additionalAllowedPackets: [], + /** + * @memberof module:config + * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages + */ + showVersion: false, + /** + * @memberof module:config + * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages + */ + showComment: false, + /** + * @memberof module:config + * @property {String} versionString A version string to be included in armored messages + */ + versionString: 'OpenPGP.js 6.0.0', + /** + * @memberof module:config + * @property {String} commentString A comment string to be included in armored messages + */ + commentString: 'https://openpgpjs.org', + + /** + * Max userID string length (used for parsing) + * @memberof module:config + * @property {Integer} maxUserIDLength + */ + maxUserIDLength: 1024 * 5, + /** + * Contains notatations that are considered "known". Known notations do not trigger + * validation error when the notation is marked as critical. + * @memberof module:config + * @property {Array} knownNotations + */ + knownNotations: [], + /** + * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design). + * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur + * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of + * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks. + * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases. + */ + nonDeterministicSignaturesViaNotation: true, + /** + * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API. + * When false, certain standard curves will not be supported (depending on the platform). + * @memberof module:config + * @property {Boolean} useEllipticFallback + */ + useEllipticFallback: true, + /** + * Reject insecure hash algorithms + * @memberof module:config + * @property {Set} rejectHashAlgorithms {@link module:enums.hash} + */ + rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), + /** + * Reject insecure message hash algorithms + * @memberof module:config + * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} + */ + rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), + /** + * Reject insecure public key algorithms for key generation and message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} + */ + rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), + /** + * Reject non-standard curves for key generation, message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectCurves {@link module:enums.curve} + */ + rejectCurves: new Set([enums.curve.secp256k1]) +}; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +const createRequire = () => () => {}; // Must be stripped in browser built + +const debugMode = (() => { + try { return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env } catch (e) {} return false; @@ -2042,6 +1741,8 @@ const util = { return typeof data === 'string' || data instanceof String; }, + nodeRequire: createRequire(), + isArray: function(data) { return data instanceof Array; }, @@ -2050,6 +1751,35 @@ const util = { isStream: isStream, + /** + * Load noble-curves lib on demand and return the requested curve function + * @param {enums.publicKey} publicKeyAlgo + * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA) + * @returns curve implementation + * @throws on unrecognized curve, or curve not implemented by noble-curve + */ + getNobleCurve: async (publicKeyAlgo, curveName) => { + if (!config.useEllipticFallback) { + throw new Error('This curve is only supported in the full build of OpenPGP.js'); + } + + const { nobleCurves } = await import('./noble_curves.mjs'); + switch (publicKeyAlgo) { + case enums.publicKey.ecdh: + case enums.publicKey.ecdsa: { + const curve = nobleCurves.get(curveName); + if (!curve) throw new Error('Unsupported curve'); + return curve; + } + case enums.publicKey.x448: + return nobleCurves.get('x448'); + case enums.publicKey.ed448: + return nobleCurves.get('ed448'); + default: + throw new Error('Unsupported curve'); + } + }, + readNumber: function (bytes) { let n = 0; for (let i = 0; i < bytes.length; i++) { @@ -2091,7 +1821,26 @@ const util = { readMPI: function (bytes) { const bits = (bytes[0] << 8) | bytes[1]; const bytelen = (bits + 7) >>> 3; - return bytes.subarray(2, 2 + bytelen); + // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures, + // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed + // has not been authenticated (yet). + // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues. + // Also, AEAD is also not affected. + return util.readExactSubarray(bytes, 2, 2 + bytelen); + }, + + /** + * Read exactly `end - start` bytes from input. + * This is a stricter version of `.subarray`. + * @param {Uint8Array} input - Input data to parse + * @returns {Uint8Array} subarray of size always equal to `end - start` + * @throws if the input array is too short. + */ + readExactSubarray: function (input, start, end) { + if (input.length < (end - start)) { + throw new Error('Input array too short'); + } + return input.subarray(start, end); }, /** @@ -2101,6 +1850,9 @@ const util = { * @returns {Uint8Array} Padded bytes. */ leftPad(bytes, length) { + if (bytes.length > length) { + throw new Error('Input array too long'); + } const padded = new Uint8Array(length); const offset = length - bytes.length; padded.set(bytes, offset); @@ -2156,18 +1908,10 @@ const util = { * @returns {String} Hexadecimal representation of the array. */ uint8ArrayToHex: function (bytes) { - const r = []; - const e = bytes.length; - let c = 0; - let h; - while (c < e) { - h = bytes[c++].toString(16); - while (h.length < 2) { - h = '0' + h; - } - r.push('' + h); - } - return r.join(''); + const hexAlphabet = '0123456789abcdef'; + let s = ''; + bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; }); + return s; }, /** @@ -2378,32 +2122,30 @@ const util = { }, /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available */ getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; }, - /** - * Get BigInteger class - * It wraps the native BigInt type if it's available - * Otherwise it relies on bn.js - * @returns {BigInteger} - * @async - */ - getBigInteger, - /** * Get native Node.js crypto api. * @returns {Object} The crypto module or 'undefined'. */ getNodeCrypto: function() { - return void('crypto'); + return this.nodeRequire('crypto'); }, getNodeZlib: function() { - return void('zlib'); + return this.nodeRequire('zlib'); }, /** @@ -2412,7 +2154,7 @@ const util = { * @returns {Function} The Buffer constructor or 'undefined'. */ getNodeBuffer: function() { - return ({}).Buffer; + return (this.nodeRequire('buffer') || {}).Buffer; }, getHardwareConcurrency: function() { @@ -2420,15 +2162,24 @@ const util = { return navigator.hardwareConcurrency || 1; } - const os = void('os'); // Assume we're on Node.js. + const os = this.nodeRequire('os'); // Assume we're on Node.js. return os.cpus().length; }, + /** + * Test email format to ensure basic compliance: + * - must include a single @ + * - no control or space unicode chars allowed + * - no backslash and square brackets (as the latter can mess with the userID parsing) + * - cannot end with a punctuation char + * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation, + * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)). + */ isEmailAddress: function(data) { if (!util.isString(data)) { return false; } - const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/; + const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u; return re.test(data); }, @@ -2631,14 +2382,15 @@ const util = { * provided with the application or distribution. */ -const Buffer = util.getNodeBuffer(); + +const Buffer$2 = util.getNodeBuffer(); let encodeChunk; let decodeChunk; -if (Buffer) { - encodeChunk = buf => Buffer.from(buf).toString('base64'); +if (Buffer$2) { + encodeChunk = buf => Buffer$2.from(buf).toString('base64'); decodeChunk = str => { - const b = Buffer.from(str, 'base64'); + const b = Buffer$2.from(str, 'base64'); return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); }; } else { @@ -2652,7 +2404,7 @@ if (Buffer) { * @returns {String | ReadableStream} Radix-64 version of input string. * @static */ -function encode(data) { +function encode$1(data) { let buf = new Uint8Array(); return transform(data, value => { buf = util.concatUint8Array([buf, value]); @@ -2676,7 +2428,7 @@ function encode(data) { * @returns {Uint8Array | ReadableStream} Binary array version of input string. * @static */ -function decode(data) { +function decode$1(data) { let buf = ''; return transform(data, value => { buf += value; @@ -2712,7 +2464,7 @@ function decode(data) { * @returns {Uint8Array} An array of 8-bit integers. */ function b64ToUint8Array(base64) { - return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); + return decode$1(base64.replace(/-/g, '+').replace(/_/g, '/')); } /** @@ -2722,248 +2474,30 @@ function b64ToUint8Array(base64) { * @returns {String} Base-64 encoded string. */ function uint8ArrayToB64(bytes, url) { - let encoded = encode(bytes).replace(/[\r\n]/g, ''); - if (url) { + let encoded = encode$1(bytes).replace(/[\r\n]/g, ''); + { encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); } return encoded; } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -var config = { - /** - * @memberof module:config - * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} - */ - preferredHashAlgorithm: enums.hash.sha256, - /** - * @memberof module:config - * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} - */ - preferredSymmetricAlgorithm: enums.symmetric.aes256, - /** - * @memberof module:config - * @property {Integer} compression Default compression algorithm {@link module:enums.compression} - */ - preferredCompressionAlgorithm: enums.compression.uncompressed, - /** - * @memberof module:config - * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9 - */ - deflateLevel: 6, - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} - * @memberof module:config - * @property {Boolean} aeadProtect - */ - aeadProtect: false, - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. - * @memberof module:config - * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} - */ - preferredAEADAlgorithm: enums.aead.eax, - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. - * Must be an integer value from 0 to 56. - * @memberof module:config - * @property {Integer} aeadChunkSizeByte - */ - aeadChunkSizeByte: 12, - /** - * Use V5 keys. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @memberof module:config - * @property {Boolean} v5Keys - */ - v5Keys: false, - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - * @memberof module:config - * @property {Integer} s2kIterationCountByte - */ - s2kIterationCountByte: 224, - /** - * Allow decryption of messages without integrity protection. - * This is an **insecure** setting: - * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. - * - it enables downgrade attacks against integrity-protected messages. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedMessages - */ - allowUnauthenticatedMessages: false, - /** - * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to - * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible - * and deferring checking their integrity until the decrypted stream has been read in full. - * - * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedStream - */ - allowUnauthenticatedStream: false, - /** - * @memberof module:config - * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum - */ - checksumRequired: false, - /** - * Minimum RSA key size allowed for key generation and message signing, verification and encryption. - * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. - * @memberof module:config - * @property {Number} minRSABits - */ - minRSABits: 2047, - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - * @memberof module:config - * @property {Boolean} passwordCollisionCheck - */ - passwordCollisionCheck: false, - /** - * @memberof module:config - * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored - */ - revocationsExpire: false, - /** - * Allow decryption using RSA keys without `encrypt` flag. - * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug - * where key flags were ignored when selecting a key for encryption. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureDecryptionWithSigningKeys: false, - /** - * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. - * Instead, a verification key will also be consider valid as long as it is valid at the current time. - * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, - * and have self-signature's creation date that does not match the primary key creation date. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureVerificationWithReformattedKeys: false, - - /** - * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). - * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: - * - new/incoming messages are automatically decrypted (without user interaction); - * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). - * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. - * @memberof module:config - * @property {Boolean} constantTimePKCS1Decryption - */ - constantTimePKCS1Decryption: false, - /** - * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. - * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. - * However, the more algorithms are added, the slower the decryption procedure becomes. - * @memberof module:config - * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} - */ - constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), - - /** - * @memberof module:config - * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available - */ - minBytesForWebCrypto: 1000, - /** - * @memberof module:config - * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error - */ - ignoreUnsupportedPackets: true, - /** - * @memberof module:config - * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error - */ - ignoreMalformedPackets: false, - /** - * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only - * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable - * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). - * @memberof module:config - * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] - */ - additionalAllowedPackets: [], - /** - * @memberof module:config - * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages - */ - showVersion: false, - /** - * @memberof module:config - * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages - */ - showComment: false, - /** - * @memberof module:config - * @property {String} versionString A version string to be included in armored messages - */ - versionString: 'OpenPGP.js 5.11.2', - /** - * @memberof module:config - * @property {String} commentString A comment string to be included in armored messages - */ - commentString: 'https://openpgpjs.org', - - /** - * Max userID string length (used for parsing) - * @memberof module:config - * @property {Integer} maxUserIDLength - */ - maxUserIDLength: 1024 * 5, - /** - * Contains notatations that are considered "known". Known notations do not trigger - * validation error when the notation is marked as critical. - * @memberof module:config - * @property {Array} knownNotations - */ - knownNotations: [], - /** - * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. - * When false, certain standard curves will not be supported (depending on the platform). - * Note: the indutny/elliptic curve library is not designed to be constant time. - * @memberof module:config - * @property {Boolean} useIndutnyElliptic - */ - useIndutnyElliptic: true, - /** - * Reject insecure hash algorithms - * @memberof module:config - * @property {Set} rejectHashAlgorithms {@link module:enums.hash} - */ - rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), - /** - * Reject insecure message hash algorithms - * @memberof module:config - * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} - */ - rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), - /** - * Reject insecure public key algorithms for key generation and message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} - */ - rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), - /** - * Reject non-standard curves for key generation, message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectCurves {@link module:enums.curve} - */ - rejectCurves: new Set([enums.curve.secp256k1]) -}; - -// GPG4Browsers - An OpenPGP implementation in javascript /** * Finds out which Ascii Armoring type is used. Throws error if unknown type. @@ -2991,33 +2525,33 @@ function getType(text) { // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipartSection; - } else + } // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipartLast; - } else + } // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; - } else + } // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; - } else + } // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.publicKey; - } else + } // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.privateKey; - } else + } // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE @@ -3051,7 +2585,6 @@ function addheader(customComment, config) { return result; } - /** * Calculates a checksum over the given data and returns it base64 encoded * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for @@ -3060,7 +2593,7 @@ function addheader(customComment, config) { */ function getCheckSum(data) { const crc = createcrc24(data); - return encode(crc); + return encode$1(crc); } // https://create.stephan-brumme.com/crc32/#slicing-by-8-overview @@ -3133,7 +2666,7 @@ function createcrc24(input) { * @private * @param {Array} headers - Armor headers */ -function verifyHeaders(headers) { +function verifyHeaders$1(headers) { for (let i = 0; i < headers.length; i++) { if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); @@ -3145,24 +2678,21 @@ function verifyHeaders(headers) { } /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param {String} text - OpenPGP armored message part - * @returns {Object} An object with attribute "body" containing the body. - * and an attribute "checksum" containing the checksum. + * Remove the (optional) checksum from an armored message. + * @param {String} text - OpenPGP armored message + * @returns {String} The body of the armored message. * @private */ -function splitChecksum(text) { +function removeChecksum(text) { let body = text; - let checksum = ''; const lastEquals = text.lastIndexOf('='); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); - checksum = text.slice(lastEquals + 1).substr(0, 4); } - return { body: body, checksum: checksum }; + return body; } /** @@ -3174,7 +2704,7 @@ function splitChecksum(text) { * @async * @static */ -function unarmor(input, config$1 = config) { +function unarmor(input) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { @@ -3187,8 +2717,7 @@ function unarmor(input, config$1 = config) { let headersDone; let text = []; let textDone; - let checksum; - let data = decode(transformPair(input, async (readable, writable) => { + const data = decode$1(transformPair(input, async (readable, writable) => { const reader = getReader(readable); try { while (true) { @@ -3209,21 +2738,21 @@ function unarmor(input, config$1 = config) { if (!reEmptyLine.test(line)) { lastHeaders.push(line); } else { - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); headersDone = true; - if (textDone || type !== 2) { + if (textDone || type !== enums.armor.signed) { resolve({ text, data, headers, type }); break; } } - } else if (!textDone && type === 2) { + } else if (!textDone && type === enums.armor.signed) { if (!reSplit.test(line)) { // Reverse dash-escaping for msg text.push(line.replace(/^- /, '')); } else { text = text.join('\r\n'); textDone = true; - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); lastHeaders = []; headersDone = false; } @@ -3253,9 +2782,8 @@ function unarmor(input, config$1 = config) { if (parts.length === 1) { throw new Error('Misformed armored text'); } - const split = splitChecksum(parts[0].slice(0, -1)); - checksum = split.checksum; - await writer.write(split.body); + const body = removeChecksum(parts[0].slice(0, -1)); + await writer.write(body); break; } } @@ -3265,24 +2793,6 @@ function unarmor(input, config$1 = config) { await writer.abort(e); } })); - data = transformPair(data, async (readable, writable) => { - const checksumVerified = readToEnd(getCheckSum(passiveClone(readable))); - checksumVerified.catch(() => {}); - await pipe(readable, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - const checksumVerifiedString = (await checksumVerified).replace('\n', ''); - if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) { - throw new Error('Ascii armor integrity check failed'); - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); } catch (e) { reject(e); } @@ -3302,10 +2812,13 @@ function unarmor(input, config$1 = config) { * @param {Integer} [partIndex] * @param {Integer} [partTotal] * @param {String} [customComment] - Additional comment to add to the armored string + * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum + * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks) + * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {String | ReadableStream} Armored text. * @static */ -function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) { +function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) { let text; let hash; if (messageType === enums.armor.signed) { @@ -3313,59 +2826,62 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 hash = body.hash; body = body.data; } - const bodyClone = passiveClone(body); + // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug + // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071) + const maybeBodyClone = emitChecksum && passiveClone(body); + const result = []; switch (messageType) { case enums.armor.multipartSection: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); break; case enums.armor.multipartLast: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); break; case enums.armor.signed: result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); - result.push('Hash: ' + hash + '\n\n'); + result.push(hash ? `Hash: ${hash}\n\n` : '\n'); result.push(text.replace(/^-/mg, '- -')); result.push('\n-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; case enums.armor.message: result.push('-----BEGIN PGP MESSAGE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE-----\n'); break; case enums.armor.publicKey: result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); break; case enums.armor.privateKey: result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); break; case enums.armor.signature: result.push('-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; } @@ -3373,19653 +2889,9715 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 return util.concat(result); } -// GPG4Browsers - An OpenPGP implementation in javascript +async function getLegacyCipher(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + throw new Error('Not a legacy cipher'); + case enums.symmetric.cast5: + case enums.symmetric.blowfish: + case enums.symmetric.twofish: + case enums.symmetric.tripledes: { + const { legacyCiphers } = await import('./legacy_ciphers.mjs'); + const cipher = legacyCiphers.get(algo); + if (!cipher) { + throw new Error('Unsupported cipher algorithm'); + } + return cipher; + } + default: + throw new Error('Unsupported cipher algorithm'); + } +} /** - * Implementation of type key id - * - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. + * Get block size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -class KeyID { - constructor() { - this.bytes = ''; +function getCipherBlockSize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 16; + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + case enums.symmetric.tripledes: + return 8; + default: + throw new Error('Unsupported cipher'); } +} - /** - * Parsing method for a key id - * @param {Uint8Array} bytes - Input to read the key id from - */ - read(bytes) { - this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); - return this.bytes.length; - } - - /** - * Serializes the Key ID - * @returns {Uint8Array} Key ID as a Uint8Array. - */ - write() { - return util.stringToUint8Array(this.bytes); - } - - /** - * Returns the Key ID represented as a hexadecimal string - * @returns {String} Key ID as a hexadecimal string. - */ - toHex() { - return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); - } - - /** - * Checks equality of Key ID's - * @param {KeyID} keyID - * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard - */ - equals(keyID, matchWildcard = false) { - return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; - } - - /** - * Checks to see if the Key ID is unset - * @returns {Boolean} True if the Key ID is null. - */ - isNull() { - return this.bytes === ''; - } - - /** - * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) - * @returns {Boolean} True if this is a wildcard Key ID. - */ - isWildcard() { - return /^0+$/.test(this.toHex()); - } - - static mapToHex(keyID) { - return keyID.toHex(); - } - - static fromID(hex) { - const keyID = new KeyID(); - keyID.read(util.hexToUint8Array(hex)); - return keyID; - } - - static wildcard() { - const keyID = new KeyID(); - keyID.read(new Uint8Array(8)); - return keyID; +/** + * Get key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherKeySize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + return 16; + case enums.symmetric.aes192: + case enums.symmetric.tripledes: + return 24; + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 32; + default: + throw new Error('Unsupported cipher'); } } /** - * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. - * @author Artem S Vybornov - * @license MIT + * Get block and key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -var AES_asm = function () { +function getCipherParams(algo) { + return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) }; +} - /** - * Galois Field stuff init flag - */ - var ginit_done = false; +var cipher = /*#__PURE__*/Object.freeze({ + __proto__: null, + getCipherParams: getCipherParams, + getLegacyCipher: getLegacyCipher +}); - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; +/** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ - /** - * Init Galois Field tables - */ - function ginit() { - gexp3 = [], - glog3 = []; - var a = 1, c, d; - for (c = 0; c < 255; c++) { - gexp3[c] = a; +// MD5 Digest +async function md5(entree) { + const digest = md51(util.uint8ArrayToString(entree)); + return util.hexToUint8Array(hex(digest)); +} - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if (d === 0x80) a ^= 0x1b; - a ^= gexp3[c]; +function md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; + a = ff(a, b, c, d, k[0], 7, -680876936); + d = ff(d, a, b, c, k[1], 12, -389564586); + c = ff(c, d, a, b, k[2], 17, 606105819); + b = ff(b, c, d, a, k[3], 22, -1044525330); + a = ff(a, b, c, d, k[4], 7, -176418897); + d = ff(d, a, b, c, k[5], 12, 1200080426); + c = ff(c, d, a, b, k[6], 17, -1473231341); + b = ff(b, c, d, a, k[7], 22, -45705983); + a = ff(a, b, c, d, k[8], 7, 1770035416); + d = ff(d, a, b, c, k[9], 12, -1958414417); + c = ff(c, d, a, b, k[10], 17, -42063); + b = ff(b, c, d, a, k[11], 22, -1990404162); + a = ff(a, b, c, d, k[12], 7, 1804603682); + d = ff(d, a, b, c, k[13], 12, -40341101); + c = ff(c, d, a, b, k[14], 17, -1502002290); + b = ff(b, c, d, a, k[15], 22, 1236535329); - ginit_done = true; - } + a = gg(a, b, c, d, k[1], 5, -165796510); + d = gg(d, a, b, c, k[6], 9, -1069501632); + c = gg(c, d, a, b, k[11], 14, 643717713); + b = gg(b, c, d, a, k[0], 20, -373897302); + a = gg(a, b, c, d, k[5], 5, -701558691); + d = gg(d, a, b, c, k[10], 9, 38016083); + c = gg(c, d, a, b, k[15], 14, -660478335); + b = gg(b, c, d, a, k[4], 20, -405537848); + a = gg(a, b, c, d, k[9], 5, 568446438); + d = gg(d, a, b, c, k[14], 9, -1019803690); + c = gg(c, d, a, b, k[3], 14, -187363961); + b = gg(b, c, d, a, k[8], 20, 1163531501); + a = gg(a, b, c, d, k[13], 5, -1444681467); + d = gg(d, a, b, c, k[2], 9, -51403784); + c = gg(c, d, a, b, k[7], 14, 1735328473); + b = gg(b, c, d, a, k[12], 20, -1926607734); - /** - * Galois Field multiplication - * @param {number} a - * @param {number} b - * @return {number} - */ - function gmul(a, b) { - var c = gexp3[(glog3[a] + glog3[b]) % 255]; - if (a === 0 || b === 0) c = 0; - return c; - } + a = hh(a, b, c, d, k[5], 4, -378558); + d = hh(d, a, b, c, k[8], 11, -2022574463); + c = hh(c, d, a, b, k[11], 16, 1839030562); + b = hh(b, c, d, a, k[14], 23, -35309556); + a = hh(a, b, c, d, k[1], 4, -1530992060); + d = hh(d, a, b, c, k[4], 11, 1272893353); + c = hh(c, d, a, b, k[7], 16, -155497632); + b = hh(b, c, d, a, k[10], 23, -1094730640); + a = hh(a, b, c, d, k[13], 4, 681279174); + d = hh(d, a, b, c, k[0], 11, -358537222); + c = hh(c, d, a, b, k[3], 16, -722521979); + b = hh(b, c, d, a, k[6], 23, 76029189); + a = hh(a, b, c, d, k[9], 4, -640364487); + d = hh(d, a, b, c, k[12], 11, -421815835); + c = hh(c, d, a, b, k[15], 16, 530742520); + b = hh(b, c, d, a, k[2], 23, -995338651); - /** - * Galois Field reciprocal - * @param {number} a - * @return {number} - */ - function ginv(a) { - var i = gexp3[255 - glog3[a]]; - if (a === 0) i = 0; - return i; - } + a = ii(a, b, c, d, k[0], 6, -198630844); + d = ii(d, a, b, c, k[7], 10, 1126891415); + c = ii(c, d, a, b, k[14], 15, -1416354905); + b = ii(b, c, d, a, k[5], 21, -57434055); + a = ii(a, b, c, d, k[12], 6, 1700485571); + d = ii(d, a, b, c, k[3], 10, -1894986606); + c = ii(c, d, a, b, k[10], 15, -1051523); + b = ii(b, c, d, a, k[1], 21, -2054922799); + a = ii(a, b, c, d, k[8], 6, 1873313359); + d = ii(d, a, b, c, k[15], 10, -30611744); + c = ii(c, d, a, b, k[6], 15, -1560198380); + b = ii(b, c, d, a, k[13], 21, 1309151649); + a = ii(a, b, c, d, k[4], 6, -145523070); + d = ii(d, a, b, c, k[11], 10, -1120210379); + c = ii(c, d, a, b, k[2], 15, 718787259); + b = ii(b, c, d, a, k[9], 21, -343485551); - /** - * AES stuff init flag - */ - var aes_init_done = false; + x[0] = add32(a, x[0]); + x[1] = add32(b, x[1]); + x[2] = add32(c, x[2]); + x[3] = add32(d, x[3]); +} - /** - * Encryption, Decryption, S-Box and KeyTransform tables - * - * @type {number[]} - */ - var aes_sbox; +function cmn(q, a, b, x, s, t) { + a = add32(add32(a, q), add32(x, t)); + return add32((a << s) | (a >>> (32 - s)), b); +} - /** - * @type {number[]} - */ - var aes_sinv; +function ff(a, b, c, d, x, s, t) { + return cmn((b & c) | ((~b) & d), a, b, x, s, t); +} - /** - * @type {number[][]} - */ - var aes_enc; +function gg(a, b, c, d, x, s, t) { + return cmn((b & d) | (c & (~d)), a, b, x, s, t); +} - /** - * @type {number[][]} - */ - var aes_dec; +function hh(a, b, c, d, x, s, t) { + return cmn(b ^ c ^ d, a, b, x, s, t); +} - /** - * Init AES tables - */ - function aes_init() { - if (!ginit_done) ginit(); +function ii(a, b, c, d, x, s, t) { + return cmn(c ^ (b | (~d)), a, b, x, s, t); +} - // Calculates AES S-Box value - function _s(a) { - var c, s, x; - s = x = ginv(a); - for (c = 0; c < 4; c++) { - s = ((s << 1) | (s >>> 7)) & 255; - x ^= s; - } - x ^= 99; - return x; - } - - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [[], [], [], []], - aes_dec = [[], [], [], []]; - - for (var i = 0; i < 256; i++) { - var s = _s(i); - - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; - - // Ecryption and Decryption tables - aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s); - aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i); - // Rotate tables - for (var t = 1; t < 4; t++) { - aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24); - aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24); - } +function md51(s) { + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; + for (i = 64; i <= s.length; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); + } + s = s.substring(i - 64); + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < s.length; i++) { + tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + } + tail[i >> 2] |= 0x80 << ((i % 4) << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i++) { + tail[i] = 0; } + } + tail[14] = n * 8; + md5cycle(state, tail); + return state; +} - aes_init_done = true; +/* there needs to be support for Unicode here, + * unless we pretend that we can redefine the MD-5 + * algorithm for multi-byte characters (perhaps + * by adding every four 16-bit characters and + * shortening the sum to 32 bits). Otherwise + * I suggest performing MD-5 as if every character + * was two bytes--e.g., 0040 0025 = @%--but then + * how will an ordinary MD-5 sum be matched? + * There is no way to standardize text to something + * like UTF-8 before transformation; speed cost is + * utterly prohibitive. The JavaScript standard + * itself needs to look at this: it should start + * providing access to strings as preformed UTF-8 + * 8-bit unsigned value arrays. + */ +function md5blk(s) { /* I figured global was faster. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << + 24); } + return md5blks; +} - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-   * 0x0000   encryption key schedule
-   * 0x0400   decryption key schedule
-   * 0x0800   sbox
-   * 0x0c00   inv sbox
-   * 0x1000   encryption tables
-   * 0x2000   decryption tables
-   * 0x3000   reserved (future GCM multiplication lookup table)
-   * 0x4000   data
-   * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param foreign - ignored - * @param buffer - heap buffer to link with - */ - var wrapper = function (foreign, buffer) { - // Init AES stuff for the first time - if (!aes_init_done) aes_init(); - - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set(aes_sbox, 0x0800 >> 2); - heap.set(aes_sinv, 0x0c00 >> 2); - for (var i = 0; i < 4; i++) { - heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2); - heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2); - } +const hex_chr = '0123456789abcdef'.split(''); - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {number} k0 - key vector components - * @param {number} k1 - key vector components - * @param {number} k2 - key vector components - * @param {number} k3 - key vector components - * @param {number} k4 - key vector components - * @param {number} k5 - key vector components - * @param {number} k6 - key vector components - * @param {number} k7 - key vector components - */ - function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { - var ekeys = heap.subarray(0x000, 60), - dkeys = heap.subarray(0x100, 0x100 + 60); - - // Encryption key schedule - ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); - for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { - var k = ekeys[i - 1]; - if ((i % ks === 0) || (ks === 8 && i % ks === 4)) { - k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; - } - if (i % ks === 0) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0); - } - ekeys[i] = ekeys[i - ks] ^ k; - } +function rhex(n) { + let s = ''; + let j = 0; + for (; j < 4; j++) { + s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; + } + return s; +} - // Decryption key schedule - for (var j = 0; j < i; j += 4) { - for (var jj = 0; jj < 4; jj++) { - var k = ekeys[i - (4 + j) + (4 - jj) % 4]; - if (j < 4 || j >= i - 4) { - dkeys[j + jj] = k; - } else { - dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] - ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] - ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] - ^ aes_dec[3][aes_sbox[k & 255]]; - } - } - } +function hex(x) { + for (let i = 0; i < x.length; i++) { + x[i] = rhex(x[i]); + } + return x.join(''); +} - // Set rounds number - asm.set_rounds(ks + 5); - } +/* this function is much faster, +so if possible we use it. Some IEs +are the only ones I know of that +need the idiotic second function, +generated by an if clause. */ - // create library object with necessary properties - var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array}; +function add32(a, b) { + return (a + b) & 0xFFFFFFFF; +} - var asm = function (stdlib, foreign, buffer) { - "use asm"; +/** + * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. + * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} + * @see {@link https://github.com/indutny/hash.js|hash.js} + * @module crypto/hash + */ - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); +const webCrypto$a = util.getWebCrypto(); +const nodeCrypto$9 = util.getNodeCrypto(); +const nodeCryptoHashes = nodeCrypto$9 && nodeCrypto$9.getHashes(); - /** - * AES core - * @param {number} k - precomputed key schedule offset - * @param {number} s - precomputed sbox table offset - * @param {number} t - precomputed round table offset - * @param {number} r - number of inner rounds to perform - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _core(k, s, t, r, x0, x1, x2, x3) { - k = k | 0; - s = s | 0; - t = t | 0; - r = r | 0; - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k | 0) >> 2], - x1 = x1 ^ HEAP[(k | 4) >> 2], - x2 = x2 ^ HEAP[(k | 8) >> 2], - x3 = x3 ^ HEAP[(k | 12) >> 2]; - - // round 1..r - for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) { - y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } +function nodeHash(type) { + if (!nodeCrypto$9 || !nodeCryptoHashes.includes(type)) { + return; + } + return async function (data) { + const shasum = nodeCrypto$9.createHash(type); + return transform(data, value => { + shasum.update(value); + }, () => new Uint8Array(shasum.digest())); + }; +} - // final round - S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - } +function nobleHash(nobleHashName, webCryptoHashName) { + const getNobleHash = async () => { + const { nobleHashes } = await import('./noble_hashes.mjs'); + const hash = nobleHashes.get(nobleHashName); + if (!hash) throw new Error('Unsupported hash'); + return hash; + }; - /** - * ECB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } + return async function(data) { + if (isArrayStream(data)) { + data = await readToEnd(data); + } + if (util.isStream(data)) { + const hash = await getNobleHash(); - /** - * ECB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); + const hashInstance = hash.create(); + return transform(data, value => { + hashInstance.update(value); + }, () => hashInstance.digest()); + } else if (webCrypto$a && webCryptoHashName) { + return new Uint8Array(await webCrypto$a.digest(webCryptoHashName, data)); + } else { + const hash = await getNobleHash(); - t = S1, S1 = S3, S3 = t; - } + return hash(data); + } + }; +} +var hash = { - /** - * CBC mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); + /** @see module:md5 */ + md5: nodeHash('md5') || md5, + sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'), + sha224: nodeHash('sha224') || nobleHash('sha224'), + sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'), + sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'), + sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'), + ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'), + sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'), + sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'), - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } + /** + * Create a hash on the specified data using the specified algorithm + * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param {Uint8Array} data - Data to be hashed + * @returns {Promise} Hash value. + */ + digest: function(algo, data) { + switch (algo) { + case enums.hash.md5: + return this.md5(data); + case enums.hash.sha1: + return this.sha1(data); + case enums.hash.ripemd: + return this.ripemd(data); + case enums.hash.sha256: + return this.sha256(data); + case enums.hash.sha384: + return this.sha384(data); + case enums.hash.sha512: + return this.sha512(data); + case enums.hash.sha224: + return this.sha224(data); + case enums.hash.sha3_256: + return this.sha3_256(data); + case enums.hash.sha3_512: + return this.sha3_512(data); + default: + throw new Error('Unsupported hash function'); + } + }, - /** - * CBC mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns {Integer} Size in bytes of the resulting hash. + */ + getHashByteLength: function(algo) { + switch (algo) { + case enums.hash.md5: + return 16; + case enums.hash.sha1: + case enums.hash.ripemd: + return 20; + case enums.hash.sha256: + return 32; + case enums.hash.sha384: + return 48; + case enums.hash.sha512: + return 64; + case enums.hash.sha224: + return 28; + case enums.hash.sha3_256: + return 32; + case enums.hash.sha3_512: + return 64; + default: + throw new Error('Invalid hash algorithm.'); + } + } +}; - t = S1, S1 = S3, S3 = t; +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// Cast array to different type +const u8$1 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + else if (isBytes(data)) + data = copyBytes(data); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = 0; + const l = 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +// copy bytes to new u8a (aligned). Because Buffer.slice is broken. +function copyBytes(bytes) { + return Uint8Array.from(bytes); +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE$1 = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32$1(ZEROS16); +const POLY$1 = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2$1 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE$1; + this.outputLen = BLOCK_SIZE$1; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes(key); + bytes(key, 16); + const kView = createView(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes(data); + exists(this); + const b32 = u32$1(data); + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + const left = data.length % BLOCK_SIZE$1; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + clean(ZEROS32); // clean tmp buffer + } + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32$1(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE$1); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes(key); + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + data = toBytes(data); + exists(this); + const b32 = u32$1(data); + const left = data.length % BLOCK_SIZE$1; + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + clean(ZEROS32); + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32$1(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + +// prettier-ignore +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// The byte swap operation for uint32 (LE<->BE) +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +function expandKeyLE(key) { + bytes(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const toClean = []; + if (!isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = u32$1(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; +} +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (dst === undefined) + return new Uint8Array(len); + bytes(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + if (!isAligned32(dst)) + throw new Error('unaligned dst'); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + bytes(nonce, BLOCK_SIZE); + bytes(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32$1(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32$1(src); + const dst32 = u32$1(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + bytes(nonce, BLOCK_SIZE); + bytes(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32$1(ctr); + const view = createView(ctr); + const src32 = u32$1(src); + const dst32 = u32$1(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + bytes(key); + bytes(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + bytes(buf); + if (dst !== undefined) { + bytes(dst); + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + bytes(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + bytes(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (!isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32$1(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32$1(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error('aes/pcks5: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error('aes/pcks5: wrong padding'); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error('aes/pcks5: wrong padding'); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32$1(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + bytes(key); + bytes(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$1(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$1(_iv); + const out = getDst(ciphertext.length, dst); + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32$1(ciphertext); + const o = u32$1(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$6(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); + } + clean(...toClean); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +const cfb$1 = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + bytes(key); + bytes(iv, 16); + function processCfb(src, isEncrypt, dst) { + bytes(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32$1(src); + const dst32 = u32$1(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32$1(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$6(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + const buf = u8$1(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD == null ? 0 : AAD.length; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView(num); + if (AAD) + setBigUint64(view, 0, BigInt(aadLength * 8), isLE); + setBigUint64(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} +/** + * GCM: Galois/Counter Mode. + * Modern, parallel version of CTR, with MAC. + * Be careful: MACs can be forged. + * Unsafe to use random nonces under the same key, due to collision chance. + * As for nonce size, prefer 12-byte, instead of 8-byte. + */ +const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + bytes(key); + bytes(nonce); + if (AAD !== undefined) + bytes(AAD); + // NIST 800-38d doesn't enforce minimum nonce length. + // We enforce 8 bytes for compat with openssl. + // 12 bytes are recommended. More than 12 bytes would be converted into 12. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); + } + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView(nonceLen); + setBigUint64(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + bytes(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + bytes(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + if (!equalBytes(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + bytes(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32$1(block); + let { s0, s1, s2, s3 } = encrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + bytes(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32$1(block); + let { s0, s1, s2, s3 } = decrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +/** + * AES-W (base for AESKW/AESKWP). + * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf), + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/). + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints. + // If you need it larger, open an issue. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32$1(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i + (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); // out = A || out + } + xk.fill(0); + }, + decrypt(kek, out) { + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32$1(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap(ctr); + const { s0, s1, s2, s3 } = decrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); + } + xk.fill(0); + }, +}; +const AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * For padded version, use aeskwp. + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf). + */ +const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + bytes(plaintext); + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + bytes(ciphertext); + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, +})); +// Private, unsafe low-level methods. Can change at any time. +const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt: encrypt$6, + decrypt: decrypt$6, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; - /** - * CFB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } +// Modified by ProtonTech AG - /** - * CFB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); +const webCrypto$9 = util.getWebCrypto(); +const nodeCrypto$8 = util.getNodeCrypto(); + +const knownAlgos = nodeCrypto$8 ? nodeCrypto$8.getCiphers() : []; +const nodeAlgos = { + idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ + tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, + cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, + blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, + aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, + aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, + aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined + /* twofish is not implemented in OpenSSL */ +}; - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; +/** + * CFB encryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} plaintext + * @param {Uint8Array} iv + * @param {Object} config - full configuration, defaults to openpgp.config + * @returns MaybeStream + */ +async function encrypt$5(algo, key, plaintext, iv, config) { + const algoName = enums.read(enums.symmetric, algo); + if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. + return nodeEncrypt$1(algo, key, plaintext, iv); + } + if (util.isAES(algo)) { + return aesEncrypt(algo, key, plaintext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; + const blockc = iv.slice(); + let pt = new Uint8Array(); + const process = chunk => { + if (chunk) { + pt = util.concatUint8Array([pt, chunk]); + } + const ciphertext = new Uint8Array(pt.length); + let i; + let j = 0; + while (chunk ? pt.length >= block_size : pt.length) { + const encblock = cipherfn.encrypt(blockc); + for (i = 0; i < block_size; i++) { + blockc[i] = pt[i] ^ encblock[i]; + ciphertext[j++] = blockc[i]; } + pt = pt.subarray(block_size); + } + return ciphertext.subarray(0, j); + }; + return transform(plaintext, process, process); +} - /** - * OFB mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ofb(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); +/** + * CFB decryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} ciphertext + * @param {Uint8Array} iv + * @returns MaybeStream + */ +async function decrypt$5(algo, key, ciphertext, iv) { + const algoName = enums.read(enums.symmetric, algo); + if (nodeCrypto$8 && nodeAlgos[algoName]) { // Node crypto library. + return nodeDecrypt$1(algo, key, ciphertext, iv); + } + if (util.isAES(algo)) { + return aesDecrypt(algo, key, ciphertext, iv); + } - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; + let blockp = iv; + let ct = new Uint8Array(); + const process = chunk => { + if (chunk) { + ct = util.concatUint8Array([ct, chunk]); + } + const plaintext = new Uint8Array(ct.length); + let i; + let j = 0; + while (chunk ? ct.length >= block_size : ct.length) { + const decblock = cipherfn.encrypt(blockp); + blockp = ct.subarray(0, block_size); + for (i = 0; i < block_size; i++) { + plaintext[j++] = blockp[i] ^ decblock[i]; } + ct = ct.subarray(block_size); + } + return plaintext.subarray(0, j); + }; + return transform(ciphertext, process, process); +} - /** - * CTR mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ctr(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); +class WebCryptoEncryptor { + constructor(algo, key, iv) { + const { blockSize } = getCipherParams(algo); + this.key = key; + this.prevBlock = iv; + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + this.zeroBlock = new Uint8Array(this.blockSize); + } - N3 = (~M3 & N3) | M3 & (N3 + 1); - N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0)); - N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0)); - N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0)); + static async isSupported(algo) { + const { keySize } = getCipherParams(algo); + return webCrypto$9.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt']) + .then(() => true, () => false); + } - S0 = S0 ^ x0; - S1 = S1 ^ x1; - S2 = S2 ^ x2; - S3 = S3 ^ x3; - } + async _runCBC(plaintext, nonZeroIV) { + const mode = 'AES-CBC'; + this.keyRef = this.keyRef || await webCrypto$9.importKey('raw', this.key, mode, false, ['encrypt']); + const ciphertext = await webCrypto$9.encrypt( + { name: mode, iv: nonZeroIV || this.zeroBlock }, + this.keyRef, + plaintext + ); + return new Uint8Array(ciphertext).subarray(0, plaintext.length); + } + + async encryptChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const plaintext = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + const toEncrypt = util.concatUint8Array([ + this.prevBlock, + plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock + ]); - /** - * GCM mode MAC calculation - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _gcm_mac(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0 | 0, - y1 = H1 | 0, - y2 = H2 | 0, - y3 = H3 | 0; - - for (; (i | 0) < 128; i = (i + 1) | 0) { - if (y0 >>> 31) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } + const encryptedBlocks = await this._runCBC(toEncrypt); + xorMut$1(encryptedBlocks, plaintext); + this.prevBlock = encryptedBlocks.slice(-this.blockSize); - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - c = x3 & 1; + return encryptedBlocks; + } - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); + this.i += added.length; + let encryptedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + const curBlock = this.nextBlock; + encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + this.prevBlock = encryptedBlock.slice(); + this.i = 0; - if (c) x0 = x0 ^ 0xe1000000; - } + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + encryptedBlock = new Uint8Array(); + } - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } + return encryptedBlock; + } - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {number} r - number if inner AES rounds - */ - function set_rounds(r) { - r = r | 0; - R = r; - } + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + this.nextBlock = this.nextBlock.subarray(0, this.i); + const curBlock = this.nextBlock; + const encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + result = encryptedBlock.subarray(0, curBlock.length); + } - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {number} s0 - state vector - * @param {number} s1 - state vector - * @param {number} s2 - state vector - * @param {number} s3 - state vector - */ - function set_state(s0, s1, s2, s3) { - s0 = s0 | 0; - s1 = s1 | 0; - s2 = s2 | 0; - s3 = s3 | 0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } + this.clearSensitiveData(); + return result; + } - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {number} i0 - iv vector - * @param {number} i1 - iv vector - * @param {number} i2 - iv vector - * @param {number} i3 - iv vector - */ - function set_iv(i0, i1, i2, i3) { - i0 = i0 | 0; - i1 = i1 | 0; - i2 = i2 | 0; - i3 = i3 | 0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.keyRef = null; + this.key = null; + } - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} n0 - nonce vector - * @param {number} n1 - nonce vector - * @param {number} n2 - nonce vector - * @param {number} n3 - nonce vector - */ - function set_nonce(n0, n1, n2, n3) { - n0 = n0 | 0; - n1 = n1 | 0; - n2 = n2 | 0; - n3 = n3 | 0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } + async encrypt(plaintext) { + // plaintext is internally padded to block length before encryption + const encryptedWithPadding = await this._runCBC( + util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), + this.iv + ); + // drop encrypted padding + const ct = encryptedWithPadding.subarray(0, plaintext.length); + xorMut$1(ct, plaintext); + this.clearSensitiveData(); + return ct; + } +} - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} m0 - counter mask vector - * @param {number} m1 - counter mask vector - * @param {number} m2 - counter mask vector - * @param {number} m3 - counter mask vector - */ - function set_mask(m0, m1, m2, m3) { - m0 = m0 | 0; - m1 = m1 | 0; - m2 = m2 | 0; - m3 = m3 | 0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } +class NobleStreamProcessor { + constructor(forEncryption, algo, key, iv) { + this.forEncryption = forEncryption; + const { blockSize } = getCipherParams(algo); + this.key = unsafe.expandKeyLE(key); - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} c0 - counter vector - * @param {number} c1 - counter vector - * @param {number} c2 - counter vector - * @param {number} c3 - counter vector - */ - function set_counter(c0, c1, c2, c3) { - c0 = c0 | 0; - c1 = c1 | 0; - c2 = c2 | 0; - c3 = c3 | 0; - - N3 = (~M3 & N3) | M3 & c3, - N2 = (~M2 & N2) | M2 & c2, - N1 = (~M1 & N1) | M1 & c1, - N0 = (~M0 & N0) | M0 & c0; - } + if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers + this.prevBlock = getUint32Array(iv); + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + } - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_state(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; + _runCFB(src) { + const src32 = getUint32Array(src); + const dst = new Uint8Array(src.length); + const dst32 = getUint32Array(dst); + for (let i = 0; i + 4 <= dst32.length; i += 4) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4); + } + return dst; + } - return 16; - } + async processChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_iv(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = I0 >>> 24, - DATA[pos | 1] = I0 >>> 16 & 255, - DATA[pos | 2] = I0 >>> 8 & 255, - DATA[pos | 3] = I0 & 255, - DATA[pos | 4] = I1 >>> 24, - DATA[pos | 5] = I1 >>> 16 & 255, - DATA[pos | 6] = I1 >>> 8 & 255, - DATA[pos | 7] = I1 & 255, - DATA[pos | 8] = I2 >>> 24, - DATA[pos | 9] = I2 >>> 16 & 255, - DATA[pos | 10] = I2 >>> 8 & 255, - DATA[pos | 11] = I2 & 255, - DATA[pos | 12] = I3 >>> 24, - DATA[pos | 13] = I3 >>> 16 & 255, - DATA[pos | 14] = I3 >>> 8 & 255, - DATA[pos | 15] = I3 & 255; + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const toProcess = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); - return 16; - } + const processedBlocks = this._runCFB(toProcess); - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init() { - _ecb_enc(0, 0, 0, 0); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function cipher(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; + return processedBlocks; + } - var ret = 0; + this.i += added.length; - if (pos & 15) return -1; + let processedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + processedBlock = this._runCFB(this.nextBlock); + this.i = 0; - while ((len | 0) >= 16) { - _cipher_modes[mode & 7]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + processedBlock = new Uint8Array(); + } - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } + return processedBlock; + } - return ret | 0; - } + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + const processedBlock = this._runCFB(this.nextBlock); - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function mac(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; + result = processedBlock.subarray(0, this.i); + } - var ret = 0; + this.clearSensitiveData(); + return result; + } - if (pos & 15) return -1; + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.key.fill(0); + } +} - while ((len | 0) >= 16) { - _mac_modes[mode & 1]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } +async function aesEncrypt(algo, key, pt, iv) { + if (webCrypto$9 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys + const cfb = new WebCryptoEncryptor(algo, key, iv); + return util.isStream(pt) ? transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt); + } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream + const cfb = new NobleStreamProcessor(true, algo, key, iv); + return transform(pt, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).encrypt(pt); +} - return ret | 0; - } +async function aesDecrypt(algo, key, ct, iv) { + if (util.isStream(ct)) { + const cfb = new NobleStreamProcessor(false, algo, key, iv); + return transform(ct, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).decrypt(ct); +} - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; +function xorMut$1(a, b) { + const aLength = Math.min(a.length, b.length); + for (let i = 0; i < aLength; i++) { + a[i] = a[i] ^ b[i]; + } +} - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [_cbc_enc, _gcm_mac]; +const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter: set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac, - }; - }(stdlib, foreign, buffer); +function nodeEncrypt$1(algo, key, pt, iv) { + const algoName = enums.read(enums.symmetric, algo); + const cipherObj = new nodeCrypto$8.createCipheriv(nodeAlgos[algoName], key, iv); + return transform(pt, value => new Uint8Array(cipherObj.update(value))); +} + +function nodeDecrypt$1(algo, key, ct, iv) { + const algoName = enums.read(enums.symmetric, algo); + const decipherObj = new nodeCrypto$8.createDecipheriv(nodeAlgos[algoName], key, iv); + return transform(ct, value => new Uint8Array(decipherObj.update(value))); +} - asm.set_key = set_key; +var cfb = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$5, + encrypt: encrypt$5 +}); - return asm; - }; +/** + * @fileoverview This module implements AES-CMAC on top of + * native AES-CBC using either the WebCrypto API or Node.js' crypto API. + * @module crypto/cmac + */ - /** - * AES enciphering mode constants - * @enum {number} - * @const - */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7, - }, - /** - * AES deciphering mode constants - * @enum {number} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7, - }, +const webCrypto$8 = util.getWebCrypto(); +const nodeCrypto$7 = util.getNodeCrypto(); - /** - * AES MAC mode constants - * @enum {number} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1, - }; - /** - * Heap data offset - * @type {number} - * @const - */ - wrapper.HEAP_DATA = 0x4000; +/** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ - return wrapper; -}(); +const blockLength$3 = 16; -function is_bytes(a) { - return a instanceof Uint8Array; -} -function _heap_init(heap, heapSize) { - const size = heap ? heap.byteLength : heapSize || 65536; - if (size & 0xfff || size <= 0) - throw new Error('heap size must be a positive integer and a multiple of 4096'); - heap = heap || new Uint8Array(new ArrayBuffer(size)); - return heap; -} -function _heap_write(heap, hpos, data, dpos, dlen) { - const hlen = heap.length - hpos; - const wlen = hlen < dlen ? hlen : dlen; - heap.set(data.subarray(dpos, dpos + wlen), hpos); - return wlen; -} -function joinBytes(...arg) { - const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0); - const ret = new Uint8Array(totalLenght); - let cursor = 0; - for (let i = 0; i < arg.length; i++) { - ret.set(arg[i], cursor); - cursor += arg[i].length; - } - return ret; -} -class IllegalStateError extends Error { - constructor(...args) { - super(...args); - } -} -class IllegalArgumentError extends Error { - constructor(...args) { - super(...args); - } -} -class SecurityError extends Error { - constructor(...args) { - super(...args); - } +/** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param {Uint8Array} data + * @param {Uint8Array} padding + */ +function rightXORMut(data, padding) { + const offset = data.length - blockLength$3; + for (let i = 0; i < blockLength$3; i++) { + data[i + offset] ^= padding[i]; + } + return data; } -const heap_pool = []; -const asm_pool = []; -class AES { - constructor(key, iv, padding = true, mode, heap, asm) { - this.pos = 0; - this.len = 0; - this.mode = mode; - // The AES object state - this.pos = 0; - this.len = 0; - this.key = key; - this.iv = iv; - this.padding = padding; - // The AES "worker" - this.acquire_asm(heap, asm); - } - acquire_asm(heap, asm) { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA); - this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer); - this.reset(this.key, this.iv); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool.push(this.heap); - asm_pool.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - reset(key, iv) { - const { asm } = this.acquire_asm(); - // Key - const keylen = key.length; - if (keylen !== 16 && keylen !== 24 && keylen !== 32) - throw new IllegalArgumentError('illegal key size'); - const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); - asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0); - // IV - if (iv !== undefined) { - if (iv.length !== 16) - throw new IllegalArgumentError('illegal iv size'); - let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); - asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); - } - else { - asm.set_iv(0, 0, 0, 0); - } - } - AES_Encrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - let result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.pos = pos; - this.len = len; - return result; - } - AES_Encrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let plen = 16 - (len % 16); - let rlen = len; - if (this.hasOwnProperty('padding')) { - if (this.padding) { - for (let p = 0; p < plen; ++p) { - heap[pos + len + p] = plen; - } - len += plen; - rlen = len; - } - else if (len % 16) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - } - else { - len += plen; - } - const result = new Uint8Array(rlen); - if (len) - asm.cipher(amode, hpos + pos, len); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - AES_Decrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let plen = 0; - let wlen = 0; - if (this.padding) { - plen = len + dlen - rlen || 16; - rlen -= plen; - } - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.pos = pos; - this.len = len; - return result; - } - AES_Decrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let rlen = len; - if (len > 0) { - if (len % 16) { - if (this.hasOwnProperty('padding')) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - else { - len += 16 - (len % 16); - } - } - asm.cipher(amode, hpos + pos, len); - if (this.hasOwnProperty('padding') && this.padding) { - let pad = heap[pos + rlen - 1]; - if (pad < 1 || pad > 16 || pad > rlen) - throw new SecurityError('bad padding'); - let pcheck = 0; - for (let i = pad; i > 1; i--) - pcheck |= pad ^ heap[pos + rlen - i]; - if (pcheck) - throw new SecurityError('bad padding'); - rlen -= pad; - } - } - const result = new Uint8Array(rlen); - if (rlen > 0) { - result.set(heap.subarray(pos, pos + rlen)); - } - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } +function pad(data, padding, padding2) { + // if |M| in {n, 2n, 3n, ...} + if (data.length && data.length % blockLength$3 === 0) { + // then return M xor→ B, + return rightXORMut(data, padding); + } + // else return (M || 10^(n−1−(|M| mod n))) xor→ P + const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3))); + padded.set(data); + padded[data.length] = 0b10000000; + return rightXORMut(padded, padding2); } -class AES_ECB { - static encrypt(data, key, padding = false) { - return new AES_ECB(key, padding).encrypt(data); - } - static decrypt(data, key, padding = false) { - return new AES_ECB(key, padding).decrypt(data); - } - constructor(key, padding = false, aes) { - this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} +const zeroBlock$1 = new Uint8Array(blockLength$3); -/** - * Javascript AES implementation. - * This is used as fallback if the native Crypto APIs are not available. - */ -function aes(length) { - const C = function(key) { - const aesECB = new AES_ECB(key); +async function CMAC(key) { + const cbc = await CBC(key); - this.encrypt = function(block) { - return aesECB.encrypt(block); - }; + // L ← E_K(0^n); B ← 2L; P ← 4L + const padding = util.double(await cbc(zeroBlock$1)); + const padding2 = util.double(padding); - this.decrypt = function(block) { - return aesECB.decrypt(block); - }; + return async function(data) { + // return CBC_K(pad(M; B, P)) + return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3); }; - - C.blockSize = C.prototype.blockSize = 16; - C.keySize = C.prototype.keySize = length / 8; - - return C; } -//Paul Tero, July 2001 -//http://www.tero.co.uk/des/ -// -//Optimised for performance with large blocks by Michael Hayworth, November 2001 -//http://www.netdealing.com -// -// Modified by Recurity Labs GmbH - -//THIS SOFTWARE IS PROVIDED "AS IS" AND -//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -//SUCH DAMAGE. - -//des -//this takes the key, the message, and whether to encrypt or decrypt - -function des(keys, message, encrypt, mode, iv, padding) { - //declaring this locally speeds things up a bit - const spfunction1 = [ - 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, - 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, - 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, - 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, - 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 - ]; - const spfunction2 = [ - -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, - -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, - -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, - -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, - -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, - 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000 - ]; - const spfunction3 = [ - 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, - 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, - 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, - 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, - 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 - ]; - const spfunction4 = [ - 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, - 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, - 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, - 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 - ]; - const spfunction5 = [ - 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, - 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, - 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, - 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, - 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, - 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100 - ]; - const spfunction6 = [ - 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, - 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, - 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, - 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, - 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 - ]; - const spfunction7 = [ - 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, - 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, - 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, - 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, - 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 - ]; - const spfunction8 = [ - 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, - 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, - 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, - 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, - 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 - ]; - - //create the 16 or 48 subkeys we will need - let m = 0; - let i; - let j; - let temp; - let right1; - let right2; - let left; - let right; - let looping; - let cbcleft; - let cbcleft2; - let cbcright; - let cbcright2; - let endloop; - let loopinc; - let len = message.length; - - //set up the loops for single and triple des - const iterations = keys.length === 32 ? 3 : 9; //single or triple des - if (iterations === 3) { - looping = encrypt ? [0, 32, 2] : [30, -2, -2]; - } else { - looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; - } - - //pad the message depending on the padding parameter - //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt - if (encrypt) { - message = desAddPadding(message, padding); - len = message.length; - } - - //store the result here - let result = new Uint8Array(len); - let k = 0; - - if (mode === 1) { //CBC mode - cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - m = 0; +async function CBC(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt) { + const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1); + const ct = en.update(pt); + return new Uint8Array(ct); + }; } - //loop through each 64 bit chunk of the message - while (m < len) { - left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - left ^= cbcleft; - right ^= cbcright; - } else { - cbcleft2 = cbcleft; - cbcright2 = cbcright; - cbcleft = left; - cbcright = right; - } - } - - //first each 64 but chunk of the message must be permuted according to IP - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); - - //do this either 1 or 3 times for each chunk of the message - for (j = 0; j < iterations; j += 3) { - endloop = looping[j + 1]; - loopinc = looping[j + 2]; - //now go through and perform the encryption or decryption - for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency - right1 = right ^ keys[i]; - right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - //the result is attained by passing these bytes through the S selection functions - temp = left; - left = right; - right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> - 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & - 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); - } - temp = left; - left = right; - right = temp; //unreverse left and right - } //for either 1 or 3 iterations - - //move then each one bit to the right - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); - - //now perform IP-1, which is IP in the opposite direction - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - cbcleft = left; - cbcright = right; - } else { - left ^= cbcleft2; - right ^= cbcright2; + if (util.getWebCrypto()) { + try { + key = await webCrypto$8.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); + return async function(pt) { + const ct = await webCrypto$8.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt); + return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); } + } - result[k++] = (left >>> 24); - result[k++] = ((left >>> 16) & 0xff); - result[k++] = ((left >>> 8) & 0xff); - result[k++] = (left & 0xff); - result[k++] = (right >>> 24); - result[k++] = ((right >>> 16) & 0xff); - result[k++] = ((right >>> 8) & 0xff); - result[k++] = (right & 0xff); - } //for every 8 characters, or 64 bits in the message + return async function(pt) { + return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt); + }; +} - //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt - if (!encrypt) { - result = desRemovePadding(result, padding); - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return result; -} //end of des - - -//desCreateKeys -//this takes as input a 64 bit key (even though only 56 bits are used) -//as an array of 2 integers, and returns 16 48 bit keys - -function desCreateKeys(key) { - //declaring this locally speeds things up a bit - const pc2bytes0 = [ - 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 - ]; - const pc2bytes1 = [ - 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 - ]; - const pc2bytes2 = [ - 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808 - ]; - const pc2bytes3 = [ - 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 - ]; - const pc2bytes4 = [ - 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010 - ]; - const pc2bytes5 = [ - 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420 - ]; - const pc2bytes6 = [ - 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 - ]; - const pc2bytes7 = [ - 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 - ]; - const pc2bytes8 = [ - 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002 - ]; - const pc2bytes9 = [ - 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 - ]; - const pc2bytes10 = [ - 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020 - ]; - const pc2bytes11 = [ - 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 - ]; - const pc2bytes12 = [ - 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 - ]; - const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; - - //how many iterations (1 for des, 3 for triple des) - const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - //stores the return keys - const keys = new Array(32 * iterations); - //now define the left shifts which need to be done - const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - //other variables - let lefttemp; - let righttemp; - let m = 0; - let n = 0; - let temp; - - for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations - let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 2) ^ right) & 0x33333333; - right ^= temp; - left ^= (temp << 2); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - - //the right side needs to be shifted and to get the last four bits of the left side - temp = (left << 8) | ((right >>> 20) & 0x000000f0); - //left needs to be put upside down - left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); - right = temp; - - //now go through and perform these shifts on the left and right keys - for (let i = 0; i < shifts.length; i++) { - //shift the keys either one or two bits to the left - if (shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; - - //now apply PC-2, in such a way that E is easier when encrypting or decrypting - //this conversion will look like PC-2 except only the last 6 bits of each byte are used - //rather than 48 consecutive bits and the order of lines will be according to - //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 - lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( - left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & - 0xf]; - righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | - pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]; - temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; - keys[n++] = lefttemp ^ temp; - keys[n++] = righttemp ^ (temp << 16); - } - } //for each iterations - //return the keys we've created - return keys; -} //end of desCreateKeys +const webCrypto$7 = util.getWebCrypto(); +const nodeCrypto$6 = util.getNodeCrypto(); +const Buffer$1 = util.getNodeBuffer(); -function desAddPadding(message, padding) { - const padLength = 8 - (message.length % 8); - let pad; - if (padding === 2 && (padLength < 8)) { //pad the message with spaces - pad = ' '.charCodeAt(0); - } else if (padding === 1) { //PKCS7 padding - pad = padLength; - } else if (!padding && (padLength < 8)) { //pad the message out with null bytes - pad = 0; - } else if (padLength === 8) { - return message; - } else { - throw new Error('des: invalid padding'); - } +const blockLength$2 = 16; +const ivLength$2 = blockLength$2; +const tagLength$2 = blockLength$2; - const paddedMessage = new Uint8Array(message.length + padLength); - for (let i = 0; i < message.length; i++) { - paddedMessage[i] = message[i]; - } - for (let j = 0; j < padLength; j++) { - paddedMessage[message.length + j] = pad; - } +const zero = new Uint8Array(blockLength$2); +const one$1 = new Uint8Array(blockLength$2); one$1[blockLength$2 - 1] = 1; +const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2; - return paddedMessage; +async function OMAC(key) { + const cmac = await CMAC(key); + return function(t, message) { + return cmac(util.concatUint8Array([t, message])); + }; } -function desRemovePadding(message, padding) { - let padLength = null; - let pad; - if (padding === 2) { // space padded - pad = ' '.charCodeAt(0); - } else if (padding === 1) { // PKCS7 - padLength = message[message.length - 1]; - } else if (!padding) { // null padding - pad = 0; - } else { - throw new Error('des: invalid padding'); +async function CTR(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt, iv) { + const en = new nodeCrypto$6.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); + const ct = Buffer$1.concat([en.update(pt), en.final()]); + return new Uint8Array(ct); + }; } - if (!padLength) { - padLength = 1; - while (message[message.length - padLength] === pad) { - padLength++; + if (util.getWebCrypto()) { + try { + const keyRef = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); + return async function(pt, iv) { + const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt); + return new Uint8Array(ct); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); } - padLength--; } - return message.subarray(0, message.length - padLength); -} - -// added by Recurity Labs - -function TripleDES(key) { - this.key = []; - - for (let i = 0; i < 3; i++) { - this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); - } - - this.encrypt = function(block) { - return des( - desCreateKeys(this.key[2]), - des( - desCreateKeys(this.key[1]), - des( - desCreateKeys(this.key[0]), - block, true, 0, null, null - ), - false, 0, null, null - ), true, 0, null, null - ); + return async function(pt, iv) { + return ctr(key, iv).encrypt(pt); }; } -TripleDES.keySize = TripleDES.prototype.keySize = 24; -TripleDES.blockSize = TripleDES.prototype.blockSize = 8; -// This is "original" DES +/** + * Class to en/decrypt using EAX mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function EAX(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('EAX mode supports only AES cipher'); + } -function DES(key) { - this.key = key; + const [ + omac, + ctr + ] = await Promise.all([ + OMAC(key), + CTR(key) + ]); - this.encrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, true, 0, null, padding); - }; + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + const [ + omacNonce, + omacAdata + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata) + ]); + const ciphered = await ctr(plaintext, omacNonce); + const omacCiphered = await omac(two, ciphered); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + return util.concatUint8Array([ciphered, tag]); + }, - this.decrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, false, 0, null, padding); + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to verify + * @returns {Promise} The plaintext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$2) throw new Error('Invalid EAX ciphertext'); + const ciphered = ciphertext.subarray(0, -tagLength$2); + const ctTag = ciphertext.subarray(-tagLength$2); + const [ + omacNonce, + omacAdata, + omacCiphered + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata), + omac(two, ciphered) + ]); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); + const plaintext = await ctr(ciphered, omacNonce); + return plaintext; + } }; } -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Copyright 2010 pjacobs@xeekr.com . All rights reserved. +/** + * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. + * @param {Uint8Array} iv - The initialization vector (16 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +EAX.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[8 + i] ^= chunkIndex[i]; + } + return nonce; +}; -// Modified by Recurity Labs GmbH +EAX.blockLength = blockLength$2; +EAX.ivLength = ivLength$2; +EAX.tagLength = tagLength$2; -// fixed/modified by Herbert Hanewinkel, www.haneWIN.de -// check www.haneWIN.de for the latest version +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. -// CAST-128 is a common OpenPGP cipher. +const blockLength$1 = 16; +const ivLength$1 = 15; -// CAST5 constructor +// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: +// While OCB [RFC7253] allows the authentication tag length to be of any +// number up to 128 bits long, this document requires a fixed +// authentication tag length of 128 bits (16 octets) for simplicity. +const tagLength$1 = 16; -function OpenPGPSymEncCAST5() { - this.BlockSize = 8; - this.KeySize = 16; - this.setKey = function(key) { - this.masking = new Array(16); - this.rotate = new Array(16); +function ntz(n) { + let ntz = 0; + for (let i = 1; (n & i) === 0; i <<= 1) { + ntz++; + } + return ntz; +} - this.reset(); +function xorMut(S, T) { + for (let i = 0; i < S.length; i++) { + S[i] ^= T[i]; + } + return S; +} - if (key.length === this.KeySize) { - this.keySchedule(key); - } else { - throw new Error('CAST-128: keys must be 16 bytes'); - } - return true; - }; +function xor(S, T) { + return xorMut(S.slice(), T); +} - this.reset = function() { - for (let i = 0; i < 16; i++) { - this.masking[i] = 0; - this.rotate[i] = 0; - } - }; +const zeroBlock = new Uint8Array(blockLength$1); +const one = new Uint8Array([1]); - this.getBlockSize = function() { - return this.BlockSize; - }; +/** + * Class to en/decrypt using OCB mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function OCB(cipher, key) { + const { keySize } = getCipherParams(cipher); + // sanity checks + if (!util.isAES(cipher) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - this.encrypt = function(src) { - const dst = new Array(src.length); - - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; - - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >>> 16) & 255; - dst[i + 6] = (l >>> 8) & 255; - dst[i + 7] = l & 255; - } + let maxNtz = 0; - return dst; - }; + // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls, + // hence its execution cannot be broken up. + // As a result, WebCrypto cannot currently be used for `encipher`. + const aes = cbc(key, zeroBlock, { disablePadding: true }); + const encipher = block => aes.encrypt(block); + const decipher = block => aes.decrypt(block); + let mask; - this.decrypt = function(src) { - const dst = new Array(src.length); - - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; - - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >> 16) & 255; - dst[i + 6] = (l >> 8) & 255; - dst[i + 7] = l & 255; - } + constructKeyVariables(); - return dst; - }; - const scheduleA = new Array(4); - - scheduleA[0] = new Array(4); - scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; - scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - - scheduleA[1] = new Array(4); - scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - - scheduleA[2] = new Array(4); - scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; - scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - - - scheduleA[3] = new Array(4); - scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - - const scheduleB = new Array(4); - - scheduleB[0] = new Array(4); - scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; - scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; - scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; - scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; - - scheduleB[1] = new Array(4); - scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; - scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; - scheduleB[1][2] = [7, 6, 8, 9, 3]; - scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; - - - scheduleB[2] = new Array(4); - scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; - scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; - scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; - scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; - - - scheduleB[3] = new Array(4); - scheduleB[3][0] = [8, 9, 7, 6, 3]; - scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; - scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; - scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; - - // changed 'in' to 'inn' (in javascript 'in' is a reserved word) - this.keySchedule = function(inn) { - const t = new Array(8); - const k = new Array(32); - - let j; - - for (let i = 0; i < 4; i++) { - j = i * 4; - t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; - } - - const x = [6, 7, 4, 5]; - let ki = 0; - let w; - - for (let half = 0; half < 2; half++) { - for (let round = 0; round < 4; round++) { - for (j = 0; j < 4; j++) { - const a = scheduleA[round][j]; - w = t[a[1]]; - - w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; - w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; - w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; - w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; - w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; - t[a[0]] = w; - } + function constructKeyVariables() { + const mask_x = encipher(zeroBlock); + const mask_$ = util.double(mask_x); + mask = []; + mask[0] = util.double(mask_$); - for (j = 0; j < 4; j++) { - const b = scheduleB[round][j]; - w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; - w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; - w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; - w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; - k[ki] = w; - ki++; - } - } - } + mask.x = mask_x; + mask.$ = mask_$; + } - for (let i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; + function extendKeyVariables(text, adata) { + const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1; + for (let i = maxNtz + 1; i <= newMaxNtz; i++) { + mask[i] = util.double(mask[i - 1]); } - }; - - // These are the three 'f' functions. See RFC 2144, section 2.2. - - function f1(d, m, r) { - const t = m + d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; - } - - function f2(d, m, r) { - const t = m ^ d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; - } - - function f3(d, m, r) { - const t = m - d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; - } - - const sBox = new Array(8); - sBox[0] = [ - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf - ]; - - sBox[1] = [ - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 - ]; - - sBox[2] = [ - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 - ]; - - sBox[3] = [ - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 - ]; - - sBox[4] = [ - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 - ]; - - sBox[5] = [ - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f - ]; - - sBox[6] = [ - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 - ]; - - sBox[7] = [ - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e - ]; -} - -function CAST5(key) { - this.cast5 = new OpenPGPSymEncCAST5(); - this.cast5.setKey(key); - - this.encrypt = function(block) { - return this.cast5.encrypt(block); - }; -} - -CAST5.blockSize = CAST5.prototype.blockSize = 8; -CAST5.keySize = CAST5.prototype.keySize = 16; - -/* eslint-disable no-mixed-operators, no-fallthrough */ + maxNtz = newMaxNtz; + } + function hash(adata) { + if (!adata.length) { + // Fast path + return zeroBlock; + } -/* Modified by Recurity Labs GmbH - * - * Cipher.js - * A block-cipher algorithm implementation on JavaScript - * See Cipher.readme.txt for further information. - * - * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] - * This script file is distributed under the LGPL - * - * ACKNOWLEDGMENT - * - * The main subroutines are written by Michiel van Everdingen. - * - * Michiel van Everdingen - * http://home.versatel.nl/MAvanEverdingen/index.html - * - * All rights for these routines are reserved to Michiel van Everdingen. - * - */ + // + // Consider A as a sequence of 128-bit blocks + // + const m = adata.length / blockLength$1 | 0; -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Math -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + const offset = new Uint8Array(blockLength$1); + const sum = new Uint8Array(blockLength$1); + for (let i = 0; i < m; i++) { + xorMut(offset, mask[ntz(i + 1)]); + xorMut(sum, encipher(xor(offset, adata))); + adata = adata.subarray(blockLength$1); + } -const MAXINT = 0xFFFFFFFF; + // + // Process any final partial block; compute final hash value + // + if (adata.length) { + xorMut(offset, mask.x); -function rotw(w, n) { - return (w << n | w >>> (32 - n)) & MAXINT; -} + const cipherInput = new Uint8Array(blockLength$1); + cipherInput.set(adata, 0); + cipherInput[adata.length] = 0b10000000; + xorMut(cipherInput, offset); -function getW(a, i) { - return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; -} + xorMut(sum, encipher(cipherInput)); + } -function setW(a, i, w) { - a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); -} + return sum; + } -function getB(x, n) { - return (x >>> (n * 8)) & 0xFF; -} + /** + * Encrypt/decrypt data. + * @param {encipher|decipher} fn - Encryption/decryption block cipher function + * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. + */ + function crypt(fn, text, nonce, adata) { + // + // Consider P as a sequence of 128-bit blocks + // + const m = text.length / blockLength$1 | 0; -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Twofish -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // + // Key-dependent variables + // + extendKeyVariables(text, adata); -function createTwofish() { - // - let keyBytes = null; - let dataBytes = null; - let dataOffset = -1; - // var dataLength = -1; - // var idx2 = -1; - // + // + // Nonce-dependent and per-encryption variables + // + // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + // Note: We assume here that tagLength mod 16 == 0. + const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]); + // bottom = str2num(Nonce[123..128]) + const bottom = paddedNonce[blockLength$1 - 1] & 0b111111; + // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + paddedNonce[blockLength$1 - 1] &= 0b11000000; + const kTop = encipher(paddedNonce); + // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); + // Offset_0 = Stretch[1+bottom..128+bottom] + const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); + // Checksum_0 = zeros(128) + const checksum = new Uint8Array(blockLength$1); - let tfsKey = []; - let tfsM = [ - [], - [], - [], - [] - ]; + const ct = new Uint8Array(text.length + tagLength$1); - function tfsInit(key) { - keyBytes = key; + // + // Process any whole blocks + // let i; - let a; - let b; - let c; - let d; - const meKey = []; - const moKey = []; - const inKey = []; - let kLen; - const sKey = []; - let f01; - let f5b; - let fef; - - const q0 = [ - [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], - [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] - ]; - const q1 = [ - [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], - [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] - ]; - const q2 = [ - [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], - [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] - ]; - const q3 = [ - [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], - [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] - ]; - const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - const q = [ - [], - [] - ]; - const m = [ - [], - [], - [], - [] - ]; - - function ffm5b(x) { - return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; - } - - function ffmEf(x) { - return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; - } + let pos = 0; + for (i = 0; i < m; i++) { + // Offset_i = Offset_{i-1} xor L_{ntz(i)} + xorMut(offset, mask[ntz(i + 1)]); + // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + ct.set(xorMut(fn(xor(offset, text)), offset), pos); + // Checksum_i = Checksum_{i-1} xor P_i + xorMut(checksum, fn === encipher ? text : ct.subarray(pos)); - function mdsRem(p, q) { - let i; - let t; - let u; - for (i = 0; i < 8; i++) { - t = q >>> 24; - q = ((q << 8) & MAXINT) | p >>> 24; - p = (p << 8) & MAXINT; - u = t << 1; - if (t & 128) { - u ^= 333; - } - q ^= t ^ (u << 16); - u ^= t >>> 1; - if (t & 1) { - u ^= 166; - } - q ^= u << 24 | u << 8; - } - return q; - } - - function qp(n, x) { - const a = x >> 4; - const b = x & 15; - const c = q0[n][a ^ b]; - const d = q1[n][ror4[b] ^ ashx[a]]; - return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; - } - - function hFun(x, key) { - let a = getB(x, 0); - let b = getB(x, 1); - let c = getB(x, 2); - let d = getB(x, 3); - switch (kLen) { - case 4: - a = q[1][a] ^ getB(key[3], 0); - b = q[0][b] ^ getB(key[3], 1); - c = q[0][c] ^ getB(key[3], 2); - d = q[1][d] ^ getB(key[3], 3); - case 3: - a = q[1][a] ^ getB(key[2], 0); - b = q[1][b] ^ getB(key[2], 1); - c = q[0][c] ^ getB(key[2], 2); - d = q[0][d] ^ getB(key[2], 3); - case 2: - a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); - b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); - c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); - d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); - } - return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; - } - - keyBytes = keyBytes.slice(0, 32); - i = keyBytes.length; - while (i !== 16 && i !== 24 && i !== 32) { - keyBytes[i++] = 0; - } - - for (i = 0; i < keyBytes.length; i += 4) { - inKey[i >> 2] = getW(keyBytes, i); - } - for (i = 0; i < 256; i++) { - q[0][i] = qp(0, i); - q[1][i] = qp(1, i); - } - for (i = 0; i < 256; i++) { - f01 = q[1][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - f01 = q[0][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } - - kLen = inKey.length / 2; - for (i = 0; i < kLen; i++) { - a = inKey[i + i]; - meKey[i] = a; - b = inKey[i + i + 1]; - moKey[i] = b; - sKey[kLen - i - 1] = mdsRem(a, b); - } - for (i = 0; i < 40; i += 2) { - a = 0x1010101 * i; - b = a + 0x1010101; - a = hFun(a, meKey); - b = rotw(hFun(b, moKey), 8); - tfsKey[i] = (a + b) & MAXINT; - tfsKey[i + 1] = rotw(a + 2 * b, 9); - } - for (i = 0; i < 256; i++) { - a = b = c = d = i; - switch (kLen) { - case 4: - a = q[1][a] ^ getB(sKey[3], 0); - b = q[0][b] ^ getB(sKey[3], 1); - c = q[0][c] ^ getB(sKey[3], 2); - d = q[1][d] ^ getB(sKey[3], 3); - case 3: - a = q[1][a] ^ getB(sKey[2], 0); - b = q[1][b] ^ getB(sKey[2], 1); - c = q[0][c] ^ getB(sKey[2], 2); - d = q[0][d] ^ getB(sKey[2], 3); - case 2: - tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; - tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; - tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; - tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; - } + text = text.subarray(blockLength$1); + pos += blockLength$1; } - } - - function tfsG0(x) { - return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; - } - function tfsG1(x) { - return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; - } - - function tfsFrnd(r, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); - blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); - blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; - } - - function tfsIrnd(i, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; - blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; - blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); - } - - function tfsClose() { - tfsKey = []; - tfsM = [ - [], - [], - [], - [] - ]; - } + // + // Process any final partial block and compute raw tag + // + if (text.length) { + // Offset_* = Offset_m xor L_* + xorMut(offset, mask.x); + // Pad = ENCIPHER(K, Offset_*) + const padding = encipher(offset); + // C_* = P_* xor Pad[1..bitlen(P_*)] + ct.set(xor(text, padding), pos); - function tfsEncrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; - for (let j = 0; j < 8; j++) { - tfsFrnd(j, blk); + // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) + const xorInput = new Uint8Array(blockLength$1); + xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); + xorInput[text.length] = 0b10000000; + xorMut(checksum, xorInput); + pos += text.length; } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); - dataOffset += 16; - return dataBytes; - } + // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata)); - function tfsDecrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; - for (let j = 7; j >= 0; j--) { - tfsIrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); - dataOffset += 16; + // + // Assemble ciphertext + // + // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] + ct.set(tag, pos); + return ct; } - // added by Recurity Labs - - function tfsFinal() { - return dataBytes; - } return { - name: 'twofish', - blocksize: 128 / 8, - open: tfsInit, - close: tfsClose, - encrypt: tfsEncrypt, - decrypt: tfsDecrypt, - // added by Recurity Labs - finalize: tfsFinal - }; -} + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + return crypt(encipher, plaintext, nonce, adata); + }, -// added by Recurity Labs + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); -function TF(key) { - this.tf = createTwofish(); - this.tf.open(Array.from(key), 0); + const tag = ciphertext.subarray(-tagLength$1); + ciphertext = ciphertext.subarray(0, -tagLength$1); - this.encrypt = function(block) { - return this.tf.encrypt(Array.from(block), 0); + const crypted = crypt(decipher, ciphertext, nonce, adata); + // if (Tag[1..TAGLEN] == T) + if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { + return crypted.subarray(0, -tagLength$1); + } + throw new Error('Authentication tag mismatch'); + } }; } -TF.keySize = TF.prototype.keySize = 32; -TF.blockSize = TF.prototype.blockSize = 16; - -/* Modified by Recurity Labs GmbH - * - * Originally written by nklein software (nklein.com) - */ - -/* - * Javascript implementation based on Bruce Schneier's reference implementation. - * - * - * The constructor doesn't do much of anything. It's just here - * so we can start defining properties and methods and such. - */ -function Blowfish() {} -/* - * Declare the block size so that protocols know what size - * Initialization Vector (IV) they will need. +/** + * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. + * @param {Uint8Array} iv - The initialization vector (15 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) */ -Blowfish.prototype.BLOCKSIZE = 8; - -/* - * These are the default SBOXES. - */ -Blowfish.prototype.SBOXES = [ - [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a - ], - [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 - ], - [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 - ], - [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ] -]; - -//* -//* This is the default PARRAY -//* -Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b -]; - -//* -//* This is the number of rounds the cipher will go -//* -Blowfish.prototype.NN = 16; - -//* -//* This function is needed to get rid of problems -//* with the high-bit getting set. If we don't do -//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not -//* equal to ( bb & 0x00FFFFFFFF ) even when they -//* agree bit-for-bit for the first 32 bits. -//* -Blowfish.prototype._clean = function(xx) { - if (xx < 0) { - const yy = xx & 0x7FFFFFFF; - xx = yy + 0x80000000; - } - return xx; -}; - -//* -//* This is the mixing function that uses the sboxes -//* -Blowfish.prototype._F = function(xx) { - let yy; - - const dd = xx & 0x00FF; - xx >>>= 8; - const cc = xx & 0x00FF; - xx >>>= 8; - const bb = xx & 0x00FF; - xx >>>= 8; - const aa = xx & 0x00FF; - - yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy ^= this.sboxes[2][cc]; - yy += this.sboxes[3][dd]; - - return yy; +OCB.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[7 + i] ^= chunkIndex[i]; + } + return nonce; }; -//* -//* This method takes an array with two values, left and right -//* and does NN rounds of Blowfish on them. -//* -Blowfish.prototype._encryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; - - let ii; - - for (ii = 0; ii < this.NN; ++ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; - - const tmp = dataL; - dataL = dataR; - dataR = tmp; - } +OCB.blockLength = blockLength$1; +OCB.ivLength = ivLength$1; +OCB.tagLength = tagLength$1; - dataL ^= this.parray[this.NN + 0]; - dataR ^= this.parray[this.NN + 1]; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; -//* -//* This method takes a vector of numbers and turns them -//* into long words so that they can be processed by the -//* real algorithm. -//* -//* Maybe I should make the real algorithm above take a vector -//* instead. That will involve more looping, but it won't require -//* the F() method to deconstruct the vector. -//* -Blowfish.prototype.encryptBlock = function(vector) { - let ii; - const vals = [0, 0]; - const off = this.BLOCKSIZE / 2; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); - vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); - } - - this._encryptBlock(vals); - - const ret = []; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); - ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); - // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); - // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); - } - - return ret; -}; +const webCrypto$6 = util.getWebCrypto(); +const nodeCrypto$5 = util.getNodeCrypto(); +const Buffer = util.getNodeBuffer(); -//* -//* This method takes an array with two values, left and right -//* and undoes NN rounds of Blowfish on them. -//* -Blowfish.prototype._decryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; +const blockLength = 16; +const ivLength = 12; // size of the IV in bytes +const tagLength = 16; // size of the tag in bytes +const ALGO = 'AES-GCM'; - let ii; +/** + * Class to en/decrypt using GCM mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function GCM(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('GCM mode supports only AES cipher'); + } - for (ii = this.NN + 1; ii > 1; --ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; + if (util.getNodeCrypto()) { // Node crypto library + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + const en = new nodeCrypto$5.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + en.setAAD(adata); + const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext + return new Uint8Array(ct); + }, - const tmp = dataL; - dataL = dataR; - dataR = tmp; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + const de = new nodeCrypto$5.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + de.setAAD(adata); + de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext + const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]); + return new Uint8Array(pt); + } + }; } - dataL ^= this.parray[1]; - dataR ^= this.parray[0]; - - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; + if (util.getWebCrypto()) { + try { + const _key = await webCrypto$6.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); + // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages + const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) || + navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/); + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && !pt.length) { + return gcm(key, iv, adata).encrypt(pt); + } + const ct = await webCrypto$6.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt); + return new Uint8Array(ct); + }, -//* -//* This method takes a key array and initializes the -//* sboxes and parray for this encryption. -//* -Blowfish.prototype.init = function(key) { - let ii; - let jj = 0; - - this.parray = []; - for (ii = 0; ii < this.NN + 2; ++ii) { - let data = 0x00000000; - for (let kk = 0; kk < 4; ++kk) { - data = (data << 8) | (key[jj] & 0x00FF); - if (++jj >= key.length) { - jj = 0; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) { + return gcm(key, iv, adata).decrypt(ct); + } + try { + const pt = await webCrypto$6.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct); + return new Uint8Array(pt); + } catch (e) { + if (e.name === 'OperationError') { + throw new Error('Authentication tag mismatch'); + } + } + } + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); } - this.parray[ii] = this.PARRAY[ii] ^ data; } - this.sboxes = []; - for (ii = 0; ii < 4; ++ii) { - this.sboxes[ii] = []; - for (jj = 0; jj < 256; ++jj) { - this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + return { + encrypt: async function(pt, iv, adata) { + return gcm(key, iv, adata).encrypt(pt); + }, + + decrypt: async function(ct, iv, adata) { + return gcm(key, iv, adata).decrypt(ct); } - } + }; +} - const vals = [0x00000000, 0x00000000]; - for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encryptBlock(vals); - this.parray[ii + 0] = vals[0]; - this.parray[ii + 1] = vals[1]; - } - - for (ii = 0; ii < 4; ++ii) { - for (jj = 0; jj < 256; jj += 2) { - this._encryptBlock(vals); - this.sboxes[ii][jj + 0] = vals[0]; - this.sboxes[ii][jj + 1] = vals[1]; - } +/** + * Get GCM nonce. Note: this operation is not defined by the standard. + * A future version of the standard may define GCM mode differently, + * hopefully under a different ID (we use Private/Experimental algorithm + * ID 100) so that we can maintain backwards compatibility. + * @param {Uint8Array} iv - The initialization vector (12 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +GCM.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[4 + i] ^= chunkIndex[i]; } + return nonce; }; -// added by Recurity Labs -function BF(key) { - this.bf = new Blowfish(); - this.bf.init(key); - - this.encrypt = function(block) { - return this.bf.encryptBlock(block); - }; -} - -BF.keySize = BF.prototype.keySize = 16; -BF.blockSize = BF.prototype.blockSize = 8; +GCM.blockLength = blockLength; +GCM.ivLength = ivLength; +GCM.tagLength = tagLength; /** - * @fileoverview Symmetric cryptography functions - * @module crypto/cipher - * @private + * @fileoverview Cipher modes + * @module crypto/mode */ + +var mode = { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: GCM, + experimentalGCM: GCM, + /** @see module:crypto/mode/eax */ + eax: EAX, + /** @see module:crypto/mode/ocb */ + ocb: OCB +}; + +// Operations are not constant time, but we try and limit timing leakage where we can +const _0n$1 = BigInt(0); +const _1n$4 = BigInt(1); +function uint8ArrayToBigInt(bytes) { + const hexAlphabet = '0123456789ABCDEF'; + let s = ''; + bytes.forEach(v => { + s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; + }); + return BigInt('0x0' + s); +} +function mod$1(a, m) { + const reduced = a % m; + return reduced < _0n$1 ? reduced + m : reduced; +} /** - * AES-128 encryption and decryption (ID 7) - * @function - * @param {String} key - 128-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes128 = aes(128); + * Compute modular exponentiation using square and multiply + * @param {BigInt} a - Base + * @param {BigInt} e - Exponent + * @param {BigInt} n - Modulo + * @returns {BigInt} b ** e mod n. + */ +function modExp(b, e, n) { + if (n === _0n$1) + throw Error('Modulo cannot be zero'); + if (n === _1n$4) + return BigInt(0); + if (e < _0n$1) + throw Error('Unsopported negative exponent'); + let exp = e; + let x = b; + x %= n; + let r = BigInt(1); + while (exp > _0n$1) { + const lsb = exp & _1n$4; + exp >>= _1n$4; // e / 2 + // Always compute multiplication step, to reduce timing leakage + const rx = (r * x) % n; + // Update r only if lsb is 1 (odd exponent) + r = lsb ? rx : r; + x = (x * x) % n; // Square + } + return r; +} +function abs(x) { + return x >= _0n$1 ? x : -x; +} /** - * AES-128 Block Cipher (ID 8) - * @function - * @param {String} key - 192-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes192 = aes(192); + * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) + * Given a and b, compute (x, y) such that ax + by = gdc(a, b). + * Negative numbers are also supported. + * @param {BigInt} a - First operand + * @param {BigInt} b - Second operand + * @returns {{ gcd, x, y: bigint }} + */ +function _egcd(aInput, bInput) { + let x = BigInt(0); + let y = BigInt(1); + let xPrev = BigInt(1); + let yPrev = BigInt(0); + // Deal with negative numbers: run algo over absolute values, + // and "move" the sign to the returned x and/or y. + // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers + let a = abs(aInput); + let b = abs(bInput); + const aNegated = aInput < _0n$1; + const bNegated = bInput < _0n$1; + while (b !== _0n$1) { + const q = a / b; + let tmp = x; + x = xPrev - q * x; + xPrev = tmp; + tmp = y; + y = yPrev - q * y; + yPrev = tmp; + tmp = b; + b = a % b; + a = tmp; + } + return { + x: aNegated ? -xPrev : xPrev, + y: bNegated ? -yPrev : yPrev, + gcd: a + }; +} /** - * AES-128 Block Cipher (ID 9) - * @function - * @param {String} key - 256-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} + * Compute the inverse of `a` modulo `n` + * Note: `a` and and `n` must be relatively prime + * @param {BigInt} a + * @param {BigInt} n - Modulo + * @returns {BigInt} x such that a*x = 1 mod n + * @throws {Error} if the inverse does not exist */ -const aes256 = aes(256); -// Not in OpenPGP specifications -const des$1 = DES; +function modInv(a, n) { + const { gcd, x } = _egcd(a, n); + if (gcd !== _1n$4) { + throw new Error('Inverse does not exist'); + } + return mod$1(x + n, n); +} /** - * Triple DES Block Cipher (ID 2) - * @function - * @param {String} key - 192-bit key - * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67} - * @returns {Object} + * Compute greatest common divisor between this and n + * @param {BigInt} aInput - Operand + * @param {BigInt} bInput - Operand + * @returns {BigInt} gcd */ -const tripledes = TripleDES; +function gcd(aInput, bInput) { + let a = aInput; + let b = bInput; + while (b !== _0n$1) { + const tmp = b; + b = a % b; + a = tmp; + } + return a; +} /** - * CAST-128 Block Cipher (ID 3) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} - * @returns {Object} + * Get this value as an exact Number (max 53 bits) + * Fails if this value is too large + * @returns {Number} */ -const cast5 = CAST5; +function bigIntToNumber(x) { + const number = Number(x); + if (number > Number.MAX_SAFE_INTEGER) { + // We throw and error to conform with the bn.js implementation + throw new Error('Number can only safely store up to 53 bits'); + } + return number; +} /** - * Twofish Block Cipher (ID 10) - * @function - * @param {String} key - 256-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH} - * @returns {Object} + * Get value of i-th bit + * @param {BigInt} x + * @param {Number} i - Bit index + * @returns {Number} Bit value. */ -const twofish = TF; +function getBit(x, i) { + const bit = (x >> BigInt(i)) & _1n$4; + return bit === _0n$1 ? 0 : 1; +} /** - * Blowfish Block Cipher (ID 4) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH} - * @returns {Object} + * Compute bit length */ -const blowfish = BF; +function bitLength(x) { + // -1n >> -1n is -1n + // 1n >> 1n is 0n + const target = x < _0n$1 ? BigInt(-1) : _0n$1; + let bitlen = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _1n$4) !== target) { + bitlen++; + } + return bitlen; +} /** - * Not implemented - * @function - * @throws {Error} + * Compute byte length */ -const idea = function() { - throw new Error('IDEA symmetric-key algorithm not implemented'); -}; - -var cipher = /*#__PURE__*/Object.freeze({ - __proto__: null, - aes128: aes128, - aes192: aes192, - aes256: aes256, - des: des$1, - tripledes: tripledes, - cast5: cast5, - twofish: twofish, - blowfish: blowfish, - idea: idea -}); - -var sha1_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0, - w16 = 0, w17 = 0, w18 = 0, w19 = 0, - w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0, - w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0, - w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0, - w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0, - w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0, - w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - - // 0 - t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 1 - t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 2 - t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 3 - t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 4 - t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 5 - t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 6 - t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 7 - t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 8 - t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 9 - t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 10 - t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 11 - t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 12 - t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 13 - t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 14 - t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 15 - t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 16 - n = w13 ^ w8 ^ w2 ^ w0; - w16 = (n << 1) | (n >>> 31); - t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 17 - n = w14 ^ w9 ^ w3 ^ w1; - w17 = (n << 1) | (n >>> 31); - t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 18 - n = w15 ^ w10 ^ w4 ^ w2; - w18 = (n << 1) | (n >>> 31); - t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 19 - n = w16 ^ w11 ^ w5 ^ w3; - w19 = (n << 1) | (n >>> 31); - t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 20 - n = w17 ^ w12 ^ w6 ^ w4; - w20 = (n << 1) | (n >>> 31); - t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 21 - n = w18 ^ w13 ^ w7 ^ w5; - w21 = (n << 1) | (n >>> 31); - t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 22 - n = w19 ^ w14 ^ w8 ^ w6; - w22 = (n << 1) | (n >>> 31); - t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 23 - n = w20 ^ w15 ^ w9 ^ w7; - w23 = (n << 1) | (n >>> 31); - t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 24 - n = w21 ^ w16 ^ w10 ^ w8; - w24 = (n << 1) | (n >>> 31); - t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 25 - n = w22 ^ w17 ^ w11 ^ w9; - w25 = (n << 1) | (n >>> 31); - t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 26 - n = w23 ^ w18 ^ w12 ^ w10; - w26 = (n << 1) | (n >>> 31); - t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 27 - n = w24 ^ w19 ^ w13 ^ w11; - w27 = (n << 1) | (n >>> 31); - t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 28 - n = w25 ^ w20 ^ w14 ^ w12; - w28 = (n << 1) | (n >>> 31); - t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 29 - n = w26 ^ w21 ^ w15 ^ w13; - w29 = (n << 1) | (n >>> 31); - t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 30 - n = w27 ^ w22 ^ w16 ^ w14; - w30 = (n << 1) | (n >>> 31); - t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 31 - n = w28 ^ w23 ^ w17 ^ w15; - w31 = (n << 1) | (n >>> 31); - t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 32 - n = w29 ^ w24 ^ w18 ^ w16; - w32 = (n << 1) | (n >>> 31); - t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 33 - n = w30 ^ w25 ^ w19 ^ w17; - w33 = (n << 1) | (n >>> 31); - t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 34 - n = w31 ^ w26 ^ w20 ^ w18; - w34 = (n << 1) | (n >>> 31); - t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 35 - n = w32 ^ w27 ^ w21 ^ w19; - w35 = (n << 1) | (n >>> 31); - t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 36 - n = w33 ^ w28 ^ w22 ^ w20; - w36 = (n << 1) | (n >>> 31); - t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 37 - n = w34 ^ w29 ^ w23 ^ w21; - w37 = (n << 1) | (n >>> 31); - t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 38 - n = w35 ^ w30 ^ w24 ^ w22; - w38 = (n << 1) | (n >>> 31); - t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 39 - n = w36 ^ w31 ^ w25 ^ w23; - w39 = (n << 1) | (n >>> 31); - t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 40 - n = w37 ^ w32 ^ w26 ^ w24; - w40 = (n << 1) | (n >>> 31); - t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 41 - n = w38 ^ w33 ^ w27 ^ w25; - w41 = (n << 1) | (n >>> 31); - t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 42 - n = w39 ^ w34 ^ w28 ^ w26; - w42 = (n << 1) | (n >>> 31); - t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 43 - n = w40 ^ w35 ^ w29 ^ w27; - w43 = (n << 1) | (n >>> 31); - t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 44 - n = w41 ^ w36 ^ w30 ^ w28; - w44 = (n << 1) | (n >>> 31); - t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 45 - n = w42 ^ w37 ^ w31 ^ w29; - w45 = (n << 1) | (n >>> 31); - t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 46 - n = w43 ^ w38 ^ w32 ^ w30; - w46 = (n << 1) | (n >>> 31); - t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 47 - n = w44 ^ w39 ^ w33 ^ w31; - w47 = (n << 1) | (n >>> 31); - t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 48 - n = w45 ^ w40 ^ w34 ^ w32; - w48 = (n << 1) | (n >>> 31); - t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 49 - n = w46 ^ w41 ^ w35 ^ w33; - w49 = (n << 1) | (n >>> 31); - t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 50 - n = w47 ^ w42 ^ w36 ^ w34; - w50 = (n << 1) | (n >>> 31); - t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 51 - n = w48 ^ w43 ^ w37 ^ w35; - w51 = (n << 1) | (n >>> 31); - t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 52 - n = w49 ^ w44 ^ w38 ^ w36; - w52 = (n << 1) | (n >>> 31); - t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 53 - n = w50 ^ w45 ^ w39 ^ w37; - w53 = (n << 1) | (n >>> 31); - t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 54 - n = w51 ^ w46 ^ w40 ^ w38; - w54 = (n << 1) | (n >>> 31); - t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 55 - n = w52 ^ w47 ^ w41 ^ w39; - w55 = (n << 1) | (n >>> 31); - t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 56 - n = w53 ^ w48 ^ w42 ^ w40; - w56 = (n << 1) | (n >>> 31); - t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 57 - n = w54 ^ w49 ^ w43 ^ w41; - w57 = (n << 1) | (n >>> 31); - t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 58 - n = w55 ^ w50 ^ w44 ^ w42; - w58 = (n << 1) | (n >>> 31); - t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 59 - n = w56 ^ w51 ^ w45 ^ w43; - w59 = (n << 1) | (n >>> 31); - t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 60 - n = w57 ^ w52 ^ w46 ^ w44; - w60 = (n << 1) | (n >>> 31); - t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 61 - n = w58 ^ w53 ^ w47 ^ w45; - w61 = (n << 1) | (n >>> 31); - t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 62 - n = w59 ^ w54 ^ w48 ^ w46; - w62 = (n << 1) | (n >>> 31); - t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 63 - n = w60 ^ w55 ^ w49 ^ w47; - w63 = (n << 1) | (n >>> 31); - t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 64 - n = w61 ^ w56 ^ w50 ^ w48; - w64 = (n << 1) | (n >>> 31); - t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 65 - n = w62 ^ w57 ^ w51 ^ w49; - w65 = (n << 1) | (n >>> 31); - t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 66 - n = w63 ^ w58 ^ w52 ^ w50; - w66 = (n << 1) | (n >>> 31); - t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 67 - n = w64 ^ w59 ^ w53 ^ w51; - w67 = (n << 1) | (n >>> 31); - t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 68 - n = w65 ^ w60 ^ w54 ^ w52; - w68 = (n << 1) | (n >>> 31); - t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 69 - n = w66 ^ w61 ^ w55 ^ w53; - w69 = (n << 1) | (n >>> 31); - t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 70 - n = w67 ^ w62 ^ w56 ^ w54; - w70 = (n << 1) | (n >>> 31); - t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 71 - n = w68 ^ w63 ^ w57 ^ w55; - w71 = (n << 1) | (n >>> 31); - t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 72 - n = w69 ^ w64 ^ w58 ^ w56; - w72 = (n << 1) | (n >>> 31); - t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 73 - n = w70 ^ w65 ^ w59 ^ w57; - w73 = (n << 1) | (n >>> 31); - t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 74 - n = w71 ^ w66 ^ w60 ^ w58; - w74 = (n << 1) | (n >>> 31); - t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 75 - n = w72 ^ w67 ^ w61 ^ w59; - w75 = (n << 1) | (n >>> 31); - t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 76 - n = w73 ^ w68 ^ w62 ^ w60; - w76 = (n << 1) | (n >>> 31); - t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 77 - n = w74 ^ w69 ^ w63 ^ w61; - w77 = (n << 1) | (n >>> 31); - t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 78 - n = w75 ^ w70 ^ w64 ^ w62; - w78 = (n << 1) | (n >>> 31); - t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 79 - n = w76 ^ w71 ^ w65 ^ w63; - w79 = (n << 1) | (n >>> 31); - t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); +function byteLength(x) { + const target = x < _0n$1 ? BigInt(-1) : _0n$1; + const _8n = BigInt(8); + let len = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _8n) !== target) { + len++; } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - } - - function reset () { - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; + return len; +} +/** + * Get Uint8Array representation of this number + * @param {String} endian - Endianess of output array (defaults to 'be') + * @param {Number} length - Of output array + * @returns {Uint8Array} + */ +function bigIntToUint8Array(x, endian = 'be', length) { + // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) + // this is faster than shift+mod iterations + let hex = x.toString(16); + if (hex.length % 2 === 1) { + hex = '0' + hex; } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - - TOTAL0 = 64; - TOTAL1 = 0; + const rawLength = hex.length / 2; + const bytes = new Uint8Array(length || rawLength); + // parse hex + const offset = length ? length - rawLength : 0; + let i = 0; + while (i < rawLength) { + bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + i++; } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; + if (endian !== 'be') { + bytes.reverse(); } + return bytes; +} - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if ( offset & 63 ) - return -1; - if ( ~output ) - if ( output & 31 ) - return -1; +const nodeCrypto$4 = util.getNodeCrypto(); - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; +/** + * Retrieve secure random byte array of the specified length + * @param {Integer} length - Length in bytes to generate + * @returns {Uint8Array} Random byte array. + */ +function getRandomBytes(length) { + const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$4?.webcrypto; + if (webcrypto?.getRandomValues) { + const buf = new Uint8Array(length); + return webcrypto.getRandomValues(buf); + } else { + throw new Error('No secure random number generator available.'); + } +} - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4; - count = (count-1)|0; +/** + * Create a secure random BigInt that is greater than or equal to min and less than max. + * @param {bigint} min - Lower bound, included + * @param {bigint} max - Upper bound, excluded + * @returns {bigint} Random BigInt. + * @async + */ +function getRandomBigInteger(min, max) { + if (max < min) { + throw new Error('Illegal parameter value: max <= min'); + } - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + const modulus = max - min; + const bytes = byteLength(modulus); - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8)); + return mod$1(r, modulus) + min; +} - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; +var random = /*#__PURE__*/Object.freeze({ + __proto__: null, + getRandomBigInteger: getRandomBigInteger, + getRandomBytes: getRandomBytes +}); - count = (count-1)|0; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +/** + * @fileoverview Algorithms for probabilistic random prime generation + * @module crypto/public_key/prime + */ +const _1n$3 = BigInt(1); +/** + * Generate a probably prime random number + * @param bits - Bit length of the prime + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function randomProbablePrime(bits, e, k) { + const _30n = BigInt(30); + const min = _1n$3 << BigInt(bits - 1); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 + * the next possible prime is mod 30: + * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 + */ + const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; + let n = getRandomBigInteger(min, min << _1n$3); + let i = bigIntToNumber(mod$1(n, _30n)); + do { + n += BigInt(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (bitLength(n) > bits) { + n = mod$1(n, min << _1n$3); + n += min; + i = bigIntToNumber(mod$1(n, _30n)); } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA1 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA1 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA1 - pbkdf2_generate_block: pbkdf2_generate_block + } while (!isProbablePrime(n, e, k)); + return n; +} +/** + * Probabilistic primality testing + * @param n - Number to test + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function isProbablePrime(n, e, k) { + if (e && gcd(n - _1n$3, e) !== _1n$3) { + return false; } -}; - -class Hash { - constructor() { - this.pos = 0; - this.len = 0; - } - reset() { - const { asm } = this.acquire_asm(); - this.result = null; - this.pos = 0; - this.len = 0; - asm.reset(); - return this; + if (!divisionTest(n)) { + return false; } - process(data) { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - let hpos = this.pos; - let hlen = this.len; - let dpos = 0; - let dlen = data.length; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.process(hpos, hlen); - hpos += wlen; - hlen -= wlen; - if (!hlen) - hpos = 0; - } - this.pos = hpos; - this.len = hlen; - return this; + if (!fermat(n)) { + return false; } - finish() { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - asm.finish(this.pos, this.len, 0); - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set(heap.subarray(0, this.HASH_SIZE)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return this; + if (!millerRabin(n, k)) { + return false; } + // TODO implement the Lucas test + // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + return true; } - -const _sha1_block_size = 64; -const _sha1_hash_size = 20; -const heap_pool$1 = []; -const asm_pool$1 = []; -class Sha1 extends Hash { - constructor() { - super(); - this.NAME = 'sha1'; - this.BLOCK_SIZE = _sha1_block_size; - this.HASH_SIZE = _sha1_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$1.pop() || _heap_init(); - this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; +/** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n != 1. + * @param n - Number to test + * @param b - Optional Fermat test base + */ +function fermat(n, b = BigInt(2)) { + return modExp(b, n - _1n$3, n) === _1n$3; +} +function divisionTest(n) { + const _0n = BigInt(0); + return smallPrimes.every(m => mod$1(n, m) !== _0n); +} +// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c +const smallPrimes = [ + 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, + 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, + 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, + 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, + 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, + 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, + 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, + 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, + 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, + 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, + 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, + 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, + 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, + 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, + 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, + 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, + 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, + 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, + 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, + 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, + 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, + 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, + 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, + 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, + 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, + 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, + 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, + 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, + 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, + 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, + 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, + 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, + 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, + 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, + 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, + 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, + 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, + 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, + 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, + 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, + 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, + 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, + 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, + 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, + 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, + 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, + 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, + 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, + 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, + 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, + 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, + 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, + 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, + 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, + 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, + 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, + 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, + 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, + 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, + 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, + 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, + 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, + 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, + 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, + 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, + 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, + 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, + 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, + 4957, 4967, 4969, 4973, 4987, 4993, 4999 +].map(n => BigInt(n)); +// Miller-Rabin - Miller Rabin algorithm for primality test +// Copyright Fedor Indutny, 2014. +// +// This software is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin +// Sample syntax for Fixed-Base Miller-Rabin: +// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) +/** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n - Number to test + * @param k - Optional number of iterations of Miller-Rabin test + * @param rand - Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ +function millerRabin(n, k, rand) { + const len = bitLength(n); + if (!k) { + k = Math.max(1, (len / 48) | 0); } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$1.push(this.heap); - asm_pool$1.push(this.asm); + const n1 = n - _1n$3; // n - 1 + // Find d and s, (n - 1) = (2 ^ s) * d; + let s = 0; + while (!getBit(n1, s)) { + s++; + } + const d = n >> BigInt(s); + for (; k > 0; k--) { + const a = getRandomBigInteger(BigInt(2), n1); + let x = modExp(a, d, n); + if (x === _1n$3 || x === n1) { + continue; + } + let i; + for (i = 1; i < s; i++) { + x = mod$1(x * x, n); + if (x === _1n$3) { + return false; + } + if (x === n1) { + break; + } + } + if (i === s) { + return false; } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha1().process(data).finish().result; - } -} -Sha1.NAME = 'sha1'; -Sha1.heap_pool = []; -Sha1.asm_pool = []; -Sha1.asm_function = sha1_asm; - -var sha256_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - f = H5; - g = H6; - h = H7; - - // 0 - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 1 - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 2 - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 3 - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 4 - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 5 - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 6 - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 7 - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 8 - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 9 - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 10 - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 11 - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 12 - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 13 - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 14 - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 15 - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 16 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 17 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 18 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 19 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 20 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 21 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 22 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 23 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 24 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 25 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 26 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 27 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 28 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 29 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 30 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 31 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 32 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 33 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 34 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 35 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 36 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 37 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 38 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 39 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 40 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 41 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 42 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 43 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 44 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 45 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 46 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 47 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 48 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 49 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 50 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 51 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 52 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 53 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 54 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 55 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 56 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 57 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 58 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 59 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 60 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 61 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 62 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 63 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); } + return true; +} - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; - } - - function reset () { - H0 = 0x6a09e667; - H1 = 0xbb67ae85; - H2 = 0x3c6ef372; - H3 = 0xa54ff53a; - H4 = 0x510e527f; - H5 = 0x9b05688c; - H6 = 0x1f83d9ab; - H7 = 0x5be0cd19; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - H5 = I5; - H6 = I6; - H7 = I7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - H5 = O5; - H6 = O6; - H7 = O7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - O5 = H5; - O6 = H6; - O7 = H7; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - I5 = H5; - I6 = H6; - I7 = H7; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - h5 = h5 ^ H5; - h6 = h6 ^ H6; - h7 = h7 ^ H7; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA256 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA256 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA256 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; - -const _sha256_block_size = 64; -const _sha256_hash_size = 32; -const heap_pool$2 = []; -const asm_pool$2 = []; -class Sha256 extends Hash { - constructor() { - super(); - this.NAME = 'sha256'; - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$2.pop() || _heap_init(); - this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$2.push(this.heap); - asm_pool$2.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha256().process(data).finish().result; - } -} -Sha256.NAME = 'sha256'; - -var minimalisticAssert = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var inherits_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; -} -}); +/** + * ASN1 object identifiers for hashes + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} + */ +const hash_headers = []; +hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, + 0x10]; +hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; +hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; +hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, + 0x04, 0x20]; +hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x30]; +hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40]; +hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C]; -var inherits_1 = inherits_browser; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); +/** + * Create padding with secure random data + * @private + * @param {Integer} length - Length of the padding in bytes + * @returns {Uint8Array} Random padding. + */ +function getPKCS1Padding(length) { + const result = new Uint8Array(length); + let count = 0; + while (count < length) { + const randomBytes = getRandomBytes(length - count); + for (let i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result[count++] = randomBytes[i]; } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -var toArray_1 = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -var htonl_1 = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -var toHex32_1 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -var zero2_1 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -var zero8_1 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -var join32_1 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; } } - return res; -} -var split32_1 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -var rotr32_1 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); + return result; } -var rotl32_1 = rotl32; -function sum32(a, b) { - return (a + b) >>> 0; +/** + * Create a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} + * @param {Uint8Array} message - Message to be encoded + * @param {Integer} keyLength - The length in octets of the key modulus + * @returns {Uint8Array} EME-PKCS1 padded message. + */ +function emeEncode(message, keyLength) { + const mLength = message.length; + // length checking + if (mLength > keyLength - 11) { + throw new Error('Message too long'); + } + // Generate an octet string PS of length k - mLen - 3 consisting of + // pseudo-randomly generated nonzero octets + const PS = getPKCS1Padding(keyLength - mLength - 3); + // Concatenate PS, the message M, and other padding to form an + // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. + const encoded = new Uint8Array(keyLength); + // 0x00 byte + encoded[1] = 2; + encoded.set(PS, 2); + // 0x00 bytes + encoded.set(message, keyLength - mLength); + return encoded; } -var sum32_1 = sum32; -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -var sum32_3_1 = sum32_3; +/** + * Decode a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} + * @param {Uint8Array} encoded - Encoded message bytes + * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) + * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) + * @throws {Error} on decoding failure, unless `randomPayload` is provided + */ +function emeDecode(encoded, randomPayload) { + // encoded format: 0x00 0x02 0x00 + let offset = 2; + let separatorNotFound = 1; + for (let j = offset; j < encoded.length; j++) { + separatorNotFound &= encoded[j] !== 0; + offset += separatorNotFound; + } -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -var sum32_4_1 = sum32_4; + const psLen = offset - 2; + const payload = encoded.subarray(offset + 1); // discard the 0x00 separator + const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -var sum32_5_1 = sum32_5; + if (randomPayload) { + return util.selectUint8Array(isValidPadding, payload, randomPayload); + } -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; + if (isValidPadding) { + return payload; + } - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; + throw new Error('Decryption error'); } -var sum64_1 = sum64; -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; +/** + * Create a EMSA-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} + * @param {Integer} algo - Hash algorithm type used + * @param {Uint8Array} hashed - Message to be encoded + * @param {Integer} emLen - Intended length in octets of the encoded message + * @returns {Uint8Array} Encoded message. + */ +function emsaEncode(algo, hashed, emLen) { + let i; + if (hashed.length !== hash.getHashByteLength(algo)) { + throw new Error('Invalid hash length'); + } + // produce an ASN.1 DER value for the hash function used. + // Let T be the full hash prefix + const hashPrefix = new Uint8Array(hash_headers[algo].length); + for (i = 0; i < hash_headers[algo].length; i++) { + hashPrefix[i] = hash_headers[algo][i]; + } + // and let tLen be the length in octets prefix and hashed data + const tLen = hashPrefix.length + hashed.length; + if (emLen < tLen + 11) { + throw new Error('Intended encoded message length too short'); + } + // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF + // The length of PS will be at least 8 octets + const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; + // Concatenate PS, the hash prefix, hashed data, and other padding to form the + // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed + const EM = new Uint8Array(emLen); + EM[1] = 0x01; + EM.set(PS, 2); + EM.set(hashPrefix, emLen - tLen); + EM.set(hashed, emLen - hashed.length); + return EM; } -var sum64_lo_1 = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; +var pkcs1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + emeDecode: emeDecode, + emeEncode: emeEncode, + emsaEncode: emsaEncode +}); -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; +const webCrypto$5 = util.getWebCrypto(); +const nodeCrypto$3 = util.getNodeCrypto(); +const _1n$2 = BigInt(1); -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; +/** Create signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} hashed - Hashed message + * @returns {Promise} RSA Signature. + * @async + */ +async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) { + if (hash.getHashByteLength(hashAlgo) >= n.length) { + // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error + // e.g. if a 512-bit RSA key is used with a SHA-512 digest. + // The size limit is actually slightly different but here we only care about throwing + // on common key sizes. + throw new Error('Digest size cannot exceed key modulus size'); + } - return lo >>> 0; + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeSign$1(hashAlgo, data, n, e, d, p, q, u); + } + } + return bnSign(hashAlgo, n, d, hashed); } -var sum64_5_lo_1 = sum64_5_lo; -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; +/** + * Verify signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} s - Signature + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} hashed - Hashed message + * @returns {Boolean} + * @async + */ +async function verify$6(hashAlgo, data, s, n, e, hashed) { + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeVerify$1(hashAlgo, data, s, n, e); + } + } + return bnVerify(hashAlgo, s, n, e, hashed); } -var rotr64_hi_1 = rotr64_hi; -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; +/** + * Encrypt message + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @returns {Promise} RSA Ciphertext. + * @async + */ +async function encrypt$4(data, n, e) { + if (util.getNodeCrypto()) { + return nodeEncrypt(data, n, e); + } + return bnEncrypt(data, n, e); } -var rotr64_lo_1 = rotr64_lo; -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var shr64_lo_1 = shr64_lo; - -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; +/** + * Decrypt RSA message + * @param {Uint8Array} m - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} RSA Plaintext. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$4(data, n, e, d, p, q, u, randomPayload) { + // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, + // and we want to avoid checking the error type to decide if the random payload + // should indeed be returned. + if (util.getNodeCrypto() && !randomPayload) { + try { + return await nodeDecrypt(data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } } - - return res; -}; - -var common = { - BlockHash: BlockHash_1 -}; - -var rotr32$1 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); + return bnDecrypt(data, n, e, d, p, q, u, randomPayload); } -var ft_1_1 = ft_1; -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -var ch32_1 = ch32; +/** + * Generate a new random private key B bits long with public exponent E. + * + * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param {Integer} bits - RSA bit length + * @param {Integer} e - RSA public exponent + * @returns {{n, e, d, + * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = p ** -1 mod q + * @async + */ +async function generate$4(bits, e) { + e = BigInt(e); -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -var maj32_1 = maj32; + // Native RSA keygen using Web Crypto + if (util.getWebCrypto()) { + const keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, // the specified keysize in bits + publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); + // map JWK parameters to corresponding OpenPGP names + return jwkToPrivate(jwk, e); + } else if (util.getNodeCrypto()) { + const opts = { + modulusLength: bits, + publicExponent: bigIntToNumber(e), + publicKeyEncoding: { type: 'pkcs1', format: 'jwk' }, + privateKeyEncoding: { type: 'pkcs1', format: 'jwk' } + }; + const jwk = await new Promise((resolve, reject) => { + nodeCrypto$3.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => { + if (err) { + reject(err); + } else { + resolve(jwkPrivateKey); + } + }); + }); + return jwkToPrivate(jwk, e); + } -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; + // RSA keygen fallback using 40 iterations of the Miller-Rabin test + // See https://stackoverflow.com/a/6330138 for justification + // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST + let p; + let q; + let n; + do { + q = randomProbablePrime(bits - (bits >> 1), e, 40); + p = randomProbablePrime(bits >> 1, e, 40); + n = p * q; + } while (bitLength(n) !== bits); -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; + const phi = (p - _1n$2) * (q - _1n$2); -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); -} -var g0_256_1 = g0_256; + if (q < p) { + [p, q] = [q, p]; + } -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); + return { + n: bigIntToUint8Array(n), + e: bigIntToUint8Array(e), + d: bigIntToUint8Array(modInv(e, phi)), + p: bigIntToUint8Array(p), + q: bigIntToUint8Array(q), + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: bigIntToUint8Array(modInv(p, q)) + }; } -var g1_256_1 = g1_256; - -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; - -var sum32$1 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$1 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; - -var BlockHash$1 = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$1); -var _256 = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - _256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, _256); -var _224 = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; -var rotr64_hi$1 = utils.rotr64_hi; -var rotr64_lo$1 = utils.rotr64_lo; -var shr64_hi$1 = utils.shr64_hi; -var shr64_lo$1 = utils.shr64_lo; -var sum64$1 = utils.sum64; -var sum64_hi$1 = utils.sum64_hi; -var sum64_lo$1 = utils.sum64_lo; -var sum64_4_hi$1 = utils.sum64_4_hi; -var sum64_4_lo$1 = utils.sum64_4_lo; -var sum64_5_hi$1 = utils.sum64_5_hi; -var sum64_5_lo$1 = utils.sum64_5_lo; - -var BlockHash$2 = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; +/** + * Validate RSA parameters + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA inverse of p w.r.t. q + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$8(n, e, d, p, q, u) { + n = uint8ArrayToBigInt(n); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash$2); -var _512 = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); + // expect pq = n + if ((p * q) !== n) { + return false; } -}; -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - minimalisticAssert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); -}; + const _2n = BigInt(2); + // expect p*u = 1 mod q + u = uint8ArrayToBigInt(u); + if (mod$1(p * u, q) !== BigInt(1)) { + return false; + } -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + /** + * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) + * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] + * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] + * + * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) + */ + const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3)); + const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q + const rde = r * d * e; -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} + const areInverses = mod$1(rde, p - _1n$2) === r && mod$1(rde, q - _1n$2) === r; + if (!areInverses) { + return false; + } -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; + return true; } -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; +async function bnSign(hashAlgo, n, d, hashed) { + n = uint8ArrayToBigInt(n); + const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n))); + d = uint8ArrayToBigInt(d); + return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n)); } -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; +async function webSign$1(hashName, data, n, e, d, p, q, u) { + /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. + * We swap them in privateToJWK, so it usually works out, but nevertheless, + * not all OpenPGP keys are compatible with this requirement. + * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still + * does if the underlying Web Crypto does so (though the tested implementations + * don't do so). + */ + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }; + const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); + return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); } -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); // 34 - var c2_hi = rotr64_hi$1(xl, xh, 7); // 39 +async function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) { + const sign = nodeCrypto$3.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(data); + sign.end(); - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; + const jwk = await privateToJWK$1(n, e, d, p, q, u); + return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' })); } -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); // 34 - var c2_lo = rotr64_lo$1(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; +async function bnVerify(hashAlgo, s, n, e, hashed) { + n = uint8ArrayToBigInt(n); + s = uint8ArrayToBigInt(s); + e = uint8ArrayToBigInt(e); + if (s >= n) { + throw new Error('Signature size cannot exceed modulus size'); + } + const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n)); + const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n)); + return util.equalsUint8Array(EM1, EM2); } -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; +async function webVerify$1(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = await webCrypto$5.importKey('jwk', jwk, { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }, false, ['verify']); + return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); } -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} +async function nodeVerify$1(hashAlgo, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1' }; -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); + const verify = nodeCrypto$3.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(data); + verify.end(); - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; + try { + return verify.verify(key, s); + } catch (err) { + return false; + } } -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); +async function nodeEncrypt(data, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; + return new Uint8Array(nodeCrypto$3.publicEncrypt(key, data)); } -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); // 61 - var c2_hi = shr64_hi$1(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; +async function bnEncrypt(data, n, e) { + n = uint8ArrayToBigInt(n); + data = uint8ArrayToBigInt(emeEncode(data, byteLength(n))); + e = uint8ArrayToBigInt(e); + if (data >= n) { + throw new Error('Message size cannot exceed modulus size'); + } + return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n)); } -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); // 61 - var c2_lo = shr64_lo$1(xh, xl, 6); +async function nodeDecrypt(data, n, e, d, p, q, u) { + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; + try { + return new Uint8Array(nodeCrypto$3.privateDecrypt(key, data)); + } catch (err) { + throw new Error('Decryption error'); + } } -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - _512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, _512); -var _384 = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; +async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { + data = uint8ArrayToBigInt(data); + n = uint8ArrayToBigInt(n); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + u = uint8ArrayToBigInt(u); + if (data >= n) { + throw new Error('Data too large.'); + } + const dq = mod$1(d, q - _1n$2); // d mod (q-1) + const dp = mod$1(d, p - _1n$2); // d mod (p-1) -var rotl32$1 = utils.rotl32; -var sum32$2 = utils.sum32; -var sum32_3$1 = utils.sum32_3; -var sum32_4$2 = utils.sum32_4; -var BlockHash$3 = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash$3.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash$3); -var ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32$2( - rotl32$1( - sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32$1(C, 10); - C = B; - B = T; - T = sum32$2( - rotl32$1( - sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$1(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; -}; + const unblinder = getRandomBigInteger(BigInt(2), n); + const blinder = modExp(modInv(unblinder, n), e, n); + data = mod$1(data * blinder, n); -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; + const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p + const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q + const h = mod$1(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q) -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; + let result = h * p + mp; // result < n due to relations above -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; + result = mod$1(result * unblinder, n); -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; + return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload); +} -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; +/** Convert Openpgp private key params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + * @param {Uint8Array} d + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} u + */ +async function privateToJWK$1(n, e, d, p, q, u) { + const pNum = uint8ArrayToBigInt(p); + const qNum = uint8ArrayToBigInt(q); + const dNum = uint8ArrayToBigInt(d); -var ripemd = { - ripemd160: ripemd160 -}; + let dq = mod$1(dNum, qNum - _1n$2); // d mod (q-1) + let dp = mod$1(dNum, pNum - _1n$2); // d mod (p-1) + dp = bigIntToUint8Array(dp); + dq = bigIntToUint8Array(dq); + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + d: uint8ArrayToB64(d), + // switch p and q + p: uint8ArrayToB64(q), + q: uint8ArrayToB64(p), + // switch dp and dq + dp: uint8ArrayToB64(dq), + dq: uint8ArrayToB64(dp), + qi: uint8ArrayToB64(u), + ext: true + }; +} -/** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. +/** Convert Openpgp key public params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e */ +function publicToJWK(n, e) { + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + ext: true + }; +} -// MD5 Digest -async function md5(entree) { - const digest = md51(util.uint8ArrayToString(entree)); - return util.hexToUint8Array(hex(digest)); +/** Convert JWK private key to OpenPGP private key params */ +function jwkToPrivate(jwk, e) { + return { + n: b64ToUint8Array(jwk.n), + e: bigIntToUint8Array(e), + d: b64ToUint8Array(jwk.d), + // switch p and q + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), + // Since p and q are switched in places, u is the inverse of jwk.q + u: b64ToUint8Array(jwk.qi) + }; } -function md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; +var rsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$4, + encrypt: encrypt$4, + generate: generate$4, + sign: sign$6, + validateParams: validateParams$8, + verify: verify$6 +}); - a = ff(a, b, c, d, k[0], 7, -680876936); - d = ff(d, a, b, c, k[1], 12, -389564586); - c = ff(c, d, a, b, k[2], 17, 606105819); - b = ff(b, c, d, a, k[3], 22, -1044525330); - a = ff(a, b, c, d, k[4], 7, -176418897); - d = ff(d, a, b, c, k[5], 12, 1200080426); - c = ff(c, d, a, b, k[6], 17, -1473231341); - b = ff(b, c, d, a, k[7], 22, -45705983); - a = ff(a, b, c, d, k[8], 7, 1770035416); - d = ff(d, a, b, c, k[9], 12, -1958414417); - c = ff(c, d, a, b, k[10], 17, -42063); - b = ff(b, c, d, a, k[11], 22, -1990404162); - a = ff(a, b, c, d, k[12], 7, 1804603682); - d = ff(d, a, b, c, k[13], 12, -40341101); - c = ff(c, d, a, b, k[14], 17, -1502002290); - b = ff(b, c, d, a, k[15], 22, 1236535329); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - a = gg(a, b, c, d, k[1], 5, -165796510); - d = gg(d, a, b, c, k[6], 9, -1069501632); - c = gg(c, d, a, b, k[11], 14, 643717713); - b = gg(b, c, d, a, k[0], 20, -373897302); - a = gg(a, b, c, d, k[5], 5, -701558691); - d = gg(d, a, b, c, k[10], 9, 38016083); - c = gg(c, d, a, b, k[15], 14, -660478335); - b = gg(b, c, d, a, k[4], 20, -405537848); - a = gg(a, b, c, d, k[9], 5, 568446438); - d = gg(d, a, b, c, k[14], 9, -1019803690); - c = gg(c, d, a, b, k[3], 14, -187363961); - b = gg(b, c, d, a, k[8], 20, 1163531501); - a = gg(a, b, c, d, k[13], 5, -1444681467); - d = gg(d, a, b, c, k[2], 9, -51403784); - c = gg(c, d, a, b, k[7], 14, 1735328473); - b = gg(b, c, d, a, k[12], 20, -1926607734); - a = hh(a, b, c, d, k[5], 4, -378558); - d = hh(d, a, b, c, k[8], 11, -2022574463); - c = hh(c, d, a, b, k[11], 16, 1839030562); - b = hh(b, c, d, a, k[14], 23, -35309556); - a = hh(a, b, c, d, k[1], 4, -1530992060); - d = hh(d, a, b, c, k[4], 11, 1272893353); - c = hh(c, d, a, b, k[7], 16, -155497632); - b = hh(b, c, d, a, k[10], 23, -1094730640); - a = hh(a, b, c, d, k[13], 4, 681279174); - d = hh(d, a, b, c, k[0], 11, -358537222); - c = hh(c, d, a, b, k[3], 16, -722521979); - b = hh(b, c, d, a, k[6], 23, 76029189); - a = hh(a, b, c, d, k[9], 4, -640364487); - d = hh(d, a, b, c, k[12], 11, -421815835); - c = hh(c, d, a, b, k[15], 16, 530742520); - b = hh(b, c, d, a, k[2], 23, -995338651); +const _1n$1 = BigInt(1); - a = ii(a, b, c, d, k[0], 6, -198630844); - d = ii(d, a, b, c, k[7], 10, 1126891415); - c = ii(c, d, a, b, k[14], 15, -1416354905); - b = ii(b, c, d, a, k[5], 21, -57434055); - a = ii(a, b, c, d, k[12], 6, 1700485571); - d = ii(d, a, b, c, k[3], 10, -1894986606); - c = ii(c, d, a, b, k[10], 15, -1051523); - b = ii(b, c, d, a, k[1], 21, -2054922799); - a = ii(a, b, c, d, k[8], 6, 1873313359); - d = ii(d, a, b, c, k[15], 10, -30611744); - c = ii(c, d, a, b, k[6], 15, -1560198380); - b = ii(b, c, d, a, k[13], 21, 1309151649); - a = ii(a, b, c, d, k[4], 6, -145523070); - d = ii(d, a, b, c, k[11], 10, -1120210379); - c = ii(c, d, a, b, k[2], 15, 718787259); - b = ii(b, c, d, a, k[9], 21, -343485551); +/** + * ElGamal Encryption function + * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) + * @param {Uint8Array} data - To be padded and encrypted + * @param {Uint8Array} p + * @param {Uint8Array} g + * @param {Uint8Array} y + * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} + * @async + */ +async function encrypt$3(data, p, g, y) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - x[0] = add32(a, x[0]); - x[1] = add32(b, x[1]); - x[2] = add32(c, x[2]); - x[3] = add32(d, x[3]); -} + const padded = emeEncode(data, byteLength(p)); + const m = uint8ArrayToBigInt(padded); -function cmn(q, a, b, x, s, t) { - a = add32(add32(a, q), add32(x, t)); - return add32((a << s) | (a >>> (32 - s)), b); + // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* + // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] + const k = getRandomBigInteger(_1n$1, p - _1n$1); + return { + c1: bigIntToUint8Array(modExp(g, k, p)), + c2: bigIntToUint8Array(mod$1(modExp(y, k, p) * m, p)) + }; } -function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} +/** + * ElGamal Encryption function + * @param {Uint8Array} c1 + * @param {Uint8Array} c2 + * @param {Uint8Array} p + * @param {Uint8Array} x + * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} Unpadded message. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$3(c1, c2, p, x, randomPayload) { + c1 = uint8ArrayToBigInt(c1); + c2 = uint8ArrayToBigInt(c2); + p = uint8ArrayToBigInt(p); + x = uint8ArrayToBigInt(x); -function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); + const padded = mod$1(modInv(modExp(c1, x, p), p) * c2, p); + return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload); } -function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); -} +/** + * Validate ElGamal parameters + * @param {Uint8Array} p - ElGamal prime + * @param {Uint8Array} g - ElGamal group generator + * @param {Uint8Array} y - ElGamal public key + * @param {Uint8Array} x - ElGamal private exponent + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$7(p, g, y, x) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); -function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); -} + // Check that 1 < g < p + if (g <= _1n$1 || g >= p) { + return false; + } -function md51(s) { - const n = s.length; - const state = [1732584193, -271733879, -1732584194, 271733878]; - let i; - for (i = 64; i <= s.length; i += 64) { - md5cycle(state, md5blk(s.substring(i - 64, i))); + // Expect p-1 to be large + const pSize = BigInt(bitLength(p)); + const _1023n = BigInt(1023); + if (pSize < _1023n) { + return false; } - s = s.substring(i - 64); - const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (i = 0; i < s.length; i++) { - tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + + /** + * g should have order p-1 + * Check that g ** (p-1) = 1 mod p + */ + if (modExp(g, p - _1n$1, p) !== _1n$1) { + return false; } - tail[i >> 2] |= 0x80 << ((i % 4) << 3); - if (i > 55) { - md5cycle(state, tail); - for (i = 0; i < 16; i++) { - tail[i] = 0; + + /** + * Since p-1 is not prime, g might have a smaller order that divides p-1 + * We want to make sure that the order is large enough to hinder a small subgroup attack + * + * We just check g**i != 1 for all i up to a threshold + */ + let res = g; + let i = BigInt(1); + const _2n = BigInt(2); + const threshold = _2n << BigInt(17); // we want order > threshold + while (i < threshold) { + res = mod$1(res * g, p); + if (res === _1n$1) { + return false; } + i++; } - tail[14] = n * 8; - md5cycle(state, tail); - return state; -} -/* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ -function md5blk(s) { /* I figured global was faster. */ - const md5blks = []; - let i; /* Andy King said do it this way. */ - for (i = 0; i < 64; i += 4) { - md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << - 24); + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{r(p-1) + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const r = getRandomBigInteger(_2n << (pSize - _1n$1), _2n << pSize); // draw r of same size as p-1 + const rqx = (p - _1n$1) * r + x; + if (y !== modExp(g, rqx, p)) { + return false; } - return md5blks; + + return true; } -const hex_chr = '0123456789abcdef'.split(''); +var elgamal = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$3, + encrypt: encrypt$3, + validateParams: validateParams$7 +}); -function rhex(n) { - let s = ''; - let j = 0; - for (; j < 4; j++) { - s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; - } - return s; -} +// declare const globalThis: Record | undefined; +const crypto$2 = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; -function hex(x) { - for (let i = 0; i < x.length; i++) { - x[i] = rhex(x[i]); - } - return x.join(''); -} +const nacl = {}; -/* this function is much faster, -so if possible we use it. Some IEs -are the only ones I know of that -need the idiotic second function, -generated by an if clause. */ +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ -function add32(a, b) { - return (a + b) & 0xFFFFFFFF; -} +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; -/** - * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://github.com/indutny/hash.js|hash.js} - * @module crypto/hash - * @private - */ +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; -const webCrypto = util.getWebCrypto(); -const nodeCrypto = util.getNodeCrypto(); -const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes(); +var _9 = new Uint8Array(32); _9[0] = 9; -function nodeHash(type) { - if (!nodeCrypto || !nodeCryptoHashes.includes(type)) { - return; - } - return async function (data) { - const shasum = nodeCrypto.createHash(type); - return transform(data, value => { - shasum.update(value); - }, () => new Uint8Array(shasum.digest())); - }; -} +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); -function hashjsHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } - const hashInstance = hash(); - return transform(data, value => { - hashInstance.update(value); - }, () => new Uint8Array(hashInstance.digest())); - }; +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; } -function asmcryptoHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (util.isStream(data)) { - const hashInstance = new hash(); - return transform(data, value => { - hashInstance.process(value); - }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } else { - return hash.bytes(data); - } - }; +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; } -const hashFunctions = { - md5: nodeHash('md5') || md5, - sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'), - sha224: nodeHash('sha224') || hashjsHash(_224), - sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'), - sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'), - sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160) -}; - -var hash = { +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} - /** @see module:md5 */ - md5: hashFunctions.md5, - /** @see asmCrypto */ - sha1: hashFunctions.sha1, - /** @see hash.js */ - sha224: hashFunctions.sha224, - /** @see asmCrypto */ - sha256: hashFunctions.sha256, - /** @see hash.js */ - sha384: hashFunctions.sha384, - /** @see asmCrypto */ - sha512: hashFunctions.sha512, - /** @see hash.js */ - ripemd: hashFunctions.ripemd, +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - /** - * Create a hash on the specified data using the specified algorithm - * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {Uint8Array} data - Data to be hashed - * @returns {Promise} Hash value. - */ - digest: function(algo, data) { - switch (algo) { - case enums.hash.md5: - return this.md5(data); - case enums.hash.sha1: - return this.sha1(data); - case enums.hash.ripemd: - return this.ripemd(data); - case enums.hash.sha256: - return this.sha256(data); - case enums.hash.sha384: - return this.sha384(data); - case enums.hash.sha512: - return this.sha512(data); - case enums.hash.sha224: - return this.sha224(data); - default: - throw new Error('Invalid hash function.'); - } - }, +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns {Integer} Size in bytes of the resulting hash. - */ - getHashByteLength: function(algo) { - switch (algo) { - case enums.hash.md5: - return 16; - case enums.hash.sha1: - case enums.hash.ripemd: - return 20; - case enums.hash.sha256: - return 32; - case enums.hash.sha384: - return 48; - case enums.hash.sha512: - return 64; - case enums.hash.sha224: - return 28; - default: - throw new Error('Invalid hash algorithm.'); - } +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; } -}; +} -class AES_CFB { - static encrypt(data, key, iv) { - return new AES_CFB(key, iv).encrypt(data); - } - static decrypt(data, key, iv) { - return new AES_CFB(key, iv).decrypt(data); - } - constructor(key, iv, aes) { - this.aes = aes ? aes : new AES(key, iv, true, 'CFB'); - delete this.aes.padding; - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } } -/** - * Get implementation of the given cipher - * @param {enums.symmetric} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getCipher(algo) { - const algoName = enums.read(enums.symmetric, algo); - return cipher[algoName]; +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); } -// Modified by ProtonTech AG - -const webCrypto$1 = util.getWebCrypto(); -const nodeCrypto$1 = util.getNodeCrypto(); - -const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : []; -const nodeAlgos = { - idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ - tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, - cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, - blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, - aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, - aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, - aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined - /* twofish is not implemented in OpenSSL */ -}; +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} -/** - * CFB encryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} plaintext - * @param {Uint8Array} iv - * @param {Object} config - full configuration, defaults to openpgp.config - * @returns MaybeStream - */ -async function encrypt(algo, key, plaintext, iv, config) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeEncrypt(algo, key, plaintext, iv); - } - if (util.isAES(algo)) { - return aesEncrypt(algo, key, plaintext, iv, config); - } +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} - const blockc = iv.slice(); - let pt = new Uint8Array(); - const process = chunk => { - if (chunk) { - pt = util.concatUint8Array([pt, chunk]); - } - const ciphertext = new Uint8Array(pt.length); - let i; - let j = 0; - while (chunk ? pt.length >= block_size : pt.length) { - const encblock = cipherfn.encrypt(blockc); - for (i = 0; i < block_size; i++) { - blockc[i] = pt[i] ^ encblock[i]; - ciphertext[j++] = blockc[i]; - } - pt = pt.subarray(block_size); - } - return ciphertext.subarray(0, j); - }; - return transform(plaintext, process, process); +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } -/** - * CFB decryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} ciphertext - * @param {Uint8Array} iv - * @returns MaybeStream - */ -async function decrypt(algo, key, ciphertext, iv) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeDecrypt(algo, key, ciphertext, iv); - } - if (util.isAES(algo)) { - return aesDecrypt(algo, key, ciphertext, iv); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - let blockp = iv; - let ct = new Uint8Array(); - const process = chunk => { - if (chunk) { - ct = util.concatUint8Array([ct, chunk]); - } - const plaintext = new Uint8Array(ct.length); - let i; - let j = 0; - while (chunk ? ct.length >= block_size : ct.length) { - const decblock = cipherfn.encrypt(blockp); - blockp = ct.subarray(0, block_size); - for (i = 0; i < block_size; i++) { - plaintext[j++] = blockp[i] ^ decblock[i]; - } - ct = ct.subarray(block_size); - } - return plaintext.subarray(0, j); - }; - return transform(ciphertext, process, process); -} - -function aesEncrypt(algo, key, pt, iv, config) { - if ( - util.getWebCrypto() && - key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support - !util.isStream(pt) && - pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2 - ) { // Web Crypto - return webEncrypt(algo, key, pt, iv); - } - // asm.js fallback - const cfb = new AES_CFB(key, iv); - return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish()); -} - -function aesDecrypt(algo, key, ct, iv) { - if (util.isStream(ct)) { - const cfb = new AES_CFB(key, iv); - return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish()); - } - return AES_CFB.decrypt(ct, key, iv); -} - -function xorMut(a, b) { - for (let i = 0; i < a.length; i++) { - a[i] = a[i] ^ b[i]; - } -} - -async function webEncrypt(algo, key, pt, iv) { - const ALGO = 'AES-CBC'; - const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']); - const { blockSize } = getCipher(algo); - const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]); - const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length); - xorMut(ct, pt); - return ct; -} - -function nodeEncrypt(algo, key, pt, iv) { - const algoName = enums.read(enums.symmetric, algo); - const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv); - return transform(pt, value => new Uint8Array(cipherObj.update(value))); -} - -function nodeDecrypt(algo, key, ct, iv) { - const algoName = enums.read(enums.symmetric, algo); - const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv); - return transform(ct, value => new Uint8Array(decipherObj.update(value))); -} - -var cfb = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt, - decrypt: decrypt -}); - -class AES_CTR { - static encrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - static decrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - constructor(key, nonce, aes) { - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - delete this.aes.padding; - this.AES_CTR_set_options(nonce); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - AES_CTR_set_options(nonce, counter, size) { - let { asm } = this.aes.acquire_asm(); - if (size !== undefined) { - if (size < 8 || size > 48) - throw new IllegalArgumentError('illegal counter size'); - let mask = Math.pow(2, size) - 1; - asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0); - } - else { - size = 48; - asm.set_mask(0, 0, 0xffff, 0xffffffff); - } - if (nonce !== undefined) { - let len = nonce.length; - if (!len || len > 16) - throw new IllegalArgumentError('illegal nonce size'); - let view = new DataView(new ArrayBuffer(16)); - new Uint8Array(view.buffer).set(nonce); - asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); - } - else { - throw new Error('nonce is required'); - } - if (counter !== undefined) { - if (counter < 0 || counter >= Math.pow(2, size)) - throw new IllegalArgumentError('illegal counter value'); - asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0); - } - } -} - -class AES_CBC { - static encrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).encrypt(data); - } - static decrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).decrypt(data); - } - constructor(key, iv, padding = true, aes) { - this.aes = aes ? aes : new AES(key, iv, padding, 'CBC'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * @fileoverview This module implements AES-CMAC on top of - * native AES-CBC using either the WebCrypto API or Node.js' crypto API. - * @module crypto/cmac - * @private - */ - -const webCrypto$2 = util.getWebCrypto(); -const nodeCrypto$2 = util.getNodeCrypto(); - - -/** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - -const blockLength = 16; - - -/** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param {Uint8Array} data - * @param {Uint8Array} padding - */ -function rightXORMut(data, padding) { - const offset = data.length - blockLength; - for (let i = 0; i < blockLength; i++) { - data[i + offset] ^= padding[i]; - } - return data; -} - -function pad(data, padding, padding2) { - // if |M| in {n, 2n, 3n, ...} - if (data.length && data.length % blockLength === 0) { - // then return M xor→ B, - return rightXORMut(data, padding); - } - // else return (M || 10^(n−1−(|M| mod n))) xor→ P - const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength))); - padded.set(data); - padded[data.length] = 0b10000000; - return rightXORMut(padded, padding2); -} - -const zeroBlock = new Uint8Array(blockLength); - -async function CMAC(key) { - const cbc = await CBC(key); - - // L ← E_K(0^n); B ← 2L; P ← 4L - const padding = util.double(await cbc(zeroBlock)); - const padding2 = util.double(padding); - - return async function(data) { - // return CBC_K(pad(M; B, P)) - return (await cbc(pad(data, padding, padding2))).subarray(-blockLength); - }; -} - -async function CBC(key) { - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); - return async function(pt) { - const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt); - return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt) { - const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); - const ct = en.update(pt); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt) { - return AES_CBC.encrypt(pt, key, false, zeroBlock); - }; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$3 = util.getWebCrypto(); -const nodeCrypto$3 = util.getNodeCrypto(); -const Buffer$1 = util.getNodeBuffer(); - - -const blockLength$1 = 16; -const ivLength = blockLength$1; -const tagLength = blockLength$1; - -const zero = new Uint8Array(blockLength$1); -const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1; -const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2; - -async function OMAC(key) { - const cmac = await CMAC(key); - return function(t, message) { - return cmac(util.concatUint8Array([t, message])); - }; -} - -async function CTR(key) { - if ( - util.getWebCrypto() && - key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - ) { - key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); - return async function(pt, iv) { - const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt); - return new Uint8Array(ct); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt, iv) { - const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); - const ct = Buffer$1.concat([en.update(pt), en.final()]); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt, iv) { - return AES_CTR.encrypt(pt, key, iv); - }; -} - - -/** - * Class to en/decrypt using EAX mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function EAX(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('EAX mode supports only AES cipher'); - } - - const [ - omac, - ctr - ] = await Promise.all([ - OMAC(key), - CTR(key) - ]); - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - const [ - omacNonce, - omacAdata - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata) - ]); - const ciphered = await ctr(plaintext, omacNonce); - const omacCiphered = await omac(two, ciphered); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - return util.concatUint8Array([ciphered, tag]); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to verify - * @returns {Promise} The plaintext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext'); - const ciphered = ciphertext.subarray(0, -tagLength); - const ctTag = ciphertext.subarray(-tagLength); - const [ - omacNonce, - omacAdata, - omacCiphered - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata), - omac(two, ciphered) - ]); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); - const plaintext = await ctr(ciphered, omacNonce); - return plaintext; - } - }; -} - - -/** - * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. - * @param {Uint8Array} iv - The initialization vector (16 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -EAX.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[8 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -EAX.blockLength = blockLength$1; -EAX.ivLength = ivLength; -EAX.tagLength = tagLength; - -// OpenPGP.js - An OpenPGP implementation in javascript - -const blockLength$2 = 16; -const ivLength$1 = 15; - -// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: -// While OCB [RFC7253] allows the authentication tag length to be of any -// number up to 128 bits long, this document requires a fixed -// authentication tag length of 128 bits (16 octets) for simplicity. -const tagLength$1 = 16; - - -function ntz(n) { - let ntz = 0; - for (let i = 1; (n & i) === 0; i <<= 1) { - ntz++; - } - return ntz; -} - -function xorMut$1(S, T) { - for (let i = 0; i < S.length; i++) { - S[i] ^= T[i]; - } - return S; -} - -function xor(S, T) { - return xorMut$1(S.slice(), T); -} - -const zeroBlock$1 = new Uint8Array(blockLength$2); -const one$1 = new Uint8Array([1]); - -/** - * Class to en/decrypt using OCB mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function OCB(cipher$1, key) { - - let maxNtz = 0; - let encipher; - let decipher; - let mask; - - constructKeyVariables(cipher$1, key); - - function constructKeyVariables(cipher$1, key) { - const cipherName = enums.read(enums.symmetric, cipher$1); - const aes = new cipher[cipherName](key); - encipher = aes.encrypt.bind(aes); - decipher = aes.decrypt.bind(aes); - - const mask_x = encipher(zeroBlock$1); - const mask_$ = util.double(mask_x); - mask = []; - mask[0] = util.double(mask_$); - - - mask.x = mask_x; - mask.$ = mask_$; - } - - function extendKeyVariables(text, adata) { - const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1; - for (let i = maxNtz + 1; i <= newMaxNtz; i++) { - mask[i] = util.double(mask[i - 1]); - } - maxNtz = newMaxNtz; - } - - function hash(adata) { - if (!adata.length) { - // Fast path - return zeroBlock$1; - } - - // - // Consider A as a sequence of 128-bit blocks - // - const m = adata.length / blockLength$2 | 0; - - const offset = new Uint8Array(blockLength$2); - const sum = new Uint8Array(blockLength$2); - for (let i = 0; i < m; i++) { - xorMut$1(offset, mask[ntz(i + 1)]); - xorMut$1(sum, encipher(xor(offset, adata))); - adata = adata.subarray(blockLength$2); - } - - // - // Process any final partial block; compute final hash value - // - if (adata.length) { - xorMut$1(offset, mask.x); - - const cipherInput = new Uint8Array(blockLength$2); - cipherInput.set(adata, 0); - cipherInput[adata.length] = 0b10000000; - xorMut$1(cipherInput, offset); - - xorMut$1(sum, encipher(cipherInput)); - } - - return sum; - } - - /** - * Encrypt/decrypt data. - * @param {encipher|decipher} fn - Encryption/decryption block cipher function - * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. - */ - function crypt(fn, text, nonce, adata) { - // - // Consider P as a sequence of 128-bit blocks - // - const m = text.length / blockLength$2 | 0; - - // - // Key-dependent variables - // - extendKeyVariables(text, adata); - - // - // Nonce-dependent and per-encryption variables - // - // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N - // Note: We assume here that tagLength mod 16 == 0. - const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]); - // bottom = str2num(Nonce[123..128]) - const bottom = paddedNonce[blockLength$2 - 1] & 0b111111; - // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) - paddedNonce[blockLength$2 - 1] &= 0b11000000; - const kTop = encipher(paddedNonce); - // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) - const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); - // Offset_0 = Stretch[1+bottom..128+bottom] - const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); - // Checksum_0 = zeros(128) - const checksum = new Uint8Array(blockLength$2); - - const ct = new Uint8Array(text.length + tagLength$1); - - // - // Process any whole blocks - // - let i; - let pos = 0; - for (i = 0; i < m; i++) { - // Offset_i = Offset_{i-1} xor L_{ntz(i)} - xorMut$1(offset, mask[ntz(i + 1)]); - // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) - // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) - ct.set(xorMut$1(fn(xor(offset, text)), offset), pos); - // Checksum_i = Checksum_{i-1} xor P_i - xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos)); - - text = text.subarray(blockLength$2); - pos += blockLength$2; - } - - // - // Process any final partial block and compute raw tag - // - if (text.length) { - // Offset_* = Offset_m xor L_* - xorMut$1(offset, mask.x); - // Pad = ENCIPHER(K, Offset_*) - const padding = encipher(offset); - // C_* = P_* xor Pad[1..bitlen(P_*)] - ct.set(xor(text, padding), pos); - - // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - const xorInput = new Uint8Array(blockLength$2); - xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); - xorInput[text.length] = 0b10000000; - xorMut$1(checksum, xorInput); - pos += text.length; - } - // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) - const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata)); - - // - // Assemble ciphertext - // - // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] - ct.set(tag, pos); - return ct; - } - - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - return crypt(encipher, plaintext, nonce, adata); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); - - const tag = ciphertext.subarray(-tagLength$1); - ciphertext = ciphertext.subarray(0, -tagLength$1); - - const crypted = crypt(decipher, ciphertext, nonce, adata); - // if (Tag[1..TAGLEN] == T) - if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { - return crypted.subarray(0, -tagLength$1); - } - throw new Error('Authentication tag mismatch'); - } - }; -} - - -/** - * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. - * @param {Uint8Array} iv - The initialization vector (15 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -OCB.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[7 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -OCB.blockLength = blockLength$2; -OCB.ivLength = ivLength$1; -OCB.tagLength = tagLength$1; - -const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 -class AES_GCM { - constructor(key, nonce, adata, tagSize = 16, aes) { - this.tagSize = tagSize; - this.gamma0 = 0; - this.counter = 1; - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - let { asm, heap } = this.aes.acquire_asm(); - // Init GCM - asm.gcm_init(); - // Tag size - if (this.tagSize < 4 || this.tagSize > 16) - throw new IllegalArgumentError('illegal tagSize value'); - // Nonce - const noncelen = nonce.length || 0; - const noncebuf = new Uint8Array(16); - if (noncelen !== 12) { - this._gcm_mac_process(nonce); - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = 0; - heap[4] = 0; - heap[5] = 0; - heap[6] = 0; - heap[7] = 0; - heap[8] = 0; - heap[9] = 0; - heap[10] = 0; - heap[11] = noncelen >>> 29; - heap[12] = (noncelen >>> 21) & 255; - heap[13] = (noncelen >>> 13) & 255; - heap[14] = (noncelen >>> 5) & 255; - heap[15] = (noncelen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_iv(0, 0, 0, 0); - noncebuf.set(heap.subarray(0, 16)); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; - } - const nonceview = new DataView(noncebuf.buffer); - this.gamma0 = nonceview.getUint32(12); - asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); - asm.set_mask(0, 0, 0, 0xffffffff); - // Associated data - if (adata !== undefined) { - if (adata.length > _AES_GCM_data_maxLength) - throw new IllegalArgumentError('illegal adata length'); - if (adata.length) { - this.adata = adata; - this._gcm_mac_process(adata); - } - else { - this.adata = undefined; - } - } - else { - this.adata = undefined; - } - // Counter - if (this.counter < 1 || this.counter > 0xffffffff) - throw new RangeError('counter must be a positive 32-bit integer'); - asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0); - } - static encrypt(cleartext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext); - } - static decrypt(ciphertext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext); - } - encrypt(data) { - return this.AES_GCM_encrypt(data); - } - decrypt(data) { - return this.AES_GCM_decrypt(data); - } - AES_GCM_Encrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len); - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Encrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let adata = this.adata; - let pos = this.aes.pos; - let len = this.aes.len; - const result = new Uint8Array(len + tagSize); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16); - if (len) - result.set(heap.subarray(pos, pos + len)); - let i = len; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - result.set(heap.subarray(0, tagSize), len); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_Decrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0; - let tlen = len + dlen - rlen; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > tlen) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - pos = 0; - len = 0; - } - if (dlen > 0) { - len += _heap_write(heap, 0, data, dpos, dlen); - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Decrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let tagSize = this.tagSize; - let adata = this.adata; - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rlen = len - tagSize; - if (len < tagSize) - throw new IllegalStateError('authentication tag not found'); - const result = new Uint8Array(rlen); - const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); - let i = rlen; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len - tagSize; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - let acheck = 0; - for (let i = 0; i < tagSize; ++i) - acheck |= atag[i] ^ heap[i]; - if (acheck) - throw new SecurityError('data integrity check failed'); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_decrypt(data) { - const result1 = this.AES_GCM_Decrypt_process(data); - const result2 = this.AES_GCM_Decrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - AES_GCM_encrypt(data) { - const result1 = this.AES_GCM_Encrypt_process(data); - const result2 = this.AES_GCM_Encrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - _gcm_mac_process(data) { - let { asm, heap } = this.aes.acquire_asm(); - let dpos = 0; - let dlen = data.length || 0; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, 0, data, dpos, dlen); - dpos += wlen; - dlen -= wlen; - while (wlen & 15) - heap[wlen++] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$4 = util.getWebCrypto(); -const nodeCrypto$4 = util.getNodeCrypto(); -const Buffer$2 = util.getNodeBuffer(); - -const blockLength$3 = 16; -const ivLength$2 = 12; // size of the IV in bytes -const tagLength$2 = 16; // size of the tag in bytes -const ALGO = 'AES-GCM'; - -/** - * Class to en/decrypt using GCM mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function GCM(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('GCM mode supports only AES cipher'); - } - - if (util.getNodeCrypto()) { // Node crypto library - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - en.setAAD(adata); - const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - de.setAAD(adata); - de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext - const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]); - return new Uint8Array(pt); - } - }; - } - - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); - - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.encrypt(pt, key, iv, adata); - } - const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt); - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.decrypt(ct, key, iv, adata); - } - const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct); - return new Uint8Array(pt); - } - }; - } - - return { - encrypt: async function(pt, iv, adata) { - return AES_GCM.encrypt(pt, key, iv, adata); - }, - - decrypt: async function(ct, iv, adata) { - return AES_GCM.decrypt(ct, key, iv, adata); - } - }; -} - - -/** - * Get GCM nonce. Note: this operation is not defined by the standard. - * A future version of the standard may define GCM mode differently, - * hopefully under a different ID (we use Private/Experimental algorithm - * ID 100) so that we can maintain backwards compatibility. - * @param {Uint8Array} iv - The initialization vector (12 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -GCM.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[4 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -GCM.blockLength = blockLength$3; -GCM.ivLength = ivLength$2; -GCM.tagLength = tagLength$2; - -/** - * @fileoverview Cipher modes - * @module crypto/mode - * @private - */ - -var mode = { - /** @see module:crypto/mode/cfb */ - cfb: cfb, - /** @see module:crypto/mode/gcm */ - gcm: GCM, - experimentalGCM: GCM, - /** @see module:crypto/mode/eax */ - eax: EAX, - /** @see module:crypto/mode/ocb */ - ocb: OCB -}; - -var naclFastLight = createCommonjsModule(function (module) { -/*jshint bitwise: false*/ - -(function(nacl) { - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d; - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d, h, r; - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - r = nacl.hash(sm.subarray(32, smlen)); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - h = nacl.hash(sm.subarray(0, smlen)); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i; - var t = new Uint8Array(32), h; - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - h = nacl.hash(m.subarray(0, n)); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - return n; -} - -var crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32; - -function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError('unexpected type, use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.box = {}; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof commonjsRequire !== 'undefined') { - // Node.js. - crypto = void('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(module.exports ? module.exports : (self.nacl = self.nacl || {})); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const nodeCrypto$5 = util.getNodeCrypto(); - -/** - * Retrieve secure random byte array of the specified length - * @param {Integer} length - Length in bytes to generate - * @returns {Uint8Array} Random byte array. - */ -function getRandomBytes(length) { - const buf = new Uint8Array(length); - if (nodeCrypto$5) { - const bytes = nodeCrypto$5.randomBytes(buf.length); - buf.set(bytes); - } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - crypto.getRandomValues(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; -} - -/** - * Create a secure random BigInteger that is greater than or equal to min and less than max. - * @param {module:BigInteger} min - Lower bound, included - * @param {module:BigInteger} max - Upper bound, excluded - * @returns {Promise} Random BigInteger. - * @async - */ -async function getRandomBigInteger(min, max) { - const BigInteger = await util.getBigInteger(); - - if (max.lt(min)) { - throw new Error('Illegal parameter value: max <= min'); - } - - const modulus = max.sub(min); - const bytes = modulus.byteLength(); - - // Using a while loop is necessary to avoid bias introduced by the mod operation. - // However, we request 64 extra random bits so that the bias is negligible. - // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - const r = new BigInteger(await getRandomBytes(bytes + 8)); - return r.mod(modulus).add(min); -} - -var random = /*#__PURE__*/Object.freeze({ - __proto__: null, - getRandomBytes: getRandomBytes, - getRandomBigInteger: getRandomBigInteger -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Generate a probably prime random number - * @param {Integer} bits - Bit length of the prime - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns BigInteger - * @async - */ -async function randomProbablePrime(bits, e, k) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - const min = one.leftShift(new BigInteger(bits - 1)); - const thirty = new BigInteger(30); - /* - * We can avoid any multiples of 3 and 5 by looking at n mod 30 - * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 - * the next possible prime is mod 30: - * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 - */ - const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; - - const n = await getRandomBigInteger(min, min.leftShift(one)); - let i = n.mod(thirty).toNumber(); - - do { - n.iadd(new BigInteger(adds[i])); - i = (i + adds[i]) % adds.length; - // If reached the maximum, go back to the minimum. - if (n.bitLength() > bits) { - n.imod(min.leftShift(one)).iadd(min); - i = n.mod(thirty).toNumber(); - } - } while (!await isProbablePrime(n, e, k)); - return n; -} - -/** - * Probabilistic primality testing - * @param {BigInteger} n - Number to test - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns {boolean} - * @async - */ -async function isProbablePrime(n, e, k) { - if (e && !n.dec().gcd(e).isOne()) { - return false; - } - if (!await divisionTest(n)) { - return false; - } - if (!await fermat(n)) { - return false; - } - if (!await millerRabin(n, k)) { - return false; - } - // TODO implement the Lucas test - // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - return true; -} - -/** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n != 1. - * @param {BigInteger} n - Number to test - * @param {BigInteger} b - Optional Fermat test base - * @returns {boolean} - */ -async function fermat(n, b) { - const BigInteger = await util.getBigInteger(); - b = b || new BigInteger(2); - return b.modExp(n.dec(), n).isOne(); -} - -async function divisionTest(n) { - const BigInteger = await util.getBigInteger(); - return smallPrimes.every(m => { - return n.mod(new BigInteger(m)) !== 0; - }); -} - -// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c -const smallPrimes = [ - 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, - 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, - 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, - 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, - 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, - 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, - 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, - 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, - 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, - 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, - 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, - 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, - 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, - 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, - 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, - 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, - 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, - 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, - 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, - 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, - 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, - 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, - 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, - 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, - 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, - 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, - 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, - 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, - 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, - 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, - 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, - 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, - 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, - 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, - 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, - 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, - 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, - 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, - 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, - 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, - 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, - 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, - 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, - 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, - 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, - 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, - 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, - 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, - 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, - 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, - 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, - 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, - 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, - 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, - 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, - 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, - 4957, 4967, 4969, 4973, 4987, 4993, 4999 -]; - - -// Miller-Rabin - Miller Rabin algorithm for primality test -// Copyright Fedor Indutny, 2014. -// -// This software is licensed under the MIT License. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin - -// Sample syntax for Fixed-Base Miller-Rabin: -// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) - -/** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param {BigInteger} n - Number to test - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @param {Function} rand - Optional function to generate potential witnesses - * @returns {boolean} - * @async - */ -async function millerRabin(n, k, rand) { - const BigInteger = await util.getBigInteger(); - const len = n.bitLength(); - - if (!k) { - k = Math.max(1, (len / 48) | 0); - } - - const n1 = n.dec(); // n - 1 - - // Find d and s, (n - 1) = (2 ^ s) * d; - let s = 0; - while (!n1.getBit(s)) { s++; } - const d = n.rightShift(new BigInteger(s)); - - for (; k > 0; k--) { - const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1); - - let x = a.modExp(d, n); - if (x.isOne() || x.equal(n1)) { - continue; - } - - let i; - for (i = 1; i < s; i++) { - x = x.mul(x).mod(n); - - if (x.isOne()) { - return false; - } - if (x.equal(n1)) { - break; - } - } - - if (i === s) { - return false; - } - } - - return true; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ASN1 object identifiers for hashes - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} - */ -const hash_headers = []; -hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; -hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; -hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; -hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; -hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; -hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; -hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; - -/** - * Create padding with secure random data - * @private - * @param {Integer} length - Length of the padding in bytes - * @returns {Uint8Array} Random padding. - */ -function getPKCS1Padding(length) { - const result = new Uint8Array(length); - let count = 0; - while (count < length) { - const randomBytes = getRandomBytes(length - count); - for (let i = 0; i < randomBytes.length; i++) { - if (randomBytes[i] !== 0) { - result[count++] = randomBytes[i]; - } - } - } - return result; -} - -/** - * Create a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} - * @param {Uint8Array} message - Message to be encoded - * @param {Integer} keyLength - The length in octets of the key modulus - * @returns {Uint8Array} EME-PKCS1 padded message. - */ -function emeEncode(message, keyLength) { - const mLength = message.length; - // length checking - if (mLength > keyLength - 11) { - throw new Error('Message too long'); - } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - const PS = getPKCS1Padding(keyLength - mLength - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - const encoded = new Uint8Array(keyLength); - // 0x00 byte - encoded[1] = 2; - encoded.set(PS, 2); - // 0x00 bytes - encoded.set(message, keyLength - mLength); - return encoded; -} - -/** - * Decode a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} - * @param {Uint8Array} encoded - Encoded message bytes - * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) - * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) - * @throws {Error} on decoding failure, unless `randomPayload` is provided - */ -function emeDecode(encoded, randomPayload) { - // encoded format: 0x00 0x02 0x00 - let offset = 2; - let separatorNotFound = 1; - for (let j = offset; j < encoded.length; j++) { - separatorNotFound &= encoded[j] !== 0; - offset += separatorNotFound; - } - - const psLen = offset - 2; - const payload = encoded.subarray(offset + 1); // discard the 0x00 separator - const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - - if (randomPayload) { - return util.selectUint8Array(isValidPadding, payload, randomPayload); - } - - if (isValidPadding) { - return payload; - } - - throw new Error('Decryption error'); -} - -/** - * Create a EMSA-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} - * @param {Integer} algo - Hash algorithm type used - * @param {Uint8Array} hashed - Message to be encoded - * @param {Integer} emLen - Intended length in octets of the encoded message - * @returns {Uint8Array} Encoded message. - */ -async function emsaEncode(algo, hashed, emLen) { - let i; - if (hashed.length !== hash.getHashByteLength(algo)) { - throw new Error('Invalid hash length'); - } - // produce an ASN.1 DER value for the hash function used. - // Let T be the full hash prefix - const hashPrefix = new Uint8Array(hash_headers[algo].length); - for (i = 0; i < hash_headers[algo].length; i++) { - hashPrefix[i] = hash_headers[algo][i]; - } - // and let tLen be the length in octets prefix and hashed data - const tLen = hashPrefix.length + hashed.length; - if (emLen < tLen + 11) { - throw new Error('Intended encoded message length too short'); - } - // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF - // The length of PS will be at least 8 octets - const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - - // Concatenate PS, the hash prefix, hashed data, and other padding to form the - // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed - const EM = new Uint8Array(emLen); - EM[1] = 0x01; - EM.set(PS, 2); - EM.set(hashPrefix, emLen - tLen); - EM.set(hashed, emLen - hashed.length); - return EM; -} - -var pkcs1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - emeEncode: emeEncode, - emeDecode: emeDecode, - emsaEncode: emsaEncode -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const webCrypto$5 = util.getWebCrypto(); -const nodeCrypto$6 = util.getNodeCrypto(); -const asn1 = nodeCrypto$6 ? void('asn1.js') : undefined; - -/* eslint-disable no-invalid-this */ -const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('version').int(), // 0 - this.key('modulus').int(), // n - this.key('publicExponent').int(), // e - this.key('privateExponent').int(), // d - this.key('prime1').int(), // p - this.key('prime2').int(), // q - this.key('exponent1').int(), // dp - this.key('exponent2').int(), // dq - this.key('coefficient').int() // u - ); -}) : undefined; - -const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('modulus').int(), // n - this.key('publicExponent').int() // e - ); -}) : undefined; -/* eslint-enable no-invalid-this */ - -/** Create signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} hashed - Hashed message - * @returns {Promise} RSA Signature. - * @async - */ -async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeSign(hashAlgo, data, n, e, d, p, q, u); - } - } - return bnSign(hashAlgo, n, d, hashed); -} - -/** - * Verify signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} s - Signature - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} hashed - Hashed message - * @returns {Boolean} - * @async - */ -async function verify(hashAlgo, data, s, n, e, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeVerify(hashAlgo, data, s, n, e); - } - } - return bnVerify(hashAlgo, s, n, e, hashed); -} - -/** - * Encrypt message - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @returns {Promise} RSA Ciphertext. - * @async - */ -async function encrypt$1(data, n, e) { - if (util.getNodeCrypto()) { - return nodeEncrypt$1(data, n, e); - } - return bnEncrypt(data, n, e); -} - -/** - * Decrypt RSA message - * @param {Uint8Array} m - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} RSA Plaintext. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$1(data, n, e, d, p, q, u, randomPayload) { - // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, - // and we want to avoid checking the error type to decide if the random payload - // should indeed be returned. - if (util.getNodeCrypto() && !randomPayload) { - try { - return await nodeDecrypt$1(data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } - return bnDecrypt(data, n, e, d, p, q, u, randomPayload); -} - -/** - * Generate a new random private key B bits long with public exponent E. - * - * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param {Integer} bits - RSA bit length - * @param {Integer} e - RSA public exponent - * @returns {{n, e, d, - * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = p ** -1 mod q - * @async - */ -async function generate(bits, e) { - const BigInteger = await util.getBigInteger(); - - e = new BigInteger(e); - - // Native RSA keygen using Web Crypto - if (util.getWebCrypto()) { - const keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, // the specified keysize in bits - publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); - // map JWK parameters to corresponding OpenPGP names - return { - n: b64ToUint8Array(jwk.n), - e: e.toUint8Array(), - d: b64ToUint8Array(jwk.d), - // switch p and q - p: b64ToUint8Array(jwk.q), - q: b64ToUint8Array(jwk.p), - // Since p and q are switched in places, u is the inverse of jwk.q - u: b64ToUint8Array(jwk.qi) - }; - } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) { - const opts = { - modulusLength: bits, - publicExponent: e.toNumber(), - publicKeyEncoding: { type: 'pkcs1', format: 'der' }, - privateKeyEncoding: { type: 'pkcs1', format: 'der' } - }; - const prv = await new Promise((resolve, reject) => { - nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => { - if (err) { - reject(err); - } else { - resolve(RSAPrivateKey.decode(der, 'der')); - } - }); - }); - /** - * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`. - * @link https://tools.ietf.org/html/rfc3447#section-3.2 - * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1 - */ - return { - n: prv.modulus.toArrayLike(Uint8Array), - e: prv.publicExponent.toArrayLike(Uint8Array), - d: prv.privateExponent.toArrayLike(Uint8Array), - // switch p and q - p: prv.prime2.toArrayLike(Uint8Array), - q: prv.prime1.toArrayLike(Uint8Array), - // Since p and q are switched in places, we can keep u as defined by DER - u: prv.coefficient.toArrayLike(Uint8Array) - }; - } - - // RSA keygen fallback using 40 iterations of the Miller-Rabin test - // See https://stackoverflow.com/a/6330138 for justification - // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST - let p; - let q; - let n; - do { - q = await randomProbablePrime(bits - (bits >> 1), e, 40); - p = await randomProbablePrime(bits >> 1, e, 40); - n = p.mul(q); - } while (n.bitLength() !== bits); - - const phi = p.dec().imul(q.dec()); - - if (q.lt(p)) { - [p, q] = [q, p]; - } - - return { - n: n.toUint8Array(), - e: e.toUint8Array(), - d: e.modInv(phi).toUint8Array(), - p: p.toUint8Array(), - q: q.toUint8Array(), - // dp: d.mod(p.subn(1)), - // dq: d.mod(q.subn(1)), - u: p.modInv(q).toUint8Array() - }; -} - -/** - * Validate RSA parameters - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA inverse of p w.r.t. q - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - p = new BigInteger(p); - q = new BigInteger(q); - - // expect pq = n - if (!p.mul(q).equal(n)) { - return false; - } - - const two = new BigInteger(2); - // expect p*u = 1 mod q - u = new BigInteger(u); - if (!p.mul(u).mod(q).isOne()) { - return false; - } - - e = new BigInteger(e); - d = new BigInteger(d); - /** - * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) - * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] - * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] - * - * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) - */ - const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3)); - const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q - const rde = r.mul(d).mul(e); - - const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r); - if (!areInverses) { - return false; - } - - return true; -} - -async function bnSign(hashAlgo, n, d, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); - d = new BigInteger(d); - if (m.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return m.modExp(d, n).toUint8Array('be', n.byteLength()); -} - -async function webSign(hashName, data, n, e, d, p, q, u) { - /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJWK, so it usually works out, but nevertheless, - * not all OpenPGP keys are compatible with this requirement. - * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still - * does if the underlying Web Crypto does so (though the tested implementations - * don't do so). - */ - const jwk = await privateToJWK(n, e, d, p, q, u); - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }; - const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); - return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); -} - -async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { - const { default: BN } = await import('./bn.mjs'); - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(data); - sign.end(); - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPrivateKey.encode(keyObject, 'der'); - return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' })); - } - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - return new Uint8Array(sign.sign(pem)); -} - -async function bnVerify(hashAlgo, s, n, e, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - s = new BigInteger(s); - e = new BigInteger(e); - if (s.gte(n)) { - throw new Error('Signature size cannot exceed modulus size'); - } - const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); - return util.equalsUint8Array(EM1, EM2); -} - -async function webVerify(hashName, data, s, n, e) { - const jwk = publicToJWK(n, e); - const key = await webCrypto$5.importKey('jwk', jwk, { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }, false, ['verify']); - return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); -} - -async function nodeVerify(hashAlgo, data, s, n, e) { - const { default: BN } = await import('./bn.mjs'); - - const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(data); - verify.end(); - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1' }; - } else { - key = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - } - try { - return await verify.verify(key, s); - } catch (err) { - return false; - } -} - -async function nodeEncrypt$1(data, n, e) { - const { default: BN } = await import('./bn.mjs'); - - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data)); -} - -async function bnEncrypt(data, n, e) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - data = new BigInteger(emeEncode(data, n.byteLength())); - e = new BigInteger(e); - if (data.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return data.modExp(e, n).toUint8Array('be', n.byteLength()); -} - -async function nodeDecrypt$1(data, n, e, d, p, q, u) { - const { default: BN } = await import('./bn.mjs'); - - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPrivateKey.encode(keyObject, 'der'); - key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - try { - return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data)); - } catch (err) { - throw new Error('Decryption error'); - } -} - -async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { - const BigInteger = await util.getBigInteger(); - data = new BigInteger(data); - n = new BigInteger(n); - e = new BigInteger(e); - d = new BigInteger(d); - p = new BigInteger(p); - q = new BigInteger(q); - u = new BigInteger(u); - if (data.gte(n)) { - throw new Error('Data too large.'); - } - const dq = d.mod(q.dec()); // d mod (q-1) - const dp = d.mod(p.dec()); // d mod (p-1) - - const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n); - const blinder = unblinder.modInv(n).modExp(e, n); - data = data.mul(blinder).mod(n); - - - const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p - const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q - const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q) - - let result = h.mul(p).add(mp); // result < n due to relations above - - result = result.mul(unblinder).mod(n); - - - return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload); -} - -/** Convert Openpgp private key params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - * @param {Uint8Array} d - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} u - */ -async function privateToJWK(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - const pNum = new BigInteger(p); - const qNum = new BigInteger(q); - const dNum = new BigInteger(d); - - let dq = dNum.mod(qNum.dec()); // d mod (q-1) - let dp = dNum.mod(pNum.dec()); // d mod (p-1) - dp = dp.toUint8Array(); - dq = dq.toUint8Array(); - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - d: uint8ArrayToB64(d, true), - // switch p and q - p: uint8ArrayToB64(q, true), - q: uint8ArrayToB64(p, true), - // switch dp and dq - dp: uint8ArrayToB64(dq, true), - dq: uint8ArrayToB64(dp, true), - qi: uint8ArrayToB64(u, true), - ext: true - }; -} - -/** Convert Openpgp key public params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - */ -function publicToJWK(n, e) { - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - ext: true - }; -} - -var rsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign, - verify: verify, - encrypt: encrypt$1, - decrypt: decrypt$1, - generate: generate, - validateParams: validateParams -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ElGamal Encryption function - * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) - * @param {Uint8Array} data - To be padded and encrypted - * @param {Uint8Array} p - * @param {Uint8Array} g - * @param {Uint8Array} y - * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} - * @async - */ -async function encrypt$2(data, p, g, y) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const padded = emeEncode(data, p.byteLength()); - const m = new BigInteger(padded); - - // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* - // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] - const k = await getRandomBigInteger(new BigInteger(1), p.dec()); - return { - c1: g.modExp(k, p).toUint8Array(), - c2: y.modExp(k, p).imul(m).imod(p).toUint8Array() - }; -} - -/** - * ElGamal Encryption function - * @param {Uint8Array} c1 - * @param {Uint8Array} c2 - * @param {Uint8Array} p - * @param {Uint8Array} x - * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} Unpadded message. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$2(c1, c2, p, x, randomPayload) { - const BigInteger = await util.getBigInteger(); - c1 = new BigInteger(c1); - c2 = new BigInteger(c2); - p = new BigInteger(p); - x = new BigInteger(x); - - const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p); - return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload); -} - -/** - * Validate ElGamal parameters - * @param {Uint8Array} p - ElGamal prime - * @param {Uint8Array} g - ElGamal group generator - * @param {Uint8Array} y - ElGamal public key - * @param {Uint8Array} x - ElGamal private exponent - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$1(p, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - // Expect p-1 to be large - const pSize = new BigInteger(p.bitLength()); - const n1023 = new BigInteger(1023); - if (pSize.lt(n1023)) { - return false; - } - - /** - * g should have order p-1 - * Check that g ** (p-1) = 1 mod p - */ - if (!g.modExp(p.dec(), p).isOne()) { - return false; - } - - /** - * Since p-1 is not prime, g might have a smaller order that divides p-1 - * We want to make sure that the order is large enough to hinder a small subgroup attack - * - * We just check g**i != 1 for all i up to a threshold - */ - let res = g; - const i = new BigInteger(1); - const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold - while (i.lt(threshold)) { - res = res.mul(g).imod(p); - if (res.isOne()) { - return false; - } - i.iinc(); - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{r(p-1) + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1 - const rqx = p.dec().imul(r).iadd(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var elgamal = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt$2, - decrypt: decrypt$2, - validateParams: validateParams$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class OID { - constructor(oid) { - if (oid instanceof OID) { - this.oid = oid.oid; - } else if (util.isArray(oid) || - util.isUint8Array(oid)) { - oid = new Uint8Array(oid); - if (oid[0] === 0x06) { // DER encoded oid byte array - if (oid[1] !== oid.length - 2) { - throw new Error('Length mismatch in DER encoded oid'); - } - oid = oid.subarray(2); - } - this.oid = oid; - } else { - this.oid = ''; - } - } - - /** - * Method to read an OID object - * @param {Uint8Array} input - Where to read the OID from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length >= 1) { - const length = input[0]; - if (input.length >= 1 + length) { - this.oid = input.subarray(1, 1 + length); - return 1 + this.oid.length; - } - } - throw new Error('Invalid oid'); - } - - /** - * Serialize an OID object - * @returns {Uint8Array} Array with the serialized value the OID. - */ - write() { - return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); - } - - /** - * Serialize an OID object as a hex string - * @returns {string} String with the hex value of the OID. - */ - toHex() { - return util.uint8ArrayToHex(this.oid); - } - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns {string} String with the canonical name of the curve. - */ - getName() { - const hex = this.toHex(); - if (enums.curve[hex]) { - return enums.write(enums.curve, hex); - } else { - throw new Error('Unknown curve object identifier.'); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -function keyFromPrivate(indutnyCurve, priv) { - const keyPair = indutnyCurve.keyPair({ priv: priv }); - return keyPair; -} - -function keyFromPublic(indutnyCurve, pub) { - const keyPair = indutnyCurve.keyPair({ pub: pub }); - if (keyPair.validate().result !== true) { - throw new Error('Invalid elliptic public key'); - } - return keyPair; -} - -async function getIndutnyCurve(name) { - if (!config.useIndutnyElliptic) { - throw new Error('This curve is only supported in the full build of OpenPGP.js'); - } - const { default: elliptic } = await import('./elliptic.mjs'); - return new elliptic.ec(name); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -function readSimpleLength(bytes) { - let len = 0; - let offset; - const type = bytes[0]; - - - if (type < 192) { - [len] = bytes; - offset = 1; - } else if (type < 255) { - len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; - offset = 2; - } else if (type === 255) { - len = util.readNumber(bytes.subarray(1, 1 + 4)); - offset = 5; - } - - return { - len: len, - offset: offset - }; -} - -/** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * - * @param {Integer} length - The length to encode - * @returns {Uint8Array} String with openpgp length representation. - */ -function writeSimpleLength(length) { - if (length < 192) { - return new Uint8Array([length]); - } else if (length > 191 && length < 8384) { - /* - * let a = (total data packet length) - 192 let bc = two octet - * representation of a let d = b + 192 - */ - return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); -} - -function writePartialLength(power) { - if (power < 0 || power > 30) { - throw new Error('Partial Length power must be between 1 and 30'); - } - return new Uint8Array([224 + power]); -} - -function writeTag(tag_type) { - /* we're only generating v4 packet headers here */ - return new Uint8Array([0xC0 | tag_type]); -} - -/** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * - * @param {Integer} tag_type - Tag type - * @param {Integer} length - Length of the payload - * @returns {String} String of the header. - */ -function writeHeader(tag_type, length) { - /* we're only generating v4 packet headers here */ - return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); -} - -/** - * Whether the packet type supports partial lengths per RFC4880 - * @param {Integer} tag - Tag type - * @returns {Boolean} String of the header. - */ -function supportsStreaming(tag) { - return [ - enums.packet.literalData, - enums.packet.compressedData, - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ].includes(tag); -} - -/** - * Generic static Packet Parser function - * - * @param {Uint8Array | ReadableStream} input - Input stream as string - * @param {Function} callback - Function to call with the parsed packet - * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. - */ -async function readPackets(input, callback) { - const reader = getReader(input); - let writer; - let callbackReturned; - try { - const peekedBytes = await reader.peekBytes(2); - // some sanity checks - if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { - throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); - } - const headerByte = await reader.readByte(); - let tag = -1; - let format = -1; - let packetLength; - - format = 0; // 0 = old format; 1 = new format - if ((headerByte & 0x40) !== 0) { - format = 1; - } - - let packetLengthType; - if (format) { - // new format header - tag = headerByte & 0x3F; // bit 5-0 - } else { - // old format header - tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packetLengthType = headerByte & 0x03; // bit 1-0 - } - - const packetSupportsStreaming = supportsStreaming(tag); - let packet = null; - if (packetSupportsStreaming) { - if (util.isStream(input) === 'array') { - const arrayStream = new ArrayStream(); - writer = getWriter(arrayStream); - packet = arrayStream; - } else { - const transform = new TransformStream(); - writer = getWriter(transform.writable); - packet = transform.readable; - } - // eslint-disable-next-line callback-return - callbackReturned = callback({ tag, packet }); - } else { - packet = []; - } - - let wasPartialLength; - do { - if (!format) { - // 4.2.1. Old Format Packet Lengths - switch (packetLengthType) { - case 0: - // The packet has a one-octet length. The header is 2 octets - // long. - packetLength = await reader.readByte(); - break; - case 1: - // The packet has a two-octet length. The header is 3 octets - // long. - packetLength = (await reader.readByte() << 8) | await reader.readByte(); - break; - case 2: - // The packet has a four-octet length. The header is 5 - // octets long. - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - break; - default: - // 3 - The packet is of indeterminate length. The header is 1 - // octet long, and the implementation must determine how long - // the packet is. If the packet is in a file, this means that - // the packet extends until the end of the file. In general, - // an implementation SHOULD NOT use indeterminate-length - // packets except where the end of the data will be clear - // from the context, and even then it is better to use a - // definite length, or a new format header. The new format - // headers described below have a mechanism for precisely - // encoding data of indeterminate length. - packetLength = Infinity; - break; - } - } else { // 4.2.2. New Format Packet Lengths - // 4.2.2.1. One-Octet Lengths - const lengthByte = await reader.readByte(); - wasPartialLength = false; - if (lengthByte < 192) { - packetLength = lengthByte; - // 4.2.2.2. Two-Octet Lengths - } else if (lengthByte >= 192 && lengthByte < 224) { - packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; - // 4.2.2.4. Partial Body Lengths - } else if (lengthByte > 223 && lengthByte < 255) { - packetLength = 1 << (lengthByte & 0x1F); - wasPartialLength = true; - if (!packetSupportsStreaming) { - throw new TypeError('This packet type does not support partial lengths.'); - } - // 4.2.2.3. Five-Octet Lengths - } else { - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - } - } - if (packetLength > 0) { - let bytesRead = 0; - while (true) { - if (writer) await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (packetLength === Infinity) break; - throw new Error('Unexpected end of packet'); - } - const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); - if (writer) await writer.write(chunk); - else packet.push(chunk); - bytesRead += value.length; - if (bytesRead >= packetLength) { - reader.unshift(value.subarray(packetLength - bytesRead + value.length)); - break; - } - } - } - } while (wasPartialLength); - - // If this was not a packet that "supports streaming", we peek to check - // whether it is the last packet in the message. We peek 2 bytes instead - // of 1 because the beginning of this function also peeks 2 bytes, and we - // want to cut a `subarray` of the correct length into `web-stream-tools`' - // `externalBuffer` as a tiny optimization here. - // - // If it *was* a streaming packet (i.e. the data packets), we peek at the - // entire remainder of the stream, in order to forward errors in the - // remainder of the stream to the packet data. (Note that this means we - // read/peek at all signature packets before closing the literal data - // packet, for example.) This forwards MDC errors to the literal data - // stream, for example, so that they don't get lost / forgotten on - // decryptedMessage.packets.stream, which we never look at. - // - // An example of what we do when stream-parsing a message containing - // [ one-pass signature packet, literal data packet, signature packet ]: - // 1. Read the one-pass signature packet - // 2. Peek 2 bytes of the literal data packet - // 3. Parse the one-pass signature packet - // - // 4. Read the literal data packet, simultaneously stream-parsing it - // 5. Peek until the end of the message - // 6. Finish parsing the literal data packet - // - // 7. Read the signature packet again (we already peeked at it in step 5) - // 8. Peek at the end of the stream again (`peekBytes` returns undefined) - // 9. Parse the signature packet - // - // Note that this means that if there's an error in the very end of the - // stream, such as an MDC error, we throw in step 5 instead of in step 8 - // (or never), which is the point of this exercise. - const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); - if (writer) { - await writer.ready; - await writer.close(); - } else { - packet = util.concatUint8Array(packet); - // eslint-disable-next-line callback-return - await callback({ tag, packet }); - } - return !nextPacket || !nextPacket.length; - } catch (e) { - if (writer) { - await writer.abort(e); - return true; - } else { - throw e; - } - } finally { - if (writer) { - await callbackReturned; - } - reader.releaseLock(); - } -} - -class UnsupportedError extends Error { - constructor(...params) { - super(...params); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, UnsupportedError); - } - - this.name = 'UnsupportedError'; - } -} - -class UnparseablePacket { - constructor(tag, rawContent) { - this.tag = tag; - this.rawContent = rawContent; - } - - write() { - return this.rawContent; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$6 = util.getWebCrypto(); -const nodeCrypto$7 = util.getNodeCrypto(); - -const webCurves = { - 'p256': 'P-256', - 'p384': 'P-384', - 'p521': 'P-521' -}; -const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : []; -const nodeCurves = nodeCrypto$7 ? { - secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, - p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, - p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, - p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, - ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined, - curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined, - brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, - brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, - brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined -} : {}; - -const curves = { - p256: { - oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.p256, - web: webCurves.p256, - payloadSize: 32, - sharedSize: 256 - }, - p384: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.p384, - web: webCurves.p384, - payloadSize: 48, - sharedSize: 384 - }, - p521: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.p521, - web: webCurves.p521, - payloadSize: 66, - sharedSize: 528 - }, - secp256k1: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1, - payloadSize: 32 - }, - ed25519: { - oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], - keyType: enums.publicKey.eddsaLegacy, - hash: enums.hash.sha512, - node: false, // nodeCurves.ed25519 TODO - payloadSize: 32 - }, - curve25519: { - oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], - keyType: enums.publicKey.ecdh, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: false, // nodeCurves.curve25519 TODO - payloadSize: 32 - }, - brainpoolP256r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1, - payloadSize: 32 - }, - brainpoolP384r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1, - payloadSize: 48 - }, - brainpoolP512r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1, - payloadSize: 64 - } -}; - -class CurveWithOID { - constructor(oidOrName, params) { - try { - if (util.isArray(oidOrName) || - util.isUint8Array(oidOrName)) { - // by oid byte array - oidOrName = new OID(oidOrName); - } - if (oidOrName instanceof OID) { - // by curve OID - oidOrName = oidOrName.getName(); - } - // by curve name or oid string - this.name = enums.write(enums.curve, oidOrName); - } catch (err) { - throw new UnsupportedError('Unknown curve'); - } - params = params || curves[this.name]; - - this.keyType = params.keyType; - - this.oid = params.oid; - this.hash = params.hash; - this.cipher = params.cipher; - this.node = params.node && curves[this.name]; - this.web = params.web && curves[this.name]; - this.payloadSize = params.payloadSize; - if (this.web && util.getWebCrypto()) { - this.type = 'web'; - } else if (this.node && util.getNodeCrypto()) { - this.type = 'node'; - } else if (this.name === 'curve25519') { - this.type = 'curve25519'; - } else if (this.name === 'ed25519') { - this.type = 'ed25519'; - } - } - - async genKeyPair() { - let keyPair; - switch (this.type) { - case 'web': - try { - return await webGenKeyPair(this.name); - } catch (err) { - util.printDebugError('Browser did not support generating ec key ' + err.message); - break; - } - case 'node': - return nodeGenKeyPair(this.name); - case 'curve25519': { - const privateKey = getRandomBytes(32); - privateKey[0] = (privateKey[0] & 127) | 64; - privateKey[31] &= 248; - const secretKey = privateKey.slice().reverse(); - keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - case 'ed25519': { - const privateKey = getRandomBytes(32); - const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - } - const indutnyCurve = await getIndutnyCurve(this.name); - keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToString(getRandomBytes(32)) - }); - return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; - } -} - -async function generate$1(curve) { - const BigInteger = await util.getBigInteger(); - - curve = new CurveWithOID(curve); - const keyPair = await curve.genKeyPair(); - const Q = new BigInteger(keyPair.publicKey).toUint8Array(); - const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize); - return { - oid: curve.oid, - Q, - secret, - hash: curve.hash, - cipher: curve.cipher - }; -} - -/** - * Get preferred hash algo to use with the given curve - * @param {module:type/oid} oid - curve oid - * @returns {enums.hash} hash algorithm - */ -function getPreferredHashAlgo(oid) { - return curves[enums.write(enums.curve, oid.toHex())].hash; -} - -/** - * Validate ECDH and ECDSA parameters - * Not suitable for EdDSA (different secret key format) - * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves - * @param {module:type/oid} oid - EC object identifier - * @param {Uint8Array} Q - EC public point - * @param {Uint8Array} d - EC secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateStandardParams(algo, oid, Q, d) { - const supportedCurves = { - p256: true, - p384: true, - p521: true, - secp256k1: true, - curve25519: algo === enums.publicKey.ecdh, - brainpoolP256r1: true, - brainpoolP384r1: true, - brainpoolP512r1: true - }; - - // Check whether the given curve is supported - const curveName = oid.getName(); - if (!supportedCurves[curveName]) { - return false; - } - - if (curveName === 'curve25519') { - d = d.slice().reverse(); - // Re-derive public point Q' - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d); - - Q = new Uint8Array(Q); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - if (!util.equalsUint8Array(dG, Q)) { - return false; - } - - return true; - } - - const curve = await getIndutnyCurve(curveName); - try { - // Parse Q and check that it is on the curve but not at infinity - Q = keyFromPublic(curve, Q).getPublic(); - } catch (validationErrors) { - return false; - } - - /** - * Re-derive public point Q' = dG from private key - * Expect Q == Q' - */ - const dG = keyFromPrivate(curve, d).getPublic(); - if (!dG.eq(Q)) { - return false; - } - - return true; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -async function webGenKeyPair(name) { - // Note: keys generated with ECDSA and ECDH are structurally equivalent - const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - - const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey); - const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey); - - return { - publicKey: jwkToRawPublic(publicKey), - privateKey: b64ToUint8Array(privateKey.d) - }; -} - -async function nodeGenKeyPair(name) { - // Note: ECDSA and ECDH key generation is structurally equivalent - const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]); - await ecdh.generateKeys(); - return { - publicKey: new Uint8Array(ecdh.getPublicKey()), - privateKey: new Uint8Array(ecdh.getPrivateKey()) - }; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -/** - * @param {JsonWebKey} jwk - key for conversion - * - * @returns {Uint8Array} Raw public key. - */ -function jwkToRawPublic(jwk) { - const bufX = b64ToUint8Array(jwk.x); - const bufY = b64ToUint8Array(jwk.y); - const publicKey = new Uint8Array(bufX.length + bufY.length + 1); - publicKey[0] = 0x04; - publicKey.set(bufX, 1); - publicKey.set(bufY, bufX.length + 1); - return publicKey; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * - * @returns {JsonWebKey} Public key in jwk format. - */ -function rawPublicToJWK(payloadSize, name, publicKey) { - const len = payloadSize; - const bufX = publicKey.slice(1, len + 1); - const bufY = publicKey.slice(len + 1, len * 2 + 1); - // https://www.rfc-editor.org/rfc/rfc7518.txt - const jwk = { - kty: 'EC', - crv: name, - x: uint8ArrayToB64(bufX, true), - y: uint8ArrayToB64(bufY, true), - ext: true - }; - return jwk; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * @param {Uint8Array} privateKey - private key - * - * @returns {JsonWebKey} Private key in jwk format. - */ -function privateToJWK$1(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJWK(payloadSize, name, publicKey); - jwk.d = uint8ArrayToB64(privateKey, true); - return jwk; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$7 = util.getWebCrypto(); -const nodeCrypto$8 = util.getNodeCrypto(); - -/** - * Sign a message using the provided key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - const keyPair = { publicKey, privateKey }; - switch (curve.type) { - case 'web': { - // If browser doesn't support a curve, we'll catch it - try { - // Need to await to make sure browser succeeds - return await webSign$1(curve, hashAlgo, message, keyPair); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunaley Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support signing: ' + err.message); - } - break; - } - case 'node': { - const signature = await nodeSign$1(curve, hashAlgo, message, keyPair); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - } - } - return ellipticSign(curve, hashed, privateKey); -} - -/** - * Verifies if a signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify - * @param {Uint8Array} message - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - switch (curve.type) { - case 'web': - try { - // Need to await to make sure browser succeeds - return await webVerify$1(curve, hashAlgo, signature, message, publicKey); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunately Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support verifying: ' + err.message); - } - break; - case 'node': - return nodeVerify$1(curve, hashAlgo, signature, message, publicKey); - } - } - const digest = (typeof hashAlgo === 'undefined') ? message : hashed; - return ellipticVerify(curve, signature, digest, publicKey); -} - -/** - * Validate ECDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDSA public point - * @param {Uint8Array} d - ECDSA secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$2(oid, Q, d) { - const curve = new CurveWithOID(oid); - // Reject curves x25519 and ed25519 - if (curve.keyType !== enums.publicKey.ecdsa) { - return false; - } - - // To speed up the validation, we try to use node- or webcrypto when available - // and sign + verify a random message - switch (curve.type) { - case 'web': - case 'node': { - const message = getRandomBytes(8); - const hashAlgo = enums.hash.sha256; - const hashed = await hash.digest(hashAlgo, message); - try { - const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed); - return await verify$1(oid, hashAlgo, signature, message, Q, hashed); - } catch (err) { - return false; - } - } - default: - return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); - } -} - - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -async function ellipticSign(curve, hashed, privateKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPrivate(indutnyCurve, privateKey); - const signature = key.sign(hashed); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; -} - -async function ellipticVerify(curve, signature, digest, publicKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPublic(indutnyCurve, publicKey); - return key.verify(digest, signature); -} - -async function webSign$1(curve, hashAlgo, message, keyPair) { - const len = curve.payloadSize; - const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['sign'] - ); - - const signature = new Uint8Array(await webCrypto$7.sign( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - message - )); - - return { - r: signature.slice(0, len), - s: signature.slice(len, len << 1) - }; -} - -async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['verify'] - ); - - const signature = util.concatUint8Array([r, s]).buffer; - - return webCrypto$7.verify( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - signature, - message - ); -} - -async function nodeSign$1(curve, hashAlgo, message, keyPair) { - const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(message); - sign.end(); - const key = ECPrivateKey.encode({ - version: 1, - parameters: curve.oid, - privateKey: Array.from(keyPair.privateKey), - publicKey: { unused: 0, data: Array.from(keyPair.publicKey) } - }, 'pem', { - label: 'EC PRIVATE KEY' - }); - - return ECDSASignature.decode(sign.sign(key), 'der'); -} - -async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const { default: BN } = await import('./bn.mjs'); - - const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(message); - verify.end(); - const key = SubjectPublicKeyInfo.encode({ - algorithm: { - algorithm: [1, 2, 840, 10045, 2, 1], - parameters: curve.oid - }, - subjectPublicKey: { unused: 0, data: Array.from(publicKey) } - }, 'pem', { - label: 'PUBLIC KEY' - }); - const signature = ECDSASignature.encode({ - r: new BN(r), s: new BN(s) - }, 'der'); - - try { - return verify.verify(key, signature); - } catch (err) { - return false; - } -} - -// Originally written by Owen Smith https://github.com/omsmith -// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ - -/* eslint-disable no-invalid-this */ - -const asn1$1 = nodeCrypto$8 ? void('asn1.js') : undefined; - -const ECDSASignature = nodeCrypto$8 ? - asn1$1.define('ECDSASignature', function() { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ); - }) : undefined; - -const ECPrivateKey = nodeCrypto$8 ? - asn1$1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().any(), - this.key('publicKey').explicit(1).optional().bitstr() - ); - }) : undefined; - -const AlgorithmIdentifier = nodeCrypto$8 ? - asn1$1.define('AlgorithmIdentifier', function() { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional().any() - ); - }) : undefined; - -const SubjectPublicKeyInfo = nodeCrypto$8 ? - asn1$1.define('SubjectPublicKeyInfo', function() { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ); - }) : undefined; - -var ecdsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$1, - verify: verify$1, - validateParams: validateParams$2 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Sign a message using the provided legacy EdDSA key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - // EdDSA signature params are returned in little-endian format - return { - r: signature.subarray(0, 32), - s: signature.subarray(32) - }; -} - -/** - * Verifies if a legacy EdDSA signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const signature = util.concatUint8Array([r, s]); - return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1)); -} -/** - * Validate legacy EdDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - EdDSA public point - * @param {Uint8Array} k - EdDSA secret seed - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$3(oid, Q, k) { - // Check whether the given curve is supported - if (oid.getName() !== 'ed25519') { - return false; - } - - /** - * Derive public point Q' = dG from private key - * and expect Q == Q' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - return util.equalsUint8Array(Q, dG); - -} - -var eddsa_legacy = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$2, - verify: verify$2, - validateParams: validateParams$3 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Generate (non-legacy) EdDSA key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} - */ -async function generate$2(algo) { - switch (algo) { - case enums.publicKey.ed25519: { - const seed = getRandomBytes(32); - const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed); - return { A, seed }; - } - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} - -/** - * Sign a message using the provided key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * RS: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - const secretKey = util.concatUint8Array([privateKey, publicKey]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - return { RS: signature }; - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - -} - -/** - * Verifies if a signature is valid for a message - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{ RS: Uint8Array }} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - return naclFastLight.sign.detached.verify(hashed, RS, publicKey); - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} -/** - * Validate (non-legacy) EdDSA parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - EdDSA public point - * @param {Uint8Array} seed - EdDSA secret seed - * @param {Uint8Array} oid - (legacy only) EdDSA OID - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$4(algo, A, seed) { - switch (algo) { - case enums.publicKey.ed25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed); - return util.equalsUint8Array(A, publicKey); - } - - case enums.publicKey.ed448: // unsupported - default: - return false; - } -} - -function getPreferredHashAlgo$1(algo) { - switch (algo) { - case enums.publicKey.ed25519: - return enums.hash.sha256; - default: - throw new Error('Unknown EdDSA algo'); - } -} - -var eddsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$2, - sign: sign$3, - verify: verify$3, - validateParams: validateParams$4, - getPreferredHashAlgo: getPreferredHashAlgo$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * AES key wrap - * @function - * @param {Uint8Array} key - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -function wrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const P = unpack(data); - let A = IV; - const R = P; - const n = P.length / 2; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 0; j <= 5; ++j) { - for (let i = 0; i < n; ++i) { - t[1] = n * j + (1 + i); - // B = A - B[0] = A[0]; - B[1] = A[1]; - // B = A || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES(K, B) - B = unpack(aes.encrypt(pack(B))); - // A = MSB(64, B) ^ t - A = B.subarray(0, 2); - A[0] ^= t[0]; - A[1] ^= t[1]; - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - return pack(A, R); -} - -/** - * AES key unwrap - * @function - * @param {String} key - * @param {String} data - * @returns {Uint8Array} - * @throws {Error} - */ -function unwrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const C = unpack(data); - let A = C.subarray(0, 2); - const R = C.subarray(2); - const n = C.length / 2 - 1; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 5; j >= 0; --j) { - for (let i = n - 1; i >= 0; --i) { - t[1] = n * j + (i + 1); - // B = A ^ t - B[0] = A[0] ^ t[0]; - B[1] = A[1] ^ t[1]; - // B = (A ^ t) || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES-1(B) - B = unpack(aes.decrypt(pack(B))); - // A = MSB(64, B) - A = B.subarray(0, 2); - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - if (A[0] === IV[0] && A[1] === IV[1]) { - return pack(R); - } - throw new Error('Key Data Integrity failed'); -} - -function createArrayBuffer(data) { - if (util.isString(data)) { - const { length } = data; - const buffer = new ArrayBuffer(length); - const view = new Uint8Array(buffer); - for (let j = 0; j < length; ++j) { - view[j] = data.charCodeAt(j); - } - return buffer; - } - return new Uint8Array(data).buffer; -} - -function unpack(data) { - const { length } = data; - const buffer = createArrayBuffer(data); - const view = new DataView(buffer); - const arr = new Uint32Array(length / 4); - for (let i = 0; i < length / 4; ++i) { - arr[i] = view.getUint32(4 * i); - } - return arr; -} - -function pack() { - let length = 0; - for (let k = 0; k < arguments.length; ++k) { - length += 4 * arguments[k].length; - } - const buffer = new ArrayBuffer(length); - const view = new DataView(buffer); - let offset = 0; - for (let i = 0; i < arguments.length; ++i) { - for (let j = 0; j < arguments[i].length; ++j) { - view.setUint32(offset + 4 * j, arguments[i][j]); - } - offset += 4 * arguments[i].length; - } - return new Uint8Array(buffer); -} - -var aesKW = /*#__PURE__*/Object.freeze({ - __proto__: null, - wrap: wrap, - unwrap: unwrap -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * @fileoverview Functions to add and remove PKCS5 padding - * @see PublicKeyEncryptedSessionKeyPacket - * @module crypto/pkcs5 - * @private - */ - -/** - * Add pkcs5 padding to a message - * @param {Uint8Array} message - message to pad - * @returns {Uint8Array} Padded message. - */ -function encode$1(message) { - const c = 8 - (message.length % 8); - const padded = new Uint8Array(message.length + c).fill(c); - padded.set(message); - return padded; -} - -/** - * Remove pkcs5 padding from a message - * @param {Uint8Array} message - message to remove padding from - * @returns {Uint8Array} Message without padding. - */ -function decode$1(message) { - const len = message.length; - if (len > 0) { - const c = message[len - 1]; - if (c >= 1) { - const provided = message.subarray(len - c); - const computed = new Uint8Array(c).fill(c); - if (util.equalsUint8Array(provided, computed)) { - return message.subarray(0, len - c); - } - } - } - throw new Error('Invalid padding'); -} - -var pkcs5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - encode: encode$1, - decode: decode$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$8 = util.getWebCrypto(); -const nodeCrypto$9 = util.getNodeCrypto(); - -/** - * Validate ECDH parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDH public point - * @param {Uint8Array} d - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$5(oid, Q, d) { - return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); -} - -// Build Param for ECDH algorithm (RFC 6637) -function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { - return util.concatUint8Array([ - oid.write(), - new Uint8Array([public_algo]), - kdfParams.write(), - util.stringToUint8Array('Anonymous Sender '), - fingerprint.subarray(0, 20) - ]); -} - -// Key Derivation Function (RFC 6637) -async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { - // Note: X is little endian for Curve25519, big-endian for all others. - // This is not ideal, but the RFC's are unclear - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - let i; - if (stripLeading) { - // Work around old go crypto bug - for (i = 0; i < X.length && X[i] === 0; i++); - X = X.subarray(i); - } - if (stripTrailing) { - // Work around old OpenPGP.js bug - for (i = X.length - 1; i >= 0 && X[i] === 0; i--); - X = X.subarray(0, i + 1); - } - const digest = await hash.digest(hashAlgo, util.concatUint8Array([ - new Uint8Array([0, 0, 0, 1]), - X, - param - ])); - return digest.subarray(0, length); -} - -/** - * Generate ECDHE ephemeral key and secret from public key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPublicEphemeralKey(curve, Q) { - switch (curve.type) { - case 'curve25519': { - const d = getRandomBytes(32); - const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d); - let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey); - publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); - return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPublicEphemeralKey(curve, Q); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePublicEphemeralKey(curve, Q); - } - return ellipticPublicEphemeralKey(curve, Q); -} - -/** - * Encrypt and wrap a session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} data - Unpadded session key data - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} - * @async - */ -async function encrypt$3(oid, kdfParams, data, Q, fingerprint) { - const m = encode$1(data); - - const curve = new CurveWithOID(oid); - const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); - const wrappedKey = wrap(Z, m); - return { publicKey, wrappedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPrivateEphemeralKey(curve, V, Q, d) { - if (d.length !== curve.payloadSize) { - const privateKey = new Uint8Array(curve.payloadSize); - privateKey.set(d, curve.payloadSize - d.length); - d = privateKey; - } - switch (curve.type) { - case 'curve25519': { - const secretKey = d.slice().reverse(); - const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1)); - return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPrivateEphemeralKey(curve, V, Q, d); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePrivateEphemeralKey(curve, V, d); - } - return ellipticPrivateEphemeralKey(curve, V, d); -} - -/** - * Decrypt and unwrap the value derived from session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} C - Encrypted and wrapped value derived from session key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Value derived from session key. - * @async - */ -async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) { - const curve = new CurveWithOID(oid); - const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - let err; - for (let i = 0; i < 3; i++) { - try { - // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); - return decode$1(unwrap(Z, C)); - } catch (e) { - err = e; - } - } - throw err; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d); - let privateKey = webCrypto$8.importKey( - 'jwk', - recipient, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); - let sender = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - [] - ); - [privateKey, sender] = await Promise.all([privateKey, sender]); - let S = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: sender - }, - privateKey, - curve.web.sharedSize - ); - let secret = webCrypto$8.exportKey( - 'jwk', - privateKey - ); - [S, secret] = await Promise.all([S, secret]); - const sharedKey = new Uint8Array(S); - const secretKey = b64ToUint8Array(secret.d); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); - let keyPair = webCrypto$8.generateKey( - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - let recipient = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - false, - [] - ); - [keyPair, recipient] = await Promise.all([keyPair, recipient]); - let s = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: recipient - }, - keyPair.privateKey, - curve.web.sharedSize - ); - let p = webCrypto$8.exportKey( - 'jwk', - keyPair.publicKey - ); - [s, p] = await Promise.all([s, p]); - const sharedKey = new Uint8Array(s); - const publicKey = new Uint8Array(jwkToRawPublic(p)); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPrivateEphemeralKey(curve, V, d) { - const indutnyCurve = await getIndutnyCurve(curve.name); - V = keyFromPublic(indutnyCurve, V); - d = keyFromPrivate(indutnyCurve, d); - const secretKey = new Uint8Array(d.getPrivate()); - const S = d.derive(V.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPublicEphemeralKey(curve, Q) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const v = await curve.genKeyPair(); - Q = keyFromPublic(indutnyCurve, Q); - const V = keyFromPrivate(indutnyCurve, v.privateKey); - const publicKey = v.publicKey; - const S = V.derive(Q.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePrivateEphemeralKey(curve, V, d) { - const recipient = nodeCrypto$9.createECDH(curve.node.node); - recipient.setPrivateKey(d); - const sharedKey = new Uint8Array(recipient.computeSecret(V)); - const secretKey = new Uint8Array(recipient.getPrivateKey()); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePublicEphemeralKey(curve, Q) { - const sender = nodeCrypto$9.createECDH(curve.node.node); - sender.generateKeys(); - const sharedKey = new Uint8Array(sender.computeSecret(Q)); - const publicKey = new Uint8Array(sender.getPublicKey()); - return { publicKey, sharedKey }; -} - -var ecdh = /*#__PURE__*/Object.freeze({ - __proto__: null, - validateParams: validateParams$5, - encrypt: encrypt$3, - decrypt: decrypt$3 -}); - -/** - * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. - * @module crypto/hkdf - * @private - */ - -const webCrypto$9 = util.getWebCrypto(); -const nodeCrypto$a = util.getNodeCrypto(); -const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle; - -async function HKDF(hashAlgo, inputKey, salt, info, outLen) { - const hash = enums.read(enums.webHash, hashAlgo); - if (!hash) throw new Error('Hash algo not supported with HKDF'); - - if (webCrypto$9 || nodeSubtleCrypto) { - const crypto = webCrypto$9 || nodeSubtleCrypto; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); - return new Uint8Array(bits); - } - - if (nodeCrypto$a) { - const hashAlgoName = enums.read(enums.hash, hashAlgo); - // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869 - - const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest(); - // Step 1: Extract - // PRK = HMAC-Hash(salt, IKM) - const pseudoRandomKey = computeHMAC(salt, inputKey); - - const hashLen = pseudoRandomKey.length; - - // Step 2: Expand - // HKDF-Expand(PRK, info, L) -> OKM - const n = Math.ceil(outLen / hashLen); - const outputKeyingMaterial = new Uint8Array(n * hashLen); - - // HMAC input buffer updated at each iteration - const roundInput = new Uint8Array(hashLen + info.length + 1); - // T_i and last byte are updated at each iteration, but `info` remains constant - roundInput.set(info, hashLen); - - for (let i = 0; i < n; i++) { - // T(0) = empty string (zero length) - // T(i) = HMAC-Hash(PRK, T(i-1) | info | i) - roundInput[roundInput.length - 1] = i + 1; - // t = T(i+1) - const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen)); - roundInput.set(t, 0); - - outputKeyingMaterial.set(t, i * hashLen); - } - - return outputKeyingMaterial.subarray(0, outLen); - } - - throw new Error('No HKDF implementation available'); -} - -/** - * @fileoverview Key encryption and decryption for RFC 6637 ECDH - * @module crypto/public_key/elliptic/ecdh - * @private - */ - -const HKDF_INFO = { - x25519: util.encodeUTF8('OpenPGP X25519') -}; - -/** - * Generate ECDH key for Montgomery curves - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} - */ -async function generate$3(algo) { - switch (algo) { - case enums.publicKey.x25519: { - // k stays in little-endian, unlike legacy ECDH over curve25519 - const k = getRandomBytes(32); - const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k); - return { A, k }; - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** -* Validate ECDH parameters -* @param {module:enums.publicKey} algo - Algorithm identifier -* @param {Uint8Array} A - ECDH public point -* @param {Uint8Array} k - ECDH secret scalar -* @returns {Promise} Whether params are valid. -* @async -*/ -async function validateParams$6(algo, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k); - return util.equalsUint8Array(A, publicKey); - } - - default: - return false; - } -} - -/** - * Wrap and encrypt a session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} data - session key data to be encrypted - * @param {Uint8Array} recipientA - Recipient public key (K_B) - * @returns {Promise<{ - * ephemeralPublicKey: Uint8Array, - * wrappedKey: Uint8Array - * }>} ephemeral public key (K_A) and encrypted key - * @async - */ -async function encrypt$4(algo, data, recipientA) { - switch (algo) { - case enums.publicKey.x25519: { - const ephemeralSecretKey = getRandomBytes(32); - const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA); - const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - recipientA, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - const wrappedKey = wrap(encryptionKey, data); - return { ephemeralPublicKey, wrappedKey }; - } - - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** - * Decrypt and unwrap the session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} ephemeralPublicKey - (K_A) - * @param {Uint8Array} wrappedKey, - * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF - * @param {Uint8Array} k - Recipient secret key (b) - * @returns {Promise} decrypted session key data - * @async - */ -async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - A, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - return unwrap(encryptionKey, wrappedKey); - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -var ecdh_x = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$3, - validateParams: validateParams$6, - encrypt: encrypt$4, - decrypt: decrypt$4 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -var elliptic = /*#__PURE__*/Object.freeze({ - __proto__: null, - CurveWithOID: CurveWithOID, - ecdh: ecdh, - ecdhX: ecdh_x, - ecdsa: ecdsa, - eddsaLegacy: eddsa_legacy, - eddsa: eddsa, - generate: generate$1, - getPreferredHashAlgo: getPreferredHashAlgo -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/* - TODO regarding the hash function, read: - https://tools.ietf.org/html/rfc4880#section-13.6 - https://tools.ietf.org/html/rfc4880#section-14 -*/ - -/** - * DSA Sign function - * @param {Integer} hashAlgo - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} x - * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} - * @async - */ -async function sign$4(hashAlgo, hashed, g, p, q, x) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - x = new BigInteger(x); - - let k; - let r; - let s; - let t; - g = g.mod(p); - x = x.mod(q); - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - while (true) { - // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - k = await getRandomBigInteger(one, q); // returns in [1, q-1] - r = g.modExp(k, p).imod(q); // (g**k mod p) mod q - if (r.isZero()) { - continue; - } - const xr = x.mul(r).imod(q); - t = h.add(xr).imod(q); // H(m) + x*r mod q - s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q - if (s.isZero()) { - continue; - } - break; - } - return { - r: r.toUint8Array('be', q.byteLength()), - s: s.toUint8Array('be', q.byteLength()) - }; -} - -/** - * DSA Verify function - * @param {Integer} hashAlgo - * @param {Uint8Array} r - * @param {Uint8Array} s - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} y - * @returns {boolean} - * @async - */ -async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) { - const BigInteger = await util.getBigInteger(); - const zero = new BigInteger(0); - r = new BigInteger(r); - s = new BigInteger(s); - - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - - if (r.lte(zero) || r.gte(q) || - s.lte(zero) || s.gte(q)) { - util.printDebug('invalid DSA Signature'); - return false; - } - const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q); - const w = s.modInv(q); // s**-1 mod q - if (w.isZero()) { - util.printDebug('invalid DSA Signature'); - return false; - } - - g = g.mod(p); - y = y.mod(p); - const u1 = h.mul(w).imod(q); // H(m) * w mod q - const u2 = r.mul(w).imod(q); // r * w mod q - const t1 = g.modExp(u1, p); // g**u1 mod p - const t2 = y.modExp(u2, p); // y**u2 mod p - const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q - return v.equal(r); -} - -/** - * Validate DSA parameters - * @param {Uint8Array} p - DSA prime - * @param {Uint8Array} q - DSA group order - * @param {Uint8Array} g - DSA sub-group generator - * @param {Uint8Array} y - DSA public key - * @param {Uint8Array} x - DSA private key - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$7(p, q, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - /** - * Check that subgroup order q divides p-1 - */ - if (!p.dec().mod(q).isZero()) { - return false; - } - - /** - * g has order q - * Check that g ** q = 1 mod p - */ - if (!g.modExp(q, p).isOne()) { - return false; - } - - /** - * Check q is large and probably prime (we mainly want to avoid small factors) - */ - const qSize = new BigInteger(q.bitLength()); - const n150 = new BigInteger(150); - if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) { - return false; - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{rq + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q - const rqx = q.mul(r).add(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var dsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$4, - verify: verify$4, - validateParams: validateParams$7 -}); - -/** - * @fileoverview Asymmetric cryptography functions - * @module crypto/public_key - * @private - */ - -var publicKey = { - /** @see module:crypto/public_key/rsa */ - rsa: rsa, - /** @see module:crypto/public_key/elgamal */ - elgamal: elgamal, - /** @see module:crypto/public_key/elliptic */ - elliptic: elliptic, - /** @see module:crypto/public_key/dsa */ - dsa: dsa, - /** @see tweetnacl */ - nacl: naclFastLight -}; - -/** - * @fileoverview Provides functions for asymmetric signing and signature verification - * @module crypto/signature - * @private - */ - -/** - * Parse signature in binary form to get the parameters. - * The returned values are only padded for EdDSA, since in the other cases their expected length - * depends on the key params, hence we delegate the padding to the signature verification function. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Uint8Array} signature - Data for which the signature was created - * @returns {Promise} True if signature is valid. - * @async - */ -function parseSignatureParams(algo, signature) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA signatures: - // - MPI of RSA signature value m**d mod n. - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const s = util.readMPI(signature.subarray(read)); - // The signature needs to be the same length as the public key modulo n. - // We pad s on signature verification, where we have access to n. - return { s }; - } - // Algorithm-Specific Fields for DSA or ECDSA signatures: - // - MPI of DSA or ECDSA value r. - // - MPI of DSA or ECDSA value s. - case enums.publicKey.dsa: - case enums.publicKey.ecdsa: - { - const r = util.readMPI(signature.subarray(read)); read += r.length + 2; - const s = util.readMPI(signature.subarray(read)); - return { r, s }; - } - // Algorithm-Specific Fields for legacy EdDSA signatures: - // - MPI of an EC point r. - // - EdDSA value s, in MPI, in the little endian representation - case enums.publicKey.eddsaLegacy: { - // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values: - // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 - let r = util.readMPI(signature.subarray(read)); read += r.length + 2; - r = util.leftPad(r, 32); - let s = util.readMPI(signature.subarray(read)); - s = util.leftPad(s, 32); - return { r, s }; - } - // Algorithm-Specific Fields for Ed25519 signatures: - // - 64 octets of the native signature - case enums.publicKey.ed25519: { - const RS = signature.subarray(read, read + 64); read += RS.length; - return { RS }; - } - default: - throw new UnsupportedError('Unknown signature algorithm.'); - } -} - -/** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} signature - Named algorithm-specific signature parameters - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Data for which the signature was created - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} True if signature is valid. - * @async - */ -async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto - return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); - } - case enums.publicKey.dsa: { - const { g, p, q, y } = publicParams; - const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers - return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicParams; - const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; - // padding needed for webcrypto - const r = util.leftPad(signature.r, curveSize); - const s = util.leftPad(signature.s, curveSize); - return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicParams; - // signature already padded on parsing - return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -/** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters - * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters - * @param {Uint8Array} data - Data to be signed - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} Signature Object containing named signature parameters. - * @async - */ -async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { - if (!publicKeyParams || !privateKeyParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); - return { s }; - } - case enums.publicKey.dsa: { - const { g, p, q } = publicKeyParams; - const { x } = privateKeyParams; - return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); - } - case enums.publicKey.elgamal: { - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicKeyParams; - const { d } = privateKeyParams; - return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -var signature = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseSignatureParams: parseSignatureParams, - verify: verify$5, - sign: sign$5 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class ECDHSymmetricKey { - constructor(data) { - if (data) { - this.data = data; - } - } - - /** - * Read an ECDHSymmetricKey from an Uint8Array: - * - 1 octect for the length `l` - * - `l` octects of encoded session key data - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - if (bytes.length >= 1) { - const length = bytes[0]; - if (bytes.length >= 1 + length) { - this.data = bytes.subarray(1, 1 + length); - return 1 + this.data.length; - } - } - throw new Error('Invalid symmetric key'); - } - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Implementation of type KDF parameters - * - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - * @module type/kdf_params - * @private - */ - -class KDFParams { - /** - * @param {enums.hash} hash - Hash algorithm - * @param {enums.symmetric} cipher - Symmetric algorithm - */ - constructor(data) { - if (data) { - const { hash, cipher } = data; - this.hash = hash; - this.cipher = cipher; - } else { - this.hash = null; - this.cipher = null; - } - } - - /** - * Read KDFParams from an Uint8Array - * @param {Uint8Array} input - Where to read the KDFParams from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { - throw new UnsupportedError('Cannot read KDFParams'); - } - this.hash = input[2]; - this.cipher = input[3]; - return 4; - } +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - /** - * Write KDFParams to an Uint8Array - * @returns {Uint8Array} Array with the KDFParams value - */ - write() { - return new Uint8Array([3, 1, this.hash, this.cipher]); - } -} + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; -/** - * Encoded symmetric key for x25519 and x448 - * The payload format varies for v3 and v6 PKESK: - * the former includes an algorithm byte preceeding the encrypted session key. - * - * @module type/x25519x448_symkey - */ + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is -class ECDHXSymmetricKey { - static fromObject({ wrappedKey, algorithm }) { - const instance = new ECDHXSymmetricKey(); - instance.wrappedKey = wrappedKey; - instance.algorithm = algorithm; - return instance; - } + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - /** - * - 1 octect for the length `l` - * - `l` octects of encoded session key data (with optional leading algorithm byte) - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - let read = 0; - let followLength = bytes[read++]; - this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even - followLength -= followLength % 2; - this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength; - } + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - /** - * Write an MontgomerySymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([ - this.algorithm ? - new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : - new Uint8Array([this.wrappedKey.length]), - this.wrappedKey - ]); - } + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; } -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param {module:enums.publicKey} keyAlgo - Public key algorithm - * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Session key data to be encrypted - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Encrypted session key parameters. - * @async - */ -async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const { n, e } = publicParams; - const c = await publicKey.rsa.encrypt(data, n, e); - return { c }; - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - return publicKey.elgamal.encrypt(data, p, g, y); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicParams; - const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( - oid, kdfParams, data, Q, fingerprint); - return { V, C: new ECDHSymmetricKey(C) }; - } - case enums.publicKey.x25519: { - if (!util.isAES(symmetricAlgo)) { - // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 - throw new Error('X25519 keys can only encrypt AES session keys'); - } - const { A } = publicParams; - const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( - keyAlgo, data, A); - const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); - return { ephemeralPublicKey, C }; - } - default: - return []; - } +function S(o, a) { + M(o, a, a); } -/** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Object} publicKeyParams - Algorithm-specific public key parameters - * @param {Object} privateKeyParams - Algorithm-specific private key parameters - * @param {Object} sessionKeyParams - Encrypted session key parameters - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing - * (needed for constant-time processing in RSA and ElGamal) - * @returns {Promise} Decrypted data. - * @throws {Error} on sensitive decryption error, unless `randomPayload` is given - * @async - */ -async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: { - const { c } = sessionKeyParams; - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); - } - case enums.publicKey.elgamal: { - const { c1, c2 } = sessionKeyParams; - const p = publicKeyParams.p; - const x = privateKeyParams.x; - return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicKeyParams; - const { d } = privateKeyParams; - const { V, C } = sessionKeyParams; - return publicKey.elliptic.ecdh.decrypt( - oid, kdfParams, V, C.data, Q, d, fingerprint); - } - case enums.publicKey.x25519: { - const { A } = publicKeyParams; - const { k } = privateKeyParams; - const { ephemeralPublicKey, C } = sessionKeyParams; - if (!util.isAES(C.algorithm)) { - throw new Error('AES session key expected'); - } - return publicKey.elliptic.ecdhX.decrypt( - algo, ephemeralPublicKey, C.wrappedKey, A, k); - } - default: - throw new Error('Unknown public key encryption algorithm.'); +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; } -/** - * Parse public key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. - */ -function parsePublicKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; - const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; - return { read, publicParams: { n, e } }; - } - case enums.publicKey.dsa: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, q, g, y } }; - } - case enums.publicKey.elgamal: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, g, y } }; - } - case enums.publicKey.ecdsa: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.eddsaLegacy: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - Q = util.leftPad(Q, 33); - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.ecdh: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); - return { read: read, publicParams: { oid, Q, kdfParams } }; - } - case enums.publicKey.ed25519: - case enums.publicKey.x25519: { - const A = bytes.subarray(read, read + 32); read += A.length; - return { read, publicParams: { A } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; } -/** - * Parse private key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @param {Object} publicParams - (ECC only) public params, needed to format some private params - * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. - */ -function parsePrivateKeyParams(algo, bytes, publicParams) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; - return { read, privateParams: { d, p, q, u } }; - } - case enums.publicKey.dsa: - case enums.publicKey.elgamal: { - const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; - return { read, privateParams: { x } }; - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const curve = new CurveWithOID(publicParams.oid); - let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - d = util.leftPad(d, curve.payloadSize); - return { read, privateParams: { d } }; - } - case enums.publicKey.eddsaLegacy: { - const curve = new CurveWithOID(publicParams.oid); - let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; - seed = util.leftPad(seed, curve.payloadSize); - return { read, privateParams: { seed } }; - } - case enums.publicKey.ed25519: { - const seed = bytes.subarray(read, read + 32); read += seed.length; - return { read, privateParams: { seed } }; - } - case enums.publicKey.x25519: { - const k = bytes.subarray(read, read + 32); read += k.length; - return { read, privateParams: { k } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; } -/** Returns the types comprising the encrypted session key of an algorithm - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {Object} The session key parameters referenced by name. - */ -function parseEncSessionKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA encrypted session keys: - // - MPI of RSA encrypted value m**e mod n. - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const c = util.readMPI(bytes.subarray(read)); - return { c }; - } - - // Algorithm-Specific Fields for Elgamal encrypted session keys: - // - MPI of Elgamal value g**k mod p - // - MPI of Elgamal value m * y**k mod p - case enums.publicKey.elgamal: { - const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; - const c2 = util.readMPI(bytes.subarray(read)); - return { c1, c2 }; - } - // Algorithm-Specific Fields for ECDH encrypted session keys: - // - MPI containing the ephemeral key used to establish the shared secret - // - ECDH Symmetric Key - case enums.publicKey.ecdh: { - const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; - const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); - return { V, C }; - } - // Algorithm-Specific Fields for X25519 encrypted session keys: - // - 32 octets representing an ephemeral X25519 public key. - // - A one-octet size of the following fields. - // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). - // - The encrypted session key. - case enums.publicKey.x25519: { - const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length; - const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); - return { ephemeralPublicKey, C }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); } -/** - * Convert params to MPI and serializes them in the proper order - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} params - The key parameters indexed by name - * @returns {Uint8Array} The array containing the MPIs. - */ -function serializeParams(algo, params) { - // Some algorithms do not rely on MPIs to store the binary params - const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]); - const orderedParams = Object.keys(params).map(name => { - const param = params[name]; - if (!util.isUint8Array(param)) return param.write(); - return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); - }); - return util.concatUint8Array(orderedParams); +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); } -/** - * Generate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Integer} bits - Bit length for RSA keys - * @param {module:type/oid} oid - Object identifier for ECC keys - * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. - * @async - */ -function generateParams(algo, bits, oid) { - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ - privateParams: { d, p, q, u }, - publicParams: { n, e } - })); +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } - case enums.publicKey.ecdsa: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { d: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { seed: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.ecdh: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ - privateParams: { d: secret }, - publicParams: { - oid: new OID(oid), - Q, - kdfParams: new KDFParams({ hash, cipher }) + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); } - })); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ - privateParams: { seed }, - publicParams: { A } - })); - case enums.publicKey.x25519: - return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ - privateParams: { k }, - publicParams: { A } - })); - case enums.publicKey.dsa: - case enums.publicKey.elgamal: - throw new Error('Unsupported algorithm for key generation.'); - default: - throw new Error('Unknown public key algorithm.'); + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; } + + return n; } -/** - * Validate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Object} privateParams - Algorithm-specific private key parameters - * @returns {Promise} Whether the parameters are valid. - * @async - */ -async function validateParams$8(algo, publicParams, privateParams) { - if (!publicParams || !privateParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const { d, p, q, u } = privateParams; - return publicKey.rsa.validateParams(n, e, d, p, q, u); - } - case enums.publicKey.dsa: { - const { p, q, g, y } = publicParams; - const { x } = privateParams; - return publicKey.dsa.validateParams(p, q, g, y, x); - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - const { x } = privateParams; - return publicKey.elgamal.validateParams(p, g, y, x); - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; - const { oid, Q } = publicParams; - const { d } = privateParams; - return algoModule.validateParams(oid, Q, d); - } - case enums.publicKey.eddsaLegacy: { - const { Q, oid } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsa.validateParams(algo, A, seed); - } - case enums.publicKey.x25519: { - const { A } = publicParams; - const { k } = privateParams; - return publicKey.elliptic.ecdhX.validateParams(algo, A, k); - } - default: - throw new Error('Unknown public key algorithm.'); - } +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; } -/** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - * @async - */ -async function getPrefixRandom(algo) { - const { blockSize } = getCipher(algo); - const prefixrandom = await getRandomBytes(blockSize); - const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - return util.concat([prefixrandom, repeat]); +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); } -/** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Uint8Array} Random bytes as a string to be used as a key. - */ -function generateSessionKey(algo) { - const { keySize } = getCipher(algo); - return getRandomBytes(keySize); +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } } -/** - * Get implementation of the given AEAD mode - * @param {enums.aead} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getAEADMode(algo) { - const algoName = enums.read(enums.aead, algo); - return mode[algoName]; +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; } -/** - * Check whether the given curve OID is supported - * @param {module:type/oid} oid - EC object identifier - * @throws {UnsupportedError} if curve is not supported - */ -function checkSupportedCurve(oid) { - try { - oid.getName(); - } catch (e) { - throw new UnsupportedError('Unknown curve OID'); +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); } } -/** - * Get preferred hash algo for a given elliptic algo - * @param {module:enums.publicKey} algo - alrogithm identifier - * @param {module:type/oid} [oid] - curve OID if needed by algo - */ -function getPreferredCurveHashAlgo(algo, oid) { - switch (algo) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.getPreferredHashAlgo(oid); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); - default: - throw new Error('Unknown elliptic signing algo'); - } +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); } -var crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - publicKeyEncrypt: publicKeyEncrypt, - publicKeyDecrypt: publicKeyDecrypt, - parsePublicKeyParams: parsePublicKeyParams, - parsePrivateKeyParams: parsePrivateKeyParams, - parseEncSessionKeyParams: parseEncSessionKeyParams, - serializeParams: serializeParams, - generateParams: generateParams, - validateParams: validateParams$8, - getPrefixRandom: getPrefixRandom, - generateSessionKey: generateSessionKey, - getAEADMode: getAEADMode, - getCipher: getCipher, - getPreferredCurveHashAlgo: getPreferredCurveHashAlgo -}); +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; -/** - * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash - * @module crypto - * @private - */ + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; -// TODO move cfb and gcm to cipher -const mod = { - /** @see module:crypto/cipher */ - cipher: cipher, - /** @see module:crypto/hash */ - hash: hash, - /** @see module:crypto/mode */ - mode: mode, - /** @see module:crypto/public_key */ - publicKey: publicKey, - /** @see module:crypto/signature */ - signature: signature, - /** @see module:crypto/random */ - random: random, - /** @see module:crypto/pkcs1 */ - pkcs1: pkcs1, - /** @see module:crypto/pkcs5 */ - pkcs5: pkcs5, - /** @see module:crypto/aes_kw */ - aesKW: aesKW -}; + scalarbase(p, d); + pack(pk, p); -Object.assign(mod, crypto$1); + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} -var TYPED_OK = typeof Uint8Array !== "undefined" && - typeof Uint16Array !== "undefined" && - typeof Int32Array !== "undefined"; +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; -// reduce buffer size, avoiding mem copy -function shrinkBuf(buf, size) { - if (buf.length === size) { - return buf; - } - if (buf.subarray) { - return buf.subarray(0, size); - } - buf.length = size; - return buf; -} + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; -const fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - let i, l, len, pos, chunk; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - // join chunks - const result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - return result; + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; } -}; + } -const fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; + modL(sm.subarray(32), x); + return smlen; +} +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); -// Enable/Disable typed arrays use, for testing -// + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); -let Buf8 = TYPED_OK ? Uint8Array : Array; -let Buf16 = TYPED_OK ? Uint16Array : Array; -let Buf32 = TYPED_OK ? Int32Array : Array; -let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks; -let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet; + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; -/* Allowed flush values; see deflate() and inflate() below for details */ -const Z_NO_FLUSH = 0; -const Z_PARTIAL_FLUSH = 1; -const Z_SYNC_FLUSH = 2; -const Z_FULL_FLUSH = 3; -const Z_FINISH = 4; -const Z_BLOCK = 5; -const Z_TREES = 6; + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -const Z_OK = 0; -const Z_STREAM_END = 1; -const Z_NEED_DICT = 2; -const Z_STREAM_ERROR = -2; -const Z_DATA_ERROR = -3; -//export const Z_MEM_ERROR = -4; -const Z_BUF_ERROR = -5; -const Z_DEFAULT_COMPRESSION = -1; + M(r[3], r[0], r[1]); + return 0; +} +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; -const Z_FILTERED = 1; -const Z_HUFFMAN_ONLY = 2; -const Z_RLE = 3; -const Z_FIXED = 4; -const Z_DEFAULT_STRATEGY = 0; + if (n < 64) return -1; -/* Possible values of the data_type field (though see inflate()) */ -const Z_BINARY = 0; -const Z_TEXT = 1; -//export const Z_ASCII = 1; // = Z_TEXT (deprecated) -const Z_UNKNOWN = 2; + if (unpackneg(q, pk)) return -1; -/* The deflate compression method */ -const Z_DEFLATED = 8; -//export const Z_NULL = null // Use -1 or null inline, depending on var type + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); -/*============================================================================*/ + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } -function zero$1(buf) { - let len = buf.length; while (--len >= 0) { - buf[len] = 0; - } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; } -// From zutil.h - -const STORED_BLOCK = 0; -const STATIC_TREES = 1; -const DYN_TREES = 2; -/* The three kinds of block type */ +var crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32; -const MIN_MATCH = 3; -const MAX_MATCH = 258; -/* The minimum and maximum match lengths */ +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} -const LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; -const LITERALS = 256; -/* number of literal bytes 0..255 */ +nacl.box = {}; -const L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; -const D_CODES = 30; -/* number of distance codes */ +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; -const BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; -const HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; -const MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; -const Buf_size = 16; -/* size of bit buffer in bi_buf */ +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; -/* =========================================================================== - * Constants - */ +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; -const MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ +nacl.setPRNG = function(fn) { + randombytes = fn; +}; -const END_BLOCK = 256; -/* end of block literal code */ +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + if (crypto$2 && crypto$2.getRandomValues) { + // Browsers and Node v16+ + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto$2.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } +})(); -const REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const knownOIDs = { + '2a8648ce3d030107': enums.curve.nistP256, + '2b81040022': enums.curve.nistP384, + '2b81040023': enums.curve.nistP521, + '2b8104000a': enums.curve.secp256k1, + '2b06010401da470f01': enums.curve.ed25519Legacy, + '2b060104019755010501': enums.curve.curve25519Legacy, + '2b2403030208010107': enums.curve.brainpoolP256r1, + '2b240303020801010b': enums.curve.brainpoolP384r1, + '2b240303020801010d': enums.curve.brainpoolP512r1 +}; -const REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ +class OID { + constructor(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (util.isArray(oid) || + util.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { // DER encoded oid byte array + if (oid[1] !== oid.length - 2) { + throw new Error('Length mismatch in DER encoded oid'); + } + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; + } + } -const REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ + /** + * Method to read an OID object + * @param {Uint8Array} input - Where to read the OID from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } + } + throw new Error('Invalid oid'); + } -/* eslint-disable comma-spacing,array-bracket-spacing */ -const extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + /** + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID. + */ + write() { + return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); + } -const extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + /** + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID. + */ + toHex() { + return util.uint8ArrayToHex(this.oid); + } -const extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns {enums.curve} String with the canonical name of the curve + * @throws if unknown + */ + getName() { + const name = knownOIDs[this.toHex()]; + if (!name) { + throw new Error('Unknown curve object identifier.'); + } -const bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ + return name; + } +} -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/* =========================================================================== - * Local data. These are initialized only once. - */ -// We pre-fill arrays with 0 to avoid uninitialized gaps +function readSimpleLength(bytes) { + let len = 0; + let offset; + const type = bytes[0]; -const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -const static_ltree = new Array((L_CODES + 2) * 2); -zero$1(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ + if (type < 192) { + [len] = bytes; + offset = 1; + } else if (type < 255) { + len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; + offset = 2; + } else if (type === 255) { + len = util.readNumber(bytes.subarray(1, 1 + 4)); + offset = 5; + } -const static_dtree = new Array(D_CODES * 2); -zero$1(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ + return { + len: len, + offset: offset + }; +} -const _dist_code = new Array(DIST_CODE_LEN); -zero$1(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. +/** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * + * @param {Integer} length - The length to encode + * @returns {Uint8Array} String with openpgp length representation. */ - -const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero$1(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -const base_length = new Array(LENGTH_CODES); -zero$1(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -const base_dist = new Array(D_CODES); -zero$1(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; +function writeSimpleLength(length) { + if (length < 192) { + return new Uint8Array([length]); + } else if (length > 191 && length < 8384) { + /* + * let a = (total data packet length) - 192 let bc = two octet + * representation of a let d = b + 192 + */ + return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); + } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); } - -let static_l_desc; -let static_d_desc; -let static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ +function writePartialLength(power) { + if (power < 0 || power > 30) { + throw new Error('Partial Length power must be between 1 and 30'); + } + return new Uint8Array([224 + power]); } - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +function writeTag(tag_type) { + /* we're only generating v4 packet headers here */ + return new Uint8Array([0xC0 | tag_type]); } - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. +/** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * + * @param {Integer} tag_type - Tag type + * @param {Integer} length - Length of the payload + * @returns {String} String of the header. */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = w & 0xff; - s.pending_buf[s.pending++] = w >>> 8 & 0xff; +function writeHeader(tag_type, length) { + /* we're only generating v4 packet headers here */ + return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); } - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. +/** + * Whether the packet type supports partial lengths per RFC4880 + * @param {Integer} tag - Tag type + * @returns {Boolean} String of the header. */ -function send_bits(s, value, length) { - if (s.bi_valid > Buf_size - length) { - s.bi_buf |= value << s.bi_valid & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> Buf_size - s.bi_valid; - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= value << s.bi_valid & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +function supportsStreaming(tag) { + return [ + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ].includes(tag); } - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 +/** + * Generic static Packet Parser function + * + * @param {Uint8Array | ReadableStream} input - Input stream as string + * @param {Function} callback - Function to call with the parsed packet + * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. */ -function bi_reverse(code, len) { - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { - continue; - } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { - return; +async function readPackets(input, callback) { + const reader = getReader(input); + let writer; + let callbackReturned; + try { + const peekedBytes = await reader.peekBytes(2); + // some sanity checks + if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { + throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); } + const headerByte = await reader.readByte(); + let tag = -1; + let format = -1; + let packetLength; - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { - bits--; - } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { - continue; - } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } + format = 0; // 0 = old format; 1 = new format + if ((headerByte & 0x40) !== 0) { + format = 1; } -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = code + bl_count[bits - 1] << 1; + let packetLengthType; + if (format) { + // new format header + tag = headerByte & 0x3F; // bit 5-0 + } else { + // old format header + tag = (headerByte & 0x3F) >> 2; // bit 5-2 + packetLengthType = headerByte & 0x03; // bit 1-0 } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < 1 << extra_lbits[code]; n++) { - _length_code[length++] = code; + let wasPartialLength; + do { + if (!format) { + // 4.2.1. Old Format Packet Lengths + switch (packetLengthType) { + case 0: + // The packet has a one-octet length. The header is 2 octets + // long. + packetLength = await reader.readByte(); + break; + case 1: + // The packet has a two-octet length. The header is 3 octets + // long. + packetLength = (await reader.readByte() << 8) | await reader.readByte(); + break; + case 2: + // The packet has a four-octet length. The header is 5 + // octets long. + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + break; + default: + // 3 - The packet is of indeterminate length. The header is 1 + // octet long, and the implementation must determine how long + // the packet is. If the packet is in a file, this means that + // the packet extends until the end of the file. In general, + // an implementation SHOULD NOT use indeterminate-length + // packets except where the end of the data will be clear + // from the context, and even then it is better to use a + // definite length, or a new format header. The new format + // headers described below have a mechanism for precisely + // encoding data of indeterminate length. + packetLength = Infinity; + break; } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < 1 << extra_dbits[code]; n++) { - _dist_code[dist++] = code; + } else { // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + const lengthByte = await reader.readByte(); + wasPartialLength = false; + if (lengthByte < 192) { + packetLength = lengthByte; + // 4.2.2.2. Two-Octet Lengths + } else if (lengthByte >= 192 && lengthByte < 224) { + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + // 4.2.2.4. Partial Body Lengths + } else if (lengthByte > 223 && lengthByte < 255) { + packetLength = 1 << (lengthByte & 0x1F); + wasPartialLength = true; + if (!packetSupportsStreaming) { + throw new TypeError('This packet type does not support partial lengths.'); + } + // 4.2.2.3. Five-Octet Lengths + } else { + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { - _dist_code[256 + dist++] = code; + } + if (packetLength > 0) { + let bytesRead = 0; + while (true) { + if (writer) await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (packetLength === Infinity) break; + throw new Error('Unexpected end of packet'); + } + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); + if (writer) await writer.write(chunk); + else packet.push(chunk); + bytesRead += value.length; + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); + break; + } } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - let n; /* iterates over tree elements */ + } + } while (wasPartialLength); - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { - s.dyn_ltree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < D_CODES; n++) { - s.dyn_dtree[n * 2]/*.Freq*/ = 0; + // If this was not a packet that "supports streaming", we peek to check + // whether it is the last packet in the message. We peek 2 bytes instead + // of 1 because the beginning of this function also peeks 2 bytes, and we + // want to cut a `subarray` of the correct length into `web-stream-tools`' + // `externalBuffer` as a tiny optimization here. + // + // If it *was* a streaming packet (i.e. the data packets), we peek at the + // entire remainder of the stream, in order to forward errors in the + // remainder of the stream to the packet data. (Note that this means we + // read/peek at all signature packets before closing the literal data + // packet, for example.) This forwards MDC errors to the literal data + // stream, for example, so that they don't get lost / forgotten on + // decryptedMessage.packets.stream, which we never look at. + // + // An example of what we do when stream-parsing a message containing + // [ one-pass signature packet, literal data packet, signature packet ]: + // 1. Read the one-pass signature packet + // 2. Peek 2 bytes of the literal data packet + // 3. Parse the one-pass signature packet + // + // 4. Read the literal data packet, simultaneously stream-parsing it + // 5. Peek until the end of the message + // 6. Finish parsing the literal data packet + // + // 7. Read the signature packet again (we already peeked at it in step 5) + // 8. Peek at the end of the stream again (`peekBytes` returns undefined) + // 9. Parse the signature packet + // + // Note that this means that if there's an error in the very end of the + // stream, such as an MDC error, we throw in step 5 instead of in step 8 + // (or never), which is the point of this exercise. + const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); + if (writer) { + await writer.ready; + await writer.close(); + } else { + packet = util.concatUint8Array(packet); + // eslint-disable-next-line callback-return + await callback({ tag, packet }); } - for (n = 0; n < BL_CODES; n++) { - s.bl_tree[n * 2]/*.Freq*/ = 0; + return !nextPacket || !nextPacket.length; + } catch (e) { + if (writer) { + await writer.abort(e); + return true; + } else { + throw e; } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; + } finally { + if (writer) { + await callbackReturned; } - s.bi_buf = 0; - s.bi_valid = 0; + reader.releaseLock(); + } } -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ +class UnsupportedError extends Error { + constructor(...params) { + super(...params); - if (header) { - put_short(s, len); - put_short(s, ~len); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - // while (len--) { - // put_byte(s, *buf++); - // } - arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - const _n2 = n * 2; - const _m2 = m * 2; - return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]; -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { - break; - } - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; + this.name = 'UnsupportedError'; + } } +// unknown packet types are handled differently depending on the packet criticality +class UnknownPacketError extends UnsupportedError { + constructor(...params) { + super(...params); -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - send_code(s, END_BLOCK, ltree); + this.name = 'UnknownPacketError'; + } } +class UnparseablePacket { + constructor(tag, rawContent) { + this.tag = tag; + this.rawContent = rawContent; + } -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) { - pqdownheap(s, tree, n); - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); + write() { + return this.rawContent; + } } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { - s.bl_tree[curlen * 2]/*.Freq*/++; - } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. +/** + * Generate (non-legacy) EdDSA key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { - send_code(s, curlen, s.bl_tree); - } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; +async function generate$3(algo) { + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']); - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; + const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey); - } else { - max_count = 7; - min_count = 4; + return { + A: new Uint8Array(b64ToUint8Array(publicKey.x)), + seed: b64ToUint8Array(privateKey.d, true) + }; + } catch (err) { + if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux + throw err; } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - let max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ + const seed = getRandomBytes(getPayloadSize$1(algo)); + const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed); + return { A, seed }; + } - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const seed = ed448.utils.randomPrivateKey(); + const A = ed448.getPublicKey(seed); + return { A, seed }; } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; + default: + throw new Error('Unsupported EdDSA algorithm'); + } } - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. +/** + * Sign a message using the provided key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * RS: Uint8Array + * }>} Signature of the message + * @async */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - let rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - +async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = privateKeyToJWK(algo, publicKey, privateKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']); -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - let black_mask = 0xf3ffc07f; - let n; + const signature = new Uint8Array( + await webCrypto.sign('Ed25519', key, hashed) + ); - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_BINARY; + return { RS: signature }; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; } - } + const secretKey = util.concatUint8Array([privateKey, publicKey]); + const signature = nacl.sign.detached(hashed, secretKey); + return { RS: signature }; + } - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const signature = ed448.sign(hashed, privateKey); + return { RS: signature }; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; } - -let static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. +/** + * Verifies if a signature is valid for a message + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{ RS: Uint8Array }} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async */ -function _tr_init(s) { +async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) { + if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = publicKeyToJWK(algo, publicKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']); + const verified = await webCrypto.verify('Ed25519', key, RS, hashed); + return verified; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + return nacl.sign.detached.verify(hashed, RS, publicKey); + } - if (!static_init_done) { - tr_static_init(); - static_init_done = true; + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + return ed448.verify(RS, hashed, publicKey); } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); + default: + throw new Error('Unsupported EdDSA algorithm'); + } } - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. +/** + * Validate (non-legacy) EdDSA parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - EdDSA public point + * @param {Uint8Array} seed - EdDSA secret seed + * @param {Uint8Array} oid - (legacy only) EdDSA OID + * @returns {Promise} Whether params are valid. + * @async */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = s.opt_len + 3 + 7 >>> 3; - static_lenb = s.static_len + 3 + 7 >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); +async function validateParams$6(algo, A, seed) { + switch (algo) { + case enums.publicKey.ed25519: { + /** + * Derive public point A' from private key + * and expect A == A' + * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(seed); + return util.equalsUint8Array(A, publicKey); + } - if (static_lenb <= opt_lenb) { - opt_lenb = static_lenb; - } + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + const publicKey = ed448.getPublicKey(seed); + return util.equalsUint8Array(A, publicKey); } + default: + return false; + } +} - if (stored_len + 4 <= opt_lenb && buf !== -1) { - /* 4: two words for the lengths */ +function getPayloadSize$1(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return 32; - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); + case enums.publicKey.ed448: + return 57; - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + default: + throw new Error('Unsupported EdDSA algorithm'); + } +} - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); +function getPreferredHashAlgo$2(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return enums.hash.sha256; + case enums.publicKey.ed448: + return enums.hash.sha512; + default: + throw new Error('Unknown EdDSA algo'); + } +} - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); +const publicKeyToJWK = (algo, publicKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: uint8ArrayToB64(publicKey), + ext: true + }; + return jwk; } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; - if (last) { - bi_windup(s); +const privateKeyToJWK = (algo, publicKey, privateKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = publicKeyToJWK(algo, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; +var eddsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + generate: generate$3, + getPayloadSize: getPayloadSize$1, + getPreferredHashAlgo: getPreferredHashAlgo$2, + sign: sign$5, + validateParams: validateParams$6, + verify: verify$5 +}); - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif - - return s.last_lit === s.lit_bufsize - 1; - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral // -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. // -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. // -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function adler32(adler, buf, len, pos) { - let s1 = adler & 0xffff |0, - s2 = adler >>> 16 & 0xffff |0, - n = 0; - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = s1 + buf[pos++] |0; - s2 = s2 + s1 |0; - } while (--n); +const webCrypto$4 = util.getWebCrypto(); +/** + * AES key wrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} dataToWrap + * @returns {Uint8Array} wrapped key + */ +async function wrap(algo, key, dataToWrap) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - s1 %= 65521; - s2 %= 65521; + try { + const wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']); + // Import data as HMAC key, as it has no key length requirements + const keyToWrap = await webCrypto$4.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + const wrapped = await webCrypto$4.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' }); + return new Uint8Array(wrapped); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + } - return s1 | s2 << 16 |0; + return aeskw(key).encrypt(dataToWrap); } -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. +/** + * AES key unwrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} wrappedData + * @returns {Uint8Array} unwrapped data + */ +async function unwrap(algo, key, wrappedData) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - let c; - const table = []; - - for (let n = 0; n < 256; n++) { - c = n; - for (let k = 0; k < 8; k++) { - c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; - } - table[n] = c; + let wrappingKey; + try { + wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + return aeskw(key).decrypt(wrappedData); + } - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -const crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - const t = crcTable, - end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; + try { + const unwrapped = await webCrypto$4.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + return new Uint8Array(await webCrypto$4.exportKey('raw', unwrapped)); + } catch (err) { + if (err.name === 'OperationError') { + throw new Error('Key Data Integrity failed'); } - - return crc ^ -1; // >>> 0; + throw err; + } } -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var msg = { - 2: "need dictionary", /* Z_NEED_DICT 2 */ - 1: "stream end", /* Z_STREAM_END 1 */ - 0: "", /* Z_OK 0 */ - "-1": "file error", /* Z_ERRNO (-1) */ - "-2": "stream error", /* Z_STREAM_ERROR (-2) */ - "-3": "data error", /* Z_DATA_ERROR (-3) */ - "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */ - "-5": "buffer error", /* Z_BUF_ERROR (-5) */ - "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */ -}; - -/*============================================================================*/ - +var aesKW = /*#__PURE__*/Object.freeze({ + __proto__: null, + unwrap: unwrap, + wrap: wrap +}); -const MAX_MEM_LEVEL = 9; +/** + * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. + * @module crypto/hkdf + */ -const LENGTH_CODES$1 = 29; -/* number of length codes, not counting the special END_BLOCK code */ -const LITERALS$1 = 256; -/* number of literal bytes 0..255 */ -const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; -/* number of Literal or Length codes, including the END_BLOCK code */ -const D_CODES$1 = 30; -/* number of distance codes */ -const BL_CODES$1 = 19; -/* number of codes used to transfer the bit lengths */ -const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; -/* maximum heap size */ -const MAX_BITS$1 = 15; -/* All codes must not exceed MAX_BITS bits */ +const webCrypto$3 = util.getWebCrypto(); -const MIN_MATCH$1 = 3; -const MAX_MATCH$1 = 258; -const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); +async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { + const hash = enums.read(enums.webHash, hashAlgo); + if (!hash) throw new Error('Hash algo not supported with HKDF'); -const PRESET_DICT = 0x20; + const importedKey = await webCrypto$3.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto$3.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + return new Uint8Array(bits); +} -const INIT_STATE = 42; -const EXTRA_STATE = 69; -const NAME_STATE = 73; -const COMMENT_STATE = 91; -const HCRC_STATE = 103; -const BUSY_STATE = 113; -const FINISH_STATE = 666; +/** + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @module crypto/public_key/elliptic/ecdh + */ -const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -const BS_BLOCK_DONE = 2; /* block flush performed */ -const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ -const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. +const HKDF_INFO = { + x25519: util.encodeUTF8('OpenPGP X25519'), + x448: util.encodeUTF8('OpenPGP X448') +}; -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} +/** + * Generate ECDH key for Montgomery curves + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} + */ +async function generate$2(algo) { + switch (algo) { + case enums.publicKey.x25519: { + // k stays in little-endian, unlike legacy ECDH over curve25519 + const k = getRandomBytes(32); + const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k); + return { A, k }; + } -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const k = x448.utils.randomPrivateKey(); + const A = x448.getPublicKey(k); + return { A, k }; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } } -function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } +/** +* Validate ECDH parameters +* @param {module:enums.publicKey} algo - Algorithm identifier +* @param {Uint8Array} A - ECDH public point +* @param {Uint8Array} k - ECDH secret scalar +* @returns {Promise} Whether params are valid. +* @async +*/ +async function validateParams$5(algo, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + /** + * Derive public point A' from private key + * and expect A == A' + */ + const { publicKey } = nacl.box.keyPair.fromSecretKey(k); + return util.equalsUint8Array(A, publicKey); + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + /** + * Derive public point A' from private key + * and expect A == A' + */ + const publicKey = x448.getPublicKey(k); + return util.equalsUint8Array(A, publicKey); + } + default: + return false; + } +} -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). +/** + * Wrap and encrypt a session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} data - session key data to be encrypted + * @param {Uint8Array} recipientA - Recipient public key (K_B) + * @returns {Promise<{ + * ephemeralPublicKey: Uint8Array, + * wrappedKey: Uint8Array + * }>} ephemeral public key (K_A) and encrypted key + * @async */ -function flush_pending(strm) { - const s = strm.state; +async function encrypt$2(algo, data, recipientA) { + const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + recipientA, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; + default: + throw new Error('Unsupported ECDH algorithm'); } - if (len === 0) { return; } +} - arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; +/** + * Decrypt and unwrap the session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} ephemeralPublicKey - (K_A) + * @param {Uint8Array} wrappedKey, + * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF + * @param {Uint8Array} k - Recipient secret key (b) + * @returns {Promise} decrypted session key data + * @async + */ +async function decrypt$2(algo, ephemeralPublicKey, wrappedKey, A, k) { + const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + A, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + default: + throw new Error('Unsupported ECDH algorithm'); } } +function getPayloadSize(algo) { + switch (algo) { + case enums.publicKey.x25519: + return 32; -function flush_block_only(s, last) { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - + case enums.publicKey.x448: + return 56; -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; + default: + throw new Error('Unsupported ECDH algorithm'); + } } - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. +/** + * Generate shared secret and ephemeral public key for encryption + * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret + * @async */ -function putShortMSB(s, b) { - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; +async function generateEphemeralEncryptionMaterial(algo, recipientA) { + switch (algo) { + case enums.publicKey.x25519: { + const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo)); + const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const ephemeralSecretKey = x448.utils.randomPrivateKey(); + const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } } +async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). +/** + * x25519 and x448 produce an all-zero value when given as input a point with small order. + * This does not lead to a security issue in the context of ECDH, but it is still unexpected, + * hence we throw. + * @param {Uint8Array} sharedSecret */ -function read_buf(strm, buf, start, size) { - let len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); +function assertNonZeroArray(sharedSecret) { + let acc = 0; + for (let i = 0; i < sharedSecret.length; i++) { + acc |= sharedSecret[i]; } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); + if (acc === 0) { + throw new Error('Unexpected low order point'); } - - strm.next_in += len; - strm.total_in += len; - - return len; } +var ecdh_x = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$2, + encrypt: encrypt$2, + generate: generate$2, + generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial, + getPayloadSize: getPayloadSize, + recomputeSharedSecret: recomputeSharedSecret, + validateParams: validateParams$5 +}); -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - const _win = s.window; // shortcut - - const wmask = s.w_mask; - const prev = s.prev; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - const strend = s.strstart + MAX_MATCH$1; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; +const webCrypto$2 = util.getWebCrypto(); +const nodeCrypto$2 = util.getNodeCrypto(); - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); +const webCurves = { + [enums.curve.nistP256]: 'P-256', + [enums.curve.nistP384]: 'P-384', + [enums.curve.nistP521]: 'P-521' +}; +const knownCurves = nodeCrypto$2 ? nodeCrypto$2.getCurves() : []; +const nodeCurves = nodeCrypto$2 ? { + [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, + [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, + [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, + [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, + [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined, + [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined, + [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, + [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, + [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined +} : {}; - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; +const curves = { + [enums.curve.nistP256]: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.nistP256], + web: webCurves[enums.curve.nistP256], + payloadSize: 32, + sharedSize: 256, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP384]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.nistP384], + web: webCurves[enums.curve.nistP384], + payloadSize: 48, + sharedSize: 384, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP521]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.nistP521], + web: webCurves[enums.curve.nistP521], + payloadSize: 66, + sharedSize: 528, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.secp256k1]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.secp256k1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.ed25519Legacy]: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: enums.publicKey.eddsaLegacy, + hash: enums.hash.sha512, + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.curve25519Legacy]: { + oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: enums.publicKey.ecdh, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.brainpoolP256r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.brainpoolP256r1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP384r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.brainpoolP384r1], + payloadSize: 48, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP512r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.brainpoolP512r1], + payloadSize: 64, + wireFormatLeadingByte: 0x04 } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ +}; - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; +class CurveWithOID { + constructor(oidOrName) { + try { + this.name = oidOrName instanceof OID ? + oidOrName.getName() : + enums.write(enums.curve,oidOrName); + } catch (err) { + throw new UnsupportedError('Unknown curve'); } + const params = curves[this.name]; - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); + this.keyType = params.keyType; - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH$1 - (strend - scan); - scan = strend - MAX_MATCH$1; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node; + this.web = params.web; + this.payloadSize = params.payloadSize; + this.sharedSize = params.sharedSize; + this.wireFormatLeadingByte = params.wireFormatLeadingByte; + if (this.web && util.getWebCrypto()) { + this.type = 'web'; + } else if (this.node && util.getNodeCrypto()) { + this.type = 'node'; + } else if (this.name === enums.curve.curve25519Legacy) { + this.type = 'curve25519Legacy'; + } else if (this.name === enums.curve.ed25519Legacy) { + this.type = 'ed25519Legacy'; } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - const _w_size = s.w_size; - let p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH$1) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH$1) { - break; + async genKeyPair() { + switch (this.type) { + case 'web': + try { + return await webGenKeyPair(this.name, this.wireFormatLeadingByte); + } catch (err) { + util.printDebugError('Browser did not support generating ec key ' + err.message); + return jsGenKeyPair(this.name); } + case 'node': + return nodeGenKeyPair(this.name); + case 'curve25519Legacy': { + // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3 + const { k, A } = await generate$2(enums.publicKey.x25519); + const privateKey = k.slice().reverse(); + privateKey[0] = (privateKey[0] & 127) | 64; + privateKey[31] &= 248; + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // var curr = s.strstart + s.lookahead; - // var init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (; ;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; + case 'ed25519Legacy': { + const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519); + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; } - /* flush the current block */ + default: + return jsGenKeyPair(this.name); } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; + } +} - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; +async function generate$1(curveName) { + const curve = new CurveWithOID(curveName); + const { oid, hash, cipher } = curve; + const keyPair = await curve.genKeyPair(); + return { + oid, + Q: keyPair.publicKey, + secret: util.leftPad(keyPair.privateKey, curve.payloadSize), + hash, + cipher + }; +} - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ +/** + * Get preferred hash algo to use with the given curve + * @param {module:type/oid} oid - curve oid + * @returns {enums.hash} hash algorithm + */ +function getPreferredHashAlgo$1(oid) { + return curves[oid.getName()].hash; +} +/** + * Validate ECDH and ECDSA parameters + * Not suitable for EdDSA (different secret key format) + * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves + * @param {module:type/oid} oid - EC object identifier + * @param {Uint8Array} Q - EC public point + * @param {Uint8Array} d - EC secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateStandardParams(algo, oid, Q, d) { + const supportedCurves = { + [enums.curve.nistP256]: true, + [enums.curve.nistP384]: true, + [enums.curve.nistP521]: true, + [enums.curve.secp256k1]: true, + [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh, + [enums.curve.brainpoolP256r1]: true, + [enums.curve.brainpoolP384r1]: true, + [enums.curve.brainpoolP512r1]: true + }; - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } + // Check whether the given curve is supported + const curveName = oid.getName(); + if (!supportedCurves[curveName]) { + return false; } - s.insert = 0; + if (curveName === enums.curve.curve25519Legacy) { + d = d.slice().reverse(); + // Re-derive public point Q' + const { publicKey } = nacl.box.keyPair.fromSecretKey(d); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; + Q = new Uint8Array(Q); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + if (!util.equalsUint8Array(dG, Q)) { + return false; } - /***/ - return BS_FINISH_DONE; + + return true; } - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + /* + * Re-derive public point Q' = dG from private key + * Expect Q == Q' + */ + const dG = nobleCurve.getPublicKey(d, false); + if (!util.equalsUint8Array(dG, Q)) { + return false; } - return BS_NEED_MORE; + return true; } -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. +/** + * Check whether the public point has a valid encoding. + * NB: this function does not check e.g. whether the point belongs to the curve. */ -function deflate_fast(s, flush) { - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH$1) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); +function checkPublicPointEnconding(curve, V) { + const { payloadSize, wireFormatLeadingByte, name: curveName } = curve; - s.lookahead -= s.match_length; + const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2; - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; + if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) { + throw new Error('Invalid point encoding'); } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; } -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - - let max_insert; - - /* Process the input block. */ - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// +async function jsGenKeyPair(name) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + const privateKey = nobleCurve.utils.randomPrivateKey(); + const publicKey = nobleCurve.getPublicKey(privateKey, false); + return { publicKey, privateKey }; +} + +async function webGenKeyPair(name, wireFormatLeadingByte) { + // Note: keys generated with ECDSA and ECDH are structurally equivalent + const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } + const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey); - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH$1 - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ + return { + publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte), + privateKey: b64ToUint8Array(privateKey.d) + }; +} - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { +async function nodeGenKeyPair(name) { + // Note: ECDSA and ECDH key generation is structurally equivalent + const ecdh = nodeCrypto$2.createECDH(nodeCurves[name]); + await ecdh.generateKeys(); + return { + publicKey: new Uint8Array(ecdh.getPublicKey()), + privateKey: new Uint8Array(ecdh.getPrivateKey()) + }; +} - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH$1 - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH$1; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH$1 - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); +/** + * @param {JsonWebKey} jwk - key for conversion + * + * @returns {Uint8Array} Raw public key. + */ +function jwkToRawPublic(jwk, wireFormatLeadingByte) { + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); + const publicKey = new Uint8Array(bufX.length + bufY.length + 1); + publicKey[0] = wireFormatLeadingByte; + publicKey.set(bufX, 1); + publicKey.set(bufY, bufX.length + 1); + return publicKey; +} - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * + * @returns {JsonWebKey} Public key in jwk format. + */ +function rawPublicToJWK(payloadSize, name, publicKey) { + const len = payloadSize; + const bufX = publicKey.slice(1, len + 1); + const bufY = publicKey.slice(len + 1, len * 2 + 1); + // https://www.rfc-editor.org/rfc/rfc7518.txt + const jwk = { + kty: 'EC', + crv: name, + x: uint8ArrayToB64(bufX), + y: uint8ArrayToB64(bufY), + ext: true + }; + return jwk; +} - return BS_BLOCK_DONE; +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * @param {Uint8Array} privateKey - private key + * + * @returns {JsonWebKey} Private key in jwk format. + */ +function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - const _win = s.window; +const webCrypto$1 = util.getWebCrypto(); +const nodeCrypto$1 = util.getNodeCrypto(); - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH$1) { - fill_window(s); - if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH$1; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH$1 - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; +/** + * Sign a message using the provided key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (message && !util.isStream(message)) { + const keyPair = { publicKey, privateKey }; + switch (curve.type) { + case 'web': + // If browser doesn't support a curve, we'll catch it + try { + // Need to await to make sure browser succeeds + return await webSign(curve, hashAlgo, message, keyPair); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunaley Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support signing: ' + err.message); } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + break; + case 'node': + return nodeSign(curve, hashAlgo, message, privateKey); } + } - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH$1) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + const signature = nobleCurve.sign(hashed, privateKey, { lowS: false }); + return { + r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize), + s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize) + }; +} - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); +/** + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} message - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + // See https://github.com/openpgpjs/openpgpjs/pull/948. + // NB: the impact was more likely limited to Brainpool curves, since thanks + // to WebCrypto availability, NIST curve should not have been affected. + // Similarly, secp256k1 should have been used rarely enough. + // However, we implement the fix for all curves, since it's only needed in case of + // verification failure, which is unexpected, hence a minor slowdown is acceptable. + const tryFallbackVerificationForOldBug = async () => ( + hashed[0] === 0 ? + jsVerify(curve, signature, hashed.subarray(1), publicKey) : + false + ); - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + if (message && !util.isStream(message)) { + switch (curve.type) { + case 'web': + try { + // Need to await to make sure browser succeeds + const verified = await webVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunately Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support verifying: ' + err.message); + } + break; + case 'node': { + const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; } - /***/ } - return BS_BLOCK_DONE; + + const verified = await jsVerify(curve, signature, hashed, publicKey); + return verified || tryFallbackVerificationForOldBug(); } -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) +/** + * Validate ECDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDSA public point + * @param {Uint8Array} d - ECDSA secret scalar + * @returns {Promise} Whether params are valid. + * @async */ -function deflate_huff(s, flush) { - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } +async function validateParams$4(oid, Q, d) { + const curve = new CurveWithOID(oid); + // Reject curves x25519 and ed25519 + if (curve.keyType !== enums.publicKey.ecdsa) { + return false; + } - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; + // To speed up the validation, we try to use node- or webcrypto when available + // and sign + verify a random message + switch (curve.type) { + case 'web': + case 'node': { + const message = getRandomBytes(8); + const hashAlgo = enums.hash.sha256; + const hashed = await hash.digest(hashAlgo, message); + try { + const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed); + // eslint-disable-next-line @typescript-eslint/return-await + return await verify$4(oid, hashAlgo, signature, message, Q, hashed); + } catch (err) { + return false; } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; } - /***/ + default: + return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); } - return BS_BLOCK_DONE; } -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + +/** + * Fallback javascript implementation of ECDSA verification. + * To be used if no native implementation is available for the given curve/operation. */ -class Config { - constructor(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } +async function jsVerify(curve, signature, hashed, publicKey) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false }); } -const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; +async function webSign(curve, hashAlgo, message, keyPair) { + const len = curve.payloadSize; + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['sign'] + ); + const signature = new Uint8Array(await webCrypto$1.sign( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + message + )); -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; + return { + r: signature.slice(0, len), + s: signature.slice(len, len << 1) + }; +} - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); +async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['verify'] + ); - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; + const signature = util.concatUint8Array([r, s]).buffer; - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - s.ins_h = 0; + return webCrypto$1.verify( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + signature, + message + ); } -class DeflateState { - constructor() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ +async function nodeSign(curve, hashAlgo, message, privateKey) { + // JWT encoding cannot be used for now, as Brainpool curves are not supported + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + privateKey: nodeBuffer.from(privateKey) + }); - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ + const sign = nodeCrypto$1.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(message); + sign.end(); - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ + const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' })); + const len = curve.payloadSize; - this.head = null; /* Heads of the hash chains or NIL. */ + return { + r: signature.subarray(0, len), + s: signature.subarray(len, len << 1) + }; +} - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ +async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { publicKey: derPublicKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + publicKey: nodeBuffer.from(publicKey) + }); - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ + const verify = nodeCrypto$1.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(message); + verify.end(); - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ + const signature = util.concatUint8Array([r, s]); - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ + try { + return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature); + } catch (err) { + return false; + } +} - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ +var ecdsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$4, + validateParams: validateParams$4, + verify: verify$4 +}); - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ +/** + * Sign a message using the provided legacy EdDSA key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed); + // EdDSA signature params are returned in little-endian format + return { + r: signature.subarray(0, 32), + s: signature.subarray(32) + }; +} - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ +/** + * Verifies if a legacy EdDSA signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + const RS = util.concatUint8Array([r, s]); + return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed); +} +/** + * Validate legacy EdDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - EdDSA public point + * @param {Uint8Array} k - EdDSA secret seed + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$3(oid, Q, k) { + // Check whether the given curve is supported + if (oid.getName() !== enums.curve.ed25519Legacy) { + return false; + } - this.nice_match = 0; /* Stop searching when current match exceeds this */ + /** + * Derive public point Q' = dG from private key + * and expect Q == Q' + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(k); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + return util.equalsUint8Array(Q, dG); - /* used by trees.c: */ +} - /* Didn't use ct_data typedef below to suppress compiler warning */ +var eddsa_legacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$3, + validateParams: validateParams$3, + verify: verify$3 +}); - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); - this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); - this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); - zero$2(this.dyn_ltree); - zero$2(this.dyn_dtree); - zero$2(this.bl_tree); - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ +/** + * @fileoverview Functions to add and remove PKCS5 padding + * @see PublicKeyEncryptedSessionKeyPacket + * @module crypto/pkcs5 + * @private + */ - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Buf16(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ +/** + * Add pkcs5 padding to a message + * @param {Uint8Array} message - message to pad + * @returns {Uint8Array} Padded message. + */ +function encode(message) { + const c = 8 - (message.length % 8); + const padded = new Uint8Array(message.length + c).fill(c); + padded.set(message); + return padded; +} - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ - zero$2(this.heap); +/** + * Remove pkcs5 padding from a message + * @param {Uint8Array} message - message to remove padding from + * @returns {Uint8Array} Message without padding. + */ +function decode(message) { + const len = message.length; + if (len > 0) { + const c = message[len - 1]; + if (c >= 1) { + const provided = message.subarray(len - c); + const computed = new Uint8Array(c).fill(c); + if (util.equalsUint8Array(provided, computed)) { + return message.subarray(0, len - c); + } + } + } + throw new Error('Invalid padding'); +} - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ +var pkcs5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: decode, + encode: encode +}); - this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; - zero$2(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - this.last_lit = 0; /* running index in l_buf */ +const webCrypto = util.getWebCrypto(); +const nodeCrypto = util.getNodeCrypto(); - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ +/** + * Validate ECDH parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDH public point + * @param {Uint8Array} d - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$2(oid, Q, d) { + return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); +} - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ +// Build Param for ECDH algorithm (RFC 6637) +function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { + return util.concatUint8Array([ + oid.write(), + new Uint8Array([public_algo]), + kdfParams.write(), + util.stringToUint8Array('Anonymous Sender '), + fingerprint + ]); +} +// Key Derivation Function (RFC 6637) +async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { + // Note: X is little endian for Curve25519, big-endian for all others. + // This is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + let i; + if (stripLeading) { + // Work around old go crypto bug + for (i = 0; i < X.length && X[i] === 0; i++); + X = X.subarray(i); + } + if (stripTrailing) { + // Work around old OpenPGP.js bug + for (i = X.length - 1; i >= 0 && X[i] === 0; i--); + X = X.subarray(0, i + 1); + } + const digest = await hash.digest(hashAlgo, util.concatUint8Array([ + new Uint8Array([0, 0, 0, 1]), + X, + param + ])); + return digest.subarray(0, length); +} - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ +/** + * Generate ECDHE ephemeral key and secret from public key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPublicEphemeralKey(curve, Q) { + switch (curve.type) { + case 'curve25519Legacy': { + const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1)); + const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]); + return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPublicEphemeralKey(curve, Q); + } catch (err) { + util.printDebugError(err); + return jsPublicEphemeralKey(curve, Q); + } + } + break; + case 'node': + return nodePublicEphemeralKey(curve, Q); + default: + return jsPublicEphemeralKey(curve, Q); - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ } } -function deflateResetKeep(strm) { - let s; +/** + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} data - Unpadded session key data + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} + * @async + */ +async function encrypt$1(oid, kdfParams, data, Q, fingerprint) { + const m = encode(data); + + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); + const wrappedKey = await wrap(kdfParams.cipher, Z, m); + return { publicKey, wrappedKey }; +} - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); +/** + * Generate ECDHE secret from private key and public part of ephemeral key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ + switch (curve.type) { + case 'curve25519Legacy': { + const secretKey = d.slice().reverse(); + const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey); + return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPrivateEphemeralKey(curve, V, Q, d); + } catch (err) { + util.printDebugError(err); + return jsPrivateEphemeralKey(curve, V, d); + } + } + break; + case 'node': + return nodePrivateEphemeralKey(curve, V, d); + default: + return jsPrivateEphemeralKey(curve, V, d); } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - _tr_init(s); - return Z_OK; } - -function deflateReset(strm) { - const ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); +/** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} C - Encrypted and wrapped value derived from session key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise} Value derived from session key. + * @async + */ +async function decrypt$1(oid, kdfParams, V, C, Q, d, fingerprint) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + checkPublicPointEnconding(curve, V); + const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + let err; + for (let i = 0; i < 3; i++) { + try { + // Work around old go crypto bug and old OpenPGP.js bug, respectively. + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); + return decode(await unwrap(kdfParams.cipher, Z, C)); + } catch (e) { + err = e; + } } - return ret; + throw err; } - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; +async function jsPrivateEphemeralKey(curve, V, d) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V); + const sharedKey = sharedSecretWithParity.subarray(1); + return { secretKey: d, sharedKey }; } +async function jsPublicEphemeralKey(curve, Q) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + const { publicKey: V, privateKey: v } = await curve.genKeyPair(); -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - let wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); - s.window = new Buf8(s.w_size * 2); - s.head = new Buf16(s.hash_size); - s.prev = new Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q); + const sharedKey = sharedSecretWithParity.subarray(1); + return { publicKey: V, sharedKey }; } +/** + * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPrivateEphemeralKey(curve, V, Q, d) { + const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d); + let privateKey = webCrypto.importKey( + 'jwk', + recipient, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V); + let sender = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + [] + ); + [privateKey, sender] = await Promise.all([privateKey, sender]); + let S = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: sender + }, + privateKey, + curve.sharedSize + ); + let secret = webCrypto.exportKey( + 'jwk', + privateKey + ); + [S, secret] = await Promise.all([S, secret]); + const sharedKey = new Uint8Array(S); + const secretKey = b64ToUint8Array(secret.d); + return { secretKey, sharedKey }; +} -function deflate(strm, flush) { - let old_flush, s; - let beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } +/** + * Generate ECDHE ephemeral key and secret from public key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPublicEphemeralKey(curve, Q) { + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q); + let keyPair = webCrypto.generateKey( + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + let recipient = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + false, + [] + ); + [keyPair, recipient] = await Promise.all([keyPair, recipient]); + let s = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: recipient + }, + keyPair.privateKey, + curve.sharedSize + ); + let p = webCrypto.exportKey( + 'jwk', + keyPair.publicKey + ); + [s, p] = await Promise.all([s, p]); + const sharedKey = new Uint8Array(s); + const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte)); + return { publicKey, sharedKey }; +} - s = strm.state; +/** + * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePrivateEphemeralKey(curve, V, d) { + const recipient = nodeCrypto.createECDH(curve.node); + recipient.setPrivateKey(d); + const sharedKey = new Uint8Array(recipient.computeSecret(V)); + const secretKey = new Uint8Array(recipient.getPrivateKey()); + return { secretKey, sharedKey }; +} - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } +/** + * Generate ECDHE ephemeral key and secret from public key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePublicEphemeralKey(curve, Q) { + const sender = nodeCrypto.createECDH(curve.node); + sender.generateKeys(); + const sharedKey = new Uint8Array(sender.computeSecret(Q)); + const publicKey = new Uint8Array(sender.getPublicKey()); + return { publicKey, sharedKey }; +} - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; +var ecdh = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$1, + encrypt: encrypt$1, + validateParams: validateParams$2 +}); - /* Write the header */ - if (s.status === INIT_STATE) { +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); +var elliptic = /*#__PURE__*/Object.freeze({ + __proto__: null, + CurveWithOID: CurveWithOID, + ecdh: ecdh, + ecdhX: ecdh_x, + ecdsa: ecdsa, + eddsa: eddsa, + eddsaLegacy: eddsa_legacy, + generate: generate$1, + getPreferredHashAlgo: getPreferredHashAlgo$1 +}); - s.status = BUSY_STATE; - putShortMSB(s, header); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ +/* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 +*/ - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; +const _0n = BigInt(0); +const _1n = BigInt(1); - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); +/** + * DSA Sign function + * @param {Integer} hashAlgo + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} x + * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} + * @async + */ +async function sign$2(hashAlgo, hashed, g, p, q, x) { + const _0n = BigInt(0); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + x = uint8ArrayToBigInt(x); - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } + let k; + let r; + let s; + let t; + g = mod$1(g, p); + x = mod$1(x, q); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + const h = mod$1(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + while (true) { + // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + k = getRandomBigInteger(_1n, q); // returns in [1, q-1] + r = mod$1(modExp(g, k, p), q); // (g**k mod p) mod q + if (r === _0n) { + continue; } - else { - s.status = COMMENT_STATE; + const xr = mod$1(x * r, q); + t = mod$1(h + xr, q); // H(m) + x*r mod q + s = mod$1(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q + if (s === _0n) { + continue; } + break; } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; + return { + r: bigIntToUint8Array(r, 'be', byteLength(p)), + s: bigIntToUint8Array(s, 'be', byteLength(p)) + }; +} - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); +/** + * DSA Verify function + * @param {Integer} hashAlgo + * @param {Uint8Array} r + * @param {Uint8Array} s + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} y + * @returns {boolean} + * @async + */ +async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) { + r = uint8ArrayToBigInt(r); + s = uint8ArrayToBigInt(s); - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + + if (r <= _0n || r >= q || + s <= _0n || s >= q) { + util.printDebug('invalid DSA Signature'); + return false; } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } + const h = mod$1(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + const w = modInv(s, q); // s**-1 mod q + if (w === _0n) { + util.printDebug('invalid DSA Signature'); + return false; } - //#endif - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } + g = mod$1(g, p); + y = mod$1(y, p); + const u1 = mod$1(h * w, q); // H(m) * w mod q + const u2 = mod$1(r * w, q); // r * w mod q + const t1 = modExp(g, u1, p); // g**u1 mod p + const t2 = modExp(y, u2, p); // y**u2 mod p + const v = mod$1(mod$1(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q + return v === r; +} - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); +/** + * Validate DSA parameters + * @param {Uint8Array} p - DSA prime + * @param {Uint8Array} q - DSA group order + * @param {Uint8Array} g - DSA sub-group generator + * @param {Uint8Array} y - DSA public key + * @param {Uint8Array} x - DSA private key + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$1(p, q, g, y, x) { + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + // Check that 1 < g < p + if (g <= _1n || g >= p) { + return false; } - /* Start a new block or continue the current one. + /** + * Check that subgroup order q divides p-1 */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero$2(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } + if (mod$1(p - _1n, q) !== _0n) { + return false; } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); + /** + * g has order q + * Check that g ** q = 1 mod p + */ + if (modExp(g, q, p) !== _1n) { + return false; } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. + /** + * Check q is large and probably prime (we mainly want to avoid small factors) */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - let status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; + const qSize = BigInt(bitLength(q)); + const _150n = BigInt(150); + if (qSize < _150n || !isProbablePrime(q, null, 32)) { + return false; } - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{rq + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const _2n = BigInt(2); + const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q + const rqx = q * r + x; + if (y !== modExp(g, rqx, p)) { + return false; } - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + return true; } +var dsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$2, + validateParams: validateParams$1, + verify: verify$2 +}); -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. +/** + * @fileoverview Asymmetric cryptography functions + * @module crypto/public_key */ -function deflateSetDictionary(strm, dictionary) { - let dictLength = dictionary.length; - - let s; - let str, n; - let wrap; - let avail; - let next; - let input; - let tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new Buf8(s.w_size); - arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH$1) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH$1 - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH$1 - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - -// String encode/decode helpers -try { - String.fromCharCode.apply(null, [ 0 ]); -} catch (__) { -} -try { - String.fromCharCode.apply(null, new Uint8Array(1)); -} catch (__) { -} +var publicKey = { + /** @see module:crypto/public_key/rsa */ + rsa: rsa, + /** @see module:crypto/public_key/elgamal */ + elgamal: elgamal, + /** @see module:crypto/public_key/elliptic */ + elliptic: elliptic, + /** @see module:crypto/public_key/dsa */ + dsa: dsa +}; -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -const _utf8len = new Buf8(256); -for (let q = 0; q < 256; q++) { - _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - +/** + * @fileoverview Provides functions for asymmetric signing and signature verification + * @module crypto/signature + */ -// convert string to array (typed, when possible) -function string2buf (str) { - let c, c2, m_pos, i, buf_len = 0; - const str_len = str.length; - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; +/** + * Parse signature in binary form to get the parameters. + * The returned values are only padded for EdDSA, since in the other cases their expected length + * depends on the key params, hence we delegate the padding to the signature verification function. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Uint8Array} signature - Data for which the signature was created + * @returns {Promise} True if signature is valid. + * @async + */ +function parseSignatureParams(algo, signature) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA signatures: + // - MPI of RSA signature value m**d mod n. + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + // The signature needs to be the same length as the public key modulo n. + // We pad s on signature verification, where we have access to n. + return { read, signatureParams: { s } }; } - - // allocate buffer - const buf = new Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | c >>> 6; - buf[i++] = 0x80 | c & 0x3f; - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | c >>> 12; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } else { - /* four bytes */ - buf[i++] = 0xf0 | c >>> 18; - buf[i++] = 0x80 | c >>> 12 & 0x3f; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } + // Algorithm-Specific Fields for DSA or ECDSA signatures: + // - MPI of DSA or ECDSA value r. + // - MPI of DSA or ECDSA value s. + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + { + // If the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; } - - return buf; -} - - -// Convert binary string (typed, when possible) -function binstring2buf (str) { - const buf = new Buf8(str.length); - for (let i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); + // Algorithm-Specific Fields for legacy EdDSA signatures: + // - MPI of an EC point r. + // - EdDSA value s, in MPI, in the little endian representation + case enums.publicKey.eddsaLegacy: { + // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature + // verification: if the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for Ed25519 signatures: + // - 64 octets of the native signature + // Algorithm-Specific Fields for Ed448 signatures: + // - 114 octets of the native signature + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo); + const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length; + return { read, signatureParams: { RS } }; } - return buf; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class ZStream { - constructor() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } -} - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ + default: + throw new UnsupportedError('Unknown signature algorithm.'); + } +} /** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} signature - Named algorithm-specific signature parameters + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Data for which the signature was created + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} True if signature is valid. + * @async + */ +async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto + return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); + } + case enums.publicKey.dsa: { + const { g, p, q, y } = publicParams; + const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers + return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); + } + case enums.publicKey.ecdsa: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // padding needed for webcrypto + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values: + // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); + } +} /** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ - -class Deflate { - constructor(options) { - this.options = { - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - ...(options || {}) - }; - - const opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters + * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters + * @param {Uint8Array} data - Data to be signed + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} Signature Object containing named signature parameters. + * @async + */ +async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { + if (!publicKeyParams || !privateKeyParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); + return { s }; } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; + case enums.publicKey.dsa: { + const { g, p, q } = publicKeyParams; + const { x } = privateKeyParams; + return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); + case enums.publicKey.elgamal: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + case enums.publicKey.ecdsa: { + const { oid, Q } = publicKeyParams; + const { d } = privateKeyParams; + return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); } - - if (opt.header) { - deflateSetHeader(this.strm, opt.header); + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); } + default: + throw new Error('Unknown signature algorithm.'); + } +} - if (opt.dictionary) { - let dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } +var signature = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseSignatureParams: parseSignatureParams, + sign: sign$1, + verify: verify$1 +}); - status = deflateSetDictionary(this.strm, dict); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (status !== Z_OK) { - throw new Error(msg[status]); - } - this._dict_set = true; +class ECDHSymmetricKey { + constructor(data) { + if (data) { + this.data = data; } } /** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize } } = this; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = string2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); + * Read an ECDHSymmetricKey from an Uint8Array: + * - 1 octect for the length `l` + * - `l` octects of encoded session key data + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + if (bytes.length >= 1) { + const length = bytes[0]; + if (bytes.length >= 1 + length) { + this.data = bytes.subarray(1, 1 + length); + return 1 + this.data.length; } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; } - - return true; - }; - /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; + throw new Error('Invalid symmetric key'); + } /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); + } } -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral // -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. // -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. // -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -const BAD = 30; /* got a data error -- remain here until reset */ -const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let _out; /* local strm.output */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; - - - - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - const input = strm.input; - const last = _in + (strm.avail_in - 5); - _out = strm.next_out; - const output = strm.output; - const beg = _out - (start - strm.avail_out); - const end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - const dmax = state.dmax; - //#endif - const wsize = state.wsize; - const whave = state.whave; - const wnext = state.wnext; - const s_window = state.window; - hold = state.hold; - bits = state.bits; - const lcode = state.lencode; - const dcode = state.distcode; - const lmask = (1 << state.lenbits) - 1; - const dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & (1 << op) - 1; - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & (1 << op) - 1; - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dodist; - } else { - strm.msg = "invalid distance code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dolen; - } else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } else { - strm.msg = "invalid literal/length code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); - strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); - state.hold = hold; - state.bits = bits; - return; -} - -const MAXBITS = 15; -const ENOUGH_LENS = 852; -const ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -const CODES = 0; -const LENS = 1; -const DISTS = 2; - -const lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -const lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -const dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -const dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // var shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { - break; - } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { - break; - } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } +/** + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @module type/kdf_params + * @private + */ - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } +class KDFParams { + /** + * @param {enums.hash} hash - Hash algorithm + * @param {enums.symmetric} cipher - Symmetric algorithm + */ + constructor(data) { + if (data) { + const { hash, cipher } = data; + this.hash = hash; + this.cipher = cipher; + } else { + this.hash = null; + this.cipher = null; } + } - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - const mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << len - drop; - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << len - 1; - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { - break; - } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { - break; - } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = root << 24 | curr << 16 | next - table_index |0; - } + /** + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input - Where to read the KDFParams from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new UnsupportedError('Cannot read KDFParams'); } + this.hash = input[2]; + this.cipher = input[3]; + return 4; + } - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = len - drop << 24 | 64 << 16 |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -} - -const CODES$1 = 0; -const LENS$1 = 1; -const DISTS$1 = 2; - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -const HEAD = 1; /* i: waiting for magic header */ -const FLAGS = 2; /* i: waiting for method and flags (gzip) */ -const TIME = 3; /* i: waiting for modification time (gzip) */ -const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -const EXLEN = 5; /* i: waiting for extra length (gzip) */ -const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -const NAME = 7; /* i: waiting for end of file name (gzip) */ -const COMMENT = 8; /* i: waiting for end of comment (gzip) */ -const HCRC = 9; /* i: waiting for header crc (gzip) */ -const DICTID = 10; /* i: waiting for dictionary check value */ -const DICT = 11; /* waiting for inflateSetDictionary() call */ -const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ -const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -const STORED = 14; /* i: waiting for stored size (length and complement) */ -const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -const COPY = 16; /* i/o: waiting for input or output to copy stored block */ -const TABLE = 17; /* i: waiting for dynamic block table lengths */ -const LENLENS = 18; /* i: waiting for code length code lengths */ -const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -const LEN_ = 20; /* i: same as LEN below, but only first time in */ -const LEN = 21; /* i: waiting for length/lit/eob code */ -const LENEXT = 22; /* i: waiting for length extra bits */ -const DIST = 23; /* i: waiting for distance code */ -const DISTEXT = 24; /* i: waiting for distance extra bits */ -const MATCH = 25; /* o: waiting for output space to copy string */ -const LIT = 26; /* o: waiting for output space to write literal */ -const CHECK = 27; /* i: waiting for 32-bit check value */ -const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -const DONE = 29; /* finished check, done -- remain here until reset */ -const BAD$1 = 30; /* got a data error -- remain here until reset */ -//const MEM = 31; /* got an inflate() memory error -- remain here until reset */ -const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -const ENOUGH_LENS$1 = 852; -const ENOUGH_DISTS$1 = 592; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -class InflateState { - constructor() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Buf16(320); /* temporary storage for code lengths */ - this.work = new Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ + /** + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value + */ + write() { + return new Uint8Array([3, 1, this.hash, this.cipher]); } } -function inflateResetKeep(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); - state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); +/** + * Encoded symmetric key for x25519 and x448 + * The payload format varies for v3 and v6 PKESK: + * the former includes an algorithm byte preceeding the encrypted session key. + * + * @module type/x25519x448_symkey + */ - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} -function inflateReset(strm) { - let state; +class ECDHXSymmetricKey { + static fromObject({ wrappedKey, algorithm }) { + const instance = new ECDHXSymmetricKey(); + instance.wrappedKey = wrappedKey; + instance.algorithm = algorithm; + return instance; + } - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); + /** + * - 1 octect for the length `l` + * - `l` octects of encoded session key data (with optional leading algorithm byte) + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + let read = 0; + let followLength = bytes[read++]; + this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even + followLength -= followLength % 2; + this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength; + } + /** + * Write an MontgomerySymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([ + this.algorithm ? + new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : + new Uint8Array([this.wrappedKey.length]), + this.wrappedKey + ]); + } } -function inflateReset2(strm, windowBits) { - let wrap; - let state; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; +/** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} keyAlgo - Public key algorithm + * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only) + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Session key data to be encrypted + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @returns {Promise} Encrypted session key parameters. + * @async + */ +async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const { n, e } = publicParams; + const c = await publicKey.rsa.encrypt(data, n, e); + return { c }; + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + return publicKey.elgamal.encrypt(data, p, g, y); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicParams; + const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( + oid, kdfParams, data, Q, fingerprint); + return { V, C: new ECDHSymmetricKey(C) }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + if (symmetricAlgo && !util.isAES(symmetricAlgo)) { + // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 + throw new Error('X25519 and X448 keys can only encrypt AES session keys'); + } + const { A } = publicParams; + const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( + keyAlgo, data, A); + const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); + return { ephemeralPublicKey, C }; } + default: + return []; } +} - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; +/** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Object} publicKeyParams - Algorithm-specific public key parameters + * @param {Object} privateKeyParams - Algorithm-specific private key parameters + * @param {Object} sessionKeyParams - Encrypted session key parameters + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing + * (needed for constant-time processing in RSA and ElGamal) + * @returns {Promise} Decrypted data. + * @throws {Error} on sensitive decryption error, unless `randomPayload` is given + * @async + */ +async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: { + const { c } = sessionKeyParams; + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); + } + case enums.publicKey.elgamal: { + const { c1, c2 } = sessionKeyParams; + const p = publicKeyParams.p; + const x = privateKeyParams.x; + return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicKeyParams; + const { d } = privateKeyParams; + const { V, C } = sessionKeyParams; + return publicKey.elliptic.ecdh.decrypt( + oid, kdfParams, V, C.data, Q, d, fingerprint); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicKeyParams; + const { k } = privateKeyParams; + const { ephemeralPublicKey, C } = sessionKeyParams; + if (C.algorithm !== null && !util.isAES(C.algorithm)) { + throw new Error('AES session key expected'); + } + return publicKey.elliptic.ecdhX.decrypt( + algo, ephemeralPublicKey, C.wrappedKey, A, k); + } + default: + throw new Error('Unknown public key encryption algorithm.'); } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); } -function inflateInit2(strm, windowBits) { - let ret; - let state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; +/** + * Parse public key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. + */ +function parsePublicKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; + const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; + return { read, publicParams: { n, e } }; + } + case enums.publicKey.dsa: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, q, g, y } }; + } + case enums.publicKey.elgamal: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, g, y } }; + } + case enums.publicKey.ecdsa: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.eddsaLegacy: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + if (oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + Q = util.leftPad(Q, 33); + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.ecdh: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); + return { read: read, publicParams: { oid, Q, kdfParams } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length; + return { read, publicParams: { A } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - return ret; } - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. +/** + * Parse private key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @param {Object} publicParams - (ECC only) public params, needed to format some private params + * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. */ -let virgin = true; - -let lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - let sym; - - lenfix = new Buf32(512); - distfix = new Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; +function parsePrivateKeyParams(algo, bytes, publicParams) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; + return { read, privateParams: { d, p, q, u } }; + } + case enums.publicKey.dsa: + case enums.publicKey.elgamal: { + const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; + return { read, privateParams: { x } }; + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + d = util.leftPad(d, payloadSize); + return { read, privateParams: { d } }; + } + case enums.publicKey.eddsaLegacy: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; + seed = util.leftPad(seed, payloadSize); + return { read, privateParams: { seed } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const payloadSize = getCurvePayloadSize(algo); + const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length; + return { read, privateParams: { seed } }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const payloadSize = getCurvePayloadSize(algo); + const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length; + return { read, privateParams: { k } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; } +/** Returns the types comprising the encrypted session key of an algorithm + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {Object} The session key parameters referenced by name. + */ +function parseEncSessionKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const c = util.readMPI(bytes.subarray(read)); + return { c }; + } -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - let dist; - const state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case enums.publicKey.elgamal: { + const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; + const c2 = util.readMPI(bytes.subarray(read)); + return { c1, c2 }; } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case enums.publicKey.ecdh: { + const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; + const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); + return { V, C }; + } + // Algorithm-Specific Fields for X25519 or X448 encrypted session keys: + // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448). + // - A one-octet size of the following fields. + // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). + // - The encrypted session key. + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const pointSize = getCurvePayloadSize(algo); + const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length; + const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); + return { ephemeralPublicKey, C }; } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - return 0; } -function inflate(strm, flush) { - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ - let opts; - - let n; // temporary var for NEED_BITS - - const order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD$1; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD$1; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE$1; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD$1; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE$1; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE$1; - /* falls through */ - case TYPE$1: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD$1; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD$1; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE$1; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD$1; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD$1) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD$1; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD$1; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE$1) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE$1; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); +/** + * Convert params to MPI and serializes them in the proper order + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} params - The key parameters indexed by name + * @returns {Uint8Array} The array containing the MPIs. + */ +function serializeParams(algo, params) { + // Some algorithms do not rely on MPIs to store the binary params + const algosWithNativeRepresentation = new Set([ + enums.publicKey.ed25519, + enums.publicKey.x25519, + enums.publicKey.ed448, + enums.publicKey.x448 + ]); + const orderedParams = Object.keys(params).map(name => { + const param = params[name]; + if (!util.isUint8Array(param)) return param.write(); + return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); + }); + return util.concatUint8Array(orderedParams); +} - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); +/** + * Generate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Integer} bits - Bit length for RSA keys + * @param {module:type/oid} oid - Object identifier for ECC keys + * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. + * @async + */ +function generateParams(algo, bits, oid) { + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ + privateParams: { d, p, q, u }, + publicParams: { n, e } + })); + case enums.publicKey.ecdsa: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { d: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { seed: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.ecdh: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ + privateParams: { d: secret }, + publicParams: { + oid: new OID(oid), + Q, + kdfParams: new KDFParams({ hash, cipher }) } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD$1: - ret = Z_DATA_ERROR; - break inf_leave; - // case MEM: - // return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE$1 ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; + })); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ + privateParams: { seed }, + publicParams: { A } + })); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ + privateParams: { k }, + publicParams: { A } + })); + case enums.publicKey.dsa: + case enums.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + default: + throw new Error('Unknown public key algorithm.'); } - return ret; } -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; +/** + * Validate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Object} privateParams - Algorithm-specific private key parameters + * @returns {Promise} Whether the parameters are valid. + * @async + */ +async function validateParams(algo, publicParams, privateParams) { + if (!publicParams || !privateParams) { + throw new Error('Missing key parameters'); } - - const state = strm.state; - if (state.window) { - state.window = null; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const { d, p, q, u } = privateParams; + return publicKey.rsa.validateParams(n, e, d, p, q, u); + } + case enums.publicKey.dsa: { + const { p, q, g, y } = publicParams; + const { x } = privateParams; + return publicKey.dsa.validateParams(p, q, g, y, x); + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + const { x } = privateParams; + return publicKey.elgamal.validateParams(p, g, y, x); + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; + const { oid, Q } = publicParams; + const { d } = privateParams; + return algoModule.validateParams(oid, Q, d); + } + case enums.publicKey.eddsaLegacy: { + const { Q, oid } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsa.validateParams(algo, A, seed); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicParams; + const { k } = privateParams; + return publicKey.elliptic.ecdhX.validateParams(algo, A, k); + } + default: + throw new Error('Unknown public key algorithm.'); } - strm.state = null; - return Z_OK; } -function inflateGetHeader(strm, head) { - let state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; +/** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + * @async + */ +async function getPrefixRandom(algo) { + const { blockSize } = getCipherParams(algo); + const prefixrandom = await getRandomBytes(blockSize); + const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + return util.concat([prefixrandom, repeat]); } -function inflateSetDictionary(strm, dictionary) { - const dictLength = dictionary.length; +/** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key. + */ +function generateSessionKey$1(algo) { + const { keySize } = getCipherParams(algo); + return getRandomBytes(keySize); +} - let state; - let dictid; +/** + * Get implementation of the given AEAD mode + * @param {enums.aead} algo + * @returns {Object} + * @throws {Error} on invalid algo + */ +function getAEADMode(algo) { + const algoName = enums.read(enums.aead, algo); + return mode[algoName]; +} - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; +/** + * Check whether the given curve OID is supported + * @param {module:type/oid} oid - EC object identifier + * @throws {UnsupportedError} if curve is not supported + */ +function checkSupportedCurve(oid) { + try { + oid.getName(); + } catch (e) { + throw new UnsupportedError('Unknown curve OID'); + } +} - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; +/** + * Get encoded secret size for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getCurvePayloadSize(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: + case enums.publicKey.eddsaLegacy: + return new publicKey.elliptic.CurveWithOID(oid).payloadSize; + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPayloadSize(algo); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.getPayloadSize(algo); + default: + throw new Error('Unknown elliptic algo'); } +} - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } +/** + * Get preferred signing hash algo for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getPreferredCurveHashAlgo(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.getPreferredHashAlgo(oid); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); + default: + throw new Error('Unknown elliptic signing algo'); } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - updatewindow(strm, dictionary, dictLength, dictLength); - // if (ret) { - // state.mode = MEM; - // return Z_MEM_ERROR; - // } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; } -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ +var crypto$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + generateParams: generateParams, + generateSessionKey: generateSessionKey$1, + getAEADMode: getAEADMode, + getCipherParams: getCipherParams, + getCurvePayloadSize: getCurvePayloadSize, + getPreferredCurveHashAlgo: getPreferredCurveHashAlgo, + getPrefixRandom: getPrefixRandom, + parseEncSessionKeyParams: parseEncSessionKeyParams, + parsePrivateKeyParams: parsePrivateKeyParams, + parsePublicKeyParams: parsePublicKeyParams, + publicKeyDecrypt: publicKeyDecrypt, + publicKeyEncrypt: publicKeyEncrypt, + serializeParams: serializeParams, + validateParams: validateParams +}); -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class GZheader { - constructor() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications +/** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; - } -} +// TODO move cfb and gcm to cipher +const mod = { + /** @see module:crypto/cipher */ + cipher: cipher, + /** @see module:crypto/hash */ + hash: hash, + /** @see module:crypto/mode */ + mode: mode, + /** @see module:crypto/public_key */ + publicKey: publicKey, + /** @see module:crypto/signature */ + signature: signature, + /** @see module:crypto/random */ + random: random, + /** @see module:crypto/pkcs1 */ + pkcs1: pkcs1, + /** @see module:crypto/pkcs5 */ + pkcs5: pkcs5, + /** @see module:crypto/aes_kw */ + aesKW: aesKW +}; -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ +Object.assign(mod, crypto$1); -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ +const ARGON2_TYPE = 0x02; // id +const ARGON2_VERSION = 0x13; +const ARGON2_SALT_SIZE = 16; -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ +class Argon2OutOfMemoryError extends Error { + constructor(...params) { + super(...params); -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Argon2OutOfMemoryError); + } -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ + this.name = 'Argon2OutOfMemoryError'; + } +} +// cache argon wasm module +let loadArgonWasmModule; +let argon2Promise; +// reload wasm module above this treshold, to deallocated used memory +const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -class Inflate { - constructor(options) { - this.options = { - chunkSize: 16384, - windowBits: 0, - ...(options || {}) - }; +class Argon2S2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params; - const opt = this.options; + this.type = 'argon2'; + /** + * 16 bytes of salt + * @type {Uint8Array} + */ + this.salt = null; + /** + * number of passes + * @type {Integer} + */ + this.t = passes; + /** + * degree of parallelism (lanes) + * @type {Integer} + */ + this.p = parallelism; + /** + * exponent indicating memory size + * @type {Integer} + */ + this.encodedM = memoryExponent; + } - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } + generateSalt() { + this.salt = mod.random.getRandomBytes(ARGON2_SALT_SIZE); + } - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } + /** + * Parsing function for argon2 string-to-key specifier. + * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } + this.salt = bytes.subarray(i, i + 16); + i += 16; - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data + this.t = bytes[i++]; + this.p = bytes[i++]; + this.encodedM = bytes[i++]; // memory size exponent, one-octect - this.strm = new ZStream(); - this.strm.avail_out = 0; + return i; + } - let status = inflateInit2( - this.strm, - opt.windowBits - ); + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + const arr = [ + new Uint8Array([enums.write(enums.s2k, this.type)]), + this.salt, + new Uint8Array([this.t, this.p, this.encodedM]) + ]; - if (status !== Z_OK) { - throw new Error(msg[status]); - } + return util.concatUint8Array(arr); + } - this.header = new GZheader(); + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to `keySize` + * @throws {Argon2OutOfMemoryError|Errors} + * @async + */ + async produceKey(passphrase, keySize) { + const decodedM = 2 << (this.encodedM - 1); - inflateGetHeader(this.strm, this.header); + try { + // on first load, the argon2 lib is imported and the WASM module is initialized. + // the two steps need to be atomic to avoid race conditions causing multiple wasm modules + // being loaded when `argon2Promise` is not initialized. + loadArgonWasmModule = loadArgonWasmModule || (await import('./argon2id.mjs')).default; + argon2Promise = argon2Promise || loadArgonWasmModule(); + + // important to keep local ref to argon2 in case the module is reloaded by another instance + const argon2 = await argon2Promise; + + const passwordBytes = util.encodeUTF8(passphrase); + const hash = argon2({ + version: ARGON2_VERSION, + type: ARGON2_TYPE, + password: passwordBytes, + salt: this.salt, + tagLength: keySize, + memorySize: decodedM, + parallelism: this.p, + passes: this.t + }); - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - opt.dictionary = new Uint8Array(opt.dictionary); + // a lot of memory was used, reload to deallocate + if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(msg[status]); - } + return hash; + } catch (e) { + if (e.message && ( + e.message.includes('Unable to grow instance memory') || // Chrome + e.message.includes('failed to grow memory') || // Firefox + e.message.includes('WebAssembly.Memory.grow') || // Safari + e.message.includes('Out of memory') // Safari iOS + )) { + throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2'); + } else { + throw e; } } } - /** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize, dictionary } } = this; - let status, _mode; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - let allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = binstring2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } +} - strm.next_in = 0; - strm.avail_in = strm.input.length; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = inflate(strm, Z_NO_FLUSH); /* no bad return value */ +class GenericS2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(s2kType, config$1 = config) { + /** + * Hash function identifier, or 0 for gnu-dummy keys + * @type {module:enums.hash | 0} + */ + this.algorithm = enums.hash.sha256; + /** + * enums.s2k identifier or 'gnu-dummy' + * @type {String} + */ + this.type = enums.read(enums.s2k, s2kType); + /** @type {Integer} */ + this.c = config$1.s2kIterationCountByte; + /** Eight bytes of salt in a binary string. + * @type {Uint8Array} + */ + this.salt = null; + } - if (status === Z_NEED_DICT && dictionary) { - status = inflateSetDictionary(this.strm, dictionary); - } + generateSalt() { + switch (this.type) { + case 'salted': + case 'iterated': + this.salt = mod.random.getRandomBytes(8); + } + } - if (status === Z_BUF_ERROR && allowBufError === true) { - status = Z_OK; - allowBufError = false; - } + getCount() { + // Exponent bias, defined in RFC4880 + const expbias = 6; - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } + return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); + } - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } + /** + * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param {Uint8Array} bytes - Payload of string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; + this.algorithm = bytes[i++]; - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } + switch (this.type) { + case 'simple': + break; - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + case 'salted': + this.salt = bytes.subarray(i, i + 8); + i += 8; + break; - if (status === Z_STREAM_END) { - _mode = Z_FINISH; - } + case 'iterated': + this.salt = bytes.subarray(i, i + 8); + i += 8; - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } + // Octet 10: count, a one-octet, coded value + this.c = bytes[i++]; + break; - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; + case 'gnu': + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { + i += 3; // GNU + const gnuExtType = 1000 + bytes[i++]; + if (gnuExtType === 1001) { + this.type = 'gnu-dummy'; + // GnuPG extension mode 1001 -- don't write secret key at all + } else { + throw new UnsupportedError('Unknown s2k gnu protection mode.'); + } + } else { + throw new UnsupportedError('Unknown s2k type.'); + } + break; + + default: + throw new UnsupportedError('Unknown s2k type.'); // unreachable } - return true; - }; + return i; + } /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + if (this.type === 'gnu-dummy') { + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); + } + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; + switch (this.type) { + case 'simple': + break; + case 'salted': + arr.push(this.salt); + break; + case 'iterated': + arr.push(this.salt); + arr.push(new Uint8Array([this.c])); + break; + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + return util.concatUint8Array(arr); + } /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -/* -node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - -Copyright (C) 2012 Eli Skeggs - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to. + * hashAlgorithm hash length + * @async + */ + async produceKey(passphrase, numBytes) { + passphrase = util.encodeUTF8(passphrase); -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html + const arr = []; + let rlength = 0; -Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). + let prefixlen = 0; + while (rlength < numBytes) { + let toHash; + switch (this.type) { + case 'simple': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); + break; + case 'salted': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); + break; + case 'iterated': { + const data = util.concatUint8Array([this.salt, passphrase]); + let datalen = data.length; + const count = Math.max(this.getCount(), datalen); + toHash = new Uint8Array(prefixlen + count); + toHash.set(data, prefixlen); + for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { + toHash.copyWithin(pos, prefixlen, pos); + } + break; + } + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + const result = await mod.hash.digest(this.algorithm, toHash); + arr.push(result); + rlength += result.length; + prefixlen++; + } -Based on micro-bunzip by Rob Landley (rob@landley.net). + return util.concatUint8Array(arr).subarray(0, numBytes); + } +} -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ +const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]); -var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; +/** + * Instantiate a new S2K instance of the given type + * @param {module:enums.s2k} type + * @oaram {Object} [config] + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromType(type, config$1 = config) { + switch (type) { + case enums.s2k.argon2: + return new Argon2S2K(config$1); + case enums.s2k.iterated: + case enums.s2k.gnu: + case enums.s2k.salted: + case enums.s2k.simple: + return new GenericS2K(type, config$1); + default: + throw new UnsupportedError('Unsupported S2K type'); + } +} -// offset in bytes -var BitReader = function(stream) { - this.stream = stream; - this.bitOffset = 0; - this.curByte = 0; - this.hasByte = false; +/** + * Instantiate a new S2K instance based on the config settings + * @oaram {Object} config + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromConfig(config) { + const { s2kType } = config; + + if (!allowedS2KTypesForEncryption.has(s2kType)) { + throw new Error('The provided `config.s2kType` value is not allowed'); + } + + return newS2KFromType(s2kType, config); +} + +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +// see fleb note +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new u32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return [b, r]; }; - -BitReader.prototype._ensureByte = function() { - if (!this.hasByte) { - this.curByte = this.stream.readByte(); - this.hasByte = true; - } +var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >>> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; }; - -// reads bits from the buffer -BitReader.prototype.read = function(bits) { - var result = 0; - while (bits > 0) { - this._ensureByte(); - var remaining = 8 - this.bitOffset; - // if we're in a byte - if (bits >= remaining) { - result <<= remaining; - result |= BITMASK[remaining] & this.curByte; - this.hasByte = false; - this.bitOffset = 0; - bits -= remaining; - } else { - result <<= bits; - var shift = remaining - bits; - result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; - this.bitOffset += bits; - bits = 0; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, buf, st) { + // source length + var sl = dat.length; + if (!sl || (st && st.f && !st.l)) + return buf || new u8(0); + // have to estimate size + var noBuf = !buf || st; + // no state + var noSt = !st || st.i; + if (!st) + st = {}; + // Assumes roughly 33% compression ratio average + if (!buf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (noBuf) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >>> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17; + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + d[o + 2] |= v >>> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return [et, 0]; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return [v, 1]; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; } - } - return result; + return [new u8(tr), mbt]; }; - -// seek to an arbitrary point in the buffer (expressed in bits) -BitReader.prototype.seek = function(pos) { - var n_bit = pos % 8; - var n_byte = (pos - n_bit) / 8; - this.bitOffset = n_bit; - this.stream.seek(n_byte); - this.hasByte = false; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return [cl.subarray(0, cli), s]; }; - -// reads 6 bytes worth of data using the read method -BitReader.prototype.pi = function() { - var buf = new Uint8Array(6), i; - for (i = 0; i < buf.length; i++) { - buf[i] = this.read(8); - } - return bufToHex(buf); +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; }; - -function bufToHex(buf) { - return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); -} - -var bitreader = BitReader; - -/* very simple input/output stream interface */ -var Stream = function() { +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >>> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; }; - -// input streams ////////////// -/** Returns the next byte, or -1 for EOF. */ -Stream.prototype.readByte = function() { - throw new Error("abstract method readByte() not implemented"); +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; + var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; + var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; + var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + lcfreq[lclt[i] & 31]++; + for (var i = 0; i < lcdt.length; ++i) + lcfreq[lcdt[i] & 31]++; + var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); + if (flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + if (syms[i] > 255) { + var len = (syms[i] >>> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; + var dst = syms[i] & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; }; -/** Attempts to fill the buffer; returns number of bytes read, or - * -1 for EOF. */ -Stream.prototype.read = function(buffer, bufOffset, length) { - var bytesRead = 0; - while (bytesRead < length) { - var c = this.readByte(); - if (c < 0) { // EOF - return (bytesRead===0) ? -1 : bytesRead; - } - buffer[bufOffset++] = c; - bytesRead++; - } - return bytesRead; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, lst) { + var s = dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var pos = 0; + if (!lvl || s < 8) { + for (var i = 0; i <= s; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[pos >> 3] = lst; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + } + else { + var opt = deo[lvl - 1]; + var n = opt >>> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = new u16(32768), head = new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new u32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx bitpos + var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; + for (; i < s; ++i) { + // hash value + // deopt when i > s - 3 - at end, deopt acceptable + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && rem > 423) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = (i - dif + j + 32768) & 32767; + var pti = prev[ti]; + var cd = (ti - pti + 32768) & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += (imod - pimod + 32768) & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one Uint32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + // this is the easiest way to avoid needing to maintain state + if (!lst && pos & 7) + pos = wfblk(w, pos + 1, et); + } + return slc(o, 0, pre + shft(pos) + post); }; -Stream.prototype.seek = function(new_pos) { - throw new Error("abstract method seek() not implemented"); +// Alder32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); + } + }; }; - -// output streams /////////// -Stream.prototype.writeByte = function(_byte) { - throw new Error("abstract method readByte() not implemented"); +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st); }; -Stream.prototype.write = function(buffer, bufOffset, length) { - var i; - for (i=0; i>>= 8; }; -Stream.prototype.flush = function() { +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); }; - -var stream = Stream; - -/* CRC32, used in Bzip2 implementation. - * This is a port of CRC32.java from the jbzip2 implementation at - * https://code.google.com/p/jbzip2 - * which is: - * Copyright (c) 2011 Matthew Francis - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * This JavaScript implementation is: - * Copyright (c) 2013 C. Scott Ananian - * with the same licensing terms as Matthew Francis' original implementation. - */ -var crc32$1 = (function() { - - /** - * A static CRC lookup table - */ - var crc32Lookup = new Uint32Array([ - 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, - 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, - 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, - 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, - 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, - 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, - 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, - 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, - 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, - 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, - 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, - 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, - 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, - 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, - 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, - 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, - 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, - 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, - 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, - 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, - 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, - 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, - 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, - 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, - 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, - 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, - 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, - 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, - 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, - 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, - 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, - 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 - ]); - - var CRC32 = function() { +// zlib footer: -4 to -0 is Adler32 +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (!cb && typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, !f), f); + }; /** - * The current CRC + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk */ - var crc = 0xffffffff; - + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.d = final; + this.p(chunk, final || false); + }; + return Deflate; +}()); +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { /** - * @return The current CRC + * Creates an inflation stream + * @param cb The callback to call whenever data is inflated */ - this.getCRC = function() { - return (~crc) >>> 0; // return an unsigned value + function Inflate(cb) { + this.s = {}; + this.p = new u8(0); + this.ondata = cb; + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + var l = this.p.length; + var n = new u8(l + c.length); + n.set(this.p), n.set(c, l), this.p = n; + }; + Inflate.prototype.c = function (final) { + this.d = this.s.i = final || false; + var bts = this.s.b; + var dt = inflt(this.p, this.o, this.s); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; }; - /** - * Update the CRC with a single byte - * @param value The value to update the CRC with + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk */ - this.updateCRC = function(value) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); }; - + return Inflate; +}()); +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } /** - * Update the CRC with a sequence of identical bytes - * @param value The value to update the CRC with - * @param count The number of bytes + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk */ - this.updateCRCRun = function(value, count) { - while (count-- > 0) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - } + Zlib.prototype.push = function (chunk, final) { + Deflate.prototype.push.call(this, chunk, final); }; - }; - return CRC32; -})(); - -/* -seek-bzip - a pure-javascript module for seeking within bzip2 data - -Copyright (C) 2013 C. Scott Ananian -Copyright (C) 2012 Eli Skeggs -Copyright (C) 2011 Kevin Kwok - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from node-bzip, copyright 2012 Eli Skeggs. -Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - - - - - -var MAX_HUFCODE_BITS = 20; -var MAX_SYMBOLS = 258; -var SYMBOL_RUNA = 0; -var SYMBOL_RUNB = 1; -var MIN_GROUPS = 2; -var MAX_GROUPS = 6; -var GROUP_SIZE = 50; - -var WHOLEPI = "314159265359"; -var SQRTPI = "177245385090"; - -var mtf = function(array, index) { - var src = array[index], i; - for (i = index; i > 0; i--) { - array[i] = array[i-1]; - } - array[0] = src; - return src; -}; - -var Err = { - OK: 0, - LAST_BLOCK: -1, - NOT_BZIP_DATA: -2, - UNEXPECTED_INPUT_EOF: -3, - UNEXPECTED_OUTPUT_EOF: -4, - DATA_ERROR: -5, - OUT_OF_MEMORY: -6, - OBSOLETE_INPUT: -7, - END_OF_BLOCK: -8 -}; -var ErrorMessages = {}; -ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; -ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; -ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; -ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; -ErrorMessages[Err.DATA_ERROR] = "Data error"; -ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; -ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - -var _throw = function(status, optDetail) { - var msg = ErrorMessages[status] || 'unknown error'; - if (optDetail) { msg += ': '+optDetail; } - var e = new TypeError(msg); - e.errorCode = status; - throw e; -}; - -var Bunzip = function(inputStream, outputStream) { - this.writePos = this.writeCurrent = this.writeCount = 0; - - this._start_bunzip(inputStream, outputStream); -}; -Bunzip.prototype._init_block = function() { - var moreBlocks = this._get_next_block(); - if ( !moreBlocks ) { - this.writeCount = -1; - return false; /* no more blocks */ - } - this.blockCRC = new crc32$1(); - return true; -}; -/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ -Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { - /* Ensure that file starts with "BZh['1'-'9']." */ - var buf = new Uint8Array(4); - if (inputStream.read(buf, 0, 4) !== 4 || - String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') - _throw(Err.NOT_BZIP_DATA, 'bad magic'); - - var level = buf[3] - 0x30; - if (level < 1 || level > 9) - _throw(Err.NOT_BZIP_DATA, 'level out of range'); - - this.reader = new bitreader(inputStream); - - /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of - uncompressed data. Allocate intermediate buffer for block. */ - this.dbufSize = 100000 * level; - this.nextoutput = 0; - this.outputStream = outputStream; - this.streamCRC = 0; -}; -Bunzip.prototype._get_next_block = function() { - var i, j, k; - var reader = this.reader; - // this is get_next_block() function from micro-bunzip: - /* Read in header signature and CRC, then validate signature. - (last block signature means CRC is for whole file, return now) */ - var h = reader.pi(); - if (h === SQRTPI) { // last block - return false; /* no more blocks */ - } - if (h !== WHOLEPI) - _throw(Err.NOT_BZIP_DATA); - this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) - this.streamCRC = (this.targetBlockCRC ^ - ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; - /* We can add support for blockRandomised if anybody complains. There was - some code for this in busybox 1.0.0-pre3, but nobody ever noticed that - it didn't actually work. */ - if (reader.read(1)) - _throw(Err.OBSOLETE_INPUT); - var origPointer = reader.read(24); - if (origPointer > this.dbufSize) - _throw(Err.DATA_ERROR, 'initial position out of bounds'); - /* mapping table: if some byte values are never used (encoding things - like ascii text), the compression code removes the gaps to have fewer - symbols to deal with, and writes a sparse bitfield indicating which - values were present. We make a translation table to convert the symbols - back to the corresponding bytes. */ - var t = reader.read(16); - var symToByte = new Uint8Array(256), symTotal = 0; - for (i = 0; i < 16; i++) { - if (t & (1 << (0xF - i))) { - var o = i * 16; - k = reader.read(16); - for (j = 0; j < 16; j++) - if (k & (1 << (0xF - j))) - symToByte[symTotal++] = o + j; - } - } - - /* How many different huffman coding groups does this block use? */ - var groupCount = reader.read(3); - if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) - _throw(Err.DATA_ERROR); - /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding - group. Read in the group selector list, which is stored as MTF encoded - bit runs. (MTF=Move To Front, as each value is used it's moved to the - start of the list.) */ - var nSelectors = reader.read(15); - if (nSelectors === 0) - _throw(Err.DATA_ERROR); - - var mtfSymbol = new Uint8Array(256); - for (i = 0; i < groupCount; i++) - mtfSymbol[i] = i; - - var selectors = new Uint8Array(nSelectors); // was 32768... - - for (i = 0; i < nSelectors; i++) { - /* Get next value */ - for (j = 0; reader.read(1); j++) - if (j >= groupCount) _throw(Err.DATA_ERROR); - /* Decode MTF to get the next selector */ - selectors[i] = mtf(mtfSymbol, j); - } - - /* Read the huffman coding tables for each group, which code for symTotal - literal symbols, plus two run symbols (RUNA, RUNB) */ - var symCount = symTotal + 2; - var groups = [], hufGroup; - for (j = 0; j < groupCount; j++) { - var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); - /* Read huffman code lengths for each symbol. They're stored in - a way similar to mtf; record a starting value for the first symbol, - and an offset from the previous value for everys symbol after that. */ - t = reader.read(5); // lengths - for (i = 0; i < symCount; i++) { - for (;;) { - if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); - /* If first bit is 0, stop. Else second bit indicates whether - to increment or decrement the value. */ - if(!reader.read(1)) - break; - if(!reader.read(1)) - t++; - else - t--; - } - length[i] = t; - } - - /* Find largest and smallest lengths in this group */ - var minLen, maxLen; - minLen = maxLen = length[0]; - for (i = 1; i < symCount; i++) { - if (length[i] > maxLen) - maxLen = length[i]; - else if (length[i] < minLen) - minLen = length[i]; - } - - /* Calculate permute[], base[], and limit[] tables from length[]. - * - * permute[] is the lookup table for converting huffman coded symbols - * into decoded symbols. base[] is the amount to subtract from the - * value of a huffman symbol of a given length when using permute[]. - * - * limit[] indicates the largest numerical value a symbol with a given - * number of bits can have. This is how the huffman codes can vary in - * length: each code with a value>limit[length] needs another bit. + Zlib.prototype.p = function (c, f) { + this.c.p(c); + var raw = dopt(c, this.o, this.v && 2, f && 4, !f); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + return Zlib; +}()); +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated */ - hufGroup = {}; - groups.push(hufGroup); - hufGroup.permute = new Uint16Array(MAX_SYMBOLS); - hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); - hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); - hufGroup.minLen = minLen; - hufGroup.maxLen = maxLen; - /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ - var pp = 0; - for (i = minLen; i <= maxLen; i++) { - temp[i] = hufGroup.limit[i] = 0; - for (t = 0; t < symCount; t++) - if (length[t] === i) - hufGroup.permute[pp++] = t; - } - /* Count symbols coded for at each bit length */ - for (i = 0; i < symCount; i++) - temp[length[i]]++; - /* Calculate limit[] (the largest symbol-coding value at each bit - * length, which is (previous limit<<1)+symbols at this level), and - * base[] (number of symbols to ignore at each bit length, which is - * limit minus the cumulative count of symbols coded for already). */ - pp = t = 0; - for (i = minLen; i < maxLen; i++) { - pp += temp[i]; - /* We read the largest possible symbol size and then unget bits - after determining how many we need, and those extra bits could - be set to anything. (They're noise from future symbols.) At - each level we're really only interested in the first few bits, - so here we set all the trailing to-be-ignored bits to 1 so they - don't affect the value>limit[length] comparison. */ - hufGroup.limit[i] = pp - 1; - pp <<= 1; - t += temp[i]; - hufGroup.base[i + 1] = pp - t; - } - hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ - hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; - hufGroup.base[minLen] = 0; - } - /* We've finished reading and digesting the block header. Now read this - block's huffman coded symbols from the file and undo the huffman coding - and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - - /* Initialize symbol occurrence counters and symbol Move To Front table */ - var byteCount = new Uint32Array(256); - for (i = 0; i < 256; i++) - mtfSymbol[i] = i; - /* Loop through compressed symbols. */ - var runPos = 0, dbufCount = 0, selector = 0, uc; - var dbuf = this.dbuf = new Uint32Array(this.dbufSize); - symCount = 0; - for (;;) { - /* Determine which huffman coding group to use. */ - if (!(symCount--)) { - symCount = GROUP_SIZE - 1; - if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } - hufGroup = groups[selectors[selector++]]; - } - /* Read next huffman-coded symbol. */ - i = hufGroup.minLen; - j = reader.read(i); - for (;;i++) { - if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } - if (j <= hufGroup.limit[i]) - break; - j = (j << 1) | reader.read(1); - } - /* Huffman decode value to get nextSym (with bounds checking) */ - j -= hufGroup.base[i]; - if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } - var nextSym = hufGroup.permute[j]; - /* We have now decoded the symbol, which indicates either a new literal - byte, or a repeated run of the most recent literal byte. First, - check if nextSym indicates a repeated run, and if so loop collecting - how many times to repeat the last literal. */ - if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { - /* If this is the start of a new run, zero out counter */ - if (!runPos){ - runPos = 1; - t = 0; - } - /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at - each bit position, add 1 or 2 instead. For example, - 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. - You can make any bit pattern that way using 1 less symbol than - the basic or 0/1 method (except all bits 0, which would use no - symbols, but a run of length 0 doesn't mean anything in this - context). Thus space is saved. */ - if (nextSym === SYMBOL_RUNA) - t += runPos; - else - t += 2 * runPos; - runPos <<= 1; - continue; - } - /* When we hit the first non-run symbol after a run, we now know - how many times to repeat the last literal, so append that many - copies to our buffer of decoded symbols (dbuf) now. (The last - literal used is the one at the head of the mtfSymbol array.) */ - if (runPos){ - runPos = 0; - if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } - uc = symToByte[mtfSymbol[0]]; - byteCount[uc] += t; - while (t--) - dbuf[dbufCount++] = uc; - } - /* Is this the terminating symbol? */ - if (nextSym > symTotal) - break; - /* At this point, nextSym indicates a new literal character. Subtract - one to get the position in the MTF array at which this literal is - currently to be found. (Note that the result can't be -1 or 0, - because 0 and 1 are RUNA and RUNB. But another instance of the - first symbol in the mtf array, position 0, would have been handled - as part of a run above. Therefore 1 unused mtf position minus - 2 non-literal nextSym values equals -1.) */ - if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } - i = nextSym - 1; - uc = mtf(mtfSymbol, i); - uc = symToByte[uc]; - /* We have our literal byte. Save it into dbuf. */ - byteCount[uc]++; - dbuf[dbufCount++] = uc; - } - /* At this point, we've read all the huffman-coded symbols (and repeated - runs) for this block from the input stream, and decoded them into the - intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. - Now undo the Burrows-Wheeler transform on dbuf. - See http://dogma.net/markn/articles/bwt/bwt.htm - */ - if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } - /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ - j = 0; - for (i = 0; i < 256; i++) { - k = j + byteCount[i]; - byteCount[i] = j; - j = k; - } - /* Figure out what order dbuf would be in if we sorted it. */ - for (i = 0; i < dbufCount; i++) { - uc = dbuf[i] & 0xff; - dbuf[byteCount[uc]] |= (i << 8); - byteCount[uc]++; - } - /* Decode first byte by hand to initialize "previous" byte. Note that it - doesn't get output, and if the first three characters are identical - it doesn't qualify as a run (hence writeRunCountdown=5). */ - var pos = 0, current = 0, run = 0; - if (dbufCount) { - pos = dbuf[origPointer]; - current = (pos & 0xff); - pos >>= 8; - run = -1; - } - this.writePos = pos; - this.writeCurrent = current; - this.writeCount = dbufCount; - this.writeRun = run; - - return true; /* more blocks to come */ -}; -/* Undo burrows-wheeler transform on intermediate buffer to produce output. - If start_bunzip was initialized with out_fd=-1, then up to len bytes of - data are written to outbuf. Return value is number of bytes written or - error (all errors are negative numbers). If out_fd!=-1, outbuf and len - are ignored, data is written to out_fd and return is RETVAL_OK or error. -*/ -Bunzip.prototype._read_bunzip = function(outputBuffer, len) { - var copies, previous, outbyte; - /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully - decoded, which results in this returning RETVAL_LAST_BLOCK, also - equal to -1... Confusing, I'm returning 0 here to indicate no - bytes written into the buffer */ - if (this.writeCount < 0) { return 0; } - var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; - var dbufCount = this.writeCount; this.outputsize; - var run = this.writeRun; - - while (dbufCount) { - dbufCount--; - previous = current; - pos = dbuf[pos]; - current = pos & 0xff; - pos >>= 8; - if (run++ === 3){ - copies = current; - outbyte = previous; - current = -1; - } else { - copies = 1; - outbyte = current; - } - this.blockCRC.updateCRCRun(outbyte, copies); - while (copies--) { - this.outputStream.writeByte(outbyte); - this.nextoutput++; - } - if (current != previous) - run = 0; - } - this.writeCount = dbufCount; - // check CRC - if (this.blockCRC.getCRC() !== this.targetBlockCRC) { - _throw(Err.DATA_ERROR, "Bad block CRC "+ - "(got "+this.blockCRC.getCRC().toString(16)+ - " expected "+this.targetBlockCRC.toString(16)+")"); - } - return this.nextoutput; -}; - -var coerceInputStream = function(input) { - if ('readByte' in input) { return input; } - var inputStream = new stream(); - inputStream.pos = 0; - inputStream.readByte = function() { return input[this.pos++]; }; - inputStream.seek = function(pos) { this.pos = pos; }; - inputStream.eof = function() { return this.pos >= input.length; }; - return inputStream; -}; -var coerceOutputStream = function(output) { - var outputStream = new stream(); - var resizeOk = true; - if (output) { - if (typeof(output)==='number') { - outputStream.buffer = new Uint8Array(output); - resizeOk = false; - } else if ('writeByte' in output) { - return output; - } else { - outputStream.buffer = output; - resizeOk = false; - } - } else { - outputStream.buffer = new Uint8Array(16384); - } - outputStream.pos = 0; - outputStream.writeByte = function(_byte) { - if (resizeOk && this.pos >= this.buffer.length) { - var newBuffer = new Uint8Array(this.buffer.length*2); - newBuffer.set(this.buffer); - this.buffer = newBuffer; + function Unzlib(cb) { + this.v = 1; + Inflate.call(this, cb); } - this.buffer[this.pos++] = _byte; - }; - outputStream.getBuffer = function() { - // trim buffer - if (this.pos !== this.buffer.length) { - if (!resizeOk) - throw new TypeError('outputsize does not match decoded input'); - var newBuffer = new Uint8Array(this.pos); - newBuffer.set(this.buffer.subarray(0, this.pos)); - this.buffer = newBuffer; - } - return this.buffer; - }; - outputStream._coerced = true; - return outputStream; -}; - -/* Static helper functions */ -// 'input' can be a stream or a buffer -// 'output' can be a stream or a buffer or a number (buffer size) -const decode$2 = function(input, output, multistream) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - - var bz = new Bunzip(inputStream, outputStream); - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - if (bz._init_block()) { - bz._read_bunzip(); - } else { - var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) - if (targetStreamCRC !== bz.streamCRC) { - _throw(Err.DATA_ERROR, "Bad stream CRC "+ - "(got "+bz.streamCRC.toString(16)+ - " expected "+targetStreamCRC.toString(16)+")"); - } - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - } else break; - } - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -const decodeBlock = function(input, pos, output) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - var bz = new Bunzip(inputStream, outputStream); - bz.reader.seek(pos); - /* Fill the decode buffer for the block */ - var moreBlocks = bz._get_next_block(); - if (moreBlocks) { - /* Init the CRC for writing */ - bz.blockCRC = new crc32$1(); - - /* Zero this so the current byte from before the seek is not written */ - bz.writeCopies = 0; - - /* Decompress the block and write to stdout */ - bz._read_bunzip(); - // XXX keep writing? - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -/* Reads bzip2 file from stream or buffer `input`, and invoke - * `callback(position, size)` once for each bzip2 block, - * where position gives the starting position (in *bits*) - * and size gives uncompressed size of the block (in *bytes*). */ -const table = function(input, callback, multistream) { - // make a stream from a buffer, if necessary - var inputStream = new stream(); - inputStream.delegate = coerceInputStream(input); - inputStream.pos = 0; - inputStream.readByte = function() { - this.pos++; - return this.delegate.readByte(); - }; - if (inputStream.delegate.eof) { - inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); - } - var outputStream = new stream(); - outputStream.pos = 0; - outputStream.writeByte = function() { this.pos++; }; - - var bz = new Bunzip(inputStream, outputStream); - var blockSize = bz.dbufSize; - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - - var position = inputStream.pos*8 + bz.reader.bitOffset; - if (bz.reader.hasByte) { position -= 8; } - - if (bz._init_block()) { - var start = outputStream.pos; - bz._read_bunzip(); - callback(position, outputStream.pos - start); - } else { - bz.reader.read(32); // (but we ignore the crc) - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - console.assert(bz.dbufSize === blockSize, - "shouldn't change block size within multistream file"); - } else break; - } - } -}; - -var lib = { - Bunzip, - Stream: stream, - Err, - decode: decode$2, - decodeBlock, - table -}; -var lib_4 = lib.decode; + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 2 && !final) + return; + this.p = this.p.subarray(2), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Implementation of the Literal Data Packet (Tag 11) @@ -23139,43 +12717,166 @@ class LiteralDataPacket { } /** - * Creates a Uint8Array representation of the packet, excluding the data - * - * @returns {Uint8Array} Uint8Array representation of the packet. + * Creates a Uint8Array representation of the packet, excluding the data + * + * @returns {Uint8Array} Uint8Array representation of the packet. + */ + writeHeader() { + const filename = util.encodeUTF8(this.filename); + const filename_length = new Uint8Array([filename.length]); + + const format = new Uint8Array([this.format]); + const date = util.writeDate(this.date); + + return util.concatUint8Array([format, filename_length, filename, date]); + } + + /** + * Creates a Uint8Array representation of the packet + * + * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. + */ + write() { + const header = this.writeHeader(); + const data = this.getBytes(); + + return util.concat([header, data]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ +class KeyID { + constructor() { + this.bytes = ''; + } + + /** + * Parsing method for a key id + * @param {Uint8Array} bytes - Input to read the key id from + */ + read(bytes) { + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); + return this.bytes.length; + } + + /** + * Serializes the Key ID + * @returns {Uint8Array} Key ID as a Uint8Array. + */ + write() { + return util.stringToUint8Array(this.bytes); + } + + /** + * Returns the Key ID represented as a hexadecimal string + * @returns {String} Key ID as a hexadecimal string. + */ + toHex() { + return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); + } + + /** + * Checks equality of Key ID's + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard + */ + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; + } + + /** + * Checks to see if the Key ID is unset + * @returns {Boolean} True if the Key ID is null. + */ + isNull() { + return this.bytes === ''; + } + + /** + * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) + * @returns {Boolean} True if this is a wildcard Key ID. */ - writeHeader() { - const filename = util.encodeUTF8(this.filename); - const filename_length = new Uint8Array([filename.length]); - - const format = new Uint8Array([this.format]); - const date = util.writeDate(this.date); + isWildcard() { + return /^0+$/.test(this.toHex()); + } - return util.concatUint8Array([format, filename_length, filename, date]); + static mapToHex(keyID) { + return keyID.toHex(); } - /** - * Creates a Uint8Array representation of the packet - * - * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. - */ - write() { - const header = this.writeHeader(); - const data = this.getBytes(); + static fromID(hex) { + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; + } - return util.concat([header, data]); + static wildcard() { + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; } } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. const verified = Symbol('verified'); +// A salt notation is used to randomize signatures. +// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks +// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170). +// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g. +// some chosen-prefix attacks. +// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt. +const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org'; + // GPG puts the Issuer and Signature subpackets in the unhashed area. // Tampering with those invalidates the signature, so we still trust them and parse them. // All other unhashed subpackets are ignored. const allowedUnhashedSubpackets = new Set([ - enums.signatureSubpacket.issuer, + enums.signatureSubpacket.issuerKeyID, enums.signatureSubpacket.issuerFingerprint, enums.signatureSubpacket.embeddedSignature ]); @@ -23204,7 +12905,9 @@ class SignaturePacket { this.signatureData = null; this.unhashedSubpackets = []; + this.unknownSubpackets = []; this.signedHashValue = null; + this.salt = null; this.created = null; this.signatureExpirationTime = null; @@ -23241,6 +12944,7 @@ class SignaturePacket { this.issuerKeyVersion = null; this.issuerFingerprint = null; this.preferredAEADAlgorithms = null; + this.preferredCipherSuites = null; this.revoked = null; this[verified] = null; @@ -23251,11 +12955,14 @@ class SignaturePacket { * @param {String} bytes - Payload of a tag 2 packet * @returns {SignaturePacket} Object representation. */ - read(bytes) { + read(bytes, config$1 = config) { let i = 0; this.version = bytes[i++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } - if (this.version !== 4 && this.version !== 5) { + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); } @@ -23284,7 +12991,24 @@ class SignaturePacket { this.signedHashValue = bytes.subarray(i, i + 2); i += 2; - this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length)); + // Only for v6 signatures, a variable-length field containing: + if (this.version === 6) { + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[i++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(i, i + saltLength); + i += saltLength; + } + + const signatureMaterial = bytes.subarray(i, bytes.length); + const { read, signatureParams } = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial); + if (read < signatureMaterial.length) { + throw new Error('Error reading MPIs'); + } + this.params = signatureParams; } /** @@ -23304,6 +13028,10 @@ class SignaturePacket { arr.push(this.signatureData); arr.push(this.writeUnhashedSubPackets()); arr.push(this.signedHashValue); + if (this.version === 6) { + arr.push(new Uint8Array([this.salt.length])); + arr.push(this.salt); + } arr.push(this.writeParams()); return util.concat(arr); } @@ -23317,19 +13045,41 @@ class SignaturePacket { * @throws {Error} if signing failed * @async */ - async sign(key, data, date = new Date(), detached = false) { - if (key.version === 5) { - this.version = 5; - } else { - this.version = 4; - } - const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; + async sign(key, data, date = new Date(), detached = false, config) { + this.version = key.version; this.created = util.normalizeDate(date); this.issuerKeyVersion = key.version; this.issuerFingerprint = key.getFingerprintBytes(); this.issuerKeyID = key.getKeyID(); + const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; + + // add randomness to the signature + if (this.version === 6) { + const saltLength = saltLengthForHash(this.hashAlgorithm); + if (this.salt === null) { + this.salt = mod.random.getRandomBytes(saltLength); + } else if (saltLength !== this.salt.length) { + throw new Error('Provided salt does not have the required length'); + } + } else if (config.nonDeterministicSignaturesViaNotation) { + const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME)); + // since re-signing the same object is not supported, it's not expected to have multiple salt notations, + // but we guard against it as a sanity check + if (saltNotations.length === 0) { + const saltValue = mod.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm)); + this.rawNotations.push({ + name: SALT_NOTATION_NAME, + value: saltValue, + humanReadable: false, + critical: false + }); + } else { + throw new Error('Unexpected existing salt notation'); + } + } + // Add hashed subpackets arr.push(this.writeHashedSubPackets()); @@ -23400,10 +13150,10 @@ class SignaturePacket { bytes = util.concat([bytes, this.revocationKeyFingerprint]); arr.push(writeSubPacket(sub.revocationKey, false, bytes)); } - if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) { // If the version of [the] key is greater than 4, this subpacket // MUST NOT be included in the signature. - arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write())); + arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write())); } this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; @@ -23465,15 +13215,19 @@ class SignaturePacket { if (this.issuerFingerprint !== null) { bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes)); + arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes)); } if (this.preferredAEADAlgorithms !== null) { bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); } + if (this.preferredCipherSuites !== null) { + bytes = new Uint8Array([].concat(...this.preferredCipherSuites)); + arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes)); + } const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); return util.concat([length, result]); } @@ -23483,19 +13237,17 @@ class SignaturePacket { * @returns {Uint8Array} Subpacket data. */ writeUnhashedSubPackets() { - const arr = []; - this.unhashedSubpackets.forEach(data => { - arr.push(writeSimpleLength(data.length)); - arr.push(data); + const arr = this.unhashedSubpackets.map(({ type, critical, body }) => { + return writeSubPacket(type, critical, body); }); const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); return util.concat([length, result]); } - // V4 signature sub packets + // Signature subpackets readSubPacket(bytes, hashed = true) { let mypos = 0; @@ -23503,15 +13255,19 @@ class SignaturePacket { const critical = !!(bytes[mypos] & 0x80); const type = bytes[mypos] & 0x7F; + mypos++; + if (!hashed) { - this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length)); + this.unhashedSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); if (!allowedUnhashedSubpackets.has(type)) { return; } } - mypos++; - // subpacket type switch (type) { case enums.signatureSubpacket.signatureCreationTime: @@ -23567,9 +13323,21 @@ class SignaturePacket { this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); break; - case enums.signatureSubpacket.issuer: + case enums.signatureSubpacket.issuerKeyID: // Issuer - this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + if (this.version === 4) { + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + } else if (hashed) { + // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature, + // since the Issuer Fingerprint subpacket is to be used instead. + // The `issuerKeyID` value will be set when reading the issuerFingerprint packet. + // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it, + // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed) + // issuerFingerprint. + // If the packet is hashed, then we reject the signature, to avoid verifying data different from + // what was parsed. + throw new Error('Unexpected Issuer Key ID subpacket'); + } break; case enums.signatureSubpacket.notationData: { @@ -23654,7 +13422,7 @@ class SignaturePacket { // Issuer Fingerprint this.issuerKeyVersion = bytes[mypos++]; this.issuerFingerprint = bytes.subarray(mypos, bytes.length); - if (this.issuerKeyVersion === 5) { + if (this.issuerKeyVersion >= 5) { this.issuerKeyID.read(this.issuerFingerprint); } else { this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); @@ -23664,22 +13432,30 @@ class SignaturePacket { // Preferred AEAD Algorithms this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; break; - default: { - const err = new Error(`Unknown signature subpacket type ${type}`); - if (critical) { - throw err; - } else { - util.printDebug(err); + case enums.signatureSubpacket.preferredCipherSuites: + // Preferred AEAD Cipher Suites + this.preferredCipherSuites = []; + for (let i = mypos; i < bytes.length; i += 2) { + this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]); } - } + break; + default: + this.unknownSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + break; } } readSubPackets(bytes, trusted = true, config) { + const subpacketLengthBytes = this.version === 6 ? 4 : 2; + // Two-octet scalar octet count for following subpacket data. - const subpacketLength = util.readNumber(bytes.subarray(0, 2)); + const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes)); - let i = 2; + let i = subpacketLengthBytes; // subpacket data set (zero or more subpackets) while (i < 2 + subpacketLength) { @@ -23790,10 +13566,15 @@ class SignaturePacket { toHash(signatureType, data, detached = false) { const bytes = this.toSign(signatureType, data); - return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); + return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]); } async hash(signatureType, data, toHash, detached = false) { + if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) { + // avoid hashing unexpected salt size + throw new Error('Signature salt does not have the expected length'); + } + if (!toHash) toHash = this.toHash(signatureType, data, detached); return mod.hash.digest(this.hashAlgorithm, toHash); } @@ -23863,6 +13644,11 @@ class SignaturePacket { [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); } + this.unknownSubpackets.forEach(({ type, critical }) => { + if (critical) { + throw new Error(`Unknown critical signature subpacket type ${type}`); + } + }); this.rawNotations.forEach(({ name, critical }) => { if (critical && (config$1.knownNotations.indexOf(name) < 0)) { throw new Error(`Unknown critical notation: ${name}`); @@ -23913,9 +13699,42 @@ function writeSubPacket(type, critical, data) { return util.concat(arr); } +/** + * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh. + * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5} + * @param {enums.hash} hashAlgorithm - Hash algorithm. + * @returns {Integer} Salt length. + * @private + */ +function saltLengthForHash(hashAlgorithm) { + switch (hashAlgorithm) { + case enums.hash.sha256: return 16; + case enums.hash.sha384: return 24; + case enums.hash.sha512: return 32; + case enums.hash.sha224: return 16; + case enums.hash.sha3_256: return 16; + case enums.hash.sha3_512: return 32; + default: throw new Error('Unsupported hash function'); + } +} + // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -const VERSION = 3; /** * Implementation of the One-Pass Signature Packets (Tag 4) @@ -23932,8 +13751,22 @@ class OnePassSignaturePacket { return enums.packet.onePassSignature; } + static fromSignaturePacket(signaturePacket, isLast) { + const onePassSig = new OnePassSignaturePacket(); + onePassSig.version = signaturePacket.version === 6 ? 6 : 3; + onePassSig.signatureType = signaturePacket.signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; + onePassSig.salt = signaturePacket.salt; // v6 only + onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only + + onePassSig.flags = isLast ? 1 : 0; + return onePassSig; + } + constructor() { - /** A one-octet version number. The current version is 3. */ + /** A one-octet version number. The current versions are 3 and 6. */ this.version = null; /** * A one-octet signature type. @@ -23955,8 +13788,12 @@ class OnePassSignaturePacket { * @type {enums.publicKey} */ this.publicKeyAlgorithm = null; - /** An eight-octet number holding the Key ID of the signing key. */ + /** Only for v6, a variable-length field containing the salt. */ + this.salt = null; + /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */ this.issuerKeyID = null; + /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */ + this.issuerFingerprint = null; /** * A one-octet number holding a flag showing whether the signature is nested. * A zero value indicates that the next packet is another One-Pass Signature packet @@ -23972,9 +13809,9 @@ class OnePassSignaturePacket { */ read(bytes) { let mypos = 0; - // A one-octet version number. The current version is 3. + // A one-octet version number. The current versions are 3 or 6. this.version = bytes[mypos++]; - if (this.version !== VERSION) { + if (this.version !== 3 && this.version !== 6) { throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); } @@ -23988,10 +13825,30 @@ class OnePassSignaturePacket { // A one-octet number describing the public-key algorithm used. this.publicKeyAlgorithm = bytes[mypos++]; - // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyID = new KeyID(); - this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); - mypos += 8; + if (this.version === 6) { + // Only for v6 signatures, a variable-length field containing: + + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[mypos++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(mypos, mypos + saltLength); + mypos += saltLength; + + // Only for v6 packets, 32 octets of the fingerprint of the signing key. + this.issuerFingerprint = bytes.subarray(mypos, mypos + 32); + mypos += 32; + this.issuerKeyID = new KeyID(); + // For v6 the Key ID is the high-order 64 bits of the fingerprint. + this.issuerKeyID.read(this.issuerFingerprint); + } else { + // Only for v3 packets, an eight-octet number holding the Key ID of the signing key. + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); + mypos += 8; + } // A one-octet number holding a flag showing whether the signature // is nested. A zero value indicates that the next packet is @@ -24006,11 +13863,23 @@ class OnePassSignaturePacket { * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. */ write() { - const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]); - - const end = new Uint8Array([this.flags]); - - return util.concatUint8Array([start, this.issuerKeyID.write(), end]); + const arr = [new Uint8Array([ + this.version, + this.signatureType, + this.hashAlgorithm, + this.publicKeyAlgorithm + ])]; + if (this.version === 6) { + arr.push( + new Uint8Array([this.salt.length]), + this.salt, + this.issuerFingerprint + ); + } else { + arr.push(this.issuerKeyID.write()); + } + arr.push(new Uint8Array([this.flags])); + return util.concatUint8Array(arr); } calculateTrailer(...args) { @@ -24026,7 +13895,11 @@ class OnePassSignaturePacket { correspondingSig.signatureType !== this.signatureType || correspondingSig.hashAlgorithm !== this.hashAlgorithm || correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyID.equals(this.issuerKeyID) + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) || + (this.version === 3 && correspondingSig.version === 6) || + (this.version === 6 && correspondingSig.version !== 6) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt)) ) { throw new Error('Corresponding signature packet does not match one-pass signature packet'); } @@ -24054,7 +13927,7 @@ function newPacketFromTag(tag, allowedPackets) { try { packetType = enums.read(enums.packet, tag); } catch (e) { - throw new UnsupportedError(`Unknown packet type with tag: ${tag}`); + throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`); } throw new Error(`Packet not allowed in this context: ${packetType}`); } @@ -24103,10 +13976,11 @@ class PacketList extends Array { await writer.ready; const done = await readPackets(readable, async parsed => { try { - if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) { + if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) { // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 + // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21 return; } const packet = newPacketFromTag(parsed.tag, allowedPackets); @@ -24115,6 +13989,17 @@ class PacketList extends Array { await packet.read(parsed.packet, config$1); await writer.write(packet); } catch (e) { + // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence, + // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored. + // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical. + if (e instanceof UnknownPacketError) { + if (parsed.tag <= 39) { + await writer.abort(e); + } else { + return; + } + } + const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { @@ -24249,9 +14134,25 @@ class PacketList extends Array { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A Compressed Data packet can contain the following packet types -const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ +const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, OnePassSignaturePacket, SignaturePacket @@ -24290,11 +14191,6 @@ class CompressedDataPacket { * @type {Uint8Array | ReadableStream} */ this.compressed = null; - - /** - * zip/zlib compression level, between 1 and 9 - */ - this.deflateLevel = config$1.deflateLevel; } /** @@ -24336,12 +14232,12 @@ class CompressedDataPacket { */ async decompress(config$1 = config) { const compressionName = enums.read(enums.compression, this.algorithm); - const decompressionFn = decompress_fns[compressionName]; + const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async if (!decompressionFn) { throw new Error(`${compressionName} decompression not supported`); } - this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1); + this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets$5, config$1); } /** @@ -24354,7 +14250,7 @@ class CompressedDataPacket { throw new Error(`${compressionName} compression not supported`); } - this.compressed = compressionFn(this.packets.write(), this.deflateLevel); + this.compressed = compressionFn(this.packets.write()); } } @@ -24364,84 +14260,127 @@ class CompressedDataPacket { // // ////////////////////////// - -const nodeZlib = util.getNodeZlib(); - -function uncompressed(data) { - return data; -} - -function node_zlib(func, create, options = {}) { - return function (data) { +/** + * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise. + * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator + * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor + * @returns {ReadableStream} compressed or decompressed data + */ +function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) { + return data => { if (!util.isStream(data) || isArrayStream(data)) { - return fromAsync(() => readToEnd(data).then(data => { + return fromAsync(() => readToEnd(data).then(inputData => { return new Promise((resolve, reject) => { - func(data, options, (err, result) => { - if (err) return reject(err); - resolve(result); - }); + const zlibStream = new ZlibStreamedConstructor(); + zlibStream.ondata = processedData => { + resolve(processedData); + }; + try { + zlibStream.push(inputData, true); // only one chunk to push + } catch (err) { + reject(err); + } }); })); } - return nodeToWeb(webToNode(data).pipe(create(options))); - }; -} -function pako_zlib(constructor, options = {}) { - return function(data) { - const obj = new constructor(options); - return transform(data, value => { - if (value.length) { - obj.push(value, Z_SYNC_FLUSH); - return obj.result; + // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) + if (compressionStreamInstantiator) { + try { + const compressorOrDecompressor = compressionStreamInstantiator(); + return data.pipeThrough(compressorOrDecompressor); + } catch (err) { + // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate. + if (err.name !== 'TypeError') { + throw err; + } } - }, () => { - if (constructor === Deflate) { - obj.push([], Z_FINISH); - return obj.result; + } + + // JS fallback + const inputReader = data.getReader(); + const zlibStream = new ZlibStreamedConstructor(); + + return new ReadableStream({ + async start(controller) { + zlibStream.ondata = async (value, isLast) => { + controller.enqueue(value); + if (isLast) { + controller.close(); + } + }; + + while (true) { + const { done, value } = await inputReader.read(); + if (done) { + zlibStream.push(new Uint8Array(), true); + return; + } else if (value.length) { + zlibStream.push(value); + } + } } }); }; } -function bzip2(func) { - return function(data) { - return fromAsync(async () => func(await readToEnd(data))); +function bzip2Decompress() { + return async function(data) { + const { decode: bunzipDecode } = await import('./seek-bzip.mjs').then(function (n) { return n.i; }); + return fromAsync(async () => bunzipDecode(await readToEnd(data))); }; } -const compress_fns = nodeZlib ? { - zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed) -} : { - zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed) +/** + * Get Compression Stream API instatiators if the constructors are implemented. + * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported + * (supported formats cannot be determined in advance). + * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat + * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }} + */ +const getCompressionStreamInstantiators = compressionFormat => ({ + compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)), + decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat)) +}); + +const compress_fns = { + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib) }; -const decompress_fns = nodeZlib ? { - uncompressed: uncompressed, - zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw), - zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -} : { - uncompressed: uncompressed, - zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), - zlib: /*#__PURE__*/ pako_zlib(Inflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) +const decompress_fns = { + uncompressed: data => data, + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib), + bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import }; // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A SEIP packet can contain the following packet types -const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([ +const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, SignaturePacket ]); -const VERSION$1 = 1; // A one-octet version number of the data packet. - /** * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) * @@ -24457,29 +14396,70 @@ class SymEncryptedIntegrityProtectedDataPacket { return enums.packet.symEncryptedIntegrityProtectedData; } + static fromObject({ version, aeadAlgorithm }) { + if (version !== 1 && version !== 2) { + throw new Error('Unsupported SEIPD version'); + } + + const seip = new SymEncryptedIntegrityProtectedDataPacket(); + seip.version = version; + if (version === 2) { + seip.aeadAlgorithm = aeadAlgorithm; + } + + return seip; + } + constructor() { - this.version = VERSION$1; + this.version = null; + + // The following 4 fields are for V2 only. + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = null; + this.chunkSizeByte = null; + this.salt = null; + this.encrypted = null; this.packets = null; } async read(bytes) { await parse(bytes, async reader => { - const version = await reader.readByte(); - // - A one-octet version number. The only currently defined value is 1. - if (version !== VERSION$1) { - throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`); + this.version = await reader.readByte(); + // - A one-octet version number with value 1 or 2. + if (this.version !== 1 && this.version !== 2) { + throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`); + } + + if (this.version === 2) { + // - A one-octet cipher algorithm. + this.cipherAlgorithm = await reader.readByte(); + // - A one-octet AEAD algorithm. + this.aeadAlgorithm = await reader.readByte(); + // - A one-octet chunk size. + this.chunkSizeByte = await reader.readByte(); + // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique. + this.salt = await reader.readBytes(32); } + // For V1: // - Encrypted data, the output of the selected symmetric-key cipher // operating in Cipher Feedback mode with shift amount equal to the // block size of the cipher (CFB-n where n is the block size). + // For V2: + // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode. + // - A final, summary authentication tag for the AEAD mode. this.encrypted = reader.remainder(); }); } write() { - return util.concat([new Uint8Array([VERSION$1]), this.encrypted]); + if (this.version === 2) { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]); + } + return util.concat([new Uint8Array([this.version]), this.encrypted]); } /** @@ -24492,18 +14472,35 @@ class SymEncryptedIntegrityProtectedDataPacket { * @async */ async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + const { blockSize, keySize } = mod.getCipherParams(sessionKeyAlgorithm); + if (key.length !== keySize) { + throw new Error('Unexpected session key size'); + } let bytes = this.packets.write(); if (isArrayStream(bytes)) bytes = await readToEnd(bytes); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - const tohash = util.concat([prefix, bytes, mdc]); - const hash = await mod.hash.sha1(passiveClone(tohash)); - const plaintext = util.concat([tohash, hash]); + if (this.version === 2) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + this.salt = mod.random.getRandomBytes(32); + this.chunkSizeByte = config$1.aeadChunkSizeByte; + this.encrypted = await runAEAD(this, 'encrypt', key, bytes); + } else { + const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); + const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet + + const tohash = util.concat([prefix, bytes, mdc]); + const hash = await mod.hash.sha1(passiveClone(tohash)); + const plaintext = util.concat([tohash, hash]); - this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); + this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); + } return true; } @@ -24517,46 +14514,196 @@ class SymEncryptedIntegrityProtectedDataPacket { * @async */ async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + if (key.length !== mod.getCipherParams(sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + let encrypted = clone(this.encrypted); if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); - - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - const realHash = slice(passiveClone(decrypted), -20); - const tohash = slice(decrypted, 0, -20); - const verifyHash = Promise.all([ - readToEnd(await mod.hash.sha1(passiveClone(tohash))), - readToEnd(realHash) - ]).then(([hash, mdc]) => { - if (!util.equalsUint8Array(hash, mdc)) { - throw new Error('Modification detected.'); + + let packetbytes; + if (this.version === 2) { + if (this.cipherAlgorithm !== sessionKeyAlgorithm) { + // sanity check + throw new Error('Unexpected session key algorithm'); + } + packetbytes = await runAEAD(this, 'decrypt', key, encrypted); + } else { + const { blockSize } = mod.getCipherParams(sessionKeyAlgorithm); + const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); + + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + const realHash = slice(passiveClone(decrypted), -20); + const tohash = slice(decrypted, 0, -20); + const verifyHash = Promise.all([ + readToEnd(await mod.hash.sha1(passiveClone(tohash))), + readToEnd(realHash) + ]).then(([hash, mdc]) => { + if (!util.equalsUint8Array(hash, mdc)) { + throw new Error('Modification detected.'); + } + return new Uint8Array(); + }); + const bytes = slice(tohash, blockSize + 2); // Remove random prefix + packetbytes = slice(bytes, 0, -2); // Remove MDC packet + packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); + if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { + packetbytes = await readToEnd(packetbytes); } - return new Uint8Array(); - }); - const bytes = slice(tohash, blockSize + 2); // Remove random prefix - let packetbytes = slice(bytes, 0, -2); // Remove MDC packet - packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); - if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { - packetbytes = await readToEnd(packetbytes); } - this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1); + + this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1); return true; } } +/** + * En/decrypt the payload. + * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt + * @param {Uint8Array} key - The session key used to en/decrypt the payload + * @param {Uint8Array | ReadableStream} data - The data to en/decrypt + * @returns {Promise>} + * @async + */ +async function runAEAD(packet, fn, key, data) { + const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2; + const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import) + if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type'); + + const mode = mod.getAEADMode(packet.aeadAlgorithm); + const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; + const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; + const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) + const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0; + const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP); + const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP); + const adataTagArray = new Uint8Array(adataBuffer); + const adataView = new DataView(adataBuffer); + const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); + adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0); + let chunkIndex = 0; + let latestPromise = Promise.resolve(); + let cryptedBytes = 0; + let queuedBytes = 0; + let iv; + let ivView; + if (isSEIPDv2) { + const { keySize } = mod.getCipherParams(packet.cipherAlgorithm); + const { ivLength } = mode; + const info = new Uint8Array(adataBuffer, 0, 5); + const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength); + key = derived.subarray(0, keySize); + iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. + iv.fill(0, iv.length - 8); + ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + } else { // AEADEncryptedDataPacket + iv = packet.iv; + // ivView is unused in this case + } + const modeInstance = await mode(packet.cipherAlgorithm, key); + return transformPair(data, async (readable, writable) => { + if (util.isStream(readable) !== 'array') { + const buffer = new TransformStream({}, { + highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6), + size: array => array.length + }); + pipe(buffer.readable, writable); + writable = buffer.writable; + } + const reader = getReader(readable); + const writer = getWriter(writable); + try { + while (true) { + let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); + const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); + chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); + let cryptedPromise; + let done; + let nonce; + if (isSEIPDv2) { // SEIPD V2 + nonce = iv; + } else { // AEADEncryptedDataPacket + nonce = iv.slice(); + for (let i = 0; i < 8; i++) { + nonce[iv.length - 8 + i] ^= chunkIndexArray[i]; + } + } + if (!chunkIndex || chunk.length) { + reader.unshift(finalChunk); + cryptedPromise = modeInstance[fn](chunk, nonce, adataArray); + cryptedPromise.catch(() => {}); + queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; + } else { + // After the last chunk, we either encrypt a final, empty + // data chunk to get the final authentication tag or + // validate that final authentication tag. + adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...) + cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray); + cryptedPromise.catch(() => {}); + queuedBytes += tagLengthIfEncrypting; + done = true; + } + cryptedBytes += chunk.length - tagLengthIfDecrypting; + // eslint-disable-next-line @typescript-eslint/no-loop-func + latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { + await writer.ready; + await writer.write(crypted); + queuedBytes -= crypted.length; + }).catch(err => writer.abort(err)); + if (done || queuedBytes > writer.desiredSize) { + await latestPromise; // Respect backpressure + } + if (!done) { + if (isSEIPDv2) { // SEIPD V2 + ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...) + } else { // AEADEncryptedDataPacket + adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) + } + } else { + await writer.close(); + break; + } + } + } catch (e) { + await writer.ready.catch(() => {}); + await writer.abort(e); + } + }); +} + // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // An AEAD-encrypted Data packet can contain the following packet types -const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ +const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, SignaturePacket ]); -const VERSION$2 = 1; // A one-octet version number of the data packet. +const VERSION = 1; // A one-octet version number of the data packet. /** * Implementation of the Symmetrically Encrypted Authenticated Encryption with @@ -24571,7 +14718,7 @@ class AEADEncryptedDataPacket { } constructor() { - this.version = VERSION$2; + this.version = VERSION; /** @type {enums.symmetric} */ this.cipherAlgorithm = null; /** @type {enums.aead} */ @@ -24590,7 +14737,7 @@ class AEADEncryptedDataPacket { async read(bytes) { await parse(bytes, async reader => { const version = await reader.readByte(); - if (version !== VERSION$2) { // The only currently defined value is 1. + if (version !== VERSION) { // The only currently defined value is 1. throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); } this.cipherAlgorithm = await reader.readByte(); @@ -24621,8 +14768,8 @@ class AEADEncryptedDataPacket { */ async decrypt(sessionKeyAlgorithm, key, config$1 = config) { this.packets = await PacketList.fromBinary( - await this.crypt('decrypt', key, clone(this.encrypted)), - allowedPackets$2, + await runAEAD(this, 'decrypt', key, clone(this.encrypted)), + allowedPackets$3, config$1 ); } @@ -24642,92 +14789,27 @@ class AEADEncryptedDataPacket { this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV this.chunkSizeByte = config$1.aeadChunkSizeByte; const data = this.packets.write(); - this.encrypted = await this.crypt('encrypt', key, data); - } - - /** - * En/decrypt the payload. - * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt - * @param {Uint8Array} key - The session key used to en/decrypt the payload - * @param {Uint8Array | ReadableStream} data - The data to en/decrypt - * @returns {Promise>} - * @async - */ - async crypt(fn, key, data) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const modeInstance = await mode(this.cipherAlgorithm, key); - const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; - const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; - const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) - const adataBuffer = new ArrayBuffer(21); - const adataArray = new Uint8Array(adataBuffer, 0, 13); - const adataTagArray = new Uint8Array(adataBuffer); - const adataView = new DataView(adataBuffer); - const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0); - let chunkIndex = 0; - let latestPromise = Promise.resolve(); - let cryptedBytes = 0; - let queuedBytes = 0; - const iv = this.iv; - return transformPair(data, async (readable, writable) => { - if (util.isStream(readable) !== 'array') { - const buffer = new TransformStream({}, { - highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6), - size: array => array.length - }); - pipe(buffer.readable, writable); - writable = buffer.writable; - } - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); - const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); - chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); - let cryptedPromise; - let done; - if (!chunkIndex || chunk.length) { - reader.unshift(finalChunk); - cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray); - queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; - } else { - // After the last chunk, we either encrypt a final, empty - // data chunk to get the final authentication tag or - // validate that final authentication tag. - adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...) - cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray); - queuedBytes += tagLengthIfEncrypting; - done = true; - } - cryptedBytes += chunk.length - tagLengthIfDecrypting; - // eslint-disable-next-line no-loop-func - latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { - await writer.ready; - await writer.write(crypted); - queuedBytes -= crypted.length; - }).catch(err => writer.abort(err)); - if (done || queuedBytes > writer.desiredSize) { - await latestPromise; // Respect backpressure - } - if (!done) { - adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) - } else { - await writer.close(); - break; - } - } - } catch (e) { - await writer.abort(e); - } - }); + this.encrypted = await runAEAD(this, 'encrypt', key, data); } } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -const VERSION$3 = 3; /** * Public-Key Encrypted Session Key Packets (Tag 1) @@ -24751,9 +14833,16 @@ class PublicKeyEncryptedSessionKeyPacket { } constructor() { - this.version = 3; + this.version = null; + // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()` this.publicKeyID = new KeyID(); + + // For version 6: + this.publicKeyVersion = null; + this.publicKeyFingerprint = null; + + // For all versions: this.publicKeyAlgorithm = null; this.sessionKey = null; @@ -24767,22 +14856,74 @@ class PublicKeyEncryptedSessionKeyPacket { this.encrypted = {}; } + static fromObject({ + version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm + }) { + const pkesk = new PublicKeyEncryptedSessionKeyPacket(); + + if (version !== 3 && version !== 6) { + throw new Error('Unsupported PKESK version'); + } + + pkesk.version = version; + + if (version === 6) { + pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version; + pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes(); + } + + pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID(); + pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkesk.sessionKey = sessionKey; + pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm; + + return pkesk; + } + /** * Parsing function for a publickey encrypted session key packet (tag 1). * * @param {Uint8Array} bytes - Payload of a tag 1 packet */ read(bytes) { - let i = 0; - this.version = bytes[i++]; - if (this.version !== VERSION$3) { + let offset = 0; + this.version = bytes[offset++]; + if (this.version !== 3 && this.version !== 6) { throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); } - i += this.publicKeyID.read(bytes.subarray(i)); - this.publicKeyAlgorithm = bytes[i++]; - this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version); - if (this.publicKeyAlgorithm === enums.publicKey.x25519) { - this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + if (this.version === 6) { + // A one-octet size of the following two fields: + // - A one octet key version number. + // - The fingerprint of the public key or subkey to which the session key is encrypted. + // The size may also be zero. + const versionAndFingerprintLength = bytes[offset++]; + if (versionAndFingerprintLength) { + this.publicKeyVersion = bytes[offset++]; + const fingerprintLength = versionAndFingerprintLength - 1; + this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength; + if (this.publicKeyVersion >= 5) { + // For v5/6 the Key ID is the high-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint); + } else { + // For v4 The Key ID is the low-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8)); + } + } else { + // The size may also be zero, and the key version and + // fingerprint omitted for an "anonymous recipient" + this.publicKeyID = KeyID.wildcard(); + } + } else { + offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8)); + } + this.publicKeyAlgorithm = bytes[offset++]; + this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset)); + if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) { + if (this.version === 3) { + this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + } else if (this.encrypted.C.algorithm !== null) { + throw new Error('Unexpected cleartext symmetric algorithm'); + } } } @@ -24793,11 +14934,27 @@ class PublicKeyEncryptedSessionKeyPacket { */ write() { const arr = [ - new Uint8Array([this.version]), - this.publicKeyID.write(), + new Uint8Array([this.version]) + ]; + + if (this.version === 6) { + if (this.publicKeyFingerprint !== null) { + arr.push(new Uint8Array([ + this.publicKeyFingerprint.length + 1, + this.publicKeyVersion] + )); + arr.push(this.publicKeyFingerprint); + } else { + arr.push(new Uint8Array([0])); + } + } else { + arr.push(this.publicKeyID.write()); + } + + arr.push( new Uint8Array([this.publicKeyAlgorithm]), mod.serializeParams(this.publicKeyAlgorithm, this.encrypted) - ]; + ); return util.concatUint8Array(arr); } @@ -24810,9 +14967,13 @@ class PublicKeyEncryptedSessionKeyPacket { */ async encrypt(key) { const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); - const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey); + // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a + // v6 PKESK packet, as it is included in the v2 SEIPD packet. + const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey); this.encrypted = await mod.publicKeyEncrypt( - algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes()); + algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint); } /** @@ -24832,13 +14993,19 @@ class PublicKeyEncryptedSessionKeyPacket { const randomPayload = randomSessionKey ? encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : null; - const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload); + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload); const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); - // v3 Montgomery curves have cleartext cipher algo - if (this.publicKeyAlgorithm !== enums.publicKey.x25519) { - this.sessionKeyAlgorithm = sessionKeyAlgorithm; + if (this.version === 3) { + // v3 Montgomery curves have cleartext cipher algo + const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448; + this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm; + + if (sessionKey.length !== mod.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } } this.sessionKey = sessionKey; } @@ -24850,15 +15017,15 @@ function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { case enums.publicKey.rsaEncrypt: case enums.publicKey.rsaEncryptSign: case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { + case enums.publicKey.ecdh: // add checksum return util.concatUint8Array([ - new Uint8Array([cipherAlgo]), + new Uint8Array(version === 6 ? [] : [cipherAlgo]), sessionKeyData, util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) ]); - } case enums.publicKey.x25519: + case enums.publicKey.x448: return sessionKeyData; default: throw new Error('Unsupported public key algorithm'); @@ -24877,7 +15044,9 @@ function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { const checksum = decryptedData.subarray(decryptedData.length - 2); const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; - const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; + const decryptedSessionKey = version === 6 ? + { sessionKeyAlgorithm: null, sessionKey: result } : + { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; if (randomSessionKey) { // We must not leak info about the validity of the decrypted checksum or cipher algo. // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. @@ -24886,14 +15055,15 @@ function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; return { sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), - sessionKeyAlgorithm: util.selectUint8( + sessionKeyAlgorithm: version === 6 ? null : util.selectUint8( isValidPayload, decryptedSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm ) }; } else { - const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm); + const isValidPayload = isValidChecksum && ( + version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm)); if (isValidPayload) { return decryptedSessionKey; } else { @@ -24902,7 +15072,9 @@ function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { } } case enums.publicKey.x25519: + case enums.publicKey.x448: return { + sessionKeyAlgorithm: null, sessionKey: decryptedData }; default: @@ -24911,170 +15083,22 @@ function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -class S2K { - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * Hash function identifier, or 0 for gnu-dummy keys - * @type {module:enums.hash | 0} - */ - this.algorithm = enums.hash.sha256; - /** - * enums.s2k identifier or 'gnu-dummy' - * @type {String} - */ - this.type = 'iterated'; - /** @type {Integer} */ - this.c = config$1.s2kIterationCountByte; - /** Eight bytes of salt in a binary string. - * @type {Uint8Array} - */ - this.salt = null; - } - - getCount() { - // Exponent bias, defined in RFC4880 - const expbias = 6; - - return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); - } - - /** - * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param {Uint8Array} bytes - Payload of string-to-key specifier - * @returns {Integer} Actual length of the object. - */ - read(bytes) { - let i = 0; - try { - this.type = enums.read(enums.s2k, bytes[i++]); - } catch (err) { - throw new UnsupportedError('Unknown S2K type.'); - } - this.algorithm = bytes[i++]; - - switch (this.type) { - case 'simple': - break; - - case 'salted': - this.salt = bytes.subarray(i, i + 8); - i += 8; - break; - - case 'iterated': - this.salt = bytes.subarray(i, i + 8); - i += 8; - - // Octet 10: count, a one-octet, coded value - this.c = bytes[i++]; - break; - - case 'gnu': - if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { - i += 3; // GNU - const gnuExtType = 1000 + bytes[i++]; - if (gnuExtType === 1001) { - this.type = 'gnu-dummy'; - // GnuPG extension mode 1001 -- don't write secret key at all - } else { - throw new UnsupportedError('Unknown s2k gnu protection mode.'); - } - } else { - throw new UnsupportedError('Unknown s2k type.'); - } - break; - - default: - throw new UnsupportedError('Unknown s2k type.'); // unreachable - } - - return i; - } - - /** - * Serializes s2k information - * @returns {Uint8Array} Binary representation of s2k. - */ - write() { - if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); - } - const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; - - switch (this.type) { - case 'simple': - break; - case 'salted': - arr.push(this.salt); - break; - case 'iterated': - arr.push(this.salt); - arr.push(new Uint8Array([this.c])); - break; - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - - return util.concatUint8Array(arr); - } - - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param {String} passphrase - Passphrase containing user input - * @returns {Promise} Produced key with a length corresponding to. - * hashAlgorithm hash length - * @async - */ - async produceKey(passphrase, numBytes) { - passphrase = util.encodeUTF8(passphrase); - - const arr = []; - let rlength = 0; - - let prefixlen = 0; - while (rlength < numBytes) { - let toHash; - switch (this.type) { - case 'simple': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); - break; - case 'salted': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); - break; - case 'iterated': { - const data = util.concatUint8Array([this.salt, passphrase]); - let datalen = data.length; - const count = Math.max(this.getCount(), datalen); - toHash = new Uint8Array(prefixlen + count); - toHash.set(data, prefixlen); - for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { - toHash.copyWithin(pos, prefixlen, pos); - } - break; - } - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - const result = await mod.hash.digest(this.algorithm, toHash); - arr.push(result); - rlength += result.length; - prefixlen++; - } - - return util.concatUint8Array(arr).subarray(0, numBytes); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript /** * Symmetric-Key Encrypted Session Key Packets (Tag 3) @@ -25098,7 +15122,7 @@ class SymEncryptedSessionKeyPacket { * @param {Object} [config] - Full configuration, defaults to openpgp.config */ constructor(config$1 = config) { - this.version = config$1.aeadProtect ? 5 : 4; + this.version = config$1.aeadProtect ? 6 : 4; this.sessionKey = null; /** * Algorithm to encrypt the session key with @@ -25109,7 +15133,7 @@ class SymEncryptedSessionKeyPacket { * Algorithm to encrypt the message with * @type {enums.symmetric} */ - this.sessionKeyAlgorithm = enums.symmetric.aes256; + this.sessionKeyAlgorithm = null; /** * AEAD mode to encrypt the session key with (if AEAD protection is enabled) * @type {enums.aead} @@ -25128,25 +15152,36 @@ class SymEncryptedSessionKeyPacket { read(bytes) { let offset = 0; - // A one-octet version number. The only currently defined version is 4. + // A one-octet version number with value 4, 5 or 6. this.version = bytes[offset++]; - if (this.version !== 4 && this.version !== 5) { + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); } + if (this.version === 6) { + // A one-octet scalar octet count of the following 5 fields. + offset++; + } + // A one-octet number describing the symmetric algorithm used. const algo = bytes[offset++]; - if (this.version === 5) { + if (this.version >= 5) { // A one-octet AEAD algorithm. this.aeadAlgorithm = bytes[offset++]; + + if (this.version === 6) { + // A one-octet scalar octet count of the following field. + offset++; + } } // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new S2K(); + const s2kType = bytes[offset++]; + this.s2k = newS2KFromType(s2kType); offset += this.s2k.read(bytes.subarray(offset, bytes.length)); - if (this.version === 5) { + if (this.version >= 5) { const mode = mod.getAEADMode(this.aeadAlgorithm); // A starting initialization vector of size specified by the AEAD @@ -25156,7 +15191,7 @@ class SymEncryptedSessionKeyPacket { // The encrypted session key itself, which is decrypted with the // string-to-key object. This is optional in version 4. - if (this.version === 5 || offset < bytes.length) { + if (this.version >= 5 || offset < bytes.length) { this.encrypted = bytes.subarray(offset, bytes.length); this.sessionKeyEncryptionAlgorithm = algo; } else { @@ -25176,10 +15211,15 @@ class SymEncryptedSessionKeyPacket { let bytes; - if (this.version === 5) { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]); + const s2k = this.s2k.write(); + if (this.version === 6) { + const s2kLen = s2k.length; + const fieldsLen = 3 + s2kLen + this.iv.length; + bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]); + } else if (this.version === 5) { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]); } else { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]); + bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]); if (this.encrypted !== null) { bytes = util.concatUint8Array([bytes, this.encrypted]); @@ -25200,20 +15240,25 @@ class SymEncryptedSessionKeyPacket { this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; - const { blockSize, keySize } = mod.getCipher(algo); + const { blockSize, keySize } = mod.getCipherParams(algo); const key = await this.s2k.produceKey(passphrase, keySize); - if (this.version === 5) { + if (this.version >= 5) { const mode = mod.getAEADMode(this.aeadAlgorithm); const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, key); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); } else if (this.encrypted !== null) { const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); this.sessionKey = decrypted.subarray(1, decrypted.length); + if (this.sessionKey.length !== mod.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } } else { + // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo this.sessionKey = key; } } @@ -25232,33 +15277,50 @@ class SymEncryptedSessionKeyPacket { this.sessionKeyEncryptionAlgorithm = algo; - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); - const { blockSize, keySize } = mod.getCipher(algo); - const encryptionKey = await this.s2k.produceKey(passphrase, keySize); + const { blockSize, keySize } = mod.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); if (this.sessionKey === null) { this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm); } - if (this.version === 5) { + if (this.version >= 5) { const mode = mod.getAEADMode(this.aeadAlgorithm); this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV - const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; const modeInstance = await mode(algo, encryptionKey); - this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData); + this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); } else { const toEncrypt = util.concatUint8Array([ new Uint8Array([this.sessionKeyAlgorithm]), this.sessionKey ]); - this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1); + this.encrypted = await mod.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config$1); } } } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Implementation of the Key Material Packet (Tag 5,6,7,14) @@ -25285,7 +15347,7 @@ class PublicKeyPacket { * Packet version * @type {Integer} */ - this.version = config$1.v5Keys ? 5 : 4; + this.version = config$1.v6Keys ? 6 : 4; /** * Key creation date. * @type {Date} @@ -25342,12 +15404,15 @@ class PublicKeyPacket { * @returns {Object} This object with attributes set by the parser * @async */ - async read(bytes) { + async read(bytes, config$1 = config) { let pos = 0; - // A one-octet version number (3, 4 or 5). + // A one-octet version number (4, 5 or 6). this.version = bytes[pos++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } - if (this.version === 4 || this.version === 5) { + if (this.version === 4 || this.version === 5 || this.version === 6) { // - A four-octet number denoting the time that the key was created. this.created = util.readDate(bytes.subarray(pos, pos + 4)); pos += 4; @@ -25355,13 +15420,24 @@ class PublicKeyPacket { // - A one-octet number denoting the public-key algorithm of this key. this.algorithm = bytes[pos++]; - if (this.version === 5) { + if (this.version >= 5) { // - A four-octet scalar octet count for the following key material. pos += 4; } // - A series of values comprising the key material. const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if ( + this.version === 6 && + publicParams.oid && ( + publicParams.oid.getName() === enums.curve.curve25519Legacy || + publicParams.oid.getName() === enums.curve.ed25519Legacy + ) + ) { + throw new Error('Legacy curve25519 cannot be used with v6 keys'); + } this.publicParams = publicParams; pos += read; @@ -25385,7 +15461,7 @@ class PublicKeyPacket { arr.push(new Uint8Array([this.algorithm])); const params = mod.serializeParams(this.algorithm, this.publicParams); - if (this.version === 5) { + if (this.version >= 5) { // A four-octet scalar octet count for the following key material arr.push(util.writeNumber(params.length, 4)); } @@ -25401,10 +15477,9 @@ class PublicKeyPacket { writeForHash(version) { const bytes = this.writePublicKey(); - if (version === 5) { - return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]); - } - return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); + const versionOctet = 0x95 + version; + const lengthOctets = version >= 5 ? 4 : 2; + return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]); } /** @@ -25439,7 +15514,7 @@ class PublicKeyPacket { await this.computeFingerprint(); this.keyID = new KeyID(); - if (this.version === 5) { + if (this.version >= 5) { this.keyID.read(this.fingerprint.subarray(0, 8)); } else if (this.version === 4) { this.keyID.read(this.fingerprint.subarray(12, 20)); @@ -25454,7 +15529,7 @@ class PublicKeyPacket { async computeFingerprint() { const toHash = this.writeForHash(this.version); - if (this.version === 5) { + if (this.version >= 5) { this.fingerprint = await mod.hash.sha256(toHash); } else if (this.version === 4) { this.fingerprint = await mod.hash.sha1(toHash); @@ -25518,9 +15593,25 @@ PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A SE packet can contain the following packet types -const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ +const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ LiteralDataPacket, CompressedDataPacket, OnePassSignaturePacket, @@ -25578,14 +15669,14 @@ class SymmetricallyEncryptedDataPacket { throw new Error('Message is not authenticated.'); } - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + const { blockSize } = mod.getCipherParams(sessionKeyAlgorithm); const encrypted = await readToEnd(clone(this.encrypted)); const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted.subarray(blockSize + 2), encrypted.subarray(2, blockSize + 2) ); - this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1); + this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1); } /** @@ -25599,7 +15690,7 @@ class SymmetricallyEncryptedDataPacket { */ async encrypt(sessionKeyAlgorithm, key, config$1 = config) { const data = this.packets.write(); - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + const { blockSize } = mod.getCipherParams(sessionKeyAlgorithm); const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); @@ -25609,6 +15700,22 @@ class SymmetricallyEncryptedDataPacket { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Implementation of the strange "Marker packet" (Tag 10) @@ -25652,6 +15759,22 @@ class MarkerPacket { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * A Public-Subkey packet (tag 14) has exactly the same format as a @@ -25670,7 +15793,7 @@ class PublicSubkeyPacket extends PublicKeyPacket { * @param {Date} [date] - Creation date * @param {Object} [config] - Full configuration, defaults to openpgp.config */ - // eslint-disable-next-line no-useless-constructor + // eslint-disable-next-line @typescript-eslint/no-useless-constructor constructor(date, config) { super(date, config); } @@ -25695,6 +15818,22 @@ class PublicSubkeyPacket extends PublicKeyPacket { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Implementation of the User Attribute Packet (Tag 17) @@ -25765,7 +15904,23 @@ class UserAttributePacket { } } -// GPG4Browsers - An OpenPGP implementation in javascript +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * A Secret-Key packet contains all the information that is found in a @@ -25812,11 +15967,27 @@ class SecretKeyPacket extends PublicKeyPacket { * @type {enums.aead} */ this.aead = null; + /** + * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis + * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older). + * This value is only relevant to know how to decrypt the key: + * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism. + * @type {Boolean} + * @private + */ + this.isLegacyAEAD = null; /** * Decrypted private parameters, referenced by name * @type {Object} */ this.privateParams = null; + /** + * `true` for keys whose integrity is already confirmed, based on + * the AEAD encryption mechanism + * @type {Boolean} + * @private + */ + this.usedModernAEAD = null; } // 5.5.3. Secret-Key Packet Formats @@ -25827,9 +15998,9 @@ class SecretKeyPacket extends PublicKeyPacket { * @param {Uint8Array} bytes - Input string to read the packet from * @async */ - async read(bytes) { + async read(bytes, config$1 = config) { // - A Public-Key or Public-Subkey packet, as described above. - let i = await this.readPublicKey(bytes); + let i = await this.readPublicKey(bytes, config$1); const startOfSecretKeyData = i; // - One octet indicating string-to-key usage conventions. Zero @@ -25844,6 +16015,14 @@ class SecretKeyPacket extends PublicKeyPacket { i++; } + // - Only for a version 6 packet where the secret key material is + // encrypted (that is, where the previous octet is not zero), a one- + // octet scalar octet count of the cumulative length of all the + // following optional string-to-key parameter fields. + if (this.version === 6 && this.s2kUsage) { + i++; + } + try { // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // one-octet symmetric encryption algorithm. @@ -25856,10 +16035,17 @@ class SecretKeyPacket extends PublicKeyPacket { this.aead = bytes[i++]; } + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + i++; + } + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // string-to-key specifier. The length of the string-to-key // specifier is implied by its type, as described above. - this.s2k = new S2K(); + const s2kType = bytes[i++]; + this.s2k = newS2KFromType(s2kType); i += this.s2k.read(bytes.subarray(i, bytes.length)); if (this.s2k.type === 'gnu-dummy') { @@ -25869,14 +16055,37 @@ class SecretKeyPacket extends PublicKeyPacket { this.symmetric = this.s2kUsage; } - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. + if (this.s2kUsage) { - this.iv = bytes.subarray( - i, - i + mod.getCipher(this.symmetric).blockSize - ); + // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5). + // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format). + // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always + // fail if the key was parsed according to the wrong format, since the keys are processed differently. + // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag. + this.isLegacyAEAD = this.s2kUsage === 253 && ( + this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy)); + // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV) + // of the same length as the cipher's block size. + // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the + // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm. + // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero + if (this.s2kUsage !== 253 || this.isLegacyAEAD) { + this.iv = bytes.subarray( + i, + i + mod.getCipherParams(this.symmetric).blockSize + ); + this.usedModernAEAD = false; + } else { + // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted), + // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which + // is used as the nonce for the AEAD algorithm. + this.iv = bytes.subarray( + i, + i + mod.getAEADMode(this.aead).ivLength + ); + // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation. + this.usedModernAEAD = true; + } i += this.iv.length; } @@ -25900,12 +16109,20 @@ class SecretKeyPacket extends PublicKeyPacket { this.isEncrypted = !!this.s2kUsage; if (!this.isEncrypted) { - const cleartext = this.keyMaterial.subarray(0, -2); - if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { - throw new Error('Key checksum mismatch'); + let cleartext; + if (this.version === 6) { + cleartext = this.keyMaterial; + } else { + cleartext = this.keyMaterial.subarray(0, -2); + if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { + throw new Error('Key checksum mismatch'); + } } try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + const { read, privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + if (read < cleartext.length) { + throw new Error('Error reading MPIs'); + } this.privateParams = privateParams; } catch (err) { if (err instanceof UnsupportedError) throw err; @@ -25943,10 +16160,18 @@ class SecretKeyPacket extends PublicKeyPacket { optionalFieldsArr.push(this.aead); } + const s2k = this.s2k.write(); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + optionalFieldsArr.push(s2k.length); + } + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a // string-to-key specifier. The length of the string-to-key // specifier is implied by its type, as described above. - optionalFieldsArr.push(...this.s2k.write()); + optionalFieldsArr.push(...s2k); } // - [Optional] If secret data is encrypted (string-to-key usage octet @@ -25956,7 +16181,7 @@ class SecretKeyPacket extends PublicKeyPacket { optionalFieldsArr.push(...this.iv); } - if (this.version === 5) { + if (this.version === 5 || (this.version === 6 && this.s2kUsage)) { arr.push(new Uint8Array([optionalFieldsArr.length])); } arr.push(new Uint8Array(optionalFieldsArr)); @@ -25971,7 +16196,7 @@ class SecretKeyPacket extends PublicKeyPacket { } arr.push(this.keyMaterial); - if (!this.s2kUsage) { + if (!this.s2kUsage && this.version !== 6) { arr.push(util.writeChecksum(this.keyMaterial)); } } @@ -26023,12 +16248,14 @@ class SecretKeyPacket extends PublicKeyPacket { delete this.unparseableKeyMaterial; this.isEncrypted = null; this.keyMaterial = null; - this.s2k = new S2K(config$1); + this.s2k = newS2KFromType(enums.s2k.gnu, config$1); this.s2k.algorithm = 0; this.s2k.c = 0; this.s2k.type = 'gnu-dummy'; this.s2kUsage = 254; this.symmetric = enums.symmetric.aes256; + this.isLegacyAEAD = null; + this.usedModernAEAD = null; } /** @@ -26039,1256 +16266,241 @@ class SecretKeyPacket extends PublicKeyPacket { * @param {String} passphrase * @param {Object} [config] - Full configuration, defaults to openpgp.config * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - if (this.isDummy()) { - return; - } - - if (!this.isDecrypted()) { - throw new Error('Key packet is already encrypted'); - } - - if (!passphrase) { - throw new Error('A non-empty passphrase is required for key encryption.'); - } - - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - const cleartext = mod.serializeParams(this.algorithm, this.privateParams); - this.symmetric = enums.symmetric.aes256; - const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - - const { blockSize } = mod.getCipher(this.symmetric); - this.iv = mod.random.getRandomBytes(blockSize); - - if (config$1.aeadProtect) { - this.s2kUsage = 253; - this.aead = enums.aead.eax; - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } else { - this.s2kUsage = 254; - this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ - cleartext, - await mod.hash.sha1(cleartext, config$1) - ]), this.iv, config$1); - } - } - - /** - * Decrypts the private key params which are needed to use the key. - * Successful decryption does not imply key integrity, call validate() to confirm that. - * {@link SecretKeyPacket.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param {String} passphrase - The passphrase for this private key as string - * @throws {Error} if the key is already decrypted, or if decryption was not successful - * @async - */ - async decrypt(passphrase) { - if (this.isDummy()) { - return false; - } - - if (this.unparseableKeyMaterial) { - throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); - } - - if (this.isDecrypted()) { - throw new Error('Key packet is already decrypted.'); - } - - let key; - if (this.s2kUsage === 254 || this.s2kUsage === 253) { - key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2kUsage === 255) { - throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); - } else { - throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); - } - - let cleartext; - if (this.s2kUsage === 253) { - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - try { - cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } catch (err) { - if (err.message === 'Authentication tag mismatch') { - throw new Error('Incorrect key passphrase: ' + err.message); - } - throw err; - } - } else { - const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); - - cleartext = cleartextWithHash.subarray(0, -20); - const hash = await mod.hash.sha1(cleartext); - - if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { - throw new Error('Incorrect key passphrase'); - } - } - - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - throw new Error('Error reading MPIs'); - } - this.isEncrypted = false; - this.keyMaterial = null; - this.s2kUsage = 0; - } - - /** - * Checks that the key parameters are consistent - * @throws {Error} if validation was not successful - * @async - */ - async validate() { - if (this.isDummy()) { - return; - } - - if (!this.isDecrypted()) { - throw new Error('Key is not decrypted'); - } - - let validParams; - try { - // this can throw if some parameters are undefined - validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); - } catch (_) { - validParams = false; - } - if (!validParams) { - throw new Error('Key is invalid'); - } - } - - async generate(bits, curve) { - const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); - this.privateParams = privateParams; - this.publicParams = publicParams; - this.isEncrypted = false; - } - - /** - * Clear private key parameters - */ - clearPrivateParams() { - if (this.isMissingSecretKeyMaterial()) { - return; - } - - Object.keys(this.privateParams).forEach(name => { - const param = this.privateParams[name]; - param.fill(0); - delete this.privateParams[name]; - }); - this.privateParams = null; - this.isEncrypted = true; - } -} - -async function produceEncryptionKey(s2k, passphrase, algorithm) { - const { keySize } = mod.getCipher(algorithm); - return s2k.produceKey(passphrase, keySize); -} - -var emailAddresses = createCommonjsModule(function (module) { -// email-addresses.js - RFC 5322 email address parser -// v 3.1.0 -// -// http://tools.ietf.org/html/rfc5322 -// -// This library does not validate email addresses. -// emailAddresses attempts to parse addresses using the (fairly liberal) -// grammar specified in RFC 5322. -// -// email-addresses returns { -// ast: , -// addresses: [{ -// node: , -// name: , -// address: , -// local: , -// domain: -// }, ...] -// } -// -// emailAddresses.parseOneAddress and emailAddresses.parseAddressList -// work as you might expect. Try it out. -// -// Many thanks to Dominic Sayers and his documentation on the is_email function, -// http://code.google.com/p/isemail/ , which helped greatly in writing this parser. - -(function (global) { - -function parse5322(opts) { - - // tokenizing functions - - function inStr() { return pos < len; } - function curTok() { return parseString[pos]; } - function getPos() { return pos; } - function setPos(i) { pos = i; } - function nextTok() { pos += 1; } - function initialize() { - pos = 0; - len = parseString.length; - } - - // parser helper functions - - function o(name, value) { - return { - name: name, - tokens: value || "", - semantic: value || "", - children: [] - }; - } - - function wrap(name, ast) { - var n; - if (ast === null) { return null; } - n = o(name); - n.tokens = ast.tokens; - n.semantic = ast.semantic; - n.children.push(ast); - return n; - } - - function add(parent, child) { - if (child !== null) { - parent.tokens += child.tokens; - parent.semantic += child.semantic; - } - parent.children.push(child); - return parent; - } - - function compareToken(fxnCompare) { - var tok; - if (!inStr()) { return null; } - tok = curTok(); - if (fxnCompare(tok)) { - nextTok(); - return o('token', tok); - } - return null; - } - - function literal(lit) { - return function literalFunc() { - return wrap('literal', compareToken(function (tok) { - return tok === lit; - })); - }; - } - - function and() { - var args = arguments; - return function andFunc() { - var i, s, result, start; - start = getPos(); - s = o('and'); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result === null) { - setPos(start); - return null; - } - add(s, result); - } - return s; - }; - } - - function or() { - var args = arguments; - return function orFunc() { - var i, result, start; - start = getPos(); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result !== null) { - return result; - } - setPos(start); - } - return null; - }; - } - - function opt(prod) { - return function optFunc() { - var result, start; - start = getPos(); - result = prod(); - if (result !== null) { - return result; - } - else { - setPos(start); - return o('opt'); - } - }; - } - - function invis(prod) { - return function invisFunc() { - var result = prod(); - if (result !== null) { - result.semantic = ""; - } - return result; - }; - } - - function colwsp(prod) { - return function collapseSemanticWhitespace() { - var result = prod(); - if (result !== null && result.semantic.length > 0) { - result.semantic = " "; - } - return result; - }; - } - - function star(prod, minimum) { - return function starFunc() { - var s, result, count, start, min; - start = getPos(); - s = o('star'); - count = 0; - min = minimum === undefined ? 0 : minimum; - while ((result = prod()) !== null) { - count = count + 1; - add(s, result); - } - if (count >= min) { - return s; - } - else { - setPos(start); - return null; - } - }; - } - - // One expects names to get normalized like this: - // " First Last " -> "First Last" - // "First Last" -> "First Last" - // "First Last" -> "First Last" - function collapseWhitespace(s) { - return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, ''); - } - - // UTF-8 pseudo-production (RFC 6532) - // RFC 6532 extends RFC 5322 productions to include UTF-8 - // using the following productions: - // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // UTF8-2 = - // UTF8-3 = - // UTF8-4 = - // - // For reference, the extended RFC 5322 productions are: - // VCHAR =/ UTF8-non-ascii - // ctext =/ UTF8-non-ascii - // atext =/ UTF8-non-ascii - // qtext =/ UTF8-non-ascii - // dtext =/ UTF8-non-ascii - function isUTF8NonAscii(tok) { - // In JavaScript, we just deal directly with Unicode code points, - // so we aren't checking individual bytes for UTF-8 encoding. - // Just check that the character is non-ascii. - return tok.charCodeAt(0) >= 128; - } - - - // common productions (RFC 5234) - // http://tools.ietf.org/html/rfc5234 - // B.1. Core Rules - - // CR = %x0D - // ; carriage return - function cr() { return wrap('cr', literal('\r')()); } - - // CRLF = CR LF - // ; Internet standard newline - function crlf() { return wrap('crlf', and(cr, lf)()); } - - // DQUOTE = %x22 - // ; " (Double Quote) - function dquote() { return wrap('dquote', literal('"')()); } - - // HTAB = %x09 - // ; horizontal tab - function htab() { return wrap('htab', literal('\t')()); } - - // LF = %x0A - // ; linefeed - function lf() { return wrap('lf', literal('\n')()); } - - // SP = %x20 - function sp() { return wrap('sp', literal(' ')()); } - - // VCHAR = %x21-7E - // ; visible (printing) characters - function vchar() { - return wrap('vchar', compareToken(function vcharFunc(tok) { - var code = tok.charCodeAt(0); - var accept = (0x21 <= code && code <= 0x7E); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } - - // WSP = SP / HTAB - // ; white space - function wsp() { return wrap('wsp', or(sp, htab)()); } - - - // email productions (RFC 5322) - // http://tools.ietf.org/html/rfc5322 - // 3.2.1. Quoted characters - - // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp - function quotedPair() { - var qp = wrap('quoted-pair', - or( - and(literal('\\'), or(vchar, wsp)), - obsQP - )()); - if (qp === null) { return null; } - // a quoted pair will be two characters, and the "\" character - // should be semantically "invisible" (RFC 5322 3.2.1) - qp.semantic = qp.semantic[1]; - return qp; - } - - // 3.2.2. Folding White Space and Comments - - // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS - function fws() { - return wrap('fws', or( - obsFws, - and( - opt(and( - star(wsp), - invis(crlf) - )), - star(wsp, 1) - ) - )()); - } - - // ctext = %d33-39 / ; Printable US-ASCII - // %d42-91 / ; characters not including - // %d93-126 / ; "(", ")", or "\" - // obs-ctext - function ctext() { - return wrap('ctext', or( - function ctextFunc1() { - return compareToken(function ctextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 39) || - (42 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsCtext - )()); - } - - // ccontent = ctext / quoted-pair / comment - function ccontent() { - return wrap('ccontent', or(ctext, quotedPair, comment)()); - } - - // comment = "(" *([FWS] ccontent) [FWS] ")" - function comment() { - return wrap('comment', and( - literal('('), - star(and(opt(fws), ccontent)), - opt(fws), - literal(')') - )()); - } - - // CFWS = (1*([FWS] comment) [FWS]) / FWS - function cfws() { - return wrap('cfws', or( - and( - star( - and(opt(fws), comment), - 1 - ), - opt(fws) - ), - fws - )()); - } - - // 3.2.3. Atom - - //atext = ALPHA / DIGIT / ; Printable US-ASCII - // "!" / "#" / ; characters not including - // "$" / "%" / ; specials. Used for atoms. - // "&" / "'" / - // "*" / "+" / - // "-" / "/" / - // "=" / "?" / - // "^" / "_" / - // "`" / "{" / - // "|" / "}" / - // "~" - function atext() { - return wrap('atext', compareToken(function atextFunc(tok) { - var accept = - ('a' <= tok && tok <= 'z') || - ('A' <= tok && tok <= 'Z') || - ('0' <= tok && tok <= '9') || - (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', - '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } - - // atom = [CFWS] 1*atext [CFWS] - function atom() { - return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))()); - } - - // dot-atom-text = 1*atext *("." 1*atext) - function dotAtomText() { - var s, maybeText; - s = wrap('dot-atom-text', star(atext, 1)()); - if (s === null) { return s; } - maybeText = star(and(literal('.'), star(atext, 1)))(); - if (maybeText !== null) { - add(s, maybeText); - } - return s; - } - - // dot-atom = [CFWS] dot-atom-text [CFWS] - function dotAtom() { - return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))()); - } - - // 3.2.4. Quoted Strings - - // qtext = %d33 / ; Printable US-ASCII - // %d35-91 / ; characters not including - // %d93-126 / ; "\" or the quote character - // obs-qtext - function qtext() { - return wrap('qtext', or( - function qtextFunc1() { - return compareToken(function qtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 === code) || - (35 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsQtext - )()); - } - - // qcontent = qtext / quoted-pair - function qcontent() { - return wrap('qcontent', or(qtext, quotedPair)()); - } - - // quoted-string = [CFWS] - // DQUOTE *([FWS] qcontent) [FWS] DQUOTE - // [CFWS] - function quotedString() { - return wrap('quoted-string', and( - invis(opt(cfws)), - invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), - invis(opt(cfws)) - )()); + * @async + */ + async encrypt(passphrase, config$1 = config) { + if (this.isDummy()) { + return; } - // 3.2.5 Miscellaneous Tokens - - // word = atom / quoted-string - function word() { - return wrap('word', or(atom, quotedString)()); + if (!this.isDecrypted()) { + throw new Error('Key packet is already encrypted'); } - // phrase = 1*word / obs-phrase - function phrase() { - return wrap('phrase', or(obsPhrase, star(word, 1))()); + if (!passphrase) { + throw new Error('A non-empty passphrase is required for key encryption.'); } - // 3.4. Address Specification - // address = mailbox / group - function address() { - return wrap('address', or(mailbox, group)()); - } + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + const cleartext = mod.serializeParams(this.algorithm, this.privateParams); + this.symmetric = enums.symmetric.aes256; - // mailbox = name-addr / addr-spec - function mailbox() { - return wrap('mailbox', or(nameAddr, addrSpec)()); - } + const { blockSize } = mod.getCipherParams(this.symmetric); - // name-addr = [display-name] angle-addr - function nameAddr() { - return wrap('name-addr', and(opt(displayName), angleAddr)()); - } + if (config$1.aeadProtect) { + this.s2kUsage = 253; + this.aead = config$1.preferredAEADAlgorithm; + const mode = mod.getAEADMode(this.aead); + this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead. + this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material - // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / - // obs-angle-addr - function angleAddr() { - return wrap('angle-addr', or( - and( - invis(opt(cfws)), - literal('<'), - addrSpec, - literal('>'), - invis(opt(cfws)) - ), - obsAngleAddr - )()); - } + const serializedPacketTag = writeTag(this.constructor.tag); + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); - // group = display-name ":" [group-list] ";" [CFWS] - function group() { - return wrap('group', and( - displayName, - literal(':'), - opt(groupList), - literal(';'), - invis(opt(cfws)) - )()); - } + const modeInstance = await mode(this.symmetric, key); + this.iv = this.isLegacyAEAD ? mod.random.getRandomBytes(blockSize) : mod.random.getRandomBytes(mode.ivLength); + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); - // display-name = phrase - function displayName() { - return wrap('display-name', function phraseFixedSemantic() { - var result = phrase(); - if (result !== null) { - result.semantic = collapseWhitespace(result.semantic); - } - return result; - }()); - } - - // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list - function mailboxList() { - return wrap('mailbox-list', or( - and( - mailbox, - star(and(literal(','), mailbox)) - ), - obsMboxList - )()); - } - - // address-list = (address *("," address)) / obs-addr-list - function addressList() { - return wrap('address-list', or( - and( - address, - star(and(literal(','), address)) - ), - obsAddrList - )()); - } - - // group-list = mailbox-list / CFWS / obs-group-list - function groupList() { - return wrap('group-list', or( - mailboxList, - invis(cfws), - obsGroupList - )()); - } - - // 3.4.1 Addr-Spec Specification - - // local-part = dot-atom / quoted-string / obs-local-part - function localPart() { - // note: quoted-string, dotAtom are proper subsets of obs-local-part - // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree - return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)()); - } - - // dtext = %d33-90 / ; Printable US-ASCII - // %d94-126 / ; characters not including - // obs-dtext ; "[", "]", or "\" - function dtext() { - return wrap('dtext', or( - function dtextFunc1() { - return compareToken(function dtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 90) || - (94 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsDtext - )() - ); + this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData); + } else { + this.s2kUsage = 254; + this.usedModernAEAD = false; + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric); + this.iv = mod.random.getRandomBytes(blockSize); + this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + cleartext, + await mod.hash.sha1(cleartext, config$1) + ]), this.iv, config$1); } + } - // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - function domainLiteral() { - return wrap('domain-literal', and( - invis(opt(cfws)), - literal('['), - star(and(opt(fws), dtext)), - opt(fws), - literal(']'), - invis(opt(cfws)) - )()); - } - - // domain = dot-atom / domain-literal / obs-domain - function domain() { - return wrap('domain', function domainCheckTLD() { - var result = or(obsDomain, dotAtom, domainLiteral)(); - if (opts.rejectTLD) { - if (result && result.semantic && result.semantic.indexOf('.') < 0) { - return null; - } - } - // strip all whitespace from domains - if (result) { - result.semantic = result.semantic.replace(/\s+/g, ''); - } - return result; - }()); - } - - // addr-spec = local-part "@" domain - function addrSpec() { - return wrap('addr-spec', and( - localPart, literal('@'), domain - )()); - } - - // 3.6.2 Originator Fields - // Below we only parse the field body, not the name of the field - // like "From:", "Sender:", or "Reply-To:". Other libraries that - // parse email headers can parse those and defer to these productions - // for the "RFC 5322" part. - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // from = "From:" (mailbox-list / address-list) CRLF - function fromSpec() { - return wrap('from', or( - mailboxList, - addressList - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // sender = "Sender:" (mailbox / address) CRLF - function senderSpec() { - return wrap('sender', or( - mailbox, - address - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // reply-to = "Reply-To:" address-list CRLF - function replyToSpec() { - return wrap('reply-to', addressList()); - } - - // 4.1. Miscellaneous Obsolete Tokens - - // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control - // %d11 / ; characters that do not - // %d12 / ; include the carriage - // %d14-31 / ; return, line feed, and - // %d127 ; white space characters - function obsNoWsCtl() { - return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) { - var code = tok.charCodeAt(0); - return ((1 <= code && code <= 8) || - (11 === code || 12 === code) || - (14 <= code && code <= 31) || - (127 === code)); - })); + /** + * Decrypts the private key params which are needed to use the key. + * Successful decryption does not imply key integrity, call validate() to confirm that. + * {@link SecretKeyPacket.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param {String} passphrase - The passphrase for this private key as string + * @throws {Error} if the key is already decrypted, or if decryption was not successful + * @async + */ + async decrypt(passphrase) { + if (this.isDummy()) { + return false; } - // obs-ctext = obs-NO-WS-CTL - function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); } - - // obs-qtext = obs-NO-WS-CTL - function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); } - - // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) - function obsQP() { - return opts.strict ? null : wrap('obs-qp', and( - literal('\\'), - or(literal('\0'), obsNoWsCtl, lf, cr) - )()); - } - - // obs-phrase = word *(word / "." / CFWS) - function obsPhrase() { - if (opts.strict ) return null; - return opts.atInDisplayName ? wrap('obs-phrase', and( - word, - star(or(word, literal('.'), literal('@'), colwsp(cfws))) - )()) : - wrap('obs-phrase', and( - word, - star(or(word, literal('.'), colwsp(cfws))) - )()); - } - - // 4.2. Obsolete Folding White Space - - // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908 - // obs-FWS = 1*([CRLF] WSP) - function obsFws() { - return opts.strict ? null : wrap('obs-FWS', star( - and(invis(opt(crlf)), wsp), - 1 - )()); - } - - // 4.4. Obsolete Addressing - - // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] - function obsAngleAddr() { - return opts.strict ? null : wrap('obs-angle-addr', and( - invis(opt(cfws)), - literal('<'), - obsRoute, - addrSpec, - literal('>'), - invis(opt(cfws)) - )()); - } - - // obs-route = obs-domain-list ":" - function obsRoute() { - return opts.strict ? null : wrap('obs-route', and( - obsDomainList, - literal(':') - )()); - } - - // obs-domain-list = *(CFWS / ",") "@" domain - // *("," [CFWS] ["@" domain]) - function obsDomainList() { - return opts.strict ? null : wrap('obs-domain-list', and( - star(or(invis(cfws), literal(','))), - literal('@'), - domain, - star(and( - literal(','), - invis(opt(cfws)), - opt(and(literal('@'), domain)) - )) - )()); - } - - // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) - function obsMboxList() { - return opts.strict ? null : wrap('obs-mbox-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - mailbox, - star(and( - literal(','), - opt(and( - mailbox, - invis(cfws) - )) - )) - )()); - } - - // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) - function obsAddrList() { - return opts.strict ? null : wrap('obs-addr-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - address, - star(and( - literal(','), - opt(and( - address, - invis(cfws) - )) - )) - )()); - } - - // obs-group-list = 1*([CFWS] ",") [CFWS] - function obsGroupList() { - return opts.strict ? null : wrap('obs-group-list', and( - star(and( - invis(opt(cfws)), - literal(',') - ), 1), - invis(opt(cfws)) - )()); - } - - // obs-local-part = word *("." word) - function obsLocalPart() { - return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))()); - } - - // obs-domain = atom *("." atom) - function obsDomain() { - return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))()); - } - - // obs-dtext = obs-NO-WS-CTL / quoted-pair - function obsDtext() { - return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)()); - } - - ///////////////////////////////////////////////////// - - // ast analysis - - function findNode(name, root) { - var i, stack, node; - if (root === null || root === undefined) { return null; } - stack = [root]; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - return node; - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return null; - } - - function findAllNodes(name, root) { - var i, stack, node, result; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - result.push(node); - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return result; + if (this.unparseableKeyMaterial) { + throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); } - function findAllNodesNoChildren(names, root) { - var i, stack, node, result, namesLookup; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - namesLookup = {}; - for (i = 0; i < names.length; i += 1) { - namesLookup[names[i]] = true; - } - - while (stack.length > 0) { - node = stack.pop(); - if (node.name in namesLookup) { - result.push(node); - // don't look at children (hence findAllNodesNoChildren) - } else { - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - } - return result; + if (this.isDecrypted()) { + throw new Error('Key packet is already decrypted.'); } - function giveResult(ast) { - var addresses, groupsAndMailboxes, i, groupOrMailbox, result; - if (ast === null) { - return null; - } - addresses = []; - - // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'. - groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast); - for (i = 0; i < groupsAndMailboxes.length; i += 1) { - groupOrMailbox = groupsAndMailboxes[i]; - if (groupOrMailbox.name === 'group') { - addresses.push(giveResultGroup(groupOrMailbox)); - } else if (groupOrMailbox.name === 'mailbox') { - addresses.push(giveResultMailbox(groupOrMailbox)); - } - } - - result = { - ast: ast, - addresses: addresses, - }; - if (opts.simple) { - result = simplifyResult(result); - } - if (opts.oneResult) { - return oneResult(result); - } - if (opts.simple) { - return result && result.addresses; - } else { - return result; - } + let key; + const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only + if (this.s2kUsage === 254 || this.s2kUsage === 253) { + key = await produceEncryptionKey( + this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + } else if (this.s2kUsage === 255) { + throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); + } else { + throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); } - function giveResultGroup(group) { - var i; - var groupName = findNode('display-name', group); - var groupResultMailboxes = []; - var mailboxes = findAllNodesNoChildren(['mailbox'], group); - for (i = 0; i < mailboxes.length; i += 1) { - groupResultMailboxes.push(giveResultMailbox(mailboxes[i])); + let cleartext; + if (this.s2kUsage === 253) { + const mode = mod.getAEADMode(this.aead); + const modeInstance = await mode(this.symmetric, key); + try { + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData); + } catch (err) { + if (err.message === 'Authentication tag mismatch') { + throw new Error('Incorrect key passphrase: ' + err.message); } - return { - node: group, - parts: { - name: groupName, - }, - type: group.name, // 'group' - name: grabSemantic(groupName), - addresses: groupResultMailboxes, - }; - } - - function giveResultMailbox(mailbox) { - var name = findNode('display-name', mailbox); - var aspec = findNode('addr-spec', mailbox); - var cfws = findAllNodes('cfws', mailbox); - var comments = findAllNodesNoChildren(['comment'], mailbox); - + throw err; + } + } else { + const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); - var local = findNode('local-part', aspec); - var domain = findNode('domain', aspec); - return { - node: mailbox, - parts: { - name: name, - address: aspec, - local: local, - domain: domain, - comments: cfws - }, - type: mailbox.name, // 'mailbox' - name: grabSemantic(name), - address: grabSemantic(aspec), - local: grabSemantic(local), - domain: grabSemantic(domain), - comments: concatComments(comments), - groupName: grabSemantic(mailbox.groupName), - }; - } + cleartext = cleartextWithHash.subarray(0, -20); + const hash = await mod.hash.sha1(cleartext); - function grabSemantic(n) { - return n !== null && n !== undefined ? n.semantic : null; + if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { + throw new Error('Incorrect key passphrase'); + } } - function simplifyResult(result) { - var i; - if (result && result.addresses) { - for (i = 0; i < result.addresses.length; i += 1) { - delete result.addresses[i].node; - } - } - return result; + try { + const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + this.privateParams = privateParams; + } catch (err) { + throw new Error('Error reading MPIs'); } + this.isEncrypted = false; + this.keyMaterial = null; + this.s2kUsage = 0; + this.aead = null; + this.symmetric = null; + this.isLegacyAEAD = null; + } - function concatComments(comments) { - var result = ''; - if (comments) { - for (var i = 0; i < comments.length; i += 1) { - result += grabSemantic(comments[i]); - } - } - return result; + /** + * Checks that the key parameters are consistent + * @throws {Error} if validation was not successful + * @async + */ + async validate() { + if (this.isDummy()) { + return; } - function oneResult(result) { - if (!result) { return null; } - if (!opts.partial && result.addresses.length > 1) { return null; } - return result.addresses && result.addresses[0]; + if (!this.isDecrypted()) { + throw new Error('Key is not decrypted'); } - ///////////////////////////////////////////////////// - - var parseString, pos, len, parsed, startProduction; - - opts = handleOpts(opts, {}); - if (opts === null) { return null; } - - parseString = opts.input; - - startProduction = { - 'address': address, - 'address-list': addressList, - 'angle-addr': angleAddr, - 'from': fromSpec, - 'group': group, - 'mailbox': mailbox, - 'mailbox-list': mailboxList, - 'reply-to': replyToSpec, - 'sender': senderSpec, - }[opts.startAt] || addressList; - - if (!opts.strict) { - initialize(); - opts.strict = true; - parsed = startProduction(parseString); - if (opts.partial || !inStr()) { - return giveResult(parsed); - } - opts.strict = false; + if (this.usedModernAEAD) { + // key integrity confirmed by successful AEAD decryption + return; } - initialize(); - parsed = startProduction(parseString); - if (!opts.partial && inStr()) { return null; } - return giveResult(parsed); -} - -function parseOneAddressSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} - -function parseAddressListSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} - -function parseFromSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'from', - })); -} - -function parseSenderSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'sender', - })); -} - -function parseReplyToSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'reply-to', - })); -} - -function handleOpts(opts, defs) { - function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; + let validParams; + try { + // this can throw if some parameters are undefined + validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); + } catch (_) { + validParams = false; } - - function isObject(o) { - return o === Object(o); + if (!validParams) { + throw new Error('Key is invalid'); } + } - function isNullUndef(o) { - return o === null || o === undefined; + async generate(bits, curve) { + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if (this.version === 6 && ( + (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) || + this.algorithm === enums.publicKey.eddsaLegacy + )) { + throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`); } + const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); + this.privateParams = privateParams; + this.publicParams = publicParams; + this.isEncrypted = false; + } - var defaults, o; - - if (isString(opts)) { - opts = { input: opts }; - } else if (!isObject(opts)) { - return null; + /** + * Clear private key parameters + */ + clearPrivateParams() { + if (this.isMissingSecretKeyMaterial()) { + return; } - if (!isString(opts.input)) { return null; } - if (!defs) { return null; } - - defaults = { - oneResult: false, - partial: false, - rejectTLD: false, - rfc6532: false, - simple: false, - startAt: 'address-list', - strict: false, - atInDisplayName: false - }; - - for (o in defaults) { - if (isNullUndef(opts[o])) { - opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o]; - } - } - return opts; + Object.keys(this.privateParams).forEach(name => { + const param = this.privateParams[name]; + param.fill(0); + delete this.privateParams[name]; + }); + this.privateParams = null; + this.isEncrypted = true; + } } -parse5322.parseOneAddress = parseOneAddressSimple; -parse5322.parseAddressList = parseAddressListSimple; -parse5322.parseFrom = parseFromSimple; -parse5322.parseSender = parseSenderSimple; -parse5322.parseReplyTo = parseReplyToSimple; - -{ - module.exports = parse5322; +/** + * Derive encryption key + * @param {Number} keyVersion - key derivation differs for v5 keys + * @param {module:type/s2k} s2k + * @param {String} passphrase + * @param {module:enums.symmetric} cipherAlgo + * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5) + * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5) + * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only) + * @returns encryption key + */ +async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) { + if (s2k.type === 'argon2' && !aeadMode) { + throw new Error('Using Argon2 S2K without AEAD is not allowed'); + } + if (s2k.type === 'simple' && keyVersion === 6) { + throw new Error('Using Simple S2K with version 6 keys is not allowed'); + } + const { keySize } = mod.getCipherParams(cipherAlgo); + const derivedKey = await s2k.produceKey(passphrase, keySize); + if (!aeadMode || keyVersion === 5 || isLegacyAEAD) { + return derivedKey; + } + const info = util.concatUint8Array([ + serializedPacketTag, + new Uint8Array([keyVersion, cipherAlgo, aeadMode]) + ]); + return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize); } -}()); -}); - // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Implementation of the User ID Packet (Tag 13) @@ -27348,12 +16560,27 @@ class UserIDPacket { if (userID.length > config$1.maxUserIDLength) { throw new Error('User ID string is too long'); } - try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); - this.comment = comments.replace(/^\(|\)$/g, ''); - this.name = name; - this.email = email; - } catch (e) {} + + /** + * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1, + * as well comments placed between the name (if present) and the bracketed email address: + * - name (comment) + * - email + * In the first case, the `email` is the only required part, and it must contain the `@` symbol. + * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, + * since they interfere with `comment` parsing. + */ + const re = /^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/; + const matches = re.exec(userID); + if (matches !== null) { + const { name, comment, email } = matches.groups; + this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace + this.name = name?.trim() || ''; + this.email = email.substring(1, email.length - 1); // remove brackets + } else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace + this.email = userID; + } + this.userID = userID; } @@ -27371,6 +16598,22 @@ class UserIDPacket { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret @@ -27424,10 +16667,86 @@ class TrustPacket { } } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2022 Proton AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Padding Packet + * + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}: + * Padding Packet + */ +class PaddingPacket { + static get tag() { + return enums.packet.padding; + } + + constructor() { + this.padding = null; + } + + /** + * Read a padding packet + * @param {Uint8Array | ReadableStream} bytes + */ + read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars + // Padding packets are ignored, so this function is never called. + } + + /** + * Write the padding packet + * @returns {Uint8Array} The padding packet. + */ + write() { + return this.padding; + } + + /** + * Create random padding. + * @param {Number} length - The length of padding to be generated. + * @throws {Error} if padding generation was not successful + * @async + */ + async createPadding(length) { + this.padding = await mod.random.getRandomBytes(length); + } +} + // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A Signature can contain the following packets -const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); +const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP signature. @@ -27454,7 +16773,9 @@ class Signature { * @returns {ReadableStream} ASCII armor. */ armor(config$1 = config) { - return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1); + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1); } /** @@ -27491,22 +16812,22 @@ async function readSignature({ armoredSignature, binarySignature, config: config const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); if (armoredSignature) { - const { type, data } = await unarmor(input, config$1); + const { type, data } = await unarmor(input); if (type !== enums.armor.signature) { throw new Error('Armored text not of type signature'); } input = data; } - const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1); + const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1); return new Signature(packetlist); } /** * @fileoverview Provides helpers methods for key module * @module key/helper - * @private */ + async function generateSecretSubkey(options, config) { const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); secretSubkeyPacket.packets = null; @@ -27529,6 +16850,8 @@ async function generateSecretKey(options, config) { * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. * @param {Array} signatures - List of signatures * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature + * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures, + * `enums.signatures.certGeneric` should be given regardless of the actual trust level) * @param {Date} date - Use the given date instead of the current time * @param {Object} config - full configuration * @returns {Promise} The latest valid signature. @@ -27582,7 +16905,7 @@ async function createBindingSignature(subkey, primaryKey, options, config) { const signatureProperties = { signatureType: enums.signature.subkeyBinding }; if (options.sign) { signatureProperties.keyFlags = [enums.keyFlags.signData]; - signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, { + signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, { signatureType: enums.signature.keyBinding }, options.date, undefined, undefined, undefined, config); } else { @@ -27592,83 +16915,166 @@ async function createBindingSignature(subkey, primaryKey, options, config) { signatureProperties.keyExpirationTime = options.keyExpirationTime; signatureProperties.keyNeverExpires = false; } - const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); + const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); return subkeySignaturePacket; } /** - * Returns the preferred signature hash algorithm of a key - * @param {Key} [key] - The key to get preferences from - * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing + * Returns the preferred signature hash algorithm for a set of keys. + * @param {Array} [targetKeys] - The keys to get preferences from + * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID + * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from * @param {Object} config - full configuration * @returns {Promise} * @async */ -async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) { - let hashAlgo = config.preferredHashAlgorithm; - let prefAlgo = hashAlgo; - if (key) { - const primaryUser = await key.getPrimaryUser(date, userID, config); - if (primaryUser.selfCertification.preferredHashAlgorithms) { - [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; +async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) { + /** + * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the + * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys). + * if no keys are available, `preferredSenderAlgo` is returned. + * For ECC signing key, the curve preferred hash is taken into account as well (see logic below). + */ + const defaultAlgo = enums.hash.sha256; // MUST implement + const preferredSenderAlgo = config.preferredHashAlgorithm; + + const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => { + const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config); + const targetPrefs = selfCertification.preferredHashAlgorithms; + return targetPrefs; + })); + const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys + for (const supportedAlgos of supportedAlgosPerTarget) { + for (const hashAlgo of supportedAlgos) { + try { + // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on + const supportedAlgo = enums.write(enums.hash, hashAlgo); + supportedAlgosMap.set( + supportedAlgo, + supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1 + ); + } catch {} } } - switch (keyPacket.algorithm) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ed25519: - prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid); + const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo; + const getStrongestSupportedHashAlgo = () => { + if (supportedAlgosMap.size === 0) { + return defaultAlgo; + } + const sortedHashAlgos = Array.from(supportedAlgosMap.keys()) + .filter(hashAlgo => isSupportedHashAlgo(hashAlgo)) + .sort((algoA, algoB) => mod.hash.getHashByteLength(algoA) - mod.hash.getHashByteLength(algoB)); + const strongestHashAlgo = sortedHashAlgos[0]; + // defaultAlgo is always implicilty supported, and might be stronger than the rest + return mod.hash.getHashByteLength(strongestHashAlgo) >= mod.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo; + }; + + const eccAlgos = new Set([ + enums.publicKey.ecdsa, + enums.publicKey.eddsaLegacy, + enums.publicKey.ed25519, + enums.publicKey.ed448 + ]); + + if (eccAlgos.has(signingKeyPacket.algorithm)) { + // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see: + // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5 + // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough; + // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve + // preferred algo, even if not supported by all targets. + const preferredCurveAlgo = mod.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid); + + const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo); + const preferredSenderAlgoStrongerThanCurveAlgo = mod.hash.getHashByteLength(preferredSenderAlgo) >= mod.hash.getHashByteLength(preferredCurveAlgo); + + if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) { + return preferredSenderAlgo; + } else { + const strongestSupportedAlgo = getStrongestSupportedHashAlgo(); + return mod.hash.getHashByteLength(strongestSupportedAlgo) >= mod.hash.getHashByteLength(preferredCurveAlgo) ? + strongestSupportedAlgo : + preferredCurveAlgo; + } } - return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; + + // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this, + // since it was manually set by the sender. + return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo(); } /** - * Returns the preferred symmetric/aead/compression algorithm for a set of keys - * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return + * Returns the preferred compression algorithm for a set of keys * @param {Array} [keys] - Set of keys * @param {Date} [date] - Use the given date for verification instead of the current time * @param {Array} [userIDs] - User IDs * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Preferred algorithm + * @returns {Promise} Preferred compression algorithm * @async */ -async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) { - const defaultAlgo = { // these are all must-implement in rfc4880bis - 'symmetric': enums.symmetric.aes128, - 'aead': enums.aead.eax, - 'compression': enums.compression.uncompressed - }[type]; - const preferredSenderAlgo = { - 'symmetric': config$1.preferredSymmetricAlgorithm, - 'aead': config$1.preferredAEADAlgorithm, - 'compression': config$1.preferredCompressionAlgorithm - }[type]; - const prefPropertyName = { - 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAEADAlgorithms', - 'compression': 'preferredCompressionAlgorithms' - }[type]; +async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const defaultAlgo = enums.compression.uncompressed; + const preferredSenderAlgo = config$1.preferredCompressionAlgorithm; // if preferredSenderAlgo appears in the prefs of all recipients, we pick it // otherwise we use the default algo // if no keys are available, preferredSenderAlgo is returned const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; + const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1); + const recipientPrefs = selfCertification.preferredCompressionAlgorithms; return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; })); return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; } +/** + * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred + * @async + */ +async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1))); + const withAEAD = keys.length ? + selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) : + config$1.aeadProtect; + + if (withAEAD) { + const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb }; + const desiredCipherSuites = [ + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm }, + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb }, + { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm } + ]; + for (const desiredCipherSuite of desiredCipherSuites) { + if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some( + cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo + ))) { + return desiredCipherSuite; + } + } + return defaultCipherSuite; + } + const defaultSymAlgo = enums.symmetric.aes128; + const desiredSymAlgo = config$1.preferredSymmetricAlgorithm; + return { + symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ? + desiredSymAlgo : + defaultSymAlgo, + aeadAlgo: undefined + }; +} + /** * Create signature packet * @param {Object} dataToSign - Contains packets to be signed - * @param {PrivateKey} privateKey - key to get preferences from + * @param {Array} recipientKeys - keys to get preferences from * @param {SecretKeyPacket| * SecretSubkeyPacket} signingKeyPacket secret key packet for signing * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing @@ -27679,7 +17085,7 @@ async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [] * @param {Object} config - full configuration * @returns {Promise} Signature packet. */ -async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) { +async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) { if (signingKeyPacket.isDummy()) { throw new Error('Cannot sign with a gnu-dummy key.'); } @@ -27689,9 +17095,9 @@ async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, s const signaturePacket = new SignaturePacket(); Object.assign(signaturePacket, signatureProperties); signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config); - signaturePacket.rawNotations = notations; - await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached); + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config); + signaturePacket.rawNotations = [...notations]; + await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config); return signaturePacket; } @@ -27753,8 +17159,14 @@ async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocation // `verifyAllCertifications`.) !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) ) { + const isHardRevocation = ![ + enums.reasonForRevocation.keyRetired, + enums.reasonForRevocation.keySuperseded, + enums.reasonForRevocation.userIDInvalid + ].includes(revocationSignature.reasonForRevocationFlag); + await revocationSignature.verify( - key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config + key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config ); // TODO get an identifier of the revoked object instead @@ -27787,28 +17199,6 @@ function getKeyExpirationTime(keyPacket, signature) { return expirationTime ? new Date(expirationTime) : Infinity; } -/** - * Returns whether aead is supported by all keys in the set - * @param {Array} keys - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} config - full configuration - * @returns {Promise} - * @async - */ -async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) { - let supported = true; - // TODO replace when Promise.some or Promise.any are implemented - await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - if (!primaryUser.selfCertification.features || - !(primaryUser.selfCertification.features[0] & enums.features.aead)) { - supported = false; - } - })); - return supported; -} - function sanitizeKeyOptions(options, subkeyDefaults = {}) { options.type = options.type || subkeyDefaults.type; options.curve = options.curve || subkeyDefaults.curve; @@ -27820,13 +17210,14 @@ function sanitizeKeyOptions(options, subkeyDefaults = {}) { options.sign = options.sign || false; switch (options.type) { - case 'ecc': + case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve` try { options.curve = enums.write(enums.curve, options.curve); } catch (e) { throw new Error('Unknown curve'); } - if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) { + if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy || + options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; } if (options.sign) { @@ -27835,6 +17226,12 @@ function sanitizeKeyOptions(options, subkeyDefaults = {}) { options.algorithm = enums.publicKey.ecdh; } break; + case 'curve25519': + options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519; + break; + case 'curve448': + options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448; + break; case 'rsa': options.algorithm = enums.publicKey.rsaEncryptSign; break; @@ -27844,37 +17241,69 @@ function sanitizeKeyOptions(options, subkeyDefaults = {}) { return options; } -function isValidSigningKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.rsaEncrypt && - keyAlgo !== enums.publicKey.elgamal && - keyAlgo !== enums.publicKey.ecdh && - keyAlgo !== enums.publicKey.x25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.signData) !== 0); -} - -function isValidEncryptionKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.dsa && - keyAlgo !== enums.publicKey.rsaSign && - keyAlgo !== enums.publicKey.ecdsa && - keyAlgo !== enums.publicKey.eddsaLegacy && - keyAlgo !== enums.publicKey.ed25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0); +function validateSigningKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + default: + return false; + } } -function isValidDecryptionKeyPacket(signature, config) { - if (config.allowInsecureDecryptionWithSigningKeys) { - // This is only relevant for RSA keys, all other signing algorithms cannot decrypt - return true; +function validateEncryptionKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + default: + return false; } +} + +function validateDecryptionKeyPacket(keyPacket, signature, config) { + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) { + // This is only relevant for RSA keys, all other signing algorithms cannot decrypt + return true; + } - return !signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + } + default: + return false; + } } /** @@ -27910,9 +17339,9 @@ function checkKeyRequirements(keyPacket, config) { /** * @module key/User - * @private */ + /** * Class that represents an user ID or attribute packet and the relevant signatures. * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info @@ -27977,7 +17406,7 @@ class User { throw new Error("The user's own key can only be used for self-certifications"); } const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); - return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, { + return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, { // Most OpenPGP implementations use generic certification (0x10) signatureType: enums.signature.certGeneric, keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] @@ -28165,7 +17594,7 @@ class User { key: primaryKey }; const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { + user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { signatureType: enums.signature.certRevocation, reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), reasonForRevocationString @@ -28177,9 +17606,9 @@ class User { /** * @module key/Subkey - * @private */ + /** * Class that represents a subkey packet and the relevant signatures. * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID @@ -28358,7 +17787,7 @@ class Subkey { ) { const dataToSign = { key: primaryKey, bind: this.keyPacket }; const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { + subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { signatureType: enums.signature.subkeyRevocation, reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), reasonForRevocationString @@ -28380,6 +17809,22 @@ class Subkey { }); // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A key revocation certificate can contain the following packets const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); @@ -28612,6 +18057,11 @@ class Key { async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { await this.verifyPrimaryKey(date, userID, config$1); const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); + } const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); let exception; for (const subkey of subkeys) { @@ -28622,7 +18072,7 @@ class Key { const bindingSignature = await getLatestValidSignature( subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 ); - if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) { + if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { continue; } if (!bindingSignature.embeddedSignature) { @@ -28641,9 +18091,9 @@ class Key { } try { - const primaryUser = await this.getPrimaryUser(date, userID, config$1); + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) { + validateSigningKeyPacket(primaryKey, selfCertification, config$1)) { checkKeyRequirements(primaryKey, config$1); return this; } @@ -28666,6 +18116,11 @@ class Key { async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { await this.verifyPrimaryKey(date, userID, config$1); const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); + } // V4: by convention subkeys are preferred for encryption service const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); let exception; @@ -28675,7 +18130,7 @@ class Key { await subkey.verify(date, config$1); const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) { + if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { checkKeyRequirements(subkey.keyPacket, config$1); return subkey; } @@ -28687,9 +18142,9 @@ class Key { try { // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { + validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) { checkKeyRequirements(primaryKey, config$1); return this; } @@ -28733,18 +18188,20 @@ class Key { throw new Error('Primary key is revoked'); } // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); // check for expiration time in binding signatures if (isDataExpired(primaryKey, selfCertification, date)) { throw new Error('Primary key is expired'); } - // check for expiration time in direct signatures - const directSignature = await getLatestValidSignature( - this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 - ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key + if (primaryKey.version !== 6) { + // check for expiration time in direct signatures (for V6 keys, the above already did so) + const directSignature = await getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key - if (directSignature && isDataExpired(primaryKey, directSignature, date)) { - throw new Error('Primary key is expired'); + if (directSignature && isDataExpired(primaryKey, directSignature, date)) { + throw new Error('Primary key is expired'); + } } } @@ -28759,12 +18216,13 @@ class Key { async getExpirationTime(userID, config$1 = config) { let primaryKeyExpiry; try { - const { selfCertification } = await this.getPrimaryUser(null, userID, config$1); + const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1); const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); const selfSigExpiry = selfCertification.getExpirationTime(); - const directSignature = await getLatestValidSignature( - this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 - ).catch(() => {}); + const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature. + await getLatestValidSignature( + this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 + ).catch(() => {}); if (directSignature) { const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, @@ -28781,6 +18239,28 @@ class Key { } + /** + * For V4 keys, returns the self-signature of the primary user. + * For V5 keys, returns the latest valid direct-key self-signature. + * This self-signature is to be used to check the key expiration, + * algorithm preferences, and so on. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} The primary self-signature + * @async + */ + async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + if (primaryKey.version === 6) { + return getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ); + } + const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + return selfCertification; + } + /** * Returns primary user and most significant (latest valid) self signature * - if multiple primary users exist, returns the one with the latest self signature @@ -28819,6 +18299,7 @@ class Key { } } if (!users.length) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw exception || new Error('Could not find primary user'); } await Promise.all(users.map(async function (a) { @@ -28930,7 +18411,9 @@ class Key { const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); const packetlist = new PacketList(); packetlist.push(revocationSignature); - return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1); } /** @@ -28944,7 +18427,7 @@ class Key { * @async */ async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { - const input = await unarmor(revocationCertificate, config$1); + const input = await unarmor(revocationCertificate); const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); const revocationSignature = packetlist.findPacket(enums.packet.signature); if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { @@ -29062,6 +18545,19 @@ class Key { }); // This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** * Class that represents an OpenPGP Public Key @@ -29107,7 +18603,9 @@ class PublicKey extends Key { * @returns {ReadableStream} ASCII armor. */ armor(config$1 = config) { - return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); } } @@ -29166,7 +18664,9 @@ class PrivateKey extends PublicKey { * @returns {ReadableStream} ASCII armor. */ armor(config$1 = config) { - return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); } /** @@ -29177,28 +18677,45 @@ class PrivateKey extends PublicKey { * @param {String} userID, optional * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise>} Array of decryption keys. + * @throws {Error} if no decryption key is found * @async */ async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { const primaryKey = this.keyPacket; const keys = []; + let exception = null; for (let i = 0; i < this.subkeys.length; i++) { if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { + if (this.subkeys[i].keyPacket.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + continue; + } + try { const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidDecryptionKeyPacket(bindingSignature, config$1)) { + if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) { keys.push(this.subkeys[i]); } - } catch (e) {} + } catch (e) { + exception = e; + } } } // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && - isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) { - keys.push(this); + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) { + if (primaryKey.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + } else { + keys.push(this); + } + } + + if (keys.length === 0) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('No decryption key packets found'); } return keys; @@ -29289,7 +18806,7 @@ class PrivateKey extends PublicKey { } const dataToSign = { key: this.keyPacket }; const key = this.clone(); - key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, { + key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, { signatureType: enums.signature.keyRevocation, reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), reasonForRevocationString @@ -29300,8 +18817,10 @@ class PrivateKey extends PublicKey { /** * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. - * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. - * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA + * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519. + * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. + * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format). + * Note: Curve448 and Curve25519 are not widely supported yet. * @param {String} options.curve (optional) Elliptic curve for ECC keys * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires @@ -29327,11 +18846,15 @@ class PrivateKey extends PublicKey { throw new Error('Key is not decrypted'); } const defaultOptions = secretKeyPacket.getAlgorithmInfo(); - defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA + defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm); defaultOptions.rsaBits = defaultOptions.bits || 4096; - defaultOptions.curve = defaultOptions.curve || 'curve25519'; + defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy'; options = sanitizeKeyOptions(options, defaultOptions); - const keyPacket = await generateSecretSubkey(options); + // Every subkey for a v4 primary key MUST be a v4 subkey. + // Every subkey for a v6 primary key MUST be a v6 subkey. + // For v5 keys, since we dropped generation support, a v4 subkey is added. + // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user. + const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 }); checkKeyRequirements(keyPacket, config$1); const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); const packetList = this.toPacketList(); @@ -29340,7 +18863,44 @@ class PrivateKey extends PublicKey { } } +function getDefaultSubkeyType(algoName) { + const algo = enums.write(enums.publicKey, algoName); + // NB: no encryption-only algos, since they cannot be in primary keys + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + return 'rsa'; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return 'ecc'; + case enums.publicKey.ed25519: + return 'curve25519'; + case enums.publicKey.ed448: + return 'curve448'; + default: + throw new Error('Unsupported algorithm'); + } +} + // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A Key can contain the following packets const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ @@ -29373,9 +18933,9 @@ function createKey(packetlist) { /** - * Generates a new OpenPGP key. Supports RSA and ECC keys. + * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. * By default, primary and subkeys will be of same type. - * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA + * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format). * @param {String} options.curve Elliptic curve for ECC keys * @param {Integer} options.rsaBits Number of bits for RSA keys * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } @@ -29390,7 +18950,7 @@ function createKey(packetlist) { * @static * @private */ -async function generate$4(options, config) { +async function generate(options, config) { options.sign = true; // primary key is always a signing key options = sanitizeKeyOptions(options); options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); @@ -29497,59 +19057,81 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf const packetlist = new PacketList(); packetlist.push(secretKeyPacket); - await Promise.all(options.userIDs.map(async function(userID, index) { - function createPreferredAlgos(algos, preferredAlgo) { - return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; - } - - const userIDPacket = UserIDPacket.fromObject(userID); - const dataToSign = {}; - dataToSign.userID = userIDPacket; - dataToSign.key = secretKeyPacket; + function createPreferredAlgos(algos, preferredAlgo) { + return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + } + function getKeySignatureProperties() { const signatureProperties = {}; - signatureProperties.signatureType = enums.signature.certGeneric; signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; - signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([ - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + const symmetricAlgorithms = createPreferredAlgos([ + // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support) enums.symmetric.aes256, - enums.symmetric.aes128, - enums.symmetric.aes192 + enums.symmetric.aes128 ], config.preferredSymmetricAlgorithm); + signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms; if (config.aeadProtect) { - signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([ + const aeadAlgorithms = createPreferredAlgos([ + enums.aead.gcm, enums.aead.eax, enums.aead.ocb ], config.preferredAEADAlgorithm); + signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => { + return symmetricAlgorithms.map(symmetricAlgorithm => { + return [symmetricAlgorithm, aeadAlgorithm]; + }); + }); } signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ // prefer fast asm.js implementations (SHA-256) enums.hash.sha256, - enums.hash.sha512 + enums.hash.sha512, + enums.hash.sha3_256, + enums.hash.sha3_512 ], config.preferredHashAlgorithm); signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ + enums.compression.uncompressed, enums.compression.zlib, - enums.compression.zip, - enums.compression.uncompressed + enums.compression.zip ], config.preferredCompressionAlgorithm); - if (index === 0) { - signatureProperties.isPrimaryUserID = true; - } // integrity protection always enabled signatureProperties.features = [0]; signatureProperties.features[0] |= enums.features.modificationDetection; if (config.aeadProtect) { - signatureProperties.features[0] |= enums.features.aead; - } - if (config.v5Keys) { - signatureProperties.features[0] |= enums.features.v5Keys; + signatureProperties.features[0] |= enums.features.seipdv2; } if (options.keyExpirationTime > 0) { signatureProperties.keyExpirationTime = options.keyExpirationTime; signatureProperties.keyNeverExpires = false; } + return signatureProperties; + } + + if (secretKeyPacket.version === 6) { // add direct key signature with key prefs + const dataToSign = { + key: secretKeyPacket + }; + + const signatureProperties = getKeySignatureProperties(); + signatureProperties.signatureType = enums.signature.key; + + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + packetlist.push(signaturePacket); + } + + await Promise.all(options.userIDs.map(async function(userID, index) { + const userIDPacket = UserIDPacket.fromObject(userID); + const dataToSign = { + userID: userIDPacket, + key: secretKeyPacket + }; + const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {}; + signatureProperties.signatureType = enums.signature.certPositive; + if (index === 0) { + signatureProperties.isPrimaryUserID = true; + } - const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); return { userIDPacket, signaturePacket }; })).then(list => { @@ -29573,7 +19155,7 @@ async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, conf // Add revocation signature packet for creating a revocation certificate. // This packet should be removed before returning the key. const dataToSign = { key: secretKeyPacket }; - packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, { + packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, { signatureType: enums.signature.keyRevocation, reasonForRevocationFlag: enums.reasonForRevocation.noReason, reasonForRevocationString: '' @@ -29618,7 +19200,7 @@ async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { let input; if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); + const { type, data } = await unarmor(armoredKey); if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { throw new Error('Armored text not of type key'); } @@ -29627,7 +19209,12 @@ async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { input = binaryKey; } const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return createKey(packetlist); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]); + return createKey(firstKeyPacketList); } /** @@ -29655,7 +19242,7 @@ async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest let input; if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); + const { type, data } = await unarmor(armoredKey); if (!(type === enums.armor.privateKey)) { throw new Error('Armored text not of type private key'); } @@ -29664,7 +19251,15 @@ async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest input = binaryKey; } const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return new PrivateKey(packetlist); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } + const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + return new PrivateKey(firstPrivateKeyList); + } + throw new Error('No secret key packet found'); } /** @@ -29692,7 +19287,7 @@ async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); + const { type, data } = await unarmor(armoredKeys); if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { throw new Error('Armored text not of type key'); } @@ -29735,7 +19330,7 @@ async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); } if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); + const { type, data } = await unarmor(armoredKeys); if (type !== enums.armor.privateKey) { throw new Error('Armored text not of type private key'); } @@ -29743,19 +19338,38 @@ async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { } const keys = []; const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No secret key packet found'); - } + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); const newKey = new PrivateKey(oneKeyList); keys.push(newKey); } + if (keys.length === 0) { + throw new Error('No secret key packet found'); + } return keys; } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A Message can contain the following packets const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ @@ -29827,8 +19441,6 @@ class Message { * @async */ async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { - const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - const symEncryptedPacketlist = this.packets.filterByTag( enums.packet.symmetricallyEncryptedData, enums.packet.symEncryptedIntegrityProtectedData, @@ -29840,14 +19452,18 @@ class Message { } const symEncryptedPacket = symEncryptedPacketlist[0]; + const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm; + + const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1); + let exception = null; const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { - if (!util.isUint8Array(data) || !util.isString(algorithmName)) { + if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) { throw new Error('Invalid session key for decryption.'); } try { - const algo = enums.write(enums.symmetric, algorithmName); + const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName); await symEncryptedPacket.decrypt(algo, data, config$1); } catch (e) { util.printDebugError(e); @@ -29873,6 +19489,7 @@ class Message { * Decrypt encrypted session keys either with private keys or passwords. * @param {Array} [decryptionKeys] - Private keys with decrypted secret data * @param {Array} [passwords] - Passwords used to decrypt + * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable) * @param {Date} [date] - Use the given date for key verification, instead of current time * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise>} array of object with potential sessionKey, algorithm pairs * @async */ - async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) { + async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) { let decryptedSessionKeyPackets = []; let exception; @@ -29903,6 +19520,9 @@ class Message { decryptedSessionKeyPackets.push(skeskPacket); } catch (err) { util.printDebugError(err); + if (err instanceof Argon2OutOfMemoryError) { + exception = err; + } } })); })); @@ -29913,6 +19533,15 @@ class Message { } await Promise.all(pkeskPackets.map(async function(pkeskPacket) { await Promise.all(decryptionKeys.map(async function(decryptionKey) { + let decryptionKeyPackets; + try { + // do not check key expiration to allow decryption of old messages + decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); + } catch (err) { + exception = err; + return; + } + let algos = [ enums.symmetric.aes256, // Old OpenPGP.js default fallback enums.symmetric.aes128, // RFC4880bis fallback @@ -29920,18 +19549,13 @@ class Message { enums.symmetric.cast5 // Golang OpenPGP fallback ]; try { - const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere. - if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { - algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); + const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere. + if (selfCertification.preferredSymmetricAlgorithms) { + algos = algos.concat(selfCertification.preferredSymmetricAlgorithms); } } catch (e) {} - // do not check key expiration to allow decryption of old messages - const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { - if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) { - return; - } if (!decryptionKeyPacket.isDecrypted()) { throw new Error('Decryption key is not decrypted.'); } @@ -29956,7 +19580,11 @@ class Message { // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times - await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => { + await Promise.all(( + expectedSymmetricAlgorithm ? + [expectedSymmetricAlgorithm] : + Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms) + ).map(async sessionKeyAlgorithm => { const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); pkeskPacketCopy.read(serialisedPKESK); const randomSessionKey = { @@ -29976,7 +19604,8 @@ class Message { } else { try { await pkeskPacket.decrypt(decryptionKeyPacket); - if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) { + const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm; + if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) { throw new Error('A non-preferred symmetric algorithm was used.'); } decryptedSessionKeyPackets.push(pkeskPacket); @@ -30010,7 +19639,7 @@ class Message { return decryptedSessionKeyPackets.map(packet => ({ data: packet.sessionKey, - algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm) + algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm) })); } throw exception || new Error('Session key decryption failed.'); @@ -30059,23 +19688,22 @@ class Message { * @async */ static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { - const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1); - const algorithmName = enums.read(enums.symmetric, algo); - const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ? - enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) : - undefined; + const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1); + const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo); + const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined; await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() .catch(() => null) // ignore key strength requirements .then(maybeKey => { - if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) { - throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); + if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) && + !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted + throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); } }) )); - const sessionKeyData = mod.generateSessionKey(algo); - return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName }; + const sessionKeyData = mod.generateSessionKey(symmetricAlgo); + return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName }; } /** @@ -30108,13 +19736,10 @@ class Message { const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); - let symEncryptedPacket; - if (aeadAlgorithmName) { - symEncryptedPacket = new AEADEncryptedDataPacket(); - symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName); - } else { - symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); - } + const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({ + version: aeadAlgorithmName ? 2 : 1, + aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null + }); symEncryptedPacket.packets = this.packets; const algorithm = enums.write(enums.symmetric, algorithmName); @@ -30142,17 +19767,21 @@ class Message { */ static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { const packetlist = new PacketList(); - const algorithm = enums.write(enums.symmetric, algorithmName); + const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName); const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); if (encryptionKeys) { const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = algorithm; + + const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({ + version: aeadAlgorithm ? 6 : 3, + encryptionKeyPacket: encryptionKey.keyPacket, + anonymousRecipient: wildcard, + sessionKey, + sessionKeyAlgorithm: symmetricAlgorithm + }); + await pkESKeyPacket.encrypt(encryptionKey.keyPacket); delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption return pkESKeyPacket; @@ -30191,7 +19820,7 @@ class Message { return symEncryptedSessionKeyPacket; }; - const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd))); + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd))); packetlist.push(...results); } @@ -30201,16 +19830,18 @@ class Message { /** * Sign the message (the literal data packet of the message) * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from * @param {Signature} [signature] - Any existing detached signature to add to the message * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise} New message with signed content. * @async */ - async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { const packetlist = new PacketList(); const literalDataPacket = this.packets.findPacket(enums.packet.literalData); @@ -30218,49 +19849,14 @@ class Message { throw new Error('No literal data packet to sign.'); } - let i; - let existingSigPacketlist; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; - - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signaturePacket.signatureType; - onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; - onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyID = signaturePacket.issuerKeyID; - if (!signingKeys.length && i === 0) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); - } - } - - await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) { - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i]; - const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1); - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1); - onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyID = signingKey.getKeyID(); - if (i === signingKeys.length - 1) { - onePassSig.flags = 1; - } - return onePassSig; - })).then(onePassSignatureList => { - onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig)); - }); + const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well + const onePassSignaturePackets = signaturePackets.map( + (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0)) + .reverse(); // innermost OPS refers to the first signature packet + packetlist.push(...onePassSignaturePackets); packetlist.push(literalDataPacket); - packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1))); + packetlist.push(...signaturePackets); return new Message(packetlist); } @@ -30289,21 +19885,23 @@ class Message { /** * Create a detached signature for the message (the literal data packet of the message) * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from * @param {Signature} [signature] - Any existing detached signature * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise} New detached signature of message content. * @async */ - async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { const literalDataPacket = this.packets.findPacket(enums.packet.literalData); if (!literalDataPacket) { throw new Error('No literal data packet to sign.'); } - return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); + return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config$1)); } /** @@ -30424,7 +20022,13 @@ class Message { * @returns {ReadableStream} ASCII armor. */ armor(config$1 = config) { - return armor(enums.armor.message, this.write(), null, null, null, config$1); + const trailingPacket = this.packets[this.packets.length - 1]; + // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer. + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ? + trailingPacket.version !== 2 : + this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1); } } @@ -30432,18 +20036,21 @@ class Message { * Create signature packets for the message * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing + * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from * @param {Signature} [signature] - Any existing detached signature to append * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures * @param {Boolean} [detached] - Whether to create detached signature packets * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise} List of signature packets. * @async * @private */ -async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) { +async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) { const packetlist = new PacketList(); // If data packet was created from Uint8Array, use binary, otherwise use text @@ -30451,12 +20058,12 @@ async function createSignaturePackets(literalDataPacket, signingKeys, signature enums.signature.binary : enums.signature.text; await Promise.all(signingKeys.map(async (primaryKey, i) => { - const userID = userIDs[i]; + const signingUserID = signingUserIDs[i]; if (!primaryKey.isPrivate()) { throw new Error('Need private key for signing'); } - const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1); - return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1); + const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1); + return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1); })).then(signatureList => { packetlist.push(...signatureList); }); @@ -30597,12 +20204,8 @@ async function readMessage({ armoredMessage, binaryMessage, config: config$1, .. const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } if (armoredMessage) { - const { type, data } = await unarmor(input, config$1); + const { type, data } = await unarmor(input); if (type !== enums.armor.message) { throw new Error('Armored text not of type message'); } @@ -30627,7 +20230,7 @@ async function readMessage({ armoredMessage, binaryMessage, config: config$1, .. * @static */ async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { - let input = text !== undefined ? text : binary; + const input = text !== undefined ? text : binary; if (input === undefined) { throw new Error('createMessage: must pass options object containing `text` or `binary`'); } @@ -30640,10 +20243,6 @@ async function createMessage({ text, binary, filename, date = new Date(), format const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } const literalDataPacket = new LiteralDataPacket(date); if (text !== undefined) { literalDataPacket.setText(input, enums.write(enums.literal, format)); @@ -30661,9 +20260,25 @@ async function createMessage({ text, binary, filename, date = new Date(), format } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A Cleartext message can contain the following packets -const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** * Class that represents an OpenPGP cleartext signed message. @@ -30698,20 +20313,22 @@ class CleartextMessage { /** * Sign the cleartext message - * @param {Array} privateKeys - private keys with decrypted secret key data for signing + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from * @param {Signature} [signature] - Any existing detached signature * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {Promise} New cleartext message with signed content. * @async */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { const literalDataPacket = new LiteralDataPacket(); literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1)); return new CleartextMessage(this.text, newSignature); } @@ -30750,16 +20367,22 @@ class CleartextMessage { * @returns {String | ReadableStream} ASCII armor. */ armor(config$1 = config) { - let hashes = this.signature.packets.map(function(packet) { - return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); - }); - hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); + // emit header and checksum if one of the signatures has a version not 6 + const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6); + const hash = emitHeaderAndChecksum ? + Array.from(new Set(this.signature.packets.map( + packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase() + ))).join() : + null; + const body = { - hash: hashes.join(), + hash, text: this.text, data: this.signature.packets.write() }; - return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1); + + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1); } } @@ -30786,8 +20409,8 @@ async function readCleartextMessage({ cleartextMessage, config: config$1, ...res if (input.type !== enums.armor.signed) { throw new Error('No cleartext signed message.'); } - const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1); - verifyHeaders$1(input.headers, packetlist); + const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1); + verifyHeaders(input.headers, packetlist); const signature = new Signature(packetlist); return new CleartextMessage(input.text, signature); } @@ -30798,7 +20421,7 @@ async function readCleartextMessage({ cleartextMessage, config: config$1, ...res * @param {PacketList} packetlist - The packetlist with signature packets * @private */ -function verifyHeaders$1(headers, packetlist) { +function verifyHeaders(headers, packetlist) { const checkHashAlgos = function(hashAlgos) { const check = packet => algo => packet.hashAlgorithm === algo; @@ -30810,30 +20433,27 @@ function verifyHeaders$1(headers, packetlist) { return true; }; - let oneHeader = null; - let hashAlgos = []; - headers.forEach(function(header) { - oneHeader = header.match(/^Hash: (.+)$/); // get header value - if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace - oneHeader = oneHeader.split(','); - oneHeader = oneHeader.map(function(hash) { - hash = hash.toLowerCase(); - try { - return enums.write(enums.hash, hash); - } catch (e) { - throw new Error('Unknown hash algorithm in armor header: ' + hash); - } - }); - hashAlgos = hashAlgos.concat(oneHeader); + const hashAlgos = []; + headers.forEach(header => { + const hashHeader = header.match(/^Hash: (.+)$/); // get header value + if (hashHeader) { + const parsedHashIDs = hashHeader[1] + .replace(/\s/g, '') // remove whitespace + .split(',') + .map(hashName => { + try { + return enums.write(enums.hash, hashName.toLowerCase()); + } catch (e) { + throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase()); + } + }); + hashAlgos.push(...parsedHashIDs); } else { throw new Error('Only "Hash" header allowed in cleartext signed message'); } }); - if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { - throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { + if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { throw new Error('Hash algorithm mismatch in armor header and signature'); } } @@ -30858,6 +20478,22 @@ async function createCleartextMessage({ text, ...rest }) { } // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ////////////////////// @@ -30868,15 +20504,17 @@ async function createCleartextMessage({ text, ...rest }) { /** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. + * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. * @param {Object} options * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA + * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys). + * Note: Curve448 and Curve25519 (new format) are not widely supported yet. * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys - * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: - * curve25519 (default), p256, p384, p521, secp256k1, + * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys: + * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1, * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires @@ -30889,13 +20527,20 @@ async function createCleartextMessage({ text, ...rest }) { * @async * @static */ -async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { +async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); + if (!type && !curve) { + type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them) + curve = 'curve25519Legacy'; // unused with type != 'ecc' + } else { + type = type || 'ecc'; + curve = curve || 'curve25519Legacy'; + } + userIDs = toArray(userIDs); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key generation'); + if (userIDs.length === 0 && !config$1.v6Keys) { + throw new Error('UserIDs are required for V4 keys'); } if (type === 'rsa' && rsaBits < config$1.minRSABits) { throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); @@ -30904,7 +20549,7 @@ async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4 const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; try { - const { key, revocationCertificate } = await generate$4(options, config$1); + const { key, revocationCertificate } = await generate(options, config$1); key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); return { @@ -30935,11 +20580,11 @@ async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4 */ async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); + userIDs = toArray(userIDs); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key reformat'); + if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) { + throw new Error('UserIDs are required for V4 keys'); } const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; @@ -31098,11 +20743,11 @@ async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) * @async * @static */ -async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { +async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); checkMessage(message); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords); - signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations); + encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords); + signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations); if (rest.detached) { throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); } @@ -31114,13 +20759,13 @@ async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sess if (!signingKeys) { signingKeys = []; } - const streaming = message.fromStream; + try { if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified - message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); + message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1); } message = message.compress( - await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1), + await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), config$1 ); message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); @@ -31128,7 +20773,7 @@ async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sess // serialize data const armor = format === 'armored'; const data = armor ? message.armor(config$1) : message.write(); - return convertStream(data, streaming, armor ? 'utf8' : 'binary'); + return await convertStream(data); } catch (err) { throw util.wrapError('Error encrypting message', err); } @@ -31167,9 +20812,9 @@ async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sess * @async * @static */ -async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { +async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys); + checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys); if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); @@ -31199,7 +20844,7 @@ async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, veri }) ]); } - result.data = await convertStream(result.data, message.fromStream, format); + result.data = await convertStream(result.data); return result; } catch (err) { throw util.wrapError('Error decrypting message', err); @@ -31219,21 +20864,23 @@ async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, veri * @param {Object} options * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext + * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] * @param {Date} [options.date=current date] - Override the creation date of the signature * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys` * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). * @async * @static */ -async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { +async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); checkCleartextOrMessage(message); checkOutputMessageFormat(format); - signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations); + signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations); if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); @@ -31249,9 +20896,9 @@ async function sign$6({ message, signingKeys, format = 'armored', detached = fal try { let signature; if (detached) { - signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); + signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); } else { - signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); + signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); } if (format === 'object') return signature; @@ -31265,7 +20912,7 @@ async function sign$6({ message, signingKeys, format = 'armored', detached = fal ]); }); } - return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary'); + return await convertStream(signature); } catch (err) { throw util.wrapError('Error signing message', err); } @@ -31299,9 +20946,9 @@ async function sign$6({ message, signingKeys, format = 'armored', detached = fal * @async * @static */ -async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { +async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys); + checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys); if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); @@ -31328,7 +20975,7 @@ async function verify$6({ message, verificationKeys, expectSigned = false, forma }) ]); } - result.data = await convertStream(result.data, message.fromStream, format); + result.data = await convertStream(result.data); return result; } catch (err) { throw util.wrapError('Error verifying signed message', err); @@ -31353,9 +21000,9 @@ async function verify$6({ message, verificationKeys, expectSigned = false, forma * @async * @static */ -async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { +async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs); + encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs); if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); @@ -31389,7 +21036,7 @@ async function generateSessionKey$1({ encryptionKeys, date = new Date(), encrypt async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); + encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs); if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); @@ -31422,12 +21069,12 @@ async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKey */ async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); + checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); try { - const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1); + const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1); return sessionKeys; } catch (err) { throw util.wrapError('Error decrypting session keys', err); @@ -31448,12 +21095,12 @@ async function decryptSessionKeys({ message, decryptionKeys, passwords, date = n */ function checkString(data, name) { if (!util.isString(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type String'); + throw new Error('Parameter [' + (name) + '] must be of type String'); } } function checkBinary(data, name) { if (!util.isUint8Array(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array'); + throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array'); } } function checkMessage(message) { @@ -31489,7 +21136,7 @@ function checkConfig(config$1) { * @returns {Array|undefined} The resulting array or undefined. * @private */ -function toArray$1(param) { +function toArray(param) { if (param && !util.isArray(param)) { param = [param]; } @@ -31499,25 +21146,15 @@ function toArray$1(param) { /** * Convert data to or from Stream * @param {Object} data - the data to convert - * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type - * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams * @returns {Promise} The data in the respective format. * @async * @private */ -async function convertStream(data, streaming, encoding = 'utf8') { +async function convertStream(data) { const streamType = util.isStream(data); if (streamType === 'array') { return readToEnd(data); } - if (streaming === 'node') { - data = webToNode(data); - if (encoding !== 'binary') data.setEncoding(encoding); - return data; - } - if (streaming === 'web' && streamType === 'ponyfill') { - return toNativeReadable(data); - } return data; } @@ -31565,4 +21202,4 @@ function formatObject(object, format, config) { } } -export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, _224 as _, commonjsGlobal as a, armor, common$1 as b, createCommonjsModule as c, config, createCleartextMessage, createMessage, common as d, decrypt$5 as decrypt, decryptKey, decryptSessionKeys, _256 as e, encrypt$5 as encrypt, encryptKey, encryptSessionKey, enums, _384 as f, _512 as g, generateKey, generateSessionKey$1 as generateSessionKey, inherits_browser as i, minimalisticAssert as m, ripemd as r, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign$6 as sign, utils as u, unarmor, verify$6 as verify }; +export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PaddingPacket, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt, decryptKey, decryptSessionKeys, encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign, unarmor, verify }; diff --git a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs b/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs deleted file mode 100644 index 7d3d0e7b1..000000000 --- a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs +++ /dev/null @@ -1,3 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}const r="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function o(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=t,i=Promise,a=Promise.prototype.then,s=Promise.resolve.bind(i),l=Promise.reject.bind(i);function u(e){return new i(e)}function c(e){return s(e)}function d(e){return l(e)}function f(e,t,r){return a.call(e,t,r)}function h(e,t,r){f(f(e,t,r),void 0,n)}function _(e,t){h(e,t)}function b(e,t){h(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,n)}const y=(()=>{const e=r&&r.queueMicrotask;if("function"==typeof e)return e;const t=c(void 0);return e=>f(t,e)})();function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class v{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,i=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,i}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function S(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?q(e):"closed"===t._state?function(e){q(e),k(e)}(e):E(e,t._storedError)}function R(e,t){return ar(e._ownerReadableStream,t)}function T(e){"readable"===e._ownerReadableStream._state?C(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){E(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function q(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function E(e,t){q(e),C(e,t)}function C(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function k(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const O=e("[[AbortSteps]]"),j=e("[[ErrorSteps]]"),W=e("[[CancelSteps]]"),A=e("[[PullSteps]]"),z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function B(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(t+" is not an object.");var r}function I(e,t){if("function"!=typeof e)throw new TypeError(t+" is not a function.")}function L(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(t+" is not an object.")}function M(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function D(e){return Number(e)}function x(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=x(o),!z(o))throw new TypeError(t+" is not a finite number");if(o=function(e){return x(F(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function Q(e,t){if(!nr(e))throw new TypeError(t+" is not a ReadableStream.")}function H(e){return new X(e)}function Y(e,t){e._reader._readRequests.push(t)}function V(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function U(e){return e._reader._readRequests.length}function G(e){const t=e._reader;return void 0!==t&&!!J(t)}class X{constructor(e){if(M(e,1,"ReadableStreamDefaultReader"),Q(e,"First parameter"),ir(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");S(this,e),this._readRequests=new v}get closed(){return J(this)?this._closedPromise:d(Z("closed"))}cancel(e=undefined){return J(this)?void 0===this._ownerReadableStream?d(P("cancel")):R(this,e):d(Z("cancel"))}read(){if(!J(this))return d(Z("read"));if(void 0===this._ownerReadableStream)return d(P("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw Z("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");T(this)}}}function J(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[A](t)}function Z(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let ee;Object.defineProperties(X.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(X.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof e.asyncIterator&&(ee={[e.asyncIterator](){return this}},Object.defineProperty(ee,e.asyncIterator,{enumerable:!1}));class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return d(P("iterate"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,y((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,T(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,T(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return d(P("finish iterating"));if(!this._preventCancel){const r=R(t,e);return T(t),p(r,(()=>({value:e,done:!0})))}return T(t),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl")}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ee&&Object.setPrototypeOf(re,ee);const ie=Number.isNaN||function(e){return e!=e};function ae(e){return!!function(e){if("number"!=typeof e)return!1;if(ie(e))return!1;if(e<0)return!1;return!0}(e)&&e!==1/0}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function le(e,t,r){if(!ae(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ue(e){e._queue=new v,e._queueTotalSize=0}function ce(e){return e.slice()}class de{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!_e(this))throw Oe("view");return this._view}respond(e){if(!_e(this))throw Oe("respond");if(M(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(t=Number(t),!ae(t))throw new RangeError("bytesWritten must be a finite");Te(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!_e(this))throw Oe("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");!function(e,t){const r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,Te(e,t.byteLength)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(de.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(de.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class fe{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!he(this))throw je("byobRequest");if(null===this._byobRequest&&this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(de.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest}get desiredSize(){if(!he(this))throw je("desiredSize");return Ce(this)}close(){if(!he(this))throw je("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ee(e,t),t}}qe(e),sr(t)}(this)}enqueue(e){if(!he(this))throw je("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,i=t.byteLength,a=o;if(G(r))if(0===U(r))ye(e,a,n,i);else{V(r,new Uint8Array(a,n,i),!1)}else ze(r)?(ye(e,a,n,i),Re(e)):ye(e,a,n,i);be(e)}(this,e)}error(e=undefined){if(!he(this))throw je("error");Ee(this,e)}[W](e){if(this._pendingPullIntos.length>0){this._pendingPullIntos.peek().bytesFilled=0}ue(this);const t=this._cancelAlgorithm(e);return qe(this),t}[A](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,ve(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}Y(t,e),be(this)}}function he(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function _e(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(G(t)&&U(t)>0)return!0;if(ze(t)&&Ae(t)>0)return!0;const r=Ce(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e))}),(t=>{Ee(e,t)}))}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=me(t);"default"===t.readerType?V(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function me(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ye(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ge(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),i=t.bytesFilled+n,a=i-i%r;let s=n,l=!1;a>o&&(s=a-t.bytesFilled,l=!0);const u=e._queue;for(;s>0;){const r=u.peek(),o=Math.min(s,r.byteLength),n=t.byteOffset+t.bytesFilled;c=t.buffer,d=n,f=r.buffer,h=r.byteOffset,_=o,new Uint8Array(c).set(new Uint8Array(f,h,_),d),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,we(e,o,t),s-=o}var c,d,f,h,_;return l}function we(e,t,r){Se(e),r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(qe(e),sr(e._controlledReadableByteStream)):be(e)}function Se(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Re(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ge(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Te(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;const r=e._controlledReadableByteStream;if(ze(r))for(;Ae(r)>0;)pe(r,Pe(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(we(e,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=r.buffer.slice(t-o,t);ye(e,n,0,n.byteLength)}r.buffer=r.buffer,r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),Re(e)}(e,t,r);be(e)}function Pe(e){const t=e._pendingPullIntos.shift();return Se(e),t}function qe(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ee(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(!function(e){Se(e),e._pendingPullIntos=new v}(e),ue(e),qe(e),lr(r,t))}function Ce(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function ke(e,t,r){const o=Object.create(fe.prototype);let n=()=>{},i=()=>c(void 0),a=()=>c(void 0);void 0!==t.start&&(n=()=>t.start(o)),void 0!==t.pull&&(i=()=>t.pull(o)),void 0!==t.cancel&&(a=e=>t.cancel(e));const s=t.autoAllocateChunkSize;if(0===s)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,i,a){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ue(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=i,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=a,t._pendingPullIntos=new v,e._readableStreamController=t,h(c(r()),(()=>{t._started=!0,be(t)}),(e=>{Ee(t,e)}))}(e,o,n,i,a,r,s)}function Oe(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function je(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function We(e,t){e._reader._readIntoRequests.push(t)}function Ae(e){return e._reader._readIntoRequests.length}function ze(e){const t=e._reader;return void 0!==t&&!!Be(t)}Object.defineProperties(fe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(fe.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class Fe{constructor(e){if(M(e,1,"ReadableStreamBYOBReader"),Q(e,"First parameter"),ir(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!he(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");S(this,e),this._readIntoRequests=new v}get closed(){return Be(this)?this._closedPromise:d(Ie("closed"))}cancel(e=undefined){return Be(this)?void 0===this._ownerReadableStream?d(P("cancel")):R(this,e):d(Ie("cancel"))}read(e){if(!Be(this))return d(Ie("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(void 0===this._ownerReadableStream)return d(P("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const i=t.constructor,a={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:i,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(a),void We(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(ge(e,a)){const t=me(a);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ee(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(a),We(o,r),be(e)}else{const e=new i(a.buffer,a.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Be(this))throw Ie("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");T(this)}}}function Be(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function Ie(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Le(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function $e(e,t){B(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:D(r),size:void 0===o?void 0:De(o,t+" has member 'size' that")}}function De(e,t){return I(e,t),t=>D(e(t))}function xe(e,t,r){return I(e,r),r=>w(e,t,[r])}function Ne(e,t,r){return I(e,r),()=>w(e,t,[])}function Qe(e,t,r){return I(e,r),r=>g(e,t,[r])}function He(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}function Ye(e,t){if(!Xe(e))throw new TypeError(t+" is not a WritableStream.")}Object.defineProperties(Fe.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(Fe.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});class Ve{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=$e(t,"Second parameter"),o=function(e,t){B(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,i=null==e?void 0:e.type,a=null==e?void 0:e.write;return{abort:void 0===r?void 0:xe(r,e,t+" has member 'abort' that"),close:void 0===o?void 0:Ne(o,e,t+" has member 'close' that"),start:void 0===n?void 0:Qe(n,e,t+" has member 'start' that"),write:void 0===a?void 0:He(a,e,t+" has member 'write' that"),type:i}}(e,"First parameter");Ge(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=Me(r);!function(e,t,r,o){const n=Object.create(_t.prototype);let i=()=>{},a=()=>c(void 0),s=()=>c(void 0),l=()=>c(void 0);void 0!==t.start&&(i=()=>t.start(n));void 0!==t.write&&(a=e=>t.write(e,n));void 0!==t.close&&(s=()=>t.close());void 0!==t.abort&&(l=e=>t.abort(e));bt(e,n,i,a,s,l,r,o)}(this,o,Le(r,1),n)}get locked(){if(!Xe(this))throw St("locked");return Je(this)}abort(e=undefined){return Xe(this)?Je(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Ke(this,e):d(St("abort"))}close(){return Xe(this)?Je(this)?d(new TypeError("Cannot close a stream that already has a writer")):ot(this)?d(new TypeError("Cannot close an already-closing stream")):Ze(this):d(St("close"))}getWriter(){if(!Xe(this))throw St("getWriter");return Ue(this)}}function Ue(e){return new at(e)}function Ge(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new v,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Xe(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function Je(e){return void 0!==e._writer}function Ke(e,t){const r=e._state;if("closed"===r||"errored"===r)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let o=!1;"erroring"===r&&(o=!0,t=void 0);const n=u(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=n,o||tt(e,t),n}function Ze(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&At(o),le(n=e._writableStreamController,ht,0),yt(n),r}function et(e,t){"writable"!==e._state?rt(e):tt(e,t)}function tt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&ct(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&rt(e)}function rt(e){e._state="errored",e._writableStreamController[j]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new v,void 0===e._pendingAbortRequest)return void nt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void nt(e);h(e._writableStreamController[O](r._reason),(()=>{r._resolve(),nt(e)}),(t=>{r._reject(t),nt(e)}))}function ot(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function nt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Et(t,e._storedError)}function it(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){kt(e)}(r):At(r)),e._backpressure=t}Object.defineProperties(Ve.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(Ve.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class at{constructor(e){if(M(e,1,"WritableStreamDefaultWriter"),Ye(e,"First parameter"),Je(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ot(e)&&e._backpressure?kt(this):jt(this),Pt(this);else if("erroring"===t)Ot(this,e._storedError),Pt(this);else if("closed"===t)jt(this),Pt(r=this),Ct(r);else{const t=e._storedError;Ot(this,t),qt(this,t)}var r}get closed(){return st(this)?this._closedPromise:d(Rt("closed"))}get desiredSize(){if(!st(this))throw Rt("desiredSize");if(void 0===this._ownerWritableStream)throw Tt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return mt(t._writableStreamController)}(this)}get ready(){return st(this)?this._readyPromise:d(Rt("ready"))}abort(e=undefined){return st(this)?void 0===this._ownerWritableStream?d(Tt("abort")):function(e,t){return Ke(e._ownerWritableStream,t)}(this,e):d(Rt("abort"))}close(){if(!st(this))return d(Rt("close"));const e=this._ownerWritableStream;return void 0===e?d(Tt("close")):ot(e)?d(new TypeError("Cannot close an already-closing stream")):lt(this)}releaseLock(){if(!st(this))throw Rt("releaseLock");void 0!==this._ownerWritableStream&&dt(this)}write(e=undefined){return st(this)?void 0===this._ownerWritableStream?d(Tt("write to")):ft(this,e):d(Rt("write"))}}function st(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function lt(e){return Ze(e._ownerWritableStream)}function ut(e,t){"pending"===e._closedPromiseState?Et(e,t):function(e,t){qt(e,t)}(e,t)}function ct(e,t){"pending"===e._readyPromiseState?Wt(e,t):function(e,t){Ot(e,t)}(e,t)}function dt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");ct(e,r),ut(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function ft(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return gt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(Tt("write to"));const i=r._state;if("errored"===i)return d(r._storedError);if(ot(r)||"closed"===i)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===i)return d(r._storedError);const a=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{le(e,t,r)}catch(t){return void gt(e,t)}const o=e._controlledWritableStream;if(!ot(o)&&"writable"===o._state){it(o,wt(e))}yt(e)}(o,t,n),a}Object.defineProperties(at.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(at.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const ht={};class _t{constructor(){throw new TypeError("Illegal constructor")}error(e=undefined){if(!function(e){if(!o(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream"))return!1;return!0}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&vt(this,e)}[O](e){const t=this._abortAlgorithm(e);return pt(this),t}[j](){ue(this)}}function bt(e,t,r,o,n,i,a,s){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ue(t),t._started=!1,t._strategySizeAlgorithm=s,t._strategyHWM=a,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=i;const l=wt(t);it(e,l);h(c(r()),(()=>{t._started=!0,yt(t)}),(r=>{t._started=!0,et(e,r)}))}function pt(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function mt(e){return e._strategyHWM-e._queueTotalSize}function yt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void rt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===ht?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();pt(e),h(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Ct(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),et(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);h(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!ot(r)&&"writable"===t){const t=wt(e);it(r,t)}yt(e)}),(t=>{"writable"===r._state&&pt(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,et(e,t)}(r,t)}))}(e,r)}function gt(e,t){"writable"===e._controlledWritableStream._state&&vt(e,t)}function wt(e){return mt(e)<=0}function vt(e,t){const r=e._controlledWritableStream;pt(e),tt(r,t)}function St(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Rt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Tt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Pt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function qt(e,t){Pt(e),Et(e,t)}function Et(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Ct(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function kt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Ot(e,t){kt(e),Wt(e,t)}function jt(e){kt(e),At(e)}function Wt(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function At(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(_t.prototype,{error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(_t.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const zt="undefined"!=typeof DOMException?DOMException:void 0;const Ft=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(zt)?zt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return Object.defineProperty(e.prototype=Object.create(Error.prototype),"constructor",{value:e,writable:!0,configurable:!0}),e}();function Bt(e,r,o,n,i,a){const s=H(e),l=Ue(r);e._disturbed=!0;let p=!1,y=c(void 0);return u(((g,w)=>{let v;if(void 0!==a){if(v=()=>{const t=new Ft("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===r._state?Ke(r,t):c(void 0))),i||o.push((()=>"readable"===e._state?ar(e,t):c(void 0))),C((()=>Promise.all(o.map((e=>e())))),!0,t)},a.aborted)return void v();a.addEventListener("abort",v)}var S,R,P;if(E(e,s._closedPromise,(e=>{n?k(!0,e):C((()=>Ke(r,e)),!0,e)})),E(r,l._closedPromise,(t=>{i?k(!0,t):C((()=>ar(e,t)),!0,t)})),S=e,R=s._closedPromise,P=()=>{o?k():C((()=>function(e){const t=e._ownerWritableStream,r=t._state;return ot(t)||"closed"===r?c(void 0):"errored"===r?d(t._storedError):lt(e)}(l)))},"closed"===S._state?P():_(R,P),ot(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");i?k(!0,t):C((()=>ar(e,t)),!0,t)}function q(){const e=y;return f(y,(()=>e!==y?q():void 0))}function E(e,t,r){"errored"===e._state?r(e._storedError):b(t,r)}function C(e,t,o){function n(){h(e(),(()=>O(t,o)),(e=>O(!0,e)))}p||(p=!0,"writable"!==r._state||ot(r)?n():_(q(),n))}function k(e,t){p||(p=!0,"writable"!==r._state||ot(r)?O(e,t):_(q(),(()=>O(e,t))))}function O(e,t){dt(l),T(s),void 0!==a&&a.removeEventListener("abort",v),e?w(t):g(void 0)}m(u(((e,r)=>{!function o(n){n?e():f(p?c(!0):f(l._readyPromise,(()=>u(((e,r)=>{K(s,{_chunkSteps:r=>{y=f(ft(l,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),o,r)}(!1)})))}))}class It{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Lt(this))throw Ut("desiredSize");return Ht(this)}close(){if(!Lt(this))throw Ut("close");if(!Yt(this))throw new TypeError("The stream is not in a state that permits close");xt(this)}enqueue(e=undefined){if(!Lt(this))throw Ut("enqueue");if(!Yt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Nt(this,e)}error(e=undefined){if(!Lt(this))throw Ut("error");Qt(this,e)}[W](e){ue(this);const t=this._cancelAlgorithm(e);return Dt(this),t}[A](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(Dt(this),sr(t)):Mt(this),e._chunkSteps(r)}else Y(t,e),Mt(this)}}function Lt(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function Mt(e){if(!$t(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Mt(e))}),(t=>{Qt(e,t)}))}function $t(e){const t=e._controlledReadableStream;if(!Yt(e))return!1;if(!e._started)return!1;if(ir(t)&&U(t)>0)return!0;return Ht(e)>0}function Dt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function xt(e){if(!Yt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Dt(e),sr(t))}function Nt(e,t){if(!Yt(e))return;const r=e._controlledReadableStream;if(ir(r)&&U(r)>0)V(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Qt(e,t),t}try{le(e,t,r)}catch(t){throw Qt(e,t),t}}Mt(e)}function Qt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ue(e),Dt(e),lr(r,t))}function Ht(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Yt(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Vt(e,t,r,o,n,i,a){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ue(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=a,t._strategyHWM=i,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;h(c(r()),(()=>{t._started=!0,Mt(t)}),(e=>{Qt(t,e)}))}function Ut(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Gt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Xt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Jt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Kt(e,t){if("bytes"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Zt(e,t){if("byob"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function er(e,t){B(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,i=null==e?void 0:e.signal;return void 0!==i&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(t+" is not an AbortSignal.")}(i,t+" has member 'signal' that"),{preventAbort:!!r,preventCancel:!!o,preventClose:!!n,signal:i}}Object.defineProperties(It.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(It.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class tr{constructor(e={},t={}){void 0===e?e=null:L(e,"First parameter");const r=$e(t,"Second parameter"),o=function(e,t){B(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,i=null==r?void 0:r.pull,a=null==r?void 0:r.start,s=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,t+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:Gt(n,r,t+" has member 'cancel' that"),pull:void 0===i?void 0:Xt(i,r,t+" has member 'pull' that"),start:void 0===a?void 0:Jt(a,r,t+" has member 'start' that"),type:void 0===s?void 0:Kt(s,t+" has member 'type' that")}}(e,"First parameter");if(or(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");ke(this,o,Le(r,0))}else{const e=Me(r);!function(e,t,r,o){const n=Object.create(It.prototype);let i=()=>{},a=()=>c(void 0),s=()=>c(void 0);void 0!==t.start&&(i=()=>t.start(n)),void 0!==t.pull&&(a=()=>t.pull(n)),void 0!==t.cancel&&(s=e=>t.cancel(e)),Vt(e,n,i,a,s,r,o)}(this,o,Le(r,1),e)}}get locked(){if(!nr(this))throw ur("locked");return ir(this)}cancel(e=undefined){return nr(this)?ir(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):ar(this,e):d(ur("cancel"))}getReader(e=undefined){if(!nr(this))throw ur("getReader");return void 0===function(e,t){B(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Zt(r,t+" has member 'mode' that")}}(e,"First parameter").mode?H(this):new Fe(this)}pipeThrough(e,t={}){if(!nr(this))throw ur("pipeThrough");M(e,1,"pipeThrough");const r=function(e,t){B(e,t);const r=null==e?void 0:e.readable;$(r,"readable","ReadableWritablePair"),Q(r,t+" has member 'readable' that");const o=null==e?void 0:e.writable;return $(o,"writable","ReadableWritablePair"),Ye(o,t+" has member 'writable' that"),{readable:r,writable:o}}(e,"First parameter"),o=er(t,"Second parameter");if(ir(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Je(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(Bt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!nr(this))return d(ur("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!Xe(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=er(t,"Second parameter")}catch(e){return d(e)}return ir(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Je(e)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Bt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!nr(this))throw ur("tee");const e=function(e,t){const r=H(e);let o,n,i,a,s,l=!1,d=!1,f=!1;const h=u((e=>{s=e}));function _(){return l||(l=!0,K(r,{_chunkSteps:e=>{y((()=>{l=!1;const t=e,r=e;d||Nt(i._readableStreamController,t),f||Nt(a._readableStreamController,r)}))},_closeSteps:()=>{l=!1,d||xt(i._readableStreamController),f||xt(a._readableStreamController),d&&f||s(void 0)},_errorSteps:()=>{l=!1}})),c(void 0)}function p(){}return i=rr(p,_,(function(t){if(d=!0,o=t,f){const t=ce([o,n]),r=ar(e,t);s(r)}return h})),a=rr(p,_,(function(t){if(f=!0,n=t,d){const t=ce([o,n]),r=ar(e,t);s(r)}return h})),b(r._closedPromise,(e=>{Qt(i._readableStreamController,e),Qt(a._readableStreamController,e),d&&f||s(void 0)})),[i,a]}(this);return ce(e)}values(e=undefined){if(!nr(this))throw ur("values");return function(e,t){const r=H(e),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){return B(e,t),{preventCancel:!!(null==e?void 0:e.preventCancel)}}(e,"First parameter").preventCancel)}}function rr(e,t,r,o=1,n=(()=>1)){const i=Object.create(tr.prototype);or(i);return Vt(i,Object.create(It.prototype),e,t,r,o,n),i}function or(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function nr(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function ir(e){return void 0!==e._reader}function ar(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);sr(e);return p(e._readableStreamController[W](r),t)}function sr(e){e._state="closed";const t=e._reader;void 0!==t&&(k(t),J(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new v))}function lr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(C(r,t),J(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new v):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new v))}function ur(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function cr(e,t){B(e,t);const r=null==e?void 0:e.highWaterMark;return $(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(r)}}Object.defineProperties(tr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(tr.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(tr.prototype,e.asyncIterator,{value:tr.prototype.values,writable:!0,configurable:!0});const dr=function(e){return e.byteLength};class fr{constructor(e){M(e,1,"ByteLengthQueuingStrategy"),e=cr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!_r(this))throw hr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!_r(this))throw hr("size");return dr}}function hr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function _r(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")}Object.defineProperties(fr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(fr.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const br=function(){return 1};class pr{constructor(e){M(e,1,"CountQueuingStrategy"),e=cr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!yr(this))throw mr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!yr(this))throw mr("size");return br}}function mr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function yr(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")}function gr(e,t,r){return I(e,r),r=>w(e,t,[r])}function wr(e,t,r){return I(e,r),r=>g(e,t,[r])}function vr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(pr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(pr.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class Sr{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=$e(t,"Second parameter"),n=$e(r,"Third parameter"),i=function(e,t){B(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,i=null==e?void 0:e.transform,a=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:gr(r,e,t+" has member 'flush' that"),readableType:o,start:void 0===n?void 0:wr(n,e,t+" has member 'start' that"),transform:void 0===i?void 0:vr(i,e,t+" has member 'transform' that"),writableType:a}}(e,"First parameter");if(void 0!==i.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==i.writableType)throw new RangeError("Invalid writableType specified");const a=Le(n,0),s=Me(n),l=Le(o,1),f=Me(o);let h;!function(e,t,r,o,n,i){function a(){return t}function s(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return jr(r,t)}))}return jr(r,t)}(e,t)}function l(t){return function(e,t){return Tr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,o=r._flushAlgorithm();return kr(r),p(o,(()=>{if("errored"===t._state)throw t._storedError;xt(t._readableStreamController)}),(r=>{throw Tr(e,r),t._storedError}))}(e)}function d(){return function(e){return qr(e,!1),e._backpressureChangePromise}(e)}function f(t){return Pr(e,t),c(void 0)}e._writable=function(e,t,r,o,n=1,i=(()=>1)){const a=Object.create(Ve.prototype);return Ge(a),bt(a,Object.create(_t.prototype),e,t,r,o,n,i),a}(a,s,u,l,r,o),e._readable=rr(a,d,f,n,i),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,qr(e,!0),e._transformStreamController=void 0}(this,u((e=>{h=e})),l,f,a,s),function(e,t){const r=Object.create(Er.prototype);let o=e=>{try{return Or(r,e),c(void 0)}catch(e){return d(e)}},n=()=>c(void 0);void 0!==t.transform&&(o=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,i),void 0!==i.start?h(i.start(this._transformStreamController)):h(void 0)}get readable(){if(!Rr(this))throw Ar("readable");return this._readable}get writable(){if(!Rr(this))throw Ar("writable");return this._writable}}function Rr(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function Tr(e,t){Qt(e._readable._readableStreamController,t),Pr(e,t)}function Pr(e,t){kr(e._transformStreamController),gt(e._writable._writableStreamController,t),e._backpressure&&qr(e,!1)}function qr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(Sr.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(Sr.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class Er{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Cr(this))throw Wr("desiredSize");return Ht(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=undefined){if(!Cr(this))throw Wr("enqueue");Or(this,e)}error(e=undefined){if(!Cr(this))throw Wr("error");var t;t=e,Tr(this._controlledTransformStream,t)}terminate(){if(!Cr(this))throw Wr("terminate");!function(e){const t=e._controlledTransformStream;xt(t._readable._readableStreamController);Pr(t,new TypeError("TransformStream terminated"))}(this)}}function Cr(e){return!!o(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function kr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Or(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!Yt(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{Nt(o,t)}catch(e){throw Pr(r,e),r._readable._storedError}const n=function(e){return!$t(e)}(o);n!==r._backpressure&&qr(r,!0)}function jr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw Tr(e._controlledTransformStream,t),t}))}function Wr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Ar(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(Er.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(Er.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});export{fr as ByteLengthQueuingStrategy,pr as CountQueuingStrategy,fe as ReadableByteStreamController,tr as ReadableStream,Fe as ReadableStreamBYOBReader,de as ReadableStreamBYOBRequest,It as ReadableStreamDefaultController,X as ReadableStreamDefaultReader,Sr as TransformStream,Er as TransformStreamDefaultController,Ve as WritableStream,_t as WritableStreamDefaultController,at as WritableStreamDefaultWriter}; -//# sourceMappingURL=ponyfill.es6.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs.map deleted file mode 100644 index 7f8eb7dd3..000000000 --- a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.min.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ponyfill.es6.min.mjs","sources":["../../node_modules/@openpgp/web-stream-tools/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs"],"sourcesContent":["/**\n * web-streams-polyfill v3.0.3\n */\n/// \nconst SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})`;\n\n/// \nfunction noop() {\n return undefined;\n}\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n }\n else if (typeof window !== 'undefined') {\n return window;\n }\n else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\nconst globals = getGlobals();\n\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nconst rethrowAssertionErrorRejection = noop;\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\nfunction newPromise(executor) {\n return new originalPromise(executor);\n}\nfunction promiseResolvedWith(value) {\n return originalPromiseResolve(value);\n}\nfunction promiseRejectedWith(reason) {\n return originalPromiseReject(reason);\n}\nfunction PerformPromiseThen(promise, onFulfilled, onRejected) {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected);\n}\nfunction uponPromise(promise, onFulfilled, onRejected) {\n PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);\n}\nfunction uponFulfillment(promise, onFulfilled) {\n uponPromise(promise, onFulfilled);\n}\nfunction uponRejection(promise, onRejected) {\n uponPromise(promise, undefined, onRejected);\n}\nfunction transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\nfunction setPromiseIsHandledToTrue(promise) {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\nconst queueMicrotask = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn) => PerformPromiseThen(resolvedPromise, fn);\n})();\nfunction reflectCall(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\nfunction promiseCall(F, V, args) {\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n }\n catch (value) {\n return promiseRejectedWith(value);\n }\n}\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nclass SimpleQueue {\n constructor() {\n this._cursor = 0;\n this._size = 0;\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n get length() {\n return this._size;\n }\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback) {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n node = node._next;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n }\n else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n }\n else {\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n const stream = reader._ownerReadableStream;\n return ReadableStreamCancel(stream, reason);\n}\nfunction ReadableStreamReaderGenericRelease(reader) {\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n// Helper functions for the readers.\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\nfunction defaultReaderClosedPromiseResolve(reader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nconst AbortSteps = SymbolPolyfill('[[AbortSteps]]');\nconst ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');\nconst CancelSteps = SymbolPolyfill('[[CancelSteps]]');\nconst PullSteps = SymbolPolyfill('[[PullSteps]]');\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nfunction isDictionary(x) {\n return typeof x === 'object' || typeof x === 'function';\n}\nfunction assertDictionary(obj, context) {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-callback-functions\nfunction assertFunction(x, context) {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-object\nfunction isObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nfunction assertObject(x, context) {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\nfunction assertRequiredArgument(x, position, context) {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\nfunction assertRequiredField(x, field, context) {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nfunction convertUnrestrictedDouble(value) {\n return Number(value);\n}\nfunction censorNegativeZero(x) {\n return x === 0 ? 0 : x;\n}\nfunction integerPart(x) {\n return censorNegativeZero(MathTrunc(x));\n}\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nfunction convertUnsignedLongLongWithEnforceRange(value, context) {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n let x = Number(value);\n x = censorNegativeZero(x);\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n x = integerPart(x);\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n return x;\n}\n\nfunction assertReadableStream(x, context) {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadRequest(stream, readRequest) {\n stream._reader._readRequests.push(readRequest);\n}\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readRequest = reader._readRequests.shift();\n if (done) {\n readRequest._closeSteps();\n }\n else {\n readRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\nfunction ReadableStreamHasDefaultReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamDefaultReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultReaderRead(reader, readRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n }\n else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n }\n else {\n stream._readableStreamController[PullSteps](readRequest);\n }\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n\n/// \nlet AsyncIteratorPrototype;\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolPolyfill.asyncIterator]() {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });\n}\n\n/// \nclass ReadableStreamAsyncIteratorImpl {\n constructor(reader, preventCancel) {\n this._ongoingPromise = undefined;\n this._isFinished = false;\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n next() {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n return(value) {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n _nextSteps() {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n _returnSteps(value) {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\nconst ReadableStreamAsyncIteratorPrototype = {\n next() {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n return(value) {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n};\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamAsyncIterator(stream, preventCancel) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\nfunction IsReadableStreamAsyncIterator(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n return true;\n}\n// Helper functions for the ReadableStream.\nfunction streamAsyncIteratorBrandCheckException(name) {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nfunction IsFiniteNonNegativeNumber(v) {\n if (!IsNonNegativeNumber(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n return true;\n}\nfunction IsNonNegativeNumber(v) {\n if (typeof v !== 'number') {\n return false;\n }\n if (NumberIsNaN(v)) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n return true;\n}\n\nfunction DequeueValue(container) {\n const pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n return pair.value;\n}\nfunction EnqueueValueWithSize(container, value, size) {\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\nfunction PeekQueueValue(container) {\n const pair = container._queue.peek();\n return pair.value;\n}\nfunction ResetQueue(container) {\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n\nfunction CreateArrayFromList(elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n}\nfunction CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n// Not implemented correctly\nfunction TransferArrayBuffer(O) {\n return O;\n}\n// Not implemented correctly\nfunction IsDetachedBuffer(O) {\n return false;\n}\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nclass ReadableStreamBYOBRequest {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view() {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n return this._view;\n }\n respond(bytesWritten) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n if (IsDetachedBuffer(this._view.buffer)) ;\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n respondWithNewView(view) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n if (view.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (view.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableByteStreamController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n if (this._byobRequest === null && this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, this, view);\n this._byobRequest = byobRequest;\n }\n return this._byobRequest;\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n ReadableByteStreamControllerClose(this);\n }\n enqueue(chunk) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n ReadableByteStreamControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n if (this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n firstDescriptor.bytesFilled = 0;\n }\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableByteStream;\n if (this._queueTotalSize > 0) {\n const entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n ReadableByteStreamControllerHandleQueueDrain(this);\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view);\n return;\n }\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n }\n catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n const pullIntoDescriptor = {\n buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableByteStreamController.\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n return true;\n}\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableByteStreamControllerError(controller, e);\n });\n}\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n let done = false;\n if (stream._state === 'closed') {\n done = true;\n }\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n }\n else {\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n const queue = controller._queue;\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n }\n else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n return ready;\n}\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n }\n else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === null) {\n return;\n }\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = null;\n controller._byobRequest = null;\n}\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {\n const stream = controller._controlledReadableByteStream;\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n const ctor = view.constructor;\n const buffer = TransferArrayBuffer(view.buffer);\n const pullIntoDescriptor = {\n buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n ReadableByteStreamControllerHandleQueueDrain(controller);\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n controller._pendingPullIntos.push(pullIntoDescriptor);\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n }\n else {\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n const descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return false;\n }\n if (controller._closeRequested) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableByteStreamControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n}\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\nfunction ReadableByteStreamControllerClose(controller) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n return;\n }\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n throw e;\n }\n }\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n const transferredBuffer = TransferArrayBuffer(buffer);\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n else {\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n }\n else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n }\n else {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerError(controller, e) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return;\n }\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableByteStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (!IsFiniteNonNegativeNumber(bytesWritten)) {\n throw new RangeError('bytesWritten must be a finite');\n }\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n firstDescriptor.buffer = view.buffer;\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\nfunction SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {\n controller._controlledReadableByteStream = stream;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._byobRequest = null;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._closeRequested = false;\n controller._started = false;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n controller._pendingPullIntos = new SimpleQueue();\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableByteStreamControllerError(controller, r);\n });\n}\nfunction SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {\n const controller = Object.create(ReadableByteStreamController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel(reason);\n }\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);\n}\nfunction SetUpReadableStreamBYOBRequest(request, controller, view) {\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n// Helper functions for the ReadableStreamBYOBRequest.\nfunction byobRequestBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n// Helper functions for the ReadableByteStreamController.\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {\n stream._reader._readIntoRequests.push(readIntoRequest);\n}\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readIntoRequest = reader._readIntoRequests.shift();\n if (done) {\n readIntoRequest._closeSteps(chunk);\n }\n else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\nfunction ReadableStreamHasBYOBReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamBYOBReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readIntoRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n }\n else {\n ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);\n }\n}\n// Helper functions for the ReadableStreamBYOBReader.\nfunction byobReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n\nfunction ExtractHighWaterMark(strategy, defaultHWM) {\n const { highWaterMark } = strategy;\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n return highWaterMark;\n}\nfunction ExtractSizeAlgorithm(strategy) {\n const { size } = strategy;\n if (!size) {\n return () => 1;\n }\n return size;\n}\n\nfunction convertQueuingStrategy(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n const size = init === null || init === void 0 ? void 0 : init.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\nfunction convertQueuingStrategySize(fn, context) {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n\nfunction convertUnderlyingSink(original, context) {\n assertDictionary(original, context);\n const abort = original === null || original === void 0 ? void 0 : original.abort;\n const close = original === null || original === void 0 ? void 0 : original.close;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n const write = original === null || original === void 0 ? void 0 : original.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),\n type\n };\n}\nfunction convertUnderlyingSinkAbortCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSinkCloseCallback(fn, original, context) {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\nfunction convertUnderlyingSinkStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSinkWriteCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction assertWritableStream(x, context) {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n constructor(rawUnderlyingSink = {}, rawStrategy = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n }\n else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n InitializeWritableStream(this);\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('locked');\n }\n return IsWritableStreamLocked(this);\n }\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason = undefined) {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('abort'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n return WritableStreamAbort(this, reason);\n }\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('close'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamClose(this);\n }\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('getWriter');\n }\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n// Abstract operations for the WritableStream.\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n const controller = Object.create(WritableStreamDefaultController.prototype);\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeWritableStream(stream) {\n stream._state = 'writable';\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n stream._writer = undefined;\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined;\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsWritableStreamLocked(stream) {\n if (stream._writer === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamAbort(stream, reason) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest._promise = promise;\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n return promise;\n}\nfunction WritableStreamClose(stream) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n const promise = newPromise((resolve, reject) => {\n const closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._closeRequest = closeRequest;\n });\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n return promise;\n}\n// WritableStream API exposed for controllers.\nfunction WritableStreamAddWriteRequest(stream) {\n const promise = newPromise((resolve, reject) => {\n const writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._writeRequests.push(writeRequest);\n });\n return promise;\n}\nfunction WritableStreamDealWithRejection(stream, error) {\n const state = stream._state;\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n WritableStreamFinishErroring(stream);\n}\nfunction WritableStreamStartErroring(stream, reason) {\n const controller = stream._writableStreamController;\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\nfunction WritableStreamFinishErroring(stream) {\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(promise, () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, (reason) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\nfunction WritableStreamFinishInFlightWrite(stream) {\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n WritableStreamDealWithRejection(stream, error);\n}\nfunction WritableStreamFinishInFlightClose(stream) {\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n const state = stream._state;\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n stream._state = 'closed';\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n}\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n if (stream._closeRequest !== undefined) {\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n }\n else {\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n stream._backpressure = backpressure;\n}\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nclass WritableStreamDefaultWriter {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n this._ownerWritableStream = stream;\n stream._writer = this;\n const state = stream._state;\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n }\n else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n }\n else {\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n return this._readyPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamDefaultWriterClose(this);\n }\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return;\n }\n WritableStreamDefaultWriterRelease(this);\n }\n write(chunk = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n// Abstract operations for the WritableStreamDefaultWriter.\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n return true;\n}\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n const stream = writer._ownerWritableStream;\n return WritableStreamAbort(stream, reason);\n}\nfunction WritableStreamDefaultWriterClose(writer) {\n const stream = writer._ownerWritableStream;\n return WritableStreamClose(stream);\n}\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n return WritableStreamDefaultWriterClose(writer);\n}\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n }\n else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n }\n else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\nfunction WritableStreamDefaultWriterRelease(writer) {\n const stream = writer._ownerWritableStream;\n const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n const stream = writer._ownerWritableStream;\n const controller = stream._writableStreamController;\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n const promise = WritableStreamAddWriteRequest(stream);\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n return promise;\n}\nconst closeSentinel = {};\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nclass WritableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e = undefined) {\n if (!IsWritableStreamDefaultController(this)) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n WritableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [AbortSteps](reason) {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n error: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations implementing interface required by the WritableStream.\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(startPromise, () => {\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, r => {\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n });\n}\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let writeAlgorithm = () => promiseResolvedWith(undefined);\n let closeAlgorithm = () => promiseResolvedWith(undefined);\n let abortAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort(reason);\n }\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller) {\n controller._writeAlgorithm = undefined;\n controller._closeAlgorithm = undefined;\n controller._abortAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n try {\n return controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n// Abstract operations for the WritableStreamDefaultController.\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n const stream = controller._controlledWritableStream;\n if (!controller._started) {\n return;\n }\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n const state = stream._state;\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n if (controller._queue.length === 0) {\n return;\n }\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n }\n else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkCloseRequestInFlight(stream);\n DequeueValue(controller);\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(sinkClosePromise, () => {\n WritableStreamFinishInFlightClose(stream);\n }, reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(sinkWritePromise, () => {\n WritableStreamFinishInFlightWrite(stream);\n const state = stream._state;\n DequeueValue(controller);\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\nfunction WritableStreamDefaultControllerError(controller, error) {\n const stream = controller._controlledWritableStream;\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n// Helper functions for the WritableStream.\nfunction streamBrandCheckException$2(name) {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n// Helper functions for the WritableStreamDefaultWriter.\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterClosedPromiseResolve(writer) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\nfunction defaultWriterReadyPromiseReset(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n}\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterReadyPromiseResolve(writer) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction isAbortSignal(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof value.aborted === 'boolean';\n }\n catch (_a) {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/// \nconst NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;\n\n/// \nfunction isDOMExceptionConstructor(ctor) {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new ctor();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createDOMExceptionPolyfill() {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(message, name) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n };\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n// eslint-disable-next-line no-redeclare\nconst DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nfunction ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n source._disturbed = true;\n let shuttingDown = false;\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n return newPromise((resolve, reject) => {\n let abortAlgorithm;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException$1('Aborted', 'AbortError');\n const actions = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n signal.addEventListener('abort', abortAlgorithm);\n }\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done) {\n if (done) {\n resolveLoop();\n }\n else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n next(false);\n });\n }\n function pipeStep() {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(reader, {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n });\n });\n });\n }\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n }\n else {\n shutdown();\n }\n });\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n }\n else {\n shutdown(true, destClosed);\n }\n }\n setPromiseIsHandledToTrue(pipeLoop());\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);\n }\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n }\n else {\n uponRejection(promise, action);\n }\n }\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n }\n else {\n uponFulfillment(promise, action);\n }\n }\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n }\n else {\n doTheRest();\n }\n function doTheRest() {\n uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));\n }\n }\n function shutdown(isError, error) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n }\n else {\n finalize(isError, error);\n }\n }\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n }\n else {\n resolve(undefined);\n }\n }\n });\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('desiredSize');\n }\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('close');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n ReadableStreamDefaultControllerClose(this);\n }\n enqueue(chunk = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('enqueue');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('error');\n }\n ReadableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableStream;\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n }\n else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n readRequest._chunkSteps(chunk);\n }\n else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableStreamDefaultController.\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableStreamDefaultControllerError(controller, e);\n });\n}\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableStream;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\nfunction ReadableStreamDefaultControllerClose(controller) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n controller._closeRequested = true;\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n }\n else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\nfunction ReadableStreamDefaultControllerError(controller, e) {\n const stream = controller._controlledReadableStream;\n if (stream._state !== 'readable') {\n return;\n }\n ResetQueue(controller);\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\n// This is used in the implementation of TransformStream.\nfunction ReadableStreamDefaultControllerHasBackpressure(controller) {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {\n const state = controller._controlledReadableStream._state;\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n return false;\n}\nfunction SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledReadableStream = stream;\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableStreamDefaultControllerError(controller, r);\n });\n}\nfunction SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel(reason);\n }\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// Helper functions for the ReadableStreamDefaultController.\nfunction defaultControllerBrandCheckException$1(name) {\n return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let branch1;\n let branch2;\n let resolveCancelPromise;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n function pullAlgorithm() {\n if (reading) {\n return promiseResolvedWith(undefined);\n }\n reading = true;\n const readRequest = {\n _chunkSteps: value => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n reading = false;\n const value1 = value;\n const value2 = value;\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promiseResolvedWith(undefined);\n }\n function cancel1Algorithm(reason) {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function cancel2Algorithm(reason) {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function startAlgorithm() {\n // do nothing\n }\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n uponRejection(reader._closedPromise, (r) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n return [branch1, branch2];\n}\n\nfunction convertUnderlyingDefaultOrByteSource(source, context) {\n assertDictionary(source, context);\n const original = source;\n const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;\n const cancel = original === null || original === void 0 ? void 0 : original.cancel;\n const pull = original === null || original === void 0 ? void 0 : original.pull;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\nfunction convertUnderlyingSourceCancelCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSourcePullCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSourceStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertReadableStreamType(type, context) {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n\nfunction convertReaderOptions(options, context) {\n assertDictionary(options, context);\n const mode = options === null || options === void 0 ? void 0 : options.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\nfunction convertReadableStreamReaderMode(mode, context) {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nfunction convertIteratorOptions(options, context) {\n assertDictionary(options, context);\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n\nfunction convertPipeOptions(options, context) {\n assertDictionary(options, context);\n const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;\n const signal = options === null || options === void 0 ? void 0 : options.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\nfunction assertAbortSignal(signal, context) {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n\nfunction convertReadableWritablePair(pair, context) {\n assertDictionary(pair, context);\n const readable = pair === null || pair === void 0 ? void 0 : pair.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n const writable = pair === null || pair === void 0 ? void 0 : pair.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n return { readable, writable };\n}\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nclass ReadableStream {\n constructor(rawUnderlyingSource = {}, rawStrategy = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n }\n else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n InitializeReadableStream(this);\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);\n }\n else {\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);\n }\n }\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('locked');\n }\n return IsReadableStreamLocked(this);\n }\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason = undefined) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('cancel'));\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n return ReadableStreamCancel(this, reason);\n }\n getReader(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('getReader');\n }\n const options = convertReaderOptions(rawOptions, 'First parameter');\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n return AcquireReadableStreamBYOBReader(this);\n }\n pipeThrough(rawTransform, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n setPromiseIsHandledToTrue(promise);\n return transform.readable;\n }\n pipeTo(destination, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));\n }\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));\n }\n let options;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n }\n catch (e) {\n return promiseRejectedWith(e);\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n }\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('tee');\n }\n const branches = ReadableStreamTee(this);\n return CreateArrayFromList(branches);\n }\n values(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('values');\n }\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n}\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n// Abstract operations for the ReadableStream.\n// Throws if and only if startAlgorithm throws.\nfunction CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeReadableStream(stream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamLocked(stream) {\n if (stream._reader === undefined) {\n return false;\n }\n return true;\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n ReadableStreamClose(stream);\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\nfunction ReadableStreamClose(stream) {\n stream._state = 'closed';\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseResolve(reader);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\nfunction ReadableStreamError(stream, e) {\n stream._state = 'errored';\n stream._storedError = e;\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseReject(reader, e);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n reader._readRequests = new SimpleQueue();\n }\n else {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n// Helper functions for the ReadableStream.\nfunction streamBrandCheckException$1(name) {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n\nfunction convertQueuingStrategyInit(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n\nconst byteLengthSizeFunction = function size(chunk) {\n return chunk.byteLength;\n};\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nclass ByteLengthQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the ByteLengthQueuingStrategy.\nfunction byteLengthBrandCheckException(name) {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\nfunction IsByteLengthQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nconst countSizeFunction = function size() {\n return 1;\n};\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nclass CountQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the CountQueuingStrategy.\nfunction countBrandCheckException(name) {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\nfunction IsCountQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nfunction convertTransformer(original, context) {\n assertDictionary(original, context);\n const flush = original === null || original === void 0 ? void 0 : original.flush;\n const readableType = original === null || original === void 0 ? void 0 : original.readableType;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const transform = original === null || original === void 0 ? void 0 : original.transform;\n const writableType = original === null || original === void 0 ? void 0 : original.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),\n writableType\n };\n}\nfunction convertTransformerFlushCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertTransformerStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertTransformerTransformCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\n// Class TransformStream\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nclass TransformStream {\n constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n let startPromise_resolve;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n }\n else {\n startPromise_resolve(undefined);\n }\n }\n /**\n * The readable side of the transform stream.\n */\n get readable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n return this._readable;\n }\n /**\n * The writable side of the transform stream.\n */\n get writable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n return this._writable;\n }\n}\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\nfunction InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {\n function startAlgorithm() {\n return startPromise;\n }\n function writeAlgorithm(chunk) {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n function abortAlgorithm(reason) {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n function closeAlgorithm() {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);\n function pullAlgorithm() {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n function cancelAlgorithm(reason) {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined;\n stream._backpressureChangePromise = undefined;\n stream._backpressureChangePromise_resolve = undefined;\n TransformStreamSetBackpressure(stream, true);\n stream._transformStreamController = undefined;\n}\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n return true;\n}\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream, e) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\nfunction TransformStreamErrorWritableAndUnblockWrite(stream, e) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\nfunction TransformStreamSetBackpressure(stream, backpressure) {\n // Passes also when called during construction.\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n stream._backpressure = backpressure;\n}\n// Class TransformStreamDefaultController\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nclass TransformStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n enqueue(chunk = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n TransformStreamDefaultControllerError(this, reason);\n }\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n TransformStreamDefaultControllerTerminate(this);\n }\n}\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n// Transform Stream Default Controller Abstract Operations\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {\n const controller = Object.create(TransformStreamDefaultController.prototype);\n let transformAlgorithm = (chunk) => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk);\n return promiseResolvedWith(undefined);\n }\n catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n let flushAlgorithm = () => promiseResolvedWith(undefined);\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush(controller);\n }\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\nfunction TransformStreamDefaultControllerClearAlgorithms(controller) {\n controller._transformAlgorithm = undefined;\n controller._flushAlgorithm = undefined;\n}\nfunction TransformStreamDefaultControllerEnqueue(controller, chunk) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n }\n catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n throw stream._readable._storedError;\n }\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n TransformStreamSetBackpressure(stream, true);\n }\n}\nfunction TransformStreamDefaultControllerError(controller, e) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\nfunction TransformStreamDefaultControllerPerformTransform(controller, chunk) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\nfunction TransformStreamDefaultControllerTerminate(controller) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n ReadableStreamDefaultControllerClose(readableController);\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n// TransformStreamDefaultSink Algorithms\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {\n const controller = stream._transformStreamController;\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream) {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n// TransformStreamDefaultSource Algorithms\nfunction TransformStreamDefaultSourcePullAlgorithm(stream) {\n // Invariant. Enforced by the promises returned by start() and pull().\n TransformStreamSetBackpressure(stream, false);\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n// Helper functions for the TransformStreamDefaultController.\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n// Helper functions for the TransformStream.\nfunction streamBrandCheckException(name) {\n return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n\nexport { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };\n//# sourceMappingURL=ponyfill.es6.mjs.map\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","globals","self","window","global","typeIsObject","x","rethrowAssertionErrorRejection","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseResolve","resolve","bind","originalPromiseReject","reject","newPromise","executor","promiseResolvedWith","value","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","fn","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","callback","i","node","peek","front","cursor","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","name","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","Object","hasOwnProperty","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","enumerable","toStringTag","defineProperty","configurable","asyncIterator","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","next","nextSteps","_nextSteps","return","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","IsFiniteNonNegativeNumber","IsNonNegativeNumber","Infinity","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","RangeError","ResetQueue","CreateArrayFromList","slice","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","buffer","controller","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespond","respondWithNewView","ArrayBuffer","isView","byteLength","firstDescriptor","_pendingPullIntos","byteOffset","bytesFilled","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","_byobRequest","Uint8Array","create","request","SetUpReadableStreamBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerError","ReadableByteStreamControllerClearAlgorithms","ReadableStreamClose","ReadableByteStreamControllerClose","enqueue","transferredBuffer","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableStreamHasBYOBReader","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerEnqueue","error","_cancelAlgorithm","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","elementSize","viewConstructor","readerType","shouldPull","_started","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","min","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","ready","queue","headOfQueue","bytesToCopy","destStart","dest","destOffset","src","srcOffset","n","set","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInClosedState","remainderSize","end","remainder","ReadableByteStreamControllerRespondInReadableState","descriptor","ReadableByteStreamControllerClearPendingPullIntos","ReadableStreamError","_strategyHWM","SetUpReadableByteStreamControllerFromUnderlyingSource","underlyingByteSource","highWaterMark","startAlgorithm","pullAlgorithm","cancelAlgorithm","start","pull","r","SetUpReadableByteStreamController","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","ReadableStreamBYOBReader","byobReaderBrandCheckException","DataView","BYTES_PER_ELEMENT","ctor","emptyView","ReadableByteStreamControllerPullInto","ReadableStreamBYOBReaderRead","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException$2","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","DOMException$1","_a","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createDOMExceptionPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","signal","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","defaultControllerBrandCheckException$1","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","mode","convertPipeOptions","options","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","SetUpReadableStreamDefaultControllerFromUnderlyingSource","streamBrandCheckException$1","getReader","rawOptions","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","branches","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","canceled1","canceled2","cancelPromise","value1","value2","CreateReadableStream","compositeReason","cancelResult","ReadableStreamTee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","streamBrandCheckException","IsTransformStreamDefaultController","defaultControllerBrandCheckException","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure"],"mappings":";yGAIMA,EAAmC,mBAAXC,QAAoD,iBAApBA,OAAOC,SACjED,OACAE,GAAe,UAAUA,KAG7B,SAASC,IAET,CAaA,MAAMC,EAXkB,oBAATC,KACAA,KAEgB,oBAAXC,OACLA,OAEgB,oBAAXC,OACLA,YADN,EAOT,SAASC,EAAaC,GAClB,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CAC3D,CACA,MAAMC,EAAiCP,EAEjCQ,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAyBJ,QAAQK,QAAQC,KAAKP,GAC9CQ,EAAwBP,QAAQQ,OAAOF,KAAKP,GAClD,SAASU,EAAWC,GAChB,OAAO,IAAIX,EAAgBW,EAC/B,CACA,SAASC,EAAoBC,GACzB,OAAOR,EAAuBQ,EAClC,CACA,SAASC,EAAoBC,GACzB,OAAOP,EAAsBO,EACjC,CACA,SAASC,EAAmBC,EAASC,EAAaC,GAG9C,OAAOjB,EAAoBkB,KAAKH,EAASC,EAAaC,EAC1D,CACA,SAASE,EAAYJ,EAASC,EAAaC,GACvCH,EAAmBA,EAAmBC,EAASC,EAAaC,QAAaG,EAAWvB,EACxF,CACA,SAASwB,EAAgBN,EAASC,GAC9BG,EAAYJ,EAASC,EACzB,CACA,SAASM,EAAcP,EAASE,GAC5BE,EAAYJ,OAASK,EAAWH,EACpC,CACA,SAASM,EAAqBR,EAASS,EAAoBC,GACvD,OAAOX,EAAmBC,EAASS,EAAoBC,EAC3D,CACA,SAASC,EAA0BX,GAC/BD,EAAmBC,OAASK,EAAWvB,EAC3C,CACA,MAAM8B,EAAiB,MACnB,MAAMC,EAAuBrC,GAAWA,EAAQoC,eAChD,GAAoC,mBAAzBC,EACP,OAAOA,EAEX,MAAMC,EAAkBnB,OAAoBU,GAC5C,OAAQU,GAAOhB,EAAmBe,EAAiBC,EACtD,EAPsB,GAQ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KAEW,iBAA/BnK,EAAeoK,aACtBP,OAAOQ,eAAegb,GAAiCtkB,UAAWf,EAAeoK,YAAa,CAC1F3I,MAAO,mCACP6I,cAAc"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.mjs b/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.mjs deleted file mode 100644 index ce6dd54b1..000000000 --- a/app/node_modules/openpgp/dist/lightweight/ponyfill.es6.mjs +++ /dev/null @@ -1,3831 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -/** - * web-streams-polyfill v3.0.3 - */ -/// -const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? - Symbol : - description => `Symbol(${description})`; - -/// -function noop() { - return undefined; -} -function getGlobals() { - if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else if (typeof global !== 'undefined') { - return global; - } - return undefined; -} -const globals = getGlobals(); - -function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -const rethrowAssertionErrorRejection = noop; - -const originalPromise = Promise; -const originalPromiseThen = Promise.prototype.then; -const originalPromiseResolve = Promise.resolve.bind(originalPromise); -const originalPromiseReject = Promise.reject.bind(originalPromise); -function newPromise(executor) { - return new originalPromise(executor); -} -function promiseResolvedWith(value) { - return originalPromiseResolve(value); -} -function promiseRejectedWith(reason) { - return originalPromiseReject(reason); -} -function PerformPromiseThen(promise, onFulfilled, onRejected) { - // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an - // approximation. - return originalPromiseThen.call(promise, onFulfilled, onRejected); -} -function uponPromise(promise, onFulfilled, onRejected) { - PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); -} -function uponFulfillment(promise, onFulfilled) { - uponPromise(promise, onFulfilled); -} -function uponRejection(promise, onRejected) { - uponPromise(promise, undefined, onRejected); -} -function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { - return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); -} -function setPromiseIsHandledToTrue(promise) { - PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); -} -const queueMicrotask = (() => { - const globalQueueMicrotask = globals && globals.queueMicrotask; - if (typeof globalQueueMicrotask === 'function') { - return globalQueueMicrotask; - } - const resolvedPromise = promiseResolvedWith(undefined); - return (fn) => PerformPromiseThen(resolvedPromise, fn); -})(); -function reflectCall(F, V, args) { - if (typeof F !== 'function') { - throw new TypeError('Argument is not a function'); - } - return Function.prototype.apply.call(F, V, args); -} -function promiseCall(F, V, args) { - try { - return promiseResolvedWith(reflectCall(F, V, args)); - } - catch (value) { - return promiseRejectedWith(value); - } -} - -// Original from Chromium -// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js -const QUEUE_MAX_ARRAY_SIZE = 16384; -/** - * Simple queue structure. - * - * Avoids scalability issues with using a packed array directly by using - * multiple arrays in a linked list and keeping the array size bounded. - */ -class SimpleQueue { - constructor() { - this._cursor = 0; - this._size = 0; - // _front and _back are always defined. - this._front = { - _elements: [], - _next: undefined - }; - this._back = this._front; - // The cursor is used to avoid calling Array.shift(). - // It contains the index of the front element of the array inside the - // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). - this._cursor = 0; - // When there is only one node, size === elements.length - cursor. - this._size = 0; - } - get length() { - return this._size; - } - // For exception safety, this method is structured in order: - // 1. Read state - // 2. Calculate required state mutations - // 3. Perform state mutations - push(element) { - const oldBack = this._back; - let newBack = oldBack; - if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { - newBack = { - _elements: [], - _next: undefined - }; - } - // push() is the mutation most likely to throw an exception, so it - // goes first. - oldBack._elements.push(element); - if (newBack !== oldBack) { - this._back = newBack; - oldBack._next = newBack; - } - ++this._size; - } - // Like push(), shift() follows the read -> calculate -> mutate pattern for - // exception safety. - shift() { // must not be called on an empty queue - const oldFront = this._front; - let newFront = oldFront; - const oldCursor = this._cursor; - let newCursor = oldCursor + 1; - const elements = oldFront._elements; - const element = elements[oldCursor]; - if (newCursor === QUEUE_MAX_ARRAY_SIZE) { - newFront = oldFront._next; - newCursor = 0; - } - // No mutations before this point. - --this._size; - this._cursor = newCursor; - if (oldFront !== newFront) { - this._front = newFront; - } - // Permit shifted element to be garbage collected. - elements[oldCursor] = undefined; - return element; - } - // The tricky thing about forEach() is that it can be called - // re-entrantly. The queue may be mutated inside the callback. It is easy to - // see that push() within the callback has no negative effects since the end - // of the queue is checked for on every iteration. If shift() is called - // repeatedly within the callback then the next iteration may return an - // element that has been removed. In this case the callback will be called - // with undefined values until we either "catch up" with elements that still - // exist or reach the back of the queue. - forEach(callback) { - let i = this._cursor; - let node = this._front; - let elements = node._elements; - while (i !== elements.length || node._next !== undefined) { - if (i === elements.length) { - node = node._next; - elements = node._elements; - i = 0; - if (elements.length === 0) { - break; - } - } - callback(elements[i]); - ++i; - } - } - // Return the element that would be returned if shift() was called now, - // without modifying the queue. - peek() { // must not be called on an empty queue - const front = this._front; - const cursor = this._cursor; - return front._elements[cursor]; - } -} - -function ReadableStreamReaderGenericInitialize(reader, stream) { - reader._ownerReadableStream = stream; - stream._reader = reader; - if (stream._state === 'readable') { - defaultReaderClosedPromiseInitialize(reader); - } - else if (stream._state === 'closed') { - defaultReaderClosedPromiseInitializeAsResolved(reader); - } - else { - defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); - } -} -// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state -// check. -function ReadableStreamReaderGenericCancel(reader, reason) { - const stream = reader._ownerReadableStream; - return ReadableStreamCancel(stream, reason); -} -function ReadableStreamReaderGenericRelease(reader) { - if (reader._ownerReadableStream._state === 'readable') { - defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - else { - defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - reader._ownerReadableStream._reader = undefined; - reader._ownerReadableStream = undefined; -} -// Helper functions for the readers. -function readerLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released reader'); -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderClosedPromiseInitialize(reader) { - reader._closedPromise = newPromise((resolve, reject) => { - reader._closedPromise_resolve = resolve; - reader._closedPromise_reject = reject; - }); -} -function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseReject(reader, reason); -} -function defaultReaderClosedPromiseInitializeAsResolved(reader) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseResolve(reader); -} -function defaultReaderClosedPromiseReject(reader, reason) { - if (reader._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(reader._closedPromise); - reader._closedPromise_reject(reason); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -function defaultReaderClosedPromiseResetToRejected(reader, reason) { - defaultReaderClosedPromiseInitializeAsRejected(reader, reason); -} -function defaultReaderClosedPromiseResolve(reader) { - if (reader._closedPromise_resolve === undefined) { - return; - } - reader._closedPromise_resolve(undefined); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} - -const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); -const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); -const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); -const PullSteps = SymbolPolyfill('[[PullSteps]]'); - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill -const NumberIsFinite = Number.isFinite || function (x) { - return typeof x === 'number' && isFinite(x); -}; - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill -const MathTrunc = Math.trunc || function (v) { - return v < 0 ? Math.ceil(v) : Math.floor(v); -}; - -// https://heycam.github.io/webidl/#idl-dictionaries -function isDictionary(x) { - return typeof x === 'object' || typeof x === 'function'; -} -function assertDictionary(obj, context) { - if (obj !== undefined && !isDictionary(obj)) { - throw new TypeError(`${context} is not an object.`); - } -} -// https://heycam.github.io/webidl/#idl-callback-functions -function assertFunction(x, context) { - if (typeof x !== 'function') { - throw new TypeError(`${context} is not a function.`); - } -} -// https://heycam.github.io/webidl/#idl-object -function isObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -function assertObject(x, context) { - if (!isObject(x)) { - throw new TypeError(`${context} is not an object.`); - } -} -function assertRequiredArgument(x, position, context) { - if (x === undefined) { - throw new TypeError(`Parameter ${position} is required in '${context}'.`); - } -} -function assertRequiredField(x, field, context) { - if (x === undefined) { - throw new TypeError(`${field} is required in '${context}'.`); - } -} -// https://heycam.github.io/webidl/#idl-unrestricted-double -function convertUnrestrictedDouble(value) { - return Number(value); -} -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} -function integerPart(x) { - return censorNegativeZero(MathTrunc(x)); -} -// https://heycam.github.io/webidl/#idl-unsigned-long-long -function convertUnsignedLongLongWithEnforceRange(value, context) { - const lowerBound = 0; - const upperBound = Number.MAX_SAFE_INTEGER; - let x = Number(value); - x = censorNegativeZero(x); - if (!NumberIsFinite(x)) { - throw new TypeError(`${context} is not a finite number`); - } - x = integerPart(x); - if (x < lowerBound || x > upperBound) { - throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); - } - if (!NumberIsFinite(x) || x === 0) { - return 0; - } - // TODO Use BigInt if supported? - // let xBigInt = BigInt(integerPart(x)); - // xBigInt = BigInt.asUintN(64, xBigInt); - // return Number(xBigInt); - return x; -} - -function assertReadableStream(x, context) { - if (!IsReadableStream(x)) { - throw new TypeError(`${context} is not a ReadableStream.`); - } -} - -// Abstract operations for the ReadableStream. -function AcquireReadableStreamDefaultReader(stream) { - return new ReadableStreamDefaultReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadRequest(stream, readRequest) { - stream._reader._readRequests.push(readRequest); -} -function ReadableStreamFulfillReadRequest(stream, chunk, done) { - const reader = stream._reader; - const readRequest = reader._readRequests.shift(); - if (done) { - readRequest._closeSteps(); - } - else { - readRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadRequests(stream) { - return stream._reader._readRequests.length; -} -function ReadableStreamHasDefaultReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamDefaultReader(reader)) { - return false; - } - return true; -} -/** - * A default reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamDefaultReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, - * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } - /** - * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('read')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: () => resolvePromise({ value: undefined, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamDefaultReaderRead(this, readRequest); - return promise; - } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamDefaultReader(this)) { - throw defaultReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamDefaultReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamDefaultReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { - return false; - } - return true; -} -function ReadableStreamDefaultReaderRead(reader, readRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'closed') { - readRequest._closeSteps(); - } - else if (stream._state === 'errored') { - readRequest._errorSteps(stream._storedError); - } - else { - stream._readableStreamController[PullSteps](readRequest); - } -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); -} - -/// -let AsyncIteratorPrototype; -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - // We're running inside a ES2018+ environment, but we're compiling to an older syntax. - // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. - AsyncIteratorPrototype = { - // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) - // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator - [SymbolPolyfill.asyncIterator]() { - return this; - } - }; - Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); -} - -/// -class ReadableStreamAsyncIteratorImpl { - constructor(reader, preventCancel) { - this._ongoingPromise = undefined; - this._isFinished = false; - this._reader = reader; - this._preventCancel = preventCancel; - } - next() { - const nextSteps = () => this._nextSteps(); - this._ongoingPromise = this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : - nextSteps(); - return this._ongoingPromise; - } - return(value) { - const returnSteps = () => this._returnSteps(value); - return this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : - returnSteps(); - } - _nextSteps() { - if (this._isFinished) { - return Promise.resolve({ value: undefined, done: true }); - } - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('iterate')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => { - this._ongoingPromise = undefined; - // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. - // FIXME Is this a bug in the specification, or in the test? - queueMicrotask(() => resolvePromise({ value: chunk, done: false })); - }, - _closeSteps: () => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - resolvePromise({ value: undefined, done: true }); - }, - _errorSteps: reason => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - rejectPromise(reason); - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promise; - } - _returnSteps(value) { - if (this._isFinished) { - return Promise.resolve({ value, done: true }); - } - this._isFinished = true; - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('finish iterating')); - } - if (!this._preventCancel) { - const result = ReadableStreamReaderGenericCancel(reader, value); - ReadableStreamReaderGenericRelease(reader); - return transformPromiseWith(result, () => ({ value, done: true })); - } - ReadableStreamReaderGenericRelease(reader); - return promiseResolvedWith({ value, done: true }); - } -} -const ReadableStreamAsyncIteratorPrototype = { - next() { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); - } - return this._asyncIteratorImpl.next(); - }, - return(value) { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); - } - return this._asyncIteratorImpl.return(value); - } -}; -if (AsyncIteratorPrototype !== undefined) { - Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); -} -// Abstract operations for the ReadableStream. -function AcquireReadableStreamAsyncIterator(stream, preventCancel) { - const reader = AcquireReadableStreamDefaultReader(stream); - const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); - iterator._asyncIteratorImpl = impl; - return iterator; -} -function IsReadableStreamAsyncIterator(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { - return false; - } - return true; -} -// Helper functions for the ReadableStream. -function streamAsyncIteratorBrandCheckException(name) { - return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); -} - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill -const NumberIsNaN = Number.isNaN || function (x) { - // eslint-disable-next-line no-self-compare - return x !== x; -}; - -function IsFiniteNonNegativeNumber(v) { - if (!IsNonNegativeNumber(v)) { - return false; - } - if (v === Infinity) { - return false; - } - return true; -} -function IsNonNegativeNumber(v) { - if (typeof v !== 'number') { - return false; - } - if (NumberIsNaN(v)) { - return false; - } - if (v < 0) { - return false; - } - return true; -} - -function DequeueValue(container) { - const pair = container._queue.shift(); - container._queueTotalSize -= pair.size; - if (container._queueTotalSize < 0) { - container._queueTotalSize = 0; - } - return pair.value; -} -function EnqueueValueWithSize(container, value, size) { - size = Number(size); - if (!IsFiniteNonNegativeNumber(size)) { - throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); - } - container._queue.push({ value, size }); - container._queueTotalSize += size; -} -function PeekQueueValue(container) { - const pair = container._queue.peek(); - return pair.value; -} -function ResetQueue(container) { - container._queue = new SimpleQueue(); - container._queueTotalSize = 0; -} - -function CreateArrayFromList(elements) { - // We use arrays to represent lists, so this is basically a no-op. - // Do a slice though just in case we happen to depend on the unique-ness. - return elements.slice(); -} -function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { - new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); -} -// Not implemented correctly -function TransferArrayBuffer(O) { - return O; -} -// Not implemented correctly -function IsDetachedBuffer(O) { - return false; -} - -/** - * A pull-into request in a {@link ReadableByteStreamController}. - * - * @public - */ -class ReadableStreamBYOBRequest { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. - */ - get view() { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('view'); - } - return this._view; - } - respond(bytesWritten) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respond'); - } - assertRequiredArgument(bytesWritten, 1, 'respond'); - bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - if (IsDetachedBuffer(this._view.buffer)) ; - ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); - } - respondWithNewView(view) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respondWithNewView'); - } - assertRequiredArgument(view, 1, 'respondWithNewView'); - if (!ArrayBuffer.isView(view)) { - throw new TypeError('You can only respond with array buffer views'); - } - if (view.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (view.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); - } -} -Object.defineProperties(ReadableStreamBYOBRequest.prototype, { - respond: { enumerable: true }, - respondWithNewView: { enumerable: true }, - view: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBRequest', - configurable: true - }); -} -/** - * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. - * - * @public - */ -class ReadableByteStreamController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the current BYOB pull request, or `null` if there isn't one. - */ - get byobRequest() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('byobRequest'); - } - if (this._byobRequest === null && this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); - const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); - SetUpReadableStreamBYOBRequest(byobRequest, this, view); - this._byobRequest = byobRequest; - } - return this._byobRequest; - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('desiredSize'); - } - return ReadableByteStreamControllerGetDesiredSize(this); - } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('close'); - } - if (this._closeRequested) { - throw new TypeError('The stream has already been closed; do not close it again!'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); - } - ReadableByteStreamControllerClose(this); - } - enqueue(chunk) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('enqueue'); - } - assertRequiredArgument(chunk, 1, 'enqueue'); - if (!ArrayBuffer.isView(chunk)) { - throw new TypeError('chunk must be an array buffer view'); - } - if (chunk.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (chunk.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._closeRequested) { - throw new TypeError('stream is closed or draining'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); - } - ReadableByteStreamControllerEnqueue(this, chunk); - } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('error'); - } - ReadableByteStreamControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - if (this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - firstDescriptor.bytesFilled = 0; - } - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableByteStreamControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableByteStream; - if (this._queueTotalSize > 0) { - const entry = this._queue.shift(); - this._queueTotalSize -= entry.byteLength; - ReadableByteStreamControllerHandleQueueDrain(this); - const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); - readRequest._chunkSteps(view); - return; - } - const autoAllocateChunkSize = this._autoAllocateChunkSize; - if (autoAllocateChunkSize !== undefined) { - let buffer; - try { - buffer = new ArrayBuffer(autoAllocateChunkSize); - } - catch (bufferE) { - readRequest._errorSteps(bufferE); - return; - } - const pullIntoDescriptor = { - buffer, - byteOffset: 0, - byteLength: autoAllocateChunkSize, - bytesFilled: 0, - elementSize: 1, - viewConstructor: Uint8Array, - readerType: 'default' - }; - this._pendingPullIntos.push(pullIntoDescriptor); - } - ReadableStreamAddReadRequest(stream, readRequest); - ReadableByteStreamControllerCallPullIfNeeded(this); - } -} -Object.defineProperties(ReadableByteStreamController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - byobRequest: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableByteStreamController', - configurable: true - }); -} -// Abstract operations for the ReadableByteStreamController. -function IsReadableByteStreamController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { - return false; - } - return true; -} -function IsReadableStreamBYOBRequest(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { - return false; - } - return true; -} -function ReadableByteStreamControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - // TODO: Test controller argument - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableByteStreamControllerError(controller, e); - }); -} -function ReadableByteStreamControllerClearPendingPullIntos(controller) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - controller._pendingPullIntos = new SimpleQueue(); -} -function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { - let done = false; - if (stream._state === 'closed') { - done = true; - } - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - if (pullIntoDescriptor.readerType === 'default') { - ReadableStreamFulfillReadRequest(stream, filledView, done); - } - else { - ReadableStreamFulfillReadIntoRequest(stream, filledView, done); - } -} -function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { - const bytesFilled = pullIntoDescriptor.bytesFilled; - const elementSize = pullIntoDescriptor.elementSize; - return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); -} -function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { - controller._queue.push({ buffer, byteOffset, byteLength }); - controller._queueTotalSize += byteLength; -} -function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { - const elementSize = pullIntoDescriptor.elementSize; - const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; - const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); - const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; - const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; - let totalBytesToCopyRemaining = maxBytesToCopy; - let ready = false; - if (maxAlignedBytes > currentAlignedBytes) { - totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; - ready = true; - } - const queue = controller._queue; - while (totalBytesToCopyRemaining > 0) { - const headOfQueue = queue.peek(); - const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); - const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); - if (headOfQueue.byteLength === bytesToCopy) { - queue.shift(); - } - else { - headOfQueue.byteOffset += bytesToCopy; - headOfQueue.byteLength -= bytesToCopy; - } - controller._queueTotalSize -= bytesToCopy; - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); - totalBytesToCopyRemaining -= bytesToCopy; - } - return ready; -} -function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - pullIntoDescriptor.bytesFilled += size; -} -function ReadableByteStreamControllerHandleQueueDrain(controller) { - if (controller._queueTotalSize === 0 && controller._closeRequested) { - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(controller._controlledReadableByteStream); - } - else { - ReadableByteStreamControllerCallPullIfNeeded(controller); - } -} -function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { - if (controller._byobRequest === null) { - return; - } - controller._byobRequest._associatedReadableByteStreamController = undefined; - controller._byobRequest._view = null; - controller._byobRequest = null; -} -function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { - while (controller._pendingPullIntos.length > 0) { - if (controller._queueTotalSize === 0) { - return; - } - const pullIntoDescriptor = controller._pendingPullIntos.peek(); - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { - const stream = controller._controlledReadableByteStream; - let elementSize = 1; - if (view.constructor !== DataView) { - elementSize = view.constructor.BYTES_PER_ELEMENT; - } - const ctor = view.constructor; - const buffer = TransferArrayBuffer(view.buffer); - const pullIntoDescriptor = { - buffer, - byteOffset: view.byteOffset, - byteLength: view.byteLength, - bytesFilled: 0, - elementSize, - viewConstructor: ctor, - readerType: 'byob' - }; - if (controller._pendingPullIntos.length > 0) { - controller._pendingPullIntos.push(pullIntoDescriptor); - // No ReadableByteStreamControllerCallPullIfNeeded() call since: - // - No change happens on desiredSize - // - The source has already been notified of that there's at least 1 pending read(view) - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - return; - } - if (stream._state === 'closed') { - const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); - readIntoRequest._closeSteps(emptyView); - return; - } - if (controller._queueTotalSize > 0) { - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - ReadableByteStreamControllerHandleQueueDrain(controller); - readIntoRequest._chunkSteps(filledView); - return; - } - if (controller._closeRequested) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - readIntoRequest._errorSteps(e); - return; - } - } - controller._pendingPullIntos.push(pullIntoDescriptor); - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { - firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); - const stream = controller._controlledReadableByteStream; - if (ReadableStreamHasBYOBReader(stream)) { - while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { - const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { - if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { - throw new RangeError('bytesWritten out of range'); - } - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); - if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { - // TODO: Figure out whether we should detach the buffer or not here. - return; - } - ReadableByteStreamControllerShiftPendingPullInto(controller); - const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; - if (remainderSize > 0) { - const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); - ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); - } - pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); - pullIntoDescriptor.bytesFilled -= remainderSize; - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); -} -function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { - const firstDescriptor = controller._pendingPullIntos.peek(); - const state = controller._controlledReadableByteStream._state; - if (state === 'closed') { - if (bytesWritten !== 0) { - throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); - } - ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); - } - else { - ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerShiftPendingPullInto(controller) { - const descriptor = controller._pendingPullIntos.shift(); - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - return descriptor; -} -function ReadableByteStreamControllerShouldCallPull(controller) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return false; - } - if (controller._closeRequested) { - return false; - } - if (!controller._started) { - return false; - } - if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; - } - return false; -} -function ReadableByteStreamControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; -} -// A client of ReadableByteStreamController may use these functions directly to bypass state check. -function ReadableByteStreamControllerClose(controller) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; - } - if (controller._queueTotalSize > 0) { - controller._closeRequested = true; - return; - } - if (controller._pendingPullIntos.length > 0) { - const firstPendingPullInto = controller._pendingPullIntos.peek(); - if (firstPendingPullInto.bytesFilled > 0) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - throw e; - } - } - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(stream); -} -function ReadableByteStreamControllerEnqueue(controller, chunk) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; - } - const buffer = chunk.buffer; - const byteOffset = chunk.byteOffset; - const byteLength = chunk.byteLength; - const transferredBuffer = TransferArrayBuffer(buffer); - if (ReadableStreamHasDefaultReader(stream)) { - if (ReadableStreamGetNumReadRequests(stream) === 0) { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - else { - const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); - ReadableStreamFulfillReadRequest(stream, transferredView, false); - } - } - else if (ReadableStreamHasBYOBReader(stream)) { - // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); - } - else { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerError(controller, e) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return; - } - ReadableByteStreamControllerClearPendingPullIntos(controller); - ResetQueue(controller); - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableByteStreamControllerGetDesiredSize(controller) { - const state = controller._controlledReadableByteStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -function ReadableByteStreamControllerRespond(controller, bytesWritten) { - bytesWritten = Number(bytesWritten); - if (!IsFiniteNonNegativeNumber(bytesWritten)) { - throw new RangeError('bytesWritten must be a finite'); - } - ReadableByteStreamControllerRespondInternal(controller, bytesWritten); -} -function ReadableByteStreamControllerRespondWithNewView(controller, view) { - const firstDescriptor = controller._pendingPullIntos.peek(); - if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { - throw new RangeError('The region specified by view does not match byobRequest'); - } - if (firstDescriptor.byteLength !== view.byteLength) { - throw new RangeError('The buffer of view has different capacity than byobRequest'); - } - firstDescriptor.buffer = view.buffer; - ReadableByteStreamControllerRespondInternal(controller, view.byteLength); -} -function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { - controller._controlledReadableByteStream = stream; - controller._pullAgain = false; - controller._pulling = false; - controller._byobRequest = null; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._closeRequested = false; - controller._started = false; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - controller._autoAllocateChunkSize = autoAllocateChunkSize; - controller._pendingPullIntos = new SimpleQueue(); - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableByteStreamControllerCallPullIfNeeded(controller); - }, r => { - ReadableByteStreamControllerError(controller, r); - }); -} -function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { - const controller = Object.create(ReadableByteStreamController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingByteSource.start !== undefined) { - startAlgorithm = () => underlyingByteSource.start(controller); - } - if (underlyingByteSource.pull !== undefined) { - pullAlgorithm = () => underlyingByteSource.pull(controller); - } - if (underlyingByteSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingByteSource.cancel(reason); - } - const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; - if (autoAllocateChunkSize === 0) { - throw new TypeError('autoAllocateChunkSize must be greater than 0'); - } - SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); -} -function SetUpReadableStreamBYOBRequest(request, controller, view) { - request._associatedReadableByteStreamController = controller; - request._view = view; -} -// Helper functions for the ReadableStreamBYOBRequest. -function byobRequestBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); -} -// Helper functions for the ReadableByteStreamController. -function byteStreamControllerBrandCheckException(name) { - return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); -} - -// Abstract operations for the ReadableStream. -function AcquireReadableStreamBYOBReader(stream) { - return new ReadableStreamBYOBReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { - stream._reader._readIntoRequests.push(readIntoRequest); -} -function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { - const reader = stream._reader; - const readIntoRequest = reader._readIntoRequests.shift(); - if (done) { - readIntoRequest._closeSteps(chunk); - } - else { - readIntoRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadIntoRequests(stream) { - return stream._reader._readIntoRequests.length; -} -function ReadableStreamHasBYOBReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamBYOBReader(reader)) { - return false; - } - return true; -} -/** - * A BYOB reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamBYOBReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - if (!IsReadableByteStreamController(stream._readableStreamController)) { - throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + - 'source'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readIntoRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } - /** - * Attempts to reads bytes into view, and returns a promise resolved with the result. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read(view) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('read')); - } - if (!ArrayBuffer.isView(view)) { - return promiseRejectedWith(new TypeError('view must be an array buffer view')); - } - if (view.byteLength === 0) { - return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); - } - if (view.buffer.byteLength === 0) { - return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readIntoRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamBYOBReaderRead(this, view, readIntoRequest); - return promise; - } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamBYOBReader(this)) { - throw byobReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readIntoRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamBYOBReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamBYOBReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { - return false; - } - return true; -} -function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'errored') { - readIntoRequest._errorSteps(stream._storedError); - } - else { - ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); - } -} -// Helper functions for the ReadableStreamBYOBReader. -function byobReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); -} - -function ExtractHighWaterMark(strategy, defaultHWM) { - const { highWaterMark } = strategy; - if (highWaterMark === undefined) { - return defaultHWM; - } - if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { - throw new RangeError('Invalid highWaterMark'); - } - return highWaterMark; -} -function ExtractSizeAlgorithm(strategy) { - const { size } = strategy; - if (!size) { - return () => 1; - } - return size; -} - -function convertQueuingStrategy(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - const size = init === null || init === void 0 ? void 0 : init.size; - return { - highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), - size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) - }; -} -function convertQueuingStrategySize(fn, context) { - assertFunction(fn, context); - return chunk => convertUnrestrictedDouble(fn(chunk)); -} - -function convertUnderlyingSink(original, context) { - assertDictionary(original, context); - const abort = original === null || original === void 0 ? void 0 : original.abort; - const close = original === null || original === void 0 ? void 0 : original.close; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - const write = original === null || original === void 0 ? void 0 : original.write; - return { - abort: abort === undefined ? - undefined : - convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), - close: close === undefined ? - undefined : - convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), - start: start === undefined ? - undefined : - convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), - write: write === undefined ? - undefined : - convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), - type - }; -} -function convertUnderlyingSinkAbortCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSinkCloseCallback(fn, original, context) { - assertFunction(fn, context); - return () => promiseCall(fn, original, []); -} -function convertUnderlyingSinkStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertUnderlyingSinkWriteCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} - -function assertWritableStream(x, context) { - if (!IsWritableStream(x)) { - throw new TypeError(`${context} is not a WritableStream.`); - } -} - -/** - * A writable stream represents a destination for data, into which you can write. - * - * @public - */ -class WritableStream { - constructor(rawUnderlyingSink = {}, rawStrategy = {}) { - if (rawUnderlyingSink === undefined) { - rawUnderlyingSink = null; - } - else { - assertObject(rawUnderlyingSink, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); - InitializeWritableStream(this); - const type = underlyingSink.type; - if (type !== undefined) { - throw new RangeError('Invalid type is specified'); - } - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); - } - /** - * Returns whether or not the writable stream is locked to a writer. - */ - get locked() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('locked'); - } - return IsWritableStreamLocked(this); - } - /** - * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be - * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort - * mechanism of the underlying sink. - * - * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled - * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel - * the stream) if the stream is currently locked. - */ - abort(reason = undefined) { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('abort')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); - } - return WritableStreamAbort(this, reason); - } - /** - * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its - * close behavior. During this time any further attempts to write will fail (without erroring the stream). - * - * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream - * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with - * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. - */ - close() { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('close')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); - } - if (WritableStreamCloseQueuedOrInFlight(this)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamClose(this); - } - /** - * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream - * is locked, no other writer can be acquired until this one is released. - * - * This functionality is especially useful for creating abstractions that desire the ability to write to a stream - * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at - * the same time, which would cause the resulting written data to be unpredictable and probably useless. - */ - getWriter() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('getWriter'); - } - return AcquireWritableStreamDefaultWriter(this); - } -} -Object.defineProperties(WritableStream.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - getWriter: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStream', - configurable: true - }); -} -// Abstract operations for the WritableStream. -function AcquireWritableStreamDefaultWriter(stream) { - return new WritableStreamDefaultWriter(stream); -} -// Throws if and only if startAlgorithm throws. -function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(WritableStream.prototype); - InitializeWritableStream(stream); - const controller = Object.create(WritableStreamDefaultController.prototype); - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeWritableStream(stream) { - stream._state = 'writable'; - // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is - // 'erroring' or 'errored'. May be set to an undefined value. - stream._storedError = undefined; - stream._writer = undefined; - // Initialize to undefined first because the constructor of the controller checks this - // variable to validate the caller. - stream._writableStreamController = undefined; - // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data - // producer without waiting for the queued writes to finish. - stream._writeRequests = new SimpleQueue(); - // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents - // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. - stream._inFlightWriteRequest = undefined; - // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer - // has been detached. - stream._closeRequest = undefined; - // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it - // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. - stream._inFlightCloseRequest = undefined; - // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. - stream._pendingAbortRequest = undefined; - // The backpressure signal set by the controller. - stream._backpressure = false; -} -function IsWritableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { - return false; - } - return true; -} -function IsWritableStreamLocked(stream) { - if (stream._writer === undefined) { - return false; - } - return true; -} -function WritableStreamAbort(stream, reason) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseResolvedWith(undefined); - } - if (stream._pendingAbortRequest !== undefined) { - return stream._pendingAbortRequest._promise; - } - let wasAlreadyErroring = false; - if (state === 'erroring') { - wasAlreadyErroring = true; - // reason will not be used, so don't keep a reference to it. - reason = undefined; - } - const promise = newPromise((resolve, reject) => { - stream._pendingAbortRequest = { - _promise: undefined, - _resolve: resolve, - _reject: reject, - _reason: reason, - _wasAlreadyErroring: wasAlreadyErroring - }; - }); - stream._pendingAbortRequest._promise = promise; - if (!wasAlreadyErroring) { - WritableStreamStartErroring(stream, reason); - } - return promise; -} -function WritableStreamClose(stream) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); - } - const promise = newPromise((resolve, reject) => { - const closeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._closeRequest = closeRequest; - }); - const writer = stream._writer; - if (writer !== undefined && stream._backpressure && state === 'writable') { - defaultWriterReadyPromiseResolve(writer); - } - WritableStreamDefaultControllerClose(stream._writableStreamController); - return promise; -} -// WritableStream API exposed for controllers. -function WritableStreamAddWriteRequest(stream) { - const promise = newPromise((resolve, reject) => { - const writeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._writeRequests.push(writeRequest); - }); - return promise; -} -function WritableStreamDealWithRejection(stream, error) { - const state = stream._state; - if (state === 'writable') { - WritableStreamStartErroring(stream, error); - return; - } - WritableStreamFinishErroring(stream); -} -function WritableStreamStartErroring(stream, reason) { - const controller = stream._writableStreamController; - stream._state = 'erroring'; - stream._storedError = reason; - const writer = stream._writer; - if (writer !== undefined) { - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); - } - if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { - WritableStreamFinishErroring(stream); - } -} -function WritableStreamFinishErroring(stream) { - stream._state = 'errored'; - stream._writableStreamController[ErrorSteps](); - const storedError = stream._storedError; - stream._writeRequests.forEach(writeRequest => { - writeRequest._reject(storedError); - }); - stream._writeRequests = new SimpleQueue(); - if (stream._pendingAbortRequest === undefined) { - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const abortRequest = stream._pendingAbortRequest; - stream._pendingAbortRequest = undefined; - if (abortRequest._wasAlreadyErroring) { - abortRequest._reject(storedError); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); - uponPromise(promise, () => { - abortRequest._resolve(); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }, (reason) => { - abortRequest._reject(reason); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }); -} -function WritableStreamFinishInFlightWrite(stream) { - stream._inFlightWriteRequest._resolve(undefined); - stream._inFlightWriteRequest = undefined; -} -function WritableStreamFinishInFlightWriteWithError(stream, error) { - stream._inFlightWriteRequest._reject(error); - stream._inFlightWriteRequest = undefined; - WritableStreamDealWithRejection(stream, error); -} -function WritableStreamFinishInFlightClose(stream) { - stream._inFlightCloseRequest._resolve(undefined); - stream._inFlightCloseRequest = undefined; - const state = stream._state; - if (state === 'erroring') { - // The error was too late to do anything, so it is ignored. - stream._storedError = undefined; - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._resolve(); - stream._pendingAbortRequest = undefined; - } - } - stream._state = 'closed'; - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseResolve(writer); - } -} -function WritableStreamFinishInFlightCloseWithError(stream, error) { - stream._inFlightCloseRequest._reject(error); - stream._inFlightCloseRequest = undefined; - // Never execute sink abort() after sink close(). - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._reject(error); - stream._pendingAbortRequest = undefined; - } - WritableStreamDealWithRejection(stream, error); -} -// TODO(ricea): Fix alphabetical order. -function WritableStreamCloseQueuedOrInFlight(stream) { - if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamHasOperationMarkedInFlight(stream) { - if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamMarkCloseRequestInFlight(stream) { - stream._inFlightCloseRequest = stream._closeRequest; - stream._closeRequest = undefined; -} -function WritableStreamMarkFirstWriteRequestInFlight(stream) { - stream._inFlightWriteRequest = stream._writeRequests.shift(); -} -function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { - if (stream._closeRequest !== undefined) { - stream._closeRequest._reject(stream._storedError); - stream._closeRequest = undefined; - } - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseReject(writer, stream._storedError); - } -} -function WritableStreamUpdateBackpressure(stream, backpressure) { - const writer = stream._writer; - if (writer !== undefined && backpressure !== stream._backpressure) { - if (backpressure) { - defaultWriterReadyPromiseReset(writer); - } - else { - defaultWriterReadyPromiseResolve(writer); - } - } - stream._backpressure = backpressure; -} -/** - * A default writer vended by a {@link WritableStream}. - * - * @public - */ -class WritableStreamDefaultWriter { - constructor(stream) { - assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); - assertWritableStream(stream, 'First parameter'); - if (IsWritableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive writing by another writer'); - } - this._ownerWritableStream = stream; - stream._writer = this; - const state = stream._state; - if (state === 'writable') { - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { - defaultWriterReadyPromiseInitialize(this); - } - else { - defaultWriterReadyPromiseInitializeAsResolved(this); - } - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'erroring') { - defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'closed') { - defaultWriterReadyPromiseInitializeAsResolved(this); - defaultWriterClosedPromiseInitializeAsResolved(this); - } - else { - const storedError = stream._storedError; - defaultWriterReadyPromiseInitializeAsRejected(this, storedError); - defaultWriterClosedPromiseInitializeAsRejected(this, storedError); - } - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the writer’s lock is released before the stream finishes closing. - */ - get closed() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. - * A producer can use this information to determine the right amount of data to write. - * - * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort - * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when - * the writer’s lock is released. - */ - get desiredSize() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('desiredSize'); - } - if (this._ownerWritableStream === undefined) { - throw defaultWriterLockException('desiredSize'); - } - return WritableStreamDefaultWriterGetDesiredSize(this); - } - /** - * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions - * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips - * back to zero or below, the getter will return a new promise that stays pending until the next transition. - * - * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become - * rejected. - */ - get ready() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('ready')); - } - return this._readyPromise; - } - /** - * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. - */ - abort(reason = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('abort')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('abort')); - } - return WritableStreamDefaultWriterAbort(this, reason); - } - /** - * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. - */ - close() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('close')); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return promiseRejectedWith(defaultWriterLockException('close')); - } - if (WritableStreamCloseQueuedOrInFlight(stream)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamDefaultWriterClose(this); - } - /** - * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. - * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from - * now on; otherwise, the writer will appear closed. - * - * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the - * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). - * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents - * other producers from writing in an interleaved manner. - */ - releaseLock() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('releaseLock'); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return; - } - WritableStreamDefaultWriterRelease(this); - } - write(chunk = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('write')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - return WritableStreamDefaultWriterWrite(this, chunk); - } -} -Object.defineProperties(WritableStreamDefaultWriter.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - releaseLock: { enumerable: true }, - write: { enumerable: true }, - closed: { enumerable: true }, - desiredSize: { enumerable: true }, - ready: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultWriter', - configurable: true - }); -} -// Abstract operations for the WritableStreamDefaultWriter. -function IsWritableStreamDefaultWriter(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { - return false; - } - return true; -} -// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. -function WritableStreamDefaultWriterAbort(writer, reason) { - const stream = writer._ownerWritableStream; - return WritableStreamAbort(stream, reason); -} -function WritableStreamDefaultWriterClose(writer) { - const stream = writer._ownerWritableStream; - return WritableStreamClose(stream); -} -function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseResolvedWith(undefined); - } - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - return WritableStreamDefaultWriterClose(writer); -} -function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { - if (writer._closedPromiseState === 'pending') { - defaultWriterClosedPromiseReject(writer, error); - } - else { - defaultWriterClosedPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { - if (writer._readyPromiseState === 'pending') { - defaultWriterReadyPromiseReject(writer, error); - } - else { - defaultWriterReadyPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterGetDesiredSize(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (state === 'errored' || state === 'erroring') { - return null; - } - if (state === 'closed') { - return 0; - } - return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); -} -function WritableStreamDefaultWriterRelease(writer) { - const stream = writer._ownerWritableStream; - const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); - // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not - // rejected until afterwards. This means that simply testing state will not work. - WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); - stream._writer = undefined; - writer._ownerWritableStream = undefined; -} -function WritableStreamDefaultWriterWrite(writer, chunk) { - const stream = writer._ownerWritableStream; - const controller = stream._writableStreamController; - const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); - if (stream !== writer._ownerWritableStream) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - const state = stream._state; - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); - } - if (state === 'erroring') { - return promiseRejectedWith(stream._storedError); - } - const promise = WritableStreamAddWriteRequest(stream); - WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); - return promise; -} -const closeSentinel = {}; -/** - * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. - * - * @public - */ -class WritableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. - * - * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying - * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the - * normal lifecycle of interactions with the underlying sink. - */ - error(e = undefined) { - if (!IsWritableStreamDefaultController(this)) { - throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); - } - const state = this._controlledWritableStream._state; - if (state !== 'writable') { - // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so - // just treat it as a no-op. - return; - } - WritableStreamDefaultControllerError(this, e); - } - /** @internal */ - [AbortSteps](reason) { - const result = this._abortAlgorithm(reason); - WritableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [ErrorSteps]() { - ResetQueue(this); - } -} -Object.defineProperties(WritableStreamDefaultController.prototype, { - error: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultController', - configurable: true - }); -} -// Abstract operations implementing interface required by the WritableStream. -function IsWritableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { - return false; - } - return true; -} -function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledWritableStream = stream; - stream._writableStreamController = controller; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._writeAlgorithm = writeAlgorithm; - controller._closeAlgorithm = closeAlgorithm; - controller._abortAlgorithm = abortAlgorithm; - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - const startResult = startAlgorithm(); - const startPromise = promiseResolvedWith(startResult); - uponPromise(startPromise, () => { - controller._started = true; - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, r => { - controller._started = true; - WritableStreamDealWithRejection(stream, r); - }); -} -function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { - const controller = Object.create(WritableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let writeAlgorithm = () => promiseResolvedWith(undefined); - let closeAlgorithm = () => promiseResolvedWith(undefined); - let abortAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSink.start !== undefined) { - startAlgorithm = () => underlyingSink.start(controller); - } - if (underlyingSink.write !== undefined) { - writeAlgorithm = chunk => underlyingSink.write(chunk, controller); - } - if (underlyingSink.close !== undefined) { - closeAlgorithm = () => underlyingSink.close(); - } - if (underlyingSink.abort !== undefined) { - abortAlgorithm = reason => underlyingSink.abort(reason); - } - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); -} -// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. -function WritableStreamDefaultControllerClearAlgorithms(controller) { - controller._writeAlgorithm = undefined; - controller._closeAlgorithm = undefined; - controller._abortAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -function WritableStreamDefaultControllerClose(controller) { - EnqueueValueWithSize(controller, closeSentinel, 0); - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { - try { - return controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); - return 1; - } -} -function WritableStreamDefaultControllerGetDesiredSize(controller) { - return controller._strategyHWM - controller._queueTotalSize; -} -function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); - return; - } - const stream = controller._controlledWritableStream; - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -// Abstract operations for the WritableStreamDefaultController. -function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { - const stream = controller._controlledWritableStream; - if (!controller._started) { - return; - } - if (stream._inFlightWriteRequest !== undefined) { - return; - } - const state = stream._state; - if (state === 'erroring') { - WritableStreamFinishErroring(stream); - return; - } - if (controller._queue.length === 0) { - return; - } - const value = PeekQueueValue(controller); - if (value === closeSentinel) { - WritableStreamDefaultControllerProcessClose(controller); - } - else { - WritableStreamDefaultControllerProcessWrite(controller, value); - } -} -function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { - if (controller._controlledWritableStream._state === 'writable') { - WritableStreamDefaultControllerError(controller, error); - } -} -function WritableStreamDefaultControllerProcessClose(controller) { - const stream = controller._controlledWritableStream; - WritableStreamMarkCloseRequestInFlight(stream); - DequeueValue(controller); - const sinkClosePromise = controller._closeAlgorithm(); - WritableStreamDefaultControllerClearAlgorithms(controller); - uponPromise(sinkClosePromise, () => { - WritableStreamFinishInFlightClose(stream); - }, reason => { - WritableStreamFinishInFlightCloseWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerProcessWrite(controller, chunk) { - const stream = controller._controlledWritableStream; - WritableStreamMarkFirstWriteRequestInFlight(stream); - const sinkWritePromise = controller._writeAlgorithm(chunk); - uponPromise(sinkWritePromise, () => { - WritableStreamFinishInFlightWrite(stream); - const state = stream._state; - DequeueValue(controller); - if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, reason => { - if (stream._state === 'writable') { - WritableStreamDefaultControllerClearAlgorithms(controller); - } - WritableStreamFinishInFlightWriteWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerGetBackpressure(controller) { - const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); - return desiredSize <= 0; -} -// A client of WritableStreamDefaultController may use these functions directly to bypass state check. -function WritableStreamDefaultControllerError(controller, error) { - const stream = controller._controlledWritableStream; - WritableStreamDefaultControllerClearAlgorithms(controller); - WritableStreamStartErroring(stream, error); -} -// Helper functions for the WritableStream. -function streamBrandCheckException$2(name) { - return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); -} -// Helper functions for the WritableStreamDefaultWriter. -function defaultWriterBrandCheckException(name) { - return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); -} -function defaultWriterLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released writer'); -} -function defaultWriterClosedPromiseInitialize(writer) { - writer._closedPromise = newPromise((resolve, reject) => { - writer._closedPromise_resolve = resolve; - writer._closedPromise_reject = reject; - writer._closedPromiseState = 'pending'; - }); -} -function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseReject(writer, reason); -} -function defaultWriterClosedPromiseInitializeAsResolved(writer) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseResolve(writer); -} -function defaultWriterClosedPromiseReject(writer, reason) { - if (writer._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._closedPromise); - writer._closedPromise_reject(reason); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'rejected'; -} -function defaultWriterClosedPromiseResetToRejected(writer, reason) { - defaultWriterClosedPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterClosedPromiseResolve(writer) { - if (writer._closedPromise_resolve === undefined) { - return; - } - writer._closedPromise_resolve(undefined); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'resolved'; -} -function defaultWriterReadyPromiseInitialize(writer) { - writer._readyPromise = newPromise((resolve, reject) => { - writer._readyPromise_resolve = resolve; - writer._readyPromise_reject = reject; - }); - writer._readyPromiseState = 'pending'; -} -function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseReject(writer, reason); -} -function defaultWriterReadyPromiseInitializeAsResolved(writer) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseResolve(writer); -} -function defaultWriterReadyPromiseReject(writer, reason) { - if (writer._readyPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._readyPromise); - writer._readyPromise_reject(reason); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'rejected'; -} -function defaultWriterReadyPromiseReset(writer) { - defaultWriterReadyPromiseInitialize(writer); -} -function defaultWriterReadyPromiseResetToRejected(writer, reason) { - defaultWriterReadyPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterReadyPromiseResolve(writer) { - if (writer._readyPromise_resolve === undefined) { - return; - } - writer._readyPromise_resolve(undefined); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'fulfilled'; -} - -function isAbortSignal(value) { - if (typeof value !== 'object' || value === null) { - return false; - } - try { - return typeof value.aborted === 'boolean'; - } - catch (_a) { - // AbortSignal.prototype.aborted throws if its brand check fails - return false; - } -} - -/// -const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; - -/// -function isDOMExceptionConstructor(ctor) { - if (!(typeof ctor === 'function' || typeof ctor === 'object')) { - return false; - } - try { - new ctor(); - return true; - } - catch (_a) { - return false; - } -} -function createDOMExceptionPolyfill() { - // eslint-disable-next-line no-shadow - const ctor = function DOMException(message, name) { - this.message = message || ''; - this.name = name || 'Error'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - }; - ctor.prototype = Object.create(Error.prototype); - Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); - return ctor; -} -// eslint-disable-next-line no-redeclare -const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); - -function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { - const reader = AcquireReadableStreamDefaultReader(source); - const writer = AcquireWritableStreamDefaultWriter(dest); - source._disturbed = true; - let shuttingDown = false; - // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. - let currentWrite = promiseResolvedWith(undefined); - return newPromise((resolve, reject) => { - let abortAlgorithm; - if (signal !== undefined) { - abortAlgorithm = () => { - const error = new DOMException$1('Aborted', 'AbortError'); - const actions = []; - if (!preventAbort) { - actions.push(() => { - if (dest._state === 'writable') { - return WritableStreamAbort(dest, error); - } - return promiseResolvedWith(undefined); - }); - } - if (!preventCancel) { - actions.push(() => { - if (source._state === 'readable') { - return ReadableStreamCancel(source, error); - } - return promiseResolvedWith(undefined); - }); - } - shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); - }; - if (signal.aborted) { - abortAlgorithm(); - return; - } - signal.addEventListener('abort', abortAlgorithm); - } - // Using reader and writer, read all chunks from this and write them to dest - // - Backpressure must be enforced - // - Shutdown must stop all activity - function pipeLoop() { - return newPromise((resolveLoop, rejectLoop) => { - function next(done) { - if (done) { - resolveLoop(); - } - else { - // Use `PerformPromiseThen` instead of `uponPromise` to avoid - // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers - PerformPromiseThen(pipeStep(), next, rejectLoop); - } - } - next(false); - }); - } - function pipeStep() { - if (shuttingDown) { - return promiseResolvedWith(true); - } - return PerformPromiseThen(writer._readyPromise, () => { - return newPromise((resolveRead, rejectRead) => { - ReadableStreamDefaultReaderRead(reader, { - _chunkSteps: chunk => { - currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); - resolveRead(false); - }, - _closeSteps: () => resolveRead(true), - _errorSteps: rejectRead - }); - }); - }); - } - // Errors must be propagated forward - isOrBecomesErrored(source, reader._closedPromise, storedError => { - if (!preventAbort) { - shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Errors must be propagated backward - isOrBecomesErrored(dest, writer._closedPromise, storedError => { - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Closing must be propagated forward - isOrBecomesClosed(source, reader._closedPromise, () => { - if (!preventClose) { - shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); - } - else { - shutdown(); - } - }); - // Closing must be propagated backward - if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { - const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); - } - else { - shutdown(true, destClosed); - } - } - setPromiseIsHandledToTrue(pipeLoop()); - function waitForWritesToFinish() { - // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait - // for that too. - const oldCurrentWrite = currentWrite; - return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); - } - function isOrBecomesErrored(stream, promise, action) { - if (stream._state === 'errored') { - action(stream._storedError); - } - else { - uponRejection(promise, action); - } - } - function isOrBecomesClosed(stream, promise, action) { - if (stream._state === 'closed') { - action(); - } - else { - uponFulfillment(promise, action); - } - } - function shutdownWithAction(action, originalIsError, originalError) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), doTheRest); - } - else { - doTheRest(); - } - function doTheRest() { - uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); - } - } - function shutdown(isError, error) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); - } - else { - finalize(isError, error); - } - } - function finalize(isError, error) { - WritableStreamDefaultWriterRelease(writer); - ReadableStreamReaderGenericRelease(reader); - if (signal !== undefined) { - signal.removeEventListener('abort', abortAlgorithm); - } - if (isError) { - reject(error); - } - else { - resolve(undefined); - } - } - }); -} - -/** - * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. - * - * @public - */ -class ReadableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('desiredSize'); - } - return ReadableStreamDefaultControllerGetDesiredSize(this); - } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('close'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits close'); - } - ReadableStreamDefaultControllerClose(this); - } - enqueue(chunk = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('enqueue'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits enqueue'); - } - return ReadableStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('error'); - } - ReadableStreamDefaultControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableStream; - if (this._queue.length > 0) { - const chunk = DequeueValue(this); - if (this._closeRequested && this._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(this); - ReadableStreamClose(stream); - } - else { - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - readRequest._chunkSteps(chunk); - } - else { - ReadableStreamAddReadRequest(stream, readRequest); - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - } -} -Object.defineProperties(ReadableStreamDefaultController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultController', - configurable: true - }); -} -// Abstract operations for the ReadableStreamDefaultController. -function IsReadableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { - return false; - } - return true; -} -function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableStreamDefaultControllerError(controller, e); - }); -} -function ReadableStreamDefaultControllerShouldCallPull(controller) { - const stream = controller._controlledReadableStream; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return false; - } - if (!controller._started) { - return false; - } - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; - } - return false; -} -function ReadableStreamDefaultControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. -function ReadableStreamDefaultControllerClose(controller) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; - } - const stream = controller._controlledReadableStream; - controller._closeRequested = true; - if (controller._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamClose(stream); - } -} -function ReadableStreamDefaultControllerEnqueue(controller, chunk) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; - } - const stream = controller._controlledReadableStream; - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - ReadableStreamFulfillReadRequest(stream, chunk, false); - } - else { - let chunkSize; - try { - chunkSize = controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - ReadableStreamDefaultControllerError(controller, chunkSizeE); - throw chunkSizeE; - } - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - ReadableStreamDefaultControllerError(controller, enqueueE); - throw enqueueE; - } - } - ReadableStreamDefaultControllerCallPullIfNeeded(controller); -} -function ReadableStreamDefaultControllerError(controller, e) { - const stream = controller._controlledReadableStream; - if (stream._state !== 'readable') { - return; - } - ResetQueue(controller); - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableStreamDefaultControllerGetDesiredSize(controller) { - const state = controller._controlledReadableStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -// This is used in the implementation of TransformStream. -function ReadableStreamDefaultControllerHasBackpressure(controller) { - if (ReadableStreamDefaultControllerShouldCallPull(controller)) { - return false; - } - return true; -} -function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { - const state = controller._controlledReadableStream._state; - if (!controller._closeRequested && state === 'readable') { - return true; - } - return false; -} -function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledReadableStream = stream; - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._closeRequested = false; - controller._pullAgain = false; - controller._pulling = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - }, r => { - ReadableStreamDefaultControllerError(controller, r); - }); -} -function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { - const controller = Object.create(ReadableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSource.start !== undefined) { - startAlgorithm = () => underlyingSource.start(controller); - } - if (underlyingSource.pull !== undefined) { - pullAlgorithm = () => underlyingSource.pull(controller); - } - if (underlyingSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingSource.cancel(reason); - } - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); -} -// Helper functions for the ReadableStreamDefaultController. -function defaultControllerBrandCheckException$1(name) { - return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); -} - -function ReadableStreamTee(stream, cloneForBranch2) { - const reader = AcquireReadableStreamDefaultReader(stream); - let reading = false; - let canceled1 = false; - let canceled2 = false; - let reason1; - let reason2; - let branch1; - let branch2; - let resolveCancelPromise; - const cancelPromise = newPromise(resolve => { - resolveCancelPromise = resolve; - }); - function pullAlgorithm() { - if (reading) { - return promiseResolvedWith(undefined); - } - reading = true; - const readRequest = { - _chunkSteps: value => { - // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using - // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let - // successful synchronously-available reads get ahead of asynchronously-available errors. - queueMicrotask(() => { - reading = false; - const value1 = value; - const value2 = value; - // There is no way to access the cloning code right now in the reference implementation. - // If we add one then we'll need an implementation for serializable objects. - // if (!canceled2 && cloneForBranch2) { - // value2 = StructuredDeserialize(StructuredSerialize(value2)); - // } - if (!canceled1) { - ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1); - } - if (!canceled2) { - ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2); - } - }); - }, - _closeSteps: () => { - reading = false; - if (!canceled1) { - ReadableStreamDefaultControllerClose(branch1._readableStreamController); - } - if (!canceled2) { - ReadableStreamDefaultControllerClose(branch2._readableStreamController); - } - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }, - _errorSteps: () => { - reading = false; - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promiseResolvedWith(undefined); - } - function cancel1Algorithm(reason) { - canceled1 = true; - reason1 = reason; - if (canceled2) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function cancel2Algorithm(reason) { - canceled2 = true; - reason2 = reason; - if (canceled1) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function startAlgorithm() { - // do nothing - } - branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); - branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); - uponRejection(reader._closedPromise, (r) => { - ReadableStreamDefaultControllerError(branch1._readableStreamController, r); - ReadableStreamDefaultControllerError(branch2._readableStreamController, r); - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }); - return [branch1, branch2]; -} - -function convertUnderlyingDefaultOrByteSource(source, context) { - assertDictionary(source, context); - const original = source; - const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; - const cancel = original === null || original === void 0 ? void 0 : original.cancel; - const pull = original === null || original === void 0 ? void 0 : original.pull; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - return { - autoAllocateChunkSize: autoAllocateChunkSize === undefined ? - undefined : - convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), - cancel: cancel === undefined ? - undefined : - convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), - pull: pull === undefined ? - undefined : - convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), - start: start === undefined ? - undefined : - convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), - type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) - }; -} -function convertUnderlyingSourceCancelCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSourcePullCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertUnderlyingSourceStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertReadableStreamType(type, context) { - type = `${type}`; - if (type !== 'bytes') { - throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); - } - return type; -} - -function convertReaderOptions(options, context) { - assertDictionary(options, context); - const mode = options === null || options === void 0 ? void 0 : options.mode; - return { - mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) - }; -} -function convertReadableStreamReaderMode(mode, context) { - mode = `${mode}`; - if (mode !== 'byob') { - throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); - } - return mode; -} - -function convertIteratorOptions(options, context) { - assertDictionary(options, context); - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - return { preventCancel: Boolean(preventCancel) }; -} - -function convertPipeOptions(options, context) { - assertDictionary(options, context); - const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; - const signal = options === null || options === void 0 ? void 0 : options.signal; - if (signal !== undefined) { - assertAbortSignal(signal, `${context} has member 'signal' that`); - } - return { - preventAbort: Boolean(preventAbort), - preventCancel: Boolean(preventCancel), - preventClose: Boolean(preventClose), - signal - }; -} -function assertAbortSignal(signal, context) { - if (!isAbortSignal(signal)) { - throw new TypeError(`${context} is not an AbortSignal.`); - } -} - -function convertReadableWritablePair(pair, context) { - assertDictionary(pair, context); - const readable = pair === null || pair === void 0 ? void 0 : pair.readable; - assertRequiredField(readable, 'readable', 'ReadableWritablePair'); - assertReadableStream(readable, `${context} has member 'readable' that`); - const writable = pair === null || pair === void 0 ? void 0 : pair.writable; - assertRequiredField(writable, 'writable', 'ReadableWritablePair'); - assertWritableStream(writable, `${context} has member 'writable' that`); - return { readable, writable }; -} - -/** - * A readable stream represents a source of data, from which you can read. - * - * @public - */ -class ReadableStream { - constructor(rawUnderlyingSource = {}, rawStrategy = {}) { - if (rawUnderlyingSource === undefined) { - rawUnderlyingSource = null; - } - else { - assertObject(rawUnderlyingSource, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); - InitializeReadableStream(this); - if (underlyingSource.type === 'bytes') { - if (strategy.size !== undefined) { - throw new RangeError('The strategy for a byte stream cannot have a size function'); - } - const highWaterMark = ExtractHighWaterMark(strategy, 0); - SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); - } - else { - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); - } - } - /** - * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. - */ - get locked() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('locked'); - } - return IsReadableStreamLocked(this); - } - /** - * Cancels the stream, signaling a loss of interest in the stream by a consumer. - * - * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} - * method, which might or might not use it. - */ - cancel(reason = undefined) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('cancel')); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); - } - return ReadableStreamCancel(this, reason); - } - getReader(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('getReader'); - } - const options = convertReaderOptions(rawOptions, 'First parameter'); - if (options.mode === undefined) { - return AcquireReadableStreamDefaultReader(this); - } - return AcquireReadableStreamBYOBReader(this); - } - pipeThrough(rawTransform, rawOptions = {}) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('pipeThrough'); - } - assertRequiredArgument(rawTransform, 1, 'pipeThrough'); - const transform = convertReadableWritablePair(rawTransform, 'First parameter'); - const options = convertPipeOptions(rawOptions, 'Second parameter'); - if (IsReadableStreamLocked(this)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); - } - if (IsWritableStreamLocked(transform.writable)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); - } - const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - setPromiseIsHandledToTrue(promise); - return transform.readable; - } - pipeTo(destination, rawOptions = {}) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); - } - if (destination === undefined) { - return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); - } - if (!IsWritableStream(destination)) { - return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); - } - let options; - try { - options = convertPipeOptions(rawOptions, 'Second parameter'); - } - catch (e) { - return promiseRejectedWith(e); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); - } - if (IsWritableStreamLocked(destination)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); - } - return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - } - /** - * Tees this readable stream, returning a two-element array containing the two resulting branches as - * new {@link ReadableStream} instances. - * - * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. - * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be - * propagated to the stream's underlying source. - * - * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, - * this could allow interference between the two branches. - */ - tee() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('tee'); - } - const branches = ReadableStreamTee(this); - return CreateArrayFromList(branches); - } - values(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('values'); - } - const options = convertIteratorOptions(rawOptions, 'First parameter'); - return AcquireReadableStreamAsyncIterator(this, options.preventCancel); - } -} -Object.defineProperties(ReadableStream.prototype, { - cancel: { enumerable: true }, - getReader: { enumerable: true }, - pipeThrough: { enumerable: true }, - pipeTo: { enumerable: true }, - tee: { enumerable: true }, - values: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStream', - configurable: true - }); -} -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { - value: ReadableStream.prototype.values, - writable: true, - configurable: true - }); -} -// Abstract operations for the ReadableStream. -// Throws if and only if startAlgorithm throws. -function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(ReadableStream.prototype); - InitializeReadableStream(stream); - const controller = Object.create(ReadableStreamDefaultController.prototype); - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeReadableStream(stream) { - stream._state = 'readable'; - stream._reader = undefined; - stream._storedError = undefined; - stream._disturbed = false; -} -function IsReadableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { - return false; - } - return true; -} -function IsReadableStreamLocked(stream) { - if (stream._reader === undefined) { - return false; - } - return true; -} -// ReadableStream API exposed for controllers. -function ReadableStreamCancel(stream, reason) { - stream._disturbed = true; - if (stream._state === 'closed') { - return promiseResolvedWith(undefined); - } - if (stream._state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - ReadableStreamClose(stream); - const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); - return transformPromiseWith(sourceCancelPromise, noop); -} -function ReadableStreamClose(stream) { - stream._state = 'closed'; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseResolve(reader); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._closeSteps(); - }); - reader._readRequests = new SimpleQueue(); - } -} -function ReadableStreamError(stream, e) { - stream._state = 'errored'; - stream._storedError = e; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseReject(reader, e); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._errorSteps(e); - }); - reader._readRequests = new SimpleQueue(); - } - else { - reader._readIntoRequests.forEach(readIntoRequest => { - readIntoRequest._errorSteps(e); - }); - reader._readIntoRequests = new SimpleQueue(); - } -} -// Helper functions for the ReadableStream. -function streamBrandCheckException$1(name) { - return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); -} - -function convertQueuingStrategyInit(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); - return { - highWaterMark: convertUnrestrictedDouble(highWaterMark) - }; -} - -const byteLengthSizeFunction = function size(chunk) { - return chunk.byteLength; -}; -/** - * A queuing strategy that counts the number of bytes in each chunk. - * - * @public - */ -class ByteLengthQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('highWaterMark'); - } - return this._byteLengthQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by returning the value of its `byteLength` property. - */ - get size() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('size'); - } - return byteLengthSizeFunction; - } -} -Object.defineProperties(ByteLengthQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'ByteLengthQueuingStrategy', - configurable: true - }); -} -// Helper functions for the ByteLengthQueuingStrategy. -function byteLengthBrandCheckException(name) { - return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); -} -function IsByteLengthQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { - return false; - } - return true; -} - -const countSizeFunction = function size() { - return 1; -}; -/** - * A queuing strategy that counts the number of chunks. - * - * @public - */ -class CountQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'CountQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._countQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('highWaterMark'); - } - return this._countQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by always returning 1. - * This ensures that the total queue size is a count of the number of chunks in the queue. - */ - get size() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('size'); - } - return countSizeFunction; - } -} -Object.defineProperties(CountQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'CountQueuingStrategy', - configurable: true - }); -} -// Helper functions for the CountQueuingStrategy. -function countBrandCheckException(name) { - return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); -} -function IsCountQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { - return false; - } - return true; -} - -function convertTransformer(original, context) { - assertDictionary(original, context); - const flush = original === null || original === void 0 ? void 0 : original.flush; - const readableType = original === null || original === void 0 ? void 0 : original.readableType; - const start = original === null || original === void 0 ? void 0 : original.start; - const transform = original === null || original === void 0 ? void 0 : original.transform; - const writableType = original === null || original === void 0 ? void 0 : original.writableType; - return { - flush: flush === undefined ? - undefined : - convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), - readableType, - start: start === undefined ? - undefined : - convertTransformerStartCallback(start, original, `${context} has member 'start' that`), - transform: transform === undefined ? - undefined : - convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), - writableType - }; -} -function convertTransformerFlushCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertTransformerStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertTransformerTransformCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} - -// Class TransformStream -/** - * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, - * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. - * In a manner specific to the transform stream in question, writes to the writable side result in new data being - * made available for reading from the readable side. - * - * @public - */ -class TransformStream { - constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { - if (rawTransformer === undefined) { - rawTransformer = null; - } - const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); - const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); - const transformer = convertTransformer(rawTransformer, 'First parameter'); - if (transformer.readableType !== undefined) { - throw new RangeError('Invalid readableType specified'); - } - if (transformer.writableType !== undefined) { - throw new RangeError('Invalid writableType specified'); - } - const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); - const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); - const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); - const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); - let startPromise_resolve; - const startPromise = newPromise(resolve => { - startPromise_resolve = resolve; - }); - InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); - if (transformer.start !== undefined) { - startPromise_resolve(transformer.start(this._transformStreamController)); - } - else { - startPromise_resolve(undefined); - } - } - /** - * The readable side of the transform stream. - */ - get readable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('readable'); - } - return this._readable; - } - /** - * The writable side of the transform stream. - */ - get writable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('writable'); - } - return this._writable; - } -} -Object.defineProperties(TransformStream.prototype, { - readable: { enumerable: true }, - writable: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStream', - configurable: true - }); -} -function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { - function startAlgorithm() { - return startPromise; - } - function writeAlgorithm(chunk) { - return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); - } - function abortAlgorithm(reason) { - return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); - } - function closeAlgorithm() { - return TransformStreamDefaultSinkCloseAlgorithm(stream); - } - stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); - function pullAlgorithm() { - return TransformStreamDefaultSourcePullAlgorithm(stream); - } - function cancelAlgorithm(reason) { - TransformStreamErrorWritableAndUnblockWrite(stream, reason); - return promiseResolvedWith(undefined); - } - stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. - stream._backpressure = undefined; - stream._backpressureChangePromise = undefined; - stream._backpressureChangePromise_resolve = undefined; - TransformStreamSetBackpressure(stream, true); - stream._transformStreamController = undefined; -} -function IsTransformStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { - return false; - } - return true; -} -// This is a no-op if both sides are already errored. -function TransformStreamError(stream, e) { - ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); - TransformStreamErrorWritableAndUnblockWrite(stream, e); -} -function TransformStreamErrorWritableAndUnblockWrite(stream, e) { - TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); - WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); - if (stream._backpressure) { - // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() - // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time - // _backpressure is set. - TransformStreamSetBackpressure(stream, false); - } -} -function TransformStreamSetBackpressure(stream, backpressure) { - // Passes also when called during construction. - if (stream._backpressureChangePromise !== undefined) { - stream._backpressureChangePromise_resolve(); - } - stream._backpressureChangePromise = newPromise(resolve => { - stream._backpressureChangePromise_resolve = resolve; - }); - stream._backpressure = backpressure; -} -// Class TransformStreamDefaultController -/** - * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. - * - * @public - */ -class TransformStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. - */ - get desiredSize() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('desiredSize'); - } - const readableController = this._controlledTransformStream._readable._readableStreamController; - return ReadableStreamDefaultControllerGetDesiredSize(readableController); - } - enqueue(chunk = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('enqueue'); - } - TransformStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors both the readable side and the writable side of the controlled transform stream, making all future - * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. - */ - error(reason = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('error'); - } - TransformStreamDefaultControllerError(this, reason); - } - /** - * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the - * transformer only needs to consume a portion of the chunks written to the writable side. - */ - terminate() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('terminate'); - } - TransformStreamDefaultControllerTerminate(this); - } -} -Object.defineProperties(TransformStreamDefaultController.prototype, { - enqueue: { enumerable: true }, - error: { enumerable: true }, - terminate: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStreamDefaultController', - configurable: true - }); -} -// Transform Stream Default Controller Abstract Operations -function IsTransformStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { - return false; - } - return true; -} -function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { - controller._controlledTransformStream = stream; - stream._transformStreamController = controller; - controller._transformAlgorithm = transformAlgorithm; - controller._flushAlgorithm = flushAlgorithm; -} -function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { - const controller = Object.create(TransformStreamDefaultController.prototype); - let transformAlgorithm = (chunk) => { - try { - TransformStreamDefaultControllerEnqueue(controller, chunk); - return promiseResolvedWith(undefined); - } - catch (transformResultE) { - return promiseRejectedWith(transformResultE); - } - }; - let flushAlgorithm = () => promiseResolvedWith(undefined); - if (transformer.transform !== undefined) { - transformAlgorithm = chunk => transformer.transform(chunk, controller); - } - if (transformer.flush !== undefined) { - flushAlgorithm = () => transformer.flush(controller); - } - SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); -} -function TransformStreamDefaultControllerClearAlgorithms(controller) { - controller._transformAlgorithm = undefined; - controller._flushAlgorithm = undefined; -} -function TransformStreamDefaultControllerEnqueue(controller, chunk) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { - throw new TypeError('Readable side is not in a state that permits enqueue'); - } - // We throttle transform invocations based on the backpressure of the ReadableStream, but we still - // accept TransformStreamDefaultControllerEnqueue() calls. - try { - ReadableStreamDefaultControllerEnqueue(readableController, chunk); - } - catch (e) { - // This happens when readableStrategy.size() throws. - TransformStreamErrorWritableAndUnblockWrite(stream, e); - throw stream._readable._storedError; - } - const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); - if (backpressure !== stream._backpressure) { - TransformStreamSetBackpressure(stream, true); - } -} -function TransformStreamDefaultControllerError(controller, e) { - TransformStreamError(controller._controlledTransformStream, e); -} -function TransformStreamDefaultControllerPerformTransform(controller, chunk) { - const transformPromise = controller._transformAlgorithm(chunk); - return transformPromiseWith(transformPromise, undefined, r => { - TransformStreamError(controller._controlledTransformStream, r); - throw r; - }); -} -function TransformStreamDefaultControllerTerminate(controller) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - ReadableStreamDefaultControllerClose(readableController); - const error = new TypeError('TransformStream terminated'); - TransformStreamErrorWritableAndUnblockWrite(stream, error); -} -// TransformStreamDefaultSink Algorithms -function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { - const controller = stream._transformStreamController; - if (stream._backpressure) { - const backpressureChangePromise = stream._backpressureChangePromise; - return transformPromiseWith(backpressureChangePromise, () => { - const writable = stream._writable; - const state = writable._state; - if (state === 'erroring') { - throw writable._storedError; - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - }); - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); -} -function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { - // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already - // errored. - TransformStreamError(stream, reason); - return promiseResolvedWith(undefined); -} -function TransformStreamDefaultSinkCloseAlgorithm(stream) { - // stream._readable cannot change after construction, so caching it across a call to user code is safe. - const readable = stream._readable; - const controller = stream._transformStreamController; - const flushPromise = controller._flushAlgorithm(); - TransformStreamDefaultControllerClearAlgorithms(controller); - // Return a promise that is fulfilled with undefined on success. - return transformPromiseWith(flushPromise, () => { - if (readable._state === 'errored') { - throw readable._storedError; - } - ReadableStreamDefaultControllerClose(readable._readableStreamController); - }, r => { - TransformStreamError(stream, r); - throw readable._storedError; - }); -} -// TransformStreamDefaultSource Algorithms -function TransformStreamDefaultSourcePullAlgorithm(stream) { - // Invariant. Enforced by the promises returned by start() and pull(). - TransformStreamSetBackpressure(stream, false); - // Prevent the next pull() call until there is backpressure. - return stream._backpressureChangePromise; -} -// Helper functions for the TransformStreamDefaultController. -function defaultControllerBrandCheckException(name) { - return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); -} -// Helper functions for the TransformStream. -function streamBrandCheckException(name) { - return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); -} - -export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; diff --git a/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs b/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs new file mode 100644 index 000000000..c448367e5 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs @@ -0,0 +1,3 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var e=[0,1,3,7,15,31,63,127,255],r=function(t){this.stream=t,this.bitOffset=0,this.curByte=0,this.hasByte=!1};r.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},r.prototype.read=function(t){for(var r=0;t>0;){this._ensureByte();var i=8-this.bitOffset;if(t>=i)r<<=i,r|=e[i]&this.curByte,this.hasByte=!1,this.bitOffset=0,t-=i;else{r<<=t;var n=i-t;r|=(this.curByte&e[t]<>n,this.bitOffset+=t,t=0}}return r},r.prototype.seek=function(t){var e=t%8,r=(t-e)/8;this.bitOffset=e,this.stream.seek(r),this.hasByte=!1},r.prototype.pi=function(){var t,e=new Uint8Array(6);for(t=0;t("00"+t.toString(16)).slice(-2))).join("")}(e)};var i=r,n=function(){};n.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},n.prototype.read=function(t,e,r){for(var i=0;i>>0},this.updateCRC=function(e){t=t<<8^o[255&(t>>>24^e)]},this.updateCRCRun=function(e,r){for(;r-- >0;)t=t<<8^o[255&(t>>>24^e)]}}),f=i,u=a,h=s,p=function(t,e){var r,i=t[e];for(r=e;r>0;r--)t[r]=t[r-1];return t[0]=i,i},d={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},c={};c[d.LAST_BLOCK]="Bad file checksum",c[d.NOT_BZIP_DATA]="Not bzip data",c[d.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",c[d.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",c[d.DATA_ERROR]="Data error",c[d.OUT_OF_MEMORY]="Out of memory",c[d.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var _=function(t,e){var r=c[t]||"unknown error";e&&(r+=": "+e);var i=new TypeError(r);throw i.errorCode=t,i},b=function(t,e){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(t,e)};b.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new h,!0):(this.writeCount=-1,!1)},b.prototype._start_bunzip=function(t,e){var r=new Uint8Array(4);4===t.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||_(d.NOT_BZIP_DATA,"bad magic");var i=r[3]-48;(i<1||i>9)&&_(d.NOT_BZIP_DATA,"level out of range"),this.reader=new f(t),this.dbufSize=1e5*i,this.nextoutput=0,this.outputStream=e,this.streamCRC=0},b.prototype._get_next_block=function(){var t,e,r,i=this.reader,n=i.pi();if("177245385090"===n)return!1;"314159265359"!==n&&_(d.NOT_BZIP_DATA),this.targetBlockCRC=i.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,i.read(1)&&_(d.OBSOLETE_INPUT);var o=i.read(24);o>this.dbufSize&&_(d.DATA_ERROR,"initial position out of bounds");var a=i.read(16),s=new Uint8Array(256),f=0;for(t=0;t<16;t++)if(a&1<<15-t){var u=16*t;for(r=i.read(16),e=0;e<16;e++)r&1<<15-e&&(s[f++]=u+e)}var h=i.read(3);(h<2||h>6)&&_(d.DATA_ERROR);var c=i.read(15);0===c&&_(d.DATA_ERROR);var b=new Uint8Array(256);for(t=0;t=h&&_(d.DATA_ERROR);y[t]=p(b,e)}var R,l=f+2,C=[];for(e=0;e20)&&_(d.DATA_ERROR),i.read(1);)i.read(1)?a--:a++;O[t]=a}for(A=w=O[0],t=1;tw?w=O[t]:O[t]=c&&_(d.DATA_ERROR),R=C[y[U++]]),t=R.minLen,e=i.read(t);t>R.maxLen&&_(d.DATA_ERROR),!(e<=R.limit[t]);t++)e=e<<1|i.read(1);((e-=R.base[t])<0||e>=258)&&_(d.DATA_ERROR);var D=R.permute[e];if(0!==D&&1!==D){if(T)for(T=0,g+a>this.dbufSize&&_(d.DATA_ERROR),E[m=s[b[0]]]+=a;a--;)k[g++]=m;if(D>f)break;g>=this.dbufSize&&_(d.DATA_ERROR),E[m=s[m=p(b,t=D-1)]]++,k[g++]=m}else T||(T=1,a=0),a+=0===D?T:2*T,T<<=1}for((o<0||o>=g)&&_(d.DATA_ERROR),e=0,t=0;t<256;t++)r=e+E[t],E[t]=e,e=r;for(t=0;t>=8,S=-1),this.writePos=z,this.writeCurrent=P,this.writeCount=g,this.writeRun=S,!0},b.prototype._read_bunzip=function(t,e){var r,i,n;if(this.writeCount<0)return 0;var o=this.dbuf,a=this.writePos,s=this.writeCurrent,f=this.writeCount;this.outputsize;for(var u=this.writeRun;f;){for(f--,i=s,s=255&(a=o[a]),a>>=8,3==u++?(r=s,n=i,s=-1):(r=1,n=s),this.blockCRC.updateCRCRun(n,r);r--;)this.outputStream.writeByte(n),this.nextoutput++;s!=i&&(u=0)}return this.writeCount=f,this.blockCRC.getCRC()!==this.targetBlockCRC&&_(d.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var y=function(t){if("readByte"in t)return t;var e=new u;return e.pos=0,e.readByte=function(){return t[this.pos++]},e.seek=function(t){this.pos=t},e.eof=function(){return this.pos>=t.length},e},R=function(t){var e=new u,r=!0;if(t)if("number"==typeof t)e.buffer=new Uint8Array(t),r=!1;else{if("writeByte"in t)return t;e.buffer=t,r=!1}else e.buffer=new Uint8Array(16384);return e.pos=0,e.writeByte=function(t){if(r&&this.pos>=this.buffer.length){var e=new Uint8Array(2*this.buffer.length);e.set(this.buffer),this.buffer=e}this.buffer[this.pos++]=t},e.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var t=new Uint8Array(this.pos);t.set(this.buffer.subarray(0,this.pos)),this.buffer=t}return this.buffer},e._coerced=!0,e};var l=/*#__PURE__*/t({__proto__:null},[{Bunzip:b,Stream:u,Err:d,decode:function(t,e,r){for(var i=y(t),n=R(e),o=new b(i,n);!("eof"in i)||!i.eof();)if(o._init_block())o._read_bunzip();else{var a=o.reader.read(32)>>>0;if(a!==o.streamCRC&&_(d.DATA_ERROR,"Bad stream CRC (got "+o.streamCRC.toString(16)+" expected "+a.toString(16)+")"),!r||!("eof"in i)||i.eof())break;o._start_bunzip(i,n)}if("getBuffer"in n)return n.getBuffer()},decodeBlock:function(t,e,r){var i=y(t),n=R(r),o=new b(i,n);if(o.reader.seek(e),o._get_next_block()&&(o.blockCRC=new h,o.writeCopies=0,o._read_bunzip()),"getBuffer"in n)return n.getBuffer()},table:function(t,e,r){var i=new u;i.delegate=y(t),i.pos=0,i.readByte=function(){return this.pos++,this.delegate.readByte()},i.delegate.eof&&(i.eof=i.delegate.eof.bind(i.delegate));var n=new u;n.pos=0,n.writeByte=function(){this.pos++};for(var o=new b(i,n),a=o.dbufSize;!("eof"in i)||!i.eof();){var s=8*i.pos+o.reader.bitOffset;if(o.reader.hasByte&&(s-=8),o._init_block()){var f=n.pos;o._read_bunzip(),e(s,n.pos-f)}else{if(o.reader.read(32),!r||!("eof"in i)||i.eof())break;o._start_bunzip(i,n),console.assert(o.dbufSize===a,"shouldn't change block size within multistream file")}}}}]);export{l as i}; +//# sourceMappingURL=seek-bzip.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs.map new file mode 100644 index 000000000..d0452c540 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/seek-bzip.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"seek-bzip.min.mjs","sources":["../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js"],"sourcesContent":["/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n"],"names":["BITMASK","BitReader","stream","this","bitOffset","curByte","hasByte","prototype","_ensureByte","readByte","read","bits","result","remaining","shift","seek","pos","n_bit","n_byte","pi","i","buf","Uint8Array","length","Array","map","call","x","toString","slice","join","bufToHex","bitreader","Stream","Error","buffer","bufOffset","bytesRead","c","new_pos","writeByte","_byte","write","flush","crc32Lookup","crc32","Uint32Array","crc","getCRC","updateCRC","value","updateCRCRun","count","require$$0","require$$1","CRC32","require$$2","mtf","array","index","src","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","status","optDetail","msg","e","TypeError","errorCode","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","String","fromCharCode","level","reader","dbufSize","nextoutput","streamCRC","j","k","h","targetBlockCRC","origPointer","t","symToByte","symTotal","o","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","temp","Uint16Array","MAX_HUFCODE_BITS","push","permute","limit","base","pp","Number","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","len","copies","previous","outbyte","outputsize","coerceInputStream","input","eof","coerceOutputStream","output","resizeOk","newBuffer","set","getBuffer","subarray","_coerced","decode","multistream","bz","targetStreamCRC","decodeBlock","writeCopies","table","callback","delegate","bind","blockSize","position","start","console","assert"],"mappings":";8YA6BA,IAAIA,EAAU,CAAC,EAAM,EAAM,EAAM,EAAM,GAAM,GAAM,GAAM,IAAM,KAG3DC,EAAY,SAASC,GACvBC,KAAKD,OAASA,EACdC,KAAKC,UAAY,EACjBD,KAAKE,QAAU,EACfF,KAAKG,SAAU,CACjB,EAEAL,EAAUM,UAAUC,YAAc,WAC3BL,KAAKG,UACRH,KAAKE,QAAUF,KAAKD,OAAOO,WAC3BN,KAAKG,SAAU,EAEnB,EAGAL,EAAUM,UAAUG,KAAO,SAASC,GAElC,IADA,IAAIC,EAAS,EACND,EAAO,GAAG,CACfR,KAAKK,cACL,IAAIK,EAAY,EAAIV,KAAKC,UAEzB,GAAIO,GAAQE,EACVD,IAAWC,EACXD,GAAUZ,EAAQa,GAAaV,KAAKE,QACpCF,KAAKG,SAAU,EACfH,KAAKC,UAAY,EACjBO,GAAQE,MACH,CACLD,IAAWD,EACX,IAAIG,EAAQD,EA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EAAGrE,cAAe,CACpB,IAAI+E,EAAQpF,EAAajE,IACzB2I,EAAGpB,eACHyB,EAASI,EAAUnF,EAAajE,IAAMqJ,EAC5C,KAAW,CAEL,GADUV,EAAG/D,OAAOlF,KAAK,KACrBgJ,KACA,QAAS1E,IACRA,EAAYgE,MAKV,MAHLW,EAAGtE,cAAcL,EAAaC,GAC9BqF,QAAQC,OAAOZ,EAAG9D,WAAasE,EAChB,sDAEvB,CACA,CACA","x_google_ignoreList":[0,1,2,3]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/seek-bzip.mjs b/app/node_modules/openpgp/dist/lightweight/seek-bzip.mjs new file mode 100644 index 000000000..54090aba5 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/seek-bzip.mjs @@ -0,0 +1,866 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +/* +node-bzip - a pure-javascript Node.JS module for decoding bzip2 data + +Copyright (C) 2012 Eli Skeggs + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html + +Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). + +Based on micro-bunzip by Rob Landley (rob@landley.net). + +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ + +var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; + +// offset in bytes +var BitReader$1 = function(stream) { + this.stream = stream; + this.bitOffset = 0; + this.curByte = 0; + this.hasByte = false; +}; + +BitReader$1.prototype._ensureByte = function() { + if (!this.hasByte) { + this.curByte = this.stream.readByte(); + this.hasByte = true; + } +}; + +// reads bits from the buffer +BitReader$1.prototype.read = function(bits) { + var result = 0; + while (bits > 0) { + this._ensureByte(); + var remaining = 8 - this.bitOffset; + // if we're in a byte + if (bits >= remaining) { + result <<= remaining; + result |= BITMASK[remaining] & this.curByte; + this.hasByte = false; + this.bitOffset = 0; + bits -= remaining; + } else { + result <<= bits; + var shift = remaining - bits; + result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; + this.bitOffset += bits; + bits = 0; + } + } + return result; +}; + +// seek to an arbitrary point in the buffer (expressed in bits) +BitReader$1.prototype.seek = function(pos) { + var n_bit = pos % 8; + var n_byte = (pos - n_bit) / 8; + this.bitOffset = n_bit; + this.stream.seek(n_byte); + this.hasByte = false; +}; + +// reads 6 bytes worth of data using the read method +BitReader$1.prototype.pi = function() { + var buf = new Uint8Array(6), i; + for (i = 0; i < buf.length; i++) { + buf[i] = this.read(8); + } + return bufToHex(buf); +}; + +function bufToHex(buf) { + return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); +} + +var bitreader = BitReader$1; + +/* very simple input/output stream interface */ + +var Stream$1 = function() { +}; + +// input streams ////////////// +/** Returns the next byte, or -1 for EOF. */ +Stream$1.prototype.readByte = function() { + throw new Error("abstract method readByte() not implemented"); +}; +/** Attempts to fill the buffer; returns number of bytes read, or + * -1 for EOF. */ +Stream$1.prototype.read = function(buffer, bufOffset, length) { + var bytesRead = 0; + while (bytesRead < length) { + var c = this.readByte(); + if (c < 0) { // EOF + return (bytesRead===0) ? -1 : bytesRead; + } + buffer[bufOffset++] = c; + bytesRead++; + } + return bytesRead; +}; +Stream$1.prototype.seek = function(new_pos) { + throw new Error("abstract method seek() not implemented"); +}; + +// output streams /////////// +Stream$1.prototype.writeByte = function(_byte) { + throw new Error("abstract method readByte() not implemented"); +}; +Stream$1.prototype.write = function(buffer, bufOffset, length) { + var i; + for (i=0; i>> 0; // return an unsigned value + }; + + /** + * Update the CRC with a single byte + * @param value The value to update the CRC with + */ + this.updateCRC = function(value) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + }; + + /** + * Update the CRC with a sequence of identical bytes + * @param value The value to update the CRC with + * @param count The number of bytes + */ + this.updateCRCRun = function(value, count) { + while (count-- > 0) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + } + }; + }; + return CRC32; +})(); + +/* +seek-bzip - a pure-javascript module for seeking within bzip2 data + +Copyright (C) 2013 C. Scott Ananian +Copyright (C) 2012 Eli Skeggs +Copyright (C) 2011 Kevin Kwok + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html + +Adapted from node-bzip, copyright 2012 Eli Skeggs. +Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). + +Based on micro-bunzip by Rob Landley (rob@landley.net). + +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ + +var BitReader = bitreader; +var Stream = stream; +var CRC32 = crc32; + +var MAX_HUFCODE_BITS = 20; +var MAX_SYMBOLS = 258; +var SYMBOL_RUNA = 0; +var SYMBOL_RUNB = 1; +var MIN_GROUPS = 2; +var MAX_GROUPS = 6; +var GROUP_SIZE = 50; + +var WHOLEPI = "314159265359"; +var SQRTPI = "177245385090"; + +var mtf = function(array, index) { + var src = array[index], i; + for (i = index; i > 0; i--) { + array[i] = array[i-1]; + } + array[0] = src; + return src; +}; + +var Err = { + OK: 0, + LAST_BLOCK: -1, + NOT_BZIP_DATA: -2, + UNEXPECTED_INPUT_EOF: -3, + UNEXPECTED_OUTPUT_EOF: -4, + DATA_ERROR: -5, + OUT_OF_MEMORY: -6, + OBSOLETE_INPUT: -7, + END_OF_BLOCK: -8 +}; +var ErrorMessages = {}; +ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; +ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; +ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; +ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; +ErrorMessages[Err.DATA_ERROR] = "Data error"; +ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; +ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; + +var _throw = function(status, optDetail) { + var msg = ErrorMessages[status] || 'unknown error'; + if (optDetail) { msg += ': '+optDetail; } + var e = new TypeError(msg); + e.errorCode = status; + throw e; +}; + +var Bunzip = function(inputStream, outputStream) { + this.writePos = this.writeCurrent = this.writeCount = 0; + + this._start_bunzip(inputStream, outputStream); +}; +Bunzip.prototype._init_block = function() { + var moreBlocks = this._get_next_block(); + if ( !moreBlocks ) { + this.writeCount = -1; + return false; /* no more blocks */ + } + this.blockCRC = new CRC32(); + return true; +}; +/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ +Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { + /* Ensure that file starts with "BZh['1'-'9']." */ + var buf = new Uint8Array(4); + if (inputStream.read(buf, 0, 4) !== 4 || + String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') + _throw(Err.NOT_BZIP_DATA, 'bad magic'); + + var level = buf[3] - 0x30; + if (level < 1 || level > 9) + _throw(Err.NOT_BZIP_DATA, 'level out of range'); + + this.reader = new BitReader(inputStream); + + /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of + uncompressed data. Allocate intermediate buffer for block. */ + this.dbufSize = 100000 * level; + this.nextoutput = 0; + this.outputStream = outputStream; + this.streamCRC = 0; +}; +Bunzip.prototype._get_next_block = function() { + var i, j, k; + var reader = this.reader; + // this is get_next_block() function from micro-bunzip: + /* Read in header signature and CRC, then validate signature. + (last block signature means CRC is for whole file, return now) */ + var h = reader.pi(); + if (h === SQRTPI) { // last block + return false; /* no more blocks */ + } + if (h !== WHOLEPI) + _throw(Err.NOT_BZIP_DATA); + this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) + this.streamCRC = (this.targetBlockCRC ^ + ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; + /* We can add support for blockRandomised if anybody complains. There was + some code for this in busybox 1.0.0-pre3, but nobody ever noticed that + it didn't actually work. */ + if (reader.read(1)) + _throw(Err.OBSOLETE_INPUT); + var origPointer = reader.read(24); + if (origPointer > this.dbufSize) + _throw(Err.DATA_ERROR, 'initial position out of bounds'); + /* mapping table: if some byte values are never used (encoding things + like ascii text), the compression code removes the gaps to have fewer + symbols to deal with, and writes a sparse bitfield indicating which + values were present. We make a translation table to convert the symbols + back to the corresponding bytes. */ + var t = reader.read(16); + var symToByte = new Uint8Array(256), symTotal = 0; + for (i = 0; i < 16; i++) { + if (t & (1 << (0xF - i))) { + var o = i * 16; + k = reader.read(16); + for (j = 0; j < 16; j++) + if (k & (1 << (0xF - j))) + symToByte[symTotal++] = o + j; + } + } + + /* How many different huffman coding groups does this block use? */ + var groupCount = reader.read(3); + if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) + _throw(Err.DATA_ERROR); + /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding + group. Read in the group selector list, which is stored as MTF encoded + bit runs. (MTF=Move To Front, as each value is used it's moved to the + start of the list.) */ + var nSelectors = reader.read(15); + if (nSelectors === 0) + _throw(Err.DATA_ERROR); + + var mtfSymbol = new Uint8Array(256); + for (i = 0; i < groupCount; i++) + mtfSymbol[i] = i; + + var selectors = new Uint8Array(nSelectors); // was 32768... + + for (i = 0; i < nSelectors; i++) { + /* Get next value */ + for (j = 0; reader.read(1); j++) + if (j >= groupCount) _throw(Err.DATA_ERROR); + /* Decode MTF to get the next selector */ + selectors[i] = mtf(mtfSymbol, j); + } + + /* Read the huffman coding tables for each group, which code for symTotal + literal symbols, plus two run symbols (RUNA, RUNB) */ + var symCount = symTotal + 2; + var groups = [], hufGroup; + for (j = 0; j < groupCount; j++) { + var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); + /* Read huffman code lengths for each symbol. They're stored in + a way similar to mtf; record a starting value for the first symbol, + and an offset from the previous value for everys symbol after that. */ + t = reader.read(5); // lengths + for (i = 0; i < symCount; i++) { + for (;;) { + if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); + /* If first bit is 0, stop. Else second bit indicates whether + to increment or decrement the value. */ + if(!reader.read(1)) + break; + if(!reader.read(1)) + t++; + else + t--; + } + length[i] = t; + } + + /* Find largest and smallest lengths in this group */ + var minLen, maxLen; + minLen = maxLen = length[0]; + for (i = 1; i < symCount; i++) { + if (length[i] > maxLen) + maxLen = length[i]; + else if (length[i] < minLen) + minLen = length[i]; + } + + /* Calculate permute[], base[], and limit[] tables from length[]. + * + * permute[] is the lookup table for converting huffman coded symbols + * into decoded symbols. base[] is the amount to subtract from the + * value of a huffman symbol of a given length when using permute[]. + * + * limit[] indicates the largest numerical value a symbol with a given + * number of bits can have. This is how the huffman codes can vary in + * length: each code with a value>limit[length] needs another bit. + */ + hufGroup = {}; + groups.push(hufGroup); + hufGroup.permute = new Uint16Array(MAX_SYMBOLS); + hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); + hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); + hufGroup.minLen = minLen; + hufGroup.maxLen = maxLen; + /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ + var pp = 0; + for (i = minLen; i <= maxLen; i++) { + temp[i] = hufGroup.limit[i] = 0; + for (t = 0; t < symCount; t++) + if (length[t] === i) + hufGroup.permute[pp++] = t; + } + /* Count symbols coded for at each bit length */ + for (i = 0; i < symCount; i++) + temp[length[i]]++; + /* Calculate limit[] (the largest symbol-coding value at each bit + * length, which is (previous limit<<1)+symbols at this level), and + * base[] (number of symbols to ignore at each bit length, which is + * limit minus the cumulative count of symbols coded for already). */ + pp = t = 0; + for (i = minLen; i < maxLen; i++) { + pp += temp[i]; + /* We read the largest possible symbol size and then unget bits + after determining how many we need, and those extra bits could + be set to anything. (They're noise from future symbols.) At + each level we're really only interested in the first few bits, + so here we set all the trailing to-be-ignored bits to 1 so they + don't affect the value>limit[length] comparison. */ + hufGroup.limit[i] = pp - 1; + pp <<= 1; + t += temp[i]; + hufGroup.base[i + 1] = pp - t; + } + hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ + hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; + hufGroup.base[minLen] = 0; + } + /* We've finished reading and digesting the block header. Now read this + block's huffman coded symbols from the file and undo the huffman coding + and run length encoding, saving the result into dbuf[dbufCount++]=uc */ + + /* Initialize symbol occurrence counters and symbol Move To Front table */ + var byteCount = new Uint32Array(256); + for (i = 0; i < 256; i++) + mtfSymbol[i] = i; + /* Loop through compressed symbols. */ + var runPos = 0, dbufCount = 0, selector = 0, uc; + var dbuf = this.dbuf = new Uint32Array(this.dbufSize); + symCount = 0; + for (;;) { + /* Determine which huffman coding group to use. */ + if (!(symCount--)) { + symCount = GROUP_SIZE - 1; + if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } + hufGroup = groups[selectors[selector++]]; + } + /* Read next huffman-coded symbol. */ + i = hufGroup.minLen; + j = reader.read(i); + for (;;i++) { + if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } + if (j <= hufGroup.limit[i]) + break; + j = (j << 1) | reader.read(1); + } + /* Huffman decode value to get nextSym (with bounds checking) */ + j -= hufGroup.base[i]; + if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } + var nextSym = hufGroup.permute[j]; + /* We have now decoded the symbol, which indicates either a new literal + byte, or a repeated run of the most recent literal byte. First, + check if nextSym indicates a repeated run, and if so loop collecting + how many times to repeat the last literal. */ + if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { + /* If this is the start of a new run, zero out counter */ + if (!runPos){ + runPos = 1; + t = 0; + } + /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at + each bit position, add 1 or 2 instead. For example, + 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. + You can make any bit pattern that way using 1 less symbol than + the basic or 0/1 method (except all bits 0, which would use no + symbols, but a run of length 0 doesn't mean anything in this + context). Thus space is saved. */ + if (nextSym === SYMBOL_RUNA) + t += runPos; + else + t += 2 * runPos; + runPos <<= 1; + continue; + } + /* When we hit the first non-run symbol after a run, we now know + how many times to repeat the last literal, so append that many + copies to our buffer of decoded symbols (dbuf) now. (The last + literal used is the one at the head of the mtfSymbol array.) */ + if (runPos){ + runPos = 0; + if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } + uc = symToByte[mtfSymbol[0]]; + byteCount[uc] += t; + while (t--) + dbuf[dbufCount++] = uc; + } + /* Is this the terminating symbol? */ + if (nextSym > symTotal) + break; + /* At this point, nextSym indicates a new literal character. Subtract + one to get the position in the MTF array at which this literal is + currently to be found. (Note that the result can't be -1 or 0, + because 0 and 1 are RUNA and RUNB. But another instance of the + first symbol in the mtf array, position 0, would have been handled + as part of a run above. Therefore 1 unused mtf position minus + 2 non-literal nextSym values equals -1.) */ + if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } + i = nextSym - 1; + uc = mtf(mtfSymbol, i); + uc = symToByte[uc]; + /* We have our literal byte. Save it into dbuf. */ + byteCount[uc]++; + dbuf[dbufCount++] = uc; + } + /* At this point, we've read all the huffman-coded symbols (and repeated + runs) for this block from the input stream, and decoded them into the + intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. + Now undo the Burrows-Wheeler transform on dbuf. + See http://dogma.net/markn/articles/bwt/bwt.htm + */ + if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } + /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ + j = 0; + for (i = 0; i < 256; i++) { + k = j + byteCount[i]; + byteCount[i] = j; + j = k; + } + /* Figure out what order dbuf would be in if we sorted it. */ + for (i = 0; i < dbufCount; i++) { + uc = dbuf[i] & 0xff; + dbuf[byteCount[uc]] |= (i << 8); + byteCount[uc]++; + } + /* Decode first byte by hand to initialize "previous" byte. Note that it + doesn't get output, and if the first three characters are identical + it doesn't qualify as a run (hence writeRunCountdown=5). */ + var pos = 0, current = 0, run = 0; + if (dbufCount) { + pos = dbuf[origPointer]; + current = (pos & 0xff); + pos >>= 8; + run = -1; + } + this.writePos = pos; + this.writeCurrent = current; + this.writeCount = dbufCount; + this.writeRun = run; + + return true; /* more blocks to come */ +}; +/* Undo burrows-wheeler transform on intermediate buffer to produce output. + If start_bunzip was initialized with out_fd=-1, then up to len bytes of + data are written to outbuf. Return value is number of bytes written or + error (all errors are negative numbers). If out_fd!=-1, outbuf and len + are ignored, data is written to out_fd and return is RETVAL_OK or error. +*/ +Bunzip.prototype._read_bunzip = function(outputBuffer, len) { + var copies, previous, outbyte; + /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully + decoded, which results in this returning RETVAL_LAST_BLOCK, also + equal to -1... Confusing, I'm returning 0 here to indicate no + bytes written into the buffer */ + if (this.writeCount < 0) { return 0; } + var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; + var dbufCount = this.writeCount; this.outputsize; + var run = this.writeRun; + + while (dbufCount) { + dbufCount--; + previous = current; + pos = dbuf[pos]; + current = pos & 0xff; + pos >>= 8; + if (run++ === 3){ + copies = current; + outbyte = previous; + current = -1; + } else { + copies = 1; + outbyte = current; + } + this.blockCRC.updateCRCRun(outbyte, copies); + while (copies--) { + this.outputStream.writeByte(outbyte); + this.nextoutput++; + } + if (current != previous) + run = 0; + } + this.writeCount = dbufCount; + // check CRC + if (this.blockCRC.getCRC() !== this.targetBlockCRC) { + _throw(Err.DATA_ERROR, "Bad block CRC "+ + "(got "+this.blockCRC.getCRC().toString(16)+ + " expected "+this.targetBlockCRC.toString(16)+")"); + } + return this.nextoutput; +}; + +var coerceInputStream = function(input) { + if ('readByte' in input) { return input; } + var inputStream = new Stream(); + inputStream.pos = 0; + inputStream.readByte = function() { return input[this.pos++]; }; + inputStream.seek = function(pos) { this.pos = pos; }; + inputStream.eof = function() { return this.pos >= input.length; }; + return inputStream; +}; +var coerceOutputStream = function(output) { + var outputStream = new Stream(); + var resizeOk = true; + if (output) { + if (typeof(output)==='number') { + outputStream.buffer = new Uint8Array(output); + resizeOk = false; + } else if ('writeByte' in output) { + return output; + } else { + outputStream.buffer = output; + resizeOk = false; + } + } else { + outputStream.buffer = new Uint8Array(16384); + } + outputStream.pos = 0; + outputStream.writeByte = function(_byte) { + if (resizeOk && this.pos >= this.buffer.length) { + var newBuffer = new Uint8Array(this.buffer.length*2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + this.buffer[this.pos++] = _byte; + }; + outputStream.getBuffer = function() { + // trim buffer + if (this.pos !== this.buffer.length) { + if (!resizeOk) + throw new TypeError('outputsize does not match decoded input'); + var newBuffer = new Uint8Array(this.pos); + newBuffer.set(this.buffer.subarray(0, this.pos)); + this.buffer = newBuffer; + } + return this.buffer; + }; + outputStream._coerced = true; + return outputStream; +}; + +/* Static helper functions */ +// 'input' can be a stream or a buffer +// 'output' can be a stream or a buffer or a number (buffer size) +const decode = function(input, output, multistream) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + + var bz = new Bunzip(inputStream, outputStream); + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + if (bz._init_block()) { + bz._read_bunzip(); + } else { + var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) + if (targetStreamCRC !== bz.streamCRC) { + _throw(Err.DATA_ERROR, "Bad stream CRC "+ + "(got "+bz.streamCRC.toString(16)+ + " expected "+targetStreamCRC.toString(16)+")"); + } + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + } else break; + } + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); +}; +const decodeBlock = function(input, pos, output) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + var bz = new Bunzip(inputStream, outputStream); + bz.reader.seek(pos); + /* Fill the decode buffer for the block */ + var moreBlocks = bz._get_next_block(); + if (moreBlocks) { + /* Init the CRC for writing */ + bz.blockCRC = new CRC32(); + + /* Zero this so the current byte from before the seek is not written */ + bz.writeCopies = 0; + + /* Decompress the block and write to stdout */ + bz._read_bunzip(); + // XXX keep writing? + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); +}; +/* Reads bzip2 file from stream or buffer `input`, and invoke + * `callback(position, size)` once for each bzip2 block, + * where position gives the starting position (in *bits*) + * and size gives uncompressed size of the block (in *bytes*). */ +const table = function(input, callback, multistream) { + // make a stream from a buffer, if necessary + var inputStream = new Stream(); + inputStream.delegate = coerceInputStream(input); + inputStream.pos = 0; + inputStream.readByte = function() { + this.pos++; + return this.delegate.readByte(); + }; + if (inputStream.delegate.eof) { + inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); + } + var outputStream = new Stream(); + outputStream.pos = 0; + outputStream.writeByte = function() { this.pos++; }; + + var bz = new Bunzip(inputStream, outputStream); + var blockSize = bz.dbufSize; + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + + var position = inputStream.pos*8 + bz.reader.bitOffset; + if (bz.reader.hasByte) { position -= 8; } + + if (bz._init_block()) { + var start = outputStream.pos; + bz._read_bunzip(); + callback(position, outputStream.pos - start); + } else { + bz.reader.read(32); // (but we ignore the crc) + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + console.assert(bz.dbufSize === blockSize, + "shouldn't change block size within multistream file"); + } else break; + } + } +}; + +var lib = { + Bunzip, + Stream, + Err, + decode, + decodeBlock, + table +}; + +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null +}, [lib]); + +export { index as i }; diff --git a/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs b/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs new file mode 100644 index 000000000..ff9144568 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs @@ -0,0 +1,4 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t){if(!Number.isSafeInteger(t)||t<0)throw Error("positive integer expected, not "+t)}function s(t,...e){if(!((s=t)instanceof Uint8Array||null!=s&&"object"==typeof s&&"Uint8Array"===s.constructor.name))throw Error("Uint8Array expected");var s;if(e.length>0&&!e.includes(t.length))throw Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function i(t){if("function"!=typeof t||"function"!=typeof t.create)throw Error("Hash should be wrapped by utils.wrapConstructor");e(t.outputLen),e(t.blockLen)}function n(t,e=!0){if(t.destroyed)throw Error("Hash instance has been destroyed");if(e&&t.finished)throw Error("Hash#digest() has already been called")}function h(t,e){s(t);const i=e.outputLen;if(t.lengthnew DataView(t.buffer,t.byteOffset,t.byteLength),c=(t,e)=>t<<32-e|t>>>e,a=(t,e)=>t<>>32-e>>>0,f=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function d(t){for(let s=0;s>>8&65280|e>>>24&255;var e}function l(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}function u(t){return"string"==typeof t&&(t=l(t)),s(t),t}function b(...t){let e=0;for(let i=0;it().update(u(e)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function g(t=32){if(r&&"function"==typeof r.getRandomValues)return r.getRandomValues(new Uint8Array(t));if(r&&"function"==typeof r.randomBytes)return r.randomBytes(t);throw Error("crypto.getRandomValues must be defined")}const y=(t,e,s)=>t&e^~t&s,L=(t,e,s)=>t&e^t&s^e&s;class w extends x{constructor(t,e,s,i){super(),this.blockLen=t,this.outputLen=e,this.padOffset=s,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=o(this.buffer)}update(t){n(this);const{view:e,buffer:s,blockLen:i}=this,h=(t=u(t)).length;for(let n=0;ni-c&&(this.process(s,0),c=0);for(let t=c;t>n&h),o=Number(s&h),c=i?4:0,a=i?0:4;t.setUint32(e+c,r,i),t.setUint32(e+a,o,i)}(s,i-8,BigInt(8*this.length),r),this.process(s,0);const a=o(t),f=this.outputLen;if(f%4)throw Error("_sha2: outputLen should be aligned to 32bit");const d=f/4,l=this.get();if(d>l.length)throw Error("_sha2: outputLen bigger than state");for(let t=0;t>>3,n=c(s,17)^c(s,19)^s>>>10;A[t]=n+A[t-7]+i+A[t-16]|0}let{A:s,B:i,C:n,D:h,E:r,F:o,G:a,H:f}=this;for(let t=0;t<64;t++){const e=f+(c(r,6)^c(r,11)^c(r,25))+y(r,o,a)+B[t]+A[t]|0,d=(c(s,2)^c(s,13)^c(s,22))+L(s,i,n)|0;f=a,a=o,o=r,r=h+e|0,h=n,n=i,i=s,s=e+d|0}s=s+this.A|0,i=i+this.B|0,n=n+this.C|0,h=h+this.D|0,r=r+this.E|0,o=o+this.F|0,a=a+this.G|0,f=f+this.H|0,this.set(s,i,n,h,r,o,a,f)}roundClean(){A.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class k extends E{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const U=/* @__PURE__ */p((()=>new E)),I=/* @__PURE__ */p((()=>new k)),S=/* @__PURE__ */BigInt(2**32-1),C=/* @__PURE__ */BigInt(32);function F(t,e=!1){return e?{h:Number(t&S),l:Number(t>>C&S)}:{h:0|Number(t>>C&S),l:0|Number(t&S)}}function m(t,e=!1){let s=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let n=0;nt<>>32-s,G=(t,e,s)=>e<>>32-s,O=(t,e,s)=>e<>>64-s,v=(t,e,s)=>t<>>64-s;const N={fromBig:F,split:m,toBig:(t,e)=>BigInt(t>>>0)<>>0),shrSH:(t,e,s)=>t>>>s,shrSL:(t,e,s)=>t<<32-s|e>>>s,rotrSH:(t,e,s)=>t>>>s|e<<32-s,rotrSL:(t,e,s)=>t<<32-s|e>>>s,rotrBH:(t,e,s)=>t<<64-s|e>>>s-32,rotrBL:(t,e,s)=>t>>>s-32|e<<64-s,rotr32H:(t,e)=>e,rotr32L:(t,e)=>t,rotlSH:D,rotlSL:G,rotlBH:O,rotlBL:v,add:function(t,e,s,i){const n=(e>>>0)+(i>>>0);return{h:t+s+(n/2**32|0)|0,l:0|n}},add3L:(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),add3H:(t,e,s,i)=>e+s+i+(t/2**32|0)|0,add4L:(t,e,s,i)=>(t>>>0)+(e>>>0)+(s>>>0)+(i>>>0),add4H:(t,e,s,i,n)=>e+s+i+n+(t/2**32|0)|0,add5H:(t,e,s,i,n,h)=>e+s+i+n+h+(t/2**32|0)|0,add5L:(t,e,s,i,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(i>>>0)+(n>>>0)},[M,X]=/* @__PURE__ */(()=>N.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((t=>BigInt(t)))))(),_=/* @__PURE__ */new Uint32Array(80),V=/* @__PURE__ */new Uint32Array(80);class j extends w{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:e,Bh:s,Bl:i,Ch:n,Cl:h,Dh:r,Dl:o,Eh:c,El:a,Fh:f,Fl:d,Gh:l,Gl:u,Hh:b,Hl:x}=this;return[t,e,s,i,n,h,r,o,c,a,f,d,l,u,b,x]}set(t,e,s,i,n,h,r,o,c,a,f,d,l,u,b,x){this.Ah=0|t,this.Al=0|e,this.Bh=0|s,this.Bl=0|i,this.Ch=0|n,this.Cl=0|h,this.Dh=0|r,this.Dl=0|o,this.Eh=0|c,this.El=0|a,this.Fh=0|f,this.Fl=0|d,this.Gh=0|l,this.Gl=0|u,this.Hh=0|b,this.Hl=0|x}process(t,e){for(let s=0;s<16;s++,e+=4)_[s]=t.getUint32(e),V[s]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|_[t-15],s=0|V[t-15],i=N.rotrSH(e,s,1)^N.rotrSH(e,s,8)^N.shrSH(e,s,7),n=N.rotrSL(e,s,1)^N.rotrSL(e,s,8)^N.shrSL(e,s,7),h=0|_[t-2],r=0|V[t-2],o=N.rotrSH(h,r,19)^N.rotrBH(h,r,61)^N.shrSH(h,r,6),c=N.rotrSL(h,r,19)^N.rotrBL(h,r,61)^N.shrSL(h,r,6),a=N.add4L(n,c,V[t-7],V[t-16]),f=N.add4H(a,i,o,_[t-7],_[t-16]);_[t]=0|f,V[t]=0|a}let{Ah:s,Al:i,Bh:n,Bl:h,Ch:r,Cl:o,Dh:c,Dl:a,Eh:f,El:d,Fh:l,Fl:u,Gh:b,Gl:x,Hh:p,Hl:g}=this;for(let t=0;t<80;t++){const e=N.rotrSH(f,d,14)^N.rotrSH(f,d,18)^N.rotrBH(f,d,41),y=N.rotrSL(f,d,14)^N.rotrSL(f,d,18)^N.rotrBL(f,d,41),L=f&l^~f&b,w=d&u^~d&x,B=N.add5L(g,y,w,X[t],V[t]),H=N.add5H(B,p,e,L,M[t],_[t]),A=0|B,E=N.rotrSH(s,i,28)^N.rotrBH(s,i,34)^N.rotrBH(s,i,39),k=N.rotrSL(s,i,28)^N.rotrBL(s,i,34)^N.rotrBL(s,i,39),U=s&n^s&r^n&r,I=i&h^i&o^h&o;p=0|b,g=0|x,b=0|l,x=0|u,l=0|f,u=0|d,({h:f,l:d}=N.add(0|c,0|a,0|H,0|A)),c=0|r,a=0|o,r=0|n,o=0|h,n=0|s,h=0|i;const S=N.add3L(A,k,I);s=N.add3H(S,H,E,U),i=0|S}({h:s,l:i}=N.add(0|this.Ah,0|this.Al,0|s,0|i)),({h:n,l:h}=N.add(0|this.Bh,0|this.Bl,0|n,0|h)),({h:r,l:o}=N.add(0|this.Ch,0|this.Cl,0|r,0|o)),({h:c,l:a}=N.add(0|this.Dh,0|this.Dl,0|c,0|a)),({h:f,l:d}=N.add(0|this.Eh,0|this.El,0|f,0|d)),({h:l,l:u}=N.add(0|this.Fh,0|this.Fl,0|l,0|u)),({h:b,l:x}=N.add(0|this.Gh,0|this.Gl,0|b,0|x)),({h:p,l:g}=N.add(0|this.Hh,0|this.Hl,0|p,0|g)),this.set(s,i,n,h,r,o,c,a,f,d,l,u,b,x,p,g)}roundClean(){_.fill(0),V.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class R extends j{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const T=/* @__PURE__ */p((()=>new j)),$=/* @__PURE__ */p((()=>new R)),q=[],z=[],J=[],K=/* @__PURE__ */BigInt(0),P=/* @__PURE__ */BigInt(1),Q=/* @__PURE__ */BigInt(2),W=/* @__PURE__ */BigInt(7),Y=/* @__PURE__ */BigInt(256),Z=/* @__PURE__ */BigInt(113);for(let t=0,e=P,s=1,i=0;t<24;t++){[s,i]=[i,(2*s+3*i)%5],q.push(2*(5*i+s)),z.push((t+1)*(t+2)/2%64);let n=K;for(let t=0;t<7;t++)e=(e<>W)*Z)%Y,e&Q&&(n^=P<<(P<s>32?O(t,e,s):D(t,e,s),it=(t,e,s)=>s>32?v(t,e,s):G(t,e,s);class nt extends x{constructor(t,s,i,n=!1,h=24){if(super(),this.blockLen=t,this.suffix=s,this.outputLen=i,this.enableXOF=n,this.rounds=h,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,e(i),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");var r;this.state=new Uint8Array(200),this.state32=(r=this.state,new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)))}keccak(){f||d(this.state32),function(t,e=24){const s=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let e=0;e<10;e++)s[e]=t[e]^t[e+10]^t[e+20]^t[e+30]^t[e+40];for(let e=0;e<10;e+=2){const i=(e+8)%10,n=(e+2)%10,h=s[n],r=s[n+1],o=st(h,r,1)^s[i],c=it(h,r,1)^s[i+1];for(let s=0;s<50;s+=10)t[e+s]^=o,t[e+s+1]^=c}let e=t[2],n=t[3];for(let s=0;s<24;s++){const i=z[s],h=st(e,n,i),r=it(e,n,i),o=q[s];e=t[o],n=t[o+1],t[o]=h,t[o+1]=r}for(let e=0;e<50;e+=10){for(let i=0;i<10;i++)s[i]=t[e+i];for(let i=0;i<10;i++)t[e+i]^=~s[(i+2)%10]&s[(i+4)%10]}t[0]^=tt[i],t[1]^=et[i]}s.fill(0)}(this.state32,this.rounds),f||d(this.state32),this.posOut=0,this.pos=0}update(t){n(this);const{blockLen:e,state:s}=this,i=(t=u(t)).length;for(let n=0;n=i&&this.keccak();const h=Math.min(i-this.posOut,n-s);t.set(e.subarray(this.posOut,this.posOut+h),s),this.posOut+=h,s+=h}return t}xofInto(t){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return e(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(h(t,this),this.finished)throw Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:e,suffix:s,outputLen:i,rounds:n,enableXOF:h}=this;return t||(t=new nt(e,s,i,h,n)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=n,t.suffix=s,t.outputLen=i,t.enableXOF=h,t.destroyed=this.destroyed,t}}const ht=(t,e,s)=>p((()=>new nt(e,t,s))),rt=/* @__PURE__ */ht(6,136,32),ot=/* @__PURE__ */ht(6,72,64),ct=/* @__PURE__ */((t,e,s)=>function(t){const e=(e,s)=>t(s).update(u(e)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=e=>t(e),e}(((i={})=>new nt(e,t,void 0===i.dkLen?s:i.dkLen,!0))))(31,136,32);export{y as C,x as H,L as M,$ as a,s as b,b as c,T as d,n as e,ct as f,w as g,i as h,a as i,I as j,rt as k,ot as l,g as r,U as s,u as t,l as u,p as w}; +//# sourceMappingURL=sha3.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs.map new file mode 100644 index 000000000..710d0361c --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/sha3.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.min.mjs","sources":["../../node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/hashes/esm/crypto.js","../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_md.js","../../node_modules/@noble/hashes/esm/sha256.js","../../node_modules/@noble/hashes/esm/_u64.js","../../node_modules/@noble/hashes/esm/sha512.js","../../node_modules/@noble/hashes/esm/sha3.js"],"sourcesContent":["function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\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// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map"],"names":["number","n","Number","isSafeInteger","Error","bytes","b","lengths","a","Uint8Array","constructor","name","length","includes","hash","h","create","outputLen","blockLen","exists","instance","checkFinished","destroyed","finished","output","out","min","crypto","globalThis","undefined","createView","arr","DataView","buffer","byteOffset","byteLength","rotr","word","shift","rotl","isLE","Uint32Array","byteSwap32","i","utf8ToBytes","str","TextEncoder","encode","toBytes","data","abytes","concatBytes","arrays","sum","res","pad","set","Hash","clone","this","_cloneInto","wrapConstructor","hashCons","hashC","msg","update","digest","tmp","randomBytes","bytesLength","getRandomValues","Chi","c","Maj","HashMD","padOffset","super","pos","view","len","take","Math","subarray","process","dataView","roundClean","digestInto","fill","value","setBigUint64","_32n","BigInt","_u32_max","wh","wl","l","setUint32","oview","outLen","state","get","slice","destroy","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","B","C","D","E","F","G","H","offset","getUint32","W15","W2","s0","s1","T1","T2","SHA224","sha256","sha224","U32_MASK64","fromBig","le","split","lst","Ah","Al","rotlSH","s","rotlSL","rotlBH","rotlBL","u64","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","add","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","map","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","SHA384","sha512","sha384","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_0n","_1n","_2n","_7n","_256n","_0x71n","round","R","x","y","push","t","j","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","suffix","enableXOF","rounds","posOut","state32","floor","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","finish","writeInto","bufferOut","xofInto","xof","gen","sha3_256","sha3_512","shake256","opts","wrapXOFConstructorWithOpts","dkLen","genShake"],"mappings":";6GAAA,SAASA,EAAOC,GACZ,IAAKC,OAAOC,cAAcF,IAAMA,EAAI,EAChC,MAAUG,MAAM,kCAAkCH,EAC1D,CAUA,SAASI,EAAMC,KAAMC,GACjB,MALoBC,EAKPF,aAJQG,YACX,MAALD,GAA0B,iBAANA,GAAyC,eAAvBA,EAAEE,YAAYC,MAIrD,MAAUP,MAAM,uBANjB,IAAiBI,EAOpB,GAAID,EAAQK,OAAS,IAAML,EAAQM,SAASP,EAAEM,QAC1C,MAAUR,MAAM,iCAAiCG,oBAA0BD,EAAEM,SACrF,CACA,SAASE,EAAKC,GACV,GAAiB,mBAANA,GAAwC,mBAAbA,EAAEC,OACpC,MAAUZ,MAAM,mDACpBJ,EAAOe,EAAEE,WACTjB,EAAOe,EAAEG,SACb,CACA,SAASC,EAAOC,EAAUC,GAAgB,GACtC,GAAID,EAASE,UACT,MAAUlB,MAAM,oCACpB,GAAIiB,GAAiBD,EAASG,SAC1B,MAAUnB,MAAM,wCACxB,CACA,SAASoB,EAAOC,EAAKL,GACjBf,EAAMoB,GACN,MAAMC,EAAMN,EAASH,UACrB,GAAIQ,EAAIb,OAASc,EACb,MA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AG1B,IAAMlB,KAAKkB,IACd0B,EAAG6H,OAASzK,KAAKyK,OACjB7H,EAAGhF,SAAWoC,KAAKpC,SACnBgF,EAAG4H,OAASA,EAEZ5H,EAAG0H,OAASA,EACZ1H,EAAGtF,UAAYA,EACfsF,EAAG2H,UAAYA,EACf3H,EAAGjF,UAAYqC,KAAKrC,UACbiF,CACf,EAEA,MAAMgJ,GAAM,CAACtB,EAAQ/M,EAAUD,IAAc4C,GAAgB,IAAM,IAAImK,GAAO9M,EAAU+M,EAAQhN,KAMnFuO,kBAA2BD,GAAI,EAAM,IAAK,IAE1CE,kBAA2BF,GAAI,EAAM,GAAI,IAWzCG,kBAFI,EAACzB,EAAQ/M,EAAUD,ILzC7B,SAAoC6C,GACvC,MAAMC,EAAQ,CAACC,EAAK2L,IAAS7L,EAAS6L,GAAM1L,OAAOjB,EAAQgB,IAAME,SAC3DC,EAAML,EAAS,IAIrB,OAHAC,EAAM9C,UAAYkD,EAAIlD,UACtB8C,EAAM7C,SAAWiD,EAAIjD,SACrB6C,EAAM/C,OAAU2O,GAAS7L,EAAS6L,GAC3B5L,CACX,CKkCkD6L,EAA2B,CAACD,EAAO,CAAA,IAAO,IAAI3B,GAAO9M,EAAU+M,OAAuBpM,IAAf8N,EAAKE,MAAsB5O,EAAY0O,EAAKE,OAAO,KAEpIC,CAAS,GAAM,IAAK","x_google_ignoreList":[0,1,2,3,4,5,6,7]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/sha3.mjs b/app/node_modules/openpgp/dist/lightweight/sha3.mjs new file mode 100644 index 000000000..ae10d02b6 --- /dev/null +++ b/app/node_modules/openpgp/dist/lightweight/sha3.mjs @@ -0,0 +1,830 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +// copied from utils +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + bytes(data); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === 'function') { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto && typeof crypto.randomBytes === 'function') { + return crypto.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} + +/** + * Polyfill for Safari 14 + */ +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +/** + * Choice: a ? b : c + */ +const Chi = (a, b, c) => (a & b) ^ (~a & c); +/** + * Majority function, true if any two inputs is true + */ +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +const _2n = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); + +export { Chi as C, Hash as H, Maj as M, sha384 as a, bytes as b, concatBytes as c, sha512 as d, exists as e, shake256 as f, HashMD as g, hash as h, rotl as i, sha224 as j, sha3_256 as k, sha3_512 as l, randomBytes as r, sha256 as s, toBytes as t, utf8ToBytes as u, wrapConstructor as w }; diff --git a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs b/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs deleted file mode 100644 index 66d080272..000000000 --- a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs +++ /dev/null @@ -1,17 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+r+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}function r(t){if(!t)throw new TypeError("Assertion failed")}function n(){}function i(t){return"object"==typeof t&&null!==t||"function"==typeof t}function o(t){if("function"!=typeof t)return!1;var e=!1;try{new t({start:function(){e=!0}})}catch(t){}return e}function a(t){return!!i(t)&&"function"==typeof t.getReader}function s(t){return!!i(t)&&"function"==typeof t.getWriter}function u(t){return!!i(t)&&(!!a(t.readable)&&!!s(t.writable))}function d(t){try{return t.getReader({mode:"byob"}).releaseLock(),!0}catch(t){return!1}}function h(t){r(function(t){return!!o(t)&&!!a(new t)}(t));var e=function(t){try{return new t({type:"bytes"}),!0}catch(t){return!1}}(t);return function(r,n){var i=(void 0===n?{}:n).type;if("bytes"!==(i=f(i))||e||(i=void 0),r.constructor===t&&("bytes"!==i||d(r)))return r;if("bytes"===i){var o=c(r,{type:i});return new t(o)}o=c(r);return new t(o)}}function c(t,e){var n=(void 0===e?{}:e).type;return r(a(t)),r(!1===t.locked),"bytes"===(n=f(n))?new y(t):new _(t)}function f(t){var e=t+"";if("bytes"===e)return e;if(void 0===t)return t;throw new RangeError("Invalid type is specified")}var l=function(){function t(t){this._underlyingReader=void 0,this._readerMode=void 0,this._readableStreamController=void 0,this._pendingRead=void 0,this._underlyingStream=t,this._attachDefaultReader()}return t.prototype.start=function(t){this._readableStreamController=t},t.prototype.cancel=function(t){return r(void 0!==this._underlyingReader),this._underlyingReader.cancel(t)},t.prototype._attachDefaultReader=function(){if("default"!==this._readerMode){this._detachReader();var t=this._underlyingStream.getReader();this._readerMode="default",this._attachReader(t)}},t.prototype._attachReader=function(t){var e=this;r(void 0===this._underlyingReader),this._underlyingReader=t;var i=this._underlyingReader.closed;i&&i.then((function(){return e._finishPendingRead()})).then((function(){t===e._underlyingReader&&e._readableStreamController.close()}),(function(r){t===e._underlyingReader&&e._readableStreamController.error(r)})).catch(n)},t.prototype._detachReader=function(){void 0!==this._underlyingReader&&(this._underlyingReader.releaseLock(),this._underlyingReader=void 0,this._readerMode=void 0)},t.prototype._pullWithDefaultReader=function(){var t=this;this._attachDefaultReader();var e=this._underlyingReader.read().then((function(e){var r=t._readableStreamController;e.done?t._tryClose():r.enqueue(e.value)}));return this._setPendingRead(e),e},t.prototype._tryClose=function(){try{this._readableStreamController.close()}catch(t){}},t.prototype._setPendingRead=function(t){var e,r=this,n=function(){r._pendingRead===e&&(r._pendingRead=void 0)};this._pendingRead=e=t.then(n,n)},t.prototype._finishPendingRead=function(){var t=this;if(this._pendingRead){var e=function(){return t._finishPendingRead()};return this._pendingRead.then(e,e)}},t}(),_=function(t){function r(){return null!==t&&t.apply(this,arguments)||this}return e(r,t),r.prototype.pull=function(){return this._pullWithDefaultReader()},r}(l);function p(t){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}var y=function(t){function n(e){var r=this,n=d(e);return(r=t.call(this,e)||this)._supportsByob=n,r}return e(n,t),Object.defineProperty(n.prototype,"type",{get:function(){return"bytes"},enumerable:!1,configurable:!0}),n.prototype._attachByobReader=function(){if("byob"!==this._readerMode){r(this._supportsByob),this._detachReader();var t=this._underlyingStream.getReader({mode:"byob"});this._readerMode="byob",this._attachReader(t)}},n.prototype.pull=function(){if(this._supportsByob){var t=this._readableStreamController.byobRequest;if(t)return this._pullWithByobRequest(t)}return this._pullWithDefaultReader()},n.prototype._pullWithByobRequest=function(t){var e=this;this._attachByobReader();var r=new Uint8Array(t.view.byteLength),n=this._underlyingReader.read(r).then((function(r){var n,i,o;e._readableStreamController,r.done?(e._tryClose(),t.respond(0)):(n=r.value,i=t.view,o=p(n),p(i).set(o,0),t.respond(r.value.byteLength))}));return this._setPendingRead(n),n},n}(l);function v(t){return r(function(t){return!!o(t)&&!!s(new t)}(t)),function(e){if(e.constructor===t)return e;var r=g(e);return new t(r)}}function g(t){r(s(t)),r(!1===t.locked);var e=t.getWriter();return new b(e)}var b=function(){function t(t){var e=this;this._writableStreamController=void 0,this._pendingWrite=void 0,this._state="writable",this._storedError=void 0,this._underlyingWriter=t,this._errorPromise=new Promise((function(t,r){e._errorPromiseReject=r})),this._errorPromise.catch(n)}return t.prototype.start=function(t){var e=this;this._writableStreamController=t,this._underlyingWriter.closed.then((function(){e._state="closed"})).catch((function(t){return e._finishErroring(t)}))},t.prototype.write=function(t){var e=this,r=this._underlyingWriter;if(null===r.desiredSize)return r.ready;var n=r.write(t);n.catch((function(t){return e._finishErroring(t)})),r.ready.catch((function(t){return e._startErroring(t)}));var i=Promise.race([n,this._errorPromise]);return this._setPendingWrite(i),i},t.prototype.close=function(){var t=this;return void 0===this._pendingWrite?this._underlyingWriter.close():this._finishPendingWrite().then((function(){return t.close()}))},t.prototype.abort=function(t){if("errored"!==this._state)return this._underlyingWriter.abort(t)},t.prototype._setPendingWrite=function(t){var e,r=this,n=function(){r._pendingWrite===e&&(r._pendingWrite=void 0)};this._pendingWrite=e=t.then(n,n)},t.prototype._finishPendingWrite=function(){var t=this;if(void 0===this._pendingWrite)return Promise.resolve();var e=function(){return t._finishPendingWrite()};return this._pendingWrite.then(e,e)},t.prototype._startErroring=function(t){var e=this;if("writable"===this._state){this._state="erroring",this._storedError=t;var r=function(){return e._finishErroring(t)};void 0===this._pendingWrite?r():this._finishPendingWrite().then(r,r),this._writableStreamController.error(t)}},t.prototype._finishErroring=function(t){"writable"===this._state&&this._startErroring(t),"erroring"===this._state&&(this._state="errored",this._errorPromiseReject(this._storedError))},t}();function R(t){return r(function(t){return!!o(t)&&!!u(new t)}(t)),function(e){if(e.constructor===t)return e;var r=w(e);return new t(r)}}function w(t){r(u(t));var e=t.readable,n=t.writable;r(!1===e.locked),r(!1===n.locked);var i,o=e.getReader();try{i=n.getWriter()}catch(t){throw o.releaseLock(),t}return new m(o,i)}var m=function(){function t(t,e){var r=this;this._transformStreamController=void 0,this._onRead=function(t){if(!t.done)return r._transformStreamController.enqueue(t.value),r._reader.read().then(r._onRead)},this._onError=function(t){r._flushReject(t),r._transformStreamController.error(t),r._reader.cancel(t).catch(n),r._writer.abort(t).catch(n)},this._onTerminate=function(){r._flushResolve(),r._transformStreamController.terminate();var t=new TypeError("TransformStream terminated");r._writer.abort(t).catch(n)},this._reader=t,this._writer=e,this._flushPromise=new Promise((function(t,e){r._flushResolve=t,r._flushReject=e}))}return t.prototype.start=function(t){this._transformStreamController=t,this._reader.read().then(this._onRead).then(this._onTerminate,this._onError);var e=this._reader.closed;e&&e.then(this._onTerminate,this._onError)},t.prototype.transform=function(t){return this._writer.write(t)},t.prototype.flush=function(){var t=this;return this._writer.close().then((function(){return t._flushPromise}))},t}();export{h as createReadableStreamWrapper,R as createTransformStreamWrapper,c as createWrappingReadableSource,w as createWrappingTransformer,g as createWrappingWritableSink,v as createWritableStreamWrapper}; -//# sourceMappingURL=web-streams-adapter.min.mjs.map diff --git a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs.map b/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs.map deleted file mode 100644 index f21dd2b49..000000000 --- a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.min.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"web-streams-adapter.min.mjs","sources":["../../node_modules/@mattiasbuelens/web-streams-adapter/dist/web-streams-adapter.mjs"],"sourcesContent":["/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nfunction assert(test) {\n if (!test) {\n throw new TypeError('Assertion failed');\n }\n}\n\nfunction noop() {\n return;\n}\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nfunction isStreamConstructor(ctor) {\n if (typeof ctor !== 'function') {\n return false;\n }\n var startCalled = false;\n try {\n new ctor({\n start: function () {\n startCalled = true;\n }\n });\n }\n catch (e) {\n // ignore\n }\n return startCalled;\n}\nfunction isReadableStream(readable) {\n if (!typeIsObject(readable)) {\n return false;\n }\n if (typeof readable.getReader !== 'function') {\n return false;\n }\n return true;\n}\nfunction isReadableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isReadableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isWritableStream(writable) {\n if (!typeIsObject(writable)) {\n return false;\n }\n if (typeof writable.getWriter !== 'function') {\n return false;\n }\n return true;\n}\nfunction isWritableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isWritableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isTransformStream(transform) {\n if (!typeIsObject(transform)) {\n return false;\n }\n if (!isReadableStream(transform.readable)) {\n return false;\n }\n if (!isWritableStream(transform.writable)) {\n return false;\n }\n return true;\n}\nfunction isTransformStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isTransformStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction supportsByobReader(readable) {\n try {\n var reader = readable.getReader({ mode: 'byob' });\n reader.releaseLock();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction supportsByteSource(ctor) {\n try {\n new ctor({ type: 'bytes' });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\nfunction createReadableStreamWrapper(ctor) {\n assert(isReadableStreamConstructor(ctor));\n var byteSourceSupported = supportsByteSource(ctor);\n return function (readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n type = parseReadableType(type);\n if (type === 'bytes' && !byteSourceSupported) {\n type = undefined;\n }\n if (readable.constructor === ctor) {\n if (type !== 'bytes' || supportsByobReader(readable)) {\n return readable;\n }\n }\n if (type === 'bytes') {\n var source = createWrappingReadableSource(readable, { type: type });\n return new ctor(source);\n }\n else {\n var source = createWrappingReadableSource(readable);\n return new ctor(source);\n }\n };\n}\nfunction createWrappingReadableSource(readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n assert(isReadableStream(readable));\n assert(readable.locked === false);\n type = parseReadableType(type);\n var source;\n if (type === 'bytes') {\n source = new WrappingReadableByteStreamSource(readable);\n }\n else {\n source = new WrappingReadableStreamDefaultSource(readable);\n }\n return source;\n}\nfunction parseReadableType(type) {\n var typeString = String(type);\n if (typeString === 'bytes') {\n return typeString;\n }\n else if (type === undefined) {\n return type;\n }\n else {\n throw new RangeError('Invalid type is specified');\n }\n}\nvar AbstractWrappingReadableStreamSource = /** @class */ (function () {\n function AbstractWrappingReadableStreamSource(underlyingStream) {\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n this._readableStreamController = undefined;\n this._pendingRead = undefined;\n this._underlyingStream = underlyingStream;\n // always keep a reader attached to detect close/error\n this._attachDefaultReader();\n }\n AbstractWrappingReadableStreamSource.prototype.start = function (controller) {\n this._readableStreamController = controller;\n };\n AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {\n assert(this._underlyingReader !== undefined);\n return this._underlyingReader.cancel(reason);\n };\n AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {\n if (this._readerMode === \"default\" /* DEFAULT */) {\n return;\n }\n this._detachReader();\n var reader = this._underlyingStream.getReader();\n this._readerMode = \"default\" /* DEFAULT */;\n this._attachReader(reader);\n };\n AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {\n var _this = this;\n assert(this._underlyingReader === undefined);\n this._underlyingReader = reader;\n var closed = this._underlyingReader.closed;\n if (!closed) {\n return;\n }\n closed\n .then(function () { return _this._finishPendingRead(); })\n .then(function () {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.close();\n }\n }, function (reason) {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.error(reason);\n }\n })\n .catch(noop);\n };\n AbstractWrappingReadableStreamSource.prototype._detachReader = function () {\n if (this._underlyingReader === undefined) {\n return;\n }\n this._underlyingReader.releaseLock();\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n };\n AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {\n var _this = this;\n this._attachDefaultReader();\n // TODO Backpressure?\n var read = this._underlyingReader.read()\n .then(function (result) {\n var controller = _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n }\n else {\n controller.enqueue(result.value);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n AbstractWrappingReadableStreamSource.prototype._tryClose = function () {\n try {\n this._readableStreamController.close();\n }\n catch (_a) {\n // already errored or closed\n }\n };\n AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {\n var _this = this;\n var pendingRead;\n var finishRead = function () {\n if (_this._pendingRead === pendingRead) {\n _this._pendingRead = undefined;\n }\n };\n this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);\n };\n AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {\n var _this = this;\n if (!this._pendingRead) {\n return undefined;\n }\n var afterRead = function () { return _this._finishPendingRead(); };\n return this._pendingRead.then(afterRead, afterRead);\n };\n return AbstractWrappingReadableStreamSource;\n}());\nvar WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {\n __extends(WrappingReadableStreamDefaultSource, _super);\n function WrappingReadableStreamDefaultSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WrappingReadableStreamDefaultSource.prototype.pull = function () {\n return this._pullWithDefaultReader();\n };\n return WrappingReadableStreamDefaultSource;\n}(AbstractWrappingReadableStreamSource));\nfunction toUint8Array(view) {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\nfunction copyArrayBufferView(from, to) {\n var fromArray = toUint8Array(from);\n var toArray = toUint8Array(to);\n toArray.set(fromArray, 0);\n}\nvar WrappingReadableByteStreamSource = /** @class */ (function (_super) {\n __extends(WrappingReadableByteStreamSource, _super);\n function WrappingReadableByteStreamSource(underlyingStream) {\n var _this = this;\n var supportsByob = supportsByobReader(underlyingStream);\n _this = _super.call(this, underlyingStream) || this;\n _this._supportsByob = supportsByob;\n return _this;\n }\n Object.defineProperty(WrappingReadableByteStreamSource.prototype, \"type\", {\n get: function () {\n return 'bytes';\n },\n enumerable: false,\n configurable: true\n });\n WrappingReadableByteStreamSource.prototype._attachByobReader = function () {\n if (this._readerMode === \"byob\" /* BYOB */) {\n return;\n }\n assert(this._supportsByob);\n this._detachReader();\n var reader = this._underlyingStream.getReader({ mode: 'byob' });\n this._readerMode = \"byob\" /* BYOB */;\n this._attachReader(reader);\n };\n WrappingReadableByteStreamSource.prototype.pull = function () {\n if (this._supportsByob) {\n var byobRequest = this._readableStreamController.byobRequest;\n if (byobRequest) {\n return this._pullWithByobRequest(byobRequest);\n }\n }\n return this._pullWithDefaultReader();\n };\n WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {\n var _this = this;\n this._attachByobReader();\n // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly\n // create a separate buffer to read into, then copy that to byobRequest.view\n var buffer = new Uint8Array(byobRequest.view.byteLength);\n // TODO Backpressure?\n var read = this._underlyingReader.read(buffer)\n .then(function (result) {\n _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n byobRequest.respond(0);\n }\n else {\n copyArrayBufferView(result.value, byobRequest.view);\n byobRequest.respond(result.value.byteLength);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n return WrappingReadableByteStreamSource;\n}(AbstractWrappingReadableStreamSource));\n\nfunction createWritableStreamWrapper(ctor) {\n assert(isWritableStreamConstructor(ctor));\n return function (writable) {\n if (writable.constructor === ctor) {\n return writable;\n }\n var sink = createWrappingWritableSink(writable);\n return new ctor(sink);\n };\n}\nfunction createWrappingWritableSink(writable) {\n assert(isWritableStream(writable));\n assert(writable.locked === false);\n var writer = writable.getWriter();\n return new WrappingWritableStreamSink(writer);\n}\nvar WrappingWritableStreamSink = /** @class */ (function () {\n function WrappingWritableStreamSink(underlyingWriter) {\n var _this = this;\n this._writableStreamController = undefined;\n this._pendingWrite = undefined;\n this._state = \"writable\" /* WRITABLE */;\n this._storedError = undefined;\n this._underlyingWriter = underlyingWriter;\n this._errorPromise = new Promise(function (resolve, reject) {\n _this._errorPromiseReject = reject;\n });\n this._errorPromise.catch(noop);\n }\n WrappingWritableStreamSink.prototype.start = function (controller) {\n var _this = this;\n this._writableStreamController = controller;\n this._underlyingWriter.closed\n .then(function () {\n _this._state = \"closed\" /* CLOSED */;\n })\n .catch(function (reason) { return _this._finishErroring(reason); });\n };\n WrappingWritableStreamSink.prototype.write = function (chunk) {\n var _this = this;\n var writer = this._underlyingWriter;\n // Detect past errors\n if (writer.desiredSize === null) {\n return writer.ready;\n }\n var writeRequest = writer.write(chunk);\n // Detect future errors\n writeRequest.catch(function (reason) { return _this._finishErroring(reason); });\n writer.ready.catch(function (reason) { return _this._startErroring(reason); });\n // Reject write when errored\n var write = Promise.race([writeRequest, this._errorPromise]);\n this._setPendingWrite(write);\n return write;\n };\n WrappingWritableStreamSink.prototype.close = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return this._underlyingWriter.close();\n }\n return this._finishPendingWrite().then(function () { return _this.close(); });\n };\n WrappingWritableStreamSink.prototype.abort = function (reason) {\n if (this._state === \"errored\" /* ERRORED */) {\n return undefined;\n }\n var writer = this._underlyingWriter;\n return writer.abort(reason);\n };\n WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {\n var _this = this;\n var pendingWrite;\n var finishWrite = function () {\n if (_this._pendingWrite === pendingWrite) {\n _this._pendingWrite = undefined;\n }\n };\n this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);\n };\n WrappingWritableStreamSink.prototype._finishPendingWrite = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return Promise.resolve();\n }\n var afterWrite = function () { return _this._finishPendingWrite(); };\n return this._pendingWrite.then(afterWrite, afterWrite);\n };\n WrappingWritableStreamSink.prototype._startErroring = function (reason) {\n var _this = this;\n if (this._state === \"writable\" /* WRITABLE */) {\n this._state = \"erroring\" /* ERRORING */;\n this._storedError = reason;\n var afterWrite = function () { return _this._finishErroring(reason); };\n if (this._pendingWrite === undefined) {\n afterWrite();\n }\n else {\n this._finishPendingWrite().then(afterWrite, afterWrite);\n }\n this._writableStreamController.error(reason);\n }\n };\n WrappingWritableStreamSink.prototype._finishErroring = function (reason) {\n if (this._state === \"writable\" /* WRITABLE */) {\n this._startErroring(reason);\n }\n if (this._state === \"erroring\" /* ERRORING */) {\n this._state = \"errored\" /* ERRORED */;\n this._errorPromiseReject(this._storedError);\n }\n };\n return WrappingWritableStreamSink;\n}());\n\nfunction createTransformStreamWrapper(ctor) {\n assert(isTransformStreamConstructor(ctor));\n return function (transform) {\n if (transform.constructor === ctor) {\n return transform;\n }\n var transformer = createWrappingTransformer(transform);\n return new ctor(transformer);\n };\n}\nfunction createWrappingTransformer(transform) {\n assert(isTransformStream(transform));\n var readable = transform.readable, writable = transform.writable;\n assert(readable.locked === false);\n assert(writable.locked === false);\n var reader = readable.getReader();\n var writer;\n try {\n writer = writable.getWriter();\n }\n catch (e) {\n reader.releaseLock(); // do not leak reader\n throw e;\n }\n return new WrappingTransformStreamTransformer(reader, writer);\n}\nvar WrappingTransformStreamTransformer = /** @class */ (function () {\n function WrappingTransformStreamTransformer(reader, writer) {\n var _this = this;\n this._transformStreamController = undefined;\n this._onRead = function (result) {\n if (result.done) {\n return;\n }\n _this._transformStreamController.enqueue(result.value);\n return _this._reader.read().then(_this._onRead);\n };\n this._onError = function (reason) {\n _this._flushReject(reason);\n _this._transformStreamController.error(reason);\n _this._reader.cancel(reason).catch(noop);\n _this._writer.abort(reason).catch(noop);\n };\n this._onTerminate = function () {\n _this._flushResolve();\n _this._transformStreamController.terminate();\n var error = new TypeError('TransformStream terminated');\n _this._writer.abort(error).catch(noop);\n };\n this._reader = reader;\n this._writer = writer;\n this._flushPromise = new Promise(function (resolve, reject) {\n _this._flushResolve = resolve;\n _this._flushReject = reject;\n });\n }\n WrappingTransformStreamTransformer.prototype.start = function (controller) {\n this._transformStreamController = controller;\n this._reader.read()\n .then(this._onRead)\n .then(this._onTerminate, this._onError);\n var readerClosed = this._reader.closed;\n if (readerClosed) {\n readerClosed\n .then(this._onTerminate, this._onError);\n }\n };\n WrappingTransformStreamTransformer.prototype.transform = function (chunk) {\n return this._writer.write(chunk);\n };\n WrappingTransformStreamTransformer.prototype.flush = function () {\n var _this = this;\n return this._writer.close()\n .then(function () { return _this._flushPromise; });\n };\n return WrappingTransformStreamTransformer;\n}());\n\nexport { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper };\n//# sourceMappingURL=web-streams-adapter.mjs.map\n"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","prototype","hasOwnProperty","call","__extends","TypeError","__","this","constructor","create","assert","test","noop","typeIsObject","x","isStreamConstructor","ctor","startCalled","start","e","isReadableStream","readable","getReader","isWritableStream","writable","getWriter","isTransformStream","transform","supportsByobReader","mode","releaseLock","_a","createReadableStreamWrapper","isReadableStreamConstructor","byteSourceSupported","type","supportsByteSource","parseReadableType","undefined","source","createWrappingReadableSource","locked","WrappingReadableByteStreamSource","WrappingReadableStreamDefaultSource","typeString","String","RangeError","AbstractWrappingReadableStreamSource","underlyingStream","_underlyingReader","_readerMode","_readableStreamController","_pendingRead","_underlyingStream","_attachDefaultReader","controller","cancel","reason","_detachReader","reader","_attachReader","_this","closed","then","_finishPendingRead","close","error","catch","_pullWithDefaultReader","read","result","done","_tryClose","enqueue","value","_setPendingRead","readPromise","pendingRead","finishRead","afterRead","_super","apply","arguments","pull","toUint8Array","view","Uint8Array","buffer","byteOffset","byteLength","supportsByob","_supportsByob","defineProperty","get","enumerable","configurable","_attachByobReader","byobRequest","_pullWithByobRequest","from","to","fromArray","respond","set","createWritableStreamWrapper","isWritableStreamConstructor","sink","createWrappingWritableSink","writer","WrappingWritableStreamSink","underlyingWriter","_writableStreamController","_pendingWrite","_state","_storedError","_underlyingWriter","_errorPromise","Promise","resolve","reject","_errorPromiseReject","_finishErroring","write","chunk","desiredSize","ready","writeRequest","_startErroring","race","_setPendingWrite","_finishPendingWrite","abort","writePromise","pendingWrite","finishWrite","afterWrite","createTransformStreamWrapper","isTransformStreamConstructor","transformer","createWrappingTransformer","WrappingTransformStreamTransformer","_transformStreamController","_onRead","_reader","_onError","_flushReject","_writer","_onTerminate","_flushResolve","terminate","_flushPromise","readerClosed","flush"],"mappings":";;;;;;;;;;;;;;;gFAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOC,OAAOK,UAAUC,eAAeC,KAAKR,EAAGK,KAAIN,EAAEM,GAAKL,EAAEK,KACzFP,EAAcC,EAAGC,EAC5B,EAEA,SAASS,EAAUV,EAAGC,GAClB,GAAiB,mBAANA,GAA0B,OAANA,EAC3B,MAAM,IAAIU,UAAU,uBAAgCV,EAAK,iCAE7D,SAASW,IAAOC,KAAKC,YAAcd,EADnCD,EAAcC,EAAGC,GAEjBD,EAAEO,UAAkB,OAANN,EAAaC,OAAOa,OAAOd,IAAMW,EAAGL,UAAYN,EAAEM,UAAW,IAAIK,EACnF,CAEA,SAASI,EAAOC,GACZ,IAAKA,EACD,MAAM,IAAIN,UAAU,mBAE5B,CAEA,SAASO,IAET,CACA,SAASC,EAAaC,GAClB,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CAC3D,CAEA,SAASC,EAAoBC,GACzB,GAAoB,mBAATA,EACP,OAAO,EAEX,IAAIC,GAAc,EAClB,IACI,IAAID,EAAK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AAIO,EAAehJ,KAAKwI,QAAQjF,OAC5ByF,GACAA,EACKxF,KAAKxD,KAAK4I,aAAc5I,KAAKyI,WAG1CJ,EAAmC3I,UAAU0B,UAAY,SAAUgG,GAC/D,OAAOpH,KAAK2I,QAAQxB,MAAMC,IAE9BiB,EAAmC3I,UAAUuJ,MAAQ,WACjD,IAAI3F,EAAQtD,KACZ,OAAOA,KAAK2I,QAAQjF,QACfF,MAAK,WAAc,OAAOF,EAAMyF,kBAElCV,CACX"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.mjs b/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.mjs deleted file mode 100644 index 2bc2a8091..000000000 --- a/app/node_modules/openpgp/dist/lightweight/web-streams-adapter.mjs +++ /dev/null @@ -1,561 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -function assert(test) { - if (!test) { - throw new TypeError('Assertion failed'); - } -} - -function noop() { - return; -} -function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} - -function isStreamConstructor(ctor) { - if (typeof ctor !== 'function') { - return false; - } - var startCalled = false; - try { - new ctor({ - start: function () { - startCalled = true; - } - }); - } - catch (e) { - // ignore - } - return startCalled; -} -function isReadableStream(readable) { - if (!typeIsObject(readable)) { - return false; - } - if (typeof readable.getReader !== 'function') { - return false; - } - return true; -} -function isReadableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isReadableStream(new ctor())) { - return false; - } - return true; -} -function isWritableStream(writable) { - if (!typeIsObject(writable)) { - return false; - } - if (typeof writable.getWriter !== 'function') { - return false; - } - return true; -} -function isWritableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isWritableStream(new ctor())) { - return false; - } - return true; -} -function isTransformStream(transform) { - if (!typeIsObject(transform)) { - return false; - } - if (!isReadableStream(transform.readable)) { - return false; - } - if (!isWritableStream(transform.writable)) { - return false; - } - return true; -} -function isTransformStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isTransformStream(new ctor())) { - return false; - } - return true; -} -function supportsByobReader(readable) { - try { - var reader = readable.getReader({ mode: 'byob' }); - reader.releaseLock(); - return true; - } - catch (_a) { - return false; - } -} -function supportsByteSource(ctor) { - try { - new ctor({ type: 'bytes' }); - return true; - } - catch (_a) { - return false; - } -} - -function createReadableStreamWrapper(ctor) { - assert(isReadableStreamConstructor(ctor)); - var byteSourceSupported = supportsByteSource(ctor); - return function (readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - type = parseReadableType(type); - if (type === 'bytes' && !byteSourceSupported) { - type = undefined; - } - if (readable.constructor === ctor) { - if (type !== 'bytes' || supportsByobReader(readable)) { - return readable; - } - } - if (type === 'bytes') { - var source = createWrappingReadableSource(readable, { type: type }); - return new ctor(source); - } - else { - var source = createWrappingReadableSource(readable); - return new ctor(source); - } - }; -} -function createWrappingReadableSource(readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - assert(isReadableStream(readable)); - assert(readable.locked === false); - type = parseReadableType(type); - var source; - if (type === 'bytes') { - source = new WrappingReadableByteStreamSource(readable); - } - else { - source = new WrappingReadableStreamDefaultSource(readable); - } - return source; -} -function parseReadableType(type) { - var typeString = String(type); - if (typeString === 'bytes') { - return typeString; - } - else if (type === undefined) { - return type; - } - else { - throw new RangeError('Invalid type is specified'); - } -} -var AbstractWrappingReadableStreamSource = /** @class */ (function () { - function AbstractWrappingReadableStreamSource(underlyingStream) { - this._underlyingReader = undefined; - this._readerMode = undefined; - this._readableStreamController = undefined; - this._pendingRead = undefined; - this._underlyingStream = underlyingStream; - // always keep a reader attached to detect close/error - this._attachDefaultReader(); - } - AbstractWrappingReadableStreamSource.prototype.start = function (controller) { - this._readableStreamController = controller; - }; - AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) { - assert(this._underlyingReader !== undefined); - return this._underlyingReader.cancel(reason); - }; - AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () { - if (this._readerMode === "default" /* DEFAULT */) { - return; - } - this._detachReader(); - var reader = this._underlyingStream.getReader(); - this._readerMode = "default" /* DEFAULT */; - this._attachReader(reader); - }; - AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) { - var _this = this; - assert(this._underlyingReader === undefined); - this._underlyingReader = reader; - var closed = this._underlyingReader.closed; - if (!closed) { - return; - } - closed - .then(function () { return _this._finishPendingRead(); }) - .then(function () { - if (reader === _this._underlyingReader) { - _this._readableStreamController.close(); - } - }, function (reason) { - if (reader === _this._underlyingReader) { - _this._readableStreamController.error(reason); - } - }) - .catch(noop); - }; - AbstractWrappingReadableStreamSource.prototype._detachReader = function () { - if (this._underlyingReader === undefined) { - return; - } - this._underlyingReader.releaseLock(); - this._underlyingReader = undefined; - this._readerMode = undefined; - }; - AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () { - var _this = this; - this._attachDefaultReader(); - // TODO Backpressure? - var read = this._underlyingReader.read() - .then(function (result) { - var controller = _this._readableStreamController; - if (result.done) { - _this._tryClose(); - } - else { - controller.enqueue(result.value); - } - }); - this._setPendingRead(read); - return read; - }; - AbstractWrappingReadableStreamSource.prototype._tryClose = function () { - try { - this._readableStreamController.close(); - } - catch (_a) { - // already errored or closed - } - }; - AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) { - var _this = this; - var pendingRead; - var finishRead = function () { - if (_this._pendingRead === pendingRead) { - _this._pendingRead = undefined; - } - }; - this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead); - }; - AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () { - var _this = this; - if (!this._pendingRead) { - return undefined; - } - var afterRead = function () { return _this._finishPendingRead(); }; - return this._pendingRead.then(afterRead, afterRead); - }; - return AbstractWrappingReadableStreamSource; -}()); -var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) { - __extends(WrappingReadableStreamDefaultSource, _super); - function WrappingReadableStreamDefaultSource() { - return _super !== null && _super.apply(this, arguments) || this; - } - WrappingReadableStreamDefaultSource.prototype.pull = function () { - return this._pullWithDefaultReader(); - }; - return WrappingReadableStreamDefaultSource; -}(AbstractWrappingReadableStreamSource)); -function toUint8Array(view) { - return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); -} -function copyArrayBufferView(from, to) { - var fromArray = toUint8Array(from); - var toArray = toUint8Array(to); - toArray.set(fromArray, 0); -} -var WrappingReadableByteStreamSource = /** @class */ (function (_super) { - __extends(WrappingReadableByteStreamSource, _super); - function WrappingReadableByteStreamSource(underlyingStream) { - var _this = this; - var supportsByob = supportsByobReader(underlyingStream); - _this = _super.call(this, underlyingStream) || this; - _this._supportsByob = supportsByob; - return _this; - } - Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", { - get: function () { - return 'bytes'; - }, - enumerable: false, - configurable: true - }); - WrappingReadableByteStreamSource.prototype._attachByobReader = function () { - if (this._readerMode === "byob" /* BYOB */) { - return; - } - assert(this._supportsByob); - this._detachReader(); - var reader = this._underlyingStream.getReader({ mode: 'byob' }); - this._readerMode = "byob" /* BYOB */; - this._attachReader(reader); - }; - WrappingReadableByteStreamSource.prototype.pull = function () { - if (this._supportsByob) { - var byobRequest = this._readableStreamController.byobRequest; - if (byobRequest) { - return this._pullWithByobRequest(byobRequest); - } - } - return this._pullWithDefaultReader(); - }; - WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) { - var _this = this; - this._attachByobReader(); - // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly - // create a separate buffer to read into, then copy that to byobRequest.view - var buffer = new Uint8Array(byobRequest.view.byteLength); - // TODO Backpressure? - var read = this._underlyingReader.read(buffer) - .then(function (result) { - _this._readableStreamController; - if (result.done) { - _this._tryClose(); - byobRequest.respond(0); - } - else { - copyArrayBufferView(result.value, byobRequest.view); - byobRequest.respond(result.value.byteLength); - } - }); - this._setPendingRead(read); - return read; - }; - return WrappingReadableByteStreamSource; -}(AbstractWrappingReadableStreamSource)); - -function createWritableStreamWrapper(ctor) { - assert(isWritableStreamConstructor(ctor)); - return function (writable) { - if (writable.constructor === ctor) { - return writable; - } - var sink = createWrappingWritableSink(writable); - return new ctor(sink); - }; -} -function createWrappingWritableSink(writable) { - assert(isWritableStream(writable)); - assert(writable.locked === false); - var writer = writable.getWriter(); - return new WrappingWritableStreamSink(writer); -} -var WrappingWritableStreamSink = /** @class */ (function () { - function WrappingWritableStreamSink(underlyingWriter) { - var _this = this; - this._writableStreamController = undefined; - this._pendingWrite = undefined; - this._state = "writable" /* WRITABLE */; - this._storedError = undefined; - this._underlyingWriter = underlyingWriter; - this._errorPromise = new Promise(function (resolve, reject) { - _this._errorPromiseReject = reject; - }); - this._errorPromise.catch(noop); - } - WrappingWritableStreamSink.prototype.start = function (controller) { - var _this = this; - this._writableStreamController = controller; - this._underlyingWriter.closed - .then(function () { - _this._state = "closed" /* CLOSED */; - }) - .catch(function (reason) { return _this._finishErroring(reason); }); - }; - WrappingWritableStreamSink.prototype.write = function (chunk) { - var _this = this; - var writer = this._underlyingWriter; - // Detect past errors - if (writer.desiredSize === null) { - return writer.ready; - } - var writeRequest = writer.write(chunk); - // Detect future errors - writeRequest.catch(function (reason) { return _this._finishErroring(reason); }); - writer.ready.catch(function (reason) { return _this._startErroring(reason); }); - // Reject write when errored - var write = Promise.race([writeRequest, this._errorPromise]); - this._setPendingWrite(write); - return write; - }; - WrappingWritableStreamSink.prototype.close = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return this._underlyingWriter.close(); - } - return this._finishPendingWrite().then(function () { return _this.close(); }); - }; - WrappingWritableStreamSink.prototype.abort = function (reason) { - if (this._state === "errored" /* ERRORED */) { - return undefined; - } - var writer = this._underlyingWriter; - return writer.abort(reason); - }; - WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) { - var _this = this; - var pendingWrite; - var finishWrite = function () { - if (_this._pendingWrite === pendingWrite) { - _this._pendingWrite = undefined; - } - }; - this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite); - }; - WrappingWritableStreamSink.prototype._finishPendingWrite = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return Promise.resolve(); - } - var afterWrite = function () { return _this._finishPendingWrite(); }; - return this._pendingWrite.then(afterWrite, afterWrite); - }; - WrappingWritableStreamSink.prototype._startErroring = function (reason) { - var _this = this; - if (this._state === "writable" /* WRITABLE */) { - this._state = "erroring" /* ERRORING */; - this._storedError = reason; - var afterWrite = function () { return _this._finishErroring(reason); }; - if (this._pendingWrite === undefined) { - afterWrite(); - } - else { - this._finishPendingWrite().then(afterWrite, afterWrite); - } - this._writableStreamController.error(reason); - } - }; - WrappingWritableStreamSink.prototype._finishErroring = function (reason) { - if (this._state === "writable" /* WRITABLE */) { - this._startErroring(reason); - } - if (this._state === "erroring" /* ERRORING */) { - this._state = "errored" /* ERRORED */; - this._errorPromiseReject(this._storedError); - } - }; - return WrappingWritableStreamSink; -}()); - -function createTransformStreamWrapper(ctor) { - assert(isTransformStreamConstructor(ctor)); - return function (transform) { - if (transform.constructor === ctor) { - return transform; - } - var transformer = createWrappingTransformer(transform); - return new ctor(transformer); - }; -} -function createWrappingTransformer(transform) { - assert(isTransformStream(transform)); - var readable = transform.readable, writable = transform.writable; - assert(readable.locked === false); - assert(writable.locked === false); - var reader = readable.getReader(); - var writer; - try { - writer = writable.getWriter(); - } - catch (e) { - reader.releaseLock(); // do not leak reader - throw e; - } - return new WrappingTransformStreamTransformer(reader, writer); -} -var WrappingTransformStreamTransformer = /** @class */ (function () { - function WrappingTransformStreamTransformer(reader, writer) { - var _this = this; - this._transformStreamController = undefined; - this._onRead = function (result) { - if (result.done) { - return; - } - _this._transformStreamController.enqueue(result.value); - return _this._reader.read().then(_this._onRead); - }; - this._onError = function (reason) { - _this._flushReject(reason); - _this._transformStreamController.error(reason); - _this._reader.cancel(reason).catch(noop); - _this._writer.abort(reason).catch(noop); - }; - this._onTerminate = function () { - _this._flushResolve(); - _this._transformStreamController.terminate(); - var error = new TypeError('TransformStream terminated'); - _this._writer.abort(error).catch(noop); - }; - this._reader = reader; - this._writer = writer; - this._flushPromise = new Promise(function (resolve, reject) { - _this._flushResolve = resolve; - _this._flushReject = reject; - }); - } - WrappingTransformStreamTransformer.prototype.start = function (controller) { - this._transformStreamController = controller; - this._reader.read() - .then(this._onRead) - .then(this._onTerminate, this._onError); - var readerClosed = this._reader.closed; - if (readerClosed) { - readerClosed - .then(this._onTerminate, this._onError); - } - }; - WrappingTransformStreamTransformer.prototype.transform = function (chunk) { - return this._writer.write(chunk); - }; - WrappingTransformStreamTransformer.prototype.flush = function () { - var _this = this; - return this._writer.close() - .then(function () { return _this._flushPromise; }); - }; - return WrappingTransformStreamTransformer; -}()); - -export { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper }; diff --git a/app/node_modules/openpgp/dist/node/openpgp.cjs b/app/node_modules/openpgp/dist/node/openpgp.cjs new file mode 100644 index 000000000..5f469109a --- /dev/null +++ b/app/node_modules/openpgp/dist/node/openpgp.cjs @@ -0,0 +1,28651 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +'use strict'; + +const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +var module$1 = require('module'); +var nc = require('node:crypto'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +var nc__namespace = /*#__PURE__*/_interopNamespaceDefault(nc); + +const doneWritingPromise = Symbol('doneWritingPromise'); +const doneWritingResolve = Symbol('doneWritingResolve'); +const doneWritingReject = Symbol('doneWritingReject'); + +const readingIndex = Symbol('readingIndex'); + +class ArrayStream extends Array { + constructor() { + super(); + // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work + Object.setPrototypeOf(this, ArrayStream.prototype); + + this[doneWritingPromise] = new Promise((resolve, reject) => { + this[doneWritingResolve] = resolve; + this[doneWritingReject] = reject; + }); + this[doneWritingPromise].catch(() => {}); + } +} + +ArrayStream.prototype.getReader = function() { + if (this[readingIndex] === undefined) { + this[readingIndex] = 0; + } + return { + read: async () => { + await this[doneWritingPromise]; + if (this[readingIndex] === this.length) { + return { value: undefined, done: true }; + } + return { value: this[this[readingIndex]++], done: false }; + } + }; +}; + +ArrayStream.prototype.readToEnd = async function(join) { + await this[doneWritingPromise]; + const result = join(this.slice(this[readingIndex])); + this.length = 0; + return result; +}; + +ArrayStream.prototype.clone = function() { + const clone = new ArrayStream(); + clone[doneWritingPromise] = this[doneWritingPromise].then(() => { + clone.push(...this); + }); + return clone; +}; + +/** + * Check whether data is an ArrayStream + * @param {Any} input data to check + * @returns {boolean} + */ +function isArrayStream(input) { + return input && input.getReader && Array.isArray(input); +} + +/** + * A wrapper class over the native WritableStreamDefaultWriter. + * It also lets you "write data to" array streams instead of streams. + * @class + */ +function Writer(input) { + if (!isArrayStream(input)) { + const writer = input.getWriter(); + const releaseLock = writer.releaseLock; + writer.releaseLock = () => { + writer.closed.catch(function() {}); + releaseLock.call(writer); + }; + return writer; + } + this.stream = input; +} + +/** + * Write a chunk of data. + * @returns {Promise} + * @async + */ +Writer.prototype.write = async function(chunk) { + this.stream.push(chunk); +}; + +/** + * Close the stream. + * @returns {Promise} + * @async + */ +Writer.prototype.close = async function() { + this.stream[doneWritingResolve](); +}; + +/** + * Error the stream. + * @returns {Promise} + * @async + */ +Writer.prototype.abort = async function(reason) { + this.stream[doneWritingReject](reason); + return reason; +}; + +/** + * Release the writer's lock. + * @returns {undefined} + * @async + */ +Writer.prototype.releaseLock = function() {}; + +/* eslint-disable no-prototype-builtins */ +typeof globalThis.process === 'object' && + typeof globalThis.process.versions === 'object'; + +/** + * Check whether data is a Stream, and if so of which type + * @param {Any} input data to check + * @returns {'web'|'node'|'array'|'web-like'|false} + */ +function isStream(input) { + if (isArrayStream(input)) { + return 'array'; + } + if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { + return 'web'; + } + // try and detect a node native stream without having to import its class + if (input && + !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) && + typeof input._read === 'function' && typeof input._readableState === 'object') { + throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`'); + } + if (input && input.getReader) { + return 'web-like'; + } + return false; +} + +/** + * Check whether data is a Uint8Array + * @param {Any} input data to check + * @returns {Boolean} + */ +function isUint8Array(input) { + return Uint8Array.prototype.isPrototypeOf(input); +} + +/** + * Concat Uint8Arrays + * @param {Array} Array of Uint8Arrays to concatenate + * @returns {Uint8array} Concatenated array + */ +function concatUint8Array(arrays) { + if (arrays.length === 1) return arrays[0]; + + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!isUint8Array(arrays[i])) { + throw new Error('concatUint8Array: Data must be in the form of a Uint8Array'); + } + + totalLength += arrays[i].length; + } + + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach(function (element) { + result.set(element, pos); + pos += element.length; + }); + + return result; +} + +const doneReadingSet = new WeakSet(); +/** + * The external buffer is used to store values that have been peeked or unshifted from the original stream. + * Because of how streams are implemented, such values cannot be "put back" in the original stream, + * but they need to be returned first when reading from the input again. + */ +const externalBuffer = Symbol('externalBuffer'); + +/** + * A wrapper class over the native ReadableStreamDefaultReader. + * This additionally implements pushing back data on the stream, which + * lets us implement peeking and a host of convenience functions. + * It also lets you read data other than streams, such as a Uint8Array. + * @class + */ +function Reader(input) { + this.stream = input; + if (input[externalBuffer]) { + this[externalBuffer] = input[externalBuffer].slice(); + } + if (isArrayStream(input)) { + const reader = input.getReader(); + this._read = reader.read.bind(reader); + this._releaseLock = () => {}; + this._cancel = () => {}; + return; + } + let streamType = isStream(input); + if (streamType) { + const reader = input.getReader(); + this._read = reader.read.bind(reader); + this._releaseLock = () => { + reader.closed.catch(function() {}); + reader.releaseLock(); + }; + this._cancel = reader.cancel.bind(reader); + return; + } + let doneReading = false; + this._read = async () => { + if (doneReading || doneReadingSet.has(input)) { + return { value: undefined, done: true }; + } + doneReading = true; + return { value: input, done: false }; + }; + this._releaseLock = () => { + if (doneReading) { + try { + doneReadingSet.add(input); + } catch(e) {} + } + }; +} + +/** + * Read a chunk of data. + * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined } + * @async + */ +Reader.prototype.read = async function() { + if (this[externalBuffer] && this[externalBuffer].length) { + const value = this[externalBuffer].shift(); + return { done: false, value }; + } + return this._read(); +}; + +/** + * Allow others to read the stream. + */ +Reader.prototype.releaseLock = function() { + if (this[externalBuffer]) { + this.stream[externalBuffer] = this[externalBuffer]; + } + this._releaseLock(); +}; + +/** + * Cancel the stream. + */ +Reader.prototype.cancel = function(reason) { + return this._cancel(reason); +}; + +/** + * Read up to and including the first \n character. + * @returns {Promise} + * @async + */ +Reader.prototype.readLine = async function() { + let buffer = []; + let returnVal; + while (!returnVal) { + let { done, value } = await this.read(); + value += ''; + if (done) { + if (buffer.length) return concat(buffer); + return; + } + const lineEndIndex = value.indexOf('\n') + 1; + if (lineEndIndex) { + returnVal = concat(buffer.concat(value.substr(0, lineEndIndex))); + buffer = []; + } + if (lineEndIndex !== value.length) { + buffer.push(value.substr(lineEndIndex)); + } + } + this.unshift(...buffer); + return returnVal; +}; + +/** + * Read a single byte/character. + * @returns {Promise} + * @async + */ +Reader.prototype.readByte = async function() { + const { done, value } = await this.read(); + if (done) return; + const byte = value[0]; + this.unshift(slice(value, 1)); + return byte; +}; + +/** + * Read a specific amount of bytes/characters, unless the stream ends before that amount. + * @returns {Promise} + * @async + */ +Reader.prototype.readBytes = async function(length) { + const buffer = []; + let bufferLength = 0; + // eslint-disable-next-line no-constant-condition + while (true) { + const { done, value } = await this.read(); + if (done) { + if (buffer.length) return concat(buffer); + return; + } + buffer.push(value); + bufferLength += value.length; + if (bufferLength >= length) { + const bufferConcat = concat(buffer); + this.unshift(slice(bufferConcat, length)); + return slice(bufferConcat, 0, length); + } + } +}; + +/** + * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount. + * @returns {Promise} + * @async + */ +Reader.prototype.peekBytes = async function(length) { + const bytes = await this.readBytes(length); + this.unshift(bytes); + return bytes; +}; + +/** + * Push data to the front of the stream. + * Data must have been read in the last call to read*. + * @param {...(Uint8Array|String|Undefined)} values + */ +Reader.prototype.unshift = function(...values) { + if (!this[externalBuffer]) { + this[externalBuffer] = []; + } + if ( + values.length === 1 && isUint8Array(values[0]) && + this[externalBuffer].length && values[0].length && + this[externalBuffer][0].byteOffset >= values[0].length + ) { + this[externalBuffer][0] = new Uint8Array( + this[externalBuffer][0].buffer, + this[externalBuffer][0].byteOffset - values[0].length, + this[externalBuffer][0].byteLength + values[0].length + ); + return; + } + this[externalBuffer].unshift(...values.filter(value => value && value.length)); +}; + +/** + * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat). + * @param {Function} join + * @returns {Promise} the return value of join() + * @async + */ +Reader.prototype.readToEnd = async function(join=concat) { + const result = []; + // eslint-disable-next-line no-constant-condition + while (true) { + const { done, value } = await this.read(); + if (done) break; + result.push(value); + } + return join(result); +}; + +/** + * Convert data to Stream + * @param {ReadableStream|Uint8array|String} input data to convert + * @returns {ReadableStream} Converted data + */ +function toStream(input) { + let streamType = isStream(input); + if (streamType) { + return input; + } + return new ReadableStream({ + start(controller) { + controller.enqueue(input); + controller.close(); + } + }); +} + +/** + * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream. + * @param {Object} input data to convert + * @returns {ArrayStream} Converted data + */ +function toArrayStream(input) { + if (isStream(input)) { + return input; + } + const stream = new ArrayStream(); + (async () => { + const writer = getWriter(stream); + await writer.write(input); + await writer.close(); + })(); + return stream; +} + +/** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate + * @returns {Uint8array|String|ReadableStream} Concatenated array + */ +function concat(list) { + if (list.some(stream => isStream(stream) && !isArrayStream(stream))) { + return concatStream(list); + } + if (list.some(stream => isArrayStream(stream))) { + return concatArrayStream(list); + } + if (typeof list[0] === 'string') { + return list.join(''); + } + return concatUint8Array(list); +} + +/** + * Concat a list of Streams + * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate + * @returns {ReadableStream} Concatenated list + */ +function concatStream(list) { + list = list.map(toStream); + const transform = transformWithCancel(async function(reason) { + await Promise.all(transforms.map(stream => cancel(stream, reason))); + }); + let prev = Promise.resolve(); + const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => { + prev = prev.then(() => pipe(readable, transform.writable, { + preventClose: i !== list.length - 1 + })); + return prev; + })); + return transform.readable; +} + +/** + * Concat a list of ArrayStreams + * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate + * @returns {ArrayStream} Concatenated streams + */ +function concatArrayStream(list) { + const result = new ArrayStream(); + let prev = Promise.resolve(); + list.forEach((stream, i) => { + prev = prev.then(() => pipe(stream, result, { + preventClose: i !== list.length - 1 + })); + return prev; + }); + return result; +} + +/** + * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. + * @param {ReadableStream|Uint8array|String} input + * @param {WritableStream} target + * @param {Object} (optional) options + * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored) + * @async + */ +async function pipe(input, target, { + preventClose = false, + preventAbort = false, + preventCancel = false +} = {}) { + if (isStream(input) && !isArrayStream(input)) { + input = toStream(input); + try { + if (input[externalBuffer]) { + const writer = getWriter(target); + for (let i = 0; i < input[externalBuffer].length; i++) { + await writer.ready; + await writer.write(input[externalBuffer][i]); + } + writer.releaseLock(); + } + await input.pipeTo(target, { + preventClose, + preventAbort, + preventCancel + }); + } catch(e) {} + return; + } + input = toArrayStream(input); + const reader = getReader(input); + const writer = getWriter(target); + try { + // eslint-disable-next-line no-constant-condition + while (true) { + await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (!preventClose) await writer.close(); + break; + } + await writer.write(value); + } + } catch (e) { + if (!preventAbort) await writer.abort(e); + } finally { + reader.releaseLock(); + writer.releaseLock(); + } +} + +/** + * Pipe a readable stream through a transform stream. + * @param {ReadableStream|Uint8array|String} input + * @param {Object} (optional) options + * @returns {ReadableStream} transformed stream + */ +function transformRaw(input, options) { + const transformStream = new TransformStream(options); + pipe(input, transformStream.writable); + return transformStream.readable; +} + +/** + * Create a cancelable TransformStream. + * @param {Function} cancel + * @returns {TransformStream} + */ +function transformWithCancel(customCancel) { + let pulled = false; + let cancelled = false; + let backpressureChangePromiseResolve, backpressureChangePromiseReject; + let outputController; + return { + readable: new ReadableStream({ + start(controller) { + outputController = controller; + }, + pull() { + if (backpressureChangePromiseResolve) { + backpressureChangePromiseResolve(); + } else { + pulled = true; + } + }, + async cancel(reason) { + cancelled = true; + if (customCancel) { + await customCancel(reason); + } + if (backpressureChangePromiseReject) { + backpressureChangePromiseReject(reason); + } + } + }, {highWaterMark: 0}), + writable: new WritableStream({ + write: async function(chunk) { + if (cancelled) { + throw new Error('Stream is cancelled'); + } + outputController.enqueue(chunk); + if (!pulled) { + await new Promise((resolve, reject) => { + backpressureChangePromiseResolve = resolve; + backpressureChangePromiseReject = reject; + }); + backpressureChangePromiseResolve = null; + backpressureChangePromiseReject = null; + } else { + pulled = false; + } + }, + close: outputController.close.bind(outputController), + abort: outputController.error.bind(outputController) + }) + }; +} + +/** + * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively. + * @param {ReadableStream|Uint8array|String} input + * @param {Function} process + * @param {Function} finish + * @returns {ReadableStream|Uint8array|String} + */ +function transform(input, process = () => undefined, finish = () => undefined) { + if (isArrayStream(input)) { + const output = new ArrayStream(); + (async () => { + const writer = getWriter(output); + try { + const data = await readToEnd(input); + const result1 = process(data); + const result2 = finish(); + let result; + if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]); + else result = result1 !== undefined ? result1 : result2; + await writer.write(result); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + })(); + return output; + } + if (isStream(input)) { + return transformRaw(input, { + async transform(value, controller) { + try { + const result = await process(value); + if (result !== undefined) controller.enqueue(result); + } catch(e) { + controller.error(e); + } + }, + async flush(controller) { + try { + const result = await finish(); + if (result !== undefined) controller.enqueue(result); + } catch(e) { + controller.error(e); + } + } + }); + } + const result1 = process(input); + const result2 = finish(); + if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]); + return result1 !== undefined ? result1 : result2; +} + +/** + * Transform a stream using a helper function which is passed a readable and a writable stream. + * This function also maintains the possibility to cancel the input stream, + * and does so on cancelation of the output stream, despite cancelation + * normally being impossible when the input stream is being read from. + * @param {ReadableStream|Uint8array|String} input + * @param {Function} fn + * @returns {ReadableStream} + */ +function transformPair(input, fn) { + if (isStream(input) && !isArrayStream(input)) { + let incomingTransformController; + const incoming = new TransformStream({ + start(controller) { + incomingTransformController = controller; + } + }); + + const pipeDonePromise = pipe(input, incoming.writable); + + const outgoing = transformWithCancel(async function(reason) { + incomingTransformController.error(reason); + await pipeDonePromise; + await new Promise(setTimeout); + }); + fn(incoming.readable, outgoing.writable); + return outgoing.readable; + } + input = toArrayStream(input); + const output = new ArrayStream(); + fn(input, output); + return output; +} + +/** + * Parse a stream using a helper function which is passed a Reader. + * The reader additionally has a remainder() method which returns a + * stream pointing to the remainder of input, and is linked to input + * for cancelation. + * @param {ReadableStream|Uint8array|String} input + * @param {Function} fn + * @returns {Any} the return value of fn() + */ +function parse(input, fn) { + let returnValue; + const transformed = transformPair(input, (readable, writable) => { + const reader = getReader(readable); + reader.remainder = () => { + reader.releaseLock(); + pipe(readable, writable); + return transformed; + }; + returnValue = fn(reader); + }); + return returnValue; +} + +/** + * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing. + * Reading either of the two returned streams will pull from the input stream. + * The input stream will only be canceled if both of the returned streams are canceled. + * @param {ReadableStream|Uint8array|String} input + * @returns {Array} array containing two copies of input + */ +function tee(input) { + if (isArrayStream(input)) { + throw new Error('ArrayStream cannot be tee()d, use clone() instead'); + } + if (isStream(input)) { + const teed = toStream(input).tee(); + teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer]; + return teed; + } + return [slice(input), slice(input)]; +} + +/** + * Clone a Stream for reading it twice. The input stream can still be read after clone()ing. + * Reading from the clone will pull from the input stream. + * The input stream will only be canceled if both the clone and the input stream are canceled. + * @param {ReadableStream|Uint8array|String} input + * @returns {ReadableStream|Uint8array|String} cloned input + */ +function clone(input) { + if (isArrayStream(input)) { + return input.clone(); + } + if (isStream(input)) { + const teed = tee(input); + overwrite(input, teed[0]); + return teed[1]; + } + return slice(input); +} + +/** + * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read. + * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream. + * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled. + * If the input stream is canceled, the clone will be errored. + * @param {ReadableStream|Uint8array|String} input + * @returns {ReadableStream|Uint8array|String} cloned input + */ +function passiveClone(input) { + if (isArrayStream(input)) { + return clone(input); + } + if (isStream(input)) { + return new ReadableStream({ + start(controller) { + const transformed = transformPair(input, async (readable, writable) => { + const reader = getReader(readable); + const writer = getWriter(writable); + try { + // eslint-disable-next-line no-constant-condition + while (true) { + await writer.ready; + const { done, value } = await reader.read(); + if (done) { + try { controller.close(); } catch(e) {} + await writer.close(); + return; + } + try { controller.enqueue(value); } catch(e) {} + await writer.write(value); + } + } catch(e) { + controller.error(e); + await writer.abort(e); + } + }); + overwrite(input, transformed); + } + }); + } + return slice(input); +} + +/** + * Modify a stream object to point to a different stream object. + * This is used internally by clone() and passiveClone() to provide an abstraction over tee(). + * @param {ReadableStream} input + * @param {ReadableStream} clone + */ +function overwrite(input, clone) { + // Overwrite input.getReader, input.locked, etc to point to clone + Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => { + if (name === 'constructor') { + return; + } + if (descriptor.value) { + descriptor.value = descriptor.value.bind(clone); + } else { + descriptor.get = descriptor.get.bind(clone); + } + Object.defineProperty(input, name, descriptor); + }); +} + +/** + * Return a stream pointing to a part of the input stream. + * @param {ReadableStream|Uint8array|String} input + * @returns {ReadableStream|Uint8array|String} clone + */ +function slice(input, begin=0, end=Infinity) { + if (isArrayStream(input)) { + throw new Error('Not implemented'); + } + if (isStream(input)) { + if (begin >= 0 && end >= 0) { + let bytesRead = 0; + return transformRaw(input, { + transform(value, controller) { + if (bytesRead < end) { + if (bytesRead + value.length >= begin) { + controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead)); + } + bytesRead += value.length; + } else { + controller.terminate(); + } + } + }); + } + if (begin < 0 && (end < 0 || end === Infinity)) { + let lastBytes = []; + return transform(input, value => { + if (value.length >= -begin) lastBytes = [value]; + else lastBytes.push(value); + }, () => slice(concat(lastBytes), begin, end)); + } + if (begin === 0 && end < 0) { + let lastBytes; + return transform(input, value => { + const returnValue = lastBytes ? concat([lastBytes, value]) : value; + if (returnValue.length >= -end) { + lastBytes = slice(returnValue, end); + return slice(returnValue, begin, end); + } + lastBytes = returnValue; + }); + } + console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); + return fromAsync(async () => slice(await readToEnd(input), begin, end)); + } + if (input[externalBuffer]) { + input = concat(input[externalBuffer].concat([input])); + } + if (isUint8Array(input)) { + return input.subarray(begin, end === Infinity ? input.length : end); + } + return input.slice(begin, end); +} + +/** + * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat). + * @param {ReadableStream|Uint8array|String} input + * @param {Function} join + * @returns {Promise} the return value of join() + * @async + */ +async function readToEnd(input, join=concat) { + if (isArrayStream(input)) { + return input.readToEnd(join); + } + if (isStream(input)) { + return getReader(input).readToEnd(join); + } + return input; +} + +/** + * Cancel a stream. + * @param {ReadableStream|Uint8array|String} input + * @param {Any} reason + * @returns {Promise} indicates when the stream has been canceled + * @async + */ +async function cancel(input, reason) { + if (isStream(input)) { + if (input.cancel) { + const cancelled = await input.cancel(reason); + // the stream is not always cancelled at this point, so we wait some more + await new Promise(setTimeout); + return cancelled; + } + if (input.destroy) { + input.destroy(reason); + await new Promise(setTimeout); + return reason; + } + } +} + +/** + * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream. + * @param {Function} fn + * @returns {ArrayStream} + */ +function fromAsync(fn) { + const arrayStream = new ArrayStream(); + (async () => { + const writer = getWriter(arrayStream); + try { + await writer.write(await fn()); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + })(); + return arrayStream; +} + +/** + * Get a Reader + * @param {ReadableStream|Uint8array|String} input + * @returns {Reader} + */ +function getReader(input) { + return new Reader(input); +} + +/** + * Get a Writer + * @param {WritableStream} input + * @returns {Writer} + */ +function getWriter(input) { + return new Writer(input); +} + +/** + * @module enums + */ + +const byValue = Symbol('byValue'); + +var enums = { + + /** Maps curve names under various standards to one + * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} + * @enum {String} + * @readonly + */ + curve: { + /** NIST P-256 Curve */ + 'nistP256': 'nistP256', + /** @deprecated use `nistP256` instead */ + 'p256': 'nistP256', + + /** NIST P-384 Curve */ + 'nistP384': 'nistP384', + /** @deprecated use `nistP384` instead */ + 'p384': 'nistP384', + + /** NIST P-521 Curve */ + 'nistP521': 'nistP521', + /** @deprecated use `nistP521` instead */ + 'p521': 'nistP521', + + /** SECG SECP256k1 Curve */ + 'secp256k1': 'secp256k1', + + /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ + 'ed25519Legacy': 'ed25519Legacy', + /** @deprecated use `ed25519Legacy` instead */ + 'ed25519': 'ed25519Legacy', + + /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ + 'curve25519Legacy': 'curve25519Legacy', + /** @deprecated use `curve25519Legacy` instead */ + 'curve25519': 'curve25519Legacy', + + /** BrainpoolP256r1 Curve */ + 'brainpoolP256r1': 'brainpoolP256r1', + + /** BrainpoolP384r1 Curve */ + 'brainpoolP384r1': 'brainpoolP384r1', + + /** BrainpoolP512r1 Curve */ + 'brainpoolP512r1': 'brainpoolP512r1' + }, + + /** A string to key specifier type + * @enum {Integer} + * @readonly + */ + s2k: { + simple: 0, + salted: 1, + iterated: 3, + argon2: 4, + gnu: 101 + }, + + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} + * @enum {Integer} + * @readonly + */ + publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ + rsaEncryptSign: 1, + /** RSA (Encrypt only) [HAC] */ + rsaEncrypt: 2, + /** RSA (Sign only) [HAC] */ + rsaSign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ + elgamal: 16, + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsaLegacy: 22, + /** Reserved for AEDH */ + aedh: 23, + /** Reserved for AEDSA */ + aedsa: 24, + /** X25519 (Encrypt only) */ + x25519: 25, + /** X448 (Encrypt only) */ + x448: 26, + /** Ed25519 (Sign only) */ + ed25519: 27, + /** Ed448 (Sign only) */ + ed448: 28 + }, + + /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + * @enum {Integer} + * @readonly + */ + symmetric: { + /** Not implemented! */ + idea: 1, + tripledes: 2, + cast5: 3, + blowfish: 4, + aes128: 7, + aes192: 8, + aes256: 9, + twofish: 10 + }, + + /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + * @enum {Integer} + * @readonly + */ + compression: { + uncompressed: 0, + /** RFC1951 */ + zip: 1, + /** RFC1950 */ + zlib: 2, + bzip2: 3 + }, + + /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + * @enum {Integer} + * @readonly + */ + hash: { + md5: 1, + sha1: 2, + ripemd: 3, + sha256: 8, + sha384: 9, + sha512: 10, + sha224: 11, + sha3_256: 12, + sha3_512: 14 + }, + + /** A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + * @enum {String} + */ + webHash: { + 'SHA-1': 2, + 'SHA-256': 8, + 'SHA-384': 9, + 'SHA-512': 10 + }, + + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} + * @enum {Integer} + * @readonly + */ + aead: { + eax: 1, + ocb: 2, + gcm: 3, + experimentalGCM: 100 // Private algorithm + }, + + /** A list of packet types and numeric tags associated with them. + * @enum {Integer} + * @readonly + */ + packet: { + publicKeyEncryptedSessionKey: 1, + signature: 2, + symEncryptedSessionKey: 3, + onePassSignature: 4, + secretKey: 5, + publicKey: 6, + secretSubkey: 7, + compressedData: 8, + symmetricallyEncryptedData: 9, + marker: 10, + literalData: 11, + trust: 12, + userID: 13, + publicSubkey: 14, + userAttribute: 17, + symEncryptedIntegrityProtectedData: 18, + modificationDetectionCode: 19, + aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + padding: 21 + }, + + /** Data types in the literal packet + * @enum {Integer} + * @readonly + */ + literal: { + /** Binary data 'b' */ + binary: 'b'.charCodeAt(), + /** Text data 't' */ + text: 't'.charCodeAt(), + /** Utf8 data 'u' */ + utf8: 'u'.charCodeAt(), + /** MIME message body part 'm' */ + mime: 'm'.charCodeAt() + }, + + + /** One pass signature packet type + * @enum {Integer} + * @readonly + */ + signature: { + /** 0x00: Signature of a binary document. */ + binary: 0, + /** 0x01: Signature of a canonical text document. + * + * Canonicalyzing the document by converting line endings. */ + text: 1, + /** 0x02: Standalone signature. + * + * This signature is a signature of only its own subpacket contents. + * It is calculated identically to a signature over a zero-lengh + * binary document. Note that it doesn't make sense to have a V3 + * standalone signature. */ + standalone: 2, + /** 0x10: Generic certification of a User ID and Public-Key packet. + * + * The issuer of this certification does not make any particular + * assertion as to how well the certifier has checked that the owner + * of the key is in fact the person described by the User ID. */ + certGeneric: 16, + /** 0x11: Persona certification of a User ID and Public-Key packet. + * + * The issuer of this certification has not done any verification of + * the claim that the owner of this key is the User ID specified. */ + certPersona: 17, + /** 0x12: Casual certification of a User ID and Public-Key packet. + * + * The issuer of this certification has done some casual + * verification of the claim of identity. */ + certCasual: 18, + /** 0x13: Positive certification of a User ID and Public-Key packet. + * + * The issuer of this certification has done substantial + * verification of the claim of identity. + * + * Most OpenPGP implementations make their "key signatures" as 0x10 + * certifications. Some implementations can issue 0x11-0x13 + * certifications, but few differentiate between the types. */ + certPositive: 19, + /** 0x30: Certification revocation signature + * + * This signature revokes an earlier User ID certification signature + * (signature class 0x10 through 0x13) or direct-key signature + * (0x1F). It should be issued by the same key that issued the + * revoked signature or an authorized revocation key. The signature + * is computed over the same data as the certificate that it + * revokes, and should have a later creation date than that + * certificate. */ + certRevocation: 48, + /** 0x18: Subkey Binding Signature + * + * This signature is a statement by the top-level signing key that + * indicates that it owns the subkey. This signature is calculated + * directly on the primary key and subkey, and not on any User ID or + * other packets. A signature that binds a signing subkey MUST have + * an Embedded Signature subpacket in this binding signature that + * contains a 0x19 signature made by the signing subkey on the + * primary key and subkey. */ + subkeyBinding: 24, + /** 0x19: Primary Key Binding Signature + * + * This signature is a statement by a signing subkey, indicating + * that it is owned by the primary key and subkey. This signature + * is calculated the same way as a 0x18 signature: directly on the + * primary key and subkey, and not on any User ID or other packets. + * + * When a signature is made over a key, the hash data starts with the + * octet 0x99, followed by a two-octet length of the key, and then body + * of the key packet. (Note that this is an old-style packet header for + * a key packet with two-octet length.) A subkey binding signature + * (type 0x18) or primary key binding signature (type 0x19) then hashes + * the subkey using the same format as the main key (also using 0x99 as + * the first octet). */ + keyBinding: 25, + /** 0x1F: Signature directly on a key + * + * This signature is calculated directly on a key. It binds the + * information in the Signature subpackets to the key, and is + * appropriate to be used for subpackets that provide information + * about the key, such as the Revocation Key subpacket. It is also + * appropriate for statements that non-self certifiers want to make + * about the key itself, rather than the binding between a key and a + * name. */ + key: 31, + /** 0x20: Key revocation signature + * + * The signature is calculated directly on the key being revoked. A + * revoked key is not to be used. Only revocation signatures by the + * key being revoked, or by an authorized revocation key, should be + * considered valid revocation signatures.a */ + keyRevocation: 32, + /** 0x28: Subkey revocation signature + * + * The signature is calculated directly on the subkey being revoked. + * A revoked subkey is not to be used. Only revocation signatures + * by the top-level signature key that is bound to this subkey, or + * by an authorized revocation key, should be considered valid + * revocation signatures. + * + * Key revocation signatures (types 0x20 and 0x28) + * hash only the key being revoked. */ + subkeyRevocation: 40, + /** 0x40: Timestamp signature. + * This signature is only meaningful for the timestamp contained in + * it. */ + timestamp: 64, + /** 0x50: Third-Party Confirmation signature. + * + * This signature is a signature over some other OpenPGP Signature + * packet(s). It is analogous to a notary seal on the signed data. + * A third-party signature SHOULD include Signature Target + * subpacket(s) to give easy identification. Note that we really do + * mean SHOULD. There are plausible uses for this (such as a blind + * party that only sees the signature, not the key or source + * document) that cannot include a target subpacket. */ + thirdParty: 80 + }, + + /** Signature subpacket type + * @enum {Integer} + * @readonly + */ + signatureSubpacket: { + signatureCreationTime: 2, + signatureExpirationTime: 3, + exportableCertification: 4, + trustSignature: 5, + regularExpression: 6, + revocable: 7, + keyExpirationTime: 9, + placeholderBackwardsCompatibility: 10, + preferredSymmetricAlgorithms: 11, + revocationKey: 12, + issuerKeyID: 16, + notationData: 20, + preferredHashAlgorithms: 21, + preferredCompressionAlgorithms: 22, + keyServerPreferences: 23, + preferredKeyServer: 24, + primaryUserID: 25, + policyURI: 26, + keyFlags: 27, + signersUserID: 28, + reasonForRevocation: 29, + features: 30, + signatureTarget: 31, + embeddedSignature: 32, + issuerFingerprint: 33, + preferredAEADAlgorithms: 34, + preferredCipherSuites: 39 + }, + + /** Key flags + * @enum {Integer} + * @readonly + */ + keyFlags: { + /** 0x01 - This key may be used to certify other keys. */ + certifyKeys: 1, + /** 0x02 - This key may be used to sign data. */ + signData: 2, + /** 0x04 - This key may be used to encrypt communications. */ + encryptCommunication: 4, + /** 0x08 - This key may be used to encrypt storage. */ + encryptStorage: 8, + /** 0x10 - The private component of this key may have been split + * by a secret-sharing mechanism. */ + splitPrivateKey: 16, + /** 0x20 - This key may be used for authentication. */ + authentication: 32, + /** 0x80 - The private component of this key may be in the + * possession of more than one person. */ + sharedPrivateKey: 128 + }, + + /** Armor type + * @enum {Integer} + * @readonly + */ + armor: { + multipartSection: 0, + multipartLast: 1, + signed: 2, + message: 3, + publicKey: 4, + privateKey: 5, + signature: 6 + }, + + /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} + * @enum {Integer} + * @readonly + */ + reasonForRevocation: { + /** No reason specified (key revocations or cert revocations) */ + noReason: 0, + /** Key is superseded (key revocations) */ + keySuperseded: 1, + /** Key material has been compromised (key revocations) */ + keyCompromised: 2, + /** Key is retired and no longer used (key revocations) */ + keyRetired: 3, + /** User ID information is no longer valid (cert revocations) */ + userIDInvalid: 32 + }, + + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} + * @enum {Integer} + * @readonly + */ + features: { + /** 0x01 - Modification Detection (packets 18 and 19) */ + modificationDetection: 1, + /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 + * Symmetric-Key Encrypted Session Key Packets (packet 3) */ + aead: 2, + /** 0x04 - Version 5 Public-Key Packet format and corresponding new + * fingerprint format */ + v5Keys: 4, + seipdv2: 8 + }, + + /** + * Asserts validity of given value and converts from string/integer to integer. + * @param {Object} type target enum type + * @param {String|Integer} e value to check and/or convert + * @returns {Integer} enum value if it exists + * @throws {Error} if the value is invalid + */ + write: function(type, e) { + if (typeof e === 'number') { + e = this.read(type, e); + } + + if (type[e] !== undefined) { + return type[e]; + } + + throw new Error('Invalid enum value.'); + }, + + /** + * Converts enum integer value to the corresponding string, if it exists. + * @param {Object} type target enum type + * @param {Integer} e value to convert + * @returns {String} name of enum value if it exists + * @throws {Error} if the value is invalid + */ + read: function(type, e) { + if (!type[byValue]) { + type[byValue] = []; + Object.entries(type).forEach(([key, value]) => { + type[byValue][value] = key; + }); + } + + if (type[byValue][e] !== undefined) { + return type[byValue][e]; + } + + throw new Error('Invalid enum value.'); + } +}; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +var config = { + /** + * @memberof module:config + * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} + */ + preferredHashAlgorithm: enums.hash.sha512, + /** + * @memberof module:config + * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} + */ + preferredSymmetricAlgorithm: enums.symmetric.aes256, + /** + * @memberof module:config + * @property {Integer} compression Default compression algorithm {@link module:enums.compression} + */ + preferredCompressionAlgorithm: enums.compression.uncompressed, + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * This option is applicable to: + * - key generation (encryption key preferences), + * - password-based message encryption, and + * - private key encryption. + * In the case of message encryption using public keys, the encryption key preferences are respected instead. + * Note: not all OpenPGP implementations are compatible with this option. + * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10} + * @memberof module:config + * @property {Boolean} aeadProtect + */ + aeadProtect: false, + /** + * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`) + * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`, + * this option must be set, otherwise key parsing and/or key decryption will fail. + * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys + * will be processed incorrectly. + */ + parseAEADEncryptedV4KeysAsLegacy: false, + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aeadProtect is set to true. + * @memberof module:config + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} + */ + preferredAEADAlgorithm: enums.aead.gcm, + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aeadProtect is set to true. + * Must be an integer value from 0 to 56. + * @memberof module:config + * @property {Integer} aeadChunkSizeByte + */ + aeadChunkSizeByte: 12, + /** + * Use v6 keys. + * Note: not all OpenPGP implementations are compatible with this option. + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + * @memberof module:config + * @property {Boolean} v6Keys + */ + v6Keys: false, + /** + * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet). + * These are non-standard entities, which in the crypto-refresh have been superseded + * by v6 keys and v6 signatures, respectively. + * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries, + * hence parsing them might be necessary in some cases. + */ + enableParsingV5Entities: false, + /** + * S2K (String to Key) type, used for key derivation in the context of secret key encryption + * and password-encrypted data. Weaker s2k options are not allowed. + * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it + * (pending standardisation). + * @memberof module:config + * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k} + */ + s2kType: enums.s2k.iterated, + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}: + * Iteration Count Byte for Iterated and Salted S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`. + * Note: this is the exponent value, not the final number of iterations (refer to specs for more details). + * @memberof module:config + * @property {Integer} s2kIterationCountByte + */ + s2kIterationCountByte: 224, + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}: + * Argon2 parameters for S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`. + * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"), + * to ensure compatibility with memory-constrained environments. + * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4. + * @memberof module:config + * @property {Object} params + * @property {Integer} params.passes - number of iterations t + * @property {Integer} params.parallelism - degree of parallelism p + * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes. + */ + s2kArgon2Params: { + passes: 3, + parallelism: 4, // lanes + memoryExponent: 16 // 64 MiB of RAM + }, + /** + * Allow decryption of messages without integrity protection. + * This is an **insecure** setting: + * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. + * - it enables downgrade attacks against integrity-protected messages. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedMessages + */ + allowUnauthenticatedMessages: false, + /** + * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to + * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible + * and deferring checking their integrity until the decrypted stream has been read in full. + * + * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity: + * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL + * (see https://efail.de/). + * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data. + * + * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedStream + */ + allowUnauthenticatedStream: false, + /** + * Minimum RSA key size allowed for key generation and message signing, verification and encryption. + * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. + * @memberof module:config + * @property {Number} minRSABits + */ + minRSABits: 2047, + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + * @memberof module:config + * @property {Boolean} passwordCollisionCheck + */ + passwordCollisionCheck: false, + /** + * Allow decryption using RSA keys without `encrypt` flag. + * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug + * where key flags were ignored when selecting a key for encryption. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureDecryptionWithSigningKeys: false, + /** + * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. + * Instead, a verification key will also be consider valid as long as it is valid at the current time. + * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, + * and have self-signature's creation date that does not match the primary key creation date. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureVerificationWithReformattedKeys: false, + /** + * Allow using keys that do not have any key flags set. + * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages + * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29). + * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation. + * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm. + */ + allowMissingKeyFlags: false, + /** + * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). + * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: + * - new/incoming messages are automatically decrypted (without user interaction); + * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). + * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. + * @memberof module:config + * @property {Boolean} constantTimePKCS1Decryption + */ + constantTimePKCS1Decryption: false, + /** + * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. + * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. + * However, the more algorithms are added, the slower the decryption procedure becomes. + * @memberof module:config + * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} + */ + constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), + /** + * @memberof module:config + * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error + */ + ignoreUnsupportedPackets: true, + /** + * @memberof module:config + * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error + */ + ignoreMalformedPackets: false, + /** + * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only + * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable + * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). + * @memberof module:config + * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] + */ + additionalAllowedPackets: [], + /** + * @memberof module:config + * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages + */ + showVersion: false, + /** + * @memberof module:config + * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages + */ + showComment: false, + /** + * @memberof module:config + * @property {String} versionString A version string to be included in armored messages + */ + versionString: 'OpenPGP.js 6.0.0', + /** + * @memberof module:config + * @property {String} commentString A comment string to be included in armored messages + */ + commentString: 'https://openpgpjs.org', + + /** + * Max userID string length (used for parsing) + * @memberof module:config + * @property {Integer} maxUserIDLength + */ + maxUserIDLength: 1024 * 5, + /** + * Contains notatations that are considered "known". Known notations do not trigger + * validation error when the notation is marked as critical. + * @memberof module:config + * @property {Array} knownNotations + */ + knownNotations: [], + /** + * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design). + * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur + * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of + * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks. + * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases. + */ + nonDeterministicSignaturesViaNotation: true, + /** + * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API. + * When false, certain standard curves will not be supported (depending on the platform). + * @memberof module:config + * @property {Boolean} useEllipticFallback + */ + useEllipticFallback: true, + /** + * Reject insecure hash algorithms + * @memberof module:config + * @property {Set} rejectHashAlgorithms {@link module:enums.hash} + */ + rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), + /** + * Reject insecure message hash algorithms + * @memberof module:config + * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} + */ + rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), + /** + * Reject insecure public key algorithms for key generation and message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} + */ + rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), + /** + * Reject non-standard curves for key generation, message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectCurves {@link module:enums.curve} + */ + rejectCurves: new Set([enums.curve.secp256k1]) +}; + +/** + * @fileoverview This object contains global configuration values. + * @see module:config/config + * @module config + */ + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const debugMode = (() => { + try { + return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env + } catch (e) {} + return false; +})(); + +const util = { + isString: function(data) { + return typeof data === 'string' || data instanceof String; + }, + + nodeRequire: module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('openpgp.cjs', document.baseURI).href))), + + isArray: function(data) { + return data instanceof Array; + }, + + isUint8Array: isUint8Array, + + isStream: isStream, + + /** + * Load noble-curves lib on demand and return the requested curve function + * @param {enums.publicKey} publicKeyAlgo + * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA) + * @returns curve implementation + * @throws on unrecognized curve, or curve not implemented by noble-curve + */ + getNobleCurve: async (publicKeyAlgo, curveName) => { + if (!config.useEllipticFallback) { + throw new Error('This curve is only supported in the full build of OpenPGP.js'); + } + + const { nobleCurves } = await Promise.resolve().then(function () { return noble_curves; }); + switch (publicKeyAlgo) { + case enums.publicKey.ecdh: + case enums.publicKey.ecdsa: { + const curve = nobleCurves.get(curveName); + if (!curve) throw new Error('Unsupported curve'); + return curve; + } + case enums.publicKey.x448: + return nobleCurves.get('x448'); + case enums.publicKey.ed448: + return nobleCurves.get('ed448'); + default: + throw new Error('Unsupported curve'); + } + }, + + readNumber: function (bytes) { + let n = 0; + for (let i = 0; i < bytes.length; i++) { + n += (256 ** i) * bytes[bytes.length - 1 - i]; + } + return n; + }, + + writeNumber: function (n, bytes) { + const b = new Uint8Array(bytes); + for (let i = 0; i < bytes; i++) { + b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF; + } + + return b; + }, + + readDate: function (bytes) { + const n = util.readNumber(bytes); + const d = new Date(n * 1000); + return d; + }, + + writeDate: function (time) { + const numeric = Math.floor(time.getTime() / 1000); + + return util.writeNumber(numeric, 4); + }, + + normalizeDate: function (time = Date.now()) { + return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000); + }, + + /** + * Read one MPI from bytes in input + * @param {Uint8Array} bytes - Input data to parse + * @returns {Uint8Array} Parsed MPI. + */ + readMPI: function (bytes) { + const bits = (bytes[0] << 8) | bytes[1]; + const bytelen = (bits + 7) >>> 3; + // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures, + // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed + // has not been authenticated (yet). + // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues. + // Also, AEAD is also not affected. + return util.readExactSubarray(bytes, 2, 2 + bytelen); + }, + + /** + * Read exactly `end - start` bytes from input. + * This is a stricter version of `.subarray`. + * @param {Uint8Array} input - Input data to parse + * @returns {Uint8Array} subarray of size always equal to `end - start` + * @throws if the input array is too short. + */ + readExactSubarray: function (input, start, end) { + if (input.length < (end - start)) { + throw new Error('Input array too short'); + } + return input.subarray(start, end); + }, + + /** + * Left-pad Uint8Array to length by adding 0x0 bytes + * @param {Uint8Array} bytes - Data to pad + * @param {Number} length - Padded length + * @returns {Uint8Array} Padded bytes. + */ + leftPad(bytes, length) { + if (bytes.length > length) { + throw new Error('Input array too long'); + } + const padded = new Uint8Array(length); + const offset = length - bytes.length; + padded.set(bytes, offset); + return padded; + }, + + /** + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * @param {Uint8Array} bin - An array of 8-bit integers to convert + * @returns {Uint8Array} MPI-formatted Uint8Array. + */ + uint8ArrayToMPI: function (bin) { + const bitSize = util.uint8ArrayBitLength(bin); + if (bitSize === 0) { + throw new Error('Zero MPI'); + } + const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8)); + const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]); + return util.concatUint8Array([prefix, stripped]); + }, + + /** + * Return bit length of the input data + * @param {Uint8Array} bin input data (big endian) + * @returns bit length + */ + uint8ArrayBitLength: function (bin) { + let i; // index of leading non-zero byte + for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break; + if (i === bin.length) { + return 0; + } + const stripped = bin.subarray(i); + return (stripped.length - 1) * 8 + util.nbits(stripped[0]); + }, + + /** + * Convert a hex string to an array of 8-bit integers + * @param {String} hex - A hex string to convert + * @returns {Uint8Array} An array of 8-bit integers. + */ + hexToUint8Array: function (hex) { + const result = new Uint8Array(hex.length >> 1); + for (let k = 0; k < hex.length >> 1; k++) { + result[k] = parseInt(hex.substr(k << 1, 2), 16); + } + return result; + }, + + /** + * Convert an array of 8-bit integers to a hex string + * @param {Uint8Array} bytes - Array of 8-bit integers to convert + * @returns {String} Hexadecimal representation of the array. + */ + uint8ArrayToHex: function (bytes) { + const hexAlphabet = '0123456789abcdef'; + let s = ''; + bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; }); + return s; + }, + + /** + * Convert a string to an array of 8-bit integers + * @param {String} str - String to convert + * @returns {Uint8Array} An array of 8-bit integers. + */ + stringToUint8Array: function (str) { + return transform(str, str => { + if (!util.isString(str)) { + throw new Error('stringToUint8Array: Data must be in the form of a string'); + } + + const result = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + result[i] = str.charCodeAt(i); + } + return result; + }); + }, + + /** + * Convert an array of 8-bit integers to a string + * @param {Uint8Array} bytes - An array of 8-bit integers to convert + * @returns {String} String representation of the array. + */ + uint8ArrayToString: function (bytes) { + bytes = new Uint8Array(bytes); + const result = []; + const bs = 1 << 14; + const j = bytes.length; + + for (let i = 0; i < j; i += bs) { + result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j))); + } + return result.join(''); + }, + + /** + * Convert a native javascript string to a Uint8Array of utf8 bytes + * @param {String|ReadableStream} str - The string to convert + * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes. + */ + encodeUTF8: function (str) { + const encoder = new TextEncoder('utf-8'); + // eslint-disable-next-line no-inner-declarations + function process(value, lastChunk = false) { + return encoder.encode(value, { stream: !lastChunk }); + } + return transform(str, process, () => process('', true)); + }, + + /** + * Convert a Uint8Array of utf8 bytes to a native javascript string + * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes + * @returns {String|ReadableStream} A native javascript string. + */ + decodeUTF8: function (utf8) { + const decoder = new TextDecoder('utf-8'); + // eslint-disable-next-line no-inner-declarations + function process(value, lastChunk = false) { + return decoder.decode(value, { stream: !lastChunk }); + } + return transform(utf8, process, () => process(new Uint8Array(), true)); + }, + + /** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate + * @returns {Uint8Array|String|ReadableStream} Concatenated array. + */ + concat: concat, + + /** + * Concat Uint8Arrays + * @param {Array} Array - Of Uint8Arrays to concatenate + * @returns {Uint8Array} Concatenated array. + */ + concatUint8Array: concatUint8Array, + + /** + * Check Uint8Array equality + * @param {Uint8Array} array1 - First array + * @param {Uint8Array} array2 - Second array + * @returns {Boolean} Equality. + */ + equalsUint8Array: function (array1, array2) { + if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) { + throw new Error('Data must be in the form of a Uint8Array'); + } + + if (array1.length !== array2.length) { + return false; + } + + for (let i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + }, + + /** + * Calculates a 16bit sum of a Uint8Array by adding each character + * codes modulus 65535 + * @param {Uint8Array} Uint8Array - To create a sum of + * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535. + */ + writeChecksum: function (text) { + let s = 0; + for (let i = 0; i < text.length; i++) { + s = (s + text[i]) & 0xFFFF; + } + return util.writeNumber(s, 2); + }, + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param {String} str - String of the debug message + */ + printDebug: function (str) { + if (debugMode) { + console.log('[OpenPGP.js debug]', str); + } + }, + + /** + * Helper function to print a debug error. Debug + * messages are only printed if + * @param {String} str - String of the debug message + */ + printDebugError: function (error) { + if (debugMode) { + console.error('[OpenPGP.js debug]', error); + } + }, + + // returns bit length of the integer x + nbits: function (x) { + let r = 1; + let t = x >>> 16; + if (t !== 0) { + x = t; + r += 16; + } + t = x >> 8; + if (t !== 0) { + x = t; + r += 8; + } + t = x >> 4; + if (t !== 0) { + x = t; + r += 4; + } + t = x >> 2; + if (t !== 0) { + x = t; + r += 2; + } + t = x >> 1; + if (t !== 0) { + x = t; + r += 1; + } + return r; + }, + + /** + * If S[1] == 0, then double(S) == (S[2..128] || 0); + * otherwise, double(S) == (S[2..128] || 0) xor + * (zeros(120) || 10000111). + * + * Both OCB and EAX (through CMAC) require this function to be constant-time. + * + * @param {Uint8Array} data + */ + double: function(data) { + const doubleVar = new Uint8Array(data.length); + const last = data.length - 1; + for (let i = 0; i < last; i++) { + doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7); + } + doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87); + return doubleVar; + }, + + /** + * Shift a Uint8Array to the right by n bits + * @param {Uint8Array} array - The array to shift + * @param {Integer} bits - Amount of bits to shift (MUST be smaller + * than 8) + * @returns {String} Resulting array. + */ + shiftRight: function (array, bits) { + if (bits) { + for (let i = array.length - 1; i >= 0; i--) { + array[i] >>= bits; + if (i > 0) { + array[i] |= (array[i - 1] << (8 - bits)); + } + } + } + return array; + }, + + /** + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available + */ + getWebCrypto: function() { + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; + }, + + /** + * Get native Node.js crypto api. + * @returns {Object} The crypto module or 'undefined'. + */ + getNodeCrypto: function() { + return this.nodeRequire('crypto'); + }, + + getNodeZlib: function() { + return this.nodeRequire('zlib'); + }, + + /** + * Get native Node.js Buffer constructor. This should be used since + * Buffer is not available under browserify. + * @returns {Function} The Buffer constructor or 'undefined'. + */ + getNodeBuffer: function() { + return (this.nodeRequire('buffer') || {}).Buffer; + }, + + getHardwareConcurrency: function() { + if (typeof navigator !== 'undefined') { + return navigator.hardwareConcurrency || 1; + } + + const os = this.nodeRequire('os'); // Assume we're on Node.js. + return os.cpus().length; + }, + + /** + * Test email format to ensure basic compliance: + * - must include a single @ + * - no control or space unicode chars allowed + * - no backslash and square brackets (as the latter can mess with the userID parsing) + * - cannot end with a punctuation char + * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation, + * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)). + */ + isEmailAddress: function(data) { + if (!util.isString(data)) { + return false; + } + const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u; + return re.test(data); + }, + + /** + * Normalize line endings to + * Support any encoding where CR=0x0D, LF=0x0A + */ + canonicalizeEOL: function(data) { + const CR = 13; + const LF = 10; + let carryOverCR = false; + + return transform(data, bytes => { + if (carryOverCR) { + bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); + } + + if (bytes[bytes.length - 1] === CR) { + carryOverCR = true; + bytes = bytes.subarray(0, -1); + } else { + carryOverCR = false; + } + + let index; + const indices = []; + for (let i = 0; ; i = index) { + index = bytes.indexOf(LF, i) + 1; + if (index) { + if (bytes[index - 2] !== CR) indices.push(index); + } else { + break; + } + } + if (!indices.length) { + return bytes; + } + + const normalized = new Uint8Array(bytes.length + indices.length); + let j = 0; + for (let i = 0; i < indices.length; i++) { + const sub = bytes.subarray(indices[i - 1] || 0, indices[i]); + normalized.set(sub, j); + j += sub.length; + normalized[j - 1] = CR; + normalized[j] = LF; + j++; + } + normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j); + return normalized; + }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); + }, + + /** + * Convert line endings from canonicalized to native + * Support any encoding where CR=0x0D, LF=0x0A + */ + nativeEOL: function(data) { + const CR = 13; + const LF = 10; + let carryOverCR = false; + + return transform(data, bytes => { + if (carryOverCR && bytes[0] !== LF) { + bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); + } else { + bytes = new Uint8Array(bytes); // Don't mutate passed bytes + } + + if (bytes[bytes.length - 1] === CR) { + carryOverCR = true; + bytes = bytes.subarray(0, -1); + } else { + carryOverCR = false; + } + + let index; + let j = 0; + for (let i = 0; i !== bytes.length; i = index) { + index = bytes.indexOf(CR, i) + 1; + if (!index) index = bytes.length; + const last = index - (bytes[index] === LF ? 1 : 0); + if (i) bytes.copyWithin(j, i, last); + j += last - i; + } + return bytes.subarray(0, j); + }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); + }, + + /** + * Remove trailing spaces, carriage returns and tabs from each line + */ + removeTrailingSpaces: function(text) { + return text.split('\n').map(line => { + let i = line.length - 1; + for (; i >= 0 && (line[i] === ' ' || line[i] === '\t' || line[i] === '\r'); i--); + return line.substr(0, i + 1); + }).join('\n'); + }, + + wrapError: function(message, error) { + if (!error) { + return new Error(message); + } + + // update error message + try { + error.message = message + ': ' + error.message; + } catch (e) {} + + return error; + }, + + /** + * Map allowed packet tags to corresponding classes + * Meant to be used to format `allowedPacket` for Packetlist.read + * @param {Array} allowedClasses + * @returns {Object} map from enum.packet to corresponding *Packet class + */ + constructAllowedPackets: function(allowedClasses) { + const map = {}; + allowedClasses.forEach(PacketClass => { + if (!PacketClass.tag) { + throw new Error('Invalid input: expected a packet class'); + } + map[PacketClass.tag] = PacketClass; + }); + return map; + }, + + /** + * Return a Promise that will resolve as soon as one of the promises in input resolves + * or will reject if all input promises all rejected + * (similar to Promise.any, but with slightly different error handling) + * @param {Array} promises + * @return {Promise} Promise resolving to the result of the fastest fulfilled promise + * or rejected with the Error of the last resolved Promise (if all promises are rejected) + */ + anyPromise: function(promises) { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve, reject) => { + let exception; + await Promise.all(promises.map(async promise => { + try { + resolve(await promise); + } catch (e) { + exception = e; + } + })); + reject(exception); + }); + }, + + /** + * Return either `a` or `b` based on `cond`, in algorithmic constant time. + * @param {Boolean} cond + * @param {Uint8Array} a + * @param {Uint8Array} b + * @returns `a` if `cond` is true, `b` otherwise + */ + selectUint8Array: function(cond, a, b) { + const length = Math.max(a.length, b.length); + const result = new Uint8Array(length); + let end = 0; + for (let i = 0; i < result.length; i++) { + result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond)); + end += (cond & i < a.length) | ((1 - cond) & i < b.length); + } + return result.subarray(0, end); + }, + /** + * Return either `a` or `b` based on `cond`, in algorithmic constant time. + * NB: it only supports `a, b` with values between 0-255. + * @param {Boolean} cond + * @param {Uint8} a + * @param {Uint8} b + * @returns `a` if `cond` is true, `b` otherwise + */ + selectUint8: function(cond, a, b) { + return (a & (256 - cond)) | (b & (255 + cond)); + }, + /** + * @param {module:enums.symmetric} cipherAlgo + */ + isAES: function(cipherAlgo) { + return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256; + } +}; + +/* OpenPGP radix-64/base64 string encoding/decoding + * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de + * version 1.0, check www.haneWIN.de for the latest version + * + * This software is provided as-is, without express or implied warranty. + * Permission to use, copy, modify, distribute or sell this software, with or + * without fee, for any purpose and by any individual or organization, is hereby + * granted, provided that the above copyright notice and this paragraph appear + * in all copies. Distribution as a part of an application or binary must + * include the above copyright notice in the documentation and/or other materials + * provided with the application or distribution. + */ + + +const Buffer$3 = util.getNodeBuffer(); + +let encodeChunk; +let decodeChunk; +if (Buffer$3) { + encodeChunk = buf => Buffer$3.from(buf).toString('base64'); + decodeChunk = str => { + const b = Buffer$3.from(str, 'base64'); + return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); + }; +} else { + encodeChunk = buf => btoa(util.uint8ArrayToString(buf)); + decodeChunk = str => util.stringToUint8Array(atob(str)); +} + +/** + * Convert binary array to radix-64 + * @param {Uint8Array | ReadableStream} data - Uint8Array to convert + * @returns {String | ReadableStream} Radix-64 version of input string. + * @static + */ +function encode$1(data) { + let buf = new Uint8Array(); + return transform(data, value => { + buf = util.concatUint8Array([buf, value]); + const r = []; + const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64). + const lines = Math.floor(buf.length / bytesPerLine); + const bytes = lines * bytesPerLine; + const encoded = encodeChunk(buf.subarray(0, bytes)); + for (let i = 0; i < lines; i++) { + r.push(encoded.substr(i * 60, 60)); + r.push('\n'); + } + buf = buf.subarray(bytes); + return r.join(''); + }, () => (buf.length ? encodeChunk(buf) + '\n' : '')); +} + +/** + * Convert radix-64 to binary array + * @param {String | ReadableStream} data - Radix-64 string to convert + * @returns {Uint8Array | ReadableStream} Binary array version of input string. + * @static + */ +function decode$2(data) { + let buf = ''; + return transform(data, value => { + buf += value; + + // Count how many whitespace characters there are in buf + let spaces = 0; + const spacechars = [' ', '\t', '\r', '\n']; + for (let i = 0; i < spacechars.length; i++) { + const spacechar = spacechars[i]; + for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) { + spaces++; + } + } + + // Backtrack until we have 4n non-whitespace characters + // that we can safely base64-decode + let length = buf.length; + for (; length > 0 && (length - spaces) % 4 !== 0; length--) { + if (spacechars.includes(buf[length])) spaces--; + } + + const decoded = decodeChunk(buf.substr(0, length)); + buf = buf.substr(length); + return decoded; + }, () => decodeChunk(buf)); +} + +/** + * Convert a Base-64 encoded string an array of 8-bit integer + * + * Note: accepts both Radix-64 and URL-safe strings + * @param {String} base64 - Base-64 encoded string to convert + * @returns {Uint8Array} An array of 8-bit integers. + */ +function b64ToUint8Array(base64) { + return decode$2(base64.replace(/-/g, '+').replace(/_/g, '/')); +} + +/** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param {Uint8Array} bytes - An array of 8-bit integers to convert + * @param {bool} url - If true, output is URL-safe + * @returns {String} Base-64 encoded string. + */ +function uint8ArrayToB64(bytes, url) { + let encoded = encode$1(bytes).replace(/[\r\n]/g, ''); + { + encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); + } + return encoded; +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Finds out which Ascii Armoring type is used. Throws error if unknown type. + * @param {String} text - ascii armored text + * @returns {Integer} 0 = MESSAGE PART n of m. + * 1 = MESSAGE PART n + * 2 = SIGNED MESSAGE + * 3 = PGP MESSAGE + * 4 = PUBLIC KEY BLOCK + * 5 = PRIVATE KEY BLOCK + * 6 = SIGNATURE + * @private + */ +function getType(text) { + const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m; + + const header = text.match(reHeader); + + if (!header) { + throw new Error('Unknown ASCII armor type'); + } + + // BEGIN PGP MESSAGE, PART X/Y + // Used for multi-part messages, where the armor is split amongst Y + // parts, and this is the Xth part out of Y. + if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { + return enums.armor.multipartSection; + } + // BEGIN PGP MESSAGE, PART X + // Used for multi-part messages, where this is the Xth part of an + // unspecified number of parts. Requires the MESSAGE-ID Armor + // Header to be used. + if (/MESSAGE, PART \d+/.test(header[1])) { + return enums.armor.multipartLast; + } + // BEGIN PGP SIGNED MESSAGE + if (/SIGNED MESSAGE/.test(header[1])) { + return enums.armor.signed; + } + // BEGIN PGP MESSAGE + // Used for signed, encrypted, or compressed files. + if (/MESSAGE/.test(header[1])) { + return enums.armor.message; + } + // BEGIN PGP PUBLIC KEY BLOCK + // Used for armoring public keys. + if (/PUBLIC KEY BLOCK/.test(header[1])) { + return enums.armor.publicKey; + } + // BEGIN PGP PRIVATE KEY BLOCK + // Used for armoring private keys. + if (/PRIVATE KEY BLOCK/.test(header[1])) { + return enums.armor.privateKey; + } + // BEGIN PGP SIGNATURE + // Used for detached signatures, OpenPGP/MIME signatures, and + // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE + // for detached signatures. + if (/SIGNATURE/.test(header[1])) { + return enums.armor.signature; + } +} + +/** + * Add additional information to the armor version of an OpenPGP binary + * packet block. + * @author Alex + * @version 2011-12-16 + * @param {String} [customComment] - Additional comment to add to the armored string + * @returns {String} The header information. + * @private + */ +function addheader(customComment, config) { + let result = ''; + if (config.showVersion) { + result += 'Version: ' + config.versionString + '\n'; + } + if (config.showComment) { + result += 'Comment: ' + config.commentString + '\n'; + } + if (customComment) { + result += 'Comment: ' + customComment + '\n'; + } + result += '\n'; + return result; +} + +/** + * Calculates a checksum over the given data and returns it base64 encoded + * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for + * @returns {String | ReadableStream} Base64 encoded checksum. + * @private + */ +function getCheckSum(data) { + const crc = createcrc24(data); + return encode$1(crc); +} + +// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview + +const crc_table = [ + new Array(0xFF), + new Array(0xFF), + new Array(0xFF), + new Array(0xFF) +]; + +for (let i = 0; i <= 0xFF; i++) { + let crc = i << 16; + for (let j = 0; j < 8; j++) { + crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0); + } + crc_table[0][i] = + ((crc & 0xFF0000) >> 16) | + (crc & 0x00FF00) | + ((crc & 0x0000FF) << 16); +} +for (let i = 0; i <= 0xFF; i++) { + crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF]; +} +for (let i = 0; i <= 0xFF; i++) { + crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF]; +} +for (let i = 0; i <= 0xFF; i++) { + crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF]; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness +const isLittleEndian$1 = (function() { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 0xFF; +}()); + +/** + * Internal function to calculate a CRC-24 checksum over a given string (data) + * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for + * @returns {Uint8Array | ReadableStream} The CRC-24 checksum. + * @private + */ +function createcrc24(input) { + let crc = 0xCE04B7; + return transform(input, value => { + const len32 = isLittleEndian$1 ? Math.floor(value.length / 4) : 0; + const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32); + for (let i = 0; i < len32; i++) { + crc ^= arr32[i]; + crc = + crc_table[0][(crc >> 24) & 0xFF] ^ + crc_table[1][(crc >> 16) & 0xFF] ^ + crc_table[2][(crc >> 8) & 0xFF] ^ + crc_table[3][(crc >> 0) & 0xFF]; + } + for (let i = len32 * 4; i < value.length; i++) { + crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]]; + } + }, () => new Uint8Array([crc, crc >> 8, crc >> 16])); +} + +/** + * Verify armored headers. crypto-refresh-06, section 6.2: + * "An OpenPGP implementation may consider improperly formatted Armor + * Headers to be corruption of the ASCII Armor, but SHOULD make an + * effort to recover." + * @private + * @param {Array} headers - Armor headers + */ +function verifyHeaders$1(headers) { + for (let i = 0; i < headers.length; i++) { + if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { + util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); + } + if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) { + util.printDebugError(new Error('Unknown header: ' + headers[i])); + } + } +} + +/** + * Remove the (optional) checksum from an armored message. + * @param {String} text - OpenPGP armored message + * @returns {String} The body of the armored message. + * @private + */ +function removeChecksum(text) { + let body = text; + + const lastEquals = text.lastIndexOf('='); + + if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum + body = text.slice(0, lastEquals); + } + + return body; +} + +/** + * Dearmor an OpenPGP armored message; verify the checksum and return + * the encoded bytes + * @param {String} input - OpenPGP armored message + * @returns {Promise} An object with attribute "text" containing the message text, + * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type + * @async + * @static + */ +function unarmor(input) { + // eslint-disable-next-line no-async-promise-executor + return new Promise(async (resolve, reject) => { + try { + const reSplit = /^-----[^-]+-----$/m; + const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/; + + let type; + const headers = []; + let lastHeaders = headers; + let headersDone; + let text = []; + let textDone; + const data = decode$2(transformPair(input, async (readable, writable) => { + const reader = getReader(readable); + try { + while (true) { + let line = await reader.readLine(); + if (line === undefined) { + throw new Error('Misformed armored text'); + } + // remove trailing whitespace at end of lines + line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, '')); + if (!type) { + if (reSplit.test(line)) { + type = getType(line); + } + } else if (!headersDone) { + if (reSplit.test(line)) { + reject(new Error('Mandatory blank line missing between armor headers and armor data')); + } + if (!reEmptyLine.test(line)) { + lastHeaders.push(line); + } else { + verifyHeaders$1(lastHeaders); + headersDone = true; + if (textDone || type !== enums.armor.signed) { + resolve({ text, data, headers, type }); + break; + } + } + } else if (!textDone && type === enums.armor.signed) { + if (!reSplit.test(line)) { + // Reverse dash-escaping for msg + text.push(line.replace(/^- /, '')); + } else { + text = text.join('\r\n'); + textDone = true; + verifyHeaders$1(lastHeaders); + lastHeaders = []; + headersDone = false; + } + } + } + } catch (e) { + reject(e); + return; + } + const writer = getWriter(writable); + try { + while (true) { + await writer.ready; + const { done, value } = await reader.read(); + if (done) { + throw new Error('Misformed armored text'); + } + const line = value + ''; + if (line.indexOf('=') === -1 && line.indexOf('-') === -1) { + await writer.write(line); + } else { + let remainder = await reader.readToEnd(); + if (!remainder.length) remainder = ''; + remainder = line + remainder; + remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, '')); + const parts = remainder.split(reSplit); + if (parts.length === 1) { + throw new Error('Misformed armored text'); + } + const body = removeChecksum(parts[0].slice(0, -1)); + await writer.write(body); + break; + } + } + await writer.ready; + await writer.close(); + } catch (e) { + await writer.abort(e); + } + })); + } catch (e) { + reject(e); + } + }).then(async result => { + if (isArrayStream(result.data)) { + result.data = await readToEnd(result.data); + } + return result; + }); +} + + +/** + * Armor an OpenPGP binary packet block + * @param {module:enums.armor} messageType - Type of the message + * @param {Uint8Array | ReadableStream} body - The message body to armor + * @param {Integer} [partIndex] + * @param {Integer} [partTotal] + * @param {String} [customComment] - Additional comment to add to the armored string + * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum + * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks) + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {String | ReadableStream} Armored text. + * @static + */ +function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) { + let text; + let hash; + if (messageType === enums.armor.signed) { + text = body.text; + hash = body.hash; + body = body.data; + } + // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug + // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071) + const maybeBodyClone = emitChecksum && passiveClone(body); + + const result = []; + switch (messageType) { + case enums.armor.multipartSection: + result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); + break; + case enums.armor.multipartLast: + result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); + break; + case enums.armor.signed: + result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); + result.push(hash ? `Hash: ${hash}\n\n` : '\n'); + result.push(text.replace(/^-/mg, '- -')); + result.push('\n-----BEGIN PGP SIGNATURE-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP SIGNATURE-----\n'); + break; + case enums.armor.message: + result.push('-----BEGIN PGP MESSAGE-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP MESSAGE-----\n'); + break; + case enums.armor.publicKey: + result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); + break; + case enums.armor.privateKey: + result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); + break; + case enums.armor.signature: + result.push('-----BEGIN PGP SIGNATURE-----\n'); + result.push(addheader(customComment, config$1)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); + result.push('-----END PGP SIGNATURE-----\n'); + break; + } + + return util.concat(result); +} + +async function getLegacyCipher(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + throw new Error('Not a legacy cipher'); + case enums.symmetric.cast5: + case enums.symmetric.blowfish: + case enums.symmetric.twofish: + case enums.symmetric.tripledes: { + const { legacyCiphers } = await Promise.resolve().then(function () { return legacy_ciphers; }); + const cipher = legacyCiphers.get(algo); + if (!cipher) { + throw new Error('Unsupported cipher algorithm'); + } + return cipher; + } + default: + throw new Error('Unsupported cipher algorithm'); + } +} + +/** + * Get block size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherBlockSize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 16; + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + case enums.symmetric.tripledes: + return 8; + default: + throw new Error('Unsupported cipher'); + } +} + +/** + * Get key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherKeySize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + return 16; + case enums.symmetric.aes192: + case enums.symmetric.tripledes: + return 24; + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 32; + default: + throw new Error('Unsupported cipher'); + } +} + +/** + * Get block and key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherParams(algo) { + return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) }; +} + +var cipher = /*#__PURE__*/Object.freeze({ + __proto__: null, + getCipherParams: getCipherParams, + getLegacyCipher: getLegacyCipher +}); + +/** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ + + +// MD5 Digest +async function md5(entree) { + const digest = md51(util.uint8ArrayToString(entree)); + return util.hexToUint8Array(hex(digest)); +} + +function md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + + a = ff(a, b, c, d, k[0], 7, -680876936); + d = ff(d, a, b, c, k[1], 12, -389564586); + c = ff(c, d, a, b, k[2], 17, 606105819); + b = ff(b, c, d, a, k[3], 22, -1044525330); + a = ff(a, b, c, d, k[4], 7, -176418897); + d = ff(d, a, b, c, k[5], 12, 1200080426); + c = ff(c, d, a, b, k[6], 17, -1473231341); + b = ff(b, c, d, a, k[7], 22, -45705983); + a = ff(a, b, c, d, k[8], 7, 1770035416); + d = ff(d, a, b, c, k[9], 12, -1958414417); + c = ff(c, d, a, b, k[10], 17, -42063); + b = ff(b, c, d, a, k[11], 22, -1990404162); + a = ff(a, b, c, d, k[12], 7, 1804603682); + d = ff(d, a, b, c, k[13], 12, -40341101); + c = ff(c, d, a, b, k[14], 17, -1502002290); + b = ff(b, c, d, a, k[15], 22, 1236535329); + + a = gg(a, b, c, d, k[1], 5, -165796510); + d = gg(d, a, b, c, k[6], 9, -1069501632); + c = gg(c, d, a, b, k[11], 14, 643717713); + b = gg(b, c, d, a, k[0], 20, -373897302); + a = gg(a, b, c, d, k[5], 5, -701558691); + d = gg(d, a, b, c, k[10], 9, 38016083); + c = gg(c, d, a, b, k[15], 14, -660478335); + b = gg(b, c, d, a, k[4], 20, -405537848); + a = gg(a, b, c, d, k[9], 5, 568446438); + d = gg(d, a, b, c, k[14], 9, -1019803690); + c = gg(c, d, a, b, k[3], 14, -187363961); + b = gg(b, c, d, a, k[8], 20, 1163531501); + a = gg(a, b, c, d, k[13], 5, -1444681467); + d = gg(d, a, b, c, k[2], 9, -51403784); + c = gg(c, d, a, b, k[7], 14, 1735328473); + b = gg(b, c, d, a, k[12], 20, -1926607734); + + a = hh(a, b, c, d, k[5], 4, -378558); + d = hh(d, a, b, c, k[8], 11, -2022574463); + c = hh(c, d, a, b, k[11], 16, 1839030562); + b = hh(b, c, d, a, k[14], 23, -35309556); + a = hh(a, b, c, d, k[1], 4, -1530992060); + d = hh(d, a, b, c, k[4], 11, 1272893353); + c = hh(c, d, a, b, k[7], 16, -155497632); + b = hh(b, c, d, a, k[10], 23, -1094730640); + a = hh(a, b, c, d, k[13], 4, 681279174); + d = hh(d, a, b, c, k[0], 11, -358537222); + c = hh(c, d, a, b, k[3], 16, -722521979); + b = hh(b, c, d, a, k[6], 23, 76029189); + a = hh(a, b, c, d, k[9], 4, -640364487); + d = hh(d, a, b, c, k[12], 11, -421815835); + c = hh(c, d, a, b, k[15], 16, 530742520); + b = hh(b, c, d, a, k[2], 23, -995338651); + + a = ii(a, b, c, d, k[0], 6, -198630844); + d = ii(d, a, b, c, k[7], 10, 1126891415); + c = ii(c, d, a, b, k[14], 15, -1416354905); + b = ii(b, c, d, a, k[5], 21, -57434055); + a = ii(a, b, c, d, k[12], 6, 1700485571); + d = ii(d, a, b, c, k[3], 10, -1894986606); + c = ii(c, d, a, b, k[10], 15, -1051523); + b = ii(b, c, d, a, k[1], 21, -2054922799); + a = ii(a, b, c, d, k[8], 6, 1873313359); + d = ii(d, a, b, c, k[15], 10, -30611744); + c = ii(c, d, a, b, k[6], 15, -1560198380); + b = ii(b, c, d, a, k[13], 21, 1309151649); + a = ii(a, b, c, d, k[4], 6, -145523070); + d = ii(d, a, b, c, k[11], 10, -1120210379); + c = ii(c, d, a, b, k[2], 15, 718787259); + b = ii(b, c, d, a, k[9], 21, -343485551); + + x[0] = add32(a, x[0]); + x[1] = add32(b, x[1]); + x[2] = add32(c, x[2]); + x[3] = add32(d, x[3]); +} + +function cmn(q, a, b, x, s, t) { + a = add32(add32(a, q), add32(x, t)); + return add32((a << s) | (a >>> (32 - s)), b); +} + +function ff(a, b, c, d, x, s, t) { + return cmn((b & c) | ((~b) & d), a, b, x, s, t); +} + +function gg(a, b, c, d, x, s, t) { + return cmn((b & d) | (c & (~d)), a, b, x, s, t); +} + +function hh(a, b, c, d, x, s, t) { + return cmn(b ^ c ^ d, a, b, x, s, t); +} + +function ii(a, b, c, d, x, s, t) { + return cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +function md51(s) { + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; + for (i = 64; i <= s.length; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); + } + s = s.substring(i - 64); + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < s.length; i++) { + tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + } + tail[i >> 2] |= 0x80 << ((i % 4) << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i++) { + tail[i] = 0; + } + } + tail[14] = n * 8; + md5cycle(state, tail); + return state; +} + +/* there needs to be support for Unicode here, + * unless we pretend that we can redefine the MD-5 + * algorithm for multi-byte characters (perhaps + * by adding every four 16-bit characters and + * shortening the sum to 32 bits). Otherwise + * I suggest performing MD-5 as if every character + * was two bytes--e.g., 0040 0025 = @%--but then + * how will an ordinary MD-5 sum be matched? + * There is no way to standardize text to something + * like UTF-8 before transformation; speed cost is + * utterly prohibitive. The JavaScript standard + * itself needs to look at this: it should start + * providing access to strings as preformed UTF-8 + * 8-bit unsigned value arrays. + */ +function md5blk(s) { /* I figured global was faster. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << + 24); + } + return md5blks; +} + +const hex_chr = '0123456789abcdef'.split(''); + +function rhex(n) { + let s = ''; + let j = 0; + for (; j < 4; j++) { + s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; + } + return s; +} + +function hex(x) { + for (let i = 0; i < x.length; i++) { + x[i] = rhex(x[i]); + } + return x.join(''); +} + +/* this function is much faster, +so if possible we use it. Some IEs +are the only ones I know of that +need the idiotic second function, +generated by an if clause. */ + +function add32(a, b) { + return (a + b) & 0xFFFFFFFF; +} + +/** + * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. + * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} + * @see {@link https://github.com/indutny/hash.js|hash.js} + * @module crypto/hash + */ + + +const webCrypto$a = util.getWebCrypto(); +const nodeCrypto$9 = util.getNodeCrypto(); +const nodeCryptoHashes = nodeCrypto$9 && nodeCrypto$9.getHashes(); + +function nodeHash(type) { + if (!nodeCrypto$9 || !nodeCryptoHashes.includes(type)) { + return; + } + return async function (data) { + const shasum = nodeCrypto$9.createHash(type); + return transform(data, value => { + shasum.update(value); + }, () => new Uint8Array(shasum.digest())); + }; +} + +function nobleHash(nobleHashName, webCryptoHashName) { + const getNobleHash = async () => { + const { nobleHashes } = await Promise.resolve().then(function () { return noble_hashes; }); + const hash = nobleHashes.get(nobleHashName); + if (!hash) throw new Error('Unsupported hash'); + return hash; + }; + + return async function(data) { + if (isArrayStream(data)) { + data = await readToEnd(data); + } + if (util.isStream(data)) { + const hash = await getNobleHash(); + + const hashInstance = hash.create(); + return transform(data, value => { + hashInstance.update(value); + }, () => hashInstance.digest()); + } else if (webCrypto$a && webCryptoHashName) { + return new Uint8Array(await webCrypto$a.digest(webCryptoHashName, data)); + } else { + const hash = await getNobleHash(); + + return hash(data); + } + }; +} + +var hash$1 = { + + /** @see module:md5 */ + md5: nodeHash('md5') || md5, + sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'), + sha224: nodeHash('sha224') || nobleHash('sha224'), + sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'), + sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'), + sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'), + ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'), + sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'), + sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'), + + /** + * Create a hash on the specified data using the specified algorithm + * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param {Uint8Array} data - Data to be hashed + * @returns {Promise} Hash value. + */ + digest: function(algo, data) { + switch (algo) { + case enums.hash.md5: + return this.md5(data); + case enums.hash.sha1: + return this.sha1(data); + case enums.hash.ripemd: + return this.ripemd(data); + case enums.hash.sha256: + return this.sha256(data); + case enums.hash.sha384: + return this.sha384(data); + case enums.hash.sha512: + return this.sha512(data); + case enums.hash.sha224: + return this.sha224(data); + case enums.hash.sha3_256: + return this.sha3_256(data); + case enums.hash.sha3_512: + return this.sha3_512(data); + default: + throw new Error('Unsupported hash function'); + } + }, + + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns {Integer} Size in bytes of the resulting hash. + */ + getHashByteLength: function(algo) { + switch (algo) { + case enums.hash.md5: + return 16; + case enums.hash.sha1: + case enums.hash.ripemd: + return 20; + case enums.hash.sha256: + return 32; + case enums.hash.sha384: + return 48; + case enums.hash.sha512: + return 64; + case enums.hash.sha224: + return 28; + case enums.hash.sha3_256: + return 32; + case enums.hash.sha3_512: + return 64; + default: + throw new Error('Invalid hash algorithm.'); + } + } +}; + +function isBytes$2(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes$1(b, ...lengths) { + if (!isBytes$2(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output$1(out, instance) { + bytes$1(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// Cast array to different type +const u8$1 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32$2 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE$1) + throw new Error('Non little-endian hardware is not supported'); +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$2(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes$1(data) { + if (typeof data === 'string') + data = utf8ToBytes$2(data); + else if (isBytes$2(data)) + data = copyBytes(data); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes$1(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes$1(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +// Polyfill for Safari 14 +function setBigUint64$1(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = 0; + const l = 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +// copy bytes to new u8a (aligned). Because Buffer.slice is broken. +function copyBytes(bytes) { + return Uint8Array.from(bytes); +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE$1 = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32$2(ZEROS16); +const POLY$1 = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2$1 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE$1; + this.outputLen = BLOCK_SIZE$1; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes$1(key); + bytes$1(key, 16); + const kView = createView$1(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + const left = data.length % BLOCK_SIZE$1; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + clean(ZEROS32); // clean tmp buffer + } + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE$1); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes$1(key); + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const left = data.length % BLOCK_SIZE$1; + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + clean(ZEROS32); + } + return this; + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes$1(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + +// prettier-ignore +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// The byte swap operation for uint32 (LE<->BE) +const byteSwap$1 = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +function expandKeyLE(key) { + bytes$1(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const toClean = []; + if (!isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = u32$2(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; +} +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (dst === undefined) + return new Uint8Array(len); + bytes$1(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + if (!isAligned32(dst)) + throw new Error('unaligned dst'); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32$2(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32$2(ctr); + const view = createView$1(ctr); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + bytes$1(key); + bytes$1(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + bytes$1(buf); + if (dst !== undefined) { + bytes$1(dst); + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + bytes$1(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + bytes$1(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (!isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32$2(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32$2(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error('aes/pcks5: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error('aes/pcks5: wrong padding'); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error('aes/pcks5: wrong padding'); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32$2(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + bytes$1(key); + bytes$1(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + const out = getDst(ciphertext.length, dst); + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32$2(ciphertext); + const o = u32$2(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$6(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); + } + clean(...toClean); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +const cfb$1 = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + bytes$1(key); + bytes$1(iv, 16); + function processCfb(src, isEncrypt, dst) { + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$6(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + const buf = u8$1(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD == null ? 0 : AAD.length; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView$1(num); + if (AAD) + setBigUint64$1(view, 0, BigInt(aadLength * 8), isLE); + setBigUint64$1(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} +/** + * GCM: Galois/Counter Mode. + * Modern, parallel version of CTR, with MAC. + * Be careful: MACs can be forged. + * Unsafe to use random nonces under the same key, due to collision chance. + * As for nonce size, prefer 12-byte, instead of 8-byte. + */ +const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + bytes$1(key); + bytes$1(nonce); + if (AAD !== undefined) + bytes$1(AAD); + // NIST 800-38d doesn't enforce minimum nonce length. + // We enforce 8 bytes for compat with openssl. + // 12 bytes are recommended. More than 12 bytes would be converted into 12. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); + } + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView$1(nonceLen); + setBigUint64$1(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + bytes$1(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + if (!equalBytes$1(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = encrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = decrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +/** + * AES-W (base for AESKW/AESKWP). + * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf), + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/). + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints. + // If you need it larger, open an issue. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i + (a0 = s0), (a1 = s1 ^ byteSwap$1(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); // out = A || out + } + xk.fill(0); + }, + decrypt(kek, out) { + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap$1(ctr); + const { s0, s1, s2, s3 } = decrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); + } + xk.fill(0); + }, +}; +const AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * For padded version, use aeskwp. + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf). + */ +const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + bytes$1(plaintext); + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes$2(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes$1(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, +})); +// Private, unsafe low-level methods. Can change at any time. +const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt: encrypt$6, + decrypt: decrypt$6, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; + +// Modified by ProtonTech AG + + +const webCrypto$9 = util.getWebCrypto(); +const nodeCrypto$8 = util.getNodeCrypto(); + +const knownAlgos = nodeCrypto$8 ? nodeCrypto$8.getCiphers() : []; +const nodeAlgos = { + idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ + tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, + cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, + blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, + aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, + aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, + aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined + /* twofish is not implemented in OpenSSL */ +}; + +/** + * CFB encryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} plaintext + * @param {Uint8Array} iv + * @param {Object} config - full configuration, defaults to openpgp.config + * @returns MaybeStream + */ +async function encrypt$5(algo, key, plaintext, iv, config) { + const algoName = enums.read(enums.symmetric, algo); + if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. + return nodeEncrypt$1(algo, key, plaintext, iv); + } + if (util.isAES(algo)) { + return aesEncrypt(algo, key, plaintext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; + + const blockc = iv.slice(); + let pt = new Uint8Array(); + const process = chunk => { + if (chunk) { + pt = util.concatUint8Array([pt, chunk]); + } + const ciphertext = new Uint8Array(pt.length); + let i; + let j = 0; + while (chunk ? pt.length >= block_size : pt.length) { + const encblock = cipherfn.encrypt(blockc); + for (i = 0; i < block_size; i++) { + blockc[i] = pt[i] ^ encblock[i]; + ciphertext[j++] = blockc[i]; + } + pt = pt.subarray(block_size); + } + return ciphertext.subarray(0, j); + }; + return transform(plaintext, process, process); +} + +/** + * CFB decryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} ciphertext + * @param {Uint8Array} iv + * @returns MaybeStream + */ +async function decrypt$5(algo, key, ciphertext, iv) { + const algoName = enums.read(enums.symmetric, algo); + if (nodeCrypto$8 && nodeAlgos[algoName]) { // Node crypto library. + return nodeDecrypt$1(algo, key, ciphertext, iv); + } + if (util.isAES(algo)) { + return aesDecrypt(algo, key, ciphertext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; + + let blockp = iv; + let ct = new Uint8Array(); + const process = chunk => { + if (chunk) { + ct = util.concatUint8Array([ct, chunk]); + } + const plaintext = new Uint8Array(ct.length); + let i; + let j = 0; + while (chunk ? ct.length >= block_size : ct.length) { + const decblock = cipherfn.encrypt(blockp); + blockp = ct.subarray(0, block_size); + for (i = 0; i < block_size; i++) { + plaintext[j++] = blockp[i] ^ decblock[i]; + } + ct = ct.subarray(block_size); + } + return plaintext.subarray(0, j); + }; + return transform(ciphertext, process, process); +} + +class WebCryptoEncryptor { + constructor(algo, key, iv) { + const { blockSize } = getCipherParams(algo); + this.key = key; + this.prevBlock = iv; + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + this.zeroBlock = new Uint8Array(this.blockSize); + } + + static async isSupported(algo) { + const { keySize } = getCipherParams(algo); + return webCrypto$9.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt']) + .then(() => true, () => false); + } + + async _runCBC(plaintext, nonZeroIV) { + const mode = 'AES-CBC'; + this.keyRef = this.keyRef || await webCrypto$9.importKey('raw', this.key, mode, false, ['encrypt']); + const ciphertext = await webCrypto$9.encrypt( + { name: mode, iv: nonZeroIV || this.zeroBlock }, + this.keyRef, + plaintext + ); + return new Uint8Array(ciphertext).subarray(0, plaintext.length); + } + + async encryptChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const plaintext = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + const toEncrypt = util.concatUint8Array([ + this.prevBlock, + plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock + ]); + + const encryptedBlocks = await this._runCBC(toEncrypt); + xorMut$1(encryptedBlocks, plaintext); + this.prevBlock = encryptedBlocks.slice(-this.blockSize); + + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; + + return encryptedBlocks; + } + + this.i += added.length; + let encryptedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + const curBlock = this.nextBlock; + encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + this.prevBlock = encryptedBlock.slice(); + this.i = 0; + + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + encryptedBlock = new Uint8Array(); + } + + return encryptedBlock; + } + + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + this.nextBlock = this.nextBlock.subarray(0, this.i); + const curBlock = this.nextBlock; + const encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + result = encryptedBlock.subarray(0, curBlock.length); + } + + this.clearSensitiveData(); + return result; + } + + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.keyRef = null; + this.key = null; + } + + async encrypt(plaintext) { + // plaintext is internally padded to block length before encryption + const encryptedWithPadding = await this._runCBC( + util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), + this.iv + ); + // drop encrypted padding + const ct = encryptedWithPadding.subarray(0, plaintext.length); + xorMut$1(ct, plaintext); + this.clearSensitiveData(); + return ct; + } +} + +class NobleStreamProcessor { + constructor(forEncryption, algo, key, iv) { + this.forEncryption = forEncryption; + const { blockSize } = getCipherParams(algo); + this.key = unsafe.expandKeyLE(key); + + if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers + this.prevBlock = getUint32Array(iv); + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + } + + _runCFB(src) { + const src32 = getUint32Array(src); + const dst = new Uint8Array(src.length); + const dst32 = getUint32Array(dst); + for (let i = 0; i + 4 <= dst32.length; i += 4) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4); + } + return dst; + } + + async processChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const toProcess = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + + const processedBlocks = this._runCFB(toProcess); + + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; + + return processedBlocks; + } + + this.i += added.length; + + let processedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + processedBlock = this._runCFB(this.nextBlock); + this.i = 0; + + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + processedBlock = new Uint8Array(); + } + + return processedBlock; + } + + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + const processedBlock = this._runCFB(this.nextBlock); + + result = processedBlock.subarray(0, this.i); + } + + this.clearSensitiveData(); + return result; + } + + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.key.fill(0); + } +} + + +async function aesEncrypt(algo, key, pt, iv) { + if (webCrypto$9 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys + const cfb = new WebCryptoEncryptor(algo, key, iv); + return util.isStream(pt) ? transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt); + } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream + const cfb = new NobleStreamProcessor(true, algo, key, iv); + return transform(pt, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).encrypt(pt); +} + +async function aesDecrypt(algo, key, ct, iv) { + if (util.isStream(ct)) { + const cfb = new NobleStreamProcessor(false, algo, key, iv); + return transform(ct, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).decrypt(ct); +} + +function xorMut$1(a, b) { + const aLength = Math.min(a.length, b.length); + for (let i = 0; i < aLength; i++) { + a[i] = a[i] ^ b[i]; + } +} + +const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + +function nodeEncrypt$1(algo, key, pt, iv) { + const algoName = enums.read(enums.symmetric, algo); + const cipherObj = new nodeCrypto$8.createCipheriv(nodeAlgos[algoName], key, iv); + return transform(pt, value => new Uint8Array(cipherObj.update(value))); +} + +function nodeDecrypt$1(algo, key, ct, iv) { + const algoName = enums.read(enums.symmetric, algo); + const decipherObj = new nodeCrypto$8.createDecipheriv(nodeAlgos[algoName], key, iv); + return transform(ct, value => new Uint8Array(decipherObj.update(value))); +} + +var cfb = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$5, + encrypt: encrypt$5 +}); + +/** + * @fileoverview This module implements AES-CMAC on top of + * native AES-CBC using either the WebCrypto API or Node.js' crypto API. + * @module crypto/cmac + */ + + +const webCrypto$8 = util.getWebCrypto(); +const nodeCrypto$7 = util.getNodeCrypto(); + + +/** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ + +const blockLength$3 = 16; + + +/** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param {Uint8Array} data + * @param {Uint8Array} padding + */ +function rightXORMut(data, padding) { + const offset = data.length - blockLength$3; + for (let i = 0; i < blockLength$3; i++) { + data[i + offset] ^= padding[i]; + } + return data; +} + +function pad(data, padding, padding2) { + // if |M| in {n, 2n, 3n, ...} + if (data.length && data.length % blockLength$3 === 0) { + // then return M xor→ B, + return rightXORMut(data, padding); + } + // else return (M || 10^(n−1−(|M| mod n))) xor→ P + const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3))); + padded.set(data); + padded[data.length] = 0b10000000; + return rightXORMut(padded, padding2); +} + +const zeroBlock$1 = new Uint8Array(blockLength$3); + +async function CMAC(key) { + const cbc = await CBC(key); + + // L ← E_K(0^n); B ← 2L; P ← 4L + const padding = util.double(await cbc(zeroBlock$1)); + const padding2 = util.double(padding); + + return async function(data) { + // return CBC_K(pad(M; B, P)) + return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3); + }; +} + +async function CBC(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt) { + const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1); + const ct = en.update(pt); + return new Uint8Array(ct); + }; + } + + if (util.getWebCrypto()) { + try { + key = await webCrypto$8.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); + return async function(pt) { + const ct = await webCrypto$8.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt); + return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } + + return async function(pt) { + return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt); + }; +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$7 = util.getWebCrypto(); +const nodeCrypto$6 = util.getNodeCrypto(); +const Buffer$2 = util.getNodeBuffer(); + + +const blockLength$2 = 16; +const ivLength$2 = blockLength$2; +const tagLength$2 = blockLength$2; + +const zero = new Uint8Array(blockLength$2); +const one$1 = new Uint8Array(blockLength$2); one$1[blockLength$2 - 1] = 1; +const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2; + +async function OMAC(key) { + const cmac = await CMAC(key); + return function(t, message) { + return cmac(util.concatUint8Array([t, message])); + }; +} + +async function CTR(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt, iv) { + const en = new nodeCrypto$6.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); + const ct = Buffer$2.concat([en.update(pt), en.final()]); + return new Uint8Array(ct); + }; + } + + if (util.getWebCrypto()) { + try { + const keyRef = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); + return async function(pt, iv) { + const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt); + return new Uint8Array(ct); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } + + return async function(pt, iv) { + return ctr(key, iv).encrypt(pt); + }; +} + + +/** + * Class to en/decrypt using EAX mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function EAX(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('EAX mode supports only AES cipher'); + } + + const [ + omac, + ctr + ] = await Promise.all([ + OMAC(key), + CTR(key) + ]); + + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + const [ + omacNonce, + omacAdata + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata) + ]); + const ciphered = await ctr(plaintext, omacNonce); + const omacCiphered = await omac(two, ciphered); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + return util.concatUint8Array([ciphered, tag]); + }, + + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to verify + * @returns {Promise} The plaintext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$2) throw new Error('Invalid EAX ciphertext'); + const ciphered = ciphertext.subarray(0, -tagLength$2); + const ctTag = ciphertext.subarray(-tagLength$2); + const [ + omacNonce, + omacAdata, + omacCiphered + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata), + omac(two, ciphered) + ]); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); + const plaintext = await ctr(ciphered, omacNonce); + return plaintext; + } + }; +} + + +/** + * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. + * @param {Uint8Array} iv - The initialization vector (16 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +EAX.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[8 + i] ^= chunkIndex[i]; + } + return nonce; +}; + +EAX.blockLength = blockLength$2; +EAX.ivLength = ivLength$2; +EAX.tagLength = tagLength$2; + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const blockLength$1 = 16; +const ivLength$1 = 15; + +// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: +// While OCB [RFC7253] allows the authentication tag length to be of any +// number up to 128 bits long, this document requires a fixed +// authentication tag length of 128 bits (16 octets) for simplicity. +const tagLength$1 = 16; + + +function ntz(n) { + let ntz = 0; + for (let i = 1; (n & i) === 0; i <<= 1) { + ntz++; + } + return ntz; +} + +function xorMut(S, T) { + for (let i = 0; i < S.length; i++) { + S[i] ^= T[i]; + } + return S; +} + +function xor(S, T) { + return xorMut(S.slice(), T); +} + +const zeroBlock = new Uint8Array(blockLength$1); +const one = new Uint8Array([1]); + +/** + * Class to en/decrypt using OCB mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function OCB(cipher, key) { + const { keySize } = getCipherParams(cipher); + // sanity checks + if (!util.isAES(cipher) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } + + let maxNtz = 0; + + // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls, + // hence its execution cannot be broken up. + // As a result, WebCrypto cannot currently be used for `encipher`. + const aes = cbc(key, zeroBlock, { disablePadding: true }); + const encipher = block => aes.encrypt(block); + const decipher = block => aes.decrypt(block); + let mask; + + constructKeyVariables(); + + function constructKeyVariables() { + const mask_x = encipher(zeroBlock); + const mask_$ = util.double(mask_x); + mask = []; + mask[0] = util.double(mask_$); + + + mask.x = mask_x; + mask.$ = mask_$; + } + + function extendKeyVariables(text, adata) { + const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1; + for (let i = maxNtz + 1; i <= newMaxNtz; i++) { + mask[i] = util.double(mask[i - 1]); + } + maxNtz = newMaxNtz; + } + + function hash(adata) { + if (!adata.length) { + // Fast path + return zeroBlock; + } + + // + // Consider A as a sequence of 128-bit blocks + // + const m = adata.length / blockLength$1 | 0; + + const offset = new Uint8Array(blockLength$1); + const sum = new Uint8Array(blockLength$1); + for (let i = 0; i < m; i++) { + xorMut(offset, mask[ntz(i + 1)]); + xorMut(sum, encipher(xor(offset, adata))); + adata = adata.subarray(blockLength$1); + } + + // + // Process any final partial block; compute final hash value + // + if (adata.length) { + xorMut(offset, mask.x); + + const cipherInput = new Uint8Array(blockLength$1); + cipherInput.set(adata, 0); + cipherInput[adata.length] = 0b10000000; + xorMut(cipherInput, offset); + + xorMut(sum, encipher(cipherInput)); + } + + return sum; + } + + /** + * Encrypt/decrypt data. + * @param {encipher|decipher} fn - Encryption/decryption block cipher function + * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. + */ + function crypt(fn, text, nonce, adata) { + // + // Consider P as a sequence of 128-bit blocks + // + const m = text.length / blockLength$1 | 0; + + // + // Key-dependent variables + // + extendKeyVariables(text, adata); + + // + // Nonce-dependent and per-encryption variables + // + // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + // Note: We assume here that tagLength mod 16 == 0. + const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]); + // bottom = str2num(Nonce[123..128]) + const bottom = paddedNonce[blockLength$1 - 1] & 0b111111; + // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + paddedNonce[blockLength$1 - 1] &= 0b11000000; + const kTop = encipher(paddedNonce); + // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); + // Offset_0 = Stretch[1+bottom..128+bottom] + const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); + // Checksum_0 = zeros(128) + const checksum = new Uint8Array(blockLength$1); + + const ct = new Uint8Array(text.length + tagLength$1); + + // + // Process any whole blocks + // + let i; + let pos = 0; + for (i = 0; i < m; i++) { + // Offset_i = Offset_{i-1} xor L_{ntz(i)} + xorMut(offset, mask[ntz(i + 1)]); + // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + ct.set(xorMut(fn(xor(offset, text)), offset), pos); + // Checksum_i = Checksum_{i-1} xor P_i + xorMut(checksum, fn === encipher ? text : ct.subarray(pos)); + + text = text.subarray(blockLength$1); + pos += blockLength$1; + } + + // + // Process any final partial block and compute raw tag + // + if (text.length) { + // Offset_* = Offset_m xor L_* + xorMut(offset, mask.x); + // Pad = ENCIPHER(K, Offset_*) + const padding = encipher(offset); + // C_* = P_* xor Pad[1..bitlen(P_*)] + ct.set(xor(text, padding), pos); + + // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) + const xorInput = new Uint8Array(blockLength$1); + xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); + xorInput[text.length] = 0b10000000; + xorMut(checksum, xorInput); + pos += text.length; + } + // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata)); + + // + // Assemble ciphertext + // + // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] + ct.set(tag, pos); + return ct; + } + + + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + return crypt(encipher, plaintext, nonce, adata); + }, + + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); + + const tag = ciphertext.subarray(-tagLength$1); + ciphertext = ciphertext.subarray(0, -tagLength$1); + + const crypted = crypt(decipher, ciphertext, nonce, adata); + // if (Tag[1..TAGLEN] == T) + if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { + return crypted.subarray(0, -tagLength$1); + } + throw new Error('Authentication tag mismatch'); + } + }; +} + + +/** + * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. + * @param {Uint8Array} iv - The initialization vector (15 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +OCB.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[7 + i] ^= chunkIndex[i]; + } + return nonce; +}; + +OCB.blockLength = blockLength$1; +OCB.ivLength = ivLength$1; +OCB.tagLength = tagLength$1; + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$6 = util.getWebCrypto(); +const nodeCrypto$5 = util.getNodeCrypto(); +const Buffer$1 = util.getNodeBuffer(); + +const blockLength = 16; +const ivLength = 12; // size of the IV in bytes +const tagLength = 16; // size of the tag in bytes +const ALGO = 'AES-GCM'; + +/** + * Class to en/decrypt using GCM mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function GCM(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('GCM mode supports only AES cipher'); + } + + if (util.getNodeCrypto()) { // Node crypto library + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + const en = new nodeCrypto$5.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + en.setAAD(adata); + const ct = Buffer$1.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext + return new Uint8Array(ct); + }, + + decrypt: async function(ct, iv, adata = new Uint8Array()) { + const de = new nodeCrypto$5.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + de.setAAD(adata); + de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext + const pt = Buffer$1.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]); + return new Uint8Array(pt); + } + }; + } + + if (util.getWebCrypto()) { + try { + const _key = await webCrypto$6.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); + // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages + const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) || + navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/); + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && !pt.length) { + return gcm(key, iv, adata).encrypt(pt); + } + const ct = await webCrypto$6.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt); + return new Uint8Array(ct); + }, + + decrypt: async function(ct, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) { + return gcm(key, iv, adata).decrypt(ct); + } + try { + const pt = await webCrypto$6.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct); + return new Uint8Array(pt); + } catch (e) { + if (e.name === 'OperationError') { + throw new Error('Authentication tag mismatch'); + } + } + } + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } + + return { + encrypt: async function(pt, iv, adata) { + return gcm(key, iv, adata).encrypt(pt); + }, + + decrypt: async function(ct, iv, adata) { + return gcm(key, iv, adata).decrypt(ct); + } + }; +} + + +/** + * Get GCM nonce. Note: this operation is not defined by the standard. + * A future version of the standard may define GCM mode differently, + * hopefully under a different ID (we use Private/Experimental algorithm + * ID 100) so that we can maintain backwards compatibility. + * @param {Uint8Array} iv - The initialization vector (12 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +GCM.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[4 + i] ^= chunkIndex[i]; + } + return nonce; +}; + +GCM.blockLength = blockLength; +GCM.ivLength = ivLength; +GCM.tagLength = tagLength; + +/** + * @fileoverview Cipher modes + * @module crypto/mode + */ + + +var mode = { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: GCM, + experimentalGCM: GCM, + /** @see module:crypto/mode/eax */ + eax: EAX, + /** @see module:crypto/mode/ocb */ + ocb: OCB +}; + +// Operations are not constant time, but we try and limit timing leakage where we can +const _0n$8 = BigInt(0); +const _1n$d = BigInt(1); +function uint8ArrayToBigInt(bytes) { + const hexAlphabet = '0123456789ABCDEF'; + let s = ''; + bytes.forEach(v => { + s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; + }); + return BigInt('0x0' + s); +} +function mod$2(a, m) { + const reduced = a % m; + return reduced < _0n$8 ? reduced + m : reduced; +} +/** + * Compute modular exponentiation using square and multiply + * @param {BigInt} a - Base + * @param {BigInt} e - Exponent + * @param {BigInt} n - Modulo + * @returns {BigInt} b ** e mod n. + */ +function modExp(b, e, n) { + if (n === _0n$8) + throw Error('Modulo cannot be zero'); + if (n === _1n$d) + return BigInt(0); + if (e < _0n$8) + throw Error('Unsopported negative exponent'); + let exp = e; + let x = b; + x %= n; + let r = BigInt(1); + while (exp > _0n$8) { + const lsb = exp & _1n$d; + exp >>= _1n$d; // e / 2 + // Always compute multiplication step, to reduce timing leakage + const rx = (r * x) % n; + // Update r only if lsb is 1 (odd exponent) + r = lsb ? rx : r; + x = (x * x) % n; // Square + } + return r; +} +function abs(x) { + return x >= _0n$8 ? x : -x; +} +/** + * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) + * Given a and b, compute (x, y) such that ax + by = gdc(a, b). + * Negative numbers are also supported. + * @param {BigInt} a - First operand + * @param {BigInt} b - Second operand + * @returns {{ gcd, x, y: bigint }} + */ +function _egcd(aInput, bInput) { + let x = BigInt(0); + let y = BigInt(1); + let xPrev = BigInt(1); + let yPrev = BigInt(0); + // Deal with negative numbers: run algo over absolute values, + // and "move" the sign to the returned x and/or y. + // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers + let a = abs(aInput); + let b = abs(bInput); + const aNegated = aInput < _0n$8; + const bNegated = bInput < _0n$8; + while (b !== _0n$8) { + const q = a / b; + let tmp = x; + x = xPrev - q * x; + xPrev = tmp; + tmp = y; + y = yPrev - q * y; + yPrev = tmp; + tmp = b; + b = a % b; + a = tmp; + } + return { + x: aNegated ? -xPrev : xPrev, + y: bNegated ? -yPrev : yPrev, + gcd: a + }; +} +/** + * Compute the inverse of `a` modulo `n` + * Note: `a` and and `n` must be relatively prime + * @param {BigInt} a + * @param {BigInt} n - Modulo + * @returns {BigInt} x such that a*x = 1 mod n + * @throws {Error} if the inverse does not exist + */ +function modInv(a, n) { + const { gcd, x } = _egcd(a, n); + if (gcd !== _1n$d) { + throw new Error('Inverse does not exist'); + } + return mod$2(x + n, n); +} +/** + * Compute greatest common divisor between this and n + * @param {BigInt} aInput - Operand + * @param {BigInt} bInput - Operand + * @returns {BigInt} gcd + */ +function gcd(aInput, bInput) { + let a = aInput; + let b = bInput; + while (b !== _0n$8) { + const tmp = b; + b = a % b; + a = tmp; + } + return a; +} +/** + * Get this value as an exact Number (max 53 bits) + * Fails if this value is too large + * @returns {Number} + */ +function bigIntToNumber(x) { + const number = Number(x); + if (number > Number.MAX_SAFE_INTEGER) { + // We throw and error to conform with the bn.js implementation + throw new Error('Number can only safely store up to 53 bits'); + } + return number; +} +/** + * Get value of i-th bit + * @param {BigInt} x + * @param {Number} i - Bit index + * @returns {Number} Bit value. + */ +function getBit(x, i) { + const bit = (x >> BigInt(i)) & _1n$d; + return bit === _0n$8 ? 0 : 1; +} +/** + * Compute bit length + */ +function bitLength(x) { + // -1n >> -1n is -1n + // 1n >> 1n is 0n + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + let bitlen = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _1n$d) !== target) { + bitlen++; + } + return bitlen; +} +/** + * Compute byte length + */ +function byteLength(x) { + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + const _8n = BigInt(8); + let len = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _8n) !== target) { + len++; + } + return len; +} +/** + * Get Uint8Array representation of this number + * @param {String} endian - Endianess of output array (defaults to 'be') + * @param {Number} length - Of output array + * @returns {Uint8Array} + */ +function bigIntToUint8Array(x, endian = 'be', length) { + // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) + // this is faster than shift+mod iterations + let hex = x.toString(16); + if (hex.length % 2 === 1) { + hex = '0' + hex; + } + const rawLength = hex.length / 2; + const bytes = new Uint8Array(length || rawLength); + // parse hex + const offset = length ? length - rawLength : 0; + let i = 0; + while (i < rawLength) { + bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + i++; + } + if (endian !== 'be') { + bytes.reverse(); + } + return bytes; +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const nodeCrypto$4 = util.getNodeCrypto(); + +/** + * Retrieve secure random byte array of the specified length + * @param {Integer} length - Length in bytes to generate + * @returns {Uint8Array} Random byte array. + */ +function getRandomBytes(length) { + const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$4?.webcrypto; + if (webcrypto?.getRandomValues) { + const buf = new Uint8Array(length); + return webcrypto.getRandomValues(buf); + } else { + throw new Error('No secure random number generator available.'); + } +} + +/** + * Create a secure random BigInt that is greater than or equal to min and less than max. + * @param {bigint} min - Lower bound, included + * @param {bigint} max - Upper bound, excluded + * @returns {bigint} Random BigInt. + * @async + */ +function getRandomBigInteger(min, max) { + if (max < min) { + throw new Error('Illegal parameter value: max <= min'); + } + + const modulus = max - min; + const bytes = byteLength(modulus); + + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8)); + return mod$2(r, modulus) + min; +} + +var random = /*#__PURE__*/Object.freeze({ + __proto__: null, + getRandomBigInteger: getRandomBigInteger, + getRandomBytes: getRandomBytes +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +/** + * @fileoverview Algorithms for probabilistic random prime generation + * @module crypto/public_key/prime + */ +const _1n$c = BigInt(1); +/** + * Generate a probably prime random number + * @param bits - Bit length of the prime + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function randomProbablePrime(bits, e, k) { + const _30n = BigInt(30); + const min = _1n$c << BigInt(bits - 1); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 + * the next possible prime is mod 30: + * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 + */ + const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; + let n = getRandomBigInteger(min, min << _1n$c); + let i = bigIntToNumber(mod$2(n, _30n)); + do { + n += BigInt(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (bitLength(n) > bits) { + n = mod$2(n, min << _1n$c); + n += min; + i = bigIntToNumber(mod$2(n, _30n)); + } + } while (!isProbablePrime(n, e, k)); + return n; +} +/** + * Probabilistic primality testing + * @param n - Number to test + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function isProbablePrime(n, e, k) { + if (e && gcd(n - _1n$c, e) !== _1n$c) { + return false; + } + if (!divisionTest(n)) { + return false; + } + if (!fermat(n)) { + return false; + } + if (!millerRabin(n, k)) { + return false; + } + // TODO implement the Lucas test + // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + return true; +} +/** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n != 1. + * @param n - Number to test + * @param b - Optional Fermat test base + */ +function fermat(n, b = BigInt(2)) { + return modExp(b, n - _1n$c, n) === _1n$c; +} +function divisionTest(n) { + const _0n = BigInt(0); + return smallPrimes.every(m => mod$2(n, m) !== _0n); +} +// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c +const smallPrimes = [ + 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, + 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, + 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, + 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, + 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, + 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, + 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, + 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, + 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, + 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, + 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, + 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, + 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, + 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, + 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, + 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, + 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, + 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, + 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, + 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, + 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, + 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, + 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, + 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, + 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, + 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, + 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, + 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, + 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, + 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, + 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, + 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, + 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, + 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, + 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, + 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, + 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, + 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, + 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, + 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, + 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, + 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, + 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, + 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, + 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, + 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, + 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, + 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, + 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, + 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, + 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, + 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, + 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, + 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, + 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, + 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, + 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, + 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, + 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, + 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, + 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, + 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, + 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, + 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, + 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, + 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, + 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, + 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, + 4957, 4967, 4969, 4973, 4987, 4993, 4999 +].map(n => BigInt(n)); +// Miller-Rabin - Miller Rabin algorithm for primality test +// Copyright Fedor Indutny, 2014. +// +// This software is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin +// Sample syntax for Fixed-Base Miller-Rabin: +// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) +/** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n - Number to test + * @param k - Optional number of iterations of Miller-Rabin test + * @param rand - Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ +function millerRabin(n, k, rand) { + const len = bitLength(n); + if (!k) { + k = Math.max(1, (len / 48) | 0); + } + const n1 = n - _1n$c; // n - 1 + // Find d and s, (n - 1) = (2 ^ s) * d; + let s = 0; + while (!getBit(n1, s)) { + s++; + } + const d = n >> BigInt(s); + for (; k > 0; k--) { + const a = getRandomBigInteger(BigInt(2), n1); + let x = modExp(a, d, n); + if (x === _1n$c || x === n1) { + continue; + } + let i; + for (i = 1; i < s; i++) { + x = mod$2(x * x, n); + if (x === _1n$c) { + return false; + } + if (x === n1) { + break; + } + } + if (i === s) { + return false; + } + } + return true; +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * ASN1 object identifiers for hashes + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} + */ +const hash_headers = []; +hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, + 0x10]; +hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; +hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; +hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, + 0x04, 0x20]; +hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x30]; +hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40]; +hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C]; + +/** + * Create padding with secure random data + * @private + * @param {Integer} length - Length of the padding in bytes + * @returns {Uint8Array} Random padding. + */ +function getPKCS1Padding(length) { + const result = new Uint8Array(length); + let count = 0; + while (count < length) { + const randomBytes = getRandomBytes(length - count); + for (let i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result[count++] = randomBytes[i]; + } + } + } + return result; +} + +/** + * Create a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} + * @param {Uint8Array} message - Message to be encoded + * @param {Integer} keyLength - The length in octets of the key modulus + * @returns {Uint8Array} EME-PKCS1 padded message. + */ +function emeEncode(message, keyLength) { + const mLength = message.length; + // length checking + if (mLength > keyLength - 11) { + throw new Error('Message too long'); + } + // Generate an octet string PS of length k - mLen - 3 consisting of + // pseudo-randomly generated nonzero octets + const PS = getPKCS1Padding(keyLength - mLength - 3); + // Concatenate PS, the message M, and other padding to form an + // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. + const encoded = new Uint8Array(keyLength); + // 0x00 byte + encoded[1] = 2; + encoded.set(PS, 2); + // 0x00 bytes + encoded.set(message, keyLength - mLength); + return encoded; +} + +/** + * Decode a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} + * @param {Uint8Array} encoded - Encoded message bytes + * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) + * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) + * @throws {Error} on decoding failure, unless `randomPayload` is provided + */ +function emeDecode(encoded, randomPayload) { + // encoded format: 0x00 0x02 0x00 + let offset = 2; + let separatorNotFound = 1; + for (let j = offset; j < encoded.length; j++) { + separatorNotFound &= encoded[j] !== 0; + offset += separatorNotFound; + } + + const psLen = offset - 2; + const payload = encoded.subarray(offset + 1); // discard the 0x00 separator + const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; + + if (randomPayload) { + return util.selectUint8Array(isValidPadding, payload, randomPayload); + } + + if (isValidPadding) { + return payload; + } + + throw new Error('Decryption error'); +} + +/** + * Create a EMSA-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} + * @param {Integer} algo - Hash algorithm type used + * @param {Uint8Array} hashed - Message to be encoded + * @param {Integer} emLen - Intended length in octets of the encoded message + * @returns {Uint8Array} Encoded message. + */ +function emsaEncode(algo, hashed, emLen) { + let i; + if (hashed.length !== hash$1.getHashByteLength(algo)) { + throw new Error('Invalid hash length'); + } + // produce an ASN.1 DER value for the hash function used. + // Let T be the full hash prefix + const hashPrefix = new Uint8Array(hash_headers[algo].length); + for (i = 0; i < hash_headers[algo].length; i++) { + hashPrefix[i] = hash_headers[algo][i]; + } + // and let tLen be the length in octets prefix and hashed data + const tLen = hashPrefix.length + hashed.length; + if (emLen < tLen + 11) { + throw new Error('Intended encoded message length too short'); + } + // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF + // The length of PS will be at least 8 octets + const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); + + // Concatenate PS, the hash prefix, hashed data, and other padding to form the + // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed + const EM = new Uint8Array(emLen); + EM[1] = 0x01; + EM.set(PS, 2); + EM.set(hashPrefix, emLen - tLen); + EM.set(hashed, emLen - hashed.length); + return EM; +} + +var pkcs1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + emeDecode: emeDecode, + emeEncode: emeEncode, + emsaEncode: emsaEncode +}); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$5 = util.getWebCrypto(); +const nodeCrypto$3 = util.getNodeCrypto(); +const _1n$b = BigInt(1); + +/** Create signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} hashed - Hashed message + * @returns {Promise} RSA Signature. + * @async + */ +async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) { + if (hash$1.getHashByteLength(hashAlgo) >= n.length) { + // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error + // e.g. if a 512-bit RSA key is used with a SHA-512 digest. + // The size limit is actually slightly different but here we only care about throwing + // on common key sizes. + throw new Error('Digest size cannot exceed key modulus size'); + } + + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeSign$1(hashAlgo, data, n, e, d, p, q, u); + } + } + return bnSign(hashAlgo, n, d, hashed); +} + +/** + * Verify signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} s - Signature + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} hashed - Hashed message + * @returns {Boolean} + * @async + */ +async function verify$6(hashAlgo, data, s, n, e, hashed) { + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeVerify$1(hashAlgo, data, s, n, e); + } + } + return bnVerify(hashAlgo, s, n, e, hashed); +} + +/** + * Encrypt message + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @returns {Promise} RSA Ciphertext. + * @async + */ +async function encrypt$4(data, n, e) { + if (util.getNodeCrypto()) { + return nodeEncrypt(data, n, e); + } + return bnEncrypt(data, n, e); +} + +/** + * Decrypt RSA message + * @param {Uint8Array} m - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} RSA Plaintext. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$4(data, n, e, d, p, q, u, randomPayload) { + // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, + // and we want to avoid checking the error type to decide if the random payload + // should indeed be returned. + if (util.getNodeCrypto() && !randomPayload) { + try { + return await nodeDecrypt(data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } + return bnDecrypt(data, n, e, d, p, q, u, randomPayload); +} + +/** + * Generate a new random private key B bits long with public exponent E. + * + * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param {Integer} bits - RSA bit length + * @param {Integer} e - RSA public exponent + * @returns {{n, e, d, + * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = p ** -1 mod q + * @async + */ +async function generate$4(bits, e) { + e = BigInt(e); + + // Native RSA keygen using Web Crypto + if (util.getWebCrypto()) { + const keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, // the specified keysize in bits + publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); + + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); + // map JWK parameters to corresponding OpenPGP names + return jwkToPrivate(jwk, e); + } else if (util.getNodeCrypto()) { + const opts = { + modulusLength: bits, + publicExponent: bigIntToNumber(e), + publicKeyEncoding: { type: 'pkcs1', format: 'jwk' }, + privateKeyEncoding: { type: 'pkcs1', format: 'jwk' } + }; + const jwk = await new Promise((resolve, reject) => { + nodeCrypto$3.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => { + if (err) { + reject(err); + } else { + resolve(jwkPrivateKey); + } + }); + }); + return jwkToPrivate(jwk, e); + } + + // RSA keygen fallback using 40 iterations of the Miller-Rabin test + // See https://stackoverflow.com/a/6330138 for justification + // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST + let p; + let q; + let n; + do { + q = randomProbablePrime(bits - (bits >> 1), e, 40); + p = randomProbablePrime(bits >> 1, e, 40); + n = p * q; + } while (bitLength(n) !== bits); + + const phi = (p - _1n$b) * (q - _1n$b); + + if (q < p) { + [p, q] = [q, p]; + } + + return { + n: bigIntToUint8Array(n), + e: bigIntToUint8Array(e), + d: bigIntToUint8Array(modInv(e, phi)), + p: bigIntToUint8Array(p), + q: bigIntToUint8Array(q), + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: bigIntToUint8Array(modInv(p, q)) + }; +} + +/** + * Validate RSA parameters + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA inverse of p w.r.t. q + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$9(n, e, d, p, q, u) { + n = uint8ArrayToBigInt(n); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + + // expect pq = n + if ((p * q) !== n) { + return false; + } + + const _2n = BigInt(2); + // expect p*u = 1 mod q + u = uint8ArrayToBigInt(u); + if (mod$2(p * u, q) !== BigInt(1)) { + return false; + } + + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + /** + * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) + * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] + * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] + * + * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) + */ + const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3)); + const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q + const rde = r * d * e; + + const areInverses = mod$2(rde, p - _1n$b) === r && mod$2(rde, q - _1n$b) === r; + if (!areInverses) { + return false; + } + + return true; +} + +async function bnSign(hashAlgo, n, d, hashed) { + n = uint8ArrayToBigInt(n); + const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n))); + d = uint8ArrayToBigInt(d); + return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n)); +} + +async function webSign$1(hashName, data, n, e, d, p, q, u) { + /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. + * We swap them in privateToJWK, so it usually works out, but nevertheless, + * not all OpenPGP keys are compatible with this requirement. + * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still + * does if the underlying Web Crypto does so (though the tested implementations + * don't do so). + */ + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }; + const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); + return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); +} + +async function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) { + const sign = nodeCrypto$3.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(data); + sign.end(); + + const jwk = await privateToJWK$1(n, e, d, p, q, u); + return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' })); +} + +async function bnVerify(hashAlgo, s, n, e, hashed) { + n = uint8ArrayToBigInt(n); + s = uint8ArrayToBigInt(s); + e = uint8ArrayToBigInt(e); + if (s >= n) { + throw new Error('Signature size cannot exceed modulus size'); + } + const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n)); + const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n)); + return util.equalsUint8Array(EM1, EM2); +} + +async function webVerify$1(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = await webCrypto$5.importKey('jwk', jwk, { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }, false, ['verify']); + return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); +} + +async function nodeVerify$1(hashAlgo, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1' }; + + const verify = nodeCrypto$3.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(data); + verify.end(); + + try { + return verify.verify(key, s); + } catch (err) { + return false; + } +} + +async function nodeEncrypt(data, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; + + return new Uint8Array(nodeCrypto$3.publicEncrypt(key, data)); +} + +async function bnEncrypt(data, n, e) { + n = uint8ArrayToBigInt(n); + data = uint8ArrayToBigInt(emeEncode(data, byteLength(n))); + e = uint8ArrayToBigInt(e); + if (data >= n) { + throw new Error('Message size cannot exceed modulus size'); + } + return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n)); +} + +async function nodeDecrypt(data, n, e, d, p, q, u) { + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; + + try { + return new Uint8Array(nodeCrypto$3.privateDecrypt(key, data)); + } catch (err) { + throw new Error('Decryption error'); + } +} + +async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { + data = uint8ArrayToBigInt(data); + n = uint8ArrayToBigInt(n); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + u = uint8ArrayToBigInt(u); + if (data >= n) { + throw new Error('Data too large.'); + } + const dq = mod$2(d, q - _1n$b); // d mod (q-1) + const dp = mod$2(d, p - _1n$b); // d mod (p-1) + + const unblinder = getRandomBigInteger(BigInt(2), n); + const blinder = modExp(modInv(unblinder, n), e, n); + data = mod$2(data * blinder, n); + + const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p + const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q + const h = mod$2(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q) + + let result = h * p + mp; // result < n due to relations above + + result = mod$2(result * unblinder, n); + + return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload); +} + +/** Convert Openpgp private key params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + * @param {Uint8Array} d + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} u + */ +async function privateToJWK$1(n, e, d, p, q, u) { + const pNum = uint8ArrayToBigInt(p); + const qNum = uint8ArrayToBigInt(q); + const dNum = uint8ArrayToBigInt(d); + + let dq = mod$2(dNum, qNum - _1n$b); // d mod (q-1) + let dp = mod$2(dNum, pNum - _1n$b); // d mod (p-1) + dp = bigIntToUint8Array(dp); + dq = bigIntToUint8Array(dq); + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + d: uint8ArrayToB64(d), + // switch p and q + p: uint8ArrayToB64(q), + q: uint8ArrayToB64(p), + // switch dp and dq + dp: uint8ArrayToB64(dq), + dq: uint8ArrayToB64(dp), + qi: uint8ArrayToB64(u), + ext: true + }; +} + +/** Convert Openpgp key public params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + */ +function publicToJWK(n, e) { + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + ext: true + }; +} + +/** Convert JWK private key to OpenPGP private key params */ +function jwkToPrivate(jwk, e) { + return { + n: b64ToUint8Array(jwk.n), + e: bigIntToUint8Array(e), + d: b64ToUint8Array(jwk.d), + // switch p and q + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), + // Since p and q are switched in places, u is the inverse of jwk.q + u: b64ToUint8Array(jwk.qi) + }; +} + +var rsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$4, + encrypt: encrypt$4, + generate: generate$4, + sign: sign$6, + validateParams: validateParams$9, + verify: verify$6 +}); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const _1n$a = BigInt(1); + +/** + * ElGamal Encryption function + * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) + * @param {Uint8Array} data - To be padded and encrypted + * @param {Uint8Array} p + * @param {Uint8Array} g + * @param {Uint8Array} y + * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} + * @async + */ +async function encrypt$3(data, p, g, y) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + + const padded = emeEncode(data, byteLength(p)); + const m = uint8ArrayToBigInt(padded); + + // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* + // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] + const k = getRandomBigInteger(_1n$a, p - _1n$a); + return { + c1: bigIntToUint8Array(modExp(g, k, p)), + c2: bigIntToUint8Array(mod$2(modExp(y, k, p) * m, p)) + }; +} + +/** + * ElGamal Encryption function + * @param {Uint8Array} c1 + * @param {Uint8Array} c2 + * @param {Uint8Array} p + * @param {Uint8Array} x + * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} Unpadded message. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$3(c1, c2, p, x, randomPayload) { + c1 = uint8ArrayToBigInt(c1); + c2 = uint8ArrayToBigInt(c2); + p = uint8ArrayToBigInt(p); + x = uint8ArrayToBigInt(x); + + const padded = mod$2(modInv(modExp(c1, x, p), p) * c2, p); + return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload); +} + +/** + * Validate ElGamal parameters + * @param {Uint8Array} p - ElGamal prime + * @param {Uint8Array} g - ElGamal group generator + * @param {Uint8Array} y - ElGamal public key + * @param {Uint8Array} x - ElGamal private exponent + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$8(p, g, y, x) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + + // Check that 1 < g < p + if (g <= _1n$a || g >= p) { + return false; + } + + // Expect p-1 to be large + const pSize = BigInt(bitLength(p)); + const _1023n = BigInt(1023); + if (pSize < _1023n) { + return false; + } + + /** + * g should have order p-1 + * Check that g ** (p-1) = 1 mod p + */ + if (modExp(g, p - _1n$a, p) !== _1n$a) { + return false; + } + + /** + * Since p-1 is not prime, g might have a smaller order that divides p-1 + * We want to make sure that the order is large enough to hinder a small subgroup attack + * + * We just check g**i != 1 for all i up to a threshold + */ + let res = g; + let i = BigInt(1); + const _2n = BigInt(2); + const threshold = _2n << BigInt(17); // we want order > threshold + while (i < threshold) { + res = mod$2(res * g, p); + if (res === _1n$a) { + return false; + } + i++; + } + + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{r(p-1) + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const r = getRandomBigInteger(_2n << (pSize - _1n$a), _2n << pSize); // draw r of same size as p-1 + const rqx = (p - _1n$a) * r + x; + if (y !== modExp(g, rqx, p)) { + return false; + } + + return true; +} + +var elgamal = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$3, + encrypt: encrypt$3, + validateParams: validateParams$8 +}); + +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +const crypto$3 = + nc__namespace && typeof nc__namespace === 'object' && 'webcrypto' in nc__namespace ? nc__namespace.webcrypto : undefined; + +const nacl = {}; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add$1(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add$1(q, p); + add$1(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add$1(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32; + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.box = {}; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + if (crypto$3 && crypto$3.getRandomValues) { + // Browsers and Node v16+ + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto$3.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } +})(); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const knownOIDs = { + '2a8648ce3d030107': enums.curve.nistP256, + '2b81040022': enums.curve.nistP384, + '2b81040023': enums.curve.nistP521, + '2b8104000a': enums.curve.secp256k1, + '2b06010401da470f01': enums.curve.ed25519Legacy, + '2b060104019755010501': enums.curve.curve25519Legacy, + '2b2403030208010107': enums.curve.brainpoolP256r1, + '2b240303020801010b': enums.curve.brainpoolP384r1, + '2b240303020801010d': enums.curve.brainpoolP512r1 +}; + +class OID { + constructor(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (util.isArray(oid) || + util.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { // DER encoded oid byte array + if (oid[1] !== oid.length - 2) { + throw new Error('Length mismatch in DER encoded oid'); + } + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; + } + } + + /** + * Method to read an OID object + * @param {Uint8Array} input - Where to read the OID from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } + } + throw new Error('Invalid oid'); + } + + /** + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID. + */ + write() { + return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); + } + + /** + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID. + */ + toHex() { + return util.uint8ArrayToHex(this.oid); + } + + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns {enums.curve} String with the canonical name of the curve + * @throws if unknown + */ + getName() { + const name = knownOIDs[this.toHex()]; + if (!name) { + throw new Error('Unknown curve object identifier.'); + } + + return name; + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +function readSimpleLength(bytes) { + let len = 0; + let offset; + const type = bytes[0]; + + + if (type < 192) { + [len] = bytes; + offset = 1; + } else if (type < 255) { + len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; + offset = 2; + } else if (type === 255) { + len = util.readNumber(bytes.subarray(1, 1 + 4)); + offset = 5; + } + + return { + len: len, + offset: offset + }; +} + +/** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * + * @param {Integer} length - The length to encode + * @returns {Uint8Array} String with openpgp length representation. + */ +function writeSimpleLength(length) { + if (length < 192) { + return new Uint8Array([length]); + } else if (length > 191 && length < 8384) { + /* + * let a = (total data packet length) - 192 let bc = two octet + * representation of a let d = b + 192 + */ + return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); + } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); +} + +function writePartialLength(power) { + if (power < 0 || power > 30) { + throw new Error('Partial Length power must be between 1 and 30'); + } + return new Uint8Array([224 + power]); +} + +function writeTag(tag_type) { + /* we're only generating v4 packet headers here */ + return new Uint8Array([0xC0 | tag_type]); +} + +/** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * + * @param {Integer} tag_type - Tag type + * @param {Integer} length - Length of the payload + * @returns {String} String of the header. + */ +function writeHeader(tag_type, length) { + /* we're only generating v4 packet headers here */ + return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); +} + +/** + * Whether the packet type supports partial lengths per RFC4880 + * @param {Integer} tag - Tag type + * @returns {Boolean} String of the header. + */ +function supportsStreaming(tag) { + return [ + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ].includes(tag); +} + +/** + * Generic static Packet Parser function + * + * @param {Uint8Array | ReadableStream} input - Input stream as string + * @param {Function} callback - Function to call with the parsed packet + * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. + */ +async function readPackets(input, callback) { + const reader = getReader(input); + let writer; + let callbackReturned; + try { + const peekedBytes = await reader.peekBytes(2); + // some sanity checks + if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { + throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); + } + const headerByte = await reader.readByte(); + let tag = -1; + let format = -1; + let packetLength; + + format = 0; // 0 = old format; 1 = new format + if ((headerByte & 0x40) !== 0) { + format = 1; + } + + let packetLengthType; + if (format) { + // new format header + tag = headerByte & 0x3F; // bit 5-0 + } else { + // old format header + tag = (headerByte & 0x3F) >> 2; // bit 5-2 + packetLengthType = headerByte & 0x03; // bit 1-0 + } + + const packetSupportsStreaming = supportsStreaming(tag); + let packet = null; + if (packetSupportsStreaming) { + if (util.isStream(input) === 'array') { + const arrayStream = new ArrayStream(); + writer = getWriter(arrayStream); + packet = arrayStream; + } else { + const transform = new TransformStream(); + writer = getWriter(transform.writable); + packet = transform.readable; + } + // eslint-disable-next-line callback-return + callbackReturned = callback({ tag, packet }); + } else { + packet = []; + } + + let wasPartialLength; + do { + if (!format) { + // 4.2.1. Old Format Packet Lengths + switch (packetLengthType) { + case 0: + // The packet has a one-octet length. The header is 2 octets + // long. + packetLength = await reader.readByte(); + break; + case 1: + // The packet has a two-octet length. The header is 3 octets + // long. + packetLength = (await reader.readByte() << 8) | await reader.readByte(); + break; + case 2: + // The packet has a four-octet length. The header is 5 + // octets long. + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + break; + default: + // 3 - The packet is of indeterminate length. The header is 1 + // octet long, and the implementation must determine how long + // the packet is. If the packet is in a file, this means that + // the packet extends until the end of the file. In general, + // an implementation SHOULD NOT use indeterminate-length + // packets except where the end of the data will be clear + // from the context, and even then it is better to use a + // definite length, or a new format header. The new format + // headers described below have a mechanism for precisely + // encoding data of indeterminate length. + packetLength = Infinity; + break; + } + } else { // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + const lengthByte = await reader.readByte(); + wasPartialLength = false; + if (lengthByte < 192) { + packetLength = lengthByte; + // 4.2.2.2. Two-Octet Lengths + } else if (lengthByte >= 192 && lengthByte < 224) { + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + // 4.2.2.4. Partial Body Lengths + } else if (lengthByte > 223 && lengthByte < 255) { + packetLength = 1 << (lengthByte & 0x1F); + wasPartialLength = true; + if (!packetSupportsStreaming) { + throw new TypeError('This packet type does not support partial lengths.'); + } + // 4.2.2.3. Five-Octet Lengths + } else { + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + } + } + if (packetLength > 0) { + let bytesRead = 0; + while (true) { + if (writer) await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (packetLength === Infinity) break; + throw new Error('Unexpected end of packet'); + } + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); + if (writer) await writer.write(chunk); + else packet.push(chunk); + bytesRead += value.length; + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); + break; + } + } + } + } while (wasPartialLength); + + // If this was not a packet that "supports streaming", we peek to check + // whether it is the last packet in the message. We peek 2 bytes instead + // of 1 because the beginning of this function also peeks 2 bytes, and we + // want to cut a `subarray` of the correct length into `web-stream-tools`' + // `externalBuffer` as a tiny optimization here. + // + // If it *was* a streaming packet (i.e. the data packets), we peek at the + // entire remainder of the stream, in order to forward errors in the + // remainder of the stream to the packet data. (Note that this means we + // read/peek at all signature packets before closing the literal data + // packet, for example.) This forwards MDC errors to the literal data + // stream, for example, so that they don't get lost / forgotten on + // decryptedMessage.packets.stream, which we never look at. + // + // An example of what we do when stream-parsing a message containing + // [ one-pass signature packet, literal data packet, signature packet ]: + // 1. Read the one-pass signature packet + // 2. Peek 2 bytes of the literal data packet + // 3. Parse the one-pass signature packet + // + // 4. Read the literal data packet, simultaneously stream-parsing it + // 5. Peek until the end of the message + // 6. Finish parsing the literal data packet + // + // 7. Read the signature packet again (we already peeked at it in step 5) + // 8. Peek at the end of the stream again (`peekBytes` returns undefined) + // 9. Parse the signature packet + // + // Note that this means that if there's an error in the very end of the + // stream, such as an MDC error, we throw in step 5 instead of in step 8 + // (or never), which is the point of this exercise. + const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); + if (writer) { + await writer.ready; + await writer.close(); + } else { + packet = util.concatUint8Array(packet); + // eslint-disable-next-line callback-return + await callback({ tag, packet }); + } + return !nextPacket || !nextPacket.length; + } catch (e) { + if (writer) { + await writer.abort(e); + return true; + } else { + throw e; + } + } finally { + if (writer) { + await callbackReturned; + } + reader.releaseLock(); + } +} + +class UnsupportedError extends Error { + constructor(...params) { + super(...params); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); + } + + this.name = 'UnsupportedError'; + } +} + +// unknown packet types are handled differently depending on the packet criticality +class UnknownPacketError extends UnsupportedError { + constructor(...params) { + super(...params); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); + } + + this.name = 'UnknownPacketError'; + } +} + +class UnparseablePacket { + constructor(tag, rawContent) { + this.tag = tag; + this.rawContent = rawContent; + } + + write() { + return this.rawContent; + } +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + +/** + * Generate (non-legacy) EdDSA key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} + */ +async function generate$3(algo) { + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']); + + const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey); + + return { + A: new Uint8Array(b64ToUint8Array(publicKey.x)), + seed: b64ToUint8Array(privateKey.d, true) + }; + } catch (err) { + if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux + throw err; + } + const seed = getRandomBytes(getPayloadSize$1(algo)); + const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed); + return { A, seed }; + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const seed = ed448.utils.randomPrivateKey(); + const A = ed448.getPublicKey(seed); + return { A, seed }; + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +} + +/** + * Sign a message using the provided key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * RS: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = privateKeyToJWK(algo, publicKey, privateKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']); + + const signature = new Uint8Array( + await webCrypto.sign('Ed25519', key, hashed) + ); + + return { RS: signature }; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + const secretKey = util.concatUint8Array([privateKey, publicKey]); + const signature = nacl.sign.detached(hashed, secretKey); + return { RS: signature }; + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const signature = ed448.sign(hashed, privateKey); + return { RS: signature }; + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } + +} + +/** + * Verifies if a signature is valid for a message + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{ RS: Uint8Array }} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = publicKeyToJWK(algo, publicKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']); + const verified = await webCrypto.verify('Ed25519', key, RS, hashed); + return verified; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + return nacl.sign.detached.verify(hashed, RS, publicKey); + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + return ed448.verify(RS, hashed, publicKey); + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +} +/** + * Validate (non-legacy) EdDSA parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - EdDSA public point + * @param {Uint8Array} seed - EdDSA secret seed + * @param {Uint8Array} oid - (legacy only) EdDSA OID + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$7(algo, A, seed) { + switch (algo) { + case enums.publicKey.ed25519: { + /** + * Derive public point A' from private key + * and expect A == A' + * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(seed); + return util.equalsUint8Array(A, publicKey); + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + + const publicKey = ed448.getPublicKey(seed); + return util.equalsUint8Array(A, publicKey); + } + default: + return false; + } +} + +function getPayloadSize$1(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return 32; + + case enums.publicKey.ed448: + return 57; + + default: + throw new Error('Unsupported EdDSA algorithm'); + } +} + +function getPreferredHashAlgo$2(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return enums.hash.sha256; + case enums.publicKey.ed448: + return enums.hash.sha512; + default: + throw new Error('Unknown EdDSA algo'); + } +} + +const publicKeyToJWK = (algo, publicKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: uint8ArrayToB64(publicKey), + ext: true + }; + return jwk; + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; + +const privateKeyToJWK = (algo, publicKey, privateKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = publicKeyToJWK(algo, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; + +var eddsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + generate: generate$3, + getPayloadSize: getPayloadSize$1, + getPreferredHashAlgo: getPreferredHashAlgo$2, + sign: sign$5, + validateParams: validateParams$7, + verify: verify$5 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$4 = util.getWebCrypto(); +/** + * AES key wrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} dataToWrap + * @returns {Uint8Array} wrapped key + */ +async function wrap(algo, key, dataToWrap) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } + + try { + const wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']); + // Import data as HMAC key, as it has no key length requirements + const keyToWrap = await webCrypto$4.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + const wrapped = await webCrypto$4.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' }); + return new Uint8Array(wrapped); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + + return aeskw(key).encrypt(dataToWrap); +} + +/** + * AES key unwrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} wrappedData + * @returns {Uint8Array} unwrapped data + */ +async function unwrap(algo, key, wrappedData) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } + + let wrappingKey; + try { + wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + return aeskw(key).decrypt(wrappedData); + } + + try { + const unwrapped = await webCrypto$4.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + return new Uint8Array(await webCrypto$4.exportKey('raw', unwrapped)); + } catch (err) { + if (err.name === 'OperationError') { + throw new Error('Key Data Integrity failed'); + } + throw err; + } +} + +var aesKW = /*#__PURE__*/Object.freeze({ + __proto__: null, + unwrap: unwrap, + wrap: wrap +}); + +/** + * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. + * @module crypto/hkdf + */ + + +const webCrypto$3 = util.getWebCrypto(); + +async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { + const hash = enums.read(enums.webHash, hashAlgo); + if (!hash) throw new Error('Hash algo not supported with HKDF'); + + const importedKey = await webCrypto$3.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto$3.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + return new Uint8Array(bits); +} + +/** + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @module crypto/public_key/elliptic/ecdh + */ + + +const HKDF_INFO = { + x25519: util.encodeUTF8('OpenPGP X25519'), + x448: util.encodeUTF8('OpenPGP X448') +}; + +/** + * Generate ECDH key for Montgomery curves + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} + */ +async function generate$2(algo) { + switch (algo) { + case enums.publicKey.x25519: { + // k stays in little-endian, unlike legacy ECDH over curve25519 + const k = getRandomBytes(32); + const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k); + return { A, k }; + } + + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const k = x448.utils.randomPrivateKey(); + const A = x448.getPublicKey(k); + return { A, k }; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +/** +* Validate ECDH parameters +* @param {module:enums.publicKey} algo - Algorithm identifier +* @param {Uint8Array} A - ECDH public point +* @param {Uint8Array} k - ECDH secret scalar +* @returns {Promise} Whether params are valid. +* @async +*/ +async function validateParams$6(algo, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + /** + * Derive public point A' from private key + * and expect A == A' + */ + const { publicKey } = nacl.box.keyPair.fromSecretKey(k); + return util.equalsUint8Array(A, publicKey); + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + /** + * Derive public point A' from private key + * and expect A == A' + */ + const publicKey = x448.getPublicKey(k); + return util.equalsUint8Array(A, publicKey); + } + + default: + return false; + } +} + +/** + * Wrap and encrypt a session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} data - session key data to be encrypted + * @param {Uint8Array} recipientA - Recipient public key (K_B) + * @returns {Promise<{ + * ephemeralPublicKey: Uint8Array, + * wrappedKey: Uint8Array + * }>} ephemeral public key (K_A) and encrypted key + * @async + */ +async function encrypt$2(algo, data, recipientA) { + const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + recipientA, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } + + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +/** + * Decrypt and unwrap the session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} ephemeralPublicKey - (K_A) + * @param {Uint8Array} wrappedKey, + * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF + * @param {Uint8Array} k - Recipient secret key (b) + * @returns {Promise} decrypted session key data + * @async + */ +async function decrypt$2(algo, ephemeralPublicKey, wrappedKey, A, k) { + const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + A, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +function getPayloadSize(algo) { + switch (algo) { + case enums.publicKey.x25519: + return 32; + + case enums.publicKey.x448: + return 56; + + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +/** + * Generate shared secret and ephemeral public key for encryption + * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret + * @async + */ +async function generateEphemeralEncryptionMaterial(algo, recipientA) { + switch (algo) { + case enums.publicKey.x25519: { + const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo)); + const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const ephemeralSecretKey = x448.utils.randomPrivateKey(); + const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +/** + * x25519 and x448 produce an all-zero value when given as input a point with small order. + * This does not lead to a security issue in the context of ECDH, but it is still unexpected, + * hence we throw. + * @param {Uint8Array} sharedSecret + */ +function assertNonZeroArray(sharedSecret) { + let acc = 0; + for (let i = 0; i < sharedSecret.length; i++) { + acc |= sharedSecret[i]; + } + if (acc === 0) { + throw new Error('Unexpected low order point'); + } +} + +var ecdh_x = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$2, + encrypt: encrypt$2, + generate: generate$2, + generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial, + getPayloadSize: getPayloadSize, + recomputeSharedSecret: recomputeSharedSecret, + validateParams: validateParams$6 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$2 = util.getWebCrypto(); +const nodeCrypto$2 = util.getNodeCrypto(); + +const webCurves = { + [enums.curve.nistP256]: 'P-256', + [enums.curve.nistP384]: 'P-384', + [enums.curve.nistP521]: 'P-521' +}; +const knownCurves = nodeCrypto$2 ? nodeCrypto$2.getCurves() : []; +const nodeCurves = nodeCrypto$2 ? { + [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, + [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, + [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, + [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, + [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined, + [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined, + [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, + [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, + [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined +} : {}; + +const curves = { + [enums.curve.nistP256]: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.nistP256], + web: webCurves[enums.curve.nistP256], + payloadSize: 32, + sharedSize: 256, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP384]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.nistP384], + web: webCurves[enums.curve.nistP384], + payloadSize: 48, + sharedSize: 384, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP521]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.nistP521], + web: webCurves[enums.curve.nistP521], + payloadSize: 66, + sharedSize: 528, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.secp256k1]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.secp256k1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.ed25519Legacy]: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: enums.publicKey.eddsaLegacy, + hash: enums.hash.sha512, + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.curve25519Legacy]: { + oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: enums.publicKey.ecdh, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.brainpoolP256r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.brainpoolP256r1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP384r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.brainpoolP384r1], + payloadSize: 48, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP512r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.brainpoolP512r1], + payloadSize: 64, + wireFormatLeadingByte: 0x04 + } +}; + +class CurveWithOID { + constructor(oidOrName) { + try { + this.name = oidOrName instanceof OID ? + oidOrName.getName() : + enums.write(enums.curve,oidOrName); + } catch (err) { + throw new UnsupportedError('Unknown curve'); + } + const params = curves[this.name]; + + this.keyType = params.keyType; + + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node; + this.web = params.web; + this.payloadSize = params.payloadSize; + this.sharedSize = params.sharedSize; + this.wireFormatLeadingByte = params.wireFormatLeadingByte; + if (this.web && util.getWebCrypto()) { + this.type = 'web'; + } else if (this.node && util.getNodeCrypto()) { + this.type = 'node'; + } else if (this.name === enums.curve.curve25519Legacy) { + this.type = 'curve25519Legacy'; + } else if (this.name === enums.curve.ed25519Legacy) { + this.type = 'ed25519Legacy'; + } + } + + async genKeyPair() { + switch (this.type) { + case 'web': + try { + return await webGenKeyPair(this.name, this.wireFormatLeadingByte); + } catch (err) { + util.printDebugError('Browser did not support generating ec key ' + err.message); + return jsGenKeyPair(this.name); + } + case 'node': + return nodeGenKeyPair(this.name); + case 'curve25519Legacy': { + // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3 + const { k, A } = await generate$2(enums.publicKey.x25519); + const privateKey = k.slice().reverse(); + privateKey[0] = (privateKey[0] & 127) | 64; + privateKey[31] &= 248; + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + case 'ed25519Legacy': { + const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519); + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + default: + return jsGenKeyPair(this.name); + } + } +} + +async function generate$1(curveName) { + const curve = new CurveWithOID(curveName); + const { oid, hash, cipher } = curve; + const keyPair = await curve.genKeyPair(); + return { + oid, + Q: keyPair.publicKey, + secret: util.leftPad(keyPair.privateKey, curve.payloadSize), + hash, + cipher + }; +} + +/** + * Get preferred hash algo to use with the given curve + * @param {module:type/oid} oid - curve oid + * @returns {enums.hash} hash algorithm + */ +function getPreferredHashAlgo$1(oid) { + return curves[oid.getName()].hash; +} + +/** + * Validate ECDH and ECDSA parameters + * Not suitable for EdDSA (different secret key format) + * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves + * @param {module:type/oid} oid - EC object identifier + * @param {Uint8Array} Q - EC public point + * @param {Uint8Array} d - EC secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateStandardParams(algo, oid, Q, d) { + const supportedCurves = { + [enums.curve.nistP256]: true, + [enums.curve.nistP384]: true, + [enums.curve.nistP521]: true, + [enums.curve.secp256k1]: true, + [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh, + [enums.curve.brainpoolP256r1]: true, + [enums.curve.brainpoolP384r1]: true, + [enums.curve.brainpoolP512r1]: true + }; + + // Check whether the given curve is supported + const curveName = oid.getName(); + if (!supportedCurves[curveName]) { + return false; + } + + if (curveName === enums.curve.curve25519Legacy) { + d = d.slice().reverse(); + // Re-derive public point Q' + const { publicKey } = nacl.box.keyPair.fromSecretKey(d); + + Q = new Uint8Array(Q); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + if (!util.equalsUint8Array(dG, Q)) { + return false; + } + + return true; + } + + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + /* + * Re-derive public point Q' = dG from private key + * Expect Q == Q' + */ + const dG = nobleCurve.getPublicKey(d, false); + if (!util.equalsUint8Array(dG, Q)) { + return false; + } + + return true; +} + +/** + * Check whether the public point has a valid encoding. + * NB: this function does not check e.g. whether the point belongs to the curve. + */ +function checkPublicPointEnconding(curve, V) { + const { payloadSize, wireFormatLeadingByte, name: curveName } = curve; + + const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2; + + if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) { + throw new Error('Invalid point encoding'); + } +} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// +async function jsGenKeyPair(name) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + const privateKey = nobleCurve.utils.randomPrivateKey(); + const publicKey = nobleCurve.getPublicKey(privateKey, false); + return { publicKey, privateKey }; +} + +async function webGenKeyPair(name, wireFormatLeadingByte) { + // Note: keys generated with ECDSA and ECDH are structurally equivalent + const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); + + const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey); + + return { + publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte), + privateKey: b64ToUint8Array(privateKey.d) + }; +} + +async function nodeGenKeyPair(name) { + // Note: ECDSA and ECDH key generation is structurally equivalent + const ecdh = nodeCrypto$2.createECDH(nodeCurves[name]); + await ecdh.generateKeys(); + return { + publicKey: new Uint8Array(ecdh.getPublicKey()), + privateKey: new Uint8Array(ecdh.getPrivateKey()) + }; +} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + +/** + * @param {JsonWebKey} jwk - key for conversion + * + * @returns {Uint8Array} Raw public key. + */ +function jwkToRawPublic(jwk, wireFormatLeadingByte) { + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); + const publicKey = new Uint8Array(bufX.length + bufY.length + 1); + publicKey[0] = wireFormatLeadingByte; + publicKey.set(bufX, 1); + publicKey.set(bufY, bufX.length + 1); + return publicKey; +} + +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * + * @returns {JsonWebKey} Public key in jwk format. + */ +function rawPublicToJWK(payloadSize, name, publicKey) { + const len = payloadSize; + const bufX = publicKey.slice(1, len + 1); + const bufY = publicKey.slice(len + 1, len * 2 + 1); + // https://www.rfc-editor.org/rfc/rfc7518.txt + const jwk = { + kty: 'EC', + crv: name, + x: uint8ArrayToB64(bufX), + y: uint8ArrayToB64(bufY), + ext: true + }; + return jwk; +} + +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * @param {Uint8Array} privateKey - private key + * + * @returns {JsonWebKey} Private key in jwk format. + */ +function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$1 = util.getWebCrypto(); +const nodeCrypto$1 = util.getNodeCrypto(); + +/** + * Sign a message using the provided key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (message && !util.isStream(message)) { + const keyPair = { publicKey, privateKey }; + switch (curve.type) { + case 'web': + // If browser doesn't support a curve, we'll catch it + try { + // Need to await to make sure browser succeeds + return await webSign(curve, hashAlgo, message, keyPair); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunaley Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support signing: ' + err.message); + } + break; + case 'node': + return nodeSign(curve, hashAlgo, message, privateKey); + } + } + + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + const signature = nobleCurve.sign(hashed, privateKey, { lowS: false }); + return { + r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize), + s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize) + }; +} + +/** + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} message - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + // See https://github.com/openpgpjs/openpgpjs/pull/948. + // NB: the impact was more likely limited to Brainpool curves, since thanks + // to WebCrypto availability, NIST curve should not have been affected. + // Similarly, secp256k1 should have been used rarely enough. + // However, we implement the fix for all curves, since it's only needed in case of + // verification failure, which is unexpected, hence a minor slowdown is acceptable. + const tryFallbackVerificationForOldBug = async () => ( + hashed[0] === 0 ? + jsVerify(curve, signature, hashed.subarray(1), publicKey) : + false + ); + + if (message && !util.isStream(message)) { + switch (curve.type) { + case 'web': + try { + // Need to await to make sure browser succeeds + const verified = await webVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunately Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support verifying: ' + err.message); + } + break; + case 'node': { + const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } + } + } + + const verified = await jsVerify(curve, signature, hashed, publicKey); + return verified || tryFallbackVerificationForOldBug(); +} + +/** + * Validate ECDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDSA public point + * @param {Uint8Array} d - ECDSA secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$5(oid, Q, d) { + const curve = new CurveWithOID(oid); + // Reject curves x25519 and ed25519 + if (curve.keyType !== enums.publicKey.ecdsa) { + return false; + } + + // To speed up the validation, we try to use node- or webcrypto when available + // and sign + verify a random message + switch (curve.type) { + case 'web': + case 'node': { + const message = getRandomBytes(8); + const hashAlgo = enums.hash.sha256; + const hashed = await hash$1.digest(hashAlgo, message); + try { + const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed); + // eslint-disable-next-line @typescript-eslint/return-await + return await verify$4(oid, hashAlgo, signature, message, Q, hashed); + } catch (err) { + return false; + } + } + default: + return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); + } +} + + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + +/** + * Fallback javascript implementation of ECDSA verification. + * To be used if no native implementation is available for the given curve/operation. + */ +async function jsVerify(curve, signature, hashed, publicKey) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false }); +} + +async function webSign(curve, hashAlgo, message, keyPair) { + const len = curve.payloadSize; + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['sign'] + ); + + const signature = new Uint8Array(await webCrypto$1.sign( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + message + )); + + return { + r: signature.slice(0, len), + s: signature.slice(len, len << 1) + }; +} + +async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['verify'] + ); + + const signature = util.concatUint8Array([r, s]).buffer; + + return webCrypto$1.verify( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + signature, + message + ); +} + +async function nodeSign(curve, hashAlgo, message, privateKey) { + // JWT encoding cannot be used for now, as Brainpool curves are not supported + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + privateKey: nodeBuffer.from(privateKey) + }); + + const sign = nodeCrypto$1.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(message); + sign.end(); + + const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' })); + const len = curve.payloadSize; + + return { + r: signature.subarray(0, len), + s: signature.subarray(len, len << 1) + }; +} + +async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { publicKey: derPublicKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + publicKey: nodeBuffer.from(publicKey) + }); + + const verify = nodeCrypto$1.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(message); + verify.end(); + + const signature = util.concatUint8Array([r, s]); + + try { + return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature); + } catch (err) { + return false; + } +} + +var ecdsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$4, + validateParams: validateParams$5, + verify: verify$4 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Sign a message using the provided legacy EdDSA key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed); + // EdDSA signature params are returned in little-endian format + return { + r: signature.subarray(0, 32), + s: signature.subarray(32) + }; +} + +/** + * Verifies if a legacy EdDSA signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + const RS = util.concatUint8Array([r, s]); + return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed); +} +/** + * Validate legacy EdDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - EdDSA public point + * @param {Uint8Array} k - EdDSA secret seed + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$4(oid, Q, k) { + // Check whether the given curve is supported + if (oid.getName() !== enums.curve.ed25519Legacy) { + return false; + } + + /** + * Derive public point Q' = dG from private key + * and expect Q == Q' + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(k); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + return util.equalsUint8Array(Q, dG); + +} + +var eddsa_legacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$3, + validateParams: validateParams$4, + verify: verify$3 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * @fileoverview Functions to add and remove PKCS5 padding + * @see PublicKeyEncryptedSessionKeyPacket + * @module crypto/pkcs5 + * @private + */ + +/** + * Add pkcs5 padding to a message + * @param {Uint8Array} message - message to pad + * @returns {Uint8Array} Padded message. + */ +function encode(message) { + const c = 8 - (message.length % 8); + const padded = new Uint8Array(message.length + c).fill(c); + padded.set(message); + return padded; +} + +/** + * Remove pkcs5 padding from a message + * @param {Uint8Array} message - message to remove padding from + * @returns {Uint8Array} Message without padding. + */ +function decode$1(message) { + const len = message.length; + if (len > 0) { + const c = message[len - 1]; + if (c >= 1) { + const provided = message.subarray(len - c); + const computed = new Uint8Array(c).fill(c); + if (util.equalsUint8Array(provided, computed)) { + return message.subarray(0, len - c); + } + } + } + throw new Error('Invalid padding'); +} + +var pkcs5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: decode$1, + encode: encode +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto = util.getWebCrypto(); +const nodeCrypto = util.getNodeCrypto(); + +/** + * Validate ECDH parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDH public point + * @param {Uint8Array} d - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$3(oid, Q, d) { + return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); +} + +// Build Param for ECDH algorithm (RFC 6637) +function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { + return util.concatUint8Array([ + oid.write(), + new Uint8Array([public_algo]), + kdfParams.write(), + util.stringToUint8Array('Anonymous Sender '), + fingerprint + ]); +} + +// Key Derivation Function (RFC 6637) +async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { + // Note: X is little endian for Curve25519, big-endian for all others. + // This is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + let i; + if (stripLeading) { + // Work around old go crypto bug + for (i = 0; i < X.length && X[i] === 0; i++); + X = X.subarray(i); + } + if (stripTrailing) { + // Work around old OpenPGP.js bug + for (i = X.length - 1; i >= 0 && X[i] === 0; i--); + X = X.subarray(0, i + 1); + } + const digest = await hash$1.digest(hashAlgo, util.concatUint8Array([ + new Uint8Array([0, 0, 0, 1]), + X, + param + ])); + return digest.subarray(0, length); +} + +/** + * Generate ECDHE ephemeral key and secret from public key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPublicEphemeralKey(curve, Q) { + switch (curve.type) { + case 'curve25519Legacy': { + const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1)); + const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]); + return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPublicEphemeralKey(curve, Q); + } catch (err) { + util.printDebugError(err); + return jsPublicEphemeralKey(curve, Q); + } + } + break; + case 'node': + return nodePublicEphemeralKey(curve, Q); + default: + return jsPublicEphemeralKey(curve, Q); + + } +} + +/** + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} data - Unpadded session key data + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} + * @async + */ +async function encrypt$1(oid, kdfParams, data, Q, fingerprint) { + const m = encode(data); + + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); + const wrappedKey = await wrap(kdfParams.cipher, Z, m); + return { publicKey, wrappedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; + } + switch (curve.type) { + case 'curve25519Legacy': { + const secretKey = d.slice().reverse(); + const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey); + return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPrivateEphemeralKey(curve, V, Q, d); + } catch (err) { + util.printDebugError(err); + return jsPrivateEphemeralKey(curve, V, d); + } + } + break; + case 'node': + return nodePrivateEphemeralKey(curve, V, d); + default: + return jsPrivateEphemeralKey(curve, V, d); + } +} + +/** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} C - Encrypted and wrapped value derived from session key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise} Value derived from session key. + * @async + */ +async function decrypt$1(oid, kdfParams, V, C, Q, d, fingerprint) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + checkPublicPointEnconding(curve, V); + const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + let err; + for (let i = 0; i < 3; i++) { + try { + // Work around old go crypto bug and old OpenPGP.js bug, respectively. + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); + return decode$1(await unwrap(kdfParams.cipher, Z, C)); + } catch (e) { + err = e; + } + } + throw err; +} + +async function jsPrivateEphemeralKey(curve, V, d) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V); + const sharedKey = sharedSecretWithParity.subarray(1); + return { secretKey: d, sharedKey }; +} + +async function jsPublicEphemeralKey(curve, Q) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + const { publicKey: V, privateKey: v } = await curve.genKeyPair(); + + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q); + const sharedKey = sharedSecretWithParity.subarray(1); + return { publicKey: V, sharedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPrivateEphemeralKey(curve, V, Q, d) { + const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d); + let privateKey = webCrypto.importKey( + 'jwk', + recipient, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V); + let sender = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + [] + ); + [privateKey, sender] = await Promise.all([privateKey, sender]); + let S = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: sender + }, + privateKey, + curve.sharedSize + ); + let secret = webCrypto.exportKey( + 'jwk', + privateKey + ); + [S, secret] = await Promise.all([S, secret]); + const sharedKey = new Uint8Array(S); + const secretKey = b64ToUint8Array(secret.d); + return { secretKey, sharedKey }; +} + +/** + * Generate ECDHE ephemeral key and secret from public key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPublicEphemeralKey(curve, Q) { + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q); + let keyPair = webCrypto.generateKey( + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + let recipient = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + false, + [] + ); + [keyPair, recipient] = await Promise.all([keyPair, recipient]); + let s = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: recipient + }, + keyPair.privateKey, + curve.sharedSize + ); + let p = webCrypto.exportKey( + 'jwk', + keyPair.publicKey + ); + [s, p] = await Promise.all([s, p]); + const sharedKey = new Uint8Array(s); + const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte)); + return { publicKey, sharedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePrivateEphemeralKey(curve, V, d) { + const recipient = nodeCrypto.createECDH(curve.node); + recipient.setPrivateKey(d); + const sharedKey = new Uint8Array(recipient.computeSecret(V)); + const secretKey = new Uint8Array(recipient.getPrivateKey()); + return { secretKey, sharedKey }; +} + +/** + * Generate ECDHE ephemeral key and secret from public key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePublicEphemeralKey(curve, Q) { + const sender = nodeCrypto.createECDH(curve.node); + sender.generateKeys(); + const sharedKey = new Uint8Array(sender.computeSecret(Q)); + const publicKey = new Uint8Array(sender.getPublicKey()); + return { publicKey, sharedKey }; +} + +var ecdh = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$1, + encrypt: encrypt$1, + validateParams: validateParams$3 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +var elliptic = /*#__PURE__*/Object.freeze({ + __proto__: null, + CurveWithOID: CurveWithOID, + ecdh: ecdh, + ecdhX: ecdh_x, + ecdsa: ecdsa, + eddsa: eddsa, + eddsaLegacy: eddsa_legacy, + generate: generate$1, + getPreferredHashAlgo: getPreferredHashAlgo$1 +}); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 +*/ + +const _0n$7 = BigInt(0); +const _1n$9 = BigInt(1); + +/** + * DSA Sign function + * @param {Integer} hashAlgo + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} x + * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} + * @async + */ +async function sign$2(hashAlgo, hashed, g, p, q, x) { + const _0n = BigInt(0); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + x = uint8ArrayToBigInt(x); + + let k; + let r; + let s; + let t; + g = mod$2(g, p); + x = mod$2(x, q); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + while (true) { + // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + k = getRandomBigInteger(_1n$9, q); // returns in [1, q-1] + r = mod$2(modExp(g, k, p), q); // (g**k mod p) mod q + if (r === _0n) { + continue; + } + const xr = mod$2(x * r, q); + t = mod$2(h + xr, q); // H(m) + x*r mod q + s = mod$2(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q + if (s === _0n) { + continue; + } + break; + } + return { + r: bigIntToUint8Array(r, 'be', byteLength(p)), + s: bigIntToUint8Array(s, 'be', byteLength(p)) + }; +} + +/** + * DSA Verify function + * @param {Integer} hashAlgo + * @param {Uint8Array} r + * @param {Uint8Array} s + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} y + * @returns {boolean} + * @async + */ +async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) { + r = uint8ArrayToBigInt(r); + s = uint8ArrayToBigInt(s); + + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + + if (r <= _0n$7 || r >= q || + s <= _0n$7 || s >= q) { + util.printDebug('invalid DSA Signature'); + return false; + } + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + const w = modInv(s, q); // s**-1 mod q + if (w === _0n$7) { + util.printDebug('invalid DSA Signature'); + return false; + } + + g = mod$2(g, p); + y = mod$2(y, p); + const u1 = mod$2(h * w, q); // H(m) * w mod q + const u2 = mod$2(r * w, q); // r * w mod q + const t1 = modExp(g, u1, p); // g**u1 mod p + const t2 = modExp(y, u2, p); // y**u2 mod p + const v = mod$2(mod$2(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q + return v === r; +} + +/** + * Validate DSA parameters + * @param {Uint8Array} p - DSA prime + * @param {Uint8Array} q - DSA group order + * @param {Uint8Array} g - DSA sub-group generator + * @param {Uint8Array} y - DSA public key + * @param {Uint8Array} x - DSA private key + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$2(p, q, g, y, x) { + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + // Check that 1 < g < p + if (g <= _1n$9 || g >= p) { + return false; + } + + /** + * Check that subgroup order q divides p-1 + */ + if (mod$2(p - _1n$9, q) !== _0n$7) { + return false; + } + + /** + * g has order q + * Check that g ** q = 1 mod p + */ + if (modExp(g, q, p) !== _1n$9) { + return false; + } + + /** + * Check q is large and probably prime (we mainly want to avoid small factors) + */ + const qSize = BigInt(bitLength(q)); + const _150n = BigInt(150); + if (qSize < _150n || !isProbablePrime(q, null, 32)) { + return false; + } + + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{rq + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const _2n = BigInt(2); + const r = getRandomBigInteger(_2n << (qSize - _1n$9), _2n << qSize); // draw r of same size as q + const rqx = q * r + x; + if (y !== modExp(g, rqx, p)) { + return false; + } + + return true; +} + +var dsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$2, + validateParams: validateParams$2, + verify: verify$2 +}); + +/** + * @fileoverview Asymmetric cryptography functions + * @module crypto/public_key + */ + + +var publicKey = { + /** @see module:crypto/public_key/rsa */ + rsa: rsa, + /** @see module:crypto/public_key/elgamal */ + elgamal: elgamal, + /** @see module:crypto/public_key/elliptic */ + elliptic: elliptic, + /** @see module:crypto/public_key/dsa */ + dsa: dsa +}; + +/** + * @fileoverview Provides functions for asymmetric signing and signature verification + * @module crypto/signature + */ + + +/** + * Parse signature in binary form to get the parameters. + * The returned values are only padded for EdDSA, since in the other cases their expected length + * depends on the key params, hence we delegate the padding to the signature verification function. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Uint8Array} signature - Data for which the signature was created + * @returns {Promise} True if signature is valid. + * @async + */ +function parseSignatureParams(algo, signature) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA signatures: + // - MPI of RSA signature value m**d mod n. + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + // The signature needs to be the same length as the public key modulo n. + // We pad s on signature verification, where we have access to n. + return { read, signatureParams: { s } }; + } + // Algorithm-Specific Fields for DSA or ECDSA signatures: + // - MPI of DSA or ECDSA value r. + // - MPI of DSA or ECDSA value s. + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + { + // If the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for legacy EdDSA signatures: + // - MPI of an EC point r. + // - EdDSA value s, in MPI, in the little endian representation + case enums.publicKey.eddsaLegacy: { + // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature + // verification: if the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for Ed25519 signatures: + // - 64 octets of the native signature + // Algorithm-Specific Fields for Ed448 signatures: + // - 114 octets of the native signature + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo); + const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length; + return { read, signatureParams: { RS } }; + } + + default: + throw new UnsupportedError('Unknown signature algorithm.'); + } +} + +/** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} signature - Named algorithm-specific signature parameters + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Data for which the signature was created + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} True if signature is valid. + * @async + */ +async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto + return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); + } + case enums.publicKey.dsa: { + const { g, p, q, y } = publicParams; + const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers + return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); + } + case enums.publicKey.ecdsa: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // padding needed for webcrypto + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values: + // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); + } +} + +/** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters + * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters + * @param {Uint8Array} data - Data to be signed + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} Signature Object containing named signature parameters. + * @async + */ +async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { + if (!publicKeyParams || !privateKeyParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); + return { s }; + } + case enums.publicKey.dsa: { + const { g, p, q } = publicKeyParams; + const { x } = privateKeyParams; + return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); + } + case enums.publicKey.elgamal: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + case enums.publicKey.ecdsa: { + const { oid, Q } = publicKeyParams; + const { d } = privateKeyParams; + return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); + } +} + +var signature = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseSignatureParams: parseSignatureParams, + sign: sign$1, + verify: verify$1 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +class ECDHSymmetricKey { + constructor(data) { + if (data) { + this.data = data; + } + } + + /** + * Read an ECDHSymmetricKey from an Uint8Array: + * - 1 octect for the length `l` + * - `l` octects of encoded session key data + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + if (bytes.length >= 1) { + const length = bytes[0]; + if (bytes.length >= 1 + length) { + this.data = bytes.subarray(1, 1 + length); + return 1 + this.data.length; + } + } + throw new Error('Invalid symmetric key'); + } + + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); + } +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @module type/kdf_params + * @private + */ + +class KDFParams { + /** + * @param {enums.hash} hash - Hash algorithm + * @param {enums.symmetric} cipher - Symmetric algorithm + */ + constructor(data) { + if (data) { + const { hash, cipher } = data; + this.hash = hash; + this.cipher = cipher; + } else { + this.hash = null; + this.cipher = null; + } + } + + /** + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input - Where to read the KDFParams from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new UnsupportedError('Cannot read KDFParams'); + } + this.hash = input[2]; + this.cipher = input[3]; + return 4; + } + + /** + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value + */ + write() { + return new Uint8Array([3, 1, this.hash, this.cipher]); + } +} + +/** + * Encoded symmetric key for x25519 and x448 + * The payload format varies for v3 and v6 PKESK: + * the former includes an algorithm byte preceeding the encrypted session key. + * + * @module type/x25519x448_symkey + */ + + +class ECDHXSymmetricKey { + static fromObject({ wrappedKey, algorithm }) { + const instance = new ECDHXSymmetricKey(); + instance.wrappedKey = wrappedKey; + instance.algorithm = algorithm; + return instance; + } + + /** + * - 1 octect for the length `l` + * - `l` octects of encoded session key data (with optional leading algorithm byte) + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + let read = 0; + let followLength = bytes[read++]; + this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even + followLength -= followLength % 2; + this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength; + } + + /** + * Write an MontgomerySymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([ + this.algorithm ? + new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : + new Uint8Array([this.wrappedKey.length]), + this.wrappedKey + ]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} keyAlgo - Public key algorithm + * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only) + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Session key data to be encrypted + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @returns {Promise} Encrypted session key parameters. + * @async + */ +async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const { n, e } = publicParams; + const c = await publicKey.rsa.encrypt(data, n, e); + return { c }; + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + return publicKey.elgamal.encrypt(data, p, g, y); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicParams; + const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( + oid, kdfParams, data, Q, fingerprint); + return { V, C: new ECDHSymmetricKey(C) }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + if (symmetricAlgo && !util.isAES(symmetricAlgo)) { + // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 + throw new Error('X25519 and X448 keys can only encrypt AES session keys'); + } + const { A } = publicParams; + const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( + keyAlgo, data, A); + const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); + return { ephemeralPublicKey, C }; + } + default: + return []; + } +} + +/** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Object} publicKeyParams - Algorithm-specific public key parameters + * @param {Object} privateKeyParams - Algorithm-specific private key parameters + * @param {Object} sessionKeyParams - Encrypted session key parameters + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing + * (needed for constant-time processing in RSA and ElGamal) + * @returns {Promise} Decrypted data. + * @throws {Error} on sensitive decryption error, unless `randomPayload` is given + * @async + */ +async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: { + const { c } = sessionKeyParams; + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); + } + case enums.publicKey.elgamal: { + const { c1, c2 } = sessionKeyParams; + const p = publicKeyParams.p; + const x = privateKeyParams.x; + return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicKeyParams; + const { d } = privateKeyParams; + const { V, C } = sessionKeyParams; + return publicKey.elliptic.ecdh.decrypt( + oid, kdfParams, V, C.data, Q, d, fingerprint); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicKeyParams; + const { k } = privateKeyParams; + const { ephemeralPublicKey, C } = sessionKeyParams; + if (C.algorithm !== null && !util.isAES(C.algorithm)) { + throw new Error('AES session key expected'); + } + return publicKey.elliptic.ecdhX.decrypt( + algo, ephemeralPublicKey, C.wrappedKey, A, k); + } + default: + throw new Error('Unknown public key encryption algorithm.'); + } +} + +/** + * Parse public key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. + */ +function parsePublicKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; + const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; + return { read, publicParams: { n, e } }; + } + case enums.publicKey.dsa: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, q, g, y } }; + } + case enums.publicKey.elgamal: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, g, y } }; + } + case enums.publicKey.ecdsa: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.eddsaLegacy: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + if (oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + Q = util.leftPad(Q, 33); + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.ecdh: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); + return { read: read, publicParams: { oid, Q, kdfParams } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length; + return { read, publicParams: { A } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); + } +} + +/** + * Parse private key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @param {Object} publicParams - (ECC only) public params, needed to format some private params + * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. + */ +function parsePrivateKeyParams(algo, bytes, publicParams) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; + return { read, privateParams: { d, p, q, u } }; + } + case enums.publicKey.dsa: + case enums.publicKey.elgamal: { + const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; + return { read, privateParams: { x } }; + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + d = util.leftPad(d, payloadSize); + return { read, privateParams: { d } }; + } + case enums.publicKey.eddsaLegacy: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; + seed = util.leftPad(seed, payloadSize); + return { read, privateParams: { seed } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const payloadSize = getCurvePayloadSize(algo); + const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length; + return { read, privateParams: { seed } }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const payloadSize = getCurvePayloadSize(algo); + const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length; + return { read, privateParams: { k } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); + } +} + +/** Returns the types comprising the encrypted session key of an algorithm + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {Object} The session key parameters referenced by name. + */ +function parseEncSessionKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const c = util.readMPI(bytes.subarray(read)); + return { c }; + } + + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case enums.publicKey.elgamal: { + const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; + const c2 = util.readMPI(bytes.subarray(read)); + return { c1, c2 }; + } + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case enums.publicKey.ecdh: { + const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; + const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); + return { V, C }; + } + // Algorithm-Specific Fields for X25519 or X448 encrypted session keys: + // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448). + // - A one-octet size of the following fields. + // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). + // - The encrypted session key. + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const pointSize = getCurvePayloadSize(algo); + const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length; + const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); + return { ephemeralPublicKey, C }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); + } +} + +/** + * Convert params to MPI and serializes them in the proper order + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} params - The key parameters indexed by name + * @returns {Uint8Array} The array containing the MPIs. + */ +function serializeParams(algo, params) { + // Some algorithms do not rely on MPIs to store the binary params + const algosWithNativeRepresentation = new Set([ + enums.publicKey.ed25519, + enums.publicKey.x25519, + enums.publicKey.ed448, + enums.publicKey.x448 + ]); + const orderedParams = Object.keys(params).map(name => { + const param = params[name]; + if (!util.isUint8Array(param)) return param.write(); + return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); + }); + return util.concatUint8Array(orderedParams); +} + +/** + * Generate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Integer} bits - Bit length for RSA keys + * @param {module:type/oid} oid - Object identifier for ECC keys + * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. + * @async + */ +function generateParams(algo, bits, oid) { + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ + privateParams: { d, p, q, u }, + publicParams: { n, e } + })); + case enums.publicKey.ecdsa: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { d: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { seed: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.ecdh: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ + privateParams: { d: secret }, + publicParams: { + oid: new OID(oid), + Q, + kdfParams: new KDFParams({ hash, cipher }) + } + })); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ + privateParams: { seed }, + publicParams: { A } + })); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ + privateParams: { k }, + publicParams: { A } + })); + case enums.publicKey.dsa: + case enums.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + default: + throw new Error('Unknown public key algorithm.'); + } +} + +/** + * Validate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Object} privateParams - Algorithm-specific private key parameters + * @returns {Promise} Whether the parameters are valid. + * @async + */ +async function validateParams$1(algo, publicParams, privateParams) { + if (!publicParams || !privateParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const { d, p, q, u } = privateParams; + return publicKey.rsa.validateParams(n, e, d, p, q, u); + } + case enums.publicKey.dsa: { + const { p, q, g, y } = publicParams; + const { x } = privateParams; + return publicKey.dsa.validateParams(p, q, g, y, x); + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + const { x } = privateParams; + return publicKey.elgamal.validateParams(p, g, y, x); + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; + const { oid, Q } = publicParams; + const { d } = privateParams; + return algoModule.validateParams(oid, Q, d); + } + case enums.publicKey.eddsaLegacy: { + const { Q, oid } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsa.validateParams(algo, A, seed); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicParams; + const { k } = privateParams; + return publicKey.elliptic.ecdhX.validateParams(algo, A, k); + } + default: + throw new Error('Unknown public key algorithm.'); + } +} + +/** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + * @async + */ +async function getPrefixRandom(algo) { + const { blockSize } = getCipherParams(algo); + const prefixrandom = await getRandomBytes(blockSize); + const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + return util.concat([prefixrandom, repeat]); +} + +/** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key. + */ +function generateSessionKey$1(algo) { + const { keySize } = getCipherParams(algo); + return getRandomBytes(keySize); +} + +/** + * Get implementation of the given AEAD mode + * @param {enums.aead} algo + * @returns {Object} + * @throws {Error} on invalid algo + */ +function getAEADMode(algo) { + const algoName = enums.read(enums.aead, algo); + return mode[algoName]; +} + +/** + * Check whether the given curve OID is supported + * @param {module:type/oid} oid - EC object identifier + * @throws {UnsupportedError} if curve is not supported + */ +function checkSupportedCurve(oid) { + try { + oid.getName(); + } catch (e) { + throw new UnsupportedError('Unknown curve OID'); + } +} + +/** + * Get encoded secret size for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getCurvePayloadSize(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: + case enums.publicKey.eddsaLegacy: + return new publicKey.elliptic.CurveWithOID(oid).payloadSize; + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPayloadSize(algo); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.getPayloadSize(algo); + default: + throw new Error('Unknown elliptic algo'); + } +} + +/** + * Get preferred signing hash algo for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getPreferredCurveHashAlgo(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.getPreferredHashAlgo(oid); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); + default: + throw new Error('Unknown elliptic signing algo'); + } +} + +var crypto$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + generateParams: generateParams, + generateSessionKey: generateSessionKey$1, + getAEADMode: getAEADMode, + getCipherParams: getCipherParams, + getCurvePayloadSize: getCurvePayloadSize, + getPreferredCurveHashAlgo: getPreferredCurveHashAlgo, + getPrefixRandom: getPrefixRandom, + parseEncSessionKeyParams: parseEncSessionKeyParams, + parsePrivateKeyParams: parsePrivateKeyParams, + parsePublicKeyParams: parsePublicKeyParams, + publicKeyDecrypt: publicKeyDecrypt, + publicKeyEncrypt: publicKeyEncrypt, + serializeParams: serializeParams, + validateParams: validateParams$1 +}); + +/** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ + + +// TODO move cfb and gcm to cipher +const mod$1 = { + /** @see module:crypto/cipher */ + cipher: cipher, + /** @see module:crypto/hash */ + hash: hash$1, + /** @see module:crypto/mode */ + mode: mode, + /** @see module:crypto/public_key */ + publicKey: publicKey, + /** @see module:crypto/signature */ + signature: signature, + /** @see module:crypto/random */ + random: random, + /** @see module:crypto/pkcs1 */ + pkcs1: pkcs1, + /** @see module:crypto/pkcs5 */ + pkcs5: pkcs5, + /** @see module:crypto/aes_kw */ + aesKW: aesKW +}; + +Object.assign(mod$1, crypto$2); + +const ARGON2_TYPE = 0x02; // id +const ARGON2_VERSION = 0x13; +const ARGON2_SALT_SIZE = 16; + +class Argon2OutOfMemoryError extends Error { + constructor(...params) { + super(...params); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Argon2OutOfMemoryError); + } + + this.name = 'Argon2OutOfMemoryError'; + } +} + +// cache argon wasm module +let loadArgonWasmModule; +let argon2Promise; +// reload wasm module above this treshold, to deallocated used memory +const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; + +class Argon2S2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params; + + this.type = 'argon2'; + /** + * 16 bytes of salt + * @type {Uint8Array} + */ + this.salt = null; + /** + * number of passes + * @type {Integer} + */ + this.t = passes; + /** + * degree of parallelism (lanes) + * @type {Integer} + */ + this.p = parallelism; + /** + * exponent indicating memory size + * @type {Integer} + */ + this.encodedM = memoryExponent; + } + + generateSalt() { + this.salt = mod$1.random.getRandomBytes(ARGON2_SALT_SIZE); + } + + /** + * Parsing function for argon2 string-to-key specifier. + * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; + + this.salt = bytes.subarray(i, i + 16); + i += 16; + + this.t = bytes[i++]; + this.p = bytes[i++]; + this.encodedM = bytes[i++]; // memory size exponent, one-octect + + return i; + } + + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + const arr = [ + new Uint8Array([enums.write(enums.s2k, this.type)]), + this.salt, + new Uint8Array([this.t, this.p, this.encodedM]) + ]; + + return util.concatUint8Array(arr); + } + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to `keySize` + * @throws {Argon2OutOfMemoryError|Errors} + * @async + */ + async produceKey(passphrase, keySize) { + const decodedM = 2 << (this.encodedM - 1); + + try { + // on first load, the argon2 lib is imported and the WASM module is initialized. + // the two steps need to be atomic to avoid race conditions causing multiple wasm modules + // being loaded when `argon2Promise` is not initialized. + loadArgonWasmModule = loadArgonWasmModule || (await Promise.resolve().then(function () { return index$1; })).default; + argon2Promise = argon2Promise || loadArgonWasmModule(); + + // important to keep local ref to argon2 in case the module is reloaded by another instance + const argon2 = await argon2Promise; + + const passwordBytes = util.encodeUTF8(passphrase); + const hash = argon2({ + version: ARGON2_VERSION, + type: ARGON2_TYPE, + password: passwordBytes, + salt: this.salt, + tagLength: keySize, + memorySize: decodedM, + parallelism: this.p, + passes: this.t + }); + + // a lot of memory was used, reload to deallocate + if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); + } + return hash; + } catch (e) { + if (e.message && ( + e.message.includes('Unable to grow instance memory') || // Chrome + e.message.includes('failed to grow memory') || // Firefox + e.message.includes('WebAssembly.Memory.grow') || // Safari + e.message.includes('Out of memory') // Safari iOS + )) { + throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2'); + } else { + throw e; + } + } + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +class GenericS2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(s2kType, config$1 = config) { + /** + * Hash function identifier, or 0 for gnu-dummy keys + * @type {module:enums.hash | 0} + */ + this.algorithm = enums.hash.sha256; + /** + * enums.s2k identifier or 'gnu-dummy' + * @type {String} + */ + this.type = enums.read(enums.s2k, s2kType); + /** @type {Integer} */ + this.c = config$1.s2kIterationCountByte; + /** Eight bytes of salt in a binary string. + * @type {Uint8Array} + */ + this.salt = null; + } + + generateSalt() { + switch (this.type) { + case 'salted': + case 'iterated': + this.salt = mod$1.random.getRandomBytes(8); + } + } + + getCount() { + // Exponent bias, defined in RFC4880 + const expbias = 6; + + return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); + } + + /** + * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param {Uint8Array} bytes - Payload of string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; + this.algorithm = bytes[i++]; + + switch (this.type) { + case 'simple': + break; + + case 'salted': + this.salt = bytes.subarray(i, i + 8); + i += 8; + break; + + case 'iterated': + this.salt = bytes.subarray(i, i + 8); + i += 8; + + // Octet 10: count, a one-octet, coded value + this.c = bytes[i++]; + break; + + case 'gnu': + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { + i += 3; // GNU + const gnuExtType = 1000 + bytes[i++]; + if (gnuExtType === 1001) { + this.type = 'gnu-dummy'; + // GnuPG extension mode 1001 -- don't write secret key at all + } else { + throw new UnsupportedError('Unknown s2k gnu protection mode.'); + } + } else { + throw new UnsupportedError('Unknown s2k type.'); + } + break; + + default: + throw new UnsupportedError('Unknown s2k type.'); // unreachable + } + + return i; + } + + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + if (this.type === 'gnu-dummy') { + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); + } + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; + + switch (this.type) { + case 'simple': + break; + case 'salted': + arr.push(this.salt); + break; + case 'iterated': + arr.push(this.salt); + arr.push(new Uint8Array([this.c])); + break; + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + + return util.concatUint8Array(arr); + } + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to. + * hashAlgorithm hash length + * @async + */ + async produceKey(passphrase, numBytes) { + passphrase = util.encodeUTF8(passphrase); + + const arr = []; + let rlength = 0; + + let prefixlen = 0; + while (rlength < numBytes) { + let toHash; + switch (this.type) { + case 'simple': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); + break; + case 'salted': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); + break; + case 'iterated': { + const data = util.concatUint8Array([this.salt, passphrase]); + let datalen = data.length; + const count = Math.max(this.getCount(), datalen); + toHash = new Uint8Array(prefixlen + count); + toHash.set(data, prefixlen); + for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { + toHash.copyWithin(pos, prefixlen, pos); + } + break; + } + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + const result = await mod$1.hash.digest(this.algorithm, toHash); + arr.push(result); + rlength += result.length; + prefixlen++; + } + + return util.concatUint8Array(arr).subarray(0, numBytes); + } +} + +const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]); + +/** + * Instantiate a new S2K instance of the given type + * @param {module:enums.s2k} type + * @oaram {Object} [config] + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromType(type, config$1 = config) { + switch (type) { + case enums.s2k.argon2: + return new Argon2S2K(config$1); + case enums.s2k.iterated: + case enums.s2k.gnu: + case enums.s2k.salted: + case enums.s2k.simple: + return new GenericS2K(type, config$1); + default: + throw new UnsupportedError('Unsupported S2K type'); + } +} + +/** + * Instantiate a new S2K instance based on the config settings + * @oaram {Object} config + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromConfig(config) { + const { s2kType } = config; + + if (!allowedS2KTypesForEncryption.has(s2kType)) { + throw new Error('The provided `config.s2kType` value is not allowed'); + } + + return newS2KFromType(s2kType, config); +} + +var require$1 = module$1.createRequire('/'); +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +// Mediocre shim +var Worker; +try { + Worker = require$1('worker_threads').Worker; +} +catch (e) { +} + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, u32$1 = Uint32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +// see fleb note +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new u32$1(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return [b, r]; +}; +var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >>> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32$1 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, buf, st) { + // source length + var sl = dat.length; + if (!sl || (st && st.f && !st.l)) + return buf || new u8(0); + // have to estimate size + var noBuf = !buf || st; + // no state + var noSt = !st || st.i; + if (!st) + st = {}; + // Assumes roughly 33% compression ratio average + if (!buf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (noBuf) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >>> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17; + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + d[o + 2] |= v >>> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return [et, 0]; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return [v, 1]; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return [new u8(tr), mbt]; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return [cl.subarray(0, cli), s]; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >>> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; + var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; + var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; + var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + lcfreq[lclt[i] & 31]++; + for (var i = 0; i < lcdt.length; ++i) + lcfreq[lcdt[i] & 31]++; + var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); + if (flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + if (syms[i] > 255) { + var len = (syms[i] >>> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; + var dst = syms[i] & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new u32$1([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, lst) { + var s = dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var pos = 0; + if (!lvl || s < 8) { + for (var i = 0; i <= s; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[pos >> 3] = lst; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + } + else { + var opt = deo[lvl - 1]; + var n = opt >>> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = new u16(32768), head = new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new u32$1(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx bitpos + var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; + for (; i < s; ++i) { + // hash value + // deopt when i > s - 3 - at end, deopt acceptable + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && rem > 423) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = (i - dif + j + 32768) & 32767; + var pti = prev[ti]; + var cd = (ti - pti + 32768) & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += (imod - pimod + 32768) & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one Uint32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + // this is the easiest way to avoid needing to maintain state + if (!lst && pos & 7) + pos = wfblk(w, pos + 1, et); + } + return slc(o, 0, pre + shft(pos) + post); +}; +// Alder32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); + } + }; +}; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st); +}; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); +}; +// zlib footer: -4 to -0 is Adler32 +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (!cb && typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, !f), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.d = final; + this.p(chunk, final || false); + }; + return Deflate; +}()); +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + /** + * Creates an inflation stream + * @param cb The callback to call whenever data is inflated + */ + function Inflate(cb) { + this.s = {}; + this.p = new u8(0); + this.ondata = cb; + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + var l = this.p.length; + var n = new u8(l + c.length); + n.set(this.p), n.set(c, l), this.p = n; + }; + Inflate.prototype.c = function (final) { + this.d = this.s.i = final || false; + var bts = this.s.b; + var dt = inflt(this.p, this.o, this.s); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + this.c.p(c); + var raw = dopt(c, this.o, this.v && 2, f && 4, !f); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + return Zlib; +}()); +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + function Unzlib(cb) { + this.v = 1; + Inflate.call(this, cb); + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 2 && !final) + return; + this.p = this.p.subarray(2), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Literal Data Packet (Tag 11) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. + */ +class LiteralDataPacket { + static get tag() { + return enums.packet.literalData; + } + + /** + * @param {Date} date - The creation date of the literal package + */ + constructor(date = new Date()) { + this.format = enums.literal.utf8; // default format for literal data packets + this.date = util.normalizeDate(date); + this.text = null; // textual data representation + this.data = null; // literal data representation + this.filename = ''; + } + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param {String | ReadableStream} text - Any native javascript string + * @param {enums.literal} [format] - The format of the string of bytes + */ + setText(text, format = enums.literal.utf8) { + this.format = format; + this.text = text; + this.data = null; + } + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {String | ReadableStream} Literal data as text. + */ + getText(clone = false) { + if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read + this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); + } + return this.text; + } + + /** + * Set the packet data to value represented by the provided string of bytes. + * @param {Uint8Array | ReadableStream} bytes - The string of bytes + * @param {enums.literal} format - The format of the string of bytes + */ + setBytes(bytes, format) { + this.format = format; + this.data = bytes; + this.text = null; + } + + + /** + * Get the byte sequence representing the literal packet data + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {Uint8Array | ReadableStream} A sequence of bytes. + */ + getBytes(clone = false) { + if (this.data === null) { + // encode UTF8 and normalize EOL to \r\n + this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); + } + if (clone) { + return passiveClone(this.data); + } + return this.data; + } + + + /** + * Sets the filename of the literal packet data + * @param {String} filename - Any native javascript string + */ + setFilename(filename) { + this.filename = filename; + } + + + /** + * Get the filename of the literal packet data + * @returns {String} Filename. + */ + getFilename() { + return this.filename; + } + + /** + * Parsing function for a literal data packet (tag 11). + * + * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet + * @returns {Promise} Object representation. + * @async + */ + async read(bytes) { + await parse(bytes, async reader => { + // - A one-octet field that describes how the data is formatted. + const format = await reader.readByte(); // enums.literal + + const filename_len = await reader.readByte(); + this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); + + this.date = util.readDate(await reader.readBytes(4)); + + let data = reader.remainder(); + if (isArrayStream(data)) data = await readToEnd(data); + this.setBytes(data, format); + }); + } + + /** + * Creates a Uint8Array representation of the packet, excluding the data + * + * @returns {Uint8Array} Uint8Array representation of the packet. + */ + writeHeader() { + const filename = util.encodeUTF8(this.filename); + const filename_length = new Uint8Array([filename.length]); + + const format = new Uint8Array([this.format]); + const date = util.writeDate(this.date); + + return util.concatUint8Array([format, filename_length, filename, date]); + } + + /** + * Creates a Uint8Array representation of the packet + * + * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. + */ + write() { + const header = this.writeHeader(); + const data = this.getBytes(); + + return util.concat([header, data]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ +class KeyID { + constructor() { + this.bytes = ''; + } + + /** + * Parsing method for a key id + * @param {Uint8Array} bytes - Input to read the key id from + */ + read(bytes) { + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); + return this.bytes.length; + } + + /** + * Serializes the Key ID + * @returns {Uint8Array} Key ID as a Uint8Array. + */ + write() { + return util.stringToUint8Array(this.bytes); + } + + /** + * Returns the Key ID represented as a hexadecimal string + * @returns {String} Key ID as a hexadecimal string. + */ + toHex() { + return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); + } + + /** + * Checks equality of Key ID's + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard + */ + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; + } + + /** + * Checks to see if the Key ID is unset + * @returns {Boolean} True if the Key ID is null. + */ + isNull() { + return this.bytes === ''; + } + + /** + * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) + * @returns {Boolean} True if this is a wildcard Key ID. + */ + isWildcard() { + return /^0+$/.test(this.toHex()); + } + + static mapToHex(keyID) { + return keyID.toHex(); + } + + static fromID(hex) { + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; + } + + static wildcard() { + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. +const verified = Symbol('verified'); + +// A salt notation is used to randomize signatures. +// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks +// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170). +// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g. +// some chosen-prefix attacks. +// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt. +const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org'; + +// GPG puts the Issuer and Signature subpackets in the unhashed area. +// Tampering with those invalidates the signature, so we still trust them and parse them. +// All other unhashed subpackets are ignored. +const allowedUnhashedSubpackets = new Set([ + enums.signatureSubpacket.issuerKeyID, + enums.signatureSubpacket.issuerFingerprint, + enums.signatureSubpacket.embeddedSignature +]); + +/** + * Implementation of the Signature Packet (Tag 2) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + */ +class SignaturePacket { + static get tag() { + return enums.packet.signature; + } + + constructor() { + this.version = null; + /** @type {enums.signature} */ + this.signatureType = null; + /** @type {enums.hash} */ + this.hashAlgorithm = null; + /** @type {enums.publicKey} */ + this.publicKeyAlgorithm = null; + + this.signatureData = null; + this.unhashedSubpackets = []; + this.unknownSubpackets = []; + this.signedHashValue = null; + this.salt = null; + + this.created = null; + this.signatureExpirationTime = null; + this.signatureNeverExpires = true; + this.exportable = null; + this.trustLevel = null; + this.trustAmount = null; + this.regularExpression = null; + this.revocable = null; + this.keyExpirationTime = null; + this.keyNeverExpires = null; + this.preferredSymmetricAlgorithms = null; + this.revocationKeyClass = null; + this.revocationKeyAlgorithm = null; + this.revocationKeyFingerprint = null; + this.issuerKeyID = new KeyID(); + this.rawNotations = []; + this.notations = {}; + this.preferredHashAlgorithms = null; + this.preferredCompressionAlgorithms = null; + this.keyServerPreferences = null; + this.preferredKeyServer = null; + this.isPrimaryUserID = null; + this.policyURI = null; + this.keyFlags = null; + this.signersUserID = null; + this.reasonForRevocationFlag = null; + this.reasonForRevocationString = null; + this.features = null; + this.signatureTargetPublicKeyAlgorithm = null; + this.signatureTargetHashAlgorithm = null; + this.signatureTargetHash = null; + this.embeddedSignature = null; + this.issuerKeyVersion = null; + this.issuerFingerprint = null; + this.preferredAEADAlgorithms = null; + this.preferredCipherSuites = null; + + this.revoked = null; + this[verified] = null; + } + + /** + * parsing function for a signature packet (tag 2). + * @param {String} bytes - Payload of a tag 2 packet + * @returns {SignaturePacket} Object representation. + */ + read(bytes, config$1 = config) { + let i = 0; + this.version = bytes[i++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } + + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); + } + + this.signatureType = bytes[i++]; + this.publicKeyAlgorithm = bytes[i++]; + this.hashAlgorithm = bytes[i++]; + + // hashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), true); + if (!this.created) { + throw new Error('Missing signature creation time subpacket.'); + } + + // A V4 signature hashes the packet body + // starting from its first field, the version number, through the end + // of the hashed subpacket data. Thus, the fields hashed are the + // signature version, the signature type, the public-key algorithm, the + // hash algorithm, the hashed subpacket length, and the hashed + // subpacket body. + this.signatureData = bytes.subarray(0, i); + + // unhashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), false); + + // Two-octet field holding left 16 bits of signed hash value. + this.signedHashValue = bytes.subarray(i, i + 2); + i += 2; + + // Only for v6 signatures, a variable-length field containing: + if (this.version === 6) { + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[i++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(i, i + saltLength); + i += saltLength; + } + + const signatureMaterial = bytes.subarray(i, bytes.length); + const { read, signatureParams } = mod$1.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial); + if (read < signatureMaterial.length) { + throw new Error('Error reading MPIs'); + } + this.params = signatureParams; + } + + /** + * @returns {Uint8Array | ReadableStream} + */ + writeParams() { + if (this.params instanceof Promise) { + return fromAsync( + async () => mod$1.serializeParams(this.publicKeyAlgorithm, await this.params) + ); + } + return mod$1.serializeParams(this.publicKeyAlgorithm, this.params); + } + + write() { + const arr = []; + arr.push(this.signatureData); + arr.push(this.writeUnhashedSubPackets()); + arr.push(this.signedHashValue); + if (this.version === 6) { + arr.push(new Uint8Array([this.salt.length])); + arr.push(this.salt); + } + arr.push(this.writeParams()); + return util.concat(arr); + } + + /** + * Signs provided data. This needs to be done prior to serialization. + * @param {SecretKeyPacket} key - Private key used to sign the message. + * @param {Object} data - Contains packets to be signed. + * @param {Date} [date] - The signature creation time. + * @param {Boolean} [detached] - Whether to create a detached signature + * @throws {Error} if signing failed + * @async + */ + async sign(key, data, date = new Date(), detached = false, config) { + this.version = key.version; + + this.created = util.normalizeDate(date); + this.issuerKeyVersion = key.version; + this.issuerFingerprint = key.getFingerprintBytes(); + this.issuerKeyID = key.getKeyID(); + + const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; + + // add randomness to the signature + if (this.version === 6) { + const saltLength = saltLengthForHash(this.hashAlgorithm); + if (this.salt === null) { + this.salt = mod$1.random.getRandomBytes(saltLength); + } else if (saltLength !== this.salt.length) { + throw new Error('Provided salt does not have the required length'); + } + } else if (config.nonDeterministicSignaturesViaNotation) { + const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME)); + // since re-signing the same object is not supported, it's not expected to have multiple salt notations, + // but we guard against it as a sanity check + if (saltNotations.length === 0) { + const saltValue = mod$1.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm)); + this.rawNotations.push({ + name: SALT_NOTATION_NAME, + value: saltValue, + humanReadable: false, + critical: false + }); + } else { + throw new Error('Unexpected existing salt notation'); + } + } + + // Add hashed subpackets + arr.push(this.writeHashedSubPackets()); + + // Remove unhashed subpackets, in case some allowed unhashed + // subpackets existed, in order not to duplicate them (in both + // the hashed and unhashed subpackets) when re-signing. + this.unhashedSubpackets = []; + + this.signatureData = util.concat(arr); + + const toHash = this.toHash(this.signatureType, data, detached); + const hash = await this.hash(this.signatureType, data, toHash, detached); + + this.signedHashValue = slice(clone(hash), 0, 2); + const signed = async () => mod$1.signature.sign( + this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) + ); + if (util.isStream(hash)) { + this.params = signed(); + } else { + this.params = await signed(); + + // Store the fact that this signature is valid, e.g. for when we call `await + // getLatestValidSignature(this.revocationSignatures, key, data)` later. + // Note that this only holds up if the key and data passed to verify are the + // same as the ones passed to sign. + this[verified] = true; + } + } + + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns {Uint8Array} Subpacket data. + */ + writeHashedSubPackets() { + const sub = enums.signatureSubpacket; + const arr = []; + let bytes; + if (this.created === null) { + throw new Error('Missing signature creation time'); + } + arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); + if (this.signatureExpirationTime !== null) { + arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); + } + if (this.exportable !== null) { + arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); + } + if (this.trustLevel !== null) { + bytes = new Uint8Array([this.trustLevel, this.trustAmount]); + arr.push(writeSubPacket(sub.trustSignature, true, bytes)); + } + if (this.regularExpression !== null) { + arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); + } + if (this.revocable !== null) { + arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); + } + if (this.keyExpirationTime !== null) { + arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); + } + if (this.preferredSymmetricAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); + arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); + } + if (this.revocationKeyClass !== null) { + bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); + bytes = util.concat([bytes, this.revocationKeyFingerprint]); + arr.push(writeSubPacket(sub.revocationKey, false, bytes)); + } + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) { + // If the version of [the] key is greater than 4, this subpacket + // MUST NOT be included in the signature. + arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write())); + } + this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { + bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; + const encodedName = util.encodeUTF8(name); + // 2 octets of name length + bytes.push(util.writeNumber(encodedName.length, 2)); + // 2 octets of value length + bytes.push(util.writeNumber(value.length, 2)); + bytes.push(encodedName); + bytes.push(value); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.notationData, critical, bytes)); + }); + if (this.preferredHashAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); + arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); + } + if (this.preferredCompressionAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); + arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); + } + if (this.keyServerPreferences !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); + arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); + } + if (this.preferredKeyServer !== null) { + arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); + } + if (this.isPrimaryUserID !== null) { + arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + } + if (this.policyURI !== null) { + arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); + } + if (this.keyFlags !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); + arr.push(writeSubPacket(sub.keyFlags, true, bytes)); + } + if (this.signersUserID !== null) { + arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); + } + if (this.reasonForRevocationFlag !== null) { + bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); + } + if (this.features !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); + arr.push(writeSubPacket(sub.features, false, bytes)); + } + if (this.signatureTargetPublicKeyAlgorithm !== null) { + bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; + bytes.push(util.stringToUint8Array(this.signatureTargetHash)); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); + } + if (this.embeddedSignature !== null) { + arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); + } + if (this.issuerFingerprint !== null) { + bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes)); + } + if (this.preferredAEADAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); + arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); + } + if (this.preferredCipherSuites !== null) { + bytes = new Uint8Array([].concat(...this.preferredCipherSuites)); + arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes)); + } + + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); + + return util.concat([length, result]); + } + + /** + * Creates an Uint8Array containing the unhashed subpackets + * @returns {Uint8Array} Subpacket data. + */ + writeUnhashedSubPackets() { + const arr = this.unhashedSubpackets.map(({ type, critical, body }) => { + return writeSubPacket(type, critical, body); + }); + + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); + + return util.concat([length, result]); + } + + // Signature subpackets + readSubPacket(bytes, hashed = true) { + let mypos = 0; + + // The leftmost bit denotes a "critical" packet + const critical = !!(bytes[mypos] & 0x80); + const type = bytes[mypos] & 0x7F; + + mypos++; + + if (!hashed) { + this.unhashedSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + if (!allowedUnhashedSubpackets.has(type)) { + return; + } + } + + // subpacket type + switch (type) { + case enums.signatureSubpacket.signatureCreationTime: + // Signature Creation Time + this.created = util.readDate(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.signatureExpirationTime: { + // Signature Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); + + this.signatureNeverExpires = seconds === 0; + this.signatureExpirationTime = seconds; + + break; + } + case enums.signatureSubpacket.exportableCertification: + // Exportable Certification + this.exportable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.trustSignature: + // Trust Signature + this.trustLevel = bytes[mypos++]; + this.trustAmount = bytes[mypos++]; + break; + case enums.signatureSubpacket.regularExpression: + // Regular Expression + this.regularExpression = bytes[mypos]; + break; + case enums.signatureSubpacket.revocable: + // Revocable + this.revocable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.keyExpirationTime: { + // Key Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); + + this.keyExpirationTime = seconds; + this.keyNeverExpires = seconds === 0; + + break; + } + case enums.signatureSubpacket.preferredSymmetricAlgorithms: + // Preferred Symmetric Algorithms + this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.revocationKey: + // Revocation Key + // (1 octet of class, 1 octet of public-key algorithm ID, 20 + // octets of + // fingerprint) + this.revocationKeyClass = bytes[mypos++]; + this.revocationKeyAlgorithm = bytes[mypos++]; + this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); + break; + + case enums.signatureSubpacket.issuerKeyID: + // Issuer + if (this.version === 4) { + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + } else if (hashed) { + // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature, + // since the Issuer Fingerprint subpacket is to be used instead. + // The `issuerKeyID` value will be set when reading the issuerFingerprint packet. + // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it, + // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed) + // issuerFingerprint. + // If the packet is hashed, then we reject the signature, to avoid verifying data different from + // what was parsed. + throw new Error('Unexpected Issuer Key ID subpacket'); + } + break; + + case enums.signatureSubpacket.notationData: { + // Notation Data + const humanReadable = !!(bytes[mypos] & 0x80); + + // We extract key/value tuple from the byte stream. + mypos += 4; + const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + + const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); + const value = bytes.subarray(mypos + m, mypos + m + n); + + this.rawNotations.push({ name, humanReadable, value, critical }); + + if (humanReadable) { + this.notations[name] = util.decodeUTF8(value); + } + break; + } + case enums.signatureSubpacket.preferredHashAlgorithms: + // Preferred Hash Algorithms + this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCompressionAlgorithms: + // Preferred Compression Algorithms + this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.keyServerPreferences: + // Key Server Preferences + this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredKeyServer: + // Preferred Key Server + this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.primaryUserID: + // Primary User ID + this.isPrimaryUserID = bytes[mypos++] !== 0; + break; + case enums.signatureSubpacket.policyURI: + // Policy URI + this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.keyFlags: + // Key Flags + this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signersUserID: + // Signer's User ID + this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.reasonForRevocation: + // Reason for Revocation + this.reasonForRevocationFlag = bytes[mypos++]; + this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.features: + // Features + this.features = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signatureTarget: { + // Signature Target + // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; + this.signatureTargetHashAlgorithm = bytes[mypos++]; + + const len = mod$1.getHashByteLength(this.signatureTargetHashAlgorithm); + + this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); + break; + } + case enums.signatureSubpacket.embeddedSignature: + // Embedded Signature + this.embeddedSignature = new SignaturePacket(); + this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.issuerFingerprint: + // Issuer Fingerprint + this.issuerKeyVersion = bytes[mypos++]; + this.issuerFingerprint = bytes.subarray(mypos, bytes.length); + if (this.issuerKeyVersion >= 5) { + this.issuerKeyID.read(this.issuerFingerprint); + } else { + this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); + } + break; + case enums.signatureSubpacket.preferredAEADAlgorithms: + // Preferred AEAD Algorithms + this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCipherSuites: + // Preferred AEAD Cipher Suites + this.preferredCipherSuites = []; + for (let i = mypos; i < bytes.length; i += 2) { + this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]); + } + break; + default: + this.unknownSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + break; + } + } + + readSubPackets(bytes, trusted = true, config) { + const subpacketLengthBytes = this.version === 6 ? 4 : 2; + + // Two-octet scalar octet count for following subpacket data. + const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes)); + + let i = subpacketLengthBytes; + + // subpacket data set (zero or more subpackets) + while (i < 2 + subpacketLength) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); + + i += len.len; + } + + return i; + } + + // Produces data to produce signature on + toSign(type, data) { + const t = enums.signature; + + switch (type) { + case t.binary: + if (data.text !== null) { + return util.encodeUTF8(data.getText(true)); + } + return data.getBytes(true); + + case t.text: { + const bytes = data.getBytes(true); + // normalize EOL to \r\n + return util.canonicalizeEOL(bytes); + } + case t.standalone: + return new Uint8Array(0); + + case t.certGeneric: + case t.certPersona: + case t.certCasual: + case t.certPositive: + case t.certRevocation: { + let packet; + let tag; + + if (data.userID) { + tag = 0xB4; + packet = data.userID; + } else if (data.userAttribute) { + tag = 0xD1; + packet = data.userAttribute; + } else { + throw new Error('Either a userID or userAttribute packet needs to be ' + + 'supplied for certification.'); + } + + const bytes = packet.write(); + + return util.concat([this.toSign(t.key, data), + new Uint8Array([tag]), + util.writeNumber(bytes.length, 4), + bytes]); + } + case t.subkeyBinding: + case t.subkeyRevocation: + case t.keyBinding: + return util.concat([this.toSign(t.key, data), this.toSign(t.key, { + key: data.bind + })]); + + case t.key: + if (data.key === undefined) { + throw new Error('Key packet is required for this signature.'); + } + return data.key.writeForHash(this.version); + + case t.keyRevocation: + return this.toSign(t.key, data); + case t.timestamp: + return new Uint8Array(0); + case t.thirdParty: + throw new Error('Not implemented'); + default: + throw new Error('Unknown signature type.'); + } + } + + calculateTrailer(data, detached) { + let length = 0; + return transform(clone(this.signatureData), value => { + length += value.length; + }, () => { + const arr = []; + if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { + if (detached) { + arr.push(new Uint8Array(6)); + } else { + arr.push(data.writeHeader()); + } + } + arr.push(new Uint8Array([this.version, 0xFF])); + if (this.version === 5) { + arr.push(new Uint8Array(4)); + } + arr.push(util.writeNumber(length, 4)); + // For v5, this should really be writeNumber(length, 8) rather than the + // hardcoded 4 zero bytes above + return util.concat(arr); + }); + } + + toHash(signatureType, data, detached = false) { + const bytes = this.toSign(signatureType, data); + + return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]); + } + + async hash(signatureType, data, toHash, detached = false) { + if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) { + // avoid hashing unexpected salt size + throw new Error('Signature salt does not have the expected length'); + } + + if (!toHash) toHash = this.toHash(signatureType, data, detached); + return mod$1.hash.digest(this.hashAlgorithm, toHash); + } + + /** + * verifies the signature packet. Note: not all signature types are implemented + * @param {PublicSubkeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature + * @param {module:enums.signature} signatureType - Expected signature type + * @param {Uint8Array|Object} data - Data which on the signature applies + * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration + * @param {Boolean} [detached] - Whether to verify a detached signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if signature validation failed + * @async + */ + async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { + if (!this.issuerKeyID.equals(key.getKeyID())) { + throw new Error('Signature was not issued by the given public key'); + } + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); + } + + const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; + // Cryptographic validity is cached after one successful verification. + // However, for message signatures, we always re-verify, since the passed `data` can change + const skipVerify = this[verified] && !isMessageSignature; + if (!skipVerify) { + let toHash; + let hash; + if (this.hashed) { + hash = await this.hashed; + } else { + toHash = this.toHash(signatureType, data, detached); + hash = await this.hash(signatureType, data, toHash); + } + hash = await readToEnd(hash); + if (this.signedHashValue[0] !== hash[0] || + this.signedHashValue[1] !== hash[1]) { + throw new Error('Signed digest did not match'); + } + + this.params = await this.params; + + this[verified] = await mod$1.signature.verify( + this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, + toHash, hash + ); + + if (!this[verified]) { + throw new Error('Signature verification failed'); + } + } + + const normDate = util.normalizeDate(date); + if (normDate && this.created > normDate) { + throw new Error('Signature creation time is in the future'); + } + if (normDate && normDate >= this.getExpirationTime()) { + throw new Error('Signature is expired'); + } + if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { + throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && + [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { + throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + this.unknownSubpackets.forEach(({ type, critical }) => { + if (critical) { + throw new Error(`Unknown critical signature subpacket type ${type}`); + } + }); + this.rawNotations.forEach(({ name, critical }) => { + if (critical && (config$1.knownNotations.indexOf(name) < 0)) { + throw new Error(`Unknown critical notation: ${name}`); + } + }); + if (this.revocationKeyClass !== null) { + throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); + } + } + + /** + * Verifies signature expiration date + * @param {Date} [date] - Use the given date for verification instead of the current time + * @returns {Boolean} True if expired. + */ + isExpired(date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + return !(this.created <= normDate && normDate < this.getExpirationTime()); + } + return false; + } + + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns {Date | Infinity} Expiration time. + */ + getExpirationTime() { + return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); + } +} + +/** + * Creates a Uint8Array representation of a sub signature packet + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} + * @param {Integer} type - Subpacket signature type. + * @param {Boolean} critical - Whether the subpacket should be critical. + * @param {String} data - Data to be included + * @returns {Uint8Array} The signature subpacket. + * @private + */ +function writeSubPacket(type, critical, data) { + const arr = []; + arr.push(writeSimpleLength(data.length + 1)); + arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); + arr.push(data); + return util.concat(arr); +} + +/** + * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh. + * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5} + * @param {enums.hash} hashAlgorithm - Hash algorithm. + * @returns {Integer} Salt length. + * @private + */ +function saltLengthForHash(hashAlgorithm) { + switch (hashAlgorithm) { + case enums.hash.sha256: return 16; + case enums.hash.sha384: return 24; + case enums.hash.sha512: return 32; + case enums.hash.sha224: return 16; + case enums.hash.sha3_256: return 16; + case enums.hash.sha3_512: return 32; + default: throw new Error('Unsupported hash function'); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the One-Pass Signature Packets (Tag 4) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + */ +class OnePassSignaturePacket { + static get tag() { + return enums.packet.onePassSignature; + } + + static fromSignaturePacket(signaturePacket, isLast) { + const onePassSig = new OnePassSignaturePacket(); + onePassSig.version = signaturePacket.version === 6 ? 6 : 3; + onePassSig.signatureType = signaturePacket.signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; + onePassSig.salt = signaturePacket.salt; // v6 only + onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only + + onePassSig.flags = isLast ? 1 : 0; + return onePassSig; + } + + constructor() { + /** A one-octet version number. The current versions are 3 and 6. */ + this.version = null; + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + * @type {enums.signature} + + */ + this.signatureType = null; + /** + * A one-octet number describing the hash algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} + * @type {enums.hash} + */ + this.hashAlgorithm = null; + /** + * A one-octet number describing the public-key algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} + * @type {enums.publicKey} + */ + this.publicKeyAlgorithm = null; + /** Only for v6, a variable-length field containing the salt. */ + this.salt = null; + /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */ + this.issuerKeyID = null; + /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */ + this.issuerFingerprint = null; + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + this.flags = null; + } + + /** + * parsing function for a one-pass signature packet (tag 4). + * @param {Uint8Array} bytes - Payload of a tag 4 packet + * @returns {OnePassSignaturePacket} Object representation. + */ + read(bytes) { + let mypos = 0; + // A one-octet version number. The current versions are 3 or 6. + this.version = bytes[mypos++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); + } + + // A one-octet signature type. Signature types are described in + // Section 5.2.1. + this.signatureType = bytes[mypos++]; + + // A one-octet number describing the hash algorithm used. + this.hashAlgorithm = bytes[mypos++]; + + // A one-octet number describing the public-key algorithm used. + this.publicKeyAlgorithm = bytes[mypos++]; + + if (this.version === 6) { + // Only for v6 signatures, a variable-length field containing: + + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[mypos++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(mypos, mypos + saltLength); + mypos += saltLength; + + // Only for v6 packets, 32 octets of the fingerprint of the signing key. + this.issuerFingerprint = bytes.subarray(mypos, mypos + 32); + mypos += 32; + this.issuerKeyID = new KeyID(); + // For v6 the Key ID is the high-order 64 bits of the fingerprint. + this.issuerKeyID.read(this.issuerFingerprint); + } else { + // Only for v3 packets, an eight-octet number holding the Key ID of the signing key. + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); + mypos += 8; + } + + // A one-octet number holding a flag showing whether the signature + // is nested. A zero value indicates that the next packet is + // another One-Pass Signature packet that describes another + // signature to be applied to the same message data. + this.flags = bytes[mypos++]; + return this; + } + + /** + * creates a string representation of a one-pass signature packet + * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. + */ + write() { + const arr = [new Uint8Array([ + this.version, + this.signatureType, + this.hashAlgorithm, + this.publicKeyAlgorithm + ])]; + if (this.version === 6) { + arr.push( + new Uint8Array([this.salt.length]), + this.salt, + this.issuerFingerprint + ); + } else { + arr.push(this.issuerKeyID.write()); + } + arr.push(new Uint8Array([this.flags])); + return util.concatUint8Array(arr); + } + + calculateTrailer(...args) { + return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); + } + + async verify() { + const correspondingSig = await this.correspondingSig; + if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { + throw new Error('Corresponding signature packet missing'); + } + if ( + correspondingSig.signatureType !== this.signatureType || + correspondingSig.hashAlgorithm !== this.hashAlgorithm || + correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) || + (this.version === 3 && correspondingSig.version === 6) || + (this.version === 6 && correspondingSig.version !== 6) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt)) + ) { + throw new Error('Corresponding signature packet does not match one-pass signature packet'); + } + correspondingSig.hashed = this.hashed; + return correspondingSig.verify.apply(correspondingSig, arguments); + } +} + +OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; +OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; +OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; + +/** + * Instantiate a new packet given its tag + * @function newPacketFromTag + * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @returns {Object} New packet object with type based on tag + * @throws {Error|UnsupportedError} for disallowed or unknown packets + */ +function newPacketFromTag(tag, allowedPackets) { + if (!allowedPackets[tag]) { + // distinguish between disallowed packets and unknown ones + let packetType; + try { + packetType = enums.read(enums.packet, tag); + } catch (e) { + throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`); + } + throw new Error(`Packet not allowed in this context: ${packetType}`); + } + return new allowedPackets[tag](); +} + +/** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + * @extends Array + */ +class PacketList extends Array { + /** + * Parses the given binary data and returns a list of packets. + * Equivalent to calling `read` on an empty PacketList instance. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @returns {PacketList} parsed list of packets + * @throws on parsing errors + * @async + */ + static async fromBinary(bytes, allowedPackets, config$1 = config) { + const packets = new PacketList(); + await packets.read(bytes, allowedPackets, config$1); + return packets; + } + + /** + * Reads a stream of binary data and interprets it as a list of packets. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @throws on parsing errors + * @async + */ + async read(bytes, allowedPackets, config$1 = config) { + if (config$1.additionalAllowedPackets.length) { + allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; + } + this.stream = transformPair(bytes, async (readable, writable) => { + const writer = getWriter(writable); + try { + while (true) { + await writer.ready; + const done = await readPackets(readable, async parsed => { + try { + if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) { + // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: + // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 + // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 + // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21 + return; + } + const packet = newPacketFromTag(parsed.tag, allowedPackets); + packet.packets = new PacketList(); + packet.fromStream = util.isStream(parsed.packet); + await packet.read(parsed.packet, config$1); + await writer.write(packet); + } catch (e) { + // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence, + // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored. + // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical. + if (e instanceof UnknownPacketError) { + if (parsed.tag <= 39) { + await writer.abort(e); + } else { + return; + } + } + + const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; + const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); + if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { + // The packets that support streaming are the ones that contain message data. + // Those are also the ones we want to be more strict about and throw on parse errors + // (since we likely cannot process the message without these packets anyway). + await writer.abort(e); + } else { + const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); + await writer.write(unparsedPacket); + } + util.printDebugError(e); + } + }); + if (done) { + await writer.ready; + await writer.close(); + return; + } + } + } catch (e) { + await writer.abort(e); + } + }); + + // Wait until first few packets have been read + const reader = getReader(this.stream); + while (true) { + const { done, value } = await reader.read(); + if (!done) { + this.push(value); + } else { + this.stream = null; + } + if (done || supportsStreaming(value.constructor.tag)) { + break; + } + } + reader.releaseLock(); + } + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. + */ + write() { + const arr = []; + + for (let i = 0; i < this.length; i++) { + const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; + const packetbytes = this[i].write(); + if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { + let buffer = []; + let bufferLength = 0; + const minLength = 512; + arr.push(writeTag(tag)); + arr.push(transform(packetbytes, value => { + buffer.push(value); + bufferLength += value.length; + if (bufferLength >= minLength) { + const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); + const chunkSize = 2 ** powerOf2; + const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); + buffer = [bufferConcat.subarray(1 + chunkSize)]; + bufferLength = buffer[0].length; + return bufferConcat.subarray(0, 1 + chunkSize); + } + }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); + } else { + if (util.isStream(packetbytes)) { + let length = 0; + arr.push(transform(clone(packetbytes), value => { + length += value.length; + }, () => writeHeader(tag, length))); + } else { + arr.push(writeHeader(tag, packetbytes.length)); + } + arr.push(packetbytes); + } + } + + return util.concat(arr); + } + + /** + * Creates a new PacketList with all packets matching the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {PacketList} + */ + filterByTag(...tags) { + const filtered = new PacketList(); + + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(this[i].constructor.tag))) { + filtered.push(this[i]); + } + } + + return filtered; + } + + /** + * Traverses packet list and returns first packet with matching tag + * @param {module:enums.packet} tag - The packet tag + * @returns {Packet|undefined} + */ + findPacket(tag) { + return this.find(packet => packet.constructor.tag === tag); + } + + /** + * Find indices of packets with the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {Integer[]} packet indices + */ + indexOfTag(...tags) { + const tagIndex = []; + const that = this; + + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(that[i].constructor.tag))) { + tagIndex.push(i); + } + } + return tagIndex; + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Compressed Data packet can contain the following packet types +const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +/** + * Implementation of the Compressed Data Packet (Tag 8) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. + */ +class CompressedDataPacket { + static get tag() { + return enums.packet.compressedData; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + /** + * List of packets + * @type {PacketList} + */ + this.packets = null; + /** + * Compression algorithm + * @type {enums.compression} + */ + this.algorithm = config$1.preferredCompressionAlgorithm; + + /** + * Compressed packet data + * @type {Uint8Array | ReadableStream} + */ + this.compressed = null; + } + + /** + * Parsing function for the packet. + * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async read(bytes, config$1 = config) { + await parse(bytes, async reader => { + + // One octet that gives the algorithm used to compress the packet. + this.algorithm = await reader.readByte(); + + // Compressed data, which makes up the remainder of the packet. + this.compressed = reader.remainder(); + + await this.decompress(config$1); + }); + } + + + /** + * Return the compressed packet. + * @returns {Uint8Array | ReadableStream} Binary compressed packet. + */ + write() { + if (this.compressed === null) { + this.compress(); + } + + return util.concat([new Uint8Array([this.algorithm]), this.compressed]); + } + + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async decompress(config$1 = config) { + const compressionName = enums.read(enums.compression, this.algorithm); + const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async + if (!decompressionFn) { + throw new Error(`${compressionName} decompression not supported`); + } + + this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets$5, config$1); + } + + /** + * Compress the packet data (member decompressedData) + */ + compress() { + const compressionName = enums.read(enums.compression, this.algorithm); + const compressionFn = compress_fns[compressionName]; + if (!compressionFn) { + throw new Error(`${compressionName} compression not supported`); + } + + this.compressed = compressionFn(this.packets.write()); + } +} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + +/** + * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise. + * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator + * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor + * @returns {ReadableStream} compressed or decompressed data + */ +function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) { + return data => { + if (!util.isStream(data) || isArrayStream(data)) { + return fromAsync(() => readToEnd(data).then(inputData => { + return new Promise((resolve, reject) => { + const zlibStream = new ZlibStreamedConstructor(); + zlibStream.ondata = processedData => { + resolve(processedData); + }; + try { + zlibStream.push(inputData, true); // only one chunk to push + } catch (err) { + reject(err); + } + }); + })); + } + + // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) + if (compressionStreamInstantiator) { + try { + const compressorOrDecompressor = compressionStreamInstantiator(); + return data.pipeThrough(compressorOrDecompressor); + } catch (err) { + // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate. + if (err.name !== 'TypeError') { + throw err; + } + } + } + + // JS fallback + const inputReader = data.getReader(); + const zlibStream = new ZlibStreamedConstructor(); + + return new ReadableStream({ + async start(controller) { + zlibStream.ondata = async (value, isLast) => { + controller.enqueue(value); + if (isLast) { + controller.close(); + } + }; + + while (true) { + const { done, value } = await inputReader.read(); + if (done) { + zlibStream.push(new Uint8Array(), true); + return; + } else if (value.length) { + zlibStream.push(value); + } + } + } + }); + }; +} + +function bzip2Decompress() { + return async function(data) { + const { decode: bunzipDecode } = await Promise.resolve().then(function () { return index; }); + return fromAsync(async () => bunzipDecode(await readToEnd(data))); + }; +} + +/** + * Get Compression Stream API instatiators if the constructors are implemented. + * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported + * (supported formats cannot be determined in advance). + * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat + * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }} + */ +const getCompressionStreamInstantiators = compressionFormat => ({ + compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)), + decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat)) +}); + +const compress_fns = { + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib) +}; + +const decompress_fns = { + uncompressed: data => data, + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib), + bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import +}; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A SEIP packet can contain the following packet types +const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +/** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ +class SymEncryptedIntegrityProtectedDataPacket { + static get tag() { + return enums.packet.symEncryptedIntegrityProtectedData; + } + + static fromObject({ version, aeadAlgorithm }) { + if (version !== 1 && version !== 2) { + throw new Error('Unsupported SEIPD version'); + } + + const seip = new SymEncryptedIntegrityProtectedDataPacket(); + seip.version = version; + if (version === 2) { + seip.aeadAlgorithm = aeadAlgorithm; + } + + return seip; + } + + constructor() { + this.version = null; + + // The following 4 fields are for V2 only. + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = null; + this.chunkSizeByte = null; + this.salt = null; + + this.encrypted = null; + this.packets = null; + } + + async read(bytes) { + await parse(bytes, async reader => { + this.version = await reader.readByte(); + // - A one-octet version number with value 1 or 2. + if (this.version !== 1 && this.version !== 2) { + throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`); + } + + if (this.version === 2) { + // - A one-octet cipher algorithm. + this.cipherAlgorithm = await reader.readByte(); + // - A one-octet AEAD algorithm. + this.aeadAlgorithm = await reader.readByte(); + // - A one-octet chunk size. + this.chunkSizeByte = await reader.readByte(); + // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique. + this.salt = await reader.readBytes(32); + } + + // For V1: + // - Encrypted data, the output of the selected symmetric-key cipher + // operating in Cipher Feedback mode with shift amount equal to the + // block size of the cipher (CFB-n where n is the block size). + // For V2: + // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode. + // - A final, summary authentication tag for the AEAD mode. + this.encrypted = reader.remainder(); + }); + } + + write() { + if (this.version === 2) { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]); + } + return util.concat([new Uint8Array([this.version]), this.encrypted]); + } + + /** + * Encrypt the payload in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on encryption failure + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + const { blockSize, keySize } = mod$1.getCipherParams(sessionKeyAlgorithm); + if (key.length !== keySize) { + throw new Error('Unexpected session key size'); + } + + let bytes = this.packets.write(); + if (isArrayStream(bytes)) bytes = await readToEnd(bytes); + + if (this.version === 2) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + this.salt = mod$1.random.getRandomBytes(32); + this.chunkSizeByte = config$1.aeadChunkSizeByte; + this.encrypted = await runAEAD(this, 'encrypt', key, bytes); + } else { + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet + + const tohash = util.concat([prefix, bytes, mdc]); + const hash = await mod$1.hash.sha1(passiveClone(tohash)); + const plaintext = util.concat([tohash, hash]); + + this.encrypted = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); + } + return true; + } + + /** + * Decrypts the encrypted data contained in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on decryption failure + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + if (key.length !== mod$1.getCipherParams(sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + + let encrypted = clone(this.encrypted); + if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); + + let packetbytes; + if (this.version === 2) { + if (this.cipherAlgorithm !== sessionKeyAlgorithm) { + // sanity check + throw new Error('Unexpected session key algorithm'); + } + packetbytes = await runAEAD(this, 'decrypt', key, encrypted); + } else { + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); + + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + const realHash = slice(passiveClone(decrypted), -20); + const tohash = slice(decrypted, 0, -20); + const verifyHash = Promise.all([ + readToEnd(await mod$1.hash.sha1(passiveClone(tohash))), + readToEnd(realHash) + ]).then(([hash, mdc]) => { + if (!util.equalsUint8Array(hash, mdc)) { + throw new Error('Modification detected.'); + } + return new Uint8Array(); + }); + const bytes = slice(tohash, blockSize + 2); // Remove random prefix + packetbytes = slice(bytes, 0, -2); // Remove MDC packet + packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); + if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { + packetbytes = await readToEnd(packetbytes); + } + } + + this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1); + return true; + } +} + +/** + * En/decrypt the payload. + * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt + * @param {Uint8Array} key - The session key used to en/decrypt the payload + * @param {Uint8Array | ReadableStream} data - The data to en/decrypt + * @returns {Promise>} + * @async + */ +async function runAEAD(packet, fn, key, data) { + const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2; + const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import) + if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type'); + + const mode = mod$1.getAEADMode(packet.aeadAlgorithm); + const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; + const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; + const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) + const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0; + const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP); + const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP); + const adataTagArray = new Uint8Array(adataBuffer); + const adataView = new DataView(adataBuffer); + const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); + adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0); + let chunkIndex = 0; + let latestPromise = Promise.resolve(); + let cryptedBytes = 0; + let queuedBytes = 0; + let iv; + let ivView; + if (isSEIPDv2) { + const { keySize } = mod$1.getCipherParams(packet.cipherAlgorithm); + const { ivLength } = mode; + const info = new Uint8Array(adataBuffer, 0, 5); + const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength); + key = derived.subarray(0, keySize); + iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. + iv.fill(0, iv.length - 8); + ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + } else { // AEADEncryptedDataPacket + iv = packet.iv; + // ivView is unused in this case + } + const modeInstance = await mode(packet.cipherAlgorithm, key); + return transformPair(data, async (readable, writable) => { + if (util.isStream(readable) !== 'array') { + const buffer = new TransformStream({}, { + highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6), + size: array => array.length + }); + pipe(buffer.readable, writable); + writable = buffer.writable; + } + const reader = getReader(readable); + const writer = getWriter(writable); + try { + while (true) { + let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); + const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); + chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); + let cryptedPromise; + let done; + let nonce; + if (isSEIPDv2) { // SEIPD V2 + nonce = iv; + } else { // AEADEncryptedDataPacket + nonce = iv.slice(); + for (let i = 0; i < 8; i++) { + nonce[iv.length - 8 + i] ^= chunkIndexArray[i]; + } + } + if (!chunkIndex || chunk.length) { + reader.unshift(finalChunk); + cryptedPromise = modeInstance[fn](chunk, nonce, adataArray); + cryptedPromise.catch(() => {}); + queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; + } else { + // After the last chunk, we either encrypt a final, empty + // data chunk to get the final authentication tag or + // validate that final authentication tag. + adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...) + cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray); + cryptedPromise.catch(() => {}); + queuedBytes += tagLengthIfEncrypting; + done = true; + } + cryptedBytes += chunk.length - tagLengthIfDecrypting; + // eslint-disable-next-line @typescript-eslint/no-loop-func + latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { + await writer.ready; + await writer.write(crypted); + queuedBytes -= crypted.length; + }).catch(err => writer.abort(err)); + if (done || queuedBytes > writer.desiredSize) { + await latestPromise; // Respect backpressure + } + if (!done) { + if (isSEIPDv2) { // SEIPD V2 + ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...) + } else { // AEADEncryptedDataPacket + adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) + } + } else { + await writer.close(); + break; + } + } + } catch (e) { + await writer.ready.catch(() => {}); + await writer.abort(e); + } + }); +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// An AEAD-encrypted Data packet can contain the following packet types +const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +const VERSION$1 = 1; // A one-octet version number of the data packet. + +/** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ +class AEADEncryptedDataPacket { + static get tag() { + return enums.packet.aeadEncryptedData; + } + + constructor() { + this.version = VERSION$1; + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = enums.aead.eax; + this.chunkSizeByte = null; + this.iv = null; + this.encrypted = null; + this.packets = null; + } + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param {Uint8Array | ReadableStream} bytes + * @throws {Error} on parsing failure + */ + async read(bytes) { + await parse(bytes, async reader => { + const version = await reader.readByte(); + if (version !== VERSION$1) { // The only currently defined value is 1. + throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); + } + this.cipherAlgorithm = await reader.readByte(); + this.aeadAlgorithm = await reader.readByte(); + this.chunkSizeByte = await reader.readByte(); + + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = await reader.readBytes(mode.ivLength); + this.encrypted = reader.remainder(); + }); + } + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns {Uint8Array | ReadableStream} The encrypted payload. + */ + write() { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); + } + + /** + * Decrypt the encrypted payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.packets = await PacketList.fromBinary( + await runAEAD(this, 'decrypt', key, clone(this.encrypted)), + allowedPackets$3, + config$1 + ); + } + + /** + * Encrypt the packet payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + const { ivLength } = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(ivLength); // generate new random IV + this.chunkSizeByte = config$1.aeadChunkSizeByte; + const data = this.packets.write(); + this.encrypted = await runAEAD(this, 'encrypt', key, data); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Public-Key Encrypted Session Key Packets (Tag 1) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ +class PublicKeyEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.publicKeyEncryptedSessionKey; + } + + constructor() { + this.version = null; + + // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()` + this.publicKeyID = new KeyID(); + + // For version 6: + this.publicKeyVersion = null; + this.publicKeyFingerprint = null; + + // For all versions: + this.publicKeyAlgorithm = null; + + this.sessionKey = null; + /** + * Algorithm to encrypt the message with + * @type {enums.symmetric} + */ + this.sessionKeyAlgorithm = null; + + /** @type {Object} */ + this.encrypted = {}; + } + + static fromObject({ + version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm + }) { + const pkesk = new PublicKeyEncryptedSessionKeyPacket(); + + if (version !== 3 && version !== 6) { + throw new Error('Unsupported PKESK version'); + } + + pkesk.version = version; + + if (version === 6) { + pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version; + pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes(); + } + + pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID(); + pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkesk.sessionKey = sessionKey; + pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm; + + return pkesk; + } + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * + * @param {Uint8Array} bytes - Payload of a tag 1 packet + */ + read(bytes) { + let offset = 0; + this.version = bytes[offset++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); + } + if (this.version === 6) { + // A one-octet size of the following two fields: + // - A one octet key version number. + // - The fingerprint of the public key or subkey to which the session key is encrypted. + // The size may also be zero. + const versionAndFingerprintLength = bytes[offset++]; + if (versionAndFingerprintLength) { + this.publicKeyVersion = bytes[offset++]; + const fingerprintLength = versionAndFingerprintLength - 1; + this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength; + if (this.publicKeyVersion >= 5) { + // For v5/6 the Key ID is the high-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint); + } else { + // For v4 The Key ID is the low-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8)); + } + } else { + // The size may also be zero, and the key version and + // fingerprint omitted for an "anonymous recipient" + this.publicKeyID = KeyID.wildcard(); + } + } else { + offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8)); + } + this.publicKeyAlgorithm = bytes[offset++]; + this.encrypted = mod$1.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset)); + if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) { + if (this.version === 3) { + this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + } else if (this.encrypted.C.algorithm !== null) { + throw new Error('Unexpected cleartext symmetric algorithm'); + } + } + } + + /** + * Create a binary representation of a tag 1 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const arr = [ + new Uint8Array([this.version]) + ]; + + if (this.version === 6) { + if (this.publicKeyFingerprint !== null) { + arr.push(new Uint8Array([ + this.publicKeyFingerprint.length + 1, + this.publicKeyVersion] + )); + arr.push(this.publicKeyFingerprint); + } else { + arr.push(new Uint8Array([0])); + } + } else { + arr.push(this.publicKeyID.write()); + } + + arr.push( + new Uint8Array([this.publicKeyAlgorithm]), + mod$1.serializeParams(this.publicKeyAlgorithm, this.encrypted) + ); + + return util.concatUint8Array(arr); + } + + /** + * Encrypt session key packet + * @param {PublicKeyPacket} key - Public key + * @throws {Error} if encryption failed + * @async + */ + async encrypt(key) { + const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); + // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a + // v6 PKESK packet, as it is included in the v2 SEIPD packet. + const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey); + this.encrypted = await mod$1.publicKeyEncrypt( + algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint); + } + + /** + * Decrypts the session key (only for public key encrypted session key packets (tag 1) + * @param {SecretKeyPacket} key - decrypted private key + * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. + * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } + * @throws {Error} if decryption failed, unless `randomSessionKey` is given + * @async + */ + async decrypt(key, randomSessionKey) { + // check that session key algo matches the secret key algo + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Decryption error'); + } + + const randomPayload = randomSessionKey ? + encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : + null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const decryptedData = await mod$1.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload); + + const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); + + if (this.version === 3) { + // v3 Montgomery curves have cleartext cipher algo + const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448; + this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm; + + if (sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + } + this.sessionKey = sessionKey; + } +} + + +function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + // add checksum + return util.concatUint8Array([ + new Uint8Array(version === 6 ? [] : [cipherAlgo]), + sessionKeyData, + util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) + ]); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return sessionKeyData; + default: + throw new Error('Unsupported public key algorithm'); + } +} + + +function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: { + // verify checksum in constant time + const result = decryptedData.subarray(0, decryptedData.length - 2); + const checksum = decryptedData.subarray(decryptedData.length - 2); + const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); + const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; + const decryptedSessionKey = version === 6 ? + { sessionKeyAlgorithm: null, sessionKey: result } : + { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; + if (randomSessionKey) { + // We must not leak info about the validity of the decrypted checksum or cipher algo. + // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. + const isValidPayload = isValidChecksum & + decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & + decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; + return { + sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), + sessionKeyAlgorithm: version === 6 ? null : util.selectUint8( + isValidPayload, + decryptedSessionKey.sessionKeyAlgorithm, + randomSessionKey.sessionKeyAlgorithm + ) + }; + } else { + const isValidPayload = isValidChecksum && ( + version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm)); + if (isValidPayload) { + return decryptedSessionKey; + } else { + throw new Error('Decryption error'); + } + } + } + case enums.publicKey.x25519: + case enums.publicKey.x448: + return { + sessionKeyAlgorithm: null, + sessionKey: decryptedData + }; + default: + throw new Error('Unsupported public key algorithm'); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Symmetric-Key Encrypted Session Key Packets (Tag 3) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: + * The Symmetric-Key Encrypted Session Key packet holds the + * symmetric-key encryption of a session key used to encrypt a message. + * Zero or more Public-Key Encrypted Session Key packets and/or + * Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data packet that holds an encrypted message. + * The message is encrypted with a session key, and the session key is + * itself encrypted and stored in the Encrypted Session Key packet or + * the Symmetric-Key Encrypted Session Key packet. + */ +class SymEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.symEncryptedSessionKey; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + this.version = config$1.aeadProtect ? 6 : 4; + this.sessionKey = null; + /** + * Algorithm to encrypt the session key with + * @type {enums.symmetric} + */ + this.sessionKeyEncryptionAlgorithm = null; + /** + * Algorithm to encrypt the message with + * @type {enums.symmetric} + */ + this.sessionKeyAlgorithm = null; + /** + * AEAD mode to encrypt the session key with (if AEAD protection is enabled) + * @type {enums.aead} + */ + this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); + this.encrypted = null; + this.s2k = null; + this.iv = null; + } + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * + * @param {Uint8Array} bytes - Payload of a tag 3 packet + */ + read(bytes) { + let offset = 0; + + // A one-octet version number with value 4, 5 or 6. + this.version = bytes[offset++]; + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); + } + + if (this.version === 6) { + // A one-octet scalar octet count of the following 5 fields. + offset++; + } + + // A one-octet number describing the symmetric algorithm used. + const algo = bytes[offset++]; + + if (this.version >= 5) { + // A one-octet AEAD algorithm. + this.aeadAlgorithm = bytes[offset++]; + + if (this.version === 6) { + // A one-octet scalar octet count of the following field. + offset++; + } + } + + // A string-to-key (S2K) specifier, length as defined above. + const s2kType = bytes[offset++]; + this.s2k = newS2KFromType(s2kType); + offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + + // A starting initialization vector of size specified by the AEAD + // algorithm. + this.iv = bytes.subarray(offset, offset += mode.ivLength); + } + + // The encrypted session key itself, which is decrypted with the + // string-to-key object. This is optional in version 4. + if (this.version >= 5 || offset < bytes.length) { + this.encrypted = bytes.subarray(offset, bytes.length); + this.sessionKeyEncryptionAlgorithm = algo; + } else { + this.sessionKeyAlgorithm = algo; + } + } + + /** + * Create a binary representation of a tag 3 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const algo = this.encrypted === null ? + this.sessionKeyAlgorithm : + this.sessionKeyEncryptionAlgorithm; + + let bytes; + + const s2k = this.s2k.write(); + if (this.version === 6) { + const s2kLen = s2k.length; + const fieldsLen = 3 + s2kLen + this.iv.length; + bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]); + } else if (this.version === 5) { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]); + } else { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]); + + if (this.encrypted !== null) { + bytes = util.concatUint8Array([bytes, this.encrypted]); + } + } + + return bytes; + } + + /** + * Decrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(passphrase) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); + } else if (this.encrypted !== null) { + const decrypted = await mod$1.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + + this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); + this.sessionKey = decrypted.subarray(1, decrypted.length); + if (this.sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + } else { + // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo + this.sessionKey = key; + } + } + + /** + * Encrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + this.sessionKeyEncryptionAlgorithm = algo; + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.sessionKey === null) { + this.sessionKey = mod$1.generateSessionKey(this.sessionKeyAlgorithm); + } + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(mode.ivLength); // generate new random IV + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); + } else { + const toEncrypt = util.concatUint8Array([ + new Uint8Array([this.sessionKeyAlgorithm]), + this.sessionKey + ]); + this.encrypted = await mod$1.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config$1); + } + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ +class PublicKeyPacket { + static get tag() { + return enums.packet.publicKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + /** + * Packet version + * @type {Integer} + */ + this.version = config$1.v6Keys ? 6 : 4; + /** + * Key creation date. + * @type {Date} + */ + this.created = util.normalizeDate(date); + /** + * Public key algorithm. + * @type {enums.publicKey} + */ + this.algorithm = null; + /** + * Algorithm specific public params + * @type {Object} + */ + this.publicParams = null; + /** + * Time until expiration in days (V3 only) + * @type {Integer} + */ + this.expirationTimeV3 = 0; + /** + * Fingerprint bytes + * @type {Uint8Array} + */ + this.fingerprint = null; + /** + * KeyID + * @type {module:type/keyid~KeyID} + */ + this.keyID = null; + } + + /** + * Create a PublicKeyPacket from a SecretKeyPacket + * @param {SecretKeyPacket} secretKeyPacket - key packet to convert + * @returns {PublicKeyPacket} public key packet + * @static + */ + static fromSecretKeyPacket(secretKeyPacket) { + const keyPacket = new PublicKeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * @param {Uint8Array} bytes - Input array to read the packet from + * @returns {Object} This object with attributes set by the parser + * @async + */ + async read(bytes, config$1 = config) { + let pos = 0; + // A one-octet version number (4, 5 or 6). + this.version = bytes[pos++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } + + if (this.version === 4 || this.version === 5 || this.version === 6) { + // - A four-octet number denoting the time that the key was created. + this.created = util.readDate(bytes.subarray(pos, pos + 4)); + pos += 4; + + // - A one-octet number denoting the public-key algorithm of this key. + this.algorithm = bytes[pos++]; + + if (this.version >= 5) { + // - A four-octet scalar octet count for the following key material. + pos += 4; + } + + // - A series of values comprising the key material. + const { read, publicParams } = mod$1.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if ( + this.version === 6 && + publicParams.oid && ( + publicParams.oid.getName() === enums.curve.curve25519Legacy || + publicParams.oid.getName() === enums.curve.ed25519Legacy + ) + ) { + throw new Error('Legacy curve25519 cannot be used with v6 keys'); + } + this.publicParams = publicParams; + pos += read; + + // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor + await this.computeFingerprintAndKeyID(); + return pos; + } + throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); + } + + /** + * Creates an OpenPGP public key packet for the given key. + * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. + */ + write() { + const arr = []; + // Version + arr.push(new Uint8Array([this.version])); + arr.push(util.writeDate(this.created)); + // A one-octet number denoting the public-key algorithm of this key + arr.push(new Uint8Array([this.algorithm])); + + const params = mod$1.serializeParams(this.algorithm, this.publicParams); + if (this.version >= 5) { + // A four-octet scalar octet count for the following key material + arr.push(util.writeNumber(params.length, 4)); + } + // Algorithm-specific params + arr.push(params); + return util.concatUint8Array(arr); + } + + /** + * Write packet in order to be hashed; either for a signature or a fingerprint + * @param {Integer} version - target version of signature or key + */ + writeForHash(version) { + const bytes = this.writePublicKey(); + + const versionOctet = 0x95 + version; + const lengthOctets = version >= 5 ? 4 : 2; + return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]); + } + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return null; + } + + /** + * Returns the creation time of the key + * @returns {Date} + */ + getCreationTime() { + return this.created; + } + + /** + * Return the key ID of the key + * @returns {module:type/keyid~KeyID} The 8-byte key ID + */ + getKeyID() { + return this.keyID; + } + + /** + * Computes and set the key ID and fingerprint of the key + * @async + */ + async computeFingerprintAndKeyID() { + await this.computeFingerprint(); + this.keyID = new KeyID(); + + if (this.version >= 5) { + this.keyID.read(this.fingerprint.subarray(0, 8)); + } else if (this.version === 4) { + this.keyID.read(this.fingerprint.subarray(12, 20)); + } else { + throw new Error('Unsupported key version'); + } + } + + /** + * Computes and set the fingerprint of the key + */ + async computeFingerprint() { + const toHash = this.writeForHash(this.version); + + if (this.version >= 5) { + this.fingerprint = await mod$1.hash.sha256(toHash); + } else if (this.version === 4) { + this.fingerprint = await mod$1.hash.sha1(toHash); + } else { + throw new Error('Unsupported key version'); + } + } + + /** + * Returns the fingerprint of the key, as an array of bytes + * @returns {Uint8Array} A Uint8Array containing the fingerprint + */ + getFingerprintBytes() { + return this.fingerprint; + } + + /** + * Calculates and returns the fingerprint of the key, as a string + * @returns {String} A string containing the fingerprint in lowercase hex + */ + getFingerprint() { + return util.uint8ArrayToHex(this.getFingerprintBytes()); + } + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns {Boolean} Whether the two keys have the same version and public key data. + */ + hasSameFingerprintAs(other) { + return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); + } + + /** + * Returns algorithm information + * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. + */ + getAlgorithmInfo() { + const result = {}; + result.algorithm = enums.read(enums.publicKey, this.algorithm); + // RSA, DSA or ElGamal public modulo + const modulo = this.publicParams.n || this.publicParams.p; + if (modulo) { + result.bits = util.uint8ArrayBitLength(modulo); + } else if (this.publicParams.oid) { + result.curve = this.publicParams.oid.getName(); + } + return result; + } +} + +/** + * Alias of read() + * @see PublicKeyPacket#read + */ +PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; + +/** + * Alias of write() + * @see PublicKeyPacket#write + */ +PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A SE packet can contain the following packet types +const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +/** + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ +class SymmetricallyEncryptedDataPacket { + static get tag() { + return enums.packet.symmetricallyEncryptedData; + } + + constructor() { + /** + * Encrypted secret-key data + */ + this.encrypted = null; + /** + * Decrypted packets contained within. + * @type {PacketList} + */ + this.packets = null; + } + + read(bytes) { + this.encrypted = bytes; + } + + write() { + return this.encrypted; + } + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error + if (!config$1.allowUnauthenticatedMessages) { + throw new Error('Message is not authenticated.'); + } + + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const encrypted = await readToEnd(clone(this.encrypted)); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, + encrypted.subarray(blockSize + 2), + encrypted.subarray(2, blockSize + 2) + ); + + this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1); + } + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + const data = this.packets.write(); + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const FRE = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); + const ciphertext = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); + this.encrypted = util.concat([FRE, ciphertext]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the strange "Marker packet" (Tag 10) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * + * The body of this packet consists of: + * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + * + * Such a packet MUST be ignored when received. It may be placed at the + * beginning of a message that uses features not available in PGP + * version 2.6 in order to cause that version to report that newer + * software is necessary to process the message. + */ +class MarkerPacket { + static get tag() { + return enums.packet.marker; + } + + /** + * Parsing function for a marker data packet (tag 10). + * @param {Uint8Array} bytes - Payload of a tag 10 packet + * @returns {Boolean} whether the packet payload contains "PGP" + */ + read(bytes) { + if (bytes[0] === 0x50 && // P + bytes[1] === 0x47 && // G + bytes[2] === 0x50) { // P + return true; + } + return false; + } + + write() { + return new Uint8Array([0x50, 0x47, 0x50]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + * @extends PublicKeyPacket + */ +class PublicSubkeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.publicSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(date, config) { + super(date, config); + } + + /** + * Create a PublicSubkeyPacket from a SecretSubkeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert + * @returns {SecretSubkeyPacket} public key packet + * @static + */ + static fromSecretSubkeyPacket(secretSubkeyPacket) { + const keyPacket = new PublicSubkeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the User Attribute Packet (Tag 17) + * + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ +class UserAttributePacket { + static get tag() { + return enums.packet.userAttribute; + } + + constructor() { + this.attributes = []; + } + + /** + * parsing function for a user attribute packet (tag 17). + * @param {Uint8Array} input - Payload of a tag 17 packet + */ + read(bytes) { + let i = 0; + while (i < bytes.length) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); + i += len.len; + } + } + + /** + * Creates a binary representation of the user attribute packet + * @returns {Uint8Array} String representation. + */ + write() { + const arr = []; + for (let i = 0; i < this.attributes.length; i++) { + arr.push(writeSimpleLength(this.attributes[i].length)); + arr.push(util.stringToUint8Array(this.attributes[i])); + } + return util.concatUint8Array(arr); + } + + /** + * Compare for equality + * @param {UserAttributePacket} usrAttr + * @returns {Boolean} True if equal. + */ + equals(usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { + return false; + } + return this.attributes.every(function(attr, index) { + return attr === usrAttr.attributes[index]; + }); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + * @extends PublicKeyPacket + */ +class SecretKeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.secretKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); + /** + * Secret-key data + */ + this.keyMaterial = null; + /** + * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + this.isEncrypted = null; + /** + * S2K usage + * @type {enums.symmetric} + */ + this.s2kUsage = 0; + /** + * S2K object + * @type {type/s2k} + */ + this.s2k = null; + /** + * Symmetric algorithm to encrypt the key with + * @type {enums.symmetric} + */ + this.symmetric = null; + /** + * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) + * @type {enums.aead} + */ + this.aead = null; + /** + * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis + * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older). + * This value is only relevant to know how to decrypt the key: + * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism. + * @type {Boolean} + * @private + */ + this.isLegacyAEAD = null; + /** + * Decrypted private parameters, referenced by name + * @type {Object} + */ + this.privateParams = null; + /** + * `true` for keys whose integrity is already confirmed, based on + * the AEAD encryption mechanism + * @type {Boolean} + * @private + */ + this.usedModernAEAD = null; + } + + // 5.5.3. Secret-Key Packet Formats + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param {Uint8Array} bytes - Input string to read the packet from + * @async + */ + async read(bytes, config$1 = config) { + // - A Public-Key or Public-Subkey packet, as described above. + let i = await this.readPublicKey(bytes, config$1); + const startOfSecretKeyData = i; + + // - One octet indicating string-to-key usage conventions. Zero + // indicates that the secret-key data is not encrypted. 255 or 254 + // indicates that a string-to-key specifier is being given. Any + // other value is a symmetric-key encryption algorithm identifier. + this.s2kUsage = bytes[i++]; + + // - Only for a version 5 packet, a one-octet scalar octet count of + // the next 4 optional fields. + if (this.version === 5) { + i++; + } + + // - Only for a version 6 packet where the secret key material is + // encrypted (that is, where the previous octet is not zero), a one- + // octet scalar octet count of the cumulative length of all the + // following optional string-to-key parameter fields. + if (this.version === 6 && this.s2kUsage) { + i++; + } + + try { + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one-octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + this.symmetric = bytes[i++]; + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + this.aead = bytes[i++]; + } + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + i++; + } + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + const s2kType = bytes[i++]; + this.s2k = newS2KFromType(s2kType); + i += this.s2k.read(bytes.subarray(i, bytes.length)); + + if (this.s2k.type === 'gnu-dummy') { + return; + } + } else if (this.s2kUsage) { + this.symmetric = this.s2kUsage; + } + + + if (this.s2kUsage) { + // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5). + // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format). + // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always + // fail if the key was parsed according to the wrong format, since the keys are processed differently. + // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag. + this.isLegacyAEAD = this.s2kUsage === 253 && ( + this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy)); + // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV) + // of the same length as the cipher's block size. + // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the + // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm. + // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero + if (this.s2kUsage !== 253 || this.isLegacyAEAD) { + this.iv = bytes.subarray( + i, + i + mod$1.getCipherParams(this.symmetric).blockSize + ); + this.usedModernAEAD = false; + } else { + // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted), + // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which + // is used as the nonce for the AEAD algorithm. + this.iv = bytes.subarray( + i, + i + mod$1.getAEADMode(this.aead).ivLength + ); + // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation. + this.usedModernAEAD = true; + } + + i += this.iv.length; + } + } catch (e) { + // if the s2k is unsupported, we still want to support encrypting and verifying with the given key + if (!this.s2kUsage) throw e; // always throw for decrypted keys + this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); + this.isEncrypted = true; + } + + // - Only for a version 5 packet, a four-octet scalar octet count for + // the following key material. + if (this.version === 5) { + i += 4; + } + + // - Plain or encrypted multiprecision integers comprising the secret + // key data. These algorithm-specific fields are as described + // below. + this.keyMaterial = bytes.subarray(i); + this.isEncrypted = !!this.s2kUsage; + + if (!this.isEncrypted) { + let cleartext; + if (this.version === 6) { + cleartext = this.keyMaterial; + } else { + cleartext = this.keyMaterial.subarray(0, -2); + if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { + throw new Error('Key checksum mismatch'); + } + } + try { + const { read, privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + if (read < cleartext.length) { + throw new Error('Error reading MPIs'); + } + this.privateParams = privateParams; + } catch (err) { + if (err instanceof UnsupportedError) throw err; + // avoid throwing potentially sensitive errors + throw new Error('Error reading MPIs'); + } + } + } + + /** + * Creates an OpenPGP key packet for the given key. + * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. + */ + write() { + const serializedPublicKey = this.writePublicKey(); + if (this.unparseableKeyMaterial) { + return util.concatUint8Array([ + serializedPublicKey, + this.unparseableKeyMaterial + ]); + } + + const arr = [serializedPublicKey]; + arr.push(new Uint8Array([this.s2kUsage])); + + const optionalFieldsArr = []; + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one- octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + optionalFieldsArr.push(this.symmetric); + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + optionalFieldsArr.push(this.aead); + } + + const s2k = this.s2k.write(); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + optionalFieldsArr.push(s2k.length); + } + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + optionalFieldsArr.push(...s2k); + } + + // - [Optional] If secret data is encrypted (string-to-key usage octet + // not zero), an Initial Vector (IV) of the same length as the + // cipher's block size. + if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { + optionalFieldsArr.push(...this.iv); + } + + if (this.version === 5 || (this.version === 6 && this.s2kUsage)) { + arr.push(new Uint8Array([optionalFieldsArr.length])); + } + arr.push(new Uint8Array(optionalFieldsArr)); + + if (!this.isDummy()) { + if (!this.s2kUsage) { + this.keyMaterial = mod$1.serializeParams(this.algorithm, this.privateParams); + } + + if (this.version === 5) { + arr.push(util.writeNumber(this.keyMaterial.length, 4)); + } + arr.push(this.keyMaterial); + + if (!this.s2kUsage && this.version !== 6) { + arr.push(util.writeChecksum(this.keyMaterial)); + } + } + + return util.concatUint8Array(arr); + } + + /** + * Check whether secret-key data is available in decrypted form. + * Returns false for gnu-dummy keys and null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return this.isEncrypted === false; + } + + /** + * Check whether the key includes secret key material. + * Some secret keys do not include it, and can thus only be used + * for public-key operations (encryption and verification). + * Such keys are: + * - GNU-dummy keys, where the secret material has been stripped away + * - encrypted keys with unsupported S2K or cipher + */ + isMissingSecretKeyMaterial() { + return this.unparseableKeyMaterial !== undefined || this.isDummy(); + } + + /** + * Check whether this is a gnu-dummy key + * @returns {Boolean} + */ + isDummy() { + return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + } + + /** + * Remove private key material, converting the key to a dummy one. + * The resulting key cannot be used for signing/decrypting but can still verify signatures. + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + makeDummy(config$1 = config) { + if (this.isDummy()) { + return; + } + if (this.isDecrypted()) { + this.clearPrivateParams(); + } + delete this.unparseableKeyMaterial; + this.isEncrypted = null; + this.keyMaterial = null; + this.s2k = newS2KFromType(enums.s2k.gnu, config$1); + this.s2k.algorithm = 0; + this.s2k.c = 0; + this.s2k.type = 'gnu-dummy'; + this.s2kUsage = 254; + this.symmetric = enums.symmetric.aes256; + this.isLegacyAEAD = null; + this.usedModernAEAD = null; + } + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param {String} passphrase + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + if (this.isDummy()) { + return; + } + + if (!this.isDecrypted()) { + throw new Error('Key packet is already encrypted'); + } + + if (!passphrase) { + throw new Error('A non-empty passphrase is required for key encryption.'); + } + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + const cleartext = mod$1.serializeParams(this.algorithm, this.privateParams); + this.symmetric = enums.symmetric.aes256; + + const { blockSize } = mod$1.getCipherParams(this.symmetric); + + if (config$1.aeadProtect) { + this.s2kUsage = 253; + this.aead = config$1.preferredAEADAlgorithm; + const mode = mod$1.getAEADMode(this.aead); + this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead. + this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material + + const serializedPacketTag = writeTag(this.constructor.tag); + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + + const modeInstance = await mode(this.symmetric, key); + this.iv = this.isLegacyAEAD ? mod$1.random.getRandomBytes(blockSize) : mod$1.random.getRandomBytes(mode.ivLength); + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + + this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData); + } else { + this.s2kUsage = 254; + this.usedModernAEAD = false; + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric); + this.iv = mod$1.random.getRandomBytes(blockSize); + this.keyMaterial = await mod$1.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + cleartext, + await mod$1.hash.sha1(cleartext, config$1) + ]), this.iv, config$1); + } + } + + /** + * Decrypts the private key params which are needed to use the key. + * Successful decryption does not imply key integrity, call validate() to confirm that. + * {@link SecretKeyPacket.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param {String} passphrase - The passphrase for this private key as string + * @throws {Error} if the key is already decrypted, or if decryption was not successful + * @async + */ + async decrypt(passphrase) { + if (this.isDummy()) { + return false; + } + + if (this.unparseableKeyMaterial) { + throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); + } + + if (this.isDecrypted()) { + throw new Error('Key packet is already decrypted.'); + } + + let key; + const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only + if (this.s2kUsage === 254 || this.s2kUsage === 253) { + key = await produceEncryptionKey( + this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + } else if (this.s2kUsage === 255) { + throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); + } else { + throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); + } + + let cleartext; + if (this.s2kUsage === 253) { + const mode = mod$1.getAEADMode(this.aead); + const modeInstance = await mode(this.symmetric, key); + try { + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData); + } catch (err) { + if (err.message === 'Authentication tag mismatch') { + throw new Error('Incorrect key passphrase: ' + err.message); + } + throw err; + } + } else { + const cleartextWithHash = await mod$1.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + + cleartext = cleartextWithHash.subarray(0, -20); + const hash = await mod$1.hash.sha1(cleartext); + + if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { + throw new Error('Incorrect key passphrase'); + } + } + + try { + const { privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + this.privateParams = privateParams; + } catch (err) { + throw new Error('Error reading MPIs'); + } + this.isEncrypted = false; + this.keyMaterial = null; + this.s2kUsage = 0; + this.aead = null; + this.symmetric = null; + this.isLegacyAEAD = null; + } + + /** + * Checks that the key parameters are consistent + * @throws {Error} if validation was not successful + * @async + */ + async validate() { + if (this.isDummy()) { + return; + } + + if (!this.isDecrypted()) { + throw new Error('Key is not decrypted'); + } + + if (this.usedModernAEAD) { + // key integrity confirmed by successful AEAD decryption + return; + } + + let validParams; + try { + // this can throw if some parameters are undefined + validParams = await mod$1.validateParams(this.algorithm, this.publicParams, this.privateParams); + } catch (_) { + validParams = false; + } + if (!validParams) { + throw new Error('Key is invalid'); + } + } + + async generate(bits, curve) { + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if (this.version === 6 && ( + (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) || + this.algorithm === enums.publicKey.eddsaLegacy + )) { + throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`); + } + const { privateParams, publicParams } = await mod$1.generateParams(this.algorithm, bits, curve); + this.privateParams = privateParams; + this.publicParams = publicParams; + this.isEncrypted = false; + } + + /** + * Clear private key parameters + */ + clearPrivateParams() { + if (this.isMissingSecretKeyMaterial()) { + return; + } + + Object.keys(this.privateParams).forEach(name => { + const param = this.privateParams[name]; + param.fill(0); + delete this.privateParams[name]; + }); + this.privateParams = null; + this.isEncrypted = true; + } +} + +/** + * Derive encryption key + * @param {Number} keyVersion - key derivation differs for v5 keys + * @param {module:type/s2k} s2k + * @param {String} passphrase + * @param {module:enums.symmetric} cipherAlgo + * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5) + * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5) + * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only) + * @returns encryption key + */ +async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) { + if (s2k.type === 'argon2' && !aeadMode) { + throw new Error('Using Argon2 S2K without AEAD is not allowed'); + } + if (s2k.type === 'simple' && keyVersion === 6) { + throw new Error('Using Simple S2K with version 6 keys is not allowed'); + } + const { keySize } = mod$1.getCipherParams(cipherAlgo); + const derivedKey = await s2k.produceKey(passphrase, keySize); + if (!aeadMode || keyVersion === 5 || isLegacyAEAD) { + return derivedKey; + } + const info = util.concatUint8Array([ + serializedPacketTag, + new Uint8Array([keyVersion, cipherAlgo, aeadMode]) + ]); + return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize); +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the User ID Packet (Tag 13) + * + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ +class UserIDPacket { + static get tag() { + return enums.packet.userID; + } + + constructor() { + /** A string containing the user id. Usually in the form + * John Doe + * @type {String} + */ + this.userID = ''; + + this.name = ''; + this.email = ''; + this.comment = ''; + } + + /** + * Create UserIDPacket instance from object + * @param {Object} userID - Object specifying userID name, email and comment + * @returns {UserIDPacket} + * @static + */ + static fromObject(userID) { + if (util.isString(userID) || + (userID.name && !util.isString(userID.name)) || + (userID.email && !util.isEmailAddress(userID.email)) || + (userID.comment && !util.isString(userID.comment))) { + throw new Error('Invalid user ID format'); + } + const packet = new UserIDPacket(); + Object.assign(packet, userID); + const components = []; + if (packet.name) components.push(packet.name); + if (packet.comment) components.push(`(${packet.comment})`); + if (packet.email) components.push(`<${packet.email}>`); + packet.userID = components.join(' '); + return packet; + } + + /** + * Parsing function for a user id packet (tag 13). + * @param {Uint8Array} input - Payload of a tag 13 packet + */ + read(bytes, config$1 = config) { + const userID = util.decodeUTF8(bytes); + if (userID.length > config$1.maxUserIDLength) { + throw new Error('User ID string is too long'); + } + + /** + * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1, + * as well comments placed between the name (if present) and the bracketed email address: + * - name (comment) + * - email + * In the first case, the `email` is the only required part, and it must contain the `@` symbol. + * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, + * since they interfere with `comment` parsing. + */ + const re = /^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/; + const matches = re.exec(userID); + if (matches !== null) { + const { name, comment, email } = matches.groups; + this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace + this.name = name?.trim() || ''; + this.email = email.substring(1, email.length - 1); // remove brackets + } else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace + this.email = userID; + } + + this.userID = userID; + } + + /** + * Creates a binary representation of the user id packet + * @returns {Uint8Array} Binary representation. + */ + write() { + return util.encodeUTF8(this.userID); + } + + equals(otherUserID) { + return otherUserID && otherUserID.userID === this.userID; + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + * @extends SecretKeyPacket + */ +class SecretSubkeyPacket extends SecretKeyPacket { + static get tag() { + return enums.packet.secretSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); + } +} + +/** + * Implementation of the Trust Packet (Tag 12) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ +class TrustPacket { + static get tag() { + return enums.packet.trust; + } + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + */ + read() { + throw new UnsupportedError('Trust packets are not supported'); + } + + write() { + throw new UnsupportedError('Trust packets are not supported'); + } +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2022 Proton AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Padding Packet + * + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}: + * Padding Packet + */ +class PaddingPacket { + static get tag() { + return enums.packet.padding; + } + + constructor() { + this.padding = null; + } + + /** + * Read a padding packet + * @param {Uint8Array | ReadableStream} bytes + */ + read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars + // Padding packets are ignored, so this function is never called. + } + + /** + * Write the padding packet + * @returns {Uint8Array} The padding packet. + */ + write() { + return this.padding; + } + + /** + * Create random padding. + * @param {Number} length - The length of padding to be generated. + * @throws {Error} if padding generation was not successful + * @async + */ + async createPadding(length) { + this.padding = await mod$1.random.getRandomBytes(length); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Signature can contain the following packets +const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + +/** + * Class that represents an OpenPGP signature. + */ +class Signature { + /** + * @param {PacketList} packetlist - The signature packets + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } + + /** + * Returns binary encoded signature + * @returns {ReadableStream} Binary signature. + */ + write() { + return this.packets.write(); + } + + /** + * Returns ASCII armored text of signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1); + } + + /** + * Returns an array of KeyIDs of all of the issuers who created this signature + * @returns {Array} The Key IDs of the signing keys + */ + getSigningKeyIDs() { + return this.packets.map(packet => packet.issuerKeyID); + } +} + +/** + * reads an (optionally armored) OpenPGP signature and returns a signature object + * @param {Object} options + * @param {String} [options.armoredSignature] - Armored signature to be parsed + * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New signature object. + * @async + * @static + */ +async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredSignature || binarySignature; + if (!input) { + throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); + } + if (armoredSignature && !util.isString(armoredSignature)) { + throw new Error('readSignature: options.armoredSignature must be a string'); + } + if (binarySignature && !util.isUint8Array(binarySignature)) { + throw new Error('readSignature: options.binarySignature must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (armoredSignature) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.signature) { + throw new Error('Armored text not of type signature'); + } + input = data; + } + const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1); + return new Signature(packetlist); +} + +/** + * @fileoverview Provides helpers methods for key module + * @module key/helper + */ + + +async function generateSecretSubkey(options, config) { + const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); + secretSubkeyPacket.packets = null; + secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretSubkeyPacket.generate(options.rsaBits, options.curve); + await secretSubkeyPacket.computeFingerprintAndKeyID(); + return secretSubkeyPacket; +} + +async function generateSecretKey(options, config) { + const secretKeyPacket = new SecretKeyPacket(options.date, config); + secretKeyPacket.packets = null; + secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); + await secretKeyPacket.computeFingerprintAndKeyID(); + return secretKeyPacket; +} + +/** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param {Array} signatures - List of signatures + * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature + * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures, + * `enums.signatures.certGeneric` should be given regardless of the actual trust level) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - full configuration + * @returns {Promise} The latest valid signature. + * @async + */ +async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { + let latestValid; + let exception; + for (let i = signatures.length - 1; i >= 0; i--) { + try { + if ( + (!latestValid || signatures[i].created >= latestValid.created) + ) { + await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); + latestValid = signatures[i]; + } + } catch (e) { + exception = e; + } + } + if (!latestValid) { + throw util.wrapError( + `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` + .replace('certGeneric ', 'self-') + .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), + exception); + } + return latestValid; +} + +function isDataExpired(keyPacket, signature, date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + const expirationTime = getKeyExpirationTime(keyPacket, signature); + return !(keyPacket.created <= normDate && normDate < expirationTime); + } + return false; +} + +/** + * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} + * @param {SecretSubkeyPacket} subkey - Subkey key packet + * @param {SecretKeyPacket} primaryKey - Primary key packet + * @param {Object} options + * @param {Object} config - Full configuration + */ +async function createBindingSignature(subkey, primaryKey, options, config) { + const dataToSign = {}; + dataToSign.key = primaryKey; + dataToSign.bind = subkey; + const signatureProperties = { signatureType: enums.signature.subkeyBinding }; + if (options.sign) { + signatureProperties.keyFlags = [enums.keyFlags.signData]; + signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, { + signatureType: enums.signature.keyBinding + }, options.date, undefined, undefined, undefined, config); + } else { + signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; + } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; + } + const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); + return subkeySignaturePacket; +} + +/** + * Returns the preferred signature hash algorithm for a set of keys. + * @param {Array} [targetKeys] - The keys to get preferences from + * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from + * @param {Object} config - full configuration + * @returns {Promise} + * @async + */ +async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) { + /** + * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the + * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys). + * if no keys are available, `preferredSenderAlgo` is returned. + * For ECC signing key, the curve preferred hash is taken into account as well (see logic below). + */ + const defaultAlgo = enums.hash.sha256; // MUST implement + const preferredSenderAlgo = config.preferredHashAlgorithm; + + const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => { + const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config); + const targetPrefs = selfCertification.preferredHashAlgorithms; + return targetPrefs; + })); + const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys + for (const supportedAlgos of supportedAlgosPerTarget) { + for (const hashAlgo of supportedAlgos) { + try { + // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on + const supportedAlgo = enums.write(enums.hash, hashAlgo); + supportedAlgosMap.set( + supportedAlgo, + supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1 + ); + } catch {} + } + } + const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo; + const getStrongestSupportedHashAlgo = () => { + if (supportedAlgosMap.size === 0) { + return defaultAlgo; + } + const sortedHashAlgos = Array.from(supportedAlgosMap.keys()) + .filter(hashAlgo => isSupportedHashAlgo(hashAlgo)) + .sort((algoA, algoB) => mod$1.hash.getHashByteLength(algoA) - mod$1.hash.getHashByteLength(algoB)); + const strongestHashAlgo = sortedHashAlgos[0]; + // defaultAlgo is always implicilty supported, and might be stronger than the rest + return mod$1.hash.getHashByteLength(strongestHashAlgo) >= mod$1.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo; + }; + + const eccAlgos = new Set([ + enums.publicKey.ecdsa, + enums.publicKey.eddsaLegacy, + enums.publicKey.ed25519, + enums.publicKey.ed448 + ]); + + if (eccAlgos.has(signingKeyPacket.algorithm)) { + // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see: + // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5 + // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough; + // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve + // preferred algo, even if not supported by all targets. + const preferredCurveAlgo = mod$1.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid); + + const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo); + const preferredSenderAlgoStrongerThanCurveAlgo = mod$1.hash.getHashByteLength(preferredSenderAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo); + + if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) { + return preferredSenderAlgo; + } else { + const strongestSupportedAlgo = getStrongestSupportedHashAlgo(); + return mod$1.hash.getHashByteLength(strongestSupportedAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo) ? + strongestSupportedAlgo : + preferredCurveAlgo; + } + } + + // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this, + // since it was manually set by the sender. + return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo(); +} + +/** + * Returns the preferred compression algorithm for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Preferred compression algorithm + * @async + */ +async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const defaultAlgo = enums.compression.uncompressed; + const preferredSenderAlgo = config$1.preferredCompressionAlgorithm; + + // if preferredSenderAlgo appears in the prefs of all recipients, we pick it + // otherwise we use the default algo + // if no keys are available, preferredSenderAlgo is returned + const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { + const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1); + const recipientPrefs = selfCertification.preferredCompressionAlgorithms; + return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; + })); + return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; +} + +/** + * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred + * @async + */ +async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1))); + const withAEAD = keys.length ? + selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) : + config$1.aeadProtect; + + if (withAEAD) { + const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb }; + const desiredCipherSuites = [ + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm }, + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb }, + { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm } + ]; + for (const desiredCipherSuite of desiredCipherSuites) { + if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some( + cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo + ))) { + return desiredCipherSuite; + } + } + return defaultCipherSuite; + } + const defaultSymAlgo = enums.symmetric.aes128; + const desiredSymAlgo = config$1.preferredSymmetricAlgorithm; + return { + symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ? + desiredSymAlgo : + defaultSymAlgo, + aeadAlgo: undefined + }; +} + +/** + * Create signature packet + * @param {Object} dataToSign - Contains packets to be signed + * @param {Array} recipientKeys - keys to get preferences from + * @param {SecretKeyPacket| + * SecretSubkeyPacket} signingKeyPacket secret key packet for signing + * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing + * @param {Date} [date] - Override the creationtime of the signature + * @param {Object} [userID] - User ID + * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [detached] - Whether to create a detached signature packet + * @param {Object} config - full configuration + * @returns {Promise} Signature packet. + */ +async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) { + if (signingKeyPacket.isDummy()) { + throw new Error('Cannot sign with a gnu-dummy key.'); + } + if (!signingKeyPacket.isDecrypted()) { + throw new Error('Signing key is not decrypted.'); + } + const signaturePacket = new SignaturePacket(); + Object.assign(signaturePacket, signatureProperties); + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config); + signaturePacket.rawNotations = [...notations]; + await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config); + return signaturePacket; +} + +/** + * Merges signatures from source[attr] to dest[attr] + * @param {Object} source + * @param {Object} dest + * @param {String} attr + * @param {Date} [date] - date to use for signature expiration check, instead of the current time + * @param {Function} [checkFn] - signature only merged if true + */ +async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { + source = source[attr]; + if (source) { + if (!dest[attr].length) { + dest[attr] = source; + } else { + await Promise.all(source.map(async function(sourceSig) { + if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && + !dest[attr].some(function(destSig) { + return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); + })) { + dest[attr].push(sourceSig); + } + })); + } + } +} + +/** + * Checks if a given certificate or binding signature is revoked + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Object} dataToVerify - The data to check + * @param {Array} revocations - The revocation signatures to check + * @param {SignaturePacket} signature - The certificate or signature to check + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the signature revokes the data. + * @async + */ +async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { + key = key || primaryKey; + const revocationKeyIDs = []; + await Promise.all(revocations.map(async function(revocationSignature) { + try { + if ( + // Note: a third-party revocation signature could legitimately revoke a + // self-signature if the signature has an authorized revocation key. + // However, we don't support passing authorized revocation keys, nor + // verifying such revocation signatures. Instead, we indicate an error + // when parsing a key with an authorized revocation key, and ignore + // third-party revocation signatures here. (It could also be revoking a + // third-party key certification, which should only affect + // `verifyAllCertifications`.) + !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) + ) { + const isHardRevocation = ![ + enums.reasonForRevocation.keyRetired, + enums.reasonForRevocation.keySuperseded, + enums.reasonForRevocation.userIDInvalid + ].includes(revocationSignature.reasonForRevocationFlag); + + await revocationSignature.verify( + key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config + ); + + // TODO get an identifier of the revoked object instead + revocationKeyIDs.push(revocationSignature.issuerKeyID); + } + } catch (e) {} + })); + // TODO further verify that this is the signature that should be revoked + if (signature) { + signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : + signature.revoked || false; + return signature.revoked; + } + return revocationKeyIDs.length > 0; +} + +/** + * Returns key expiration time based on the given certification signature. + * The expiration time of the signature is ignored. + * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check + * @param {SignaturePacket} signature - signature to process + * @returns {Date|Infinity} expiration time or infinity if the key does not expire + */ +function getKeyExpirationTime(keyPacket, signature) { + let expirationTime; + // check V4 expiration time + if (signature.keyNeverExpires === false) { + expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; + } + return expirationTime ? new Date(expirationTime) : Infinity; +} + +function sanitizeKeyOptions(options, subkeyDefaults = {}) { + options.type = options.type || subkeyDefaults.type; + options.curve = options.curve || subkeyDefaults.curve; + options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; + options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; + + options.sign = options.sign || false; + + switch (options.type) { + case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve` + try { + options.curve = enums.write(enums.curve, options.curve); + } catch (e) { + throw new Error('Unknown curve'); + } + if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy || + options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now + options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; + } + if (options.sign) { + options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; + } else { + options.algorithm = enums.publicKey.ecdh; + } + break; + case 'curve25519': + options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519; + break; + case 'curve448': + options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448; + break; + case 'rsa': + options.algorithm = enums.publicKey.rsaEncryptSign; + break; + default: + throw new Error(`Unsupported key type ${options.type}`); + } + return options; +} + +function validateSigningKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + default: + return false; + } +} + +function validateEncryptionKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + default: + return false; + } +} + +function validateDecryptionKeyPacket(keyPacket, signature, config) { + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) { + // This is only relevant for RSA keys, all other signing algorithms cannot decrypt + return true; + } + + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + } + default: + return false; + } +} + +/** + * Check key against blacklisted algorithms and minimum strength requirements. + * @param {SecretKeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket + * @param {Config} config + * @throws {Error} if the key packet does not meet the requirements + */ +function checkKeyRequirements(keyPacket, config) { + const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); + const algoInfo = keyPacket.getAlgorithmInfo(); + if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { + throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); + } + switch (keyAlgo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.rsaEncrypt: + if (algoInfo.bits < config.minRSABits) { + throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); + } + break; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ecdh: + if (config.rejectCurves.has(algoInfo.curve)) { + throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); + } + break; + } +} + +/** + * @module key/User + */ + + +/** + * Class that represents an user ID or attribute packet and the relevant signatures. + * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info + * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + */ +class User { + constructor(userPacket, mainKey) { + this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; + this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; + this.selfCertifications = []; + this.otherCertifications = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } + + /** + * Transforms structured user data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.userID || this.userAttribute); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.selfCertifications); + packetlist.push(...this.otherCertifications); + return packetlist; + } + + /** + * Shallow clone + * @returns {User} + */ + clone() { + const user = new User(this.userID || this.userAttribute, this.mainKey); + user.selfCertifications = [...this.selfCertifications]; + user.otherCertifications = [...this.otherCertifications]; + user.revocationSignatures = [...this.revocationSignatures]; + return user; + } + + /** + * Generate third-party certifications over this user and its primary key + * @param {Array} signingKeys - Decrypted private keys for signing + * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} New user with new certifications. + * @async + */ + async certify(signingKeys, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { + if (!privateKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + if (privateKey.hasSameFingerprintAs(primaryKey)) { + throw new Error("The user's own key can only be used for self-certifications"); + } + const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); + return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, { + // Most OpenPGP implementations use generic certification (0x10) + signatureType: enums.signature.certGeneric, + keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] + }, date, undefined, undefined, undefined, config); + })); + await user.update(this, date, config); + return user; + } + + /** + * Checks if a given certificate of the user is revoked + * @param {SignaturePacket} certificate - The certificate to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked(primaryKey, enums.signature.certRevocation, { + key: primaryKey, + userID: this.userID, + userAttribute: this.userAttribute + }, this.revocationSignatures, certificate, keyPacket, date, config$1); + } + + /** + * Verifies the user certificate. + * @param {SignaturePacket} certificate - A certificate of this user + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate + * @throws if the user certificate is invalid. + * @async + */ + async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const { issuerKeyID } = certificate; + const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); + if (issuerKeys.length === 0) { + return null; + } + await Promise.all(issuerKeys.map(async key => { + const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); + if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { + throw new Error('User certificate is revoked'); + } + try { + await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('User certificate is invalid', e); + } + })); + return true; + } + + /** + * Verifies all user certificates + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllCertifications(verificationKeys, date = new Date(), config) { + const that = this; + const certifications = this.selfCertifications.concat(this.otherCertifications); + return Promise.all(certifications.map(async certification => ({ + keyID: certification.issuerKeyID, + valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) + }))); + } + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} Status of user. + * @throws {Error} if there are no valid self signatures. + * @async + */ + async verify(date = new Date(), config) { + if (!this.selfCertifications.length) { + throw new Error('No self-certifications found'); + } + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // TODO replace when Promise.some or Promise.any are implemented + let exception; + for (let i = this.selfCertifications.length - 1; i >= 0; i--) { + try { + const selfCertification = this.selfCertifications[i]; + if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { + throw new Error('Self-certification is revoked'); + } + try { + await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('Self-certification is invalid', e); + } + return true; + } catch (e) { + exception = e; + } + } + throw exception; + } + + /** + * Update user with new components from specified user + * @param {User} sourceUser - Source user to merge + * @param {Date} date - Date to verify the validity of signatures + * @param {Object} config - Full configuration + * @returns {Promise} + * @async + */ + async update(sourceUser, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // self signatures + await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { + try { + await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); + return true; + } catch (e) { + return false; + } + }); + // other signatures + await mergeSignatures(sourceUser, this, 'otherCertifications', date); + // revocation signatures + await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); + }); + } + + /** + * Revokes the user + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New user with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.certRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await user.update(this); + return user; + } +} + +/** + * @module key/Subkey + */ + + +/** + * Class that represents a subkey packet and the relevant signatures. + * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID + * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint + * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs + * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo + * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime + * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + */ +class Subkey { + /** + * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey + * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey + */ + constructor(subkeyPacket, mainKey) { + this.keyPacket = subkeyPacket; + this.bindingSignatures = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } + + /** + * Transforms structured subkey data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.bindingSignatures); + return packetlist; + } + + /** + * Shallow clone + * @return {Subkey} + */ + clone() { + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.bindingSignatures = [...this.bindingSignatures]; + subkey.revocationSignatures = [...this.revocationSignatures]; + return subkey; + } + + /** + * Checks if a binding signature of a subkey is revoked + * @param {SignaturePacket} signature - The binding signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the binding signature is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked( + primaryKey, enums.signature.subkeyRevocation, { + key: primaryKey, + bind: this.keyPacket + }, this.revocationSignatures, signature, key, date, config$1 + ); + } + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} if the subkey is invalid. + * @async + */ + async verify(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + // check subkey binding signatures + const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + // check binding signature is not revoked + if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { + throw new Error('Subkey is revoked'); + } + // check for expiration time + if (isDataExpired(this.keyPacket, bindingSignature, date)) { + throw new Error('Subkey is expired'); + } + return bindingSignature; + } + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire. + * Returns null if the subkey is invalid. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + let bindingSignature; + try { + bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + } catch (e) { + return null; + } + const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); + const sigExpiry = bindingSignature.getExpirationTime(); + return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; + } + + /** + * Update subkey with new components from specified subkey + * @param {Subkey} subkey - Source subkey to merge + * @param {Date} [date] - Date to verify validity of signatures + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if update failed + * @async + */ + async update(subkey, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + if (!this.hasSameFingerprintAs(subkey)) { + throw new Error('Subkey update method: fingerprints of subkeys not equal'); + } + // key packet + if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && + subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { + this.keyPacket = subkey.keyPacket; + } + // update missing binding signatures + const that = this; + const dataToVerify = { key: primaryKey, bind: that.keyPacket }; + await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { + for (let i = 0; i < that.bindingSignatures.length; i++) { + if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { + if (srcBindSig.created > that.bindingSignatures[i].created) { + that.bindingSignatures[i] = srcBindSig; + } + return false; + } + } + try { + await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); + return true; + } catch (e) { + return false; + } + }); + // revocation signatures + await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); + }); + } + + /** + * Revokes the subkey + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New subkey with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { key: primaryKey, bind: this.keyPacket }; + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.subkeyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await subkey.update(this); + return subkey; + } + + hasSameFingerprintAs(other) { + return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + } +} + +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { + Subkey.prototype[name] = + function() { + return this.keyPacket[name](); + }; +}); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A key revocation certificate can contain the following packets +const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); +const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); +const keyPacketTags = new Set([ + enums.packet.publicKey, enums.packet.privateKey, + enums.packet.publicSubkey, enums.packet.privateSubkey +]); + +/** + * Abstract class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + * @borrows PublicKeyPacket#getKeyID as Key#getKeyID + * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint + * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs + * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo + * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + */ +class Key { + /** + * Transforms packetlist to structured key data + * @param {PacketList} packetlist - The packets that form a key + * @param {Set} disallowedPackets - disallowed packet tags + */ + packetListToStructure(packetlist, disallowedPackets = new Set()) { + let user; + let primaryKeyID; + let subkey; + let ignoreUntil; + + for (const packet of packetlist) { + + if (packet instanceof UnparseablePacket) { + const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); + if (isUnparseableKeyPacket && !ignoreUntil) { + // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must + // discard all non-key packets that follow, until another (sub)key packet is found. + if (mainKeyPacketTags.has(packet.tag)) { + ignoreUntil = mainKeyPacketTags; + } else { + ignoreUntil = keyPacketTags; + } + } + continue; + } + + const tag = packet.constructor.tag; + if (ignoreUntil) { + if (!ignoreUntil.has(tag)) continue; + ignoreUntil = null; + } + if (disallowedPackets.has(tag)) { + throw new Error(`Unexpected packet type: ${tag}`); + } + switch (tag) { + case enums.packet.publicKey: + case enums.packet.secretKey: + if (this.keyPacket) { + throw new Error('Key block contains multiple keys'); + } + this.keyPacket = packet; + primaryKeyID = this.getKeyID(); + if (!primaryKeyID) { + throw new Error('Missing Key ID'); + } + break; + case enums.packet.userID: + case enums.packet.userAttribute: + user = new User(packet, this); + this.users.push(user); + break; + case enums.packet.publicSubkey: + case enums.packet.secretSubkey: + user = null; + subkey = new Subkey(packet, this); + this.subkeys.push(subkey); + break; + case enums.packet.signature: + switch (packet.signatureType) { + case enums.signature.certGeneric: + case enums.signature.certPersona: + case enums.signature.certCasual: + case enums.signature.certPositive: + if (!user) { + util.printDebug('Dropping certification signatures without preceding user packet'); + continue; + } + if (packet.issuerKeyID.equals(primaryKeyID)) { + user.selfCertifications.push(packet); + } else { + user.otherCertifications.push(packet); + } + break; + case enums.signature.certRevocation: + if (user) { + user.revocationSignatures.push(packet); + } else { + this.directSignatures.push(packet); + } + break; + case enums.signature.key: + this.directSignatures.push(packet); + break; + case enums.signature.subkeyBinding: + if (!subkey) { + util.printDebug('Dropping subkey binding signature without preceding subkey packet'); + continue; + } + subkey.bindingSignatures.push(packet); + break; + case enums.signature.keyRevocation: + this.revocationSignatures.push(packet); + break; + case enums.signature.subkeyRevocation: + if (!subkey) { + util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); + continue; + } + subkey.revocationSignatures.push(packet); + break; + } + break; + } + } + } + + /** + * Transforms structured key data to packetlist + * @returns {PacketList} The packets that form a key. + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.directSignatures); + this.users.map(user => packetlist.push(...user.toPacketList())); + this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); + return packetlist; + } + + /** + * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. + * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. + * @returns {Promise} Clone of the key. + */ + clone(clonePrivateParams = false) { + const key = new this.constructor(this.toPacketList()); + if (clonePrivateParams) { + key.getKeys().forEach(k => { + // shallow clone the key packets + k.keyPacket = Object.create( + Object.getPrototypeOf(k.keyPacket), + Object.getOwnPropertyDescriptors(k.keyPacket) + ); + if (!k.keyPacket.isDecrypted()) return; + // deep clone the private params, which are cleared during encryption + const privateParams = {}; + Object.keys(k.keyPacket.privateParams).forEach(name => { + privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); + }); + k.keyPacket.privateParams = privateParams; + }); + } + return key; + } + + /** + * Returns an array containing all public or private subkeys matching keyID; + * If no keyID is given, returns all subkeys. + * @param {type/keyID} [keyID] - key ID to look for + * @returns {Array} array of subkeys + */ + getSubkeys(keyID = null) { + const subkeys = this.subkeys.filter(subkey => ( + !keyID || subkey.getKeyID().equals(keyID, true) + )); + return subkeys; + } + + /** + * Returns an array containing all public or private keys matching keyID. + * If no keyID is given, returns all keys, starting with the primary key. + * @param {type/keyid~KeyID} [keyID] - key ID to look for + * @returns {Array} array of keys + */ + getKeys(keyID = null) { + const keys = []; + if (!keyID || this.getKeyID().equals(keyID, true)) { + keys.push(this); + } + return keys.concat(this.getSubkeys(keyID)); + } + + /** + * Returns key IDs of all keys + * @returns {Array} + */ + getKeyIDs() { + return this.getKeys().map(key => key.getKeyID()); + } + + /** + * Returns userIDs + * @returns {Array} Array of userIDs. + */ + getUserIDs() { + return this.users.map(user => { + return user.userID ? user.userID.userID : null; + }).filter(userID => userID !== null); + } + + /** + * Returns binary encoded key + * @returns {Uint8Array} Binary key. + */ + write() { + return this.toPacketList().write(); + } + + /** + * Returns last created key or key by given keyID that is available for signing and verification + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} signing key + * @throws if no valid signing key was found + * @async + */ + async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); + } + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature( + subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 + ); + if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + continue; + } + if (!bindingSignature.embeddedSignature) { + throw new Error('Missing embedded signature'); + } + // verify embedded signature + await getLatestValidSignature( + [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 + ); + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } catch (e) { + exception = e; + } + } + } + + try { + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateSigningKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; + } + throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); + } + + /** + * Returns last created key or key by given keyID that is available for encryption or decryption + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} encryption key + * @throws if no valid encryption key was found + * @async + */ + async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); + } + // V4: by convention subkeys are preferred for encryption service + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } + } catch (e) { + exception = e; + } + } + } + + try { + // if no valid subkey for encryption, evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; + } + throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + } + + /** + * Checks if a signature on a key is revoked + * @param {SignaturePacket} signature - The signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + return isDataRevoked( + this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 + ); + } + + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature. Throws if the primary key is invalid. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} If key verification failed + * @async + */ + async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + // check for key revocation signatures + if (await this.isRevoked(null, null, date, config$1)) { + throw new Error('Primary key is revoked'); + } + // check for valid, unrevoked, unexpired self signature + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + // check for expiration time in binding signatures + if (isDataExpired(primaryKey, selfCertification, date)) { + throw new Error('Primary key is expired'); + } + if (primaryKey.version !== 6) { + // check for expiration time in direct signatures (for V6 keys, the above already did so) + const directSignature = await getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key + + if (directSignature && isDataExpired(primaryKey, directSignature, date)) { + throw new Error('Primary key is expired'); + } + } + } + + /** + * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. + * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. + * @param {Object} [userID] - User ID to consider instead of the primary user + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(userID, config$1 = config) { + let primaryKeyExpiry; + try { + const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1); + const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); + const selfSigExpiry = selfCertification.getExpirationTime(); + const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature. + await getLatestValidSignature( + this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 + ).catch(() => {}); + if (directSignature) { + const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); + // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, + // causing a discountinous validy period for the key + primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); + } else { + primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; + } + } catch (e) { + primaryKeyExpiry = null; + } + + return util.normalizeDate(primaryKeyExpiry); + } + + + /** + * For V4 keys, returns the self-signature of the primary user. + * For V5 keys, returns the latest valid direct-key self-signature. + * This self-signature is to be used to check the key expiration, + * algorithm preferences, and so on. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} The primary self-signature + * @async + */ + async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + if (primaryKey.version === 6) { + return getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ); + } + const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + return selfCertification; + } + + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * user: User, + * selfCertification: SignaturePacket + * }>} The primary user and the self signature + * @async + */ + async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const users = []; + let exception; + for (let i = 0; i < this.users.length; i++) { + try { + const user = this.users[i]; + if (!user.userID) { + continue; + } + if ( + (userID.name !== undefined && user.userID.name !== userID.name) || + (userID.email !== undefined && user.userID.email !== userID.email) || + (userID.comment !== undefined && user.userID.comment !== userID.comment) + ) { + throw new Error('Could not find user that matches that user ID'); + } + const dataToVerify = { userID: user.userID, key: primaryKey }; + const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); + users.push({ index: i, user, selfCertification }); + } catch (e) { + exception = e; + } + } + if (!users.length) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('Could not find primary user'); + } + await Promise.all(users.map(async function (a) { + return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); + })); + // sort by primary user flag and signature creation time + const primaryUser = users.sort(function(a, b) { + const A = a.selfCertification; + const B = b.selfCertification; + return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; + }).pop(); + const { user, selfCertification: cert } = primaryUser; + if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { + throw new Error('Primary user is revoked'); + } + return primaryUser; + } + + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * + * If the source key is a private key and the destination key is public, + * a private key is returned. + * @param {Key} sourceKey - Source key to merge + * @param {Date} [date] - Date to verify validity of signatures and keys + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} updated key + * @async + */ + async update(sourceKey, date = new Date(), config$1 = config) { + if (!this.hasSameFingerprintAs(sourceKey)) { + throw new Error('Primary key fingerprints must be equal to update the key'); + } + if (!this.isPrivate() && sourceKey.isPrivate()) { + // check for equal subkey packets + const equal = (this.subkeys.length === sourceKey.subkeys.length) && + (this.subkeys.every(destSubkey => { + return sourceKey.subkeys.some(srcSubkey => { + return destSubkey.hasSameFingerprintAs(srcSubkey); + }); + })); + if (!equal) { + throw new Error('Cannot update public key with private key if subkeys mismatch'); + } + + return sourceKey.update(this, config$1); + } + // from here on, either: + // - destination key is private, source key is public + // - the keys are of the same type + // hence we don't need to convert the destination key type + const updatedKey = this.clone(); + // revocation signatures + await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { + return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); + }); + // direct signatures + await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); + // update users + await Promise.all(sourceKey.users.map(async srcUser => { + // multiple users with the same ID/attribute are not explicitly disallowed by the spec + // hence we support them, just in case + const usersToUpdate = updatedKey.users.filter(dstUser => ( + (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || + (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) + )); + if (usersToUpdate.length > 0) { + await Promise.all( + usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) + ); + } else { + const newUser = srcUser.clone(); + newUser.mainKey = updatedKey; + updatedKey.users.push(newUser); + } + })); + // update subkeys + await Promise.all(sourceKey.subkeys.map(async srcSubkey => { + // multiple subkeys with same fingerprint might be preset + const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( + dstSubkey.hasSameFingerprintAs(srcSubkey) + )); + if (subkeysToUpdate.length > 0) { + await Promise.all( + subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) + ); + } else { + const newSubkey = srcSubkey.clone(); + newSubkey.mainKey = updatedKey; + updatedKey.subkeys.push(newSubkey); + } + })); + + return updatedKey; + } + + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Armored revocation certificate. + * @async + */ + async getRevocationCertificate(date = new Date(), config$1 = config) { + const dataToVerify = { key: this.keyPacket }; + const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); + const packetlist = new PacketList(); + packetlist.push(revocationSignature); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1); + } + + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param {String} revocationCertificate - armored revocation certificate + * @param {Date} [date] - Date to verify the certificate + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Revoked key. + * @async + */ + async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { + const input = await unarmor(revocationCertificate); + const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); + const revocationSignature = packetlist.findPacket(enums.packet.signature); + if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { + throw new Error('Could not find revocation signature packet'); + } + if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { + throw new Error('Revocation signature does not match key'); + } + try { + await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); + } catch (e) { + throw util.wrapError('Could not verify revocation signature', e); + } + const key = this.clone(); + key.revocationSignatures.push(revocationSignature); + return key; + } + + /** + * Signs primary user of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signPrimaryUser(privateKeys, date, userID, config$1 = config) { + const { index, user } = await this.getPrimaryUser(date, userID, config$1); + const userSign = await user.certify(privateKeys, date, config$1); + const key = this.clone(); + key.users[index] = userSign; + return key; + } + + /** + * Signs all users of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for signing, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signAllUsers(privateKeys, date = new Date(), config$1 = config) { + const key = this.clone(); + key.users = await Promise.all(this.users.map(function(user) { + return user.certify(privateKeys, date, config$1); + })); + return key; + } + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { + const primaryKey = this.keyPacket; + const { user } = await this.getPrimaryUser(date, userID, config$1); + const results = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + return results; + } + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of userID, signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { + const primaryKey = this.keyPacket; + const results = []; + await Promise.all(this.users.map(async user => { + const signatures = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + + results.push(...signatures.map( + signature => ({ + userID: user.userID ? user.userID.userID : null, + userAttribute: user.userAttribute, + keyID: signature.keyID, + valid: signature.valid + })) + ); + })); + return results; + } +} + +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { + Key.prototype[name] = + Subkey.prototype[name]; +}); + +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Class that represents an OpenPGP Public Key + */ +class PublicKey extends Key { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.keyPacket = null; + this.revocationSignatures = []; + this.directSignatures = []; + this.users = []; + this.subkeys = []; + if (packetlist) { + this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing public-key packet'); + } + } + } + + /** + * Returns true if this is a private key + * @returns {false} + */ + isPrivate() { + return false; + } + + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + return this; + } + + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } +} + +/** + * Class that represents an OpenPGP Private key + */ +class PrivateKey extends PublicKey { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing private-key packet'); + } + } + + /** + * Returns true if this is a private key + * @returns {Boolean} + */ + isPrivate() { + return true; + } + + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + const packetlist = new PacketList(); + const keyPackets = this.toPacketList(); + for (const keyPacket of keyPackets) { + switch (keyPacket.constructor.tag) { + case enums.packet.secretKey: { + const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); + packetlist.push(pubKeyPacket); + break; + } + case enums.packet.secretSubkey: { + const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); + packetlist.push(pubSubkeyPacket); + break; + } + default: + packetlist.push(keyPacket); + } + } + return new PublicKey(packetlist); + } + + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } + + /** + * Returns all keys that are available for decryption, matching the keyID when given + * This is useful to retrieve keys for session key decryption + * @param {module:type/keyid~KeyID} keyID, optional + * @param {Date} date, optional + * @param {String} userID, optional + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} Array of decryption keys. + * @throws {Error} if no decryption key is found + * @async + */ + async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const keys = []; + let exception = null; + for (let i = 0; i < this.subkeys.length; i++) { + if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { + if (this.subkeys[i].keyPacket.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + continue; + } + + try { + const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; + const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) { + keys.push(this.subkeys[i]); + } + } catch (e) { + exception = e; + } + } + } + + // evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) { + if (primaryKey.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + } else { + keys.push(this); + } + } + + if (keys.length === 0) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('No decryption key packets found'); + } + + return keys; + } + + /** + * Returns true if the primary key or any subkey is decrypted. + * A dummy key is considered encrypted. + */ + isDecrypted() { + return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); + } + + /** + * Check whether the private and public primary key parameters correspond + * Together with verification of binding signatures, this guarantees key integrity + * In case of gnu-dummy primary key, it is enough to validate any signing subkeys + * otherwise all encryption subkeys are validated + * If only gnu-dummy keys are found, we cannot properly validate so we throw an error + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if validation was not successful and the key cannot be trusted + * @async + */ + async validate(config$1 = config) { + if (!this.isPrivate()) { + throw new Error('Cannot validate a public key'); + } + + let signingKeyPacket; + if (!this.keyPacket.isDummy()) { + signingKeyPacket = this.keyPacket; + } else { + /** + * It is enough to validate any signing keys + * since its binding signatures are also checked + */ + const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); + // This could again be a dummy key + if (signingKey && !signingKey.keyPacket.isDummy()) { + signingKeyPacket = signingKey.keyPacket; + } + } + + if (signingKeyPacket) { + return signingKeyPacket.validate(); + } else { + const keys = this.getKeys(); + const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); + if (allDummies) { + throw new Error('Cannot validate an all-gnu-dummy key'); + } + + return Promise.all(keys.map(async key => key.keyPacket.validate())); + } + } + + /** + * Clear private key parameters + */ + clearPrivateParams() { + this.getKeys().forEach(({ keyPacket }) => { + if (keyPacket.isDecrypted()) { + keyPacket.clearPrivateParams(); + } + }); + } + + /** + * Revokes the key + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New key with revocation signature. + * @async + */ + async revoke( + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + if (!this.isPrivate()) { + throw new Error('Need private key for revoking'); + } + const dataToSign = { key: this.keyPacket }; + const key = this.clone(); + key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, undefined, config$1)); + return key; + } + + + /** + * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. + * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519. + * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. + * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format). + * Note: Curve448 and Curve25519 are not widely supported yet. + * @param {String} options.curve (optional) Elliptic curve for ECC keys + * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date (optional) Override the creation date of the key and the key signatures + * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false + * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} + * @async + */ + async addSubkey(options = {}) { + const config$1 = { ...config, ...options.config }; + if (options.passphrase) { + throw new Error('Subkey could not be encrypted here, please encrypt whole key'); + } + if (options.rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); + } + const secretKeyPacket = this.keyPacket; + if (secretKeyPacket.isDummy()) { + throw new Error('Cannot add subkey to gnu-dummy primary key'); + } + if (!secretKeyPacket.isDecrypted()) { + throw new Error('Key is not decrypted'); + } + const defaultOptions = secretKeyPacket.getAlgorithmInfo(); + defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm); + defaultOptions.rsaBits = defaultOptions.bits || 4096; + defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy'; + options = sanitizeKeyOptions(options, defaultOptions); + // Every subkey for a v4 primary key MUST be a v4 subkey. + // Every subkey for a v6 primary key MUST be a v6 subkey. + // For v5 keys, since we dropped generation support, a v4 subkey is added. + // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user. + const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 }); + checkKeyRequirements(keyPacket, config$1); + const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); + const packetList = this.toPacketList(); + packetList.push(keyPacket, bindingSignature); + return new PrivateKey(packetList); + } +} + +function getDefaultSubkeyType(algoName) { + const algo = enums.write(enums.publicKey, algoName); + // NB: no encryption-only algos, since they cannot be in primary keys + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + return 'rsa'; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return 'ecc'; + case enums.publicKey.ed25519: + return 'curve25519'; + case enums.publicKey.ed448: + return 'curve448'; + default: + throw new Error('Unsupported algorithm'); + } +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Key can contain the following packets +const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +]); + +/** + * Creates a PublicKey or PrivateKey depending on the packetlist in input + * @param {PacketList} - packets to parse + * @return {Key} parsed key + * @throws if no key packet was found + */ +function createKey(packetlist) { + for (const packet of packetlist) { + switch (packet.constructor.tag) { + case enums.packet.secretKey: + return new PrivateKey(packetlist); + case enums.packet.publicKey: + return new PublicKey(packetlist); + } + } + throw new Error('No key packet found'); +} + + +/** + * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format). + * @param {String} options.curve Elliptic curve for ECC keys + * @param {Integer} options.rsaBits Number of bits for RSA keys + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Creation date of the key and the key signatures + * @param {Object} config - Full configuration + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function generate(options, config) { + options.sign = true; // primary key is always a signing key + options = sanitizeKeyOptions(options); + options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); + let promises = [generateSecretKey(options, config)]; + promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); + const packets = await Promise.all(promises); + + const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; +} + +/** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param {PrivateKey} options.privateKey The private key to reformat + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Override the creation date of the key signatures + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * @param {Object} config - Full configuration + * + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function reformat(options, config) { + options = sanitize(options); + const { privateKey } = options; + + if (!privateKey.isPrivate()) { + throw new Error('Cannot reformat a public key'); + } + + if (privateKey.keyPacket.isDummy()) { + throw new Error('Cannot reformat a gnu-dummy primary key'); + } + + const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); + if (!isDecrypted) { + throw new Error('Key is not decrypted'); + } + + const secretKeyPacket = privateKey.keyPacket; + + if (!options.subkeys) { + options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { + const secretSubkeyPacket = subkey.keyPacket; + const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; + const bindingSignature = await ( + getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) + ).catch(() => ({})); + return { + sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) + }; + })); + } + + const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); + if (options.subkeys.length !== secretSubkeyPackets.length) { + throw new Error('Number of subkey options does not match number of subkeys'); + } + + options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); + + const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; + + function sanitize(options, subkeyDefaults = {}) { + options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; + + return options; + } +} + +/** + * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection + * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. + * @param {SecretKeyPacket} secretKeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPackets + * @param {Object} options + * @param {Object} config - Full configuration + * @returns {PrivateKey} + */ +async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { + // set passphrase protection + if (options.passphrase) { + await secretKeyPacket.encrypt(options.passphrase, config); + } + + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + await secretSubkeyPacket.encrypt(subkeyPassphrase, config); + } + })); + + const packetlist = new PacketList(); + packetlist.push(secretKeyPacket); + + function createPreferredAlgos(algos, preferredAlgo) { + return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + } + + function getKeySignatureProperties() { + const signatureProperties = {}; + signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; + const symmetricAlgorithms = createPreferredAlgos([ + // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + enums.symmetric.aes256, + enums.symmetric.aes128 + ], config.preferredSymmetricAlgorithm); + signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms; + if (config.aeadProtect) { + const aeadAlgorithms = createPreferredAlgos([ + enums.aead.gcm, + enums.aead.eax, + enums.aead.ocb + ], config.preferredAEADAlgorithm); + signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => { + return symmetricAlgorithms.map(symmetricAlgorithm => { + return [symmetricAlgorithm, aeadAlgorithm]; + }); + }); + } + signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ + // prefer fast asm.js implementations (SHA-256) + enums.hash.sha256, + enums.hash.sha512, + enums.hash.sha3_256, + enums.hash.sha3_512 + ], config.preferredHashAlgorithm); + signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ + enums.compression.uncompressed, + enums.compression.zlib, + enums.compression.zip + ], config.preferredCompressionAlgorithm); + // integrity protection always enabled + signatureProperties.features = [0]; + signatureProperties.features[0] |= enums.features.modificationDetection; + if (config.aeadProtect) { + signatureProperties.features[0] |= enums.features.seipdv2; + } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; + } + return signatureProperties; + } + + if (secretKeyPacket.version === 6) { // add direct key signature with key prefs + const dataToSign = { + key: secretKeyPacket + }; + + const signatureProperties = getKeySignatureProperties(); + signatureProperties.signatureType = enums.signature.key; + + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + packetlist.push(signaturePacket); + } + + await Promise.all(options.userIDs.map(async function(userID, index) { + const userIDPacket = UserIDPacket.fromObject(userID); + const dataToSign = { + userID: userIDPacket, + key: secretKeyPacket + }; + const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {}; + signatureProperties.signatureType = enums.signature.certPositive; + if (index === 0) { + signatureProperties.isPrimaryUserID = true; + } + + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + + return { userIDPacket, signaturePacket }; + })).then(list => { + list.forEach(({ userIDPacket, signaturePacket }) => { + packetlist.push(userIDPacket); + packetlist.push(signaturePacket); + }); + }); + + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyOptions = options.subkeys[index]; + const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); + return { secretSubkeyPacket, subkeySignaturePacket }; + })).then(packets => { + packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { + packetlist.push(secretSubkeyPacket); + packetlist.push(subkeySignaturePacket); + }); + }); + + // Add revocation signature packet for creating a revocation certificate. + // This packet should be removed before returning the key. + const dataToSign = { key: secretKeyPacket }; + packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.reasonForRevocation.noReason, + reasonForRevocationString: '' + }, options.date, undefined, undefined, undefined, config)); + + if (options.passphrase) { + secretKeyPacket.clearPrivateParams(); + } + + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + secretSubkeyPacket.clearPrivateParams(); + } + })); + + return new PrivateKey(packetlist); +} + +/** + * Reads an (optionally armored) OpenPGP key and returns a key object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { + throw new Error('Armored text not of type key'); + } + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]); + return createKey(firstKeyPacketList); +} + +/** + * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readPrivateKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.privateKey)) { + throw new Error('Armored text not of type private key'); + } + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } + const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + return new PrivateKey(firstPrivateKeyList); + } + throw new Error('No secret key packet found'); +} + +/** + * Reads an (optionally armored) OpenPGP key block and returns a list of key objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { + throw new Error('Armored text not of type key'); + } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + for (let i = 0; i < keyIndex.length; i++) { + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = createKey(oneKeyList); + keys.push(newKey); + } + return keys; +} + +/** + * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readPrivateKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); + } + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.privateKey) { + throw new Error('Armored text not of type private key'); + } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = new PrivateKey(oneKeyList); + keys.push(newKey); + } + if (keys.length === 0) { + throw new Error('No secret key packet found'); + } + return keys; +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Message can contain the following packets +const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + AEADEncryptedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket +]); +// A SKESK packet can contain the following packets +const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); +// A detached signature can contain the following packets +const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + +/** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ +class Message { + /** + * @param {PacketList} packetlist - The packets that form this message + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } + + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns {Array} Array of keyID objects. + */ + getEncryptionKeyIDs() { + const keyIDs = []; + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + pkESKeyPacketlist.forEach(function(packet) { + keyIDs.push(packet.publicKeyID); + }); + return keyIDs; + } + + /** + * Returns the key IDs of the keys that signed the message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const msg = this.unwrapCompressed(); + // search for one pass signatures + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); + if (onePassSigList.length > 0) { + return onePassSigList.map(packet => packet.issuerKeyID); + } + // if nothing found look for signature packets + const signatureList = msg.packets.filterByTag(enums.packet.signature); + return signatureList.map(packet => packet.issuerKeyID); + } + + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Date} [date] - Use the given date for key verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with decrypted content. + * @async + */ + async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { + const symEncryptedPacketlist = this.packets.filterByTag( + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ); + + if (symEncryptedPacketlist.length === 0) { + throw new Error('No encrypted data found'); + } + + const symEncryptedPacket = symEncryptedPacketlist[0]; + const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm; + + const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1); + + let exception = null; + const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { + if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) { + throw new Error('Invalid session key for decryption.'); + } + + try { + const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.decrypt(algo, data, config$1); + } catch (e) { + util.printDebugError(e); + exception = e; + } + })); + // We don't await stream.cancel here because it only returns when the other copy is canceled too. + cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. + symEncryptedPacket.encrypted = null; + await decryptedPromise; + + if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { + throw exception || new Error('Decryption failed.'); + } + + const resultMsg = new Message(symEncryptedPacket.packets); + symEncryptedPacket.packets = new PacketList(); // remove packets after decryption + + return resultMsg; + } + + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable) + * @param {Date} [date] - Use the given date for key verification, instead of current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * @async + */ + async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) { + let decryptedSessionKeyPackets = []; + + let exception; + if (passwords) { + const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); + if (skeskPackets.length === 0) { + throw new Error('No symmetrically encrypted session key packet found.'); + } + await Promise.all(passwords.map(async function(password, i) { + let packets; + if (i) { + packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); + } else { + packets = skeskPackets; + } + await Promise.all(packets.map(async function(skeskPacket) { + try { + await skeskPacket.decrypt(password); + decryptedSessionKeyPackets.push(skeskPacket); + } catch (err) { + util.printDebugError(err); + if (err instanceof Argon2OutOfMemoryError) { + exception = err; + } + } + })); + })); + } else if (decryptionKeys) { + const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + if (pkeskPackets.length === 0) { + throw new Error('No public key encrypted session key packet found.'); + } + await Promise.all(pkeskPackets.map(async function(pkeskPacket) { + await Promise.all(decryptionKeys.map(async function(decryptionKey) { + let decryptionKeyPackets; + try { + // do not check key expiration to allow decryption of old messages + decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); + } catch (err) { + exception = err; + return; + } + + let algos = [ + enums.symmetric.aes256, // Old OpenPGP.js default fallback + enums.symmetric.aes128, // RFC4880bis fallback + enums.symmetric.tripledes, // RFC4880 fallback + enums.symmetric.cast5 // Golang OpenPGP fallback + ]; + try { + const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere. + if (selfCertification.preferredSymmetricAlgorithms) { + algos = algos.concat(selfCertification.preferredSymmetricAlgorithms); + } + } catch (e) {} + + await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { + if (!decryptionKeyPacket.isDecrypted()) { + throw new Error('Decryption key is not decrypted.'); + } + + // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. + const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal + ); + + if (doConstantTimeDecryption) { + // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, + // either with the successfully decrypted session key, or with a randomly generated one. + // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on + // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: + // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the + // randomly generated keys of the remaining key types. + // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly + // generated session keys. + // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. + + const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times + await Promise.all(( + expectedSymmetricAlgorithm ? + [expectedSymmetricAlgorithm] : + Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms) + ).map(async sessionKeyAlgorithm => { + const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); + pkeskPacketCopy.read(serialisedPKESK); + const randomSessionKey = { + sessionKeyAlgorithm, + sessionKey: mod$1.generateSessionKey(sessionKeyAlgorithm) + }; + try { + await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); + decryptedSessionKeyPackets.push(pkeskPacketCopy); + } catch (err) { + // `decrypt` can still throw some non-security-sensitive errors + util.printDebugError(err); + exception = err; + } + })); + + } else { + try { + await pkeskPacket.decrypt(decryptionKeyPacket); + const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm; + if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) { + throw new Error('A non-preferred symmetric algorithm was used.'); + } + decryptedSessionKeyPackets.push(pkeskPacket); + } catch (err) { + util.printDebugError(err); + exception = err; + } + } + })); + })); + cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. + pkeskPacket.encrypted = null; + })); + } else { + throw new Error('No key or password specified.'); + } + + if (decryptedSessionKeyPackets.length > 0) { + // Return only unique session keys + if (decryptedSessionKeyPackets.length > 1) { + const seen = new Set(); + decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { + const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); + if (seen.has(k)) { + return false; + } + seen.add(k); + return true; + }); + } + + return decryptedSessionKeyPackets.map(packet => ({ + data: packet.sessionKey, + algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm) + })); + } + throw exception || new Error('Session key decryption failed.'); + } + + /** + * Get literal data that is the body of the message + * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + */ + getLiteralData() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getBytes()) || null; + } + + /** + * Get filename from literal data packet + * @returns {(String|null)} Filename of literal data packet as string. + */ + getFilename() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getFilename()) || null; + } + + /** + * Get literal data as text + * @returns {(String|null)} Literal body of the message interpreted as text. + */ + getText() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + if (literal) { + return literal.getText(); + } + return null; + } + + /** + * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. + * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for + * @param {Date} [date] - Date to select algorithm preferences at + * @param {Array} [userIDs] - User IDs to select algorithm preferences for + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. + * @async + */ + static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { + const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1); + const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo); + const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined; + + await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() + .catch(() => null) // ignore key strength requirements + .then(maybeKey => { + if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) && + !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted + throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); + } + }) + )); + + const sessionKeyData = mod$1.generateSessionKey(symmetricAlgo); + return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName }; + } + + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - Password(s) for message encryption + * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] + * @param {Date} [date] - Override the creation date of the literal package + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + if (sessionKey) { + if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { + throw new Error('Invalid session key for encryption.'); + } + } else if (encryptionKeys && encryptionKeys.length) { + sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); + } else if (passwords && passwords.length) { + sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); + } else { + throw new Error('No keys, passwords, or session key provided.'); + } + + const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; + + const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); + + const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({ + version: aeadAlgorithmName ? 2 : 1, + aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null + }); + symEncryptedPacket.packets = this.packets; + + const algorithm = enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); + + msg.packets.push(symEncryptedPacket); + symEncryptedPacket.packets = new PacketList(); // remove packets after encryption + return msg; + } + + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param {Uint8Array} sessionKey - session key for encryption + * @param {String} algorithmName - session key algorithm + * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - For message encryption + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [date] - Override the date + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + const packetlist = new PacketList(); + const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName); + const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); + + if (encryptionKeys) { + const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { + const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); + + const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({ + version: aeadAlgorithm ? 6 : 3, + encryptionKeyPacket: encryptionKey.keyPacket, + anonymousRecipient: wildcard, + sessionKey, + sessionKeyAlgorithm: symmetricAlgorithm + }); + + await pkESKeyPacket.encrypt(encryptionKey.keyPacket); + delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption + return pkESKeyPacket; + })); + packetlist.push(...results); + } + if (passwords) { + const testDecrypt = async function(keyPacket, password) { + try { + await keyPacket.decrypt(password); + return 1; + } catch (e) { + return 0; + } + }; + + const sum = (accumulator, currentValue) => accumulator + currentValue; + + const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { + const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); + symEncryptedSessionKeyPacket.sessionKey = sessionKey; + symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; + if (aeadAlgorithm) { + symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; + } + await symEncryptedSessionKeyPacket.encrypt(password, config$1); + + if (config$1.passwordCollisionCheck) { + const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); + if (results.reduce(sum) !== 1) { + return encryptPassword(sessionKey, algorithm, password); + } + } + + delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption + return symEncryptedSessionKeyPacket; + }; + + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd))); + packetlist.push(...results); + } + + return new Message(packetlist); + } + + /** + * Sign the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to add to the message + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with signed content. + * @async + */ + async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const packetlist = new PacketList(); + + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); + } + + const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well + const onePassSignaturePackets = signaturePackets.map( + (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0)) + .reverse(); // innermost OPS refers to the first signature packet + + packetlist.push(...onePassSignaturePackets); + packetlist.push(literalDataPacket); + packetlist.push(...signaturePackets); + + return new Message(packetlist); + } + + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param {module:enums.compression} algo - compression algorithm + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Message} New message with compressed content. + */ + compress(algo, config$1 = config) { + if (algo === enums.compression.uncompressed) { + return this; + } + + const compressed = new CompressedDataPacket(config$1); + compressed.algorithm = algo; + compressed.packets = this.packets; + + const packetList = new PacketList(); + packetList.push(compressed); + + return new Message(packetList); + } + + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New detached signature of message content. + * @async + */ + async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); + } + return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config$1)); + } + + /** + * Verify message signatures + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signatures. + * @async + */ + async verify(verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + if (isArrayStream(msg.packets.stream)) { + msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + } + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); + const signatureList = msg.packets.filterByTag(enums.packet.signature); + if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { + await Promise.all(onePassSigList.map(async onePassSig => { + onePassSig.correspondingSig = new Promise((resolve, reject) => { + onePassSig.correspondingSigResolve = resolve; + onePassSig.correspondingSigReject = reject; + }); + onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); + onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); + onePassSig.hashed.catch(() => {}); + })); + msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { + const reader = getReader(readable); + const writer = getWriter(writable); + try { + for (let i = 0; i < onePassSigList.length; i++) { + const { value: signature } = await reader.read(); + onePassSigList[i].correspondingSigResolve(signature); + } + await reader.readToEnd(); + await writer.ready; + await writer.close(); + } catch (e) { + onePassSigList.forEach(onePassSig => { + onePassSig.correspondingSigReject(e); + }); + await writer.abort(e); + } + }); + return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + } + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); + } + + /** + * Verify detached message signature + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Signature} signature + * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); + } + + /** + * Unwrap compressed message + * @returns {Message} Message Content of compressed message. + */ + unwrapCompressed() { + const compressed = this.packets.filterByTag(enums.packet.compressedData); + if (compressed.length) { + return new Message(compressed[0].packets); + } + return this; + } + + /** + * Append signature to unencrypted message object + * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async appendSignature(detachedSignature, config$1 = config) { + await this.packets.read( + util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, + allowedDetachedSignaturePackets, + config$1 + ); + } + + /** + * Returns binary encoded message + * @returns {ReadableStream} Binary message. + */ + write() { + return this.packets.write(); + } + + /** + * Returns ASCII armored text of message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + const trailingPacket = this.packets[this.packets.length - 1]; + // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer. + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ? + trailingPacket.version !== 2 : + this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1); + } +} + +/** + * Create signature packets for the message + * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign + * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing + * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to append + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creationtime of the signature + * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures + * @param {Boolean} [detached] - Whether to create detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} List of signature packets. + * @async + * @private + */ +async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) { + const packetlist = new PacketList(); + + // If data packet was created from Uint8Array, use binary, otherwise use text + const signatureType = literalDataPacket.text === null ? + enums.signature.binary : enums.signature.text; + + await Promise.all(signingKeys.map(async (primaryKey, i) => { + const signingUserID = signingUserIDs[i]; + if (!primaryKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1); + return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1); + })).then(signatureList => { + packetlist.push(...signatureList); + }); + + if (signature) { + const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + packetlist.push(...existingSigPacketlist); + } + return packetlist; +} + +/** + * Create object containing signer's keyID and validity of signature + * @param {SignaturePacket} signature - Signature packet + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Check signature validity with respect to the given date + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * keyID: module:type/keyid~KeyID, + * signature: Promise, + * verified: Promise + * }>} signer's keyID and validity of signature + * @async + * @private + */ +async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + let primaryKey; + let unverifiedSigningKey; + + for (const key of verificationKeys) { + const issuerKeys = key.getKeys(signature.issuerKeyID); + if (issuerKeys.length > 0) { + primaryKey = key; + unverifiedSigningKey = issuerKeys[0]; + break; + } + } + + const isOnePassSignature = signature instanceof OnePassSignaturePacket; + const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; + + const verifiedSig = { + keyID: signature.issuerKeyID, + verified: (async () => { + if (!unverifiedSigningKey) { + throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + } + + await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); + const signaturePacket = await signaturePacketPromise; + if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { + throw new Error('Key is newer than the signature'); + } + // We pass the signature creation time to check whether the key was expired at the time of signing. + // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before + try { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); + } catch (e) { + // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, + // making the key invalid at the time of signing. + // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. + // Note: we do not support the edge case of a key that was reformatted and it has expired. + if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + } else { + throw e; + } + } + return true; + })(), + signature: (async () => { + const signaturePacket = await signaturePacketPromise; + const packetlist = new PacketList(); + signaturePacket && packetlist.push(signaturePacket); + return new Signature(packetlist); + })() + }; + + // Mark potential promise rejections as "handled". This is needed because in + // some cases, we reject them before the user has a reasonable chance to + // handle them (e.g. `await readToEnd(result.data); await result.verified` and + // the data stream errors). + verifiedSig.signature.catch(() => {}); + verifiedSig.verified.catch(() => {}); + + return verifiedSig; +} + +/** + * Create list of objects containing signer's keyID and validity of signature + * @param {Array} signatureList - Array of signature packets + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} date - Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) + * @async + * @private + */ +async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + return Promise.all(signatureList.filter(function(signature) { + return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); + }).map(async function(signature) { + return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); + })); +} + +/** + * Reads an (optionally armored) OpenPGP message and returns a Message object + * @param {Object} options + * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed + * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New message object. + * @async + * @static + */ +async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredMessage || binaryMessage; + if (!input) { + throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); + } + if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { + throw new Error('readMessage: options.armoredMessage must be a string or stream'); + } + if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { + throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + const streamType = util.isStream(input); + if (armoredMessage) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.message) { + throw new Error('Armored text not of type message'); + } + input = data; + } + const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); + const message = new Message(packetlist); + message.fromStream = streamType; + return message; +} + +/** + * Creates new message object from text or binary data. + * @param {Object} options + * @param {String | ReadableStream} [options.text] - The text message contents + * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents + * @param {String} [options.filename=""] - Name of the file (if any) + * @param {Date} [options.date=current date] - Date of the message, or modification date of the file + * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type + * @returns {Promise} New message object. + * @async + * @static + */ +async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { + const input = text !== undefined ? text : binary; + if (input === undefined) { + throw new Error('createMessage: must pass options object containing `text` or `binary`'); + } + if (text && !util.isString(text) && !util.isStream(text)) { + throw new Error('createMessage: options.text must be a string or stream'); + } + if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { + throw new Error('createMessage: options.binary must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + const streamType = util.isStream(input); + const literalDataPacket = new LiteralDataPacket(date); + if (text !== undefined) { + literalDataPacket.setText(input, enums.write(enums.literal, format)); + } else { + literalDataPacket.setBytes(input, enums.write(enums.literal, format)); + } + if (filename !== undefined) { + literalDataPacket.setFilename(filename); + } + const literalDataPacketlist = new PacketList(); + literalDataPacketlist.push(literalDataPacket); + const message = new Message(literalDataPacketlist); + message.fromStream = streamType; + return message; +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Cleartext message can contain the following packets +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + +/** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ +class CleartextMessage { + /** + * @param {String} text - The cleartext of the signed message + * @param {Signature} signature - The detached signature or an empty signature for unsigned messages + */ + constructor(text, signature) { + // remove trailing whitespace and normalize EOL to canonical form + this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); + if (signature && !(signature instanceof Signature)) { + throw new Error('Invalid signature input'); + } + this.signature = signature || new Signature(new PacketList()); + } + + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const keyIDs = []; + const signatureList = this.signature.packets; + signatureList.forEach(function(packet) { + keyIDs.push(packet.issuerKeyID); + }); + return keyIDs; + } + + /** + * Sign the cleartext message + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] + * @param {Date} [date] - The creation time of the signature that should be created + * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New cleartext message with signed content. + * @async + */ + async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const literalDataPacket = new LiteralDataPacket(); + literalDataPacket.setText(this.text); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1)); + return new CleartextMessage(this.text, newSignature); + } + + /** + * Verify signatures of cleartext signed message + * @param {Array} keys - Array of keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verify(keys, date = new Date(), config$1 = config) { + const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + const literalDataPacket = new LiteralDataPacket(); + // we assume that cleartext signature is generated based on UTF8 cleartext + literalDataPacket.setText(this.text); + return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + } + + /** + * Get cleartext + * @returns {String} Cleartext of message. + */ + getText() { + // normalize end of line to \n + return this.text.replace(/\r\n/g, '\n'); + } + + /** + * Returns ASCII armored text of cleartext signed message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {String | ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // emit header and checksum if one of the signatures has a version not 6 + const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6); + const hash = emitHeaderAndChecksum ? + Array.from(new Set(this.signature.packets.map( + packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase() + ))).join() : + null; + + const body = { + hash, + text: this.text, + data: this.signature.packets.write() + }; + + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1); + } +} + +/** + * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param {Object} options + * @param {String} options.cleartextMessage - Text to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New cleartext message object. + * @async + * @static + */ +async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!cleartextMessage) { + throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); + } + if (!util.isString(cleartextMessage)) { + throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + const input = await unarmor(cleartextMessage); + if (input.type !== enums.armor.signed) { + throw new Error('No cleartext signed message.'); + } + const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1); + verifyHeaders(input.headers, packetlist); + const signature = new Signature(packetlist); + return new CleartextMessage(input.text, signature); +} + +/** + * Compare hash algorithm specified in the armor header with signatures + * @param {Array} headers - Armor headers + * @param {PacketList} packetlist - The packetlist with signature packets + * @private + */ +function verifyHeaders(headers, packetlist) { + const checkHashAlgos = function(hashAlgos) { + const check = packet => algo => packet.hashAlgorithm === algo; + + for (let i = 0; i < packetlist.length; i++) { + if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { + return false; + } + } + return true; + }; + + const hashAlgos = []; + headers.forEach(header => { + const hashHeader = header.match(/^Hash: (.+)$/); // get header value + if (hashHeader) { + const parsedHashIDs = hashHeader[1] + .replace(/\s/g, '') // remove whitespace + .split(',') + .map(hashName => { + try { + return enums.write(enums.hash, hashName.toLowerCase()); + } catch (e) { + throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase()); + } + }); + hashAlgos.push(...parsedHashIDs); + } else { + throw new Error('Only "Hash" header allowed in cleartext signed message'); + } + }); + + if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { + throw new Error('Hash algorithm mismatch in armor header and signature'); + } +} + +/** + * Creates a new CleartextMessage object from text + * @param {Object} options + * @param {String} options.text + * @static + * @async + */ +async function createCleartextMessage({ text, ...rest }) { + if (!text) { + throw new Error('createCleartextMessage: must pass options object containing `text`'); + } + if (!util.isString(text)) { + throw new Error('createCleartextMessage: options.text must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + return new CleartextMessage(text); +} + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + +////////////////////// +// // +// Key handling // +// // +////////////////////// + + +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. + * @param {Object} options + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys). + * Note: Curve448 and Curve25519 (new format) are not widely supported yet. + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys + * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys: + * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 + * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` + * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + if (!type && !curve) { + type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them) + curve = 'curve25519Legacy'; // unused with type != 'ecc' + } else { + type = type || 'ecc'; + curve = curve || 'curve25519Legacy'; + } + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (userIDs.length === 0 && !config$1.v6Keys) { + throw new Error('UserIDs are required for V4 keys'); + } + if (type === 'rsa' && rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + } + + const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; + + try { + const { key, revocationCertificate } = await generate(options, config$1); + key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); + + return { + privateKey: formatObject(key, format, config$1), + publicKey: formatObject(key.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error generating keypair', err); + } +} + +/** + * Reformats signature packets for a key and rewraps key object. + * @param {Object} options + * @param {PrivateKey} options.privateKey - Private key to reformat + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended + * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) { + throw new Error('UserIDs are required for V4 keys'); + } + const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; + + try { + const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); + + return { + privateKey: formatObject(reformattedKey, format, config$1), + publicKey: formatObject(reformattedKey.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error reformatting keypair', err); + } +} + +/** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. + * @param {Object} options + * @param {Key} options.key - Public or private key to revoke + * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with + * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation + * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation + * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The revoked key in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or + * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise + * @async + * @static + */ +async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + try { + const revokedKey = revocationCertificate ? + await key.applyRevocationCertificate(revocationCertificate, date, config$1) : + await key.revoke(reasonForRevocation, date, config$1); + + return revokedKey.isPrivate() ? { + privateKey: formatObject(revokedKey, format, config$1), + publicKey: formatObject(revokedKey.toPublic(), format, config$1) + } : { + privateKey: null, + publicKey: formatObject(revokedKey, format, config$1) + }; + } catch (err) { + throw util.wrapError('Error revoking key', err); + } +} + +/** + * Unlock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to decrypt + * @param {String|Array} options.passphrase - The user's passphrase(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The unlocked key object. + * @async + */ +async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (!privateKey.isPrivate()) { + throw new Error('Cannot decrypt a public key'); + } + const clonedPrivateKey = privateKey.clone(true); + const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; + + try { + await Promise.all(clonedPrivateKey.getKeys().map(key => ( + // try to decrypt each key with any of the given passphrases + util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) + ))); + + await clonedPrivateKey.validate(config$1); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error decrypting private key', err); + } +} + +/** + * Lock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to encrypt + * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The locked key object. + * @async + */ +async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (!privateKey.isPrivate()) { + throw new Error('Cannot encrypt a public key'); + } + const clonedPrivateKey = privateKey.clone(true); + + const keys = clonedPrivateKey.getKeys(); + const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); + if (passphrases.length !== keys.length) { + throw new Error('Invalid number of passphrases given for key encryption'); + } + + try { + await Promise.all(keys.map(async (key, i) => { + const { keyPacket } = key; + await keyPacket.encrypt(passphrases[i], config$1); + keyPacket.clearPrivateParams(); + })); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error encrypting private key', err); + } +} + + +/////////////////////////////////////////// +// // +// Message encryption and decryption // +// // +/////////////////////////////////////////// + + +/** + * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` + * must be specified. If signing keys are specified, those will be used to sign the message. + * @param {Object} options + * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message + * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed + * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message + * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Signature} [options.signature] - A detached signature to add to the encrypted message + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` + * @param {Date} [options.date=current date] - Override the creation date of the message signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords); + signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations); + if (rest.detached) { + throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); + } + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (!signingKeys) { + signingKeys = []; + } + + try { + if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified + message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1); + } + message = message.compress( + await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), + config$1 + ); + message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + if (format === 'object') return message; + // serialize data + const armor = format === 'armored'; + const data = armor ? message.armor(config$1) : message.write(); + return await convertStream(data); + } catch (err) { + throw util.wrapError('Error encrypting message', err); + } +} + +/** + * Decrypts a message with the user's private key, a session key or a password. + * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). + * @param {Object} options + * @param {Message} options.message - The message object with the encrypted data + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key + * @param {String|String[]} [options.passwords] - Passwords to decrypt the message + * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } + * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing decrypted and verified message in the form: + * + * { + * data: MaybeStream, (if format was 'utf8', the default) + * data: MaybeStream, (if format was 'binary') + * filename: String, + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static + */ +async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + try { + const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); + if (!verificationKeys) { + verificationKeys = []; + } + + const result = {}; + result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); + result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); + result.filename = decrypted.getFilename(); + linkStreams(result, message); + if (expectSigned) { + if (verificationKeys.length === 0) { + throw new Error('Verification keys are required to verify message signatures'); + } + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error decrypting message', err); + } +} + + +////////////////////////////////////////// +// // +// Message signing and verification // +// // +////////////////////////////////////////// + + +/** + * Signs a message. + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed + * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext + * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [options.date=current date] - Override the creation date of the signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); checkOutputMessageFormat(format); + signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations); + + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); + if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); + + if (!signingKeys || signingKeys.length === 0) { + throw new Error('No signing keys provided'); + } + + try { + let signature; + if (detached) { + signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } else { + signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } + if (format === 'object') return signature; + + const armor = format === 'armored'; + signature = armor ? signature.armor(config$1) : signature.write(); + if (detached) { + signature = transformPair(message.packets.write(), async (readable, writable) => { + await Promise.all([ + pipe(signature, writable), + readToEnd(readable).catch(() => {}) + ]); + }); + } + return await convertStream(signature); + } catch (err) { + throw util.wrapError('Error signing message', err); + } +} + +/** + * Verifies signatures of cleartext signed message + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures + * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing verified message in the form: + * + * { + * data: MaybeStream, (if `message` was a CleartextMessage) + * data: MaybeStream, (if `message` was a Message) + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static + */ +async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); + if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); + + try { + const result = {}; + if (signature) { + result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); + } else { + result.signatures = await message.verify(verificationKeys, date, config$1); + } + result.data = format === 'binary' ? message.getLiteralData() : message.getText(); + if (message.fromStream && !signature) linkStreams(result, message); + if (expectSigned) { + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error verifying signed message', err); + } +} + + +/////////////////////////////////////////////// +// // +// Session key encryption and decryption // +// // +/////////////////////////////////////////////// + +/** + * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. + * @param {Object} options + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} + * @param {Date} [options.date=current date] - Date to select algorithm preferences at + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. + * @async + * @static + */ +async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + try { + const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error generating session key', err); + } +} + +/** + * Encrypt a symmetric session key with public keys, passwords, or both at once. + * At least one of `encryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) + * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key + * @param {String|String[]} [options.passwords] - Passwords for the message + * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [options.date=current date] - Override the date + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { + throw new Error('No encryption keys or passwords provided.'); + } + + try { + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + return formatObject(message, format, config$1); + } catch (err) { + throw util.wrapError('Error encrypting session key', err); + } +} + +/** + * Decrypt symmetric session keys using private keys or passwords (not both). + * One of `decryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Message} options.message - A message object containing the encrypted session key packets + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data + * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key + * @param {Date} [options.date] - Date to use for key verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: + * { data:Uint8Array, algorithm:String } + * @throws if no session key could be found or decrypted + * @async + * @static + */ +async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + try { + const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error decrypting session keys', err); + } +} + + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + + +/** + * Input validation + * @private + */ +function checkString(data, name) { + if (!util.isString(data)) { + throw new Error('Parameter [' + (name) + '] must be of type String'); + } +} +function checkBinary(data, name) { + if (!util.isUint8Array(data)) { + throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array'); + } +} +function checkMessage(message) { + if (!(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message'); + } +} +function checkCleartextOrMessage(message) { + if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); + } +} +function checkOutputMessageFormat(format) { + if (format !== 'armored' && format !== 'binary' && format !== 'object') { + throw new Error(`Unsupported format ${format}`); + } +} +const defaultConfigPropsCount = Object.keys(config).length; +function checkConfig(config$1) { + const inputConfigProps = Object.keys(config$1); + if (inputConfigProps.length !== defaultConfigPropsCount) { + for (const inputProp of inputConfigProps) { + if (config[inputProp] === undefined) { + throw new Error(`Unknown config property: ${inputProp}`); + } + } + } +} + +/** + * Normalize parameter to an array if it is not undefined. + * @param {Object} param - the parameter to be normalized + * @returns {Array|undefined} The resulting array or undefined. + * @private + */ +function toArray(param) { + if (param && !util.isArray(param)) { + param = [param]; + } + return param; +} + +/** + * Convert data to or from Stream + * @param {Object} data - the data to convert + * @returns {Promise} The data in the respective format. + * @async + * @private + */ +async function convertStream(data) { + const streamType = util.isStream(data); + if (streamType === 'array') { + return readToEnd(data); + } + return data; +} + +/** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param {Object} result - the data to convert + * @param {Message} message - message object + * @returns {Object} + * @private + */ +function linkStreams(result, message) { + result.data = transformPair(message.packets.stream, async (readable, writable) => { + await pipe(result.data, writable, { + preventClose: true + }); + const writer = getWriter(writable); + try { + // Forward errors in the message stream to result.data. + await readToEnd(readable, _ => _); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + }); +} + +/** + * Convert the object to the given format + * @param {Key|Message} object + * @param {'armored'|'binary'|'object'} format + * @param {Object} config - Full configuration + * @returns {String|Uint8Array|Object} + */ +function formatObject(object, format, config) { + switch (format) { + case 'object': + return object; + case 'armored': + return object.armor(config); + case 'binary': + return object.write(); + default: + throw new Error(`Unsupported format ${format}`); + } +} + +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +// copied from utils +function isBytes$1(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes$1(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 +// See utils.ts for details. +// @ts-ignore +const crypto$1 = nc__namespace && typeof nc__namespace === 'object' && 'webcrypto' in nc__namespace + ? nc__namespace.webcrypto + : nc__namespace && typeof nc__namespace === 'object' && 'randomBytes' in nc__namespace + ? nc__namespace + : undefined; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$1(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes$1(data); + bytes(data); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$1(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto$1 && typeof crypto$1.randomBytes === 'function') { + return crypto$1.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} + +/** + * Polyfill for Safari 14 + */ +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +/** + * Choice: a ? b : c + */ +const Chi = (a, b, c) => (a & b) ^ (~a & c); +/** + * Majority function, true if any two inputs is true + */ +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); + +// HMAC (RFC 2104) +class HMAC extends Hash { + constructor(hash$1, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash$1.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + * @example + * import { hmac } from '@noble/hashes/hmac'; + * import { sha256 } from '@noble/hashes/sha2'; + * const mac1 = hmac(sha256, 'key', 'message'); + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n$6 = /* @__PURE__ */ BigInt(0); +const _1n$8 = /* @__PURE__ */ BigInt(1); +const _2n$5 = /* @__PURE__ */ BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Is positive bigint +const isPosBig = (n) => typeof n === 'bigint' && _0n$6 <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +/** + * Asserts min <= n < max. NOTE: It's < max and not <= max. + * @example + * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) + */ +function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n$6; n >>= _1n$8, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n$8; +} +/** + * Sets single bit at position. + */ +function bitSet(n, pos, value) { + return n | ((value ? _1n$8 : _0n$6) << BigInt(pos)); +} +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n$5 << BigInt(n - 1)) - _1n$8; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +/** + * throws not implemented error + */ +const notImplemented = () => { + throw new Error('not implemented'); +}; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +function memoized(fn) { + const map = new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} + +var ut = /*#__PURE__*/Object.freeze({ + __proto__: null, + aInRange: aInRange, + abool: abool, + abytes: abytes, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + inRange: inRange, + isBytes: isBytes, + memoized: memoized, + notImplemented: notImplemented, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject +}); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +// prettier-ignore +const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$4 = BigInt(2), _3n$2 = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n$1 = BigInt(8); +// prettier-ignore +BigInt(9); BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n$5 ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n$5 || power < _0n$5) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n$7) + return _0n$5; + let res = _1n$7; + while (power > _0n$5) { + if (power & _1n$7) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n$7; + } + return res; +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$5) { + res *= res; + res %= modulo; + } + return res; +} +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n$5 || modulo <= _0n$5) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n$5, u = _1n$7; + while (a !== _0n$5) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + // prettier-ignore + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$7) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n$7) / _2n$4; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n$7, S = 0; Q % _2n$4 === _0n$5; Q /= _2n$4, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n$4; Z < P && pow(Z, legendreC, P) !== P - _1n$7; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n$7) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n$7) / _2n$4; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n$7 << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n$2) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n$7) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n$1 === _5n) { + const c1 = (P - _5n) / _8n$1; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$4); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$4), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n$5) + throw new Error('Expected power > 0'); + if (power === _0n$5) + return f.ONE; + if (power === _1n$7) + return num; + let p = f.ONE; + let d = num; + while (power > _0n$5) { + if (power & _1n$7) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$7; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * NOTE: operations don't check 'isValid' for all elements for performance reasons, + * it is caller responsibility to check this. + * This is low-level code, please make sure you know what you doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$5) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$5, + ONE: _1n$7, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$5 <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n$5, + isOdd: (num) => (num & _1n$7) === _1n$7, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n$7) + _1n$7; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const _0n$4 = BigInt(0); +const _1n$6 = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$4) { + if (n & _1n$6) + p = p.add(d); + d = d.double(); + n >>= _1n$6; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$6; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c Curve Point constructor + * @param field field over CURVE.N - important that it's not over CURVE.P + * @param points array of L curve points + * @param scalars array of L scalars (aka private keys / bigints) + */ +function pippenger(c, field, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.ZERO; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html + */ +const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 128) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 127; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n$3) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected assertion'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 128)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + abytes(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + return tlv.encode(0x30, seq); + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$3 = BigInt(0), _1n$5 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return inRange(num, _1n$5, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (isBytes(key)) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, N); // disabled by default, enabled for BLS + aInRange('private key', num, _1n$5, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // Memoized toAffine / validity check. They are heavy. Points are immutable. + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p) => { + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n$1); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + aInRange('scalar', sc, _0n$3, CURVE.n); + const I = Point.ZERO; + if (sc === _0n$3) + return I; + if (sc === _1n$5) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$3 || k2 > _0n$3) { + if (k1 & _1n$5) + k1p = k1p.add(d); + if (k2 & _1n$5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$5; + k2 >>= _1n$5; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange('scalar', scalar, _1n$5, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n$3 || a === _1n$5 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$5) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$5) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; +} +function validateOpts$2(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +function weierstrass(curveDef) { + const CURVE = validateOpts$2(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n$5, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n$5) === _1n$5; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$5; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + // slice bytes num + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange('r', this.r, _1n$5, CURVE_ORDER); // r in [1..N] + aInRange('s', this.s, _1n$5, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$3, ORDER_MASK); + // works with order, can have different size than numToField! + return numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n$3) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n$3) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$5); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), + randomBytes, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp$7 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A$4 = Fp$7.create(BigInt('-3')); +const CURVE_B$4 = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +const p256 = createCurve({ + a: CURVE_A$4, // Equation params: a, b + b: CURVE_B$4, + Fp: Fp$7, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp$6 = Field(P$1); +const CURVE_A$3 = Fp$6.create(BigInt('-3')); +// prettier-ignore +const CURVE_B$3 = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +const p384 = createCurve({ + a: CURVE_A$3, // Equation params: a, b + b: CURVE_B$3, + Fp: Fp$6, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp$5 = Field(P); +const CURVE = { + a: Fp$5.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp: Fp$5, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp: Fp$5, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n$2 = /* @__PURE__ */ BigInt(0); +const _1n$4 = /* @__PURE__ */ BigInt(1); +const _2n$3 = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n$2; + for (let j = 0; j < 7; j++) { + R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n$3) + t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts$1(curve) { + const opts = validateBasic(curve); + validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +function twistedEdwards(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n$1 }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + aInRange('coordinate ' + title, n, _0n$1, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n$1, y: _1n$3 }; + if (zz !== _1n$3) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n$3, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n$2 * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n$1) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n$2 * T2); + const D = modP(T1 * _2n$2 * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n$1) + return I; + if (this.equals(I) || n === _1n$3) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n$3) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('pointHex.y', y, _0n$1, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n$3); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n$3) === _1n$3; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n$1 && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n$1, _1n$3, _1n$3, _0n$1); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l + const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n = BigInt(0); +const _1n$2 = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n$2; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n$2; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n$2; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n$1, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n$1, P) * b2) % P; + const b223 = (pow2(b222, _1n$1, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp$4 = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp: Fp$4, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes$1(utf8ToBytes$1('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +/* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +(Fp$4.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +BigInt(156326); +// 1-d +BigInt('39082'); +// 1-2d +BigInt('78163'); +// √(-d) +BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp$3.eql(Fp$3.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp$3 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$3, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +BigInt(0); +secp256k1.ProjectivePoint; + +// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4 +// eslint-disable-next-line new-cap +const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377')); +const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9')); +const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'); +// prettier-ignore +const brainpoolP256r1 = createCurve({ + a: CURVE_A$2, // Equation params: a, b + b: CURVE_B$2, + Fp: Fp$2, + // Curve order (q), total count of valid points in the field + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + // Base (generator) point (x, y) + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), + lowS: false +}, sha256); + +// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6 +// eslint-disable-next-line new-cap +const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53')); +const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826')); +const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'); +// prettier-ignore +const brainpoolP384r1 = createCurve({ + a: CURVE_A$1, // Equation params: a, b + b: CURVE_B$1, + Fp: Fp$1, + // Curve order (q), total count of valid points in the field + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + // Base (generator) point (x, y) + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), + lowS: false +}, sha384); + +// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7 +// eslint-disable-next-line new-cap +const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3')); +const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca')); +const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'); +// prettier-ignore +const brainpoolP512r1 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, + // Curve order (q), total count of valid points in the field + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + // Base (generator) point (x, y) + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), + lowS: false +}, sha512); + +/** + * This file is needed to dynamic import the noble-curves. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleCurves = new Map(Object.entries({ + nistP256: p256, + nistP384: p384, + nistP521: p521, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, + secp256k1, + x448, + ed448 +})); + +var noble_curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleCurves: nobleCurves +}); + +//Paul Tero, July 2001 +//http://www.tero.co.uk/des/ +// +//Optimised for performance with large blocks by Michael Hayworth, November 2001 +//http://www.netdealing.com +// +// Modified by Recurity Labs GmbH + +//THIS SOFTWARE IS PROVIDED "AS IS" AND +//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +//SUCH DAMAGE. + +//des +//this takes the key, the message, and whether to encrypt or decrypt + +function des(keys, message, encrypt, mode, iv, padding) { + //declaring this locally speeds things up a bit + const spfunction1 = [ + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, + 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, + 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, + 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ]; + const spfunction2 = [ + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, + -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, + -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, + -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, + 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, + -0x7fef7fe0, 0x108000 + ]; + const spfunction3 = [ + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, + 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, + 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, + 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ]; + const spfunction4 = [ + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, + 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, + 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ]; + const spfunction5 = [ + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, + 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, + 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, + 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, + 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, + 0x40080000, 0x2080100, 0x40000100 + ]; + const spfunction6 = [ + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, + 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, + 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, + 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ]; + const spfunction7 = [ + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, + 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, + 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, + 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ]; + const spfunction8 = [ + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, + 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, + 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, + 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ]; + + //create the 16 or 48 subkeys we will need + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let endloop; + let loopinc; + let len = message.length; + + //set up the loops for single and triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des + if (iterations === 3) { + looping = encrypt ? [0, 32, 2] : [30, -2, -2]; + } else { + looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; + } + + //pad the message depending on the padding parameter + //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt + if (encrypt) { + message = desAddPadding(message); + len = message.length; + } + + //store the result here + let result = new Uint8Array(len); + let k = 0; + + //loop through each 64 bit chunk of the message + while (m < len) { + left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + + //first each 64 but chunk of the message must be permuted according to IP + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + //do this either 1 or 3 times for each chunk of the message + for (j = 0; j < iterations; j += 3) { + endloop = looping[j + 1]; + loopinc = looping[j + 2]; + //now go through and perform the encryption or decryption + for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency + right1 = right ^ keys[i]; + right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + //the result is attained by passing these bytes through the S selection functions + temp = left; + left = right; + right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> + 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & + 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); + } + temp = left; + left = right; + right = temp; //unreverse left and right + } //for either 1 or 3 iterations + + //move then each one bit to the right + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + //now perform IP-1, which is IP in the opposite direction + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + + result[k++] = (left >>> 24); + result[k++] = ((left >>> 16) & 0xff); + result[k++] = ((left >>> 8) & 0xff); + result[k++] = (left & 0xff); + result[k++] = (right >>> 24); + result[k++] = ((right >>> 16) & 0xff); + result[k++] = ((right >>> 8) & 0xff); + result[k++] = (right & 0xff); + } //for every 8 characters, or 64 bits in the message + + //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt + if (!encrypt) { + result = desRemovePadding(result); + } + + return result; +} //end of des + + +//desCreateKeys +//this takes as input a 64 bit key (even though only 56 bits are used) +//as an array of 2 integers, and returns 16 48 bit keys + +function desCreateKeys(key) { + //declaring this locally speeds things up a bit + const pc2bytes0 = [ + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ]; + const pc2bytes1 = [ + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ]; + const pc2bytes2 = [ + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ]; + const pc2bytes3 = [ + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ]; + const pc2bytes4 = [ + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ]; + const pc2bytes5 = [ + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ]; + const pc2bytes6 = [ + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ]; + const pc2bytes7 = [ + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ]; + const pc2bytes8 = [ + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ]; + const pc2bytes9 = [ + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ]; + const pc2bytes10 = [ + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ]; + const pc2bytes11 = [ + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ]; + const pc2bytes12 = [ + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ]; + const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; + + //how many iterations (1 for des, 3 for triple des) + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + //stores the return keys + const keys = new Array(32 * iterations); + //now define the left shifts which need to be done + const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + //other variables + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; + + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 2) ^ right) & 0x33333333; + right ^= temp; + left ^= (temp << 2); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + + //the right side needs to be shifted and to get the last four bits of the left side + temp = (left << 8) | ((right >>> 20) & 0x000000f0); + //left needs to be put upside down + left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); + right = temp; + + //now go through and perform these shifts on the left and right keys + for (let i = 0; i < shifts.length; i++) { + //shift the keys either one or two bits to the left + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + //now apply PC-2, in such a way that E is easier when encrypting or decrypting + //this conversion will look like PC-2 except only the last 6 bits of each byte are used + //rather than 48 consecutive bits and the order of lines will be according to + //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 + lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( + left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & + 0xf]; + righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | + pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]; + temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; + keys[n++] = lefttemp ^ temp; + keys[n++] = righttemp ^ (temp << 16); + } + } //for each iterations + //return the keys we've created + return keys; +} //end of desCreateKeys + + +function desAddPadding(message, padding) { + const padLength = 8 - (message.length % 8); + + let pad; + if ((padLength < 8)) { //pad the message out with null bytes + pad = 0; + } else if (padLength === 8) { + return message; + } else { + throw new Error('des: invalid padding'); + } + + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { + paddedMessage[i] = message[i]; + } + for (let j = 0; j < padLength; j++) { + paddedMessage[message.length + j] = pad; + } + + return paddedMessage; +} + +function desRemovePadding(message, padding) { + let padLength = null; + let pad; + { // null padding + pad = 0; + } + + if (!padLength) { + padLength = 1; + while (message[message.length - padLength] === pad) { + padLength++; + } + padLength--; + } + + return message.subarray(0, message.length - padLength); +} + +// added by Recurity Labs + +function TripleDES(key) { + this.key = []; + + for (let i = 0; i < 3; i++) { + this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); + } + + this.encrypt = function(block) { + return des( + desCreateKeys(this.key[2]), + des( + desCreateKeys(this.key[1]), + des( + desCreateKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true); + }; +} + +TripleDES.keySize = TripleDES.prototype.keySize = 24; +TripleDES.blockSize = TripleDES.prototype.blockSize = 8; + +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Copyright 2010 pjacobs@xeekr.com . All rights reserved. + +// Modified by Recurity Labs GmbH + +// fixed/modified by Herbert Hanewinkel, www.haneWIN.de +// check www.haneWIN.de for the latest version + +// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. +// CAST-128 is a common OpenPGP cipher. + + +// CAST5 constructor + +function OpenPGPSymEncCAST5() { + this.BlockSize = 8; + this.KeySize = 16; + + this.setKey = function(key) { + this.masking = new Array(16); + this.rotate = new Array(16); + + this.reset(); + + if (key.length === this.KeySize) { + this.keySchedule(key); + } else { + throw new Error('CAST-128: keys must be 16 bytes'); + } + return true; + }; + + this.reset = function() { + for (let i = 0; i < 16; i++) { + this.masking[i] = 0; + this.rotate[i] = 0; + } + }; + + this.getBlockSize = function() { + return this.BlockSize; + }; + + this.encrypt = function(src) { + const dst = new Array(src.length); + + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; + + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >>> 16) & 255; + dst[i + 6] = (l >>> 8) & 255; + dst[i + 7] = l & 255; + } + + return dst; + }; + + this.decrypt = function(src) { + const dst = new Array(src.length); + + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; + + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >> 16) & 255; + dst[i + 6] = (l >> 8) & 255; + dst[i + 7] = l & 255; + } + + return dst; + }; + const scheduleA = new Array(4); + + scheduleA[0] = new Array(4); + scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; + scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + + scheduleA[1] = new Array(4); + scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + + scheduleA[2] = new Array(4); + scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; + scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + + + scheduleA[3] = new Array(4); + scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + + const scheduleB = new Array(4); + + scheduleB[0] = new Array(4); + scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; + scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; + scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; + scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; + + scheduleB[1] = new Array(4); + scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; + scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; + scheduleB[1][2] = [7, 6, 8, 9, 3]; + scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; + + + scheduleB[2] = new Array(4); + scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; + scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; + scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; + scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; + + + scheduleB[3] = new Array(4); + scheduleB[3][0] = [8, 9, 7, 6, 3]; + scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; + scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; + scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; + + // changed 'in' to 'inn' (in javascript 'in' is a reserved word) + this.keySchedule = function(inn) { + const t = new Array(8); + const k = new Array(32); + + let j; + + for (let i = 0; i < 4; i++) { + j = i * 4; + t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + } + + const x = [6, 7, 4, 5]; + let ki = 0; + let w; + + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { + for (j = 0; j < 4; j++) { + const a = scheduleA[round][j]; + w = t[a[1]]; + + w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; + w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; + w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; + w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; + w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; + t[a[0]] = w; + } + + for (j = 0; j < 4; j++) { + const b = scheduleB[round][j]; + w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; + + w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; + w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; + w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; + w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; + k[ki] = w; + ki++; + } + } + } + + for (let i = 0; i < 16; i++) { + this.masking[i] = k[i]; + this.rotate[i] = k[16 + i] & 0x1f; + } + }; + + // These are the three 'f' functions. See RFC 2144, section 2.2. + + function f1(d, m, r) { + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; + } + + function f2(d, m, r) { + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; + } + + function f3(d, m, r) { + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; + } + + const sBox = new Array(8); + sBox[0] = [ + 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, + 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, + 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, + 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, + 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, + 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, + 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, + 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, + 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, + 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, + 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, + 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, + 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, + 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, + 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, + 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, + 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, + 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, + 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, + 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, + 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, + 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, + 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, + 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, + 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, + 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, + 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, + 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, + 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, + 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, + 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ]; + + sBox[1] = [ + 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, + 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, + 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, + 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, + 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, + 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, + 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, + 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, + 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, + 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, + 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, + 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, + 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, + 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, + 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, + 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, + 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, + 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, + 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, + 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, + 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, + 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, + 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, + 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, + 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, + 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, + 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, + 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, + 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, + 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, + 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ]; + + sBox[2] = [ + 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, + 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, + 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, + 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, + 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, + 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, + 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, + 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, + 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, + 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, + 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, + 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, + 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, + 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, + 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, + 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, + 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, + 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, + 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, + 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, + 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, + 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, + 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, + 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, + 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, + 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, + 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, + 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, + 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, + 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, + 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ]; + + sBox[3] = [ + 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, + 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, + 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, + 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, + 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, + 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, + 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, + 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, + 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, + 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, + 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, + 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, + 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, + 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, + 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, + 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, + 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, + 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, + 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, + 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, + 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, + 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, + 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, + 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, + 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, + 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, + 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, + 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, + 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, + 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, + 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ]; + + sBox[4] = [ + 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, + 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, + 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, + 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, + 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, + 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, + 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, + 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, + 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, + 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, + 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, + 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, + 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, + 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, + 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, + 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, + 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, + 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, + 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, + 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, + 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, + 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, + 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, + 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, + 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, + 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, + 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, + 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, + 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, + 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, + 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ]; + + sBox[5] = [ + 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, + 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, + 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, + 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, + 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, + 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, + 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, + 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, + 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, + 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, + 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, + 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, + 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, + 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, + 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, + 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, + 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, + 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, + 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, + 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, + 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, + 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, + 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, + 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, + 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, + 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, + 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, + 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, + 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, + 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, + 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ]; + + sBox[6] = [ + 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, + 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, + 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, + 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, + 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, + 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, + 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, + 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, + 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, + 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, + 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, + 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, + 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, + 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, + 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, + 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, + 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, + 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, + 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, + 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, + 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, + 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, + 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, + 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, + 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, + 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, + 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, + 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, + 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, + 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, + 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ]; + + sBox[7] = [ + 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, + 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, + 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, + 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, + 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, + 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, + 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, + 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, + 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, + 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, + 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, + 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, + 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, + 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, + 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, + 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, + 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, + 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, + 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, + 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, + 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, + 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, + 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, + 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, + 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, + 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, + 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, + 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, + 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, + 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, + 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ]; +} + +function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); + this.cast5.setKey(key); + + this.encrypt = function(block) { + return this.cast5.encrypt(block); + }; +} + +CAST5.blockSize = CAST5.prototype.blockSize = 8; +CAST5.keySize = CAST5.prototype.keySize = 16; + +/* eslint-disable no-mixed-operators, no-fallthrough */ + + +/* Modified by Recurity Labs GmbH + * + * Cipher.js + * A block-cipher algorithm implementation on JavaScript + * See Cipher.readme.txt for further information. + * + * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] + * This script file is distributed under the LGPL + * + * ACKNOWLEDGMENT + * + * The main subroutines are written by Michiel van Everdingen. + * + * Michiel van Everdingen + * http://home.versatel.nl/MAvanEverdingen/index.html + * + * All rights for these routines are reserved to Michiel van Everdingen. + * + */ + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//Math +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +const MAXINT = 0xFFFFFFFF; + +function rotw(w, n) { + return (w << n | w >>> (32 - n)) & MAXINT; +} + +function getW(a, i) { + return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +} + +function setW(a, i, w) { + a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +} + +function getB(x, n) { + return (x >>> (n * 8)) & 0xFF; +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Twofish +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +function createTwofish() { + // + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; + // var dataLength = -1; + // var idx2 = -1; + // + + let tfsKey = []; + let tfsM = [ + [], + [], + [], + [] + ]; + + function tfsInit(key) { + keyBytes = key; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; + + const q0 = [ + [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], + [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] + ]; + const q1 = [ + [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], + [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] + ]; + const q2 = [ + [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], + [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] + ]; + const q3 = [ + [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], + [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] + ]; + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ + [], + [] + ]; + const m = [ + [], + [], + [], + [] + ]; + + function ffm5b(x) { + return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + } + + function ffmEf(x) { + return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + } + + function mdsRem(p, q) { + let i; + let t; + let u; + for (i = 0; i < 8; i++) { + t = q >>> 24; + q = ((q << 8) & MAXINT) | p >>> 24; + p = (p << 8) & MAXINT; + u = t << 1; + if (t & 128) { + u ^= 333; + } + q ^= t ^ (u << 16); + u ^= t >>> 1; + if (t & 1) { + u ^= 166; + } + q ^= u << 24 | u << 8; + } + return q; + } + + function qp(n, x) { + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; + return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; + } + + function hFun(x, key) { + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); + switch (kLen) { + case 4: + a = q[1][a] ^ getB(key[3], 0); + b = q[0][b] ^ getB(key[3], 1); + c = q[0][c] ^ getB(key[3], 2); + d = q[1][d] ^ getB(key[3], 3); + case 3: + a = q[1][a] ^ getB(key[2], 0); + b = q[1][b] ^ getB(key[2], 1); + c = q[0][c] ^ getB(key[2], 2); + d = q[0][d] ^ getB(key[2], 3); + case 2: + a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); + b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); + c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); + d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); + } + return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; + } + + keyBytes = keyBytes.slice(0, 32); + i = keyBytes.length; + while (i !== 16 && i !== 24 && i !== 32) { + keyBytes[i++] = 0; + } + + for (i = 0; i < keyBytes.length; i += 4) { + inKey[i >> 2] = getW(keyBytes, i); + } + for (i = 0; i < 256; i++) { + q[0][i] = qp(0, i); + q[1][i] = qp(1, i); + } + for (i = 0; i < 256; i++) { + f01 = q[1][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + f01 = q[0][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } + + kLen = inKey.length / 2; + for (i = 0; i < kLen; i++) { + a = inKey[i + i]; + meKey[i] = a; + b = inKey[i + i + 1]; + moKey[i] = b; + sKey[kLen - i - 1] = mdsRem(a, b); + } + for (i = 0; i < 40; i += 2) { + a = 0x1010101 * i; + b = a + 0x1010101; + a = hFun(a, meKey); + b = rotw(hFun(b, moKey), 8); + tfsKey[i] = (a + b) & MAXINT; + tfsKey[i + 1] = rotw(a + 2 * b, 9); + } + for (i = 0; i < 256; i++) { + a = b = c = d = i; + switch (kLen) { + case 4: + a = q[1][a] ^ getB(sKey[3], 0); + b = q[0][b] ^ getB(sKey[3], 1); + c = q[0][c] ^ getB(sKey[3], 2); + d = q[1][d] ^ getB(sKey[3], 3); + case 3: + a = q[1][a] ^ getB(sKey[2], 0); + b = q[1][b] ^ getB(sKey[2], 1); + c = q[0][c] ^ getB(sKey[2], 2); + d = q[0][d] ^ getB(sKey[2], 3); + case 2: + tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; + tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; + tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; + tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + } + } + } + + function tfsG0(x) { + return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; + } + + function tfsG1(x) { + return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; + } + + function tfsFrnd(r, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); + blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); + blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + } + + function tfsIrnd(i, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; + blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; + blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + } + + function tfsClose() { + tfsKey = []; + tfsM = [ + [], + [], + [], + [] + ]; + } + + function tfsEncrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { + tfsFrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); + dataOffset += 16; + return dataBytes; + } + + function tfsDecrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { + tfsIrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); + dataOffset += 16; + } + + // added by Recurity Labs + + function tfsFinal() { + return dataBytes; + } + + return { + name: 'twofish', + blocksize: 128 / 8, + open: tfsInit, + close: tfsClose, + encrypt: tfsEncrypt, + decrypt: tfsDecrypt, + // added by Recurity Labs + finalize: tfsFinal + }; +} + +// added by Recurity Labs + +function TF(key) { + this.tf = createTwofish(); + this.tf.open(Array.from(key), 0); + + this.encrypt = function(block) { + return this.tf.encrypt(Array.from(block), 0); + }; +} + +TF.keySize = TF.prototype.keySize = 32; +TF.blockSize = TF.prototype.blockSize = 16; + +/* Modified by Recurity Labs GmbH + * + * Originally written by nklein software (nklein.com) + */ + +/* + * Javascript implementation based on Bruce Schneier's reference implementation. + * + * + * The constructor doesn't do much of anything. It's just here + * so we can start defining properties and methods and such. + */ +function Blowfish() {} + +/* + * Declare the block size so that protocols know what size + * Initialization Vector (IV) they will need. + */ +Blowfish.prototype.BLOCKSIZE = 8; + +/* + * These are the default SBOXES. + */ +Blowfish.prototype.SBOXES = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] +]; + +//* +//* This is the default PARRAY +//* +Blowfish.prototype.PARRAY = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b +]; + +//* +//* This is the number of rounds the cipher will go +//* +Blowfish.prototype.NN = 16; + +//* +//* This function is needed to get rid of problems +//* with the high-bit getting set. If we don't do +//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not +//* equal to ( bb & 0x00FFFFFFFF ) even when they +//* agree bit-for-bit for the first 32 bits. +//* +Blowfish.prototype._clean = function(xx) { + if (xx < 0) { + const yy = xx & 0x7FFFFFFF; + xx = yy + 0x80000000; + } + return xx; +}; + +//* +//* This is the mixing function that uses the sboxes +//* +Blowfish.prototype._F = function(xx) { + let yy; + + const dd = xx & 0x00FF; + xx >>>= 8; + const cc = xx & 0x00FF; + xx >>>= 8; + const bb = xx & 0x00FF; + xx >>>= 8; + const aa = xx & 0x00FF; + + yy = this.sboxes[0][aa] + this.sboxes[1][bb]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; + + return yy; +}; + +//* +//* This method takes an array with two values, left and right +//* and does NN rounds of Blowfish on them. +//* +Blowfish.prototype._encryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; + + let ii; + + for (ii = 0; ii < this.NN; ++ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; + + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } + + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; + + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); +}; + +//* +//* This method takes a vector of numbers and turns them +//* into long words so that they can be processed by the +//* real algorithm. +//* +//* Maybe I should make the real algorithm above take a vector +//* instead. That will involve more looping, but it won't require +//* the F() method to deconstruct the vector. +//* +Blowfish.prototype.encryptBlock = function(vector) { + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); + vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); + } + + this._encryptBlock(vals); + + const ret = []; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); + ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); + // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); + // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + } + + return ret; +}; + +//* +//* This method takes an array with two values, left and right +//* and undoes NN rounds of Blowfish on them. +//* +Blowfish.prototype._decryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; + + let ii; + + for (ii = this.NN + 1; ii > 1; --ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; + + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } + + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; + + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); +}; + +//* +//* This method takes a key array and initializes the +//* sboxes and parray for this encryption. +//* +Blowfish.prototype.init = function(key) { + let ii; + let jj = 0; + + this.parray = []; + for (ii = 0; ii < this.NN + 2; ++ii) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { + data = (data << 8) | (key[jj] & 0x00FF); + if (++jj >= key.length) { + jj = 0; + } + } + this.parray[ii] = this.PARRAY[ii] ^ data; + } + + this.sboxes = []; + for (ii = 0; ii < 4; ++ii) { + this.sboxes[ii] = []; + for (jj = 0; jj < 256; ++jj) { + this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + } + } + + const vals = [0x00000000, 0x00000000]; + + for (ii = 0; ii < this.NN + 2; ii += 2) { + this._encryptBlock(vals); + this.parray[ii + 0] = vals[0]; + this.parray[ii + 1] = vals[1]; + } + + for (ii = 0; ii < 4; ++ii) { + for (jj = 0; jj < 256; jj += 2) { + this._encryptBlock(vals); + this.sboxes[ii][jj + 0] = vals[0]; + this.sboxes[ii][jj + 1] = vals[1]; + } + } +}; + +// added by Recurity Labs +function BF(key) { + this.bf = new Blowfish(); + this.bf.init(key); + + this.encrypt = function(block) { + return this.bf.encryptBlock(block); + }; +} + +BF.keySize = BF.prototype.keySize = 16; +BF.blockSize = BF.prototype.blockSize = 8; + +/** + * This file is needed to dynamic import the legacy ciphers. + * Separate dynamic imports are not convenient as they result in multiple chunks. + */ + + +const legacyCiphers = new Map([ + [enums.symmetric.tripledes, TripleDES], + [enums.symmetric.cast5, CAST5], + [enums.symmetric.blowfish, BF], + [enums.symmetric.twofish, TF] +]); + +var legacy_ciphers = /*#__PURE__*/Object.freeze({ + __proto__: null, + legacyCiphers: legacyCiphers +}); + +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends HashMD { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + R_BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); + +/** + * This file is needed to dynamic import the noble-hashes. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleHashes = new Map(Object.entries({ + sha1, + sha224, + sha256, + sha384, + sha512, + sha3_256, + sha3_512, + ripemd160 +})); + +var noble_hashes = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleHashes: nobleHashes +}); + +// Adapted from the reference implementation in RFC7693 +// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes + +// Uint64 values are represented using two Uint32s, stored as little endian +// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays +// need to be manually handled + +// 64-bit unsigned addition (little endian, in place) +// Sets a[i,i+1] += b[j,j+1] +// `a` and `b` must be Uint32Array(2) +function ADD64 (a, i, b, j) { + a[i] += b[j]; + a[i+1] += b[j+1] + (a[i] < b[j]); // add carry +} + +// Increment 64-bit little-endian unsigned value by `c` (in place) +// `a` must be Uint32Array(2) +function INC64 (a, c) { + a[0] += c; + a[1] += (a[0] < c); +} + +// G Mixing function +// The ROTRs are inlined for speed +function G$1 (v, m, a, b, c, d, ix, iy) { + ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1] + ADD64(v, a, m, ix); // v[a, a+1] += x ... x0 + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; + + ADD64(v, c, v, d); + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor0 >>> 24) ^ (xor1 << 8); + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); + + ADD64(v, a, v, b); + ADD64(v, a, m, iy); + + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = (xor0 >>> 16) ^ (xor1 << 16); + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); + + ADD64(v, c, v, d); + + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor1 >>> 31) ^ (xor0 << 1); + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); +} + +// Initialization Vector +const BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]); + +// These are offsets into a Uint64 buffer. +// Multiply them all by 2 to make them offsets into a Uint32 buffer +const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +].map(x => x * 2)); + +// Compression function. 'last' flag indicates last block. +// Note: we're representing 16 uint64s as 32 uint32s +function compress(S, last) { + const v = new Uint32Array(32); + const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32); + + // init work variables + for (let i = 0; i < 16; i++) { + v[i] = S.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + + // low 64 bits of offset + v[24] ^= S.t0[0]; + v[25] ^= S.t0[1]; + // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1 + + // if last block + const f0 = last ? 0xFFFFFFFF : 0; + v[28] ^= f0; + v[29] ^= f0; + + // twelve rounds of mixing + for (let i = 0; i < 12; i++) { + // ROUND(r) + const i16 = i << 4; + G$1(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1]); + G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]); + G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]); + G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]); + G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]); + G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]); + G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]); + G$1(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15]); + } + + for (let i = 0; i < 16; i++) { + S.h[i] ^= v[i] ^ v[i + 16]; + } +} + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +class Blake2b { + constructor(outlen, key, salt, personal) { + const params = new Uint8Array(64); + // 0: outlen, keylen, fanout, depth + // 4: leaf length, sequential mode + // 8: node offset + // 12: node offset + // 16: node depth, inner length, rfu + // 20: rfu + // 24: rfu + // 28: rfu + // 32: salt + // 36: salt + // 40: salt + // 44: salt + // 48: personal + // 52: personal + // 56: personal + // 60: personal + + // init internal state + this.S = { + b: new Uint8Array(BLOCKBYTES), + h: new Uint32Array(OUTBYTES_MAX / 4), + t0: new Uint32Array(2), // input counter `t`, lower 64-bits only + c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES` + outlen // output length in bytes + }; + + // init parameter block + params[0] = outlen; + if (key) params[1] = key.length; + params[2] = 1; // fanout + params[3] = 1; // depth + if (salt) params.set(salt, 32); + if (personal) params.set(personal, 48); + const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT); + + // initialize hash state + for (let i = 0; i < 16; i++) { + this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i]; + } + + // key the hash, if applicable + if (key) { + const block = new Uint8Array(BLOCKBYTES); + block.set(key); + this.update(block); + } + } + + // Updates a BLAKE2b streaming hash + // Requires Uint8Array (byte array) + update(input) { + if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer') + // for (let i = 0; i < input.length; i++) { + // if (this.S.c === BLOCKBYTES) { // buffer full + // INC64(this.S.t0, this.S.c) // add counters + // compress(this.S, false) + // this.S.c = 0 // empty buffer + // } + // this.S.b[this.S.c++] = input[i] + // } + let i = 0; + while(i < input.length) { + if (this.S.c === BLOCKBYTES) { // buffer full + INC64(this.S.t0, this.S.c); // add counters + compress(this.S, false); + this.S.c = 0; // empty buffer + } + let left = BLOCKBYTES - this.S.c; + this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds + const fill = Math.min(left, input.length - i); + this.S.c += fill; + i += fill; + } + return this + } + + /** + * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one + * @param {Uint8Array} [prealloc] - optional preallocated buffer + * @returns {ArrayBuffer} message digest + */ + digest(prealloc) { + INC64(this.S.t0, this.S.c); // mark last block offset + + // final block, padded + this.S.b.fill(0, this.S.c); + this.S.c = BLOCKBYTES; + compress(this.S, true); + + const out = prealloc || new Uint8Array(this.S.outlen); + for (let i = 0; i < this.S.outlen; i++) { + // must be loaded individually since default Uint32 endianness is platform dependant + out[i] = this.S.h[i >> 2] >> (8 * (i & 3)); + } + this.S.h = null; // prevent calling `update` after `digest` + return out.buffer; + } +} + + +function createHash(outlen, key, salt, personal) { + if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`) + + return new Blake2b(outlen, key, salt, personal) +} + +const OUTBYTES_MAX = 64; +const BLOCKBYTES = 128; + +const TYPE = 2; // Argon2id +const VERSION = 0x13; +const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1; +const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const SALTBYTES_MIN = 8; +const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const passwordBYTES_MIN = 8; +const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional) +const SECRETBYTES_MAX = 32; // key (optional) + +const ARGON2_BLOCK_SIZE = 1024; +const ARGON2_PREHASH_DIGEST_LENGTH = 64; + +const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd; + +// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3]) +function LE32(buf, n, i) { + buf[i+0] = n; + buf[i+1] = n >> 8; + buf[i+2] = n >> 16; + buf[i+3] = n >> 24; + return buf; +} + +/** + * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7]) + * @param {Uint8Array} buf + * @param {Number} n + * @param {Number} i + */ +function LE64(buf, n, i) { + if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported"); + // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations + // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps) + // so we manually extract each byte + let remainder = n; + for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER + buf[offset] = remainder; // implicit & 0xff + remainder = (remainder - buf[offset]) / 256; + } + return buf; +} + +/** + * Variable-Length Hash Function H' + * @param {Number} outlen - T + * @param {Uint8Array} X - value to hash + * @param {Uint8Array} res - output buffer, of length `outlength` or larger + */ +function H_(outlen, X, res) { + const V = new Uint8Array(64); // no need to keep around all V_i + + const V1_in = new Uint8Array(4 + X.length); + LE32(V1_in, outlen, 0); + V1_in.set(X, 4); + if (outlen <= 64) { + // H'^T(A) = H^T(LE32(T)||A) + createHash(outlen).update(V1_in).digest(res); + return res + } + + const r = Math.ceil(outlen / 32) - 2; + + // Let V_i be a 64-byte block and W_i be its first 32 bytes. + // V_1 = H^(64)(LE32(T)||A) + // V_2 = H^(64)(V_1) + // ... + // V_r = H^(64)(V_{r-1}) + // V_{r+1} = H^(T-32*r)(V_{r}) + // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1} + for (let i = 0; i < r; i++) { + createHash(64).update(i === 0 ? V1_in : V).digest(V); + // store W_i in result buffer already + res.set(V.subarray(0, 32), i*32); + } + // V_{r+1} + const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest()); + res.set(V_r1, r*32); + + return res; +} + +// compute buf = xs ^ ys +function XOR(wasmContext, buf, xs, ys) { + wasmContext.fn.XOR( + buf.byteOffset, + xs.byteOffset, + ys.byteOffset, + ); + return buf +} + +/** + * @param {Uint8Array} X (read-only) + * @param {Uint8Array} Y (read-only) + * @param {Uint8Array} R - output buffer + * @returns + */ +function G(wasmContext, X, Y, R) { + wasmContext.fn.G( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +function G2(wasmContext, X, Y, R) { + wasmContext.fn.G2( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values. +function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) { + // For each segment, we do the following. First, we compute the value Z as: + // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) ) + wasmContext.refs.prngTmp.fill(0); + const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8); + LE64(Z, pass, 0); + LE64(Z, lane, 8); + LE64(Z, slice, 16); + LE64(Z, m_, 24); + LE64(Z, totalPasses, 32); + LE64(Z, TYPE, 40); + + // Then we compute q/(128*SL) 1024-byte values + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ), + // ..., + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )), + for(let i = 1; i <= segmentLength; i++) { + // tmp.set(Z); // no need to re-copy + LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed + const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR ); + + // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2 + // NB: the first generated pair must be used for the first block of the segment, and so on. + // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset. + for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) { + yield g2.subarray(k, k+8); + } + } + return []; +} + +function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) { + const assertLength = (name, value, min, max) => { + if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); } + }; + + if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version'); + assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX); + assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX); + assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX); + assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX); + // optional fields + ad && assertLength('associated data', ad, 0, ADBYTES_MAX); + secret && assertLength('secret', secret, 0, SECRETBYTES_MAX); + + return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes }; +} + +const KB = 1024; +const WASM_PAGE_SIZE = 64 * KB; + +function argon2id(params, { memory, instance: wasmInstance }) { + if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system + + const ctx = validateParams({ type: TYPE, version: VERSION, ...params }); + + const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports; + const wasmRefs = {}; + const wasmFn = {}; + wasmFn.G = wasmG; + wasmFn.G2 = wasmG2; + wasmFn.XOR = wasmXOR; + + // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p. + const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes)); + const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references + if (memory.buffer.byteLength < requiredMemory) { + const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE); + // If enough memory is available, the `memory.buffer` is internally detached and the reference updated. + // Otherwise, the operation fails, and the original memory can still be used. + memory.grow(missing); + } + + let offset = 0; + // Init wasm memory needed in other functions + wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length; + wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length; + wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length; + wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length; + // Init wasm memory needed locally + const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT; + const wasmContext = { fn: wasmFn, refs: wasmRefs }; + const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length; + const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE); + const allocatedMemory = new Uint8Array(memory.buffer, 0, offset); + + // 1. Establish H_0 + const H0 = getH0(ctx); + + // 2. Allocate the memory as m' 1024-byte blocks + // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns. + const q = m_ / ctx.lanes; + const B = new Array(ctx.lanes).fill(null).map(() => new Array(q)); + const initBlock = (i, j) => { + B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE); + return B[i][j]; + }; + + for (let i = 0; i < ctx.lanes; i++) { + // const LEi = LE0; // since p = 1 for us + const tmp = new Uint8Array(H0.length + 8); + // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0)); + // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + LE32(tmp, 1, H0.length); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1)); + } + + // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2 + // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes + // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc. + const SL = 4; // vertical slices + const segmentLength = q / SL; + for (let pass = 0; pass < ctx.passes; pass++) { + // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel + for (let sl = 0; sl < SL; sl++) { + const isDataIndependent = pass === 0 && sl <= 1; + for (let i = 0; i < ctx.lanes; i++) { // lane + // On the first slice of the first pass, blocks 0 and 1 are already filled + let segmentOffset = sl === 0 && pass === 0 ? 2 : 0; + // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory) + const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null; + for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) { + const j = sl * segmentLength + segmentOffset; + const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q] + + // we can assume the PRNG is never done + const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength); + const l = lz[0]; const z = lz[1]; + // for (let i = 0; i < p; i++ ) + // B[i][j] = G(B[i][j-1], B[l][z]) + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + if (pass === 0) initBlock(i, j); + G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]); + + // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one + if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]); + } + } + } + } + + // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column: + // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1] + const C = B[0][q-1]; + for(let i = 1; i < ctx.lanes; i++) { + XOR(wasmContext, C, C, B[i][q-1]); + } + + const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength)); + // clear memory since the module might be cached + allocatedMemory.fill(0); // clear sensitive contents + memory.grow(0); // allow deallocation + // 8. The output tag is computed as H'^T(C). + return tag; + +} + +function getH0(ctx) { + const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH); + const ZERO32 = new Uint8Array(4); + const params = new Uint8Array(24); + LE32(params, ctx.lanes, 0); + LE32(params, ctx.tagLength, 4); + LE32(params, ctx.memorySize, 8); + LE32(params, ctx.passes, 12); + LE32(params, ctx.version, 16); + LE32(params, ctx.type, 20); + + const toHash = [params]; + if (ctx.password) { + toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0)); + toHash.push(ctx.password); + } else { + toHash.push(ZERO32); // context.password.length + } + + if (ctx.salt) { + toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0)); + toHash.push(ctx.salt); + } else { + toHash.push(ZERO32); // context.salt.length + } + + if (ctx.secret) { + toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0)); + toHash.push(ctx.secret); + // todo clear secret? + } else { + toHash.push(ZERO32); // context.secret.length + } + + if (ctx.ad) { + toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0)); + toHash.push(ctx.ad); + } else { + toHash.push(ZERO32); // context.ad.length + } + H.update(concatArrays(toHash)); + + const outputBuffer = H.digest(); + return new Uint8Array(outputBuffer); +} + +function concatArrays(arrays) { + if (arrays.length === 1) return arrays[0]; + + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!(arrays[i] instanceof Uint8Array)) { + throw new Error('concatArrays: Data must be in the form of a Uint8Array'); + } + + totalLength += arrays[i].length; + } + + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach((element) => { + result.set(element, pos); + pos += element.length; + }); + + return result; +} + +let isSIMDSupported; +async function wasmLoader(memory, getSIMD, getNonSIMD) { + const importObject = { env: { memory } }; + if (isSIMDSupported === undefined) { + try { + const loaded = await getSIMD(importObject); + isSIMDSupported = true; + return loaded; + } catch(e) { + isSIMDSupported = false; + } + } + + const loader = isSIMDSupported ? getSIMD : getNonSIMD; + return loader(importObject); +} + +async function setupWasm(getSIMD, getNonSIMD) { + const memory = new WebAssembly.Memory({ + // in pages of 64KiB each + // these values need to be compatible with those declared when building in `build-wasm` + initial: 1040, // 65MB + maximum: 65536, // 4GB + }); + const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD); + + /** + * Argon2id hash function + * @callback computeHash + * @param {Object} params + * @param {Uint8Array} params.password - password + * @param {Uint8Array} params.salt - salt + * @param {Integer} params.parallelism + * @param {Integer} params.passes + * @param {Integer} params.memorySize - in kibibytes + * @param {Integer} params.tagLength - output tag length + * @param {Uint8Array} [params.ad] - associated data (optional) + * @param {Uint8Array} [params.secret] - secret data (optional) + * @return {Uint8Array} argon2id hash + */ + const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory }); + + return computeHash; +} + +function _loadWasmModule (sync, filepath, src, imports) { + function _instantiateOrCompile(source, imports, stream) { + var instantiateFunc = WebAssembly.instantiate; + var compileFunc = WebAssembly.compile; + + if (imports) { + return instantiateFunc(source, imports) + } else { + return compileFunc(source) + } + } + + +var buf = null; + + +buf = Buffer.from(src, 'base64'); + + + + { + return _instantiateOrCompile(buf, imports) + } +} + +function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDC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QAEACAP/QAEAP1R/QsEACACIABBIHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBMHIiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)} + +function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)} + +const loadWasm = async () => setupWasm( + (instanceObject) => wasmSIMD(instanceObject), + (instanceObject) => wasmNonSIMD(instanceObject), +); + +var index$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: loadWasm +}); + +/* +node-bzip - a pure-javascript Node.JS module for decoding bzip2 data + +Copyright (C) 2012 Eli Skeggs + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html + +Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). + +Based on micro-bunzip by Rob Landley (rob@landley.net). + +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ + +var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; + +// offset in bytes +var BitReader$1 = function(stream) { + this.stream = stream; + this.bitOffset = 0; + this.curByte = 0; + this.hasByte = false; +}; + +BitReader$1.prototype._ensureByte = function() { + if (!this.hasByte) { + this.curByte = this.stream.readByte(); + this.hasByte = true; + } +}; + +// reads bits from the buffer +BitReader$1.prototype.read = function(bits) { + var result = 0; + while (bits > 0) { + this._ensureByte(); + var remaining = 8 - this.bitOffset; + // if we're in a byte + if (bits >= remaining) { + result <<= remaining; + result |= BITMASK[remaining] & this.curByte; + this.hasByte = false; + this.bitOffset = 0; + bits -= remaining; + } else { + result <<= bits; + var shift = remaining - bits; + result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; + this.bitOffset += bits; + bits = 0; + } + } + return result; +}; + +// seek to an arbitrary point in the buffer (expressed in bits) +BitReader$1.prototype.seek = function(pos) { + var n_bit = pos % 8; + var n_byte = (pos - n_bit) / 8; + this.bitOffset = n_bit; + this.stream.seek(n_byte); + this.hasByte = false; +}; + +// reads 6 bytes worth of data using the read method +BitReader$1.prototype.pi = function() { + var buf = new Uint8Array(6), i; + for (i = 0; i < buf.length; i++) { + buf[i] = this.read(8); + } + return bufToHex(buf); +}; + +function bufToHex(buf) { + return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); +} + +var bitreader = BitReader$1; + +/* very simple input/output stream interface */ + +var Stream$1 = function() { +}; + +// input streams ////////////// +/** Returns the next byte, or -1 for EOF. */ +Stream$1.prototype.readByte = function() { + throw new Error("abstract method readByte() not implemented"); +}; +/** Attempts to fill the buffer; returns number of bytes read, or + * -1 for EOF. */ +Stream$1.prototype.read = function(buffer, bufOffset, length) { + var bytesRead = 0; + while (bytesRead < length) { + var c = this.readByte(); + if (c < 0) { // EOF + return (bytesRead===0) ? -1 : bytesRead; + } + buffer[bufOffset++] = c; + bytesRead++; + } + return bytesRead; +}; +Stream$1.prototype.seek = function(new_pos) { + throw new Error("abstract method seek() not implemented"); +}; + +// output streams /////////// +Stream$1.prototype.writeByte = function(_byte) { + throw new Error("abstract method readByte() not implemented"); +}; +Stream$1.prototype.write = function(buffer, bufOffset, length) { + var i; + for (i=0; i>> 0; // return an unsigned value + }; + + /** + * Update the CRC with a single byte + * @param value The value to update the CRC with + */ + this.updateCRC = function(value) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + }; + + /** + * Update the CRC with a sequence of identical bytes + * @param value The value to update the CRC with + * @param count The number of bytes + */ + this.updateCRCRun = function(value, count) { + while (count-- > 0) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + } + }; + }; + return CRC32; +})(); + +/* +seek-bzip - a pure-javascript module for seeking within bzip2 data + +Copyright (C) 2013 C. Scott Ananian +Copyright (C) 2012 Eli Skeggs +Copyright (C) 2011 Kevin Kwok + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html + +Adapted from node-bzip, copyright 2012 Eli Skeggs. +Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). + +Based on micro-bunzip by Rob Landley (rob@landley.net). + +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ + +var BitReader = bitreader; +var Stream = stream; +var CRC32 = crc32; + +var MAX_HUFCODE_BITS = 20; +var MAX_SYMBOLS = 258; +var SYMBOL_RUNA = 0; +var SYMBOL_RUNB = 1; +var MIN_GROUPS = 2; +var MAX_GROUPS = 6; +var GROUP_SIZE = 50; + +var WHOLEPI = "314159265359"; +var SQRTPI = "177245385090"; + +var mtf = function(array, index) { + var src = array[index], i; + for (i = index; i > 0; i--) { + array[i] = array[i-1]; + } + array[0] = src; + return src; +}; + +var Err = { + OK: 0, + LAST_BLOCK: -1, + NOT_BZIP_DATA: -2, + UNEXPECTED_INPUT_EOF: -3, + UNEXPECTED_OUTPUT_EOF: -4, + DATA_ERROR: -5, + OUT_OF_MEMORY: -6, + OBSOLETE_INPUT: -7, + END_OF_BLOCK: -8 +}; +var ErrorMessages = {}; +ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; +ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; +ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; +ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; +ErrorMessages[Err.DATA_ERROR] = "Data error"; +ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; +ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; + +var _throw = function(status, optDetail) { + var msg = ErrorMessages[status] || 'unknown error'; + if (optDetail) { msg += ': '+optDetail; } + var e = new TypeError(msg); + e.errorCode = status; + throw e; +}; + +var Bunzip = function(inputStream, outputStream) { + this.writePos = this.writeCurrent = this.writeCount = 0; + + this._start_bunzip(inputStream, outputStream); +}; +Bunzip.prototype._init_block = function() { + var moreBlocks = this._get_next_block(); + if ( !moreBlocks ) { + this.writeCount = -1; + return false; /* no more blocks */ + } + this.blockCRC = new CRC32(); + return true; +}; +/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ +Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { + /* Ensure that file starts with "BZh['1'-'9']." */ + var buf = new Uint8Array(4); + if (inputStream.read(buf, 0, 4) !== 4 || + String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') + _throw(Err.NOT_BZIP_DATA, 'bad magic'); + + var level = buf[3] - 0x30; + if (level < 1 || level > 9) + _throw(Err.NOT_BZIP_DATA, 'level out of range'); + + this.reader = new BitReader(inputStream); + + /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of + uncompressed data. Allocate intermediate buffer for block. */ + this.dbufSize = 100000 * level; + this.nextoutput = 0; + this.outputStream = outputStream; + this.streamCRC = 0; +}; +Bunzip.prototype._get_next_block = function() { + var i, j, k; + var reader = this.reader; + // this is get_next_block() function from micro-bunzip: + /* Read in header signature and CRC, then validate signature. + (last block signature means CRC is for whole file, return now) */ + var h = reader.pi(); + if (h === SQRTPI) { // last block + return false; /* no more blocks */ + } + if (h !== WHOLEPI) + _throw(Err.NOT_BZIP_DATA); + this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) + this.streamCRC = (this.targetBlockCRC ^ + ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; + /* We can add support for blockRandomised if anybody complains. There was + some code for this in busybox 1.0.0-pre3, but nobody ever noticed that + it didn't actually work. */ + if (reader.read(1)) + _throw(Err.OBSOLETE_INPUT); + var origPointer = reader.read(24); + if (origPointer > this.dbufSize) + _throw(Err.DATA_ERROR, 'initial position out of bounds'); + /* mapping table: if some byte values are never used (encoding things + like ascii text), the compression code removes the gaps to have fewer + symbols to deal with, and writes a sparse bitfield indicating which + values were present. We make a translation table to convert the symbols + back to the corresponding bytes. */ + var t = reader.read(16); + var symToByte = new Uint8Array(256), symTotal = 0; + for (i = 0; i < 16; i++) { + if (t & (1 << (0xF - i))) { + var o = i * 16; + k = reader.read(16); + for (j = 0; j < 16; j++) + if (k & (1 << (0xF - j))) + symToByte[symTotal++] = o + j; + } + } + + /* How many different huffman coding groups does this block use? */ + var groupCount = reader.read(3); + if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) + _throw(Err.DATA_ERROR); + /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding + group. Read in the group selector list, which is stored as MTF encoded + bit runs. (MTF=Move To Front, as each value is used it's moved to the + start of the list.) */ + var nSelectors = reader.read(15); + if (nSelectors === 0) + _throw(Err.DATA_ERROR); + + var mtfSymbol = new Uint8Array(256); + for (i = 0; i < groupCount; i++) + mtfSymbol[i] = i; + + var selectors = new Uint8Array(nSelectors); // was 32768... + + for (i = 0; i < nSelectors; i++) { + /* Get next value */ + for (j = 0; reader.read(1); j++) + if (j >= groupCount) _throw(Err.DATA_ERROR); + /* Decode MTF to get the next selector */ + selectors[i] = mtf(mtfSymbol, j); + } + + /* Read the huffman coding tables for each group, which code for symTotal + literal symbols, plus two run symbols (RUNA, RUNB) */ + var symCount = symTotal + 2; + var groups = [], hufGroup; + for (j = 0; j < groupCount; j++) { + var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); + /* Read huffman code lengths for each symbol. They're stored in + a way similar to mtf; record a starting value for the first symbol, + and an offset from the previous value for everys symbol after that. */ + t = reader.read(5); // lengths + for (i = 0; i < symCount; i++) { + for (;;) { + if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); + /* If first bit is 0, stop. Else second bit indicates whether + to increment or decrement the value. */ + if(!reader.read(1)) + break; + if(!reader.read(1)) + t++; + else + t--; + } + length[i] = t; + } + + /* Find largest and smallest lengths in this group */ + var minLen, maxLen; + minLen = maxLen = length[0]; + for (i = 1; i < symCount; i++) { + if (length[i] > maxLen) + maxLen = length[i]; + else if (length[i] < minLen) + minLen = length[i]; + } + + /* Calculate permute[], base[], and limit[] tables from length[]. + * + * permute[] is the lookup table for converting huffman coded symbols + * into decoded symbols. base[] is the amount to subtract from the + * value of a huffman symbol of a given length when using permute[]. + * + * limit[] indicates the largest numerical value a symbol with a given + * number of bits can have. This is how the huffman codes can vary in + * length: each code with a value>limit[length] needs another bit. + */ + hufGroup = {}; + groups.push(hufGroup); + hufGroup.permute = new Uint16Array(MAX_SYMBOLS); + hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); + hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); + hufGroup.minLen = minLen; + hufGroup.maxLen = maxLen; + /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ + var pp = 0; + for (i = minLen; i <= maxLen; i++) { + temp[i] = hufGroup.limit[i] = 0; + for (t = 0; t < symCount; t++) + if (length[t] === i) + hufGroup.permute[pp++] = t; + } + /* Count symbols coded for at each bit length */ + for (i = 0; i < symCount; i++) + temp[length[i]]++; + /* Calculate limit[] (the largest symbol-coding value at each bit + * length, which is (previous limit<<1)+symbols at this level), and + * base[] (number of symbols to ignore at each bit length, which is + * limit minus the cumulative count of symbols coded for already). */ + pp = t = 0; + for (i = minLen; i < maxLen; i++) { + pp += temp[i]; + /* We read the largest possible symbol size and then unget bits + after determining how many we need, and those extra bits could + be set to anything. (They're noise from future symbols.) At + each level we're really only interested in the first few bits, + so here we set all the trailing to-be-ignored bits to 1 so they + don't affect the value>limit[length] comparison. */ + hufGroup.limit[i] = pp - 1; + pp <<= 1; + t += temp[i]; + hufGroup.base[i + 1] = pp - t; + } + hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ + hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; + hufGroup.base[minLen] = 0; + } + /* We've finished reading and digesting the block header. Now read this + block's huffman coded symbols from the file and undo the huffman coding + and run length encoding, saving the result into dbuf[dbufCount++]=uc */ + + /* Initialize symbol occurrence counters and symbol Move To Front table */ + var byteCount = new Uint32Array(256); + for (i = 0; i < 256; i++) + mtfSymbol[i] = i; + /* Loop through compressed symbols. */ + var runPos = 0, dbufCount = 0, selector = 0, uc; + var dbuf = this.dbuf = new Uint32Array(this.dbufSize); + symCount = 0; + for (;;) { + /* Determine which huffman coding group to use. */ + if (!(symCount--)) { + symCount = GROUP_SIZE - 1; + if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } + hufGroup = groups[selectors[selector++]]; + } + /* Read next huffman-coded symbol. */ + i = hufGroup.minLen; + j = reader.read(i); + for (;;i++) { + if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } + if (j <= hufGroup.limit[i]) + break; + j = (j << 1) | reader.read(1); + } + /* Huffman decode value to get nextSym (with bounds checking) */ + j -= hufGroup.base[i]; + if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } + var nextSym = hufGroup.permute[j]; + /* We have now decoded the symbol, which indicates either a new literal + byte, or a repeated run of the most recent literal byte. First, + check if nextSym indicates a repeated run, and if so loop collecting + how many times to repeat the last literal. */ + if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { + /* If this is the start of a new run, zero out counter */ + if (!runPos){ + runPos = 1; + t = 0; + } + /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at + each bit position, add 1 or 2 instead. For example, + 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. + You can make any bit pattern that way using 1 less symbol than + the basic or 0/1 method (except all bits 0, which would use no + symbols, but a run of length 0 doesn't mean anything in this + context). Thus space is saved. */ + if (nextSym === SYMBOL_RUNA) + t += runPos; + else + t += 2 * runPos; + runPos <<= 1; + continue; + } + /* When we hit the first non-run symbol after a run, we now know + how many times to repeat the last literal, so append that many + copies to our buffer of decoded symbols (dbuf) now. (The last + literal used is the one at the head of the mtfSymbol array.) */ + if (runPos){ + runPos = 0; + if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } + uc = symToByte[mtfSymbol[0]]; + byteCount[uc] += t; + while (t--) + dbuf[dbufCount++] = uc; + } + /* Is this the terminating symbol? */ + if (nextSym > symTotal) + break; + /* At this point, nextSym indicates a new literal character. Subtract + one to get the position in the MTF array at which this literal is + currently to be found. (Note that the result can't be -1 or 0, + because 0 and 1 are RUNA and RUNB. But another instance of the + first symbol in the mtf array, position 0, would have been handled + as part of a run above. Therefore 1 unused mtf position minus + 2 non-literal nextSym values equals -1.) */ + if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } + i = nextSym - 1; + uc = mtf(mtfSymbol, i); + uc = symToByte[uc]; + /* We have our literal byte. Save it into dbuf. */ + byteCount[uc]++; + dbuf[dbufCount++] = uc; + } + /* At this point, we've read all the huffman-coded symbols (and repeated + runs) for this block from the input stream, and decoded them into the + intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. + Now undo the Burrows-Wheeler transform on dbuf. + See http://dogma.net/markn/articles/bwt/bwt.htm + */ + if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } + /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ + j = 0; + for (i = 0; i < 256; i++) { + k = j + byteCount[i]; + byteCount[i] = j; + j = k; + } + /* Figure out what order dbuf would be in if we sorted it. */ + for (i = 0; i < dbufCount; i++) { + uc = dbuf[i] & 0xff; + dbuf[byteCount[uc]] |= (i << 8); + byteCount[uc]++; + } + /* Decode first byte by hand to initialize "previous" byte. Note that it + doesn't get output, and if the first three characters are identical + it doesn't qualify as a run (hence writeRunCountdown=5). */ + var pos = 0, current = 0, run = 0; + if (dbufCount) { + pos = dbuf[origPointer]; + current = (pos & 0xff); + pos >>= 8; + run = -1; + } + this.writePos = pos; + this.writeCurrent = current; + this.writeCount = dbufCount; + this.writeRun = run; + + return true; /* more blocks to come */ +}; +/* Undo burrows-wheeler transform on intermediate buffer to produce output. + If start_bunzip was initialized with out_fd=-1, then up to len bytes of + data are written to outbuf. Return value is number of bytes written or + error (all errors are negative numbers). If out_fd!=-1, outbuf and len + are ignored, data is written to out_fd and return is RETVAL_OK or error. +*/ +Bunzip.prototype._read_bunzip = function(outputBuffer, len) { + var copies, previous, outbyte; + /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully + decoded, which results in this returning RETVAL_LAST_BLOCK, also + equal to -1... Confusing, I'm returning 0 here to indicate no + bytes written into the buffer */ + if (this.writeCount < 0) { return 0; } + var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; + var dbufCount = this.writeCount; this.outputsize; + var run = this.writeRun; + + while (dbufCount) { + dbufCount--; + previous = current; + pos = dbuf[pos]; + current = pos & 0xff; + pos >>= 8; + if (run++ === 3){ + copies = current; + outbyte = previous; + current = -1; + } else { + copies = 1; + outbyte = current; + } + this.blockCRC.updateCRCRun(outbyte, copies); + while (copies--) { + this.outputStream.writeByte(outbyte); + this.nextoutput++; + } + if (current != previous) + run = 0; + } + this.writeCount = dbufCount; + // check CRC + if (this.blockCRC.getCRC() !== this.targetBlockCRC) { + _throw(Err.DATA_ERROR, "Bad block CRC "+ + "(got "+this.blockCRC.getCRC().toString(16)+ + " expected "+this.targetBlockCRC.toString(16)+")"); + } + return this.nextoutput; +}; + +var coerceInputStream = function(input) { + if ('readByte' in input) { return input; } + var inputStream = new Stream(); + inputStream.pos = 0; + inputStream.readByte = function() { return input[this.pos++]; }; + inputStream.seek = function(pos) { this.pos = pos; }; + inputStream.eof = function() { return this.pos >= input.length; }; + return inputStream; +}; +var coerceOutputStream = function(output) { + var outputStream = new Stream(); + var resizeOk = true; + if (output) { + if (typeof(output)==='number') { + outputStream.buffer = new Uint8Array(output); + resizeOk = false; + } else if ('writeByte' in output) { + return output; + } else { + outputStream.buffer = output; + resizeOk = false; + } + } else { + outputStream.buffer = new Uint8Array(16384); + } + outputStream.pos = 0; + outputStream.writeByte = function(_byte) { + if (resizeOk && this.pos >= this.buffer.length) { + var newBuffer = new Uint8Array(this.buffer.length*2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + this.buffer[this.pos++] = _byte; + }; + outputStream.getBuffer = function() { + // trim buffer + if (this.pos !== this.buffer.length) { + if (!resizeOk) + throw new TypeError('outputsize does not match decoded input'); + var newBuffer = new Uint8Array(this.pos); + newBuffer.set(this.buffer.subarray(0, this.pos)); + this.buffer = newBuffer; + } + return this.buffer; + }; + outputStream._coerced = true; + return outputStream; +}; + +/* Static helper functions */ +// 'input' can be a stream or a buffer +// 'output' can be a stream or a buffer or a number (buffer size) +const decode = function(input, output, multistream) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + + var bz = new Bunzip(inputStream, outputStream); + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + if (bz._init_block()) { + bz._read_bunzip(); + } else { + var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) + if (targetStreamCRC !== bz.streamCRC) { + _throw(Err.DATA_ERROR, "Bad stream CRC "+ + "(got "+bz.streamCRC.toString(16)+ + " expected "+targetStreamCRC.toString(16)+")"); + } + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + } else break; + } + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); +}; +const decodeBlock = function(input, pos, output) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + var bz = new Bunzip(inputStream, outputStream); + bz.reader.seek(pos); + /* Fill the decode buffer for the block */ + var moreBlocks = bz._get_next_block(); + if (moreBlocks) { + /* Init the CRC for writing */ + bz.blockCRC = new CRC32(); + + /* Zero this so the current byte from before the seek is not written */ + bz.writeCopies = 0; + + /* Decompress the block and write to stdout */ + bz._read_bunzip(); + // XXX keep writing? + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); +}; +/* Reads bzip2 file from stream or buffer `input`, and invoke + * `callback(position, size)` once for each bzip2 block, + * where position gives the starting position (in *bits*) + * and size gives uncompressed size of the block (in *bytes*). */ +const table = function(input, callback, multistream) { + // make a stream from a buffer, if necessary + var inputStream = new Stream(); + inputStream.delegate = coerceInputStream(input); + inputStream.pos = 0; + inputStream.readByte = function() { + this.pos++; + return this.delegate.readByte(); + }; + if (inputStream.delegate.eof) { + inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); + } + var outputStream = new Stream(); + outputStream.pos = 0; + outputStream.writeByte = function() { this.pos++; }; + + var bz = new Bunzip(inputStream, outputStream); + var blockSize = bz.dbufSize; + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + + var position = inputStream.pos*8 + bz.reader.bitOffset; + if (bz.reader.hasByte) { position -= 8; } + + if (bz._init_block()) { + var start = outputStream.pos; + bz._read_bunzip(); + callback(position, outputStream.pos - start); + } else { + bz.reader.read(32); // (but we ignore the crc) + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + console.assert(bz.dbufSize === blockSize, + "shouldn't change block size within multistream file"); + } else break; + } + } +}; + +var lib = { + Bunzip, + Stream, + Err, + decode, + decodeBlock, + table +}; + +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null +}, [lib]); + +exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket; +exports.CleartextMessage = CleartextMessage; +exports.CompressedDataPacket = CompressedDataPacket; +exports.LiteralDataPacket = LiteralDataPacket; +exports.MarkerPacket = MarkerPacket; +exports.Message = Message; +exports.OnePassSignaturePacket = OnePassSignaturePacket; +exports.PacketList = PacketList; +exports.PaddingPacket = PaddingPacket; +exports.PrivateKey = PrivateKey; +exports.PublicKey = PublicKey; +exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket; +exports.PublicKeyPacket = PublicKeyPacket; +exports.PublicSubkeyPacket = PublicSubkeyPacket; +exports.SecretKeyPacket = SecretKeyPacket; +exports.SecretSubkeyPacket = SecretSubkeyPacket; +exports.Signature = Signature; +exports.SignaturePacket = SignaturePacket; +exports.Subkey = Subkey; +exports.SymEncryptedIntegrityProtectedDataPacket = SymEncryptedIntegrityProtectedDataPacket; +exports.SymEncryptedSessionKeyPacket = SymEncryptedSessionKeyPacket; +exports.SymmetricallyEncryptedDataPacket = SymmetricallyEncryptedDataPacket; +exports.TrustPacket = TrustPacket; +exports.UnparseablePacket = UnparseablePacket; +exports.UserAttributePacket = UserAttributePacket; +exports.UserIDPacket = UserIDPacket; +exports.armor = armor; +exports.config = config; +exports.createCleartextMessage = createCleartextMessage; +exports.createMessage = createMessage; +exports.decrypt = decrypt; +exports.decryptKey = decryptKey; +exports.decryptSessionKeys = decryptSessionKeys; +exports.encrypt = encrypt; +exports.encryptKey = encryptKey; +exports.encryptSessionKey = encryptSessionKey; +exports.enums = enums; +exports.generateKey = generateKey; +exports.generateSessionKey = generateSessionKey; +exports.readCleartextMessage = readCleartextMessage; +exports.readKey = readKey; +exports.readKeys = readKeys; +exports.readMessage = readMessage; +exports.readPrivateKey = readPrivateKey; +exports.readPrivateKeys = readPrivateKeys; +exports.readSignature = readSignature; +exports.reformatKey = reformatKey; +exports.revokeKey = revokeKey; +exports.sign = sign; +exports.unarmor = unarmor; +exports.verify = verify; diff --git a/app/node_modules/openpgp/dist/node/openpgp.js b/app/node_modules/openpgp/dist/node/openpgp.js deleted file mode 100644 index 72a0ea578..000000000 --- a/app/node_modules/openpgp/dist/node/openpgp.js +++ /dev/null @@ -1,44142 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -'use strict'; - -const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var buffer = require('buffer'); -var stream$1 = require('stream'); -var crypto$3 = require('crypto'); -var zlib = require('zlib'); -var os = require('os'); -var util$1 = require('util'); -var asn1$2 = require('asn1.js'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -var buffer__default = /*#__PURE__*/_interopDefaultLegacy(buffer); -var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$1); -var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto$3); -var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); -var os__default = /*#__PURE__*/_interopDefaultLegacy(os); -var util__default = /*#__PURE__*/_interopDefaultLegacy(util$1); -var asn1__default = /*#__PURE__*/_interopDefaultLegacy(asn1$2); - -const doneWritingPromise = Symbol('doneWritingPromise'); -const doneWritingResolve = Symbol('doneWritingResolve'); -const doneWritingReject = Symbol('doneWritingReject'); - -const readingIndex = Symbol('readingIndex'); - -class ArrayStream extends Array { - constructor() { - super(); - this[doneWritingPromise] = new Promise((resolve, reject) => { - this[doneWritingResolve] = resolve; - this[doneWritingReject] = reject; - }); - this[doneWritingPromise].catch(() => {}); - } -} - -ArrayStream.prototype.getReader = function() { - if (this[readingIndex] === undefined) { - this[readingIndex] = 0; - } - return { - read: async () => { - await this[doneWritingPromise]; - if (this[readingIndex] === this.length) { - return { value: undefined, done: true }; - } - return { value: this[this[readingIndex]++], done: false }; - } - }; -}; - -ArrayStream.prototype.readToEnd = async function(join) { - await this[doneWritingPromise]; - const result = join(this.slice(this[readingIndex])); - this.length = 0; - return result; -}; - -ArrayStream.prototype.clone = function() { - const clone = new ArrayStream(); - clone[doneWritingPromise] = this[doneWritingPromise].then(() => { - clone.push(...this); - }); - return clone; -}; - -/** - * Check whether data is an ArrayStream - * @param {Any} input data to check - * @returns {boolean} - */ -function isArrayStream(input) { - return input && input.getReader && Array.isArray(input); -} - -/** - * A wrapper class over the native WritableStreamDefaultWriter. - * It also lets you "write data to" array streams instead of streams. - * @class - */ -function Writer(input) { - if (!isArrayStream(input)) { - const writer = input.getWriter(); - const releaseLock = writer.releaseLock; - writer.releaseLock = () => { - writer.closed.catch(function() {}); - releaseLock.call(writer); - }; - return writer; - } - this.stream = input; -} - -/** - * Write a chunk of data. - * @returns {Promise} - * @async - */ -Writer.prototype.write = async function(chunk) { - this.stream.push(chunk); -}; - -/** - * Close the stream. - * @returns {Promise} - * @async - */ -Writer.prototype.close = async function() { - this.stream[doneWritingResolve](); -}; - -/** - * Error the stream. - * @returns {Promise} - * @async - */ -Writer.prototype.abort = async function(reason) { - this.stream[doneWritingReject](reason); - return reason; -}; - -/** - * Release the writer's lock. - * @returns {undefined} - * @async - */ -Writer.prototype.releaseLock = function() {}; - -const isNode = typeof globalThis.process === 'object' && - typeof globalThis.process.versions === 'object'; - -const NodeReadableStream = isNode && stream__default['default'].Readable; - -/** - * Check whether data is a Stream, and if so of which type - * @param {Any} input data to check - * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false} - */ -function isStream(input) { - if (isArrayStream(input)) { - return 'array'; - } - if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { - return 'web'; - } - if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) { - return 'ponyfill'; - } - if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) { - return 'node'; - } - if (input && input.getReader) { - return 'web-like'; - } - return false; -} - -/** - * Check whether data is a Uint8Array - * @param {Any} input data to check - * @returns {Boolean} - */ -function isUint8Array(input) { - return Uint8Array.prototype.isPrototypeOf(input); -} - -/** - * Concat Uint8Arrays - * @param {Array} Array of Uint8Arrays to concatenate - * @returns {Uint8array} Concatenated array - */ -function concatUint8Array(arrays) { - if (arrays.length === 1) return arrays[0]; - - let totalLength = 0; - for (let i = 0; i < arrays.length; i++) { - if (!isUint8Array(arrays[i])) { - throw new Error('concatUint8Array: Data must be in the form of a Uint8Array'); - } - - totalLength += arrays[i].length; - } - - const result = new Uint8Array(totalLength); - let pos = 0; - arrays.forEach(function (element) { - result.set(element, pos); - pos += element.length; - }); - - return result; -} - -const NodeBuffer = isNode && buffer__default['default'].Buffer; -const NodeReadableStream$1 = isNode && stream__default['default'].Readable; - -/** - * Web / node stream conversion functions - * From https://github.com/gwicke/node-web-streams - */ - -let nodeToWeb; -let webToNode; - -if (NodeReadableStream$1) { - - /** - * Convert a Node Readable Stream to a Web ReadableStream - * @param {Readable} nodeStream - * @returns {ReadableStream} - */ - nodeToWeb = function(nodeStream) { - let canceled = false; - return new ReadableStream({ - start(controller) { - nodeStream.pause(); - nodeStream.on('data', chunk => { - if (canceled) { - return; - } - if (NodeBuffer.isBuffer(chunk)) { - chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - controller.enqueue(chunk); - nodeStream.pause(); - }); - nodeStream.on('end', () => { - if (canceled) { - return; - } - controller.close(); - }); - nodeStream.on('error', e => controller.error(e)); - }, - pull() { - nodeStream.resume(); - }, - cancel(reason) { - canceled = true; - nodeStream.destroy(reason); - } - }); - }; - - - class NodeReadable extends NodeReadableStream$1 { - constructor(webStream, options) { - super(options); - this._reader = getReader(webStream); - } - - async _read(size) { - try { - while (true) { - const { done, value } = await this._reader.read(); - if (done) { - this.push(null); - break; - } - if (!this.push(value)) { - break; - } - } - } catch (e) { - this.destroy(e); - } - } - - async _destroy(error, callback) { - this._reader.cancel(error).then(callback, callback); - } - } - - /** - * Convert a Web ReadableStream to a Node Readable Stream - * @param {ReadableStream} webStream - * @param {Object} options - * @returns {Readable} - */ - webToNode = function(webStream, options) { - return new NodeReadable(webStream, options); - }; - -} - -const doneReadingSet = new WeakSet(); -const externalBuffer = Symbol('externalBuffer'); - -/** - * A wrapper class over the native ReadableStreamDefaultReader. - * This additionally implements pushing back data on the stream, which - * lets us implement peeking and a host of convenience functions. - * It also lets you read data other than streams, such as a Uint8Array. - * @class - */ -function Reader(input) { - this.stream = input; - if (input[externalBuffer]) { - this[externalBuffer] = input[externalBuffer].slice(); - } - if (isArrayStream(input)) { - const reader = input.getReader(); - this._read = reader.read.bind(reader); - this._releaseLock = () => {}; - this._cancel = async () => {}; - return; - } - let streamType = isStream(input); - if (streamType === 'node') { - input = nodeToWeb(input); - } - if (streamType) { - const reader = input.getReader(); - this._read = reader.read.bind(reader); - this._releaseLock = () => { - reader.closed.catch(function() {}); - reader.releaseLock(); - }; - this._cancel = reader.cancel.bind(reader); - return; - } - let doneReading = false; - this._read = async () => { - if (doneReading || doneReadingSet.has(input)) { - return { value: undefined, done: true }; - } - doneReading = true; - return { value: input, done: false }; - }; - this._releaseLock = () => { - if (doneReading) { - try { - doneReadingSet.add(input); - } catch(e) {} - } - }; -} - -/** - * Read a chunk of data. - * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined } - * @async - */ -Reader.prototype.read = async function() { - if (this[externalBuffer] && this[externalBuffer].length) { - const value = this[externalBuffer].shift(); - return { done: false, value }; - } - return this._read(); -}; - -/** - * Allow others to read the stream. - */ -Reader.prototype.releaseLock = function() { - if (this[externalBuffer]) { - this.stream[externalBuffer] = this[externalBuffer]; - } - this._releaseLock(); -}; - -/** - * Cancel the stream. - */ -Reader.prototype.cancel = function(reason) { - return this._cancel(reason); -}; - -/** - * Read up to and including the first \n character. - * @returns {Promise} - * @async - */ -Reader.prototype.readLine = async function() { - let buffer = []; - let returnVal; - while (!returnVal) { - let { done, value } = await this.read(); - value += ''; - if (done) { - if (buffer.length) return concat(buffer); - return; - } - const lineEndIndex = value.indexOf('\n') + 1; - if (lineEndIndex) { - returnVal = concat(buffer.concat(value.substr(0, lineEndIndex))); - buffer = []; - } - if (lineEndIndex !== value.length) { - buffer.push(value.substr(lineEndIndex)); - } - } - this.unshift(...buffer); - return returnVal; -}; - -/** - * Read a single byte/character. - * @returns {Promise} - * @async - */ -Reader.prototype.readByte = async function() { - const { done, value } = await this.read(); - if (done) return; - const byte = value[0]; - this.unshift(slice(value, 1)); - return byte; -}; - -/** - * Read a specific amount of bytes/characters, unless the stream ends before that amount. - * @returns {Promise} - * @async - */ -Reader.prototype.readBytes = async function(length) { - const buffer = []; - let bufferLength = 0; - while (true) { - const { done, value } = await this.read(); - if (done) { - if (buffer.length) return concat(buffer); - return; - } - buffer.push(value); - bufferLength += value.length; - if (bufferLength >= length) { - const bufferConcat = concat(buffer); - this.unshift(slice(bufferConcat, length)); - return slice(bufferConcat, 0, length); - } - } -}; - -/** - * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount. - * @returns {Promise} - * @async - */ -Reader.prototype.peekBytes = async function(length) { - const bytes = await this.readBytes(length); - this.unshift(bytes); - return bytes; -}; - -/** - * Push data to the front of the stream. - * Data must have been read in the last call to read*. - * @param {...(Uint8Array|String|Undefined)} values - */ -Reader.prototype.unshift = function(...values) { - if (!this[externalBuffer]) { - this[externalBuffer] = []; - } - if ( - values.length === 1 && isUint8Array(values[0]) && - this[externalBuffer].length && values[0].length && - this[externalBuffer][0].byteOffset >= values[0].length - ) { - this[externalBuffer][0] = new Uint8Array( - this[externalBuffer][0].buffer, - this[externalBuffer][0].byteOffset - values[0].length, - this[externalBuffer][0].byteLength + values[0].length - ); - return; - } - this[externalBuffer].unshift(...values.filter(value => value && value.length)); -}; - -/** - * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat). - * @param {Function} join - * @returns {Promise} the return value of join() - * @async - */ -Reader.prototype.readToEnd = async function(join=concat) { - const result = []; - while (true) { - const { done, value } = await this.read(); - if (done) break; - result.push(value); - } - return join(result); -}; - -let { ReadableStream, WritableStream, TransformStream } = globalThis; - -let toPonyfillReadable, toNativeReadable; - -async function loadStreamsPonyfill() { - if (TransformStream) { - return; - } - - const [ponyfill, adapter] = await Promise.all([ - Promise.resolve().then(function () { return ponyfill_es6; }), - Promise.resolve().then(function () { return webStreamsAdapter; }) - ]); - - ({ ReadableStream, WritableStream, TransformStream } = ponyfill); - - const { createReadableStreamWrapper } = adapter; - - if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) { - toPonyfillReadable = createReadableStreamWrapper(ReadableStream); - toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream); - } -} - -const NodeBuffer$1 = isNode && buffer__default['default'].Buffer; - -/** - * Convert data to Stream - * @param {ReadableStream|Uint8array|String} input data to convert - * @returns {ReadableStream} Converted data - */ -function toStream(input) { - let streamType = isStream(input); - if (streamType === 'node') { - return nodeToWeb(input); - } - if (streamType === 'web' && toPonyfillReadable) { - return toPonyfillReadable(input); - } - if (streamType) { - return input; - } - return new ReadableStream({ - start(controller) { - controller.enqueue(input); - controller.close(); - } - }); -} - -/** - * Convert data to ArrayStream - * @param {Object} input data to convert - * @returns {ArrayStream} Converted data - */ -function toArrayStream(input) { - if (isStream(input)) { - return input; - } - const stream = new ArrayStream(); - (async () => { - const writer = getWriter(stream); - await writer.write(input); - await writer.close(); - })(); - return stream; -} - -/** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate - * @returns {Uint8array|String|ReadableStream} Concatenated array - */ -function concat(list) { - if (list.some(stream => isStream(stream) && !isArrayStream(stream))) { - return concatStream(list); - } - if (list.some(stream => isArrayStream(stream))) { - return concatArrayStream(list); - } - if (typeof list[0] === 'string') { - return list.join(''); - } - if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) { - return NodeBuffer$1.concat(list); - } - return concatUint8Array(list); -} - -/** - * Concat a list of Streams - * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate - * @returns {ReadableStream} Concatenated list - */ -function concatStream(list) { - list = list.map(toStream); - const transform = transformWithCancel(async function(reason) { - await Promise.all(transforms.map(stream => cancel(stream, reason))); - }); - let prev = Promise.resolve(); - const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => { - prev = prev.then(() => pipe(readable, transform.writable, { - preventClose: i !== list.length - 1 - })); - return prev; - })); - return transform.readable; -} - -/** - * Concat a list of ArrayStreams - * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate - * @returns {ArrayStream} Concatenated streams - */ -function concatArrayStream(list) { - const result = new ArrayStream(); - let prev = Promise.resolve(); - list.forEach((stream, i) => { - prev = prev.then(() => pipe(stream, result, { - preventClose: i !== list.length - 1 - })); - return prev; - }); - return result; -} - -/** - * Get a Reader - * @param {ReadableStream|Uint8array|String} input - * @returns {Reader} - */ -function getReader(input) { - return new Reader(input); -} - -/** - * Get a Writer - * @param {WritableStream} input - * @returns {Writer} - */ -function getWriter(input) { - return new Writer(input); -} - -/** - * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. - * @param {ReadableStream|Uint8array|String} input - * @param {WritableStream} target - * @param {Object} (optional) options - * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored) - * @async - */ -async function pipe(input, target, { - preventClose = false, - preventAbort = false, - preventCancel = false -} = {}) { - if (isStream(input) && !isArrayStream(input)) { - input = toStream(input); - try { - if (input[externalBuffer]) { - const writer = getWriter(target); - for (let i = 0; i < input[externalBuffer].length; i++) { - await writer.ready; - await writer.write(input[externalBuffer][i]); - } - writer.releaseLock(); - } - await input.pipeTo(target, { - preventClose, - preventAbort, - preventCancel - }); - } catch(e) {} - return; - } - input = toArrayStream(input); - const reader = getReader(input); - const writer = getWriter(target); - try { - while (true) { - await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (!preventClose) await writer.close(); - break; - } - await writer.write(value); - } - } catch (e) { - if (!preventAbort) await writer.abort(e); - } finally { - reader.releaseLock(); - writer.releaseLock(); - } -} - -/** - * Pipe a readable stream through a transform stream. - * @param {ReadableStream|Uint8array|String} input - * @param {Object} (optional) options - * @returns {ReadableStream} transformed stream - */ -function transformRaw(input, options) { - const transformStream = new TransformStream(options); - pipe(input, transformStream.writable); - return transformStream.readable; -} - -/** - * Create a cancelable TransformStream. - * @param {Function} cancel - * @returns {TransformStream} - */ -function transformWithCancel(customCancel) { - let pulled = false; - let cancelled = false; - let backpressureChangePromiseResolve, backpressureChangePromiseReject; - let outputController; - return { - readable: new ReadableStream({ - start(controller) { - outputController = controller; - }, - pull() { - if (backpressureChangePromiseResolve) { - backpressureChangePromiseResolve(); - } else { - pulled = true; - } - }, - async cancel(reason) { - cancelled = true; - if (customCancel) { - await customCancel(reason); - } - if (backpressureChangePromiseReject) { - backpressureChangePromiseReject(reason); - } - } - }, {highWaterMark: 0}), - writable: new WritableStream({ - write: async function(chunk) { - if (cancelled) { - throw new Error('Stream is cancelled'); - } - outputController.enqueue(chunk); - if (!pulled) { - await new Promise((resolve, reject) => { - backpressureChangePromiseResolve = resolve; - backpressureChangePromiseReject = reject; - }); - backpressureChangePromiseResolve = null; - backpressureChangePromiseReject = null; - } else { - pulled = false; - } - }, - close: outputController.close.bind(outputController), - abort: outputController.error.bind(outputController) - }) - }; -} - -/** - * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively. - * @param {ReadableStream|Uint8array|String} input - * @param {Function} process - * @param {Function} finish - * @returns {ReadableStream|Uint8array|String} - */ -function transform(input, process = () => undefined, finish = () => undefined) { - if (isArrayStream(input)) { - const output = new ArrayStream(); - (async () => { - const writer = getWriter(output); - try { - const data = await readToEnd(input); - const result1 = process(data); - const result2 = finish(); - let result; - if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]); - else result = result1 !== undefined ? result1 : result2; - await writer.write(result); - await writer.close(); - } catch (e) { - await writer.abort(e); - } - })(); - return output; - } - if (isStream(input)) { - return transformRaw(input, { - async transform(value, controller) { - try { - const result = await process(value); - if (result !== undefined) controller.enqueue(result); - } catch(e) { - controller.error(e); - } - }, - async flush(controller) { - try { - const result = await finish(); - if (result !== undefined) controller.enqueue(result); - } catch(e) { - controller.error(e); - } - } - }); - } - const result1 = process(input); - const result2 = finish(); - if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]); - return result1 !== undefined ? result1 : result2; -} - -/** - * Transform a stream using a helper function which is passed a readable and a writable stream. - * This function also maintains the possibility to cancel the input stream, - * and does so on cancelation of the output stream, despite cancelation - * normally being impossible when the input stream is being read from. - * @param {ReadableStream|Uint8array|String} input - * @param {Function} fn - * @returns {ReadableStream} - */ -function transformPair(input, fn) { - if (isStream(input) && !isArrayStream(input)) { - let incomingTransformController; - const incoming = new TransformStream({ - start(controller) { - incomingTransformController = controller; - } - }); - - const pipeDonePromise = pipe(input, incoming.writable); - - const outgoing = transformWithCancel(async function(reason) { - incomingTransformController.error(reason); - await pipeDonePromise; - await new Promise(setTimeout); - }); - fn(incoming.readable, outgoing.writable); - return outgoing.readable; - } - input = toArrayStream(input); - const output = new ArrayStream(); - fn(input, output); - return output; -} - -/** - * Parse a stream using a helper function which is passed a Reader. - * The reader additionally has a remainder() method which returns a - * stream pointing to the remainder of input, and is linked to input - * for cancelation. - * @param {ReadableStream|Uint8array|String} input - * @param {Function} fn - * @returns {Any} the return value of fn() - */ -function parse(input, fn) { - let returnValue; - const transformed = transformPair(input, (readable, writable) => { - const reader = getReader(readable); - reader.remainder = () => { - reader.releaseLock(); - pipe(readable, writable); - return transformed; - }; - returnValue = fn(reader); - }); - return returnValue; -} - -/** - * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing. - * Reading either of the two returned streams will pull from the input stream. - * The input stream will only be canceled if both of the returned streams are canceled. - * @param {ReadableStream|Uint8array|String} input - * @returns {Array} array containing two copies of input - */ -function tee(input) { - if (isArrayStream(input)) { - throw new Error('ArrayStream cannot be tee()d, use clone() instead'); - } - if (isStream(input)) { - const teed = toStream(input).tee(); - teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer]; - return teed; - } - return [slice(input), slice(input)]; -} - -/** - * Clone a Stream for reading it twice. The input stream can still be read after clone()ing. - * Reading from the clone will pull from the input stream. - * The input stream will only be canceled if both the clone and the input stream are canceled. - * @param {ReadableStream|Uint8array|String} input - * @returns {ReadableStream|Uint8array|String} cloned input - */ -function clone(input) { - if (isArrayStream(input)) { - return input.clone(); - } - if (isStream(input)) { - const teed = tee(input); - overwrite(input, teed[0]); - return teed[1]; - } - return slice(input); -} - -/** - * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read. - * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream. - * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled. - * If the input stream is canceled, the clone will be errored. - * @param {ReadableStream|Uint8array|String} input - * @returns {ReadableStream|Uint8array|String} cloned input - */ -function passiveClone(input) { - if (isArrayStream(input)) { - return clone(input); - } - if (isStream(input)) { - return new ReadableStream({ - start(controller) { - const transformed = transformPair(input, async (readable, writable) => { - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const { done, value } = await reader.read(); - if (done) { - try { controller.close(); } catch(e) {} - await writer.close(); - return; - } - try { controller.enqueue(value); } catch(e) {} - await writer.write(value); - } - } catch(e) { - controller.error(e); - await writer.abort(e); - } - }); - overwrite(input, transformed); - } - }); - } - return slice(input); -} - -/** - * Modify a stream object to point to a different stream object. - * This is used internally by clone() and passiveClone() to provide an abstraction over tee(). - * @param {ReadableStream} input - * @param {ReadableStream} clone - */ -function overwrite(input, clone) { - // Overwrite input.getReader, input.locked, etc to point to clone - Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => { - if (name === 'constructor') { - return; - } - if (descriptor.value) { - descriptor.value = descriptor.value.bind(clone); - } else { - descriptor.get = descriptor.get.bind(clone); - } - Object.defineProperty(input, name, descriptor); - }); -} - -/** - * Return a stream pointing to a part of the input stream. - * @param {ReadableStream|Uint8array|String} input - * @returns {ReadableStream|Uint8array|String} clone - */ -function slice(input, begin=0, end=Infinity) { - if (isArrayStream(input)) { - throw new Error('Not implemented'); - } - if (isStream(input)) { - if (begin >= 0 && end >= 0) { - let bytesRead = 0; - return transformRaw(input, { - transform(value, controller) { - if (bytesRead < end) { - if (bytesRead + value.length >= begin) { - controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead)); - } - bytesRead += value.length; - } else { - controller.terminate(); - } - } - }); - } - if (begin < 0 && (end < 0 || end === Infinity)) { - let lastBytes = []; - return transform(input, value => { - if (value.length >= -begin) lastBytes = [value]; - else lastBytes.push(value); - }, () => slice(concat(lastBytes), begin, end)); - } - if (begin === 0 && end < 0) { - let lastBytes; - return transform(input, value => { - const returnValue = lastBytes ? concat([lastBytes, value]) : value; - if (returnValue.length >= -end) { - lastBytes = slice(returnValue, end); - return slice(returnValue, begin, end); - } else { - lastBytes = returnValue; - } - }); - } - console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); - return fromAsync(async () => slice(await readToEnd(input), begin, end)); - } - if (input[externalBuffer]) { - input = concat(input[externalBuffer].concat([input])); - } - if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) { - if (end === Infinity) end = input.length; - return input.subarray(begin, end); - } - return input.slice(begin, end); -} - -/** - * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat). - * @param {ReadableStream|Uint8array|String} input - * @param {Function} join - * @returns {Promise} the return value of join() - * @async - */ -async function readToEnd(input, join=concat) { - if (isArrayStream(input)) { - return input.readToEnd(join); - } - if (isStream(input)) { - return getReader(input).readToEnd(join); - } - return input; -} - -/** - * Cancel a stream. - * @param {ReadableStream|Uint8array|String} input - * @param {Any} reason - * @returns {Promise} indicates when the stream has been canceled - * @async - */ -async function cancel(input, reason) { - if (isStream(input)) { - if (input.cancel) { - return input.cancel(reason); - } - if (input.destroy) { - input.destroy(reason); - await new Promise(setTimeout); - return reason; - } - } -} - -/** - * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream. - * @param {Function} fn - * @returns {ArrayStream} - */ -function fromAsync(fn) { - const arrayStream = new ArrayStream(); - (async () => { - const writer = getWriter(arrayStream); - try { - await writer.write(await fn()); - await writer.close(); - } catch (e) { - await writer.abort(e); - } - })(); - return arrayStream; -} - -/* eslint-disable new-cap */ - -/** - * @fileoverview - * BigInteger implementation of basic operations - * that wraps the native BigInt library. - * Operations are not constant time, - * but we try and limit timing leakage where we can - * @module biginteger/native - * @private - */ - -/** - * @private - */ -class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on null or undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - - if (n instanceof Uint8Array) { - const bytes = n; - const hex = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - const hexByte = bytes[i].toString(16); - hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte; - } - this.value = BigInt('0x0' + hex.join('')); - } else { - this.value = BigInt(n); - } - } - - clone() { - return new BigInteger(this.value); - } - - /** - * BigInteger increment in place - */ - iinc() { - this.value++; - return this; - } - - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - - /** - * BigInteger decrement in place - */ - idec() { - this.value--; - return this; - } - - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } - - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value += x.value; - return this; - } - - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } - - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value -= x.value; - return this; - } - - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } - - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value *= x.value; - return this; - } - - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); - } - - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value %= m.value; - if (this.isNegative()) { - this.iadd(m); - } - return this; - } - - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } - - /** - * Compute modular exponentiation using square and multiply - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - if (n.isZero()) throw Error('Modulo cannot be zero'); - if (n.isOne()) return new BigInteger(0); - if (e.isNegative()) throw Error('Unsopported negative exponent'); - - let exp = e.value; - let x = this.value; - - x %= n.value; - let r = BigInt(1); - while (exp > BigInt(0)) { - const lsb = exp & BigInt(1); - exp >>= BigInt(1); // e / 2 - // Always compute multiplication step, to reduce timing leakage - const rx = (r * x) % n.value; - // Update r only if lsb is 1 (odd exponent) - r = lsb ? rx : r; - x = (x * x) % n.value; // Square - } - return new BigInteger(r); - } - - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - const { gcd, x } = this._egcd(n); - if (!gcd.isOne()) { - throw new Error('Inverse does not exist'); - } - return x.add(n).mod(n); - } - - /** - * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) - * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b) - * @param {BigInteger} b - Second operand - * @returns {{ gcd, x, y: BigInteger }} - */ - _egcd(b) { - let x = BigInt(0); - let y = BigInt(1); - let xPrev = BigInt(1); - let yPrev = BigInt(0); - - let a = this.value; - b = b.value; - - while (b !== BigInt(0)) { - const q = a / b; - let tmp = x; - x = xPrev - q * x; - xPrev = tmp; - - tmp = y; - y = yPrev - q * y; - yPrev = tmp; - - tmp = b; - b = a % b; - a = tmp; - } - - return { - x: new BigInteger(xPrev), - y: new BigInteger(yPrev), - gcd: new BigInteger(a) - }; - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} b - Operand - * @returns {BigInteger} gcd - */ - gcd(b) { - let a = this.value; - b = b.value; - while (b !== BigInt(0)) { - const tmp = b; - b = a % b; - a = tmp; - } - return new BigInteger(a); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value <<= x.value; - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value >>= x.value; - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value === x.value; - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value < x.value; - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value <= x.value; - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value > x.value; - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value >= x.value; - } - - isZero() { - return this.value === BigInt(0); - } - - isOne() { - return this.value === BigInt(1); - } - - isNegative() { - return this.value < BigInt(0); - } - - isEven() { - return !(this.value & BigInt(1)); - } - - abs() { - const res = this.clone(); - if (this.isNegative()) { - res.value = -res.value; - } - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - const number = Number(this.value); - if (number > Number.MAX_SAFE_INTEGER) { - // We throw and error to conform with the bn.js implementation - throw new Error('Number can only safely store up to 53 bits'); - } - return number; - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - const bit = (this.value >> BigInt(i)) & BigInt(1); - return (bit === BigInt(0)) ? 0 : 1; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - const zero = new BigInteger(0); - const one = new BigInteger(1); - const negOne = new BigInteger(-1); - - // -1n >> -1n is -1n - // 1n >> 1n is 0n - const target = this.isNegative() ? negOne : zero; - let bitlen = 1; - const tmp = this.clone(); - while (!tmp.irightShift(one).equal(target)) { - bitlen++; - } - return bitlen; - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - const zero = new BigInteger(0); - const negOne = new BigInteger(-1); - - const target = this.isNegative() ? negOne : zero; - const eight = new BigInteger(8); - let len = 1; - const tmp = this.clone(); - while (!tmp.irightShift(eight).equal(target)) { - len++; - } - return len; - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) - // this is faster than shift+mod iterations - let hex = this.value.toString(16); - if (hex.length % 2 === 1) { - hex = '0' + hex; - } - - const rawLength = hex.length / 2; - const bytes = new Uint8Array(length || rawLength); - // parse hex - const offset = length ? (length - rawLength) : 0; - let i = 0; - while (i < rawLength) { - bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); - i++; - } - - if (endian !== 'be') { - bytes.reverse(); - } - - return bytes; - } -} - -const detectBigInt = () => typeof BigInt !== 'undefined'; - -async function getBigInteger() { - if (detectBigInt()) { - return BigInteger; - } else { - const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; }); - return BigInteger; - } -} - -/** - * @module enums - */ - -const byValue = Symbol('byValue'); - -var enums = { - - /** Maps curve names under various standards to one - * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} - * @enum {String} - * @readonly - */ - curve: { - /** NIST P-256 Curve */ - 'p256': 'p256', - 'P-256': 'p256', - 'secp256r1': 'p256', - 'prime256v1': 'p256', - '1.2.840.10045.3.1.7': 'p256', - '2a8648ce3d030107': 'p256', - '2A8648CE3D030107': 'p256', - - /** NIST P-384 Curve */ - 'p384': 'p384', - 'P-384': 'p384', - 'secp384r1': 'p384', - '1.3.132.0.34': 'p384', - '2b81040022': 'p384', - '2B81040022': 'p384', - - /** NIST P-521 Curve */ - 'p521': 'p521', - 'P-521': 'p521', - 'secp521r1': 'p521', - '1.3.132.0.35': 'p521', - '2b81040023': 'p521', - '2B81040023': 'p521', - - /** SECG SECP256k1 Curve */ - 'secp256k1': 'secp256k1', - '1.3.132.0.10': 'secp256k1', - '2b8104000a': 'secp256k1', - '2B8104000A': 'secp256k1', - - /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ - 'ed25519Legacy': 'ed25519', - 'ED25519': 'ed25519', - /** @deprecated use `ed25519Legacy` instead */ - 'ed25519': 'ed25519', - 'Ed25519': 'ed25519', - '1.3.6.1.4.1.11591.15.1': 'ed25519', - '2b06010401da470f01': 'ed25519', - '2B06010401DA470F01': 'ed25519', - - /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ - 'curve25519Legacy': 'curve25519', - 'X25519': 'curve25519', - 'cv25519': 'curve25519', - /** @deprecated use `curve25519Legacy` instead */ - 'curve25519': 'curve25519', - 'Curve25519': 'curve25519', - '1.3.6.1.4.1.3029.1.5.1': 'curve25519', - '2b060104019755010501': 'curve25519', - '2B060104019755010501': 'curve25519', - - /** BrainpoolP256r1 Curve */ - 'brainpoolP256r1': 'brainpoolP256r1', - '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1', - '2b2403030208010107': 'brainpoolP256r1', - '2B2403030208010107': 'brainpoolP256r1', - - /** BrainpoolP384r1 Curve */ - 'brainpoolP384r1': 'brainpoolP384r1', - '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1', - '2b240303020801010b': 'brainpoolP384r1', - '2B240303020801010B': 'brainpoolP384r1', - - /** BrainpoolP512r1 Curve */ - 'brainpoolP512r1': 'brainpoolP512r1', - '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1', - '2b240303020801010d': 'brainpoolP512r1', - '2B240303020801010D': 'brainpoolP512r1' - }, - - /** A string to key specifier type - * @enum {Integer} - * @readonly - */ - s2k: { - simple: 0, - salted: 1, - iterated: 3, - gnu: 101 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} - * @enum {Integer} - * @readonly - */ - publicKey: { - /** RSA (Encrypt or Sign) [HAC] */ - rsaEncryptSign: 1, - /** RSA (Encrypt only) [HAC] */ - rsaEncrypt: 2, - /** RSA (Sign only) [HAC] */ - rsaSign: 3, - /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ - elgamal: 16, - /** DSA (Sign only) [FIPS186] [HAC] */ - dsa: 17, - /** ECDH (Encrypt only) [RFC6637] */ - ecdh: 18, - /** ECDSA (Sign only) [RFC6637] */ - ecdsa: 19, - /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) - * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ - eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility - /** @deprecated use `eddsaLegacy` instead */ - ed25519Legacy: 22, - /** @deprecated use `eddsaLegacy` instead */ - eddsa: 22, - /** Reserved for AEDH */ - aedh: 23, - /** Reserved for AEDSA */ - aedsa: 24, - /** X25519 (Encrypt only) */ - x25519: 25, - /** X448 (Encrypt only) */ - x448: 26, - /** Ed25519 (Sign only) */ - ed25519: 27, - /** Ed448 (Sign only) */ - ed448: 28 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - * @enum {Integer} - * @readonly - */ - symmetric: { - plaintext: 0, - /** Not implemented! */ - idea: 1, - tripledes: 2, - cast5: 3, - blowfish: 4, - aes128: 7, - aes192: 8, - aes256: 9, - twofish: 10 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - * @enum {Integer} - * @readonly - */ - compression: { - uncompressed: 0, - /** RFC1951 */ - zip: 1, - /** RFC1950 */ - zlib: 2, - bzip2: 3 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} - * @enum {Integer} - * @readonly - */ - hash: { - md5: 1, - sha1: 2, - ripemd: 3, - sha256: 8, - sha384: 9, - sha512: 10, - sha224: 11 - }, - - /** A list of hash names as accepted by webCrypto functions. - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} - * @enum {String} - */ - webHash: { - 'SHA-1': 2, - 'SHA-256': 8, - 'SHA-384': 9, - 'SHA-512': 10 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} - * @enum {Integer} - * @readonly - */ - aead: { - eax: 1, - ocb: 2, - experimentalGCM: 100 // Private algorithm - }, - - /** A list of packet types and numeric tags associated with them. - * @enum {Integer} - * @readonly - */ - packet: { - publicKeyEncryptedSessionKey: 1, - signature: 2, - symEncryptedSessionKey: 3, - onePassSignature: 4, - secretKey: 5, - publicKey: 6, - secretSubkey: 7, - compressedData: 8, - symmetricallyEncryptedData: 9, - marker: 10, - literalData: 11, - trust: 12, - userID: 13, - publicSubkey: 14, - userAttribute: 17, - symEncryptedIntegrityProtectedData: 18, - modificationDetectionCode: 19, - aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 - }, - - /** Data types in the literal packet - * @enum {Integer} - * @readonly - */ - literal: { - /** Binary data 'b' */ - binary: 'b'.charCodeAt(), - /** Text data 't' */ - text: 't'.charCodeAt(), - /** Utf8 data 'u' */ - utf8: 'u'.charCodeAt(), - /** MIME message body part 'm' */ - mime: 'm'.charCodeAt() - }, - - - /** One pass signature packet type - * @enum {Integer} - * @readonly - */ - signature: { - /** 0x00: Signature of a binary document. */ - binary: 0, - /** 0x01: Signature of a canonical text document. - * - * Canonicalyzing the document by converting line endings. */ - text: 1, - /** 0x02: Standalone signature. - * - * This signature is a signature of only its own subpacket contents. - * It is calculated identically to a signature over a zero-lengh - * binary document. Note that it doesn't make sense to have a V3 - * standalone signature. */ - standalone: 2, - /** 0x10: Generic certification of a User ID and Public-Key packet. - * - * The issuer of this certification does not make any particular - * assertion as to how well the certifier has checked that the owner - * of the key is in fact the person described by the User ID. */ - certGeneric: 16, - /** 0x11: Persona certification of a User ID and Public-Key packet. - * - * The issuer of this certification has not done any verification of - * the claim that the owner of this key is the User ID specified. */ - certPersona: 17, - /** 0x12: Casual certification of a User ID and Public-Key packet. - * - * The issuer of this certification has done some casual - * verification of the claim of identity. */ - certCasual: 18, - /** 0x13: Positive certification of a User ID and Public-Key packet. - * - * The issuer of this certification has done substantial - * verification of the claim of identity. - * - * Most OpenPGP implementations make their "key signatures" as 0x10 - * certifications. Some implementations can issue 0x11-0x13 - * certifications, but few differentiate between the types. */ - certPositive: 19, - /** 0x30: Certification revocation signature - * - * This signature revokes an earlier User ID certification signature - * (signature class 0x10 through 0x13) or direct-key signature - * (0x1F). It should be issued by the same key that issued the - * revoked signature or an authorized revocation key. The signature - * is computed over the same data as the certificate that it - * revokes, and should have a later creation date than that - * certificate. */ - certRevocation: 48, - /** 0x18: Subkey Binding Signature - * - * This signature is a statement by the top-level signing key that - * indicates that it owns the subkey. This signature is calculated - * directly on the primary key and subkey, and not on any User ID or - * other packets. A signature that binds a signing subkey MUST have - * an Embedded Signature subpacket in this binding signature that - * contains a 0x19 signature made by the signing subkey on the - * primary key and subkey. */ - subkeyBinding: 24, - /** 0x19: Primary Key Binding Signature - * - * This signature is a statement by a signing subkey, indicating - * that it is owned by the primary key and subkey. This signature - * is calculated the same way as a 0x18 signature: directly on the - * primary key and subkey, and not on any User ID or other packets. - * - * When a signature is made over a key, the hash data starts with the - * octet 0x99, followed by a two-octet length of the key, and then body - * of the key packet. (Note that this is an old-style packet header for - * a key packet with two-octet length.) A subkey binding signature - * (type 0x18) or primary key binding signature (type 0x19) then hashes - * the subkey using the same format as the main key (also using 0x99 as - * the first octet). */ - keyBinding: 25, - /** 0x1F: Signature directly on a key - * - * This signature is calculated directly on a key. It binds the - * information in the Signature subpackets to the key, and is - * appropriate to be used for subpackets that provide information - * about the key, such as the Revocation Key subpacket. It is also - * appropriate for statements that non-self certifiers want to make - * about the key itself, rather than the binding between a key and a - * name. */ - key: 31, - /** 0x20: Key revocation signature - * - * The signature is calculated directly on the key being revoked. A - * revoked key is not to be used. Only revocation signatures by the - * key being revoked, or by an authorized revocation key, should be - * considered valid revocation signatures.a */ - keyRevocation: 32, - /** 0x28: Subkey revocation signature - * - * The signature is calculated directly on the subkey being revoked. - * A revoked subkey is not to be used. Only revocation signatures - * by the top-level signature key that is bound to this subkey, or - * by an authorized revocation key, should be considered valid - * revocation signatures. - * - * Key revocation signatures (types 0x20 and 0x28) - * hash only the key being revoked. */ - subkeyRevocation: 40, - /** 0x40: Timestamp signature. - * This signature is only meaningful for the timestamp contained in - * it. */ - timestamp: 64, - /** 0x50: Third-Party Confirmation signature. - * - * This signature is a signature over some other OpenPGP Signature - * packet(s). It is analogous to a notary seal on the signed data. - * A third-party signature SHOULD include Signature Target - * subpacket(s) to give easy identification. Note that we really do - * mean SHOULD. There are plausible uses for this (such as a blind - * party that only sees the signature, not the key or source - * document) that cannot include a target subpacket. */ - thirdParty: 80 - }, - - /** Signature subpacket type - * @enum {Integer} - * @readonly - */ - signatureSubpacket: { - signatureCreationTime: 2, - signatureExpirationTime: 3, - exportableCertification: 4, - trustSignature: 5, - regularExpression: 6, - revocable: 7, - keyExpirationTime: 9, - placeholderBackwardsCompatibility: 10, - preferredSymmetricAlgorithms: 11, - revocationKey: 12, - issuer: 16, - notationData: 20, - preferredHashAlgorithms: 21, - preferredCompressionAlgorithms: 22, - keyServerPreferences: 23, - preferredKeyServer: 24, - primaryUserID: 25, - policyURI: 26, - keyFlags: 27, - signersUserID: 28, - reasonForRevocation: 29, - features: 30, - signatureTarget: 31, - embeddedSignature: 32, - issuerFingerprint: 33, - preferredAEADAlgorithms: 34 - }, - - /** Key flags - * @enum {Integer} - * @readonly - */ - keyFlags: { - /** 0x01 - This key may be used to certify other keys. */ - certifyKeys: 1, - /** 0x02 - This key may be used to sign data. */ - signData: 2, - /** 0x04 - This key may be used to encrypt communications. */ - encryptCommunication: 4, - /** 0x08 - This key may be used to encrypt storage. */ - encryptStorage: 8, - /** 0x10 - The private component of this key may have been split - * by a secret-sharing mechanism. */ - splitPrivateKey: 16, - /** 0x20 - This key may be used for authentication. */ - authentication: 32, - /** 0x80 - The private component of this key may be in the - * possession of more than one person. */ - sharedPrivateKey: 128 - }, - - /** Armor type - * @enum {Integer} - * @readonly - */ - armor: { - multipartSection: 0, - multipartLast: 1, - signed: 2, - message: 3, - publicKey: 4, - privateKey: 5, - signature: 6 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} - * @enum {Integer} - * @readonly - */ - reasonForRevocation: { - /** No reason specified (key revocations or cert revocations) */ - noReason: 0, - /** Key is superseded (key revocations) */ - keySuperseded: 1, - /** Key material has been compromised (key revocations) */ - keyCompromised: 2, - /** Key is retired and no longer used (key revocations) */ - keyRetired: 3, - /** User ID information is no longer valid (cert revocations) */ - userIDInvalid: 32 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} - * @enum {Integer} - * @readonly - */ - features: { - /** 0x01 - Modification Detection (packets 18 and 19) */ - modificationDetection: 1, - /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 - * Symmetric-Key Encrypted Session Key Packets (packet 3) */ - aead: 2, - /** 0x04 - Version 5 Public-Key Packet format and corresponding new - * fingerprint format */ - v5Keys: 4 - }, - - /** - * Asserts validity of given value and converts from string/integer to integer. - * @param {Object} type target enum type - * @param {String|Integer} e value to check and/or convert - * @returns {Integer} enum value if it exists - * @throws {Error} if the value is invalid - */ - write: function(type, e) { - if (typeof e === 'number') { - e = this.read(type, e); - } - - if (type[e] !== undefined) { - return type[e]; - } - - throw new Error('Invalid enum value.'); - }, - - /** - * Converts enum integer value to the corresponding string, if it exists. - * @param {Object} type target enum type - * @param {Integer} e value to convert - * @returns {String} name of enum value if it exists - * @throws {Error} if the value is invalid - */ - read: function(type, e) { - if (!type[byValue]) { - type[byValue] = []; - Object.entries(type).forEach(([key, value]) => { - type[byValue][value] = key; - }); - } - - if (type[byValue][e] !== undefined) { - return type[byValue][e]; - } - - throw new Error('Invalid enum value.'); - } -}; - -const debugMode = (() => { - try { - return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env - } catch (e) {} - return false; -})(); - -const util = { - isString: function(data) { - return typeof data === 'string' || data instanceof String; - }, - - isArray: function(data) { - return data instanceof Array; - }, - - isUint8Array: isUint8Array, - - isStream: isStream, - - readNumber: function (bytes) { - let n = 0; - for (let i = 0; i < bytes.length; i++) { - n += (256 ** i) * bytes[bytes.length - 1 - i]; - } - return n; - }, - - writeNumber: function (n, bytes) { - const b = new Uint8Array(bytes); - for (let i = 0; i < bytes; i++) { - b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF; - } - - return b; - }, - - readDate: function (bytes) { - const n = util.readNumber(bytes); - const d = new Date(n * 1000); - return d; - }, - - writeDate: function (time) { - const numeric = Math.floor(time.getTime() / 1000); - - return util.writeNumber(numeric, 4); - }, - - normalizeDate: function (time = Date.now()) { - return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000); - }, - - /** - * Read one MPI from bytes in input - * @param {Uint8Array} bytes - Input data to parse - * @returns {Uint8Array} Parsed MPI. - */ - readMPI: function (bytes) { - const bits = (bytes[0] << 8) | bytes[1]; - const bytelen = (bits + 7) >>> 3; - return bytes.subarray(2, 2 + bytelen); - }, - - /** - * Left-pad Uint8Array to length by adding 0x0 bytes - * @param {Uint8Array} bytes - Data to pad - * @param {Number} length - Padded length - * @returns {Uint8Array} Padded bytes. - */ - leftPad(bytes, length) { - const padded = new Uint8Array(length); - const offset = length - bytes.length; - padded.set(bytes, offset); - return padded; - }, - - /** - * Convert a Uint8Array to an MPI-formatted Uint8Array. - * @param {Uint8Array} bin - An array of 8-bit integers to convert - * @returns {Uint8Array} MPI-formatted Uint8Array. - */ - uint8ArrayToMPI: function (bin) { - const bitSize = util.uint8ArrayBitLength(bin); - if (bitSize === 0) { - throw new Error('Zero MPI'); - } - const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8)); - const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]); - return util.concatUint8Array([prefix, stripped]); - }, - - /** - * Return bit length of the input data - * @param {Uint8Array} bin input data (big endian) - * @returns bit length - */ - uint8ArrayBitLength: function (bin) { - let i; // index of leading non-zero byte - for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break; - if (i === bin.length) { - return 0; - } - const stripped = bin.subarray(i); - return (stripped.length - 1) * 8 + util.nbits(stripped[0]); - }, - - /** - * Convert a hex string to an array of 8-bit integers - * @param {String} hex - A hex string to convert - * @returns {Uint8Array} An array of 8-bit integers. - */ - hexToUint8Array: function (hex) { - const result = new Uint8Array(hex.length >> 1); - for (let k = 0; k < hex.length >> 1; k++) { - result[k] = parseInt(hex.substr(k << 1, 2), 16); - } - return result; - }, - - /** - * Convert an array of 8-bit integers to a hex string - * @param {Uint8Array} bytes - Array of 8-bit integers to convert - * @returns {String} Hexadecimal representation of the array. - */ - uint8ArrayToHex: function (bytes) { - const r = []; - const e = bytes.length; - let c = 0; - let h; - while (c < e) { - h = bytes[c++].toString(16); - while (h.length < 2) { - h = '0' + h; - } - r.push('' + h); - } - return r.join(''); - }, - - /** - * Convert a string to an array of 8-bit integers - * @param {String} str - String to convert - * @returns {Uint8Array} An array of 8-bit integers. - */ - stringToUint8Array: function (str) { - return transform(str, str => { - if (!util.isString(str)) { - throw new Error('stringToUint8Array: Data must be in the form of a string'); - } - - const result = new Uint8Array(str.length); - for (let i = 0; i < str.length; i++) { - result[i] = str.charCodeAt(i); - } - return result; - }); - }, - - /** - * Convert an array of 8-bit integers to a string - * @param {Uint8Array} bytes - An array of 8-bit integers to convert - * @returns {String} String representation of the array. - */ - uint8ArrayToString: function (bytes) { - bytes = new Uint8Array(bytes); - const result = []; - const bs = 1 << 14; - const j = bytes.length; - - for (let i = 0; i < j; i += bs) { - result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j))); - } - return result.join(''); - }, - - /** - * Convert a native javascript string to a Uint8Array of utf8 bytes - * @param {String|ReadableStream} str - The string to convert - * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes. - */ - encodeUTF8: function (str) { - const encoder = new TextEncoder('utf-8'); - // eslint-disable-next-line no-inner-declarations - function process(value, lastChunk = false) { - return encoder.encode(value, { stream: !lastChunk }); - } - return transform(str, process, () => process('', true)); - }, - - /** - * Convert a Uint8Array of utf8 bytes to a native javascript string - * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes - * @returns {String|ReadableStream} A native javascript string. - */ - decodeUTF8: function (utf8) { - const decoder = new TextDecoder('utf-8'); - // eslint-disable-next-line no-inner-declarations - function process(value, lastChunk = false) { - return decoder.decode(value, { stream: !lastChunk }); - } - return transform(utf8, process, () => process(new Uint8Array(), true)); - }, - - /** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate - * @returns {Uint8Array|String|ReadableStream} Concatenated array. - */ - concat: concat, - - /** - * Concat Uint8Arrays - * @param {Array} Array - Of Uint8Arrays to concatenate - * @returns {Uint8Array} Concatenated array. - */ - concatUint8Array: concatUint8Array, - - /** - * Check Uint8Array equality - * @param {Uint8Array} array1 - First array - * @param {Uint8Array} array2 - Second array - * @returns {Boolean} Equality. - */ - equalsUint8Array: function (array1, array2) { - if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) { - throw new Error('Data must be in the form of a Uint8Array'); - } - - if (array1.length !== array2.length) { - return false; - } - - for (let i = 0; i < array1.length; i++) { - if (array1[i] !== array2[i]) { - return false; - } - } - return true; - }, - - /** - * Calculates a 16bit sum of a Uint8Array by adding each character - * codes modulus 65535 - * @param {Uint8Array} Uint8Array - To create a sum of - * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535. - */ - writeChecksum: function (text) { - let s = 0; - for (let i = 0; i < text.length; i++) { - s = (s + text[i]) & 0xFFFF; - } - return util.writeNumber(s, 2); - }, - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param {String} str - String of the debug message - */ - printDebug: function (str) { - if (debugMode) { - console.log('[OpenPGP.js debug]', str); - } - }, - - /** - * Helper function to print a debug error. Debug - * messages are only printed if - * @param {String} str - String of the debug message - */ - printDebugError: function (error) { - if (debugMode) { - console.error('[OpenPGP.js debug]', error); - } - }, - - // returns bit length of the integer x - nbits: function (x) { - let r = 1; - let t = x >>> 16; - if (t !== 0) { - x = t; - r += 16; - } - t = x >> 8; - if (t !== 0) { - x = t; - r += 8; - } - t = x >> 4; - if (t !== 0) { - x = t; - r += 4; - } - t = x >> 2; - if (t !== 0) { - x = t; - r += 2; - } - t = x >> 1; - if (t !== 0) { - x = t; - r += 1; - } - return r; - }, - - /** - * If S[1] == 0, then double(S) == (S[2..128] || 0); - * otherwise, double(S) == (S[2..128] || 0) xor - * (zeros(120) || 10000111). - * - * Both OCB and EAX (through CMAC) require this function to be constant-time. - * - * @param {Uint8Array} data - */ - double: function(data) { - const doubleVar = new Uint8Array(data.length); - const last = data.length - 1; - for (let i = 0; i < last; i++) { - doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7); - } - doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87); - return doubleVar; - }, - - /** - * Shift a Uint8Array to the right by n bits - * @param {Uint8Array} array - The array to shift - * @param {Integer} bits - Amount of bits to shift (MUST be smaller - * than 8) - * @returns {String} Resulting array. - */ - shiftRight: function (array, bits) { - if (bits) { - for (let i = array.length - 1; i >= 0; i--) { - array[i] >>= bits; - if (i > 0) { - array[i] |= (array[i - 1] << (8 - bits)); - } - } - } - return array; - }, - - /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. - */ - getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; - }, - - /** - * Get BigInteger class - * It wraps the native BigInt type if it's available - * Otherwise it relies on bn.js - * @returns {BigInteger} - * @async - */ - getBigInteger, - - /** - * Get native Node.js crypto api. - * @returns {Object} The crypto module or 'undefined'. - */ - getNodeCrypto: function() { - return crypto__default['default']; - }, - - getNodeZlib: function() { - return zlib__default['default']; - }, - - /** - * Get native Node.js Buffer constructor. This should be used since - * Buffer is not available under browserify. - * @returns {Function} The Buffer constructor or 'undefined'. - */ - getNodeBuffer: function() { - return (buffer__default['default'] || {}).Buffer; - }, - - getHardwareConcurrency: function() { - if (typeof navigator !== 'undefined') { - return navigator.hardwareConcurrency || 1; - } - - const os = os__default['default']; // Assume we're on Node.js. - return os.cpus().length; - }, - - isEmailAddress: function(data) { - if (!util.isString(data)) { - return false; - } - const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/; - return re.test(data); - }, - - /** - * Normalize line endings to - * Support any encoding where CR=0x0D, LF=0x0A - */ - canonicalizeEOL: function(data) { - const CR = 13; - const LF = 10; - let carryOverCR = false; - - return transform(data, bytes => { - if (carryOverCR) { - bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); - } - - if (bytes[bytes.length - 1] === CR) { - carryOverCR = true; - bytes = bytes.subarray(0, -1); - } else { - carryOverCR = false; - } - - let index; - const indices = []; - for (let i = 0; ; i = index) { - index = bytes.indexOf(LF, i) + 1; - if (index) { - if (bytes[index - 2] !== CR) indices.push(index); - } else { - break; - } - } - if (!indices.length) { - return bytes; - } - - const normalized = new Uint8Array(bytes.length + indices.length); - let j = 0; - for (let i = 0; i < indices.length; i++) { - const sub = bytes.subarray(indices[i - 1] || 0, indices[i]); - normalized.set(sub, j); - j += sub.length; - normalized[j - 1] = CR; - normalized[j] = LF; - j++; - } - normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j); - return normalized; - }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); - }, - - /** - * Convert line endings from canonicalized to native - * Support any encoding where CR=0x0D, LF=0x0A - */ - nativeEOL: function(data) { - const CR = 13; - const LF = 10; - let carryOverCR = false; - - return transform(data, bytes => { - if (carryOverCR && bytes[0] !== LF) { - bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); - } else { - bytes = new Uint8Array(bytes); // Don't mutate passed bytes - } - - if (bytes[bytes.length - 1] === CR) { - carryOverCR = true; - bytes = bytes.subarray(0, -1); - } else { - carryOverCR = false; - } - - let index; - let j = 0; - for (let i = 0; i !== bytes.length; i = index) { - index = bytes.indexOf(CR, i) + 1; - if (!index) index = bytes.length; - const last = index - (bytes[index] === LF ? 1 : 0); - if (i) bytes.copyWithin(j, i, last); - j += last - i; - } - return bytes.subarray(0, j); - }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); - }, - - /** - * Remove trailing spaces, carriage returns and tabs from each line - */ - removeTrailingSpaces: function(text) { - return text.split('\n').map(line => { - let i = line.length - 1; - for (; i >= 0 && (line[i] === ' ' || line[i] === '\t' || line[i] === '\r'); i--); - return line.substr(0, i + 1); - }).join('\n'); - }, - - wrapError: function(message, error) { - if (!error) { - return new Error(message); - } - - // update error message - try { - error.message = message + ': ' + error.message; - } catch (e) {} - - return error; - }, - - /** - * Map allowed packet tags to corresponding classes - * Meant to be used to format `allowedPacket` for Packetlist.read - * @param {Array} allowedClasses - * @returns {Object} map from enum.packet to corresponding *Packet class - */ - constructAllowedPackets: function(allowedClasses) { - const map = {}; - allowedClasses.forEach(PacketClass => { - if (!PacketClass.tag) { - throw new Error('Invalid input: expected a packet class'); - } - map[PacketClass.tag] = PacketClass; - }); - return map; - }, - - /** - * Return a Promise that will resolve as soon as one of the promises in input resolves - * or will reject if all input promises all rejected - * (similar to Promise.any, but with slightly different error handling) - * @param {Array} promises - * @return {Promise} Promise resolving to the result of the fastest fulfilled promise - * or rejected with the Error of the last resolved Promise (if all promises are rejected) - */ - anyPromise: function(promises) { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - let exception; - await Promise.all(promises.map(async promise => { - try { - resolve(await promise); - } catch (e) { - exception = e; - } - })); - reject(exception); - }); - }, - - /** - * Return either `a` or `b` based on `cond`, in algorithmic constant time. - * @param {Boolean} cond - * @param {Uint8Array} a - * @param {Uint8Array} b - * @returns `a` if `cond` is true, `b` otherwise - */ - selectUint8Array: function(cond, a, b) { - const length = Math.max(a.length, b.length); - const result = new Uint8Array(length); - let end = 0; - for (let i = 0; i < result.length; i++) { - result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond)); - end += (cond & i < a.length) | ((1 - cond) & i < b.length); - } - return result.subarray(0, end); - }, - /** - * Return either `a` or `b` based on `cond`, in algorithmic constant time. - * NB: it only supports `a, b` with values between 0-255. - * @param {Boolean} cond - * @param {Uint8} a - * @param {Uint8} b - * @returns `a` if `cond` is true, `b` otherwise - */ - selectUint8: function(cond, a, b) { - return (a & (256 - cond)) | (b & (255 + cond)); - }, - /** - * @param {module:enums.symmetric} cipherAlgo - */ - isAES: function(cipherAlgo) { - return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256; - } -}; - -/* OpenPGP radix-64/base64 string encoding/decoding - * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de - * version 1.0, check www.haneWIN.de for the latest version - * - * This software is provided as-is, without express or implied warranty. - * Permission to use, copy, modify, distribute or sell this software, with or - * without fee, for any purpose and by any individual or organization, is hereby - * granted, provided that the above copyright notice and this paragraph appear - * in all copies. Distribution as a part of an application or binary must - * include the above copyright notice in the documentation and/or other materials - * provided with the application or distribution. - */ - -const Buffer = util.getNodeBuffer(); - -let encodeChunk; -let decodeChunk; -if (Buffer) { - encodeChunk = buf => Buffer.from(buf).toString('base64'); - decodeChunk = str => { - const b = Buffer.from(str, 'base64'); - return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); - }; -} else { - encodeChunk = buf => btoa(util.uint8ArrayToString(buf)); - decodeChunk = str => util.stringToUint8Array(atob(str)); -} - -/** - * Convert binary array to radix-64 - * @param {Uint8Array | ReadableStream} data - Uint8Array to convert - * @returns {String | ReadableStream} Radix-64 version of input string. - * @static - */ -function encode(data) { - let buf = new Uint8Array(); - return transform(data, value => { - buf = util.concatUint8Array([buf, value]); - const r = []; - const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64). - const lines = Math.floor(buf.length / bytesPerLine); - const bytes = lines * bytesPerLine; - const encoded = encodeChunk(buf.subarray(0, bytes)); - for (let i = 0; i < lines; i++) { - r.push(encoded.substr(i * 60, 60)); - r.push('\n'); - } - buf = buf.subarray(bytes); - return r.join(''); - }, () => (buf.length ? encodeChunk(buf) + '\n' : '')); -} - -/** - * Convert radix-64 to binary array - * @param {String | ReadableStream} data - Radix-64 string to convert - * @returns {Uint8Array | ReadableStream} Binary array version of input string. - * @static - */ -function decode(data) { - let buf = ''; - return transform(data, value => { - buf += value; - - // Count how many whitespace characters there are in buf - let spaces = 0; - const spacechars = [' ', '\t', '\r', '\n']; - for (let i = 0; i < spacechars.length; i++) { - const spacechar = spacechars[i]; - for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) { - spaces++; - } - } - - // Backtrack until we have 4n non-whitespace characters - // that we can safely base64-decode - let length = buf.length; - for (; length > 0 && (length - spaces) % 4 !== 0; length--) { - if (spacechars.includes(buf[length])) spaces--; - } - - const decoded = decodeChunk(buf.substr(0, length)); - buf = buf.substr(length); - return decoded; - }, () => decodeChunk(buf)); -} - -/** - * Convert a Base-64 encoded string an array of 8-bit integer - * - * Note: accepts both Radix-64 and URL-safe strings - * @param {String} base64 - Base-64 encoded string to convert - * @returns {Uint8Array} An array of 8-bit integers. - */ -function b64ToUint8Array(base64) { - return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); -} - -/** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param {Uint8Array} bytes - An array of 8-bit integers to convert - * @param {bool} url - If true, output is URL-safe - * @returns {String} Base-64 encoded string. - */ -function uint8ArrayToB64(bytes, url) { - let encoded = encode(bytes).replace(/[\r\n]/g, ''); - if (url) { - encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); - } - return encoded; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -var config = { - /** - * @memberof module:config - * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} - */ - preferredHashAlgorithm: enums.hash.sha256, - /** - * @memberof module:config - * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} - */ - preferredSymmetricAlgorithm: enums.symmetric.aes256, - /** - * @memberof module:config - * @property {Integer} compression Default compression algorithm {@link module:enums.compression} - */ - preferredCompressionAlgorithm: enums.compression.uncompressed, - /** - * @memberof module:config - * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9 - */ - deflateLevel: 6, - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} - * @memberof module:config - * @property {Boolean} aeadProtect - */ - aeadProtect: false, - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. - * @memberof module:config - * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} - */ - preferredAEADAlgorithm: enums.aead.eax, - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. - * Must be an integer value from 0 to 56. - * @memberof module:config - * @property {Integer} aeadChunkSizeByte - */ - aeadChunkSizeByte: 12, - /** - * Use V5 keys. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @memberof module:config - * @property {Boolean} v5Keys - */ - v5Keys: false, - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - * @memberof module:config - * @property {Integer} s2kIterationCountByte - */ - s2kIterationCountByte: 224, - /** - * Allow decryption of messages without integrity protection. - * This is an **insecure** setting: - * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. - * - it enables downgrade attacks against integrity-protected messages. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedMessages - */ - allowUnauthenticatedMessages: false, - /** - * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to - * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible - * and deferring checking their integrity until the decrypted stream has been read in full. - * - * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedStream - */ - allowUnauthenticatedStream: false, - /** - * @memberof module:config - * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum - */ - checksumRequired: false, - /** - * Minimum RSA key size allowed for key generation and message signing, verification and encryption. - * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. - * @memberof module:config - * @property {Number} minRSABits - */ - minRSABits: 2047, - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - * @memberof module:config - * @property {Boolean} passwordCollisionCheck - */ - passwordCollisionCheck: false, - /** - * @memberof module:config - * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored - */ - revocationsExpire: false, - /** - * Allow decryption using RSA keys without `encrypt` flag. - * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug - * where key flags were ignored when selecting a key for encryption. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureDecryptionWithSigningKeys: false, - /** - * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. - * Instead, a verification key will also be consider valid as long as it is valid at the current time. - * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, - * and have self-signature's creation date that does not match the primary key creation date. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureVerificationWithReformattedKeys: false, - - /** - * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). - * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: - * - new/incoming messages are automatically decrypted (without user interaction); - * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). - * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. - * @memberof module:config - * @property {Boolean} constantTimePKCS1Decryption - */ - constantTimePKCS1Decryption: false, - /** - * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. - * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. - * However, the more algorithms are added, the slower the decryption procedure becomes. - * @memberof module:config - * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} - */ - constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), - - /** - * @memberof module:config - * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available - */ - minBytesForWebCrypto: 1000, - /** - * @memberof module:config - * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error - */ - ignoreUnsupportedPackets: true, - /** - * @memberof module:config - * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error - */ - ignoreMalformedPackets: false, - /** - * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only - * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable - * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). - * @memberof module:config - * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] - */ - additionalAllowedPackets: [], - /** - * @memberof module:config - * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages - */ - showVersion: false, - /** - * @memberof module:config - * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages - */ - showComment: false, - /** - * @memberof module:config - * @property {String} versionString A version string to be included in armored messages - */ - versionString: 'OpenPGP.js 5.11.2', - /** - * @memberof module:config - * @property {String} commentString A comment string to be included in armored messages - */ - commentString: 'https://openpgpjs.org', - - /** - * Max userID string length (used for parsing) - * @memberof module:config - * @property {Integer} maxUserIDLength - */ - maxUserIDLength: 1024 * 5, - /** - * Contains notatations that are considered "known". Known notations do not trigger - * validation error when the notation is marked as critical. - * @memberof module:config - * @property {Array} knownNotations - */ - knownNotations: [], - /** - * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. - * When false, certain standard curves will not be supported (depending on the platform). - * Note: the indutny/elliptic curve library is not designed to be constant time. - * @memberof module:config - * @property {Boolean} useIndutnyElliptic - */ - useIndutnyElliptic: true, - /** - * Reject insecure hash algorithms - * @memberof module:config - * @property {Set} rejectHashAlgorithms {@link module:enums.hash} - */ - rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), - /** - * Reject insecure message hash algorithms - * @memberof module:config - * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} - */ - rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), - /** - * Reject insecure public key algorithms for key generation and message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} - */ - rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), - /** - * Reject non-standard curves for key generation, message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectCurves {@link module:enums.curve} - */ - rejectCurves: new Set([enums.curve.secp256k1]) -}; - -/** - * @fileoverview This object contains global configuration values. - * @see module:config/config - * @module config - */ - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Finds out which Ascii Armoring type is used. Throws error if unknown type. - * @param {String} text - ascii armored text - * @returns {Integer} 0 = MESSAGE PART n of m. - * 1 = MESSAGE PART n - * 2 = SIGNED MESSAGE - * 3 = PGP MESSAGE - * 4 = PUBLIC KEY BLOCK - * 5 = PRIVATE KEY BLOCK - * 6 = SIGNATURE - * @private - */ -function getType(text) { - const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m; - - const header = text.match(reHeader); - - if (!header) { - throw new Error('Unknown ASCII armor type'); - } - - // BEGIN PGP MESSAGE, PART X/Y - // Used for multi-part messages, where the armor is split amongst Y - // parts, and this is the Xth part out of Y. - if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { - return enums.armor.multipartSection; - } else - // BEGIN PGP MESSAGE, PART X - // Used for multi-part messages, where this is the Xth part of an - // unspecified number of parts. Requires the MESSAGE-ID Armor - // Header to be used. - if (/MESSAGE, PART \d+/.test(header[1])) { - return enums.armor.multipartLast; - } else - // BEGIN PGP SIGNED MESSAGE - if (/SIGNED MESSAGE/.test(header[1])) { - return enums.armor.signed; - } else - // BEGIN PGP MESSAGE - // Used for signed, encrypted, or compressed files. - if (/MESSAGE/.test(header[1])) { - return enums.armor.message; - } else - // BEGIN PGP PUBLIC KEY BLOCK - // Used for armoring public keys. - if (/PUBLIC KEY BLOCK/.test(header[1])) { - return enums.armor.publicKey; - } else - // BEGIN PGP PRIVATE KEY BLOCK - // Used for armoring private keys. - if (/PRIVATE KEY BLOCK/.test(header[1])) { - return enums.armor.privateKey; - } else - // BEGIN PGP SIGNATURE - // Used for detached signatures, OpenPGP/MIME signatures, and - // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE - // for detached signatures. - if (/SIGNATURE/.test(header[1])) { - return enums.armor.signature; - } -} - -/** - * Add additional information to the armor version of an OpenPGP binary - * packet block. - * @author Alex - * @version 2011-12-16 - * @param {String} [customComment] - Additional comment to add to the armored string - * @returns {String} The header information. - * @private - */ -function addheader(customComment, config) { - let result = ''; - if (config.showVersion) { - result += 'Version: ' + config.versionString + '\n'; - } - if (config.showComment) { - result += 'Comment: ' + config.commentString + '\n'; - } - if (customComment) { - result += 'Comment: ' + customComment + '\n'; - } - result += '\n'; - return result; -} - - -/** - * Calculates a checksum over the given data and returns it base64 encoded - * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for - * @returns {String | ReadableStream} Base64 encoded checksum. - * @private - */ -function getCheckSum(data) { - const crc = createcrc24(data); - return encode(crc); -} - -// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview - -const crc_table = [ - new Array(0xFF), - new Array(0xFF), - new Array(0xFF), - new Array(0xFF) -]; - -for (let i = 0; i <= 0xFF; i++) { - let crc = i << 16; - for (let j = 0; j < 8; j++) { - crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0); - } - crc_table[0][i] = - ((crc & 0xFF0000) >> 16) | - (crc & 0x00FF00) | - ((crc & 0x0000FF) << 16); -} -for (let i = 0; i <= 0xFF; i++) { - crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF]; -} -for (let i = 0; i <= 0xFF; i++) { - crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF]; -} -for (let i = 0; i <= 0xFF; i++) { - crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF]; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness -const isLittleEndian = (function() { - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 0xFF; -}()); - -/** - * Internal function to calculate a CRC-24 checksum over a given string (data) - * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for - * @returns {Uint8Array | ReadableStream} The CRC-24 checksum. - * @private - */ -function createcrc24(input) { - let crc = 0xCE04B7; - return transform(input, value => { - const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0; - const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32); - for (let i = 0; i < len32; i++) { - crc ^= arr32[i]; - crc = - crc_table[0][(crc >> 24) & 0xFF] ^ - crc_table[1][(crc >> 16) & 0xFF] ^ - crc_table[2][(crc >> 8) & 0xFF] ^ - crc_table[3][(crc >> 0) & 0xFF]; - } - for (let i = len32 * 4; i < value.length; i++) { - crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]]; - } - }, () => new Uint8Array([crc, crc >> 8, crc >> 16])); -} - -/** - * Verify armored headers. crypto-refresh-06, section 6.2: - * "An OpenPGP implementation may consider improperly formatted Armor - * Headers to be corruption of the ASCII Armor, but SHOULD make an - * effort to recover." - * @private - * @param {Array} headers - Armor headers - */ -function verifyHeaders(headers) { - for (let i = 0; i < headers.length; i++) { - if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { - util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); - } - if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) { - util.printDebugError(new Error('Unknown header: ' + headers[i])); - } - } -} - -/** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param {String} text - OpenPGP armored message part - * @returns {Object} An object with attribute "body" containing the body. - * and an attribute "checksum" containing the checksum. - * @private - */ -function splitChecksum(text) { - let body = text; - let checksum = ''; - - const lastEquals = text.lastIndexOf('='); - - if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum - body = text.slice(0, lastEquals); - checksum = text.slice(lastEquals + 1).substr(0, 4); - } - - return { body: body, checksum: checksum }; -} - -/** - * Dearmor an OpenPGP armored message; verify the checksum and return - * the encoded bytes - * @param {String} input - OpenPGP armored message - * @returns {Promise} An object with attribute "text" containing the message text, - * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type - * @async - * @static - */ -function unarmor(input, config$1 = config) { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - const reSplit = /^-----[^-]+-----$/m; - const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/; - - let type; - const headers = []; - let lastHeaders = headers; - let headersDone; - let text = []; - let textDone; - let checksum; - let data = decode(transformPair(input, async (readable, writable) => { - const reader = getReader(readable); - try { - while (true) { - let line = await reader.readLine(); - if (line === undefined) { - throw new Error('Misformed armored text'); - } - // remove trailing whitespace at end of lines - line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, '')); - if (!type) { - if (reSplit.test(line)) { - type = getType(line); - } - } else if (!headersDone) { - if (reSplit.test(line)) { - reject(new Error('Mandatory blank line missing between armor headers and armor data')); - } - if (!reEmptyLine.test(line)) { - lastHeaders.push(line); - } else { - verifyHeaders(lastHeaders); - headersDone = true; - if (textDone || type !== 2) { - resolve({ text, data, headers, type }); - break; - } - } - } else if (!textDone && type === 2) { - if (!reSplit.test(line)) { - // Reverse dash-escaping for msg - text.push(line.replace(/^- /, '')); - } else { - text = text.join('\r\n'); - textDone = true; - verifyHeaders(lastHeaders); - lastHeaders = []; - headersDone = false; - } - } - } - } catch (e) { - reject(e); - return; - } - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const { done, value } = await reader.read(); - if (done) { - throw new Error('Misformed armored text'); - } - const line = value + ''; - if (line.indexOf('=') === -1 && line.indexOf('-') === -1) { - await writer.write(line); - } else { - let remainder = await reader.readToEnd(); - if (!remainder.length) remainder = ''; - remainder = line + remainder; - remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, '')); - const parts = remainder.split(reSplit); - if (parts.length === 1) { - throw new Error('Misformed armored text'); - } - const split = splitChecksum(parts[0].slice(0, -1)); - checksum = split.checksum; - await writer.write(split.body); - break; - } - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - })); - data = transformPair(data, async (readable, writable) => { - const checksumVerified = readToEnd(getCheckSum(passiveClone(readable))); - checksumVerified.catch(() => {}); - await pipe(readable, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - const checksumVerifiedString = (await checksumVerified).replace('\n', ''); - if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) { - throw new Error('Ascii armor integrity check failed'); - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); - } catch (e) { - reject(e); - } - }).then(async result => { - if (isArrayStream(result.data)) { - result.data = await readToEnd(result.data); - } - return result; - }); -} - - -/** - * Armor an OpenPGP binary packet block - * @param {module:enums.armor} messageType - Type of the message - * @param {Uint8Array | ReadableStream} body - The message body to armor - * @param {Integer} [partIndex] - * @param {Integer} [partTotal] - * @param {String} [customComment] - Additional comment to add to the armored string - * @returns {String | ReadableStream} Armored text. - * @static - */ -function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) { - let text; - let hash; - if (messageType === enums.armor.signed) { - text = body.text; - hash = body.hash; - body = body.data; - } - const bodyClone = passiveClone(body); - const result = []; - switch (messageType) { - case enums.armor.multipartSection: - result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); - break; - case enums.armor.multipartLast: - result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); - break; - case enums.armor.signed: - result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); - result.push('Hash: ' + hash + '\n\n'); - result.push(text.replace(/^-/mg, '- -')); - result.push('\n-----BEGIN PGP SIGNATURE-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP SIGNATURE-----\n'); - break; - case enums.armor.message: - result.push('-----BEGIN PGP MESSAGE-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP MESSAGE-----\n'); - break; - case enums.armor.publicKey: - result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); - break; - case enums.armor.privateKey: - result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); - break; - case enums.armor.signature: - result.push('-----BEGIN PGP SIGNATURE-----\n'); - result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); - result.push('-----END PGP SIGNATURE-----\n'); - break; - } - - return util.concat(result); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of type key id - * - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. - */ -class KeyID { - constructor() { - this.bytes = ''; - } - - /** - * Parsing method for a key id - * @param {Uint8Array} bytes - Input to read the key id from - */ - read(bytes) { - this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); - return this.bytes.length; - } - - /** - * Serializes the Key ID - * @returns {Uint8Array} Key ID as a Uint8Array. - */ - write() { - return util.stringToUint8Array(this.bytes); - } - - /** - * Returns the Key ID represented as a hexadecimal string - * @returns {String} Key ID as a hexadecimal string. - */ - toHex() { - return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); - } - - /** - * Checks equality of Key ID's - * @param {KeyID} keyID - * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard - */ - equals(keyID, matchWildcard = false) { - return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; - } - - /** - * Checks to see if the Key ID is unset - * @returns {Boolean} True if the Key ID is null. - */ - isNull() { - return this.bytes === ''; - } - - /** - * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) - * @returns {Boolean} True if this is a wildcard Key ID. - */ - isWildcard() { - return /^0+$/.test(this.toHex()); - } - - static mapToHex(keyID) { - return keyID.toHex(); - } - - static fromID(hex) { - const keyID = new KeyID(); - keyID.read(util.hexToUint8Array(hex)); - return keyID; - } - - static wildcard() { - const keyID = new KeyID(); - keyID.read(new Uint8Array(8)); - return keyID; - } -} - -/** - * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. - * @author Artem S Vybornov - * @license MIT - */ -var AES_asm = function () { - - /** - * Galois Field stuff init flag - */ - var ginit_done = false; - - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; - - /** - * Init Galois Field tables - */ - function ginit() { - gexp3 = [], - glog3 = []; - - var a = 1, c, d; - for (c = 0; c < 255; c++) { - gexp3[c] = a; - - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if (d === 0x80) a ^= 0x1b; - a ^= gexp3[c]; - - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; - - ginit_done = true; - } - - /** - * Galois Field multiplication - * @param {number} a - * @param {number} b - * @return {number} - */ - function gmul(a, b) { - var c = gexp3[(glog3[a] + glog3[b]) % 255]; - if (a === 0 || b === 0) c = 0; - return c; - } - - /** - * Galois Field reciprocal - * @param {number} a - * @return {number} - */ - function ginv(a) { - var i = gexp3[255 - glog3[a]]; - if (a === 0) i = 0; - return i; - } - - /** - * AES stuff init flag - */ - var aes_init_done = false; - - /** - * Encryption, Decryption, S-Box and KeyTransform tables - * - * @type {number[]} - */ - var aes_sbox; - - /** - * @type {number[]} - */ - var aes_sinv; - - /** - * @type {number[][]} - */ - var aes_enc; - - /** - * @type {number[][]} - */ - var aes_dec; - - /** - * Init AES tables - */ - function aes_init() { - if (!ginit_done) ginit(); - - // Calculates AES S-Box value - function _s(a) { - var c, s, x; - s = x = ginv(a); - for (c = 0; c < 4; c++) { - s = ((s << 1) | (s >>> 7)) & 255; - x ^= s; - } - x ^= 99; - return x; - } - - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [[], [], [], []], - aes_dec = [[], [], [], []]; - - for (var i = 0; i < 256; i++) { - var s = _s(i); - - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; - - // Ecryption and Decryption tables - aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s); - aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i); - // Rotate tables - for (var t = 1; t < 4; t++) { - aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24); - aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24); - } - } - - aes_init_done = true; - } - - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-   * 0x0000   encryption key schedule
-   * 0x0400   decryption key schedule
-   * 0x0800   sbox
-   * 0x0c00   inv sbox
-   * 0x1000   encryption tables
-   * 0x2000   decryption tables
-   * 0x3000   reserved (future GCM multiplication lookup table)
-   * 0x4000   data
-   * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param foreign - ignored - * @param buffer - heap buffer to link with - */ - var wrapper = function (foreign, buffer) { - // Init AES stuff for the first time - if (!aes_init_done) aes_init(); - - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set(aes_sbox, 0x0800 >> 2); - heap.set(aes_sinv, 0x0c00 >> 2); - for (var i = 0; i < 4; i++) { - heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2); - heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2); - } - - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {number} k0 - key vector components - * @param {number} k1 - key vector components - * @param {number} k2 - key vector components - * @param {number} k3 - key vector components - * @param {number} k4 - key vector components - * @param {number} k5 - key vector components - * @param {number} k6 - key vector components - * @param {number} k7 - key vector components - */ - function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { - var ekeys = heap.subarray(0x000, 60), - dkeys = heap.subarray(0x100, 0x100 + 60); - - // Encryption key schedule - ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); - for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { - var k = ekeys[i - 1]; - if ((i % ks === 0) || (ks === 8 && i % ks === 4)) { - k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; - } - if (i % ks === 0) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0); - } - ekeys[i] = ekeys[i - ks] ^ k; - } - - // Decryption key schedule - for (var j = 0; j < i; j += 4) { - for (var jj = 0; jj < 4; jj++) { - var k = ekeys[i - (4 + j) + (4 - jj) % 4]; - if (j < 4 || j >= i - 4) { - dkeys[j + jj] = k; - } else { - dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] - ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] - ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] - ^ aes_dec[3][aes_sbox[k & 255]]; - } - } - } - - // Set rounds number - asm.set_rounds(ks + 5); - } - - // create library object with necessary properties - var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array}; - - var asm = function (stdlib, foreign, buffer) { - "use asm"; - - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); - - /** - * AES core - * @param {number} k - precomputed key schedule offset - * @param {number} s - precomputed sbox table offset - * @param {number} t - precomputed round table offset - * @param {number} r - number of inner rounds to perform - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _core(k, s, t, r, x0, x1, x2, x3) { - k = k | 0; - s = s | 0; - t = t | 0; - r = r | 0; - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k | 0) >> 2], - x1 = x1 ^ HEAP[(k | 4) >> 2], - x2 = x2 ^ HEAP[(k | 8) >> 2], - x3 = x3 ^ HEAP[(k | 12) >> 2]; - - // round 1..r - for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) { - y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } - - // final round - S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - } - - /** - * ECB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } - - /** - * ECB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - } - - - /** - * CBC mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } - - /** - * CBC mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * CFB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } - - - /** - * CFB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * OFB mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ofb(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * CTR mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ctr(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); - - N3 = (~M3 & N3) | M3 & (N3 + 1); - N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0)); - N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0)); - N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0)); - - S0 = S0 ^ x0; - S1 = S1 ^ x1; - S2 = S2 ^ x2; - S3 = S3 ^ x3; - } - - /** - * GCM mode MAC calculation - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _gcm_mac(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0 | 0, - y1 = H1 | 0, - y2 = H2 | 0, - y3 = H3 | 0; - - for (; (i | 0) < 128; i = (i + 1) | 0) { - if (y0 >>> 31) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } - - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); - - c = x3 & 1; - - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); - - if (c) x0 = x0 ^ 0xe1000000; - } - - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } - - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {number} r - number if inner AES rounds - */ - function set_rounds(r) { - r = r | 0; - R = r; - } - - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {number} s0 - state vector - * @param {number} s1 - state vector - * @param {number} s2 - state vector - * @param {number} s3 - state vector - */ - function set_state(s0, s1, s2, s3) { - s0 = s0 | 0; - s1 = s1 | 0; - s2 = s2 | 0; - s3 = s3 | 0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } - - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {number} i0 - iv vector - * @param {number} i1 - iv vector - * @param {number} i2 - iv vector - * @param {number} i3 - iv vector - */ - function set_iv(i0, i1, i2, i3) { - i0 = i0 | 0; - i1 = i1 | 0; - i2 = i2 | 0; - i3 = i3 | 0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } - - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} n0 - nonce vector - * @param {number} n1 - nonce vector - * @param {number} n2 - nonce vector - * @param {number} n3 - nonce vector - */ - function set_nonce(n0, n1, n2, n3) { - n0 = n0 | 0; - n1 = n1 | 0; - n2 = n2 | 0; - n3 = n3 | 0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } - - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} m0 - counter mask vector - * @param {number} m1 - counter mask vector - * @param {number} m2 - counter mask vector - * @param {number} m3 - counter mask vector - */ - function set_mask(m0, m1, m2, m3) { - m0 = m0 | 0; - m1 = m1 | 0; - m2 = m2 | 0; - m3 = m3 | 0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } - - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} c0 - counter vector - * @param {number} c1 - counter vector - * @param {number} c2 - counter vector - * @param {number} c3 - counter vector - */ - function set_counter(c0, c1, c2, c3) { - c0 = c0 | 0; - c1 = c1 | 0; - c2 = c2 | 0; - c3 = c3 | 0; - - N3 = (~M3 & N3) | M3 & c3, - N2 = (~M2 & N2) | M2 & c2, - N1 = (~M1 & N1) | M1 & c1, - N0 = (~M0 & N0) | M0 & c0; - } - - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_state(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - return 16; - } - - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_iv(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = I0 >>> 24, - DATA[pos | 1] = I0 >>> 16 & 255, - DATA[pos | 2] = I0 >>> 8 & 255, - DATA[pos | 3] = I0 & 255, - DATA[pos | 4] = I1 >>> 24, - DATA[pos | 5] = I1 >>> 16 & 255, - DATA[pos | 6] = I1 >>> 8 & 255, - DATA[pos | 7] = I1 & 255, - DATA[pos | 8] = I2 >>> 24, - DATA[pos | 9] = I2 >>> 16 & 255, - DATA[pos | 10] = I2 >>> 8 & 255, - DATA[pos | 11] = I2 & 255, - DATA[pos | 12] = I3 >>> 24, - DATA[pos | 13] = I3 >>> 16 & 255, - DATA[pos | 14] = I3 >>> 8 & 255, - DATA[pos | 15] = I3 & 255; - - return 16; - } - - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init() { - _ecb_enc(0, 0, 0, 0); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } - - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function cipher(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; - - var ret = 0; - - if (pos & 15) return -1; - - while ((len | 0) >= 16) { - _cipher_modes[mode & 7]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } - - return ret | 0; - } - - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function mac(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; - - var ret = 0; - - if (pos & 15) return -1; - - while ((len | 0) >= 16) { - _mac_modes[mode & 1]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } - - return ret | 0; - } - - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; - - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [_cbc_enc, _gcm_mac]; - - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter: set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac, - }; - }(stdlib, foreign, buffer); - - asm.set_key = set_key; - - return asm; - }; - - /** - * AES enciphering mode constants - * @enum {number} - * @const - */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7, - }, - - /** - * AES deciphering mode constants - * @enum {number} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7, - }, - - /** - * AES MAC mode constants - * @enum {number} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1, - }; - - /** - * Heap data offset - * @type {number} - * @const - */ - wrapper.HEAP_DATA = 0x4000; - - return wrapper; -}(); - -function is_bytes(a) { - return a instanceof Uint8Array; -} -function _heap_init(heap, heapSize) { - const size = heap ? heap.byteLength : heapSize || 65536; - if (size & 0xfff || size <= 0) - throw new Error('heap size must be a positive integer and a multiple of 4096'); - heap = heap || new Uint8Array(new ArrayBuffer(size)); - return heap; -} -function _heap_write(heap, hpos, data, dpos, dlen) { - const hlen = heap.length - hpos; - const wlen = hlen < dlen ? hlen : dlen; - heap.set(data.subarray(dpos, dpos + wlen), hpos); - return wlen; -} -function joinBytes(...arg) { - const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0); - const ret = new Uint8Array(totalLenght); - let cursor = 0; - for (let i = 0; i < arg.length; i++) { - ret.set(arg[i], cursor); - cursor += arg[i].length; - } - return ret; -} - -class IllegalStateError extends Error { - constructor(...args) { - super(...args); - } -} -class IllegalArgumentError extends Error { - constructor(...args) { - super(...args); - } -} -class SecurityError extends Error { - constructor(...args) { - super(...args); - } -} - -const heap_pool = []; -const asm_pool = []; -class AES { - constructor(key, iv, padding = true, mode, heap, asm) { - this.pos = 0; - this.len = 0; - this.mode = mode; - // The AES object state - this.pos = 0; - this.len = 0; - this.key = key; - this.iv = iv; - this.padding = padding; - // The AES "worker" - this.acquire_asm(heap, asm); - } - acquire_asm(heap, asm) { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA); - this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer); - this.reset(this.key, this.iv); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool.push(this.heap); - asm_pool.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - reset(key, iv) { - const { asm } = this.acquire_asm(); - // Key - const keylen = key.length; - if (keylen !== 16 && keylen !== 24 && keylen !== 32) - throw new IllegalArgumentError('illegal key size'); - const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); - asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0); - // IV - if (iv !== undefined) { - if (iv.length !== 16) - throw new IllegalArgumentError('illegal iv size'); - let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); - asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); - } - else { - asm.set_iv(0, 0, 0, 0); - } - } - AES_Encrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - let result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.pos = pos; - this.len = len; - return result; - } - AES_Encrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let plen = 16 - (len % 16); - let rlen = len; - if (this.hasOwnProperty('padding')) { - if (this.padding) { - for (let p = 0; p < plen; ++p) { - heap[pos + len + p] = plen; - } - len += plen; - rlen = len; - } - else if (len % 16) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - } - else { - len += plen; - } - const result = new Uint8Array(rlen); - if (len) - asm.cipher(amode, hpos + pos, len); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - AES_Decrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let plen = 0; - let wlen = 0; - if (this.padding) { - plen = len + dlen - rlen || 16; - rlen -= plen; - } - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.pos = pos; - this.len = len; - return result; - } - AES_Decrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let rlen = len; - if (len > 0) { - if (len % 16) { - if (this.hasOwnProperty('padding')) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - else { - len += 16 - (len % 16); - } - } - asm.cipher(amode, hpos + pos, len); - if (this.hasOwnProperty('padding') && this.padding) { - let pad = heap[pos + rlen - 1]; - if (pad < 1 || pad > 16 || pad > rlen) - throw new SecurityError('bad padding'); - let pcheck = 0; - for (let i = pad; i > 1; i--) - pcheck |= pad ^ heap[pos + rlen - i]; - if (pcheck) - throw new SecurityError('bad padding'); - rlen -= pad; - } - } - const result = new Uint8Array(rlen); - if (rlen > 0) { - result.set(heap.subarray(pos, pos + rlen)); - } - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } -} - -class AES_ECB { - static encrypt(data, key, padding = false) { - return new AES_ECB(key, padding).encrypt(data); - } - static decrypt(data, key, padding = false) { - return new AES_ECB(key, padding).decrypt(data); - } - constructor(key, padding = false, aes) { - this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * Javascript AES implementation. - * This is used as fallback if the native Crypto APIs are not available. - */ -function aes(length) { - const C = function(key) { - const aesECB = new AES_ECB(key); - - this.encrypt = function(block) { - return aesECB.encrypt(block); - }; - - this.decrypt = function(block) { - return aesECB.decrypt(block); - }; - }; - - C.blockSize = C.prototype.blockSize = 16; - C.keySize = C.prototype.keySize = length / 8; - - return C; -} - -//Paul Tero, July 2001 -//http://www.tero.co.uk/des/ -// -//Optimised for performance with large blocks by Michael Hayworth, November 2001 -//http://www.netdealing.com -// -// Modified by Recurity Labs GmbH - -//THIS SOFTWARE IS PROVIDED "AS IS" AND -//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -//SUCH DAMAGE. - -//des -//this takes the key, the message, and whether to encrypt or decrypt - -function des(keys, message, encrypt, mode, iv, padding) { - //declaring this locally speeds things up a bit - const spfunction1 = [ - 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, - 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, - 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, - 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, - 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 - ]; - const spfunction2 = [ - -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, - -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, - -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, - -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, - -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, - 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000 - ]; - const spfunction3 = [ - 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, - 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, - 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, - 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, - 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 - ]; - const spfunction4 = [ - 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, - 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, - 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, - 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 - ]; - const spfunction5 = [ - 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, - 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, - 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, - 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, - 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, - 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100 - ]; - const spfunction6 = [ - 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, - 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, - 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, - 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, - 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 - ]; - const spfunction7 = [ - 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, - 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, - 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, - 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, - 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 - ]; - const spfunction8 = [ - 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, - 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, - 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, - 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, - 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 - ]; - - //create the 16 or 48 subkeys we will need - let m = 0; - let i; - let j; - let temp; - let right1; - let right2; - let left; - let right; - let looping; - let cbcleft; - let cbcleft2; - let cbcright; - let cbcright2; - let endloop; - let loopinc; - let len = message.length; - - //set up the loops for single and triple des - const iterations = keys.length === 32 ? 3 : 9; //single or triple des - if (iterations === 3) { - looping = encrypt ? [0, 32, 2] : [30, -2, -2]; - } else { - looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; - } - - //pad the message depending on the padding parameter - //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt - if (encrypt) { - message = desAddPadding(message, padding); - len = message.length; - } - - //store the result here - let result = new Uint8Array(len); - let k = 0; - - if (mode === 1) { //CBC mode - cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - m = 0; - } - - //loop through each 64 bit chunk of the message - while (m < len) { - left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - left ^= cbcleft; - right ^= cbcright; - } else { - cbcleft2 = cbcleft; - cbcright2 = cbcright; - cbcleft = left; - cbcright = right; - } - } - - //first each 64 but chunk of the message must be permuted according to IP - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); - - //do this either 1 or 3 times for each chunk of the message - for (j = 0; j < iterations; j += 3) { - endloop = looping[j + 1]; - loopinc = looping[j + 2]; - //now go through and perform the encryption or decryption - for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency - right1 = right ^ keys[i]; - right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - //the result is attained by passing these bytes through the S selection functions - temp = left; - left = right; - right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> - 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & - 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); - } - temp = left; - left = right; - right = temp; //unreverse left and right - } //for either 1 or 3 iterations - - //move then each one bit to the right - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); - - //now perform IP-1, which is IP in the opposite direction - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - cbcleft = left; - cbcright = right; - } else { - left ^= cbcleft2; - right ^= cbcright2; - } - } - - result[k++] = (left >>> 24); - result[k++] = ((left >>> 16) & 0xff); - result[k++] = ((left >>> 8) & 0xff); - result[k++] = (left & 0xff); - result[k++] = (right >>> 24); - result[k++] = ((right >>> 16) & 0xff); - result[k++] = ((right >>> 8) & 0xff); - result[k++] = (right & 0xff); - } //for every 8 characters, or 64 bits in the message - - //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt - if (!encrypt) { - result = desRemovePadding(result, padding); - } - - return result; -} //end of des - - -//desCreateKeys -//this takes as input a 64 bit key (even though only 56 bits are used) -//as an array of 2 integers, and returns 16 48 bit keys - -function desCreateKeys(key) { - //declaring this locally speeds things up a bit - const pc2bytes0 = [ - 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 - ]; - const pc2bytes1 = [ - 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 - ]; - const pc2bytes2 = [ - 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808 - ]; - const pc2bytes3 = [ - 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 - ]; - const pc2bytes4 = [ - 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010 - ]; - const pc2bytes5 = [ - 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420 - ]; - const pc2bytes6 = [ - 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 - ]; - const pc2bytes7 = [ - 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 - ]; - const pc2bytes8 = [ - 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002 - ]; - const pc2bytes9 = [ - 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 - ]; - const pc2bytes10 = [ - 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020 - ]; - const pc2bytes11 = [ - 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 - ]; - const pc2bytes12 = [ - 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 - ]; - const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; - - //how many iterations (1 for des, 3 for triple des) - const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - //stores the return keys - const keys = new Array(32 * iterations); - //now define the left shifts which need to be done - const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - //other variables - let lefttemp; - let righttemp; - let m = 0; - let n = 0; - let temp; - - for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations - let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 2) ^ right) & 0x33333333; - right ^= temp; - left ^= (temp << 2); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - - //the right side needs to be shifted and to get the last four bits of the left side - temp = (left << 8) | ((right >>> 20) & 0x000000f0); - //left needs to be put upside down - left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); - right = temp; - - //now go through and perform these shifts on the left and right keys - for (let i = 0; i < shifts.length; i++) { - //shift the keys either one or two bits to the left - if (shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; - - //now apply PC-2, in such a way that E is easier when encrypting or decrypting - //this conversion will look like PC-2 except only the last 6 bits of each byte are used - //rather than 48 consecutive bits and the order of lines will be according to - //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 - lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( - left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & - 0xf]; - righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | - pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]; - temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; - keys[n++] = lefttemp ^ temp; - keys[n++] = righttemp ^ (temp << 16); - } - } //for each iterations - //return the keys we've created - return keys; -} //end of desCreateKeys - - -function desAddPadding(message, padding) { - const padLength = 8 - (message.length % 8); - - let pad; - if (padding === 2 && (padLength < 8)) { //pad the message with spaces - pad = ' '.charCodeAt(0); - } else if (padding === 1) { //PKCS7 padding - pad = padLength; - } else if (!padding && (padLength < 8)) { //pad the message out with null bytes - pad = 0; - } else if (padLength === 8) { - return message; - } else { - throw new Error('des: invalid padding'); - } - - const paddedMessage = new Uint8Array(message.length + padLength); - for (let i = 0; i < message.length; i++) { - paddedMessage[i] = message[i]; - } - for (let j = 0; j < padLength; j++) { - paddedMessage[message.length + j] = pad; - } - - return paddedMessage; -} - -function desRemovePadding(message, padding) { - let padLength = null; - let pad; - if (padding === 2) { // space padded - pad = ' '.charCodeAt(0); - } else if (padding === 1) { // PKCS7 - padLength = message[message.length - 1]; - } else if (!padding) { // null padding - pad = 0; - } else { - throw new Error('des: invalid padding'); - } - - if (!padLength) { - padLength = 1; - while (message[message.length - padLength] === pad) { - padLength++; - } - padLength--; - } - - return message.subarray(0, message.length - padLength); -} - -// added by Recurity Labs - -function TripleDES(key) { - this.key = []; - - for (let i = 0; i < 3; i++) { - this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); - } - - this.encrypt = function(block) { - return des( - desCreateKeys(this.key[2]), - des( - desCreateKeys(this.key[1]), - des( - desCreateKeys(this.key[0]), - block, true, 0, null, null - ), - false, 0, null, null - ), true, 0, null, null - ); - }; -} - -TripleDES.keySize = TripleDES.prototype.keySize = 24; -TripleDES.blockSize = TripleDES.prototype.blockSize = 8; - -// This is "original" DES - -function DES(key) { - this.key = key; - - this.encrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, true, 0, null, padding); - }; - - this.decrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, false, 0, null, padding); - }; -} - -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Copyright 2010 pjacobs@xeekr.com . All rights reserved. - -// Modified by Recurity Labs GmbH - -// fixed/modified by Herbert Hanewinkel, www.haneWIN.de -// check www.haneWIN.de for the latest version - -// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. -// CAST-128 is a common OpenPGP cipher. - - -// CAST5 constructor - -function OpenPGPSymEncCAST5() { - this.BlockSize = 8; - this.KeySize = 16; - - this.setKey = function(key) { - this.masking = new Array(16); - this.rotate = new Array(16); - - this.reset(); - - if (key.length === this.KeySize) { - this.keySchedule(key); - } else { - throw new Error('CAST-128: keys must be 16 bytes'); - } - return true; - }; - - this.reset = function() { - for (let i = 0; i < 16; i++) { - this.masking[i] = 0; - this.rotate[i] = 0; - } - }; - - this.getBlockSize = function() { - return this.BlockSize; - }; - - this.encrypt = function(src) { - const dst = new Array(src.length); - - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; - - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >>> 16) & 255; - dst[i + 6] = (l >>> 8) & 255; - dst[i + 7] = l & 255; - } - - return dst; - }; - - this.decrypt = function(src) { - const dst = new Array(src.length); - - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; - - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >> 16) & 255; - dst[i + 6] = (l >> 8) & 255; - dst[i + 7] = l & 255; - } - - return dst; - }; - const scheduleA = new Array(4); - - scheduleA[0] = new Array(4); - scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; - scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - - scheduleA[1] = new Array(4); - scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - - scheduleA[2] = new Array(4); - scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; - scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - - - scheduleA[3] = new Array(4); - scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - - const scheduleB = new Array(4); - - scheduleB[0] = new Array(4); - scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; - scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; - scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; - scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; - - scheduleB[1] = new Array(4); - scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; - scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; - scheduleB[1][2] = [7, 6, 8, 9, 3]; - scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; - - - scheduleB[2] = new Array(4); - scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; - scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; - scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; - scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; - - - scheduleB[3] = new Array(4); - scheduleB[3][0] = [8, 9, 7, 6, 3]; - scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; - scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; - scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; - - // changed 'in' to 'inn' (in javascript 'in' is a reserved word) - this.keySchedule = function(inn) { - const t = new Array(8); - const k = new Array(32); - - let j; - - for (let i = 0; i < 4; i++) { - j = i * 4; - t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; - } - - const x = [6, 7, 4, 5]; - let ki = 0; - let w; - - for (let half = 0; half < 2; half++) { - for (let round = 0; round < 4; round++) { - for (j = 0; j < 4; j++) { - const a = scheduleA[round][j]; - w = t[a[1]]; - - w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; - w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; - w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; - w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; - w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; - t[a[0]] = w; - } - - for (j = 0; j < 4; j++) { - const b = scheduleB[round][j]; - w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - - w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; - w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; - w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; - w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; - k[ki] = w; - ki++; - } - } - } - - for (let i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; - } - }; - - // These are the three 'f' functions. See RFC 2144, section 2.2. - - function f1(d, m, r) { - const t = m + d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; - } - - function f2(d, m, r) { - const t = m ^ d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; - } - - function f3(d, m, r) { - const t = m - d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; - } - - const sBox = new Array(8); - sBox[0] = [ - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf - ]; - - sBox[1] = [ - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 - ]; - - sBox[2] = [ - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 - ]; - - sBox[3] = [ - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 - ]; - - sBox[4] = [ - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 - ]; - - sBox[5] = [ - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f - ]; - - sBox[6] = [ - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 - ]; - - sBox[7] = [ - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e - ]; -} - -function CAST5(key) { - this.cast5 = new OpenPGPSymEncCAST5(); - this.cast5.setKey(key); - - this.encrypt = function(block) { - return this.cast5.encrypt(block); - }; -} - -CAST5.blockSize = CAST5.prototype.blockSize = 8; -CAST5.keySize = CAST5.prototype.keySize = 16; - -/* eslint-disable no-mixed-operators, no-fallthrough */ - - -/* Modified by Recurity Labs GmbH - * - * Cipher.js - * A block-cipher algorithm implementation on JavaScript - * See Cipher.readme.txt for further information. - * - * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] - * This script file is distributed under the LGPL - * - * ACKNOWLEDGMENT - * - * The main subroutines are written by Michiel van Everdingen. - * - * Michiel van Everdingen - * http://home.versatel.nl/MAvanEverdingen/index.html - * - * All rights for these routines are reserved to Michiel van Everdingen. - * - */ - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Math -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -const MAXINT = 0xFFFFFFFF; - -function rotw(w, n) { - return (w << n | w >>> (32 - n)) & MAXINT; -} - -function getW(a, i) { - return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; -} - -function setW(a, i, w) { - a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); -} - -function getB(x, n) { - return (x >>> (n * 8)) & 0xFF; -} - -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Twofish -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -function createTwofish() { - // - let keyBytes = null; - let dataBytes = null; - let dataOffset = -1; - // var dataLength = -1; - // var idx2 = -1; - // - - let tfsKey = []; - let tfsM = [ - [], - [], - [], - [] - ]; - - function tfsInit(key) { - keyBytes = key; - let i; - let a; - let b; - let c; - let d; - const meKey = []; - const moKey = []; - const inKey = []; - let kLen; - const sKey = []; - let f01; - let f5b; - let fef; - - const q0 = [ - [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], - [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] - ]; - const q1 = [ - [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], - [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] - ]; - const q2 = [ - [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], - [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] - ]; - const q3 = [ - [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], - [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] - ]; - const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - const q = [ - [], - [] - ]; - const m = [ - [], - [], - [], - [] - ]; - - function ffm5b(x) { - return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; - } - - function ffmEf(x) { - return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; - } - - function mdsRem(p, q) { - let i; - let t; - let u; - for (i = 0; i < 8; i++) { - t = q >>> 24; - q = ((q << 8) & MAXINT) | p >>> 24; - p = (p << 8) & MAXINT; - u = t << 1; - if (t & 128) { - u ^= 333; - } - q ^= t ^ (u << 16); - u ^= t >>> 1; - if (t & 1) { - u ^= 166; - } - q ^= u << 24 | u << 8; - } - return q; - } - - function qp(n, x) { - const a = x >> 4; - const b = x & 15; - const c = q0[n][a ^ b]; - const d = q1[n][ror4[b] ^ ashx[a]]; - return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; - } - - function hFun(x, key) { - let a = getB(x, 0); - let b = getB(x, 1); - let c = getB(x, 2); - let d = getB(x, 3); - switch (kLen) { - case 4: - a = q[1][a] ^ getB(key[3], 0); - b = q[0][b] ^ getB(key[3], 1); - c = q[0][c] ^ getB(key[3], 2); - d = q[1][d] ^ getB(key[3], 3); - case 3: - a = q[1][a] ^ getB(key[2], 0); - b = q[1][b] ^ getB(key[2], 1); - c = q[0][c] ^ getB(key[2], 2); - d = q[0][d] ^ getB(key[2], 3); - case 2: - a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); - b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); - c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); - d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); - } - return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; - } - - keyBytes = keyBytes.slice(0, 32); - i = keyBytes.length; - while (i !== 16 && i !== 24 && i !== 32) { - keyBytes[i++] = 0; - } - - for (i = 0; i < keyBytes.length; i += 4) { - inKey[i >> 2] = getW(keyBytes, i); - } - for (i = 0; i < 256; i++) { - q[0][i] = qp(0, i); - q[1][i] = qp(1, i); - } - for (i = 0; i < 256; i++) { - f01 = q[1][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - f01 = q[0][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } - - kLen = inKey.length / 2; - for (i = 0; i < kLen; i++) { - a = inKey[i + i]; - meKey[i] = a; - b = inKey[i + i + 1]; - moKey[i] = b; - sKey[kLen - i - 1] = mdsRem(a, b); - } - for (i = 0; i < 40; i += 2) { - a = 0x1010101 * i; - b = a + 0x1010101; - a = hFun(a, meKey); - b = rotw(hFun(b, moKey), 8); - tfsKey[i] = (a + b) & MAXINT; - tfsKey[i + 1] = rotw(a + 2 * b, 9); - } - for (i = 0; i < 256; i++) { - a = b = c = d = i; - switch (kLen) { - case 4: - a = q[1][a] ^ getB(sKey[3], 0); - b = q[0][b] ^ getB(sKey[3], 1); - c = q[0][c] ^ getB(sKey[3], 2); - d = q[1][d] ^ getB(sKey[3], 3); - case 3: - a = q[1][a] ^ getB(sKey[2], 0); - b = q[1][b] ^ getB(sKey[2], 1); - c = q[0][c] ^ getB(sKey[2], 2); - d = q[0][d] ^ getB(sKey[2], 3); - case 2: - tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; - tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; - tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; - tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; - } - } - } - - function tfsG0(x) { - return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; - } - - function tfsG1(x) { - return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; - } - - function tfsFrnd(r, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); - blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); - blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; - } - - function tfsIrnd(i, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; - blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; - blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); - } - - function tfsClose() { - tfsKey = []; - tfsM = [ - [], - [], - [], - [] - ]; - } - - function tfsEncrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; - for (let j = 0; j < 8; j++) { - tfsFrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); - dataOffset += 16; - return dataBytes; - } - - function tfsDecrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; - for (let j = 7; j >= 0; j--) { - tfsIrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); - dataOffset += 16; - } - - // added by Recurity Labs - - function tfsFinal() { - return dataBytes; - } - - return { - name: 'twofish', - blocksize: 128 / 8, - open: tfsInit, - close: tfsClose, - encrypt: tfsEncrypt, - decrypt: tfsDecrypt, - // added by Recurity Labs - finalize: tfsFinal - }; -} - -// added by Recurity Labs - -function TF(key) { - this.tf = createTwofish(); - this.tf.open(Array.from(key), 0); - - this.encrypt = function(block) { - return this.tf.encrypt(Array.from(block), 0); - }; -} - -TF.keySize = TF.prototype.keySize = 32; -TF.blockSize = TF.prototype.blockSize = 16; - -/* Modified by Recurity Labs GmbH - * - * Originally written by nklein software (nklein.com) - */ - -/* - * Javascript implementation based on Bruce Schneier's reference implementation. - * - * - * The constructor doesn't do much of anything. It's just here - * so we can start defining properties and methods and such. - */ -function Blowfish() {} - -/* - * Declare the block size so that protocols know what size - * Initialization Vector (IV) they will need. - */ -Blowfish.prototype.BLOCKSIZE = 8; - -/* - * These are the default SBOXES. - */ -Blowfish.prototype.SBOXES = [ - [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a - ], - [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 - ], - [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 - ], - [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ] -]; - -//* -//* This is the default PARRAY -//* -Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b -]; - -//* -//* This is the number of rounds the cipher will go -//* -Blowfish.prototype.NN = 16; - -//* -//* This function is needed to get rid of problems -//* with the high-bit getting set. If we don't do -//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not -//* equal to ( bb & 0x00FFFFFFFF ) even when they -//* agree bit-for-bit for the first 32 bits. -//* -Blowfish.prototype._clean = function(xx) { - if (xx < 0) { - const yy = xx & 0x7FFFFFFF; - xx = yy + 0x80000000; - } - return xx; -}; - -//* -//* This is the mixing function that uses the sboxes -//* -Blowfish.prototype._F = function(xx) { - let yy; - - const dd = xx & 0x00FF; - xx >>>= 8; - const cc = xx & 0x00FF; - xx >>>= 8; - const bb = xx & 0x00FF; - xx >>>= 8; - const aa = xx & 0x00FF; - - yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy ^= this.sboxes[2][cc]; - yy += this.sboxes[3][dd]; - - return yy; -}; - -//* -//* This method takes an array with two values, left and right -//* and does NN rounds of Blowfish on them. -//* -Blowfish.prototype._encryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; - - let ii; - - for (ii = 0; ii < this.NN; ++ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; - - const tmp = dataL; - dataL = dataR; - dataR = tmp; - } - - dataL ^= this.parray[this.NN + 0]; - dataR ^= this.parray[this.NN + 1]; - - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; - -//* -//* This method takes a vector of numbers and turns them -//* into long words so that they can be processed by the -//* real algorithm. -//* -//* Maybe I should make the real algorithm above take a vector -//* instead. That will involve more looping, but it won't require -//* the F() method to deconstruct the vector. -//* -Blowfish.prototype.encryptBlock = function(vector) { - let ii; - const vals = [0, 0]; - const off = this.BLOCKSIZE / 2; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); - vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); - } - - this._encryptBlock(vals); - - const ret = []; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); - ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); - // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); - // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); - } - - return ret; -}; - -//* -//* This method takes an array with two values, left and right -//* and undoes NN rounds of Blowfish on them. -//* -Blowfish.prototype._decryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; - - let ii; - - for (ii = this.NN + 1; ii > 1; --ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; - - const tmp = dataL; - dataL = dataR; - dataR = tmp; - } - - dataL ^= this.parray[1]; - dataR ^= this.parray[0]; - - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; - -//* -//* This method takes a key array and initializes the -//* sboxes and parray for this encryption. -//* -Blowfish.prototype.init = function(key) { - let ii; - let jj = 0; - - this.parray = []; - for (ii = 0; ii < this.NN + 2; ++ii) { - let data = 0x00000000; - for (let kk = 0; kk < 4; ++kk) { - data = (data << 8) | (key[jj] & 0x00FF); - if (++jj >= key.length) { - jj = 0; - } - } - this.parray[ii] = this.PARRAY[ii] ^ data; - } - - this.sboxes = []; - for (ii = 0; ii < 4; ++ii) { - this.sboxes[ii] = []; - for (jj = 0; jj < 256; ++jj) { - this.sboxes[ii][jj] = this.SBOXES[ii][jj]; - } - } - - const vals = [0x00000000, 0x00000000]; - - for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encryptBlock(vals); - this.parray[ii + 0] = vals[0]; - this.parray[ii + 1] = vals[1]; - } - - for (ii = 0; ii < 4; ++ii) { - for (jj = 0; jj < 256; jj += 2) { - this._encryptBlock(vals); - this.sboxes[ii][jj + 0] = vals[0]; - this.sboxes[ii][jj + 1] = vals[1]; - } - } -}; - -// added by Recurity Labs -function BF(key) { - this.bf = new Blowfish(); - this.bf.init(key); - - this.encrypt = function(block) { - return this.bf.encryptBlock(block); - }; -} - -BF.keySize = BF.prototype.keySize = 16; -BF.blockSize = BF.prototype.blockSize = 8; - -/** - * @fileoverview Symmetric cryptography functions - * @module crypto/cipher - * @private - */ - -/** - * AES-128 encryption and decryption (ID 7) - * @function - * @param {String} key - 128-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes128 = aes(128); -/** - * AES-128 Block Cipher (ID 8) - * @function - * @param {String} key - 192-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes192 = aes(192); -/** - * AES-128 Block Cipher (ID 9) - * @function - * @param {String} key - 256-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes256 = aes(256); -// Not in OpenPGP specifications -const des$1 = DES; -/** - * Triple DES Block Cipher (ID 2) - * @function - * @param {String} key - 192-bit key - * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67} - * @returns {Object} - */ -const tripledes = TripleDES; -/** - * CAST-128 Block Cipher (ID 3) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} - * @returns {Object} - */ -const cast5 = CAST5; -/** - * Twofish Block Cipher (ID 10) - * @function - * @param {String} key - 256-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH} - * @returns {Object} - */ -const twofish = TF; -/** - * Blowfish Block Cipher (ID 4) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH} - * @returns {Object} - */ -const blowfish = BF; -/** - * Not implemented - * @function - * @throws {Error} - */ -const idea = function() { - throw new Error('IDEA symmetric-key algorithm not implemented'); -}; - -var cipher = /*#__PURE__*/Object.freeze({ - __proto__: null, - aes128: aes128, - aes192: aes192, - aes256: aes256, - des: des$1, - tripledes: tripledes, - cast5: cast5, - twofish: twofish, - blowfish: blowfish, - idea: idea -}); - -var sha1_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0, - w16 = 0, w17 = 0, w18 = 0, w19 = 0, - w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0, - w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0, - w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0, - w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0, - w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0, - w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - - // 0 - t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 1 - t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 2 - t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 3 - t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 4 - t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 5 - t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 6 - t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 7 - t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 8 - t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 9 - t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 10 - t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 11 - t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 12 - t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 13 - t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 14 - t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 15 - t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 16 - n = w13 ^ w8 ^ w2 ^ w0; - w16 = (n << 1) | (n >>> 31); - t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 17 - n = w14 ^ w9 ^ w3 ^ w1; - w17 = (n << 1) | (n >>> 31); - t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 18 - n = w15 ^ w10 ^ w4 ^ w2; - w18 = (n << 1) | (n >>> 31); - t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 19 - n = w16 ^ w11 ^ w5 ^ w3; - w19 = (n << 1) | (n >>> 31); - t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 20 - n = w17 ^ w12 ^ w6 ^ w4; - w20 = (n << 1) | (n >>> 31); - t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 21 - n = w18 ^ w13 ^ w7 ^ w5; - w21 = (n << 1) | (n >>> 31); - t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 22 - n = w19 ^ w14 ^ w8 ^ w6; - w22 = (n << 1) | (n >>> 31); - t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 23 - n = w20 ^ w15 ^ w9 ^ w7; - w23 = (n << 1) | (n >>> 31); - t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 24 - n = w21 ^ w16 ^ w10 ^ w8; - w24 = (n << 1) | (n >>> 31); - t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 25 - n = w22 ^ w17 ^ w11 ^ w9; - w25 = (n << 1) | (n >>> 31); - t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 26 - n = w23 ^ w18 ^ w12 ^ w10; - w26 = (n << 1) | (n >>> 31); - t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 27 - n = w24 ^ w19 ^ w13 ^ w11; - w27 = (n << 1) | (n >>> 31); - t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 28 - n = w25 ^ w20 ^ w14 ^ w12; - w28 = (n << 1) | (n >>> 31); - t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 29 - n = w26 ^ w21 ^ w15 ^ w13; - w29 = (n << 1) | (n >>> 31); - t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 30 - n = w27 ^ w22 ^ w16 ^ w14; - w30 = (n << 1) | (n >>> 31); - t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 31 - n = w28 ^ w23 ^ w17 ^ w15; - w31 = (n << 1) | (n >>> 31); - t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 32 - n = w29 ^ w24 ^ w18 ^ w16; - w32 = (n << 1) | (n >>> 31); - t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 33 - n = w30 ^ w25 ^ w19 ^ w17; - w33 = (n << 1) | (n >>> 31); - t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 34 - n = w31 ^ w26 ^ w20 ^ w18; - w34 = (n << 1) | (n >>> 31); - t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 35 - n = w32 ^ w27 ^ w21 ^ w19; - w35 = (n << 1) | (n >>> 31); - t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 36 - n = w33 ^ w28 ^ w22 ^ w20; - w36 = (n << 1) | (n >>> 31); - t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 37 - n = w34 ^ w29 ^ w23 ^ w21; - w37 = (n << 1) | (n >>> 31); - t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 38 - n = w35 ^ w30 ^ w24 ^ w22; - w38 = (n << 1) | (n >>> 31); - t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 39 - n = w36 ^ w31 ^ w25 ^ w23; - w39 = (n << 1) | (n >>> 31); - t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 40 - n = w37 ^ w32 ^ w26 ^ w24; - w40 = (n << 1) | (n >>> 31); - t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 41 - n = w38 ^ w33 ^ w27 ^ w25; - w41 = (n << 1) | (n >>> 31); - t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 42 - n = w39 ^ w34 ^ w28 ^ w26; - w42 = (n << 1) | (n >>> 31); - t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 43 - n = w40 ^ w35 ^ w29 ^ w27; - w43 = (n << 1) | (n >>> 31); - t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 44 - n = w41 ^ w36 ^ w30 ^ w28; - w44 = (n << 1) | (n >>> 31); - t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 45 - n = w42 ^ w37 ^ w31 ^ w29; - w45 = (n << 1) | (n >>> 31); - t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 46 - n = w43 ^ w38 ^ w32 ^ w30; - w46 = (n << 1) | (n >>> 31); - t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 47 - n = w44 ^ w39 ^ w33 ^ w31; - w47 = (n << 1) | (n >>> 31); - t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 48 - n = w45 ^ w40 ^ w34 ^ w32; - w48 = (n << 1) | (n >>> 31); - t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 49 - n = w46 ^ w41 ^ w35 ^ w33; - w49 = (n << 1) | (n >>> 31); - t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 50 - n = w47 ^ w42 ^ w36 ^ w34; - w50 = (n << 1) | (n >>> 31); - t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 51 - n = w48 ^ w43 ^ w37 ^ w35; - w51 = (n << 1) | (n >>> 31); - t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 52 - n = w49 ^ w44 ^ w38 ^ w36; - w52 = (n << 1) | (n >>> 31); - t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 53 - n = w50 ^ w45 ^ w39 ^ w37; - w53 = (n << 1) | (n >>> 31); - t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 54 - n = w51 ^ w46 ^ w40 ^ w38; - w54 = (n << 1) | (n >>> 31); - t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 55 - n = w52 ^ w47 ^ w41 ^ w39; - w55 = (n << 1) | (n >>> 31); - t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 56 - n = w53 ^ w48 ^ w42 ^ w40; - w56 = (n << 1) | (n >>> 31); - t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 57 - n = w54 ^ w49 ^ w43 ^ w41; - w57 = (n << 1) | (n >>> 31); - t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 58 - n = w55 ^ w50 ^ w44 ^ w42; - w58 = (n << 1) | (n >>> 31); - t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 59 - n = w56 ^ w51 ^ w45 ^ w43; - w59 = (n << 1) | (n >>> 31); - t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 60 - n = w57 ^ w52 ^ w46 ^ w44; - w60 = (n << 1) | (n >>> 31); - t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 61 - n = w58 ^ w53 ^ w47 ^ w45; - w61 = (n << 1) | (n >>> 31); - t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 62 - n = w59 ^ w54 ^ w48 ^ w46; - w62 = (n << 1) | (n >>> 31); - t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 63 - n = w60 ^ w55 ^ w49 ^ w47; - w63 = (n << 1) | (n >>> 31); - t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 64 - n = w61 ^ w56 ^ w50 ^ w48; - w64 = (n << 1) | (n >>> 31); - t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 65 - n = w62 ^ w57 ^ w51 ^ w49; - w65 = (n << 1) | (n >>> 31); - t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 66 - n = w63 ^ w58 ^ w52 ^ w50; - w66 = (n << 1) | (n >>> 31); - t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 67 - n = w64 ^ w59 ^ w53 ^ w51; - w67 = (n << 1) | (n >>> 31); - t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 68 - n = w65 ^ w60 ^ w54 ^ w52; - w68 = (n << 1) | (n >>> 31); - t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 69 - n = w66 ^ w61 ^ w55 ^ w53; - w69 = (n << 1) | (n >>> 31); - t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 70 - n = w67 ^ w62 ^ w56 ^ w54; - w70 = (n << 1) | (n >>> 31); - t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 71 - n = w68 ^ w63 ^ w57 ^ w55; - w71 = (n << 1) | (n >>> 31); - t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 72 - n = w69 ^ w64 ^ w58 ^ w56; - w72 = (n << 1) | (n >>> 31); - t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 73 - n = w70 ^ w65 ^ w59 ^ w57; - w73 = (n << 1) | (n >>> 31); - t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 74 - n = w71 ^ w66 ^ w60 ^ w58; - w74 = (n << 1) | (n >>> 31); - t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 75 - n = w72 ^ w67 ^ w61 ^ w59; - w75 = (n << 1) | (n >>> 31); - t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 76 - n = w73 ^ w68 ^ w62 ^ w60; - w76 = (n << 1) | (n >>> 31); - t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 77 - n = w74 ^ w69 ^ w63 ^ w61; - w77 = (n << 1) | (n >>> 31); - t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 78 - n = w75 ^ w70 ^ w64 ^ w62; - w78 = (n << 1) | (n >>> 31); - t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 79 - n = w76 ^ w71 ^ w65 ^ w63; - w79 = (n << 1) | (n >>> 31); - t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - } - - function reset () { - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA1 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA1 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA1 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; - -class Hash { - constructor() { - this.pos = 0; - this.len = 0; - } - reset() { - const { asm } = this.acquire_asm(); - this.result = null; - this.pos = 0; - this.len = 0; - asm.reset(); - return this; - } - process(data) { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - let hpos = this.pos; - let hlen = this.len; - let dpos = 0; - let dlen = data.length; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.process(hpos, hlen); - hpos += wlen; - hlen -= wlen; - if (!hlen) - hpos = 0; - } - this.pos = hpos; - this.len = hlen; - return this; - } - finish() { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - asm.finish(this.pos, this.len, 0); - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set(heap.subarray(0, this.HASH_SIZE)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return this; - } -} - -const _sha1_block_size = 64; -const _sha1_hash_size = 20; -const heap_pool$1 = []; -const asm_pool$1 = []; -class Sha1 extends Hash { - constructor() { - super(); - this.NAME = 'sha1'; - this.BLOCK_SIZE = _sha1_block_size; - this.HASH_SIZE = _sha1_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$1.pop() || _heap_init(); - this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$1.push(this.heap); - asm_pool$1.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha1().process(data).finish().result; - } -} -Sha1.NAME = 'sha1'; -Sha1.heap_pool = []; -Sha1.asm_pool = []; -Sha1.asm_function = sha1_asm; - -var sha256_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - f = H5; - g = H6; - h = H7; - - // 0 - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 1 - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 2 - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 3 - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 4 - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 5 - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 6 - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 7 - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 8 - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 9 - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 10 - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 11 - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 12 - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 13 - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 14 - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 15 - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 16 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 17 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 18 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 19 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 20 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 21 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 22 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 23 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 24 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 25 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 26 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 27 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 28 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 29 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 30 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 31 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 32 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 33 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 34 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 35 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 36 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 37 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 38 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 39 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 40 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 41 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 42 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 43 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 44 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 45 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 46 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 47 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 48 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 49 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 50 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 51 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 52 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 53 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 54 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 55 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 56 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 57 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 58 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 59 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 60 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 61 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 62 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 63 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; - } - - function reset () { - H0 = 0x6a09e667; - H1 = 0xbb67ae85; - H2 = 0x3c6ef372; - H3 = 0xa54ff53a; - H4 = 0x510e527f; - H5 = 0x9b05688c; - H6 = 0x1f83d9ab; - H7 = 0x5be0cd19; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - H5 = I5; - H6 = I6; - H7 = I7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - H5 = O5; - H6 = O6; - H7 = O7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - O5 = H5; - O6 = H6; - O7 = H7; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - I5 = H5; - I6 = H6; - I7 = H7; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - h5 = h5 ^ H5; - h6 = h6 ^ H6; - h7 = h7 ^ H7; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA256 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA256 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA256 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; - -const _sha256_block_size = 64; -const _sha256_hash_size = 32; -const heap_pool$2 = []; -const asm_pool$2 = []; -class Sha256 extends Hash { - constructor() { - super(); - this.NAME = 'sha256'; - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$2.pop() || _heap_init(); - this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$2.push(this.heap); - asm_pool$2.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha256().process(data).finish().result; - } -} -Sha256.NAME = 'sha256'; - -var minimalisticAssert = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var inherits_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; -} -}); - -var inherits = createCommonjsModule(function (module) { -try { - var util = util__default['default']; - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = inherits_browser; -} -}); - -var inherits_1 = inherits; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -var toArray_1 = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -var htonl_1 = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -var toHex32_1 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -var zero2_1 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -var zero8_1 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -var join32_1 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -var split32_1 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -var rotr32_1 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -var rotl32_1 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -var sum32_1 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -var sum32_3_1 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -var sum32_4_1 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -var sum32_5_1 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -var sum64_1 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -var sum64_lo_1 = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -var sum64_5_lo_1 = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -var rotr64_hi_1 = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var rotr64_lo_1 = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var shr64_lo_1 = shr64_lo; - -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -var common = { - BlockHash: BlockHash_1 -}; - -var rotr32$1 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -var ft_1_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -var ch32_1 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -var maj32_1 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; - -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; - -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; - -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); -} -var g0_256_1 = g0_256; - -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); -} -var g1_256_1 = g1_256; - -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; - -var sum32$1 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$1 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; - -var BlockHash$1 = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$1); -var _256 = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - _256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, _256); -var _224 = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - -var rotr64_hi$1 = utils.rotr64_hi; -var rotr64_lo$1 = utils.rotr64_lo; -var shr64_hi$1 = utils.shr64_hi; -var shr64_lo$1 = utils.shr64_lo; -var sum64$1 = utils.sum64; -var sum64_hi$1 = utils.sum64_hi; -var sum64_lo$1 = utils.sum64_lo; -var sum64_4_hi$1 = utils.sum64_4_hi; -var sum64_4_lo$1 = utils.sum64_4_lo; -var sum64_5_hi$1 = utils.sum64_5_hi; -var sum64_5_lo$1 = utils.sum64_5_lo; - -var BlockHash$2 = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash$2); -var _512 = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - minimalisticAssert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); // 34 - var c2_hi = rotr64_hi$1(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); // 34 - var c2_lo = rotr64_lo$1(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); // 61 - var c2_hi = shr64_hi$1(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); // 61 - var c2_lo = shr64_lo$1(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - _512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, _512); -var _384 = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -var rotl32$1 = utils.rotl32; -var sum32$2 = utils.sum32; -var sum32_3$1 = utils.sum32_3; -var sum32_4$2 = utils.sum32_4; -var BlockHash$3 = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash$3.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash$3); -var ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32$2( - rotl32$1( - sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32$1(C, 10); - C = B; - B = T; - T = sum32$2( - rotl32$1( - sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$1(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -var ripemd = { - ripemd160: ripemd160 -}; - -/** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. - */ - -// MD5 Digest -async function md5(entree) { - const digest = md51(util.uint8ArrayToString(entree)); - return util.hexToUint8Array(hex(digest)); -} - -function md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - - a = ff(a, b, c, d, k[0], 7, -680876936); - d = ff(d, a, b, c, k[1], 12, -389564586); - c = ff(c, d, a, b, k[2], 17, 606105819); - b = ff(b, c, d, a, k[3], 22, -1044525330); - a = ff(a, b, c, d, k[4], 7, -176418897); - d = ff(d, a, b, c, k[5], 12, 1200080426); - c = ff(c, d, a, b, k[6], 17, -1473231341); - b = ff(b, c, d, a, k[7], 22, -45705983); - a = ff(a, b, c, d, k[8], 7, 1770035416); - d = ff(d, a, b, c, k[9], 12, -1958414417); - c = ff(c, d, a, b, k[10], 17, -42063); - b = ff(b, c, d, a, k[11], 22, -1990404162); - a = ff(a, b, c, d, k[12], 7, 1804603682); - d = ff(d, a, b, c, k[13], 12, -40341101); - c = ff(c, d, a, b, k[14], 17, -1502002290); - b = ff(b, c, d, a, k[15], 22, 1236535329); - - a = gg(a, b, c, d, k[1], 5, -165796510); - d = gg(d, a, b, c, k[6], 9, -1069501632); - c = gg(c, d, a, b, k[11], 14, 643717713); - b = gg(b, c, d, a, k[0], 20, -373897302); - a = gg(a, b, c, d, k[5], 5, -701558691); - d = gg(d, a, b, c, k[10], 9, 38016083); - c = gg(c, d, a, b, k[15], 14, -660478335); - b = gg(b, c, d, a, k[4], 20, -405537848); - a = gg(a, b, c, d, k[9], 5, 568446438); - d = gg(d, a, b, c, k[14], 9, -1019803690); - c = gg(c, d, a, b, k[3], 14, -187363961); - b = gg(b, c, d, a, k[8], 20, 1163531501); - a = gg(a, b, c, d, k[13], 5, -1444681467); - d = gg(d, a, b, c, k[2], 9, -51403784); - c = gg(c, d, a, b, k[7], 14, 1735328473); - b = gg(b, c, d, a, k[12], 20, -1926607734); - - a = hh(a, b, c, d, k[5], 4, -378558); - d = hh(d, a, b, c, k[8], 11, -2022574463); - c = hh(c, d, a, b, k[11], 16, 1839030562); - b = hh(b, c, d, a, k[14], 23, -35309556); - a = hh(a, b, c, d, k[1], 4, -1530992060); - d = hh(d, a, b, c, k[4], 11, 1272893353); - c = hh(c, d, a, b, k[7], 16, -155497632); - b = hh(b, c, d, a, k[10], 23, -1094730640); - a = hh(a, b, c, d, k[13], 4, 681279174); - d = hh(d, a, b, c, k[0], 11, -358537222); - c = hh(c, d, a, b, k[3], 16, -722521979); - b = hh(b, c, d, a, k[6], 23, 76029189); - a = hh(a, b, c, d, k[9], 4, -640364487); - d = hh(d, a, b, c, k[12], 11, -421815835); - c = hh(c, d, a, b, k[15], 16, 530742520); - b = hh(b, c, d, a, k[2], 23, -995338651); - - a = ii(a, b, c, d, k[0], 6, -198630844); - d = ii(d, a, b, c, k[7], 10, 1126891415); - c = ii(c, d, a, b, k[14], 15, -1416354905); - b = ii(b, c, d, a, k[5], 21, -57434055); - a = ii(a, b, c, d, k[12], 6, 1700485571); - d = ii(d, a, b, c, k[3], 10, -1894986606); - c = ii(c, d, a, b, k[10], 15, -1051523); - b = ii(b, c, d, a, k[1], 21, -2054922799); - a = ii(a, b, c, d, k[8], 6, 1873313359); - d = ii(d, a, b, c, k[15], 10, -30611744); - c = ii(c, d, a, b, k[6], 15, -1560198380); - b = ii(b, c, d, a, k[13], 21, 1309151649); - a = ii(a, b, c, d, k[4], 6, -145523070); - d = ii(d, a, b, c, k[11], 10, -1120210379); - c = ii(c, d, a, b, k[2], 15, 718787259); - b = ii(b, c, d, a, k[9], 21, -343485551); - - x[0] = add32(a, x[0]); - x[1] = add32(b, x[1]); - x[2] = add32(c, x[2]); - x[3] = add32(d, x[3]); -} - -function cmn(q, a, b, x, s, t) { - a = add32(add32(a, q), add32(x, t)); - return add32((a << s) | (a >>> (32 - s)), b); -} - -function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} - -function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); -} - -function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); -} - -function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -function md51(s) { - const n = s.length; - const state = [1732584193, -271733879, -1732584194, 271733878]; - let i; - for (i = 64; i <= s.length; i += 64) { - md5cycle(state, md5blk(s.substring(i - 64, i))); - } - s = s.substring(i - 64); - const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (i = 0; i < s.length; i++) { - tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); - } - tail[i >> 2] |= 0x80 << ((i % 4) << 3); - if (i > 55) { - md5cycle(state, tail); - for (i = 0; i < 16; i++) { - tail[i] = 0; - } - } - tail[14] = n * 8; - md5cycle(state, tail); - return state; -} - -/* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ -function md5blk(s) { /* I figured global was faster. */ - const md5blks = []; - let i; /* Andy King said do it this way. */ - for (i = 0; i < 64; i += 4) { - md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << - 24); - } - return md5blks; -} - -const hex_chr = '0123456789abcdef'.split(''); - -function rhex(n) { - let s = ''; - let j = 0; - for (; j < 4; j++) { - s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; - } - return s; -} - -function hex(x) { - for (let i = 0; i < x.length; i++) { - x[i] = rhex(x[i]); - } - return x.join(''); -} - -/* this function is much faster, -so if possible we use it. Some IEs -are the only ones I know of that -need the idiotic second function, -generated by an if clause. */ - -function add32(a, b) { - return (a + b) & 0xFFFFFFFF; -} - -/** - * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://github.com/indutny/hash.js|hash.js} - * @module crypto/hash - * @private - */ - -const webCrypto = util.getWebCrypto(); -const nodeCrypto = util.getNodeCrypto(); -const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes(); - -function nodeHash(type) { - if (!nodeCrypto || !nodeCryptoHashes.includes(type)) { - return; - } - return async function (data) { - const shasum = nodeCrypto.createHash(type); - return transform(data, value => { - shasum.update(value); - }, () => new Uint8Array(shasum.digest())); - }; -} - -function hashjsHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } - const hashInstance = hash(); - return transform(data, value => { - hashInstance.update(value); - }, () => new Uint8Array(hashInstance.digest())); - }; -} - -function asmcryptoHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (util.isStream(data)) { - const hashInstance = new hash(); - return transform(data, value => { - hashInstance.process(value); - }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } else { - return hash.bytes(data); - } - }; -} - -const hashFunctions = { - md5: nodeHash('md5') || md5, - sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'), - sha224: nodeHash('sha224') || hashjsHash(_224), - sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'), - sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'), - sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160) -}; - -var hash = { - - /** @see module:md5 */ - md5: hashFunctions.md5, - /** @see asmCrypto */ - sha1: hashFunctions.sha1, - /** @see hash.js */ - sha224: hashFunctions.sha224, - /** @see asmCrypto */ - sha256: hashFunctions.sha256, - /** @see hash.js */ - sha384: hashFunctions.sha384, - /** @see asmCrypto */ - sha512: hashFunctions.sha512, - /** @see hash.js */ - ripemd: hashFunctions.ripemd, - - /** - * Create a hash on the specified data using the specified algorithm - * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {Uint8Array} data - Data to be hashed - * @returns {Promise} Hash value. - */ - digest: function(algo, data) { - switch (algo) { - case enums.hash.md5: - return this.md5(data); - case enums.hash.sha1: - return this.sha1(data); - case enums.hash.ripemd: - return this.ripemd(data); - case enums.hash.sha256: - return this.sha256(data); - case enums.hash.sha384: - return this.sha384(data); - case enums.hash.sha512: - return this.sha512(data); - case enums.hash.sha224: - return this.sha224(data); - default: - throw new Error('Invalid hash function.'); - } - }, - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns {Integer} Size in bytes of the resulting hash. - */ - getHashByteLength: function(algo) { - switch (algo) { - case enums.hash.md5: - return 16; - case enums.hash.sha1: - case enums.hash.ripemd: - return 20; - case enums.hash.sha256: - return 32; - case enums.hash.sha384: - return 48; - case enums.hash.sha512: - return 64; - case enums.hash.sha224: - return 28; - default: - throw new Error('Invalid hash algorithm.'); - } - } -}; - -class AES_CFB { - static encrypt(data, key, iv) { - return new AES_CFB(key, iv).encrypt(data); - } - static decrypt(data, key, iv) { - return new AES_CFB(key, iv).decrypt(data); - } - constructor(key, iv, aes) { - this.aes = aes ? aes : new AES(key, iv, true, 'CFB'); - delete this.aes.padding; - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * Get implementation of the given cipher - * @param {enums.symmetric} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getCipher(algo) { - const algoName = enums.read(enums.symmetric, algo); - return cipher[algoName]; -} - -// Modified by ProtonTech AG - -const webCrypto$1 = util.getWebCrypto(); -const nodeCrypto$1 = util.getNodeCrypto(); - -const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : []; -const nodeAlgos = { - idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ - tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, - cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, - blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, - aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, - aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, - aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined - /* twofish is not implemented in OpenSSL */ -}; - -/** - * CFB encryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} plaintext - * @param {Uint8Array} iv - * @param {Object} config - full configuration, defaults to openpgp.config - * @returns MaybeStream - */ -async function encrypt(algo, key, plaintext, iv, config) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeEncrypt(algo, key, plaintext, iv); - } - if (util.isAES(algo)) { - return aesEncrypt(algo, key, plaintext, iv, config); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - const blockc = iv.slice(); - let pt = new Uint8Array(); - const process = chunk => { - if (chunk) { - pt = util.concatUint8Array([pt, chunk]); - } - const ciphertext = new Uint8Array(pt.length); - let i; - let j = 0; - while (chunk ? pt.length >= block_size : pt.length) { - const encblock = cipherfn.encrypt(blockc); - for (i = 0; i < block_size; i++) { - blockc[i] = pt[i] ^ encblock[i]; - ciphertext[j++] = blockc[i]; - } - pt = pt.subarray(block_size); - } - return ciphertext.subarray(0, j); - }; - return transform(plaintext, process, process); -} - -/** - * CFB decryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} ciphertext - * @param {Uint8Array} iv - * @returns MaybeStream - */ -async function decrypt(algo, key, ciphertext, iv) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeDecrypt(algo, key, ciphertext, iv); - } - if (util.isAES(algo)) { - return aesDecrypt(algo, key, ciphertext, iv); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - let blockp = iv; - let ct = new Uint8Array(); - const process = chunk => { - if (chunk) { - ct = util.concatUint8Array([ct, chunk]); - } - const plaintext = new Uint8Array(ct.length); - let i; - let j = 0; - while (chunk ? ct.length >= block_size : ct.length) { - const decblock = cipherfn.encrypt(blockp); - blockp = ct.subarray(0, block_size); - for (i = 0; i < block_size; i++) { - plaintext[j++] = blockp[i] ^ decblock[i]; - } - ct = ct.subarray(block_size); - } - return plaintext.subarray(0, j); - }; - return transform(ciphertext, process, process); -} - -function aesEncrypt(algo, key, pt, iv, config) { - if ( - util.getWebCrypto() && - key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support - !util.isStream(pt) && - pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2 - ) { // Web Crypto - return webEncrypt(algo, key, pt, iv); - } - // asm.js fallback - const cfb = new AES_CFB(key, iv); - return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish()); -} - -function aesDecrypt(algo, key, ct, iv) { - if (util.isStream(ct)) { - const cfb = new AES_CFB(key, iv); - return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish()); - } - return AES_CFB.decrypt(ct, key, iv); -} - -function xorMut(a, b) { - for (let i = 0; i < a.length; i++) { - a[i] = a[i] ^ b[i]; - } -} - -async function webEncrypt(algo, key, pt, iv) { - const ALGO = 'AES-CBC'; - const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']); - const { blockSize } = getCipher(algo); - const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]); - const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length); - xorMut(ct, pt); - return ct; -} - -function nodeEncrypt(algo, key, pt, iv) { - const algoName = enums.read(enums.symmetric, algo); - const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv); - return transform(pt, value => new Uint8Array(cipherObj.update(value))); -} - -function nodeDecrypt(algo, key, ct, iv) { - const algoName = enums.read(enums.symmetric, algo); - const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv); - return transform(ct, value => new Uint8Array(decipherObj.update(value))); -} - -var cfb = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt, - decrypt: decrypt -}); - -class AES_CTR { - static encrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - static decrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - constructor(key, nonce, aes) { - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - delete this.aes.padding; - this.AES_CTR_set_options(nonce); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - AES_CTR_set_options(nonce, counter, size) { - let { asm } = this.aes.acquire_asm(); - if (size !== undefined) { - if (size < 8 || size > 48) - throw new IllegalArgumentError('illegal counter size'); - let mask = Math.pow(2, size) - 1; - asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0); - } - else { - size = 48; - asm.set_mask(0, 0, 0xffff, 0xffffffff); - } - if (nonce !== undefined) { - let len = nonce.length; - if (!len || len > 16) - throw new IllegalArgumentError('illegal nonce size'); - let view = new DataView(new ArrayBuffer(16)); - new Uint8Array(view.buffer).set(nonce); - asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); - } - else { - throw new Error('nonce is required'); - } - if (counter !== undefined) { - if (counter < 0 || counter >= Math.pow(2, size)) - throw new IllegalArgumentError('illegal counter value'); - asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0); - } - } -} - -class AES_CBC { - static encrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).encrypt(data); - } - static decrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).decrypt(data); - } - constructor(key, iv, padding = true, aes) { - this.aes = aes ? aes : new AES(key, iv, padding, 'CBC'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * @fileoverview This module implements AES-CMAC on top of - * native AES-CBC using either the WebCrypto API or Node.js' crypto API. - * @module crypto/cmac - * @private - */ - -const webCrypto$2 = util.getWebCrypto(); -const nodeCrypto$2 = util.getNodeCrypto(); - - -/** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - -const blockLength = 16; - - -/** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param {Uint8Array} data - * @param {Uint8Array} padding - */ -function rightXORMut(data, padding) { - const offset = data.length - blockLength; - for (let i = 0; i < blockLength; i++) { - data[i + offset] ^= padding[i]; - } - return data; -} - -function pad(data, padding, padding2) { - // if |M| in {n, 2n, 3n, ...} - if (data.length && data.length % blockLength === 0) { - // then return M xor→ B, - return rightXORMut(data, padding); - } - // else return (M || 10^(n−1−(|M| mod n))) xor→ P - const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength))); - padded.set(data); - padded[data.length] = 0b10000000; - return rightXORMut(padded, padding2); -} - -const zeroBlock = new Uint8Array(blockLength); - -async function CMAC(key) { - const cbc = await CBC(key); - - // L ← E_K(0^n); B ← 2L; P ← 4L - const padding = util.double(await cbc(zeroBlock)); - const padding2 = util.double(padding); - - return async function(data) { - // return CBC_K(pad(M; B, P)) - return (await cbc(pad(data, padding, padding2))).subarray(-blockLength); - }; -} - -async function CBC(key) { - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); - return async function(pt) { - const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt); - return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt) { - const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); - const ct = en.update(pt); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt) { - return AES_CBC.encrypt(pt, key, false, zeroBlock); - }; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$3 = util.getWebCrypto(); -const nodeCrypto$3 = util.getNodeCrypto(); -const Buffer$1 = util.getNodeBuffer(); - - -const blockLength$1 = 16; -const ivLength = blockLength$1; -const tagLength = blockLength$1; - -const zero = new Uint8Array(blockLength$1); -const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1; -const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2; - -async function OMAC(key) { - const cmac = await CMAC(key); - return function(t, message) { - return cmac(util.concatUint8Array([t, message])); - }; -} - -async function CTR(key) { - if ( - util.getWebCrypto() && - key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - ) { - key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); - return async function(pt, iv) { - const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt); - return new Uint8Array(ct); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt, iv) { - const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); - const ct = Buffer$1.concat([en.update(pt), en.final()]); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt, iv) { - return AES_CTR.encrypt(pt, key, iv); - }; -} - - -/** - * Class to en/decrypt using EAX mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function EAX(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('EAX mode supports only AES cipher'); - } - - const [ - omac, - ctr - ] = await Promise.all([ - OMAC(key), - CTR(key) - ]); - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - const [ - omacNonce, - omacAdata - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata) - ]); - const ciphered = await ctr(plaintext, omacNonce); - const omacCiphered = await omac(two, ciphered); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - return util.concatUint8Array([ciphered, tag]); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to verify - * @returns {Promise} The plaintext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext'); - const ciphered = ciphertext.subarray(0, -tagLength); - const ctTag = ciphertext.subarray(-tagLength); - const [ - omacNonce, - omacAdata, - omacCiphered - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata), - omac(two, ciphered) - ]); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); - const plaintext = await ctr(ciphered, omacNonce); - return plaintext; - } - }; -} - - -/** - * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. - * @param {Uint8Array} iv - The initialization vector (16 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -EAX.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[8 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -EAX.blockLength = blockLength$1; -EAX.ivLength = ivLength; -EAX.tagLength = tagLength; - -// OpenPGP.js - An OpenPGP implementation in javascript - -const blockLength$2 = 16; -const ivLength$1 = 15; - -// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: -// While OCB [RFC7253] allows the authentication tag length to be of any -// number up to 128 bits long, this document requires a fixed -// authentication tag length of 128 bits (16 octets) for simplicity. -const tagLength$1 = 16; - - -function ntz(n) { - let ntz = 0; - for (let i = 1; (n & i) === 0; i <<= 1) { - ntz++; - } - return ntz; -} - -function xorMut$1(S, T) { - for (let i = 0; i < S.length; i++) { - S[i] ^= T[i]; - } - return S; -} - -function xor(S, T) { - return xorMut$1(S.slice(), T); -} - -const zeroBlock$1 = new Uint8Array(blockLength$2); -const one$1 = new Uint8Array([1]); - -/** - * Class to en/decrypt using OCB mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function OCB(cipher$1, key) { - - let maxNtz = 0; - let encipher; - let decipher; - let mask; - - constructKeyVariables(cipher$1, key); - - function constructKeyVariables(cipher$1, key) { - const cipherName = enums.read(enums.symmetric, cipher$1); - const aes = new cipher[cipherName](key); - encipher = aes.encrypt.bind(aes); - decipher = aes.decrypt.bind(aes); - - const mask_x = encipher(zeroBlock$1); - const mask_$ = util.double(mask_x); - mask = []; - mask[0] = util.double(mask_$); - - - mask.x = mask_x; - mask.$ = mask_$; - } - - function extendKeyVariables(text, adata) { - const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1; - for (let i = maxNtz + 1; i <= newMaxNtz; i++) { - mask[i] = util.double(mask[i - 1]); - } - maxNtz = newMaxNtz; - } - - function hash(adata) { - if (!adata.length) { - // Fast path - return zeroBlock$1; - } - - // - // Consider A as a sequence of 128-bit blocks - // - const m = adata.length / blockLength$2 | 0; - - const offset = new Uint8Array(blockLength$2); - const sum = new Uint8Array(blockLength$2); - for (let i = 0; i < m; i++) { - xorMut$1(offset, mask[ntz(i + 1)]); - xorMut$1(sum, encipher(xor(offset, adata))); - adata = adata.subarray(blockLength$2); - } - - // - // Process any final partial block; compute final hash value - // - if (adata.length) { - xorMut$1(offset, mask.x); - - const cipherInput = new Uint8Array(blockLength$2); - cipherInput.set(adata, 0); - cipherInput[adata.length] = 0b10000000; - xorMut$1(cipherInput, offset); - - xorMut$1(sum, encipher(cipherInput)); - } - - return sum; - } - - /** - * Encrypt/decrypt data. - * @param {encipher|decipher} fn - Encryption/decryption block cipher function - * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. - */ - function crypt(fn, text, nonce, adata) { - // - // Consider P as a sequence of 128-bit blocks - // - const m = text.length / blockLength$2 | 0; - - // - // Key-dependent variables - // - extendKeyVariables(text, adata); - - // - // Nonce-dependent and per-encryption variables - // - // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N - // Note: We assume here that tagLength mod 16 == 0. - const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]); - // bottom = str2num(Nonce[123..128]) - const bottom = paddedNonce[blockLength$2 - 1] & 0b111111; - // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) - paddedNonce[blockLength$2 - 1] &= 0b11000000; - const kTop = encipher(paddedNonce); - // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) - const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); - // Offset_0 = Stretch[1+bottom..128+bottom] - const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); - // Checksum_0 = zeros(128) - const checksum = new Uint8Array(blockLength$2); - - const ct = new Uint8Array(text.length + tagLength$1); - - // - // Process any whole blocks - // - let i; - let pos = 0; - for (i = 0; i < m; i++) { - // Offset_i = Offset_{i-1} xor L_{ntz(i)} - xorMut$1(offset, mask[ntz(i + 1)]); - // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) - // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) - ct.set(xorMut$1(fn(xor(offset, text)), offset), pos); - // Checksum_i = Checksum_{i-1} xor P_i - xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos)); - - text = text.subarray(blockLength$2); - pos += blockLength$2; - } - - // - // Process any final partial block and compute raw tag - // - if (text.length) { - // Offset_* = Offset_m xor L_* - xorMut$1(offset, mask.x); - // Pad = ENCIPHER(K, Offset_*) - const padding = encipher(offset); - // C_* = P_* xor Pad[1..bitlen(P_*)] - ct.set(xor(text, padding), pos); - - // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - const xorInput = new Uint8Array(blockLength$2); - xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); - xorInput[text.length] = 0b10000000; - xorMut$1(checksum, xorInput); - pos += text.length; - } - // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) - const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata)); - - // - // Assemble ciphertext - // - // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] - ct.set(tag, pos); - return ct; - } - - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - return crypt(encipher, plaintext, nonce, adata); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); - - const tag = ciphertext.subarray(-tagLength$1); - ciphertext = ciphertext.subarray(0, -tagLength$1); - - const crypted = crypt(decipher, ciphertext, nonce, adata); - // if (Tag[1..TAGLEN] == T) - if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { - return crypted.subarray(0, -tagLength$1); - } - throw new Error('Authentication tag mismatch'); - } - }; -} - - -/** - * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. - * @param {Uint8Array} iv - The initialization vector (15 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -OCB.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[7 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -OCB.blockLength = blockLength$2; -OCB.ivLength = ivLength$1; -OCB.tagLength = tagLength$1; - -const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 -class AES_GCM { - constructor(key, nonce, adata, tagSize = 16, aes) { - this.tagSize = tagSize; - this.gamma0 = 0; - this.counter = 1; - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - let { asm, heap } = this.aes.acquire_asm(); - // Init GCM - asm.gcm_init(); - // Tag size - if (this.tagSize < 4 || this.tagSize > 16) - throw new IllegalArgumentError('illegal tagSize value'); - // Nonce - const noncelen = nonce.length || 0; - const noncebuf = new Uint8Array(16); - if (noncelen !== 12) { - this._gcm_mac_process(nonce); - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = 0; - heap[4] = 0; - heap[5] = 0; - heap[6] = 0; - heap[7] = 0; - heap[8] = 0; - heap[9] = 0; - heap[10] = 0; - heap[11] = noncelen >>> 29; - heap[12] = (noncelen >>> 21) & 255; - heap[13] = (noncelen >>> 13) & 255; - heap[14] = (noncelen >>> 5) & 255; - heap[15] = (noncelen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_iv(0, 0, 0, 0); - noncebuf.set(heap.subarray(0, 16)); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; - } - const nonceview = new DataView(noncebuf.buffer); - this.gamma0 = nonceview.getUint32(12); - asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); - asm.set_mask(0, 0, 0, 0xffffffff); - // Associated data - if (adata !== undefined) { - if (adata.length > _AES_GCM_data_maxLength) - throw new IllegalArgumentError('illegal adata length'); - if (adata.length) { - this.adata = adata; - this._gcm_mac_process(adata); - } - else { - this.adata = undefined; - } - } - else { - this.adata = undefined; - } - // Counter - if (this.counter < 1 || this.counter > 0xffffffff) - throw new RangeError('counter must be a positive 32-bit integer'); - asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0); - } - static encrypt(cleartext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext); - } - static decrypt(ciphertext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext); - } - encrypt(data) { - return this.AES_GCM_encrypt(data); - } - decrypt(data) { - return this.AES_GCM_decrypt(data); - } - AES_GCM_Encrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len); - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Encrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let adata = this.adata; - let pos = this.aes.pos; - let len = this.aes.len; - const result = new Uint8Array(len + tagSize); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16); - if (len) - result.set(heap.subarray(pos, pos + len)); - let i = len; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - result.set(heap.subarray(0, tagSize), len); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_Decrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0; - let tlen = len + dlen - rlen; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > tlen) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - pos = 0; - len = 0; - } - if (dlen > 0) { - len += _heap_write(heap, 0, data, dpos, dlen); - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Decrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let tagSize = this.tagSize; - let adata = this.adata; - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rlen = len - tagSize; - if (len < tagSize) - throw new IllegalStateError('authentication tag not found'); - const result = new Uint8Array(rlen); - const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); - let i = rlen; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len - tagSize; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - let acheck = 0; - for (let i = 0; i < tagSize; ++i) - acheck |= atag[i] ^ heap[i]; - if (acheck) - throw new SecurityError('data integrity check failed'); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_decrypt(data) { - const result1 = this.AES_GCM_Decrypt_process(data); - const result2 = this.AES_GCM_Decrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - AES_GCM_encrypt(data) { - const result1 = this.AES_GCM_Encrypt_process(data); - const result2 = this.AES_GCM_Encrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - _gcm_mac_process(data) { - let { asm, heap } = this.aes.acquire_asm(); - let dpos = 0; - let dlen = data.length || 0; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, 0, data, dpos, dlen); - dpos += wlen; - dlen -= wlen; - while (wlen & 15) - heap[wlen++] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$4 = util.getWebCrypto(); -const nodeCrypto$4 = util.getNodeCrypto(); -const Buffer$2 = util.getNodeBuffer(); - -const blockLength$3 = 16; -const ivLength$2 = 12; // size of the IV in bytes -const tagLength$2 = 16; // size of the tag in bytes -const ALGO = 'AES-GCM'; - -/** - * Class to en/decrypt using GCM mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function GCM(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('GCM mode supports only AES cipher'); - } - - if (util.getNodeCrypto()) { // Node crypto library - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - en.setAAD(adata); - const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - de.setAAD(adata); - de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext - const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]); - return new Uint8Array(pt); - } - }; - } - - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); - - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.encrypt(pt, key, iv, adata); - } - const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt); - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.decrypt(ct, key, iv, adata); - } - const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct); - return new Uint8Array(pt); - } - }; - } - - return { - encrypt: async function(pt, iv, adata) { - return AES_GCM.encrypt(pt, key, iv, adata); - }, - - decrypt: async function(ct, iv, adata) { - return AES_GCM.decrypt(ct, key, iv, adata); - } - }; -} - - -/** - * Get GCM nonce. Note: this operation is not defined by the standard. - * A future version of the standard may define GCM mode differently, - * hopefully under a different ID (we use Private/Experimental algorithm - * ID 100) so that we can maintain backwards compatibility. - * @param {Uint8Array} iv - The initialization vector (12 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -GCM.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[4 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -GCM.blockLength = blockLength$3; -GCM.ivLength = ivLength$2; -GCM.tagLength = tagLength$2; - -/** - * @fileoverview Cipher modes - * @module crypto/mode - * @private - */ - -var mode = { - /** @see module:crypto/mode/cfb */ - cfb: cfb, - /** @see module:crypto/mode/gcm */ - gcm: GCM, - experimentalGCM: GCM, - /** @see module:crypto/mode/eax */ - eax: EAX, - /** @see module:crypto/mode/ocb */ - ocb: OCB -}; - -var naclFastLight = createCommonjsModule(function (module) { -/*jshint bitwise: false*/ - -(function(nacl) { - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d; - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d, h, r; - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - r = nacl.hash(sm.subarray(32, smlen)); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - h = nacl.hash(sm.subarray(0, smlen)); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i; - var t = new Uint8Array(32), h; - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - h = nacl.hash(m.subarray(0, n)); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - return n; -} - -var crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32; - -function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError('unexpected type, use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.box = {}; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof commonjsRequire !== 'undefined') { - // Node.js. - crypto = crypto__default['default']; - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(module.exports ? module.exports : (self.nacl = self.nacl || {})); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const nodeCrypto$5 = util.getNodeCrypto(); - -/** - * Retrieve secure random byte array of the specified length - * @param {Integer} length - Length in bytes to generate - * @returns {Uint8Array} Random byte array. - */ -function getRandomBytes(length) { - const buf = new Uint8Array(length); - if (nodeCrypto$5) { - const bytes = nodeCrypto$5.randomBytes(buf.length); - buf.set(bytes); - } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - crypto.getRandomValues(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; -} - -/** - * Create a secure random BigInteger that is greater than or equal to min and less than max. - * @param {module:BigInteger} min - Lower bound, included - * @param {module:BigInteger} max - Upper bound, excluded - * @returns {Promise} Random BigInteger. - * @async - */ -async function getRandomBigInteger(min, max) { - const BigInteger = await util.getBigInteger(); - - if (max.lt(min)) { - throw new Error('Illegal parameter value: max <= min'); - } - - const modulus = max.sub(min); - const bytes = modulus.byteLength(); - - // Using a while loop is necessary to avoid bias introduced by the mod operation. - // However, we request 64 extra random bits so that the bias is negligible. - // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - const r = new BigInteger(await getRandomBytes(bytes + 8)); - return r.mod(modulus).add(min); -} - -var random = /*#__PURE__*/Object.freeze({ - __proto__: null, - getRandomBytes: getRandomBytes, - getRandomBigInteger: getRandomBigInteger -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Generate a probably prime random number - * @param {Integer} bits - Bit length of the prime - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns BigInteger - * @async - */ -async function randomProbablePrime(bits, e, k) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - const min = one.leftShift(new BigInteger(bits - 1)); - const thirty = new BigInteger(30); - /* - * We can avoid any multiples of 3 and 5 by looking at n mod 30 - * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 - * the next possible prime is mod 30: - * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 - */ - const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; - - const n = await getRandomBigInteger(min, min.leftShift(one)); - let i = n.mod(thirty).toNumber(); - - do { - n.iadd(new BigInteger(adds[i])); - i = (i + adds[i]) % adds.length; - // If reached the maximum, go back to the minimum. - if (n.bitLength() > bits) { - n.imod(min.leftShift(one)).iadd(min); - i = n.mod(thirty).toNumber(); - } - } while (!await isProbablePrime(n, e, k)); - return n; -} - -/** - * Probabilistic primality testing - * @param {BigInteger} n - Number to test - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns {boolean} - * @async - */ -async function isProbablePrime(n, e, k) { - if (e && !n.dec().gcd(e).isOne()) { - return false; - } - if (!await divisionTest(n)) { - return false; - } - if (!await fermat(n)) { - return false; - } - if (!await millerRabin(n, k)) { - return false; - } - // TODO implement the Lucas test - // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - return true; -} - -/** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n != 1. - * @param {BigInteger} n - Number to test - * @param {BigInteger} b - Optional Fermat test base - * @returns {boolean} - */ -async function fermat(n, b) { - const BigInteger = await util.getBigInteger(); - b = b || new BigInteger(2); - return b.modExp(n.dec(), n).isOne(); -} - -async function divisionTest(n) { - const BigInteger = await util.getBigInteger(); - return smallPrimes.every(m => { - return n.mod(new BigInteger(m)) !== 0; - }); -} - -// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c -const smallPrimes = [ - 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, - 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, - 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, - 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, - 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, - 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, - 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, - 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, - 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, - 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, - 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, - 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, - 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, - 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, - 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, - 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, - 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, - 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, - 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, - 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, - 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, - 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, - 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, - 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, - 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, - 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, - 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, - 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, - 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, - 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, - 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, - 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, - 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, - 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, - 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, - 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, - 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, - 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, - 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, - 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, - 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, - 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, - 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, - 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, - 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, - 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, - 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, - 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, - 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, - 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, - 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, - 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, - 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, - 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, - 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, - 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, - 4957, 4967, 4969, 4973, 4987, 4993, 4999 -]; - - -// Miller-Rabin - Miller Rabin algorithm for primality test -// Copyright Fedor Indutny, 2014. -// -// This software is licensed under the MIT License. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin - -// Sample syntax for Fixed-Base Miller-Rabin: -// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) - -/** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param {BigInteger} n - Number to test - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @param {Function} rand - Optional function to generate potential witnesses - * @returns {boolean} - * @async - */ -async function millerRabin(n, k, rand) { - const BigInteger = await util.getBigInteger(); - const len = n.bitLength(); - - if (!k) { - k = Math.max(1, (len / 48) | 0); - } - - const n1 = n.dec(); // n - 1 - - // Find d and s, (n - 1) = (2 ^ s) * d; - let s = 0; - while (!n1.getBit(s)) { s++; } - const d = n.rightShift(new BigInteger(s)); - - for (; k > 0; k--) { - const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1); - - let x = a.modExp(d, n); - if (x.isOne() || x.equal(n1)) { - continue; - } - - let i; - for (i = 1; i < s; i++) { - x = x.mul(x).mod(n); - - if (x.isOne()) { - return false; - } - if (x.equal(n1)) { - break; - } - } - - if (i === s) { - return false; - } - } - - return true; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ASN1 object identifiers for hashes - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} - */ -const hash_headers = []; -hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; -hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; -hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; -hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; -hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; -hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; -hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; - -/** - * Create padding with secure random data - * @private - * @param {Integer} length - Length of the padding in bytes - * @returns {Uint8Array} Random padding. - */ -function getPKCS1Padding(length) { - const result = new Uint8Array(length); - let count = 0; - while (count < length) { - const randomBytes = getRandomBytes(length - count); - for (let i = 0; i < randomBytes.length; i++) { - if (randomBytes[i] !== 0) { - result[count++] = randomBytes[i]; - } - } - } - return result; -} - -/** - * Create a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} - * @param {Uint8Array} message - Message to be encoded - * @param {Integer} keyLength - The length in octets of the key modulus - * @returns {Uint8Array} EME-PKCS1 padded message. - */ -function emeEncode(message, keyLength) { - const mLength = message.length; - // length checking - if (mLength > keyLength - 11) { - throw new Error('Message too long'); - } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - const PS = getPKCS1Padding(keyLength - mLength - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - const encoded = new Uint8Array(keyLength); - // 0x00 byte - encoded[1] = 2; - encoded.set(PS, 2); - // 0x00 bytes - encoded.set(message, keyLength - mLength); - return encoded; -} - -/** - * Decode a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} - * @param {Uint8Array} encoded - Encoded message bytes - * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) - * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) - * @throws {Error} on decoding failure, unless `randomPayload` is provided - */ -function emeDecode(encoded, randomPayload) { - // encoded format: 0x00 0x02 0x00 - let offset = 2; - let separatorNotFound = 1; - for (let j = offset; j < encoded.length; j++) { - separatorNotFound &= encoded[j] !== 0; - offset += separatorNotFound; - } - - const psLen = offset - 2; - const payload = encoded.subarray(offset + 1); // discard the 0x00 separator - const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - - if (randomPayload) { - return util.selectUint8Array(isValidPadding, payload, randomPayload); - } - - if (isValidPadding) { - return payload; - } - - throw new Error('Decryption error'); -} - -/** - * Create a EMSA-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} - * @param {Integer} algo - Hash algorithm type used - * @param {Uint8Array} hashed - Message to be encoded - * @param {Integer} emLen - Intended length in octets of the encoded message - * @returns {Uint8Array} Encoded message. - */ -async function emsaEncode(algo, hashed, emLen) { - let i; - if (hashed.length !== hash.getHashByteLength(algo)) { - throw new Error('Invalid hash length'); - } - // produce an ASN.1 DER value for the hash function used. - // Let T be the full hash prefix - const hashPrefix = new Uint8Array(hash_headers[algo].length); - for (i = 0; i < hash_headers[algo].length; i++) { - hashPrefix[i] = hash_headers[algo][i]; - } - // and let tLen be the length in octets prefix and hashed data - const tLen = hashPrefix.length + hashed.length; - if (emLen < tLen + 11) { - throw new Error('Intended encoded message length too short'); - } - // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF - // The length of PS will be at least 8 octets - const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - - // Concatenate PS, the hash prefix, hashed data, and other padding to form the - // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed - const EM = new Uint8Array(emLen); - EM[1] = 0x01; - EM.set(PS, 2); - EM.set(hashPrefix, emLen - tLen); - EM.set(hashed, emLen - hashed.length); - return EM; -} - -var pkcs1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - emeEncode: emeEncode, - emeDecode: emeDecode, - emsaEncode: emsaEncode -}); - -const webCrypto$5 = util.getWebCrypto(); -const nodeCrypto$6 = util.getNodeCrypto(); -const asn1 = nodeCrypto$6 ? asn1__default['default'] : undefined; - -/* eslint-disable no-invalid-this */ -const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('version').int(), // 0 - this.key('modulus').int(), // n - this.key('publicExponent').int(), // e - this.key('privateExponent').int(), // d - this.key('prime1').int(), // p - this.key('prime2').int(), // q - this.key('exponent1').int(), // dp - this.key('exponent2').int(), // dq - this.key('coefficient').int() // u - ); -}) : undefined; - -const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('modulus').int(), // n - this.key('publicExponent').int() // e - ); -}) : undefined; -/* eslint-enable no-invalid-this */ - -/** Create signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} hashed - Hashed message - * @returns {Promise} RSA Signature. - * @async - */ -async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeSign(hashAlgo, data, n, e, d, p, q, u); - } - } - return bnSign(hashAlgo, n, d, hashed); -} - -/** - * Verify signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} s - Signature - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} hashed - Hashed message - * @returns {Boolean} - * @async - */ -async function verify(hashAlgo, data, s, n, e, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeVerify(hashAlgo, data, s, n, e); - } - } - return bnVerify(hashAlgo, s, n, e, hashed); -} - -/** - * Encrypt message - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @returns {Promise} RSA Ciphertext. - * @async - */ -async function encrypt$1(data, n, e) { - if (util.getNodeCrypto()) { - return nodeEncrypt$1(data, n, e); - } - return bnEncrypt(data, n, e); -} - -/** - * Decrypt RSA message - * @param {Uint8Array} m - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} RSA Plaintext. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$1(data, n, e, d, p, q, u, randomPayload) { - // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, - // and we want to avoid checking the error type to decide if the random payload - // should indeed be returned. - if (util.getNodeCrypto() && !randomPayload) { - try { - return await nodeDecrypt$1(data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } - return bnDecrypt(data, n, e, d, p, q, u, randomPayload); -} - -/** - * Generate a new random private key B bits long with public exponent E. - * - * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param {Integer} bits - RSA bit length - * @param {Integer} e - RSA public exponent - * @returns {{n, e, d, - * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = p ** -1 mod q - * @async - */ -async function generate(bits, e) { - const BigInteger = await util.getBigInteger(); - - e = new BigInteger(e); - - // Native RSA keygen using Web Crypto - if (util.getWebCrypto()) { - const keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, // the specified keysize in bits - publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); - // map JWK parameters to corresponding OpenPGP names - return { - n: b64ToUint8Array(jwk.n), - e: e.toUint8Array(), - d: b64ToUint8Array(jwk.d), - // switch p and q - p: b64ToUint8Array(jwk.q), - q: b64ToUint8Array(jwk.p), - // Since p and q are switched in places, u is the inverse of jwk.q - u: b64ToUint8Array(jwk.qi) - }; - } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) { - const opts = { - modulusLength: bits, - publicExponent: e.toNumber(), - publicKeyEncoding: { type: 'pkcs1', format: 'der' }, - privateKeyEncoding: { type: 'pkcs1', format: 'der' } - }; - const prv = await new Promise((resolve, reject) => { - nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => { - if (err) { - reject(err); - } else { - resolve(RSAPrivateKey.decode(der, 'der')); - } - }); - }); - /** - * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`. - * @link https://tools.ietf.org/html/rfc3447#section-3.2 - * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1 - */ - return { - n: prv.modulus.toArrayLike(Uint8Array), - e: prv.publicExponent.toArrayLike(Uint8Array), - d: prv.privateExponent.toArrayLike(Uint8Array), - // switch p and q - p: prv.prime2.toArrayLike(Uint8Array), - q: prv.prime1.toArrayLike(Uint8Array), - // Since p and q are switched in places, we can keep u as defined by DER - u: prv.coefficient.toArrayLike(Uint8Array) - }; - } - - // RSA keygen fallback using 40 iterations of the Miller-Rabin test - // See https://stackoverflow.com/a/6330138 for justification - // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST - let p; - let q; - let n; - do { - q = await randomProbablePrime(bits - (bits >> 1), e, 40); - p = await randomProbablePrime(bits >> 1, e, 40); - n = p.mul(q); - } while (n.bitLength() !== bits); - - const phi = p.dec().imul(q.dec()); - - if (q.lt(p)) { - [p, q] = [q, p]; - } - - return { - n: n.toUint8Array(), - e: e.toUint8Array(), - d: e.modInv(phi).toUint8Array(), - p: p.toUint8Array(), - q: q.toUint8Array(), - // dp: d.mod(p.subn(1)), - // dq: d.mod(q.subn(1)), - u: p.modInv(q).toUint8Array() - }; -} - -/** - * Validate RSA parameters - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA inverse of p w.r.t. q - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - p = new BigInteger(p); - q = new BigInteger(q); - - // expect pq = n - if (!p.mul(q).equal(n)) { - return false; - } - - const two = new BigInteger(2); - // expect p*u = 1 mod q - u = new BigInteger(u); - if (!p.mul(u).mod(q).isOne()) { - return false; - } - - e = new BigInteger(e); - d = new BigInteger(d); - /** - * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) - * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] - * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] - * - * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) - */ - const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3)); - const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q - const rde = r.mul(d).mul(e); - - const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r); - if (!areInverses) { - return false; - } - - return true; -} - -async function bnSign(hashAlgo, n, d, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); - d = new BigInteger(d); - if (m.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return m.modExp(d, n).toUint8Array('be', n.byteLength()); -} - -async function webSign(hashName, data, n, e, d, p, q, u) { - /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJWK, so it usually works out, but nevertheless, - * not all OpenPGP keys are compatible with this requirement. - * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still - * does if the underlying Web Crypto does so (though the tested implementations - * don't do so). - */ - const jwk = await privateToJWK(n, e, d, p, q, u); - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }; - const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); - return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); -} - -async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(data); - sign.end(); - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPrivateKey.encode(keyObject, 'der'); - return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' })); - } - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - return new Uint8Array(sign.sign(pem)); -} - -async function bnVerify(hashAlgo, s, n, e, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - s = new BigInteger(s); - e = new BigInteger(e); - if (s.gte(n)) { - throw new Error('Signature size cannot exceed modulus size'); - } - const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); - return util.equalsUint8Array(EM1, EM2); -} - -async function webVerify(hashName, data, s, n, e) { - const jwk = publicToJWK(n, e); - const key = await webCrypto$5.importKey('jwk', jwk, { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }, false, ['verify']); - return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); -} - -async function nodeVerify(hashAlgo, data, s, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(data); - verify.end(); - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1' }; - } else { - key = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - } - try { - return await verify.verify(key, s); - } catch (err) { - return false; - } -} - -async function nodeEncrypt$1(data, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data)); -} - -async function bnEncrypt(data, n, e) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - data = new BigInteger(emeEncode(data, n.byteLength())); - e = new BigInteger(e); - if (data.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return data.modExp(e, n).toUint8Array('be', n.byteLength()); -} - -async function nodeDecrypt$1(data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPrivateKey.encode(keyObject, 'der'); - key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - try { - return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data)); - } catch (err) { - throw new Error('Decryption error'); - } -} - -async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { - const BigInteger = await util.getBigInteger(); - data = new BigInteger(data); - n = new BigInteger(n); - e = new BigInteger(e); - d = new BigInteger(d); - p = new BigInteger(p); - q = new BigInteger(q); - u = new BigInteger(u); - if (data.gte(n)) { - throw new Error('Data too large.'); - } - const dq = d.mod(q.dec()); // d mod (q-1) - const dp = d.mod(p.dec()); // d mod (p-1) - - const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n); - const blinder = unblinder.modInv(n).modExp(e, n); - data = data.mul(blinder).mod(n); - - - const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p - const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q - const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q) - - let result = h.mul(p).add(mp); // result < n due to relations above - - result = result.mul(unblinder).mod(n); - - - return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload); -} - -/** Convert Openpgp private key params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - * @param {Uint8Array} d - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} u - */ -async function privateToJWK(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - const pNum = new BigInteger(p); - const qNum = new BigInteger(q); - const dNum = new BigInteger(d); - - let dq = dNum.mod(qNum.dec()); // d mod (q-1) - let dp = dNum.mod(pNum.dec()); // d mod (p-1) - dp = dp.toUint8Array(); - dq = dq.toUint8Array(); - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - d: uint8ArrayToB64(d, true), - // switch p and q - p: uint8ArrayToB64(q, true), - q: uint8ArrayToB64(p, true), - // switch dp and dq - dp: uint8ArrayToB64(dq, true), - dq: uint8ArrayToB64(dp, true), - qi: uint8ArrayToB64(u, true), - ext: true - }; -} - -/** Convert Openpgp key public params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - */ -function publicToJWK(n, e) { - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - ext: true - }; -} - -var rsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign, - verify: verify, - encrypt: encrypt$1, - decrypt: decrypt$1, - generate: generate, - validateParams: validateParams -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ElGamal Encryption function - * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) - * @param {Uint8Array} data - To be padded and encrypted - * @param {Uint8Array} p - * @param {Uint8Array} g - * @param {Uint8Array} y - * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} - * @async - */ -async function encrypt$2(data, p, g, y) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const padded = emeEncode(data, p.byteLength()); - const m = new BigInteger(padded); - - // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* - // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] - const k = await getRandomBigInteger(new BigInteger(1), p.dec()); - return { - c1: g.modExp(k, p).toUint8Array(), - c2: y.modExp(k, p).imul(m).imod(p).toUint8Array() - }; -} - -/** - * ElGamal Encryption function - * @param {Uint8Array} c1 - * @param {Uint8Array} c2 - * @param {Uint8Array} p - * @param {Uint8Array} x - * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} Unpadded message. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$2(c1, c2, p, x, randomPayload) { - const BigInteger = await util.getBigInteger(); - c1 = new BigInteger(c1); - c2 = new BigInteger(c2); - p = new BigInteger(p); - x = new BigInteger(x); - - const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p); - return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload); -} - -/** - * Validate ElGamal parameters - * @param {Uint8Array} p - ElGamal prime - * @param {Uint8Array} g - ElGamal group generator - * @param {Uint8Array} y - ElGamal public key - * @param {Uint8Array} x - ElGamal private exponent - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$1(p, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - // Expect p-1 to be large - const pSize = new BigInteger(p.bitLength()); - const n1023 = new BigInteger(1023); - if (pSize.lt(n1023)) { - return false; - } - - /** - * g should have order p-1 - * Check that g ** (p-1) = 1 mod p - */ - if (!g.modExp(p.dec(), p).isOne()) { - return false; - } - - /** - * Since p-1 is not prime, g might have a smaller order that divides p-1 - * We want to make sure that the order is large enough to hinder a small subgroup attack - * - * We just check g**i != 1 for all i up to a threshold - */ - let res = g; - const i = new BigInteger(1); - const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold - while (i.lt(threshold)) { - res = res.mul(g).imod(p); - if (res.isOne()) { - return false; - } - i.iinc(); - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{r(p-1) + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1 - const rqx = p.dec().imul(r).iadd(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var elgamal = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt$2, - decrypt: decrypt$2, - validateParams: validateParams$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class OID { - constructor(oid) { - if (oid instanceof OID) { - this.oid = oid.oid; - } else if (util.isArray(oid) || - util.isUint8Array(oid)) { - oid = new Uint8Array(oid); - if (oid[0] === 0x06) { // DER encoded oid byte array - if (oid[1] !== oid.length - 2) { - throw new Error('Length mismatch in DER encoded oid'); - } - oid = oid.subarray(2); - } - this.oid = oid; - } else { - this.oid = ''; - } - } - - /** - * Method to read an OID object - * @param {Uint8Array} input - Where to read the OID from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length >= 1) { - const length = input[0]; - if (input.length >= 1 + length) { - this.oid = input.subarray(1, 1 + length); - return 1 + this.oid.length; - } - } - throw new Error('Invalid oid'); - } - - /** - * Serialize an OID object - * @returns {Uint8Array} Array with the serialized value the OID. - */ - write() { - return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); - } - - /** - * Serialize an OID object as a hex string - * @returns {string} String with the hex value of the OID. - */ - toHex() { - return util.uint8ArrayToHex(this.oid); - } - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns {string} String with the canonical name of the curve. - */ - getName() { - const hex = this.toHex(); - if (enums.curve[hex]) { - return enums.write(enums.curve, hex); - } else { - throw new Error('Unknown curve object identifier.'); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -function keyFromPrivate(indutnyCurve, priv) { - const keyPair = indutnyCurve.keyPair({ priv: priv }); - return keyPair; -} - -function keyFromPublic(indutnyCurve, pub) { - const keyPair = indutnyCurve.keyPair({ pub: pub }); - if (keyPair.validate().result !== true) { - throw new Error('Invalid elliptic public key'); - } - return keyPair; -} - -async function getIndutnyCurve(name) { - if (!config.useIndutnyElliptic) { - throw new Error('This curve is only supported in the full build of OpenPGP.js'); - } - const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; }); - return new elliptic.ec(name); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -function readSimpleLength(bytes) { - let len = 0; - let offset; - const type = bytes[0]; - - - if (type < 192) { - [len] = bytes; - offset = 1; - } else if (type < 255) { - len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; - offset = 2; - } else if (type === 255) { - len = util.readNumber(bytes.subarray(1, 1 + 4)); - offset = 5; - } - - return { - len: len, - offset: offset - }; -} - -/** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * - * @param {Integer} length - The length to encode - * @returns {Uint8Array} String with openpgp length representation. - */ -function writeSimpleLength(length) { - if (length < 192) { - return new Uint8Array([length]); - } else if (length > 191 && length < 8384) { - /* - * let a = (total data packet length) - 192 let bc = two octet - * representation of a let d = b + 192 - */ - return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); -} - -function writePartialLength(power) { - if (power < 0 || power > 30) { - throw new Error('Partial Length power must be between 1 and 30'); - } - return new Uint8Array([224 + power]); -} - -function writeTag(tag_type) { - /* we're only generating v4 packet headers here */ - return new Uint8Array([0xC0 | tag_type]); -} - -/** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * - * @param {Integer} tag_type - Tag type - * @param {Integer} length - Length of the payload - * @returns {String} String of the header. - */ -function writeHeader(tag_type, length) { - /* we're only generating v4 packet headers here */ - return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); -} - -/** - * Whether the packet type supports partial lengths per RFC4880 - * @param {Integer} tag - Tag type - * @returns {Boolean} String of the header. - */ -function supportsStreaming(tag) { - return [ - enums.packet.literalData, - enums.packet.compressedData, - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ].includes(tag); -} - -/** - * Generic static Packet Parser function - * - * @param {Uint8Array | ReadableStream} input - Input stream as string - * @param {Function} callback - Function to call with the parsed packet - * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. - */ -async function readPackets(input, callback) { - const reader = getReader(input); - let writer; - let callbackReturned; - try { - const peekedBytes = await reader.peekBytes(2); - // some sanity checks - if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { - throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); - } - const headerByte = await reader.readByte(); - let tag = -1; - let format = -1; - let packetLength; - - format = 0; // 0 = old format; 1 = new format - if ((headerByte & 0x40) !== 0) { - format = 1; - } - - let packetLengthType; - if (format) { - // new format header - tag = headerByte & 0x3F; // bit 5-0 - } else { - // old format header - tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packetLengthType = headerByte & 0x03; // bit 1-0 - } - - const packetSupportsStreaming = supportsStreaming(tag); - let packet = null; - if (packetSupportsStreaming) { - if (util.isStream(input) === 'array') { - const arrayStream = new ArrayStream(); - writer = getWriter(arrayStream); - packet = arrayStream; - } else { - const transform = new TransformStream(); - writer = getWriter(transform.writable); - packet = transform.readable; - } - // eslint-disable-next-line callback-return - callbackReturned = callback({ tag, packet }); - } else { - packet = []; - } - - let wasPartialLength; - do { - if (!format) { - // 4.2.1. Old Format Packet Lengths - switch (packetLengthType) { - case 0: - // The packet has a one-octet length. The header is 2 octets - // long. - packetLength = await reader.readByte(); - break; - case 1: - // The packet has a two-octet length. The header is 3 octets - // long. - packetLength = (await reader.readByte() << 8) | await reader.readByte(); - break; - case 2: - // The packet has a four-octet length. The header is 5 - // octets long. - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - break; - default: - // 3 - The packet is of indeterminate length. The header is 1 - // octet long, and the implementation must determine how long - // the packet is. If the packet is in a file, this means that - // the packet extends until the end of the file. In general, - // an implementation SHOULD NOT use indeterminate-length - // packets except where the end of the data will be clear - // from the context, and even then it is better to use a - // definite length, or a new format header. The new format - // headers described below have a mechanism for precisely - // encoding data of indeterminate length. - packetLength = Infinity; - break; - } - } else { // 4.2.2. New Format Packet Lengths - // 4.2.2.1. One-Octet Lengths - const lengthByte = await reader.readByte(); - wasPartialLength = false; - if (lengthByte < 192) { - packetLength = lengthByte; - // 4.2.2.2. Two-Octet Lengths - } else if (lengthByte >= 192 && lengthByte < 224) { - packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; - // 4.2.2.4. Partial Body Lengths - } else if (lengthByte > 223 && lengthByte < 255) { - packetLength = 1 << (lengthByte & 0x1F); - wasPartialLength = true; - if (!packetSupportsStreaming) { - throw new TypeError('This packet type does not support partial lengths.'); - } - // 4.2.2.3. Five-Octet Lengths - } else { - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - } - } - if (packetLength > 0) { - let bytesRead = 0; - while (true) { - if (writer) await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (packetLength === Infinity) break; - throw new Error('Unexpected end of packet'); - } - const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); - if (writer) await writer.write(chunk); - else packet.push(chunk); - bytesRead += value.length; - if (bytesRead >= packetLength) { - reader.unshift(value.subarray(packetLength - bytesRead + value.length)); - break; - } - } - } - } while (wasPartialLength); - - // If this was not a packet that "supports streaming", we peek to check - // whether it is the last packet in the message. We peek 2 bytes instead - // of 1 because the beginning of this function also peeks 2 bytes, and we - // want to cut a `subarray` of the correct length into `web-stream-tools`' - // `externalBuffer` as a tiny optimization here. - // - // If it *was* a streaming packet (i.e. the data packets), we peek at the - // entire remainder of the stream, in order to forward errors in the - // remainder of the stream to the packet data. (Note that this means we - // read/peek at all signature packets before closing the literal data - // packet, for example.) This forwards MDC errors to the literal data - // stream, for example, so that they don't get lost / forgotten on - // decryptedMessage.packets.stream, which we never look at. - // - // An example of what we do when stream-parsing a message containing - // [ one-pass signature packet, literal data packet, signature packet ]: - // 1. Read the one-pass signature packet - // 2. Peek 2 bytes of the literal data packet - // 3. Parse the one-pass signature packet - // - // 4. Read the literal data packet, simultaneously stream-parsing it - // 5. Peek until the end of the message - // 6. Finish parsing the literal data packet - // - // 7. Read the signature packet again (we already peeked at it in step 5) - // 8. Peek at the end of the stream again (`peekBytes` returns undefined) - // 9. Parse the signature packet - // - // Note that this means that if there's an error in the very end of the - // stream, such as an MDC error, we throw in step 5 instead of in step 8 - // (or never), which is the point of this exercise. - const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); - if (writer) { - await writer.ready; - await writer.close(); - } else { - packet = util.concatUint8Array(packet); - // eslint-disable-next-line callback-return - await callback({ tag, packet }); - } - return !nextPacket || !nextPacket.length; - } catch (e) { - if (writer) { - await writer.abort(e); - return true; - } else { - throw e; - } - } finally { - if (writer) { - await callbackReturned; - } - reader.releaseLock(); - } -} - -class UnsupportedError extends Error { - constructor(...params) { - super(...params); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, UnsupportedError); - } - - this.name = 'UnsupportedError'; - } -} - -class UnparseablePacket { - constructor(tag, rawContent) { - this.tag = tag; - this.rawContent = rawContent; - } - - write() { - return this.rawContent; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$6 = util.getWebCrypto(); -const nodeCrypto$7 = util.getNodeCrypto(); - -const webCurves = { - 'p256': 'P-256', - 'p384': 'P-384', - 'p521': 'P-521' -}; -const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : []; -const nodeCurves = nodeCrypto$7 ? { - secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, - p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, - p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, - p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, - ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined, - curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined, - brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, - brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, - brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined -} : {}; - -const curves = { - p256: { - oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.p256, - web: webCurves.p256, - payloadSize: 32, - sharedSize: 256 - }, - p384: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.p384, - web: webCurves.p384, - payloadSize: 48, - sharedSize: 384 - }, - p521: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.p521, - web: webCurves.p521, - payloadSize: 66, - sharedSize: 528 - }, - secp256k1: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1, - payloadSize: 32 - }, - ed25519: { - oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], - keyType: enums.publicKey.eddsaLegacy, - hash: enums.hash.sha512, - node: false, // nodeCurves.ed25519 TODO - payloadSize: 32 - }, - curve25519: { - oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], - keyType: enums.publicKey.ecdh, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: false, // nodeCurves.curve25519 TODO - payloadSize: 32 - }, - brainpoolP256r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1, - payloadSize: 32 - }, - brainpoolP384r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1, - payloadSize: 48 - }, - brainpoolP512r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1, - payloadSize: 64 - } -}; - -class CurveWithOID { - constructor(oidOrName, params) { - try { - if (util.isArray(oidOrName) || - util.isUint8Array(oidOrName)) { - // by oid byte array - oidOrName = new OID(oidOrName); - } - if (oidOrName instanceof OID) { - // by curve OID - oidOrName = oidOrName.getName(); - } - // by curve name or oid string - this.name = enums.write(enums.curve, oidOrName); - } catch (err) { - throw new UnsupportedError('Unknown curve'); - } - params = params || curves[this.name]; - - this.keyType = params.keyType; - - this.oid = params.oid; - this.hash = params.hash; - this.cipher = params.cipher; - this.node = params.node && curves[this.name]; - this.web = params.web && curves[this.name]; - this.payloadSize = params.payloadSize; - if (this.web && util.getWebCrypto()) { - this.type = 'web'; - } else if (this.node && util.getNodeCrypto()) { - this.type = 'node'; - } else if (this.name === 'curve25519') { - this.type = 'curve25519'; - } else if (this.name === 'ed25519') { - this.type = 'ed25519'; - } - } - - async genKeyPair() { - let keyPair; - switch (this.type) { - case 'web': - try { - return await webGenKeyPair(this.name); - } catch (err) { - util.printDebugError('Browser did not support generating ec key ' + err.message); - break; - } - case 'node': - return nodeGenKeyPair(this.name); - case 'curve25519': { - const privateKey = getRandomBytes(32); - privateKey[0] = (privateKey[0] & 127) | 64; - privateKey[31] &= 248; - const secretKey = privateKey.slice().reverse(); - keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - case 'ed25519': { - const privateKey = getRandomBytes(32); - const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - } - const indutnyCurve = await getIndutnyCurve(this.name); - keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToString(getRandomBytes(32)) - }); - return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; - } -} - -async function generate$1(curve) { - const BigInteger = await util.getBigInteger(); - - curve = new CurveWithOID(curve); - const keyPair = await curve.genKeyPair(); - const Q = new BigInteger(keyPair.publicKey).toUint8Array(); - const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize); - return { - oid: curve.oid, - Q, - secret, - hash: curve.hash, - cipher: curve.cipher - }; -} - -/** - * Get preferred hash algo to use with the given curve - * @param {module:type/oid} oid - curve oid - * @returns {enums.hash} hash algorithm - */ -function getPreferredHashAlgo(oid) { - return curves[enums.write(enums.curve, oid.toHex())].hash; -} - -/** - * Validate ECDH and ECDSA parameters - * Not suitable for EdDSA (different secret key format) - * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves - * @param {module:type/oid} oid - EC object identifier - * @param {Uint8Array} Q - EC public point - * @param {Uint8Array} d - EC secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateStandardParams(algo, oid, Q, d) { - const supportedCurves = { - p256: true, - p384: true, - p521: true, - secp256k1: true, - curve25519: algo === enums.publicKey.ecdh, - brainpoolP256r1: true, - brainpoolP384r1: true, - brainpoolP512r1: true - }; - - // Check whether the given curve is supported - const curveName = oid.getName(); - if (!supportedCurves[curveName]) { - return false; - } - - if (curveName === 'curve25519') { - d = d.slice().reverse(); - // Re-derive public point Q' - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d); - - Q = new Uint8Array(Q); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - if (!util.equalsUint8Array(dG, Q)) { - return false; - } - - return true; - } - - const curve = await getIndutnyCurve(curveName); - try { - // Parse Q and check that it is on the curve but not at infinity - Q = keyFromPublic(curve, Q).getPublic(); - } catch (validationErrors) { - return false; - } - - /** - * Re-derive public point Q' = dG from private key - * Expect Q == Q' - */ - const dG = keyFromPrivate(curve, d).getPublic(); - if (!dG.eq(Q)) { - return false; - } - - return true; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -async function webGenKeyPair(name) { - // Note: keys generated with ECDSA and ECDH are structurally equivalent - const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - - const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey); - const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey); - - return { - publicKey: jwkToRawPublic(publicKey), - privateKey: b64ToUint8Array(privateKey.d) - }; -} - -async function nodeGenKeyPair(name) { - // Note: ECDSA and ECDH key generation is structurally equivalent - const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]); - await ecdh.generateKeys(); - return { - publicKey: new Uint8Array(ecdh.getPublicKey()), - privateKey: new Uint8Array(ecdh.getPrivateKey()) - }; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -/** - * @param {JsonWebKey} jwk - key for conversion - * - * @returns {Uint8Array} Raw public key. - */ -function jwkToRawPublic(jwk) { - const bufX = b64ToUint8Array(jwk.x); - const bufY = b64ToUint8Array(jwk.y); - const publicKey = new Uint8Array(bufX.length + bufY.length + 1); - publicKey[0] = 0x04; - publicKey.set(bufX, 1); - publicKey.set(bufY, bufX.length + 1); - return publicKey; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * - * @returns {JsonWebKey} Public key in jwk format. - */ -function rawPublicToJWK(payloadSize, name, publicKey) { - const len = payloadSize; - const bufX = publicKey.slice(1, len + 1); - const bufY = publicKey.slice(len + 1, len * 2 + 1); - // https://www.rfc-editor.org/rfc/rfc7518.txt - const jwk = { - kty: 'EC', - crv: name, - x: uint8ArrayToB64(bufX, true), - y: uint8ArrayToB64(bufY, true), - ext: true - }; - return jwk; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * @param {Uint8Array} privateKey - private key - * - * @returns {JsonWebKey} Private key in jwk format. - */ -function privateToJWK$1(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJWK(payloadSize, name, publicKey); - jwk.d = uint8ArrayToB64(privateKey, true); - return jwk; -} - -const webCrypto$7 = util.getWebCrypto(); -const nodeCrypto$8 = util.getNodeCrypto(); - -/** - * Sign a message using the provided key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - const keyPair = { publicKey, privateKey }; - switch (curve.type) { - case 'web': { - // If browser doesn't support a curve, we'll catch it - try { - // Need to await to make sure browser succeeds - return await webSign$1(curve, hashAlgo, message, keyPair); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunaley Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support signing: ' + err.message); - } - break; - } - case 'node': { - const signature = await nodeSign$1(curve, hashAlgo, message, keyPair); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - } - } - return ellipticSign(curve, hashed, privateKey); -} - -/** - * Verifies if a signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify - * @param {Uint8Array} message - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - switch (curve.type) { - case 'web': - try { - // Need to await to make sure browser succeeds - return await webVerify$1(curve, hashAlgo, signature, message, publicKey); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunately Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support verifying: ' + err.message); - } - break; - case 'node': - return nodeVerify$1(curve, hashAlgo, signature, message, publicKey); - } - } - const digest = (typeof hashAlgo === 'undefined') ? message : hashed; - return ellipticVerify(curve, signature, digest, publicKey); -} - -/** - * Validate ECDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDSA public point - * @param {Uint8Array} d - ECDSA secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$2(oid, Q, d) { - const curve = new CurveWithOID(oid); - // Reject curves x25519 and ed25519 - if (curve.keyType !== enums.publicKey.ecdsa) { - return false; - } - - // To speed up the validation, we try to use node- or webcrypto when available - // and sign + verify a random message - switch (curve.type) { - case 'web': - case 'node': { - const message = getRandomBytes(8); - const hashAlgo = enums.hash.sha256; - const hashed = await hash.digest(hashAlgo, message); - try { - const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed); - return await verify$1(oid, hashAlgo, signature, message, Q, hashed); - } catch (err) { - return false; - } - } - default: - return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); - } -} - - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -async function ellipticSign(curve, hashed, privateKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPrivate(indutnyCurve, privateKey); - const signature = key.sign(hashed); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; -} - -async function ellipticVerify(curve, signature, digest, publicKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPublic(indutnyCurve, publicKey); - return key.verify(digest, signature); -} - -async function webSign$1(curve, hashAlgo, message, keyPair) { - const len = curve.payloadSize; - const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['sign'] - ); - - const signature = new Uint8Array(await webCrypto$7.sign( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - message - )); - - return { - r: signature.slice(0, len), - s: signature.slice(len, len << 1) - }; -} - -async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['verify'] - ); - - const signature = util.concatUint8Array([r, s]).buffer; - - return webCrypto$7.verify( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - signature, - message - ); -} - -async function nodeSign$1(curve, hashAlgo, message, keyPair) { - const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(message); - sign.end(); - const key = ECPrivateKey.encode({ - version: 1, - parameters: curve.oid, - privateKey: Array.from(keyPair.privateKey), - publicKey: { unused: 0, data: Array.from(keyPair.publicKey) } - }, 'pem', { - label: 'EC PRIVATE KEY' - }); - - return ECDSASignature.decode(sign.sign(key), 'der'); -} - -async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(message); - verify.end(); - const key = SubjectPublicKeyInfo.encode({ - algorithm: { - algorithm: [1, 2, 840, 10045, 2, 1], - parameters: curve.oid - }, - subjectPublicKey: { unused: 0, data: Array.from(publicKey) } - }, 'pem', { - label: 'PUBLIC KEY' - }); - const signature = ECDSASignature.encode({ - r: new BN(r), s: new BN(s) - }, 'der'); - - try { - return verify.verify(key, signature); - } catch (err) { - return false; - } -} - -// Originally written by Owen Smith https://github.com/omsmith -// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ - -/* eslint-disable no-invalid-this */ - -const asn1$1 = nodeCrypto$8 ? asn1__default['default'] : undefined; - -const ECDSASignature = nodeCrypto$8 ? - asn1$1.define('ECDSASignature', function() { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ); - }) : undefined; - -const ECPrivateKey = nodeCrypto$8 ? - asn1$1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().any(), - this.key('publicKey').explicit(1).optional().bitstr() - ); - }) : undefined; - -const AlgorithmIdentifier = nodeCrypto$8 ? - asn1$1.define('AlgorithmIdentifier', function() { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional().any() - ); - }) : undefined; - -const SubjectPublicKeyInfo = nodeCrypto$8 ? - asn1$1.define('SubjectPublicKeyInfo', function() { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ); - }) : undefined; - -var ecdsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$1, - verify: verify$1, - validateParams: validateParams$2 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Sign a message using the provided legacy EdDSA key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - // EdDSA signature params are returned in little-endian format - return { - r: signature.subarray(0, 32), - s: signature.subarray(32) - }; -} - -/** - * Verifies if a legacy EdDSA signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const signature = util.concatUint8Array([r, s]); - return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1)); -} -/** - * Validate legacy EdDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - EdDSA public point - * @param {Uint8Array} k - EdDSA secret seed - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$3(oid, Q, k) { - // Check whether the given curve is supported - if (oid.getName() !== 'ed25519') { - return false; - } - - /** - * Derive public point Q' = dG from private key - * and expect Q == Q' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - return util.equalsUint8Array(Q, dG); - -} - -var eddsa_legacy = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$2, - verify: verify$2, - validateParams: validateParams$3 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Generate (non-legacy) EdDSA key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} - */ -async function generate$2(algo) { - switch (algo) { - case enums.publicKey.ed25519: { - const seed = getRandomBytes(32); - const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed); - return { A, seed }; - } - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} - -/** - * Sign a message using the provided key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * RS: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - const secretKey = util.concatUint8Array([privateKey, publicKey]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - return { RS: signature }; - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - -} - -/** - * Verifies if a signature is valid for a message - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{ RS: Uint8Array }} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - return naclFastLight.sign.detached.verify(hashed, RS, publicKey); - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} -/** - * Validate (non-legacy) EdDSA parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - EdDSA public point - * @param {Uint8Array} seed - EdDSA secret seed - * @param {Uint8Array} oid - (legacy only) EdDSA OID - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$4(algo, A, seed) { - switch (algo) { - case enums.publicKey.ed25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed); - return util.equalsUint8Array(A, publicKey); - } - - case enums.publicKey.ed448: // unsupported - default: - return false; - } -} - -function getPreferredHashAlgo$1(algo) { - switch (algo) { - case enums.publicKey.ed25519: - return enums.hash.sha256; - default: - throw new Error('Unknown EdDSA algo'); - } -} - -var eddsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$2, - sign: sign$3, - verify: verify$3, - validateParams: validateParams$4, - getPreferredHashAlgo: getPreferredHashAlgo$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * AES key wrap - * @function - * @param {Uint8Array} key - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -function wrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const P = unpack(data); - let A = IV; - const R = P; - const n = P.length / 2; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 0; j <= 5; ++j) { - for (let i = 0; i < n; ++i) { - t[1] = n * j + (1 + i); - // B = A - B[0] = A[0]; - B[1] = A[1]; - // B = A || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES(K, B) - B = unpack(aes.encrypt(pack(B))); - // A = MSB(64, B) ^ t - A = B.subarray(0, 2); - A[0] ^= t[0]; - A[1] ^= t[1]; - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - return pack(A, R); -} - -/** - * AES key unwrap - * @function - * @param {String} key - * @param {String} data - * @returns {Uint8Array} - * @throws {Error} - */ -function unwrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const C = unpack(data); - let A = C.subarray(0, 2); - const R = C.subarray(2); - const n = C.length / 2 - 1; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 5; j >= 0; --j) { - for (let i = n - 1; i >= 0; --i) { - t[1] = n * j + (i + 1); - // B = A ^ t - B[0] = A[0] ^ t[0]; - B[1] = A[1] ^ t[1]; - // B = (A ^ t) || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES-1(B) - B = unpack(aes.decrypt(pack(B))); - // A = MSB(64, B) - A = B.subarray(0, 2); - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - if (A[0] === IV[0] && A[1] === IV[1]) { - return pack(R); - } - throw new Error('Key Data Integrity failed'); -} - -function createArrayBuffer(data) { - if (util.isString(data)) { - const { length } = data; - const buffer = new ArrayBuffer(length); - const view = new Uint8Array(buffer); - for (let j = 0; j < length; ++j) { - view[j] = data.charCodeAt(j); - } - return buffer; - } - return new Uint8Array(data).buffer; -} - -function unpack(data) { - const { length } = data; - const buffer = createArrayBuffer(data); - const view = new DataView(buffer); - const arr = new Uint32Array(length / 4); - for (let i = 0; i < length / 4; ++i) { - arr[i] = view.getUint32(4 * i); - } - return arr; -} - -function pack() { - let length = 0; - for (let k = 0; k < arguments.length; ++k) { - length += 4 * arguments[k].length; - } - const buffer = new ArrayBuffer(length); - const view = new DataView(buffer); - let offset = 0; - for (let i = 0; i < arguments.length; ++i) { - for (let j = 0; j < arguments[i].length; ++j) { - view.setUint32(offset + 4 * j, arguments[i][j]); - } - offset += 4 * arguments[i].length; - } - return new Uint8Array(buffer); -} - -var aesKW = /*#__PURE__*/Object.freeze({ - __proto__: null, - wrap: wrap, - unwrap: unwrap -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * @fileoverview Functions to add and remove PKCS5 padding - * @see PublicKeyEncryptedSessionKeyPacket - * @module crypto/pkcs5 - * @private - */ - -/** - * Add pkcs5 padding to a message - * @param {Uint8Array} message - message to pad - * @returns {Uint8Array} Padded message. - */ -function encode$1(message) { - const c = 8 - (message.length % 8); - const padded = new Uint8Array(message.length + c).fill(c); - padded.set(message); - return padded; -} - -/** - * Remove pkcs5 padding from a message - * @param {Uint8Array} message - message to remove padding from - * @returns {Uint8Array} Message without padding. - */ -function decode$1(message) { - const len = message.length; - if (len > 0) { - const c = message[len - 1]; - if (c >= 1) { - const provided = message.subarray(len - c); - const computed = new Uint8Array(c).fill(c); - if (util.equalsUint8Array(provided, computed)) { - return message.subarray(0, len - c); - } - } - } - throw new Error('Invalid padding'); -} - -var pkcs5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - encode: encode$1, - decode: decode$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$8 = util.getWebCrypto(); -const nodeCrypto$9 = util.getNodeCrypto(); - -/** - * Validate ECDH parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDH public point - * @param {Uint8Array} d - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$5(oid, Q, d) { - return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); -} - -// Build Param for ECDH algorithm (RFC 6637) -function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { - return util.concatUint8Array([ - oid.write(), - new Uint8Array([public_algo]), - kdfParams.write(), - util.stringToUint8Array('Anonymous Sender '), - fingerprint.subarray(0, 20) - ]); -} - -// Key Derivation Function (RFC 6637) -async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { - // Note: X is little endian for Curve25519, big-endian for all others. - // This is not ideal, but the RFC's are unclear - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - let i; - if (stripLeading) { - // Work around old go crypto bug - for (i = 0; i < X.length && X[i] === 0; i++); - X = X.subarray(i); - } - if (stripTrailing) { - // Work around old OpenPGP.js bug - for (i = X.length - 1; i >= 0 && X[i] === 0; i--); - X = X.subarray(0, i + 1); - } - const digest = await hash.digest(hashAlgo, util.concatUint8Array([ - new Uint8Array([0, 0, 0, 1]), - X, - param - ])); - return digest.subarray(0, length); -} - -/** - * Generate ECDHE ephemeral key and secret from public key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPublicEphemeralKey(curve, Q) { - switch (curve.type) { - case 'curve25519': { - const d = getRandomBytes(32); - const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d); - let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey); - publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); - return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPublicEphemeralKey(curve, Q); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePublicEphemeralKey(curve, Q); - } - return ellipticPublicEphemeralKey(curve, Q); -} - -/** - * Encrypt and wrap a session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} data - Unpadded session key data - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} - * @async - */ -async function encrypt$3(oid, kdfParams, data, Q, fingerprint) { - const m = encode$1(data); - - const curve = new CurveWithOID(oid); - const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); - const wrappedKey = wrap(Z, m); - return { publicKey, wrappedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPrivateEphemeralKey(curve, V, Q, d) { - if (d.length !== curve.payloadSize) { - const privateKey = new Uint8Array(curve.payloadSize); - privateKey.set(d, curve.payloadSize - d.length); - d = privateKey; - } - switch (curve.type) { - case 'curve25519': { - const secretKey = d.slice().reverse(); - const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1)); - return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPrivateEphemeralKey(curve, V, Q, d); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePrivateEphemeralKey(curve, V, d); - } - return ellipticPrivateEphemeralKey(curve, V, d); -} - -/** - * Decrypt and unwrap the value derived from session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} C - Encrypted and wrapped value derived from session key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Value derived from session key. - * @async - */ -async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) { - const curve = new CurveWithOID(oid); - const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - let err; - for (let i = 0; i < 3; i++) { - try { - // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); - return decode$1(unwrap(Z, C)); - } catch (e) { - err = e; - } - } - throw err; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d); - let privateKey = webCrypto$8.importKey( - 'jwk', - recipient, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); - let sender = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - [] - ); - [privateKey, sender] = await Promise.all([privateKey, sender]); - let S = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: sender - }, - privateKey, - curve.web.sharedSize - ); - let secret = webCrypto$8.exportKey( - 'jwk', - privateKey - ); - [S, secret] = await Promise.all([S, secret]); - const sharedKey = new Uint8Array(S); - const secretKey = b64ToUint8Array(secret.d); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); - let keyPair = webCrypto$8.generateKey( - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - let recipient = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - false, - [] - ); - [keyPair, recipient] = await Promise.all([keyPair, recipient]); - let s = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: recipient - }, - keyPair.privateKey, - curve.web.sharedSize - ); - let p = webCrypto$8.exportKey( - 'jwk', - keyPair.publicKey - ); - [s, p] = await Promise.all([s, p]); - const sharedKey = new Uint8Array(s); - const publicKey = new Uint8Array(jwkToRawPublic(p)); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPrivateEphemeralKey(curve, V, d) { - const indutnyCurve = await getIndutnyCurve(curve.name); - V = keyFromPublic(indutnyCurve, V); - d = keyFromPrivate(indutnyCurve, d); - const secretKey = new Uint8Array(d.getPrivate()); - const S = d.derive(V.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPublicEphemeralKey(curve, Q) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const v = await curve.genKeyPair(); - Q = keyFromPublic(indutnyCurve, Q); - const V = keyFromPrivate(indutnyCurve, v.privateKey); - const publicKey = v.publicKey; - const S = V.derive(Q.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePrivateEphemeralKey(curve, V, d) { - const recipient = nodeCrypto$9.createECDH(curve.node.node); - recipient.setPrivateKey(d); - const sharedKey = new Uint8Array(recipient.computeSecret(V)); - const secretKey = new Uint8Array(recipient.getPrivateKey()); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePublicEphemeralKey(curve, Q) { - const sender = nodeCrypto$9.createECDH(curve.node.node); - sender.generateKeys(); - const sharedKey = new Uint8Array(sender.computeSecret(Q)); - const publicKey = new Uint8Array(sender.getPublicKey()); - return { publicKey, sharedKey }; -} - -var ecdh = /*#__PURE__*/Object.freeze({ - __proto__: null, - validateParams: validateParams$5, - encrypt: encrypt$3, - decrypt: decrypt$3 -}); - -/** - * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. - * @module crypto/hkdf - * @private - */ - -const webCrypto$9 = util.getWebCrypto(); -const nodeCrypto$a = util.getNodeCrypto(); -const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle; - -async function HKDF(hashAlgo, inputKey, salt, info, outLen) { - const hash = enums.read(enums.webHash, hashAlgo); - if (!hash) throw new Error('Hash algo not supported with HKDF'); - - if (webCrypto$9 || nodeSubtleCrypto) { - const crypto = webCrypto$9 || nodeSubtleCrypto; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); - return new Uint8Array(bits); - } - - if (nodeCrypto$a) { - const hashAlgoName = enums.read(enums.hash, hashAlgo); - // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869 - - const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest(); - // Step 1: Extract - // PRK = HMAC-Hash(salt, IKM) - const pseudoRandomKey = computeHMAC(salt, inputKey); - - const hashLen = pseudoRandomKey.length; - - // Step 2: Expand - // HKDF-Expand(PRK, info, L) -> OKM - const n = Math.ceil(outLen / hashLen); - const outputKeyingMaterial = new Uint8Array(n * hashLen); - - // HMAC input buffer updated at each iteration - const roundInput = new Uint8Array(hashLen + info.length + 1); - // T_i and last byte are updated at each iteration, but `info` remains constant - roundInput.set(info, hashLen); - - for (let i = 0; i < n; i++) { - // T(0) = empty string (zero length) - // T(i) = HMAC-Hash(PRK, T(i-1) | info | i) - roundInput[roundInput.length - 1] = i + 1; - // t = T(i+1) - const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen)); - roundInput.set(t, 0); - - outputKeyingMaterial.set(t, i * hashLen); - } - - return outputKeyingMaterial.subarray(0, outLen); - } - - throw new Error('No HKDF implementation available'); -} - -/** - * @fileoverview Key encryption and decryption for RFC 6637 ECDH - * @module crypto/public_key/elliptic/ecdh - * @private - */ - -const HKDF_INFO = { - x25519: util.encodeUTF8('OpenPGP X25519') -}; - -/** - * Generate ECDH key for Montgomery curves - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} - */ -async function generate$3(algo) { - switch (algo) { - case enums.publicKey.x25519: { - // k stays in little-endian, unlike legacy ECDH over curve25519 - const k = getRandomBytes(32); - const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k); - return { A, k }; - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** -* Validate ECDH parameters -* @param {module:enums.publicKey} algo - Algorithm identifier -* @param {Uint8Array} A - ECDH public point -* @param {Uint8Array} k - ECDH secret scalar -* @returns {Promise} Whether params are valid. -* @async -*/ -async function validateParams$6(algo, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k); - return util.equalsUint8Array(A, publicKey); - } - - default: - return false; - } -} - -/** - * Wrap and encrypt a session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} data - session key data to be encrypted - * @param {Uint8Array} recipientA - Recipient public key (K_B) - * @returns {Promise<{ - * ephemeralPublicKey: Uint8Array, - * wrappedKey: Uint8Array - * }>} ephemeral public key (K_A) and encrypted key - * @async - */ -async function encrypt$4(algo, data, recipientA) { - switch (algo) { - case enums.publicKey.x25519: { - const ephemeralSecretKey = getRandomBytes(32); - const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA); - const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - recipientA, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - const wrappedKey = wrap(encryptionKey, data); - return { ephemeralPublicKey, wrappedKey }; - } - - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** - * Decrypt and unwrap the session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} ephemeralPublicKey - (K_A) - * @param {Uint8Array} wrappedKey, - * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF - * @param {Uint8Array} k - Recipient secret key (b) - * @returns {Promise} decrypted session key data - * @async - */ -async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - A, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - return unwrap(encryptionKey, wrappedKey); - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -var ecdh_x = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$3, - validateParams: validateParams$6, - encrypt: encrypt$4, - decrypt: decrypt$4 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -var elliptic = /*#__PURE__*/Object.freeze({ - __proto__: null, - CurveWithOID: CurveWithOID, - ecdh: ecdh, - ecdhX: ecdh_x, - ecdsa: ecdsa, - eddsaLegacy: eddsa_legacy, - eddsa: eddsa, - generate: generate$1, - getPreferredHashAlgo: getPreferredHashAlgo -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/* - TODO regarding the hash function, read: - https://tools.ietf.org/html/rfc4880#section-13.6 - https://tools.ietf.org/html/rfc4880#section-14 -*/ - -/** - * DSA Sign function - * @param {Integer} hashAlgo - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} x - * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} - * @async - */ -async function sign$4(hashAlgo, hashed, g, p, q, x) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - x = new BigInteger(x); - - let k; - let r; - let s; - let t; - g = g.mod(p); - x = x.mod(q); - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - while (true) { - // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - k = await getRandomBigInteger(one, q); // returns in [1, q-1] - r = g.modExp(k, p).imod(q); // (g**k mod p) mod q - if (r.isZero()) { - continue; - } - const xr = x.mul(r).imod(q); - t = h.add(xr).imod(q); // H(m) + x*r mod q - s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q - if (s.isZero()) { - continue; - } - break; - } - return { - r: r.toUint8Array('be', q.byteLength()), - s: s.toUint8Array('be', q.byteLength()) - }; -} - -/** - * DSA Verify function - * @param {Integer} hashAlgo - * @param {Uint8Array} r - * @param {Uint8Array} s - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} y - * @returns {boolean} - * @async - */ -async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) { - const BigInteger = await util.getBigInteger(); - const zero = new BigInteger(0); - r = new BigInteger(r); - s = new BigInteger(s); - - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - - if (r.lte(zero) || r.gte(q) || - s.lte(zero) || s.gte(q)) { - util.printDebug('invalid DSA Signature'); - return false; - } - const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q); - const w = s.modInv(q); // s**-1 mod q - if (w.isZero()) { - util.printDebug('invalid DSA Signature'); - return false; - } - - g = g.mod(p); - y = y.mod(p); - const u1 = h.mul(w).imod(q); // H(m) * w mod q - const u2 = r.mul(w).imod(q); // r * w mod q - const t1 = g.modExp(u1, p); // g**u1 mod p - const t2 = y.modExp(u2, p); // y**u2 mod p - const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q - return v.equal(r); -} - -/** - * Validate DSA parameters - * @param {Uint8Array} p - DSA prime - * @param {Uint8Array} q - DSA group order - * @param {Uint8Array} g - DSA sub-group generator - * @param {Uint8Array} y - DSA public key - * @param {Uint8Array} x - DSA private key - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$7(p, q, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - /** - * Check that subgroup order q divides p-1 - */ - if (!p.dec().mod(q).isZero()) { - return false; - } - - /** - * g has order q - * Check that g ** q = 1 mod p - */ - if (!g.modExp(q, p).isOne()) { - return false; - } - - /** - * Check q is large and probably prime (we mainly want to avoid small factors) - */ - const qSize = new BigInteger(q.bitLength()); - const n150 = new BigInteger(150); - if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) { - return false; - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{rq + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q - const rqx = q.mul(r).add(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var dsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$4, - verify: verify$4, - validateParams: validateParams$7 -}); - -/** - * @fileoverview Asymmetric cryptography functions - * @module crypto/public_key - * @private - */ - -var publicKey = { - /** @see module:crypto/public_key/rsa */ - rsa: rsa, - /** @see module:crypto/public_key/elgamal */ - elgamal: elgamal, - /** @see module:crypto/public_key/elliptic */ - elliptic: elliptic, - /** @see module:crypto/public_key/dsa */ - dsa: dsa, - /** @see tweetnacl */ - nacl: naclFastLight -}; - -/** - * @fileoverview Provides functions for asymmetric signing and signature verification - * @module crypto/signature - * @private - */ - -/** - * Parse signature in binary form to get the parameters. - * The returned values are only padded for EdDSA, since in the other cases their expected length - * depends on the key params, hence we delegate the padding to the signature verification function. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Uint8Array} signature - Data for which the signature was created - * @returns {Promise} True if signature is valid. - * @async - */ -function parseSignatureParams(algo, signature) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA signatures: - // - MPI of RSA signature value m**d mod n. - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const s = util.readMPI(signature.subarray(read)); - // The signature needs to be the same length as the public key modulo n. - // We pad s on signature verification, where we have access to n. - return { s }; - } - // Algorithm-Specific Fields for DSA or ECDSA signatures: - // - MPI of DSA or ECDSA value r. - // - MPI of DSA or ECDSA value s. - case enums.publicKey.dsa: - case enums.publicKey.ecdsa: - { - const r = util.readMPI(signature.subarray(read)); read += r.length + 2; - const s = util.readMPI(signature.subarray(read)); - return { r, s }; - } - // Algorithm-Specific Fields for legacy EdDSA signatures: - // - MPI of an EC point r. - // - EdDSA value s, in MPI, in the little endian representation - case enums.publicKey.eddsaLegacy: { - // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values: - // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 - let r = util.readMPI(signature.subarray(read)); read += r.length + 2; - r = util.leftPad(r, 32); - let s = util.readMPI(signature.subarray(read)); - s = util.leftPad(s, 32); - return { r, s }; - } - // Algorithm-Specific Fields for Ed25519 signatures: - // - 64 octets of the native signature - case enums.publicKey.ed25519: { - const RS = signature.subarray(read, read + 64); read += RS.length; - return { RS }; - } - default: - throw new UnsupportedError('Unknown signature algorithm.'); - } -} - -/** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} signature - Named algorithm-specific signature parameters - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Data for which the signature was created - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} True if signature is valid. - * @async - */ -async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto - return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); - } - case enums.publicKey.dsa: { - const { g, p, q, y } = publicParams; - const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers - return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicParams; - const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; - // padding needed for webcrypto - const r = util.leftPad(signature.r, curveSize); - const s = util.leftPad(signature.s, curveSize); - return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicParams; - // signature already padded on parsing - return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -/** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters - * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters - * @param {Uint8Array} data - Data to be signed - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} Signature Object containing named signature parameters. - * @async - */ -async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { - if (!publicKeyParams || !privateKeyParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); - return { s }; - } - case enums.publicKey.dsa: { - const { g, p, q } = publicKeyParams; - const { x } = privateKeyParams; - return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); - } - case enums.publicKey.elgamal: { - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicKeyParams; - const { d } = privateKeyParams; - return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -var signature = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseSignatureParams: parseSignatureParams, - verify: verify$5, - sign: sign$5 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class ECDHSymmetricKey { - constructor(data) { - if (data) { - this.data = data; - } - } - - /** - * Read an ECDHSymmetricKey from an Uint8Array: - * - 1 octect for the length `l` - * - `l` octects of encoded session key data - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - if (bytes.length >= 1) { - const length = bytes[0]; - if (bytes.length >= 1 + length) { - this.data = bytes.subarray(1, 1 + length); - return 1 + this.data.length; - } - } - throw new Error('Invalid symmetric key'); - } - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Implementation of type KDF parameters - * - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - * @module type/kdf_params - * @private - */ - -class KDFParams { - /** - * @param {enums.hash} hash - Hash algorithm - * @param {enums.symmetric} cipher - Symmetric algorithm - */ - constructor(data) { - if (data) { - const { hash, cipher } = data; - this.hash = hash; - this.cipher = cipher; - } else { - this.hash = null; - this.cipher = null; - } - } - - /** - * Read KDFParams from an Uint8Array - * @param {Uint8Array} input - Where to read the KDFParams from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { - throw new UnsupportedError('Cannot read KDFParams'); - } - this.hash = input[2]; - this.cipher = input[3]; - return 4; - } - - /** - * Write KDFParams to an Uint8Array - * @returns {Uint8Array} Array with the KDFParams value - */ - write() { - return new Uint8Array([3, 1, this.hash, this.cipher]); - } -} - -/** - * Encoded symmetric key for x25519 and x448 - * The payload format varies for v3 and v6 PKESK: - * the former includes an algorithm byte preceeding the encrypted session key. - * - * @module type/x25519x448_symkey - */ - -class ECDHXSymmetricKey { - static fromObject({ wrappedKey, algorithm }) { - const instance = new ECDHXSymmetricKey(); - instance.wrappedKey = wrappedKey; - instance.algorithm = algorithm; - return instance; - } - - /** - * - 1 octect for the length `l` - * - `l` octects of encoded session key data (with optional leading algorithm byte) - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - let read = 0; - let followLength = bytes[read++]; - this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even - followLength -= followLength % 2; - this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength; - } - - /** - * Write an MontgomerySymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([ - this.algorithm ? - new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : - new Uint8Array([this.wrappedKey.length]), - this.wrappedKey - ]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param {module:enums.publicKey} keyAlgo - Public key algorithm - * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Session key data to be encrypted - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Encrypted session key parameters. - * @async - */ -async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const { n, e } = publicParams; - const c = await publicKey.rsa.encrypt(data, n, e); - return { c }; - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - return publicKey.elgamal.encrypt(data, p, g, y); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicParams; - const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( - oid, kdfParams, data, Q, fingerprint); - return { V, C: new ECDHSymmetricKey(C) }; - } - case enums.publicKey.x25519: { - if (!util.isAES(symmetricAlgo)) { - // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 - throw new Error('X25519 keys can only encrypt AES session keys'); - } - const { A } = publicParams; - const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( - keyAlgo, data, A); - const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); - return { ephemeralPublicKey, C }; - } - default: - return []; - } -} - -/** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Object} publicKeyParams - Algorithm-specific public key parameters - * @param {Object} privateKeyParams - Algorithm-specific private key parameters - * @param {Object} sessionKeyParams - Encrypted session key parameters - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing - * (needed for constant-time processing in RSA and ElGamal) - * @returns {Promise} Decrypted data. - * @throws {Error} on sensitive decryption error, unless `randomPayload` is given - * @async - */ -async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: { - const { c } = sessionKeyParams; - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); - } - case enums.publicKey.elgamal: { - const { c1, c2 } = sessionKeyParams; - const p = publicKeyParams.p; - const x = privateKeyParams.x; - return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicKeyParams; - const { d } = privateKeyParams; - const { V, C } = sessionKeyParams; - return publicKey.elliptic.ecdh.decrypt( - oid, kdfParams, V, C.data, Q, d, fingerprint); - } - case enums.publicKey.x25519: { - const { A } = publicKeyParams; - const { k } = privateKeyParams; - const { ephemeralPublicKey, C } = sessionKeyParams; - if (!util.isAES(C.algorithm)) { - throw new Error('AES session key expected'); - } - return publicKey.elliptic.ecdhX.decrypt( - algo, ephemeralPublicKey, C.wrappedKey, A, k); - } - default: - throw new Error('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse public key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. - */ -function parsePublicKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; - const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; - return { read, publicParams: { n, e } }; - } - case enums.publicKey.dsa: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, q, g, y } }; - } - case enums.publicKey.elgamal: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, g, y } }; - } - case enums.publicKey.ecdsa: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.eddsaLegacy: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - Q = util.leftPad(Q, 33); - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.ecdh: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); - return { read: read, publicParams: { oid, Q, kdfParams } }; - } - case enums.publicKey.ed25519: - case enums.publicKey.x25519: { - const A = bytes.subarray(read, read + 32); read += A.length; - return { read, publicParams: { A } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse private key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @param {Object} publicParams - (ECC only) public params, needed to format some private params - * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. - */ -function parsePrivateKeyParams(algo, bytes, publicParams) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; - return { read, privateParams: { d, p, q, u } }; - } - case enums.publicKey.dsa: - case enums.publicKey.elgamal: { - const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; - return { read, privateParams: { x } }; - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const curve = new CurveWithOID(publicParams.oid); - let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - d = util.leftPad(d, curve.payloadSize); - return { read, privateParams: { d } }; - } - case enums.publicKey.eddsaLegacy: { - const curve = new CurveWithOID(publicParams.oid); - let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; - seed = util.leftPad(seed, curve.payloadSize); - return { read, privateParams: { seed } }; - } - case enums.publicKey.ed25519: { - const seed = bytes.subarray(read, read + 32); read += seed.length; - return { read, privateParams: { seed } }; - } - case enums.publicKey.x25519: { - const k = bytes.subarray(read, read + 32); read += k.length; - return { read, privateParams: { k } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** Returns the types comprising the encrypted session key of an algorithm - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {Object} The session key parameters referenced by name. - */ -function parseEncSessionKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA encrypted session keys: - // - MPI of RSA encrypted value m**e mod n. - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const c = util.readMPI(bytes.subarray(read)); - return { c }; - } - - // Algorithm-Specific Fields for Elgamal encrypted session keys: - // - MPI of Elgamal value g**k mod p - // - MPI of Elgamal value m * y**k mod p - case enums.publicKey.elgamal: { - const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; - const c2 = util.readMPI(bytes.subarray(read)); - return { c1, c2 }; - } - // Algorithm-Specific Fields for ECDH encrypted session keys: - // - MPI containing the ephemeral key used to establish the shared secret - // - ECDH Symmetric Key - case enums.publicKey.ecdh: { - const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; - const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); - return { V, C }; - } - // Algorithm-Specific Fields for X25519 encrypted session keys: - // - 32 octets representing an ephemeral X25519 public key. - // - A one-octet size of the following fields. - // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). - // - The encrypted session key. - case enums.publicKey.x25519: { - const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length; - const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); - return { ephemeralPublicKey, C }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Convert params to MPI and serializes them in the proper order - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} params - The key parameters indexed by name - * @returns {Uint8Array} The array containing the MPIs. - */ -function serializeParams(algo, params) { - // Some algorithms do not rely on MPIs to store the binary params - const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]); - const orderedParams = Object.keys(params).map(name => { - const param = params[name]; - if (!util.isUint8Array(param)) return param.write(); - return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); - }); - return util.concatUint8Array(orderedParams); -} - -/** - * Generate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Integer} bits - Bit length for RSA keys - * @param {module:type/oid} oid - Object identifier for ECC keys - * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. - * @async - */ -function generateParams(algo, bits, oid) { - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ - privateParams: { d, p, q, u }, - publicParams: { n, e } - })); - } - case enums.publicKey.ecdsa: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { d: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { seed: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.ecdh: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ - privateParams: { d: secret }, - publicParams: { - oid: new OID(oid), - Q, - kdfParams: new KDFParams({ hash, cipher }) - } - })); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ - privateParams: { seed }, - publicParams: { A } - })); - case enums.publicKey.x25519: - return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ - privateParams: { k }, - publicParams: { A } - })); - case enums.publicKey.dsa: - case enums.publicKey.elgamal: - throw new Error('Unsupported algorithm for key generation.'); - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Validate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Object} privateParams - Algorithm-specific private key parameters - * @returns {Promise} Whether the parameters are valid. - * @async - */ -async function validateParams$8(algo, publicParams, privateParams) { - if (!publicParams || !privateParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const { d, p, q, u } = privateParams; - return publicKey.rsa.validateParams(n, e, d, p, q, u); - } - case enums.publicKey.dsa: { - const { p, q, g, y } = publicParams; - const { x } = privateParams; - return publicKey.dsa.validateParams(p, q, g, y, x); - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - const { x } = privateParams; - return publicKey.elgamal.validateParams(p, g, y, x); - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; - const { oid, Q } = publicParams; - const { d } = privateParams; - return algoModule.validateParams(oid, Q, d); - } - case enums.publicKey.eddsaLegacy: { - const { Q, oid } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsa.validateParams(algo, A, seed); - } - case enums.publicKey.x25519: { - const { A } = publicParams; - const { k } = privateParams; - return publicKey.elliptic.ecdhX.validateParams(algo, A, k); - } - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - * @async - */ -async function getPrefixRandom(algo) { - const { blockSize } = getCipher(algo); - const prefixrandom = await getRandomBytes(blockSize); - const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - return util.concat([prefixrandom, repeat]); -} - -/** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Uint8Array} Random bytes as a string to be used as a key. - */ -function generateSessionKey(algo) { - const { keySize } = getCipher(algo); - return getRandomBytes(keySize); -} - -/** - * Get implementation of the given AEAD mode - * @param {enums.aead} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getAEADMode(algo) { - const algoName = enums.read(enums.aead, algo); - return mode[algoName]; -} - -/** - * Check whether the given curve OID is supported - * @param {module:type/oid} oid - EC object identifier - * @throws {UnsupportedError} if curve is not supported - */ -function checkSupportedCurve(oid) { - try { - oid.getName(); - } catch (e) { - throw new UnsupportedError('Unknown curve OID'); - } -} - -/** - * Get preferred hash algo for a given elliptic algo - * @param {module:enums.publicKey} algo - alrogithm identifier - * @param {module:type/oid} [oid] - curve OID if needed by algo - */ -function getPreferredCurveHashAlgo(algo, oid) { - switch (algo) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.getPreferredHashAlgo(oid); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); - default: - throw new Error('Unknown elliptic signing algo'); - } -} - -var crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - publicKeyEncrypt: publicKeyEncrypt, - publicKeyDecrypt: publicKeyDecrypt, - parsePublicKeyParams: parsePublicKeyParams, - parsePrivateKeyParams: parsePrivateKeyParams, - parseEncSessionKeyParams: parseEncSessionKeyParams, - serializeParams: serializeParams, - generateParams: generateParams, - validateParams: validateParams$8, - getPrefixRandom: getPrefixRandom, - generateSessionKey: generateSessionKey, - getAEADMode: getAEADMode, - getCipher: getCipher, - getPreferredCurveHashAlgo: getPreferredCurveHashAlgo -}); - -/** - * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash - * @module crypto - * @private - */ - -// TODO move cfb and gcm to cipher -const mod = { - /** @see module:crypto/cipher */ - cipher: cipher, - /** @see module:crypto/hash */ - hash: hash, - /** @see module:crypto/mode */ - mode: mode, - /** @see module:crypto/public_key */ - publicKey: publicKey, - /** @see module:crypto/signature */ - signature: signature, - /** @see module:crypto/random */ - random: random, - /** @see module:crypto/pkcs1 */ - pkcs1: pkcs1, - /** @see module:crypto/pkcs5 */ - pkcs5: pkcs5, - /** @see module:crypto/aes_kw */ - aesKW: aesKW -}; - -Object.assign(mod, crypto$1); - -var TYPED_OK = typeof Uint8Array !== "undefined" && - typeof Uint16Array !== "undefined" && - typeof Int32Array !== "undefined"; - - -// reduce buffer size, avoiding mem copy -function shrinkBuf(buf, size) { - if (buf.length === size) { - return buf; - } - if (buf.subarray) { - return buf.subarray(0, size); - } - buf.length = size; - return buf; -} - - -const fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - let i, l, len, pos, chunk; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - const result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -const fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// - -let Buf8 = TYPED_OK ? Uint8Array : Array; -let Buf16 = TYPED_OK ? Uint16Array : Array; -let Buf32 = TYPED_OK ? Int32Array : Array; -let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks; -let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -/* Allowed flush values; see deflate() and inflate() below for details */ -const Z_NO_FLUSH = 0; -const Z_PARTIAL_FLUSH = 1; -const Z_SYNC_FLUSH = 2; -const Z_FULL_FLUSH = 3; -const Z_FINISH = 4; -const Z_BLOCK = 5; -const Z_TREES = 6; - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -const Z_OK = 0; -const Z_STREAM_END = 1; -const Z_NEED_DICT = 2; -const Z_STREAM_ERROR = -2; -const Z_DATA_ERROR = -3; -//export const Z_MEM_ERROR = -4; -const Z_BUF_ERROR = -5; -const Z_DEFAULT_COMPRESSION = -1; - - -const Z_FILTERED = 1; -const Z_HUFFMAN_ONLY = 2; -const Z_RLE = 3; -const Z_FIXED = 4; -const Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -const Z_BINARY = 0; -const Z_TEXT = 1; -//export const Z_ASCII = 1; // = Z_TEXT (deprecated) -const Z_UNKNOWN = 2; - -/* The deflate compression method */ -const Z_DEFLATED = 8; -//export const Z_NULL = null // Use -1 or null inline, depending on var type - -/*============================================================================*/ - - -function zero$1(buf) { - let len = buf.length; while (--len >= 0) { - buf[len] = 0; - } -} - -// From zutil.h - -const STORED_BLOCK = 0; -const STATIC_TREES = 1; -const DYN_TREES = 2; -/* The three kinds of block type */ - -const MIN_MATCH = 3; -const MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -const LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -const LITERALS = 256; -/* number of literal bytes 0..255 */ - -const L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -const D_CODES = 30; -/* number of distance codes */ - -const BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -const HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -const MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -const Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -const MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -const END_BLOCK = 256; -/* end of block literal code */ - -const REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -const REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -const REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -const extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -const extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -const extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -const bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -const static_ltree = new Array((L_CODES + 2) * 2); -zero$1(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -const static_dtree = new Array(D_CODES * 2); -zero$1(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -const _dist_code = new Array(DIST_CODE_LEN); -zero$1(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero$1(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -const base_length = new Array(LENGTH_CODES); -zero$1(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -const base_dist = new Array(D_CODES); -zero$1(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -let static_l_desc; -let static_d_desc; -let static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = w & 0xff; - s.pending_buf[s.pending++] = w >>> 8 & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > Buf_size - length) { - s.bi_buf |= value << s.bi_valid & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> Buf_size - s.bi_valid; - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= value << s.bi_valid & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { - continue; - } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { - return; - } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { - bits--; - } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { - continue; - } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = code + bl_count[bits - 1] << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < 1 << extra_lbits[code]; n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < 1 << extra_dbits[code]; n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - let n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { - s.dyn_ltree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < D_CODES; n++) { - s.dyn_dtree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < BL_CODES; n++) { - s.bl_tree[n * 2]/*.Freq*/ = 0; - } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } - // while (len--) { - // put_byte(s, *buf++); - // } - arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - const _n2 = n * 2; - const _m2 = m * 2; - return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]; -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { - break; - } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) { - pqdownheap(s, tree, n); - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { - s.bl_tree[curlen * 2]/*.Freq*/++; - } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { - send_code(s, curlen, s.bl_tree); - } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - let max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - let rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - let black_mask = 0xf3ffc07f; - let n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -let static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) { - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = s.opt_len + 3 + 7 >>> 3; - static_lenb = s.static_len + 3 + 7 >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { - opt_lenb = static_lenb; - } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if (stored_len + 4 <= opt_lenb && buf !== -1) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif - - return s.last_lit === s.lit_bufsize - 1; - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function adler32(adler, buf, len, pos) { - let s1 = adler & 0xffff |0, - s2 = adler >>> 16 & 0xffff |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = s1 + buf[pos++] |0; - s2 = s2 + s1 |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return s1 | s2 << 16 |0; -} - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - let c; - const table = []; - - for (let n = 0; n < 256; n++) { - c = n; - for (let k = 0; k < 8; k++) { - c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -const crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - const t = crcTable, - end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return crc ^ -1; // >>> 0; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var msg = { - 2: "need dictionary", /* Z_NEED_DICT 2 */ - 1: "stream end", /* Z_STREAM_END 1 */ - 0: "", /* Z_OK 0 */ - "-1": "file error", /* Z_ERRNO (-1) */ - "-2": "stream error", /* Z_STREAM_ERROR (-2) */ - "-3": "data error", /* Z_DATA_ERROR (-3) */ - "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */ - "-5": "buffer error", /* Z_BUF_ERROR (-5) */ - "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */ -}; - -/*============================================================================*/ - - -const MAX_MEM_LEVEL = 9; - - -const LENGTH_CODES$1 = 29; -/* number of length codes, not counting the special END_BLOCK code */ -const LITERALS$1 = 256; -/* number of literal bytes 0..255 */ -const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; -/* number of Literal or Length codes, including the END_BLOCK code */ -const D_CODES$1 = 30; -/* number of distance codes */ -const BL_CODES$1 = 19; -/* number of codes used to transfer the bit lengths */ -const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; -/* maximum heap size */ -const MAX_BITS$1 = 15; -/* All codes must not exceed MAX_BITS bits */ - -const MIN_MATCH$1 = 3; -const MAX_MATCH$1 = 258; -const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); - -const PRESET_DICT = 0x20; - -const INIT_STATE = 42; -const EXTRA_STATE = 69; -const NAME_STATE = 73; -const COMMENT_STATE = 91; -const HCRC_STATE = 103; -const BUSY_STATE = 113; -const FINISH_STATE = 666; - -const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -const BS_BLOCK_DONE = 2; /* block flush performed */ -const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - const s = strm.state; - - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - let len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - const _win = s.window; // shortcut - - const wmask = s.w_mask; - const prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - const strend = s.strstart + MAX_MATCH$1; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH$1 - (strend - scan); - scan = strend - MAX_MATCH$1; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - const _w_size = s.w_size; - let p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH$1) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH$1) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // var curr = s.strstart + s.lookahead; - // var init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (; ;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH$1) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - - let max_insert; - - /* Process the input block. */ - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH$1 - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH$1 - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH$1; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH$1 - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - - const _win = s.window; - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH$1) { - fill_window(s); - if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH$1; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH$1 - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH$1) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -class Config { - constructor(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } -} -const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - s.ins_h = 0; -} - -class DeflateState { - constructor() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); - this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); - this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); - zero$2(this.dyn_ltree); - zero$2(this.dyn_dtree); - zero$2(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Buf16(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ - zero$2(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; - zero$2(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ - } -} - -function deflateResetKeep(strm) { - let s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - _tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - const ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - let wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); - s.window = new Buf8(s.w_size * 2); - s.head = new Buf16(s.hash_size); - s.prev = new Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - - -function deflate(strm, flush) { - let old_flush, s; - let beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } - //#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero$2(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - let status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - let dictLength = dictionary.length; - - let s; - let str, n; - let wrap; - let avail; - let next; - let input; - let tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new Buf8(s.w_size); - arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH$1) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH$1 - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH$1 - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - -// String encode/decode helpers - -try { - String.fromCharCode.apply(null, [ 0 ]); -} catch (__) { -} -try { - String.fromCharCode.apply(null, new Uint8Array(1)); -} catch (__) { -} - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -const _utf8len = new Buf8(256); -for (let q = 0; q < 256; q++) { - _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - -// convert string to array (typed, when possible) -function string2buf (str) { - let c, c2, m_pos, i, buf_len = 0; - const str_len = str.length; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - const buf = new Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | c >>> 6; - buf[i++] = 0x80 | c & 0x3f; - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | c >>> 12; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } else { - /* four bytes */ - buf[i++] = 0xf0 | c >>> 18; - buf[i++] = 0x80 | c >>> 12 & 0x3f; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } - } - - return buf; -} - - -// Convert binary string (typed, when possible) -function binstring2buf (str) { - const buf = new Buf8(str.length); - for (let i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class ZStream { - constructor() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } -} - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ - -class Deflate { - constructor(options) { - this.options = { - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - ...(options || {}) - }; - - const opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - let dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } - } - - /** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize } } = this; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = string2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -const BAD = 30; /* got a data error -- remain here until reset */ -const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let _out; /* local strm.output */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; - - - - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - const input = strm.input; - const last = _in + (strm.avail_in - 5); - _out = strm.next_out; - const output = strm.output; - const beg = _out - (start - strm.avail_out); - const end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - const dmax = state.dmax; - //#endif - const wsize = state.wsize; - const whave = state.whave; - const wnext = state.wnext; - const s_window = state.window; - hold = state.hold; - bits = state.bits; - const lcode = state.lencode; - const dcode = state.distcode; - const lmask = (1 << state.lenbits) - 1; - const dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & (1 << op) - 1; - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & (1 << op) - 1; - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dodist; - } else { - strm.msg = "invalid distance code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dolen; - } else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } else { - strm.msg = "invalid literal/length code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); - strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); - state.hold = hold; - state.bits = bits; - return; -} - -const MAXBITS = 15; -const ENOUGH_LENS = 852; -const ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -const CODES = 0; -const LENS = 1; -const DISTS = 2; - -const lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -const lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -const dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -const dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // var shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { - break; - } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { - break; - } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - const mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << len - drop; - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << len - 1; - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { - break; - } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { - break; - } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = root << 24 | curr << 16 | next - table_index |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = len - drop << 24 | 64 << 16 |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -} - -const CODES$1 = 0; -const LENS$1 = 1; -const DISTS$1 = 2; - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -const HEAD = 1; /* i: waiting for magic header */ -const FLAGS = 2; /* i: waiting for method and flags (gzip) */ -const TIME = 3; /* i: waiting for modification time (gzip) */ -const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -const EXLEN = 5; /* i: waiting for extra length (gzip) */ -const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -const NAME = 7; /* i: waiting for end of file name (gzip) */ -const COMMENT = 8; /* i: waiting for end of comment (gzip) */ -const HCRC = 9; /* i: waiting for header crc (gzip) */ -const DICTID = 10; /* i: waiting for dictionary check value */ -const DICT = 11; /* waiting for inflateSetDictionary() call */ -const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ -const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -const STORED = 14; /* i: waiting for stored size (length and complement) */ -const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -const COPY = 16; /* i/o: waiting for input or output to copy stored block */ -const TABLE = 17; /* i: waiting for dynamic block table lengths */ -const LENLENS = 18; /* i: waiting for code length code lengths */ -const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -const LEN_ = 20; /* i: same as LEN below, but only first time in */ -const LEN = 21; /* i: waiting for length/lit/eob code */ -const LENEXT = 22; /* i: waiting for length extra bits */ -const DIST = 23; /* i: waiting for distance code */ -const DISTEXT = 24; /* i: waiting for distance extra bits */ -const MATCH = 25; /* o: waiting for output space to copy string */ -const LIT = 26; /* o: waiting for output space to write literal */ -const CHECK = 27; /* i: waiting for 32-bit check value */ -const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -const DONE = 29; /* finished check, done -- remain here until reset */ -const BAD$1 = 30; /* got a data error -- remain here until reset */ -//const MEM = 31; /* got an inflate() memory error -- remain here until reset */ -const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -const ENOUGH_LENS$1 = 852; -const ENOUGH_DISTS$1 = 592; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -class InflateState { - constructor() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Buf16(320); /* temporary storage for code lengths */ - this.work = new Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ - } -} - -function inflateResetKeep(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); - state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - let wrap; - let state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - let ret; - let state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -let virgin = true; - -let lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - let sym; - - lenfix = new Buf32(512); - distfix = new Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - let dist; - const state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ - let opts; - - let n; // temporary var for NEED_BITS - - const order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD$1; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD$1; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE$1; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD$1; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE$1; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE$1; - /* falls through */ - case TYPE$1: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD$1; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD$1; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE$1; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD$1; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD$1) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD$1; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD$1; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE$1) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE$1; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD$1: - ret = Z_DATA_ERROR; - break inf_leave; - // case MEM: - // return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE$1 ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - const state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - let state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - const dictLength = dictionary.length; - - let state; - let dictid; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - updatewindow(strm, dictionary, dictLength, dictLength); - // if (ret) { - // state.mode = MEM; - // return Z_MEM_ERROR; - // } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class GZheader { - constructor() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; - } -} - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -class Inflate { - constructor(options) { - this.options = { - chunkSize: 16384, - windowBits: 0, - ...(options || {}) - }; - - const opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - let status = inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - inflateGetHeader(this.strm, this.header); - - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - opt.dictionary = new Uint8Array(opt.dictionary); - } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(msg[status]); - } - } - } - } - /** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize, dictionary } } = this; - let status, _mode; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - let allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = binstring2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = inflate(strm, Z_NO_FLUSH); /* no bad return value */ - - if (status === Z_NEED_DICT && dictionary) { - status = inflateSetDictionary(this.strm, dictionary); - } - - if (status === Z_BUF_ERROR && allowBufError === true) { - status = Z_OK; - allowBufError = false; - } - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - if (status === Z_STREAM_END) { - _mode = Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - - /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - - - /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -/* -node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - -Copyright (C) 2012 Eli Skeggs - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - -var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; - -// offset in bytes -var BitReader = function(stream) { - this.stream = stream; - this.bitOffset = 0; - this.curByte = 0; - this.hasByte = false; -}; - -BitReader.prototype._ensureByte = function() { - if (!this.hasByte) { - this.curByte = this.stream.readByte(); - this.hasByte = true; - } -}; - -// reads bits from the buffer -BitReader.prototype.read = function(bits) { - var result = 0; - while (bits > 0) { - this._ensureByte(); - var remaining = 8 - this.bitOffset; - // if we're in a byte - if (bits >= remaining) { - result <<= remaining; - result |= BITMASK[remaining] & this.curByte; - this.hasByte = false; - this.bitOffset = 0; - bits -= remaining; - } else { - result <<= bits; - var shift = remaining - bits; - result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; - this.bitOffset += bits; - bits = 0; - } - } - return result; -}; - -// seek to an arbitrary point in the buffer (expressed in bits) -BitReader.prototype.seek = function(pos) { - var n_bit = pos % 8; - var n_byte = (pos - n_bit) / 8; - this.bitOffset = n_bit; - this.stream.seek(n_byte); - this.hasByte = false; -}; - -// reads 6 bytes worth of data using the read method -BitReader.prototype.pi = function() { - var buf = new Uint8Array(6), i; - for (i = 0; i < buf.length; i++) { - buf[i] = this.read(8); - } - return bufToHex(buf); -}; - -function bufToHex(buf) { - return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); -} - -var bitreader = BitReader; - -/* very simple input/output stream interface */ -var Stream = function() { -}; - -// input streams ////////////// -/** Returns the next byte, or -1 for EOF. */ -Stream.prototype.readByte = function() { - throw new Error("abstract method readByte() not implemented"); -}; -/** Attempts to fill the buffer; returns number of bytes read, or - * -1 for EOF. */ -Stream.prototype.read = function(buffer, bufOffset, length) { - var bytesRead = 0; - while (bytesRead < length) { - var c = this.readByte(); - if (c < 0) { // EOF - return (bytesRead===0) ? -1 : bytesRead; - } - buffer[bufOffset++] = c; - bytesRead++; - } - return bytesRead; -}; -Stream.prototype.seek = function(new_pos) { - throw new Error("abstract method seek() not implemented"); -}; - -// output streams /////////// -Stream.prototype.writeByte = function(_byte) { - throw new Error("abstract method readByte() not implemented"); -}; -Stream.prototype.write = function(buffer, bufOffset, length) { - var i; - for (i=0; i>> 0; // return an unsigned value - }; - - /** - * Update the CRC with a single byte - * @param value The value to update the CRC with - */ - this.updateCRC = function(value) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - }; - - /** - * Update the CRC with a sequence of identical bytes - * @param value The value to update the CRC with - * @param count The number of bytes - */ - this.updateCRCRun = function(value, count) { - while (count-- > 0) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - } - }; - }; - return CRC32; -})(); - -/* -seek-bzip - a pure-javascript module for seeking within bzip2 data - -Copyright (C) 2013 C. Scott Ananian -Copyright (C) 2012 Eli Skeggs -Copyright (C) 2011 Kevin Kwok - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from node-bzip, copyright 2012 Eli Skeggs. -Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - - - - - -var MAX_HUFCODE_BITS = 20; -var MAX_SYMBOLS = 258; -var SYMBOL_RUNA = 0; -var SYMBOL_RUNB = 1; -var MIN_GROUPS = 2; -var MAX_GROUPS = 6; -var GROUP_SIZE = 50; - -var WHOLEPI = "314159265359"; -var SQRTPI = "177245385090"; - -var mtf = function(array, index) { - var src = array[index], i; - for (i = index; i > 0; i--) { - array[i] = array[i-1]; - } - array[0] = src; - return src; -}; - -var Err = { - OK: 0, - LAST_BLOCK: -1, - NOT_BZIP_DATA: -2, - UNEXPECTED_INPUT_EOF: -3, - UNEXPECTED_OUTPUT_EOF: -4, - DATA_ERROR: -5, - OUT_OF_MEMORY: -6, - OBSOLETE_INPUT: -7, - END_OF_BLOCK: -8 -}; -var ErrorMessages = {}; -ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; -ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; -ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; -ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; -ErrorMessages[Err.DATA_ERROR] = "Data error"; -ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; -ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - -var _throw = function(status, optDetail) { - var msg = ErrorMessages[status] || 'unknown error'; - if (optDetail) { msg += ': '+optDetail; } - var e = new TypeError(msg); - e.errorCode = status; - throw e; -}; - -var Bunzip = function(inputStream, outputStream) { - this.writePos = this.writeCurrent = this.writeCount = 0; - - this._start_bunzip(inputStream, outputStream); -}; -Bunzip.prototype._init_block = function() { - var moreBlocks = this._get_next_block(); - if ( !moreBlocks ) { - this.writeCount = -1; - return false; /* no more blocks */ - } - this.blockCRC = new crc32$1(); - return true; -}; -/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ -Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { - /* Ensure that file starts with "BZh['1'-'9']." */ - var buf = new Uint8Array(4); - if (inputStream.read(buf, 0, 4) !== 4 || - String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') - _throw(Err.NOT_BZIP_DATA, 'bad magic'); - - var level = buf[3] - 0x30; - if (level < 1 || level > 9) - _throw(Err.NOT_BZIP_DATA, 'level out of range'); - - this.reader = new bitreader(inputStream); - - /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of - uncompressed data. Allocate intermediate buffer for block. */ - this.dbufSize = 100000 * level; - this.nextoutput = 0; - this.outputStream = outputStream; - this.streamCRC = 0; -}; -Bunzip.prototype._get_next_block = function() { - var i, j, k; - var reader = this.reader; - // this is get_next_block() function from micro-bunzip: - /* Read in header signature and CRC, then validate signature. - (last block signature means CRC is for whole file, return now) */ - var h = reader.pi(); - if (h === SQRTPI) { // last block - return false; /* no more blocks */ - } - if (h !== WHOLEPI) - _throw(Err.NOT_BZIP_DATA); - this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) - this.streamCRC = (this.targetBlockCRC ^ - ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; - /* We can add support for blockRandomised if anybody complains. There was - some code for this in busybox 1.0.0-pre3, but nobody ever noticed that - it didn't actually work. */ - if (reader.read(1)) - _throw(Err.OBSOLETE_INPUT); - var origPointer = reader.read(24); - if (origPointer > this.dbufSize) - _throw(Err.DATA_ERROR, 'initial position out of bounds'); - /* mapping table: if some byte values are never used (encoding things - like ascii text), the compression code removes the gaps to have fewer - symbols to deal with, and writes a sparse bitfield indicating which - values were present. We make a translation table to convert the symbols - back to the corresponding bytes. */ - var t = reader.read(16); - var symToByte = new Uint8Array(256), symTotal = 0; - for (i = 0; i < 16; i++) { - if (t & (1 << (0xF - i))) { - var o = i * 16; - k = reader.read(16); - for (j = 0; j < 16; j++) - if (k & (1 << (0xF - j))) - symToByte[symTotal++] = o + j; - } - } - - /* How many different huffman coding groups does this block use? */ - var groupCount = reader.read(3); - if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) - _throw(Err.DATA_ERROR); - /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding - group. Read in the group selector list, which is stored as MTF encoded - bit runs. (MTF=Move To Front, as each value is used it's moved to the - start of the list.) */ - var nSelectors = reader.read(15); - if (nSelectors === 0) - _throw(Err.DATA_ERROR); - - var mtfSymbol = new Uint8Array(256); - for (i = 0; i < groupCount; i++) - mtfSymbol[i] = i; - - var selectors = new Uint8Array(nSelectors); // was 32768... - - for (i = 0; i < nSelectors; i++) { - /* Get next value */ - for (j = 0; reader.read(1); j++) - if (j >= groupCount) _throw(Err.DATA_ERROR); - /* Decode MTF to get the next selector */ - selectors[i] = mtf(mtfSymbol, j); - } - - /* Read the huffman coding tables for each group, which code for symTotal - literal symbols, plus two run symbols (RUNA, RUNB) */ - var symCount = symTotal + 2; - var groups = [], hufGroup; - for (j = 0; j < groupCount; j++) { - var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); - /* Read huffman code lengths for each symbol. They're stored in - a way similar to mtf; record a starting value for the first symbol, - and an offset from the previous value for everys symbol after that. */ - t = reader.read(5); // lengths - for (i = 0; i < symCount; i++) { - for (;;) { - if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); - /* If first bit is 0, stop. Else second bit indicates whether - to increment or decrement the value. */ - if(!reader.read(1)) - break; - if(!reader.read(1)) - t++; - else - t--; - } - length[i] = t; - } - - /* Find largest and smallest lengths in this group */ - var minLen, maxLen; - minLen = maxLen = length[0]; - for (i = 1; i < symCount; i++) { - if (length[i] > maxLen) - maxLen = length[i]; - else if (length[i] < minLen) - minLen = length[i]; - } - - /* Calculate permute[], base[], and limit[] tables from length[]. - * - * permute[] is the lookup table for converting huffman coded symbols - * into decoded symbols. base[] is the amount to subtract from the - * value of a huffman symbol of a given length when using permute[]. - * - * limit[] indicates the largest numerical value a symbol with a given - * number of bits can have. This is how the huffman codes can vary in - * length: each code with a value>limit[length] needs another bit. - */ - hufGroup = {}; - groups.push(hufGroup); - hufGroup.permute = new Uint16Array(MAX_SYMBOLS); - hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); - hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); - hufGroup.minLen = minLen; - hufGroup.maxLen = maxLen; - /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ - var pp = 0; - for (i = minLen; i <= maxLen; i++) { - temp[i] = hufGroup.limit[i] = 0; - for (t = 0; t < symCount; t++) - if (length[t] === i) - hufGroup.permute[pp++] = t; - } - /* Count symbols coded for at each bit length */ - for (i = 0; i < symCount; i++) - temp[length[i]]++; - /* Calculate limit[] (the largest symbol-coding value at each bit - * length, which is (previous limit<<1)+symbols at this level), and - * base[] (number of symbols to ignore at each bit length, which is - * limit minus the cumulative count of symbols coded for already). */ - pp = t = 0; - for (i = minLen; i < maxLen; i++) { - pp += temp[i]; - /* We read the largest possible symbol size and then unget bits - after determining how many we need, and those extra bits could - be set to anything. (They're noise from future symbols.) At - each level we're really only interested in the first few bits, - so here we set all the trailing to-be-ignored bits to 1 so they - don't affect the value>limit[length] comparison. */ - hufGroup.limit[i] = pp - 1; - pp <<= 1; - t += temp[i]; - hufGroup.base[i + 1] = pp - t; - } - hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ - hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; - hufGroup.base[minLen] = 0; - } - /* We've finished reading and digesting the block header. Now read this - block's huffman coded symbols from the file and undo the huffman coding - and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - - /* Initialize symbol occurrence counters and symbol Move To Front table */ - var byteCount = new Uint32Array(256); - for (i = 0; i < 256; i++) - mtfSymbol[i] = i; - /* Loop through compressed symbols. */ - var runPos = 0, dbufCount = 0, selector = 0, uc; - var dbuf = this.dbuf = new Uint32Array(this.dbufSize); - symCount = 0; - for (;;) { - /* Determine which huffman coding group to use. */ - if (!(symCount--)) { - symCount = GROUP_SIZE - 1; - if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } - hufGroup = groups[selectors[selector++]]; - } - /* Read next huffman-coded symbol. */ - i = hufGroup.minLen; - j = reader.read(i); - for (;;i++) { - if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } - if (j <= hufGroup.limit[i]) - break; - j = (j << 1) | reader.read(1); - } - /* Huffman decode value to get nextSym (with bounds checking) */ - j -= hufGroup.base[i]; - if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } - var nextSym = hufGroup.permute[j]; - /* We have now decoded the symbol, which indicates either a new literal - byte, or a repeated run of the most recent literal byte. First, - check if nextSym indicates a repeated run, and if so loop collecting - how many times to repeat the last literal. */ - if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { - /* If this is the start of a new run, zero out counter */ - if (!runPos){ - runPos = 1; - t = 0; - } - /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at - each bit position, add 1 or 2 instead. For example, - 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. - You can make any bit pattern that way using 1 less symbol than - the basic or 0/1 method (except all bits 0, which would use no - symbols, but a run of length 0 doesn't mean anything in this - context). Thus space is saved. */ - if (nextSym === SYMBOL_RUNA) - t += runPos; - else - t += 2 * runPos; - runPos <<= 1; - continue; - } - /* When we hit the first non-run symbol after a run, we now know - how many times to repeat the last literal, so append that many - copies to our buffer of decoded symbols (dbuf) now. (The last - literal used is the one at the head of the mtfSymbol array.) */ - if (runPos){ - runPos = 0; - if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } - uc = symToByte[mtfSymbol[0]]; - byteCount[uc] += t; - while (t--) - dbuf[dbufCount++] = uc; - } - /* Is this the terminating symbol? */ - if (nextSym > symTotal) - break; - /* At this point, nextSym indicates a new literal character. Subtract - one to get the position in the MTF array at which this literal is - currently to be found. (Note that the result can't be -1 or 0, - because 0 and 1 are RUNA and RUNB. But another instance of the - first symbol in the mtf array, position 0, would have been handled - as part of a run above. Therefore 1 unused mtf position minus - 2 non-literal nextSym values equals -1.) */ - if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } - i = nextSym - 1; - uc = mtf(mtfSymbol, i); - uc = symToByte[uc]; - /* We have our literal byte. Save it into dbuf. */ - byteCount[uc]++; - dbuf[dbufCount++] = uc; - } - /* At this point, we've read all the huffman-coded symbols (and repeated - runs) for this block from the input stream, and decoded them into the - intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. - Now undo the Burrows-Wheeler transform on dbuf. - See http://dogma.net/markn/articles/bwt/bwt.htm - */ - if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } - /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ - j = 0; - for (i = 0; i < 256; i++) { - k = j + byteCount[i]; - byteCount[i] = j; - j = k; - } - /* Figure out what order dbuf would be in if we sorted it. */ - for (i = 0; i < dbufCount; i++) { - uc = dbuf[i] & 0xff; - dbuf[byteCount[uc]] |= (i << 8); - byteCount[uc]++; - } - /* Decode first byte by hand to initialize "previous" byte. Note that it - doesn't get output, and if the first three characters are identical - it doesn't qualify as a run (hence writeRunCountdown=5). */ - var pos = 0, current = 0, run = 0; - if (dbufCount) { - pos = dbuf[origPointer]; - current = (pos & 0xff); - pos >>= 8; - run = -1; - } - this.writePos = pos; - this.writeCurrent = current; - this.writeCount = dbufCount; - this.writeRun = run; - - return true; /* more blocks to come */ -}; -/* Undo burrows-wheeler transform on intermediate buffer to produce output. - If start_bunzip was initialized with out_fd=-1, then up to len bytes of - data are written to outbuf. Return value is number of bytes written or - error (all errors are negative numbers). If out_fd!=-1, outbuf and len - are ignored, data is written to out_fd and return is RETVAL_OK or error. -*/ -Bunzip.prototype._read_bunzip = function(outputBuffer, len) { - var copies, previous, outbyte; - /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully - decoded, which results in this returning RETVAL_LAST_BLOCK, also - equal to -1... Confusing, I'm returning 0 here to indicate no - bytes written into the buffer */ - if (this.writeCount < 0) { return 0; } - var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; - var dbufCount = this.writeCount; this.outputsize; - var run = this.writeRun; - - while (dbufCount) { - dbufCount--; - previous = current; - pos = dbuf[pos]; - current = pos & 0xff; - pos >>= 8; - if (run++ === 3){ - copies = current; - outbyte = previous; - current = -1; - } else { - copies = 1; - outbyte = current; - } - this.blockCRC.updateCRCRun(outbyte, copies); - while (copies--) { - this.outputStream.writeByte(outbyte); - this.nextoutput++; - } - if (current != previous) - run = 0; - } - this.writeCount = dbufCount; - // check CRC - if (this.blockCRC.getCRC() !== this.targetBlockCRC) { - _throw(Err.DATA_ERROR, "Bad block CRC "+ - "(got "+this.blockCRC.getCRC().toString(16)+ - " expected "+this.targetBlockCRC.toString(16)+")"); - } - return this.nextoutput; -}; - -var coerceInputStream = function(input) { - if ('readByte' in input) { return input; } - var inputStream = new stream(); - inputStream.pos = 0; - inputStream.readByte = function() { return input[this.pos++]; }; - inputStream.seek = function(pos) { this.pos = pos; }; - inputStream.eof = function() { return this.pos >= input.length; }; - return inputStream; -}; -var coerceOutputStream = function(output) { - var outputStream = new stream(); - var resizeOk = true; - if (output) { - if (typeof(output)==='number') { - outputStream.buffer = new Uint8Array(output); - resizeOk = false; - } else if ('writeByte' in output) { - return output; - } else { - outputStream.buffer = output; - resizeOk = false; - } - } else { - outputStream.buffer = new Uint8Array(16384); - } - outputStream.pos = 0; - outputStream.writeByte = function(_byte) { - if (resizeOk && this.pos >= this.buffer.length) { - var newBuffer = new Uint8Array(this.buffer.length*2); - newBuffer.set(this.buffer); - this.buffer = newBuffer; - } - this.buffer[this.pos++] = _byte; - }; - outputStream.getBuffer = function() { - // trim buffer - if (this.pos !== this.buffer.length) { - if (!resizeOk) - throw new TypeError('outputsize does not match decoded input'); - var newBuffer = new Uint8Array(this.pos); - newBuffer.set(this.buffer.subarray(0, this.pos)); - this.buffer = newBuffer; - } - return this.buffer; - }; - outputStream._coerced = true; - return outputStream; -}; - -/* Static helper functions */ -// 'input' can be a stream or a buffer -// 'output' can be a stream or a buffer or a number (buffer size) -const decode$2 = function(input, output, multistream) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - - var bz = new Bunzip(inputStream, outputStream); - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - if (bz._init_block()) { - bz._read_bunzip(); - } else { - var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) - if (targetStreamCRC !== bz.streamCRC) { - _throw(Err.DATA_ERROR, "Bad stream CRC "+ - "(got "+bz.streamCRC.toString(16)+ - " expected "+targetStreamCRC.toString(16)+")"); - } - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - } else break; - } - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -const decodeBlock = function(input, pos, output) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - var bz = new Bunzip(inputStream, outputStream); - bz.reader.seek(pos); - /* Fill the decode buffer for the block */ - var moreBlocks = bz._get_next_block(); - if (moreBlocks) { - /* Init the CRC for writing */ - bz.blockCRC = new crc32$1(); - - /* Zero this so the current byte from before the seek is not written */ - bz.writeCopies = 0; - - /* Decompress the block and write to stdout */ - bz._read_bunzip(); - // XXX keep writing? - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -/* Reads bzip2 file from stream or buffer `input`, and invoke - * `callback(position, size)` once for each bzip2 block, - * where position gives the starting position (in *bits*) - * and size gives uncompressed size of the block (in *bytes*). */ -const table = function(input, callback, multistream) { - // make a stream from a buffer, if necessary - var inputStream = new stream(); - inputStream.delegate = coerceInputStream(input); - inputStream.pos = 0; - inputStream.readByte = function() { - this.pos++; - return this.delegate.readByte(); - }; - if (inputStream.delegate.eof) { - inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); - } - var outputStream = new stream(); - outputStream.pos = 0; - outputStream.writeByte = function() { this.pos++; }; - - var bz = new Bunzip(inputStream, outputStream); - var blockSize = bz.dbufSize; - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - - var position = inputStream.pos*8 + bz.reader.bitOffset; - if (bz.reader.hasByte) { position -= 8; } - - if (bz._init_block()) { - var start = outputStream.pos; - bz._read_bunzip(); - callback(position, outputStream.pos - start); - } else { - bz.reader.read(32); // (but we ignore the crc) - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - console.assert(bz.dbufSize === blockSize, - "shouldn't change block size within multistream file"); - } else break; - } - } -}; - -var lib = { - Bunzip, - Stream: stream, - Err, - decode: decode$2, - decodeBlock, - table -}; -var lib_4 = lib.decode; - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the Literal Data Packet (Tag 11) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - */ -class LiteralDataPacket { - static get tag() { - return enums.packet.literalData; - } - - /** - * @param {Date} date - The creation date of the literal package - */ - constructor(date = new Date()) { - this.format = enums.literal.utf8; // default format for literal data packets - this.date = util.normalizeDate(date); - this.text = null; // textual data representation - this.data = null; // literal data representation - this.filename = ''; - } - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param {String | ReadableStream} text - Any native javascript string - * @param {enums.literal} [format] - The format of the string of bytes - */ - setText(text, format = enums.literal.utf8) { - this.format = format; - this.text = text; - this.data = null; - } - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {String | ReadableStream} Literal data as text. - */ - getText(clone = false) { - if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read - this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); - } - return this.text; - } - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param {Uint8Array | ReadableStream} bytes - The string of bytes - * @param {enums.literal} format - The format of the string of bytes - */ - setBytes(bytes, format) { - this.format = format; - this.data = bytes; - this.text = null; - } - - - /** - * Get the byte sequence representing the literal packet data - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {Uint8Array | ReadableStream} A sequence of bytes. - */ - getBytes(clone = false) { - if (this.data === null) { - // encode UTF8 and normalize EOL to \r\n - this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); - } - if (clone) { - return passiveClone(this.data); - } - return this.data; - } - - - /** - * Sets the filename of the literal packet data - * @param {String} filename - Any native javascript string - */ - setFilename(filename) { - this.filename = filename; - } - - - /** - * Get the filename of the literal packet data - * @returns {String} Filename. - */ - getFilename() { - return this.filename; - } - - /** - * Parsing function for a literal data packet (tag 11). - * - * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet - * @returns {Promise} Object representation. - * @async - */ - async read(bytes) { - await parse(bytes, async reader => { - // - A one-octet field that describes how the data is formatted. - const format = await reader.readByte(); // enums.literal - - const filename_len = await reader.readByte(); - this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - - this.date = util.readDate(await reader.readBytes(4)); - - let data = reader.remainder(); - if (isArrayStream(data)) data = await readToEnd(data); - this.setBytes(data, format); - }); - } - - /** - * Creates a Uint8Array representation of the packet, excluding the data - * - * @returns {Uint8Array} Uint8Array representation of the packet. - */ - writeHeader() { - const filename = util.encodeUTF8(this.filename); - const filename_length = new Uint8Array([filename.length]); - - const format = new Uint8Array([this.format]); - const date = util.writeDate(this.date); - - return util.concatUint8Array([format, filename_length, filename, date]); - } - - /** - * Creates a Uint8Array representation of the packet - * - * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. - */ - write() { - const header = this.writeHeader(); - const data = this.getBytes(); - - return util.concat([header, data]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. -const verified = Symbol('verified'); - -// GPG puts the Issuer and Signature subpackets in the unhashed area. -// Tampering with those invalidates the signature, so we still trust them and parse them. -// All other unhashed subpackets are ignored. -const allowedUnhashedSubpackets = new Set([ - enums.signatureSubpacket.issuer, - enums.signatureSubpacket.issuerFingerprint, - enums.signatureSubpacket.embeddedSignature -]); - -/** - * Implementation of the Signature Packet (Tag 2) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - */ -class SignaturePacket { - static get tag() { - return enums.packet.signature; - } - - constructor() { - this.version = null; - /** @type {enums.signature} */ - this.signatureType = null; - /** @type {enums.hash} */ - this.hashAlgorithm = null; - /** @type {enums.publicKey} */ - this.publicKeyAlgorithm = null; - - this.signatureData = null; - this.unhashedSubpackets = []; - this.signedHashValue = null; - - this.created = null; - this.signatureExpirationTime = null; - this.signatureNeverExpires = true; - this.exportable = null; - this.trustLevel = null; - this.trustAmount = null; - this.regularExpression = null; - this.revocable = null; - this.keyExpirationTime = null; - this.keyNeverExpires = null; - this.preferredSymmetricAlgorithms = null; - this.revocationKeyClass = null; - this.revocationKeyAlgorithm = null; - this.revocationKeyFingerprint = null; - this.issuerKeyID = new KeyID(); - this.rawNotations = []; - this.notations = {}; - this.preferredHashAlgorithms = null; - this.preferredCompressionAlgorithms = null; - this.keyServerPreferences = null; - this.preferredKeyServer = null; - this.isPrimaryUserID = null; - this.policyURI = null; - this.keyFlags = null; - this.signersUserID = null; - this.reasonForRevocationFlag = null; - this.reasonForRevocationString = null; - this.features = null; - this.signatureTargetPublicKeyAlgorithm = null; - this.signatureTargetHashAlgorithm = null; - this.signatureTargetHash = null; - this.embeddedSignature = null; - this.issuerKeyVersion = null; - this.issuerFingerprint = null; - this.preferredAEADAlgorithms = null; - - this.revoked = null; - this[verified] = null; - } - - /** - * parsing function for a signature packet (tag 2). - * @param {String} bytes - Payload of a tag 2 packet - * @returns {SignaturePacket} Object representation. - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); - } - - this.signatureType = bytes[i++]; - this.publicKeyAlgorithm = bytes[i++]; - this.hashAlgorithm = bytes[i++]; - - // hashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), true); - if (!this.created) { - throw new Error('Missing signature creation time subpacket.'); - } - - // A V4 signature hashes the packet body - // starting from its first field, the version number, through the end - // of the hashed subpacket data. Thus, the fields hashed are the - // signature version, the signature type, the public-key algorithm, the - // hash algorithm, the hashed subpacket length, and the hashed - // subpacket body. - this.signatureData = bytes.subarray(0, i); - - // unhashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - - // Two-octet field holding left 16 bits of signed hash value. - this.signedHashValue = bytes.subarray(i, i + 2); - i += 2; - - this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length)); - } - - /** - * @returns {Uint8Array | ReadableStream} - */ - writeParams() { - if (this.params instanceof Promise) { - return fromAsync( - async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params) - ); - } - return mod.serializeParams(this.publicKeyAlgorithm, this.params); - } - - write() { - const arr = []; - arr.push(this.signatureData); - arr.push(this.writeUnhashedSubPackets()); - arr.push(this.signedHashValue); - arr.push(this.writeParams()); - return util.concat(arr); - } - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param {SecretKeyPacket} key - Private key used to sign the message. - * @param {Object} data - Contains packets to be signed. - * @param {Date} [date] - The signature creation time. - * @param {Boolean} [detached] - Whether to create a detached signature - * @throws {Error} if signing failed - * @async - */ - async sign(key, data, date = new Date(), detached = false) { - if (key.version === 5) { - this.version = 5; - } else { - this.version = 4; - } - const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; - - this.created = util.normalizeDate(date); - this.issuerKeyVersion = key.version; - this.issuerFingerprint = key.getFingerprintBytes(); - this.issuerKeyID = key.getKeyID(); - - // Add hashed subpackets - arr.push(this.writeHashedSubPackets()); - - // Remove unhashed subpackets, in case some allowed unhashed - // subpackets existed, in order not to duplicate them (in both - // the hashed and unhashed subpackets) when re-signing. - this.unhashedSubpackets = []; - - this.signatureData = util.concat(arr); - - const toHash = this.toHash(this.signatureType, data, detached); - const hash = await this.hash(this.signatureType, data, toHash, detached); - - this.signedHashValue = slice(clone(hash), 0, 2); - const signed = async () => mod.signature.sign( - this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) - ); - if (util.isStream(hash)) { - this.params = signed(); - } else { - this.params = await signed(); - - // Store the fact that this signature is valid, e.g. for when we call `await - // getLatestValidSignature(this.revocationSignatures, key, data)` later. - // Note that this only holds up if the key and data passed to verify are the - // same as the ones passed to sign. - this[verified] = true; - } - } - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeHashedSubPackets() { - const sub = enums.signatureSubpacket; - const arr = []; - let bytes; - if (this.created === null) { - throw new Error('Missing signature creation time'); - } - arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); - if (this.signatureExpirationTime !== null) { - arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); - } - if (this.exportable !== null) { - arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); - } - if (this.trustLevel !== null) { - bytes = new Uint8Array([this.trustLevel, this.trustAmount]); - arr.push(writeSubPacket(sub.trustSignature, true, bytes)); - } - if (this.regularExpression !== null) { - arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); - } - if (this.revocable !== null) { - arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); - } - if (this.keyExpirationTime !== null) { - arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); - } - if (this.preferredSymmetricAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); - arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); - } - if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); - bytes = util.concat([bytes, this.revocationKeyFingerprint]); - arr.push(writeSubPacket(sub.revocationKey, false, bytes)); - } - if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { - // If the version of [the] key is greater than 4, this subpacket - // MUST NOT be included in the signature. - arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write())); - } - this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { - bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; - const encodedName = util.encodeUTF8(name); - // 2 octets of name length - bytes.push(util.writeNumber(encodedName.length, 2)); - // 2 octets of value length - bytes.push(util.writeNumber(value.length, 2)); - bytes.push(encodedName); - bytes.push(value); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.notationData, critical, bytes)); - }); - if (this.preferredHashAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); - arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); - } - if (this.preferredCompressionAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); - arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); - } - if (this.keyServerPreferences !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); - arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); - } - if (this.preferredKeyServer !== null) { - arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); - } - if (this.isPrimaryUserID !== null) { - arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); - } - if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); - } - if (this.keyFlags !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); - arr.push(writeSubPacket(sub.keyFlags, true, bytes)); - } - if (this.signersUserID !== null) { - arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); - } - if (this.reasonForRevocationFlag !== null) { - bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); - arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); - } - if (this.features !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); - arr.push(writeSubPacket(sub.features, false, bytes)); - } - if (this.signatureTargetPublicKeyAlgorithm !== null) { - bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(util.stringToUint8Array(this.signatureTargetHash)); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); - } - if (this.embeddedSignature !== null) { - arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); - } - if (this.issuerFingerprint !== null) { - bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes)); - } - if (this.preferredAEADAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); - arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); - } - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - /** - * Creates an Uint8Array containing the unhashed subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeUnhashedSubPackets() { - const arr = []; - this.unhashedSubpackets.forEach(data => { - arr.push(writeSimpleLength(data.length)); - arr.push(data); - }); - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - // V4 signature sub packets - readSubPacket(bytes, hashed = true) { - let mypos = 0; - - // The leftmost bit denotes a "critical" packet - const critical = !!(bytes[mypos] & 0x80); - const type = bytes[mypos] & 0x7F; - - if (!hashed) { - this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length)); - if (!allowedUnhashedSubpackets.has(type)) { - return; - } - } - - mypos++; - - // subpacket type - switch (type) { - case enums.signatureSubpacket.signatureCreationTime: - // Signature Creation Time - this.created = util.readDate(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.signatureExpirationTime: { - // Signature Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.signatureNeverExpires = seconds === 0; - this.signatureExpirationTime = seconds; - - break; - } - case enums.signatureSubpacket.exportableCertification: - // Exportable Certification - this.exportable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.trustSignature: - // Trust Signature - this.trustLevel = bytes[mypos++]; - this.trustAmount = bytes[mypos++]; - break; - case enums.signatureSubpacket.regularExpression: - // Regular Expression - this.regularExpression = bytes[mypos]; - break; - case enums.signatureSubpacket.revocable: - // Revocable - this.revocable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.keyExpirationTime: { - // Key Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.keyExpirationTime = seconds; - this.keyNeverExpires = seconds === 0; - - break; - } - case enums.signatureSubpacket.preferredSymmetricAlgorithms: - // Preferred Symmetric Algorithms - this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.revocationKey: - // Revocation Key - // (1 octet of class, 1 octet of public-key algorithm ID, 20 - // octets of - // fingerprint) - this.revocationKeyClass = bytes[mypos++]; - this.revocationKeyAlgorithm = bytes[mypos++]; - this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); - break; - - case enums.signatureSubpacket.issuer: - // Issuer - this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); - break; - - case enums.signatureSubpacket.notationData: { - // Notation Data - const humanReadable = !!(bytes[mypos] & 0x80); - - // We extract key/value tuple from the byte stream. - mypos += 4; - const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - - const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); - const value = bytes.subarray(mypos + m, mypos + m + n); - - this.rawNotations.push({ name, humanReadable, value, critical }); - - if (humanReadable) { - this.notations[name] = util.decodeUTF8(value); - } - break; - } - case enums.signatureSubpacket.preferredHashAlgorithms: - // Preferred Hash Algorithms - this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredCompressionAlgorithms: - // Preferred Compression Algorithms - this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.keyServerPreferences: - // Key Server Preferences - this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredKeyServer: - // Preferred Key Server - this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.primaryUserID: - // Primary User ID - this.isPrimaryUserID = bytes[mypos++] !== 0; - break; - case enums.signatureSubpacket.policyURI: - // Policy URI - this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.keyFlags: - // Key Flags - this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signersUserID: - // Signer's User ID - this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.reasonForRevocation: - // Reason for Revocation - this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.features: - // Features - this.features = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signatureTarget: { - // Signature Target - // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) - this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; - this.signatureTargetHashAlgorithm = bytes[mypos++]; - - const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm); - - this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); - break; - } - case enums.signatureSubpacket.embeddedSignature: - // Embedded Signature - this.embeddedSignature = new SignaturePacket(); - this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.issuerFingerprint: - // Issuer Fingerprint - this.issuerKeyVersion = bytes[mypos++]; - this.issuerFingerprint = bytes.subarray(mypos, bytes.length); - if (this.issuerKeyVersion === 5) { - this.issuerKeyID.read(this.issuerFingerprint); - } else { - this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); - } - break; - case enums.signatureSubpacket.preferredAEADAlgorithms: - // Preferred AEAD Algorithms - this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - default: { - const err = new Error(`Unknown signature subpacket type ${type}`); - if (critical) { - throw err; - } else { - util.printDebug(err); - } - } - } - } - - readSubPackets(bytes, trusted = true, config) { - // Two-octet scalar octet count for following subpacket data. - const subpacketLength = util.readNumber(bytes.subarray(0, 2)); - - let i = 2; - - // subpacket data set (zero or more subpackets) - while (i < 2 + subpacketLength) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); - - i += len.len; - } - - return i; - } - - // Produces data to produce signature on - toSign(type, data) { - const t = enums.signature; - - switch (type) { - case t.binary: - if (data.text !== null) { - return util.encodeUTF8(data.getText(true)); - } - return data.getBytes(true); - - case t.text: { - const bytes = data.getBytes(true); - // normalize EOL to \r\n - return util.canonicalizeEOL(bytes); - } - case t.standalone: - return new Uint8Array(0); - - case t.certGeneric: - case t.certPersona: - case t.certCasual: - case t.certPositive: - case t.certRevocation: { - let packet; - let tag; - - if (data.userID) { - tag = 0xB4; - packet = data.userID; - } else if (data.userAttribute) { - tag = 0xD1; - packet = data.userAttribute; - } else { - throw new Error('Either a userID or userAttribute packet needs to be ' + - 'supplied for certification.'); - } - - const bytes = packet.write(); - - return util.concat([this.toSign(t.key, data), - new Uint8Array([tag]), - util.writeNumber(bytes.length, 4), - bytes]); - } - case t.subkeyBinding: - case t.subkeyRevocation: - case t.keyBinding: - return util.concat([this.toSign(t.key, data), this.toSign(t.key, { - key: data.bind - })]); - - case t.key: - if (data.key === undefined) { - throw new Error('Key packet is required for this signature.'); - } - return data.key.writeForHash(this.version); - - case t.keyRevocation: - return this.toSign(t.key, data); - case t.timestamp: - return new Uint8Array(0); - case t.thirdParty: - throw new Error('Not implemented'); - default: - throw new Error('Unknown signature type.'); - } - } - - calculateTrailer(data, detached) { - let length = 0; - return transform(clone(this.signatureData), value => { - length += value.length; - }, () => { - const arr = []; - if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { - if (detached) { - arr.push(new Uint8Array(6)); - } else { - arr.push(data.writeHeader()); - } - } - arr.push(new Uint8Array([this.version, 0xFF])); - if (this.version === 5) { - arr.push(new Uint8Array(4)); - } - arr.push(util.writeNumber(length, 4)); - // For v5, this should really be writeNumber(length, 8) rather than the - // hardcoded 4 zero bytes above - return util.concat(arr); - }); - } - - toHash(signatureType, data, detached = false) { - const bytes = this.toSign(signatureType, data); - - return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); - } - - async hash(signatureType, data, toHash, detached = false) { - if (!toHash) toHash = this.toHash(signatureType, data, detached); - return mod.hash.digest(this.hashAlgorithm, toHash); - } - - /** - * verifies the signature packet. Note: not all signature types are implemented - * @param {PublicSubkeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature - * @param {module:enums.signature} signatureType - Expected signature type - * @param {Uint8Array|Object} data - Data which on the signature applies - * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration - * @param {Boolean} [detached] - Whether to verify a detached signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if signature validation failed - * @async - */ - async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { - if (!this.issuerKeyID.equals(key.getKeyID())) { - throw new Error('Signature was not issued by the given public key'); - } - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); - } - - const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; - // Cryptographic validity is cached after one successful verification. - // However, for message signatures, we always re-verify, since the passed `data` can change - const skipVerify = this[verified] && !isMessageSignature; - if (!skipVerify) { - let toHash; - let hash; - if (this.hashed) { - hash = await this.hashed; - } else { - toHash = this.toHash(signatureType, data, detached); - hash = await this.hash(signatureType, data, toHash); - } - hash = await readToEnd(hash); - if (this.signedHashValue[0] !== hash[0] || - this.signedHashValue[1] !== hash[1]) { - throw new Error('Signed digest did not match'); - } - - this.params = await this.params; - - this[verified] = await mod.signature.verify( - this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, - toHash, hash - ); - - if (!this[verified]) { - throw new Error('Signature verification failed'); - } - } - - const normDate = util.normalizeDate(date); - if (normDate && this.created > normDate) { - throw new Error('Signature creation time is in the future'); - } - if (normDate && normDate >= this.getExpirationTime()) { - throw new Error('Signature is expired'); - } - if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { - throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && - [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { - throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - this.rawNotations.forEach(({ name, critical }) => { - if (critical && (config$1.knownNotations.indexOf(name) < 0)) { - throw new Error(`Unknown critical notation: ${name}`); - } - }); - if (this.revocationKeyClass !== null) { - throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); - } - } - - /** - * Verifies signature expiration date - * @param {Date} [date] - Use the given date for verification instead of the current time - * @returns {Boolean} True if expired. - */ - isExpired(date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - return !(this.created <= normDate && normDate < this.getExpirationTime()); - } - return false; - } - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns {Date | Infinity} Expiration time. - */ - getExpirationTime() { - return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); - } -} - -/** - * Creates a Uint8Array representation of a sub signature packet - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} - * @param {Integer} type - Subpacket signature type. - * @param {Boolean} critical - Whether the subpacket should be critical. - * @param {String} data - Data to be included - * @returns {Uint8Array} The signature subpacket. - * @private - */ -function writeSubPacket(type, critical, data) { - const arr = []; - arr.push(writeSimpleLength(data.length + 1)); - arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); - arr.push(data); - return util.concat(arr); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -const VERSION = 3; - -/** - * Implementation of the One-Pass Signature Packets (Tag 4) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ -class OnePassSignaturePacket { - static get tag() { - return enums.packet.onePassSignature; - } - - constructor() { - /** A one-octet version number. The current version is 3. */ - this.version = null; - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - * @type {enums.signature} - - */ - this.signatureType = null; - /** - * A one-octet number describing the hash algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} - * @type {enums.hash} - */ - this.hashAlgorithm = null; - /** - * A one-octet number describing the public-key algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} - * @type {enums.publicKey} - */ - this.publicKeyAlgorithm = null; - /** An eight-octet number holding the Key ID of the signing key. */ - this.issuerKeyID = null; - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - this.flags = null; - } - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param {Uint8Array} bytes - Payload of a tag 4 packet - * @returns {OnePassSignaturePacket} Object representation. - */ - read(bytes) { - let mypos = 0; - // A one-octet version number. The current version is 3. - this.version = bytes[mypos++]; - if (this.version !== VERSION) { - throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); - } - - // A one-octet signature type. Signature types are described in - // Section 5.2.1. - this.signatureType = bytes[mypos++]; - - // A one-octet number describing the hash algorithm used. - this.hashAlgorithm = bytes[mypos++]; - - // A one-octet number describing the public-key algorithm used. - this.publicKeyAlgorithm = bytes[mypos++]; - - // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyID = new KeyID(); - this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); - mypos += 8; - - // A one-octet number holding a flag showing whether the signature - // is nested. A zero value indicates that the next packet is - // another One-Pass Signature packet that describes another - // signature to be applied to the same message data. - this.flags = bytes[mypos++]; - return this; - } - - /** - * creates a string representation of a one-pass signature packet - * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. - */ - write() { - const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]); - - const end = new Uint8Array([this.flags]); - - return util.concatUint8Array([start, this.issuerKeyID.write(), end]); - } - - calculateTrailer(...args) { - return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); - } - - async verify() { - const correspondingSig = await this.correspondingSig; - if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { - throw new Error('Corresponding signature packet missing'); - } - if ( - correspondingSig.signatureType !== this.signatureType || - correspondingSig.hashAlgorithm !== this.hashAlgorithm || - correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyID.equals(this.issuerKeyID) - ) { - throw new Error('Corresponding signature packet does not match one-pass signature packet'); - } - correspondingSig.hashed = this.hashed; - return correspondingSig.verify.apply(correspondingSig, arguments); - } -} - -OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; -OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; -OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; - -/** - * Instantiate a new packet given its tag - * @function newPacketFromTag - * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @returns {Object} New packet object with type based on tag - * @throws {Error|UnsupportedError} for disallowed or unknown packets - */ -function newPacketFromTag(tag, allowedPackets) { - if (!allowedPackets[tag]) { - // distinguish between disallowed packets and unknown ones - let packetType; - try { - packetType = enums.read(enums.packet, tag); - } catch (e) { - throw new UnsupportedError(`Unknown packet type with tag: ${tag}`); - } - throw new Error(`Packet not allowed in this context: ${packetType}`); - } - return new allowedPackets[tag](); -} - -/** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - * @extends Array - */ -class PacketList extends Array { - /** - * Parses the given binary data and returns a list of packets. - * Equivalent to calling `read` on an empty PacketList instance. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @returns {PacketList} parsed list of packets - * @throws on parsing errors - * @async - */ - static async fromBinary(bytes, allowedPackets, config$1 = config) { - const packets = new PacketList(); - await packets.read(bytes, allowedPackets, config$1); - return packets; - } - - /** - * Reads a stream of binary data and interprets it as a list of packets. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @throws on parsing errors - * @async - */ - async read(bytes, allowedPackets, config$1 = config) { - if (config$1.additionalAllowedPackets.length) { - allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; - } - this.stream = transformPair(bytes, async (readable, writable) => { - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const done = await readPackets(readable, async parsed => { - try { - if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) { - // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: - // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 - // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 - return; - } - const packet = newPacketFromTag(parsed.tag, allowedPackets); - packet.packets = new PacketList(); - packet.fromStream = util.isStream(parsed.packet); - await packet.read(parsed.packet, config$1); - await writer.write(packet); - } catch (e) { - const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; - const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); - if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { - // The packets that support streaming are the ones that contain message data. - // Those are also the ones we want to be more strict about and throw on parse errors - // (since we likely cannot process the message without these packets anyway). - await writer.abort(e); - } else { - const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); - await writer.write(unparsedPacket); - } - util.printDebugError(e); - } - }); - if (done) { - await writer.ready; - await writer.close(); - return; - } - } - } catch (e) { - await writer.abort(e); - } - }); - - // Wait until first few packets have been read - const reader = getReader(this.stream); - while (true) { - const { done, value } = await reader.read(); - if (!done) { - this.push(value); - } else { - this.stream = null; - } - if (done || supportsStreaming(value.constructor.tag)) { - break; - } - } - reader.releaseLock(); - } - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. - */ - write() { - const arr = []; - - for (let i = 0; i < this.length; i++) { - const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; - const packetbytes = this[i].write(); - if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { - let buffer = []; - let bufferLength = 0; - const minLength = 512; - arr.push(writeTag(tag)); - arr.push(transform(packetbytes, value => { - buffer.push(value); - bufferLength += value.length; - if (bufferLength >= minLength) { - const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); - const chunkSize = 2 ** powerOf2; - const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); - buffer = [bufferConcat.subarray(1 + chunkSize)]; - bufferLength = buffer[0].length; - return bufferConcat.subarray(0, 1 + chunkSize); - } - }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); - } else { - if (util.isStream(packetbytes)) { - let length = 0; - arr.push(transform(clone(packetbytes), value => { - length += value.length; - }, () => writeHeader(tag, length))); - } else { - arr.push(writeHeader(tag, packetbytes.length)); - } - arr.push(packetbytes); - } - } - - return util.concat(arr); - } - - /** - * Creates a new PacketList with all packets matching the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {PacketList} - */ - filterByTag(...tags) { - const filtered = new PacketList(); - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(this[i].constructor.tag))) { - filtered.push(this[i]); - } - } - - return filtered; - } - - /** - * Traverses packet list and returns first packet with matching tag - * @param {module:enums.packet} tag - The packet tag - * @returns {Packet|undefined} - */ - findPacket(tag) { - return this.find(packet => packet.constructor.tag === tag); - } - - /** - * Find indices of packets with the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {Integer[]} packet indices - */ - indexOfTag(...tags) { - const tagIndex = []; - const that = this; - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(that[i].constructor.tag))) { - tagIndex.push(i); - } - } - return tagIndex; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Compressed Data packet can contain the following packet types -const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -/** - * Implementation of the Compressed Data Packet (Tag 8) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ -class CompressedDataPacket { - static get tag() { - return enums.packet.compressedData; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * List of packets - * @type {PacketList} - */ - this.packets = null; - /** - * Compression algorithm - * @type {enums.compression} - */ - this.algorithm = config$1.preferredCompressionAlgorithm; - - /** - * Compressed packet data - * @type {Uint8Array | ReadableStream} - */ - this.compressed = null; - - /** - * zip/zlib compression level, between 1 and 9 - */ - this.deflateLevel = config$1.deflateLevel; - } - - /** - * Parsing function for the packet. - * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async read(bytes, config$1 = config) { - await parse(bytes, async reader => { - - // One octet that gives the algorithm used to compress the packet. - this.algorithm = await reader.readByte(); - - // Compressed data, which makes up the remainder of the packet. - this.compressed = reader.remainder(); - - await this.decompress(config$1); - }); - } - - - /** - * Return the compressed packet. - * @returns {Uint8Array | ReadableStream} Binary compressed packet. - */ - write() { - if (this.compressed === null) { - this.compress(); - } - - return util.concat([new Uint8Array([this.algorithm]), this.compressed]); - } - - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async decompress(config$1 = config) { - const compressionName = enums.read(enums.compression, this.algorithm); - const decompressionFn = decompress_fns[compressionName]; - if (!decompressionFn) { - throw new Error(`${compressionName} decompression not supported`); - } - - this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1); - } - - /** - * Compress the packet data (member decompressedData) - */ - compress() { - const compressionName = enums.read(enums.compression, this.algorithm); - const compressionFn = compress_fns[compressionName]; - if (!compressionFn) { - throw new Error(`${compressionName} compression not supported`); - } - - this.compressed = compressionFn(this.packets.write(), this.deflateLevel); - } -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -const nodeZlib = util.getNodeZlib(); - -function uncompressed(data) { - return data; -} - -function node_zlib(func, create, options = {}) { - return function (data) { - if (!util.isStream(data) || isArrayStream(data)) { - return fromAsync(() => readToEnd(data).then(data => { - return new Promise((resolve, reject) => { - func(data, options, (err, result) => { - if (err) return reject(err); - resolve(result); - }); - }); - })); - } - return nodeToWeb(webToNode(data).pipe(create(options))); - }; -} - -function pako_zlib(constructor, options = {}) { - return function(data) { - const obj = new constructor(options); - return transform(data, value => { - if (value.length) { - obj.push(value, Z_SYNC_FLUSH); - return obj.result; - } - }, () => { - if (constructor === Deflate) { - obj.push([], Z_FINISH); - return obj.result; - } - }); - }; -} - -function bzip2(func) { - return function(data) { - return fromAsync(async () => func(await readToEnd(data))); - }; -} - -const compress_fns = nodeZlib ? { - zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed) -} : { - zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed) -}; - -const decompress_fns = nodeZlib ? { - uncompressed: uncompressed, - zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw), - zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -} : { - uncompressed: uncompressed, - zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), - zlib: /*#__PURE__*/ pako_zlib(Inflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -}; - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A SEIP packet can contain the following packet types -const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$1 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ -class SymEncryptedIntegrityProtectedDataPacket { - static get tag() { - return enums.packet.symEncryptedIntegrityProtectedData; - } - - constructor() { - this.version = VERSION$1; - this.encrypted = null; - this.packets = null; - } - - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - // - A one-octet version number. The only currently defined value is 1. - if (version !== VERSION$1) { - throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`); - } - - // - Encrypted data, the output of the selected symmetric-key cipher - // operating in Cipher Feedback mode with shift amount equal to the - // block size of the cipher (CFB-n where n is the block size). - this.encrypted = reader.remainder(); - }); - } - - write() { - return util.concat([new Uint8Array([VERSION$1]), this.encrypted]); - } - - /** - * Encrypt the payload in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on encryption failure - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - - let bytes = this.packets.write(); - if (isArrayStream(bytes)) bytes = await readToEnd(bytes); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - - const tohash = util.concat([prefix, bytes, mdc]); - const hash = await mod.hash.sha1(passiveClone(tohash)); - const plaintext = util.concat([tohash, hash]); - - this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); - return true; - } - - /** - * Decrypts the encrypted data contained in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on decryption failure - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - let encrypted = clone(this.encrypted); - if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); - - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - const realHash = slice(passiveClone(decrypted), -20); - const tohash = slice(decrypted, 0, -20); - const verifyHash = Promise.all([ - readToEnd(await mod.hash.sha1(passiveClone(tohash))), - readToEnd(realHash) - ]).then(([hash, mdc]) => { - if (!util.equalsUint8Array(hash, mdc)) { - throw new Error('Modification detected.'); - } - return new Uint8Array(); - }); - const bytes = slice(tohash, blockSize + 2); // Remove random prefix - let packetbytes = slice(bytes, 0, -2); // Remove MDC packet - packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); - if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { - packetbytes = await readToEnd(packetbytes); - } - this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1); - return true; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -// An AEAD-encrypted Data packet can contain the following packet types -const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$2 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ -class AEADEncryptedDataPacket { - static get tag() { - return enums.packet.aeadEncryptedData; - } - - constructor() { - this.version = VERSION$2; - /** @type {enums.symmetric} */ - this.cipherAlgorithm = null; - /** @type {enums.aead} */ - this.aeadAlgorithm = enums.aead.eax; - this.chunkSizeByte = null; - this.iv = null; - this.encrypted = null; - this.packets = null; - } - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param {Uint8Array | ReadableStream} bytes - * @throws {Error} on parsing failure - */ - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - if (version !== VERSION$2) { // The only currently defined value is 1. - throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); - } - this.cipherAlgorithm = await reader.readByte(); - this.aeadAlgorithm = await reader.readByte(); - this.chunkSizeByte = await reader.readByte(); - - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = await reader.readBytes(mode.ivLength); - this.encrypted = reader.remainder(); - }); - } - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns {Uint8Array | ReadableStream} The encrypted payload. - */ - write() { - return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); - } - - /** - * Decrypt the encrypted payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.packets = await PacketList.fromBinary( - await this.crypt('decrypt', key, clone(this.encrypted)), - allowedPackets$2, - config$1 - ); - } - - /** - * Encrypt the packet payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.cipherAlgorithm = sessionKeyAlgorithm; - - const { ivLength } = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV - this.chunkSizeByte = config$1.aeadChunkSizeByte; - const data = this.packets.write(); - this.encrypted = await this.crypt('encrypt', key, data); - } - - /** - * En/decrypt the payload. - * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt - * @param {Uint8Array} key - The session key used to en/decrypt the payload - * @param {Uint8Array | ReadableStream} data - The data to en/decrypt - * @returns {Promise>} - * @async - */ - async crypt(fn, key, data) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const modeInstance = await mode(this.cipherAlgorithm, key); - const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; - const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; - const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) - const adataBuffer = new ArrayBuffer(21); - const adataArray = new Uint8Array(adataBuffer, 0, 13); - const adataTagArray = new Uint8Array(adataBuffer); - const adataView = new DataView(adataBuffer); - const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0); - let chunkIndex = 0; - let latestPromise = Promise.resolve(); - let cryptedBytes = 0; - let queuedBytes = 0; - const iv = this.iv; - return transformPair(data, async (readable, writable) => { - if (util.isStream(readable) !== 'array') { - const buffer = new TransformStream({}, { - highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6), - size: array => array.length - }); - pipe(buffer.readable, writable); - writable = buffer.writable; - } - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); - const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); - chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); - let cryptedPromise; - let done; - if (!chunkIndex || chunk.length) { - reader.unshift(finalChunk); - cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray); - queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; - } else { - // After the last chunk, we either encrypt a final, empty - // data chunk to get the final authentication tag or - // validate that final authentication tag. - adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...) - cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray); - queuedBytes += tagLengthIfEncrypting; - done = true; - } - cryptedBytes += chunk.length - tagLengthIfDecrypting; - // eslint-disable-next-line no-loop-func - latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { - await writer.ready; - await writer.write(crypted); - queuedBytes -= crypted.length; - }).catch(err => writer.abort(err)); - if (done || queuedBytes > writer.desiredSize) { - await latestPromise; // Respect backpressure - } - if (!done) { - adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) - } else { - await writer.close(); - break; - } - } - } catch (e) { - await writer.abort(e); - } - }); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -const VERSION$3 = 3; - -/** - * Public-Key Encrypted Session Key Packets (Tag 1) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ -class PublicKeyEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.publicKeyEncryptedSessionKey; - } - - constructor() { - this.version = 3; - - this.publicKeyID = new KeyID(); - this.publicKeyAlgorithm = null; - - this.sessionKey = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = null; - - /** @type {Object} */ - this.encrypted = {}; - } - - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * - * @param {Uint8Array} bytes - Payload of a tag 1 packet - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - if (this.version !== VERSION$3) { - throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); - } - i += this.publicKeyID.read(bytes.subarray(i)); - this.publicKeyAlgorithm = bytes[i++]; - this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version); - if (this.publicKeyAlgorithm === enums.publicKey.x25519) { - this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); - } - } - - /** - * Create a binary representation of a tag 1 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const arr = [ - new Uint8Array([this.version]), - this.publicKeyID.write(), - new Uint8Array([this.publicKeyAlgorithm]), - mod.serializeParams(this.publicKeyAlgorithm, this.encrypted) - ]; - - return util.concatUint8Array(arr); - } - - /** - * Encrypt session key packet - * @param {PublicKeyPacket} key - Public key - * @throws {Error} if encryption failed - * @async - */ - async encrypt(key) { - const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); - const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey); - this.encrypted = await mod.publicKeyEncrypt( - algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes()); - } - - /** - * Decrypts the session key (only for public key encrypted session key packets (tag 1) - * @param {SecretKeyPacket} key - decrypted private key - * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. - * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } - * @throws {Error} if decryption failed, unless `randomSessionKey` is given - * @async - */ - async decrypt(key, randomSessionKey) { - // check that session key algo matches the secret key algo - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Decryption error'); - } - - const randomPayload = randomSessionKey ? - encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : - null; - const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload); - - const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); - - // v3 Montgomery curves have cleartext cipher algo - if (this.publicKeyAlgorithm !== enums.publicKey.x25519) { - this.sessionKeyAlgorithm = sessionKeyAlgorithm; - } - this.sessionKey = sessionKey; - } -} - - -function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // add checksum - return util.concatUint8Array([ - new Uint8Array([cipherAlgo]), - sessionKeyData, - util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) - ]); - } - case enums.publicKey.x25519: - return sessionKeyData; - default: - throw new Error('Unsupported public key algorithm'); - } -} - - -function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // verify checksum in constant time - const result = decryptedData.subarray(0, decryptedData.length - 2); - const checksum = decryptedData.subarray(decryptedData.length - 2); - const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); - const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; - const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; - if (randomSessionKey) { - // We must not leak info about the validity of the decrypted checksum or cipher algo. - // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. - const isValidPayload = isValidChecksum & - decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & - decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; - return { - sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), - sessionKeyAlgorithm: util.selectUint8( - isValidPayload, - decryptedSessionKey.sessionKeyAlgorithm, - randomSessionKey.sessionKeyAlgorithm - ) - }; - } else { - const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm); - if (isValidPayload) { - return decryptedSessionKey; - } else { - throw new Error('Decryption error'); - } - } - } - case enums.publicKey.x25519: - return { - sessionKey: decryptedData - }; - default: - throw new Error('Unsupported public key algorithm'); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -class S2K { - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * Hash function identifier, or 0 for gnu-dummy keys - * @type {module:enums.hash | 0} - */ - this.algorithm = enums.hash.sha256; - /** - * enums.s2k identifier or 'gnu-dummy' - * @type {String} - */ - this.type = 'iterated'; - /** @type {Integer} */ - this.c = config$1.s2kIterationCountByte; - /** Eight bytes of salt in a binary string. - * @type {Uint8Array} - */ - this.salt = null; - } - - getCount() { - // Exponent bias, defined in RFC4880 - const expbias = 6; - - return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); - } - - /** - * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param {Uint8Array} bytes - Payload of string-to-key specifier - * @returns {Integer} Actual length of the object. - */ - read(bytes) { - let i = 0; - try { - this.type = enums.read(enums.s2k, bytes[i++]); - } catch (err) { - throw new UnsupportedError('Unknown S2K type.'); - } - this.algorithm = bytes[i++]; - - switch (this.type) { - case 'simple': - break; - - case 'salted': - this.salt = bytes.subarray(i, i + 8); - i += 8; - break; - - case 'iterated': - this.salt = bytes.subarray(i, i + 8); - i += 8; - - // Octet 10: count, a one-octet, coded value - this.c = bytes[i++]; - break; - - case 'gnu': - if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { - i += 3; // GNU - const gnuExtType = 1000 + bytes[i++]; - if (gnuExtType === 1001) { - this.type = 'gnu-dummy'; - // GnuPG extension mode 1001 -- don't write secret key at all - } else { - throw new UnsupportedError('Unknown s2k gnu protection mode.'); - } - } else { - throw new UnsupportedError('Unknown s2k type.'); - } - break; - - default: - throw new UnsupportedError('Unknown s2k type.'); // unreachable - } - - return i; - } - - /** - * Serializes s2k information - * @returns {Uint8Array} Binary representation of s2k. - */ - write() { - if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); - } - const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; - - switch (this.type) { - case 'simple': - break; - case 'salted': - arr.push(this.salt); - break; - case 'iterated': - arr.push(this.salt); - arr.push(new Uint8Array([this.c])); - break; - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - - return util.concatUint8Array(arr); - } - - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param {String} passphrase - Passphrase containing user input - * @returns {Promise} Produced key with a length corresponding to. - * hashAlgorithm hash length - * @async - */ - async produceKey(passphrase, numBytes) { - passphrase = util.encodeUTF8(passphrase); - - const arr = []; - let rlength = 0; - - let prefixlen = 0; - while (rlength < numBytes) { - let toHash; - switch (this.type) { - case 'simple': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); - break; - case 'salted': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); - break; - case 'iterated': { - const data = util.concatUint8Array([this.salt, passphrase]); - let datalen = data.length; - const count = Math.max(this.getCount(), datalen); - toHash = new Uint8Array(prefixlen + count); - toHash.set(data, prefixlen); - for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { - toHash.copyWithin(pos, prefixlen, pos); - } - break; - } - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - const result = await mod.hash.digest(this.algorithm, toHash); - arr.push(result); - rlength += result.length; - prefixlen++; - } - - return util.concatUint8Array(arr).subarray(0, numBytes); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Symmetric-Key Encrypted Session Key Packets (Tag 3) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: - * The Symmetric-Key Encrypted Session Key packet holds the - * symmetric-key encryption of a session key used to encrypt a message. - * Zero or more Public-Key Encrypted Session Key packets and/or - * Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data packet that holds an encrypted message. - * The message is encrypted with a session key, and the session key is - * itself encrypted and stored in the Encrypted Session Key packet or - * the Symmetric-Key Encrypted Session Key packet. - */ -class SymEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.symEncryptedSessionKey; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - this.version = config$1.aeadProtect ? 5 : 4; - this.sessionKey = null; - /** - * Algorithm to encrypt the session key with - * @type {enums.symmetric} - */ - this.sessionKeyEncryptionAlgorithm = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = enums.symmetric.aes256; - /** - * AEAD mode to encrypt the session key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); - this.encrypted = null; - this.s2k = null; - this.iv = null; - } - - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * - * @param {Uint8Array} bytes - Payload of a tag 3 packet - */ - read(bytes) { - let offset = 0; - - // A one-octet version number. The only currently defined version is 4. - this.version = bytes[offset++]; - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); - } - - // A one-octet number describing the symmetric algorithm used. - const algo = bytes[offset++]; - - if (this.version === 5) { - // A one-octet AEAD algorithm. - this.aeadAlgorithm = bytes[offset++]; - } - - // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new S2K(); - offset += this.s2k.read(bytes.subarray(offset, bytes.length)); - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - - // A starting initialization vector of size specified by the AEAD - // algorithm. - this.iv = bytes.subarray(offset, offset += mode.ivLength); - } - - // The encrypted session key itself, which is decrypted with the - // string-to-key object. This is optional in version 4. - if (this.version === 5 || offset < bytes.length) { - this.encrypted = bytes.subarray(offset, bytes.length); - this.sessionKeyEncryptionAlgorithm = algo; - } else { - this.sessionKeyAlgorithm = algo; - } - } - - /** - * Create a binary representation of a tag 3 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const algo = this.encrypted === null ? - this.sessionKeyAlgorithm : - this.sessionKeyEncryptionAlgorithm; - - let bytes; - - if (this.version === 5) { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]); - } else { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]); - - if (this.encrypted !== null) { - bytes = util.concatUint8Array([bytes, this.encrypted]); - } - } - - return bytes; - } - - /** - * Decrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(passphrase) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; - - const { blockSize, keySize } = mod.getCipher(algo); - const key = await this.s2k.produceKey(passphrase, keySize); - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, key); - this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); - } else if (this.encrypted !== null) { - const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); - - this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1, decrypted.length); - } else { - this.sessionKey = key; - } - } - - /** - * Encrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; - - this.sessionKeyEncryptionAlgorithm = algo; - - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - - const { blockSize, keySize } = mod.getCipher(algo); - const encryptionKey = await this.s2k.produceKey(passphrase, keySize); - - if (this.sessionKey === null) { - this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm); - } - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV - const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, encryptionKey); - this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData); - } else { - const toEncrypt = util.concatUint8Array([ - new Uint8Array([this.sessionKeyAlgorithm]), - this.sessionKey - ]); - this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1); - } - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ -class PublicKeyPacket { - static get tag() { - return enums.packet.publicKey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - /** - * Packet version - * @type {Integer} - */ - this.version = config$1.v5Keys ? 5 : 4; - /** - * Key creation date. - * @type {Date} - */ - this.created = util.normalizeDate(date); - /** - * Public key algorithm. - * @type {enums.publicKey} - */ - this.algorithm = null; - /** - * Algorithm specific public params - * @type {Object} - */ - this.publicParams = null; - /** - * Time until expiration in days (V3 only) - * @type {Integer} - */ - this.expirationTimeV3 = 0; - /** - * Fingerprint bytes - * @type {Uint8Array} - */ - this.fingerprint = null; - /** - * KeyID - * @type {module:type/keyid~KeyID} - */ - this.keyID = null; - } - - /** - * Create a PublicKeyPacket from a SecretKeyPacket - * @param {SecretKeyPacket} secretKeyPacket - key packet to convert - * @returns {PublicKeyPacket} public key packet - * @static - */ - static fromSecretKeyPacket(secretKeyPacket) { - const keyPacket = new PublicKeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * @param {Uint8Array} bytes - Input array to read the packet from - * @returns {Object} This object with attributes set by the parser - * @async - */ - async read(bytes) { - let pos = 0; - // A one-octet version number (3, 4 or 5). - this.version = bytes[pos++]; - - if (this.version === 4 || this.version === 5) { - // - A four-octet number denoting the time that the key was created. - this.created = util.readDate(bytes.subarray(pos, pos + 4)); - pos += 4; - - // - A one-octet number denoting the public-key algorithm of this key. - this.algorithm = bytes[pos++]; - - if (this.version === 5) { - // - A four-octet scalar octet count for the following key material. - pos += 4; - } - - // - A series of values comprising the key material. - const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); - this.publicParams = publicParams; - pos += read; - - // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor - await this.computeFingerprintAndKeyID(); - return pos; - } - throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); - } - - /** - * Creates an OpenPGP public key packet for the given key. - * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. - */ - write() { - const arr = []; - // Version - arr.push(new Uint8Array([this.version])); - arr.push(util.writeDate(this.created)); - // A one-octet number denoting the public-key algorithm of this key - arr.push(new Uint8Array([this.algorithm])); - - const params = mod.serializeParams(this.algorithm, this.publicParams); - if (this.version === 5) { - // A four-octet scalar octet count for the following key material - arr.push(util.writeNumber(params.length, 4)); - } - // Algorithm-specific params - arr.push(params); - return util.concatUint8Array(arr); - } - - /** - * Write packet in order to be hashed; either for a signature or a fingerprint - * @param {Integer} version - target version of signature or key - */ - writeForHash(version) { - const bytes = this.writePublicKey(); - - if (version === 5) { - return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]); - } - return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); - } - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return null; - } - - /** - * Returns the creation time of the key - * @returns {Date} - */ - getCreationTime() { - return this.created; - } - - /** - * Return the key ID of the key - * @returns {module:type/keyid~KeyID} The 8-byte key ID - */ - getKeyID() { - return this.keyID; - } - - /** - * Computes and set the key ID and fingerprint of the key - * @async - */ - async computeFingerprintAndKeyID() { - await this.computeFingerprint(); - this.keyID = new KeyID(); - - if (this.version === 5) { - this.keyID.read(this.fingerprint.subarray(0, 8)); - } else if (this.version === 4) { - this.keyID.read(this.fingerprint.subarray(12, 20)); - } else { - throw new Error('Unsupported key version'); - } - } - - /** - * Computes and set the fingerprint of the key - */ - async computeFingerprint() { - const toHash = this.writeForHash(this.version); - - if (this.version === 5) { - this.fingerprint = await mod.hash.sha256(toHash); - } else if (this.version === 4) { - this.fingerprint = await mod.hash.sha1(toHash); - } else { - throw new Error('Unsupported key version'); - } - } - - /** - * Returns the fingerprint of the key, as an array of bytes - * @returns {Uint8Array} A Uint8Array containing the fingerprint - */ - getFingerprintBytes() { - return this.fingerprint; - } - - /** - * Calculates and returns the fingerprint of the key, as a string - * @returns {String} A string containing the fingerprint in lowercase hex - */ - getFingerprint() { - return util.uint8ArrayToHex(this.getFingerprintBytes()); - } - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns {Boolean} Whether the two keys have the same version and public key data. - */ - hasSameFingerprintAs(other) { - return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); - } - - /** - * Returns algorithm information - * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. - */ - getAlgorithmInfo() { - const result = {}; - result.algorithm = enums.read(enums.publicKey, this.algorithm); - // RSA, DSA or ElGamal public modulo - const modulo = this.publicParams.n || this.publicParams.p; - if (modulo) { - result.bits = util.uint8ArrayBitLength(modulo); - } else if (this.publicParams.oid) { - result.curve = this.publicParams.oid.getName(); - } - return result; - } -} - -/** - * Alias of read() - * @see PublicKeyPacket#read - */ -PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; - -/** - * Alias of write() - * @see PublicKeyPacket#write - */ -PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A SE packet can contain the following packet types -const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -/** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ -class SymmetricallyEncryptedDataPacket { - static get tag() { - return enums.packet.symmetricallyEncryptedData; - } - - constructor() { - /** - * Encrypted secret-key data - */ - this.encrypted = null; - /** - * Decrypted packets contained within. - * @type {PacketList} - */ - this.packets = null; - } - - read(bytes) { - this.encrypted = bytes; - } - - write() { - return this.encrypted; - } - - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error - if (!config$1.allowUnauthenticatedMessages) { - throw new Error('Message is not authenticated.'); - } - - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - const encrypted = await readToEnd(clone(this.encrypted)); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, - encrypted.subarray(blockSize + 2), - encrypted.subarray(2, blockSize + 2) - ); - - this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1); - } - - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const data = this.packets.write(); - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); - const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); - this.encrypted = util.concat([FRE, ciphertext]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the strange "Marker packet" (Tag 10) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * - * The body of this packet consists of: - * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). - * - * Such a packet MUST be ignored when received. It may be placed at the - * beginning of a message that uses features not available in PGP - * version 2.6 in order to cause that version to report that newer - * software is necessary to process the message. - */ -class MarkerPacket { - static get tag() { - return enums.packet.marker; - } - - /** - * Parsing function for a marker data packet (tag 10). - * @param {Uint8Array} bytes - Payload of a tag 10 packet - * @returns {Boolean} whether the packet payload contains "PGP" - */ - read(bytes) { - if (bytes[0] === 0x50 && // P - bytes[1] === 0x47 && // G - bytes[2] === 0x50) { // P - return true; - } - return false; - } - - write() { - return new Uint8Array([0x50, 0x47, 0x50]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - * @extends PublicKeyPacket - */ -class PublicSubkeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.publicSubkey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - // eslint-disable-next-line no-useless-constructor - constructor(date, config) { - super(date, config); - } - - /** - * Create a PublicSubkeyPacket from a SecretSubkeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert - * @returns {SecretSubkeyPacket} public key packet - * @static - */ - static fromSecretSubkeyPacket(secretSubkeyPacket) { - const keyPacket = new PublicSubkeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the User Attribute Packet (Tag 17) - * - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ -class UserAttributePacket { - static get tag() { - return enums.packet.userAttribute; - } - - constructor() { - this.attributes = []; - } - - /** - * parsing function for a user attribute packet (tag 17). - * @param {Uint8Array} input - Payload of a tag 17 packet - */ - read(bytes) { - let i = 0; - while (i < bytes.length) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); - i += len.len; - } - } - - /** - * Creates a binary representation of the user attribute packet - * @returns {Uint8Array} String representation. - */ - write() { - const arr = []; - for (let i = 0; i < this.attributes.length; i++) { - arr.push(writeSimpleLength(this.attributes[i].length)); - arr.push(util.stringToUint8Array(this.attributes[i])); - } - return util.concatUint8Array(arr); - } - - /** - * Compare for equality - * @param {UserAttributePacket} usrAttr - * @returns {Boolean} True if equal. - */ - equals(usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { - return false; - } - return this.attributes.every(function(attr, index) { - return attr === usrAttr.attributes[index]; - }); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - * @extends PublicKeyPacket - */ -class SecretKeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.secretKey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - /** - * Secret-key data - */ - this.keyMaterial = null; - /** - * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - this.isEncrypted = null; - /** - * S2K usage - * @type {enums.symmetric} - */ - this.s2kUsage = 0; - /** - * S2K object - * @type {type/s2k} - */ - this.s2k = null; - /** - * Symmetric algorithm to encrypt the key with - * @type {enums.symmetric} - */ - this.symmetric = null; - /** - * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aead = null; - /** - * Decrypted private parameters, referenced by name - * @type {Object} - */ - this.privateParams = null; - } - - // 5.5.3. Secret-Key Packet Formats - - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param {Uint8Array} bytes - Input string to read the packet from - * @async - */ - async read(bytes) { - // - A Public-Key or Public-Subkey packet, as described above. - let i = await this.readPublicKey(bytes); - const startOfSecretKeyData = i; - - // - One octet indicating string-to-key usage conventions. Zero - // indicates that the secret-key data is not encrypted. 255 or 254 - // indicates that a string-to-key specifier is being given. Any - // other value is a symmetric-key encryption algorithm identifier. - this.s2kUsage = bytes[i++]; - - // - Only for a version 5 packet, a one-octet scalar octet count of - // the next 4 optional fields. - if (this.version === 5) { - i++; - } - - try { - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one-octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - this.symmetric = bytes[i++]; - - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - this.aead = bytes[i++]; - } - - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - this.s2k = new S2K(); - i += this.s2k.read(bytes.subarray(i, bytes.length)); - - if (this.s2k.type === 'gnu-dummy') { - return; - } - } else if (this.s2kUsage) { - this.symmetric = this.s2kUsage; - } - - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage) { - this.iv = bytes.subarray( - i, - i + mod.getCipher(this.symmetric).blockSize - ); - - i += this.iv.length; - } - } catch (e) { - // if the s2k is unsupported, we still want to support encrypting and verifying with the given key - if (!this.s2kUsage) throw e; // always throw for decrypted keys - this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); - this.isEncrypted = true; - } - - // - Only for a version 5 packet, a four-octet scalar octet count for - // the following key material. - if (this.version === 5) { - i += 4; - } - - // - Plain or encrypted multiprecision integers comprising the secret - // key data. These algorithm-specific fields are as described - // below. - this.keyMaterial = bytes.subarray(i); - this.isEncrypted = !!this.s2kUsage; - - if (!this.isEncrypted) { - const cleartext = this.keyMaterial.subarray(0, -2); - if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { - throw new Error('Key checksum mismatch'); - } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - if (err instanceof UnsupportedError) throw err; - // avoid throwing potentially sensitive errors - throw new Error('Error reading MPIs'); - } - } - } - - /** - * Creates an OpenPGP key packet for the given key. - * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. - */ - write() { - const serializedPublicKey = this.writePublicKey(); - if (this.unparseableKeyMaterial) { - return util.concatUint8Array([ - serializedPublicKey, - this.unparseableKeyMaterial - ]); - } - - const arr = [serializedPublicKey]; - arr.push(new Uint8Array([this.s2kUsage])); - - const optionalFieldsArr = []; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one- octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - optionalFieldsArr.push(this.symmetric); - - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - optionalFieldsArr.push(this.aead); - } - - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - optionalFieldsArr.push(...this.s2k.write()); - } - - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { - optionalFieldsArr.push(...this.iv); - } - - if (this.version === 5) { - arr.push(new Uint8Array([optionalFieldsArr.length])); - } - arr.push(new Uint8Array(optionalFieldsArr)); - - if (!this.isDummy()) { - if (!this.s2kUsage) { - this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams); - } - - if (this.version === 5) { - arr.push(util.writeNumber(this.keyMaterial.length, 4)); - } - arr.push(this.keyMaterial); - - if (!this.s2kUsage) { - arr.push(util.writeChecksum(this.keyMaterial)); - } - } - - return util.concatUint8Array(arr); - } - - /** - * Check whether secret-key data is available in decrypted form. - * Returns false for gnu-dummy keys and null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return this.isEncrypted === false; - } - - /** - * Check whether the key includes secret key material. - * Some secret keys do not include it, and can thus only be used - * for public-key operations (encryption and verification). - * Such keys are: - * - GNU-dummy keys, where the secret material has been stripped away - * - encrypted keys with unsupported S2K or cipher - */ - isMissingSecretKeyMaterial() { - return this.unparseableKeyMaterial !== undefined || this.isDummy(); - } - - /** - * Check whether this is a gnu-dummy key - * @returns {Boolean} - */ - isDummy() { - return !!(this.s2k && this.s2k.type === 'gnu-dummy'); - } - - /** - * Remove private key material, converting the key to a dummy one. - * The resulting key cannot be used for signing/decrypting but can still verify signatures. - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - makeDummy(config$1 = config) { - if (this.isDummy()) { - return; - } - if (this.isDecrypted()) { - this.clearPrivateParams(); - } - delete this.unparseableKeyMaterial; - this.isEncrypted = null; - this.keyMaterial = null; - this.s2k = new S2K(config$1); - this.s2k.algorithm = 0; - this.s2k.c = 0; - this.s2k.type = 'gnu-dummy'; - this.s2kUsage = 254; - this.symmetric = enums.symmetric.aes256; - } - - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param {String} passphrase - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - if (this.isDummy()) { - return; - } - - if (!this.isDecrypted()) { - throw new Error('Key packet is already encrypted'); - } - - if (!passphrase) { - throw new Error('A non-empty passphrase is required for key encryption.'); - } - - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - const cleartext = mod.serializeParams(this.algorithm, this.privateParams); - this.symmetric = enums.symmetric.aes256; - const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - - const { blockSize } = mod.getCipher(this.symmetric); - this.iv = mod.random.getRandomBytes(blockSize); - - if (config$1.aeadProtect) { - this.s2kUsage = 253; - this.aead = enums.aead.eax; - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } else { - this.s2kUsage = 254; - this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ - cleartext, - await mod.hash.sha1(cleartext, config$1) - ]), this.iv, config$1); - } - } - - /** - * Decrypts the private key params which are needed to use the key. - * Successful decryption does not imply key integrity, call validate() to confirm that. - * {@link SecretKeyPacket.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param {String} passphrase - The passphrase for this private key as string - * @throws {Error} if the key is already decrypted, or if decryption was not successful - * @async - */ - async decrypt(passphrase) { - if (this.isDummy()) { - return false; - } - - if (this.unparseableKeyMaterial) { - throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); - } - - if (this.isDecrypted()) { - throw new Error('Key packet is already decrypted.'); - } - - let key; - if (this.s2kUsage === 254 || this.s2kUsage === 253) { - key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2kUsage === 255) { - throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); - } else { - throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); - } - - let cleartext; - if (this.s2kUsage === 253) { - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - try { - cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } catch (err) { - if (err.message === 'Authentication tag mismatch') { - throw new Error('Incorrect key passphrase: ' + err.message); - } - throw err; - } - } else { - const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); - - cleartext = cleartextWithHash.subarray(0, -20); - const hash = await mod.hash.sha1(cleartext); - - if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { - throw new Error('Incorrect key passphrase'); - } - } - - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - throw new Error('Error reading MPIs'); - } - this.isEncrypted = false; - this.keyMaterial = null; - this.s2kUsage = 0; - } - - /** - * Checks that the key parameters are consistent - * @throws {Error} if validation was not successful - * @async - */ - async validate() { - if (this.isDummy()) { - return; - } - - if (!this.isDecrypted()) { - throw new Error('Key is not decrypted'); - } - - let validParams; - try { - // this can throw if some parameters are undefined - validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); - } catch (_) { - validParams = false; - } - if (!validParams) { - throw new Error('Key is invalid'); - } - } - - async generate(bits, curve) { - const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); - this.privateParams = privateParams; - this.publicParams = publicParams; - this.isEncrypted = false; - } - - /** - * Clear private key parameters - */ - clearPrivateParams() { - if (this.isMissingSecretKeyMaterial()) { - return; - } - - Object.keys(this.privateParams).forEach(name => { - const param = this.privateParams[name]; - param.fill(0); - delete this.privateParams[name]; - }); - this.privateParams = null; - this.isEncrypted = true; - } -} - -async function produceEncryptionKey(s2k, passphrase, algorithm) { - const { keySize } = mod.getCipher(algorithm); - return s2k.produceKey(passphrase, keySize); -} - -var emailAddresses = createCommonjsModule(function (module) { -// email-addresses.js - RFC 5322 email address parser -// v 3.1.0 -// -// http://tools.ietf.org/html/rfc5322 -// -// This library does not validate email addresses. -// emailAddresses attempts to parse addresses using the (fairly liberal) -// grammar specified in RFC 5322. -// -// email-addresses returns { -// ast: , -// addresses: [{ -// node: , -// name: , -// address: , -// local: , -// domain: -// }, ...] -// } -// -// emailAddresses.parseOneAddress and emailAddresses.parseAddressList -// work as you might expect. Try it out. -// -// Many thanks to Dominic Sayers and his documentation on the is_email function, -// http://code.google.com/p/isemail/ , which helped greatly in writing this parser. - -(function (global) { - -function parse5322(opts) { - - // tokenizing functions - - function inStr() { return pos < len; } - function curTok() { return parseString[pos]; } - function getPos() { return pos; } - function setPos(i) { pos = i; } - function nextTok() { pos += 1; } - function initialize() { - pos = 0; - len = parseString.length; - } - - // parser helper functions - - function o(name, value) { - return { - name: name, - tokens: value || "", - semantic: value || "", - children: [] - }; - } - - function wrap(name, ast) { - var n; - if (ast === null) { return null; } - n = o(name); - n.tokens = ast.tokens; - n.semantic = ast.semantic; - n.children.push(ast); - return n; - } - - function add(parent, child) { - if (child !== null) { - parent.tokens += child.tokens; - parent.semantic += child.semantic; - } - parent.children.push(child); - return parent; - } - - function compareToken(fxnCompare) { - var tok; - if (!inStr()) { return null; } - tok = curTok(); - if (fxnCompare(tok)) { - nextTok(); - return o('token', tok); - } - return null; - } - - function literal(lit) { - return function literalFunc() { - return wrap('literal', compareToken(function (tok) { - return tok === lit; - })); - }; - } - - function and() { - var args = arguments; - return function andFunc() { - var i, s, result, start; - start = getPos(); - s = o('and'); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result === null) { - setPos(start); - return null; - } - add(s, result); - } - return s; - }; - } - - function or() { - var args = arguments; - return function orFunc() { - var i, result, start; - start = getPos(); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result !== null) { - return result; - } - setPos(start); - } - return null; - }; - } - - function opt(prod) { - return function optFunc() { - var result, start; - start = getPos(); - result = prod(); - if (result !== null) { - return result; - } - else { - setPos(start); - return o('opt'); - } - }; - } - - function invis(prod) { - return function invisFunc() { - var result = prod(); - if (result !== null) { - result.semantic = ""; - } - return result; - }; - } - - function colwsp(prod) { - return function collapseSemanticWhitespace() { - var result = prod(); - if (result !== null && result.semantic.length > 0) { - result.semantic = " "; - } - return result; - }; - } - - function star(prod, minimum) { - return function starFunc() { - var s, result, count, start, min; - start = getPos(); - s = o('star'); - count = 0; - min = minimum === undefined ? 0 : minimum; - while ((result = prod()) !== null) { - count = count + 1; - add(s, result); - } - if (count >= min) { - return s; - } - else { - setPos(start); - return null; - } - }; - } - - // One expects names to get normalized like this: - // " First Last " -> "First Last" - // "First Last" -> "First Last" - // "First Last" -> "First Last" - function collapseWhitespace(s) { - return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, ''); - } - - // UTF-8 pseudo-production (RFC 6532) - // RFC 6532 extends RFC 5322 productions to include UTF-8 - // using the following productions: - // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // UTF8-2 = - // UTF8-3 = - // UTF8-4 = - // - // For reference, the extended RFC 5322 productions are: - // VCHAR =/ UTF8-non-ascii - // ctext =/ UTF8-non-ascii - // atext =/ UTF8-non-ascii - // qtext =/ UTF8-non-ascii - // dtext =/ UTF8-non-ascii - function isUTF8NonAscii(tok) { - // In JavaScript, we just deal directly with Unicode code points, - // so we aren't checking individual bytes for UTF-8 encoding. - // Just check that the character is non-ascii. - return tok.charCodeAt(0) >= 128; - } - - - // common productions (RFC 5234) - // http://tools.ietf.org/html/rfc5234 - // B.1. Core Rules - - // CR = %x0D - // ; carriage return - function cr() { return wrap('cr', literal('\r')()); } - - // CRLF = CR LF - // ; Internet standard newline - function crlf() { return wrap('crlf', and(cr, lf)()); } - - // DQUOTE = %x22 - // ; " (Double Quote) - function dquote() { return wrap('dquote', literal('"')()); } - - // HTAB = %x09 - // ; horizontal tab - function htab() { return wrap('htab', literal('\t')()); } - - // LF = %x0A - // ; linefeed - function lf() { return wrap('lf', literal('\n')()); } - - // SP = %x20 - function sp() { return wrap('sp', literal(' ')()); } - - // VCHAR = %x21-7E - // ; visible (printing) characters - function vchar() { - return wrap('vchar', compareToken(function vcharFunc(tok) { - var code = tok.charCodeAt(0); - var accept = (0x21 <= code && code <= 0x7E); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } - - // WSP = SP / HTAB - // ; white space - function wsp() { return wrap('wsp', or(sp, htab)()); } - - - // email productions (RFC 5322) - // http://tools.ietf.org/html/rfc5322 - // 3.2.1. Quoted characters - - // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp - function quotedPair() { - var qp = wrap('quoted-pair', - or( - and(literal('\\'), or(vchar, wsp)), - obsQP - )()); - if (qp === null) { return null; } - // a quoted pair will be two characters, and the "\" character - // should be semantically "invisible" (RFC 5322 3.2.1) - qp.semantic = qp.semantic[1]; - return qp; - } - - // 3.2.2. Folding White Space and Comments - - // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS - function fws() { - return wrap('fws', or( - obsFws, - and( - opt(and( - star(wsp), - invis(crlf) - )), - star(wsp, 1) - ) - )()); - } - - // ctext = %d33-39 / ; Printable US-ASCII - // %d42-91 / ; characters not including - // %d93-126 / ; "(", ")", or "\" - // obs-ctext - function ctext() { - return wrap('ctext', or( - function ctextFunc1() { - return compareToken(function ctextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 39) || - (42 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsCtext - )()); - } - - // ccontent = ctext / quoted-pair / comment - function ccontent() { - return wrap('ccontent', or(ctext, quotedPair, comment)()); - } - - // comment = "(" *([FWS] ccontent) [FWS] ")" - function comment() { - return wrap('comment', and( - literal('('), - star(and(opt(fws), ccontent)), - opt(fws), - literal(')') - )()); - } - - // CFWS = (1*([FWS] comment) [FWS]) / FWS - function cfws() { - return wrap('cfws', or( - and( - star( - and(opt(fws), comment), - 1 - ), - opt(fws) - ), - fws - )()); - } - - // 3.2.3. Atom - - //atext = ALPHA / DIGIT / ; Printable US-ASCII - // "!" / "#" / ; characters not including - // "$" / "%" / ; specials. Used for atoms. - // "&" / "'" / - // "*" / "+" / - // "-" / "/" / - // "=" / "?" / - // "^" / "_" / - // "`" / "{" / - // "|" / "}" / - // "~" - function atext() { - return wrap('atext', compareToken(function atextFunc(tok) { - var accept = - ('a' <= tok && tok <= 'z') || - ('A' <= tok && tok <= 'Z') || - ('0' <= tok && tok <= '9') || - (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', - '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } - - // atom = [CFWS] 1*atext [CFWS] - function atom() { - return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))()); - } - - // dot-atom-text = 1*atext *("." 1*atext) - function dotAtomText() { - var s, maybeText; - s = wrap('dot-atom-text', star(atext, 1)()); - if (s === null) { return s; } - maybeText = star(and(literal('.'), star(atext, 1)))(); - if (maybeText !== null) { - add(s, maybeText); - } - return s; - } - - // dot-atom = [CFWS] dot-atom-text [CFWS] - function dotAtom() { - return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))()); - } - - // 3.2.4. Quoted Strings - - // qtext = %d33 / ; Printable US-ASCII - // %d35-91 / ; characters not including - // %d93-126 / ; "\" or the quote character - // obs-qtext - function qtext() { - return wrap('qtext', or( - function qtextFunc1() { - return compareToken(function qtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 === code) || - (35 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsQtext - )()); - } - - // qcontent = qtext / quoted-pair - function qcontent() { - return wrap('qcontent', or(qtext, quotedPair)()); - } - - // quoted-string = [CFWS] - // DQUOTE *([FWS] qcontent) [FWS] DQUOTE - // [CFWS] - function quotedString() { - return wrap('quoted-string', and( - invis(opt(cfws)), - invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), - invis(opt(cfws)) - )()); - } - - // 3.2.5 Miscellaneous Tokens - - // word = atom / quoted-string - function word() { - return wrap('word', or(atom, quotedString)()); - } - - // phrase = 1*word / obs-phrase - function phrase() { - return wrap('phrase', or(obsPhrase, star(word, 1))()); - } - - // 3.4. Address Specification - // address = mailbox / group - function address() { - return wrap('address', or(mailbox, group)()); - } - - // mailbox = name-addr / addr-spec - function mailbox() { - return wrap('mailbox', or(nameAddr, addrSpec)()); - } - - // name-addr = [display-name] angle-addr - function nameAddr() { - return wrap('name-addr', and(opt(displayName), angleAddr)()); - } - - // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / - // obs-angle-addr - function angleAddr() { - return wrap('angle-addr', or( - and( - invis(opt(cfws)), - literal('<'), - addrSpec, - literal('>'), - invis(opt(cfws)) - ), - obsAngleAddr - )()); - } - - // group = display-name ":" [group-list] ";" [CFWS] - function group() { - return wrap('group', and( - displayName, - literal(':'), - opt(groupList), - literal(';'), - invis(opt(cfws)) - )()); - } - - // display-name = phrase - function displayName() { - return wrap('display-name', function phraseFixedSemantic() { - var result = phrase(); - if (result !== null) { - result.semantic = collapseWhitespace(result.semantic); - } - return result; - }()); - } - - // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list - function mailboxList() { - return wrap('mailbox-list', or( - and( - mailbox, - star(and(literal(','), mailbox)) - ), - obsMboxList - )()); - } - - // address-list = (address *("," address)) / obs-addr-list - function addressList() { - return wrap('address-list', or( - and( - address, - star(and(literal(','), address)) - ), - obsAddrList - )()); - } - - // group-list = mailbox-list / CFWS / obs-group-list - function groupList() { - return wrap('group-list', or( - mailboxList, - invis(cfws), - obsGroupList - )()); - } - - // 3.4.1 Addr-Spec Specification - - // local-part = dot-atom / quoted-string / obs-local-part - function localPart() { - // note: quoted-string, dotAtom are proper subsets of obs-local-part - // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree - return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)()); - } - - // dtext = %d33-90 / ; Printable US-ASCII - // %d94-126 / ; characters not including - // obs-dtext ; "[", "]", or "\" - function dtext() { - return wrap('dtext', or( - function dtextFunc1() { - return compareToken(function dtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 90) || - (94 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsDtext - )() - ); - } - - // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - function domainLiteral() { - return wrap('domain-literal', and( - invis(opt(cfws)), - literal('['), - star(and(opt(fws), dtext)), - opt(fws), - literal(']'), - invis(opt(cfws)) - )()); - } - - // domain = dot-atom / domain-literal / obs-domain - function domain() { - return wrap('domain', function domainCheckTLD() { - var result = or(obsDomain, dotAtom, domainLiteral)(); - if (opts.rejectTLD) { - if (result && result.semantic && result.semantic.indexOf('.') < 0) { - return null; - } - } - // strip all whitespace from domains - if (result) { - result.semantic = result.semantic.replace(/\s+/g, ''); - } - return result; - }()); - } - - // addr-spec = local-part "@" domain - function addrSpec() { - return wrap('addr-spec', and( - localPart, literal('@'), domain - )()); - } - - // 3.6.2 Originator Fields - // Below we only parse the field body, not the name of the field - // like "From:", "Sender:", or "Reply-To:". Other libraries that - // parse email headers can parse those and defer to these productions - // for the "RFC 5322" part. - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // from = "From:" (mailbox-list / address-list) CRLF - function fromSpec() { - return wrap('from', or( - mailboxList, - addressList - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // sender = "Sender:" (mailbox / address) CRLF - function senderSpec() { - return wrap('sender', or( - mailbox, - address - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // reply-to = "Reply-To:" address-list CRLF - function replyToSpec() { - return wrap('reply-to', addressList()); - } - - // 4.1. Miscellaneous Obsolete Tokens - - // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control - // %d11 / ; characters that do not - // %d12 / ; include the carriage - // %d14-31 / ; return, line feed, and - // %d127 ; white space characters - function obsNoWsCtl() { - return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) { - var code = tok.charCodeAt(0); - return ((1 <= code && code <= 8) || - (11 === code || 12 === code) || - (14 <= code && code <= 31) || - (127 === code)); - })); - } - - // obs-ctext = obs-NO-WS-CTL - function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); } - - // obs-qtext = obs-NO-WS-CTL - function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); } - - // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) - function obsQP() { - return opts.strict ? null : wrap('obs-qp', and( - literal('\\'), - or(literal('\0'), obsNoWsCtl, lf, cr) - )()); - } - - // obs-phrase = word *(word / "." / CFWS) - function obsPhrase() { - if (opts.strict ) return null; - return opts.atInDisplayName ? wrap('obs-phrase', and( - word, - star(or(word, literal('.'), literal('@'), colwsp(cfws))) - )()) : - wrap('obs-phrase', and( - word, - star(or(word, literal('.'), colwsp(cfws))) - )()); - } - - // 4.2. Obsolete Folding White Space - - // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908 - // obs-FWS = 1*([CRLF] WSP) - function obsFws() { - return opts.strict ? null : wrap('obs-FWS', star( - and(invis(opt(crlf)), wsp), - 1 - )()); - } - - // 4.4. Obsolete Addressing - - // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] - function obsAngleAddr() { - return opts.strict ? null : wrap('obs-angle-addr', and( - invis(opt(cfws)), - literal('<'), - obsRoute, - addrSpec, - literal('>'), - invis(opt(cfws)) - )()); - } - - // obs-route = obs-domain-list ":" - function obsRoute() { - return opts.strict ? null : wrap('obs-route', and( - obsDomainList, - literal(':') - )()); - } - - // obs-domain-list = *(CFWS / ",") "@" domain - // *("," [CFWS] ["@" domain]) - function obsDomainList() { - return opts.strict ? null : wrap('obs-domain-list', and( - star(or(invis(cfws), literal(','))), - literal('@'), - domain, - star(and( - literal(','), - invis(opt(cfws)), - opt(and(literal('@'), domain)) - )) - )()); - } - - // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) - function obsMboxList() { - return opts.strict ? null : wrap('obs-mbox-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - mailbox, - star(and( - literal(','), - opt(and( - mailbox, - invis(cfws) - )) - )) - )()); - } - - // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) - function obsAddrList() { - return opts.strict ? null : wrap('obs-addr-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - address, - star(and( - literal(','), - opt(and( - address, - invis(cfws) - )) - )) - )()); - } - - // obs-group-list = 1*([CFWS] ",") [CFWS] - function obsGroupList() { - return opts.strict ? null : wrap('obs-group-list', and( - star(and( - invis(opt(cfws)), - literal(',') - ), 1), - invis(opt(cfws)) - )()); - } - - // obs-local-part = word *("." word) - function obsLocalPart() { - return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))()); - } - - // obs-domain = atom *("." atom) - function obsDomain() { - return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))()); - } - - // obs-dtext = obs-NO-WS-CTL / quoted-pair - function obsDtext() { - return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)()); - } - - ///////////////////////////////////////////////////// - - // ast analysis - - function findNode(name, root) { - var i, stack, node; - if (root === null || root === undefined) { return null; } - stack = [root]; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - return node; - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return null; - } - - function findAllNodes(name, root) { - var i, stack, node, result; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - result.push(node); - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return result; - } - - function findAllNodesNoChildren(names, root) { - var i, stack, node, result, namesLookup; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - namesLookup = {}; - for (i = 0; i < names.length; i += 1) { - namesLookup[names[i]] = true; - } - - while (stack.length > 0) { - node = stack.pop(); - if (node.name in namesLookup) { - result.push(node); - // don't look at children (hence findAllNodesNoChildren) - } else { - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - } - return result; - } - - function giveResult(ast) { - var addresses, groupsAndMailboxes, i, groupOrMailbox, result; - if (ast === null) { - return null; - } - addresses = []; - - // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'. - groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast); - for (i = 0; i < groupsAndMailboxes.length; i += 1) { - groupOrMailbox = groupsAndMailboxes[i]; - if (groupOrMailbox.name === 'group') { - addresses.push(giveResultGroup(groupOrMailbox)); - } else if (groupOrMailbox.name === 'mailbox') { - addresses.push(giveResultMailbox(groupOrMailbox)); - } - } - - result = { - ast: ast, - addresses: addresses, - }; - if (opts.simple) { - result = simplifyResult(result); - } - if (opts.oneResult) { - return oneResult(result); - } - if (opts.simple) { - return result && result.addresses; - } else { - return result; - } - } - - function giveResultGroup(group) { - var i; - var groupName = findNode('display-name', group); - var groupResultMailboxes = []; - var mailboxes = findAllNodesNoChildren(['mailbox'], group); - for (i = 0; i < mailboxes.length; i += 1) { - groupResultMailboxes.push(giveResultMailbox(mailboxes[i])); - } - return { - node: group, - parts: { - name: groupName, - }, - type: group.name, // 'group' - name: grabSemantic(groupName), - addresses: groupResultMailboxes, - }; - } - - function giveResultMailbox(mailbox) { - var name = findNode('display-name', mailbox); - var aspec = findNode('addr-spec', mailbox); - var cfws = findAllNodes('cfws', mailbox); - var comments = findAllNodesNoChildren(['comment'], mailbox); - - - var local = findNode('local-part', aspec); - var domain = findNode('domain', aspec); - return { - node: mailbox, - parts: { - name: name, - address: aspec, - local: local, - domain: domain, - comments: cfws - }, - type: mailbox.name, // 'mailbox' - name: grabSemantic(name), - address: grabSemantic(aspec), - local: grabSemantic(local), - domain: grabSemantic(domain), - comments: concatComments(comments), - groupName: grabSemantic(mailbox.groupName), - }; - } - - function grabSemantic(n) { - return n !== null && n !== undefined ? n.semantic : null; - } - - function simplifyResult(result) { - var i; - if (result && result.addresses) { - for (i = 0; i < result.addresses.length; i += 1) { - delete result.addresses[i].node; - } - } - return result; - } - - function concatComments(comments) { - var result = ''; - if (comments) { - for (var i = 0; i < comments.length; i += 1) { - result += grabSemantic(comments[i]); - } - } - return result; - } - - function oneResult(result) { - if (!result) { return null; } - if (!opts.partial && result.addresses.length > 1) { return null; } - return result.addresses && result.addresses[0]; - } - - ///////////////////////////////////////////////////// - - var parseString, pos, len, parsed, startProduction; - - opts = handleOpts(opts, {}); - if (opts === null) { return null; } - - parseString = opts.input; - - startProduction = { - 'address': address, - 'address-list': addressList, - 'angle-addr': angleAddr, - 'from': fromSpec, - 'group': group, - 'mailbox': mailbox, - 'mailbox-list': mailboxList, - 'reply-to': replyToSpec, - 'sender': senderSpec, - }[opts.startAt] || addressList; - - if (!opts.strict) { - initialize(); - opts.strict = true; - parsed = startProduction(parseString); - if (opts.partial || !inStr()) { - return giveResult(parsed); - } - opts.strict = false; - } - - initialize(); - parsed = startProduction(parseString); - if (!opts.partial && inStr()) { return null; } - return giveResult(parsed); -} - -function parseOneAddressSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} - -function parseAddressListSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} - -function parseFromSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'from', - })); -} - -function parseSenderSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'sender', - })); -} - -function parseReplyToSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'reply-to', - })); -} - -function handleOpts(opts, defs) { - function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; - } - - function isObject(o) { - return o === Object(o); - } - - function isNullUndef(o) { - return o === null || o === undefined; - } - - var defaults, o; - - if (isString(opts)) { - opts = { input: opts }; - } else if (!isObject(opts)) { - return null; - } - - if (!isString(opts.input)) { return null; } - if (!defs) { return null; } - - defaults = { - oneResult: false, - partial: false, - rejectTLD: false, - rfc6532: false, - simple: false, - startAt: 'address-list', - strict: false, - atInDisplayName: false - }; - - for (o in defaults) { - if (isNullUndef(opts[o])) { - opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o]; - } - } - return opts; -} - -parse5322.parseOneAddress = parseOneAddressSimple; -parse5322.parseAddressList = parseAddressListSimple; -parse5322.parseFrom = parseFromSimple; -parse5322.parseSender = parseSenderSimple; -parse5322.parseReplyTo = parseReplyToSimple; - -{ - module.exports = parse5322; -} - -}()); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the User ID Packet (Tag 13) - * - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. - */ -class UserIDPacket { - static get tag() { - return enums.packet.userID; - } - - constructor() { - /** A string containing the user id. Usually in the form - * John Doe - * @type {String} - */ - this.userID = ''; - - this.name = ''; - this.email = ''; - this.comment = ''; - } - - /** - * Create UserIDPacket instance from object - * @param {Object} userID - Object specifying userID name, email and comment - * @returns {UserIDPacket} - * @static - */ - static fromObject(userID) { - if (util.isString(userID) || - (userID.name && !util.isString(userID.name)) || - (userID.email && !util.isEmailAddress(userID.email)) || - (userID.comment && !util.isString(userID.comment))) { - throw new Error('Invalid user ID format'); - } - const packet = new UserIDPacket(); - Object.assign(packet, userID); - const components = []; - if (packet.name) components.push(packet.name); - if (packet.comment) components.push(`(${packet.comment})`); - if (packet.email) components.push(`<${packet.email}>`); - packet.userID = components.join(' '); - return packet; - } - - /** - * Parsing function for a user id packet (tag 13). - * @param {Uint8Array} input - Payload of a tag 13 packet - */ - read(bytes, config$1 = config) { - const userID = util.decodeUTF8(bytes); - if (userID.length > config$1.maxUserIDLength) { - throw new Error('User ID string is too long'); - } - try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); - this.comment = comments.replace(/^\(|\)$/g, ''); - this.name = name; - this.email = email; - } catch (e) {} - this.userID = userID; - } - - /** - * Creates a binary representation of the user id packet - * @returns {Uint8Array} Binary representation. - */ - write() { - return util.encodeUTF8(this.userID); - } - - equals(otherUserID) { - return otherUserID && otherUserID.userID === this.userID; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - * @extends SecretKeyPacket - */ -class SecretSubkeyPacket extends SecretKeyPacket { - static get tag() { - return enums.packet.secretSubkey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - } -} - -/** - * Implementation of the Trust Packet (Tag 12) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. - * - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. - */ -class TrustPacket { - static get tag() { - return enums.packet.trust; - } - - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - */ - read() { - throw new UnsupportedError('Trust packets are not supported'); - } - - write() { - throw new UnsupportedError('Trust packets are not supported'); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Signature can contain the following packets -const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - -/** - * Class that represents an OpenPGP signature. - */ -class Signature { - /** - * @param {PacketList} packetlist - The signature packets - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); - } - - /** - * Returns binary encoded signature - * @returns {ReadableStream} Binary signature. - */ - write() { - return this.packets.write(); - } - - /** - * Returns ASCII armored text of signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1); - } - - /** - * Returns an array of KeyIDs of all of the issuers who created this signature - * @returns {Array} The Key IDs of the signing keys - */ - getSigningKeyIDs() { - return this.packets.map(packet => packet.issuerKeyID); - } -} - -/** - * reads an (optionally armored) OpenPGP signature and returns a signature object - * @param {Object} options - * @param {String} [options.armoredSignature] - Armored signature to be parsed - * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New signature object. - * @async - * @static - */ -async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredSignature || binarySignature; - if (!input) { - throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); - } - if (armoredSignature && !util.isString(armoredSignature)) { - throw new Error('readSignature: options.armoredSignature must be a string'); - } - if (binarySignature && !util.isUint8Array(binarySignature)) { - throw new Error('readSignature: options.binarySignature must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (armoredSignature) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.signature) { - throw new Error('Armored text not of type signature'); - } - input = data; - } - const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1); - return new Signature(packetlist); -} - -/** - * @fileoverview Provides helpers methods for key module - * @module key/helper - * @private - */ - -async function generateSecretSubkey(options, config) { - const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); - secretSubkeyPacket.packets = null; - secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretSubkeyPacket.generate(options.rsaBits, options.curve); - await secretSubkeyPacket.computeFingerprintAndKeyID(); - return secretSubkeyPacket; -} - -async function generateSecretKey(options, config) { - const secretKeyPacket = new SecretKeyPacket(options.date, config); - secretKeyPacket.packets = null; - secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); - await secretKeyPacket.computeFingerprintAndKeyID(); - return secretKeyPacket; -} - -/** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param {Array} signatures - List of signatures - * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - full configuration - * @returns {Promise} The latest valid signature. - * @async - */ -async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { - let latestValid; - let exception; - for (let i = signatures.length - 1; i >= 0; i--) { - try { - if ( - (!latestValid || signatures[i].created >= latestValid.created) - ) { - await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); - latestValid = signatures[i]; - } - } catch (e) { - exception = e; - } - } - if (!latestValid) { - throw util.wrapError( - `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` - .replace('certGeneric ', 'self-') - .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), - exception); - } - return latestValid; -} - -function isDataExpired(keyPacket, signature, date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - const expirationTime = getKeyExpirationTime(keyPacket, signature); - return !(keyPacket.created <= normDate && normDate < expirationTime); - } - return false; -} - -/** - * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} - * @param {SecretSubkeyPacket} subkey - Subkey key packet - * @param {SecretKeyPacket} primaryKey - Primary key packet - * @param {Object} options - * @param {Object} config - Full configuration - */ -async function createBindingSignature(subkey, primaryKey, options, config) { - const dataToSign = {}; - dataToSign.key = primaryKey; - dataToSign.bind = subkey; - const signatureProperties = { signatureType: enums.signature.subkeyBinding }; - if (options.sign) { - signatureProperties.keyFlags = [enums.keyFlags.signData]; - signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, { - signatureType: enums.signature.keyBinding - }, options.date, undefined, undefined, undefined, config); - } else { - signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; - } - const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); - return subkeySignaturePacket; -} - -/** - * Returns the preferred signature hash algorithm of a key - * @param {Key} [key] - The key to get preferences from - * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} config - full configuration - * @returns {Promise} - * @async - */ -async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) { - let hashAlgo = config.preferredHashAlgorithm; - let prefAlgo = hashAlgo; - if (key) { - const primaryUser = await key.getPrimaryUser(date, userID, config); - if (primaryUser.selfCertification.preferredHashAlgorithms) { - [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; - } - } - switch (keyPacket.algorithm) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ed25519: - prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid); - } - return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; -} - -/** - * Returns the preferred symmetric/aead/compression algorithm for a set of keys - * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return - * @param {Array} [keys] - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Preferred algorithm - * @async - */ -async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) { - const defaultAlgo = { // these are all must-implement in rfc4880bis - 'symmetric': enums.symmetric.aes128, - 'aead': enums.aead.eax, - 'compression': enums.compression.uncompressed - }[type]; - const preferredSenderAlgo = { - 'symmetric': config$1.preferredSymmetricAlgorithm, - 'aead': config$1.preferredAEADAlgorithm, - 'compression': config$1.preferredCompressionAlgorithm - }[type]; - const prefPropertyName = { - 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAEADAlgorithms', - 'compression': 'preferredCompressionAlgorithms' - }[type]; - - // if preferredSenderAlgo appears in the prefs of all recipients, we pick it - // otherwise we use the default algo - // if no keys are available, preferredSenderAlgo is returned - const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; - return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; - })); - return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; -} - -/** - * Create signature packet - * @param {Object} dataToSign - Contains packets to be signed - * @param {PrivateKey} privateKey - key to get preferences from - * @param {SecretKeyPacket| - * SecretSubkeyPacket} signingKeyPacket secret key packet for signing - * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing - * @param {Date} [date] - Override the creationtime of the signature - * @param {Object} [userID] - User ID - * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [detached] - Whether to create a detached signature packet - * @param {Object} config - full configuration - * @returns {Promise} Signature packet. - */ -async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) { - if (signingKeyPacket.isDummy()) { - throw new Error('Cannot sign with a gnu-dummy key.'); - } - if (!signingKeyPacket.isDecrypted()) { - throw new Error('Signing key is not decrypted.'); - } - const signaturePacket = new SignaturePacket(); - Object.assign(signaturePacket, signatureProperties); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config); - signaturePacket.rawNotations = notations; - await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached); - return signaturePacket; -} - -/** - * Merges signatures from source[attr] to dest[attr] - * @param {Object} source - * @param {Object} dest - * @param {String} attr - * @param {Date} [date] - date to use for signature expiration check, instead of the current time - * @param {Function} [checkFn] - signature only merged if true - */ -async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { - source = source[attr]; - if (source) { - if (!dest[attr].length) { - dest[attr] = source; - } else { - await Promise.all(source.map(async function(sourceSig) { - if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && - !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); - })) { - dest[attr].push(sourceSig); - } - })); - } - } -} - -/** - * Checks if a given certificate or binding signature is revoked - * @param {SecretKeyPacket| - * PublicKeyPacket} primaryKey The primary key packet - * @param {Object} dataToVerify - The data to check - * @param {Array} revocations - The revocation signatures to check - * @param {SignaturePacket} signature - The certificate or signature to check - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the signature revokes the data. - * @async - */ -async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { - key = key || primaryKey; - const revocationKeyIDs = []; - await Promise.all(revocations.map(async function(revocationSignature) { - try { - if ( - // Note: a third-party revocation signature could legitimately revoke a - // self-signature if the signature has an authorized revocation key. - // However, we don't support passing authorized revocation keys, nor - // verifying such revocation signatures. Instead, we indicate an error - // when parsing a key with an authorized revocation key, and ignore - // third-party revocation signatures here. (It could also be revoking a - // third-party key certification, which should only affect - // `verifyAllCertifications`.) - !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) - ) { - await revocationSignature.verify( - key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config - ); - - // TODO get an identifier of the revoked object instead - revocationKeyIDs.push(revocationSignature.issuerKeyID); - } - } catch (e) {} - })); - // TODO further verify that this is the signature that should be revoked - if (signature) { - signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : - signature.revoked || false; - return signature.revoked; - } - return revocationKeyIDs.length > 0; -} - -/** - * Returns key expiration time based on the given certification signature. - * The expiration time of the signature is ignored. - * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check - * @param {SignaturePacket} signature - signature to process - * @returns {Date|Infinity} expiration time or infinity if the key does not expire - */ -function getKeyExpirationTime(keyPacket, signature) { - let expirationTime; - // check V4 expiration time - if (signature.keyNeverExpires === false) { - expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; - } - return expirationTime ? new Date(expirationTime) : Infinity; -} - -/** - * Returns whether aead is supported by all keys in the set - * @param {Array} keys - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} config - full configuration - * @returns {Promise} - * @async - */ -async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) { - let supported = true; - // TODO replace when Promise.some or Promise.any are implemented - await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - if (!primaryUser.selfCertification.features || - !(primaryUser.selfCertification.features[0] & enums.features.aead)) { - supported = false; - } - })); - return supported; -} - -function sanitizeKeyOptions(options, subkeyDefaults = {}) { - options.type = options.type || subkeyDefaults.type; - options.curve = options.curve || subkeyDefaults.curve; - options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; - options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; - - options.sign = options.sign || false; - - switch (options.type) { - case 'ecc': - try { - options.curve = enums.write(enums.curve, options.curve); - } catch (e) { - throw new Error('Unknown curve'); - } - if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) { - options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; - } - if (options.sign) { - options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; - } else { - options.algorithm = enums.publicKey.ecdh; - } - break; - case 'rsa': - options.algorithm = enums.publicKey.rsaEncryptSign; - break; - default: - throw new Error(`Unsupported key type ${options.type}`); - } - return options; -} - -function isValidSigningKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.rsaEncrypt && - keyAlgo !== enums.publicKey.elgamal && - keyAlgo !== enums.publicKey.ecdh && - keyAlgo !== enums.publicKey.x25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.signData) !== 0); -} - -function isValidEncryptionKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.dsa && - keyAlgo !== enums.publicKey.rsaSign && - keyAlgo !== enums.publicKey.ecdsa && - keyAlgo !== enums.publicKey.eddsaLegacy && - keyAlgo !== enums.publicKey.ed25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0); -} - -function isValidDecryptionKeyPacket(signature, config) { - if (config.allowInsecureDecryptionWithSigningKeys) { - // This is only relevant for RSA keys, all other signing algorithms cannot decrypt - return true; - } - - return !signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; -} - -/** - * Check key against blacklisted algorithms and minimum strength requirements. - * @param {SecretKeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket - * @param {Config} config - * @throws {Error} if the key packet does not meet the requirements - */ -function checkKeyRequirements(keyPacket, config) { - const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); - const algoInfo = keyPacket.getAlgorithmInfo(); - if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { - throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); - } - switch (keyAlgo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: - case enums.publicKey.rsaEncrypt: - if (algoInfo.bits < config.minRSABits) { - throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); - } - break; - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ecdh: - if (config.rejectCurves.has(algoInfo.curve)) { - throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); - } - break; - } -} - -/** - * @module key/User - * @private - */ - -/** - * Class that represents an user ID or attribute packet and the relevant signatures. - * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info - * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with - */ -class User { - constructor(userPacket, mainKey) { - this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; - this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; - this.selfCertifications = []; - this.otherCertifications = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } - - /** - * Transforms structured user data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.userID || this.userAttribute); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.selfCertifications); - packetlist.push(...this.otherCertifications); - return packetlist; - } - - /** - * Shallow clone - * @returns {User} - */ - clone() { - const user = new User(this.userID || this.userAttribute, this.mainKey); - user.selfCertifications = [...this.selfCertifications]; - user.otherCertifications = [...this.otherCertifications]; - user.revocationSignatures = [...this.revocationSignatures]; - return user; - } - - /** - * Generate third-party certifications over this user and its primary key - * @param {Array} signingKeys - Decrypted private keys for signing - * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} New user with new certifications. - * @async - */ - async certify(signingKeys, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { - if (!privateKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - if (privateKey.hasSameFingerprintAs(primaryKey)) { - throw new Error("The user's own key can only be used for self-certifications"); - } - const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); - return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, { - // Most OpenPGP implementations use generic certification (0x10) - signatureType: enums.signature.certGeneric, - keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] - }, date, undefined, undefined, undefined, config); - })); - await user.update(this, date, config); - return user; - } - - /** - * Checks if a given certificate of the user is revoked - * @param {SignaturePacket} certificate - The certificate to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked(primaryKey, enums.signature.certRevocation, { - key: primaryKey, - userID: this.userID, - userAttribute: this.userAttribute - }, this.revocationSignatures, certificate, keyPacket, date, config$1); - } - - /** - * Verifies the user certificate. - * @param {SignaturePacket} certificate - A certificate of this user - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate - * @throws if the user certificate is invalid. - * @async - */ - async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const { issuerKeyID } = certificate; - const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); - if (issuerKeys.length === 0) { - return null; - } - await Promise.all(issuerKeys.map(async key => { - const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); - if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { - throw new Error('User certificate is revoked'); - } - try { - await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('User certificate is invalid', e); - } - })); - return true; - } - - /** - * Verifies all user certificates - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllCertifications(verificationKeys, date = new Date(), config) { - const that = this; - const certifications = this.selfCertifications.concat(this.otherCertifications); - return Promise.all(certifications.map(async certification => ({ - keyID: certification.issuerKeyID, - valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) - }))); - } - - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} Status of user. - * @throws {Error} if there are no valid self signatures. - * @async - */ - async verify(date = new Date(), config) { - if (!this.selfCertifications.length) { - throw new Error('No self-certifications found'); - } - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // TODO replace when Promise.some or Promise.any are implemented - let exception; - for (let i = this.selfCertifications.length - 1; i >= 0; i--) { - try { - const selfCertification = this.selfCertifications[i]; - if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { - throw new Error('Self-certification is revoked'); - } - try { - await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('Self-certification is invalid', e); - } - return true; - } catch (e) { - exception = e; - } - } - throw exception; - } - - /** - * Update user with new components from specified user - * @param {User} sourceUser - Source user to merge - * @param {Date} date - Date to verify the validity of signatures - * @param {Object} config - Full configuration - * @returns {Promise} - * @async - */ - async update(sourceUser, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // self signatures - await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { - try { - await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); - return true; - } catch (e) { - return false; - } - }); - // other signatures - await mergeSignatures(sourceUser, this, 'otherCertifications', date); - // revocation signatures - await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); - }); - } - - /** - * Revokes the user - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New user with revocation signature. - * @async - */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.certRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await user.update(this); - return user; - } -} - -/** - * @module key/Subkey - * @private - */ - -/** - * Class that represents a subkey packet and the relevant signatures. - * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID - * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint - * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs - * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo - * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime - * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted - */ -class Subkey { - /** - * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey - * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey - */ - constructor(subkeyPacket, mainKey) { - this.keyPacket = subkeyPacket; - this.bindingSignatures = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } - - /** - * Transforms structured subkey data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.bindingSignatures); - return packetlist; - } - - /** - * Shallow clone - * @return {Subkey} - */ - clone() { - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.bindingSignatures = [...this.bindingSignatures]; - subkey.revocationSignatures = [...this.revocationSignatures]; - return subkey; - } - - /** - * Checks if a binding signature of a subkey is revoked - * @param {SignaturePacket} signature - The binding signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the binding signature is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked( - primaryKey, enums.signature.subkeyRevocation, { - key: primaryKey, - bind: this.keyPacket - }, this.revocationSignatures, signature, key, date, config$1 - ); - } - - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} if the subkey is invalid. - * @async - */ - async verify(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - // check subkey binding signatures - const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - // check binding signature is not revoked - if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { - throw new Error('Subkey is revoked'); - } - // check for expiration time - if (isDataExpired(this.keyPacket, bindingSignature, date)) { - throw new Error('Subkey is expired'); - } - return bindingSignature; - } - - /** - * Returns the expiration time of the subkey or Infinity if key does not expire. - * Returns null if the subkey is invalid. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async - */ - async getExpirationTime(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - let bindingSignature; - try { - bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - } catch (e) { - return null; - } - const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); - const sigExpiry = bindingSignature.getExpirationTime(); - return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; - } - - /** - * Update subkey with new components from specified subkey - * @param {Subkey} subkey - Source subkey to merge - * @param {Date} [date] - Date to verify validity of signatures - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if update failed - * @async - */ - async update(subkey, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - if (!this.hasSameFingerprintAs(subkey)) { - throw new Error('Subkey update method: fingerprints of subkeys not equal'); - } - // key packet - if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && - subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { - this.keyPacket = subkey.keyPacket; - } - // update missing binding signatures - const that = this; - const dataToVerify = { key: primaryKey, bind: that.keyPacket }; - await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { - for (let i = 0; i < that.bindingSignatures.length; i++) { - if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { - if (srcBindSig.created > that.bindingSignatures[i].created) { - that.bindingSignatures[i] = srcBindSig; - } - return false; - } - } - try { - await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); - return true; - } catch (e) { - return false; - } - }); - // revocation signatures - await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); - }); - } - - /** - * Revokes the subkey - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New subkey with revocation signature. - * @async - */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { key: primaryKey, bind: this.keyPacket }; - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.subkeyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await subkey.update(this); - return subkey; - } - - hasSameFingerprintAs(other) { - return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); - } -} - -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { - Subkey.prototype[name] = - function() { - return this.keyPacket[name](); - }; -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A key revocation certificate can contain the following packets -const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); -const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); -const keyPacketTags = new Set([ - enums.packet.publicKey, enums.packet.privateKey, - enums.packet.publicSubkey, enums.packet.privateSubkey -]); - -/** - * Abstract class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. - * @borrows PublicKeyPacket#getKeyID as Key#getKeyID - * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint - * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs - * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo - * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime - */ -class Key { - /** - * Transforms packetlist to structured key data - * @param {PacketList} packetlist - The packets that form a key - * @param {Set} disallowedPackets - disallowed packet tags - */ - packetListToStructure(packetlist, disallowedPackets = new Set()) { - let user; - let primaryKeyID; - let subkey; - let ignoreUntil; - - for (const packet of packetlist) { - - if (packet instanceof UnparseablePacket) { - const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); - if (isUnparseableKeyPacket && !ignoreUntil) { - // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must - // discard all non-key packets that follow, until another (sub)key packet is found. - if (mainKeyPacketTags.has(packet.tag)) { - ignoreUntil = mainKeyPacketTags; - } else { - ignoreUntil = keyPacketTags; - } - } - continue; - } - - const tag = packet.constructor.tag; - if (ignoreUntil) { - if (!ignoreUntil.has(tag)) continue; - ignoreUntil = null; - } - if (disallowedPackets.has(tag)) { - throw new Error(`Unexpected packet type: ${tag}`); - } - switch (tag) { - case enums.packet.publicKey: - case enums.packet.secretKey: - if (this.keyPacket) { - throw new Error('Key block contains multiple keys'); - } - this.keyPacket = packet; - primaryKeyID = this.getKeyID(); - if (!primaryKeyID) { - throw new Error('Missing Key ID'); - } - break; - case enums.packet.userID: - case enums.packet.userAttribute: - user = new User(packet, this); - this.users.push(user); - break; - case enums.packet.publicSubkey: - case enums.packet.secretSubkey: - user = null; - subkey = new Subkey(packet, this); - this.subkeys.push(subkey); - break; - case enums.packet.signature: - switch (packet.signatureType) { - case enums.signature.certGeneric: - case enums.signature.certPersona: - case enums.signature.certCasual: - case enums.signature.certPositive: - if (!user) { - util.printDebug('Dropping certification signatures without preceding user packet'); - continue; - } - if (packet.issuerKeyID.equals(primaryKeyID)) { - user.selfCertifications.push(packet); - } else { - user.otherCertifications.push(packet); - } - break; - case enums.signature.certRevocation: - if (user) { - user.revocationSignatures.push(packet); - } else { - this.directSignatures.push(packet); - } - break; - case enums.signature.key: - this.directSignatures.push(packet); - break; - case enums.signature.subkeyBinding: - if (!subkey) { - util.printDebug('Dropping subkey binding signature without preceding subkey packet'); - continue; - } - subkey.bindingSignatures.push(packet); - break; - case enums.signature.keyRevocation: - this.revocationSignatures.push(packet); - break; - case enums.signature.subkeyRevocation: - if (!subkey) { - util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); - continue; - } - subkey.revocationSignatures.push(packet); - break; - } - break; - } - } - } - - /** - * Transforms structured key data to packetlist - * @returns {PacketList} The packets that form a key. - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.directSignatures); - this.users.map(user => packetlist.push(...user.toPacketList())); - this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); - return packetlist; - } - - /** - * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. - * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. - * @returns {Promise} Clone of the key. - */ - clone(clonePrivateParams = false) { - const key = new this.constructor(this.toPacketList()); - if (clonePrivateParams) { - key.getKeys().forEach(k => { - // shallow clone the key packets - k.keyPacket = Object.create( - Object.getPrototypeOf(k.keyPacket), - Object.getOwnPropertyDescriptors(k.keyPacket) - ); - if (!k.keyPacket.isDecrypted()) return; - // deep clone the private params, which are cleared during encryption - const privateParams = {}; - Object.keys(k.keyPacket.privateParams).forEach(name => { - privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); - }); - k.keyPacket.privateParams = privateParams; - }); - } - return key; - } - - /** - * Returns an array containing all public or private subkeys matching keyID; - * If no keyID is given, returns all subkeys. - * @param {type/keyID} [keyID] - key ID to look for - * @returns {Array} array of subkeys - */ - getSubkeys(keyID = null) { - const subkeys = this.subkeys.filter(subkey => ( - !keyID || subkey.getKeyID().equals(keyID, true) - )); - return subkeys; - } - - /** - * Returns an array containing all public or private keys matching keyID. - * If no keyID is given, returns all keys, starting with the primary key. - * @param {type/keyid~KeyID} [keyID] - key ID to look for - * @returns {Array} array of keys - */ - getKeys(keyID = null) { - const keys = []; - if (!keyID || this.getKeyID().equals(keyID, true)) { - keys.push(this); - } - return keys.concat(this.getSubkeys(keyID)); - } - - /** - * Returns key IDs of all keys - * @returns {Array} - */ - getKeyIDs() { - return this.getKeys().map(key => key.getKeyID()); - } - - /** - * Returns userIDs - * @returns {Array} Array of userIDs. - */ - getUserIDs() { - return this.users.map(user => { - return user.userID ? user.userID.userID : null; - }).filter(userID => userID !== null); - } - - /** - * Returns binary encoded key - * @returns {Uint8Array} Binary key. - */ - write() { - return this.toPacketList().write(); - } - - /** - * Returns last created key or key by given keyID that is available for signing and verification - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} signing key - * @throws if no valid signing key was found - * @async - */ - async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature( - subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 - ); - if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) { - continue; - } - if (!bindingSignature.embeddedSignature) { - throw new Error('Missing embedded signature'); - } - // verify embedded signature - await getLatestValidSignature( - [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 - ); - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } catch (e) { - exception = e; - } - } - } - - try { - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; - } - throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); - } - - /** - * Returns last created key or key by given keyID that is available for encryption or decryption - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} encryption key - * @throws if no valid encryption key was found - * @async - */ - async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - // V4: by convention subkeys are preferred for encryption service - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) { - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } - } catch (e) { - exception = e; - } - } - } - - try { - // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; - } - throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); - } - - /** - * Checks if a signature on a key is revoked - * @param {SignaturePacket} signature - The signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - return isDataRevoked( - this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 - ); - } - - /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature. Throws if the primary key is invalid. - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} If key verification failed - * @async - */ - async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - // check for key revocation signatures - if (await this.isRevoked(null, null, date, config$1)) { - throw new Error('Primary key is revoked'); - } - // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); - // check for expiration time in binding signatures - if (isDataExpired(primaryKey, selfCertification, date)) { - throw new Error('Primary key is expired'); - } - // check for expiration time in direct signatures - const directSignature = await getLatestValidSignature( - this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 - ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key - - if (directSignature && isDataExpired(primaryKey, directSignature, date)) { - throw new Error('Primary key is expired'); - } - } - - /** - * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. - * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. - * @param {Object} [userID] - User ID to consider instead of the primary user - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async - */ - async getExpirationTime(userID, config$1 = config) { - let primaryKeyExpiry; - try { - const { selfCertification } = await this.getPrimaryUser(null, userID, config$1); - const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); - const selfSigExpiry = selfCertification.getExpirationTime(); - const directSignature = await getLatestValidSignature( - this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 - ).catch(() => {}); - if (directSignature) { - const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); - // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, - // causing a discountinous validy period for the key - primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); - } else { - primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; - } - } catch (e) { - primaryKeyExpiry = null; - } - - return util.normalizeDate(primaryKeyExpiry); - } - - - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * user: User, - * selfCertification: SignaturePacket - * }>} The primary user and the self signature - * @async - */ - async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const users = []; - let exception; - for (let i = 0; i < this.users.length; i++) { - try { - const user = this.users[i]; - if (!user.userID) { - continue; - } - if ( - (userID.name !== undefined && user.userID.name !== userID.name) || - (userID.email !== undefined && user.userID.email !== userID.email) || - (userID.comment !== undefined && user.userID.comment !== userID.comment) - ) { - throw new Error('Could not find user that matches that user ID'); - } - const dataToVerify = { userID: user.userID, key: primaryKey }; - const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); - users.push({ index: i, user, selfCertification }); - } catch (e) { - exception = e; - } - } - if (!users.length) { - throw exception || new Error('Could not find primary user'); - } - await Promise.all(users.map(async function (a) { - return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); - })); - // sort by primary user flag and signature creation time - const primaryUser = users.sort(function(a, b) { - const A = a.selfCertification; - const B = b.selfCertification; - return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; - }).pop(); - const { user, selfCertification: cert } = primaryUser; - if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { - throw new Error('Primary user is revoked'); - } - return primaryUser; - } - - /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * - * If the source key is a private key and the destination key is public, - * a private key is returned. - * @param {Key} sourceKey - Source key to merge - * @param {Date} [date] - Date to verify validity of signatures and keys - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} updated key - * @async - */ - async update(sourceKey, date = new Date(), config$1 = config) { - if (!this.hasSameFingerprintAs(sourceKey)) { - throw new Error('Primary key fingerprints must be equal to update the key'); - } - if (!this.isPrivate() && sourceKey.isPrivate()) { - // check for equal subkey packets - const equal = (this.subkeys.length === sourceKey.subkeys.length) && - (this.subkeys.every(destSubkey => { - return sourceKey.subkeys.some(srcSubkey => { - return destSubkey.hasSameFingerprintAs(srcSubkey); - }); - })); - if (!equal) { - throw new Error('Cannot update public key with private key if subkeys mismatch'); - } - - return sourceKey.update(this, config$1); - } - // from here on, either: - // - destination key is private, source key is public - // - the keys are of the same type - // hence we don't need to convert the destination key type - const updatedKey = this.clone(); - // revocation signatures - await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { - return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); - }); - // direct signatures - await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); - // update users - await Promise.all(sourceKey.users.map(async srcUser => { - // multiple users with the same ID/attribute are not explicitly disallowed by the spec - // hence we support them, just in case - const usersToUpdate = updatedKey.users.filter(dstUser => ( - (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || - (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) - )); - if (usersToUpdate.length > 0) { - await Promise.all( - usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) - ); - } else { - const newUser = srcUser.clone(); - newUser.mainKey = updatedKey; - updatedKey.users.push(newUser); - } - })); - // update subkeys - await Promise.all(sourceKey.subkeys.map(async srcSubkey => { - // multiple subkeys with same fingerprint might be preset - const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( - dstSubkey.hasSameFingerprintAs(srcSubkey) - )); - if (subkeysToUpdate.length > 0) { - await Promise.all( - subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) - ); - } else { - const newSubkey = srcSubkey.clone(); - newSubkey.mainKey = updatedKey; - updatedKey.subkeys.push(newSubkey); - } - })); - - return updatedKey; - } - - /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Armored revocation certificate. - * @async - */ - async getRevocationCertificate(date = new Date(), config$1 = config) { - const dataToVerify = { key: this.keyPacket }; - const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); - const packetlist = new PacketList(); - packetlist.push(revocationSignature); - return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); - } - - /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param {String} revocationCertificate - armored revocation certificate - * @param {Date} [date] - Date to verify the certificate - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Revoked key. - * @async - */ - async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { - const input = await unarmor(revocationCertificate, config$1); - const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); - const revocationSignature = packetlist.findPacket(enums.packet.signature); - if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { - throw new Error('Could not find revocation signature packet'); - } - if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { - throw new Error('Revocation signature does not match key'); - } - try { - await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); - } catch (e) { - throw util.wrapError('Could not verify revocation signature', e); - } - const key = this.clone(); - key.revocationSignatures.push(revocationSignature); - return key; - } - - /** - * Signs primary user of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signPrimaryUser(privateKeys, date, userID, config$1 = config) { - const { index, user } = await this.getPrimaryUser(date, userID, config$1); - const userSign = await user.certify(privateKeys, date, config$1); - const key = this.clone(); - key.users[index] = userSign; - return key; - } - - /** - * Signs all users of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for signing, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signAllUsers(privateKeys, date = new Date(), config$1 = config) { - const key = this.clone(); - key.users = await Promise.all(this.users.map(function(user) { - return user.certify(privateKeys, date, config$1); - })); - return key; - } - - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { - const primaryKey = this.keyPacket; - const { user } = await this.getPrimaryUser(date, userID, config$1); - const results = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - return results; - } - - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of userID, signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { - const primaryKey = this.keyPacket; - const results = []; - await Promise.all(this.users.map(async user => { - const signatures = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - - results.push(...signatures.map( - signature => ({ - userID: user.userID ? user.userID.userID : null, - userAttribute: user.userAttribute, - keyID: signature.keyID, - valid: signature.valid - })) - ); - })); - return results; - } -} - -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { - Key.prototype[name] = - Subkey.prototype[name]; -}); - -// This library is free software; you can redistribute it and/or - -/** - * Class that represents an OpenPGP Public Key - */ -class PublicKey extends Key { - /** - * @param {PacketList} packetlist - The packets that form this key - */ - constructor(packetlist) { - super(); - this.keyPacket = null; - this.revocationSignatures = []; - this.directSignatures = []; - this.users = []; - this.subkeys = []; - if (packetlist) { - this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing public-key packet'); - } - } - } - - /** - * Returns true if this is a private key - * @returns {false} - */ - isPrivate() { - return false; - } - - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - return this; - } - - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); - } -} - -/** - * Class that represents an OpenPGP Private key - */ -class PrivateKey extends PublicKey { - /** - * @param {PacketList} packetlist - The packets that form this key - */ - constructor(packetlist) { - super(); - this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing private-key packet'); - } - } - - /** - * Returns true if this is a private key - * @returns {Boolean} - */ - isPrivate() { - return true; - } - - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - const packetlist = new PacketList(); - const keyPackets = this.toPacketList(); - for (const keyPacket of keyPackets) { - switch (keyPacket.constructor.tag) { - case enums.packet.secretKey: { - const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); - packetlist.push(pubKeyPacket); - break; - } - case enums.packet.secretSubkey: { - const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); - packetlist.push(pubSubkeyPacket); - break; - } - default: - packetlist.push(keyPacket); - } - } - return new PublicKey(packetlist); - } - - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); - } - - /** - * Returns all keys that are available for decryption, matching the keyID when given - * This is useful to retrieve keys for session key decryption - * @param {module:type/keyid~KeyID} keyID, optional - * @param {Date} date, optional - * @param {String} userID, optional - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} Array of decryption keys. - * @async - */ - async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const keys = []; - for (let i = 0; i < this.subkeys.length; i++) { - if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { - try { - const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; - const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidDecryptionKeyPacket(bindingSignature, config$1)) { - keys.push(this.subkeys[i]); - } - } catch (e) {} - } - } - - // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && - isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) { - keys.push(this); - } - - return keys; - } - - /** - * Returns true if the primary key or any subkey is decrypted. - * A dummy key is considered encrypted. - */ - isDecrypted() { - return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); - } - - /** - * Check whether the private and public primary key parameters correspond - * Together with verification of binding signatures, this guarantees key integrity - * In case of gnu-dummy primary key, it is enough to validate any signing subkeys - * otherwise all encryption subkeys are validated - * If only gnu-dummy keys are found, we cannot properly validate so we throw an error - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if validation was not successful and the key cannot be trusted - * @async - */ - async validate(config$1 = config) { - if (!this.isPrivate()) { - throw new Error('Cannot validate a public key'); - } - - let signingKeyPacket; - if (!this.keyPacket.isDummy()) { - signingKeyPacket = this.keyPacket; - } else { - /** - * It is enough to validate any signing keys - * since its binding signatures are also checked - */ - const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); - // This could again be a dummy key - if (signingKey && !signingKey.keyPacket.isDummy()) { - signingKeyPacket = signingKey.keyPacket; - } - } - - if (signingKeyPacket) { - return signingKeyPacket.validate(); - } else { - const keys = this.getKeys(); - const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); - if (allDummies) { - throw new Error('Cannot validate an all-gnu-dummy key'); - } - - return Promise.all(keys.map(async key => key.keyPacket.validate())); - } - } - - /** - * Clear private key parameters - */ - clearPrivateParams() { - this.getKeys().forEach(({ keyPacket }) => { - if (keyPacket.isDecrypted()) { - keyPacket.clearPrivateParams(); - } - }); - } - - /** - * Revokes the key - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New key with revocation signature. - * @async - */ - async revoke( - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - if (!this.isPrivate()) { - throw new Error('Need private key for revoking'); - } - const dataToSign = { key: this.keyPacket }; - const key = this.clone(); - key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, undefined, config$1)); - return key; - } - - - /** - * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. - * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. - * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA - * @param {String} options.curve (optional) Elliptic curve for ECC keys - * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date (optional) Override the creation date of the key and the key signatures - * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false - * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} - * @async - */ - async addSubkey(options = {}) { - const config$1 = { ...config, ...options.config }; - if (options.passphrase) { - throw new Error('Subkey could not be encrypted here, please encrypt whole key'); - } - if (options.rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); - } - const secretKeyPacket = this.keyPacket; - if (secretKeyPacket.isDummy()) { - throw new Error('Cannot add subkey to gnu-dummy primary key'); - } - if (!secretKeyPacket.isDecrypted()) { - throw new Error('Key is not decrypted'); - } - const defaultOptions = secretKeyPacket.getAlgorithmInfo(); - defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA - defaultOptions.rsaBits = defaultOptions.bits || 4096; - defaultOptions.curve = defaultOptions.curve || 'curve25519'; - options = sanitizeKeyOptions(options, defaultOptions); - const keyPacket = await generateSecretSubkey(options); - checkKeyRequirements(keyPacket, config$1); - const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); - const packetList = this.toPacketList(); - packetList.push(keyPacket, bindingSignature); - return new PrivateKey(packetList); - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -// A Key can contain the following packets -const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ - PublicKeyPacket, - PublicSubkeyPacket, - SecretKeyPacket, - SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, - SignaturePacket -]); - -/** - * Creates a PublicKey or PrivateKey depending on the packetlist in input - * @param {PacketList} - packets to parse - * @return {Key} parsed key - * @throws if no key packet was found - */ -function createKey(packetlist) { - for (const packet of packetlist) { - switch (packet.constructor.tag) { - case enums.packet.secretKey: - return new PrivateKey(packetlist); - case enums.packet.publicKey: - return new PublicKey(packetlist); - } - } - throw new Error('No key packet found'); -} - - -/** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * By default, primary and subkeys will be of same type. - * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA - * @param {String} options.curve Elliptic curve for ECC keys - * @param {Integer} options.rsaBits Number of bits for RSA keys - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Creation date of the key and the key signatures - * @param {Object} config - Full configuration - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ -async function generate$4(options, config) { - options.sign = true; // primary key is always a signing key - options = sanitizeKeyOptions(options); - options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); - let promises = [generateSecretKey(options, config)]; - promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); - const packets = await Promise.all(promises); - - const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; -} - -/** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param {PrivateKey} options.privateKey The private key to reformat - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Override the creation date of the key signatures - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * @param {Object} config - Full configuration - * - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ -async function reformat(options, config) { - options = sanitize(options); - const { privateKey } = options; - - if (!privateKey.isPrivate()) { - throw new Error('Cannot reformat a public key'); - } - - if (privateKey.keyPacket.isDummy()) { - throw new Error('Cannot reformat a gnu-dummy primary key'); - } - - const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); - if (!isDecrypted) { - throw new Error('Key is not decrypted'); - } - - const secretKeyPacket = privateKey.keyPacket; - - if (!options.subkeys) { - options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { - const secretSubkeyPacket = subkey.keyPacket; - const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; - const bindingSignature = await ( - getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) - ).catch(() => ({})); - return { - sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) - }; - })); - } - - const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); - if (options.subkeys.length !== secretSubkeyPackets.length) { - throw new Error('Number of subkey options does not match number of subkeys'); - } - - options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); - - const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; - - function sanitize(options, subkeyDefaults = {}) { - options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; - - return options; - } -} - -/** - * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection - * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. - * @param {SecretKeyPacket} secretKeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPackets - * @param {Object} options - * @param {Object} config - Full configuration - * @returns {PrivateKey} - */ -async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { - // set passphrase protection - if (options.passphrase) { - await secretKeyPacket.encrypt(options.passphrase, config); - } - - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - await secretSubkeyPacket.encrypt(subkeyPassphrase, config); - } - })); - - const packetlist = new PacketList(); - packetlist.push(secretKeyPacket); - - await Promise.all(options.userIDs.map(async function(userID, index) { - function createPreferredAlgos(algos, preferredAlgo) { - return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; - } - - const userIDPacket = UserIDPacket.fromObject(userID); - const dataToSign = {}; - dataToSign.userID = userIDPacket; - dataToSign.key = secretKeyPacket; - - const signatureProperties = {}; - signatureProperties.signatureType = enums.signature.certGeneric; - signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; - signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([ - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) - enums.symmetric.aes256, - enums.symmetric.aes128, - enums.symmetric.aes192 - ], config.preferredSymmetricAlgorithm); - if (config.aeadProtect) { - signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([ - enums.aead.eax, - enums.aead.ocb - ], config.preferredAEADAlgorithm); - } - signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ - // prefer fast asm.js implementations (SHA-256) - enums.hash.sha256, - enums.hash.sha512 - ], config.preferredHashAlgorithm); - signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ - enums.compression.zlib, - enums.compression.zip, - enums.compression.uncompressed - ], config.preferredCompressionAlgorithm); - if (index === 0) { - signatureProperties.isPrimaryUserID = true; - } - // integrity protection always enabled - signatureProperties.features = [0]; - signatureProperties.features[0] |= enums.features.modificationDetection; - if (config.aeadProtect) { - signatureProperties.features[0] |= enums.features.aead; - } - if (config.v5Keys) { - signatureProperties.features[0] |= enums.features.v5Keys; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; - } - - const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); - - return { userIDPacket, signaturePacket }; - })).then(list => { - list.forEach(({ userIDPacket, signaturePacket }) => { - packetlist.push(userIDPacket); - packetlist.push(signaturePacket); - }); - }); - - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyOptions = options.subkeys[index]; - const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); - return { secretSubkeyPacket, subkeySignaturePacket }; - })).then(packets => { - packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { - packetlist.push(secretSubkeyPacket); - packetlist.push(subkeySignaturePacket); - }); - }); - - // Add revocation signature packet for creating a revocation certificate. - // This packet should be removed before returning the key. - const dataToSign = { key: secretKeyPacket }; - packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.reasonForRevocation.noReason, - reasonForRevocationString: '' - }, options.date, undefined, undefined, undefined, config)); - - if (options.passphrase) { - secretKeyPacket.clearPrivateParams(); - } - - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - secretSubkeyPacket.clearPrivateParams(); - } - })); - - return new PrivateKey(packetlist); -} - -/** - * Reads an (optionally armored) OpenPGP key and returns a key object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static - */ -async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { - throw new Error('Armored text not of type key'); - } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return createKey(packetlist); -} - -/** - * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static - */ -async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readPrivateKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.privateKey)) { - throw new Error('Armored text not of type private key'); - } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return new PrivateKey(packetlist); -} - -/** - * Reads an (optionally armored) OpenPGP key block and returns a list of key objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static - */ -async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { - throw new Error('Armored text not of type key'); - } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = createKey(oneKeyList); - keys.push(newKey); - } - return keys; -} - -/** - * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static - */ -async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readPrivateKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); - } - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.privateKey) { - throw new Error('Armored text not of type private key'); - } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No secret key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = new PrivateKey(oneKeyList); - keys.push(newKey); - } - return keys; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Message can contain the following packets -const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - AEADEncryptedDataPacket, - SymEncryptedIntegrityProtectedDataPacket, - SymmetricallyEncryptedDataPacket, - PublicKeyEncryptedSessionKeyPacket, - SymEncryptedSessionKeyPacket, - OnePassSignaturePacket, - SignaturePacket -]); -// A SKESK packet can contain the following packets -const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); -// A detached signature can contain the following packets -const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - -/** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} - */ -class Message { - /** - * @param {PacketList} packetlist - The packets that form this message - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); - } - - /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns {Array} Array of keyID objects. - */ - getEncryptionKeyIDs() { - const keyIDs = []; - const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - pkESKeyPacketlist.forEach(function(packet) { - keyIDs.push(packet.publicKeyID); - }); - return keyIDs; - } - - /** - * Returns the key IDs of the keys that signed the message - * @returns {Array} Array of keyID objects. - */ - getSigningKeyIDs() { - const msg = this.unwrapCompressed(); - // search for one pass signatures - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); - if (onePassSigList.length > 0) { - return onePassSigList.map(packet => packet.issuerKeyID); - } - // if nothing found look for signature packets - const signatureList = msg.packets.filterByTag(enums.packet.signature); - return signatureList.map(packet => packet.issuerKeyID); - } - - /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Date} [date] - Use the given date for key verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with decrypted content. - * @async - */ - async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { - const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - - const symEncryptedPacketlist = this.packets.filterByTag( - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ); - - if (symEncryptedPacketlist.length === 0) { - throw new Error('No encrypted data found'); - } - - const symEncryptedPacket = symEncryptedPacketlist[0]; - let exception = null; - const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { - if (!util.isUint8Array(data) || !util.isString(algorithmName)) { - throw new Error('Invalid session key for decryption.'); - } - - try { - const algo = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.decrypt(algo, data, config$1); - } catch (e) { - util.printDebugError(e); - exception = e; - } - })); - // We don't await stream.cancel here because it only returns when the other copy is canceled too. - cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. - symEncryptedPacket.encrypted = null; - await decryptedPromise; - - if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { - throw exception || new Error('Decryption failed.'); - } - - const resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - - return resultMsg; - } - - /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Date} [date] - Use the given date for key verification, instead of current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} array of object with potential sessionKey, algorithm pairs - * @async - */ - async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) { - let decryptedSessionKeyPackets = []; - - let exception; - if (passwords) { - const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); - if (skeskPackets.length === 0) { - throw new Error('No symmetrically encrypted session key packet found.'); - } - await Promise.all(passwords.map(async function(password, i) { - let packets; - if (i) { - packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); - } else { - packets = skeskPackets; - } - await Promise.all(packets.map(async function(skeskPacket) { - try { - await skeskPacket.decrypt(password); - decryptedSessionKeyPackets.push(skeskPacket); - } catch (err) { - util.printDebugError(err); - } - })); - })); - } else if (decryptionKeys) { - const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - if (pkeskPackets.length === 0) { - throw new Error('No public key encrypted session key packet found.'); - } - await Promise.all(pkeskPackets.map(async function(pkeskPacket) { - await Promise.all(decryptionKeys.map(async function(decryptionKey) { - let algos = [ - enums.symmetric.aes256, // Old OpenPGP.js default fallback - enums.symmetric.aes128, // RFC4880bis fallback - enums.symmetric.tripledes, // RFC4880 fallback - enums.symmetric.cast5 // Golang OpenPGP fallback - ]; - try { - const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere. - if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { - algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); - } - } catch (e) {} - - // do not check key expiration to allow decryption of old messages - const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); - await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { - if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) { - return; - } - if (!decryptionKeyPacket.isDecrypted()) { - throw new Error('Decryption key is not decrypted.'); - } - - // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. - const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal - ); - - if (doConstantTimeDecryption) { - // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, - // either with the successfully decrypted session key, or with a randomly generated one. - // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on - // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: - // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the - // randomly generated keys of the remaining key types. - // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly - // generated session keys. - // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. - - const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times - await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => { - const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); - pkeskPacketCopy.read(serialisedPKESK); - const randomSessionKey = { - sessionKeyAlgorithm, - sessionKey: mod.generateSessionKey(sessionKeyAlgorithm) - }; - try { - await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); - decryptedSessionKeyPackets.push(pkeskPacketCopy); - } catch (err) { - // `decrypt` can still throw some non-security-sensitive errors - util.printDebugError(err); - exception = err; - } - })); - - } else { - try { - await pkeskPacket.decrypt(decryptionKeyPacket); - if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) { - throw new Error('A non-preferred symmetric algorithm was used.'); - } - decryptedSessionKeyPackets.push(pkeskPacket); - } catch (err) { - util.printDebugError(err); - exception = err; - } - } - })); - })); - cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. - pkeskPacket.encrypted = null; - })); - } else { - throw new Error('No key or password specified.'); - } - - if (decryptedSessionKeyPackets.length > 0) { - // Return only unique session keys - if (decryptedSessionKeyPackets.length > 1) { - const seen = new Set(); - decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { - const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); - if (seen.has(k)) { - return false; - } - seen.add(k); - return true; - }); - } - - return decryptedSessionKeyPackets.map(packet => ({ - data: packet.sessionKey, - algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm) - })); - } - throw exception || new Error('Session key decryption failed.'); - } - - /** - * Get literal data that is the body of the message - * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. - */ - getLiteralData() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getBytes()) || null; - } - - /** - * Get filename from literal data packet - * @returns {(String|null)} Filename of literal data packet as string. - */ - getFilename() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getFilename()) || null; - } - - /** - * Get literal data as text - * @returns {(String|null)} Literal body of the message interpreted as text. - */ - getText() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - if (literal) { - return literal.getText(); - } - return null; - } - - /** - * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. - * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for - * @param {Date} [date] - Date to select algorithm preferences at - * @param {Array} [userIDs] - User IDs to select algorithm preferences for - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. - * @async - */ - static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { - const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1); - const algorithmName = enums.read(enums.symmetric, algo); - const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ? - enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) : - undefined; - - await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() - .catch(() => null) // ignore key strength requirements - .then(maybeKey => { - if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) { - throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); - } - }) - )); - - const sessionKeyData = mod.generateSessionKey(algo); - return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName }; - } - - /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - Password(s) for message encryption - * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] - * @param {Date} [date] - Override the creation date of the literal package - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async - */ - async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - if (sessionKey) { - if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { - throw new Error('Invalid session key for encryption.'); - } - } else if (encryptionKeys && encryptionKeys.length) { - sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); - } else if (passwords && passwords.length) { - sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); - } else { - throw new Error('No keys, passwords, or session key provided.'); - } - - const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; - - const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); - - let symEncryptedPacket; - if (aeadAlgorithmName) { - symEncryptedPacket = new AEADEncryptedDataPacket(); - symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName); - } else { - symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); - } - symEncryptedPacket.packets = this.packets; - - const algorithm = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); - - msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new PacketList(); // remove packets after encryption - return msg; - } - - /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param {Uint8Array} sessionKey - session key for encryption - * @param {String} algorithmName - session key algorithm - * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - For message encryption - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [date] - Override the date - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async - */ - static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - const packetlist = new PacketList(); - const algorithm = enums.write(enums.symmetric, algorithmName); - const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); - - if (encryptionKeys) { - const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { - const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = algorithm; - await pkESKeyPacket.encrypt(encryptionKey.keyPacket); - delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption - return pkESKeyPacket; - })); - packetlist.push(...results); - } - if (passwords) { - const testDecrypt = async function(keyPacket, password) { - try { - await keyPacket.decrypt(password); - return 1; - } catch (e) { - return 0; - } - }; - - const sum = (accumulator, currentValue) => accumulator + currentValue; - - const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { - const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); - symEncryptedSessionKeyPacket.sessionKey = sessionKey; - symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; - if (aeadAlgorithm) { - symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; - } - await symEncryptedSessionKeyPacket.encrypt(password, config$1); - - if (config$1.passwordCollisionCheck) { - const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); - if (results.reduce(sum) !== 1) { - return encryptPassword(sessionKey, algorithm, password); - } - } - - delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption - return symEncryptedSessionKeyPacket; - }; - - const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd))); - packetlist.push(...results); - } - - return new Message(packetlist); - } - - /** - * Sign the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to add to the message - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with signed content. - * @async - */ - async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const packetlist = new PacketList(); - - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } - - let i; - let existingSigPacketlist; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; - - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signaturePacket.signatureType; - onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; - onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyID = signaturePacket.issuerKeyID; - if (!signingKeys.length && i === 0) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); - } - } - - await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) { - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i]; - const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1); - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1); - onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyID = signingKey.getKeyID(); - if (i === signingKeys.length - 1) { - onePassSig.flags = 1; - } - return onePassSig; - })).then(onePassSignatureList => { - onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig)); - }); - - packetlist.push(literalDataPacket); - packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1))); - - return new Message(packetlist); - } - - /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param {module:enums.compression} algo - compression algorithm - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Message} New message with compressed content. - */ - compress(algo, config$1 = config) { - if (algo === enums.compression.uncompressed) { - return this; - } - - const compressed = new CompressedDataPacket(config$1); - compressed.algorithm = algo; - compressed.packets = this.packets; - - const packetList = new PacketList(); - packetList.push(compressed); - - return new Message(packetList); - } - - /** - * Create a detached signature for the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New detached signature of message content. - * @async - */ - async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } - return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - } - - /** - * Verify message signatures - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signatures. - * @async - */ - async verify(verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); - } - if (isArrayStream(msg.packets.stream)) { - msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); - } - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); - const signatureList = msg.packets.filterByTag(enums.packet.signature); - if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { - await Promise.all(onePassSigList.map(async onePassSig => { - onePassSig.correspondingSig = new Promise((resolve, reject) => { - onePassSig.correspondingSigResolve = resolve; - onePassSig.correspondingSigReject = reject; - }); - onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); - onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); - onePassSig.hashed.catch(() => {}); - })); - msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { - const reader = getReader(readable); - const writer = getWriter(writable); - try { - for (let i = 0; i < onePassSigList.length; i++) { - const { value: signature } = await reader.read(); - onePassSigList[i].correspondingSigResolve(signature); - } - await reader.readToEnd(); - await writer.ready; - await writer.close(); - } catch (e) { - onePassSigList.forEach(onePassSig => { - onePassSig.correspondingSigReject(e); - }); - await writer.abort(e); - } - }); - return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); - } - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); - } - - /** - * Verify detached message signature - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Signature} signature - * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); - } - const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); - } - - /** - * Unwrap compressed message - * @returns {Message} Message Content of compressed message. - */ - unwrapCompressed() { - const compressed = this.packets.filterByTag(enums.packet.compressedData); - if (compressed.length) { - return new Message(compressed[0].packets); - } - return this; - } - - /** - * Append signature to unencrypted message object - * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async appendSignature(detachedSignature, config$1 = config) { - await this.packets.read( - util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, - allowedDetachedSignaturePackets, - config$1 - ); - } - - /** - * Returns binary encoded message - * @returns {ReadableStream} Binary message. - */ - write() { - return this.packets.write(); - } - - /** - * Returns ASCII armored text of message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.message, this.write(), null, null, null, config$1); - } -} - -/** - * Create signature packets for the message - * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign - * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to append - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Boolean} [detached] - Whether to create detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} List of signature packets. - * @async - * @private - */ -async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) { - const packetlist = new PacketList(); - - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; - - await Promise.all(signingKeys.map(async (primaryKey, i) => { - const userID = userIDs[i]; - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1); - return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1); - })).then(signatureList => { - packetlist.push(...signatureList); - }); - - if (signature) { - const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - packetlist.push(...existingSigPacketlist); - } - return packetlist; -} - -/** - * Create object containing signer's keyID and validity of signature - * @param {SignaturePacket} signature - Signature packet - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Check signature validity with respect to the given date - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * keyID: module:type/keyid~KeyID, - * signature: Promise, - * verified: Promise - * }>} signer's keyID and validity of signature - * @async - * @private - */ -async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - let primaryKey; - let unverifiedSigningKey; - - for (const key of verificationKeys) { - const issuerKeys = key.getKeys(signature.issuerKeyID); - if (issuerKeys.length > 0) { - primaryKey = key; - unverifiedSigningKey = issuerKeys[0]; - break; - } - } - - const isOnePassSignature = signature instanceof OnePassSignaturePacket; - const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; - - const verifiedSig = { - keyID: signature.issuerKeyID, - verified: (async () => { - if (!unverifiedSigningKey) { - throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); - } - - await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); - const signaturePacket = await signaturePacketPromise; - if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { - throw new Error('Key is newer than the signature'); - } - // We pass the signature creation time to check whether the key was expired at the time of signing. - // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before - try { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); - } catch (e) { - // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, - // making the key invalid at the time of signing. - // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. - // Note: we do not support the edge case of a key that was reformatted and it has expired. - if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); - } else { - throw e; - } - } - return true; - })(), - signature: (async () => { - const signaturePacket = await signaturePacketPromise; - const packetlist = new PacketList(); - signaturePacket && packetlist.push(signaturePacket); - return new Signature(packetlist); - })() - }; - - // Mark potential promise rejections as "handled". This is needed because in - // some cases, we reject them before the user has a reasonable chance to - // handle them (e.g. `await readToEnd(result.data); await result.verified` and - // the data stream errors). - verifiedSig.signature.catch(() => {}); - verifiedSig.verified.catch(() => {}); - - return verifiedSig; -} - -/** - * Create list of objects containing signer's keyID and validity of signature - * @param {Array} signatureList - Array of signature packets - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} date - Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) - * @async - * @private - */ -async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - return Promise.all(signatureList.filter(function(signature) { - return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); - }).map(async function(signature) { - return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); - })); -} - -/** - * Reads an (optionally armored) OpenPGP message and returns a Message object - * @param {Object} options - * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed - * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New message object. - * @async - * @static - */ -async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredMessage || binaryMessage; - if (!input) { - throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); - } - if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { - throw new Error('readMessage: options.armoredMessage must be a string or stream'); - } - if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { - throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - if (armoredMessage) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.message) { - throw new Error('Armored text not of type message'); - } - input = data; - } - const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); - const message = new Message(packetlist); - message.fromStream = streamType; - return message; -} - -/** - * Creates new message object from text or binary data. - * @param {Object} options - * @param {String | ReadableStream} [options.text] - The text message contents - * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents - * @param {String} [options.filename=""] - Name of the file (if any) - * @param {Date} [options.date=current date] - Date of the message, or modification date of the file - * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type - * @returns {Promise} New message object. - * @async - * @static - */ -async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { - let input = text !== undefined ? text : binary; - if (input === undefined) { - throw new Error('createMessage: must pass options object containing `text` or `binary`'); - } - if (text && !util.isString(text) && !util.isStream(text)) { - throw new Error('createMessage: options.text must be a string or stream'); - } - if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { - throw new Error('createMessage: options.binary must be a Uint8Array or stream'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - const literalDataPacket = new LiteralDataPacket(date); - if (text !== undefined) { - literalDataPacket.setText(input, enums.write(enums.literal, format)); - } else { - literalDataPacket.setBytes(input, enums.write(enums.literal, format)); - } - if (filename !== undefined) { - literalDataPacket.setFilename(filename); - } - const literalDataPacketlist = new PacketList(); - literalDataPacketlist.push(literalDataPacket); - const message = new Message(literalDataPacketlist); - message.fromStream = streamType; - return message; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Cleartext message can contain the following packets -const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - -/** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} - */ -class CleartextMessage { - /** - * @param {String} text - The cleartext of the signed message - * @param {Signature} signature - The detached signature or an empty signature for unsigned messages - */ - constructor(text, signature) { - // remove trailing whitespace and normalize EOL to canonical form - this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); - if (signature && !(signature instanceof Signature)) { - throw new Error('Invalid signature input'); - } - this.signature = signature || new Signature(new PacketList()); - } - - /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns {Array} Array of keyID objects. - */ - getSigningKeyIDs() { - const keyIDs = []; - const signatureList = this.signature.packets; - signatureList.forEach(function(packet) { - keyIDs.push(packet.issuerKeyID); - }); - return keyIDs; - } - - /** - * Sign the cleartext message - * @param {Array} privateKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] - * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New cleartext message with signed content. - * @async - */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = new LiteralDataPacket(); - literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - return new CleartextMessage(this.text, newSignature); - } - - /** - * Verify signatures of cleartext signed message - * @param {Array} keys - Array of keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verify(keys, date = new Date(), config$1 = config) { - const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - const literalDataPacket = new LiteralDataPacket(); - // we assume that cleartext signature is generated based on UTF8 cleartext - literalDataPacket.setText(this.text); - return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); - } - - /** - * Get cleartext - * @returns {String} Cleartext of message. - */ - getText() { - // normalize end of line to \n - return this.text.replace(/\r\n/g, '\n'); - } - - /** - * Returns ASCII armored text of cleartext signed message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {String | ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - let hashes = this.signature.packets.map(function(packet) { - return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); - }); - hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); - const body = { - hash: hashes.join(), - text: this.text, - data: this.signature.packets.write() - }; - return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1); - } -} - -/** - * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param {Object} options - * @param {String} options.cleartextMessage - Text to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New cleartext message object. - * @async - * @static - */ -async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!cleartextMessage) { - throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); - } - if (!util.isString(cleartextMessage)) { - throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - const input = await unarmor(cleartextMessage); - if (input.type !== enums.armor.signed) { - throw new Error('No cleartext signed message.'); - } - const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1); - verifyHeaders$1(input.headers, packetlist); - const signature = new Signature(packetlist); - return new CleartextMessage(input.text, signature); -} - -/** - * Compare hash algorithm specified in the armor header with signatures - * @param {Array} headers - Armor headers - * @param {PacketList} packetlist - The packetlist with signature packets - * @private - */ -function verifyHeaders$1(headers, packetlist) { - const checkHashAlgos = function(hashAlgos) { - const check = packet => algo => packet.hashAlgorithm === algo; - - for (let i = 0; i < packetlist.length; i++) { - if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { - return false; - } - } - return true; - }; - - let oneHeader = null; - let hashAlgos = []; - headers.forEach(function(header) { - oneHeader = header.match(/^Hash: (.+)$/); // get header value - if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace - oneHeader = oneHeader.split(','); - oneHeader = oneHeader.map(function(hash) { - hash = hash.toLowerCase(); - try { - return enums.write(enums.hash, hash); - } catch (e) { - throw new Error('Unknown hash algorithm in armor header: ' + hash); - } - }); - hashAlgos = hashAlgos.concat(oneHeader); - } else { - throw new Error('Only "Hash" header allowed in cleartext signed message'); - } - }); - - if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { - throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { - throw new Error('Hash algorithm mismatch in armor header and signature'); - } -} - -/** - * Creates a new CleartextMessage object from text - * @param {Object} options - * @param {String} options.text - * @static - * @async - */ -async function createCleartextMessage({ text, ...rest }) { - if (!text) { - throw new Error('createCleartextMessage: must pass options object containing `text`'); - } - if (!util.isString(text)) { - throw new Error('createCleartextMessage: options.text must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - return new CleartextMessage(text); -} - -// OpenPGP.js - An OpenPGP implementation in javascript - - -////////////////////// -// // -// Key handling // -// // -////////////////////// - - -/** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. - * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. - * @param {Object} options - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys - * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: - * curve25519 (default), p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 - * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` - * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static - */ -async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key generation'); - } - if (type === 'rsa' && rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); - } - - const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - - try { - const { key, revocationCertificate } = await generate$4(options, config$1); - key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); - - return { - privateKey: formatObject(key, format, config$1), - publicKey: formatObject(key.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error generating keypair', err); - } -} - -/** - * Reformats signature packets for a key and rewraps key object. - * @param {Object} options - * @param {PrivateKey} options.privateKey - Private key to reformat - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended - * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static - */ -async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key reformat'); - } - const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - - try { - const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); - - return { - privateKey: formatObject(reformattedKey, format, config$1), - publicKey: formatObject(reformattedKey.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error reformatting keypair', err); - } -} - -/** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. - * @param {Object} options - * @param {Key} options.key - Public or private key to revoke - * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with - * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation - * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation - * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The revoked key in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or - * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise - * @async - * @static - */ -async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - try { - const revokedKey = revocationCertificate ? - await key.applyRevocationCertificate(revocationCertificate, date, config$1) : - await key.revoke(reasonForRevocation, date, config$1); - - return revokedKey.isPrivate() ? { - privateKey: formatObject(revokedKey, format, config$1), - publicKey: formatObject(revokedKey.toPublic(), format, config$1) - } : { - privateKey: null, - publicKey: formatObject(revokedKey, format, config$1) - }; - } catch (err) { - throw util.wrapError('Error revoking key', err); - } -} - -/** - * Unlock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to decrypt - * @param {String|Array} options.passphrase - The user's passphrase(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The unlocked key object. - * @async - */ -async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (!privateKey.isPrivate()) { - throw new Error('Cannot decrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); - const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; - - try { - await Promise.all(clonedPrivateKey.getKeys().map(key => ( - // try to decrypt each key with any of the given passphrases - util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) - ))); - - await clonedPrivateKey.validate(config$1); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error decrypting private key', err); - } -} - -/** - * Lock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to encrypt - * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The locked key object. - * @async - */ -async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (!privateKey.isPrivate()) { - throw new Error('Cannot encrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); - - const keys = clonedPrivateKey.getKeys(); - const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); - if (passphrases.length !== keys.length) { - throw new Error('Invalid number of passphrases given for key encryption'); - } - - try { - await Promise.all(keys.map(async (key, i) => { - const { keyPacket } = key; - await keyPacket.encrypt(passphrases[i], config$1); - keyPacket.clearPrivateParams(); - })); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error encrypting private key', err); - } -} - - -/////////////////////////////////////////// -// // -// Message encryption and decryption // -// // -/////////////////////////////////////////// - - -/** - * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` - * must be specified. If signing keys are specified, those will be used to sign the message. - * @param {Object} options - * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message - * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed - * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message - * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Signature} [options.signature] - A detached signature to add to the encrypted message - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` - * @param {Date} [options.date=current date] - Override the creation date of the message signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords); - signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations); - if (rest.detached) { - throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); - } - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (!signingKeys) { - signingKeys = []; - } - const streaming = message.fromStream; - try { - if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified - message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - message = message.compress( - await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1), - config$1 - ); - message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - if (format === 'object') return message; - // serialize data - const armor = format === 'armored'; - const data = armor ? message.armor(config$1) : message.write(); - return convertStream(data, streaming, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error encrypting message', err); - } -} - -/** - * Decrypts a message with the user's private key, a session key or a password. - * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). - * @param {Object} options - * @param {Message} options.message - The message object with the encrypted data - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key - * @param {String|String[]} [options.passwords] - Passwords to decrypt the message - * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } - * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: MaybeStream, (if format was 'utf8', the default) - * data: MaybeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static - */ -async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - try { - const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); - if (!verificationKeys) { - verificationKeys = []; - } - - const result = {}; - result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); - result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); - result.filename = decrypted.getFilename(); - linkStreams(result, message); - if (expectSigned) { - if (verificationKeys.length === 0) { - throw new Error('Verification keys are required to verify message signatures'); - } - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); - } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); - } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error decrypting message', err); - } -} - - -////////////////////////////////////////// -// // -// Message signing and verification // -// // -////////////////////////////////////////// - - -/** - * Signs a message. - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed - * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [options.date=current date] - Override the creation date of the signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); checkOutputMessageFormat(format); - signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations); - - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); - if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); - - if (!signingKeys || signingKeys.length === 0) { - throw new Error('No signing keys provided'); - } - - try { - let signature; - if (detached) { - signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } else { - signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - if (format === 'object') return signature; - - const armor = format === 'armored'; - signature = armor ? signature.armor(config$1) : signature.write(); - if (detached) { - signature = transformPair(message.packets.write(), async (readable, writable) => { - await Promise.all([ - pipe(signature, writable), - readToEnd(readable).catch(() => {}) - ]); - }); - } - return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error signing message', err); - } -} - -/** - * Verifies signatures of cleartext signed message - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures - * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: MaybeStream, (if `message` was a CleartextMessage) - * data: MaybeStream, (if `message` was a Message) - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static - */ -async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); - if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); - - try { - const result = {}; - if (signature) { - result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); - } else { - result.signatures = await message.verify(verificationKeys, date, config$1); - } - result.data = format === 'binary' ? message.getLiteralData() : message.getText(); - if (message.fromStream && !signature) linkStreams(result, message); - if (expectSigned) { - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); - } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); - } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error verifying signed message', err); - } -} - - -/////////////////////////////////////////////// -// // -// Session key encryption and decryption // -// // -/////////////////////////////////////////////// - -/** - * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. - * @param {Object} options - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} - * @param {Date} [options.date=current date] - Date to select algorithm preferences at - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. - * @async - * @static - */ -async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - try { - const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error generating session key', err); - } -} - -/** - * Encrypt a symmetric session key with public keys, passwords, or both at once. - * At least one of `encryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) - * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key - * @param {String|String[]} [options.passwords] - Passwords for the message - * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [options.date=current date] - Override the date - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { - throw new Error('No encryption keys or passwords provided.'); - } - - try { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - return formatObject(message, format, config$1); - } catch (err) { - throw util.wrapError('Error encrypting session key', err); - } -} - -/** - * Decrypt symmetric session keys using private keys or passwords (not both). - * One of `decryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Message} options.message - A message object containing the encrypted session key packets - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data - * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key - * @param {Date} [options.date] - Date to use for key verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: - * { data:Uint8Array, algorithm:String } - * @throws if no session key could be found or decrypted - * @async - * @static - */ -async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - try { - const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error decrypting session keys', err); - } -} - - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -/** - * Input validation - * @private - */ -function checkString(data, name) { - if (!util.isString(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type String'); - } -} -function checkBinary(data, name) { - if (!util.isUint8Array(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array'); - } -} -function checkMessage(message) { - if (!(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message'); - } -} -function checkCleartextOrMessage(message) { - if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); - } -} -function checkOutputMessageFormat(format) { - if (format !== 'armored' && format !== 'binary' && format !== 'object') { - throw new Error(`Unsupported format ${format}`); - } -} -const defaultConfigPropsCount = Object.keys(config).length; -function checkConfig(config$1) { - const inputConfigProps = Object.keys(config$1); - if (inputConfigProps.length !== defaultConfigPropsCount) { - for (const inputProp of inputConfigProps) { - if (config[inputProp] === undefined) { - throw new Error(`Unknown config property: ${inputProp}`); - } - } - } -} - -/** - * Normalize parameter to an array if it is not undefined. - * @param {Object} param - the parameter to be normalized - * @returns {Array|undefined} The resulting array or undefined. - * @private - */ -function toArray$1(param) { - if (param && !util.isArray(param)) { - param = [param]; - } - return param; -} - -/** - * Convert data to or from Stream - * @param {Object} data - the data to convert - * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type - * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams - * @returns {Promise} The data in the respective format. - * @async - * @private - */ -async function convertStream(data, streaming, encoding = 'utf8') { - const streamType = util.isStream(data); - if (streamType === 'array') { - return readToEnd(data); - } - if (streaming === 'node') { - data = webToNode(data); - if (encoding !== 'binary') data.setEncoding(encoding); - return data; - } - if (streaming === 'web' && streamType === 'ponyfill') { - return toNativeReadable(data); - } - return data; -} - -/** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param {Object} result - the data to convert - * @param {Message} message - message object - * @returns {Object} - * @private - */ -function linkStreams(result, message) { - result.data = transformPair(message.packets.stream, async (readable, writable) => { - await pipe(result.data, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - // Forward errors in the message stream to result.data. - await readToEnd(readable, _ => _); - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); -} - -/** - * Convert the object to the given format - * @param {Key|Message} object - * @param {'armored'|'binary'|'object'} format - * @param {Object} config - Full configuration - * @returns {String|Uint8Array|Object} - */ -function formatObject(object, format, config) { - switch (format) { - case 'object': - return object; - case 'armored': - return object.armor(config); - case 'binary': - return object.write(); - default: - throw new Error(`Unsupported format ${format}`); - } -} - -/** - * web-streams-polyfill v3.0.3 - */ -/// -const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? - Symbol : - description => `Symbol(${description})`; - -/// -function noop() { - return undefined; -} -function getGlobals() { - if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else if (typeof global !== 'undefined') { - return global; - } - return undefined; -} -const globals = getGlobals(); - -function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -const rethrowAssertionErrorRejection = noop; - -const originalPromise = Promise; -const originalPromiseThen = Promise.prototype.then; -const originalPromiseResolve = Promise.resolve.bind(originalPromise); -const originalPromiseReject = Promise.reject.bind(originalPromise); -function newPromise(executor) { - return new originalPromise(executor); -} -function promiseResolvedWith(value) { - return originalPromiseResolve(value); -} -function promiseRejectedWith(reason) { - return originalPromiseReject(reason); -} -function PerformPromiseThen(promise, onFulfilled, onRejected) { - // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an - // approximation. - return originalPromiseThen.call(promise, onFulfilled, onRejected); -} -function uponPromise(promise, onFulfilled, onRejected) { - PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); -} -function uponFulfillment(promise, onFulfilled) { - uponPromise(promise, onFulfilled); -} -function uponRejection(promise, onRejected) { - uponPromise(promise, undefined, onRejected); -} -function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { - return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); -} -function setPromiseIsHandledToTrue(promise) { - PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); -} -const queueMicrotask = (() => { - const globalQueueMicrotask = globals && globals.queueMicrotask; - if (typeof globalQueueMicrotask === 'function') { - return globalQueueMicrotask; - } - const resolvedPromise = promiseResolvedWith(undefined); - return (fn) => PerformPromiseThen(resolvedPromise, fn); -})(); -function reflectCall(F, V, args) { - if (typeof F !== 'function') { - throw new TypeError('Argument is not a function'); - } - return Function.prototype.apply.call(F, V, args); -} -function promiseCall(F, V, args) { - try { - return promiseResolvedWith(reflectCall(F, V, args)); - } - catch (value) { - return promiseRejectedWith(value); - } -} - -// Original from Chromium -// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js -const QUEUE_MAX_ARRAY_SIZE = 16384; -/** - * Simple queue structure. - * - * Avoids scalability issues with using a packed array directly by using - * multiple arrays in a linked list and keeping the array size bounded. - */ -class SimpleQueue { - constructor() { - this._cursor = 0; - this._size = 0; - // _front and _back are always defined. - this._front = { - _elements: [], - _next: undefined - }; - this._back = this._front; - // The cursor is used to avoid calling Array.shift(). - // It contains the index of the front element of the array inside the - // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). - this._cursor = 0; - // When there is only one node, size === elements.length - cursor. - this._size = 0; - } - get length() { - return this._size; - } - // For exception safety, this method is structured in order: - // 1. Read state - // 2. Calculate required state mutations - // 3. Perform state mutations - push(element) { - const oldBack = this._back; - let newBack = oldBack; - if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { - newBack = { - _elements: [], - _next: undefined - }; - } - // push() is the mutation most likely to throw an exception, so it - // goes first. - oldBack._elements.push(element); - if (newBack !== oldBack) { - this._back = newBack; - oldBack._next = newBack; - } - ++this._size; - } - // Like push(), shift() follows the read -> calculate -> mutate pattern for - // exception safety. - shift() { // must not be called on an empty queue - const oldFront = this._front; - let newFront = oldFront; - const oldCursor = this._cursor; - let newCursor = oldCursor + 1; - const elements = oldFront._elements; - const element = elements[oldCursor]; - if (newCursor === QUEUE_MAX_ARRAY_SIZE) { - newFront = oldFront._next; - newCursor = 0; - } - // No mutations before this point. - --this._size; - this._cursor = newCursor; - if (oldFront !== newFront) { - this._front = newFront; - } - // Permit shifted element to be garbage collected. - elements[oldCursor] = undefined; - return element; - } - // The tricky thing about forEach() is that it can be called - // re-entrantly. The queue may be mutated inside the callback. It is easy to - // see that push() within the callback has no negative effects since the end - // of the queue is checked for on every iteration. If shift() is called - // repeatedly within the callback then the next iteration may return an - // element that has been removed. In this case the callback will be called - // with undefined values until we either "catch up" with elements that still - // exist or reach the back of the queue. - forEach(callback) { - let i = this._cursor; - let node = this._front; - let elements = node._elements; - while (i !== elements.length || node._next !== undefined) { - if (i === elements.length) { - node = node._next; - elements = node._elements; - i = 0; - if (elements.length === 0) { - break; - } - } - callback(elements[i]); - ++i; - } - } - // Return the element that would be returned if shift() was called now, - // without modifying the queue. - peek() { // must not be called on an empty queue - const front = this._front; - const cursor = this._cursor; - return front._elements[cursor]; - } -} - -function ReadableStreamReaderGenericInitialize(reader, stream) { - reader._ownerReadableStream = stream; - stream._reader = reader; - if (stream._state === 'readable') { - defaultReaderClosedPromiseInitialize(reader); - } - else if (stream._state === 'closed') { - defaultReaderClosedPromiseInitializeAsResolved(reader); - } - else { - defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); - } -} -// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state -// check. -function ReadableStreamReaderGenericCancel(reader, reason) { - const stream = reader._ownerReadableStream; - return ReadableStreamCancel(stream, reason); -} -function ReadableStreamReaderGenericRelease(reader) { - if (reader._ownerReadableStream._state === 'readable') { - defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - else { - defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - reader._ownerReadableStream._reader = undefined; - reader._ownerReadableStream = undefined; -} -// Helper functions for the readers. -function readerLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released reader'); -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderClosedPromiseInitialize(reader) { - reader._closedPromise = newPromise((resolve, reject) => { - reader._closedPromise_resolve = resolve; - reader._closedPromise_reject = reject; - }); -} -function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseReject(reader, reason); -} -function defaultReaderClosedPromiseInitializeAsResolved(reader) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseResolve(reader); -} -function defaultReaderClosedPromiseReject(reader, reason) { - if (reader._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(reader._closedPromise); - reader._closedPromise_reject(reason); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -function defaultReaderClosedPromiseResetToRejected(reader, reason) { - defaultReaderClosedPromiseInitializeAsRejected(reader, reason); -} -function defaultReaderClosedPromiseResolve(reader) { - if (reader._closedPromise_resolve === undefined) { - return; - } - reader._closedPromise_resolve(undefined); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} - -const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); -const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); -const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); -const PullSteps = SymbolPolyfill('[[PullSteps]]'); - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill -const NumberIsFinite = Number.isFinite || function (x) { - return typeof x === 'number' && isFinite(x); -}; - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill -const MathTrunc = Math.trunc || function (v) { - return v < 0 ? Math.ceil(v) : Math.floor(v); -}; - -// https://heycam.github.io/webidl/#idl-dictionaries -function isDictionary(x) { - return typeof x === 'object' || typeof x === 'function'; -} -function assertDictionary(obj, context) { - if (obj !== undefined && !isDictionary(obj)) { - throw new TypeError(`${context} is not an object.`); - } -} -// https://heycam.github.io/webidl/#idl-callback-functions -function assertFunction(x, context) { - if (typeof x !== 'function') { - throw new TypeError(`${context} is not a function.`); - } -} -// https://heycam.github.io/webidl/#idl-object -function isObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -function assertObject(x, context) { - if (!isObject(x)) { - throw new TypeError(`${context} is not an object.`); - } -} -function assertRequiredArgument(x, position, context) { - if (x === undefined) { - throw new TypeError(`Parameter ${position} is required in '${context}'.`); - } -} -function assertRequiredField(x, field, context) { - if (x === undefined) { - throw new TypeError(`${field} is required in '${context}'.`); - } -} -// https://heycam.github.io/webidl/#idl-unrestricted-double -function convertUnrestrictedDouble(value) { - return Number(value); -} -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} -function integerPart(x) { - return censorNegativeZero(MathTrunc(x)); -} -// https://heycam.github.io/webidl/#idl-unsigned-long-long -function convertUnsignedLongLongWithEnforceRange(value, context) { - const lowerBound = 0; - const upperBound = Number.MAX_SAFE_INTEGER; - let x = Number(value); - x = censorNegativeZero(x); - if (!NumberIsFinite(x)) { - throw new TypeError(`${context} is not a finite number`); - } - x = integerPart(x); - if (x < lowerBound || x > upperBound) { - throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); - } - if (!NumberIsFinite(x) || x === 0) { - return 0; - } - // TODO Use BigInt if supported? - // let xBigInt = BigInt(integerPart(x)); - // xBigInt = BigInt.asUintN(64, xBigInt); - // return Number(xBigInt); - return x; -} - -function assertReadableStream(x, context) { - if (!IsReadableStream(x)) { - throw new TypeError(`${context} is not a ReadableStream.`); - } -} - -// Abstract operations for the ReadableStream. -function AcquireReadableStreamDefaultReader(stream) { - return new ReadableStreamDefaultReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadRequest(stream, readRequest) { - stream._reader._readRequests.push(readRequest); -} -function ReadableStreamFulfillReadRequest(stream, chunk, done) { - const reader = stream._reader; - const readRequest = reader._readRequests.shift(); - if (done) { - readRequest._closeSteps(); - } - else { - readRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadRequests(stream) { - return stream._reader._readRequests.length; -} -function ReadableStreamHasDefaultReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamDefaultReader(reader)) { - return false; - } - return true; -} -/** - * A default reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamDefaultReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, - * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } - /** - * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('read')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: () => resolvePromise({ value: undefined, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamDefaultReaderRead(this, readRequest); - return promise; - } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamDefaultReader(this)) { - throw defaultReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamDefaultReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamDefaultReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { - return false; - } - return true; -} -function ReadableStreamDefaultReaderRead(reader, readRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'closed') { - readRequest._closeSteps(); - } - else if (stream._state === 'errored') { - readRequest._errorSteps(stream._storedError); - } - else { - stream._readableStreamController[PullSteps](readRequest); - } -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); -} - -/// -let AsyncIteratorPrototype; -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - // We're running inside a ES2018+ environment, but we're compiling to an older syntax. - // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. - AsyncIteratorPrototype = { - // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) - // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator - [SymbolPolyfill.asyncIterator]() { - return this; - } - }; - Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); -} - -/// -class ReadableStreamAsyncIteratorImpl { - constructor(reader, preventCancel) { - this._ongoingPromise = undefined; - this._isFinished = false; - this._reader = reader; - this._preventCancel = preventCancel; - } - next() { - const nextSteps = () => this._nextSteps(); - this._ongoingPromise = this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : - nextSteps(); - return this._ongoingPromise; - } - return(value) { - const returnSteps = () => this._returnSteps(value); - return this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : - returnSteps(); - } - _nextSteps() { - if (this._isFinished) { - return Promise.resolve({ value: undefined, done: true }); - } - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('iterate')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => { - this._ongoingPromise = undefined; - // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. - // FIXME Is this a bug in the specification, or in the test? - queueMicrotask(() => resolvePromise({ value: chunk, done: false })); - }, - _closeSteps: () => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - resolvePromise({ value: undefined, done: true }); - }, - _errorSteps: reason => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - rejectPromise(reason); - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promise; - } - _returnSteps(value) { - if (this._isFinished) { - return Promise.resolve({ value, done: true }); - } - this._isFinished = true; - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('finish iterating')); - } - if (!this._preventCancel) { - const result = ReadableStreamReaderGenericCancel(reader, value); - ReadableStreamReaderGenericRelease(reader); - return transformPromiseWith(result, () => ({ value, done: true })); - } - ReadableStreamReaderGenericRelease(reader); - return promiseResolvedWith({ value, done: true }); - } -} -const ReadableStreamAsyncIteratorPrototype = { - next() { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); - } - return this._asyncIteratorImpl.next(); - }, - return(value) { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); - } - return this._asyncIteratorImpl.return(value); - } -}; -if (AsyncIteratorPrototype !== undefined) { - Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); -} -// Abstract operations for the ReadableStream. -function AcquireReadableStreamAsyncIterator(stream, preventCancel) { - const reader = AcquireReadableStreamDefaultReader(stream); - const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); - iterator._asyncIteratorImpl = impl; - return iterator; -} -function IsReadableStreamAsyncIterator(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { - return false; - } - return true; -} -// Helper functions for the ReadableStream. -function streamAsyncIteratorBrandCheckException(name) { - return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); -} - -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill -const NumberIsNaN = Number.isNaN || function (x) { - // eslint-disable-next-line no-self-compare - return x !== x; -}; - -function IsFiniteNonNegativeNumber(v) { - if (!IsNonNegativeNumber(v)) { - return false; - } - if (v === Infinity) { - return false; - } - return true; -} -function IsNonNegativeNumber(v) { - if (typeof v !== 'number') { - return false; - } - if (NumberIsNaN(v)) { - return false; - } - if (v < 0) { - return false; - } - return true; -} - -function DequeueValue(container) { - const pair = container._queue.shift(); - container._queueTotalSize -= pair.size; - if (container._queueTotalSize < 0) { - container._queueTotalSize = 0; - } - return pair.value; -} -function EnqueueValueWithSize(container, value, size) { - size = Number(size); - if (!IsFiniteNonNegativeNumber(size)) { - throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); - } - container._queue.push({ value, size }); - container._queueTotalSize += size; -} -function PeekQueueValue(container) { - const pair = container._queue.peek(); - return pair.value; -} -function ResetQueue(container) { - container._queue = new SimpleQueue(); - container._queueTotalSize = 0; -} - -function CreateArrayFromList(elements) { - // We use arrays to represent lists, so this is basically a no-op. - // Do a slice though just in case we happen to depend on the unique-ness. - return elements.slice(); -} -function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { - new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); -} -// Not implemented correctly -function TransferArrayBuffer(O) { - return O; -} -// Not implemented correctly -function IsDetachedBuffer(O) { - return false; -} - -/** - * A pull-into request in a {@link ReadableByteStreamController}. - * - * @public - */ -class ReadableStreamBYOBRequest { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. - */ - get view() { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('view'); - } - return this._view; - } - respond(bytesWritten) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respond'); - } - assertRequiredArgument(bytesWritten, 1, 'respond'); - bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - if (IsDetachedBuffer(this._view.buffer)) ; - ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); - } - respondWithNewView(view) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respondWithNewView'); - } - assertRequiredArgument(view, 1, 'respondWithNewView'); - if (!ArrayBuffer.isView(view)) { - throw new TypeError('You can only respond with array buffer views'); - } - if (view.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (view.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); - } -} -Object.defineProperties(ReadableStreamBYOBRequest.prototype, { - respond: { enumerable: true }, - respondWithNewView: { enumerable: true }, - view: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBRequest', - configurable: true - }); -} -/** - * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. - * - * @public - */ -class ReadableByteStreamController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the current BYOB pull request, or `null` if there isn't one. - */ - get byobRequest() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('byobRequest'); - } - if (this._byobRequest === null && this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); - const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); - SetUpReadableStreamBYOBRequest(byobRequest, this, view); - this._byobRequest = byobRequest; - } - return this._byobRequest; - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('desiredSize'); - } - return ReadableByteStreamControllerGetDesiredSize(this); - } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('close'); - } - if (this._closeRequested) { - throw new TypeError('The stream has already been closed; do not close it again!'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); - } - ReadableByteStreamControllerClose(this); - } - enqueue(chunk) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('enqueue'); - } - assertRequiredArgument(chunk, 1, 'enqueue'); - if (!ArrayBuffer.isView(chunk)) { - throw new TypeError('chunk must be an array buffer view'); - } - if (chunk.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (chunk.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._closeRequested) { - throw new TypeError('stream is closed or draining'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); - } - ReadableByteStreamControllerEnqueue(this, chunk); - } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('error'); - } - ReadableByteStreamControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - if (this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - firstDescriptor.bytesFilled = 0; - } - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableByteStreamControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableByteStream; - if (this._queueTotalSize > 0) { - const entry = this._queue.shift(); - this._queueTotalSize -= entry.byteLength; - ReadableByteStreamControllerHandleQueueDrain(this); - const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); - readRequest._chunkSteps(view); - return; - } - const autoAllocateChunkSize = this._autoAllocateChunkSize; - if (autoAllocateChunkSize !== undefined) { - let buffer; - try { - buffer = new ArrayBuffer(autoAllocateChunkSize); - } - catch (bufferE) { - readRequest._errorSteps(bufferE); - return; - } - const pullIntoDescriptor = { - buffer, - byteOffset: 0, - byteLength: autoAllocateChunkSize, - bytesFilled: 0, - elementSize: 1, - viewConstructor: Uint8Array, - readerType: 'default' - }; - this._pendingPullIntos.push(pullIntoDescriptor); - } - ReadableStreamAddReadRequest(stream, readRequest); - ReadableByteStreamControllerCallPullIfNeeded(this); - } -} -Object.defineProperties(ReadableByteStreamController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - byobRequest: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableByteStreamController', - configurable: true - }); -} -// Abstract operations for the ReadableByteStreamController. -function IsReadableByteStreamController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { - return false; - } - return true; -} -function IsReadableStreamBYOBRequest(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { - return false; - } - return true; -} -function ReadableByteStreamControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - // TODO: Test controller argument - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableByteStreamControllerError(controller, e); - }); -} -function ReadableByteStreamControllerClearPendingPullIntos(controller) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - controller._pendingPullIntos = new SimpleQueue(); -} -function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { - let done = false; - if (stream._state === 'closed') { - done = true; - } - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - if (pullIntoDescriptor.readerType === 'default') { - ReadableStreamFulfillReadRequest(stream, filledView, done); - } - else { - ReadableStreamFulfillReadIntoRequest(stream, filledView, done); - } -} -function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { - const bytesFilled = pullIntoDescriptor.bytesFilled; - const elementSize = pullIntoDescriptor.elementSize; - return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); -} -function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { - controller._queue.push({ buffer, byteOffset, byteLength }); - controller._queueTotalSize += byteLength; -} -function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { - const elementSize = pullIntoDescriptor.elementSize; - const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; - const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); - const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; - const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; - let totalBytesToCopyRemaining = maxBytesToCopy; - let ready = false; - if (maxAlignedBytes > currentAlignedBytes) { - totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; - ready = true; - } - const queue = controller._queue; - while (totalBytesToCopyRemaining > 0) { - const headOfQueue = queue.peek(); - const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); - const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); - if (headOfQueue.byteLength === bytesToCopy) { - queue.shift(); - } - else { - headOfQueue.byteOffset += bytesToCopy; - headOfQueue.byteLength -= bytesToCopy; - } - controller._queueTotalSize -= bytesToCopy; - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); - totalBytesToCopyRemaining -= bytesToCopy; - } - return ready; -} -function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - pullIntoDescriptor.bytesFilled += size; -} -function ReadableByteStreamControllerHandleQueueDrain(controller) { - if (controller._queueTotalSize === 0 && controller._closeRequested) { - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(controller._controlledReadableByteStream); - } - else { - ReadableByteStreamControllerCallPullIfNeeded(controller); - } -} -function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { - if (controller._byobRequest === null) { - return; - } - controller._byobRequest._associatedReadableByteStreamController = undefined; - controller._byobRequest._view = null; - controller._byobRequest = null; -} -function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { - while (controller._pendingPullIntos.length > 0) { - if (controller._queueTotalSize === 0) { - return; - } - const pullIntoDescriptor = controller._pendingPullIntos.peek(); - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { - const stream = controller._controlledReadableByteStream; - let elementSize = 1; - if (view.constructor !== DataView) { - elementSize = view.constructor.BYTES_PER_ELEMENT; - } - const ctor = view.constructor; - const buffer = TransferArrayBuffer(view.buffer); - const pullIntoDescriptor = { - buffer, - byteOffset: view.byteOffset, - byteLength: view.byteLength, - bytesFilled: 0, - elementSize, - viewConstructor: ctor, - readerType: 'byob' - }; - if (controller._pendingPullIntos.length > 0) { - controller._pendingPullIntos.push(pullIntoDescriptor); - // No ReadableByteStreamControllerCallPullIfNeeded() call since: - // - No change happens on desiredSize - // - The source has already been notified of that there's at least 1 pending read(view) - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - return; - } - if (stream._state === 'closed') { - const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); - readIntoRequest._closeSteps(emptyView); - return; - } - if (controller._queueTotalSize > 0) { - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - ReadableByteStreamControllerHandleQueueDrain(controller); - readIntoRequest._chunkSteps(filledView); - return; - } - if (controller._closeRequested) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - readIntoRequest._errorSteps(e); - return; - } - } - controller._pendingPullIntos.push(pullIntoDescriptor); - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { - firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); - const stream = controller._controlledReadableByteStream; - if (ReadableStreamHasBYOBReader(stream)) { - while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { - const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { - if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { - throw new RangeError('bytesWritten out of range'); - } - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); - if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { - // TODO: Figure out whether we should detach the buffer or not here. - return; - } - ReadableByteStreamControllerShiftPendingPullInto(controller); - const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; - if (remainderSize > 0) { - const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); - ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); - } - pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); - pullIntoDescriptor.bytesFilled -= remainderSize; - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); -} -function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { - const firstDescriptor = controller._pendingPullIntos.peek(); - const state = controller._controlledReadableByteStream._state; - if (state === 'closed') { - if (bytesWritten !== 0) { - throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); - } - ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); - } - else { - ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerShiftPendingPullInto(controller) { - const descriptor = controller._pendingPullIntos.shift(); - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - return descriptor; -} -function ReadableByteStreamControllerShouldCallPull(controller) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return false; - } - if (controller._closeRequested) { - return false; - } - if (!controller._started) { - return false; - } - if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; - } - return false; -} -function ReadableByteStreamControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; -} -// A client of ReadableByteStreamController may use these functions directly to bypass state check. -function ReadableByteStreamControllerClose(controller) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; - } - if (controller._queueTotalSize > 0) { - controller._closeRequested = true; - return; - } - if (controller._pendingPullIntos.length > 0) { - const firstPendingPullInto = controller._pendingPullIntos.peek(); - if (firstPendingPullInto.bytesFilled > 0) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - throw e; - } - } - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(stream); -} -function ReadableByteStreamControllerEnqueue(controller, chunk) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; - } - const buffer = chunk.buffer; - const byteOffset = chunk.byteOffset; - const byteLength = chunk.byteLength; - const transferredBuffer = TransferArrayBuffer(buffer); - if (ReadableStreamHasDefaultReader(stream)) { - if (ReadableStreamGetNumReadRequests(stream) === 0) { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - else { - const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); - ReadableStreamFulfillReadRequest(stream, transferredView, false); - } - } - else if (ReadableStreamHasBYOBReader(stream)) { - // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); - } - else { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerError(controller, e) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return; - } - ReadableByteStreamControllerClearPendingPullIntos(controller); - ResetQueue(controller); - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableByteStreamControllerGetDesiredSize(controller) { - const state = controller._controlledReadableByteStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -function ReadableByteStreamControllerRespond(controller, bytesWritten) { - bytesWritten = Number(bytesWritten); - if (!IsFiniteNonNegativeNumber(bytesWritten)) { - throw new RangeError('bytesWritten must be a finite'); - } - ReadableByteStreamControllerRespondInternal(controller, bytesWritten); -} -function ReadableByteStreamControllerRespondWithNewView(controller, view) { - const firstDescriptor = controller._pendingPullIntos.peek(); - if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { - throw new RangeError('The region specified by view does not match byobRequest'); - } - if (firstDescriptor.byteLength !== view.byteLength) { - throw new RangeError('The buffer of view has different capacity than byobRequest'); - } - firstDescriptor.buffer = view.buffer; - ReadableByteStreamControllerRespondInternal(controller, view.byteLength); -} -function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { - controller._controlledReadableByteStream = stream; - controller._pullAgain = false; - controller._pulling = false; - controller._byobRequest = null; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._closeRequested = false; - controller._started = false; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - controller._autoAllocateChunkSize = autoAllocateChunkSize; - controller._pendingPullIntos = new SimpleQueue(); - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableByteStreamControllerCallPullIfNeeded(controller); - }, r => { - ReadableByteStreamControllerError(controller, r); - }); -} -function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { - const controller = Object.create(ReadableByteStreamController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingByteSource.start !== undefined) { - startAlgorithm = () => underlyingByteSource.start(controller); - } - if (underlyingByteSource.pull !== undefined) { - pullAlgorithm = () => underlyingByteSource.pull(controller); - } - if (underlyingByteSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingByteSource.cancel(reason); - } - const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; - if (autoAllocateChunkSize === 0) { - throw new TypeError('autoAllocateChunkSize must be greater than 0'); - } - SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); -} -function SetUpReadableStreamBYOBRequest(request, controller, view) { - request._associatedReadableByteStreamController = controller; - request._view = view; -} -// Helper functions for the ReadableStreamBYOBRequest. -function byobRequestBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); -} -// Helper functions for the ReadableByteStreamController. -function byteStreamControllerBrandCheckException(name) { - return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); -} - -// Abstract operations for the ReadableStream. -function AcquireReadableStreamBYOBReader(stream) { - return new ReadableStreamBYOBReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { - stream._reader._readIntoRequests.push(readIntoRequest); -} -function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { - const reader = stream._reader; - const readIntoRequest = reader._readIntoRequests.shift(); - if (done) { - readIntoRequest._closeSteps(chunk); - } - else { - readIntoRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadIntoRequests(stream) { - return stream._reader._readIntoRequests.length; -} -function ReadableStreamHasBYOBReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamBYOBReader(reader)) { - return false; - } - return true; -} -/** - * A BYOB reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamBYOBReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - if (!IsReadableByteStreamController(stream._readableStreamController)) { - throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + - 'source'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readIntoRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } - /** - * Attempts to reads bytes into view, and returns a promise resolved with the result. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read(view) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('read')); - } - if (!ArrayBuffer.isView(view)) { - return promiseRejectedWith(new TypeError('view must be an array buffer view')); - } - if (view.byteLength === 0) { - return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); - } - if (view.buffer.byteLength === 0) { - return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readIntoRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamBYOBReaderRead(this, view, readIntoRequest); - return promise; - } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamBYOBReader(this)) { - throw byobReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readIntoRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamBYOBReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamBYOBReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { - return false; - } - return true; -} -function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'errored') { - readIntoRequest._errorSteps(stream._storedError); - } - else { - ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); - } -} -// Helper functions for the ReadableStreamBYOBReader. -function byobReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); -} - -function ExtractHighWaterMark(strategy, defaultHWM) { - const { highWaterMark } = strategy; - if (highWaterMark === undefined) { - return defaultHWM; - } - if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { - throw new RangeError('Invalid highWaterMark'); - } - return highWaterMark; -} -function ExtractSizeAlgorithm(strategy) { - const { size } = strategy; - if (!size) { - return () => 1; - } - return size; -} - -function convertQueuingStrategy(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - const size = init === null || init === void 0 ? void 0 : init.size; - return { - highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), - size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) - }; -} -function convertQueuingStrategySize(fn, context) { - assertFunction(fn, context); - return chunk => convertUnrestrictedDouble(fn(chunk)); -} - -function convertUnderlyingSink(original, context) { - assertDictionary(original, context); - const abort = original === null || original === void 0 ? void 0 : original.abort; - const close = original === null || original === void 0 ? void 0 : original.close; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - const write = original === null || original === void 0 ? void 0 : original.write; - return { - abort: abort === undefined ? - undefined : - convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), - close: close === undefined ? - undefined : - convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), - start: start === undefined ? - undefined : - convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), - write: write === undefined ? - undefined : - convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), - type - }; -} -function convertUnderlyingSinkAbortCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSinkCloseCallback(fn, original, context) { - assertFunction(fn, context); - return () => promiseCall(fn, original, []); -} -function convertUnderlyingSinkStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertUnderlyingSinkWriteCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} - -function assertWritableStream(x, context) { - if (!IsWritableStream(x)) { - throw new TypeError(`${context} is not a WritableStream.`); - } -} - -/** - * A writable stream represents a destination for data, into which you can write. - * - * @public - */ -class WritableStream$1 { - constructor(rawUnderlyingSink = {}, rawStrategy = {}) { - if (rawUnderlyingSink === undefined) { - rawUnderlyingSink = null; - } - else { - assertObject(rawUnderlyingSink, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); - InitializeWritableStream(this); - const type = underlyingSink.type; - if (type !== undefined) { - throw new RangeError('Invalid type is specified'); - } - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); - } - /** - * Returns whether or not the writable stream is locked to a writer. - */ - get locked() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('locked'); - } - return IsWritableStreamLocked(this); - } - /** - * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be - * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort - * mechanism of the underlying sink. - * - * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled - * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel - * the stream) if the stream is currently locked. - */ - abort(reason = undefined) { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('abort')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); - } - return WritableStreamAbort(this, reason); - } - /** - * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its - * close behavior. During this time any further attempts to write will fail (without erroring the stream). - * - * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream - * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with - * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. - */ - close() { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('close')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); - } - if (WritableStreamCloseQueuedOrInFlight(this)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamClose(this); - } - /** - * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream - * is locked, no other writer can be acquired until this one is released. - * - * This functionality is especially useful for creating abstractions that desire the ability to write to a stream - * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at - * the same time, which would cause the resulting written data to be unpredictable and probably useless. - */ - getWriter() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('getWriter'); - } - return AcquireWritableStreamDefaultWriter(this); - } -} -Object.defineProperties(WritableStream$1.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - getWriter: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStream', - configurable: true - }); -} -// Abstract operations for the WritableStream. -function AcquireWritableStreamDefaultWriter(stream) { - return new WritableStreamDefaultWriter(stream); -} -// Throws if and only if startAlgorithm throws. -function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(WritableStream$1.prototype); - InitializeWritableStream(stream); - const controller = Object.create(WritableStreamDefaultController.prototype); - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeWritableStream(stream) { - stream._state = 'writable'; - // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is - // 'erroring' or 'errored'. May be set to an undefined value. - stream._storedError = undefined; - stream._writer = undefined; - // Initialize to undefined first because the constructor of the controller checks this - // variable to validate the caller. - stream._writableStreamController = undefined; - // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data - // producer without waiting for the queued writes to finish. - stream._writeRequests = new SimpleQueue(); - // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents - // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. - stream._inFlightWriteRequest = undefined; - // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer - // has been detached. - stream._closeRequest = undefined; - // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it - // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. - stream._inFlightCloseRequest = undefined; - // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. - stream._pendingAbortRequest = undefined; - // The backpressure signal set by the controller. - stream._backpressure = false; -} -function IsWritableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { - return false; - } - return true; -} -function IsWritableStreamLocked(stream) { - if (stream._writer === undefined) { - return false; - } - return true; -} -function WritableStreamAbort(stream, reason) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseResolvedWith(undefined); - } - if (stream._pendingAbortRequest !== undefined) { - return stream._pendingAbortRequest._promise; - } - let wasAlreadyErroring = false; - if (state === 'erroring') { - wasAlreadyErroring = true; - // reason will not be used, so don't keep a reference to it. - reason = undefined; - } - const promise = newPromise((resolve, reject) => { - stream._pendingAbortRequest = { - _promise: undefined, - _resolve: resolve, - _reject: reject, - _reason: reason, - _wasAlreadyErroring: wasAlreadyErroring - }; - }); - stream._pendingAbortRequest._promise = promise; - if (!wasAlreadyErroring) { - WritableStreamStartErroring(stream, reason); - } - return promise; -} -function WritableStreamClose(stream) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); - } - const promise = newPromise((resolve, reject) => { - const closeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._closeRequest = closeRequest; - }); - const writer = stream._writer; - if (writer !== undefined && stream._backpressure && state === 'writable') { - defaultWriterReadyPromiseResolve(writer); - } - WritableStreamDefaultControllerClose(stream._writableStreamController); - return promise; -} -// WritableStream API exposed for controllers. -function WritableStreamAddWriteRequest(stream) { - const promise = newPromise((resolve, reject) => { - const writeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._writeRequests.push(writeRequest); - }); - return promise; -} -function WritableStreamDealWithRejection(stream, error) { - const state = stream._state; - if (state === 'writable') { - WritableStreamStartErroring(stream, error); - return; - } - WritableStreamFinishErroring(stream); -} -function WritableStreamStartErroring(stream, reason) { - const controller = stream._writableStreamController; - stream._state = 'erroring'; - stream._storedError = reason; - const writer = stream._writer; - if (writer !== undefined) { - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); - } - if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { - WritableStreamFinishErroring(stream); - } -} -function WritableStreamFinishErroring(stream) { - stream._state = 'errored'; - stream._writableStreamController[ErrorSteps](); - const storedError = stream._storedError; - stream._writeRequests.forEach(writeRequest => { - writeRequest._reject(storedError); - }); - stream._writeRequests = new SimpleQueue(); - if (stream._pendingAbortRequest === undefined) { - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const abortRequest = stream._pendingAbortRequest; - stream._pendingAbortRequest = undefined; - if (abortRequest._wasAlreadyErroring) { - abortRequest._reject(storedError); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); - uponPromise(promise, () => { - abortRequest._resolve(); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }, (reason) => { - abortRequest._reject(reason); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }); -} -function WritableStreamFinishInFlightWrite(stream) { - stream._inFlightWriteRequest._resolve(undefined); - stream._inFlightWriteRequest = undefined; -} -function WritableStreamFinishInFlightWriteWithError(stream, error) { - stream._inFlightWriteRequest._reject(error); - stream._inFlightWriteRequest = undefined; - WritableStreamDealWithRejection(stream, error); -} -function WritableStreamFinishInFlightClose(stream) { - stream._inFlightCloseRequest._resolve(undefined); - stream._inFlightCloseRequest = undefined; - const state = stream._state; - if (state === 'erroring') { - // The error was too late to do anything, so it is ignored. - stream._storedError = undefined; - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._resolve(); - stream._pendingAbortRequest = undefined; - } - } - stream._state = 'closed'; - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseResolve(writer); - } -} -function WritableStreamFinishInFlightCloseWithError(stream, error) { - stream._inFlightCloseRequest._reject(error); - stream._inFlightCloseRequest = undefined; - // Never execute sink abort() after sink close(). - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._reject(error); - stream._pendingAbortRequest = undefined; - } - WritableStreamDealWithRejection(stream, error); -} -// TODO(ricea): Fix alphabetical order. -function WritableStreamCloseQueuedOrInFlight(stream) { - if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamHasOperationMarkedInFlight(stream) { - if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamMarkCloseRequestInFlight(stream) { - stream._inFlightCloseRequest = stream._closeRequest; - stream._closeRequest = undefined; -} -function WritableStreamMarkFirstWriteRequestInFlight(stream) { - stream._inFlightWriteRequest = stream._writeRequests.shift(); -} -function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { - if (stream._closeRequest !== undefined) { - stream._closeRequest._reject(stream._storedError); - stream._closeRequest = undefined; - } - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseReject(writer, stream._storedError); - } -} -function WritableStreamUpdateBackpressure(stream, backpressure) { - const writer = stream._writer; - if (writer !== undefined && backpressure !== stream._backpressure) { - if (backpressure) { - defaultWriterReadyPromiseReset(writer); - } - else { - defaultWriterReadyPromiseResolve(writer); - } - } - stream._backpressure = backpressure; -} -/** - * A default writer vended by a {@link WritableStream}. - * - * @public - */ -class WritableStreamDefaultWriter { - constructor(stream) { - assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); - assertWritableStream(stream, 'First parameter'); - if (IsWritableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive writing by another writer'); - } - this._ownerWritableStream = stream; - stream._writer = this; - const state = stream._state; - if (state === 'writable') { - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { - defaultWriterReadyPromiseInitialize(this); - } - else { - defaultWriterReadyPromiseInitializeAsResolved(this); - } - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'erroring') { - defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'closed') { - defaultWriterReadyPromiseInitializeAsResolved(this); - defaultWriterClosedPromiseInitializeAsResolved(this); - } - else { - const storedError = stream._storedError; - defaultWriterReadyPromiseInitializeAsRejected(this, storedError); - defaultWriterClosedPromiseInitializeAsRejected(this, storedError); - } - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the writer’s lock is released before the stream finishes closing. - */ - get closed() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. - * A producer can use this information to determine the right amount of data to write. - * - * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort - * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when - * the writer’s lock is released. - */ - get desiredSize() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('desiredSize'); - } - if (this._ownerWritableStream === undefined) { - throw defaultWriterLockException('desiredSize'); - } - return WritableStreamDefaultWriterGetDesiredSize(this); - } - /** - * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions - * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips - * back to zero or below, the getter will return a new promise that stays pending until the next transition. - * - * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become - * rejected. - */ - get ready() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('ready')); - } - return this._readyPromise; - } - /** - * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. - */ - abort(reason = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('abort')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('abort')); - } - return WritableStreamDefaultWriterAbort(this, reason); - } - /** - * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. - */ - close() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('close')); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return promiseRejectedWith(defaultWriterLockException('close')); - } - if (WritableStreamCloseQueuedOrInFlight(stream)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamDefaultWriterClose(this); - } - /** - * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. - * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from - * now on; otherwise, the writer will appear closed. - * - * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the - * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). - * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents - * other producers from writing in an interleaved manner. - */ - releaseLock() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('releaseLock'); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return; - } - WritableStreamDefaultWriterRelease(this); - } - write(chunk = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('write')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - return WritableStreamDefaultWriterWrite(this, chunk); - } -} -Object.defineProperties(WritableStreamDefaultWriter.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - releaseLock: { enumerable: true }, - write: { enumerable: true }, - closed: { enumerable: true }, - desiredSize: { enumerable: true }, - ready: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultWriter', - configurable: true - }); -} -// Abstract operations for the WritableStreamDefaultWriter. -function IsWritableStreamDefaultWriter(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { - return false; - } - return true; -} -// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. -function WritableStreamDefaultWriterAbort(writer, reason) { - const stream = writer._ownerWritableStream; - return WritableStreamAbort(stream, reason); -} -function WritableStreamDefaultWriterClose(writer) { - const stream = writer._ownerWritableStream; - return WritableStreamClose(stream); -} -function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseResolvedWith(undefined); - } - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - return WritableStreamDefaultWriterClose(writer); -} -function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { - if (writer._closedPromiseState === 'pending') { - defaultWriterClosedPromiseReject(writer, error); - } - else { - defaultWriterClosedPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { - if (writer._readyPromiseState === 'pending') { - defaultWriterReadyPromiseReject(writer, error); - } - else { - defaultWriterReadyPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterGetDesiredSize(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (state === 'errored' || state === 'erroring') { - return null; - } - if (state === 'closed') { - return 0; - } - return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); -} -function WritableStreamDefaultWriterRelease(writer) { - const stream = writer._ownerWritableStream; - const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); - // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not - // rejected until afterwards. This means that simply testing state will not work. - WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); - stream._writer = undefined; - writer._ownerWritableStream = undefined; -} -function WritableStreamDefaultWriterWrite(writer, chunk) { - const stream = writer._ownerWritableStream; - const controller = stream._writableStreamController; - const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); - if (stream !== writer._ownerWritableStream) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - const state = stream._state; - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); - } - if (state === 'erroring') { - return promiseRejectedWith(stream._storedError); - } - const promise = WritableStreamAddWriteRequest(stream); - WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); - return promise; -} -const closeSentinel = {}; -/** - * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. - * - * @public - */ -class WritableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. - * - * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying - * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the - * normal lifecycle of interactions with the underlying sink. - */ - error(e = undefined) { - if (!IsWritableStreamDefaultController(this)) { - throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); - } - const state = this._controlledWritableStream._state; - if (state !== 'writable') { - // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so - // just treat it as a no-op. - return; - } - WritableStreamDefaultControllerError(this, e); - } - /** @internal */ - [AbortSteps](reason) { - const result = this._abortAlgorithm(reason); - WritableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [ErrorSteps]() { - ResetQueue(this); - } -} -Object.defineProperties(WritableStreamDefaultController.prototype, { - error: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultController', - configurable: true - }); -} -// Abstract operations implementing interface required by the WritableStream. -function IsWritableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { - return false; - } - return true; -} -function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledWritableStream = stream; - stream._writableStreamController = controller; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._writeAlgorithm = writeAlgorithm; - controller._closeAlgorithm = closeAlgorithm; - controller._abortAlgorithm = abortAlgorithm; - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - const startResult = startAlgorithm(); - const startPromise = promiseResolvedWith(startResult); - uponPromise(startPromise, () => { - controller._started = true; - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, r => { - controller._started = true; - WritableStreamDealWithRejection(stream, r); - }); -} -function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { - const controller = Object.create(WritableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let writeAlgorithm = () => promiseResolvedWith(undefined); - let closeAlgorithm = () => promiseResolvedWith(undefined); - let abortAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSink.start !== undefined) { - startAlgorithm = () => underlyingSink.start(controller); - } - if (underlyingSink.write !== undefined) { - writeAlgorithm = chunk => underlyingSink.write(chunk, controller); - } - if (underlyingSink.close !== undefined) { - closeAlgorithm = () => underlyingSink.close(); - } - if (underlyingSink.abort !== undefined) { - abortAlgorithm = reason => underlyingSink.abort(reason); - } - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); -} -// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. -function WritableStreamDefaultControllerClearAlgorithms(controller) { - controller._writeAlgorithm = undefined; - controller._closeAlgorithm = undefined; - controller._abortAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -function WritableStreamDefaultControllerClose(controller) { - EnqueueValueWithSize(controller, closeSentinel, 0); - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { - try { - return controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); - return 1; - } -} -function WritableStreamDefaultControllerGetDesiredSize(controller) { - return controller._strategyHWM - controller._queueTotalSize; -} -function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); - return; - } - const stream = controller._controlledWritableStream; - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -// Abstract operations for the WritableStreamDefaultController. -function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { - const stream = controller._controlledWritableStream; - if (!controller._started) { - return; - } - if (stream._inFlightWriteRequest !== undefined) { - return; - } - const state = stream._state; - if (state === 'erroring') { - WritableStreamFinishErroring(stream); - return; - } - if (controller._queue.length === 0) { - return; - } - const value = PeekQueueValue(controller); - if (value === closeSentinel) { - WritableStreamDefaultControllerProcessClose(controller); - } - else { - WritableStreamDefaultControllerProcessWrite(controller, value); - } -} -function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { - if (controller._controlledWritableStream._state === 'writable') { - WritableStreamDefaultControllerError(controller, error); - } -} -function WritableStreamDefaultControllerProcessClose(controller) { - const stream = controller._controlledWritableStream; - WritableStreamMarkCloseRequestInFlight(stream); - DequeueValue(controller); - const sinkClosePromise = controller._closeAlgorithm(); - WritableStreamDefaultControllerClearAlgorithms(controller); - uponPromise(sinkClosePromise, () => { - WritableStreamFinishInFlightClose(stream); - }, reason => { - WritableStreamFinishInFlightCloseWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerProcessWrite(controller, chunk) { - const stream = controller._controlledWritableStream; - WritableStreamMarkFirstWriteRequestInFlight(stream); - const sinkWritePromise = controller._writeAlgorithm(chunk); - uponPromise(sinkWritePromise, () => { - WritableStreamFinishInFlightWrite(stream); - const state = stream._state; - DequeueValue(controller); - if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, reason => { - if (stream._state === 'writable') { - WritableStreamDefaultControllerClearAlgorithms(controller); - } - WritableStreamFinishInFlightWriteWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerGetBackpressure(controller) { - const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); - return desiredSize <= 0; -} -// A client of WritableStreamDefaultController may use these functions directly to bypass state check. -function WritableStreamDefaultControllerError(controller, error) { - const stream = controller._controlledWritableStream; - WritableStreamDefaultControllerClearAlgorithms(controller); - WritableStreamStartErroring(stream, error); -} -// Helper functions for the WritableStream. -function streamBrandCheckException$2(name) { - return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); -} -// Helper functions for the WritableStreamDefaultWriter. -function defaultWriterBrandCheckException(name) { - return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); -} -function defaultWriterLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released writer'); -} -function defaultWriterClosedPromiseInitialize(writer) { - writer._closedPromise = newPromise((resolve, reject) => { - writer._closedPromise_resolve = resolve; - writer._closedPromise_reject = reject; - writer._closedPromiseState = 'pending'; - }); -} -function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseReject(writer, reason); -} -function defaultWriterClosedPromiseInitializeAsResolved(writer) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseResolve(writer); -} -function defaultWriterClosedPromiseReject(writer, reason) { - if (writer._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._closedPromise); - writer._closedPromise_reject(reason); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'rejected'; -} -function defaultWriterClosedPromiseResetToRejected(writer, reason) { - defaultWriterClosedPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterClosedPromiseResolve(writer) { - if (writer._closedPromise_resolve === undefined) { - return; - } - writer._closedPromise_resolve(undefined); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'resolved'; -} -function defaultWriterReadyPromiseInitialize(writer) { - writer._readyPromise = newPromise((resolve, reject) => { - writer._readyPromise_resolve = resolve; - writer._readyPromise_reject = reject; - }); - writer._readyPromiseState = 'pending'; -} -function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseReject(writer, reason); -} -function defaultWriterReadyPromiseInitializeAsResolved(writer) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseResolve(writer); -} -function defaultWriterReadyPromiseReject(writer, reason) { - if (writer._readyPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._readyPromise); - writer._readyPromise_reject(reason); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'rejected'; -} -function defaultWriterReadyPromiseReset(writer) { - defaultWriterReadyPromiseInitialize(writer); -} -function defaultWriterReadyPromiseResetToRejected(writer, reason) { - defaultWriterReadyPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterReadyPromiseResolve(writer) { - if (writer._readyPromise_resolve === undefined) { - return; - } - writer._readyPromise_resolve(undefined); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'fulfilled'; -} - -function isAbortSignal(value) { - if (typeof value !== 'object' || value === null) { - return false; - } - try { - return typeof value.aborted === 'boolean'; - } - catch (_a) { - // AbortSignal.prototype.aborted throws if its brand check fails - return false; - } -} - -/// -const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; - -/// -function isDOMExceptionConstructor(ctor) { - if (!(typeof ctor === 'function' || typeof ctor === 'object')) { - return false; - } - try { - new ctor(); - return true; - } - catch (_a) { - return false; - } -} -function createDOMExceptionPolyfill() { - // eslint-disable-next-line no-shadow - const ctor = function DOMException(message, name) { - this.message = message || ''; - this.name = name || 'Error'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - }; - ctor.prototype = Object.create(Error.prototype); - Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); - return ctor; -} -// eslint-disable-next-line no-redeclare -const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); - -function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { - const reader = AcquireReadableStreamDefaultReader(source); - const writer = AcquireWritableStreamDefaultWriter(dest); - source._disturbed = true; - let shuttingDown = false; - // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. - let currentWrite = promiseResolvedWith(undefined); - return newPromise((resolve, reject) => { - let abortAlgorithm; - if (signal !== undefined) { - abortAlgorithm = () => { - const error = new DOMException$1('Aborted', 'AbortError'); - const actions = []; - if (!preventAbort) { - actions.push(() => { - if (dest._state === 'writable') { - return WritableStreamAbort(dest, error); - } - return promiseResolvedWith(undefined); - }); - } - if (!preventCancel) { - actions.push(() => { - if (source._state === 'readable') { - return ReadableStreamCancel(source, error); - } - return promiseResolvedWith(undefined); - }); - } - shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); - }; - if (signal.aborted) { - abortAlgorithm(); - return; - } - signal.addEventListener('abort', abortAlgorithm); - } - // Using reader and writer, read all chunks from this and write them to dest - // - Backpressure must be enforced - // - Shutdown must stop all activity - function pipeLoop() { - return newPromise((resolveLoop, rejectLoop) => { - function next(done) { - if (done) { - resolveLoop(); - } - else { - // Use `PerformPromiseThen` instead of `uponPromise` to avoid - // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers - PerformPromiseThen(pipeStep(), next, rejectLoop); - } - } - next(false); - }); - } - function pipeStep() { - if (shuttingDown) { - return promiseResolvedWith(true); - } - return PerformPromiseThen(writer._readyPromise, () => { - return newPromise((resolveRead, rejectRead) => { - ReadableStreamDefaultReaderRead(reader, { - _chunkSteps: chunk => { - currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); - resolveRead(false); - }, - _closeSteps: () => resolveRead(true), - _errorSteps: rejectRead - }); - }); - }); - } - // Errors must be propagated forward - isOrBecomesErrored(source, reader._closedPromise, storedError => { - if (!preventAbort) { - shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Errors must be propagated backward - isOrBecomesErrored(dest, writer._closedPromise, storedError => { - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Closing must be propagated forward - isOrBecomesClosed(source, reader._closedPromise, () => { - if (!preventClose) { - shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); - } - else { - shutdown(); - } - }); - // Closing must be propagated backward - if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { - const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); - } - else { - shutdown(true, destClosed); - } - } - setPromiseIsHandledToTrue(pipeLoop()); - function waitForWritesToFinish() { - // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait - // for that too. - const oldCurrentWrite = currentWrite; - return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); - } - function isOrBecomesErrored(stream, promise, action) { - if (stream._state === 'errored') { - action(stream._storedError); - } - else { - uponRejection(promise, action); - } - } - function isOrBecomesClosed(stream, promise, action) { - if (stream._state === 'closed') { - action(); - } - else { - uponFulfillment(promise, action); - } - } - function shutdownWithAction(action, originalIsError, originalError) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), doTheRest); - } - else { - doTheRest(); - } - function doTheRest() { - uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); - } - } - function shutdown(isError, error) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); - } - else { - finalize(isError, error); - } - } - function finalize(isError, error) { - WritableStreamDefaultWriterRelease(writer); - ReadableStreamReaderGenericRelease(reader); - if (signal !== undefined) { - signal.removeEventListener('abort', abortAlgorithm); - } - if (isError) { - reject(error); - } - else { - resolve(undefined); - } - } - }); -} - -/** - * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. - * - * @public - */ -class ReadableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('desiredSize'); - } - return ReadableStreamDefaultControllerGetDesiredSize(this); - } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('close'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits close'); - } - ReadableStreamDefaultControllerClose(this); - } - enqueue(chunk = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('enqueue'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits enqueue'); - } - return ReadableStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('error'); - } - ReadableStreamDefaultControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableStream; - if (this._queue.length > 0) { - const chunk = DequeueValue(this); - if (this._closeRequested && this._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(this); - ReadableStreamClose(stream); - } - else { - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - readRequest._chunkSteps(chunk); - } - else { - ReadableStreamAddReadRequest(stream, readRequest); - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - } -} -Object.defineProperties(ReadableStreamDefaultController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultController', - configurable: true - }); -} -// Abstract operations for the ReadableStreamDefaultController. -function IsReadableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { - return false; - } - return true; -} -function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableStreamDefaultControllerError(controller, e); - }); -} -function ReadableStreamDefaultControllerShouldCallPull(controller) { - const stream = controller._controlledReadableStream; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return false; - } - if (!controller._started) { - return false; - } - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; - } - return false; -} -function ReadableStreamDefaultControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. -function ReadableStreamDefaultControllerClose(controller) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; - } - const stream = controller._controlledReadableStream; - controller._closeRequested = true; - if (controller._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamClose(stream); - } -} -function ReadableStreamDefaultControllerEnqueue(controller, chunk) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; - } - const stream = controller._controlledReadableStream; - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - ReadableStreamFulfillReadRequest(stream, chunk, false); - } - else { - let chunkSize; - try { - chunkSize = controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - ReadableStreamDefaultControllerError(controller, chunkSizeE); - throw chunkSizeE; - } - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - ReadableStreamDefaultControllerError(controller, enqueueE); - throw enqueueE; - } - } - ReadableStreamDefaultControllerCallPullIfNeeded(controller); -} -function ReadableStreamDefaultControllerError(controller, e) { - const stream = controller._controlledReadableStream; - if (stream._state !== 'readable') { - return; - } - ResetQueue(controller); - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableStreamDefaultControllerGetDesiredSize(controller) { - const state = controller._controlledReadableStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -// This is used in the implementation of TransformStream. -function ReadableStreamDefaultControllerHasBackpressure(controller) { - if (ReadableStreamDefaultControllerShouldCallPull(controller)) { - return false; - } - return true; -} -function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { - const state = controller._controlledReadableStream._state; - if (!controller._closeRequested && state === 'readable') { - return true; - } - return false; -} -function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledReadableStream = stream; - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._closeRequested = false; - controller._pullAgain = false; - controller._pulling = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - }, r => { - ReadableStreamDefaultControllerError(controller, r); - }); -} -function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { - const controller = Object.create(ReadableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSource.start !== undefined) { - startAlgorithm = () => underlyingSource.start(controller); - } - if (underlyingSource.pull !== undefined) { - pullAlgorithm = () => underlyingSource.pull(controller); - } - if (underlyingSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingSource.cancel(reason); - } - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); -} -// Helper functions for the ReadableStreamDefaultController. -function defaultControllerBrandCheckException$1(name) { - return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); -} - -function ReadableStreamTee(stream, cloneForBranch2) { - const reader = AcquireReadableStreamDefaultReader(stream); - let reading = false; - let canceled1 = false; - let canceled2 = false; - let reason1; - let reason2; - let branch1; - let branch2; - let resolveCancelPromise; - const cancelPromise = newPromise(resolve => { - resolveCancelPromise = resolve; - }); - function pullAlgorithm() { - if (reading) { - return promiseResolvedWith(undefined); - } - reading = true; - const readRequest = { - _chunkSteps: value => { - // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using - // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let - // successful synchronously-available reads get ahead of asynchronously-available errors. - queueMicrotask(() => { - reading = false; - const value1 = value; - const value2 = value; - // There is no way to access the cloning code right now in the reference implementation. - // If we add one then we'll need an implementation for serializable objects. - // if (!canceled2 && cloneForBranch2) { - // value2 = StructuredDeserialize(StructuredSerialize(value2)); - // } - if (!canceled1) { - ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1); - } - if (!canceled2) { - ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2); - } - }); - }, - _closeSteps: () => { - reading = false; - if (!canceled1) { - ReadableStreamDefaultControllerClose(branch1._readableStreamController); - } - if (!canceled2) { - ReadableStreamDefaultControllerClose(branch2._readableStreamController); - } - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }, - _errorSteps: () => { - reading = false; - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promiseResolvedWith(undefined); - } - function cancel1Algorithm(reason) { - canceled1 = true; - reason1 = reason; - if (canceled2) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function cancel2Algorithm(reason) { - canceled2 = true; - reason2 = reason; - if (canceled1) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function startAlgorithm() { - // do nothing - } - branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); - branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); - uponRejection(reader._closedPromise, (r) => { - ReadableStreamDefaultControllerError(branch1._readableStreamController, r); - ReadableStreamDefaultControllerError(branch2._readableStreamController, r); - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }); - return [branch1, branch2]; -} - -function convertUnderlyingDefaultOrByteSource(source, context) { - assertDictionary(source, context); - const original = source; - const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; - const cancel = original === null || original === void 0 ? void 0 : original.cancel; - const pull = original === null || original === void 0 ? void 0 : original.pull; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - return { - autoAllocateChunkSize: autoAllocateChunkSize === undefined ? - undefined : - convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), - cancel: cancel === undefined ? - undefined : - convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), - pull: pull === undefined ? - undefined : - convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), - start: start === undefined ? - undefined : - convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), - type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) - }; -} -function convertUnderlyingSourceCancelCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSourcePullCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertUnderlyingSourceStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertReadableStreamType(type, context) { - type = `${type}`; - if (type !== 'bytes') { - throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); - } - return type; -} - -function convertReaderOptions(options, context) { - assertDictionary(options, context); - const mode = options === null || options === void 0 ? void 0 : options.mode; - return { - mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) - }; -} -function convertReadableStreamReaderMode(mode, context) { - mode = `${mode}`; - if (mode !== 'byob') { - throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); - } - return mode; -} - -function convertIteratorOptions(options, context) { - assertDictionary(options, context); - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - return { preventCancel: Boolean(preventCancel) }; -} - -function convertPipeOptions(options, context) { - assertDictionary(options, context); - const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; - const signal = options === null || options === void 0 ? void 0 : options.signal; - if (signal !== undefined) { - assertAbortSignal(signal, `${context} has member 'signal' that`); - } - return { - preventAbort: Boolean(preventAbort), - preventCancel: Boolean(preventCancel), - preventClose: Boolean(preventClose), - signal - }; -} -function assertAbortSignal(signal, context) { - if (!isAbortSignal(signal)) { - throw new TypeError(`${context} is not an AbortSignal.`); - } -} - -function convertReadableWritablePair(pair, context) { - assertDictionary(pair, context); - const readable = pair === null || pair === void 0 ? void 0 : pair.readable; - assertRequiredField(readable, 'readable', 'ReadableWritablePair'); - assertReadableStream(readable, `${context} has member 'readable' that`); - const writable = pair === null || pair === void 0 ? void 0 : pair.writable; - assertRequiredField(writable, 'writable', 'ReadableWritablePair'); - assertWritableStream(writable, `${context} has member 'writable' that`); - return { readable, writable }; -} - -/** - * A readable stream represents a source of data, from which you can read. - * - * @public - */ -class ReadableStream$1 { - constructor(rawUnderlyingSource = {}, rawStrategy = {}) { - if (rawUnderlyingSource === undefined) { - rawUnderlyingSource = null; - } - else { - assertObject(rawUnderlyingSource, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); - InitializeReadableStream(this); - if (underlyingSource.type === 'bytes') { - if (strategy.size !== undefined) { - throw new RangeError('The strategy for a byte stream cannot have a size function'); - } - const highWaterMark = ExtractHighWaterMark(strategy, 0); - SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); - } - else { - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); - } - } - /** - * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. - */ - get locked() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('locked'); - } - return IsReadableStreamLocked(this); - } - /** - * Cancels the stream, signaling a loss of interest in the stream by a consumer. - * - * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} - * method, which might or might not use it. - */ - cancel(reason = undefined) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('cancel')); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); - } - return ReadableStreamCancel(this, reason); - } - getReader(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('getReader'); - } - const options = convertReaderOptions(rawOptions, 'First parameter'); - if (options.mode === undefined) { - return AcquireReadableStreamDefaultReader(this); - } - return AcquireReadableStreamBYOBReader(this); - } - pipeThrough(rawTransform, rawOptions = {}) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('pipeThrough'); - } - assertRequiredArgument(rawTransform, 1, 'pipeThrough'); - const transform = convertReadableWritablePair(rawTransform, 'First parameter'); - const options = convertPipeOptions(rawOptions, 'Second parameter'); - if (IsReadableStreamLocked(this)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); - } - if (IsWritableStreamLocked(transform.writable)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); - } - const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - setPromiseIsHandledToTrue(promise); - return transform.readable; - } - pipeTo(destination, rawOptions = {}) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); - } - if (destination === undefined) { - return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); - } - if (!IsWritableStream(destination)) { - return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); - } - let options; - try { - options = convertPipeOptions(rawOptions, 'Second parameter'); - } - catch (e) { - return promiseRejectedWith(e); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); - } - if (IsWritableStreamLocked(destination)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); - } - return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - } - /** - * Tees this readable stream, returning a two-element array containing the two resulting branches as - * new {@link ReadableStream} instances. - * - * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. - * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be - * propagated to the stream's underlying source. - * - * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, - * this could allow interference between the two branches. - */ - tee() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('tee'); - } - const branches = ReadableStreamTee(this); - return CreateArrayFromList(branches); - } - values(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('values'); - } - const options = convertIteratorOptions(rawOptions, 'First parameter'); - return AcquireReadableStreamAsyncIterator(this, options.preventCancel); - } -} -Object.defineProperties(ReadableStream$1.prototype, { - cancel: { enumerable: true }, - getReader: { enumerable: true }, - pipeThrough: { enumerable: true }, - pipeTo: { enumerable: true }, - tee: { enumerable: true }, - values: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStream', - configurable: true - }); -} -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, { - value: ReadableStream$1.prototype.values, - writable: true, - configurable: true - }); -} -// Abstract operations for the ReadableStream. -// Throws if and only if startAlgorithm throws. -function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(ReadableStream$1.prototype); - InitializeReadableStream(stream); - const controller = Object.create(ReadableStreamDefaultController.prototype); - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeReadableStream(stream) { - stream._state = 'readable'; - stream._reader = undefined; - stream._storedError = undefined; - stream._disturbed = false; -} -function IsReadableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { - return false; - } - return true; -} -function IsReadableStreamLocked(stream) { - if (stream._reader === undefined) { - return false; - } - return true; -} -// ReadableStream API exposed for controllers. -function ReadableStreamCancel(stream, reason) { - stream._disturbed = true; - if (stream._state === 'closed') { - return promiseResolvedWith(undefined); - } - if (stream._state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - ReadableStreamClose(stream); - const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); - return transformPromiseWith(sourceCancelPromise, noop); -} -function ReadableStreamClose(stream) { - stream._state = 'closed'; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseResolve(reader); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._closeSteps(); - }); - reader._readRequests = new SimpleQueue(); - } -} -function ReadableStreamError(stream, e) { - stream._state = 'errored'; - stream._storedError = e; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseReject(reader, e); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._errorSteps(e); - }); - reader._readRequests = new SimpleQueue(); - } - else { - reader._readIntoRequests.forEach(readIntoRequest => { - readIntoRequest._errorSteps(e); - }); - reader._readIntoRequests = new SimpleQueue(); - } -} -// Helper functions for the ReadableStream. -function streamBrandCheckException$1(name) { - return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); -} - -function convertQueuingStrategyInit(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); - return { - highWaterMark: convertUnrestrictedDouble(highWaterMark) - }; -} - -const byteLengthSizeFunction = function size(chunk) { - return chunk.byteLength; -}; -/** - * A queuing strategy that counts the number of bytes in each chunk. - * - * @public - */ -class ByteLengthQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('highWaterMark'); - } - return this._byteLengthQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by returning the value of its `byteLength` property. - */ - get size() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('size'); - } - return byteLengthSizeFunction; - } -} -Object.defineProperties(ByteLengthQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'ByteLengthQueuingStrategy', - configurable: true - }); -} -// Helper functions for the ByteLengthQueuingStrategy. -function byteLengthBrandCheckException(name) { - return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); -} -function IsByteLengthQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { - return false; - } - return true; -} - -const countSizeFunction = function size() { - return 1; -}; -/** - * A queuing strategy that counts the number of chunks. - * - * @public - */ -class CountQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'CountQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._countQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('highWaterMark'); - } - return this._countQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by always returning 1. - * This ensures that the total queue size is a count of the number of chunks in the queue. - */ - get size() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('size'); - } - return countSizeFunction; - } -} -Object.defineProperties(CountQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'CountQueuingStrategy', - configurable: true - }); -} -// Helper functions for the CountQueuingStrategy. -function countBrandCheckException(name) { - return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); -} -function IsCountQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { - return false; - } - return true; -} - -function convertTransformer(original, context) { - assertDictionary(original, context); - const flush = original === null || original === void 0 ? void 0 : original.flush; - const readableType = original === null || original === void 0 ? void 0 : original.readableType; - const start = original === null || original === void 0 ? void 0 : original.start; - const transform = original === null || original === void 0 ? void 0 : original.transform; - const writableType = original === null || original === void 0 ? void 0 : original.writableType; - return { - flush: flush === undefined ? - undefined : - convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), - readableType, - start: start === undefined ? - undefined : - convertTransformerStartCallback(start, original, `${context} has member 'start' that`), - transform: transform === undefined ? - undefined : - convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), - writableType - }; -} -function convertTransformerFlushCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertTransformerStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertTransformerTransformCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} - -// Class TransformStream -/** - * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, - * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. - * In a manner specific to the transform stream in question, writes to the writable side result in new data being - * made available for reading from the readable side. - * - * @public - */ -class TransformStream$1 { - constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { - if (rawTransformer === undefined) { - rawTransformer = null; - } - const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); - const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); - const transformer = convertTransformer(rawTransformer, 'First parameter'); - if (transformer.readableType !== undefined) { - throw new RangeError('Invalid readableType specified'); - } - if (transformer.writableType !== undefined) { - throw new RangeError('Invalid writableType specified'); - } - const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); - const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); - const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); - const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); - let startPromise_resolve; - const startPromise = newPromise(resolve => { - startPromise_resolve = resolve; - }); - InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); - if (transformer.start !== undefined) { - startPromise_resolve(transformer.start(this._transformStreamController)); - } - else { - startPromise_resolve(undefined); - } - } - /** - * The readable side of the transform stream. - */ - get readable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('readable'); - } - return this._readable; - } - /** - * The writable side of the transform stream. - */ - get writable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('writable'); - } - return this._writable; - } -} -Object.defineProperties(TransformStream$1.prototype, { - readable: { enumerable: true }, - writable: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStream', - configurable: true - }); -} -function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { - function startAlgorithm() { - return startPromise; - } - function writeAlgorithm(chunk) { - return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); - } - function abortAlgorithm(reason) { - return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); - } - function closeAlgorithm() { - return TransformStreamDefaultSinkCloseAlgorithm(stream); - } - stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); - function pullAlgorithm() { - return TransformStreamDefaultSourcePullAlgorithm(stream); - } - function cancelAlgorithm(reason) { - TransformStreamErrorWritableAndUnblockWrite(stream, reason); - return promiseResolvedWith(undefined); - } - stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. - stream._backpressure = undefined; - stream._backpressureChangePromise = undefined; - stream._backpressureChangePromise_resolve = undefined; - TransformStreamSetBackpressure(stream, true); - stream._transformStreamController = undefined; -} -function IsTransformStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { - return false; - } - return true; -} -// This is a no-op if both sides are already errored. -function TransformStreamError(stream, e) { - ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); - TransformStreamErrorWritableAndUnblockWrite(stream, e); -} -function TransformStreamErrorWritableAndUnblockWrite(stream, e) { - TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); - WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); - if (stream._backpressure) { - // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() - // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time - // _backpressure is set. - TransformStreamSetBackpressure(stream, false); - } -} -function TransformStreamSetBackpressure(stream, backpressure) { - // Passes also when called during construction. - if (stream._backpressureChangePromise !== undefined) { - stream._backpressureChangePromise_resolve(); - } - stream._backpressureChangePromise = newPromise(resolve => { - stream._backpressureChangePromise_resolve = resolve; - }); - stream._backpressure = backpressure; -} -// Class TransformStreamDefaultController -/** - * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. - * - * @public - */ -class TransformStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. - */ - get desiredSize() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('desiredSize'); - } - const readableController = this._controlledTransformStream._readable._readableStreamController; - return ReadableStreamDefaultControllerGetDesiredSize(readableController); - } - enqueue(chunk = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('enqueue'); - } - TransformStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors both the readable side and the writable side of the controlled transform stream, making all future - * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. - */ - error(reason = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('error'); - } - TransformStreamDefaultControllerError(this, reason); - } - /** - * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the - * transformer only needs to consume a portion of the chunks written to the writable side. - */ - terminate() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('terminate'); - } - TransformStreamDefaultControllerTerminate(this); - } -} -Object.defineProperties(TransformStreamDefaultController.prototype, { - enqueue: { enumerable: true }, - error: { enumerable: true }, - terminate: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStreamDefaultController', - configurable: true - }); -} -// Transform Stream Default Controller Abstract Operations -function IsTransformStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { - return false; - } - return true; -} -function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { - controller._controlledTransformStream = stream; - stream._transformStreamController = controller; - controller._transformAlgorithm = transformAlgorithm; - controller._flushAlgorithm = flushAlgorithm; -} -function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { - const controller = Object.create(TransformStreamDefaultController.prototype); - let transformAlgorithm = (chunk) => { - try { - TransformStreamDefaultControllerEnqueue(controller, chunk); - return promiseResolvedWith(undefined); - } - catch (transformResultE) { - return promiseRejectedWith(transformResultE); - } - }; - let flushAlgorithm = () => promiseResolvedWith(undefined); - if (transformer.transform !== undefined) { - transformAlgorithm = chunk => transformer.transform(chunk, controller); - } - if (transformer.flush !== undefined) { - flushAlgorithm = () => transformer.flush(controller); - } - SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); -} -function TransformStreamDefaultControllerClearAlgorithms(controller) { - controller._transformAlgorithm = undefined; - controller._flushAlgorithm = undefined; -} -function TransformStreamDefaultControllerEnqueue(controller, chunk) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { - throw new TypeError('Readable side is not in a state that permits enqueue'); - } - // We throttle transform invocations based on the backpressure of the ReadableStream, but we still - // accept TransformStreamDefaultControllerEnqueue() calls. - try { - ReadableStreamDefaultControllerEnqueue(readableController, chunk); - } - catch (e) { - // This happens when readableStrategy.size() throws. - TransformStreamErrorWritableAndUnblockWrite(stream, e); - throw stream._readable._storedError; - } - const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); - if (backpressure !== stream._backpressure) { - TransformStreamSetBackpressure(stream, true); - } -} -function TransformStreamDefaultControllerError(controller, e) { - TransformStreamError(controller._controlledTransformStream, e); -} -function TransformStreamDefaultControllerPerformTransform(controller, chunk) { - const transformPromise = controller._transformAlgorithm(chunk); - return transformPromiseWith(transformPromise, undefined, r => { - TransformStreamError(controller._controlledTransformStream, r); - throw r; - }); -} -function TransformStreamDefaultControllerTerminate(controller) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - ReadableStreamDefaultControllerClose(readableController); - const error = new TypeError('TransformStream terminated'); - TransformStreamErrorWritableAndUnblockWrite(stream, error); -} -// TransformStreamDefaultSink Algorithms -function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { - const controller = stream._transformStreamController; - if (stream._backpressure) { - const backpressureChangePromise = stream._backpressureChangePromise; - return transformPromiseWith(backpressureChangePromise, () => { - const writable = stream._writable; - const state = writable._state; - if (state === 'erroring') { - throw writable._storedError; - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - }); - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); -} -function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { - // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already - // errored. - TransformStreamError(stream, reason); - return promiseResolvedWith(undefined); -} -function TransformStreamDefaultSinkCloseAlgorithm(stream) { - // stream._readable cannot change after construction, so caching it across a call to user code is safe. - const readable = stream._readable; - const controller = stream._transformStreamController; - const flushPromise = controller._flushAlgorithm(); - TransformStreamDefaultControllerClearAlgorithms(controller); - // Return a promise that is fulfilled with undefined on success. - return transformPromiseWith(flushPromise, () => { - if (readable._state === 'errored') { - throw readable._storedError; - } - ReadableStreamDefaultControllerClose(readable._readableStreamController); - }, r => { - TransformStreamError(stream, r); - throw readable._storedError; - }); -} -// TransformStreamDefaultSource Algorithms -function TransformStreamDefaultSourcePullAlgorithm(stream) { - // Invariant. Enforced by the promises returned by start() and pull(). - TransformStreamSetBackpressure(stream, false); - // Prevent the next pull() call until there is backpressure. - return stream._backpressureChangePromise; -} -// Helper functions for the TransformStreamDefaultController. -function defaultControllerBrandCheckException(name) { - return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); -} -// Helper functions for the TransformStream. -function streamBrandCheckException(name) { - return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); -} - -var ponyfill_es6 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, - CountQueuingStrategy: CountQueuingStrategy, - ReadableByteStreamController: ReadableByteStreamController, - ReadableStream: ReadableStream$1, - ReadableStreamBYOBReader: ReadableStreamBYOBReader, - ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, - ReadableStreamDefaultController: ReadableStreamDefaultController, - ReadableStreamDefaultReader: ReadableStreamDefaultReader, - TransformStream: TransformStream$1, - TransformStreamDefaultController: TransformStreamDefaultController, - WritableStream: WritableStream$1, - WritableStreamDefaultController: WritableStreamDefaultController, - WritableStreamDefaultWriter: WritableStreamDefaultWriter -}); - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -function assert$1(test) { - if (!test) { - throw new TypeError('Assertion failed'); - } -} - -function noop$1() { - return; -} -function typeIsObject$1(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} - -function isStreamConstructor(ctor) { - if (typeof ctor !== 'function') { - return false; - } - var startCalled = false; - try { - new ctor({ - start: function () { - startCalled = true; - } - }); - } - catch (e) { - // ignore - } - return startCalled; -} -function isReadableStream(readable) { - if (!typeIsObject$1(readable)) { - return false; - } - if (typeof readable.getReader !== 'function') { - return false; - } - return true; -} -function isReadableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isReadableStream(new ctor())) { - return false; - } - return true; -} -function isWritableStream(writable) { - if (!typeIsObject$1(writable)) { - return false; - } - if (typeof writable.getWriter !== 'function') { - return false; - } - return true; -} -function isWritableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isWritableStream(new ctor())) { - return false; - } - return true; -} -function isTransformStream(transform) { - if (!typeIsObject$1(transform)) { - return false; - } - if (!isReadableStream(transform.readable)) { - return false; - } - if (!isWritableStream(transform.writable)) { - return false; - } - return true; -} -function isTransformStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isTransformStream(new ctor())) { - return false; - } - return true; -} -function supportsByobReader(readable) { - try { - var reader = readable.getReader({ mode: 'byob' }); - reader.releaseLock(); - return true; - } - catch (_a) { - return false; - } -} -function supportsByteSource(ctor) { - try { - new ctor({ type: 'bytes' }); - return true; - } - catch (_a) { - return false; - } -} - -function createReadableStreamWrapper(ctor) { - assert$1(isReadableStreamConstructor(ctor)); - var byteSourceSupported = supportsByteSource(ctor); - return function (readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - type = parseReadableType(type); - if (type === 'bytes' && !byteSourceSupported) { - type = undefined; - } - if (readable.constructor === ctor) { - if (type !== 'bytes' || supportsByobReader(readable)) { - return readable; - } - } - if (type === 'bytes') { - var source = createWrappingReadableSource(readable, { type: type }); - return new ctor(source); - } - else { - var source = createWrappingReadableSource(readable); - return new ctor(source); - } - }; -} -function createWrappingReadableSource(readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - assert$1(isReadableStream(readable)); - assert$1(readable.locked === false); - type = parseReadableType(type); - var source; - if (type === 'bytes') { - source = new WrappingReadableByteStreamSource(readable); - } - else { - source = new WrappingReadableStreamDefaultSource(readable); - } - return source; -} -function parseReadableType(type) { - var typeString = String(type); - if (typeString === 'bytes') { - return typeString; - } - else if (type === undefined) { - return type; - } - else { - throw new RangeError('Invalid type is specified'); - } -} -var AbstractWrappingReadableStreamSource = /** @class */ (function () { - function AbstractWrappingReadableStreamSource(underlyingStream) { - this._underlyingReader = undefined; - this._readerMode = undefined; - this._readableStreamController = undefined; - this._pendingRead = undefined; - this._underlyingStream = underlyingStream; - // always keep a reader attached to detect close/error - this._attachDefaultReader(); - } - AbstractWrappingReadableStreamSource.prototype.start = function (controller) { - this._readableStreamController = controller; - }; - AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) { - assert$1(this._underlyingReader !== undefined); - return this._underlyingReader.cancel(reason); - }; - AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () { - if (this._readerMode === "default" /* DEFAULT */) { - return; - } - this._detachReader(); - var reader = this._underlyingStream.getReader(); - this._readerMode = "default" /* DEFAULT */; - this._attachReader(reader); - }; - AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) { - var _this = this; - assert$1(this._underlyingReader === undefined); - this._underlyingReader = reader; - var closed = this._underlyingReader.closed; - if (!closed) { - return; - } - closed - .then(function () { return _this._finishPendingRead(); }) - .then(function () { - if (reader === _this._underlyingReader) { - _this._readableStreamController.close(); - } - }, function (reason) { - if (reader === _this._underlyingReader) { - _this._readableStreamController.error(reason); - } - }) - .catch(noop$1); - }; - AbstractWrappingReadableStreamSource.prototype._detachReader = function () { - if (this._underlyingReader === undefined) { - return; - } - this._underlyingReader.releaseLock(); - this._underlyingReader = undefined; - this._readerMode = undefined; - }; - AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () { - var _this = this; - this._attachDefaultReader(); - // TODO Backpressure? - var read = this._underlyingReader.read() - .then(function (result) { - var controller = _this._readableStreamController; - if (result.done) { - _this._tryClose(); - } - else { - controller.enqueue(result.value); - } - }); - this._setPendingRead(read); - return read; - }; - AbstractWrappingReadableStreamSource.prototype._tryClose = function () { - try { - this._readableStreamController.close(); - } - catch (_a) { - // already errored or closed - } - }; - AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) { - var _this = this; - var pendingRead; - var finishRead = function () { - if (_this._pendingRead === pendingRead) { - _this._pendingRead = undefined; - } - }; - this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead); - }; - AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () { - var _this = this; - if (!this._pendingRead) { - return undefined; - } - var afterRead = function () { return _this._finishPendingRead(); }; - return this._pendingRead.then(afterRead, afterRead); - }; - return AbstractWrappingReadableStreamSource; -}()); -var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) { - __extends(WrappingReadableStreamDefaultSource, _super); - function WrappingReadableStreamDefaultSource() { - return _super !== null && _super.apply(this, arguments) || this; - } - WrappingReadableStreamDefaultSource.prototype.pull = function () { - return this._pullWithDefaultReader(); - }; - return WrappingReadableStreamDefaultSource; -}(AbstractWrappingReadableStreamSource)); -function toUint8Array(view) { - return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); -} -function copyArrayBufferView(from, to) { - var fromArray = toUint8Array(from); - var toArray = toUint8Array(to); - toArray.set(fromArray, 0); -} -var WrappingReadableByteStreamSource = /** @class */ (function (_super) { - __extends(WrappingReadableByteStreamSource, _super); - function WrappingReadableByteStreamSource(underlyingStream) { - var _this = this; - var supportsByob = supportsByobReader(underlyingStream); - _this = _super.call(this, underlyingStream) || this; - _this._supportsByob = supportsByob; - return _this; - } - Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", { - get: function () { - return 'bytes'; - }, - enumerable: false, - configurable: true - }); - WrappingReadableByteStreamSource.prototype._attachByobReader = function () { - if (this._readerMode === "byob" /* BYOB */) { - return; - } - assert$1(this._supportsByob); - this._detachReader(); - var reader = this._underlyingStream.getReader({ mode: 'byob' }); - this._readerMode = "byob" /* BYOB */; - this._attachReader(reader); - }; - WrappingReadableByteStreamSource.prototype.pull = function () { - if (this._supportsByob) { - var byobRequest = this._readableStreamController.byobRequest; - if (byobRequest) { - return this._pullWithByobRequest(byobRequest); - } - } - return this._pullWithDefaultReader(); - }; - WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) { - var _this = this; - this._attachByobReader(); - // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly - // create a separate buffer to read into, then copy that to byobRequest.view - var buffer = new Uint8Array(byobRequest.view.byteLength); - // TODO Backpressure? - var read = this._underlyingReader.read(buffer) - .then(function (result) { - _this._readableStreamController; - if (result.done) { - _this._tryClose(); - byobRequest.respond(0); - } - else { - copyArrayBufferView(result.value, byobRequest.view); - byobRequest.respond(result.value.byteLength); - } - }); - this._setPendingRead(read); - return read; - }; - return WrappingReadableByteStreamSource; -}(AbstractWrappingReadableStreamSource)); - -function createWritableStreamWrapper(ctor) { - assert$1(isWritableStreamConstructor(ctor)); - return function (writable) { - if (writable.constructor === ctor) { - return writable; - } - var sink = createWrappingWritableSink(writable); - return new ctor(sink); - }; -} -function createWrappingWritableSink(writable) { - assert$1(isWritableStream(writable)); - assert$1(writable.locked === false); - var writer = writable.getWriter(); - return new WrappingWritableStreamSink(writer); -} -var WrappingWritableStreamSink = /** @class */ (function () { - function WrappingWritableStreamSink(underlyingWriter) { - var _this = this; - this._writableStreamController = undefined; - this._pendingWrite = undefined; - this._state = "writable" /* WRITABLE */; - this._storedError = undefined; - this._underlyingWriter = underlyingWriter; - this._errorPromise = new Promise(function (resolve, reject) { - _this._errorPromiseReject = reject; - }); - this._errorPromise.catch(noop$1); - } - WrappingWritableStreamSink.prototype.start = function (controller) { - var _this = this; - this._writableStreamController = controller; - this._underlyingWriter.closed - .then(function () { - _this._state = "closed" /* CLOSED */; - }) - .catch(function (reason) { return _this._finishErroring(reason); }); - }; - WrappingWritableStreamSink.prototype.write = function (chunk) { - var _this = this; - var writer = this._underlyingWriter; - // Detect past errors - if (writer.desiredSize === null) { - return writer.ready; - } - var writeRequest = writer.write(chunk); - // Detect future errors - writeRequest.catch(function (reason) { return _this._finishErroring(reason); }); - writer.ready.catch(function (reason) { return _this._startErroring(reason); }); - // Reject write when errored - var write = Promise.race([writeRequest, this._errorPromise]); - this._setPendingWrite(write); - return write; - }; - WrappingWritableStreamSink.prototype.close = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return this._underlyingWriter.close(); - } - return this._finishPendingWrite().then(function () { return _this.close(); }); - }; - WrappingWritableStreamSink.prototype.abort = function (reason) { - if (this._state === "errored" /* ERRORED */) { - return undefined; - } - var writer = this._underlyingWriter; - return writer.abort(reason); - }; - WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) { - var _this = this; - var pendingWrite; - var finishWrite = function () { - if (_this._pendingWrite === pendingWrite) { - _this._pendingWrite = undefined; - } - }; - this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite); - }; - WrappingWritableStreamSink.prototype._finishPendingWrite = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return Promise.resolve(); - } - var afterWrite = function () { return _this._finishPendingWrite(); }; - return this._pendingWrite.then(afterWrite, afterWrite); - }; - WrappingWritableStreamSink.prototype._startErroring = function (reason) { - var _this = this; - if (this._state === "writable" /* WRITABLE */) { - this._state = "erroring" /* ERRORING */; - this._storedError = reason; - var afterWrite = function () { return _this._finishErroring(reason); }; - if (this._pendingWrite === undefined) { - afterWrite(); - } - else { - this._finishPendingWrite().then(afterWrite, afterWrite); - } - this._writableStreamController.error(reason); - } - }; - WrappingWritableStreamSink.prototype._finishErroring = function (reason) { - if (this._state === "writable" /* WRITABLE */) { - this._startErroring(reason); - } - if (this._state === "erroring" /* ERRORING */) { - this._state = "errored" /* ERRORED */; - this._errorPromiseReject(this._storedError); - } - }; - return WrappingWritableStreamSink; -}()); - -function createTransformStreamWrapper(ctor) { - assert$1(isTransformStreamConstructor(ctor)); - return function (transform) { - if (transform.constructor === ctor) { - return transform; - } - var transformer = createWrappingTransformer(transform); - return new ctor(transformer); - }; -} -function createWrappingTransformer(transform) { - assert$1(isTransformStream(transform)); - var readable = transform.readable, writable = transform.writable; - assert$1(readable.locked === false); - assert$1(writable.locked === false); - var reader = readable.getReader(); - var writer; - try { - writer = writable.getWriter(); - } - catch (e) { - reader.releaseLock(); // do not leak reader - throw e; - } - return new WrappingTransformStreamTransformer(reader, writer); -} -var WrappingTransformStreamTransformer = /** @class */ (function () { - function WrappingTransformStreamTransformer(reader, writer) { - var _this = this; - this._transformStreamController = undefined; - this._onRead = function (result) { - if (result.done) { - return; - } - _this._transformStreamController.enqueue(result.value); - return _this._reader.read().then(_this._onRead); - }; - this._onError = function (reason) { - _this._flushReject(reason); - _this._transformStreamController.error(reason); - _this._reader.cancel(reason).catch(noop$1); - _this._writer.abort(reason).catch(noop$1); - }; - this._onTerminate = function () { - _this._flushResolve(); - _this._transformStreamController.terminate(); - var error = new TypeError('TransformStream terminated'); - _this._writer.abort(error).catch(noop$1); - }; - this._reader = reader; - this._writer = writer; - this._flushPromise = new Promise(function (resolve, reject) { - _this._flushResolve = resolve; - _this._flushReject = reject; - }); - } - WrappingTransformStreamTransformer.prototype.start = function (controller) { - this._transformStreamController = controller; - this._reader.read() - .then(this._onRead) - .then(this._onTerminate, this._onError); - var readerClosed = this._reader.closed; - if (readerClosed) { - readerClosed - .then(this._onTerminate, this._onError); - } - }; - WrappingTransformStreamTransformer.prototype.transform = function (chunk) { - return this._writer.write(chunk); - }; - WrappingTransformStreamTransformer.prototype.flush = function () { - var _this = this; - return this._writer.close() - .then(function () { return _this._flushPromise; }); - }; - return WrappingTransformStreamTransformer; -}()); - -var webStreamsAdapter = /*#__PURE__*/Object.freeze({ - __proto__: null, - createReadableStreamWrapper: createReadableStreamWrapper, - createTransformStreamWrapper: createTransformStreamWrapper, - createWrappingReadableSource: createWrappingReadableSource, - createWrappingTransformer: createWrappingTransformer, - createWrappingWritableSink: createWrappingWritableSink, - createWritableStreamWrapper: createWritableStreamWrapper -}); - -var bn = createCommonjsModule(function (module) { -(function (module, exports) { - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = buffer__default['default'].Buffer; - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) ; else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(module, commonjsGlobal); -}); - -var bn$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': bn, - __moduleExports: bn -}); - -/** - * @fileoverview - * BigInteger implementation of basic operations - * Wrapper of bn.js library (wwww.github.com/indutny/bn.js) - * @module biginteger/bn - * @private - */ - -/** - * @private - */ -class BigInteger$1 { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - - this.value = new bn(n); - } - - clone() { - const clone = new BigInteger$1(null); - this.value.copy(clone.value); - return clone; - } - - /** - * BigInteger increment in place - */ - iinc() { - this.value.iadd(new bn(1)); - return this; - } - - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - - /** - * BigInteger decrement in place - */ - idec() { - this.value.isub(new bn(1)); - return this; - } - - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } - - - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value.iadd(x.value); - return this; - } - - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } - - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value.isub(x.value); - return this; - } - - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } - - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value.imul(x.value); - return this; - } - - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); - } - - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value = this.value.umod(m.value); - return this; - } - - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } - - /** - * Compute modular exponentiation - * Much faster than this.exp(e).mod(n) - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - // We use either Montgomery or normal reduction context - // Montgomery requires coprime n and R (montogmery multiplier) - // bn.js picks R as power of 2, so n must be odd - const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value); - const x = this.clone(); - x.value = x.value.toRed(nred).redPow(e.value).fromRed(); - return x; - } - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - // invm returns a wrong result if the inverse does not exist - if (!this.gcd(n).isOne()) { - throw new Error('Inverse does not exist'); - } - return new BigInteger$1(this.value.invm(n.value)); - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} n - Operand - * @returns {BigInteger} gcd - */ - gcd(n) { - return new BigInteger$1(this.value.gcd(n.value)); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value.ishln(x.value.toNumber()); - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value.ishrn(x.value.toNumber()); - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value.eq(x.value); - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value.lt(x.value); - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value.lte(x.value); - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value.gt(x.value); - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value.gte(x.value); - } - - isZero() { - return this.value.isZero(); - } - - isOne() { - return this.value.eq(new bn(1)); - } - - isNegative() { - return this.value.isNeg(); - } - - isEven() { - return this.value.isEven(); - } - - abs() { - const res = this.clone(); - res.value = res.value.abs(); - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - return this.value.toNumber(); - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - return this.value.testn(i) ? 1 : 0; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - return this.value.bitLength(); - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - return this.value.byteLength(); - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - return this.value.toArrayLike(Uint8Array, endian, length); - } -} - -var bn_interface = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': BigInteger$1 -}); - -var utils_1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - return res; -} -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; -}); - -var utils_1$1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - - - - -utils.assert = minimalisticAssert; -utils.toArray = utils_1.toArray; -utils.zero2 = utils_1.zero2; -utils.toHex = utils_1.toHex; -utils.encode = utils_1.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new bn(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; -}); - -var r$1; - -var brorand = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -var Rand_1 = Rand; - -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; - -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); - - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; - -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; - - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto$2 = crypto__default['default']; - if (typeof crypto$2.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto$2.randomBytes(n); - }; - } catch (e) { - } -} -brorand.Rand = Rand_1; - -var getNAF = utils_1$1.getNAF; -var getJSF = utils_1$1.getJSF; -var assert$2 = utils_1$1.assert; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); - - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -var base = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$2(p.precomputed); - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); - - if (i < 0) - break; - var z = naf[i]; - assert$2(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert$2(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$2(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -var assert$3 = utils_1$1.assert; - -function ShortCurve(conf) { - base.call(this, 'short', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, base); -var short_1 = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; - -function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -function MontCurve(conf) { - base.call(this, 'mont', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - // Note: this implementation is according to the original paper - // by P. Montgomery, NOT the one by D. J. Bernstein. - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, base); -var mont = MontCurve; - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point$1(curve, x, z) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits(Point$1, base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - var bytes = utils_1$1.toArray(bytes, enc); - - // TODO Curve448 - // Montgomery curve points must be represented in the compressed format - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (bytes.length === 33 && bytes[0] === 0x40) - bytes = bytes.slice(1, 33).reverse(); // point must be little-endian - if (bytes.length !== 32) - throw new Error('Unknown point compression format'); - return this.point(bytes, 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); -}; - -Point$1.prototype.precompute = function precompute() { - // No-op -}; - -Point$1.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - - // Note: the output should always be little-endian - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (compact) { - return [ 0x40 ].concat(this.getX().toArray('le', len)); - } else { - return this.getX().toArray('be', len); - } -}; - -Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); -}; - -Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point$1.prototype.mul = function mul(k) { - k = new bn(k, 16); - - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -var assert$4 = utils_1$1.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - base.call(this, 'edwards', conf); - - this.a = new bn(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, base); -var edwards = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new bn(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } - - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point$2(curve, x, y, z, t) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point$2, base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$2.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point$2(this, x, y, z, t); -}; - -Point$2.fromJSON = function fromJSON(curve, obj) { - return new Point$2(curve, obj[0], obj[1], obj[2]); -}; - -Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point$2.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); -}; - -Point$2.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); - } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point$2.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point$2.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; - -Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; - -Point$2.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point$2.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point$2.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point$2.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -Point$2.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; - -Point$2.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -// Compatibility with BaseCurve -Point$2.prototype.toP = Point$2.prototype.normalize; -Point$2.prototype.mixedAdd = Point$2.prototype.add; - -var curve_1 = createCommonjsModule(function (module, exports) { - -var curve = exports; - -curve.base = base; -curve.short = short_1; -curve.mont = mont; -curve.edwards = edwards; -}); - -var rotl32$2 = utils.rotl32; -var sum32$3 = utils.sum32; -var sum32_5$2 = utils.sum32_5; -var ft_1$1 = common$1.ft_1; -var BlockHash$4 = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash$4.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash$4); -var _1 = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; - -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - - for(; i < W.length; i++) - W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$2(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32$3(this.h[0], a); - this.h[1] = sum32$3(this.h[1], b); - this.h[2] = sum32$3(this.h[2], c); - this.h[3] = sum32$3(this.h[3], d); - this.h[4] = sum32$3(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -var sha1 = _1; -var sha224 = _224; -var sha256 = _256; -var sha384 = _384; -var sha512 = _512; - -var sha = { - sha1: sha1, - sha224: sha224, - sha256: sha256, - sha384: sha384, - sha512: sha512 -}; - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -var hmac = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -var hash_1 = createCommonjsModule(function (module, exports) { -var hash = exports; - -hash.utils = utils; -hash.common = common; -hash.sha = sha; -hash.ripemd = ripemd; -hash.hmac = hmac; - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; -}); - -var secp256k1 = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; - -var curves_1 = createCommonjsModule(function (module, exports) { - -var curves = exports; - - - - - -var assert = utils_1$1.assert; - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve_1.short(options); - else if (options.type === 'edwards') - this.curve = new curve_1.edwards(options); - else if (options.type === 'mont') - this.curve = new curve_1.mont(options); - else throw new Error('Unknown curve type.'); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash_1.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash_1.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash_1.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); - -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash_1.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); - -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash_1.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); - -// https://tools.ietf.org/html/rfc7748#section-4.1 -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '9' - ] -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.4 -defineCurve('brainpoolP256r1', { - type: 'short', - prime: null, - p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377', - a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9', - b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6', - n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7', - hash: hash_1.sha256, // or 384, or 512 - gRed: false, - g: [ - '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262', - '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.6 -defineCurve('brainpoolP384r1', { - type: 'short', - prime: null, - p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' + - 'ACD3A729 901D1A71 87470013 3107EC53', - a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' + - '8AA5814A 503AD4EB 04A8C7DD 22CE2826', - b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' + - '7CB43902 95DBC994 3AB78696 FA504C11', - n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' + - 'CF3AB6AF 6B7FC310 3B883202 E9046565', - hash: hash_1.sha384, // or 512 - gRed: false, - g: [ - '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' + - 'E8E826E03436D646AAEF87B2E247D4AF1E', - '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' + - '280E4646217791811142820341263C5315' - ] -}); - -// https://tools.ietf.org/html/rfc5639#section-3.7 -defineCurve('brainpoolP512r1', { - type: 'short', - prime: null, - p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' + - '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3', - a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' + - '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA', - b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' + - '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723', - n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' + - '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069', - hash: hash_1.sha512, - gRed: false, - g: [ - '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' + - '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', - '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' + - '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892' - ] -}); - -// https://en.bitcoin.it/wiki/Secp256k1 -var pre; -try { - pre = secp256k1; -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash_1.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); -}); - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils_1.toArray(options.pers, options.persEnc || 'hex'); - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -var hmacDrbg = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); - - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils_1.encode(res, enc); -}; - -var assert$5 = utils_1$1.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); -} -var key = KeyPair; - -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; - -// TODO: should not validate for X25519 -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(enc, compact) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - if (!enc) - return this.pub; - - return this.pub.encode(enc, compact); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new bn(key, enc || 16); - - // For Curve25519/Curve448 we have a specific procedure. - // TODO Curve448 - if (this.ec.curve.type === 'mont') { - var one = this.ec.curve.one; - var mask = one.ushln(255 - 3).sub(one).ushln(3); - this.priv = this.priv.or(one.ushln(255 - 1)); - this.priv = this.priv.and(mask); - } else - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -var assert$6 = utils_1$1.assert; - -function Signature$1(options, enc) { - if (options instanceof Signature$1) - return options; - - if (this._importDER(options, enc)) - return; - - assert$6(options.r && options.s, 'Signature without r or s'); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; -} -var signature$1 = Signature$1; - -function Position() { - this.place = 0; -} - -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} - -Signature$1.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); - } - - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature$1.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); -}; - -var assert$7 = utils_1$1.assert; - - - - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options); - - options = curves_1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves_1.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash function for DRBG - this.hash = options.hash || options.curve.hash; -} -var ec = EC; - -EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); -}; - -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); -}; - -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); - - // Key generation for curve25519 is simpler - if (this.curve.type === 'mont') { - var priv = new bn(drbg.generate(32)); - return this.keyFromPrivate(priv); - } - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; - -EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) { - bitSize = bitSize || msg.byteLength() * 8; - var delta = bitSize - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.truncateMsg = function truncateMSG(msg) { - // Bit size is only determined correctly for Uint8Arrays and hex strings - var bitSize; - if (msg instanceof Uint8Array) { - bitSize = msg.byteLength * 8; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else if (typeof msg === 'string') { - bitSize = msg.length * 4; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else { - msg = this._truncateToN(new bn(msg, 16)); - } - return msg; -}; - -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this.truncateMsg(msg); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); - - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; - - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new signature$1({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - key = this.keyFromPublic(key, enc); - signature = new signature$1(signature, 'hex'); - // Fallback to the old code - var ret = this._verify(this.truncateMsg(msg), signature, key) || - this._verify(this._truncateToN(new bn(msg, 16)), signature, key); - return ret; -}; - -EC.prototype._verify = function _verify(msg, signature, key) { - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; - -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$7((3 & j) === j, 'The recovery param is more than two bits'); - signature = new signature$1(signature, enc); - - var n = this.n; - var e = new bn(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; - -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new signature$1(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; - - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -var assert$8 = utils_1$1.assert; -var parseBytes = utils_1$1.parseBytes; -var cachedProperty = utils_1$1.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair$1(eddsa, params) { - this.eddsa = eddsa; - if (params.hasOwnProperty('secret')) - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else { - this._pubBytes = parseBytes(params.pub); - if (this._pubBytes && this._pubBytes.length === 33 && - this._pubBytes[0] === 0x40) - this._pubBytes = this._pubBytes.slice(1, 33); - if (this._pubBytes && this._pubBytes.length !== 32) - throw new Error('Unknown point compression format'); - } -} - -KeyPair$1.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$1) - return pub; - return new KeyPair$1(eddsa, { pub: pub }); -}; - -KeyPair$1.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$1) - return secret; - return new KeyPair$1(eddsa, { secret: secret }); -}; - -KeyPair$1.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair$1, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair$1, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair$1, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair$1, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair$1.prototype.sign = function sign(message) { - assert$8(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair$1.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair$1.prototype.getSecret = function getSecret(enc) { - assert$8(this._secret, 'KeyPair is public only'); - return utils_1$1.encode(this.secret(), enc); -}; - -KeyPair$1.prototype.getPublic = function getPublic(enc, compact) { - return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); -}; - -var key$1 = KeyPair$1; - -var assert$9 = utils_1$1.assert; -var cachedProperty$1 = utils_1$1.cachedProperty; -var parseBytes$1 = utils_1$1.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature$2(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; - } - - assert$9(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof bn) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty$1(Signature$2, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty$1(Signature$2, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature$2.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature$2.prototype.toHex = function toHex() { - return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -var signature$2 = Signature$2; - -var assert$a = utils_1$1.assert; -var parseBytes$2 = utils_1$1.parseBytes; - - - -function EDDSA(curve) { - assert$a(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = curves_1[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash_1.sha512; -} - -var eddsa$1 = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes$2(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes$2(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n); -}; - -EDDSA.prototype.keyPair = function keyPair(options) { - return new key$1(this, options); -}; - -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return key$1.fromPublic(this, pub); -}; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return key$1.fromSecret(this, secret); -}; - -EDDSA.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.curve.n.toArray() - }); - - return this.keyFromSecret(drbg.generate(32)); -}; - -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof signature$2) - return sig; - return new signature$2(this, sig); -}; - -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; - -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils_1$1.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils_1$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; - -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; - -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils_1$1.intFromLE(bytes); -}; - -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; - -var elliptic_1 = createCommonjsModule(function (module, exports) { - -var elliptic = exports; - -elliptic.utils = utils_1$1; -elliptic.rand = brorand; -elliptic.curve = curve_1; -elliptic.curves = curves_1; - -// Protocols -elliptic.ec = ec; -elliptic.eddsa = eddsa$1; -}); - -var elliptic$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': elliptic_1, - __moduleExports: elliptic_1 -}); - -exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket; -exports.CleartextMessage = CleartextMessage; -exports.CompressedDataPacket = CompressedDataPacket; -exports.LiteralDataPacket = LiteralDataPacket; -exports.MarkerPacket = MarkerPacket; -exports.Message = Message; -exports.OnePassSignaturePacket = OnePassSignaturePacket; -exports.PacketList = PacketList; -exports.PrivateKey = PrivateKey; -exports.PublicKey = PublicKey; -exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket; -exports.PublicKeyPacket = PublicKeyPacket; -exports.PublicSubkeyPacket = PublicSubkeyPacket; -exports.SecretKeyPacket = SecretKeyPacket; -exports.SecretSubkeyPacket = SecretSubkeyPacket; -exports.Signature = Signature; -exports.SignaturePacket = SignaturePacket; -exports.Subkey = Subkey; -exports.SymEncryptedIntegrityProtectedDataPacket = SymEncryptedIntegrityProtectedDataPacket; -exports.SymEncryptedSessionKeyPacket = SymEncryptedSessionKeyPacket; -exports.SymmetricallyEncryptedDataPacket = SymmetricallyEncryptedDataPacket; -exports.TrustPacket = TrustPacket; -exports.UnparseablePacket = UnparseablePacket; -exports.UserAttributePacket = UserAttributePacket; -exports.UserIDPacket = UserIDPacket; -exports.armor = armor; -exports.config = config; -exports.createCleartextMessage = createCleartextMessage; -exports.createMessage = createMessage; -exports.decrypt = decrypt$5; -exports.decryptKey = decryptKey; -exports.decryptSessionKeys = decryptSessionKeys; -exports.encrypt = encrypt$5; -exports.encryptKey = encryptKey; -exports.encryptSessionKey = encryptSessionKey; -exports.enums = enums; -exports.generateKey = generateKey; -exports.generateSessionKey = generateSessionKey$1; -exports.readCleartextMessage = readCleartextMessage; -exports.readKey = readKey; -exports.readKeys = readKeys; -exports.readMessage = readMessage; -exports.readPrivateKey = readPrivateKey; -exports.readPrivateKeys = readPrivateKeys; -exports.readSignature = readSignature; -exports.reformatKey = reformatKey; -exports.revokeKey = revokeKey; -exports.sign = sign$6; -exports.unarmor = unarmor; -exports.verify = verify$6; diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.cjs b/app/node_modules/openpgp/dist/node/openpgp.min.cjs new file mode 100644 index 000000000..a9090f4e6 --- /dev/null +++ b/app/node_modules/openpgp/dist/node/openpgp.min.cjs @@ -0,0 +1,16 @@ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +"use strict";const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var t=require("module"),r=require("node:crypto"),n="undefined"!=typeof document?document.currentScript:null;function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}function s(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var a=/*#__PURE__*/i(r);const o=Symbol("doneWritingPromise"),c=Symbol("doneWritingResolve"),h=Symbol("doneWritingReject"),u=Symbol("readingIndex");class l extends Array{constructor(){super(),Object.setPrototypeOf(this,l.prototype),this[o]=new Promise(((e,t)=>{this[c]=e,this[h]=t})),this[o].catch((()=>{}))}}function y(e){return e&&e.getReader&&Array.isArray(e)}function f(e){if(!y(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}function g(t){if(y(t))return"array";if(e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t))return"web";if(t&&!(e.ReadableStream&&t instanceof e.ReadableStream)&&"function"==typeof t._read&&"object"==typeof t._readableState)throw Error("Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`");return!(!t||!t.getReader)&&"web-like"}function p(e){return Uint8Array.prototype.isPrototypeOf(e)}function d(e){if(1===e.length)return e[0];let t=0;for(let r=0;r(await this[o],this[u]===this.length?{value:void 0,done:!0}:{value:this[this[u]++],done:!1})}},l.prototype.readToEnd=async function(e){await this[o];const t=e(this.slice(this[u]));return this.length=0,t},l.prototype.clone=function(){const e=new l;return e[o]=this[o].then((()=>{e.push(...this)})),e},f.prototype.write=async function(e){this.stream.push(e)},f.prototype.close=async function(){this.stream[c]()},f.prototype.abort=async function(e){return this.stream[h](e),e},f.prototype.releaseLock=function(){},"object"==typeof e.process&&e.process.versions;const A=new WeakSet,w=Symbol("externalBuffer");function m(e){if(this.stream=e,e[w]&&(this[w]=e[w].slice()),y(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=()=>{})}if(g(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let t=!1;this._read=async()=>t||A.has(e)?{value:void 0,done:!0}:(t=!0,{value:e,done:!1}),this._releaseLock=()=>{if(t)try{A.add(e)}catch(e){}}}function b(e){return g(e)?e:new ReadableStream({start(t){t.enqueue(e),t.close()}})}function k(e){if(g(e))return e;const t=new l;return(async()=>{const r=M(t);await r.write(e),await r.close()})(),t}function E(e){return e.some((e=>g(e)&&!y(e)))?function(e){e=e.map(b);const t=I((async function(e){await Promise.all(n.map((t=>R(t,e))))}));let r=Promise.resolve();const n=e.map(((n,i)=>K(n,((n,s)=>(r=r.then((()=>v(n,t.writable,{preventClose:i!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>y(e)))?function(e){const t=new l;let r=Promise.resolve();return e.forEach(((n,i)=>(r=r.then((()=>v(n,t,{preventClose:i!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):d(e)}async function v(e,t,{preventClose:r=!1,preventAbort:n=!1,preventCancel:i=!1}={}){if(g(e)&&!y(e)){e=b(e);try{if(e[w]){const r=M(t);for(let t=0;t{t=e,r=n})),t=null,r=null)},close:n.close.bind(n),abort:n.error.bind(n)})}}function S(e,t=()=>{},r=()=>{}){if(y(e)){const n=new l;return(async()=>{const i=M(n);try{const n=await Q(e),s=t(n),a=r();let o;o=void 0!==s&&void 0!==a?E([s,a]):void 0!==s?s:a,await i.write(o),await i.close()}catch(e){await i.abort(e)}})(),n}if(g(e))return B(e,{async transform(e,r){try{const n=await t(e);void 0!==n&&r.enqueue(n)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const n=t(e),i=r();return void 0!==n&&void 0!==i?E([n,i]):void 0!==n?n:i}function K(e,t){if(g(e)&&!y(e)){let r;const n=new TransformStream({start(e){r=e}}),i=v(e,n.writable),s=I((async function(e){r.error(e),await i,await new Promise(setTimeout)}));return t(n.readable,s.writable),s.readable}e=k(e);const r=new l;return t(e,r),r}function C(e,t){let r;const n=K(e,((e,i)=>{const s=T(e);s.remainder=()=>(s.releaseLock(),v(e,i),n),r=t(s)}));return r}function P(e){if(y(e))return e.clone();if(g(e)){const t=function(e){if(y(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(g(e)){const t=b(e).tee();return t[0][w]=t[1][w]=e[w],t}return[x(e),x(e)]}(e);return U(e,t[0]),t[1]}return x(e)}function D(e){return y(e)?P(e):g(e)?new ReadableStream({start(t){const r=K(e,(async(e,r)=>{const n=T(e),i=M(r);try{for(;;){await i.ready;const{done:e,value:r}=await n.read();if(e){try{t.close()}catch(e){}return void await i.close()}try{t.enqueue(r)}catch(e){}await i.write(r)}}catch(e){t.error(e),await i.abort(e)}}));U(e,r)}}):x(e)}function U(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,n])=>{"constructor"!==r&&(n.value?n.value=n.value.bind(t):n.get=n.get.bind(t),Object.defineProperty(e,r,n))}))}function x(e,t=0,r=1/0){if(y(e))throw Error("Not implemented");if(g(e)){if(t>=0&&r>=0){let n=0;return B(e,{transform(e,i){n=t&&i.enqueue(x(e,Math.max(t-n,0),r-n)),n+=e.length):i.terminate()}})}if(t<0&&(r<0||r===1/0)){let n=[];return S(e,(e=>{e.length>=-t?n=[e]:n.push(e)}),(()=>x(E(n),t,r)))}if(0===t&&r<0){let n;return S(e,(e=>{const i=n?E([n,e]):e;if(i.length>=-r)return n=x(i,r),x(i,t,r);n=i}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),L((async()=>x(await Q(e),t,r)))}return e[w]&&(e=E(e[w].concat([e]))),p(e)?e.subarray(t,r===1/0?e.length:r):e.slice(t,r)}async function Q(e,t=E){return y(e)?e.readToEnd(t):g(e)?T(e).readToEnd(t):e}async function R(e,t){if(g(e)){if(e.cancel){const r=await e.cancel(t);return await new Promise(setTimeout),r}if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function L(e){const t=new l;return(async()=>{const r=M(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}function T(e){return new m(e)}function M(e){return new f(e)}m.prototype.read=async function(){if(this[w]&&this[w].length){return{done:!1,value:this[w].shift()}}return this._read()},m.prototype.releaseLock=function(){this[w]&&(this.stream[w]=this[w]),this._releaseLock()},m.prototype.cancel=function(e){return this._cancel(e)},m.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:n}=await this.read();if(n+="",r)return t.length?E(t):void 0;const i=n.indexOf("\n")+1;i&&(e=E(t.concat(n.substr(0,i))),t=[]),i!==n.length&&t.push(n.substr(i))}return this.unshift(...t),e},m.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(x(t,1)),r},m.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:n,value:i}=await this.read();if(n)return t.length?E(t):void 0;if(t.push(i),r+=i.length,r>=e){const r=E(t);return this.unshift(x(r,e)),x(r,0,e)}}},m.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},m.prototype.unshift=function(...e){this[w]||(this[w]=[]),1===e.length&&p(e[0])&&this[w].length&&e[0].length&&this[w][0].byteOffset>=e[0].length?this[w][0]=new Uint8Array(this[w][0].buffer,this[w][0].byteOffset-e[0].length,this[w][0].byteLength+e[0].length):this[w].unshift(...e.filter((e=>e&&e.length)))},m.prototype.readToEnd=async function(e=E){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};const N=Symbol("byValue");var F={curve:{nistP256:"nistP256",p256:"nistP256",nistP384:"nistP384",p384:"nistP384",nistP521:"nistP521",p521:"nistP521",secp256k1:"secp256k1",ed25519Legacy:"ed25519Legacy",ed25519:"ed25519Legacy",curve25519Legacy:"curve25519Legacy",curve25519:"curve25519Legacy",brainpoolP256r1:"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,argon2:4,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11,sha3_256:12,sha3_512:14},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,gcm:3,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20,padding:21},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuerKeyID:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34,preferredCipherSuites:39},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4,seipdv2:8},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[N]||(e[N]=[],Object.entries(e).forEach((([t,r])=>{e[N][r]=t}))),void 0!==e[N][t])return e[N][t];throw Error("Invalid enum value.")}},O={preferredHashAlgorithm:F.hash.sha512,preferredSymmetricAlgorithm:F.symmetric.aes256,preferredCompressionAlgorithm:F.compression.uncompressed,aeadProtect:!1,parseAEADEncryptedV4KeysAsLegacy:!1,preferredAEADAlgorithm:F.aead.gcm,aeadChunkSizeByte:12,v6Keys:!1,enableParsingV5Entities:!1,s2kType:F.s2k.iterated,s2kIterationCountByte:224,s2kArgon2Params:{passes:3,parallelism:4,memoryExponent:16},allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,minRSABits:2047,passwordCollisionCheck:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,allowMissingKeyFlags:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([F.symmetric.aes128,F.symmetric.aes192,F.symmetric.aes256]),ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 6.0.0",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],nonDeterministicSignaturesViaNotation:!0,useEllipticFallback:!0,rejectHashAlgorithms:new Set([F.hash.md5,F.hash.ripemd]),rejectMessageHashAlgorithms:new Set([F.hash.md5,F.hash.ripemd,F.hash.sha1]),rejectPublicKeyAlgorithms:new Set([F.publicKey.elgamal,F.publicKey.dsa]),rejectCurves:new Set([F.curve.secp256k1])};const H=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),z={isString:function(e){return"string"==typeof e||e instanceof String},nodeRequire:t.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:n&&"SCRIPT"===n.tagName.toUpperCase()&&n.src||new URL("openpgp.min.cjs",document.baseURI).href),isArray:function(e){return e instanceof Array},isUint8Array:p,isStream:g,getNobleCurve:async(e,t)=>{if(!O.useEllipticFallback)throw Error("This curve is only supported in the full build of OpenPGP.js");const{nobleCurves:r}=await Promise.resolve().then((function(){return $u}));switch(e){case F.publicKey.ecdh:case F.publicKey.ecdsa:{const e=r.get(t);if(!e)throw Error("Unsupported curve");return e}case F.publicKey.x448:return r.get("x448");case F.publicKey.ed448:return r.get("ed448");default:throw Error("Unsupported curve")}},readNumber:function(e){let t=0;for(let r=0;r>8*(t-n-1)&255;return r},readDate:function(e){const t=z.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return z.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return z.readExactSubarray(e,2,2+t)},readExactSubarray:function(e,t,r){if(e.lengtht)throw Error("Input array too long");const r=new Uint8Array(t),n=t-e.length;return r.set(e,n),r},uint8ArrayToMPI:function(e){const t=z.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),n=new Uint8Array([(65280&t)>>8,255&t]);return z.concatUint8Array([n,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t="0123456789abcdef";let r="";return e.forEach((e=>{r+=t[e>>4]+t[15&e]})),r},stringToUint8Array:function(e){return S(e,(e=>{if(!z.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return S(e,r,(()=>r(new Uint8Array,!0)))},concat:E,concatUint8Array:d,equalsUint8Array:function(e,t){if(!z.isUint8Array(e)||!z.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let n=0;n>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){const t=void 0!==e&&e.crypto&&e.crypto.subtle||this.getNodeCrypto()?.webcrypto.subtle;if(!t)throw Error("The WebCrypto API is not available");return t},getNodeCrypto:function(){return this.nodeRequire("crypto")},getNodeZlib:function(){return this.nodeRequire("zlib")},getNodeBuffer:function(){return(this.nodeRequire("buffer")||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return this.nodeRequire("os").cpus().length},isEmailAddress:function(e){if(!z.isString(e))return!1;return/^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u.test(e)},canonicalizeEOL:function(e){let t=!1;return S(e,(e=>{let r;t&&(e=z.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const n=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&n.push(r);if(!n.length)return e;const i=new Uint8Array(e.length+n.length);let s=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return S(e,(e=>{let r;13===(e=t&&10!==e[0]?z.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let n=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const i=r-(10===e[r]?1:0);t&&e.copyWithin(n,t,i),n+=i-t}return e.subarray(0,n)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let n;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){n=e}}))),r(n)}))},selectUint8Array:function(e,t,r){const n=Math.max(t.length,r.length),i=new Uint8Array(n);let s=0;for(let n=0;n{t=z.concatUint8Array([t,e]);const r=[],n=Math.floor(t.length/45),i=45*n,s=G(t.subarray(0,i));for(let e=0;et.length?G(t)+"\n":""))}function V(e){let t="";return S(e,(e=>{t+=e;let r=0;const n=[" ","\t","\r","\n"];for(let e=0;e0&&(i-r)%4!=0;i--)n.includes(t[i])&&r--;const s=j(t.substr(0,i));return t=t.substr(i),s}),(()=>j(t)))}function J(e){return V(e.replace(/-/g,"+").replace(/_/g,"/"))}function Y(e,t){let r=q(e).replace(/[\r\n]/g,"");return r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,""),r}function W(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?F.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?F.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?F.armor.signed:/MESSAGE/.test(t[1])?F.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?F.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?F.armor.privateKey:/SIGNATURE/.test(t[1])?F.armor.signature:void 0}function Z(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function $(e){const t=function(e){let t=13501623;return S(e,(e=>{const r=ee?Math.floor(e.length/4):0,n=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^X[1][t>>16&255]^X[2][t>>8&255]^X[3][255&t];for(let n=4*r;n>8^X[0][255&t^e[n]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e);return q(t)}_?(G=e=>_.from(e).toString("base64"),j=e=>{const t=_.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(G=e=>btoa(z.uint8ArrayToString(e)),j=e=>z.stringToUint8Array(atob(e)));const X=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(8388608&t?8801531:0);X[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)X[1][e]=X[0][e]>>8^X[0][255&X[0][e]];for(let e=0;e<=255;e++)X[2][e]=X[1][e]>>8^X[0][255&X[1][e]];for(let e=0;e<=255;e++)X[3][e]=X[2][e]>>8^X[0][255&X[2][e]];const ee=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function te(e){for(let t=0;t=0&&r!==e.length-1&&(t=e.slice(0,r)),t}function ne(e){return new Promise((async(t,r)=>{try{const n=/^-----[^-]+-----$/m,i=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const a=[];let o,c,h=a,u=[];const l=V(K(e,(async(e,y)=>{const f=T(e);try{for(;;){let e=await f.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=z.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(o)c||s!==F.armor.signed||(n.test(e)?(u=u.join("\r\n"),c=!0,te(h),h=[],o=!1):u.push(e.replace(/^- /,"")));else if(n.test(e)&&r(Error("Mandatory blank line missing between armor headers and armor data")),i.test(e)){if(te(h),o=!0,c||s!==F.armor.signed){t({text:u,data:l,headers:a,type:s});break}}else h.push(e);else n.test(e)&&(s=W(e))}}catch(e){return void r(e)}const g=M(y);try{for(;;){await g.ready;const{done:e,value:t}=await f.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await f.readToEnd();e.length||(e=""),e=r+e,e=z.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=re(t[0].slice(0,-1));await g.write(i);break}await g.write(r)}await g.ready,await g.close()}catch(e){await g.abort(e)}})))}catch(e){r(e)}})).then((async e=>(y(e.data)&&(e.data=await Q(e.data)),e)))}function ie(e,t,r,n,i,s=!1,a=O){let o,c;e===F.armor.signed&&(o=t.text,c=t.hash,t=t.data);const h=s&&D(t),u=[];switch(e){case F.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+n+"-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP MESSAGE, PART "+r+"/"+n+"-----\n");break;case F.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case F.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push(c?`Hash: ${c}\n\n`:"\n"),u.push(o.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP SIGNATURE-----\n");break;case F.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP MESSAGE-----\n");break;case F.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case F.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case F.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(Z(i,a)),u.push(q(t)),h&&u.push("=",$(h)),u.push("-----END PGP SIGNATURE-----\n")}return z.concat(u)}async function se(e){switch(e){case F.symmetric.aes128:case F.symmetric.aes192:case F.symmetric.aes256:throw Error("Not a legacy cipher");case F.symmetric.cast5:case F.symmetric.blowfish:case F.symmetric.twofish:case F.symmetric.tripledes:{const{legacyCiphers:t}=await Promise.resolve().then((function(){return fl})),r=t.get(e);if(!r)throw Error("Unsupported cipher algorithm");return r}default:throw Error("Unsupported cipher algorithm")}}function ae(e){switch(e){case F.symmetric.aes128:case F.symmetric.aes192:case F.symmetric.aes256:case F.symmetric.twofish:return 16;case F.symmetric.blowfish:case F.symmetric.cast5:case F.symmetric.tripledes:return 8;default:throw Error("Unsupported cipher")}}function oe(e){switch(e){case F.symmetric.aes128:case F.symmetric.blowfish:case F.symmetric.cast5:return 16;case F.symmetric.aes192:case F.symmetric.tripledes:return 24;case F.symmetric.aes256:case F.symmetric.twofish:return 32;default:throw Error("Unsupported cipher")}}function ce(e){return{keySize:oe(e),blockSize:ae(e)}}var he=/*#__PURE__*/Object.freeze({__proto__:null,getCipherParams:ce,getLegacyCipher:se});function ue(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r=ye(r,n,i,s,t[0],7,-680876936),s=ye(s,r,n,i,t[1],12,-389564586),i=ye(i,s,r,n,t[2],17,606105819),n=ye(n,i,s,r,t[3],22,-1044525330),r=ye(r,n,i,s,t[4],7,-176418897),s=ye(s,r,n,i,t[5],12,1200080426),i=ye(i,s,r,n,t[6],17,-1473231341),n=ye(n,i,s,r,t[7],22,-45705983),r=ye(r,n,i,s,t[8],7,1770035416),s=ye(s,r,n,i,t[9],12,-1958414417),i=ye(i,s,r,n,t[10],17,-42063),n=ye(n,i,s,r,t[11],22,-1990404162),r=ye(r,n,i,s,t[12],7,1804603682),s=ye(s,r,n,i,t[13],12,-40341101),i=ye(i,s,r,n,t[14],17,-1502002290),n=ye(n,i,s,r,t[15],22,1236535329),r=fe(r,n,i,s,t[1],5,-165796510),s=fe(s,r,n,i,t[6],9,-1069501632),i=fe(i,s,r,n,t[11],14,643717713),n=fe(n,i,s,r,t[0],20,-373897302),r=fe(r,n,i,s,t[5],5,-701558691),s=fe(s,r,n,i,t[10],9,38016083),i=fe(i,s,r,n,t[15],14,-660478335),n=fe(n,i,s,r,t[4],20,-405537848),r=fe(r,n,i,s,t[9],5,568446438),s=fe(s,r,n,i,t[14],9,-1019803690),i=fe(i,s,r,n,t[3],14,-187363961),n=fe(n,i,s,r,t[8],20,1163531501),r=fe(r,n,i,s,t[13],5,-1444681467),s=fe(s,r,n,i,t[2],9,-51403784),i=fe(i,s,r,n,t[7],14,1735328473),n=fe(n,i,s,r,t[12],20,-1926607734),r=ge(r,n,i,s,t[5],4,-378558),s=ge(s,r,n,i,t[8],11,-2022574463),i=ge(i,s,r,n,t[11],16,1839030562),n=ge(n,i,s,r,t[14],23,-35309556),r=ge(r,n,i,s,t[1],4,-1530992060),s=ge(s,r,n,i,t[4],11,1272893353),i=ge(i,s,r,n,t[7],16,-155497632),n=ge(n,i,s,r,t[10],23,-1094730640),r=ge(r,n,i,s,t[13],4,681279174),s=ge(s,r,n,i,t[0],11,-358537222),i=ge(i,s,r,n,t[3],16,-722521979),n=ge(n,i,s,r,t[6],23,76029189),r=ge(r,n,i,s,t[9],4,-640364487),s=ge(s,r,n,i,t[12],11,-421815835),i=ge(i,s,r,n,t[15],16,530742520),n=ge(n,i,s,r,t[2],23,-995338651),r=pe(r,n,i,s,t[0],6,-198630844),s=pe(s,r,n,i,t[7],10,1126891415),i=pe(i,s,r,n,t[14],15,-1416354905),n=pe(n,i,s,r,t[5],21,-57434055),r=pe(r,n,i,s,t[12],6,1700485571),s=pe(s,r,n,i,t[3],10,-1894986606),i=pe(i,s,r,n,t[10],15,-1051523),n=pe(n,i,s,r,t[1],21,-2054922799),r=pe(r,n,i,s,t[8],6,1873313359),s=pe(s,r,n,i,t[15],10,-30611744),i=pe(i,s,r,n,t[6],15,-1560198380),n=pe(n,i,s,r,t[13],21,1309151649),r=pe(r,n,i,s,t[4],6,-145523070),s=pe(s,r,n,i,t[11],10,-1120210379),i=pe(i,s,r,n,t[2],15,718787259),n=pe(n,i,s,r,t[9],21,-343485551),e[0]=me(r,e[0]),e[1]=me(n,e[1]),e[2]=me(i,e[2]),e[3]=me(s,e[3])}function le(e,t,r,n,i,s){return t=me(me(t,e),me(n,s)),me(t<>>32-i,r)}function ye(e,t,r,n,i,s,a){return le(t&r|~t&n,e,t,i,s,a)}function fe(e,t,r,n,i,s,a){return le(t&n|r&~n,e,t,i,s,a)}function ge(e,t,r,n,i,s,a){return le(t^r^n,e,t,i,s,a)}function pe(e,t,r,n,i,s,a){return le(r^(t|~n),e,t,i,s,a)}function de(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const Ae="0123456789abcdef".split("");function we(e){let t="",r=0;for(;r<4;r++)t+=Ae[e>>8*r+4&15]+Ae[e>>8*r&15];return t}function me(e,t){return e+t&4294967295}const be=z.getWebCrypto(),ke=z.getNodeCrypto(),Ee=ke&&ke.getHashes();function ve(e){if(ke&&Ee.includes(e))return async function(t){const r=ke.createHash(e);return S(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function Be(e,t){const r=async()=>{const{nobleHashes:t}=await Promise.resolve().then((function(){return xl})),r=t.get(e);if(!r)throw Error("Unsupported hash");return r};return async function(e){if(y(e)&&(e=await Q(e)),z.isStream(e)){const t=(await r()).create();return S(e,(e=>{t.update(e)}),(()=>t.digest()))}if(be&&t)return new Uint8Array(await be.digest(t,e));return(await r())(e)}}var Ie={md5:ve("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let n;for(n=64;n<=e.length;n+=64)ue(r,de(e.substring(n-64,n)));e=e.substring(n-64);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(ue(r,i),n=0;n<16;n++)i[n]=0;return i[14]=8*t,ue(r,i),r}(z.uint8ArrayToString(e));return z.hexToUint8Array(function(e){for(let t=0;t0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ce(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Pe(e,t){Ke(e);const r=t.outputLen;if(e.lengthnew Uint8Array(e.buffer,e.byteOffset,e.byteLength),Ue=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),xe=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw Error("Non little-endian hardware is not supported");function Qe(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Se(e))throw Error("Uint8Array expected, got "+typeof e);e=Ne(e)}return e}function Re(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t);function Te(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s);e.setUint32(t+0,a,n),e.setUint32(t+4,o,n)}function Me(e){return e.byteOffset%4==0}function Ne(e){return Uint8Array.from(e)}function Fe(...e){for(let t=0;t(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Ge{constructor(e,t){this.blockLen=Oe,this.outputLen=Oe,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Ke(e=Qe(e),16);const r=xe(e);let n=r.getUint32(0,!1),i=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:_e(n),s1:_e(i),s2:_e(s),s3:_e(a)}),({s0:n,s1:i,s2:s,s3:a}={s3:(u=s)<<31|(l=a)>>>1,s2:(h=i)<<31|u>>>1,s1:(c=n)<<31|h>>>1,s0:c>>>1^225<<24&-(1&l)});var c,h,u,l;const y=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(y))throw Error(`ghash: wrong window size=${y}, should be 2, 4 or 8`);this.W=y;const f=128/y,g=this.windowSize=2**y,p=[];for(let e=0;e>>y-a-1&1))continue;const{s0:c,s1:h,s2:u,s3:l}=o[y*e+a];r^=c,n^=h,i^=u,s^=l}p.push({s0:r,s1:n,s2:i,s3:s})}this.t=p}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:i,t:s,windowSize:a}=this;let o=0,c=0,h=0,u=0;const l=(1<>>8*e&255;for(let e=8/i-1;e>=0;e--){const r=t>>>i*e&l,{s0:n,s1:f,s2:g,s3:p}=s[y*a+r];o^=n,c^=f,h^=g,u^=p,y+=1}}this.s0=o,this.s1=c,this.s2=h,this.s3=u}update(e){e=Qe(e),Ce(this);const t=Ue(e),r=Math.floor(e.length/Oe),n=e.length%Oe;for(let e=0;e>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Ne(e=Qe(e)));super(r,t),Fe(r)}update(e){e=Qe(e),Ce(this);const t=Ue(e),r=e.length%Oe,n=Math.floor(e.length/Oe);for(let e=0;ee(r,t.length).update(Qe(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const Ve=qe(((e,t)=>new Ge(e,t)));qe(((e,t)=>new je(e,t)));const Je=16,Ye=new Uint8Array(Je),We=283;function Ze(e){return e<<1^We&-(e>>7)}function $e(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Ze(e);return r}const Xe=/* @__PURE__ */(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Ze(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Fe(e),t})(),et=/* @__PURE__ */Xe.map(((e,t)=>Xe.indexOf(t))),tt=e=>e<<24|e>>>8,rt=e=>e<<8|e>>>24,nt=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function it(e,t){if(256!==e.length)throw Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,n)=>t(e[n]))),n=r.map(rt),i=n.map(rt),s=i.map(rt),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let h=0;h<256;h++){const u=256*t+h;a[u]=r[t]^n[h],o[u]=i[t]^s[h],c[u]=e[t]<<8|e[h]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:i,T3:s,T01:a,T23:o}}const st=/* @__PURE__ */it(Xe,(e=>$e(e,3)<<24|e<<16|e<<8|$e(e,2))),at=/* @__PURE__ */it(et,(e=>$e(e,11)<<24|$e(e,13)<<16|$e(e,9)<<8|$e(e,14))),ot=/* @__PURE__ */(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Ze(r))e[t]=r;return e})();function ct(e){Ke(e);const t=e.length;if(![16,24,32].includes(t))throw Error("aes: wrong key size: should be 16, 24 or 32, got: "+t);const{sbox2:r}=st,n=[];Me(e)||n.push(e=Ne(e));const i=Ue(e),s=i.length,a=e=>lt(r,e,e,e,e),o=new Uint32Array(t+28);o.set(i);for(let e=s;e6&&e%s==4&&(t=a(t)),o[e]=o[e-s]^t}return Fe(...n),o}function ht(e){const t=ct(e),r=t.slice(),n=t.length,{sbox2:i}=st,{T0:s,T1:a,T2:o,T3:c}=at;for(let e=0;e>>8&255]^o[n>>>16&255]^c[n>>>24]}return r}function ut(e,t,r,n,i,s){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|s>>>24&255]}function lt(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function yt(e,t,r,n,i){const{sbox2:s,T01:a,T23:o}=st;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],i^=e[c++];const h=e.length/4-2;for(let s=0;s=0;e--)r=r+(255&s[e])|0,s[e]=255&r,r>>>=8;({s0:o,s1:c,s2:h,s3:u}=yt(e,a[0],a[1],a[2],a[3]))}const f=Je*Math.floor(l.length/4);if(f>>0,o.setUint32(u,y,t),({s0:f,s1:g,s2:p,s3:d}=yt(e,a[0],a[1],a[2],a[3]));const A=Je*Math.floor(c.length/4);if(Ar(e,t),decrypt:(e,t)=>r(e,t)}}));const wt=Le({blockSize:16,nonceLength:16},(function(e,t,r={}){Ke(e),Ke(t,16);const n=!r.disablePadding;return{encrypt(r,i){const s=ct(e),{b:a,o,out:c}=function(e,t,r){Ke(e);let n=e.length;const i=n%Je;if(!t&&0!==i)throw Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Me(e)||(e=Ne(e));const s=Ue(e);if(t){let e=Je-i;e||(e=Je),n+=e}const a=gt(n,r);return{b:s,o:Ue(a),out:a}}(r,n,i);let h=t;const u=[s];Me(h)||u.push(h=Ne(h));const l=Ue(h);let y=l[0],f=l[1],g=l[2],p=l[3],d=0;for(;d+4<=a.length;)y^=a[d+0],f^=a[d+1],g^=a[d+2],p^=a[d+3],({s0:y,s1:f,s2:g,s3:p}=yt(s,y,f,g,p)),o[d++]=y,o[d++]=f,o[d++]=g,o[d++]=p;if(n){const e=function(e){const t=new Uint8Array(16),r=Ue(t);t.set(e);const n=Je-e.length;for(let e=Je-n;e16)throw Error("aes/pcks5: wrong padding");const i=e.subarray(0,-n);for(let t=0;tr(e,!0,t),decrypt:(e,t)=>r(e,!1,t)}}));const bt=Le({blockSize:16,nonceLength:12,tagLength:16},(function(e,t,r){if(Ke(e),Ke(t),void 0!==r&&Ke(r),t.length<8)throw Error("aes/gcm: invalid nonce length");const n=16;function i(e,t,n){const i=function(e,t,r,n,i){const s=null==i?0:i.length,a=e.create(r,n.length+s);i&&a.update(i),a.update(n);const o=new Uint8Array(16),c=xe(o);i&&Te(c,0,BigInt(8*s),t),Te(c,8,BigInt(8*n.length),t),a.update(o);const h=a.digest();return Fe(o),h}(Ve,!1,e,n,r);for(let e=0;e=2**32)throw Error("plaintext should be less than 4gb");const r=ct(e);if(16===t.length)Et(r,t);else{const e=Ue(t);let n=e[0],i=e[1];for(let t=0,s=1;t<6;t++)for(let t=2;t=2**32)throw Error("ciphertext should be less than 4gb");const r=ht(e),n=t.length/8-1;if(1===n)vt(r,t);else{const e=Ue(t);let i=e[0],s=e[1];for(let t=0,a=6*n;t<6;t++)for(let t=2*n;t>=1;t-=2,a--){s^=nt(a);const{s0:n,s1:o,s2:c,s3:h}=ft(r,i,s,e[t],e[t+1]);i=n,s=o,e[t]=c,e[t+1]=h}e[0]=i,e[1]=s}r.fill(0)}},It=new Uint8Array(8).fill(166),St=Le({blockSize:8},(e=>({encrypt(t){if(Ke(t),!t.length||t.length%8!=0)throw Error("invalid plaintext length");if(8===t.length)throw Error("8-byte keys not allowed in AESKW, use AESKWP instead");const r=function(...e){let t=0;for(let r=0;r!0),(()=>!1))}async _runCBC(e,t){const r="AES-CBC";this.keyRef=this.keyRef||await Ct.importKey("raw",this.key,r,!1,["encrypt"]);const n=await Ct.encrypt({name:r,iv:t||this.zeroBlock},this.keyRef,e);return new Uint8Array(n).subarray(0,e.length)}async encryptChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=z.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=z.concatUint8Array([this.prevBlock,n.subarray(0,n.length-this.blockSize)]),s=await this._runCBC(i);return Rt(s,n),this.prevBlock=s.slice(-this.blockSize),r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,s}let n;if(this.i+=r.length,this.i===this.nextBlock.length){const t=this.nextBlock;n=await this._runCBC(this.prevBlock),Rt(n,t),this.prevBlock=n.slice(),this.i=0;const i=e.subarray(r.length);this.nextBlock.set(i,this.i),this.i+=i.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{this.nextBlock=this.nextBlock.subarray(0,this.i);const t=this.nextBlock,r=await this._runCBC(this.prevBlock);Rt(r,t),e=r.subarray(0,t.length)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.keyRef=null,this.key=null}async encrypt(e){const t=(await this._runCBC(z.concatUint8Array([new Uint8Array(this.blockSize),e]),this.iv)).subarray(0,e.length);return Rt(t,e),this.clearSensitiveData(),t}}class Qt{constructor(e,t,r,n){this.forEncryption=e;const{blockSize:i}=ce(t);this.key=Kt.expandKeyLE(r),n.byteOffset%4!=0&&(n=n.slice()),this.prevBlock=Lt(n),this.nextBlock=new Uint8Array(i),this.i=0,this.blockSize=i}_runCFB(e){const t=Lt(e),r=new Uint8Array(e.length),n=Lt(r);for(let e=0;e+4<=n.length;e+=4){const{s0:r,s1:i,s2:s,s3:a}=Kt.encrypt(this.key,this.prevBlock[0],this.prevBlock[1],this.prevBlock[2],this.prevBlock[3]);n[e+0]=t[e+0]^r,n[e+1]=t[e+1]^i,n[e+2]=t[e+2]^s,n[e+3]=t[e+3]^a,this.prevBlock=(this.forEncryption?n:t).slice(e,e+4)}return r}async processChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=z.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=this._runCFB(n);return r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,i}let n;if(this.i+=r.length,this.i===this.nextBlock.length){n=this._runCFB(this.nextBlock),this.i=0;const t=e.subarray(r.length);this.nextBlock.set(t,this.i),this.i+=t.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{e=this._runCFB(this.nextBlock).subarray(0,this.i)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.key.fill(0)}}function Rt(e,t){const r=Math.min(e.length,t.length);for(let n=0;nnew Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));var Tt=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n){const i=F.read(F.symmetric,e);if(Pt&&Ut[i])return function(e,t,r,n){const i=F.read(F.symmetric,e),s=new Pt.createDecipheriv(Ut[i],t,n);return S(r,(e=>new Uint8Array(s.update(e))))}(e,t,r,n);if(z.isAES(e))return async function(e,t,r,n){if(z.isStream(r)){const i=new Qt(!1,e,t,n);return S(r,(e=>i.processChunk(e)),(()=>i.finish()))}return mt(t,n).decrypt(r)}(e,t,r,n);const s=new(await se(e))(t),a=s.blockSize;let o=n,c=new Uint8Array;const h=e=>{e&&(c=z.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,n=0;for(;e?c.length>=a:c.length;){const e=s.encrypt(o);for(o=c.subarray(0,a),r=0;rnew Uint8Array(s.update(e))))}(e,t,r,n);if(z.isAES(e))return async function(e,t,r,n){if(Ct&&await xt.isSupported(e)){const i=new xt(e,t,n);return z.isStream(r)?S(r,(e=>i.encryptChunk(e)),(()=>i.finish())):i.encrypt(r)}if(z.isStream(r)){const i=new Qt(!0,e,t,n);return S(r,(e=>i.processChunk(e)),(()=>i.finish()))}return mt(t,n).encrypt(r)}(e,t,r,n);const a=new(await se(e))(t),o=a.blockSize,c=n.slice();let h=new Uint8Array;const u=e=>{e&&(h=z.concatUint8Array([h,e]));const t=new Uint8Array(h.length);let r,n=0;for(;e?h.length>=o:h.length;){const e=a.encrypt(c);for(r=0;ri.encrypt(e),a=e=>i.decrypt(e);let o;function c(e,t,r,i){const a=t.length/rr|0;!function(e,t){const r=z.nbits(Math.max(e.length,t.length)/rr|0)-1;for(let e=n+1;e<=r;e++)o[e]=z.double(o[e-1]);n=r}(t,i);const c=z.concatUint8Array([or.subarray(0,15-r.length),cr,r]),h=63&c[15];c[15]&=192;const u=s(c),l=z.concatUint8Array([u,ar(u.subarray(0,8),u.subarray(1,9))]),y=z.shiftRight(l.subarray(0+(h>>3),17+(h>>3)),8-(7&h)).subarray(1),f=new Uint8Array(rr),g=new Uint8Array(t.length+nr);let p,d=0;for(p=0;p{r+=t[e>>4]+t[15&e]})),BigInt("0x0"+r)}function br(e,t){const r=e%t;return rAr;){const e=n≀n>>=wr;s=e?s*i%r:s,i=i*i%r}return s}function Er(e){return e>=Ar?e:-e}function vr(e,t){const{gcd:r,x:n}=function(e,t){let r=BigInt(0),n=BigInt(1),i=BigInt(1),s=BigInt(0),a=Er(e),o=Er(t);const c=eNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return t}function Ir(e,t){return(e>>BigInt(t)&wr)===Ar?0:1}function Sr(e){const t=e>=wr)!==t;)r++;return r}function Kr(e){const t=e>=r)!==t;)n++;return n}function Cr(e,t="be",r){let n=e.toString(16);n.length%2==1&&(n="0"+n);const i=n.length/2,s=new Uint8Array(r||i),a=r?r-i:0;let o=0;for(;oe&&(a=br(a,i<br(e,r)!==t))}(e)&&(!!function(e,t=BigInt(2)){return kr(t,e-Qr,e)===Qr}(e)&&!!function(e,t){const r=Sr(e);t||(t=Math.max(1,r/48|0));const n=e-Qr;let i=0;for(;!Ir(n,i);)i++;const s=e>>BigInt(i);for(;t>0;t--){let t,r=kr(Ur(BigInt(2),n),s,e);if(r!==Qr&&r!==n){for(t=1;tBigInt(e)));const Mr=[];function Nr(e,t){const r=e.length;if(r>t-11)throw Error("Message too long");const n=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!n;if(t)return z.selectUint8Array(a,s,t);if(a)return s;throw Error("Decryption error")}function Or(e,t,r){let n;if(t.length!==Ie.getHashByteLength(e))throw Error("Invalid hash length");const i=new Uint8Array(Mr[e].length);for(n=0;n=t)throw Error("Data too large.");const c=br(n,s-Gr),h=br(n,i-Gr),u=Ur(BigInt(2),t),l=kr(vr(u,t),r,t);e=br(e*l,t);const y=kr(e,h,i),f=kr(e,c,s),g=br(a*(f-y),s);let p=g*i+y;return p=br(p*u,t),Fr(Cr(p,"be",Kr(t)),o)}(e,t,r,n,i,s,a,o)},encrypt:async function(e,t,r){return z.getNodeCrypto()?async function(e,t,r){const n=qr(t,r),i={key:n,format:"jwk",type:"pkcs1",padding:_r.constants.RSA_PKCS1_PADDING};return new Uint8Array(_r.publicEncrypt(i,e))}(e,t,r):async function(e,t,r){if(t=mr(t),e=mr(Nr(e,Kr(t))),r=mr(r),e>=t)throw Error("Message size cannot exceed modulus size");return Cr(kr(e,r,t),"be",Kr(t))}(e,t,r)},generate:async function(e,t){if(t=BigInt(t),z.getWebCrypto()){const r={name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Cr(t),hash:{name:"SHA-1"}},n=await zr.generateKey(r,!0,["sign","verify"]);return Vr(await zr.exportKey("jwk",n.privateKey),t)}if(z.getNodeCrypto()){const r={modulusLength:e,publicExponent:Br(t),publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}},n=await new Promise(((e,t)=>{_r.generateKeyPair("rsa",r,((r,n,i)=>{r?t(r):e(i)}))}));return Vr(n,t)}let r,n,i;do{n=Rr(e-(e>>1),t,40),r=Rr(e>>1,t,40),i=r*n}while(Sr(i)!==e);const s=(r-Gr)*(n-Gr);return n=r.length)throw Error("Digest size cannot exceed key modulus size");if(t&&!z.isStream(t))if(z.getWebCrypto())try{return await async function(e,t,r,n,i,s,a,o){const c=await jr(r,n,i,s,a,o),h={name:"RSASSA-PKCS1-v1_5",hash:{name:e}},u=await zr.importKey("jwk",c,h,!1,["sign"]);return new Uint8Array(await zr.sign("RSASSA-PKCS1-v1_5",u,t))}(F.read(F.webHash,e),t,r,n,i,s,a,o)}catch(e){z.printDebugError(e)}else if(z.getNodeCrypto())return async function(e,t,r,n,i,s,a,o){const c=_r.createSign(F.read(F.hash,e));c.write(t),c.end();const h=await jr(r,n,i,s,a,o);return new Uint8Array(c.sign({key:h,format:"jwk",type:"pkcs1"}))}(e,t,r,n,i,s,a,o);return async function(e,t,r,n){t=mr(t);const i=mr(Or(e,n,Kr(t)));return r=mr(r),Cr(kr(i,r,t),"be",Kr(t))}(e,r,i,c)},validateParams:async function(e,t,r,n,i,s){if(e=mr(e),(n=mr(n))*(i=mr(i))!==e)return!1;const a=BigInt(2);if(br(n*(s=mr(s)),i)!==BigInt(1))return!1;t=mr(t),r=mr(r);const o=Ur(a,a<=r)throw Error("Signature size cannot exceed modulus size");const s=Cr(kr(t,n,r),"be",Kr(r)),a=Or(e,i,Kr(r));return z.equalsUint8Array(s,a)}(e,r,n,i,s)}});const Yr=BigInt(1);var Wr=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i){return e=mr(e),t=mr(t),r=mr(r),Fr(Cr(br(vr(kr(e,n=mr(n),r),r)*t,r),"be",Kr(r)),i)},encrypt:async function(e,t,r,n){t=mr(t),r=mr(r),n=mr(n);const i=mr(Nr(e,Kr(t))),s=Ur(Yr,t-Yr);return{c1:Cr(kr(r,s,t)),c2:Cr(br(kr(n,s,t)*i,t))}},validateParams:async function(e,t,r,n){if(e=mr(e),t=mr(t),r=mr(r),t<=Yr||t>=e)return!1;const i=BigInt(Sr(e));if(i>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function yn(e,t,r,n){return function(e,t,r,n,i){var s,a=0;for(s=0;s>>8)-1}(e,t,r,n,32)}function fn(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function gn(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function pn(e,t,r){for(var n,i=~(r-1),s=0;s<16;s++)n=i&(e[s]^t[s]),e[s]^=n,t[s]^=n}function dn(e,t){var r,n,i,s=Xr(),a=Xr();for(r=0;r<16;r++)a[r]=t[r];for(gn(a),gn(a),gn(a),n=0;n<2;n++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,pn(a,s,1-i)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function An(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return dn(r,e),dn(n,t),yn(r,0,n,0)}function wn(e){var t=new Uint8Array(32);return dn(t,e),1&t[0]}function mn(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function bn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function kn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function En(e,t,r){var n,i,s=0,a=0,o=0,c=0,h=0,u=0,l=0,y=0,f=0,g=0,p=0,d=0,A=0,w=0,m=0,b=0,k=0,E=0,v=0,B=0,I=0,S=0,K=0,C=0,P=0,D=0,U=0,x=0,Q=0,R=0,L=0,T=r[0],M=r[1],N=r[2],F=r[3],O=r[4],H=r[5],z=r[6],_=r[7],G=r[8],j=r[9],q=r[10],V=r[11],J=r[12],Y=r[13],W=r[14],Z=r[15];s+=(n=t[0])*T,a+=n*M,o+=n*N,c+=n*F,h+=n*O,u+=n*H,l+=n*z,y+=n*_,f+=n*G,g+=n*j,p+=n*q,d+=n*V,A+=n*J,w+=n*Y,m+=n*W,b+=n*Z,a+=(n=t[1])*T,o+=n*M,c+=n*N,h+=n*F,u+=n*O,l+=n*H,y+=n*z,f+=n*_,g+=n*G,p+=n*j,d+=n*q,A+=n*V,w+=n*J,m+=n*Y,b+=n*W,k+=n*Z,o+=(n=t[2])*T,c+=n*M,h+=n*N,u+=n*F,l+=n*O,y+=n*H,f+=n*z,g+=n*_,p+=n*G,d+=n*j,A+=n*q,w+=n*V,m+=n*J,b+=n*Y,k+=n*W,E+=n*Z,c+=(n=t[3])*T,h+=n*M,u+=n*N,l+=n*F,y+=n*O,f+=n*H,g+=n*z,p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A+=(n=t[12])*T,w+=n*M,m+=n*N,b+=n*F,k+=n*O,E+=n*H,v+=n*z,B+=n*_,I+=n*G,S+=n*j,K+=n*q,C+=n*V,P+=n*J,D+=n*Y,U+=n*W,x+=n*Z,w+=(n=t[13])*T,m+=n*M,b+=n*N,k+=n*F,E+=n*O,v+=n*H,B+=n*z,I+=n*_,S+=n*G,K+=n*j,C+=n*q,P+=n*V,D+=n*J,U+=n*Y,x+=n*W,Q+=n*Z,m+=(n=t[14])*T,b+=n*M,k+=n*N,E+=n*F,v+=n*O,B+=n*H,I+=n*z,S+=n*_,K+=n*G,C+=n*j,P+=n*q,D+=n*V,U+=n*J,x+=n*Y,Q+=n*W,R+=n*Z,b+=(n=t[15])*T,a+=38*(E+=n*N),o+=38*(v+=n*F),c+=38*(B+=n*O),h+=38*(I+=n*H),u+=38*(S+=n*z),l+=38*(K+=n*_),y+=38*(C+=n*G),f+=38*(P+=n*j),g+=38*(D+=n*q),p+=38*(U+=n*V),d+=38*(x+=n*J),A+=38*(Q+=n*Y),w+=38*(R+=n*W),m+=38*(L+=n*Z),s=(n=(s+=38*(k+=n*M))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=(s+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=c,e[4]=h,e[5]=u,e[6]=l,e[7]=y,e[8]=f,e[9]=g,e[10]=p,e[11]=d,e[12]=A,e[13]=w,e[14]=m,e[15]=b}function vn(e,t){En(e,t,t)}function Bn(e,t){var r,n=Xr();for(r=0;r<16;r++)n[r]=t[r];for(r=253;r>=0;r--)vn(n,n),2!==r&&4!==r&&En(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}function In(e,t,r){var n,i,s=new Uint8Array(32),a=new Float64Array(80),o=Xr(),c=Xr(),h=Xr(),u=Xr(),l=Xr(),y=Xr();for(i=0;i<31;i++)s[i]=t[i];for(s[31]=127&t[31]|64,s[0]&=248,mn(a,r),i=0;i<16;i++)c[i]=a[i],u[i]=o[i]=h[i]=0;for(o[0]=u[0]=1,i=254;i>=0;--i)pn(o,c,n=s[i>>>3]>>>(7&i)&1),pn(h,u,n),bn(l,o,h),kn(o,o,h),bn(h,c,u),kn(c,c,u),vn(u,l),vn(y,o),En(o,h,o),En(h,c,l),bn(l,o,h),kn(o,o,h),vn(c,o),kn(h,u,y),En(o,h,sn),bn(o,o,u),En(h,h,o),En(o,u,y),En(u,c,a),vn(c,l),pn(o,c,n),pn(h,u,n);for(i=0;i<16;i++)a[i+16]=o[i],a[i+32]=h[i],a[i+48]=c[i],a[i+64]=u[i];var f=a.subarray(32),g=a.subarray(16);return Bn(f,f),En(g,g,f),dn(e,g),0}function Sn(e,t){return In(e,t,tn)}var Kn=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Cn(e,t,r,n){for(var i,s,a,o,c,h,u,l,y,f,g,p,d,A,w,m,b,k,E,v,B,I,S,K,C,P,D=new Int32Array(16),U=new Int32Array(16),x=e[0],Q=e[1],R=e[2],L=e[3],T=e[4],M=e[5],N=e[6],F=e[7],O=t[0],H=t[1],z=t[2],_=t[3],G=t[4],j=t[5],q=t[6],V=t[7],J=0;n>=128;){for(E=0;E<16;E++)v=8*E+J,D[E]=r[v+0]<<24|r[v+1]<<16|r[v+2]<<8|r[v+3],U[E]=r[v+4]<<24|r[v+5]<<16|r[v+6]<<8|r[v+7];for(E=0;E<80;E++)if(i=x,s=Q,a=R,o=L,c=T,h=M,u=N,F,y=O,f=H,g=z,p=_,d=G,A=j,w=q,V,S=65535&(I=V),K=I>>>16,C=65535&(B=F),P=B>>>16,S+=65535&(I=(G>>>14|T<<18)^(G>>>18|T<<14)^(T>>>9|G<<23)),K+=I>>>16,C+=65535&(B=(T>>>14|G<<18)^(T>>>18|G<<14)^(G>>>9|T<<23)),P+=B>>>16,S+=65535&(I=G&j^~G&q),K+=I>>>16,C+=65535&(B=T&M^~T&N),P+=B>>>16,B=Kn[2*E],S+=65535&(I=Kn[2*E+1]),K+=I>>>16,C+=65535&B,P+=B>>>16,B=D[E%16],K+=(I=U[E%16])>>>16,C+=65535&B,P+=B>>>16,C+=(K+=(S+=65535&I)>>>16)>>>16,S=65535&(I=k=65535&S|K<<16),K=I>>>16,C=65535&(B=b=65535&C|(P+=C>>>16)<<16),P=B>>>16,S+=65535&(I=(O>>>28|x<<4)^(x>>>2|O<<30)^(x>>>7|O<<25)),K+=I>>>16,C+=65535&(B=(x>>>28|O<<4)^(O>>>2|x<<30)^(O>>>7|x<<25)),P+=B>>>16,K+=(I=O&H^O&z^H&z)>>>16,C+=65535&(B=x&Q^x&R^Q&R),P+=B>>>16,l=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(P+=C>>>16)<<16,m=65535&S|K<<16,S=65535&(I=p),K=I>>>16,C=65535&(B=o),P=B>>>16,K+=(I=k)>>>16,C+=65535&(B=b),P+=B>>>16,Q=i,R=s,L=a,T=o=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(P+=C>>>16)<<16,M=c,N=h,F=u,x=l,H=y,z=f,_=g,G=p=65535&S|K<<16,j=d,q=A,V=w,O=m,E%16==15)for(v=0;v<16;v++)B=D[v],S=65535&(I=U[v]),K=I>>>16,C=65535&B,P=B>>>16,B=D[(v+9)%16],S+=65535&(I=U[(v+9)%16]),K+=I>>>16,C+=65535&B,P+=B>>>16,b=D[(v+1)%16],S+=65535&(I=((k=U[(v+1)%16])>>>1|b<<31)^(k>>>8|b<<24)^(k>>>7|b<<25)),K+=I>>>16,C+=65535&(B=(b>>>1|k<<31)^(b>>>8|k<<24)^b>>>7),P+=B>>>16,b=D[(v+14)%16],K+=(I=((k=U[(v+14)%16])>>>19|b<<13)^(b>>>29|k<<3)^(k>>>6|b<<26))>>>16,C+=65535&(B=(b>>>19|k<<13)^(k>>>29|b<<3)^b>>>6),P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,D[v]=65535&C|P<<16,U[v]=65535&S|K<<16;S=65535&(I=O),K=I>>>16,C=65535&(B=x),P=B>>>16,B=e[0],K+=(I=t[0])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[0]=x=65535&C|P<<16,t[0]=O=65535&S|K<<16,S=65535&(I=H),K=I>>>16,C=65535&(B=Q),P=B>>>16,B=e[1],K+=(I=t[1])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[1]=Q=65535&C|P<<16,t[1]=H=65535&S|K<<16,S=65535&(I=z),K=I>>>16,C=65535&(B=R),P=B>>>16,B=e[2],K+=(I=t[2])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[2]=R=65535&C|P<<16,t[2]=z=65535&S|K<<16,S=65535&(I=_),K=I>>>16,C=65535&(B=L),P=B>>>16,B=e[3],K+=(I=t[3])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[3]=L=65535&C|P<<16,t[3]=_=65535&S|K<<16,S=65535&(I=G),K=I>>>16,C=65535&(B=T),P=B>>>16,B=e[4],K+=(I=t[4])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[4]=T=65535&C|P<<16,t[4]=G=65535&S|K<<16,S=65535&(I=j),K=I>>>16,C=65535&(B=M),P=B>>>16,B=e[5],K+=(I=t[5])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[5]=M=65535&C|P<<16,t[5]=j=65535&S|K<<16,S=65535&(I=q),K=I>>>16,C=65535&(B=N),P=B>>>16,B=e[6],K+=(I=t[6])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[6]=N=65535&C|P<<16,t[6]=q=65535&S|K<<16,S=65535&(I=V),K=I>>>16,C=65535&(B=F),P=B>>>16,B=e[7],K+=(I=t[7])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[7]=F=65535&C|P<<16,t[7]=V=65535&S|K<<16,J+=128,n-=128}return n}function Pn(e,t,r){var n,i=new Int32Array(8),s=new Int32Array(8),a=new Uint8Array(256),o=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,Cn(i,s,t,r),r%=128,n=0;n=0;--i)Un(e,t,n=r[i/8|0]>>(7&i)&1),Dn(t,e),Dn(e,e),Un(e,t,n)}function Rn(e,t){var r=[Xr(),Xr(),Xr(),Xr()];fn(r[0],cn),fn(r[1],hn),fn(r[2],nn),En(r[3],cn,hn),Qn(e,r,t)}function Ln(e,t,r){var n,i=new Uint8Array(64),s=[Xr(),Xr(),Xr(),Xr()];for(r||en(t,32),Pn(i,t,32),i[0]&=248,i[31]&=127,i[31]|=64,Rn(s,i),xn(e,s),n=0;n<32;n++)t[n+32]=e[n];return 0}var Tn=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Mn(e,t){var r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*Tn[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*Tn[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function Nn(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;Mn(e,r)}function Fn(e,t){var r=Xr(),n=Xr(),i=Xr(),s=Xr(),a=Xr(),o=Xr(),c=Xr();return fn(e[2],nn),mn(e[1],t),vn(i,e[1]),En(s,i,an),kn(i,i,e[2]),bn(s,e[2],s),vn(a,s),vn(o,a),En(c,o,a),En(r,c,i),En(r,r,s),function(e,t){var r,n=Xr();for(r=0;r<16;r++)n[r]=t[r];for(r=250;r>=0;r--)vn(n,n),1!==r&&En(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}(r,r),En(r,r,i),En(r,r,s),En(r,r,s),En(e[0],r,s),vn(n,e[0]),En(n,n,s),An(n,i)&&En(e[0],e[0],un),vn(n,e[0]),En(n,n,s),An(n,i)?-1:(wn(e[0])===t[31]>>7&&kn(e[0],rn,e[0]),En(e[3],e[0],e[1]),0)}var On=64;function Hn(){for(var e=0;e=0},$r.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return Ln(e,t),{publicKey:e,secretKey:t}},$r.sign.keyPair.fromSecretKey=function(e){if(Hn(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;r=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return z.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return z.uint8ArrayToHex(this.oid)}getName(){const e=zn[this.toHex()];if(!e)throw Error("Unknown curve object identifier.");return e}}function Gn(e){let t,r=0;const n=e[0];return n<192?([r]=e,t=1):n<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===n&&(r=z.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function jn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):z.concatUint8Array([new Uint8Array([255]),z.writeNumber(e,4)])}function qn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function Vn(e){return new Uint8Array([192|e])}function Jn(e,t){return z.concatUint8Array([Vn(e),jn(t)])}function Yn(e){return[F.packet.literalData,F.packet.compressedData,F.packet.symmetricallyEncryptedData,F.packet.symEncryptedIntegrityProtectedData,F.packet.aeadEncryptedData].includes(e)}async function Wn(e,t){const r=T(e);let n,i;try{const s=await r.peekBytes(2);if(!s||s.length<2||!(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const a=await r.readByte();let o,c,h=-1,u=-1;u=0,64&a&&(u=1),u?h=63&a:(h=(63&a)>>2,c=3&a);const y=Yn(h);let f,g=null;if(y){if("array"===z.isStream(e)){const e=new l;n=M(e),g=e}else{const e=new TransformStream;n=M(e.writable),g=e.readable}i=t({tag:h,packet:g})}else g=[];do{if(u){const e=await r.readByte();if(f=!1,e<192)o=e;else if(e>=192&&e<224)o=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(o=1<<(31&e),f=!0,!y)throw new TypeError("This packet type does not support partial lengths.")}else o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(c){case 0:o=await r.readByte();break;case 1:o=await r.readByte()<<8|await r.readByte();break;case 2:o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:o=1/0}if(o>0){let e=0;for(;;){n&&await n.ready;const{done:t,value:i}=await r.read();if(t){if(o===1/0)break;throw Error("Unexpected end of packet")}const s=o===1/0?i:i.subarray(0,o-e);if(n?await n.write(s):g.push(s),e+=i.length,e>=o){r.unshift(i.subarray(o-e+i.length));break}}}}while(f);const p=await r.peekBytes(y?1/0:2);return n?(await n.ready,await n.close()):(g=z.concatUint8Array(g),await t({tag:h,packet:g})),!p||!p.length}catch(e){if(n)return await n.abort(e),!0;throw e}finally{n&&await i,r.releaseLock()}}class Zn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Zn),this.name="UnsupportedError"}}class $n extends Zn{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Zn),this.name="UnknownPacketError"}}class Xn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}async function ei(e){switch(e){case F.publicKey.ed25519:try{const e=z.getWebCrypto(),t=await e.generateKey("Ed25519",!0,["sign","verify"]),r=await e.exportKey("jwk",t.privateKey),n=await e.exportKey("jwk",t.publicKey);return{A:new Uint8Array(J(n.x)),seed:J(r.d)}}catch(t){if("NotSupportedError"!==t.name&&"OperationError"!==t.name)throw t;const r=Dr(ni(e)),{publicKey:n}=$r.sign.keyPair.fromSeed(r);return{A:n,seed:r}}case F.publicKey.ed448:{const e=await z.getNobleCurve(F.publicKey.ed448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),seed:t}}default:throw Error("Unsupported EdDSA algorithm")}}async function ti(e,t,r,n,i,s){if(Ie.getHashByteLength(t){if(e===F.publicKey.ed25519){return{kty:"OKP",crv:"Ed25519",x:Y(t),ext:!0}}throw Error("Unsupported EdDSA algorithm")},ai=(e,t,r)=>{if(e===F.publicKey.ed25519){const n=si(e,t);return n.d=Y(r),n}throw Error("Unsupported EdDSA algorithm")};var oi=/*#__PURE__*/Object.freeze({__proto__:null,generate:ei,getPayloadSize:ni,getPreferredHashAlgo:ii,sign:ti,validateParams:async function(e,t,r){switch(e){case F.publicKey.ed25519:{const{publicKey:e}=$r.sign.keyPair.fromSeed(r);return z.equalsUint8Array(t,e)}case F.publicKey.ed448:{const e=(await z.getNobleCurve(F.publicKey.ed448)).getPublicKey(r);return z.equalsUint8Array(t,e)}default:return!1}},verify:ri});const ci=z.getWebCrypto();async function hi(e,t,r){const{keySize:n}=ce(e);if(!z.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");try{const e=await ci.importKey("raw",t,{name:"AES-KW"},!1,["wrapKey"]),n=await ci.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!0,["sign"]),i=await ci.wrapKey("raw",n,e,{name:"AES-KW"});return new Uint8Array(i)}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;z.printDebugError("Browser did not support operation: "+e.message)}return St(t).encrypt(r)}async function ui(e,t,r){const{keySize:n}=ce(e);if(!z.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");let i;try{i=await ci.importKey("raw",t,{name:"AES-KW"},!1,["unwrapKey"])}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;return z.printDebugError("Browser did not support operation: "+e.message),St(t).decrypt(r)}try{const e=await ci.unwrapKey("raw",r,i,{name:"AES-KW"},{name:"HMAC",hash:"SHA-256"},!0,["sign"]);return new Uint8Array(await ci.exportKey("raw",e))}catch(e){if("OperationError"===e.name)throw Error("Key Data Integrity failed");throw e}}var li=/*#__PURE__*/Object.freeze({__proto__:null,unwrap:ui,wrap:hi});const yi=z.getWebCrypto();async function fi(e,t,r,n,i){const s=F.read(F.webHash,e);if(!s)throw Error("Hash algo not supported with HKDF");const a=await yi.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await yi.deriveBits({name:"HKDF",hash:s,salt:r,info:n},a,8*i);return new Uint8Array(o)}const gi={x25519:z.encodeUTF8("OpenPGP X25519"),x448:z.encodeUTF8("OpenPGP X448")};async function pi(e){switch(e){case F.publicKey.x25519:{const e=Dr(32),{publicKey:t}=$r.box.keyPair.fromSecretKey(e);return{A:t,k:e}}case F.publicKey.x448:{const e=await z.getNobleCurve(F.publicKey.x448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),k:t}}default:throw Error("Unsupported ECDH algorithm")}}function di(e){switch(e){case F.publicKey.x25519:return 32;case F.publicKey.x448:return 56;default:throw Error("Unsupported ECDH algorithm")}}async function Ai(e,t){switch(e){case F.publicKey.x25519:{const r=Dr(di(e)),n=$r.scalarMult(r,t);mi(n);const{publicKey:i}=$r.box.keyPair.fromSecretKey(r);return{ephemeralPublicKey:i,sharedSecret:n}}case F.publicKey.x448:{const e=await z.getNobleCurve(F.publicKey.x448),r=e.utils.randomPrivateKey(),n=e.getSharedSecret(r,t);mi(n);return{ephemeralPublicKey:e.getPublicKey(r),sharedSecret:n}}default:throw Error("Unsupported ECDH algorithm")}}async function wi(e,t,r,n){switch(e){case F.publicKey.x25519:{const e=$r.scalarMult(n,t);return mi(e),e}case F.publicKey.x448:{const e=(await z.getNobleCurve(F.publicKey.x448)).getSharedSecret(n,t);return mi(e),e}default:throw Error("Unsupported ECDH algorithm")}}function mi(e){let t=0;for(let r=0;r0===s[0]&&Ni(a,r,s.subarray(1),i);if(n&&!z.isStream(n))switch(a.type){case"web":try{const e=await async function(e,t,{r,s:n},i,s){const a=xi(e.payloadSize,vi[e.name],s),o=await Ri.importKey("jwk",a,{name:"ECDSA",namedCurve:vi[e.name],hash:{name:F.read(F.webHash,e.hash)}},!1,["verify"]),c=z.concatUint8Array([r,n]).buffer;return Ri.verify({name:"ECDSA",namedCurve:vi[e.name],hash:{name:F.read(F.webHash,t)}},o,c,i)}(a,t,r,n,i);return e||o()}catch(e){if("nistP521"!==a.name&&("DataError"===e.name||"OperationError"===e.name))throw e;z.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":{const e=await async function(e,t,{r,s:n},i,s){const a=z.nodeRequire("eckey-utils"),o=z.getNodeBuffer(),{publicKey:c}=a.generateDer({curveName:Ii[e.name],publicKey:o.from(s)}),h=Li.createVerify(F.read(F.hash,t));h.write(i),h.end();const u=z.concatUint8Array([r,n]);try{return h.verify({key:c,format:"der",type:"spki",dsaEncoding:"ieee-p1363"},u)}catch(e){return!1}}(a,t,r,n,i);return e||o()}}return await Ni(a,r,s,i)||o()}async function Ni(e,t,r,n){return(await z.getNobleCurve(F.publicKey.ecdsa,e.name)).verify(z.concatUint8Array([t.r,t.s]),r,n,{lowS:!1})}var Fi=/*#__PURE__*/Object.freeze({__proto__:null,sign:Ti,validateParams:async function(e,t,r){const n=new Ki(e);if(n.keyType!==F.publicKey.ecdsa)return!1;switch(n.type){case"web":case"node":{const n=Dr(8),i=F.hash.sha256,s=await Ie.digest(i,n);try{const a=await Ti(e,i,n,t,r,s);return await Mi(e,i,a,n,t,s)}catch(e){return!1}}default:return Ci(F.publicKey.ecdsa,e,t,r)}},verify:Mi});var Oi=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){if(Pi(new Ki(e),n),Ie.getHashByteLength(t)0){const r=e[t-1];if(r>=1){const n=e.subarray(t-r),i=new Uint8Array(r).fill(r);if(z.equalsUint8Array(n,i))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var _i=/*#__PURE__*/Object.freeze({__proto__:null,decode:zi,encode:Hi});const Gi=z.getWebCrypto(),ji=z.getNodeCrypto();function qi(e,t,r,n){return z.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),z.stringToUint8Array("Anonymous Sender "),n])}async function Vi(e,t,r,n,i=!1,s=!1){let a;if(i){for(a=0;a=0&&0===t[a];a--);t=t.subarray(0,a+1)}return(await Ie.digest(e,z.concatUint8Array([new Uint8Array([0,0,0,1]),t,n]))).subarray(0,r)}async function Ji(e,t){switch(e.type){case"curve25519Legacy":{const{sharedSecret:r,ephemeralPublicKey:n}=await Ai(F.publicKey.x25519,t.subarray(1));return{publicKey:z.concatUint8Array([new Uint8Array([e.wireFormatLeadingByte]),n]),sharedKey:r}}case"web":if(e.web&&z.getWebCrypto())try{return await async function(e,t){const r=xi(e.payloadSize,e.web,t);let n=Gi.generateKey({name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]),i=Gi.importKey("jwk",r,{name:"ECDH",namedCurve:e.web},!1,[]);[n,i]=await Promise.all([n,i]);let s=Gi.deriveBits({name:"ECDH",namedCurve:e.web,public:i},n.privateKey,e.sharedSize),a=Gi.exportKey("jwk",n.publicKey);[s,a]=await Promise.all([s,a]);const o=new Uint8Array(s),c=new Uint8Array(Ui(a,e.wireFormatLeadingByte));return{publicKey:c,sharedKey:o}}(e,t)}catch(r){return z.printDebugError(r),Zi(e,t)}break;case"node":return async function(e,t){const r=ji.createECDH(e.node);r.generateKeys();const n=new Uint8Array(r.computeSecret(t)),i=new Uint8Array(r.getPublicKey());return{publicKey:i,sharedKey:n}}(e,t);default:return Zi(e,t)}}async function Yi(e,t,r,n){if(n.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(n,e.payloadSize-n.length),n=t}switch(e.type){case"curve25519Legacy":{const e=n.slice().reverse();return{secretKey:e,sharedKey:await wi(F.publicKey.x25519,t.subarray(1),r.subarray(1),e)}}case"web":if(e.web&&z.getWebCrypto())try{return await async function(e,t,r,n){const i=Qi(e.payloadSize,e.web,r,n);let s=Gi.importKey("jwk",i,{name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]);const a=xi(e.payloadSize,e.web,t);let o=Gi.importKey("jwk",a,{name:"ECDH",namedCurve:e.web},!0,[]);[s,o]=await Promise.all([s,o]);let c=Gi.deriveBits({name:"ECDH",namedCurve:e.web,public:o},s,e.sharedSize),h=Gi.exportKey("jwk",s);[c,h]=await Promise.all([c,h]);const u=new Uint8Array(c);return{secretKey:J(h.d),sharedKey:u}}(e,t,r,n)}catch(r){return z.printDebugError(r),Wi(e,t,n)}break;case"node":return async function(e,t,r){const n=ji.createECDH(e.node);n.setPrivateKey(r);const i=new Uint8Array(n.computeSecret(t));return{secretKey:new Uint8Array(n.getPrivateKey()),sharedKey:i}}(e,t,n);default:return Wi(e,t,n)}}async function Wi(e,t,r){return{secretKey:r,sharedKey:(await z.getNobleCurve(F.publicKey.ecdh,e.name)).getSharedSecret(r,t).subarray(1)}}async function Zi(e,t){const r=await z.getNobleCurve(F.publicKey.ecdh,e.name),{publicKey:n,privateKey:i}=await e.genKeyPair();return{publicKey:n,sharedKey:r.getSharedSecret(i,t).subarray(1)}}var $i=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i,s,a){const o=new Ki(e);Pi(o,i),Pi(o,r);const{sharedKey:c}=await Yi(o,r,i,s),h=qi(F.publicKey.ecdh,e,t,a),{keySize:u}=ce(t.cipher);let l;for(let e=0;e<3;e++)try{const r=await Vi(t.hash,c,u,h,1===e,2===e);return zi(await ui(t.cipher,r,n))}catch(e){l=e}throw l},encrypt:async function(e,t,r,n,i){const s=Hi(r),a=new Ki(e);Pi(a,n);const{publicKey:o,sharedKey:c}=await Ji(a,n),h=qi(F.publicKey.ecdh,e,t,i),{keySize:u}=ce(t.cipher),l=await Vi(t.hash,c,u,h);return{publicKey:o,wrappedKey:await hi(t.cipher,l,s)}},validateParams:async function(e,t,r){return Ci(F.publicKey.ecdh,e,t,r)}}),Xi=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:Ki,ecdh:$i,ecdhX:bi,ecdsa:Fi,eddsa:oi,eddsaLegacy:Oi,generate:async function(e){const t=new Ki(e),{oid:r,hash:n,cipher:i}=t,s=await t.genKeyPair();return{oid:r,Q:s.publicKey,secret:z.leftPad(s.privateKey,t.payloadSize),hash:n,cipher:i}},getPreferredHashAlgo:function(e){return Si[e.getName()].hash}});const es=BigInt(0),ts=BigInt(1);var rs=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){const a=BigInt(0);let o,c,h,u;n=mr(n),i=mr(i),r=mr(r),s=mr(s),r=br(r,n),s=br(s,i);const l=br(mr(t.subarray(0,Kr(i))),i);for(;;){if(o=Ur(ts,i),c=br(kr(r,o,n),i),c===a)continue;const e=br(s*c,i);if(u=br(l+e,i),h=br(vr(o,i)*u,i),h!==a)break}return{r:Cr(c,"be",Kr(n)),s:Cr(h,"be",Kr(n))}},validateParams:async function(e,t,r,n,i){if(e=mr(e),t=mr(t),r=mr(r),n=mr(n),r<=ts||r>=e)return!1;if(br(e-ts,t)!==es)return!1;if(kr(r,t,e)!==ts)return!1;const s=BigInt(Sr(t));if(s=a||r<=es||r>=a)return z.printDebug("invalid DSA Signature"),!1;const c=br(mr(n.subarray(0,Kr(a))),a),h=vr(r,a);if(h===es)return z.printDebug("invalid DSA Signature"),!1;i=br(i,s),o=br(o,s);const u=br(c*h,a),l=br(t*h,a);return br(br(kr(i,u,s)*kr(o,l,s),s),a)===t}}),ns={rsa:Jr,elgamal:Wr,elliptic:Xi,dsa:rs};var is=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:case F.publicKey.rsaSign:{const e=z.readMPI(t.subarray(r));return r+=e.length+2,{read:r,signatureParams:{s:e}}}case F.publicKey.dsa:case F.publicKey.ecdsa:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=z.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case F.publicKey.eddsaLegacy:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=z.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case F.publicKey.ed25519:case F.publicKey.ed448:{const n=2*ns.elliptic.eddsa.getPayloadSize(e),i=z.readExactSubarray(t,r,r+n);return r+=i.length,{read:r,signatureParams:{RS:i}}}default:throw new Zn("Unknown signature algorithm.")}},sign:async function(e,t,r,n,i,s){if(!r||!n)throw Error("Missing key parameters");switch(e){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:case F.publicKey.rsaSign:{const{n:e,e:a}=r,{d:o,p:c,q:h,u}=n;return{s:await ns.rsa.sign(t,i,e,a,o,c,h,u,s)}}case F.publicKey.dsa:{const{g:e,p:i,q:a}=r,{x:o}=n;return ns.dsa.sign(t,s,e,i,a,o)}case F.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case F.publicKey.ecdsa:{const{oid:e,Q:a}=r,{d:o}=n;return ns.elliptic.ecdsa.sign(e,t,i,a,o,s)}case F.publicKey.eddsaLegacy:{const{oid:e,Q:a}=r,{seed:o}=n;return ns.elliptic.eddsaLegacy.sign(e,t,i,a,o,s)}case F.publicKey.ed25519:case F.publicKey.ed448:{const{A:a}=r,{seed:o}=n;return ns.elliptic.eddsa.sign(e,t,i,a,o,s)}default:throw Error("Unknown signature algorithm.")}},verify:async function(e,t,r,n,i,s){switch(e){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:case F.publicKey.rsaSign:{const{n:e,e:a}=n,o=z.leftPad(r.s,e.length);return ns.rsa.verify(t,i,o,e,a,s)}case F.publicKey.dsa:{const{g:e,p:i,q:a,y:o}=n,{r:c,s:h}=r;return ns.dsa.verify(t,c,h,s,e,i,a,o)}case F.publicKey.ecdsa:{const{oid:e,Q:a}=n,o=new ns.elliptic.CurveWithOID(e).payloadSize,c=z.leftPad(r.r,o),h=z.leftPad(r.s,o);return ns.elliptic.ecdsa.verify(e,t,{r:c,s:h},i,a,s)}case F.publicKey.eddsaLegacy:{const{oid:e,Q:a}=n,o=new ns.elliptic.CurveWithOID(e).payloadSize,c=z.leftPad(r.r,o),h=z.leftPad(r.s,o);return ns.elliptic.eddsaLegacy.verify(e,t,{r:c,s:h},i,a,s)}case F.publicKey.ed25519:case F.publicKey.ed448:{const{A:a}=n;return ns.elliptic.eddsa.verify(e,t,r,i,a,s)}default:throw Error("Unknown signature algorithm.")}}});class ss{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return z.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class as{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Zn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class os{static fromObject({wrappedKey:e,algorithm:t}){const r=new os;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=z.readExactSubarray(e,t,t+r),t+=r}write(){return z.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function cs(e){try{e.getName()}catch(e){throw new Zn("Unknown curve OID")}}function hs(e,t){switch(e){case F.publicKey.ecdsa:case F.publicKey.ecdh:case F.publicKey.eddsaLegacy:return new ns.elliptic.CurveWithOID(t).payloadSize;case F.publicKey.ed25519:case F.publicKey.ed448:return ns.elliptic.eddsa.getPayloadSize(e);case F.publicKey.x25519:case F.publicKey.x448:return ns.elliptic.ecdhX.getPayloadSize(e);default:throw Error("Unknown elliptic algo")}}var us=/*#__PURE__*/Object.freeze({__proto__:null,generateParams:function(e,t,r){switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:return ns.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:n,q:i,u:s})=>({privateParams:{d:r,p:n,q:i,u:s},publicParams:{n:e,e:t}})));case F.publicKey.ecdsa:return ns.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new _n(e),Q:t}})));case F.publicKey.eddsaLegacy:return ns.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new _n(e),Q:t}})));case F.publicKey.ecdh:return ns.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:n,cipher:i})=>({privateParams:{d:r},publicParams:{oid:new _n(e),Q:t,kdfParams:new as({hash:n,cipher:i})}})));case F.publicKey.ed25519:case F.publicKey.ed448:return ns.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case F.publicKey.x25519:case F.publicKey.x448:return ns.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case F.publicKey.dsa:case F.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},generateSessionKey:function(e){const{keySize:t}=ce(e);return Dr(t)},getAEADMode:function(e){const t=F.read(F.aead,e);return dr[t]},getCipherParams:ce,getCurvePayloadSize:hs,getPreferredCurveHashAlgo:function(e,t){switch(e){case F.publicKey.ecdsa:case F.publicKey.eddsaLegacy:return ns.elliptic.getPreferredHashAlgo(t);case F.publicKey.ed25519:case F.publicKey.ed448:return ns.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}},getPrefixRandom:async function(e){const{blockSize:t}=ce(e),r=await Dr(t),n=new Uint8Array([r[r.length-2],r[r.length-1]]);return z.concat([r,n])},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:return{c:z.readMPI(t.subarray(r))};case F.publicKey.elgamal:{const e=z.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:z.readMPI(t.subarray(r))}}case F.publicKey.ecdh:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=new ss;return n.read(t.subarray(r)),{V:e,C:n}}case F.publicKey.x25519:case F.publicKey.x448:{const n=hs(e),i=z.readExactSubarray(t,r,r+n);r+=i.length;const s=new os;return s.read(t.subarray(r)),{ephemeralPublicKey:i,C:s}}default:throw new Zn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let n=0;switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:{const e=z.readMPI(t.subarray(n));n+=e.length+2;const r=z.readMPI(t.subarray(n));n+=r.length+2;const i=z.readMPI(t.subarray(n));n+=i.length+2;const s=z.readMPI(t.subarray(n));return n+=s.length+2,{read:n,privateParams:{d:e,p:r,q:i,u:s}}}case F.publicKey.dsa:case F.publicKey.elgamal:{const e=z.readMPI(t.subarray(n));return n+=e.length+2,{read:n,privateParams:{x:e}}}case F.publicKey.ecdsa:case F.publicKey.ecdh:{const i=hs(e,r.oid);let s=z.readMPI(t.subarray(n));return n+=s.length+2,s=z.leftPad(s,i),{read:n,privateParams:{d:s}}}case F.publicKey.eddsaLegacy:{const i=hs(e,r.oid);if(r.oid.getName()!==F.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let s=z.readMPI(t.subarray(n));return n+=s.length+2,s=z.leftPad(s,i),{read:n,privateParams:{seed:s}}}case F.publicKey.ed25519:case F.publicKey.ed448:{const r=hs(e),i=z.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{seed:i}}}case F.publicKey.x25519:case F.publicKey.x448:{const r=hs(e),i=z.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{k:i}}}default:throw new Zn("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=z.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{n:e,e:n}}}case F.publicKey.dsa:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=z.readMPI(t.subarray(r));r+=n.length+2;const i=z.readMPI(t.subarray(r));r+=i.length+2;const s=z.readMPI(t.subarray(r));return r+=s.length+2,{read:r,publicParams:{p:e,q:n,g:i,y:s}}}case F.publicKey.elgamal:{const e=z.readMPI(t.subarray(r));r+=e.length+2;const n=z.readMPI(t.subarray(r));r+=n.length+2;const i=z.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{p:e,g:n,y:i}}}case F.publicKey.ecdsa:{const e=new _n;r+=e.read(t),cs(e);const n=z.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{oid:e,Q:n}}}case F.publicKey.eddsaLegacy:{const e=new _n;if(r+=e.read(t),cs(e),e.getName()!==F.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let n=z.readMPI(t.subarray(r));return r+=n.length+2,n=z.leftPad(n,33),{read:r,publicParams:{oid:e,Q:n}}}case F.publicKey.ecdh:{const e=new _n;r+=e.read(t),cs(e);const n=z.readMPI(t.subarray(r));r+=n.length+2;const i=new as;return r+=i.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:n,kdfParams:i}}}case F.publicKey.ed25519:case F.publicKey.ed448:case F.publicKey.x25519:case F.publicKey.x448:{const n=z.readExactSubarray(t,r,r+hs(e));return r+=n.length,{read:r,publicParams:{A:n}}}default:throw new Zn("Unknown public key encryption algorithm.")}},publicKeyDecrypt:async function(e,t,r,n,i,s){switch(e){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:{const{c:e}=n,{n:i,e:a}=t,{d:o,p:c,q:h,u}=r;return ns.rsa.decrypt(e,i,a,o,c,h,u,s)}case F.publicKey.elgamal:{const{c1:e,c2:i}=n,a=t.p,o=r.x;return ns.elgamal.decrypt(e,i,a,o,s)}case F.publicKey.ecdh:{const{oid:e,Q:s,kdfParams:a}=t,{d:o}=r,{V:c,C:h}=n;return ns.elliptic.ecdh.decrypt(e,a,c,h.data,s,o,i)}case F.publicKey.x25519:case F.publicKey.x448:{const{A:i}=t,{k:s}=r,{ephemeralPublicKey:a,C:o}=n;if(null!==o.algorithm&&!z.isAES(o.algorithm))throw Error("AES session key expected");return ns.elliptic.ecdhX.decrypt(e,a,o.wrappedKey,i,s)}default:throw Error("Unknown public key encryption algorithm.")}},publicKeyEncrypt:async function(e,t,r,n,i){switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await ns.rsa.encrypt(n,e,t)}}case F.publicKey.elgamal:{const{p:e,g:t,y:i}=r;return ns.elgamal.encrypt(n,e,t,i)}case F.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:s}=r,{publicKey:a,wrappedKey:o}=await ns.elliptic.ecdh.encrypt(e,s,n,t,i);return{V:a,C:new ss(o)}}case F.publicKey.x25519:case F.publicKey.x448:{if(t&&!z.isAES(t))throw Error("X25519 and X448 keys can only encrypt AES session keys");const{A:i}=r,{ephemeralPublicKey:s,wrappedKey:a}=await ns.elliptic.ecdhX.encrypt(e,n,i);return{ephemeralPublicKey:s,C:os.fromObject({algorithm:t,wrappedKey:a})}}default:return[]}},serializeParams:function(e,t){const r=new Set([F.publicKey.ed25519,F.publicKey.x25519,F.publicKey.ed448,F.publicKey.x448]),n=Object.keys(t).map((n=>{const i=t[n];return z.isUint8Array(i)?r.has(e)?i:z.uint8ArrayToMPI(i):i.write()}));return z.concatUint8Array(n)},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:{const{n:e,e:n}=t,{d:i,p:s,q:a,u:o}=r;return ns.rsa.validateParams(e,n,i,s,a,o)}case F.publicKey.dsa:{const{p:e,q:n,g:i,y:s}=t,{x:a}=r;return ns.dsa.validateParams(e,n,i,s,a)}case F.publicKey.elgamal:{const{p:e,g:n,y:i}=t,{x:s}=r;return ns.elgamal.validateParams(e,n,i,s)}case F.publicKey.ecdsa:case F.publicKey.ecdh:{const n=ns.elliptic[F.read(F.publicKey,e)],{oid:i,Q:s}=t,{d:a}=r;return n.validateParams(i,s,a)}case F.publicKey.eddsaLegacy:{const{Q:e,oid:n}=t,{seed:i}=r;return ns.elliptic.eddsaLegacy.validateParams(n,e,i)}case F.publicKey.ed25519:case F.publicKey.ed448:{const{A:n}=t,{seed:i}=r;return ns.elliptic.eddsa.validateParams(e,n,i)}case F.publicKey.x25519:case F.publicKey.x448:{const{A:n}=t,{k:i}=r;return ns.elliptic.ecdhX.validateParams(e,n,i)}default:throw Error("Unknown public key algorithm.")}}});const ls={cipher:he,hash:Ie,mode:dr,publicKey:ns,signature:is,random:xr,pkcs1:Hr,pkcs5:_i,aesKW:li};Object.assign(ls,us);class ys extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,ys),this.name="Argon2OutOfMemoryError"}}let fs,gs;class ps{constructor(e=O){const{passes:t,parallelism:r,memoryExponent:n}=e.s2kArgon2Params;this.type="argon2",this.salt=null,this.t=t,this.p=r,this.encodedM=n}generateSalt(){this.salt=ls.random.getRandomBytes(16)}read(e){let t=0;return this.salt=e.subarray(t,t+16),t+=16,this.t=e[t++],this.p=e[t++],this.encodedM=e[t++],t}write(){const e=[new Uint8Array([F.write(F.s2k,this.type)]),this.salt,new Uint8Array([this.t,this.p,this.encodedM])];return z.concatUint8Array(e)}async produceKey(e,t){const r=2<1048576&&(gs=fs(),gs.catch((()=>{}))),i}catch(e){throw e.message&&(e.message.includes("Unable to grow instance memory")||e.message.includes("failed to grow memory")||e.message.includes("WebAssembly.Memory.grow")||e.message.includes("Out of memory"))?new ys("Could not allocate required memory for Argon2"):e}}}class ds{constructor(e,t=O){this.algorithm=F.hash.sha256,this.type=F.read(F.s2k,e),this.c=t.s2kIterationCountByte,this.salt=null}generateSalt(){switch(this.type){case"salted":case"iterated":this.salt=ls.random.getRandomBytes(8)}}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==z.uint8ArrayToString(e.subarray(t,t+3)))throw new Zn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Zn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Zn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...z.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([F.write(F.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return z.concatUint8Array(e)}async produceKey(e,t){e=z.encodeUTF8(e);const r=[];let n=0,i=0;for(;n>>1|(21845&Ls)<<1;Ts=(61680&(Ts=(52428&Ts)>>>2|(13107&Ts)<<2))>>>4|(3855&Ts)<<4,Rs[Ls]=((65280&Ts)>>>8|(255&Ts)<<8)>>>1}var Ms=function(e,t,r){for(var n=e.length,i=0,s=new Es(t);i>>c]=h}else for(a=new Es(n),i=0;i>>15-e[i]);return a},Ns=new ks(288);for(Ls=0;Ls<144;++Ls)Ns[Ls]=8;for(Ls=144;Ls<256;++Ls)Ns[Ls]=9;for(Ls=256;Ls<280;++Ls)Ns[Ls]=7;for(Ls=280;Ls<288;++Ls)Ns[Ls]=8;var Fs=new ks(32);for(Ls=0;Ls<32;++Ls)Fs[Ls]=5;var Os=/*#__PURE__*/Ms(Ns,9,0),Hs=/*#__PURE__*/Ms(Ns,9,1),zs=/*#__PURE__*/Ms(Fs,5,0),_s=/*#__PURE__*/Ms(Fs,5,1),Gs=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},js=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},qs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Vs=function(e){return(e+7)/8|0},Js=function(e,t,r){(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length);var n=new(2==e.BYTES_PER_ELEMENT?Es:4==e.BYTES_PER_ELEMENT?vs:ks)(r-t);return n.set(e.subarray(t,r)),n},Ys=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ws=function(e,t,r){var n=Error(t||Ys[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ws),!r)throw n;return n},Zs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8},$s=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Xs=function(e,t){for(var r=[],n=0;ny&&(y=s[n].s);var f=new Es(y+1),g=ea(r[u-1],f,0);if(g>t){n=0;var p=0,d=g-t,A=1<t))break;p+=A-(1<>>=d;p>0;){var m=s[n].s;f[m]=0&&p;--n){var b=s[n].s;f[b]==t&&(--f[b],++p)}g=t}return[new ks(f),g]},ea=function(e,t,r){return-1==e.s?Math.max(ea(e.l,t,r+1),ea(e.r,t,r+1)):t[e.s]=r},ta=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Es(++t),n=0,i=e[0],s=1,a=function(e){r[n++]=e},o=1;o<=t;++o)if(e[o]==i&&o!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(i),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(i);s=1,i=e[o]}return[r.subarray(0,n),t]},ra=function(e,t){for(var r=0,n=0;n>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;s4&&!S[Ss[C-1]];--C);var P,D,U,x,Q=h+5<<3,R=ra(i,Ns)+ra(s,Fs)+a,L=ra(i,y)+ra(s,p)+a+14+3*C+ra(v,S)+(2*v[16]+3*v[17]+7*v[18]);if(Q<=R&&Q<=L)return na(t,u,e.subarray(c,c+h));if(Zs(t,u,1+(L15&&(Zs(t,u,F[B]>>>5&127),u+=F[B]>>>12)}}}else P=Os,D=Ns,U=zs,x=Fs;for(B=0;B255){O=n[B]>>>18&31;$s(t,u,P[O+257]),u+=D[O+257],O>7&&(Zs(t,u,n[B]>>>23&31),u+=Bs[O]);var H=31&n[B];$s(t,u,U[H]),u+=x[H],H>3&&($s(t,u,n[B]>>>5&8191),u+=Is[H])}else $s(t,u,P[n[B]]),u+=D[n[B]];return $s(t,u,P[256]),u+D[256]},sa=/*#__PURE__*/new vs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),aa=/*#__PURE__*/new ks(0),oa=function(e,t,r,n,i){return function(e,t,r,n,i,s){var a=e.length,o=new ks(n+a+5*(1+Math.ceil(a/7e3))+i),c=o.subarray(n,o.length-i),h=0;if(!t||a<8)for(var u=0;u<=a;u+=65535){var l=u+65535;l>=a&&(c[h>>3]=s),h=na(c,h+1,e.subarray(u,l))}else{for(var y=sa[t-1],f=y>>>13,g=8191&y,p=(1<7e3||S>24576)&&x>423){h=ia(e,c,0,k,E,v,I,S,C,u-C,h),S=B=I=0,C=u;for(var Q=0;Q<286;++Q)E[Q]=0;for(Q=0;Q<30;++Q)v[Q]=0}var R=2,L=0,T=g,M=D-U&32767;if(x>2&&P==b(u-M))for(var N=Math.min(f,x)-1,F=Math.min(32767,u),O=Math.min(258,x);M<=F&&--T&&D!=U;){if(e[u+R]==e[u+R-M]){for(var H=0;HR){if(R=H,L=M,H>N)break;var z=Math.min(M,H-2),_=0;for(Q=0;Q_&&(_=j,U=G)}}}M+=(D=U)-(U=d[D])+32768&32767}if(L){k[S++]=268435456|Ds[R]<<18|Qs[L];var q=31&Ds[R],V=31&Qs[L];I+=Bs[q]+Is[V],++E[257+q],++v[V],K=u+R,++B}else k[S++]=e[u],++E[e[u]]}}h=ia(e,c,s,k,E,v,I,S,C,u-C,h),!s&&7&h&&(h=na(c,h+1,aa))}return Js(o,0,n+Vs(h)+i)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,r,n,!i)},ca=/*#__PURE__*/function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(oa(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||Ws(5),this.d&&Ws(4),this.d=t,this.p(e,t||!1)},e}(),ha=/*#__PURE__*/function(){function e(e){this.s={},this.p=new ks(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||Ws(5),this.d&&Ws(4);var t=this.p.length,r=new ks(t+e.length);r.set(this.p),r.set(e,t),this.p=r},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,r=function(e,t,r){var n=e.length;if(!n||r&&r.f&&!r.l)return t||new ks(0);var i=!t||r,s=!r||r.i;r||(r={}),t||(t=new ks(3*n));var a=function(e){var r=t.length;if(e>r){var n=new ks(Math.max(2*r,e));n.set(t),t=n}},o=r.f||0,c=r.p||0,h=r.b||0,u=r.l,l=r.d,y=r.m,f=r.n,g=8*n;do{if(!u){o=js(e,c,1);var p=js(e,c+1,3);if(c+=3,!p){var d=e[(K=Vs(c)+4)-4]|e[K-3]<<8,A=K+d;if(A>n){s&&Ws(0);break}i&&a(h+d),t.set(e.subarray(K,A),h),r.b=h+=d,r.p=c=8*A,r.f=o;continue}if(1==p)u=Hs,l=_s,y=9,f=5;else if(2==p){var w=js(e,c,31)+257,m=js(e,c+10,15)+4,b=w+js(e,c+5,31)+1;c+=14;for(var k=new ks(b),E=new ks(19),v=0;v>>4)<16)k[v++]=K;else{var P=0,D=0;for(16==K?(D=3+js(e,c,3),c+=2,P=k[v-1]):17==K?(D=3+js(e,c,7),c+=3):18==K&&(D=11+js(e,c,127),c+=7);D--;)k[v++]=P}}var U=k.subarray(0,w),x=k.subarray(w);y=Gs(U),f=Gs(x),u=Ms(U,y,1),l=Ms(x,f,1)}else Ws(1);if(c>g){s&&Ws(0);break}}i&&a(h+131072);for(var Q=(1<>>4;if((c+=15&P)>g){s&&Ws(0);break}if(P||Ws(2),T<256)t[h++]=T;else{if(256==T){L=c,u=null;break}var M=T-254;if(T>264){var N=Bs[v=T-257];M=js(e,c,(1<>>4;if(F||Ws(3),c+=15&F,x=xs[O],O>3&&(N=Is[O],x+=qs(e,c)&(1<g){s&&Ws(0);break}i&&a(h+131072);for(var H=h+M;h>16),i=(65535&i)+15*(i>>16)}r=t,n=i},d:function(){return(255&(r%=65521))<<24|r>>>8<<16|(255&(n%=65521))<<8|n>>>8}}),this.v=1,ca.call(this,e,t)}return e.prototype.push=function(e,t){ca.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var r=oa(e,this.o,this.v&&2,t&&4,!t);this.v&&(function(e,t){var r=t.level,n=0==r?0:r<6?1:9==r?3:2;e[0]=120,e[1]=n<<6|(n?32-2*n:1)}(r,this.o),this.v=0),t&&function(e,t,r){for(;r;++t)e[t]=r,r>>>=8}(r,r.length-4,this.c.d()),this.ondata(r,t)},e}(),la=/*#__PURE__*/function(){function e(e){this.v=1,ha.call(this,e)}return e.prototype.push=function(e,t){if(ha.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&Ws(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),ha.prototype.c.call(this,t)},e}(),ya="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{ya.decode(aa,{stream:!0}),1}catch(e){}class fa{static get tag(){return F.packet.literalData}constructor(e=new Date){this.format=F.literal.utf8,this.date=z.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=F.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||z.isStream(this.text))&&(this.text=z.decodeUTF8(z.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=z.canonicalizeEOL(z.encodeUTF8(this.text))),e?D(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await C(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=z.decodeUTF8(await e.readBytes(r)),this.date=z.readDate(await e.readBytes(4));let n=e.remainder();y(n)&&(n=await Q(n)),this.setBytes(n,t)}))}writeHeader(){const e=z.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),n=z.writeDate(this.date);return z.concatUint8Array([r,t,e,n])}write(){const e=this.writeHeader(),t=this.getBytes();return z.concat([e,t])}}class ga{constructor(){this.bytes=""}read(e){return this.bytes=z.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return z.stringToUint8Array(this.bytes)}toHex(){return z.uint8ArrayToHex(z.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new ga;return t.read(z.hexToUint8Array(e)),t}static wildcard(){const e=new ga;return e.read(new Uint8Array(8)),e}}const pa=Symbol("verified"),da="salt@notations.openpgpjs.org",Aa=new Set([F.signatureSubpacket.issuerKeyID,F.signatureSubpacket.issuerFingerprint,F.signatureSubpacket.embeddedSignature]);class wa{static get tag(){return F.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.unknownSubpackets=[],this.signedHashValue=null,this.salt=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new ga,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.preferredCipherSuites=null,this.revoked=null,this[pa]=null}read(e,t=O){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Zn("Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4!==this.version&&5!==this.version&&6!==this.version)throw new Zn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[r++],this.publicKeyAlgorithm=e[r++],this.hashAlgorithm=e[r++],r+=this.readSubPackets(e.subarray(r,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");if(this.signatureData=e.subarray(0,r),r+=this.readSubPackets(e.subarray(r,e.length),!1),this.signedHashValue=e.subarray(r,r+2),r+=2,6===this.version){const t=e[r++];this.salt=e.subarray(r,r+t),r+=t}const n=e.subarray(r,e.length),{read:i,signatureParams:s}=ls.signature.parseSignatureParams(this.publicKeyAlgorithm,n);if(ils.serializeParams(this.publicKeyAlgorithm,await this.params))):ls.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),6===this.version&&(e.push(new Uint8Array([this.salt.length])),e.push(this.salt)),e.push(this.writeParams()),z.concat(e)}async sign(e,t,r=new Date,n=!1,i){this.version=e.version,this.created=z.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID();const s=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];if(6===this.version){const e=ba(this.hashAlgorithm);if(null===this.salt)this.salt=ls.random.getRandomBytes(e);else if(e!==this.salt.length)throw Error("Provided salt does not have the required length")}else if(i.nonDeterministicSignaturesViaNotation){if(0!==this.rawNotations.filter((({name:e})=>e===da)).length)throw Error("Unexpected existing salt notation");{const e=ls.random.getRandomBytes(ba(this.hashAlgorithm));this.rawNotations.push({name:da,value:e,humanReadable:!1,critical:!1})}}s.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=z.concat(s);const a=this.toHash(this.signatureType,t,n),o=await this.hash(this.signatureType,t,a,n);this.signedHashValue=x(P(o),0,2);const c=async()=>ls.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await Q(o));z.isStream(o)?this.params=c():(this.params=await c(),this[pa]=!0)}writeHashedSubPackets(){const e=F.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(ma(e.signatureCreationTime,!0,z.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(ma(e.signatureExpirationTime,!0,z.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(ma(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(ma(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(ma(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(ma(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(ma(e.keyExpirationTime,!0,z.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(ma(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=z.concat([r,this.revocationKeyFingerprint]),t.push(ma(e.revocationKey,!1,r))),!this.issuerKeyID.isNull()&&this.issuerKeyVersion<5&&t.push(ma(e.issuerKeyID,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:n,value:i,humanReadable:s,critical:a})=>{r=[new Uint8Array([s?128:0,0,0,0])];const o=z.encodeUTF8(n);r.push(z.writeNumber(o.length,2)),r.push(z.writeNumber(i.length,2)),r.push(o),r.push(i),r=z.concat(r),t.push(ma(e.notationData,a,r))})),null!==this.preferredHashAlgorithms&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(ma(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(ma(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.keyServerPreferences)),t.push(ma(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(ma(e.preferredKeyServer,!1,z.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(ma(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(ma(e.policyURI,!1,z.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.keyFlags)),t.push(ma(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(ma(e.signersUserID,!1,z.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=z.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(ma(e.reasonForRevocation,!0,r))),null!==this.features&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.features)),t.push(ma(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(z.stringToUint8Array(this.signatureTargetHash)),r=z.concat(r),t.push(ma(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(ma(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=z.concat(r),t.push(ma(e.issuerFingerprint,this.version>=5,r))),null!==this.preferredAEADAlgorithms&&(r=z.stringToUint8Array(z.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(ma(e.preferredAEADAlgorithms,!1,r))),null!==this.preferredCipherSuites&&(r=new Uint8Array([].concat(...this.preferredCipherSuites)),t.push(ma(e.preferredCipherSuites,!1,r)));const n=z.concat(t),i=z.writeNumber(n.length,6===this.version?4:2);return z.concat([i,n])}writeUnhashedSubPackets(){const e=this.unhashedSubpackets.map((({type:e,critical:t,body:r})=>ma(e,t,r))),t=z.concat(e),r=z.writeNumber(t.length,6===this.version?4:2);return z.concat([r,t])}readSubPacket(e,t=!0){let r=0;const n=!!(128&e[r]),i=127&e[r];if(r++,t||(this.unhashedSubpackets.push({type:i,critical:n,body:e.subarray(r,e.length)}),Aa.has(i)))switch(i){case F.signatureSubpacket.signatureCreationTime:this.created=z.readDate(e.subarray(r,e.length));break;case F.signatureSubpacket.signatureExpirationTime:{const t=z.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case F.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case F.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case F.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case F.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case F.signatureSubpacket.keyExpirationTime:{const t=z.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case F.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case F.signatureSubpacket.issuerKeyID:if(4===this.version)this.issuerKeyID.read(e.subarray(r,e.length));else if(t)throw Error("Unexpected Issuer Key ID subpacket");break;case F.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const i=z.readNumber(e.subarray(r,r+2));r+=2;const s=z.readNumber(e.subarray(r,r+2));r+=2;const a=z.decodeUTF8(e.subarray(r,r+i)),o=e.subarray(r+i,r+i+s);this.rawNotations.push({name:a,humanReadable:t,value:o,critical:n}),t&&(this.notations[a]=z.decodeUTF8(o));break}case F.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=z.decodeUTF8(e.subarray(r,e.length));break;case F.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case F.signatureSubpacket.policyURI:this.policyURI=z.decodeUTF8(e.subarray(r,e.length));break;case F.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.signersUserID:this.signersUserID=z.decodeUTF8(e.subarray(r,e.length));break;case F.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=z.decodeUTF8(e.subarray(r,e.length));break;case F.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=ls.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=z.uint8ArrayToString(e.subarray(r,r+t));break}case F.signatureSubpacket.embeddedSignature:this.embeddedSignature=new wa,this.embeddedSignature.read(e.subarray(r,e.length));break;case F.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),this.issuerKeyVersion>=5?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case F.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;case F.signatureSubpacket.preferredCipherSuites:this.preferredCipherSuites=[];for(let t=r;t{r+=e.length}),(()=>{const n=[];return 5!==this.version||this.signatureType!==F.signature.binary&&this.signatureType!==F.signature.text||(t?n.push(new Uint8Array(6)):n.push(e.writeHeader())),n.push(new Uint8Array([this.version,255])),5===this.version&&n.push(new Uint8Array(4)),n.push(z.writeNumber(r,4)),z.concat(n)}))}toHash(e,t,r=!1){const n=this.toSign(e,t);return z.concat([this.salt||new Uint8Array,n,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,n=!1){if(6===this.version&&this.salt.length!==ba(this.hashAlgorithm))throw Error("Signature salt does not have the expected length");return r||(r=this.toHash(e,t,n)),ls.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,n=new Date,i=!1,s=O){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const a=t===F.signature.binary||t===F.signature.text;if(!(this[pa]&&!a)){let n,s;if(this.hashed?s=await this.hashed:(n=this.toHash(t,r,i),s=await this.hash(t,r,n)),s=await Q(s),this.signedHashValue[0]!==s[0]||this.signedHashValue[1]!==s[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[pa]=await ls.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,n,s),!this[pa])throw Error("Signature verification failed")}const o=z.normalizeDate(n);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(s.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+F.read(F.hash,this.hashAlgorithm).toUpperCase());if(s.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[F.signature.binary,F.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+F.read(F.hash,this.hashAlgorithm).toUpperCase());if(this.unknownSubpackets.forEach((({type:e,critical:t})=>{if(t)throw Error("Unknown critical signature subpacket type "+e)})),this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&s.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=z.normalizeDate(e);return null!==t&&!(this.created<=t&&twa.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==F.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID)||3===this.version&&6===e.version||6===this.version&&6!==e.version||6===this.version&&!z.equalsUint8Array(e.issuerFingerprint,this.issuerFingerprint)||6===this.version&&!z.equalsUint8Array(e.salt,this.salt))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function Ea(e,t){if(!t[e]){let t;try{t=F.read(F.packet,e)}catch(t){throw new $n("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}ka.prototype.hash=wa.prototype.hash,ka.prototype.toHash=wa.prototype.toHash,ka.prototype.toSign=wa.prototype.toSign;class va extends Array{static async fromBinary(e,t,r=O){const n=new va;return await n.read(e,t,r),n}async read(e,t,r=O){r.additionalAllowedPackets.length&&(t={...t,...z.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=K(e,(async(e,n)=>{const i=M(n);try{for(;;){await i.ready;if(await Wn(e,(async e=>{try{if(e.tag===F.packet.marker||e.tag===F.packet.trust||e.tag===F.packet.padding)return;const n=Ea(e.tag,t);n.packets=new va,n.fromStream=z.isStream(e.packet),await n.read(e.packet,r),await i.write(n)}catch(t){if(t instanceof $n){if(!(e.tag<=39))return;await i.abort(t)}const n=!r.ignoreUnsupportedPackets&&t instanceof Zn,s=!(r.ignoreMalformedPackets||t instanceof Zn);if(n||s||Yn(e.tag))await i.abort(t);else{const t=new Xn(e.tag,e.packet);await i.write(t)}z.printDebugError(t)}})))return await i.ready,void await i.close()}}catch(e){await i.abort(e)}}));const n=T(this.stream);for(;;){const{done:e,value:t}=await n.read();if(e?this.stream=null:this.push(t),e||Yn(t.constructor.tag))break}n.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),i+=e.length,i>=s){const e=Math.min(Math.log(i)/Math.LN2|0,30),r=2**e,n=z.concat([qn(e)].concat(t));return t=[n.subarray(1+r)],i=t[0].length,n.subarray(0,1+r)}}),(()=>z.concat([jn(i)].concat(t)))))}else{if(z.isStream(n)){let t=0;e.push(S(P(n),(e=>{t+=e.length}),(()=>Jn(r,t))))}else e.push(Jn(r,n.length));e.push(n)}}return z.concat(e)}filterByTag(...e){const t=new va,r=e=>t=>e===t;for(let n=0;nt.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,n=e=>t=>e===t;for(let i=0;i{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),z.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=O){const t=F.read(F.compression,this.algorithm),r=Da[t];if(!r)throw Error(t+" decompression not supported");this.packets=await va.fromBinary(await r(this.compressed),Ba,e)}compress(){const e=F.read(F.compression,this.algorithm),t=Pa[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write())}}function Sa(e,t){return r=>{if(!z.isStream(r)||y(r))return L((()=>Q(r).then((e=>new Promise(((r,n)=>{const i=new t;i.ondata=e=>{r(e)};try{i.push(e,!0)}catch(e){n(e)}}))))));if(e)try{const t=e();return r.pipeThrough(t)}catch(e){if("TypeError"!==e.name)throw e}const n=r.getReader(),i=new t;return new ReadableStream({async start(e){for(i.ondata=async(t,r)=>{e.enqueue(t),r&&e.close()};;){const{done:e,value:t}=await n.read();if(e)return void i.push(new Uint8Array,!0);t.length&&i.push(t)}}})}}function Ka(){return async function(e){const{decode:t}=await Promise.resolve().then((function(){return Ly}));return L((async()=>t(await Q(e))))}}const Ca=e=>({compressor:"undefined"!=typeof CompressionStream&&(()=>new CompressionStream(e)),decompressor:"undefined"!=typeof DecompressionStream&&(()=>new DecompressionStream(e))}),Pa={zip:/*#__PURE__*/Sa(Ca("deflate-raw").compressor,ca),zlib:/*#__PURE__*/Sa(Ca("deflate").compressor,ua)},Da={uncompressed:e=>e,zip:/*#__PURE__*/Sa(Ca("deflate-raw").decompressor,ha),zlib:/*#__PURE__*/Sa(Ca("deflate").decompressor,la),bzip2:/*#__PURE__*/Ka()},Ua=/*#__PURE__*/z.constructAllowedPackets([fa,Ia,ka,wa]);class xa{static get tag(){return F.packet.symEncryptedIntegrityProtectedData}static fromObject({version:e,aeadAlgorithm:t}){if(1!==e&&2!==e)throw Error("Unsupported SEIPD version");const r=new xa;return r.version=e,2===e&&(r.aeadAlgorithm=t),r}constructor(){this.version=null,this.cipherAlgorithm=null,this.aeadAlgorithm=null,this.chunkSizeByte=null,this.salt=null,this.encrypted=null,this.packets=null}async read(e){await C(e,(async e=>{if(this.version=await e.readByte(),1!==this.version&&2!==this.version)throw new Zn(`Version ${this.version} of the SEIP packet is unsupported.`);2===this.version&&(this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte(),this.salt=await e.readBytes(32)),this.encrypted=e.remainder()}))}write(){return 2===this.version?z.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.salt,this.encrypted]):z.concat([new Uint8Array([this.version]),this.encrypted])}async encrypt(e,t,r=O){const{blockSize:n,keySize:i}=ls.getCipherParams(e);if(t.length!==i)throw Error("Unexpected session key size");let s=this.packets.write();if(y(s)&&(s=await Q(s)),2===this.version)this.cipherAlgorithm=e,this.salt=ls.random.getRandomBytes(32),this.chunkSizeByte=r.aeadChunkSizeByte,this.encrypted=await Qa(this,"encrypt",t,s);else{const i=await ls.getPrefixRandom(e),a=new Uint8Array([211,20]),o=z.concat([i,s,a]),c=await ls.hash.sha1(D(o)),h=z.concat([o,c]);this.encrypted=await ls.mode.cfb.encrypt(e,t,h,new Uint8Array(n),r)}return!0}async decrypt(e,t,r=O){if(t.length!==ls.getCipherParams(e).keySize)throw Error("Unexpected session key size");let n,i=P(this.encrypted);if(y(i)&&(i=await Q(i)),2===this.version){if(this.cipherAlgorithm!==e)throw Error("Unexpected session key algorithm");n=await Qa(this,"decrypt",t,i)}else{const{blockSize:s}=ls.getCipherParams(e),a=await ls.mode.cfb.decrypt(e,t,i,new Uint8Array(s)),o=x(D(a),-20),c=x(a,0,-20),h=Promise.all([Q(await ls.hash.sha1(D(c))),Q(o)]).then((([e,t])=>{if(!z.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=x(c,s+2);n=x(u,0,-2),n=E([n,L((()=>h))]),z.isStream(i)&&r.allowUnauthenticatedStream||(n=await Q(n))}return this.packets=await va.fromBinary(n,Ua,r),!0}}async function Qa(e,t,r,n){const i=e instanceof xa&&2===e.version,s=!i&&e.constructor.tag===F.packet.aeadEncryptedData;if(!i&&!s)throw Error("Unexpected packet type");const a=ls.getAEADMode(e.aeadAlgorithm),o="decrypt"===t?a.tagLength:0,c="encrypt"===t?a.tagLength:0,h=2**(e.chunkSizeByte+6)+o,u=s?8:0,l=new ArrayBuffer(13+u),y=new Uint8Array(l,0,5+u),f=new Uint8Array(l),g=new DataView(l),p=new Uint8Array(l,5,8);y.set([192|e.constructor.tag,e.version,e.cipherAlgorithm,e.aeadAlgorithm,e.chunkSizeByte],0);let d,A,w=0,m=Promise.resolve(),b=0,k=0;if(i){const{keySize:t}=ls.getCipherParams(e.cipherAlgorithm),{ivLength:n}=a,i=new Uint8Array(l,0,5),s=await fi(F.hash.sha256,r,e.salt,i,t+n);r=s.subarray(0,t),d=s.subarray(t),d.fill(0,d.length-8),A=new DataView(d.buffer,d.byteOffset,d.byteLength)}else d=e.iv;const E=await a(e.cipherAlgorithm,r);return K(n,(async(r,n)=>{if("array"!==z.isStream(r)){const t=new TransformStream({},{highWaterMark:z.getHardwareConcurrency()*2**(e.chunkSizeByte+6),size:e=>e.length});v(t.readable,n),n=t.writable}const s=T(r),a=M(n);try{for(;;){let e=await s.readBytes(h+o)||new Uint8Array;const r=e.subarray(e.length-o);let n,l,v;if(e=e.subarray(0,e.length-o),i)v=d;else{v=d.slice();for(let e=0;e<8;e++)v[d.length-8+e]^=p[e]}if(!w||e.length?(s.unshift(r),n=E[t](e,v,y),n.catch((()=>{})),k+=e.length-o+c):(g.setInt32(5+u+4,b),n=E[t](r,v,f),n.catch((()=>{})),k+=c,l=!0),b+=e.length-o,m=m.then((()=>n)).then((async e=>{await a.ready,await a.write(e),k-=e.length})).catch((e=>a.abort(e))),(l||k>a.desiredSize)&&await m,l){await a.close();break}i?A.setInt32(d.length-4,++w):g.setInt32(9,++w)}}catch(e){await a.ready.catch((()=>{})),await a.abort(e)}}))}const Ra=/*#__PURE__*/z.constructAllowedPackets([fa,Ia,ka,wa]);class La{static get tag(){return F.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=F.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await C(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Zn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=ls.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return z.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=O){this.packets=await va.fromBinary(await Qa(this,"decrypt",t,P(this.encrypted)),Ra,r)}async encrypt(e,t,r=O){this.cipherAlgorithm=e;const{ivLength:n}=ls.getAEADMode(this.aeadAlgorithm);this.iv=ls.random.getRandomBytes(n),this.chunkSizeByte=r.aeadChunkSizeByte;const i=this.packets.write();this.encrypted=await Qa(this,"encrypt",t,i)}}class Ta{static get tag(){return F.packet.publicKeyEncryptedSessionKey}constructor(){this.version=null,this.publicKeyID=new ga,this.publicKeyVersion=null,this.publicKeyFingerprint=null,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}static fromObject({version:e,encryptionKeyPacket:t,anonymousRecipient:r,sessionKey:n,sessionKeyAlgorithm:i}){const s=new Ta;if(3!==e&&6!==e)throw Error("Unsupported PKESK version");return s.version=e,6===e&&(s.publicKeyVersion=r?null:t.version,s.publicKeyFingerprint=r?null:t.getFingerprintBytes()),s.publicKeyID=r?ga.wildcard():t.getKeyID(),s.publicKeyAlgorithm=t.algorithm,s.sessionKey=n,s.sessionKeyAlgorithm=i,s}read(e){let t=0;if(this.version=e[t++],3!==this.version&&6!==this.version)throw new Zn(`Version ${this.version} of the PKESK packet is unsupported.`);if(6===this.version){const r=e[t++];if(r){this.publicKeyVersion=e[t++];const n=r-1;this.publicKeyFingerprint=e.subarray(t,t+n),t+=n,this.publicKeyVersion>=5?this.publicKeyID.read(this.publicKeyFingerprint):this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8))}else this.publicKeyID=ga.wildcard()}else t+=this.publicKeyID.read(e.subarray(t,t+8));if(this.publicKeyAlgorithm=e[t++],this.encrypted=ls.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t)),this.publicKeyAlgorithm===F.publicKey.x25519||this.publicKeyAlgorithm===F.publicKey.x448)if(3===this.version)this.sessionKeyAlgorithm=F.write(F.symmetric,this.encrypted.C.algorithm);else if(null!==this.encrypted.C.algorithm)throw Error("Unexpected cleartext symmetric algorithm")}write(){const e=[new Uint8Array([this.version])];return 6===this.version?null!==this.publicKeyFingerprint?(e.push(new Uint8Array([this.publicKeyFingerprint.length+1,this.publicKeyVersion])),e.push(this.publicKeyFingerprint)):e.push(new Uint8Array([0])):e.push(this.publicKeyID.write()),e.push(new Uint8Array([this.publicKeyAlgorithm]),ls.serializeParams(this.publicKeyAlgorithm,this.encrypted)),z.concatUint8Array(e)}async encrypt(e){const t=F.write(F.publicKey,this.publicKeyAlgorithm),r=3===this.version?this.sessionKeyAlgorithm:null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=Ma(this.version,t,r,this.sessionKey);this.encrypted=await ls.publicKeyEncrypt(t,r,e.publicParams,i,n)}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Ma(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=await ls.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,n,r),{sessionKey:s,sessionKeyAlgorithm:a}=function(e,t,r,n){switch(t){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.elgamal:case F.publicKey.ecdh:{const t=r.subarray(0,r.length-2),i=r.subarray(r.length-2),s=z.writeChecksum(t.subarray(t.length%8)),a=s[0]===i[0]&s[1]===i[1],o=6===e?{sessionKeyAlgorithm:null,sessionKey:t}:{sessionKeyAlgorithm:t[0],sessionKey:t.subarray(1)};if(n){const t=a&o.sessionKeyAlgorithm===n.sessionKeyAlgorithm&o.sessionKey.length===n.sessionKey.length;return{sessionKey:z.selectUint8Array(t,o.sessionKey,n.sessionKey),sessionKeyAlgorithm:6===e?null:z.selectUint8(t,o.sessionKeyAlgorithm,n.sessionKeyAlgorithm)}}if(a&&(6===e||F.read(F.symmetric,o.sessionKeyAlgorithm)))return o;throw Error("Decryption error")}case F.publicKey.x25519:case F.publicKey.x448:return{sessionKeyAlgorithm:null,sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);if(3===this.version){const e=this.publicKeyAlgorithm!==F.publicKey.x25519&&this.publicKeyAlgorithm!==F.publicKey.x448;if(this.sessionKeyAlgorithm=e?a:this.sessionKeyAlgorithm,s.length!==ls.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}this.sessionKey=s}}function Ma(e,t,r,n){switch(t){case F.publicKey.rsaEncrypt:case F.publicKey.rsaEncryptSign:case F.publicKey.elgamal:case F.publicKey.ecdh:return z.concatUint8Array([new Uint8Array(6===e?[]:[r]),n,z.writeChecksum(n.subarray(n.length%8))]);case F.publicKey.x25519:case F.publicKey.x448:return n;default:throw Error("Unsupported public key algorithm")}}class Na{static get tag(){return F.packet.symEncryptedSessionKey}constructor(e=O){this.version=e.aeadProtect?6:4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm=null,this.aeadAlgorithm=F.write(F.aead,e.preferredAEADAlgorithm),this.encrypted=null,this.s2k=null,this.iv=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version&&6!==this.version)throw new Zn(`Version ${this.version} of the SKESK packet is unsupported.`);6===this.version&&t++;const r=e[t++];this.version>=5&&(this.aeadAlgorithm=e[t++],6===this.version&&t++);const n=e[t++];if(this.s2k=ws(n),t+=this.s2k.read(e.subarray(t,e.length)),this.version>=5){const r=ls.getAEADMode(this.aeadAlgorithm);this.iv=e.subarray(t,t+=r.ivLength)}this.version>=5||t=5){const e=ls.getAEADMode(this.aeadAlgorithm),r=new Uint8Array([192|Na.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),s=6===this.version?await fi(F.hash.sha256,i,new Uint8Array,r,n):i,a=await e(t,s);this.sessionKey=await a.decrypt(this.encrypted,this.iv,r)}else if(null!==this.encrypted){const e=await ls.mode.cfb.decrypt(t,i,this.encrypted,new Uint8Array(r));if(this.sessionKeyAlgorithm=F.write(F.symmetric,e[0]),this.sessionKey=e.subarray(1,e.length),this.sessionKey.length!==ls.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}else this.sessionKey=i}async encrypt(e,t=O){const r=null!==this.sessionKeyEncryptionAlgorithm?this.sessionKeyEncryptionAlgorithm:this.sessionKeyAlgorithm;this.sessionKeyEncryptionAlgorithm=r,this.s2k=ms(t),this.s2k.generateSalt();const{blockSize:n,keySize:i}=ls.getCipherParams(r),s=await this.s2k.produceKey(e,i);if(null===this.sessionKey&&(this.sessionKey=ls.generateSessionKey(this.sessionKeyAlgorithm)),this.version>=5){const e=ls.getAEADMode(this.aeadAlgorithm);this.iv=ls.random.getRandomBytes(e.ivLength);const t=new Uint8Array([192|Na.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),n=6===this.version?await fi(F.hash.sha256,s,new Uint8Array,t,i):s,a=await e(r,n);this.encrypted=await a.encrypt(this.sessionKey,this.iv,t)}else{const e=z.concatUint8Array([new Uint8Array([this.sessionKeyAlgorithm]),this.sessionKey]);this.encrypted=await ls.mode.cfb.encrypt(r,s,e,new Uint8Array(n),t)}}}class Fa{static get tag(){return F.packet.publicKey}constructor(e=new Date,t=O){this.version=t.v6Keys?6:4,this.created=z.normalizeDate(e),this.algorithm=null,this.publicParams=null,this.expirationTimeV3=0,this.fingerprint=null,this.keyID=null}static fromSecretKeyPacket(e){const t=new Fa,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}async read(e,t=O){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Zn("Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4===this.version||5===this.version||6===this.version){this.created=z.readDate(e.subarray(r,r+4)),r+=4,this.algorithm=e[r++],this.version>=5&&(r+=4);const{read:t,publicParams:n}=ls.parsePublicKeyParams(this.algorithm,e.subarray(r));if(6===this.version&&n.oid&&(n.oid.getName()===F.curve.curve25519Legacy||n.oid.getName()===F.curve.ed25519Legacy))throw Error("Legacy curve25519 cannot be used with v6 keys");return this.publicParams=n,r+=t,await this.computeFingerprintAndKeyID(),r}throw new Zn(`Version ${this.version} of the key packet is unsupported.`)}write(){const e=[];e.push(new Uint8Array([this.version])),e.push(z.writeDate(this.created)),e.push(new Uint8Array([this.algorithm]));const t=ls.serializeParams(this.algorithm,this.publicParams);return this.version>=5&&e.push(z.writeNumber(t.length,4)),e.push(t),z.concatUint8Array(e)}writeForHash(e){const t=this.writePublicKey(),r=149+e,n=e>=5?4:2;return z.concatUint8Array([new Uint8Array([r]),z.writeNumber(t.length,n),t])}isDecrypted(){return null}getCreationTime(){return this.created}getKeyID(){return this.keyID}async computeFingerprintAndKeyID(){if(await this.computeFingerprint(),this.keyID=new ga,this.version>=5)this.keyID.read(this.fingerprint.subarray(0,8));else{if(4!==this.version)throw Error("Unsupported key version");this.keyID.read(this.fingerprint.subarray(12,20))}}async computeFingerprint(){const e=this.writeForHash(this.version);if(this.version>=5)this.fingerprint=await ls.hash.sha256(e);else{if(4!==this.version)throw Error("Unsupported key version");this.fingerprint=await ls.hash.sha1(e)}}getFingerprintBytes(){return this.fingerprint}getFingerprint(){return z.uint8ArrayToHex(this.getFingerprintBytes())}hasSameFingerprintAs(e){return this.version===e.version&&z.equalsUint8Array(this.writePublicKey(),e.writePublicKey())}getAlgorithmInfo(){const e={};e.algorithm=F.read(F.publicKey,this.algorithm);const t=this.publicParams.n||this.publicParams.p;return t?e.bits=z.uint8ArrayBitLength(t):this.publicParams.oid&&(e.curve=this.publicParams.oid.getName()),e}}Fa.prototype.readPublicKey=Fa.prototype.read,Fa.prototype.writePublicKey=Fa.prototype.write;const Oa=/*#__PURE__*/z.constructAllowedPackets([fa,Ia,ka,wa]);class Ha{static get tag(){return F.packet.symmetricallyEncryptedData}constructor(){this.encrypted=null,this.packets=null}read(e){this.encrypted=e}write(){return this.encrypted}async decrypt(e,t,r=O){if(!r.allowUnauthenticatedMessages)throw Error("Message is not authenticated.");const{blockSize:n}=ls.getCipherParams(e),i=await Q(P(this.encrypted)),s=await ls.mode.cfb.decrypt(e,t,i.subarray(n+2),i.subarray(2,n+2));this.packets=await va.fromBinary(s,Oa,r)}async encrypt(e,t,r=O){const n=this.packets.write(),{blockSize:i}=ls.getCipherParams(e),s=await ls.getPrefixRandom(e),a=await ls.mode.cfb.encrypt(e,t,s,new Uint8Array(i),r),o=await ls.mode.cfb.encrypt(e,t,n,a.subarray(2),r);this.encrypted=z.concat([a,o])}}class za extends Fa{static get tag(){return F.packet.publicSubkey}constructor(e,t){super(e,t)}static fromSecretSubkeyPacket(e){const t=new za,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}}class _a{static get tag(){return F.packet.userAttribute}constructor(){this.attributes=[]}read(e){let t=0;for(;t{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function ja(e,t,r,n,i,s,a){if("argon2"===t.type&&!i)throw Error("Using Argon2 S2K without AEAD is not allowed");if("simple"===t.type&&6===e)throw Error("Using Simple S2K with version 6 keys is not allowed");const{keySize:o}=ls.getCipherParams(n),c=await t.produceKey(r,o);if(!i||5===e||a)return c;const h=z.concatUint8Array([s,new Uint8Array([e,n,i])]);return fi(F.hash.sha256,c,new Uint8Array,h,o)}class qa{static get tag(){return F.packet.userID}constructor(){this.userID="",this.name="",this.email="",this.comment=""}static fromObject(e){if(z.isString(e)||e.name&&!z.isString(e.name)||e.email&&!z.isEmailAddress(e.email)||e.comment&&!z.isString(e.comment))throw Error("Invalid user ID format");const t=new qa;Object.assign(t,e);const r=[];return t.name&&r.push(t.name),t.comment&&r.push(`(${t.comment})`),t.email&&r.push(`<${t.email}>`),t.userID=r.join(" "),t}read(e,t=O){const r=z.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");const n=/^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/.exec(r);if(null!==n){const{name:e,comment:t,email:r}=n.groups;this.comment=t?.replace(/^\(|\)|\s$/g,"").trim()||"",this.name=e?.trim()||"",this.email=r.substring(1,r.length-1)}else/^[^\s@]+@[^\s@]+$/.test(r)&&(this.email=r);this.userID=r}write(){return z.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Va extends Ga{static get tag(){return F.packet.secretSubkey}constructor(e=new Date,t=O){super(e,t)}}const Ja=/*#__PURE__*/z.constructAllowedPackets([wa]);class Ya{constructor(e){this.packets=e||new va}write(){return this.packets.write()}armor(e=O){const t=this.packets.some((e=>e.constructor.tag===wa.tag&&6!==e.version));return ie(F.armor.signature,this.write(),void 0,void 0,void 0,t,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Wa(e,t){const r=new Va(e.date,t);return r.packets=null,r.algorithm=F.write(F.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function Za(e,t){const r=new Ga(e.date,t);return r.packets=null,r.algorithm=F.write(F.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function $a(e,t,r,n,i=new Date,s){let a,o;for(let c=e.length-1;c>=0;c--)try{(!a||e[c].created>=a.created)&&(await e[c].verify(t,r,n,i,void 0,s),a=e[c])}catch(e){o=e}if(!a)throw z.wrapError(`Could not find valid ${F.read(F.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return a}function Xa(e,t,r=new Date){const n=z.normalizeDate(r);if(null!==n){const r=io(e,t);return!(e.created<=n&&n0&&(s.keyExpirationTime=r.keyExpirationTime,s.keyNeverExpires=!1);return await to(i,[],t,s,r.date,void 0,void 0,void 0,n)}async function to(e,t,r,n,i,s,a=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const h=new wa;return Object.assign(h,n),h.publicKeyAlgorithm=r.algorithm,h.hashAlgorithm=await async function(e,t,r=new Date,n=[],i){const s=F.hash.sha256,a=i.preferredHashAlgorithm,o=await Promise.all(e.map((async(e,t)=>(await e.getPrimarySelfSignature(r,n[t],i)).preferredHashAlgorithms))),c=new Map;for(const e of o)for(const t of e)try{const e=F.write(F.hash,t);c.set(e,c.has(e)?c.get(e)+1:1)}catch{}const h=t=>0===e.length||c.get(t)===e.length||t===s,u=()=>{if(0===c.size)return s;const e=Array.from(c.keys()).filter((e=>h(e))).sort(((e,t)=>ls.hash.getHashByteLength(e)-ls.hash.getHashByteLength(t)))[0];return ls.hash.getHashByteLength(e)>=ls.hash.getHashByteLength(s)?e:s};if(new Set([F.publicKey.ecdsa,F.publicKey.eddsaLegacy,F.publicKey.ed25519,F.publicKey.ed448]).has(t.algorithm)){const e=ls.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid),r=h(a),n=ls.hash.getHashByteLength(a)>=ls.hash.getHashByteLength(e);if(r&&n)return a;{const t=u();return ls.hash.getHashByteLength(t)>=ls.hash.getHashByteLength(e)?t:e}}return h(a)?a:u()}(t,r,i,s,c),h.rawNotations=[...a],await h.sign(r,e,i,o,c),h}async function ro(e,t,r,n=new Date,i){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(n)||i&&!await i(e)||t[r].some((function(t){return z.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function no(e,t,r,n,i,s,a=new Date,o){s=s||e;const c=[];return await Promise.all(n.map((async function(e){try{if(!i||e.issuerKeyID.equals(i.issuerKeyID)){const n=![F.reasonForRevocation.keyRetired,F.reasonForRevocation.keySuperseded,F.reasonForRevocation.userIDInvalid].includes(e.reasonForRevocationFlag);await e.verify(s,t,r,n?null:a,!1,o),c.push(e.issuerKeyID)}}catch(e){}}))),i?(i.revoked=!!c.some((e=>e.equals(i.issuerKeyID)))||(i.revoked||!1),i.revoked):c.length>0}function io(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function so(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=z.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=F.write(F.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==F.curve.ed25519Legacy&&e.curve!==F.curve.curve25519Legacy&&"ed25519"!==e.curve&&"curve25519"!==e.curve||(e.curve=e.sign?F.curve.ed25519Legacy:F.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===F.curve.ed25519Legacy?F.publicKey.eddsaLegacy:F.publicKey.ecdsa:e.algorithm=F.publicKey.ecdh;break;case"curve25519":e.algorithm=e.sign?F.publicKey.ed25519:F.publicKey.x25519;break;case"curve448":e.algorithm=e.sign?F.publicKey.ed448:F.publicKey.x448;break;case"rsa":e.algorithm=F.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function ao(e,t,r){switch(e.algorithm){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:case F.publicKey.dsa:case F.publicKey.ecdsa:case F.publicKey.eddsaLegacy:case F.publicKey.ed25519:case F.publicKey.ed448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&F.keyFlags.signData);default:return!1}}function oo(e,t,r){switch(e.algorithm){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:case F.publicKey.elgamal:case F.publicKey.ecdh:case F.publicKey.x25519:case F.publicKey.x448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&F.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&F.keyFlags.encryptStorage);default:return!1}}function co(e,t,r){if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");switch(e.algorithm){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaEncrypt:case F.publicKey.elgamal:case F.publicKey.ecdh:case F.publicKey.x25519:case F.publicKey.x448:return!(!(!t.keyFlags||!!(t.keyFlags[0]&F.keyFlags.signData))||!r.allowInsecureDecryptionWithSigningKeys)||(!t.keyFlags||!!(t.keyFlags[0]&F.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&F.keyFlags.encryptStorage));default:return!1}}function ho(e,t){const r=F.write(F.publicKey,e.algorithm),n=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(n.algorithm+" keys are considered too weak.");switch(r){case F.publicKey.rsaEncryptSign:case F.publicKey.rsaSign:case F.publicKey.rsaEncrypt:if(n.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const s=await t.getSigningKey(o,e.created,void 0,n);if(e.revoked||await i.isRevoked(e,s.keyPacket,r,n))throw Error("User certificate is revoked");try{await e.verify(s.keyPacket,F.signature.certGeneric,a,r,void 0,n)}catch(e){throw z.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const n=this,i=this.selfCertifications.concat(this.otherCertifications);return Promise.all(i.map((async i=>({keyID:i.issuerKeyID,valid:await n.verifyCertificate(i,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};let s;for(let a=this.selfCertifications.length-1;a>=0;a--)try{const s=this.selfCertifications[a];if(s.revoked||await r.isRevoked(s,void 0,e,t))throw Error("Self-certification is revoked");try{await s.verify(n,F.signature.certGeneric,i,e,void 0,t)}catch(e){throw z.wrapError("Self-certification is invalid",e)}return!0}catch(e){s=e}throw s}async update(e,t,r){const n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};await ro(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(n,F.signature.certGeneric,i,t,!1,r),!0}catch(e){return!1}})),await ro(e,this,"otherCertifications",t),await ro(e,this,"revocationSignatures",t,(function(e){return no(n,F.signature.certRevocation,i,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=F.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=O){const s={userID:this.userID,userAttribute:this.userAttribute,key:e},a=new uo(s.userID||s.userAttribute,this.mainKey);return a.revocationSignatures.push(await to(s,[],e,{signatureType:F.signature.certRevocation,reasonForRevocationFlag:F.write(F.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}}class lo{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new va;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new lo(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,n=O){const i=this.mainKey.keyPacket;return no(i,F.signature.subkeyRevocation,{key:i,bind:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verify(e=new Date,t=O){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket},i=await $a(this.bindingSignatures,r,F.signature.subkeyBinding,n,e,t);if(i.revoked||await this.isRevoked(i,null,e,t))throw Error("Subkey is revoked");if(Xa(this.keyPacket,i,e))throw Error("Subkey is expired");return i}async getExpirationTime(e=new Date,t=O){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket};let i;try{i=await $a(this.bindingSignatures,r,F.signature.subkeyBinding,n,e,t)}catch(e){return null}const s=io(this.keyPacket,i),a=i.getExpirationTime();return si.bindingSignatures[t].created&&(i.bindingSignatures[t]=e),!1;try{return await e.verify(n,F.signature.subkeyBinding,s,t,void 0,r),!0}catch(e){return!1}})),await ro(e,this,"revocationSignatures",t,(function(e){return no(n,F.signature.subkeyRevocation,s,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=F.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=O){const s={key:e,bind:this.keyPacket},a=new lo(this.keyPacket,this.mainKey);return a.revocationSignatures.push(await to(s,[],e,{signatureType:F.signature.subkeyRevocation,reasonForRevocationFlag:F.write(F.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{lo.prototype[e]=function(){return this.keyPacket[e]()}}));const yo=/*#__PURE__*/z.constructAllowedPackets([wa]),fo=new Set([F.packet.publicKey,F.packet.privateKey]),go=new Set([F.packet.publicKey,F.packet.privateKey,F.packet.publicSubkey,F.packet.privateSubkey]);class po{packetListToStructure(e,t=new Set){let r,n,i,s;for(const a of e){if(a instanceof Xn){go.has(a.tag)&&!s&&(s=fo.has(a.tag)?fo:go);continue}const e=a.constructor.tag;if(s){if(!s.has(e))continue;s=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case F.packet.publicKey:case F.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=a,n=this.getKeyID(),!n)throw Error("Missing Key ID");break;case F.packet.userID:case F.packet.userAttribute:r=new uo(a,this),this.users.push(r);break;case F.packet.publicSubkey:case F.packet.secretSubkey:r=null,i=new lo(a,this),this.subkeys.push(i);break;case F.packet.signature:switch(a.signatureType){case F.signature.certGeneric:case F.signature.certPersona:case F.signature.certCasual:case F.signature.certPositive:if(!r){z.printDebug("Dropping certification signatures without preceding user packet");continue}a.issuerKeyID.equals(n)?r.selfCertifications.push(a):r.otherCertifications.push(a);break;case F.signature.certRevocation:r?r.revocationSignatures.push(a):this.directSignatures.push(a);break;case F.signature.key:this.directSignatures.push(a);break;case F.signature.subkeyBinding:if(!i){z.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}i.bindingSignatures.push(a);break;case F.signature.keyRevocation:this.revocationSignatures.push(a);break;case F.signature.subkeyRevocation:if(!i){z.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}i.revocationSignatures.push(a)}}}}toPacketList(){const e=new va;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},n=O){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{ho(i,n)}catch(e){throw z.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await $a(r.bindingSignatures,i,F.signature.subkeyBinding,e,t,n);if(!ao(r.keyPacket,s,n))continue;if(!s.embeddedSignature)throw Error("Missing embedded signature");return await $a([s.embeddedSignature],r.keyPacket,F.signature.keyBinding,e,t,n),ho(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&ao(i,s,n))return ho(i,n),this}catch(e){a=e}throw z.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),a)}async getEncryptionKey(e,t=new Date,r={},n=O){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{ho(i,n)}catch(e){throw z.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await $a(r.bindingSignatures,i,F.signature.subkeyBinding,e,t,n);if(oo(r.keyPacket,s,n))return ho(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&oo(i,s,n))return ho(i,n),this}catch(e){a=e}throw z.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),a)}async isRevoked(e,t,r=new Date,n=O){return no(this.keyPacket,F.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verifyPrimaryKey(e=new Date,t={},r=O){const n=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");if(Xa(n,await this.getPrimarySelfSignature(e,t,r),e))throw Error("Primary key is expired");if(6!==n.version){const t=await $a(this.directSignatures,n,F.signature.key,{key:n},e,r).catch((()=>{}));if(t&&Xa(n,t,e))throw Error("Primary key is expired")}}async getExpirationTime(e,t=O){let r;try{const n=await this.getPrimarySelfSignature(null,e,t),i=io(this.keyPacket,n),s=n.getExpirationTime(),a=6!==this.keyPacket.version&&await $a(this.directSignatures,this.keyPacket,F.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(a){const e=io(this.keyPacket,a);r=Math.min(i,s,e)}else r=ie.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const n=this.clone();return await ro(e,n,"revocationSignatures",t,(i=>no(n.keyPacket,F.signature.keyRevocation,n,[i],null,e.keyPacket,t,r))),await ro(e,n,"directSignatures",t),await Promise.all(e.users.map((async e=>{const i=n.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const i=n.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.subkeys.push(t)}}))),n}async getRevocationCertificate(e=new Date,t=O){const r={key:this.keyPacket},n=await $a(this.revocationSignatures,this.keyPacket,F.signature.keyRevocation,r,e,t),i=new va;i.push(n);const s=6!==this.keyPacket.version;return ie(F.armor.publicKey,i.write(),null,null,"This is a revocation certificate",s,t)}async applyRevocationCertificate(e,t=new Date,r=O){const n=await ne(e),i=(await va.fromBinary(n.data,yo,r)).findPacket(F.packet.signature);if(!i||i.signatureType!==F.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!i.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await i.verify(this.keyPacket,F.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw z.wrapError("Could not verify revocation signature",e)}const s=this.clone();return s.revocationSignatures.push(i),s}async signPrimaryUser(e,t,r,n=O){const{index:i,user:s}=await this.getPrimaryUser(t,r,n),a=await s.certify(e,t,n),o=this.clone();return o.users[i]=a,o}async signAllUsers(e,t=new Date,r=O){const n=this.clone();return n.users=await Promise.all(this.users.map((function(n){return n.certify(e,t,r)}))),n}async verifyPrimaryUser(e,t=new Date,r,n=O){const i=this.keyPacket,{user:s}=await this.getPrimaryUser(t,r,n);return e?await s.verifyAllCertifications(e,t,n):[{keyID:i.getKeyID(),valid:await s.verify(t,n).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=O){const n=this.keyPacket,i=[];return await Promise.all(this.users.map((async s=>{const a=e?await s.verifyAllCertifications(e,t,r):[{keyID:n.getKeyID(),valid:await s.verify(t,r).catch((()=>!1))}];i.push(...a.map((e=>({userID:s.userID?s.userID.userID:null,userAttribute:s.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),i}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{po.prototype[e]=lo.prototype[e]}));class Ao extends po{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([F.packet.secretKey,F.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=O){const t=6!==this.keyPacket.version;return ie(F.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}}class wo extends Ao{constructor(e){if(super(),this.packetListToStructure(e,new Set([F.packet.publicKey,F.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new va,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case F.packet.secretKey:{const t=Fa.fromSecretKeyPacket(r);e.push(t);break}case F.packet.secretSubkey:{const t=za.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new Ao(e)}armor(e=O){const t=6!==this.keyPacket.version;return ie(F.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}async getDecryptionKeys(e,t=new Date,r={},n=O){const i=this.keyPacket,s=[];let a=null;for(let r=0;re.isDecrypted()))}async validate(e=O){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=F.reasonForRevocation.noReason,string:t=""}={},r=new Date,n=O){if(!this.isPrivate())throw Error("Need private key for revoking");const i={key:this.keyPacket},s=this.clone();return s.revocationSignatures.push(await to(i,[],this.keyPacket,{signatureType:F.signature.keyRevocation,reasonForRevocationFlag:F.write(F.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,n)),s}async addSubkey(e={}){const t={...O,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}function a(){const e={};e.keyFlags=[F.keyFlags.certifyKeys|F.keyFlags.signData];const t=s([F.symmetric.aes256,F.symmetric.aes128],n.preferredSymmetricAlgorithm);if(e.preferredSymmetricAlgorithms=t,n.aeadProtect){const r=s([F.aead.gcm,F.aead.eax,F.aead.ocb],n.preferredAEADAlgorithm);e.preferredCipherSuites=r.flatMap((e=>t.map((t=>[t,e]))))}return e.preferredHashAlgorithms=s([F.hash.sha256,F.hash.sha512,F.hash.sha3_256,F.hash.sha3_512],n.preferredHashAlgorithm),e.preferredCompressionAlgorithms=s([F.compression.uncompressed,F.compression.zlib,F.compression.zip],n.preferredCompressionAlgorithm),e.features=[0],e.features[0]|=F.features.modificationDetection,n.aeadProtect&&(e.features[0]|=F.features.seipdv2),r.keyExpirationTime>0&&(e.keyExpirationTime=r.keyExpirationTime,e.keyNeverExpires=!1),e}if(i.push(e),6===e.version){const t={key:e},s=a();s.signatureType=F.signature.key;const o=await to(t,[],e,s,r.date,void 0,void 0,void 0,n);i.push(o)}await Promise.all(r.userIDs.map((async function(t,i){const s=qa.fromObject(t),o={userID:s,key:e},c=6!==e.version?a():{};c.signatureType=F.signature.certPositive,0===i&&(c.isPrimaryUserID=!0);return{userIDPacket:s,signaturePacket:await to(o,[],e,c,r.date,void 0,void 0,void 0,n)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{i.push(e),i.push(t)}))})),await Promise.all(t.map((async function(t,i){const s=r.subkeys[i];return{secretSubkeyPacket:t,subkeySignaturePacket:await eo(t,e,s,n)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{i.push(e),i.push(t)}))}));const o={key:e};return i.push(await to(o,[],e,{signatureType:F.signature.keyRevocation,reasonForRevocationFlag:F.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,n)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new wo(i)}const Eo=/*#__PURE__*/z.constructAllowedPackets([fa,Ia,La,xa,Ha,Ta,Na,ka,wa]),vo=/*#__PURE__*/z.constructAllowedPackets([Na]),Bo=/*#__PURE__*/z.constructAllowedPackets([wa]);class Io{constructor(e){this.packets=e||new va}getEncryptionKeyIDs(){const e=[];return this.packets.filterByTag(F.packet.publicKeyEncryptedSessionKey).forEach((function(t){e.push(t.publicKeyID)})),e}getSigningKeyIDs(){const e=this.unwrapCompressed(),t=e.packets.filterByTag(F.packet.onePassSignature);if(t.length>0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(F.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,n=new Date,i=O){const s=this.packets.filterByTag(F.packet.symmetricallyEncryptedData,F.packet.symEncryptedIntegrityProtectedData,F.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const a=s[0],o=a.cipherAlgorithm,c=r||await this.decryptSessionKeys(e,t,o,n,i);let h=null;const u=Promise.all(c.map((async({algorithm:e,data:t})=>{if(!z.isUint8Array(t)||!a.cipherAlgorithm&&!z.isString(e))throw Error("Invalid session key for decryption.");try{const r=a.cipherAlgorithm||F.write(F.symmetric,e);await a.decrypt(r,t,i)}catch(e){z.printDebugError(e),h=e}})));if(R(a.encrypted),a.encrypted=null,await u,!a.packets||!a.packets.length)throw h||Error("Decryption failed.");const l=new Io(a.packets);return a.packets=new va,l}async decryptSessionKeys(e,t,r,n=new Date,i=O){let s,a=[];if(t){const e=this.packets.filterByTag(F.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await va.fromBinary(e.write(),vo,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){z.printDebugError(e),e instanceof ys&&(s=e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(F.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let o;try{o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket))}catch(e){return void(s=e)}let c=[F.symmetric.aes256,F.symmetric.aes128,F.symmetric.tripledes,F.symmetric.cast5];try{const t=await e.getPrimarySelfSignature(n,void 0,i);t.preferredSymmetricAlgorithms&&(c=c.concat(t.preferredSymmetricAlgorithms))}catch(e){}await Promise.all(o.map((async function(e){if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===F.publicKey.rsaEncrypt||t.publicKeyAlgorithm===F.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===F.publicKey.rsaSign||t.publicKeyAlgorithm===F.publicKey.elgamal)){const n=t.write();await Promise.all((r?[r]:Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map((async t=>{const r=new Ta;r.read(n);const i={sessionKeyAlgorithm:t,sessionKey:ls.generateSessionKey(t)};try{await r.decrypt(e,i),a.push(r)}catch(e){z.printDebugError(e),s=e}})))}else try{await t.decrypt(e);const n=r||t.sessionKeyAlgorithm;if(n&&!c.includes(F.write(F.symmetric,n)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){z.printDebugError(e),s=e}})))}))),R(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+z.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:e.sessionKeyAlgorithm&&F.read(F.symmetric,e.sessionKeyAlgorithm)})))}throw s||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(F.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(F.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(F.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],n=O){const{symmetricAlgo:i,aeadAlgo:s}=await async function(e=[],t=new Date,r=[],n=O){const i=await Promise.all(e.map(((e,i)=>e.getPrimarySelfSignature(t,r[i],n))));if(e.length?i.every((e=>e.features&&e.features[0]&F.features.seipdv2)):n.aeadProtect){const e={symmetricAlgo:F.symmetric.aes128,aeadAlgo:F.aead.ocb},t=[{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:n.preferredAEADAlgorithm},{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:F.aead.ocb},{symmetricAlgo:F.symmetric.aes128,aeadAlgo:n.preferredAEADAlgorithm}];for(const e of t)if(i.every((t=>t.preferredCipherSuites&&t.preferredCipherSuites.some((t=>t[0]===e.symmetricAlgo&&t[1]===e.aeadAlgo)))))return e;return e}const s=F.symmetric.aes128,a=n.preferredSymmetricAlgorithm;return{symmetricAlgo:i.every((e=>e.preferredSymmetricAlgorithms&&e.preferredSymmetricAlgorithms.includes(a)))?a:s,aeadAlgo:void 0}}(e,t,r,n),a=F.read(F.symmetric,i),o=s?F.read(F.aead,s):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&(e.keyPacket.algorithm===F.publicKey.x25519||e.keyPacket.algorithm===F.publicKey.x448)&&!o&&!z.isAES(i))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:ls.generateSessionKey(i),algorithm:a,aeadAlgorithm:o}}async encrypt(e,t,r,n=!1,i=[],s=new Date,a=[],o=O){if(r){if(!z.isUint8Array(r.data)||!z.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Io.generateSessionKey(e,s,a,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Io.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:h,aeadAlgorithm:u}=r,l=await Io.encryptSessionKey(c,h,u,e,t,n,i,s,a,o),y=xa.fromObject({version:u?2:1,aeadAlgorithm:u?F.write(F.aead,u):null});y.packets=this.packets;const f=F.write(F.symmetric,h);return await y.encrypt(f,c,o),l.packets.push(y),y.packets=new va,l}static async encryptSessionKey(e,t,r,n,i,s=!1,a=[],o=new Date,c=[],h=O){const u=new va,l=F.write(F.symmetric,t),y=r&&F.write(F.aead,r);if(n){const t=await Promise.all(n.map((async function(t,r){const n=await t.getEncryptionKey(a[r],o,c,h),i=Ta.fromObject({version:y?6:3,encryptionKeyPacket:n.keyPacket,anonymousRecipient:s,sessionKey:e,sessionKeyAlgorithm:l});return await i.encrypt(n.keyPacket),delete i.sessionKey,i})));u.push(...t)}if(i){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,n=async function(e,s,a,o){const c=new Na(h);if(c.sessionKey=e,c.sessionKeyAlgorithm=s,a&&(c.aeadAlgorithm=a),await c.encrypt(o,h),h.passwordCollisionCheck){if(1!==(await Promise.all(i.map((e=>t(c,e))))).reduce(r))return n(e,s,o)}return delete c.sessionKey,c},s=await Promise.all(i.map((t=>n(e,l,y,t))));u.push(...s)}return new Io(u)}async sign(e=[],t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=O){const h=new va,u=this.packets.findPacket(F.packet.literalData);if(!u)throw Error("No literal data packet to sign.");const l=await So(u,e,t,r,n,i,s,a,o,!1,c),y=l.map(((e,t)=>ka.fromSignaturePacket(e,0===t))).reverse();return h.push(...y),h.push(u),h.push(...l),new Io(h)}compress(e,t=O){if(e===F.compression.uncompressed)return this;const r=new Ia(t);r.algorithm=e,r.packets=this.packets;const n=new va;return n.push(r),new Io(n)}async signDetached(e=[],t=[],r=null,n=[],i=[],s=new Date,a=[],o=[],c=O){const h=this.packets.findPacket(F.packet.literalData);if(!h)throw Error("No literal data packet to sign.");return new Ya(await So(h,e,t,r,n,i,s,a,o,!0,c))}async verify(e,t=new Date,r=O){const n=this.unwrapCompressed(),i=n.packets.filterByTag(F.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");y(n.packets.stream)&&n.packets.push(...await Q(n.packets.stream,(e=>e||[])));const s=n.packets.filterByTag(F.packet.onePassSignature).reverse(),a=n.packets.filterByTag(F.packet.signature);return s.length&&!a.length&&z.isStream(n.packets.stream)&&!y(n.packets.stream)?(await Promise.all(s.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=L((async()=>(await e.correspondingSig).signatureData)),e.hashed=Q(await e.hash(e.signatureType,i[0],void 0,!1)),e.hashed.catch((()=>{}))}))),n.packets.stream=K(n.packets.stream,(async(e,t)=>{const r=T(e),n=M(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await n.abort(e)}})),Ko(s,i,e,t,!1,r)):Ko(a,i,e,t,!1,r)}verifyDetached(e,t,r=new Date,n=O){const i=this.unwrapCompressed().packets.filterByTag(F.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");return Ko(e.packets.filterByTag(F.packet.signature),i,t,r,!0,n)}unwrapCompressed(){const e=this.packets.filterByTag(F.packet.compressedData);return e.length?new Io(e[0].packets):this}async appendSignature(e,t=O){await this.packets.read(z.isUint8Array(e)?e:(await ne(e)).data,Bo,t)}write(){return this.packets.write()}armor(e=O){const t=this.packets[this.packets.length-1],r=t.constructor.tag===xa.tag?2!==t.version:this.packets.some((e=>e.constructor.tag===wa.tag&&6!==e.version));return ie(F.armor.message,this.write(),null,null,null,r,e)}}async function So(e,t,r=[],n=null,i=[],s=new Date,a=[],o=[],c=[],h=!1,u=O){const l=new va,y=null===e.text?F.signature.binary:F.signature.text;if(await Promise.all(t.map((async(t,n)=>{const l=a[n];if(!t.isPrivate())throw Error("Need private key for signing");const f=await t.getSigningKey(i[n],s,l,u);return to(e,r.length?r:[t],f.keyPacket,{signatureType:y},s,o,c,h,u)}))).then((e=>{l.push(...e)})),n){const e=n.packets.filterByTag(F.packet.signature);l.push(...e)}return l}async function Ko(e,t,r,n=new Date,i=!1,s=O){return Promise.all(e.filter((function(e){return["text","binary"].includes(F.read(F.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,n=new Date,i=!1,s=O){let a,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){a=t,o=r[0];break}}const c=e instanceof ka?e.correspondingSig:e,h={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],n,i,s);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await a.getSigningKey(o.getKeyID(),r.created,void 0,s)}catch(e){if(!s.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await a.getSigningKey(o.getKeyID(),n,void 0,s)}return!0})(),signature:(async()=>{const e=await c,t=new va;return e&&t.push(e),new Ya(t)})()};return h.signature.catch((()=>{})),h.verified.catch((()=>{})),h}(e,t,r,n,i,s)})))}const Co=/*#__PURE__*/z.constructAllowedPackets([wa]);class Po{constructor(e,t){if(this.text=z.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof Ya))throw Error("Invalid signature input");this.signature=t||new Ya(new va)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=O){const h=new fa;h.setText(this.text);const u=new Ya(await So(h,e,t,r,n,i,s,a,o,!0,c));return new Po(this.text,u)}verify(e,t=new Date,r=O){const n=this.signature.packets.filterByTag(F.packet.signature),i=new fa;return i.setText(this.text),Ko(n,[i],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=O){const t=this.signature.packets.some((e=>6!==e.version)),r={hash:t?Array.from(new Set(this.signature.packets.map((e=>F.read(F.hash,e.hashAlgorithm).toUpperCase())))).join():null,text:this.text,data:this.signature.packets.write()};return ie(F.armor.signed,r,void 0,void 0,void 0,t,e)}}function Do(e){if(!(e instanceof Io))throw Error("Parameter [message] needs to be of type Message")}function Uo(e){if(!(e instanceof Po||e instanceof Io))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function xo(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Qo=Object.keys(O).length;function Ro(e){const t=Object.keys(e);if(t.length!==Qo)for(const e of t)if(void 0===O[e])throw Error("Unknown config property: "+e)}function Lo(e){return e&&!z.isArray(e)&&(e=[e]),e}async function To(e){return"array"===z.isStream(e)?Q(e):e}function Mo(e,t){e.data=K(t.packets.stream,(async(t,r)=>{await v(e.data,r,{preventClose:!0});const n=M(r);try{await Q(t,(e=>e)),await n.close()}catch(e){await n.abort(e)}}))}function No(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}function Fo(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, not "+e)}function Oo(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ho(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function zo(e,t){Oo(e);const r=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),jo=(e,t)=>e<<32-t|e>>>t,qo=(e,t)=>e<>>32-t>>>0,Vo=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jo(e){for(let r=0;r>>8&65280|t>>>24&255;var t}function Yo(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Wo(e){return"string"==typeof e&&(e=Yo(e)),Oo(e),e}function Zo(...e){let t=0;for(let r=0;re().update(Wo(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function ec(e=32){if(_o&&"function"==typeof _o.getRandomValues)return _o.getRandomValues(new Uint8Array(e));if(_o&&"function"==typeof _o.randomBytes)return _o.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}const tc=(e,t,r)=>e&t^~e&r,rc=(e,t,r)=>e&t^e&r^t&r;class nc extends $o{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){Ho(this);const{view:t,buffer:r,blockLen:n}=this,i=(e=Wo(e)).length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let e=s;e>i&s),o=Number(r&s),c=n?4:0,h=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+h,o,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const a=Go(e),o=this.outputLen;if(o%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=jo(r,17)^jo(r,19)^r>>>10;ac[e]=i+ac[e-7]+n+ac[e-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(jo(a,6)^jo(a,11)^jo(a,25))+tc(a,o,c)+ic[e]+ac[e]|0,u=(jo(r,2)^jo(r,13)^jo(r,22))+rc(r,n,i)|0;h=c,c=o,o=a,a=s+t|0,s=i,i=n,n=r,r=t+u|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(r,n,i,s,a,o,c,h)}roundClean(){ac.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class cc extends oc{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const hc=/* @__PURE__ */Xo((()=>new oc)),uc=/* @__PURE__ */Xo((()=>new cc));class lc extends $o{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.wrapConstructor");Fo(e.outputLen),Fo(e.blockLen)}(e);const r=Wo(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew lc(e,t).update(r).digest();yc.create=(e,t)=>new lc(e,t) +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const fc=/* @__PURE__ */BigInt(0),gc=/* @__PURE__ */BigInt(1),pc=/* @__PURE__ */BigInt(2);function dc(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Ac(e){if(!dc(e))throw Error("Uint8Array expected")}function wc(e,t){if("boolean"!=typeof t)throw Error(`${e} must be valid boolean, got "${t}".`)}const mc=/* @__PURE__ */Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function bc(e){Ac(e);let t="";for(let r=0;r=vc._0&&e<=vc._9?e-vc._0:e>=vc._A&&e<=vc._F?e-(vc._A-10):e>=vc._a&&e<=vc._f?e-(vc._a-10):void 0}function Ic(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t"bigint"==typeof e&&fc<=e;function Qc(e,t,r){return xc(e)&&xc(t)&&xc(r)&&t<=e&&efc;e>>=gc,t+=1);return t}const Tc=e=>(pc<new Uint8Array(e),Nc=e=>Uint8Array.from(e);function Fc(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");let n=Mc(e),i=Mc(e),s=0;const a=()=>{n.fill(1),i.fill(0),s=0},o=(...e)=>r(i,n,...e),c=(e=Mc())=>{i=o(Nc([0]),e),n=o(),0!==e.length&&(i=o(Nc([1]),e),n=o())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(a(),c(e);!(r=t(h()));)c();return a(),r}}const Oc={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||dc(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Hc(e,t,r={}){const n=(t,r,n)=>{const i=Oc[r];if("function"!=typeof i)throw Error(`Invalid validator "${r}", expected function`);const s=e[t];if(!(n&&void 0===s||i(s,e)))throw Error(`Invalid param ${t+""}=${s} (${typeof s}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function zc(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}var _c=/*#__PURE__*/Object.freeze({__proto__:null,aInRange:Rc,abool:wc,abytes:Ac,bitGet:function(e,t){return e>>BigInt(t)&gc},bitLen:Lc,bitMask:Tc,bitSet:function(e,t,r){return e|(r?gc:fc)<{throw Error("not implemented")},numberToBytesBE:Cc,numberToBytesLE:Pc,numberToHexUnpadded:kc,numberToVarBytesBE:function(e){return Ic(kc(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:Hc}); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gc=BigInt(0),jc=BigInt(1),qc=BigInt(2),Vc=BigInt(3),Jc=BigInt(4),Yc=BigInt(5),Wc=BigInt(8);function Zc(e,t){const r=e%t;return r>=Gc?r:t+r}function $c(e,t,r){if(r<=Gc||t 0");if(r===jc)return Gc;let n=jc;for(;t>Gc;)t&jc&&(n=n*e%r),e=e*e%r,t>>=jc;return n}function Xc(e,t,r){let n=e;for(;t-- >Gc;)n*=n,n%=r;return n}function eh(e,t){if(e===Gc||t<=Gc)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Zc(e,t),n=t,i=Gc,s=jc;for(;r!==Gc;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==jc)throw Error("invert: does not exist");return Zc(i,t)}function th(e){if(e%Jc===Vc){const t=(e+jc)/Jc;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}if(e%Wc===Yc){const t=(e-Yc)/Wc;return function(e,r){const n=e.mul(r,qc),i=e.pow(n,t),s=e.mul(r,i),a=e.mul(e.mul(s,qc),i),o=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),r))throw Error("Cannot find square root");return o}}return function(e){const t=(e-jc)/qc;let r,n,i;for(r=e-jc,n=0;r%qc===Gc;r/=qc,n++);for(i=qc;i 0, got "+e);const{nBitLength:i,nByteLength:s}=nh(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const a=th(e),o=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:Tc(i),ZERO:Gc,ONE:jc,create:t=>Zc(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("Invalid field element: expected bigint, got "+typeof t);return Gc<=t&&te===Gc,isOdd:e=>(e&jc)===jc,neg:t=>Zc(-t,e),eql:(e,t)=>e===t,sqr:t=>Zc(t*t,e),add:(t,r)=>Zc(t+r,e),sub:(t,r)=>Zc(t-r,e),mul:(t,r)=>Zc(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===Gc)return e.ONE;if(r===jc)return t;let n=e.ONE,i=t;for(;r>Gc;)r&jc&&(n=e.mul(n,i)),i=e.sqr(i),r>>=jc;return n}(o,e,t),div:(t,r)=>Zc(t*eh(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>eh(t,e),sqrt:n.sqrt||(e=>a(o,e)),invertBatch:e=>function(e,t){const r=Array(t.length),n=t.reduce(((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n))),e.ONE),i=e.inv(n);return t.reduceRight(((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n))),i),r}(o,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Pc(e,s):Cc(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?Kc(e):Sc(e)}});return Object.freeze(o)}function sh(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ah(e){const t=sh(e);return t+Math.ceil(t/2)} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const oh=BigInt(0),ch=BigInt(1),hh=new WeakMap,uh=new WeakMap;function lh(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`Wrong window size=${e}, should be [1..${t}]`)},i=e=>{n(e);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}};return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,i=t;for(;r>oh;)r&ch&&(n=n.add(i)),i=i.double(),r>>=ch;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=i(t),s=[];let a=e,o=a;for(let e=0;e>=y,i>o&&(i-=l,s+=ch);const a=t,f=t+Math.abs(i)-1,g=e%2!=0,p=i<0;0===i?h=h.add(r(g,n[a])):c=c.add(r(p,n[f]))}return{p:c,f:h}},wNAFCached(e,t,r){const n=uh.get(e)||1;let i=hh.get(e);return i||(i=this.precomputeWindow(e,n),1!==n&&hh.set(e,r(i))),this.wNAF(n,i,t)},setWindowSize(e,t){n(t),uh.set(e,t),hh.delete(e)}}}function yh(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw Error("wrong scalar at index "+r)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw Error("wrong point at index "+r)}));const i=Lc(BigInt(r.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<=0;t-=s){o.fill(e.ZERO);for(let e=0;e>BigInt(t)&BigInt(a));o[s]=o[s].add(r[e])}let i=e.ZERO;for(let t=o.length-1,r=e.ZERO;t>0;t--)r=r.add(o[t]),i=i.add(r);if(h=h.add(i),0!==t)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Hc(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nh(e.n,e.nBitLength),...e,p:e.Fp.ORDER})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function gh(e){void 0!==e.lowS&&wc("lowS",e.lowS),void 0!==e.prehash&&wc("prehash",e.prehash)}const{bytesToNumberBE:ph,hexToBytes:dh}=_c,Ah={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=Ah;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=kc(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?kc(i.length/2|128):"";return`${kc(e)}${s}${i}${t}`},decode(e,t){const{Err:r}=Ah;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let s=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const a=t.subarray(n,n+e);if(a.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=Ah;if(e{const i=t.toAffine();return Uc(Uint8Array.from([4]),r.toBytes(i.x),r.toBytes(i.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function a(e){const{a:n,b:i}=t,s=r.sqr(e),a=r.mul(s,e);return r.add(r.add(a,r.mul(e,n)),i)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:i,n:s}=t;if(r&&"bigint"!=typeof e){if(dc(e)&&(e=bc(e)),"string"!=typeof e||!r.includes(e.length))throw Error("Invalid key");e=e.padStart(2*n,"0")}let a;try{a="bigint"==typeof e?e:Sc(Dc("private key",e,n))}catch(t){throw Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return i&&(a=Zc(a,s)),Rc("private key",a,mh,s),a}function c(e){if(!(e instanceof l))throw Error("ProjectivePoint expected")}const h=zc(((e,t)=>{const{px:n,py:i,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),c=r.mul(i,t),h=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(h,r.ONE))throw Error("invZ was invalid");return{x:o,y:c}})),u=zc((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error("bad point: x or y not FE");const s=r.sqr(i),o=a(n);if(!r.eql(s,o))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));class l{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t))throw Error("y required");if(null==n||!r.isValid(n))throw Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error("invalid affine point");if(e instanceof l)throw Error("projective point not allowed");const i=e=>r.eql(e,r.ZERO);return i(t)&&i(n)?l.ZERO:new l(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(l.fromAffine)}static fromHex(e){const t=l.fromAffine(s(Dc("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return l.BASE.multiply(o(e))}static msm(e,t){return yh(l,n,e,t)}_setWindowSize(e){f.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:i}=this,{px:s,py:a,pz:o}=e,h=r.eql(r.mul(t,o),r.mul(s,i)),u=r.eql(r.mul(n,o),r.mul(a,i));return h&&u}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,i=r.mul(n,bh),{px:s,py:a,pz:o}=this;let c=r.ZERO,h=r.ZERO,u=r.ZERO,y=r.mul(s,s),f=r.mul(a,a),g=r.mul(o,o),p=r.mul(s,a);return p=r.add(p,p),u=r.mul(s,o),u=r.add(u,u),c=r.mul(e,u),h=r.mul(i,g),h=r.add(c,h),c=r.sub(f,h),h=r.add(f,h),h=r.mul(c,h),c=r.mul(p,c),u=r.mul(i,u),g=r.mul(e,g),p=r.sub(y,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(y,y),y=r.add(u,y),y=r.add(y,g),y=r.mul(y,p),h=r.add(h,y),g=r.mul(a,o),g=r.add(g,g),y=r.mul(g,p),c=r.sub(c,y),u=r.mul(g,f),u=r.add(u,u),u=r.add(u,u),new l(c,h,u)}add(e){c(e);const{px:n,py:i,pz:s}=this,{px:a,py:o,pz:h}=e;let u=r.ZERO,y=r.ZERO,f=r.ZERO;const g=t.a,p=r.mul(t.b,bh);let d=r.mul(n,a),A=r.mul(i,o),w=r.mul(s,h),m=r.add(n,i),b=r.add(a,o);m=r.mul(m,b),b=r.add(d,A),m=r.sub(m,b),b=r.add(n,s);let k=r.add(a,h);return b=r.mul(b,k),k=r.add(d,w),b=r.sub(b,k),k=r.add(i,s),u=r.add(o,h),k=r.mul(k,u),u=r.add(A,w),k=r.sub(k,u),f=r.mul(g,b),u=r.mul(p,w),f=r.add(u,f),u=r.sub(A,f),f=r.add(A,f),y=r.mul(u,f),A=r.add(d,d),A=r.add(A,d),w=r.mul(g,w),b=r.mul(p,b),A=r.add(A,w),w=r.sub(d,w),w=r.mul(g,w),b=r.add(b,w),d=r.mul(A,b),y=r.add(y,d),d=r.mul(k,b),u=r.mul(m,u),u=r.sub(u,d),d=r.mul(m,A),f=r.mul(k,f),f=r.add(f,d),new l(u,y,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(l.ZERO)}wNAF(e){return f.wNAFCached(this,e,l.normalizeZ)}multiplyUnsafe(e){Rc("scalar",e,wh,t.n);const n=l.ZERO;if(e===wh)return n;if(e===mh)return this;const{endo:i}=t;if(!i)return f.unsafeLadder(this,e);let{k1neg:s,k1:a,k2neg:o,k2:c}=i.splitScalar(e),h=n,u=n,y=this;for(;a>wh||c>wh;)a&mh&&(h=h.add(y)),c&mh&&(u=u.add(y)),y=y.double(),a>>=mh,c>>=mh;return s&&(h=h.negate()),o&&(u=u.negate()),u=new l(r.mul(u.px,i.beta),u.py,u.pz),h.add(u)}multiply(e){const{endo:n,n:i}=t;let s,a;if(Rc("scalar",e,mh,i),n){const{k1neg:t,k1:i,k2neg:o,k2:c}=n.splitScalar(e);let{p:h,f:u}=this.wNAF(i),{p:y,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),y=f.constTimeNegate(o,y),y=new l(r.mul(y.px,n.beta),y.py,y.pz),s=h.add(y),a=u.add(g)}else{const{p:t,f:r}=this.wNAF(e);s=t,a=r}return l.normalizeZ([s,a])[0]}multiplyAndAddUnsafe(e,t,r){const n=l.BASE,i=(e,t)=>t!==wh&&t!==mh&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=i(this,t).add(i(e,r));return s.is0()?void 0:s}toAffine(e){return h(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===mh)return!0;if(r)return r(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===mh?this:r?r(l,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return wc("isCompressed",e),this.assertValidity(),i(l,this,e)}toHex(e=!0){return wc("isCompressed",e),bc(this.toRawBytes(e))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);const y=t.nBitLength,f=lh(l,t.endo?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:o,weierstrassEquation:a,isWithinCurveOrder:function(e){return Qc(e,mh,t.n)}}}function Eh(e){const t=function(e){const t=fh(e);return Hc(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,i=r.BYTES+1,s=2*r.BYTES+1;function a(e){return Zc(e,n)}function o(e){return eh(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:l}=kh({...t,toBytes(e,t,n){const i=t.toAffine(),s=r.toBytes(i.x),a=Uc;return wc("isCompressed",n),n?a(Uint8Array.from([t.hasEvenY()?2:3]),s):a(Uint8Array.from([4]),s,r.toBytes(i.y))},fromBytes(e){const t=e.length,n=e[0],a=e.subarray(1);if(t!==i||2!==n&&3!==n){if(t===s&&4===n){return{x:r.fromBytes(a.subarray(0,r.BYTES)),y:r.fromBytes(a.subarray(r.BYTES,2*r.BYTES))}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const e=Sc(a);if(!Qc(e,mh,r.ORDER))throw Error("Point is not on curve");const t=u(e);let i;try{i=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+t)}return!(1&~n)!==((i&mh)===mh)&&(i=r.neg(i)),{x:e,y:i}}}}),y=e=>bc(Cc(e,t.nByteLength));function f(e){return e>n>>mh}const g=(e,t,r)=>Sc(e.slice(t,r));class p{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Dc("compactSignature",e,2*r),new p(g(e,0,r),g(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Ah.toSig(Dc("DER",e));return new p(t,r)}assertValidity(){Rc("r",this.r,mh,n),Rc("s",this.s,mh,n)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:i,recovery:s}=this,h=m(Dc("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+y(u)),g=o(u),p=a(-h*g),d=a(i*g),A=c.BASE.multiplyAndAddUnsafe(f,p,d);if(!A)throw Error("point at infinify");return A.assertValidity(),A}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Ic(this.toDERHex())}toDERHex(){return Ah.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ic(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}const d={isValidPrivateKey(e){try{return h(e),!0}catch(e){return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const e=ah(t.n);return function(e,t,r=!1){const n=e.length,i=sh(t),s=ah(t);if(n<16||n1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);const a=Zc(r?Sc(e):Kc(e),t-jc)+jc;return r?Pc(a,i):Cc(a,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function A(e){const t=dc(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===i||n===s:r?n===2*i||n===2*s:e instanceof c}const w=t.bits2int||function(e){const r=Sc(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},m=t.bits2int_modN||function(e){return a(w(e))},b=Tc(t.nBitLength);function k(e){return Rc("num < 2^"+t.nBitLength,e,wh,b),Cc(e,t.nByteLength)}function E(e,n,i=v){if(["recovered","canonical"].some((e=>e in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:y,prehash:g,extraEntropy:d}=i;null==y&&(y=!0),e=Dc("msgHash",e),gh(i),g&&(e=Dc("prehashed msgHash",s(e)));const A=m(e),b=h(n),E=[k(b),k(A)];if(null!=d&&!1!==d){const e=!0===d?u(r.BYTES):d;E.push(Dc("extraEntropy",e))}const B=Uc(...E),I=A;return{seed:B,k2sig:function(e){const t=w(e);if(!l(t))return;const r=o(t),n=c.BASE.multiply(t).toAffine(),i=a(n.x);if(i===wh)return;const s=a(r*a(I+i*b));if(s===wh)return;let h=(n.x===i?0:2)|Number(n.y&mh),u=s;return y&&f(s)&&(u=function(e){return f(e)?a(-e):e}(s),h^=1),new p(i,u,h)}}}const v={lowS:t.lowS,prehash:!1},B={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(A(e))throw Error("first arg must be private key");if(!A(t))throw Error("second arg must be public key");return c.fromHex(t).multiply(h(e)).toRawBytes(r)},sign:function(e,r,n=v){const{seed:i,k2sig:s}=E(e,r,n),a=t;return Fc(a.hash.outputLen,a.nByteLength,a.hmac)(i,s)},verify:function(e,r,n,i=B){const s=e;if(r=Dc("msgHash",r),n=Dc("publicKey",n),"strict"in i)throw Error("options.strict was renamed to lowS");gh(i);const{lowS:h,prehash:u}=i;let l,y;try{if("string"==typeof s||dc(s))try{l=p.fromDER(s)}catch(e){if(!(e instanceof Ah.Err))throw e;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:e,s:t}=s;l=new p(e,t)}}y=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;u&&(r=t.hash(r));const{r:f,s:g}=l,d=m(r),A=o(g),w=a(d*A),b=a(f*A),k=c.BASE.multiplyAndAddUnsafe(y,w,b)?.toAffine();return!!k&&a(k.x)===f},ProjectivePoint:c,Signature:p,utils:d}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function vh(e){return{hash:e,hmac:(t,...r)=>yc(e,t,Zo(...r)),randomBytes:ec}}function Bh(e,t){const r=t=>Eh({...e,...vh(t)});return Object.freeze({...r(t),create:r})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const Ih=ih(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Sh=Bh({a:Ih.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:Ih,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hc),Kh=/* @__PURE__ */BigInt(2**32-1),Ch=/* @__PURE__ */BigInt(32);function Ph(e,t=!1){return t?{h:Number(e&Kh),l:Number(e>>Ch&Kh)}:{h:0|Number(e>>Ch&Kh),l:0|Number(e&Kh)}}function Dh(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;ie<>>32-r,xh=(e,t,r)=>t<>>32-r,Qh=(e,t,r)=>t<>>64-r,Rh=(e,t,r)=>e<>>64-r;const Lh={fromBig:Ph,split:Dh,toBig:(e,t)=>BigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:Uh,rotlSL:xh,rotlBH:Qh,rotlBL:Rh,add:function(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,add5H:(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},[Th,Mh]=/* @__PURE__ */(()=>Lh.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),Nh=/* @__PURE__ */new Uint32Array(80),Fh=/* @__PURE__ */new Uint32Array(80);class Oh extends nc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:l,Gh:y,Gl:f,Hh:g,Hl:p}=this;return[e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p]}set(e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|l,this.Gh=0|y,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(e,t){for(let r=0;r<16;r++,t+=4)Nh[r]=e.getUint32(t),Fh[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Nh[e-15],r=0|Fh[e-15],n=Lh.rotrSH(t,r,1)^Lh.rotrSH(t,r,8)^Lh.shrSH(t,r,7),i=Lh.rotrSL(t,r,1)^Lh.rotrSL(t,r,8)^Lh.shrSL(t,r,7),s=0|Nh[e-2],a=0|Fh[e-2],o=Lh.rotrSH(s,a,19)^Lh.rotrBH(s,a,61)^Lh.shrSH(s,a,6),c=Lh.rotrSL(s,a,19)^Lh.rotrBL(s,a,61)^Lh.shrSL(s,a,6),h=Lh.add4L(i,c,Fh[e-7],Fh[e-16]),u=Lh.add4H(h,n,o,Nh[e-7],Nh[e-16]);Nh[e]=0|u,Fh[e]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:l,Fh:y,Fl:f,Gh:g,Gl:p,Hh:d,Hl:A}=this;for(let e=0;e<80;e++){const t=Lh.rotrSH(u,l,14)^Lh.rotrSH(u,l,18)^Lh.rotrBH(u,l,41),w=Lh.rotrSL(u,l,14)^Lh.rotrSL(u,l,18)^Lh.rotrBL(u,l,41),m=u&y^~u&g,b=l&f^~l&p,k=Lh.add5L(A,w,b,Mh[e],Fh[e]),E=Lh.add5H(k,d,t,m,Th[e],Nh[e]),v=0|k,B=Lh.rotrSH(r,n,28)^Lh.rotrBH(r,n,34)^Lh.rotrBH(r,n,39),I=Lh.rotrSL(r,n,28)^Lh.rotrBL(r,n,34)^Lh.rotrBL(r,n,39),S=r&i^r&a^i&a,K=n&s^n&o^s&o;d=0|g,A=0|p,g=0|y,p=0|f,y=0|u,f=0|l,({h:u,l}=Lh.add(0|c,0|h,0|E,0|v)),c=0|a,h=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const C=Lh.add3L(v,I,K);r=Lh.add3H(C,E,B,S),n=0|C}({h:r,l:n}=Lh.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Lh.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Lh.add(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:h}=Lh.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:u,l}=Lh.add(0|this.Eh,0|this.El,0|u,0|l)),({h:y,l:f}=Lh.add(0|this.Fh,0|this.Fl,0|y,0|f)),({h:g,l:p}=Lh.add(0|this.Gh,0|this.Gl,0|g,0|p)),({h:d,l:A}=Lh.add(0|this.Hh,0|this.Hl,0|d,0|A)),this.set(r,n,i,s,a,o,c,h,u,l,y,f,g,p,d,A)}roundClean(){Nh.fill(0),Fh.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Hh extends Oh{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const zh=/* @__PURE__ */Xo((()=>new Oh)),_h=/* @__PURE__ */Xo((()=>new Hh)),Gh=ih(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),jh=Bh({a:Gh.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:Gh,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},_h),qh=ih(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),Vh={a:qh.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:qh,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1)},Jh=Bh({a:Vh.a,b:Vh.b,Fp:qh,n:Vh.n,Gx:Vh.Gx,Gy:Vh.Gy,h:Vh.h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},zh),Yh=[],Wh=[],Zh=[],$h=/* @__PURE__ */BigInt(0),Xh=/* @__PURE__ */BigInt(1),eu=/* @__PURE__ */BigInt(2),tu=/* @__PURE__ */BigInt(7),ru=/* @__PURE__ */BigInt(256),nu=/* @__PURE__ */BigInt(113);for(let e=0,t=Xh,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Yh.push(2*(5*n+r)),Wh.push((e+1)*(e+2)/2%64);let i=$h;for(let e=0;e<7;e++)t=(t<>tu)*nu)%ru,t&eu&&(i^=Xh<<(Xh<r>32?Qh(e,t,r):Uh(e,t,r),ou=(e,t,r)=>r>32?Rh(e,t,r):xh(e,t,r);class cu extends $o{constructor(e,t,r,n=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Fo(r),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}keccak(){Vo||Jo(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,i=(t+2)%10,s=r[i],a=r[i+1],o=au(s,a,1)^r[n],c=ou(s,a,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=Wh[r],s=au(t,i,n),a=ou(t,i,n),o=Yh[r];t=e[o],i=e[o+1],e[o]=s,e[o+1]=a}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=iu[n],e[1]^=su[n]}r.fill(0)}(this.state32,this.rounds),Vo||Jo(this.state32),this.posOut=0,this.pos=0}update(e){Ho(this);const{blockLen:t,state:r}=this,n=(e=Wo(e)).length;for(let i=0;i=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Fo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zo(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return e||(e=new cu(t,r,n,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=s,e.destroyed=this.destroyed,e}}const hu=(e,t,r)=>Xo((()=>new cu(t,e,r))),uu=/* @__PURE__ */hu(6,136,32),lu=/* @__PURE__ */hu(6,72,64),yu=/* @__PURE__ */((e,t,r)=>function(e){const t=(t,r)=>e(r).update(Wo(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(((n={})=>new cu(t,e,void 0===n.dkLen?r:n.dkLen,!0))))(31,136,32),fu=BigInt(0),gu=BigInt(1),pu=BigInt(2),du=BigInt(8),Au={zip215:!0};function wu(e){const t=function(e){const t=fh(e);return Hc(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:i,hash:s,randomBytes:a,nByteLength:o,h:c}=t,h=pu<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:fu}}}),f=t.adjustScalarBytes||(e=>e),g=t.domain||((e,t,r)=>{if(wc("phflag",r),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function p(e,t){Rc("coordinate "+e,t,fu,h)}function d(e){if(!(e instanceof m))throw Error("ExtendedPoint expected")}const A=zc(((e,t)=>{const{ex:n,ey:i,ez:s}=e,a=e.is0();null==t&&(t=a?du:r.inv(s));const o=u(n*t),c=u(i*t),h=u(s*t);if(a)return{x:fu,y:gu};if(h!==gu)throw Error("invZ was invalid");return{x:o,y:c}})),w=zc((e=>{const{a:r,d:n}=t;if(e.is0())throw Error("bad point: ZERO");const{ex:i,ey:s,ez:a,et:o}=e,c=u(i*i),h=u(s*s),l=u(a*a),y=u(l*l),f=u(c*r);if(u(l*u(f+h))!==u(y+u(n*u(c*h))))throw Error("bad point: equation left != right (1)");if(u(i*s)!==u(a*o))throw Error("bad point: equation left != right (2)");return!0}));class m{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,p("x",e),p("y",t),p("z",r),p("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof m)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return p("x",t),p("y",r),new m(t,r,gu,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(m.fromAffine)}static msm(e,t){return yh(m,l,e,t)}_setWindowSize(e){E.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){d(e);const{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:a}=e,o=u(t*a),c=u(i*n),h=u(r*a),l=u(s*n);return o===c&&h===l}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:i}=this,s=u(r*r),a=u(n*n),o=u(pu*u(i*i)),c=u(e*s),h=r+n,l=u(u(h*h)-s-a),y=c+a,f=y-o,g=c-a,p=u(l*f),d=u(y*g),A=u(l*g),w=u(f*y);return new m(p,d,w,A)}add(e){d(e);const{a:r,d:n}=t,{ex:i,ey:s,ez:a,et:o}=this,{ex:c,ey:h,ez:l,et:y}=e;if(r===BigInt(-1)){const e=u((s-i)*(h+c)),t=u((s+i)*(h-c)),r=u(t-e);if(r===fu)return this.double();const n=u(a*pu*y),f=u(o*pu*l),g=f+n,p=t+e,d=f-n,A=u(g*r),w=u(p*d),b=u(g*d),k=u(r*p);return new m(A,w,k,b)}const f=u(i*c),g=u(s*h),p=u(o*n*y),A=u(a*l),w=u((i+s)*(c+h)-f-g),b=A-p,k=A+p,E=u(g-r*f),v=u(w*b),B=u(k*E),I=u(w*E),S=u(b*k);return new m(v,B,S,I)}subtract(e){return this.add(e.negate())}wNAF(e){return E.wNAFCached(this,e,m.normalizeZ)}multiply(e){const t=e;Rc("scalar",t,gu,n);const{p:r,f:i}=this.wNAF(t);return m.normalizeZ([r,i])[0]}multiplyUnsafe(e){const t=e;return Rc("scalar",t,fu,n),t===fu?k:this.equals(k)||t===gu?this:this.equals(b)?this.wNAF(t).p:E.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(e){return A(this,e)}clearCofactor(){const{h:e}=t;return e===gu?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:i,a:s}=t,a=r.BYTES;e=Dc("pointHex",e,a),wc("zip215",n);const o=e.slice(),c=e[a-1];o[a-1]=-129&c;const l=Kc(o),f=n?h:r.ORDER;Rc("pointHex.y",l,fu,f);const g=u(l*l),p=u(g-gu),d=u(i*g-s);let{isValid:A,value:w}=y(p,d);if(!A)throw Error("Point.fromHex: invalid y coordinate");const b=(w&gu)===gu,k=!!(128&c);if(!n&&w===fu&&k)throw Error("Point.fromHex: x=0 and x_0=1");return k!==b&&(w=u(-w)),m.fromAffine({x:w,y:l})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Pc(t,r.BYTES);return n[n.length-1]|=e&gu?128:0,n}toHex(){return bc(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,gu,u(t.Gx*t.Gy)),m.ZERO=new m(fu,gu,gu,fu);const{BASE:b,ZERO:k}=m,E=lh(m,8*o);function v(e){return Zc(e,n)}function B(e){return v(Kc(e))}function I(e){const t=o;e=Dc("private key",e,t);const r=Dc("hashed private key",s(e),2*t),n=f(r.slice(0,t)),i=r.slice(t,2*t),a=B(n),c=b.multiply(a),h=c.toRawBytes();return{head:n,prefix:i,scalar:a,point:c,pointBytes:h}}function S(e=new Uint8Array,...t){const r=Uc(...t);return B(s(g(r,Dc("context",e),!!i)))}const K=Au;b._setWindowSize(8);return{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Dc("message",e),i&&(e=i(e));const{prefix:a,scalar:c,pointBytes:h}=I(t),u=S(s.context,a,e),l=b.multiply(u).toRawBytes(),y=v(u+S(s.context,l,h,e)*c);return Rc("signature.s",y,fu,n),Dc("result",Uc(l,Pc(y,r.BYTES)),2*o)},verify:function(e,t,n,s=K){const{context:a,zip215:o}=s,c=r.BYTES;e=Dc("signature",e,2*c),t=Dc("message",t),void 0!==o&&wc("zip215",o),i&&(t=i(t));const h=Kc(e.slice(c,2*c));let u,l,y;try{u=m.fromHex(n,o),l=m.fromHex(e.slice(0,c),o),y=b.multiplyUnsafe(h)}catch(e){return!1}if(!o&&u.isSmallOrder())return!1;const f=S(a,l.toRawBytes(),u.toRawBytes(),t);return l.add(u.multiplyUnsafe(f)).subtract(y).clearCofactor().equals(m.ZERO)},ExtendedPoint:m,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>a(r.BYTES),precompute:(e=8,t=m.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const mu=BigInt(0),bu=BigInt(1);function ku(e){const t=(Hc(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,i=e=>Zc(e,n),s=t.montgomeryBits,a=Math.ceil(s/8),o=t.nByteLength,c=t.adjustScalarBytes||(e=>e),h=t.powPminus2||(e=>$c(e,n-BigInt(2),n));function u(e,t,r){const n=i(e*(t-r));return[t=i(t-n),r=i(r+n)]}const l=(t.a-BigInt(2))/BigInt(4);function y(e){return Pc(i(e),a)}function f(e,t){const r=function(e){const t=Dc("u coordinate",e,a);return 32===o&&(t[31]&=127),Kc(t)}(t),f=function(e){const t=Dc("scalar",e),r=t.length;if(r!==a&&r!==o)throw Error(`Expected ${a} or ${o} bytes, got ${r}`);return Kc(c(t))}(e),g=function(e,t){Rc("u",e,mu,n),Rc("scalar",t,mu,n);const r=t,a=e;let o,c=bu,y=mu,f=e,g=bu,p=mu;for(let e=BigInt(s-1);e>=mu;e--){const t=r>>e&bu;p^=t,o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1],p=t;const n=c+y,s=i(n*n),h=c-y,d=i(h*h),A=s-d,w=f+g,m=i((f-g)*n),b=i(w*h),k=m+b,E=m-b;f=i(k*k),g=i(a*i(E*E)),c=i(s*d),y=i(A*(s+i(l*A)))}o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1];const d=h(y);return i(c*d)}(r,f);if(g===mu)throw Error("Invalid private or public key received");return y(g)}const g=y(t.Gu);function p(e){return f(e,g)}return{scalarMult:f,scalarMultBase:p,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>p(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Eu=Xo((()=>yu.create({dkLen:114}))),vu=(Xo((()=>yu.create({dkLen:64}))),BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439")),Bu=BigInt(1),Iu=BigInt(2),Su=BigInt(3);BigInt(4);const Ku=BigInt(11),Cu=BigInt(22),Pu=BigInt(44),Du=BigInt(88),Uu=BigInt(223);function xu(e){const t=vu,r=e*e*e%t,n=r*r*e%t,i=Xc(n,Su,t)*n%t,s=Xc(i,Su,t)*n%t,a=Xc(s,Iu,t)*r%t,o=Xc(a,Ku,t)*a%t,c=Xc(o,Cu,t)*o%t,h=Xc(c,Pu,t)*c%t,u=Xc(h,Du,t)*h%t,l=Xc(u,Pu,t)*c%t,y=Xc(l,Iu,t)*r%t,f=Xc(y,Bu,t)*e%t;return Xc(f,Uu,t)*y%t}function Qu(e){return e[0]&=252,e[55]|=128,e[56]=0,e}const Ru=ih(vu,456,!0),Lu={a:BigInt(1),d:BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"),Fp:Ru,n:BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"),nBitLength:456,h:BigInt(4),Gx:BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"),Gy:BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"),hash:Eu,randomBytes:ec,adjustScalarBytes:Qu,domain:(e,t,r)=>{if(t.length>255)throw Error("Context is too big: "+t.length);return Zo(Yo("SigEd448"),new Uint8Array([r?1:0,t.length]),t,e)},uvRatio:function(e,t){const r=vu,n=Zc(e*e*t,r),i=Zc(n*e,r),s=Zc(i*n*t,r),a=Zc(i*xu(s),r),o=Zc(a*a,r);return{isValid:Zc(o*t,r)===e,value:a}}},Tu=/* @__PURE__ */wu(Lu),Mu=/* @__PURE__ */(()=>ku({a:BigInt(156326),montgomeryBits:448,nByteLength:56,P:vu,Gu:BigInt(5),powPminus2:e=>{const t=vu;return Zc(Xc(xu(e),BigInt(2),t)*e,t)},adjustScalarBytes:Qu,randomBytes:ec}))();Ru.ORDER,BigInt(3),BigInt(4),BigInt(156326),BigInt("39082"),BigInt("78163"),BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"),BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"),BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const Nu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ou=BigInt(1),Hu=BigInt(2),zu=(e,t)=>(e+t/Hu)/t;const _u=ih(Nu,void 0,void 0,{sqrt:function(e){const t=Nu,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),h=e*e*e%t,u=h*h*e%t,l=Xc(u,r,t)*u%t,y=Xc(l,r,t)*u%t,f=Xc(y,Hu,t)*h%t,g=Xc(f,i,t)*f%t,p=Xc(g,s,t)*g%t,d=Xc(p,o,t)*p%t,A=Xc(d,c,t)*d%t,w=Xc(A,o,t)*p%t,m=Xc(w,r,t)*u%t,b=Xc(m,a,t)*g%t,k=Xc(b,n,t)*h%t,E=Xc(k,Hu,t);if(!_u.eql(_u.sqr(E),e))throw Error("Cannot find square root");return E}}),Gu=Bh({a:BigInt(0),b:BigInt(7),Fp:_u,n:Fu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Fu,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ou*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,a=BigInt("0x100000000000000000000000000000000"),o=zu(s*e,t),c=zu(-n*e,t);let h=Zc(e-o*r-c*i,t),u=Zc(-o*n-c*s,t);const l=h>a,y=u>a;if(l&&(h=t-h),y&&(u=t-u),h>a||u>a)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:h,k2neg:y,k2:u}}}},hc);BigInt(0),Gu.ProjectivePoint;const ju=ih(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377")),qu=Bh({a:ju.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),b:BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),Fp:ju,n:BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),Gx:BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),Gy:BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),h:BigInt(1),lowS:!1},hc),Vu=ih(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53")),Ju=Bh({a:Vu.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),b:BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),Fp:Vu,n:BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),Gx:BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),Gy:BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),h:BigInt(1),lowS:!1},_h),Yu=ih(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3")),Wu=Bh({a:Yu.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),b:BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),Fp:Yu,n:BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),Gx:BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),Gy:BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),h:BigInt(1),lowS:!1},zh),Zu=new Map(Object.entries({nistP256:Sh,nistP384:jh,nistP521:Jh,brainpoolP256r1:qu,brainpoolP384r1:Ju,brainpoolP512r1:Wu,secp256k1:Gu,x448:Mu,ed448:Tu}));var $u=/*#__PURE__*/Object.freeze({__proto__:null,nobleCurves:Zu});function Xu(e,t,r,n,i,s){const a=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],h=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],y=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let g,p,d,A,w,m,b,k,E,v,B=0,I=t.length;const S=32===e.length?3:9;k=3===S?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e){const t=8-e.length%8;let r;if(!(t<8)){if(8===t)return e;throw Error("des: invalid padding")}r=0;const n=new Uint8Array(e.length+t);for(let t=0;t>>4^b),b^=d,m^=d<<4,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,m=m<<1|m>>>31,b=b<<1|b>>>31,p=0;p>>4|b<<28)^e[g+1],d=m,m=b,b=d^(o[A>>>24&63]|h[A>>>16&63]|l[A>>>8&63]|f[63&A]|a[w>>>24&63]|c[w>>>16&63]|u[w>>>8&63]|y[63&w]);d=m,m=b,b=d}m=m>>>1|m<<31,b=b>>>1|b<<31,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=252645135&(m>>>4^b),b^=d,m^=d<<4,K[C++]=m>>>24,K[C++]=m>>>16&255,K[C++]=m>>>8&255,K[C++]=255&m,K[C++]=b>>>24,K[C++]=b>>>16&255,K[C++]=b>>>8&255,K[C++]=255&b}return r||(K=function(e){let t,r=null;if(t=0,!r){for(r=1;e[e.length-r]===t;)r++;r--}return e.subarray(0,e.length-r)}(K)),K}function el(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],h=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],p=e.length>8?3:1,d=Array(32*p),A=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let w,m,b,k=0,E=0;for(let v=0;v>>4^v),v^=b,p^=b<<4,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=858993459&(p>>>2^v),v^=b,p^=b<<2,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=16711935&(v>>>8^p),p^=b,v^=b<<8,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=p<<8|v>>>20&240,p=v<<24|v<<8&16711680|v>>>8&65280|v>>>24&240,v=b;for(let e=0;e<16;e++)A[e]?(p=p<<2|p>>>26,v=v<<2|v>>>26):(p=p<<1|p>>>27,v=v<<1|v>>>27),p&=-15,v&=-15,w=t[p>>>28]|r[p>>>24&15]|n[p>>>20&15]|i[p>>>16&15]|s[p>>>12&15]|a[p>>>8&15]|o[p>>>4&15],m=c[v>>>28]|h[v>>>24&15]|u[v>>>20&15]|l[v>>>16&15]|y[v>>>12&15]|f[v>>>8&15]|g[v>>>4&15],b=65535&(m>>>16^w),d[E++]=w^b,d[E++]=m^b<<16}return d}function tl(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Xu(el(this.key[2]),Xu(el(this.key[1]),Xu(el(this.key[0]),e,!0),!1),!0)}}function rl(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>>16&255,t[s+6]=o>>>8&255,t[s+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>16&255,t[s+6]=o>>8&255,t[s+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const n=t+e,i=n<>>32-r;return(s[0][i>>>24]^s[1][i>>>16&255])-s[2][i>>>8&255]+s[3][255&i]}function n(e,t,r){const n=t^e,i=n<>>32-r;return s[0][i>>>24]-s[1][i>>>16&255]+s[2][i>>>8&255]^s[3][255&i]}function i(e,t,r){const n=t-e,i=n<>>32-r;return(s[0][i>>>24]+s[1][i>>>16&255]^s[2][i>>>8&255])-s[3][255&i]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const n=[,,,,,,,,],i=Array(32);let a;for(let e=0;e<4;e++)a=4*e,n[e]=r[a]<<24|r[a+1]<<16|r[a+2]<<8|r[a+3];const o=[6,7,4,5];let c,h=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(a=0;a<4;a++){const t=e[r][a];c=n[t[1]],c^=s[4][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=s[5][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=s[6][n[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=s[7][n[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=s[o[a]][n[t[6]>>>2]>>>24-8*(3&t[6])&255],n[t[0]]=c}for(a=0;a<4;a++){const e=t[r][a];c=s[4][n[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=s[5][n[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=s[6][n[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=s[7][n[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=s[4+a][n[e[4]>>>2]>>>24-8*(3&e[4])&255],i[h]=c,h++}}for(let e=0;e<16;e++)this.masking[e]=i[e],this.rotate[e]=31&i[16+e]};const s=[,,,,,,,,];s[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],s[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],s[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],s[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],s[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],s[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],s[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],s[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function nl(e){this.cast5=new rl,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}tl.keySize=tl.prototype.keySize=24,tl.blockSize=tl.prototype.blockSize=8,nl.blockSize=nl.prototype.blockSize=8,nl.keySize=nl.prototype.keySize=16;const il=4294967295;function sl(e,t){return(e<>>32-t)&il}function al(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function ol(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function cl(e,t){return e>>>8*t&255}function hl(e){this.tf=function(){let e=null,t=null,r=-1,n=[],i=[[],[],[],[]];function s(e){return i[0][cl(e,0)]^i[1][cl(e,1)]^i[2][cl(e,2)]^i[3][cl(e,3)]}function a(e){return i[0][cl(e,3)]^i[1][cl(e,0)]^i[2][cl(e,1)]^i[3][cl(e,2)]}function o(e,t){let r=s(t[0]),i=a(t[1]);t[2]=sl(t[2]^r+i+n[4*e+8]&il,31),t[3]=sl(t[3],1)^r+2*i+n[4*e+9]&il,r=s(t[2]),i=a(t[3]),t[0]=sl(t[0]^r+i+n[4*e+10]&il,31),t[1]=sl(t[1],1)^r+2*i+n[4*e+11]&il}function c(e,t){let r=s(t[0]),i=a(t[1]);t[2]=sl(t[2],1)^r+i+n[4*e+10]&il,t[3]=sl(t[3]^r+2*i+n[4*e+11]&il,31),r=s(t[2]),i=a(t[3]),t[0]=sl(t[0],1)^r+i+n[4*e+8]&il,t[1]=sl(t[1]^r+2*i+n[4*e+9]&il,31)}return{name:"twofish",blocksize:16,open:function(t){let r,s,a,o,c;e=t;const h=[],u=[],l=[];let y;const f=[];let g,p,d;const A=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],m=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],b=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],k=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],E=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],v=[[],[]],B=[[],[],[],[]];function I(e){return e^e>>2^[0,90,180,238][3&e]}function S(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function K(e,t){let r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&il|e>>>24,e=e<<8&il,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function C(e,t){const r=t>>4,n=15&t,i=A[e][r^n],s=w[e][k[n]^E[r]];return b[e][k[s]^E[i]]<<4|m[e][i^s]}function P(e,t){let r=cl(e,0),n=cl(e,1),i=cl(e,2),s=cl(e,3);switch(y){case 4:r=v[1][r]^cl(t[3],0),n=v[0][n]^cl(t[3],1),i=v[0][i]^cl(t[3],2),s=v[1][s]^cl(t[3],3);case 3:r=v[1][r]^cl(t[2],0),n=v[1][n]^cl(t[2],1),i=v[0][i]^cl(t[2],2),s=v[0][s]^cl(t[2],3);case 2:r=v[0][v[0][r]^cl(t[1],0)]^cl(t[0],0),n=v[0][v[1][n]^cl(t[1],1)]^cl(t[0],1),i=v[1][v[0][i]^cl(t[1],2)]^cl(t[0],2),s=v[1][v[1][s]^cl(t[1],3)]^cl(t[0],3)}return B[0][r]^B[1][n]^B[2][i]^B[3][s]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=al(e,r);for(r=0;r<256;r++)v[0][r]=C(0,r),v[1][r]=C(1,r);for(r=0;r<256;r++)g=v[1][r],p=I(g),d=S(g),B[0][r]=g+(p<<8)+(d<<16)+(d<<24),B[2][r]=p+(d<<8)+(g<<16)+(d<<24),g=v[0][r],p=I(g),d=S(g),B[1][r]=d+(d<<8)+(p<<16)+(g<<24),B[3][r]=p+(g<<8)+(d<<16)+(p<<24);for(y=l.length/2,r=0;r=0;e--)c(e,s);ol(t,r,s[2]^n[0]),ol(t,r+4,s[3]^n[1]),ol(t,r+8,s[0]^n[2]),ol(t,r+12,s[1]^n[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function ul(){}function ll(e){this.bf=new ul,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}hl.keySize=hl.prototype.keySize=32,hl.blockSize=hl.prototype.blockSize=16,ul.prototype.BLOCKSIZE=8,ul.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],ul.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],ul.prototype.NN=16,ul.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},ul.prototype._F=function(e){let t;const r=255&e,n=255&(e>>>=8),i=255&(e>>>=8),s=255&(e>>>=8);return t=this.sboxes[0][s]+this.sboxes[1][i],t^=this.sboxes[2][n],t+=this.sboxes[3][r],t},ul.prototype._encryptBlock=function(e){let t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},ul.prototype._decryptBlock=function(e){let t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],n=this._F(r)^n;const e=r;r=n,n=e}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},ul.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^n}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const n=[0,0];for(t=0;tnew dl)),wl=/* @__PURE__ */new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ml=/* @__PURE__ */new Uint8Array(Array(16).fill(0).map(((e,t)=>t))),bl=/* @__PURE__ */ml.map((e=>(9*e+5)%16));let kl=[ml],El=[bl];for(let e=0;e<4;e++)for(let t of[kl,El])t.push(t[e].map((e=>wl[e])));const vl=/* @__PURE__ */[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>new Uint8Array(e))),Bl=/* @__PURE__ */kl.map(((e,t)=>e.map((e=>vl[t][e])))),Il=/* @__PURE__ */El.map(((e,t)=>e.map((e=>vl[t][e])))),Sl=/* @__PURE__ */new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Kl=/* @__PURE__ */new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function Cl(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}const Pl=/* @__PURE__ */new Uint32Array(16);class Dl extends nc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)Pl[r]=e.getUint32(t,!0);let r=0|this.h0,n=r,i=0|this.h1,s=i,a=0|this.h2,o=a,c=0|this.h3,h=c,u=0|this.h4,l=u;for(let e=0;e<5;e++){const t=4-e,y=Sl[e],f=Kl[e],g=kl[e],p=El[e],d=Bl[e],A=Il[e];for(let t=0;t<16;t++){const n=qo(r+Cl(e,i,a,c)+Pl[g[t]]+y,d[t])+u|0;r=u,u=c,c=0|qo(a,10),a=i,i=n}for(let e=0;e<16;e++){const r=qo(n+Cl(t,s,o,h)+Pl[p[e]]+f,A[e])+l|0;n=l,l=h,h=0|qo(o,10),o=s,s=r}}this.set(this.h1+a+h|0,this.h2+c+l|0,this.h3+u+n|0,this.h4+r+s|0,this.h0+i+o|0)}roundClean(){Pl.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Ul=new Map(Object.entries({sha1:Al,sha224:uc,sha256:hc,sha384:_h,sha512:zh,sha3_256:uu,sha3_512:lu,ripemd160:/* @__PURE__ */Xo((()=>new Dl))}));var xl=/*#__PURE__*/Object.freeze({__proto__:null,nobleHashes:Ul});function Ql(e,t,r,n){e[t]+=r[n],e[t+1]+=r[n+1]+(e[t]>>24^h<<8,e[n+1]=h>>>24^c<<8,Ql(e,r,e,n),Ql(e,r,t,o),c=e[s]^e[r],h=e[s+1]^e[r+1],e[s]=c>>>16^h<<16,e[s+1]=h>>>16^c<<16,Ql(e,i,e,s),c=e[n]^e[i],h=e[n+1]^e[i+1],e[n]=h>>>31^c<<1,e[n+1]=c>>>31^h<<1}const Tl=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Ml=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((e=>2*e)));function Nl(e,t){const r=new Uint32Array(32),n=new Uint32Array(e.b.buffer,e.b.byteOffset,32);for(let t=0;t<16;t++)r[t]=e.h[t],r[t+16]=Tl[t];r[24]^=e.t0[0],r[25]^=e.t0[1];const i=t?4294967295:0;r[28]^=i,r[29]^=i;for(let e=0;e<12;e++){const t=e<<4;Ll(r,n,0,8,16,24,Ml[t+0],Ml[t+1]),Ll(r,n,2,10,18,26,Ml[t+2],Ml[t+3]),Ll(r,n,4,12,20,28,Ml[t+4],Ml[t+5]),Ll(r,n,6,14,22,30,Ml[t+6],Ml[t+7]),Ll(r,n,0,10,20,30,Ml[t+8],Ml[t+9]),Ll(r,n,2,12,22,24,Ml[t+10],Ml[t+11]),Ll(r,n,4,14,16,26,Ml[t+12],Ml[t+13]),Ll(r,n,6,8,18,28,Ml[t+14],Ml[t+15])}for(let t=0;t<16;t++)e.h[t]^=r[t]^r[t+16]}class Fl{constructor(e,t,r,n){const i=new Uint8Array(64);this.S={b:new Uint8Array(zl),h:new Uint32Array(Hl/4),t0:new Uint32Array(2),c:0,outlen:e},i[0]=e,t&&(i[1]=t.length),i[2]=1,i[3]=1,r&&i.set(r,32),n&&i.set(n,48);const s=new Uint32Array(i.buffer,i.byteOffset,i.length/Uint32Array.BYTES_PER_ELEMENT);for(let e=0;e<16;e++)this.S.h[e]=Tl[e]^s[e];if(t){const e=new Uint8Array(zl);e.set(t),this.update(e)}}update(e){if(!(e instanceof Uint8Array))throw Error("Input must be Uint8Array or Buffer");let t=0;for(;t>2]>>8*(3&e);return this.S.h=null,t.buffer}}function Ol(e,t,r,n){if(e>Hl)throw Error(`outlen must be at most ${Hl} (given: ${e})`);return new Fl(e,t,r,n)}const Hl=64,zl=128,_l=2,Gl=19,jl=4294967295,ql=4,Vl=4294967295,Jl=8,Yl=4294967295,Wl=8,Zl=4294967295,$l=4294967295,Xl=32,ey=1024,ty=64,ry=205===new Uint8Array(new Uint16Array([43981]).buffer)[0];function ny(e,t,r){return e[r+0]=t,e[r+1]=t>>8,e[r+2]=t>>16,e[r+3]=t>>24,e}function iy(e,t,r){if(t>Number.MAX_SAFE_INTEGER)throw Error("LE64: large numbers unsupported");let n=t;for(let t=r;t{if(tn)throw Error(`${e} size should be between ${r} and ${n} bytes`)};if(e!==_l||t!==Gl)throw Error("Unsupported type or version");return u("password",n,Wl,Yl),u("salt",i,Jl,Vl),u("tag",r,ql,jl),u("memory",c,8*o,Zl),s&&u("associated data",s,0,$l),a&&u("secret",a,0,Xl),{type:e,version:t,tagLength:r,password:n,salt:i,ad:s,secret:a,lanes:o,memorySize:c,passes:h}}({type:_l,version:Gl,...e}),{G:i,G2:s,xor:a,getLZ:o}=r.exports,c={},h={};h.G=i,h.G2=s,h.XOR=a;const u=4*n.lanes*Math.floor(n.memorySize/(4*n.lanes)),l=u*ey+10*uy;if(t.buffer.byteLength{r.set(e,n),n+=e.length})),r}(i));const s=t.digest();return new Uint8Array(s)}(n),m=u/n.lanes,b=Array(n.lanes).fill(null).map((()=>Array(m))),k=(e,t)=>(b[e][t]=d.subarray(e*m*1024+1024*t,e*m*1024+1024*t+ey),b[e][t]);for(let e=0;e0?b[i][c-1]:b[i][m-1],u=r?a.next().value:h;o(f.byteOffset,u.byteOffset,i,n.lanes,e,t,s,4,E);const l=f[0],y=f[1];0===e&&k(i,c),oy(g,h,b[l][y],e>0?p:b[i][c]),e>0&&ay(g,b[i][c],p,b[i][c])}}}const v=b[0][m-1];for(let e=1;eyy(e,{instance:n.instance,memory:r})}function py(e,t,r,n){return function(e,t){var r=WebAssembly.instantiate,n=WebAssembly.compile;return t?r(e,t):n(e)}(Buffer.from(r,"base64"),n)}var dy=/*#__PURE__*/Object.freeze({__proto__:null,default:async()=>gy((e=>py(0,0,"AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEUCIG/c4BIAkgCf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAX9USIFQSj9ywEgBUEY/c0B/VAiCCAE/c4BIAggCP0NAAECAwg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AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==",e)))}),Ay=[0,1,3,7,15,31,63,127,255],wy=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};wy.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},wy.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Ay[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var n=r-e;t|=(this.curByte&Ay[e]<>n,this.bitOffset+=e,e=0}}return t},wy.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},wy.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var my=wy,by=function(){};by.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},by.prototype.read=function(e,t,r){for(var n=0;n>>0},this.updateCRC=function(t){e=e<<8^ky[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^ky[255&(e>>>24^t)]}}),By=my,Iy=Ey,Sy=vy,Ky=function(e,t){var r,n=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=n,n},Cy={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},Py={};Py[Cy.LAST_BLOCK]="Bad file checksum",Py[Cy.NOT_BZIP_DATA]="Not bzip data",Py[Cy.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",Py[Cy.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",Py[Cy.DATA_ERROR]="Data error",Py[Cy.OUT_OF_MEMORY]="Out of memory",Py[Cy.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var Dy=function(e,t){var r=Py[e]||"unknown error";t&&(r+=": "+t);var n=new TypeError(r);throw n.errorCode=e,n},Uy=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};Uy.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Sy,!0):(this.writeCount=-1,!1)},Uy.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||Dy(Cy.NOT_BZIP_DATA,"bad magic");var n=r[3]-48;(n<1||n>9)&&Dy(Cy.NOT_BZIP_DATA,"level out of range"),this.reader=new By(e),this.dbufSize=1e5*n,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},Uy.prototype._get_next_block=function(){var e,t,r,n=this.reader,i=n.pi();if("177245385090"===i)return!1;"314159265359"!==i&&Dy(Cy.NOT_BZIP_DATA),this.targetBlockCRC=n.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,n.read(1)&&Dy(Cy.OBSOLETE_INPUT);var s=n.read(24);s>this.dbufSize&&Dy(Cy.DATA_ERROR,"initial position out of bounds");var a=n.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(a&1<<15-e){var h=16*e;for(r=n.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=h+t)}var u=n.read(3);(u<2||u>6)&&Dy(Cy.DATA_ERROR);var l=n.read(15);0===l&&Dy(Cy.DATA_ERROR);var y=new Uint8Array(256);for(e=0;e=u&&Dy(Cy.DATA_ERROR);f[e]=Ky(y,t)}var g,p=c+2,d=[];for(t=0;t20)&&Dy(Cy.DATA_ERROR),n.read(1);)n.read(1)?a--:a++;m[e]=a}for(A=w=m[0],e=1;ew?w=m[e]:m[e]=l&&Dy(Cy.DATA_ERROR),g=d[f[S++]]),e=g.minLen,t=n.read(e);e>g.maxLen&&Dy(Cy.DATA_ERROR),!(t<=g.limit[e]);e++)t=t<<1|n.read(1);((t-=g.base[e])<0||t>=258)&&Dy(Cy.DATA_ERROR);var C=g.permute[t];if(0!==C&&1!==C){if(B)for(B=0,I+a>this.dbufSize&&Dy(Cy.DATA_ERROR),E[v=o[y[0]]]+=a;a--;)K[I++]=v;if(C>c)break;I>=this.dbufSize&&Dy(Cy.DATA_ERROR),E[v=o[v=Ky(y,e=C-1)]]++,K[I++]=v}else B||(B=1,a=0),a+=0===C?B:2*B,B<<=1}for((s<0||s>=I)&&Dy(Cy.DATA_ERROR),t=0,e=0;e<256;e++)r=t+E[e],E[e]=t,t=r;for(e=0;e>=8,U=-1),this.writePos=P,this.writeCurrent=D,this.writeCount=I,this.writeRun=U,!0},Uy.prototype._read_bunzip=function(e,t){var r,n,i;if(this.writeCount<0)return 0;var s=this.dbuf,a=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var h=this.writeRun;c;){for(c--,n=o,o=255&(a=s[a]),a>>=8,3==h++?(r=o,i=n,o=-1):(r=1,i=o),this.blockCRC.updateCRCRun(i,r);r--;)this.outputStream.writeByte(i),this.nextoutput++;o!=n&&(h=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&Dy(Cy.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var xy=function(e){if("readByte"in e)return e;var t=new Iy;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},Qy=function(e){var t=new Iy,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var Ry={Bunzip:Uy,Stream:Iy,Err:Cy,decode:function(e,t,r){for(var n=xy(e),i=Qy(t),s=new Uy(n,i);!("eof"in n)||!n.eof();)if(s._init_block())s._read_bunzip();else{var a=s.reader.read(32)>>>0;if(a!==s.streamCRC&&Dy(Cy.DATA_ERROR,"Bad stream CRC (got "+s.streamCRC.toString(16)+" expected "+a.toString(16)+")"),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i)}if("getBuffer"in i)return i.getBuffer()},decodeBlock:function(e,t,r){var n=xy(e),i=Qy(r),s=new Uy(n,i);if(s.reader.seek(t),s._get_next_block()&&(s.blockCRC=new Sy,s.writeCopies=0,s._read_bunzip()),"getBuffer"in i)return i.getBuffer()},table:function(e,t,r){var n=new Iy;n.delegate=xy(e),n.pos=0,n.readByte=function(){return this.pos++,this.delegate.readByte()},n.delegate.eof&&(n.eof=n.delegate.eof.bind(n.delegate));var i=new Iy;i.pos=0,i.writeByte=function(){this.pos++};for(var s=new Uy(n,i),a=s.dbufSize;!("eof"in n)||!n.eof();){var o=8*n.pos+s.reader.bitOffset;if(s.reader.hasByte&&(o-=8),s._init_block()){var c=i.pos;s._read_bunzip(),t(o,i.pos-c)}else{if(s.reader.read(32),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i),console.assert(s.dbufSize===a,"shouldn't change block size within multistream file")}}}},Ly=/*#__PURE__*/s({__proto__:null},[Ry]);exports.AEADEncryptedDataPacket=La,exports.CleartextMessage=Po,exports.CompressedDataPacket=Ia,exports.LiteralDataPacket=fa,exports.MarkerPacket=class{static get tag(){return F.packet.marker}read(e){return 80===e[0]&&71===e[1]&&80===e[2]}write(){return new Uint8Array([80,71,80])}},exports.Message=Io,exports.OnePassSignaturePacket=ka,exports.PacketList=va,exports.PaddingPacket=class{static get tag(){return F.packet.padding}constructor(){this.padding=null}read(e){}write(){return this.padding}async createPadding(e){this.padding=await ls.random.getRandomBytes(e)}},exports.PrivateKey=wo,exports.PublicKey=Ao,exports.PublicKeyEncryptedSessionKeyPacket=Ta,exports.PublicKeyPacket=Fa,exports.PublicSubkeyPacket=za,exports.SecretKeyPacket=Ga,exports.SecretSubkeyPacket=Va,exports.Signature=Ya,exports.SignaturePacket=wa,exports.Subkey=lo,exports.SymEncryptedIntegrityProtectedDataPacket=xa,exports.SymEncryptedSessionKeyPacket=Na,exports.SymmetricallyEncryptedDataPacket=Ha,exports.TrustPacket=class{static get tag(){return F.packet.trust}read(){throw new Zn("Trust packets are not supported")}write(){throw new Zn("Trust packets are not supported")}},exports.UnparseablePacket=Xn,exports.UserAttributePacket=_a,exports.UserIDPacket=qa,exports.armor=ie,exports.config=O,exports.createCleartextMessage=async function({text:e,...t}){if(!e)throw Error("createCleartextMessage: must pass options object containing `text`");if(!z.isString(e))throw Error("createCleartextMessage: options.text must be a string");const r=Object.keys(t);if(r.length>0)throw Error("Unknown option: "+r.join(", "));return new Po(e)},exports.createMessage=async function({text:e,binary:t,filename:r,date:n=new Date,format:i=(void 0!==e?"utf8":"binary"),...s}){const a=void 0!==e?e:t;if(void 0===a)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!z.isString(e)&&!z.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!z.isUint8Array(t)&&!z.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=z.isStream(a),h=new fa(n);void 0!==e?h.setText(a,F.write(F.literal,i)):h.setBytes(a,F.write(F.literal,i)),void 0!==r&&h.setFilename(r);const u=new va;u.push(h);const l=new Io(u);return l.fromStream=c,l},exports.decrypt=async function({message:e,decryptionKeys:t,passwords:r,sessionKeys:n,verificationKeys:i,expectSigned:s=!1,format:a="utf8",signature:o=null,date:c=new Date,config:h,...u}){if(Ro(h={...O,...h}),Do(e),i=Lo(i),t=Lo(t),r=Lo(r),n=Lo(n),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(u.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));try{const u=await e.decrypt(t,r,n,c,h);i||(i=[]);const l={};if(l.signatures=o?await u.verifyDetached(o,i,c,h):await u.verify(i,c,h),l.data="binary"===a?u.getLiteralData():u.getText(),l.filename=u.getFilename(),Mo(l,e),s){if(0===i.length)throw Error("Verification keys are required to verify message signatures");if(0===l.signatures.length)throw Error("Message is not signed");l.data=E([l.data,L((async()=>{await z.anyPromise(l.signatures.map((e=>e.verified)))}))])}return l.data=await To(l.data),l}catch(e){throw z.wrapError("Error decrypting message",e)}},exports.decryptKey=async function({privateKey:e,passphrase:t,config:r,...n}){Ro(r={...O,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const s=e.clone(!0),a=z.isArray(t)?t:[t];try{return await Promise.all(s.getKeys().map((e=>z.anyPromise(a.map((t=>e.keyPacket.decrypt(t))))))),await s.validate(r),s}catch(e){throw s.clearPrivateParams(),z.wrapError("Error decrypting private key",e)}},exports.decryptSessionKeys=async function({message:e,decryptionKeys:t,passwords:r,date:n=new Date,config:i,...s}){if(Ro(i={...O,...i}),Do(e),t=Lo(t),r=Lo(r),s.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const a=Object.keys(s);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await e.decryptSessionKeys(t,r,void 0,n,i)}catch(e){throw z.wrapError("Error decrypting session keys",e)}},exports.encrypt=async function({message:e,encryptionKeys:t,signingKeys:r,passwords:n,sessionKey:i,format:s="armored",signature:a=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:h=[],date:u=new Date,signingUserIDs:l=[],encryptionUserIDs:y=[],signatureNotations:f=[],config:g,...p}){if(Ro(g={...O,...g}),Do(e),xo(s),t=Lo(t),r=Lo(r),n=Lo(n),c=Lo(c),h=Lo(h),l=Lo(l),y=Lo(y),f=Lo(f),p.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(p.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(p.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==p.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const d=Object.keys(p);if(d.length>0)throw Error("Unknown option: "+d.join(", "));r||(r=[]);try{if((r.length||a)&&(e=await e.sign(r,t,a,c,u,l,h,f,g)),e=e.compress(await async function(e=[],t=new Date,r=[],n=O){const i=F.compression.uncompressed,s=n.preferredCompressionAlgorithm,a=await Promise.all(e.map((async function(e,i){const a=(await e.getPrimarySelfSignature(t,r[i],n)).preferredCompressionAlgorithms;return!!a&&a.indexOf(s)>=0})));return a.every(Boolean)?s:i}(t,u,y,g),g),e=await e.encrypt(t,n,i,o,h,u,y,g),"object"===s)return e;const p="armored"===s?e.armor(g):e.write();return await To(p)}catch(e){throw z.wrapError("Error encrypting message",e)}},exports.encryptKey=async function({privateKey:e,passphrase:t,config:r,...n}){Ro(r={...O,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const s=e.clone(!0),a=s.getKeys(),o=z.isArray(t)?t:Array(a.length).fill(t);if(o.length!==a.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(a.map((async(e,t)=>{const{keyPacket:n}=e;await n.encrypt(o[t],r),n.clearPrivateParams()}))),s}catch(e){throw s.clearPrivateParams(),z.wrapError("Error encrypting private key",e)}},exports.encryptSessionKey=async function({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:n,passwords:i,format:s="armored",wildcard:a=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:h=[],config:u,...l}){if(Ro(u={...O,...u}),function(e){if(!z.isUint8Array(e))throw Error("Parameter [data] must be of type Uint8Array")}(e),function(e,t){if(!z.isString(e))throw Error("Parameter ["+t+"] must be of type String")}(t,"algorithm"),xo(s),n=Lo(n),i=Lo(i),o=Lo(o),h=Lo(h),l.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(!(n&&0!==n.length||i&&0!==i.length))throw Error("No encryption keys or passwords provided.");try{return No(await Io.encryptSessionKey(e,t,r,n,i,a,o,c,h,u),s,u)}catch(e){throw z.wrapError("Error encrypting session key",e)}},exports.enums=F,exports.generateKey=async function({userIDs:e=[],passphrase:t,type:r,curve:n,rsaBits:i=4096,keyExpirationTime:s=0,date:a=new Date,subkeys:o=[{}],format:c="armored",config:h,...u}){Ro(h={...O,...h}),r||n?(r=r||"ecc",n=n||"curve25519Legacy"):(r=h.v6Keys?"curve25519":"ecc",n="curve25519Legacy"),e=Lo(e);const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(0===e.length&&!h.v6Keys)throw Error("UserIDs are required for V4 keys");if("rsa"===r&&iso(e.subkeys[r],e)));let r=[Za(e,t)];r=r.concat(e.subkeys.map((e=>Wa(e,t))));const n=await Promise.all(r),i=await ko(n[0],n.slice(1),e,t),s=await i.getRevocationCertificate(e.date,t);return i.revocationSignatures=[],{key:i,revocationCertificate:s}}(y,h);return e.getKeys().forEach((({keyPacket:e})=>ho(e,h))),{privateKey:No(e,c,h),publicKey:No(e.toPublic(),c,h),revocationCertificate:t}}catch(e){throw z.wrapError("Error generating keypair",e)}},exports.generateSessionKey=async function({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:n,...i}){if(Ro(n={...O,...n}),e=Lo(e),r=Lo(r),i.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await Io.generateSessionKey(e,t,r,n)}catch(e){throw z.wrapError("Error generating session key",e)}},exports.readCleartextMessage=async function({cleartextMessage:e,config:t,...r}){if(t={...O,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!z.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const n=Object.keys(r);if(n.length>0)throw Error("Unknown option: "+n.join(", "));const i=await ne(e);if(i.type!==F.armor.signed)throw Error("No cleartext signed message.");const s=await va.fromBinary(i.data,Co,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let n=0;n{const t=e.match(/^Hash: (.+)$/);if(!t)throw Error('Only "Hash" header allowed in cleartext signed message');{const e=t[1].replace(/\s/g,"").split(",").map((e=>{try{return F.write(F.hash,e.toLowerCase())}catch(t){throw Error("Unknown hash algorithm in armor header: "+e.toLowerCase())}}));n.push(...e)}})),n.length&&!r(n))throw Error("Hash algorithm mismatch in armor header and signature")}(i.headers,s);const a=new Ya(s);return new Po(i.text,a)},exports.readKey=async function({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...O,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!z.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!z.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await ne(e);if(t!==F.armor.publicKey&&t!==F.armor.privateKey)throw Error("Armored text not of type key");s=r}else s=t;const a=await va.fromBinary(s,mo,r),o=a.indexOfTag(F.packet.publicKey,F.packet.secretKey);if(0===o.length)throw Error("No key packet found");return bo(a.slice(o[0],o[1]))},exports.readKeys=async function({armoredKeys:e,binaryKeys:t,config:r,...n}){r={...O,...r};let i=e||t;if(!i)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!z.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!z.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:t,data:r}=await ne(e);if(t!==F.armor.publicKey&&t!==F.armor.privateKey)throw Error("Armored text not of type key");i=r}const a=[],o=await va.fromBinary(i,mo,r),c=o.indexOfTag(F.packet.publicKey,F.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));const a=z.isStream(i);if(e){const{type:e,data:t}=await ne(i);if(e!==F.armor.message)throw Error("Armored text not of type message");i=t}const o=await va.fromBinary(i,Eo,r),c=new Io(o);return c.fromStream=a,c},exports.readPrivateKey=async function({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...O,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!z.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!z.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await ne(e);if(t!==F.armor.privateKey)throw Error("Armored text not of type private key");s=r}else s=t;const a=await va.fromBinary(s,mo,r),o=a.indexOfTag(F.packet.publicKey,F.packet.secretKey);for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:e,data:t}=await ne(i);if(e!==F.armor.signature)throw Error("Armored text not of type signature");i=t}const a=await va.fromBinary(i,Ja,r);return new Ya(a)},exports.reformatKey=async function({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:n=0,date:i,format:s="armored",config:a,...o}){Ro(a={...O,...a}),t=Lo(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length&&6!==e.keyPacket.version)throw Error("UserIDs are required for V4 keys");const h={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:n,date:i};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const n=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,i={key:n,bind:r},s=await $a(e.bindingSignatures,n,F.signature.subkeyBinding,i,null,t).catch((()=>({})));return{sign:s.keyFlags&&s.keyFlags[0]&F.keyFlags.signData}}))));const i=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==i.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const s=await ko(n,i,e,t),a=await s.getRevocationCertificate(e.date,t);return s.revocationSignatures=[],{key:s,revocationCertificate:a};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=z.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(h,a);return{privateKey:No(e,s,a),publicKey:No(e.toPublic(),s,a),revocationCertificate:t}}catch(e){throw z.wrapError("Error reformatting keypair",e)}},exports.revokeKey=async function({key:e,revocationCertificate:t,reasonForRevocation:r,date:n=new Date,format:i="armored",config:s,...a}){Ro(s={...O,...s});const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const a=t?await e.applyRevocationCertificate(t,n,s):await e.revoke(r,n,s);return a.isPrivate()?{privateKey:No(a,i,s),publicKey:No(a.toPublic(),i,s)}:{privateKey:null,publicKey:No(a,i,s)}}catch(e){throw z.wrapError("Error revoking key",e)}},exports.sign=async function({message:e,signingKeys:t,recipientKeys:r=[],format:n="armored",detached:i=!1,signingKeyIDs:s=[],date:a=new Date,signingUserIDs:o=[],recipientUserIDs:c=[],signatureNotations:h=[],config:u,...l}){if(Ro(u={...O,...u}),Uo(e),xo(n),t=Lo(t),s=Lo(s),o=Lo(o),r=Lo(r),c=Lo(c),h=Lo(h),l.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==l.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(e instanceof Po&&"binary"===n)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Po&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let l;if(l=i?await e.signDetached(t,r,void 0,s,a,o,c,h,u):await e.sign(t,r,void 0,s,a,o,c,h,u),"object"===n)return l;return l="armored"===n?l.armor(u):l.write(),i&&(l=K(e.packets.write(),(async(e,t)=>{await Promise.all([v(l,t),Q(e).catch((()=>{}))])}))),await To(l)}catch(e){throw z.wrapError("Error signing message",e)}},exports.unarmor=ne,exports.verify=async function({message:e,verificationKeys:t,expectSigned:r=!1,format:n="utf8",signature:i=null,date:s=new Date,config:a,...o}){if(Ro(a={...O,...a}),Uo(e),t=Lo(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Po&&"binary"===n)throw Error("Can't return cleartext message data as binary");if(e instanceof Po&&i)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=i?await e.verifyDetached(i,t,s,a):await e.verify(t,s,a),o.data="binary"===n?e.getLiteralData():e.getText(),e.fromStream&&!i&&Mo(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=E([o.data,L((async()=>{await z.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await To(o.data),o}catch(e){throw z.wrapError("Error verifying signed message",e)}}; +//# sourceMappingURL=openpgp.min.cjs.map diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.cjs.map b/app/node_modules/openpgp/dist/node/openpgp.min.cjs.map new file mode 100644 index 000000000..57e3500cd --- /dev/null +++ b/app/node_modules/openpgp/dist/node/openpgp.min.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"openpgp.min.cjs","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/enums.js","../../src/config/config.js","../../src/util.js","../../src/encoding/base64.js","../../src/encoding/armor.js","../../src/crypto/cipher/index.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@noble/ciphers/esm/_assert.js","../../node_modules/@noble/ciphers/esm/utils.js","../../node_modules/@noble/ciphers/esm/_polyval.js","../../node_modules/@noble/ciphers/esm/aes.js","../../src/crypto/mode/cfb.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../../../src/crypto/biginteger.ts","../../src/crypto/random.js","../../../../src/crypto/public_key/prime.ts","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../node_modules/@openpgp/tweetnacl/crypto.js","../../node_modules/@openpgp/tweetnacl/nacl-fast.js","../../src/type/oid.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../src/type/s2k/argon2.js","../../src/type/s2k/generic.js","../../src/type/s2k/index.js","../../node_modules/fflate/esm/index.mjs","../../src/packet/literal_data.js","../../src/type/keyid.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js","../../node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/hashes/esm/cryptoNode.js","../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_md.js","../../node_modules/@noble/hashes/esm/sha256.js","../../node_modules/@noble/hashes/esm/hmac.js","../../node_modules/@noble/curves/esm/abstract/utils.js","../../node_modules/@noble/curves/esm/abstract/modular.js","../../node_modules/@noble/curves/esm/abstract/curve.js","../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../node_modules/@noble/curves/esm/_shortw_utils.js","../../node_modules/@noble/curves/esm/p256.js","../../node_modules/@noble/hashes/esm/_u64.js","../../node_modules/@noble/hashes/esm/sha512.js","../../node_modules/@noble/curves/esm/p384.js","../../node_modules/@noble/curves/esm/p521.js","../../node_modules/@noble/hashes/esm/sha3.js","../../node_modules/@noble/curves/esm/abstract/edwards.js","../../node_modules/@noble/curves/esm/abstract/montgomery.js","../../node_modules/@noble/curves/esm/ed448.js","../../node_modules/@noble/curves/esm/secp256k1.js","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP256r1.ts","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP384r1.ts","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP512r1.ts","../../src/crypto/public_key/elliptic/noble_curves.js","../../src/crypto/cipher/des.js","../../src/crypto/cipher/cast5.js","../../src/crypto/cipher/twofish.js","../../src/crypto/cipher/blowfish.js","../../src/crypto/cipher/legacy_ciphers.js","../../node_modules/@noble/hashes/esm/sha1.js","../../node_modules/@noble/hashes/esm/ripemd160.js","../../src/crypto/hash/noble_hashes.js","../../node_modules/argon2id/lib/blake2b.js","../../node_modules/argon2id/lib/argon2id.js","../../node_modules/argon2id/lib/setup.js","../../node_modules/argon2id/index.js","../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js","../../src/packet/marker.js","../../src/packet/padding.js","../../src/packet/trust.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n Object.setPrototypeOf(this, ArrayStream.prototype);\n\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","/* eslint-disable no-prototype-builtins */\nimport { isArrayStream } from './writer.js';\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n // try and detect a node native stream without having to import its class\n if (input &&\n !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&\n typeof input._read === 'function' && typeof input._readableState === 'object') {\n throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isUint8Array, isStream, isArrayStream } from './util.js';\nimport * as streams from './streams.js';\n\nconst doneReadingSet = new WeakSet();\n/**\n * The external buffer is used to store values that have been peeked or unshifted from the original stream.\n * Because of how streams are implemented, such values cannot be \"put back\" in the original stream,\n * but they need to be returned first when reading from the input again.\n */\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = () => {};\n return;\n }\n let streamType = isStream(input);\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isStream, isArrayStream, isUint8Array, concatUint8Array } from './util.js';\nimport { Reader, externalBuffer } from './reader.js';\nimport { ArrayStream, Writer } from './writer.js';\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n }\n lastBytes = returnValue;\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input)) {\n return input.subarray(begin, end === Infinity ? input.length : end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n const cancelled = await input.cancel(reason);\n // the stream is not always cancelled at this point, so we wait some more\n await new Promise(setTimeout);\n return cancelled;\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n\nexport {\n ArrayStream,\n toStream,\n concatStream,\n concat,\n getReader,\n getWriter,\n pipe,\n transformRaw,\n transform,\n transformPair,\n parse,\n clone,\n passiveClone,\n slice,\n readToEnd,\n cancel,\n fromAsync\n};\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'nistP256': 'nistP256',\n /** @deprecated use `nistP256` instead */\n 'p256': 'nistP256',\n\n /** NIST P-384 Curve */\n 'nistP384': 'nistP384',\n /** @deprecated use `nistP384` instead */\n 'p384': 'nistP384',\n\n /** NIST P-521 Curve */\n 'nistP521': 'nistP521',\n /** @deprecated use `nistP521` instead */\n 'p521': 'nistP521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519Legacy',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519Legacy',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519Legacy',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519Legacy',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n argon2: 4,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11,\n sha3_256: 12,\n sha3_512: 14\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n gcm: 3,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n padding: 21\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuerKeyID: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34,\n preferredCipherSuites: 39\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4,\n seipdv2: 8\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha512,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * This option is applicable to:\n * - key generation (encryption key preferences),\n * - password-based message encryption, and\n * - private key encryption.\n * In the case of message encryption using public keys, the encryption key preferences are respected instead.\n * Note: not all OpenPGP implementations are compatible with this option.\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)\n * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,\n * this option must be set, otherwise key parsing and/or key decryption will fail.\n * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys\n * will be processed incorrectly.\n */\n parseAEADEncryptedV4KeysAsLegacy: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.gcm,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use v6 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v6Keys\n */\n v6Keys: false,\n /**\n * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).\n * These are non-standard entities, which in the crypto-refresh have been superseded\n * by v6 keys and v6 signatures, respectively.\n * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,\n * hence parsing them might be necessary in some cases.\n */\n enableParsingV5Entities: false,\n /**\n * S2K (String to Key) type, used for key derivation in the context of secret key encryption\n * and password-encrypted data. Weaker s2k options are not allowed.\n * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it\n * (pending standardisation).\n * @memberof module:config\n * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}\n */\n s2kType: enums.s2k.iterated,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:\n * Iteration Count Byte for Iterated and Salted S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.\n * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:\n * Argon2 parameters for S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.\n * Default settings correspond to the second recommendation from RFC9106 (\"uniformly safe option\"),\n * to ensure compatibility with memory-constrained environments.\n * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.\n * @memberof module:config\n * @property {Object} params\n * @property {Integer} params.passes - number of iterations t\n * @property {Integer} params.parallelism - degree of parallelism p\n * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.\n */\n s2kArgon2Params: {\n passes: 3,\n parallelism: 4, // lanes\n memoryExponent: 16 // 64 MiB of RAM\n },\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:\n * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL\n * (see https://efail.de/).\n * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.\n *\n * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n /**\n * Allow using keys that do not have any key flags set.\n * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages\n * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).\n * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.\n * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.\n */\n allowMissingKeyFlags: false,\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).\n * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur\n * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of\n * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.\n * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.\n */\n nonDeterministicSignaturesViaNotation: true,\n /**\n * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * @memberof module:config\n * @property {Boolean} useEllipticFallback\n */\n useEllipticFallback: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { createRequire } from 'module'; // Must be stripped in browser built\nimport enums from './enums';\nimport defaultConfig from './config';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n nodeRequire: createRequire(import.meta.url),\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n /**\n * Load noble-curves lib on demand and return the requested curve function\n * @param {enums.publicKey} publicKeyAlgo\n * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)\n * @returns curve implementation\n * @throws on unrecognized curve, or curve not implemented by noble-curve\n */\n getNobleCurve: async (publicKeyAlgo, curveName) => {\n if (!defaultConfig.useEllipticFallback) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n\n const { nobleCurves } = await import('./crypto/public_key/elliptic/noble_curves');\n switch (publicKeyAlgo) {\n case enums.publicKey.ecdh:\n case enums.publicKey.ecdsa: {\n const curve = nobleCurves.get(curveName);\n if (!curve) throw new Error('Unsupported curve');\n return curve;\n }\n case enums.publicKey.x448:\n return nobleCurves.get('x448');\n case enums.publicKey.ed448:\n return nobleCurves.get('ed448');\n default:\n throw new Error('Unsupported curve');\n }\n },\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,\n // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed\n // has not been authenticated (yet).\n // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.\n // Also, AEAD is also not affected.\n return util.readExactSubarray(bytes, 2, 2 + bytelen);\n },\n\n /**\n * Read exactly `end - start` bytes from input.\n * This is a stricter version of `.subarray`.\n * @param {Uint8Array} input - Input data to parse\n * @returns {Uint8Array} subarray of size always equal to `end - start`\n * @throws if the input array is too short.\n */\n readExactSubarray: function (input, start, end) {\n if (input.length < (end - start)) {\n throw new Error('Input array too short');\n }\n return input.subarray(start, end);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n if (bytes.length > length) {\n throw new Error('Input array too long');\n }\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const hexAlphabet = '0123456789abcdef';\n let s = '';\n bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });\n return s;\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography API.\n * @returns {Object} The SubtleCrypto API\n * @throws if the API is not available\n */\n getWebCrypto: function() {\n const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n // Fallback for Node 16, which does not expose WebCrypto as a global\n const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;\n if (!webCrypto) {\n throw new Error('The WebCrypto API is not available');\n }\n return webCrypto;\n },\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return this.nodeRequire('crypto');\n },\n\n getNodeZlib: function() {\n return this.nodeRequire('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (this.nodeRequire('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = this.nodeRequire('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n /**\n * Test email format to ensure basic compliance:\n * - must include a single @\n * - no control or space unicode chars allowed\n * - no backslash and square brackets (as the latter can mess with the userID parsing)\n * - cannot end with a punctuation char\n * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,\n * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).\n */\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^[^\\p{C}\\p{Z}@<>\\\\]+@[^\\p{C}\\p{Z}@<>\\\\]+[^\\p{C}\\p{Z}\\p{P}]$/u;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n }\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n }\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n }\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n }\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n }\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n }\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Remove the (optional) checksum from an armored message.\n * @param {String} text - OpenPGP armored message\n * @returns {String} The body of the armored message.\n * @private\n */\nfunction removeChecksum(text) {\n let body = text;\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n }\n\n return body;\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n const data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== enums.armor.signed) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === enums.armor.signed) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const body = removeChecksum(parts[0].slice(0, -1));\n await writer.write(body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum\n * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug\n // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)\n const maybeBodyClone = emitChecksum && stream.passiveClone(body);\n\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push(hash ? `Hash: ${hash}\\n\\n` : '\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","import enums from '../../enums';\n\nexport async function getLegacyCipher(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n throw new Error('Not a legacy cipher');\n case enums.symmetric.cast5:\n case enums.symmetric.blowfish:\n case enums.symmetric.twofish:\n case enums.symmetric.tripledes: {\n const { legacyCiphers } = await import('./legacy_ciphers');\n const cipher = legacyCiphers.get(algo);\n if (!cipher) {\n throw new Error('Unsupported cipher algorithm');\n }\n return cipher;\n }\n default:\n throw new Error('Unsupported cipher algorithm');\n }\n}\n\n/**\n * Get block size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherBlockSize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 16;\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n case enums.symmetric.tripledes:\n return 8;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherKeySize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n return 16;\n case enums.symmetric.aes192:\n case enums.symmetric.tripledes:\n return 24;\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 32;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get block and key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nexport function getCipherParams(algo) {\n return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };\n}\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction nobleHash(nobleHashName, webCryptoHashName) {\n const getNobleHash = async () => {\n const { nobleHashes } = await import('./noble_hashes');\n const hash = nobleHashes.get(nobleHashName);\n if (!hash) throw new Error('Unsupported hash');\n return hash;\n };\n\n return async function(data) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hash = await getNobleHash();\n\n const hashInstance = hash.create();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => hashInstance.digest());\n } else if (webCrypto && webCryptoHashName) {\n return new Uint8Array(await webCrypto.digest(webCryptoHashName, data));\n } else {\n const hash = await getNobleHash();\n\n return hash(data);\n }\n };\n}\n\nexport default {\n\n /** @see module:md5 */\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'),\n sha224: nodeHash('sha224') || nobleHash('sha224'),\n sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'),\n sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'),\n sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'),\n ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'),\n sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'),\n sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'),\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n case enums.hash.sha3_256:\n return this.sha3_256(data);\n case enums.hash.sha3_512:\n return this.sha3_512(data);\n default:\n throw new Error('Unsupported hash function');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n case enums.hash.sha3_256:\n return 32;\n case enums.hash.sha3_512:\n return 64;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, copyBytes, createView, toBytes, u32 } from './utils.js';\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\nclass GHASH {\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n this.blockLen = BLOCK_SIZE;\n this.outputLen = BLOCK_SIZE;\n this.s0 = 0;\n this.s1 = 0;\n this.s2 = 0;\n this.s3 = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\nclass Polyval extends GHASH {\n constructor(key, expectedLength) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\nfunction wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key, expectedLength) => hashCons(key, expectedLength);\n return hashC;\n}\nexport const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));\nexport const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));\n//# sourceMappingURL=_polyval.js.map","// prettier-ignore\nimport { bytes as abytes } from './_assert.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { clean, concatBytes, copyBytes, createView, equalBytes, isAligned32, setBigUint64, u32, u8, wrapCipher, } from './utils.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (dst === undefined)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n if (!isAligned32(dst))\n throw new Error('unaligned dst');\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n const out = getDst(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD == null ? 0 : AAD.length;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(aadLength * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(key);\n abytes(nonce);\n if (AAD !== undefined)\n abytes(AAD);\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\n// Private, unsafe low-level methods. Can change at any time.\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n */\n\nimport { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../../util';\nimport enums from '../../enums';\nimport { getLegacyCipher, getCipherParams } from '../cipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (nodeCrypto && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nclass WebCryptoEncryptor {\n constructor(algo, key, iv) {\n const { blockSize } = getCipherParams(algo);\n this.key = key;\n this.prevBlock = iv;\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n this.zeroBlock = new Uint8Array(this.blockSize);\n }\n\n static async isSupported(algo) {\n const { keySize } = getCipherParams(algo);\n return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])\n .then(() => true, () => false);\n }\n\n async _runCBC(plaintext, nonZeroIV) {\n const mode = 'AES-CBC';\n this.keyRef = this.keyRef || await webCrypto.importKey('raw', this.key, mode, false, ['encrypt']);\n const ciphertext = await webCrypto.encrypt(\n { name: mode, iv: nonZeroIV || this.zeroBlock },\n this.keyRef,\n plaintext\n );\n return new Uint8Array(ciphertext).subarray(0, plaintext.length);\n }\n\n async encryptChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const plaintext = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n const toEncrypt = util.concatUint8Array([\n this.prevBlock,\n plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block \"early\", since we only need to xor the plaintext and pass it over as prevBlock\n ]);\n\n const encryptedBlocks = await this._runCBC(toEncrypt);\n xorMut(encryptedBlocks, plaintext);\n this.prevBlock = encryptedBlocks.slice(-this.blockSize);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return encryptedBlocks;\n }\n\n this.i += added.length;\n let encryptedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n const curBlock = this.nextBlock;\n encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n this.prevBlock = encryptedBlock.slice();\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n encryptedBlock = new Uint8Array();\n }\n\n return encryptedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n this.nextBlock = this.nextBlock.subarray(0, this.i);\n const curBlock = this.nextBlock;\n const encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n result = encryptedBlock.subarray(0, curBlock.length);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.keyRef = null;\n this.key = null;\n }\n\n async encrypt(plaintext) {\n // plaintext is internally padded to block length before encryption\n const encryptedWithPadding = await this._runCBC(\n util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]),\n this.iv\n );\n // drop encrypted padding\n const ct = encryptedWithPadding.subarray(0, plaintext.length);\n xorMut(ct, plaintext);\n this.clearSensitiveData();\n return ct;\n }\n}\n\nclass NobleStreamProcessor {\n constructor(forEncryption, algo, key, iv) {\n this.forEncryption = forEncryption;\n const { blockSize } = getCipherParams(algo);\n this.key = nobleAesHelpers.expandKeyLE(key);\n\n if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers\n this.prevBlock = getUint32Array(iv);\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n }\n\n _runCFB(src) {\n const src32 = getUint32Array(src);\n const dst = new Uint8Array(src.length);\n const dst32 = getUint32Array(dst);\n for (let i = 0; i + 4 <= dst32.length; i += 4) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);\n }\n return dst;\n }\n\n async processChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const toProcess = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n\n const processedBlocks = this._runCFB(toProcess);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return processedBlocks;\n }\n\n this.i += added.length;\n\n let processedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n processedBlock = this._runCFB(this.nextBlock);\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n processedBlock = new Uint8Array();\n }\n\n return processedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n const processedBlock = this._runCFB(this.nextBlock);\n\n result = processedBlock.subarray(0, this.i);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.key.fill(0);\n }\n}\n\n\nasync function aesEncrypt(algo, key, pt, iv) {\n if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys\n const cfb = new WebCryptoEncryptor(algo, key, iv);\n return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);\n } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream\n const cfb = new NobleStreamProcessor(true, algo, key, iv);\n return stream.transform(pt, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).encrypt(pt);\n}\n\nasync function aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new NobleStreamProcessor(false, algo, key, iv);\n return stream.transform(ct, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).decrypt(ct);\n}\n\nfunction xorMut(a, b) {\n const aLength = Math.min(a.length, b.length);\n for (let i = 0; i < aLength; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nconst getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt) {\n return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n */\n\nimport { ctr as nobleAesCtr } from '@noble/ciphers/aes';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const keyRef = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, keyRef, pt);\n return new Uint8Array(ct);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt, iv) {\n return nobleAesCtr(key, iv).encrypt(pt);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport { getCipherParams } from '../cipher';\nimport util from '../../util';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n const { keySize } = getCipherParams(cipher);\n // sanity checks\n if (!util.isAES(cipher) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let maxNtz = 0;\n\n // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,\n // hence its execution cannot be broken up.\n // As a result, WebCrypto cannot currently be used for `encipher`.\n const aes = nobleAesCbc(key, zeroBlock, { disablePadding: true });\n const encipher = block => aes.encrypt(block);\n const decipher = block => aes.decrypt(block);\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables() {\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n */\n\nimport { gcm as nobleAesGcm } from '@noble/ciphers/aes';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages\n const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\\/13\\.\\d(\\.\\d)* Safari/) ||\n navigator.userAgent.match(/Version\\/(13|14)\\.\\d(\\.\\d)* Mobile\\/\\S* Safari/);\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && !pt.length) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n try {\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n } catch (e) {\n if (e.name === 'OperationError') {\n throw new Error('Authentication tag mismatch');\n }\n }\n }\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n },\n\n decrypt: async function(ct, iv, adata) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","// Operations are not constant time, but we try and limit timing leakage where we can\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport function uint8ArrayToBigInt(bytes: Uint8Array) {\n const hexAlphabet = '0123456789ABCDEF';\n let s = '';\n bytes.forEach(v => {\n s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];\n });\n return BigInt('0x0' + s);\n}\n\nexport function mod(a: bigint, m: bigint) {\n const reduced = a % m;\n return reduced < _0n ? reduced + m : reduced;\n}\n\n/**\n * Compute modular exponentiation using square and multiply\n * @param {BigInt} a - Base\n * @param {BigInt} e - Exponent\n * @param {BigInt} n - Modulo\n * @returns {BigInt} b ** e mod n.\n */\nexport function modExp(b: bigint, e: bigint, n: bigint) {\n if (n === _0n) throw Error('Modulo cannot be zero');\n if (n === _1n) return BigInt(0);\n if (e < _0n) throw Error('Unsopported negative exponent');\n\n let exp = e;\n let x = b;\n\n x %= n;\n let r = BigInt(1);\n while (exp > _0n) {\n const lsb = exp & _1n;\n exp >>= _1n; // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n; // Square\n }\n return r;\n}\n\n\nfunction abs(x: bigint) {\n return x >= _0n ? x : -x;\n}\n\n/**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a and b, compute (x, y) such that ax + by = gdc(a, b).\n * Negative numbers are also supported.\n * @param {BigInt} a - First operand\n * @param {BigInt} b - Second operand\n * @returns {{ gcd, x, y: bigint }}\n */\nfunction _egcd(aInput: bigint, bInput: bigint) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n // Deal with negative numbers: run algo over absolute values,\n // and \"move\" the sign to the returned x and/or y.\n // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers\n let a = abs(aInput);\n let b = abs(bInput);\n const aNegated = aInput < _0n;\n const bNegated = bInput < _0n;\n\n while (b !== _0n) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: aNegated ? -xPrev : xPrev,\n y: bNegated ? -yPrev : yPrev,\n gcd: a\n };\n}\n\n/**\n * Compute the inverse of `a` modulo `n`\n * Note: `a` and and `n` must be relatively prime\n * @param {BigInt} a\n * @param {BigInt} n - Modulo\n * @returns {BigInt} x such that a*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\nexport function modInv(a: bigint, n: bigint) {\n const { gcd, x } = _egcd(a, n);\n if (gcd !== _1n) {\n throw new Error('Inverse does not exist');\n }\n return mod(x + n, n);\n}\n\n/**\n * Compute greatest common divisor between this and n\n * @param {BigInt} aInput - Operand\n * @param {BigInt} bInput - Operand\n * @returns {BigInt} gcd\n */\nexport function gcd(aInput: bigint, bInput: bigint) {\n let a = aInput;\n let b = bInput;\n while (b !== _0n) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\n/**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\nexport function bigIntToNumber(x: bigint) {\n const number = Number(x);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n}\n\n/**\n * Get value of i-th bit\n * @param {BigInt} x\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\nexport function getBit(x:bigint, i: number) {\n const bit = (x >> BigInt(i)) & _1n;\n return bit === _0n ? 0 : 1;\n}\n\n/**\n * Compute bit length\n */\nexport function bitLength(x: bigint) {\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = x < _0n ? BigInt(-1) : _0n;\n let bitlen = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _1n) !== target) {\n bitlen++;\n }\n return bitlen;\n}\n\n/**\n * Compute byte length\n */\nexport function byteLength(x: bigint) {\n const target = x < _0n ? BigInt(-1) : _0n;\n const _8n = BigInt(8);\n let len = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _8n) !== target) {\n len++;\n }\n return len;\n}\n\n/**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\nexport function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = x.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? length - rawLength : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n */\nimport { byteLength, mod, uint8ArrayToBigInt } from './biginteger';\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto?.webcrypto;\n if (webcrypto?.getRandomValues) {\n const buf = new Uint8Array(length);\n return webcrypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n}\n\n/**\n * Create a secure random BigInt that is greater than or equal to min and less than max.\n * @param {bigint} min - Lower bound, included\n * @param {bigint} max - Upper bound, excluded\n * @returns {bigint} Random BigInt.\n * @async\n */\nexport function getRandomBigInteger(min, max) {\n if (max < min) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max - min;\n const bytes = byteLength(modulus);\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));\n return mod(r, modulus) + min;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n */\nimport { bigIntToNumber, bitLength, gcd, getBit, mod, modExp } from '../biginteger';\nimport { getRandomBigInteger } from '../random';\n\nconst _1n = BigInt(1);\n\n/**\n * Generate a probably prime random number\n * @param bits - Bit length of the prime\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function randomProbablePrime(bits: number, e: bigint, k: number) {\n const _30n = BigInt(30);\n const min = _1n << BigInt(bits - 1);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n let n = getRandomBigInteger(min, min << _1n);\n let i = bigIntToNumber(mod(n, _30n));\n\n do {\n n += BigInt(adds[i]);\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (bitLength(n) > bits) {\n n = mod(n, min << _1n); n += min;\n i = bigIntToNumber(mod(n, _30n));\n }\n } while (!isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param n - Number to test\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function isProbablePrime(n: bigint, e: bigint, k: number) {\n if (e && gcd(n - _1n, e) !== _1n) {\n return false;\n }\n if (!divisionTest(n)) {\n return false;\n }\n if (!fermat(n)) {\n return false;\n }\n if (!millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param n - Number to test\n * @param b - Optional Fermat test base\n */\nexport function fermat(n: bigint, b = BigInt(2)) {\n return modExp(b, n - _1n, n) === _1n;\n}\n\nexport function divisionTest(n: bigint) {\n const _0n = BigInt(0);\n return smallPrimes.every(m => mod(n, m) !== _0n);\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n].map(n => BigInt(n));\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param n - Number to test\n * @param k - Optional number of iterations of Miller-Rabin test\n * @param rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport function millerRabin(n: bigint, k: number, rand?: () => bigint) {\n const len = bitLength(n);\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n - _1n; // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!getBit(n1, s)) { s++; }\n const d = n >> BigInt(s);\n\n for (; k > 0; k--) {\n const a = rand ? rand() : getRandomBigInteger(BigInt(2), n1);\n\n let x = modExp(a, d, n);\n if (x === _1n || x === n1) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = mod(x * x, n);\n\n if (x === _1n) {\n return false;\n }\n if (x === n1) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n */\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\nimport { bigIntToNumber, bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\nimport hash from '../hash';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst _1n = BigInt(1);\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (hash.getHashByteLength(hashAlgo) >= n.length) {\n // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error\n // e.g. if a 512-bit RSA key is used with a SHA-512 digest.\n // The size limit is actually slightly different but here we only care about throwing\n // on common key sizes.\n throw new Error('Digest size cannot exceed key modulus size');\n }\n\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n e = BigInt(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return jwkToPrivate(jwk, e);\n } else if (util.getNodeCrypto()) {\n const opts = {\n modulusLength: bits,\n publicExponent: bigIntToNumber(e),\n publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },\n privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }\n };\n const jwk = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {\n if (err) {\n reject(err);\n } else {\n resolve(jwkPrivateKey);\n }\n });\n });\n return jwkToPrivate(jwk, e);\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = randomProbablePrime(bits - (bits >> 1), e, 40);\n p = randomProbablePrime(bits >> 1, e, 40);\n n = p * q;\n } while (bitLength(n) !== bits);\n\n const phi = (p - _1n) * (q - _1n);\n\n if (q < p) {\n [p, q] = [q, p];\n }\n\n return {\n n: bigIntToUint8Array(n),\n e: bigIntToUint8Array(e),\n d: bigIntToUint8Array(modInv(e, phi)),\n p: bigIntToUint8Array(p),\n q: bigIntToUint8Array(q),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: bigIntToUint8Array(modInv(p, q))\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n n = uint8ArrayToBigInt(n);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n\n // expect pq = n\n if ((p * q) !== n) {\n return false;\n }\n\n const _2n = BigInt(2);\n // expect p*u = 1 mod q\n u = uint8ArrayToBigInt(u);\n if (mod(p * u, q) !== BigInt(1)) {\n return false;\n }\n\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));\n const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r * d * e;\n\n const areInverses = mod(rde, p - _1n) === r && mod(rde, q - _1n) === r;\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n n = uint8ArrayToBigInt(n);\n const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));\n d = uint8ArrayToBigInt(d);\n return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n\n const jwk = await privateToJWK(n, e, d, p, q, u);\n return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n n = uint8ArrayToBigInt(n);\n s = uint8ArrayToBigInt(s);\n e = uint8ArrayToBigInt(e);\n if (s >= n) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));\n const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1' };\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n\n try {\n return verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n n = uint8ArrayToBigInt(n);\n data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));\n e = uint8ArrayToBigInt(e);\n if (data >= n) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n data = uint8ArrayToBigInt(data);\n n = uint8ArrayToBigInt(n);\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n u = uint8ArrayToBigInt(u);\n if (data >= n) {\n throw new Error('Data too large.');\n }\n const dq = mod(d, q - _1n); // d mod (q-1)\n const dp = mod(d, p - _1n); // d mod (p-1)\n\n const unblinder = getRandomBigInteger(BigInt(2), n);\n const blinder = modExp(modInv(unblinder, n), e, n);\n data = mod(data * blinder, n);\n\n const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p\n const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q\n const h = mod(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h * p + mp; // result < n due to relations above\n\n result = mod(result * unblinder, n);\n\n return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const pNum = uint8ArrayToBigInt(p);\n const qNum = uint8ArrayToBigInt(q);\n const dNum = uint8ArrayToBigInt(d);\n\n let dq = mod(dNum, qNum - _1n); // d mod (q-1)\n let dp = mod(dNum, pNum - _1n); // d mod (p-1)\n dp = bigIntToUint8Array(dp);\n dq = bigIntToUint8Array(dq);\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n\n/** Convert JWK private key to OpenPGP private key params */\nfunction jwkToPrivate(jwk, e) {\n return {\n n: b64ToUint8Array(jwk.n),\n e: bigIntToUint8Array(e),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n */\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\nconst _1n = BigInt(1);\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n const padded = emeEncode(data, byteLength(p));\n const m = uint8ArrayToBigInt(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = getRandomBigInteger(_1n, p - _1n);\n return {\n c1: bigIntToUint8Array(modExp(g, k, p)),\n c2: bigIntToUint8Array(mod(modExp(y, k, p) * m, p))\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n c1 = uint8ArrayToBigInt(c1);\n c2 = uint8ArrayToBigInt(c2);\n p = uint8ArrayToBigInt(p);\n x = uint8ArrayToBigInt(x);\n\n const padded = mod(modInv(modExp(c1, x, p), p) * c2, p);\n return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = BigInt(bitLength(p));\n const _1023n = BigInt(1023);\n if (pSize < _1023n) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (modExp(g, p - _1n, p) !== _1n) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n let i = BigInt(1);\n const _2n = BigInt(2);\n const threshold = _2n << BigInt(17); // we want order > threshold\n while (i < threshold) {\n res = mod(res * g, p);\n if (res === _1n) {\n return false;\n }\n i++;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const r = getRandomBigInteger(_2n << (pSize - _1n), _2n << pSize); // draw r of same size as p-1\n const rqx = (p - _1n) * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined;\n","import { crypto } from './crypto.js';\n\n'use strict';\nconst nacl = {};\nexport default nacl;\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n if (crypto && crypto.getRandomValues) {\n // Browsers and Node v16+\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n})();\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nconst knownOIDs = {\n '2a8648ce3d030107': enums.curve.nistP256,\n '2b81040022': enums.curve.nistP384,\n '2b81040023': enums.curve.nistP521,\n '2b8104000a': enums.curve.secp256k1,\n '2b06010401da470f01': enums.curve.ed25519Legacy,\n '2b060104019755010501': enums.curve.curve25519Legacy,\n '2b2403030208010107': enums.curve.brainpoolP256r1,\n '2b240303020801010b': enums.curve.brainpoolP384r1,\n '2b240303020801010d': enums.curve.brainpoolP512r1\n};\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {enums.curve} String with the canonical name of the curve\n * @throws if unknown\n */\n getName() {\n const name = knownOIDs[this.toHex()];\n if (!name) {\n throw new Error('Unknown curve object identifier.');\n }\n\n return name;\n }\n}\n\nexport default OID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\n// unknown packet types are handled differently depending on the packet criticality\nexport class UnknownPacketError extends UnsupportedError {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnknownPacketError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n */\n\nimport ed25519 from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\nimport { b64ToUint8Array, uint8ArrayToB64 } from '../../../encoding/base64';\n\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n A: new Uint8Array(b64ToUint8Array(publicKey.x)),\n seed: b64ToUint8Array(privateKey.d, true)\n };\n } catch (err) {\n if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux\n throw err;\n }\n const seed = getRandomBytes(getPayloadSize(algo));\n const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const seed = ed448.utils.randomPrivateKey();\n const A = ed448.getPublicKey(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = privateKeyToJWK(algo, publicKey, privateKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);\n\n const signature = new Uint8Array(\n await webCrypto.sign('Ed25519', key, hashed)\n );\n\n return { RS: signature };\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = ed25519.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const signature = ed448.sign(hashed, privateKey);\n return { RS: signature };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = publicKeyToJWK(algo, publicKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);\n const verified = await webCrypto.verify('Ed25519', key, RS, hashed);\n return verified;\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n return ed25519.sign.detached.verify(hashed, RS, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n return ed448.verify(RS, hashed, publicKey);\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented\n */\n const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n\n const publicKey = ed448.getPublicKey(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n default:\n return false;\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return 32;\n\n case enums.publicKey.ed448:\n return 57;\n\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n case enums.publicKey.ed448:\n return enums.hash.sha512;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n\nconst publicKeyToJWK = (algo, publicKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = {\n kty: 'OKP',\n crv: 'Ed25519',\n x: uint8ArrayToB64(publicKey, true),\n ext: true\n };\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n\nconst privateKeyToJWK = (algo, publicKey, privateKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = publicKeyToJWK(algo, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n */\n\nimport { aeskw as nobleAesKW } from '@noble/ciphers/aes';\nimport { getCipherParams } from './cipher';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n/**\n * AES key wrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} dataToWrap\n * @returns {Uint8Array} wrapped key\n */\nexport async function wrap(algo, key, dataToWrap) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n try {\n const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);\n // Import data as HMAC key, as it has no key length requirements\n const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });\n return new Uint8Array(wrapped);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n\n return nobleAesKW(key).encrypt(dataToWrap);\n}\n\n/**\n * AES key unwrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} wrappedData\n * @returns {Uint8Array} unwrapped data\n */\nexport async function unwrap(algo, key, wrappedData) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let wrappingKey;\n try {\n wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n return nobleAesKW(key).decrypt(wrappedData);\n }\n\n try {\n const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));\n } catch (err) {\n if (err.name === 'OperationError') {\n throw new Error('Key Data Integrity failed');\n }\n throw err;\n }\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n\nexport default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport x25519 from '@openpgp/tweetnacl';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport computeHKDF from '../../hkdf';\nimport { getCipherParams } from '../../cipher';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519'),\n x448: util.encodeUTF8('OpenPGP X448')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = x25519.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const k = x448.utils.randomPrivateKey();\n const A = x448.getPublicKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = x25519.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const publicKey = x448.getPublicKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.x25519:\n return 32;\n\n case enums.publicKey.x448:\n return 56;\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Generate shared secret and ephemeral public key for encryption\n * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret\n * @async\n */\nexport async function generateEphemeralEncryptionMaterial(algo, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo));\n const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const { publicKey: ephemeralPublicKey } = x25519.box.keyPair.fromSecretKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const ephemeralSecretKey = x448.utils.randomPrivateKey();\n const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * x25519 and x448 produce an all-zero value when given as input a point with small order.\n * This does not lead to a security issue in the context of ECDH, but it is still unexpected,\n * hence we throw.\n * @param {Uint8Array} sharedSecret\n */\nfunction assertNonZeroArray(sharedSecret) {\n let acc = 0;\n for (let i = 0; i < sharedSecret.length; i++) {\n acc |= sharedSecret[i];\n }\n if (acc === 0) {\n throw new Error('Unexpected low order point');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n */\nimport nacl from '@openpgp/tweetnacl';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { UnsupportedError } from '../../../packet/packet';\nimport { generate as eddsaGenerate } from './eddsa';\nimport { generate as ecdhXGenerate } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n [enums.curve.nistP256]: 'P-256',\n [enums.curve.nistP384]: 'P-384',\n [enums.curve.nistP521]: 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,\n [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n [enums.curve.nistP256]: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.nistP256],\n web: webCurves[enums.curve.nistP256],\n payloadSize: 32,\n sharedSize: 256,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP384]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.nistP384],\n web: webCurves[enums.curve.nistP384],\n payloadSize: 48,\n sharedSize: 384,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP521]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.nistP521],\n web: webCurves[enums.curve.nistP521],\n payloadSize: 66,\n sharedSize: 528,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.secp256k1]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.secp256k1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.ed25519Legacy]: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.curve25519Legacy]: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.brainpoolP256r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.brainpoolP256r1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP384r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.brainpoolP384r1],\n payloadSize: 48,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP512r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.brainpoolP512r1],\n payloadSize: 64,\n wireFormatLeadingByte: 0x04\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName) {\n try {\n this.name = oidOrName instanceof OID ?\n oidOrName.getName() :\n enums.write(enums.curve,oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n const params = curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node;\n this.web = params.web;\n this.payloadSize = params.payloadSize;\n this.sharedSize = params.sharedSize;\n this.wireFormatLeadingByte = params.wireFormatLeadingByte;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === enums.curve.curve25519Legacy) {\n this.type = 'curve25519Legacy';\n } else if (this.name === enums.curve.ed25519Legacy) {\n this.type = 'ed25519Legacy';\n }\n }\n\n async genKeyPair() {\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name, this.wireFormatLeadingByte);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n return jsGenKeyPair(this.name);\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519Legacy': {\n // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3\n const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);\n const privateKey = k.slice().reverse();\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n case 'ed25519Legacy': {\n const { seed: privateKey, A } = await eddsaGenerate(enums.publicKey.ed25519);\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n default:\n return jsGenKeyPair(this.name);\n }\n }\n}\n\nasync function generate(curveName) {\n const curve = new CurveWithOID(curveName);\n const { oid, hash, cipher } = curve;\n const keyPair = await curve.genKeyPair();\n return {\n oid,\n Q: keyPair.publicKey,\n secret: util.leftPad(keyPair.privateKey, curve.payloadSize),\n hash,\n cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[oid.getName()].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n [enums.curve.nistP256]: true,\n [enums.curve.nistP384]: true,\n [enums.curve.nistP521]: true,\n [enums.curve.secp256k1]: true,\n [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,\n [enums.curve.brainpoolP256r1]: true,\n [enums.curve.brainpoolP384r1]: true,\n [enums.curve.brainpoolP512r1]: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === enums.curve.curve25519Legacy) {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n /*\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = nobleCurve.getPublicKey(d, false);\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check whether the public point has a valid encoding.\n * NB: this function does not check e.g. whether the point belongs to the curve.\n */\nfunction checkPublicPointEnconding(curve, V) {\n const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;\n\n const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;\n\n if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {\n throw new Error('Invalid point encoding');\n }\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\nasync function jsGenKeyPair(name) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n const privateKey = nobleCurve.utils.randomPrivateKey();\n const publicKey = nobleCurve.getPublicKey(privateKey, false);\n return { publicKey, privateKey };\n}\n\nasync function webGenKeyPair(name, wireFormatLeadingByte) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk, wireFormatLeadingByte) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = wireFormatLeadingByte;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams, nodeCurves, checkPublicPointEnconding } from './oid_curves';\nimport { bigIntToUint8Array } from '../../biginteger';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web':\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n case 'node':\n return nodeSign(curve, hashAlgo, message, privateKey);\n }\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });\n return {\n r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),\n s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)\n };\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n // See https://github.com/openpgpjs/openpgpjs/pull/948.\n // NB: the impact was more likely limited to Brainpool curves, since thanks\n // to WebCrypto availability, NIST curve should not have been affected.\n // Similarly, secp256k1 should have been used rarely enough.\n // However, we implement the fix for all curves, since it's only needed in case of\n // verification failure, which is unexpected, hence a minor slowdown is acceptable.\n const tryFallbackVerificationForOldBug = async () => (\n hashed[0] === 0 ?\n jsVerify(curve, signature, hashed.subarray(1), publicKey) :\n false\n );\n\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node': {\n const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n }\n }\n }\n\n const verified = await jsVerify(curve, signature, hashed, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n // eslint-disable-next-line @typescript-eslint/return-await\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Fallback javascript implementation of ECDSA verification.\n * To be used if no native implementation is available for the given curve/operation.\n */\nasync function jsVerify(curve, signature, hashed, publicKey) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, privateKey) {\n // JWT encoding cannot be used for now, as Brainpool curves are not supported\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n privateKey: nodeBuffer.from(privateKey)\n });\n\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n\n const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));\n const len = curve.payloadSize;\n\n return {\n r: signature.subarray(0, len),\n s: signature.subarray(len, len << 1)\n };\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { publicKey: derPublicKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n publicKey: nodeBuffer.from(publicKey)\n });\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n\n const signature = util.concatUint8Array([r, s]);\n\n try {\n return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);\n } catch (err) {\n return false;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n */\n\nimport nacl from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { CurveWithOID, checkPublicPointEnconding } from './oid_curves';\nimport { sign as eddsaSign, verify as eddsaVerify } from './eddsa';\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const { RS: signature } = await eddsaSign(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const RS = util.concatUint8Array([r, s]);\n return eddsaVerify(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { getCipherParams } from '../../cipher';\nimport { generateEphemeralEncryptionMaterial as ecdhXGenerateEphemeralEncryptionMaterial, recomputeSharedSecret as ecdhXRecomputeSharedSecret } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519Legacy': {\n const { sharedSecret: sharedKey, ephemeralPublicKey } = await ecdhXGenerateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));\n const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n return jsPublicEphemeralKey(curve, Q);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n default:\n return jsPublicEphemeralKey(curve, Q);\n\n }\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = await aesKW.wrap(kdfParams.cipher, Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519Legacy': {\n const secretKey = d.slice().reverse();\n const sharedKey = await ecdhXRecomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n return jsPrivateEphemeralKey(curve, V, d);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n default:\n return jsPrivateEphemeralKey(curve, V, d);\n }\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n checkPublicPointEnconding(curve, V);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(await aesKW.unwrap(kdfParams.cipher, Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\nasync function jsPrivateEphemeralKey(curve, V, d) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { secretKey: d, sharedKey };\n}\n\nasync function jsPublicEphemeralKey(curve, Q) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n const { publicKey: V, privateKey: v } = await curve.genKeyPair();\n\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { publicKey: V, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: sender\n },\n privateKey,\n curve.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const _0n = BigInt(0);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n x = uint8ArrayToBigInt(x);\n\n let k;\n let r;\n let s;\n let t;\n g = mod(g, p);\n x = mod(x, q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = getRandomBigInteger(_1n, q); // returns in [1, q-1]\n r = mod(modExp(g, k, p), q); // (g**k mod p) mod q\n if (r === _0n) {\n continue;\n }\n const xr = mod(x * r, q);\n t = mod(h + xr, q); // H(m) + x*r mod q\n s = mod(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q\n if (s === _0n) {\n continue;\n }\n break;\n }\n return {\n r: bigIntToUint8Array(r, 'be', byteLength(p)),\n s: bigIntToUint8Array(s, 'be', byteLength(p))\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n r = uint8ArrayToBigInt(r);\n s = uint8ArrayToBigInt(s);\n\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n if (r <= _0n || r >= q ||\n s <= _0n || s >= q) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n const w = modInv(s, q); // s**-1 mod q\n if (w === _0n) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = mod(g, p);\n y = mod(y, p);\n const u1 = mod(h * w, q); // H(m) * w mod q\n const u2 = mod(r * w, q); // r * w mod q\n const t1 = modExp(g, u1, p); // g**u1 mod p\n const t2 = modExp(y, u2, p); // y**u2 mod p\n const v = mod(mod(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q\n return v === r;\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (mod(p - _1n, q) !== _0n) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (modExp(g, q, p) !== _1n) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = BigInt(bitLength(q));\n const _150n = BigInt(150);\n if (qSize < _150n || !isProbablePrime(q, null, 32)) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const _2n = BigInt(2);\n const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q\n const rqx = q * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n */\n\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { read, signatureParams: { s } };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n // If the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature\n // verification: if the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n // Algorithm-Specific Fields for Ed448 signatures:\n // - 114 octets of the native signature\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo);\n const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length;\n return { read, signatureParams: { RS } };\n }\n\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal:\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport { getCipherParams } from './cipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n if (symmetricAlgo && !util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 and X448 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (C.algorithm !== null && !util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const payloadSize = getCurvePayloadSize(algo);\n const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const payloadSize = getCurvePayloadSize(algo);\n const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 or X448 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const pointSize = getCurvePayloadSize(algo);\n const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([\n enums.publicKey.ed25519,\n enums.publicKey.x25519,\n enums.publicKey.ed448,\n enums.publicKey.x448\n ]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipherParams(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipherParams(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get encoded secret size for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getCurvePayloadSize(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh:\n case enums.publicKey.eddsaLegacy:\n return new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPayloadSize(algo);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.getPayloadSize(algo);\n default:\n throw new Error('Unknown elliptic algo');\n }\n}\n\n/**\n * Get preferred signing hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n\n\nexport { getCipherParams };\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","import defaultConfig from '../../config';\nimport enums from '../../enums';\nimport util from '../../util';\nimport crypto from '../../crypto';\n\nconst ARGON2_TYPE = 0x02; // id\nconst ARGON2_VERSION = 0x13;\nconst ARGON2_SALT_SIZE = 16;\n\nexport class Argon2OutOfMemoryError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Argon2OutOfMemoryError);\n }\n\n this.name = 'Argon2OutOfMemoryError';\n }\n}\n\n// cache argon wasm module\nlet loadArgonWasmModule;\nlet argon2Promise;\n// reload wasm module above this treshold, to deallocated used memory\nconst ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;\n\nclass Argon2S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n const { passes, parallelism, memoryExponent } = config.s2kArgon2Params;\n\n this.type = 'argon2';\n /**\n * 16 bytes of salt\n * @type {Uint8Array}\n */\n this.salt = null;\n /**\n * number of passes\n * @type {Integer}\n */\n this.t = passes;\n /**\n * degree of parallelism (lanes)\n * @type {Integer}\n */\n this.p = parallelism;\n /**\n * exponent indicating memory size\n * @type {Integer}\n */\n this.encodedM = memoryExponent;\n }\n\n generateSalt() {\n this.salt = crypto.random.getRandomBytes(ARGON2_SALT_SIZE);\n }\n\n /**\n * Parsing function for argon2 string-to-key specifier.\n * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n\n this.salt = bytes.subarray(i, i + 16);\n i += 16;\n\n this.t = bytes[i++];\n this.p = bytes[i++];\n this.encodedM = bytes[i++]; // memory size exponent, one-octect\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n const arr = [\n new Uint8Array([enums.write(enums.s2k, this.type)]),\n this.salt,\n new Uint8Array([this.t, this.p, this.encodedM])\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to `keySize`\n * @throws {Argon2OutOfMemoryError|Errors}\n * @async\n */\n async produceKey(passphrase, keySize) {\n const decodedM = 2 << (this.encodedM - 1);\n\n try {\n // on first load, the argon2 lib is imported and the WASM module is initialized.\n // the two steps need to be atomic to avoid race conditions causing multiple wasm modules\n // being loaded when `argon2Promise` is not initialized.\n loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;\n argon2Promise = argon2Promise || loadArgonWasmModule();\n\n // important to keep local ref to argon2 in case the module is reloaded by another instance\n const argon2 = await argon2Promise;\n\n const passwordBytes = util.encodeUTF8(passphrase);\n const hash = argon2({\n version: ARGON2_VERSION,\n type: ARGON2_TYPE,\n password: passwordBytes,\n salt: this.salt,\n tagLength: keySize,\n memorySize: decodedM,\n parallelism: this.p,\n passes: this.t\n });\n\n // a lot of memory was used, reload to deallocate\n if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {\n // it will be awaited if needed at the next `produceKey` invocation\n argon2Promise = loadArgonWasmModule();\n argon2Promise.catch(() => {});\n }\n return hash;\n } catch (e) {\n if (e.message && (\n e.message.includes('Unable to grow instance memory') || // Chrome\n e.message.includes('failed to grow memory') || // Firefox\n e.message.includes('WebAssembly.Memory.grow') || // Safari\n e.message.includes('Out of memory') // Safari iOS\n )) {\n throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');\n } else {\n throw e;\n }\n }\n }\n}\n\nexport default Argon2S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n */\n\nimport defaultConfig from '../../config';\nimport crypto from '../../crypto';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\nimport util from '../../util';\n\nclass GenericS2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(s2kType, config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = enums.read(enums.s2k, s2kType);\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n generateSalt() {\n switch (this.type) {\n case 'salted':\n case 'iterated':\n this.salt = crypto.random.getRandomBytes(8);\n }\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default GenericS2K;\n","import defaultConfig from '../../config';\nimport Argon2S2K, { Argon2OutOfMemoryError } from './argon2';\nimport GenericS2K from './generic';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\n\nconst allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);\n\n/**\n * Instantiate a new S2K instance of the given type\n * @param {module:enums.s2k} type\n * @oaram {Object} [config]\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromType(type, config = defaultConfig) {\n switch (type) {\n case enums.s2k.argon2:\n return new Argon2S2K(config);\n case enums.s2k.iterated:\n case enums.s2k.gnu:\n case enums.s2k.salted:\n case enums.s2k.simple:\n return new GenericS2K(type, config);\n default:\n throw new UnsupportedError('Unsupported S2K type');\n }\n}\n\n/**\n * Instantiate a new S2K instance based on the config settings\n * @oaram {Object} config\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromConfig(config) {\n const { s2kType } = config;\n\n if (!allowedS2KTypesForEncryption.has(s2kType)) {\n throw new Error('The provided `config.s2kType` value is not allowed');\n }\n\n return newS2KFromType(s2kType, config);\n}\n\nexport { Argon2OutOfMemoryError };\n","import { createRequire } from 'module';\nvar require = createRequire('/');\n// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\n// Mediocre shim\nvar Worker;\nvar workerAdd = \";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global\";\ntry {\n Worker = require('worker_threads').Worker;\n}\ncatch (e) {\n}\nvar wk = Worker ? function (c, _, msg, transfer, cb) {\n var done = false;\n var w = new Worker(c + workerAdd, { eval: true })\n .on('error', function (e) { return cb(e, null); })\n .on('message', function (m) { return cb(null, m); })\n .on('exit', function (c) {\n if (c && !done)\n cb(new Error('exited with code ' + c), null);\n });\n w.postMessage(msg, transfer);\n w.terminate = function () {\n done = true;\n return Worker.prototype.terminate.call(w);\n };\n return w;\n} : function (_, __, ___, ____, cb) {\n setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); });\n var NOP = function () { };\n return {\n terminate: NOP,\n postMessage: NOP\n };\n};\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n ,\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && st.f && !st.l))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[pos >> 3] = lst;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if (d[1] & 32)\n err(6, 'invalid zlib data: preset dictionaries not supported');\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n err(6, 'invalid gzip data');\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (val instanceof u8)\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n err(8);\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n err(8);\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this_1.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this_1.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_3 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// A salt notation is used to randomize signatures.\n// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks\n// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).\n// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.\n// some chosen-prefix attacks.\n// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.\nconst SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuerKeyID,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.unknownSubpackets = [];\n this.signedHashValue = null;\n this.salt = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n this.preferredCipherSuites = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes, config = defaultConfig) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n // Only for v6 signatures, a variable-length field containing:\n if (this.version === 6) {\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[i++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(i, i + saltLength);\n i += saltLength;\n }\n\n const signatureMaterial = bytes.subarray(i, bytes.length);\n const { read, signatureParams } = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);\n if (read < signatureMaterial.length) {\n throw new Error('Error reading MPIs');\n }\n this.params = signatureParams;\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n if (this.version === 6) {\n arr.push(new Uint8Array([this.salt.length]));\n arr.push(this.salt);\n }\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false, config) {\n this.version = key.version;\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n // add randomness to the signature\n if (this.version === 6) {\n const saltLength = saltLengthForHash(this.hashAlgorithm);\n if (this.salt === null) {\n this.salt = crypto.random.getRandomBytes(saltLength);\n } else if (saltLength !== this.salt.length) {\n throw new Error('Provided salt does not have the required length');\n }\n } else if (config.nonDeterministicSignaturesViaNotation) {\n const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));\n // since re-signing the same object is not supported, it's not expected to have multiple salt notations,\n // but we guard against it as a sanity check\n if (saltNotations.length === 0) {\n const saltValue = crypto.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm));\n this.rawNotations.push({\n name: SALT_NOTATION_NAME,\n value: saltValue,\n humanReadable: false,\n critical: false\n });\n } else {\n throw new Error('Unexpected existing salt notation');\n }\n }\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n if (this.preferredCipherSuites !== null) {\n bytes = new Uint8Array([].concat(...this.preferredCipherSuites));\n arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {\n return writeSubPacket(type, critical, body);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n // Signature subpackets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n mypos++;\n\n if (!hashed) {\n this.unhashedSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuerKeyID:\n // Issuer\n if (this.version === 4) {\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n } else if (hashed) {\n // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,\n // since the Issuer Fingerprint subpacket is to be used instead.\n // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.\n // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,\n // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)\n // issuerFingerprint.\n // If the packet is hashed, then we reject the signature, to avoid verifying data different from\n // what was parsed.\n throw new Error('Unexpected Issuer Key ID subpacket');\n }\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion >= 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCipherSuites:\n // Preferred AEAD Cipher Suites\n this.preferredCipherSuites = [];\n for (let i = mypos; i < bytes.length; i += 2) {\n this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);\n }\n break;\n default:\n this.unknownSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n break;\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n const subpacketLengthBytes = this.version === 6 ? 4 : 2;\n\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));\n\n let i = subpacketLengthBytes;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {\n // avoid hashing unexpected salt size\n throw new Error('Signature salt does not have the expected length');\n }\n\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.unknownSubpackets.forEach(({ type, critical }) => {\n if (critical) {\n throw new Error(`Unknown critical signature subpacket type ${type}`);\n }\n });\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n\n/**\n * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}\n * @param {enums.hash} hashAlgorithm - Hash algorithm.\n * @returns {Integer} Salt length.\n * @private\n */\nfunction saltLengthForHash(hashAlgorithm) {\n switch (hashAlgorithm) {\n case enums.hash.sha256: return 16;\n case enums.hash.sha384: return 24;\n case enums.hash.sha512: return 32;\n case enums.hash.sha224: return 16;\n case enums.hash.sha3_256: return 16;\n case enums.hash.sha3_512: return 32;\n default: throw new Error('Unsupported hash function');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n static fromSignaturePacket(signaturePacket, isLast) {\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.version = signaturePacket.version === 6 ? 6 : 3;\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n onePassSig.salt = signaturePacket.salt; // v6 only\n onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only\n\n onePassSig.flags = isLast ? 1 : 0;\n return onePassSig;\n }\n\n constructor() {\n /** A one-octet version number. The current versions are 3 and 6. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** Only for v6, a variable-length field containing the salt. */\n this.salt = null;\n /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */\n this.issuerFingerprint = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current versions are 3 or 6.\n this.version = bytes[mypos++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n if (this.version === 6) {\n // Only for v6 signatures, a variable-length field containing:\n\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[mypos++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(mypos, mypos + saltLength);\n mypos += saltLength;\n\n // Only for v6 packets, 32 octets of the fingerprint of the signing key.\n this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);\n mypos += 32;\n this.issuerKeyID = new KeyID();\n // For v6 the Key ID is the high-order 64 bits of the fingerprint.\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n }\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const arr = [new Uint8Array([\n this.version,\n this.signatureType,\n this.hashAlgorithm,\n this.publicKeyAlgorithm\n ])];\n if (this.version === 6) {\n arr.push(\n new Uint8Array([this.salt.length]),\n this.salt,\n this.issuerFingerprint\n );\n } else {\n arr.push(this.issuerKeyID.write());\n }\n arr.push(new Uint8Array([this.flags]));\n return util.concatUint8Array(arr);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||\n (this.version === 3 && correspondingSig.version === 6) ||\n (this.version === 6 && correspondingSig.version !== 6) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError,\n UnknownPacketError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,\n // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.\n // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.\n if (e instanceof UnknownPacketError) {\n if (parsed.tag <= 39) {\n await writer.abort(e);\n } else {\n return;\n }\n }\n\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Inflate, Deflate, Zlib, Unzlib } from 'fflate';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write());\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.\n * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator\n * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor\n * @returns {ReadableStream} compressed or decompressed data\n */\nfunction zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {\n return data => {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(inputData => {\n return new Promise((resolve, reject) => {\n const zlibStream = new ZlibStreamedConstructor();\n zlibStream.ondata = processedData => {\n resolve(processedData);\n };\n try {\n zlibStream.push(inputData, true); // only one chunk to push\n } catch (err) {\n reject(err);\n }\n });\n }));\n }\n\n // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)\n if (compressionStreamInstantiator) {\n try {\n const compressorOrDecompressor = compressionStreamInstantiator();\n return data.pipeThrough(compressorOrDecompressor);\n } catch (err) {\n // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate.\n if (err.name !== 'TypeError') {\n throw err;\n }\n }\n }\n\n // JS fallback\n const inputReader = data.getReader();\n const zlibStream = new ZlibStreamedConstructor();\n\n return new ReadableStream({\n async start(controller) {\n zlibStream.ondata = async (value, isLast) => {\n controller.enqueue(value);\n if (isLast) {\n controller.close();\n }\n };\n\n while (true) {\n const { done, value } = await inputReader.read();\n if (done) {\n zlibStream.push(new Uint8Array(), true);\n return;\n } else if (value.length) {\n zlibStream.push(value);\n }\n }\n }\n });\n };\n}\n\nfunction bzip2Decompress() {\n return async function(data) {\n const { decode: bunzipDecode } = await import('@openpgp/seek-bzip');\n return stream.fromAsync(async () => bunzipDecode(await stream.readToEnd(data)));\n };\n}\n\n/**\n * Get Compression Stream API instatiators if the constructors are implemented.\n * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported\n * (supported formats cannot be determined in advance).\n * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat\n * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}\n */\nconst getCompressionStreamInstantiators = compressionFormat => ({\n compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),\n decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))\n});\n\nconst compress_fns = {\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)\n};\n\nconst decompress_fns = {\n uncompressed: data => data,\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),\n bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n static fromObject({ version, aeadAlgorithm }) {\n if (version !== 1 && version !== 2) {\n throw new Error('Unsupported SEIPD version');\n }\n\n const seip = new SymEncryptedIntegrityProtectedDataPacket();\n seip.version = version;\n if (version === 2) {\n seip.aeadAlgorithm = aeadAlgorithm;\n }\n\n return seip;\n }\n\n constructor() {\n this.version = null;\n\n // The following 4 fields are for V2 only.\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = null;\n this.chunkSizeByte = null;\n this.salt = null;\n\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n this.version = await reader.readByte();\n // - A one-octet version number with value 1 or 2.\n if (this.version !== 1 && this.version !== 2) {\n throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);\n }\n\n if (this.version === 2) {\n // - A one-octet cipher algorithm.\n this.cipherAlgorithm = await reader.readByte();\n // - A one-octet AEAD algorithm.\n this.aeadAlgorithm = await reader.readByte();\n // - A one-octet chunk size.\n this.chunkSizeByte = await reader.readByte();\n // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.\n this.salt = await reader.readBytes(32);\n }\n\n // For V1:\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n // For V2:\n // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.\n // - A final, summary authentication tag for the AEAD mode.\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n if (this.version === 2) {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);\n }\n return util.concat([new Uint8Array([this.version]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n const { blockSize, keySize } = crypto.getCipherParams(sessionKeyAlgorithm);\n if (key.length !== keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n\n if (this.version === 2) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n this.salt = crypto.random.getRandomBytes(32);\n this.chunkSizeByte = config.aeadChunkSizeByte;\n this.encrypted = await runAEAD(this, 'encrypt', key, bytes);\n } else {\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n }\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n if (key.length !== crypto.getCipherParams(sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n\n let packetbytes;\n if (this.version === 2) {\n if (this.cipherAlgorithm !== sessionKeyAlgorithm) {\n // sanity check\n throw new Error('Unexpected session key algorithm');\n }\n packetbytes = await runAEAD(this, 'decrypt', key, encrypted);\n } else {\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n }\n\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n\n/**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\nexport async function runAEAD(packet, fn, key, data) {\n const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;\n const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)\n if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type');\n\n const mode = crypto.getAEADMode(packet.aeadAlgorithm);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;\n const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);\n const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n let iv;\n let ivView;\n if (isSEIPDv2) {\n const { keySize } = crypto.getCipherParams(packet.cipherAlgorithm);\n const { ivLength } = mode;\n const info = new Uint8Array(adataBuffer, 0, 5);\n const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);\n key = derived.subarray(0, keySize);\n iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.\n iv.fill(0, iv.length - 8);\n ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n } else { // AEADEncryptedDataPacket\n iv = packet.iv;\n // ivView is unused in this case\n }\n const modeInstance = await mode(packet.cipherAlgorithm, key);\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n let nonce;\n if (isSEIPDv2) { // SEIPD V2\n nonce = iv;\n } else { // AEADEncryptedDataPacket\n nonce = iv.slice();\n for (let i = 0; i < 8; i++) {\n nonce[iv.length - 8 + i] ^= chunkIndexArray[i];\n }\n }\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);\n cryptedPromise.catch(() => {});\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...)\n cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);\n cryptedPromise.catch(() => {});\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n if (isSEIPDv2) { // SEIPD V2\n ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...)\n } else { // AEADEncryptedDataPacket\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n }\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.ready.catch(() => {});\n await writer.abort(e);\n }\n });\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\nimport { runAEAD } from './sym_encrypted_integrity_protected_data';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await runAEAD(this, 'decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await runAEAD(this, 'encrypt', key, data);\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = null;\n\n // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`\n this.publicKeyID = new KeyID();\n\n // For version 6:\n this.publicKeyVersion = null;\n this.publicKeyFingerprint = null;\n\n // For all versions:\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n static fromObject({\n version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm\n }) {\n const pkesk = new PublicKeyEncryptedSessionKeyPacket();\n\n if (version !== 3 && version !== 6) {\n throw new Error('Unsupported PKESK version');\n }\n\n pkesk.version = version;\n\n if (version === 6) {\n pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;\n pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();\n }\n\n pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();\n pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;\n pkesk.sessionKey = sessionKey;\n pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;\n\n return pkesk;\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let offset = 0;\n this.version = bytes[offset++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n if (this.version === 6) {\n // A one-octet size of the following two fields:\n // - A one octet key version number.\n // - The fingerprint of the public key or subkey to which the session key is encrypted.\n // The size may also be zero.\n const versionAndFingerprintLength = bytes[offset++];\n if (versionAndFingerprintLength) {\n this.publicKeyVersion = bytes[offset++];\n const fingerprintLength = versionAndFingerprintLength - 1;\n this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength;\n if (this.publicKeyVersion >= 5) {\n // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint);\n } else {\n // For v4 The Key ID is the low-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));\n }\n } else {\n // The size may also be zero, and the key version and\n // fingerprint omitted for an \"anonymous recipient\"\n this.publicKeyID = KeyID.wildcard();\n }\n } else {\n offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));\n }\n this.publicKeyAlgorithm = bytes[offset++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));\n if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {\n if (this.version === 3) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n } else if (this.encrypted.C.algorithm !== null) {\n throw new Error('Unexpected cleartext symmetric algorithm');\n }\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version])\n ];\n\n if (this.version === 6) {\n if (this.publicKeyFingerprint !== null) {\n arr.push(new Uint8Array([\n this.publicKeyFingerprint.length + 1,\n this.publicKeyVersion]\n ));\n arr.push(this.publicKeyFingerprint);\n } else {\n arr.push(new Uint8Array([0]));\n }\n } else {\n arr.push(this.publicKeyID.write());\n }\n\n arr.push(\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n );\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a\n // v6 PKESK packet, as it is included in the v2 SEIPD packet.\n const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n if (this.version === 3) {\n // v3 Montgomery curves have cleartext cipher algo\n const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;\n this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;\n\n if (sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n // add checksum\n return util.concatUint8Array([\n new Uint8Array(version === 6 ? [] : [cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = version === 6 ?\n { sessionKeyAlgorithm: null, sessionKey: result } :\n { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && (\n version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return {\n sessionKeyAlgorithm: null,\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 6 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number with value 4, 5 or 6.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following 5 fields.\n offset++;\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version >= 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following field.\n offset++;\n }\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n const s2kType = bytes[offset++];\n this.s2k = newS2KFromType(s2kType);\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version >= 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n const s2k = this.s2k.write();\n if (this.version === 6) {\n const s2kLen = s2k.length;\n const fieldsLen = 3 + s2kLen + this.iv.length;\n bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);\n } else if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n if (this.sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n } else {\n // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v6Keys ? 6 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes, config = defaultConfig) {\n let pos = 0;\n // A one-octet version number (4, 5 or 6).\n this.version = bytes[pos++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version === 4 || this.version === 5 || this.version === 6) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version >= 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (\n this.version === 6 &&\n publicParams.oid && (\n publicParams.oid.getName() === enums.curve.curve25519Legacy ||\n publicParams.oid.getName() === enums.curve.ed25519Legacy\n )\n ) {\n throw new Error('Legacy curve25519 cannot be used with v6 keys');\n }\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version >= 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n const versionOctet = 0x95 + version;\n const lengthOctets = version >= 5 ? 4 : 2;\n return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version >= 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version >= 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError, writeTag } from './packet';\nimport computeHKDF from '../crypto/hkdf';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis\n * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).\n * This value is only relevant to know how to decrypt the key:\n * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.\n * @type {Boolean}\n * @private\n */\n this.isLegacyAEAD = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n /**\n * `true` for keys whose integrity is already confirmed, based on\n * the AEAD encryption mechanism\n * @type {Boolean}\n * @private\n */\n this.usedModernAEAD = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes, config = defaultConfig) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes, config);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n // - Only for a version 6 packet where the secret key material is\n // encrypted (that is, where the previous octet is not zero), a one-\n // octet scalar octet count of the cumulative length of all the\n // following optional string-to-key parameter fields.\n if (this.version === 6 && this.s2kUsage) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n i++;\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n const s2kType = bytes[i++];\n this.s2k = newS2KFromType(s2kType);\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n\n if (this.s2kUsage) {\n // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).\n // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).\n // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always\n // fail if the key was parsed according to the wrong format, since the keys are processed differently.\n // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.\n this.isLegacyAEAD = this.s2kUsage === 253 && (\n this.version === 5 || (this.version === 4 && config.parseAEADEncryptedV4KeysAsLegacy));\n // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)\n // of the same length as the cipher's block size.\n // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the\n // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.\n // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero\n if (this.s2kUsage !== 253 || this.isLegacyAEAD) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipherParams(this.symmetric).blockSize\n );\n this.usedModernAEAD = false;\n } else {\n // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),\n // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which\n // is used as the nonce for the AEAD algorithm.\n this.iv = bytes.subarray(\n i,\n i + crypto.getAEADMode(this.aead).ivLength\n );\n // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.\n this.usedModernAEAD = true;\n }\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n let cleartext;\n if (this.version === 6) {\n cleartext = this.keyMaterial;\n } else {\n cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n }\n try {\n const { read, privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n if (read < cleartext.length) {\n throw new Error('Error reading MPIs');\n }\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n const s2k = this.s2k.write();\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n optionalFieldsArr.push(s2k.length);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...s2k);\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage && this.version !== 6) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = newS2KFromType(enums.s2k.gnu, config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n this.isLegacyAEAD = null;\n this.usedModernAEAD = null;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n\n const { blockSize } = crypto.getCipherParams(this.symmetric);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = config.preferredAEADAlgorithm;\n const mode = crypto.getAEADMode(this.aead);\n this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.\n this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material\n\n const serializedPacketTag = writeTag(this.constructor.tag);\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n\n const modeInstance = await mode(this.symmetric, key);\n this.iv = this.isLegacyAEAD ? crypto.random.getRandomBytes(blockSize) : crypto.random.getRandomBytes(mode.ivLength);\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);\n } else {\n this.s2kUsage = 254;\n this.usedModernAEAD = false;\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(\n this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n this.aead = null;\n this.symmetric = null;\n this.isLegacyAEAD = null;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n if (this.usedModernAEAD) {\n // key integrity confirmed by successful AEAD decryption\n return;\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (this.version === 6 && (\n (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||\n this.algorithm === enums.publicKey.eddsaLegacy\n )) {\n throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);\n }\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\n/**\n * Derive encryption key\n * @param {Number} keyVersion - key derivation differs for v5 keys\n * @param {module:type/s2k} s2k\n * @param {String} passphrase\n * @param {module:enums.symmetric} cipherAlgo\n * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)\n * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)\n * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)\n * @returns encryption key\n */\nasync function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) {\n if (s2k.type === 'argon2' && !aeadMode) {\n throw new Error('Using Argon2 S2K without AEAD is not allowed');\n }\n if (s2k.type === 'simple' && keyVersion === 6) {\n throw new Error('Using Simple S2K with version 6 keys is not allowed');\n }\n const { keySize } = crypto.getCipherParams(cipherAlgo);\n const derivedKey = await s2k.produceKey(passphrase, keySize);\n if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {\n return derivedKey;\n }\n const info = util.concatUint8Array([\n serializedPacketTag,\n new Uint8Array([keyVersion, cipherAlgo, aeadMode])\n ]);\n return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);\n}\n\nexport default SecretKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n\n /**\n * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,\n * as well comments placed between the name (if present) and the bracketed email address:\n * - name (comment) \n * - email\n * In the first case, the `email` is the only required part, and it must contain the `@` symbol.\n * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,\n * since they interfere with `comment` parsing.\n */\n const re = /^(?[^()]+\\s+)?(?\\([^()]+\\)\\s+)?(?<\\S+@\\S+>)$/;\n const matches = re.exec(userID);\n if (matches !== null) {\n const { name, comment, email } = matches.groups;\n this.comment = comment?.replace(/^\\(|\\)|\\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace\n this.name = name?.trim() || '';\n this.email = email.substring(1, email.length - 1); // remove brackets\n } else if (/^[^\\s@]+@[^\\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace\n this.email = userID;\n }\n\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,\n * `enums.signatures.certGeneric` should be given regardless of the actual trust level)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm for a set of keys.\n * @param {Array} [targetKeys] - The keys to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {\n /**\n * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the\n * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).\n * if no keys are available, `preferredSenderAlgo` is returned.\n * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).\n */\n const defaultAlgo = enums.hash.sha256; // MUST implement\n const preferredSenderAlgo = config.preferredHashAlgorithm;\n\n const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {\n const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);\n const targetPrefs = selfCertification.preferredHashAlgorithms;\n return targetPrefs;\n }));\n const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys\n for (const supportedAlgos of supportedAlgosPerTarget) {\n for (const hashAlgo of supportedAlgos) {\n try {\n // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on\n const supportedAlgo = enums.write(enums.hash, hashAlgo);\n supportedAlgosMap.set(\n supportedAlgo,\n supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1\n );\n } catch {}\n }\n }\n const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;\n const getStrongestSupportedHashAlgo = () => {\n if (supportedAlgosMap.size === 0) {\n return defaultAlgo;\n }\n const sortedHashAlgos = Array.from(supportedAlgosMap.keys())\n .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))\n .sort((algoA, algoB) => crypto.hash.getHashByteLength(algoA) - crypto.hash.getHashByteLength(algoB));\n const strongestHashAlgo = sortedHashAlgos[0];\n // defaultAlgo is always implicilty supported, and might be stronger than the rest\n return crypto.hash.getHashByteLength(strongestHashAlgo) >= crypto.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;\n };\n\n const eccAlgos = new Set([\n enums.publicKey.ecdsa,\n enums.publicKey.eddsaLegacy,\n enums.publicKey.ed25519,\n enums.publicKey.ed448\n ]);\n\n if (eccAlgos.has(signingKeyPacket.algorithm)) {\n // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:\n // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5\n // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;\n // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve\n // preferred algo, even if not supported by all targets.\n const preferredCurveAlgo = crypto.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);\n\n const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);\n const preferredSenderAlgoStrongerThanCurveAlgo = crypto.hash.getHashByteLength(preferredSenderAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo);\n\n if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {\n return preferredSenderAlgo;\n } else {\n const strongestSupportedAlgo = getStrongestSupportedHashAlgo();\n return crypto.hash.getHashByteLength(strongestSupportedAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo) ?\n strongestSupportedAlgo :\n preferredCurveAlgo;\n }\n }\n\n // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,\n // since it was manually set by the sender.\n return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();\n}\n\n/**\n * Returns the preferred compression algorithm for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred compression algorithm\n * @async\n */\nexport async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = enums.compression.uncompressed;\n const preferredSenderAlgo = config.preferredCompressionAlgorithm;\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config);\n const recipientPrefs = selfCertification.preferredCompressionAlgorithms;\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred\n * @async\n */\nexport async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config)));\n const withAEAD = keys.length ?\n selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :\n config.aeadProtect;\n\n if (withAEAD) {\n const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };\n const desiredCipherSuites = [\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: config.preferredAEADAlgorithm },\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },\n { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config.preferredAEADAlgorithm }\n ];\n for (const desiredCipherSuite of desiredCipherSuites) {\n if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(\n cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo\n ))) {\n return desiredCipherSuite;\n }\n }\n return defaultCipherSuite;\n }\n const defaultSymAlgo = enums.symmetric.aes128;\n const desiredSymAlgo = config.preferredSymmetricAlgorithm;\n return {\n symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?\n desiredSymAlgo :\n defaultSymAlgo,\n aeadAlgo: undefined\n };\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {Array} recipientKeys - keys to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);\n signaturePacket.rawNotations = [...notations];\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n const isHardRevocation = ![\n enums.reasonForRevocation.keyRetired,\n enums.reasonForRevocation.keySuperseded,\n enums.reasonForRevocation.userIDInvalid\n ].includes(revocationSignature.reasonForRevocationFlag);\n\n await revocationSignature.verify(\n key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||\n options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'curve25519':\n options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;\n break;\n case 'curve448':\n options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function validateSigningKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateEncryptionKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateDecryptionKeyPacket(keyPacket, signature, config) {\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateSigningKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateEncryptionKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n if (primaryKey.version !== 6) {\n // check for expiration time in direct signatures (for V6 keys, the above already did so)\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const selfCertification = await this.getPrimarySelfSignature(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.\n await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * For V4 keys, returns the self-signature of the primary user.\n * For V5 keys, returns the latest valid direct-key self-signature.\n * This self-signature is to be used to check the key expiration,\n * algorithm preferences, and so on.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} The primary self-signature\n * @async\n */\n async getPrimarySelfSignature(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n if (primaryKey.version === 6) {\n return helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n );\n }\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n return selfCertification;\n }\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config);\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @throws {Error} if no decryption key is found\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n let exception = null;\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n if (this.subkeys[i].keyPacket.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n continue;\n }\n\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n // evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.validateDecryptionKeyPacket(primaryKey, selfCertification, config)) {\n if (primaryKey.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n } else {\n keys.push(this);\n }\n }\n\n if (keys.length === 0) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('No decryption key packets found');\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.\n * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).\n * Note: Curve448 and Curve25519 are not widely supported yet.\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n // Every subkey for a v4 primary key MUST be a v4 subkey.\n // Every subkey for a v6 primary key MUST be a v6 subkey.\n // For v5 keys, since we dropped generation support, a v4 subkey is added.\n // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.\n const keyPacket = await helper.generateSecretSubkey(options, { ...config, v6Keys: this.keyPacket.version === 6 });\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nfunction getDefaultSubkeyType(algoName) {\n const algo = enums.write(enums.publicKey, algoName);\n // NB: no encryption-only algos, since they cannot be in primary keys\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n return 'rsa';\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return 'ecc';\n case enums.publicKey.ed25519:\n return 'curve25519';\n case enums.publicKey.ed448:\n return 'curve448';\n default:\n throw new Error('Unsupported algorithm');\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n function getKeySignatureProperties() {\n const signatureProperties = {};\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n const symmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128\n ], config.preferredSymmetricAlgorithm);\n signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;\n if (config.aeadProtect) {\n const aeadAlgorithms = createPreferredAlgos([\n enums.aead.gcm,\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {\n return symmetricAlgorithms.map(symmetricAlgorithm => {\n return [symmetricAlgorithm, aeadAlgorithm];\n });\n });\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512,\n enums.hash.sha3_256,\n enums.hash.sha3_512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.uncompressed,\n enums.compression.zlib,\n enums.compression.zip\n ], config.preferredCompressionAlgorithm);\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.seipdv2;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n return signatureProperties;\n }\n\n if (secretKeyPacket.version === 6) { // add direct key signature with key prefs\n const dataToSign = {\n key: secretKeyPacket\n };\n\n const signatureProperties = getKeySignatureProperties();\n signatureProperties.signatureType = enums.signature.key;\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n packetlist.push(signaturePacket);\n }\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {\n userID: userIDPacket,\n key: secretKeyPacket\n };\n const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};\n signatureProperties.signatureType = enums.signature.certPositive;\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);\n return createKey(firstKeyPacketList);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n return new PrivateKey(firstPrivateKeyList);\n }\n throw new Error('No secret key packet found');\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n if (keys.length === 0) {\n throw new Error('No secret key packet found');\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport { Argon2OutOfMemoryError } from './type/s2k';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredCipherSuite, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;\n\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config);\n\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n if (err instanceof Argon2OutOfMemoryError) {\n exception = err;\n }\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let decryptionKeyPackets;\n try {\n // do not check key expiration to allow decryption of old messages\n decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n } catch (err) {\n exception = err;\n return;\n }\n\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config); // TODO: Pass userID from somewhere.\n if (selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all((\n expectedSymmetricAlgorithm ?\n [expectedSymmetricAlgorithm] :\n Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)\n ).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;\n if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config);\n const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);\n const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&\n !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(symmetricAlgo);\n return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({\n version: aeadAlgorithmName ? 2 : 1,\n aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null\n });\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n\n const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({\n version: aeadAlgorithm ? 6 : 3,\n encryptionKeyPacket: encryptionKey.keyPacket,\n anonymousRecipient: wildcard,\n sessionKey,\n sessionKeyAlgorithm: symmetricAlgorithm\n });\n\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config); // this returns the existing signature packets as well\n const onePassSignaturePackets = signaturePackets.map(\n (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))\n .reverse(); // innermost OPS refers to the first signature packet\n\n packetlist.push(...onePassSignaturePackets);\n packetlist.push(literalDataPacket);\n packetlist.push(...signaturePackets);\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n const trailingPacket = this.packets[this.packets.length - 1];\n // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?\n trailingPacket.version !== 2 :\n this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const signingUserID = signingUserIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config);\n return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n const input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // emit header and checksum if one of the signatures has a version not 6\n const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);\n const hash = emitHeaderAndChecksum ?\n Array.from(new Set(this.signature.packets.map(\n packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()\n ))).join() :\n null;\n\n const body = {\n hash,\n text: this.text,\n data: this.signature.packets.write()\n };\n\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n const hashAlgos = [];\n headers.forEach(header => {\n const hashHeader = header.match(/^Hash: (.+)$/); // get header value\n if (hashHeader) {\n const parsedHashIDs = hashHeader[1]\n .replace(/\\s/g, '') // remove whitespace\n .split(',')\n .map(hashName => {\n try {\n return enums.write(enums.hash, hashName.toLowerCase());\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());\n }\n });\n hashAlgos.push(...parsedHashIDs);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredCompressionAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).\n * Note: Curve448 and Curve25519 (new format) are not widely supported yet.\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:\n * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n if (!type && !curve) {\n type = config.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)\n curve = 'curve25519Legacy'; // unused with type != 'ecc'\n } else {\n type = type || 'ecc';\n curve = curve || 'curve25519Legacy';\n }\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && !config.v6Keys) {\n throw new Error('UserIDs are required for V4 keys');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {\n throw new Error('UserIDs are required for V4 keys');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return await convertStream(data);\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return await convertStream(signature);\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data) {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n// Falls back to Node.js built-in crypto for Node.js <=v14\n// See utils.ts for details.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc\n ? nc.webcrypto\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n//# sourceMappingURL=cryptoNode.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\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// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n}, sha256);\nexport const secp256r1 = p256;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha384 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp384r1 aka p384\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');\nconst Fp = Field(P);\nconst CURVE_A = Fp.create(BigInt('-3'));\n// prettier-ignore\nconst CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n// prettier-ignore\nexport const p384 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\n // Curve order, total count of valid points in the field.\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n // Base (generator) point (x, y)\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n h: BigInt(1),\n lowS: false,\n}, sha384);\nexport const secp384r1 = p384;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-12')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p384.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp521r1 aka p521\n// Note that it's 521, which differs from 512 of its hash function.\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst Fp = Field(P);\nconst CURVE = {\n a: Fp.create(BigInt('-3')),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Fp,\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n h: BigInt(1),\n};\n// prettier-ignore\nexport const p521 = createCurve({\n a: CURVE.a, // Equation params: a, b\n b: CURVE.b,\n Fp, // Field: 2n**521n - 1n\n // Curve order, total count of valid points in the field\n n: CURVE.n,\n Gx: CURVE.Gx, // Base point (x, y) aka generator point\n Gy: CURVE.Gy,\n h: CURVE.h,\n lowS: false,\n allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\nexport const secp521r1 = p521;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE.a,\n B: CURVE.b,\n Z: Fp.create(BigInt('-4')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p521.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3';\nimport { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xof } from './abstract/hash-to-curve.js';\nimport { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * Edwards448 (not Ed448-Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n */\nconst shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));\nconst ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');\n// prettier-ignore\nconst _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);\n// prettier-ignore\nconst _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448P;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most\n // significant bit of the last byte to 1.\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.\n// Uses algo from RFC8032 5.1.3.\nfunction uvRatio(u, v) {\n const P = ed448P;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u²v\n const u3v = mod(u2v * u, P); // u³v\n const u5v3 = mod(u3v * u2v * v, P); // u⁵v³\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x²\n // If vx² = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\nconst Fp = Field(ed448P, 456, true);\nconst ED448_DEF = {\n // Param: a\n a: BigInt(1),\n // -39081. Negative number is P - number\n d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'),\n // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n\n Fp,\n // Subgroup order: how many points curve has;\n // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\n n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n nBitLength: 456,\n // Cofactor\n h: BigInt(4),\n // Base point (x, y) aka generator point\n Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'),\n Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'),\n // SHAKE256(dom4(phflag,context)||x, 114)\n hash: shake256_114,\n randomBytes,\n adjustScalarBytes,\n // dom4\n domain: (data, ctx, phflag) => {\n if (ctx.length > 255)\n throw new Error(`Context is too big: ${ctx.length}`);\n return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n },\n uvRatio,\n};\nexport const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF);\n// NOTE: there is no ed448ctx, since ed448 supports ctx by default\nexport const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 });\nexport const x448 = /* @__PURE__ */ (() => montgomery({\n a: BigInt(156326),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n montgomeryBits: 448,\n nByteLength: 56,\n P: ed448P,\n Gu: BigInt(5),\n powPminus2: (x) => {\n const P = ed448P;\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, BigInt(2), P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts edwards448 public key to x448 public key. Uses formula:\n * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n * @example\n * const aPub = ed448.getPublicKey(utils.randomPrivateKey());\n * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed448.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version\n// Hash To Curve Elligator2 Map\nconst ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic\nconst ELL2_J = BigInt(156326);\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\nfunction map_to_curve_elligator2_edwards448(u) {\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = Fp.invertBatch([xEd, yEd]); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertDcfPoint(other) {\n if (!(other instanceof DcfPoint))\n throw new Error('DecafPoint expected');\n}\n// 1-d\nconst ONE_MINUS_D = BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = BigInt('78163');\n// √(-d)\nconst SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / √(-d)\nconst INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B);\n// Computes Elligator map for Decaf\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const r = mod(-(r0 * r0)); // 1\n const u0 = mod(d * (r - _1n)); // 2\n const u1 = mod((u0 + _1n) * (u0 - r)); // 3\n const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = mod(r0 * v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = mod(-_1n);\n const s = mod(v_prime * (r + _1n)); // 7\n let s_abs = s;\n if (isNegativeLE(s, P))\n s_abs = mod(-s);\n const s2 = s * s;\n const W0 = mod(s_abs * _2n); // 8\n const W1 = mod(s2 + _1n); // 9\n const W2 = mod(s2 - _1n); // 10\n const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11\n return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed448/ExtendedPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass DcfPoint {\n // Private property to discourage combining ExtendedPoint + DecafPoint\n // Always use Decaf encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\n * @param hex 112-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('decafHash', hex, 112);\n const r1 = bytes448ToNumberLE(hex.slice(0, 56));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = bytes448ToNumberLE(hex.slice(56, 112));\n const R2 = calcElligatorDecafMap(r2);\n return new DcfPoint(R1.add(R2));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2\n * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('decafHex', hex, 56);\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint';\n const s = bytes448ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s); // 1\n const u1 = mod(_1n + s2); // 2\n const u1sq = mod(u1 * u1);\n const u2 = mod(u1sq - _4n * d * s2); // 3\n const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4\n let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5\n if (isNegativeLE(u3, P))\n u3 = mod(-u3);\n const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6\n const y = mod((_1n - s2) * invsqrt * u1); // 7\n const t = mod(x * y); // 8\n if (!isValid)\n throw new Error(emsg);\n return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2\n */\n toRawBytes() {\n let { ex: x, ey: _y, ez: z, et: t } = this.ep;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const u1 = mod(mod(x + t) * mod(x - t)); // 1\n const x2 = mod(x * x);\n const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2\n let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3\n if (isNegativeLE(ratio, P))\n ratio = mod(-ratio);\n const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4\n let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 56);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2\n equals(other) {\n assertDcfPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed448.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2)\n return mod(X1 * Y2) === mod(Y1 * X2);\n }\n add(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new DcfPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new DcfPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new DcfPoint(this.ep.double());\n }\n negate() {\n return new DcfPoint(this.ep.negate());\n }\n}\nexport const DecafPoint = /* @__PURE__ */ (() => {\n // decaf448 base point is ed448 base x 2\n // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699\n if (!DcfPoint.BASE)\n DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n);\n if (!DcfPoint.ZERO)\n DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO);\n return DcfPoint;\n})();\n// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C\nexport const hashToDecaf448 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256);\n const P = DcfPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_decaf448 = hashToDecaf448; // legacy\n//# sourceMappingURL=ed448.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));\nconst CURVE_A = Fp.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));\nconst CURVE_B = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');\n\n// prettier-ignore\nexport const brainpoolP256r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),\n Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),\n h: BigInt(1),\n lowS: false\n} as const, sha256);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha384 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));\nconst CURVE_A = Fp.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));\nconst CURVE_B = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');\n\n// prettier-ignore\nexport const brainpoolP384r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),\n Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),\n h: BigInt(1),\n lowS: false\n} as const, sha384);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));\nconst CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));\nconst CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');\n\n// prettier-ignore\nexport const brainpoolP512r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),\n Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),\n h: BigInt(1),\n lowS: false\n} as const, sha512);\n","/**\n * This file is needed to dynamic import the noble-curves.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { p256 as nistP256 } from '@noble/curves/p256';\nimport { p384 as nistP384 } from '@noble/curves/p384';\nimport { p521 as nistP521 } from '@noble/curves/p521';\nimport { x448, ed448 } from '@noble/curves/ed448';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { brainpoolP256r1 } from './brainpool/brainpoolP256r1';\nimport { brainpoolP384r1 } from './brainpool/brainpoolP384r1';\nimport { brainpoolP512r1 } from './brainpool/brainpoolP512r1';\n\nexport const nobleCurves = new Map(Object.entries({\n nistP256,\n nistP384,\n nistP521,\n brainpoolP256r1,\n brainpoolP384r1,\n brainpoolP512r1,\n secp256k1,\n x448,\n ed448\n}));\n\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * This file is needed to dynamic import the legacy ciphers.\n * Separate dynamic imports are not convenient as they result in multiple chunks.\n */\n\nimport { TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TwoFish from './twofish';\nimport BlowFish from './blowfish';\nimport enums from '../../enums';\n\nexport const legacyCiphers = new Map([\n [enums.symmetric.tripledes, TripleDES],\n [enums.symmetric.cast5, CAST5],\n [enums.symmetric.blowfish, BlowFish],\n [enums.symmetric.twofish, TwoFish]\n]);\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms.\n// Initial state\nconst SHA1_IV = /* @__PURE__ */ new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n SHA1_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * SHA1 (RFC 3174) hash function.\n * It was cryptographically broken: prefer newer algorithms.\n * @param message - data that would be hashed\n */\nexport const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());\n//# sourceMappingURL=sha1.js.map","import { HashMD } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n R_BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.js.map","/**\n * This file is needed to dynamic import the noble-hashes.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { sha1 } from '@noble/hashes/sha1';\nimport { sha224, sha256 } from '@noble/hashes/sha256';\nimport { sha384, sha512 } from '@noble/hashes/sha512';\nimport { sha3_256, sha3_512 } from '@noble/hashes/sha3';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\n\nexport const nobleHashes = new Map(Object.entries({\n sha1,\n sha224,\n sha256,\n sha384,\n sha512,\n sha3_256,\n sha3_512,\n ripemd160\n}));\n","// Adapted from the reference implementation in RFC7693\n// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes\n\n// Uint64 values are represented using two Uint32s, stored as little endian\n// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays\n// need to be manually handled\n\n// 64-bit unsigned addition (little endian, in place)\n// Sets a[i,i+1] += b[j,j+1]\n// `a` and `b` must be Uint32Array(2)\nfunction ADD64 (a, i, b, j) {\n a[i] += b[j];\n a[i+1] += b[j+1] + (a[i] < b[j]); // add carry\n}\n\n// Increment 64-bit little-endian unsigned value by `c` (in place)\n// `a` must be Uint32Array(2)\nfunction INC64 (a, c) {\n a[0] += c;\n a[1] += (a[0] < c);\n}\n\n// G Mixing function\n// The ROTRs are inlined for speed\nfunction G (v, m, a, b, c, d, ix, iy) {\n ADD64(v, a, v, b) // v[a,a+1] += v[b,b+1]\n ADD64(v, a, m, ix) // v[a, a+1] += x ... x0\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n let xor0 = v[d] ^ v[a]\n let xor1 = v[d + 1] ^ v[a + 1]\n v[d] = xor1\n v[d + 1] = xor0\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor0 >>> 24) ^ (xor1 << 8)\n v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)\n\n ADD64(v, a, v, b)\n ADD64(v, a, m, iy)\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = v[d] ^ v[a]\n xor1 = v[d + 1] ^ v[a + 1]\n v[d] = (xor0 >>> 16) ^ (xor1 << 16)\n v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor1 >>> 31) ^ (xor0 << 1)\n v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)\n}\n\n// Initialization Vector\nconst BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n])\n\n// These are offsets into a Uint64 buffer.\n// Multiply them all by 2 to make them offsets into a Uint32 buffer\nconst SIGMA = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n].map(x => x * 2))\n\n// Compression function. 'last' flag indicates last block.\n// Note: we're representing 16 uint64s as 32 uint32s\nfunction compress(S, last) {\n const v = new Uint32Array(32)\n const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32)\n\n // init work variables\n for (let i = 0; i < 16; i++) {\n v[i] = S.h[i]\n v[i + 16] = BLAKE2B_IV32[i]\n }\n\n // low 64 bits of offset\n v[24] ^= S.t0[0]\n v[25] ^= S.t0[1]\n // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1\n\n // if last block\n const f0 = last ? 0xFFFFFFFF : 0;\n v[28] ^= f0;\n v[29] ^= f0;\n\n // twelve rounds of mixing\n for (let i = 0; i < 12; i++) {\n // ROUND(r)\n const i16 = i << 4;\n G(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1])\n G(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3])\n G(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5])\n G(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7])\n G(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9])\n G(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11])\n G(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13])\n G(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15])\n }\n\n for (let i = 0; i < 16; i++) {\n S.h[i] ^= v[i] ^ v[i + 16]\n }\n}\n\n// Creates a BLAKE2b hashing context\n// Requires an output length between 1 and 64 bytes\n// Takes an optional Uint8Array key\nclass Blake2b {\n constructor(outlen, key, salt, personal) {\n const params = new Uint8Array(64)\n // 0: outlen, keylen, fanout, depth\n // 4: leaf length, sequential mode\n // 8: node offset\n // 12: node offset\n // 16: node depth, inner length, rfu\n // 20: rfu\n // 24: rfu\n // 28: rfu\n // 32: salt\n // 36: salt\n // 40: salt\n // 44: salt\n // 48: personal\n // 52: personal\n // 56: personal\n // 60: personal\n\n // init internal state\n this.S = {\n b: new Uint8Array(BLOCKBYTES),\n h: new Uint32Array(OUTBYTES_MAX / 4),\n t0: new Uint32Array(2), // input counter `t`, lower 64-bits only\n c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`\n outlen // output length in bytes\n }\n\n // init parameter block\n params[0] = outlen\n if (key) params[1] = key.length\n params[2] = 1 // fanout\n params[3] = 1 // depth\n if (salt) params.set(salt, 32)\n if (personal) params.set(personal, 48)\n const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];\n }\n\n // key the hash, if applicable\n if (key) {\n const block = new Uint8Array(BLOCKBYTES)\n block.set(key)\n this.update(block)\n }\n }\n\n // Updates a BLAKE2b streaming hash\n // Requires Uint8Array (byte array)\n update(input) {\n if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')\n // for (let i = 0; i < input.length; i++) {\n // if (this.S.c === BLOCKBYTES) { // buffer full\n // INC64(this.S.t0, this.S.c) // add counters\n // compress(this.S, false)\n // this.S.c = 0 // empty buffer\n // }\n // this.S.b[this.S.c++] = input[i]\n // }\n let i = 0\n while(i < input.length) {\n if (this.S.c === BLOCKBYTES) { // buffer full\n INC64(this.S.t0, this.S.c) // add counters\n compress(this.S, false)\n this.S.c = 0 // empty buffer\n }\n let left = BLOCKBYTES - this.S.c\n this.S.b.set(input.subarray(i, i + left), this.S.c) // end index can be out of bounds\n const fill = Math.min(left, input.length - i)\n this.S.c += fill\n i += fill\n }\n return this\n }\n\n /**\n * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one\n * @param {Uint8Array} [prealloc] - optional preallocated buffer\n * @returns {ArrayBuffer} message digest\n */\n digest(prealloc) {\n INC64(this.S.t0, this.S.c) // mark last block offset\n\n // final block, padded\n this.S.b.fill(0, this.S.c);\n this.S.c = BLOCKBYTES;\n compress(this.S, true)\n\n const out = prealloc || new Uint8Array(this.S.outlen);\n for (let i = 0; i < this.S.outlen; i++) {\n // must be loaded individually since default Uint32 endianness is platform dependant\n out[i] = this.S.h[i >> 2] >> (8 * (i & 3))\n }\n this.S.h = null; // prevent calling `update` after `digest`\n return out.buffer;\n }\n}\n\n\nexport default function createHash(outlen, key, salt, personal) {\n if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)\n if (key) {\n if (!(key instanceof Uint8Array)) throw new Error('key must be Uint8Array or Buffer')\n if (key.length > KEYBYTES_MAX) throw new Error(`key size must be at most ${KEYBYTES_MAX} (given: ${key.length})`)\n }\n if (salt) {\n if (!(salt instanceof Uint8Array)) throw new Error('salt must be Uint8Array or Buffer')\n if (salt.length !== SALTBYTES) throw new Error(`salt must be exactly ${SALTBYTES} (given: ${salt.length}`)\n }\n if (personal) {\n if (!(personal instanceof Uint8Array)) throw new Error('personal must be Uint8Array or Buffer')\n if (personal.length !== PERSONALBYTES) throw new Error(`salt must be exactly ${PERSONALBYTES} (given: ${personal.length}`)\n }\n\n return new Blake2b(outlen, key, salt, personal)\n}\n\nconst OUTBYTES_MAX = 64;\nconst KEYBYTES_MAX = 64;\nconst SALTBYTES = 16;\nconst PERSONALBYTES = 16;\nconst BLOCKBYTES = 128;\n\n","import blake2b from \"./blake2b.js\"\nconst TYPE = 2; // Argon2id\nconst VERSION = 0x13;\nconst TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MIN = 8;\nconst passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst passwordBYTES_MIN = 8;\nconst MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)\nconst SECRETBYTES_MAX = 32; // key (optional)\n\nconst ARGON2_BLOCK_SIZE = 1024;\nconst ARGON2_PREHASH_DIGEST_LENGTH = 64;\n\nconst isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;\n\n// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])\nfunction LE32(buf, n, i) {\n buf[i+0] = n;\n buf[i+1] = n >> 8;\n buf[i+2] = n >> 16;\n buf[i+3] = n >> 24;\n return buf;\n}\n\n/**\n * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])\n * @param {Uint8Array} buf\n * @param {Number} n\n * @param {Number} i\n */\nfunction LE64(buf, n, i) {\n if (n > Number.MAX_SAFE_INTEGER) throw new Error(\"LE64: large numbers unsupported\");\n // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations\n // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)\n // so we manually extract each byte\n let remainder = n;\n for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER\n buf[offset] = remainder; // implicit & 0xff\n remainder = (remainder - buf[offset]) / 256;\n }\n return buf;\n}\n\n/**\n * Variable-Length Hash Function H'\n * @param {Number} outlen - T\n * @param {Uint8Array} X - value to hash\n * @param {Uint8Array} res - output buffer, of length `outlength` or larger\n */\nfunction H_(outlen, X, res) {\n const V = new Uint8Array(64); // no need to keep around all V_i\n\n const V1_in = new Uint8Array(4 + X.length);\n LE32(V1_in, outlen, 0);\n V1_in.set(X, 4);\n if (outlen <= 64) {\n // H'^T(A) = H^T(LE32(T)||A)\n blake2b(outlen).update(V1_in).digest(res);\n return res\n }\n\n const r = Math.ceil(outlen / 32) - 2;\n\n // Let V_i be a 64-byte block and W_i be its first 32 bytes.\n // V_1 = H^(64)(LE32(T)||A)\n // V_2 = H^(64)(V_1)\n // ...\n // V_r = H^(64)(V_{r-1})\n // V_{r+1} = H^(T-32*r)(V_{r})\n // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}\n for (let i = 0; i < r; i++) {\n blake2b(64).update(i === 0 ? V1_in : V).digest(V);\n // store W_i in result buffer already\n res.set(V.subarray(0, 32), i*32)\n }\n // V_{r+1}\n const V_r1 = new Uint8Array(blake2b(outlen - 32*r).update(V).digest());\n res.set(V_r1, r*32);\n\n return res;\n}\n\n// compute buf = xs ^ ys\nfunction XOR(wasmContext, buf, xs, ys) {\n wasmContext.fn.XOR(\n buf.byteOffset,\n xs.byteOffset,\n ys.byteOffset,\n );\n return buf\n}\n\n/**\n * @param {Uint8Array} X (read-only)\n * @param {Uint8Array} Y (read-only)\n * @param {Uint8Array} R - output buffer\n * @returns\n */\nfunction G(wasmContext, X, Y, R) {\n wasmContext.fn.G(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\nfunction G2(wasmContext, X, Y, R) {\n wasmContext.fn.G2(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\n// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.\nfunction* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {\n // For each segment, we do the following. First, we compute the value Z as:\n // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )\n wasmContext.refs.prngTmp.fill(0);\n const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);\n LE64(Z, pass, 0);\n LE64(Z, lane, 8);\n LE64(Z, slice, 16);\n LE64(Z, m_, 24);\n LE64(Z, totalPasses, 32);\n LE64(Z, TYPE, 40);\n\n // Then we compute q/(128*SL) 1024-byte values\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),\n // ...,\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),\n for(let i = 1; i <= segmentLength; i++) {\n // tmp.set(Z); // no need to re-copy\n LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed\n const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );\n\n // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2\n // NB: the first generated pair must be used for the first block of the segment, and so on.\n // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.\n for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {\n yield g2.subarray(k, k+8);\n }\n }\n return [];\n}\n\nfunction validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {\n const assertLength = (name, value, min, max) => {\n if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }\n }\n\n if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');\n assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);\n assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);\n assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);\n assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);\n // optional fields\n ad && assertLength('associated data', ad, 0, ADBYTES_MAX);\n secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);\n\n return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };\n}\n\nconst KB = 1024;\nconst WASM_PAGE_SIZE = 64 * KB;\n\nexport default function argon2id(params, { memory, instance: wasmInstance }) {\n if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system\n\n const ctx = validateParams({ type: TYPE, version: VERSION, ...params });\n\n const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;\n const wasmRefs = {};\n const wasmFn = {};\n wasmFn.G = wasmG;\n wasmFn.G2 = wasmG2;\n wasmFn.XOR = wasmXOR;\n\n // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.\n const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));\n const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references\n if (memory.buffer.byteLength < requiredMemory) {\n const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE)\n // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.\n // Otherwise, the operation fails, and the original memory can still be used.\n memory.grow(missing)\n }\n\n let offset = 0;\n // Init wasm memory needed in other functions\n wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;\n wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;\n wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;\n wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;\n // Init wasm memory needed locally\n const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;\n const wasmContext = { fn: wasmFn, refs: wasmRefs };\n const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;\n const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);\n const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);\n\n // 1. Establish H_0\n const H0 = getH0(ctx);\n\n // 2. Allocate the memory as m' 1024-byte blocks\n // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.\n const q = m_ / ctx.lanes;\n const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));\n const initBlock = (i, j) => {\n B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);\n return B[i][j];\n }\n\n for (let i = 0; i < ctx.lanes; i++) {\n // const LEi = LE0; // since p = 1 for us\n const tmp = new Uint8Array(H0.length + 8);\n // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p\n // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))\n tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));\n // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p\n // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))\n LE32(tmp, 1, H0.length);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));\n }\n\n // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2\n // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes\n // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.\n const SL = 4; // vertical slices\n const segmentLength = q / SL;\n for (let pass = 0; pass < ctx.passes; pass++) {\n // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel\n for (let sl = 0; sl < SL; sl++) {\n const isDataIndependent = pass === 0 && sl <= 1;\n for (let i = 0; i < ctx.lanes; i++) { // lane\n // On the first slice of the first pass, blocks 0 and 1 are already filled\n let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;\n // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)\n const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;\n for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {\n const j = sl * segmentLength + segmentOffset;\n const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]\n\n // we can assume the PRNG is never done\n const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength)\n const l = lz[0]; const z = lz[1];\n // for (let i = 0; i < p; i++ )\n // B[i][j] = G(B[i][j-1], B[l][z])\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n if (pass === 0) initBlock(i, j);\n G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);\n\n // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one\n if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j])\n }\n }\n }\n }\n\n // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:\n // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]\n const C = B[0][q-1];\n for(let i = 1; i < ctx.lanes; i++) {\n XOR(wasmContext, C, C, B[i][q-1])\n }\n\n const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));\n // clear memory since the module might be cached\n allocatedMemory.fill(0) // clear sensitive contents\n memory.grow(0) // allow deallocation\n // 8. The output tag is computed as H'^T(C).\n return tag;\n\n}\n\nfunction getH0(ctx) {\n const H = blake2b(ARGON2_PREHASH_DIGEST_LENGTH);\n const ZERO32 = new Uint8Array(4);\n const params = new Uint8Array(24);\n LE32(params, ctx.lanes, 0);\n LE32(params, ctx.tagLength, 4);\n LE32(params, ctx.memorySize, 8);\n LE32(params, ctx.passes, 12);\n LE32(params, ctx.version, 16);\n LE32(params, ctx.type, 20);\n\n const toHash = [params];\n if (ctx.password) {\n toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0))\n toHash.push(ctx.password)\n } else {\n toHash.push(ZERO32) // context.password.length\n }\n\n if (ctx.salt) {\n toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0))\n toHash.push(ctx.salt)\n } else {\n toHash.push(ZERO32) // context.salt.length\n }\n\n if (ctx.secret) {\n toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0))\n toHash.push(ctx.secret)\n // todo clear secret?\n } else {\n toHash.push(ZERO32) // context.secret.length\n }\n\n if (ctx.ad) {\n toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0))\n toHash.push(ctx.ad)\n } else {\n toHash.push(ZERO32) // context.ad.length\n }\n H.update(concatArrays(toHash))\n\n const outputBuffer = H.digest();\n return new Uint8Array(outputBuffer);\n}\n\nfunction concatArrays(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!(arrays[i] instanceof Uint8Array)) {\n throw new Error('concatArrays: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach((element) => {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n","import argon2id from \"./argon2id.js\";\n\nlet isSIMDSupported;\nasync function wasmLoader(memory, getSIMD, getNonSIMD) {\n const importObject = { env: { memory } };\n if (isSIMDSupported === undefined) {\n try {\n const loaded = await getSIMD(importObject);\n isSIMDSupported = true;\n return loaded;\n } catch(e) {\n isSIMDSupported = false;\n }\n }\n\n const loader = isSIMDSupported ? getSIMD : getNonSIMD;\n return loader(importObject);\n}\n\nexport default async function setupWasm(getSIMD, getNonSIMD) {\n const memory = new WebAssembly.Memory({\n // in pages of 64KiB each\n // these values need to be compatible with those declared when building in `build-wasm`\n initial: 1040, // 65MB\n maximum: 65536, // 4GB\n });\n const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);\n\n /**\n * Argon2id hash function\n * @callback computeHash\n * @param {Object} params\n * @param {Uint8Array} params.password - password\n * @param {Uint8Array} params.salt - salt\n * @param {Integer} params.parallelism\n * @param {Integer} params.passes\n * @param {Integer} params.memorySize - in kibibytes\n * @param {Integer} params.tagLength - output tag length\n * @param {Uint8Array} [params.ad] - associated data (optional)\n * @param {Uint8Array} [params.secret] - secret data (optional)\n * @return {Uint8Array} argon2id hash\n */\n const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });\n\n return computeHash;\n}\n","import setupWasm from './lib/setup.js';\nimport wasmSIMD from './dist/simd.wasm';\nimport wasmNonSIMD from './dist/no-simd.wasm';\n\nconst loadWasm = async () => setupWasm(\n (instanceObject) => wasmSIMD(instanceObject),\n (instanceObject) => wasmNonSIMD(instanceObject),\n);\n\nexport default loadWasm;\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2022 Proton AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport crypto from '../crypto';\nimport enums from '../enums';\n\n/**\n * Implementation of the Padding Packet\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:\n * Padding Packet\n */\nclass PaddingPacket {\n static get tag() {\n return enums.packet.padding;\n }\n\n constructor() {\n this.padding = null;\n }\n\n /**\n * Read a padding packet\n * @param {Uint8Array | ReadableStream} bytes\n */\n read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars\n // Padding packets are ignored, so this function is never called.\n }\n\n /**\n * Write the padding packet\n * @returns {Uint8Array} The padding packet.\n */\n write() {\n return this.padding;\n }\n\n /**\n * Create random padding.\n * @param {Number} length - The length of padding to be generated.\n * @throws {Error} if padding generation was not successful\n * @async\n */\n async createPadding(length) {\n this.padding = await crypto.random.getRandomBytes(length);\n }\n}\n\nexport default PaddingPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","Object","setPrototypeOf","this","prototype","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","isStream","globalThis","ReadableStream","isPrototypeOf","_read","_readableState","Error","isUint8Array","Uint8Array","concatUint8Array","arrays","length","totalLength","i","result","pos","forEach","element","set","undefined","read","async","value","done","readToEnd","join","slice","clone","then","push","write","chunk","close","abort","reason","process","versions","doneReadingSet","WeakSet","externalBuffer","Reader","reader","bind","_releaseLock","_cancel","cancel","doneReading","has","add","e","toStream","start","controller","enqueue","toArrayStream","concat","list","some","map","transform","transformWithCancel","all","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","options","transformStream","TransformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","pull","highWaterMark","WritableStream","error","finish","output","data","result1","result2","flush","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","destroy","arrayStream","shift","readLine","returnVal","buffer","streams.concat","lineEndIndex","indexOf","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","byteOffset","byteLength","filter","byValue","enums","curve","nistP256","p256","nistP384","p384","nistP521","p521","secp256k1","ed25519Legacy","ed25519","curve25519Legacy","curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","argon2","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","aedh","aedsa","x25519","x448","ed448","symmetric","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","sha3_256","sha3_512","webHash","aead","eax","ocb","gcm","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","padding","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuerKeyID","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","preferredCipherSuites","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","seipdv2","type","config","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","aeadProtect","parseAEADEncryptedV4KeysAsLegacy","preferredAEADAlgorithm","aeadChunkSizeByte","v6Keys","enableParsingV5Entities","s2kType","s2kIterationCountByte","s2kArgon2Params","passes","parallelism","memoryExponent","allowUnauthenticatedMessages","allowUnauthenticatedStream","minRSABits","passwordCollisionCheck","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","allowMissingKeyFlags","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","nonDeterministicSignaturesViaNotation","useEllipticFallback","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","debugMode","env","NODE_ENV","util","isString","String","nodeRequire","createRequire","stream.isUint8Array","stream.isStream","getNobleCurve","publicKeyAlgo","curveName","defaultConfig","nobleCurves","noble_curves","readNumber","n","writeNumber","b","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","readExactSubarray","leftPad","padded","offset","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","hex","k","parseInt","uint8ArrayToHex","hexAlphabet","s","v","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","printDebug","log","printDebugError","x","r","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","webCrypto","crypto","subtle","getNodeCrypto","webcrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","sub","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","a","selectUint8","isAES","cipherAlgo","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","getType","header","match","addheader","customComment","getCheckSum","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","base64.encode","from","toString","btoa","atob","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","removeChecksum","body","lastEquals","lastIndexOf","unarmor","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","stream.isArrayStream","stream.readToEnd","messageType","partIndex","partTotal","emitChecksum","maybeBodyClone","stream.passiveClone","getLegacyCipher","algo","legacyCiphers","legacy_ciphers","cipher","getCipherBlockSize","getCipherKeySize","getCipherParams","keySize","blockSize","md5cycle","c","d","ff","gg","hh","ii","add32","cmn","q","md5blk","md5blks","hex_chr","rhex","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","update","digest","nobleHash","nobleHashName","webCryptoHashName","getNobleHash","nobleHashes","noble_hashes","hashInstance","create","hash$1","entree","state","substring","tail","md51","getHashByteLength","isBytes","lengths","exists","instance","checkFinished","destroyed","finished","out","min","outputLen","u8","arr","u32","createView","toBytes","utf8ToBytes","copyBytes","equalBytes","diff","wrapCipher","params","assign","setBigUint64","view","isLE","_32n","BigInt","_u32_max","wh","Number","wl","setUint32","isAligned32","clean","fill","BLOCK_SIZE","ZEROS16","ZEROS32","swapLE","GHASH","expectedLength","blockLen","s0","s1","s2","s3","abytes","kView","k0","getUint32","k1","k2","k3","doubles","W","estimateWindow","windows","windowSize","items","w","d0","d1","d2","d3","_updateBlock","o0","o1","o2","o3","mask","num","bytePos","bitPos","bit","e0","e1","e2","e3","aexists","b32","blocks","left","elm","digestInto","aoutput","o32","res","Polyval","ghKey","reverse","hiBit","carry","_toGHASHKey","wrapConstructorWithKey","hashCons","hashC","msg","tmp","ghash","EMPTY_BLOCK","POLY","mul2","mul","sbox","box","invSbox","_","rotr32_8","rotl32_8","byteSwap","word","genTtable","T0","T1","T2","T3","T01","T23","sbox2","Uint16Array","idx","tableEncoding","tableDecoding","xPowers","p","expandKeyLE","len","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","encrypt","rounds","t0","t1","t2","t3","decrypt","getDst","dst","ctrCounter","nonce","src","srcLen","ctr","c32","src32","dst32","ctr32","ctrPos","ctrNum","nonceLength","processCtr","plaintext","ciphertext","cbc","iv","opts","pcks5","disablePadding","o","_out","outLen","remaining","validateBlockEncrypt","_iv","n32","tmp32","paddingByte","padPCKS","validateBlockDecrypt","ps0","ps1","ps2","ps3","lastByte","validatePCKS","cfb","processCfb","isEncrypt","next32","tagLength","AAD","_computeTag","authKey","tagMask","aadLength","h","computeTag","deriveKeys","counter","nonceLen","g","passedTag","isBytes32","encryptBlock","block","decryptBlock","AESW","kek","a0","a1","chunks","AESKW_IV","aeskw","sum","pad","concatBytes","unsafe","knownAlgos","getCiphers","nodeAlgos","WebCryptoEncryptor","prevBlock","nextBlock","zeroBlock","isSupported","importKey","_runCBC","nonZeroIV","mode","keyRef","encryptChunk","missing","added","leftover","toEncrypt","encryptedBlocks","xorMut","encryptedBlock","curBlock","clearSensitiveData","ct","NobleStreamProcessor","forEncryption","nobleAesHelpers","getUint32Array","_runCFB","processChunk","toProcess","processedBlocks","processedBlock","aLength","algoName","decipherObj","createDecipheriv","nodeDecrypt","nobleAesCfb","aesDecrypt","cipherfn","block_size","blockp","decblock","pt","cipherObj","createCipheriv","nodeEncrypt","aesEncrypt","blockc","encblock","blockLength","rightXORMut","CMAC","CBC","padding2","err","nobleAesCbc","ivLength","zero","one","two","OMAC","cmac","CTR","en","final","nobleAesCtr","EAX","omac","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","T","xor","OCB","maxNtz","aes","encipher","decipher","crypt","m","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","checksum","xorInput","$","cipherInput","mask_x","mask_$","constructKeyVariables","crypted","ALGO","GCM","setAAD","getAuthTag","de","setAuthTag","_key","webcryptoEmptyMessagesUnsupported","userAgent","nobleAesGcm","additionalData","_0n","_1n","uint8ArrayToBigInt","mod","reduced","modExp","exp","lsb","abs","modInv","gcd","aInput","bInput","y","xPrev","yPrev","aNegated","bNegated","_egcd","bigIntToNumber","number","MAX_SAFE_INTEGER","getBit","bitLength","bitlen","_8n","bigIntToUint8Array","endian","rawLength","getRandomBytes","getRandomValues","getRandomBigInteger","modulus","randomProbablePrime","_30n","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","n1","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","count","randomBytes","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","hashed","emLen","hashPrefix","tLen","EM","privateToJWK","u","pNum","qNum","dNum","dq","dp","kty","qi","ext","publicToJWK","jwkToPrivate","jwk","format","constants","RSA_PKCS1_PADDING","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","publicEncrypt","bnEncrypt","keyGenOpt","modulusLength","publicExponent","keyPair","generateKey","exportKey","publicKeyEncoding","privateKeyEncoding","generateKeyPair","jwkPrivateKey","phi","hashAlgo","hashName","sign","webSign","createSign","nodeSign","bnSign","_2n","rde","verify","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","c1","c2","pSize","threshold","nc","nacl","gf","init","Float64Array","randombytes","_9","gf0","gf1","_121665","D","D2","X","Y","I","ts64","l","crypto_verify_32","xi","yi","vn","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","A","Z","M","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","z","f","x32","x16","crypto_scalarmult_base","K","crypto_hashblocks_hl","hl","bh0","bh1","bh2","bh3","bh4","bh5","bh6","bh7","bl0","bl1","bl2","bl3","bl4","bl5","bl6","bl7","th","tl","Int32Array","ah0","ah1","ah2","ah3","ah4","ah5","ah6","ah7","al0","al1","al2","al3","al4","al5","al6","al7","crypto_hash","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","reduce","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","TypeError","scalarMult","crypto_box_keypair","fromSecretKey","signedMsg","sm","smlen","crypto_sign","detached","sig","crypto_sign_open","fromSeed","seed","setPRNG","cleanup","knownOIDs","OID","oid","toHex","getName","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callback","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","lengthByte","nextPacket","UnsupportedError","captureStackTrace","UnknownPacketError","UnparseablePacket","rawContent","generate","webCryptoKey","getPayloadSize","utils","randomPrivateKey","getPublicKey","getPreferredHashAlgo","privateKeyToJWK","RS","publicKeyToJWK","crv","wrap","dataToWrap","wrappingKey","keyToWrap","wrapped","wrapKey","nobleAesKW","unwrap","wrappedData","unwrapped","unwrapKey","computeHKDF","inputKey","salt","info","importedKey","deriveBits","HKDF_INFO","generateEphemeralEncryptionMaterial","recipientA","ephemeralSecretKey","sharedSecret","assertNonZeroArray","ephemeralPublicKey","getSharedSecret","recomputeSharedSecret","acc","wrappedKey","hkdfInput","aesKW.unwrap","encryptionKey","aesKW.wrap","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","wireFormatLeadingByte","CurveWithOID","oidOrName","genKeyPair","namedCurve","jwkToRawPublic","webGenKeyPair","jsGenKeyPair","createECDH","generateKeys","getPrivateKey","nodeGenKeyPair","ecdhXGenerate","eddsaGenerate","validateStandardParams","Q","supportedCurves","dG","checkPublicPointEnconding","V","pointSize","nobleCurve","bufX","bufY","rawPublicToJWK","ecKeyUtils","nodeBuffer","derPrivateKey","generateDer","dsaEncoding","lowS","tryFallbackVerificationForOldBug","jsVerify","verified","derPublicKey","eddsaSign","eddsaVerify","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","ecdhXGenerateEphemeralEncryptionMaterial","recipient","public","webPublicEphemeralKey","jsPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","genPrivateEphemeralKey","ecdhXRecomputeSharedSecret","secret","webPrivateEphemeralKey","jsPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","C","pkcs5.decode","pkcs5.encode","xr","qSize","u1","u2","rsa","elliptic","signatureParams","rsSize","eddsa","publicKeyParams","privateKeyParams","publicParams","curveSize","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","fromObject","algorithm","followLength","checkSupportedCurve","getCurvePayloadSize","ecdhX","privateParams","prefixrandom","repeat","ECDHSymkey","sessionKeyParams","keyAlgo","symmetricAlgo","algosWithNativeRepresentation","orderedParams","keys","validateParams","algoModule","random","pkcs1","pkcs5","aesKW","Argon2OutOfMemoryError","loadArgonWasmModule","argon2Promise","Argon2S2K","encodedM","generateSalt","produceKey","passphrase","decodedM","index$1","default","version","password","memorySize","GenericS2K","getCount","numBytes","rlength","prefixlen","toHash","datalen","allowedS2KTypesForEncryption","newS2KFromType","newS2KFromConfig","require","Worker","u16","fleb","fdeb","clim","freb","eb","_a","fl","revfl","_b","fd","revfd","rev","hMap","cd","mb","co","le","rvb","sv","r_1","flt","fdt","flm","flrm","fdm","fdrm","bits16","shft","slc","BYTES_PER_ELEMENT","ec","ind","nt","code","wbits","wbits16","hTree","et","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","cl","cli","cln","cls","clen","cf","wfblk","dat","wblk","syms","lf","df","li","bl","dlt","mlb","ddt","mdb","_c","lclt","nlc","_d","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","deo","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","head","bs1_1","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","level","mem","Deflate","cb","ondata","Inflate","bts","sl","noBuf","noSt","cbuf","nbuf","bt","lbt","dbt","tbts","hLit","hcLen","ldt","clt","clb","clbmsk","clm","lt","lms","dms","lpos","sym","dsym","inflt","Zlib","raw","lv","zlh","wbytes","Unzlib","td","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","KeyID","equals","keyID","matchWildcard","isWildcard","isNull","mapToHex","fromID","wildcard","SALT_NOTATION_NAME","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","unknownSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","saltLength","signatureMaterial","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","saltLengthForHash","saltValue","humanReadable","critical","writeHashedSubPackets","stream.slice","stream.clone","writeSubPacket","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLengthBytes","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","fromSignaturePacket","signaturePacket","isLast","onePassSig","flags","args","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","fromBinary","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","chunkSize","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","compressionFn","compress_fns","compressionStreamInstantiator","ZlibStreamedConstructor","inputData","zlibStream","processedData","compressorOrDecompressor","pipeThrough","inputReader","bzip2Decompress","bunzipDecode","getCompressionStreamInstantiators","compressionFormat","compressor","CompressionStream","decompressor","DecompressionStream","SymEncryptedIntegrityProtectedDataPacket","aeadAlgorithm","seip","cipherAlgorithm","chunkSizeByte","encrypted","sessionKeyAlgorithm","runAEAD","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","isSEIPDv2","isAEADP","getAEADMode","tagLengthIfDecrypting","tagLengthIfEncrypting","chunkIndexSizeIfAEADEP","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","ivView","latestPromise","cryptedBytes","queuedBytes","derived","modeInstance","size","stream.pipe","finalChunk","cryptedPromise","setInt32","desiredSize","AEADEncryptedDataPacket","PublicKeyEncryptedSessionKeyPacket","publicKeyID","publicKeyVersion","publicKeyFingerprint","sessionKey","encryptionKeyPacket","anonymousRecipient","pkesk","versionAndFingerprintLength","fingerprintLength","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","hasEncryptedAlgo","sessionKeyData","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","s2kLen","fieldsLen","generateSessionKey","PublicKeyPacket","expirationTimeV3","fromSecretKeyPacket","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","versionOctet","lengthOctets","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","PublicSubkeyPacket","fromSecretSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","isLegacyAEAD","usedModernAEAD","startOfSecretKeyData","unparseableKeyMaterial","cleartext","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","serializedPacketTag","produceEncryptionKey","associateData","cleartextWithHash","validate","validParams","generateParams","keyVersion","aeadMode","derivedKey","UserIDPacket","email","comment","components","matches","exec","groups","trim","otherUserID","SecretSubkeyPacket","Signature","packetlist","getSigningKeyIDs","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","recipientKeys","signingKeyPacket","recipientUserIDs","targetKeys","targetUserIDs","defaultAlgo","preferredSenderAlgo","supportedAlgosPerTarget","getPrimarySelfSignature","supportedAlgosMap","Map","supportedAlgos","supportedAlgo","isSupportedHashAlgo","getStrongestSupportedHashAlgo","strongestHashAlgo","algoA","algoB","preferredCurveAlgo","getPreferredCurveHashAlgo","preferredSenderAlgoIsSupported","preferredSenderAlgoStrongerThanCurveAlgo","strongestSupportedAlgo","mergeSignatures","source","dest","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","isHardRevocation","sanitizeKeyOptions","subkeyDefaults","validateSigningKeyPacket","validateEncryptionKeyPacket","validateDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","certify","signingKeys","isPrivate","signingKey","getSigningKey","isRevoked","certificate","verifyCertificate","verificationKeys","issuerKeys","getKeys","verifyAllCertifications","certifications","certification","valid","selfCertification","sourceUser","srcSelfSig","srcRevSig","revoke","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","helper.checkKeyRequirements","helper.validateSigningKeyPacket","getEncryptionKey","helper.validateEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","getPrimaryUser","primaryUser","B","pop","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","getRevocationCertificate","applyRevocationCertificate","revocationCertificate","signPrimaryUser","privateKeys","userSign","signAllUsers","verifyPrimaryUser","verifyAllUsers","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","pubSubkeyPacket","getDecryptionKeys","helper.validateDecryptionKeyPacket","Boolean","addSubkey","defaultOptions","getDefaultSubkeyType","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","getKeySignatureProperties","symmetricAlgorithms","aeadAlgorithms","flatMap","symmetricAlgorithm","userIDs","userIDPacket","subkeyOptions","subkeySignaturePacket","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","symEncryptedPacketlist","symEncryptedPacket","expectedSymmetricAlgorithm","sessionKeyObjects","decryptSessionKeys","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgo","selfSigs","selfSig","defaultCipherSuite","desiredCipherSuites","desiredCipherSuite","cipherSuite","defaultSymAlgo","desiredSymAlgo","getPreferredCipherSuite","symmetricAlgoName","aeadAlgoName","maybeKey","encryptionKeyIDs","aeadAlgorithmName","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","signingUserIDs","literalDataPacket","signaturePackets","createSignaturePackets","onePassSignaturePackets","signDetached","recipientKeyIDs","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","appendSignature","detachedSignature","trailingPacket","signingUserID","existingSigPacketlist","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","CleartextMessage","newSignature","emitHeaderAndChecksum","checkMessage","checkCleartextOrMessage","checkOutputMessageFormat","defaultConfigPropsCount","checkConfig","inputConfigProps","inputProp","toArray","convertStream","linkStreams","formatObject","object","isSafeInteger","rotr","rotl","byteSwap32","Hash","_cloneInto","wrapConstructor","bytesLength","Chi","Maj","HashMD","padOffset","take","dataView","roundClean","oview","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","E","F","G","H","W15","W2","SHA224","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","hmac","abool","title","hexes","padStart","bytesToHex","numberToHexUnpadded","hexToNumber","asciis","_0","_A","_F","_f","asciiToBase16","char","hexToBytes","al","ai","hi","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","isPosBig","inRange","aInRange","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reset","reseed","gen","pred","validatorFns","bigint","val","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","memoized","WeakMap","arg","_3n","_4n","_5n","pow","pow2","invert","FpSqrt","P","p1div4","root","eql","sqr","nv","ONE","legendreC","Q1div2","neg","ZERO","ge","tonelliShanks","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","freeze","MASK","is0","isOdd","lhs","rhs","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","constTimeNegate","condition","negate","validateW","unsafeLadder","precomputeWindow","points","base","window","precomputes","BASE","maxNumber","shiftBy","offset1","offset2","cond1","cond2","wNAFCached","comp","setWindowSize","delete","pippenger","scalars","buckets","lastBits","scalar","resI","sumI","validateBasic","Gx","Gy","validateSigVerOpts","prehash","b2n","h2b","ut","DER","Err","_tlv","dataLen","ut.numberToHexUnpadded","lenLen","first","lengthBytes","_int","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","point","_isCompressed","toAffine","ut.concatBytes","weierstrassEquation","x2","x3","normPrivateKeyToScalar","N","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","ut.aInRange","assertPrjPoint","Point","toAffineMemo","iz","px","py","pz","ax","ay","zz","assertValidMemo","right","fromAffine","normalizeZ","toInv","fromHex","assertValidity","fromPrivateKey","multiply","msm","_setWindowSize","wnaf","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","subtract","multiplyUnsafe","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","cofactor","toRawBytes","isCompressed","_bits","ProjectivePoint","isWithinCurveOrder","ut.inRange","weierstrass","curveDef","bits2int","bits2int_modN","validateOpts","compressedLen","uncompressedLen","modN","CURVE_ORDER","invN","mod.invert","cat","y2","sqrtError","suffix","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","R","ir","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","mod.getMinHashLength","fieldLen","minLen","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","privateA","publicB","privKey","ut.createHmacDrbg","drbg","sg","_sig","derError","is","getHash","msgs","createCurve","defHash","U32_MASK64","fromBig","Ah","Al","rotlSH","rotlSL","rotlBH","rotlBL","u64","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","SHA384","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_7n","_256n","_0x71n","round","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","enableXOF","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","writeInto","bufferOut","xofInto","xof","shake256","wrapXOFConstructorWithOpts","dkLen","genShake","VERIFY_DEFAULT","zip215","twistedEdwards","adjustScalarBytes","domain","uvRatio","mapToCurve","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","isSmallOrder","normed","ut.bytesToNumberLE","isXOdd","isLastByteOdd","getExtendedPublicKey","ut.numberToBytesLE","modN_LE","pointBytes","hashDomainToScalar","context","verifyOpts","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","swap","x_2","x_3","dummy","a24","encodeUCoordinate","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","shake256_114","ed448P","_11n","_22n","_44n","_88n","_223n","ed448_pow_Pminus3div4","b22","b44","b88","b176","b220","b222","b223","ED448_DEF","u2v","u3v","u5v3","secp256k1P","secp256k1N","divNearest","_6n","_23n","a2","POW_2_128","des","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","looping","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","f1","f2","f3","scheduleA","scheduleB","sBox","inn","ki","half","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","dataL","dataR","parray","vector","off","ret","_decryptBlock","jj","kk","BlowFish","TwoFish","SHA1_IV","SHA1_W","SHA1","Rho","Id","Pi","idxL","idxR","shiftsL","shiftsR","Kl","Kr","group","R_BUF","RIPEMD160","h0","h1","h2","h3","h4","ar","br","cr","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","ripemd160","ADD64","INC64","ix","iy","xor0","xor1","BLAKE2B_IV32","SIGMA","f0","i16","Blake2b","outlen","personal","BLOCKBYTES","OUTBYTES_MAX","params32","prealloc","TYPE","VERSION","TAGBYTES_MAX","TAGBYTES_MIN","SALTBYTES_MAX","SALTBYTES_MIN","passwordBYTES_MAX","passwordBYTES_MIN","MEMBYTES_MAX","ADBYTES_MAX","SECRETBYTES_MAX","ARGON2_BLOCK_SIZE","ARGON2_PREHASH_DIGEST_LENGTH","LE32","LE64","H_","V1_in","blake2b","V_r1","XOR","wasmContext","xs","ys","refs","gZ","G2","makePRNG","pass","lane","m_","totalPasses","segmentLength","segmentOffset","prngTmp","g2","ZERO1024","prngR","KB","WASM_PAGE_SIZE","argon2id","memory","wasmInstance","ad","assertLength","lanes","wasmG","wasmG2","wasmXOR","getLZ","wasmLZ","exports","wasmRefs","wasmFn","requiredMemory","grow","lz","newBlock","blockMemory","allocatedMemory","H0","ZERO32","concatArrays","outputBuffer","getH0","initBlock","isDataIndependent","PRNG","J1J2","next","isSIMDSupported","setupWasm","getSIMD","getNonSIMD","WebAssembly","Memory","initial","maximum","wasmModule","importObject","loaded","wasmLoader","instanceObject","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","seek","n_bit","n_byte","pi","bufToHex","bitreader","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","crc32","getCRC","updateCRC","updateCRCRun","require$$0","require$$1","CRC32","require$$2","mtf","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","status","optDetail","errorCode","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","maxLen","MAX_HUFCODE_BITS","permute","limit","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","lib","multistream","bz","targetStreamCRC","decodeBlock","writeCopies","table","delegate","position","assert","createPadding","rest","unknownOptions","streamType","literalDataPacketlist","expectSigned","publicKeys","clonedPrivateKey","passphrases","encryptionUserIDs","signatureNotations","senderAlgoSupport","recipientPrefs","getPreferredCompressionAlgo","checkBinary","checkString","helper.generateSecretKey","cleartextMessage","checkHashAlgos","hashAlgos","check","hashHeader","parsedHashIDs","armoredKey","binaryKey","keyIndex","armoredKeys","binaryKeys","newKey","armoredMessage","binaryMessage","firstPrivateKeyList","oneKeyList","armoredSignature","binarySignature","reformattedKey","sanitize","reformat","revokedKey"],"mappings":";4yBAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxB,WAAAC,GACEC,QAEAC,OAAOC,eAAeC,KAAMN,EAAYO,WAExCD,KAAKX,GAAsB,IAAIa,SAAQ,CAACC,EAASC,KAC/CJ,KAAKT,GAAsBY,EAC3BH,KAAKR,GAAqBY,CAAM,IAElCJ,KAAKX,GA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O8E,WAAa6+D,GAAc3jE,EAAO8E,MAClC9E,CACR,CAAC,MAAOu0B,GACP,MAAMxf,EAAK8G,UAAU,iCAAkC0Y,EAC3D,CACA","x_google_ignoreList":[0,1,2,3,12,13,14,15,28,29,52,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,111,112,114,115,116,117,118,119,120,121]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.js b/app/node_modules/openpgp/dist/node/openpgp.min.js deleted file mode 100644 index b2f777186..000000000 --- a/app/node_modules/openpgp/dist/node/openpgp.min.js +++ /dev/null @@ -1,17 +0,0 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -"use strict";const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};Object.defineProperty(exports,"__esModule",{value:!0});var t=require("buffer"),r=require("stream"),i=require("crypto"),n=require("zlib"),a=require("os"),s=require("util"),o=require("asn1.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=/*#__PURE__*/c(t),h=/*#__PURE__*/c(r),d=/*#__PURE__*/c(i),f=/*#__PURE__*/c(n),l=/*#__PURE__*/c(a),p=/*#__PURE__*/c(s),y=/*#__PURE__*/c(o);const b=Symbol("doneWritingPromise"),g=Symbol("doneWritingResolve"),m=Symbol("doneWritingReject"),w=Symbol("readingIndex");class v extends Array{constructor(){super(),this[b]=new Promise(((e,t)=>{this[g]=e,this[m]=t})),this[b].catch((()=>{}))}}function _(e){return e&&e.getReader&&Array.isArray(e)}function k(e){if(!_(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}v.prototype.getReader=function(){return void 0===this[w]&&(this[w]=0),{read:async()=>(await this[b],this[w]===this.length?{value:void 0,done:!0}:{value:this[this[w]++],done:!1})}},v.prototype.readToEnd=async function(e){await this[b];const t=e(this.slice(this[w]));return this.length=0,t},v.prototype.clone=function(){const e=new v;return e[b]=this[b].then((()=>{e.push(...this)})),e},k.prototype.write=async function(e){this.stream.push(e)},k.prototype.close=async function(){this.stream[g]()},k.prototype.abort=async function(e){return this.stream[m](e),e},k.prototype.releaseLock=function(){};const A="object"==typeof e.process&&"object"==typeof e.process.versions,S=A&&h.default.Readable;function E(t){return _(t)?"array":e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t)?"web":z&&z.prototype.isPrototypeOf(t)?"ponyfill":S&&S.prototype.isPrototypeOf(t)?"node":!(!t||!t.getReader)&&"web-like"}function P(e){return Uint8Array.prototype.isPrototypeOf(e)}function x(e){if(1===e.length)return e[0];let t=0;for(let r=0;r{t||(M.isBuffer(i)&&(i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),r.enqueue(i),e.pause())})),e.on("end",(()=>{t||r.close()})),e.on("error",(e=>r.error(e)))},pull(){e.resume()},cancel(r){t=!0,e.destroy(r)}})};class e extends K{constructor(e,t){super(t),this._reader=W(e)}async _read(e){try{for(;;){const{done:e,value:t}=await this._reader.read();if(e){this.push(null);break}if(!this.push(t))break}}catch(e){this.destroy(e)}}async _destroy(e,t){this._reader.cancel(e).then(t,t)}}D=function(t,r){return new e(t,r)}}const U=new WeakSet,R=Symbol("externalBuffer");function I(e){if(this.stream=e,e[R]&&(this[R]=e[R].slice()),_(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=async()=>{})}let t=E(e);if("node"===t&&(e=C(e)),t){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let r=!1;this._read=async()=>r||U.has(e)?{value:void 0,done:!0}:(r=!0,{value:e,done:!1}),this._releaseLock=()=>{if(r)try{U.add(e)}catch(e){}}}I.prototype.read=async function(){if(this[R]&&this[R].length){return{done:!1,value:this[R].shift()}}return this._read()},I.prototype.releaseLock=function(){this[R]&&(this.stream[R]=this[R]),this._releaseLock()},I.prototype.cancel=function(e){return this._cancel(e)},I.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:i}=await this.read();if(i+="",r)return t.length?H(t):void 0;const n=i.indexOf("\n")+1;n&&(e=H(t.concat(i.substr(0,n))),t=[]),n!==i.length&&t.push(i.substr(n))}return this.unshift(...t),e},I.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(re(t,1)),r},I.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:i,value:n}=await this.read();if(i)return t.length?H(t):void 0;if(t.push(n),r+=n.length,r>=e){const r=H(t);return this.unshift(re(r,e)),re(r,0,e)}}},I.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},I.prototype.unshift=function(...e){this[R]||(this[R]=[]),1===e.length&&P(e[0])&&this[R].length&&e[0].length&&this[R][0].byteOffset>=e[0].length?this[R][0]=new Uint8Array(this[R][0].buffer,this[R][0].byteOffset-e[0].length,this[R][0].byteLength+e[0].length):this[R].unshift(...e.filter((e=>e&&e.length)))},I.prototype.readToEnd=async function(e=H){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};let B,T,{ReadableStream:z,WritableStream:q,TransformStream:F}=e;async function O(){if(F)return;const[t,r]=await Promise.all([Promise.resolve().then((function(){return Cp})),Promise.resolve().then((function(){return Yp}))]);({ReadableStream:z,WritableStream:q,TransformStream:F}=t);const{createReadableStreamWrapper:i}=r;e.ReadableStream&&z!==e.ReadableStream&&(B=i(z),T=i(e.ReadableStream))}const L=A&&u.default.Buffer;function N(e){let t=E(e);return"node"===t?C(e):"web"===t&&B?B(e):t?e:new z({start(t){t.enqueue(e),t.close()}})}function j(e){if(E(e))return e;const t=new v;return(async()=>{const r=G(t);await r.write(e),await r.close()})(),t}function H(e){return e.some((e=>E(e)&&!_(e)))?function(e){e=e.map(N);const t=Z((async function(e){await Promise.all(i.map((t=>ne(t,e))))}));let r=Promise.resolve();const i=e.map(((i,n)=>Y(i,((i,a)=>(r=r.then((()=>V(i,t.writable,{preventClose:n!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>_(e)))?function(e){const t=new v;let r=Promise.resolve();return e.forEach(((i,n)=>(r=r.then((()=>V(i,t,{preventClose:n!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):L&&L.isBuffer(e[0])?L.concat(e):x(e)}function W(e){return new I(e)}function G(e){return new k(e)}async function V(e,t,{preventClose:r=!1,preventAbort:i=!1,preventCancel:n=!1}={}){if(E(e)&&!_(e)){e=N(e);try{if(e[R]){const r=G(t);for(let t=0;t{t=e,r=i})),t=null,r=null)},close:i.close.bind(i),abort:i.error.bind(i)})}}function X(e,t=(()=>{}),r=(()=>{})){if(_(e)){const i=new v;return(async()=>{const n=G(i);try{const i=await ie(e),a=t(i),s=r();let o;o=void 0!==a&&void 0!==s?H([a,s]):void 0!==a?a:s,await n.write(o),await n.close()}catch(e){await n.abort(e)}})(),i}if(E(e))return $(e,{async transform(e,r){try{const i=await t(e);void 0!==i&&r.enqueue(i)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const i=t(e),n=r();return void 0!==i&&void 0!==n?H([i,n]):void 0!==i?i:n}function Y(e,t){if(E(e)&&!_(e)){let r;const i=new F({start(e){r=e}}),n=V(e,i.writable),a=Z((async function(e){r.error(e),await n,await new Promise(setTimeout)}));return t(i.readable,a.writable),a.readable}e=j(e);const r=new v;return t(e,r),r}function Q(e,t){let r;const i=Y(e,((e,n)=>{const a=W(e);a.remainder=()=>(a.releaseLock(),V(e,n),i),r=t(a)}));return r}function J(e){if(_(e))return e.clone();if(E(e)){const t=function(e){if(_(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(E(e)){const t=N(e).tee();return t[0][R]=t[1][R]=e[R],t}return[re(e),re(e)]}(e);return te(e,t[0]),t[1]}return re(e)}function ee(e){return _(e)?J(e):E(e)?new z({start(t){const r=Y(e,(async(e,r)=>{const i=W(e),n=G(r);try{for(;;){await n.ready;const{done:e,value:r}=await i.read();if(e){try{t.close()}catch(e){}return void await n.close()}try{t.enqueue(r)}catch(e){}await n.write(r)}}catch(e){t.error(e),await n.abort(e)}}));te(e,r)}}):re(e)}function te(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,i])=>{"constructor"!==r&&(i.value?i.value=i.value.bind(t):i.get=i.get.bind(t),Object.defineProperty(e,r,i))}))}function re(e,t=0,r=1/0){if(_(e))throw Error("Not implemented");if(E(e)){if(t>=0&&r>=0){let i=0;return $(e,{transform(e,n){i=t&&n.enqueue(re(e,Math.max(t-i,0),r-i)),i+=e.length):n.terminate()}})}if(t<0&&(r<0||r===1/0)){let i=[];return X(e,(e=>{e.length>=-t?i=[e]:i.push(e)}),(()=>re(H(i),t,r)))}if(0===t&&r<0){let i;return X(e,(e=>{const n=i?H([i,e]):e;if(n.length>=-r)return i=re(n,r),re(n,t,r);i=n}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),ae((async()=>re(await ie(e),t,r)))}return e[R]&&(e=H(e[R].concat([e]))),!P(e)||L&&L.isBuffer(e)?e.slice(t,r):(r===1/0&&(r=e.length),e.subarray(t,r))}async function ie(e,t=H){return _(e)?e.readToEnd(t):E(e)?W(e).readToEnd(t):e}async function ne(e,t){if(E(e)){if(e.cancel)return e.cancel(t);if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function ae(e){const t=new v;return(async()=>{const r=G(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}class se{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");if(e instanceof Uint8Array){const t=e,r=Array(t.length);for(let e=0;eBigInt(0);){const e=r&BigInt(1);r>>=BigInt(1);const a=n*i%t.value;n=e?a:n,i=i*i%t.value}return new se(n)}modInv(e){const{gcd:t,x:r}=this._egcd(e);if(!t.isOne())throw Error("Inverse does not exist");return r.add(e).mod(e)}_egcd(e){let t=BigInt(0),r=BigInt(1),i=BigInt(1),n=BigInt(0),a=this.value;for(e=e.value;e!==BigInt(0);){const s=a/e;let o=t;t=i-s*t,i=o,o=r,r=n-s*r,n=o,o=e,e=a%e,a=o}return{x:new se(i),y:new se(n),gcd:new se(a)}}gcd(e){let t=this.value;for(e=e.value;e!==BigInt(0);){const r=e;e=t%e,t=r}return new se(t)}ileftShift(e){return this.value<<=e.value,this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value>>=e.value,this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value===e.value}lt(e){return this.valuee.value}gte(e){return this.value>=e.value}isZero(){return this.value===BigInt(0)}isOne(){return this.value===BigInt(1)}isNegative(){return this.valueNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return e}getBit(e){return(this.value>>BigInt(e)&BigInt(1))===BigInt(0)?0:1}bitLength(){const e=new se(0),t=new se(1),r=new se(-1),i=this.isNegative()?r:e;let n=1;const a=this.clone();for(;!a.irightShift(t).equal(i);)n++;return n}byteLength(){const e=new se(0),t=new se(-1),r=this.isNegative()?t:e,i=new se(8);let n=1;const a=this.clone();for(;!a.irightShift(i).equal(r);)n++;return n}toUint8Array(e="be",t){let r=this.value.toString(16);r.length%2==1&&(r="0"+r);const i=r.length/2,n=new Uint8Array(t||i),a=t?t-i:0;let s=0;for(;s"undefined"!=typeof BigInt;const ce=Symbol("byValue");var ue={curve:{p256:"p256","P-256":"p256",secp256r1:"p256",prime256v1:"p256","1.2.840.10045.3.1.7":"p256","2a8648ce3d030107":"p256","2A8648CE3D030107":"p256",p384:"p384","P-384":"p384",secp384r1:"p384","1.3.132.0.34":"p384","2b81040022":"p384","2B81040022":"p384",p521:"p521","P-521":"p521",secp521r1:"p521","1.3.132.0.35":"p521","2b81040023":"p521","2B81040023":"p521",secp256k1:"secp256k1","1.3.132.0.10":"secp256k1","2b8104000a":"secp256k1","2B8104000A":"secp256k1",ed25519Legacy:"ed25519",ED25519:"ed25519",ed25519:"ed25519",Ed25519:"ed25519","1.3.6.1.4.1.11591.15.1":"ed25519","2b06010401da470f01":"ed25519","2B06010401DA470F01":"ed25519",curve25519Legacy:"curve25519",X25519:"curve25519",cv25519:"curve25519",curve25519:"curve25519",Curve25519:"curve25519","1.3.6.1.4.1.3029.1.5.1":"curve25519","2b060104019755010501":"curve25519","2B060104019755010501":"curve25519",brainpoolP256r1:"brainpoolP256r1","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1","2b2403030208010107":"brainpoolP256r1","2B2403030208010107":"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1","2b240303020801010b":"brainpoolP384r1","2B240303020801010B":"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1","2b240303020801010d":"brainpoolP512r1","2B240303020801010D":"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,ed25519Legacy:22,eddsa:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuer:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[ce]||(e[ce]=[],Object.entries(e).forEach((([t,r])=>{e[ce][r]=t}))),void 0!==e[ce][t])return e[ce][t];throw Error("Invalid enum value.")}};const he=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),de={isString:function(e){return"string"==typeof e||e instanceof String},isArray:function(e){return e instanceof Array},isUint8Array:P,isStream:E,readNumber:function(e){let t=0;for(let r=0;r>8*(t-i-1)&255;return r},readDate:function(e){const t=de.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return de.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return e.subarray(2,2+t)},leftPad(e,t){const r=new Uint8Array(t),i=t-e.length;return r.set(e,i),r},uint8ArrayToMPI:function(e){const t=de.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),i=new Uint8Array([(65280&t)>>8,255&t]);return de.concatUint8Array([i,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t=[],r=e.length;let i,n=0;for(;n{if(!de.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return X(e,r,(()=>r(new Uint8Array,!0)))},concat:H,concatUint8Array:x,equalsUint8Array:function(e,t){if(!de.isUint8Array(e)||!de.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let i=0;i>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){return void 0!==e&&e.crypto&&e.crypto.subtle},getBigInteger:async function(){if(oe())return se;{const{default:e}=await Promise.resolve().then((function(){return ry}));return e}},getNodeCrypto:function(){return d.default},getNodeZlib:function(){return f.default},getNodeBuffer:function(){return(u.default||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return l.default.cpus().length},isEmailAddress:function(e){if(!de.isString(e))return!1;return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/.test(e)},canonicalizeEOL:function(e){let t=!1;return X(e,(e=>{let r;t&&(e=de.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const i=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&i.push(r);if(!i.length)return e;const n=new Uint8Array(e.length+i.length);let a=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return X(e,(e=>{let r;13===(e=t&&10!==e[0]?de.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let i=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const n=r-(10===e[r]?1:0);t&&e.copyWithin(i,t,n),i+=n-t}return e.subarray(0,i)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let i;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){i=e}}))),r(i)}))},selectUint8Array:function(e,t,r){const i=Math.max(t.length,r.length),n=new Uint8Array(i);let a=0;for(let i=0;i{t=de.concatUint8Array([t,e]);const r=[],i=Math.floor(t.length/45),n=45*i,a=le(t.subarray(0,n));for(let e=0;et.length?le(t)+"\n":""))}function be(e){let t="";return X(e,(e=>{t+=e;let r=0;const i=[" ","\t","\r","\n"];for(let e=0;e0&&(n-r)%4!=0;n--)i.includes(t[n])&&r--;const a=pe(t.substr(0,n));return t=t.substr(n),a}),(()=>pe(t)))}function ge(e){return be(e.replace(/-/g,"+").replace(/_/g,"/"))}function me(e,t){let r=ye(e).replace(/[\r\n]/g,"");return t&&(r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,"")),r}fe?(le=e=>fe.from(e).toString("base64"),pe=e=>{const t=fe.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(le=e=>btoa(de.uint8ArrayToString(e)),pe=e=>de.stringToUint8Array(atob(e)));var we={preferredHashAlgorithm:ue.hash.sha256,preferredSymmetricAlgorithm:ue.symmetric.aes256,preferredCompressionAlgorithm:ue.compression.uncompressed,deflateLevel:6,aeadProtect:!1,preferredAEADAlgorithm:ue.aead.eax,aeadChunkSizeByte:12,v5Keys:!1,s2kIterationCountByte:224,allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,checksumRequired:!1,minRSABits:2047,passwordCollisionCheck:!1,revocationsExpire:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([ue.symmetric.aes128,ue.symmetric.aes192,ue.symmetric.aes256]),minBytesForWebCrypto:1e3,ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 5.11.2",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],useIndutnyElliptic:!0,rejectHashAlgorithms:new Set([ue.hash.md5,ue.hash.ripemd]),rejectMessageHashAlgorithms:new Set([ue.hash.md5,ue.hash.ripemd,ue.hash.sha1]),rejectPublicKeyAlgorithms:new Set([ue.publicKey.elgamal,ue.publicKey.dsa]),rejectCurves:new Set([ue.curve.secp256k1])};function ve(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?ue.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?ue.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?ue.armor.signed:/MESSAGE/.test(t[1])?ue.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?ue.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?ue.armor.privateKey:/SIGNATURE/.test(t[1])?ue.armor.signature:void 0}function _e(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function ke(e){return ye(function(e){let t=13501623;return X(e,(e=>{const r=Se?Math.floor(e.length/4):0,i=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^Ae[1][t>>16&255]^Ae[2][t>>8&255]^Ae[3][t>>0&255];for(let i=4*r;i>8^Ae[0][255&t^e[i]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e))}const Ae=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(0!=(8388608&t)?8801531:0);Ae[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)Ae[1][e]=Ae[0][e]>>8^Ae[0][255&Ae[0][e]];for(let e=0;e<=255;e++)Ae[2][e]=Ae[1][e]>>8^Ae[0][255&Ae[1][e]];for(let e=0;e<=255;e++)Ae[3][e]=Ae[2][e]>>8^Ae[0][255&Ae[2][e]];const Se=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function Ee(e){for(let t=0;t=0&&i!==e.length-1&&(t=e.slice(0,i),r=e.slice(i+1).substr(0,4)),{body:t,checksum:r}}function xe(e,t=we){return new Promise((async(r,i)=>{try{const n=/^-----[^-]+-----$/m,a=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const o=[];let c,u,h,d=o,f=[],l=be(Y(e,(async(e,t)=>{const p=W(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=de.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(c)u||2!==s||(n.test(e)?(f=f.join("\r\n"),u=!0,Ee(d),d=[],c=!1):f.push(e.replace(/^- /,"")));else if(n.test(e)&&i(Error("Mandatory blank line missing between armor headers and armor data")),a.test(e)){if(Ee(d),c=!0,u||2!==s){r({text:f,data:l,headers:o,type:s});break}}else d.push(e);else n.test(e)&&(s=ve(e))}}catch(e){return void i(e)}const y=G(t);try{for(;;){await y.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=de.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=Pe(t[0].slice(0,-1));h=i.checksum,await y.write(i.body);break}await y.write(r)}await y.ready,await y.close()}catch(e){await y.abort(e)}})));l=Y(l,(async(e,r)=>{const i=ie(ke(ee(e)));i.catch((()=>{})),await V(e,r,{preventClose:!0});const n=G(r);try{const e=(await i).replace("\n","");if(h!==e&&(h||t.checksumRequired))throw Error("Ascii armor integrity check failed");await n.ready,await n.close()}catch(e){await n.abort(e)}}))}catch(e){i(e)}})).then((async e=>(_(e.data)&&(e.data=await ie(e.data)),e)))}function Me(e,t,r,i,n,a=we){let s,o;e===ue.armor.signed&&(s=t.text,o=t.hash,t=t.data);const c=ee(t),u=[];switch(e){case ue.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+i+"-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP MESSAGE, PART "+r+"/"+i+"-----\n");break;case ue.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case ue.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push("Hash: "+o+"\n\n"),u.push(s.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP SIGNATURE-----\n");break;case ue.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP MESSAGE-----\n");break;case ue.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case ue.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case ue.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(_e(n,a)),u.push(ye(t)),u.push("=",ke(c)),u.push("-----END PGP SIGNATURE-----\n")}return de.concat(u)}class Ke{constructor(){this.bytes=""}read(e){return this.bytes=de.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return de.stringToUint8Array(this.bytes)}toHex(){return de.uint8ArrayToHex(de.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new Ke;return t.read(de.hexToUint8Array(e)),t}static wildcard(){const e=new Ke;return e.read(new Uint8Array(8)),e}}var Ce=function(){var e,t,r=!1;function i(r,i){var n=e[(t[r]+t[i])%255];return 0!==r&&0!==i||(n=0),n}var n,a,s,o,c=!1;function u(){function u(r){var i,n,a;for(n=a=function(r){var i=e[255-t[r]];return 0===r&&(i=0),i}(r),i=0;i<4;i++)a^=n=255&(n<<1|n>>>7);return a^=99}r||function(){e=[],t=[];var i,n,a=1;for(i=0;i<255;i++)e[i]=a,n=128&a,a<<=1,a&=255,128===n&&(a^=27),a^=e[i],t[e[i]]=i;e[255]=e[0],t[0]=0,r=!0}(),n=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var h=0;h<256;h++){var d=u(h);n[h]=d,a[d]=h,s[0][h]=i(2,d)<<24|d<<16|d<<8|i(3,d),o[0][d]=i(14,h)<<24|i(9,h)<<16|i(13,h)<<8|i(11,h);for(var f=1;f<4;f++)s[f][h]=s[f-1][h]>>>8|s[f-1][h]<<24,o[f][d]=o[f-1][d]>>>8|o[f-1][d]<<24}c=!0}var h=function(e,t){c||u();var r=new Uint32Array(t);r.set(n,512),r.set(a,768);for(var i=0;i<4;i++)r.set(s[i],4096+1024*i>>2),r.set(o[i],8192+1024*i>>2);var h=function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0;var S=new e.Uint32Array(r),E=new e.Uint8Array(r);function P(e,t,r,o,c,u,h,d){e=e|0;t=t|0;r=r|0;o=o|0;c=c|0;u=u|0;h=h|0;d=d|0;var f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;f=r|0x400,l=r|0x800,p=r|0xc00;c=c^S[(e|0)>>2],u=u^S[(e|4)>>2],h=h^S[(e|8)>>2],d=d^S[(e|12)>>2];for(w=16;(w|0)<=o<<4;w=w+16|0){y=S[(r|c>>22&1020)>>2]^S[(f|u>>14&1020)>>2]^S[(l|h>>6&1020)>>2]^S[(p|d<<2&1020)>>2]^S[(e|w|0)>>2],b=S[(r|u>>22&1020)>>2]^S[(f|h>>14&1020)>>2]^S[(l|d>>6&1020)>>2]^S[(p|c<<2&1020)>>2]^S[(e|w|4)>>2],g=S[(r|h>>22&1020)>>2]^S[(f|d>>14&1020)>>2]^S[(l|c>>6&1020)>>2]^S[(p|u<<2&1020)>>2]^S[(e|w|8)>>2],m=S[(r|d>>22&1020)>>2]^S[(f|c>>14&1020)>>2]^S[(l|u>>6&1020)>>2]^S[(p|h<<2&1020)>>2]^S[(e|w|12)>>2];c=y,u=b,h=g,d=m}i=S[(t|c>>22&1020)>>2]<<24^S[(t|u>>14&1020)>>2]<<16^S[(t|h>>6&1020)>>2]<<8^S[(t|d<<2&1020)>>2]^S[(e|w|0)>>2],n=S[(t|u>>22&1020)>>2]<<24^S[(t|h>>14&1020)>>2]<<16^S[(t|d>>6&1020)>>2]<<8^S[(t|c<<2&1020)>>2]^S[(e|w|4)>>2],a=S[(t|h>>22&1020)>>2]<<24^S[(t|d>>14&1020)>>2]<<16^S[(t|c>>6&1020)>>2]<<8^S[(t|u<<2&1020)>>2]^S[(e|w|8)>>2],s=S[(t|d>>22&1020)>>2]<<24^S[(t|c>>14&1020)>>2]<<16^S[(t|u>>6&1020)>>2]<<8^S[(t|h<<2&1020)>>2]^S[(e|w|12)>>2]}function x(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;P(0x0000,0x0800,0x1000,A,e,t,r,i)}function M(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var a=0;P(0x0400,0x0c00,0x2000,A,e,i,r,t);a=n,n=s,s=a}function K(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o^e,c^t,u^r,h^d);o=i,c=n,u=a,h=s}function C(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;var f=0;P(0x0400,0x0c00,0x2000,A,e,d,r,t);f=n,n=s,s=f;i=i^o,n=n^c,a=a^u,s=s^h;o=e,c=t,u=r,h=d}function D(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i=i^e,c=n=n^t,u=a=a^r,h=s=s^d}function U(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);i=i^e,n=n^t,a=a^r,s=s^d;o=e,c=t,u=r,h=d}function R(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i,c=n,u=a,h=s;i=i^e,n=n^t,a=a^r,s=s^d}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;P(0x0000,0x0800,0x1000,A,d,f,l,p);p=~m&p|m&p+1;l=~g&l|g&l+((p|0)==0);f=~b&f|b&f+((l|0)==0);d=~y&d|y&d+((f|0)==0);i=i^e;n=n^t;a=a^r;s=s^o}function B(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,a=0,s=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0;e=e^o,t=t^c,r=r^u,i=i^h;n=w|0,a=v|0,s=_|0,d=k|0;for(;(b|0)<128;b=b+1|0){if(n>>>31){f=f^e,l=l^t,p=p^r,y=y^i}n=n<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|d>>>31,d=d<<1;g=i&1;i=i>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(g)e=e^0xe1000000}o=f,c=l,u=p,h=y}function T(e){e=e|0;A=e}function z(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;i=e,n=t,a=r,s=o}function q(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;o=e,c=t,u=r,h=i}function F(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;d=e,f=t,l=r,p=i}function O(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;y=e,b=t,g=r,m=i}function L(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;p=~m&p|m&i,l=~g&l|g&r,f=~b&f|b&t,d=~y&d|y&e}function N(e){e=e|0;if(e&15)return-1;E[e|0]=i>>>24,E[e|1]=i>>>16&255,E[e|2]=i>>>8&255,E[e|3]=i&255,E[e|4]=n>>>24,E[e|5]=n>>>16&255,E[e|6]=n>>>8&255,E[e|7]=n&255,E[e|8]=a>>>24,E[e|9]=a>>>16&255,E[e|10]=a>>>8&255,E[e|11]=a&255,E[e|12]=s>>>24,E[e|13]=s>>>16&255,E[e|14]=s>>>8&255,E[e|15]=s&255;return 16}function j(e){e=e|0;if(e&15)return-1;E[e|0]=o>>>24,E[e|1]=o>>>16&255,E[e|2]=o>>>8&255,E[e|3]=o&255,E[e|4]=c>>>24,E[e|5]=c>>>16&255,E[e|6]=c>>>8&255,E[e|7]=c&255,E[e|8]=u>>>24,E[e|9]=u>>>16&255,E[e|10]=u>>>8&255,E[e|11]=u&255,E[e|12]=h>>>24,E[e|13]=h>>>16&255,E[e|14]=h>>>8&255,E[e|15]=h&255;return 16}function H(){x(0,0,0,0);w=i,v=n,_=a,k=s}function W(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){V[e&7](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);E[t|0]=i>>>24,E[t|1]=i>>>16&255,E[t|2]=i>>>8&255,E[t|3]=i&255,E[t|4]=n>>>24,E[t|5]=n>>>16&255,E[t|6]=n>>>8&255,E[t|7]=n&255,E[t|8]=a>>>24,E[t|9]=a>>>16&255,E[t|10]=a>>>8&255,E[t|11]=a&255,E[t|12]=s>>>24,E[t|13]=s>>>16&255,E[t|14]=s>>>8&255,E[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function G(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t&15)return-1;while((r|0)>=16){$[e&1](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);i=i+16|0,t=t+16|0,r=r-16|0}return i|0}var V=[x,M,K,C,D,U,R,I];var $=[K,B];return{set_rounds:T,set_state:z,set_iv:q,set_nonce:F,set_mask:O,set_counter:L,get_state:N,get_iv:j,gcm_init:H,cipher:W,mac:G}}({Uint8Array,Uint32Array},e,t);return h.set_key=function(e,t,i,a,s,c,u,d,f){var l=r.subarray(0,60),p=r.subarray(256,316);l.set([t,i,a,s,c,u,d,f]);for(var y=e,b=1;y<4*e+28;y++){var g=l[y-1];(y%e==0||8===e&&y%e==4)&&(g=n[g>>>24]<<24^n[g>>>16&255]<<16^n[g>>>8&255]<<8^n[255&g]),y%e==0&&(g=g<<8^g>>>24^b<<24,b=b<<1^(128&b?27:0)),l[y]=l[y-e]^g}for(var m=0;m=y-4?g:o[0][n[g>>>24]]^o[1][n[g>>>16&255]]^o[2][n[g>>>8&255]]^o[3][n[255&g]]}h.set_rounds(e+5)},h};return h.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},h.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},h.MAC={CBC:0,GCM:1},h.HEAP_DATA=16384,h}();function De(e){return e instanceof Uint8Array}function Ue(e,t){const r=e?e.byteLength:t||65536;if(4095&r||r<=0)throw Error("heap size must be a positive integer and a multiple of 4096");return e=e||new Uint8Array(new ArrayBuffer(r))}function Re(e,t,r,i,n){const a=e.length-t,s=ae+t.length),0),r=new Uint8Array(t);let i=0;for(let t=0;t>2,n.getUint32(0),n.getUint32(4),n.getUint32(8),n.getUint32(12),i>16?n.getUint32(16):0,i>16?n.getUint32(20):0,i>24?n.getUint32(24):0,i>24?n.getUint32(28):0),void 0!==t){if(16!==t.length)throw new Te("illegal iv size");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);r.set_iv(e.getUint32(0),e.getUint32(4),e.getUint32(8),e.getUint32(12))}else r.set_iv(0,0,0,0)}AES_Encrypt_process(e){if(!De(e))throw new TypeError("data isn't of expected type");let{heap:t,asm:r}=this.acquire_asm(),i=Ce.ENC[this.mode],n=Ce.HEAP_DATA,a=this.pos,s=this.len,o=0,c=e.length||0,u=0,h=0,d=new Uint8Array(s+c&-16);for(;c>0;)h=Re(t,a+s,e,o,c),s+=h,o+=h,c-=h,h=r.cipher(i,n+a,s),h&&d.set(t.subarray(a,a+h),u),u+=h,h0;)f=Re(t,a+s,e,o,c),s+=f,o+=f,c-=f,f=r.cipher(i,n+a,s-(c?0:d)),f&&l.set(t.subarray(a,a+f),u),u+=f,f0){if(a%16){if(this.hasOwnProperty("padding"))throw new Te("data length must be a multiple of the block size");a+=16-a%16}if(t.cipher(r,i+n,a),this.hasOwnProperty("padding")&&this.padding){let t=e[n+s-1];if(t<1||t>16||t>s)throw new ze("bad padding");let r=0;for(let i=t;i>1;i--)r|=t^e[n+s-i];if(r)throw new ze("bad padding");s-=t}}const o=new Uint8Array(s);return s>0&&o.set(e.subarray(n,n+s)),this.pos=0,this.len=0,this.release_asm(),o}}class Le{static encrypt(e,t,r=!1){return new Le(t,r).encrypt(e)}static decrypt(e,t,r=!1){return new Le(t,r).decrypt(e)}constructor(e,t=!1,r){this.aes=r||new Oe(e,void 0,t,"ECB")}encrypt(e){return Ie(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return Ie(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}function Ne(e){const t=function(e){const t=new Le(e);this.encrypt=function(e){return t.encrypt(e)},this.decrypt=function(e){return t.decrypt(e)}};return t.blockSize=t.prototype.blockSize=16,t.keySize=t.prototype.keySize=e/8,t}function je(e,t,r,i,n,a){const s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],u=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],h=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],d=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],f=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],l=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,y,b,g,m,w,v,_,k,A,S,E,P,x,M=0,K=t.length;const C=32===e.length?3:9;_=3===C?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e,t){const r=8-e.length%8;let i;if(2===t&&r<8)i=32;else if(1===t)i=r;else{if(t||!(r<8)){if(8===r)return e;throw Error("des: invalid padding")}i=0}const n=new Uint8Array(e.length+r);for(let t=0;t>>4^v),v^=b,w^=b<<4,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,w=w<<1|w>>>31,v=v<<1|v>>>31,y=0;y>>4|v<<28)^e[p+1],b=w,w=v,v=b^(o[g>>>24&63]|u[g>>>16&63]|d[g>>>8&63]|l[63&g]|s[m>>>24&63]|c[m>>>16&63]|h[m>>>8&63]|f[63&m]);b=w,w=v,v=b}w=w>>>1|w<<31,v=v>>>1|v<<31,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=252645135&(w>>>4^v),v^=b,w^=b<<4,1===i&&(r?(k=w,S=v):(w^=A,v^=E)),D[U++]=w>>>24,D[U++]=w>>>16&255,D[U++]=w>>>8&255,D[U++]=255&w,D[U++]=v>>>24,D[U++]=v>>>16&255,D[U++]=v>>>8&255,D[U++]=255&v}return r||(D=function(e,t){let r,i=null;if(2===t)r=32;else if(1===t)i=e[e.length-1];else{if(t)throw Error("des: invalid padding");r=0}if(!i){for(i=1;e[e.length-i]===r;)i++;i--}return e.subarray(0,e.length-i)}(D,a)),D}function He(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],l=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length>8?3:1,b=Array(32*y),g=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let m,w,v,_=0,k=0;for(let A=0;A>>4^A),A^=v,y^=v<<4,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=858993459&(y>>>2^A),A^=v,y^=v<<2,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=16711935&(A>>>8^y),y^=v,A^=v<<8,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=y<<8|A>>>20&240,y=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=v;for(let e=0;e<16;e++)g[e]?(y=y<<2|y>>>26,A=A<<2|A>>>26):(y=y<<1|y>>>27,A=A<<1|A>>>27),y&=-15,A&=-15,m=t[y>>>28]|r[y>>>24&15]|i[y>>>20&15]|n[y>>>16&15]|a[y>>>12&15]|s[y>>>8&15]|o[y>>>4&15],w=c[A>>>28]|u[A>>>24&15]|h[A>>>20&15]|d[A>>>16&15]|f[A>>>12&15]|l[A>>>8&15]|p[A>>>4&15],v=65535&(w>>>16^m),b[k++]=m^v,b[k++]=w^v<<16}return b}function We(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return je(He(this.key[2]),je(He(this.key[1]),je(He(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}function Ge(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>>16&255,t[a+6]=o>>>8&255,t[a+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>16&255,t[a+6]=o>>8&255,t[a+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const i=t+e,n=i<>>32-r;return(a[0][n>>>24]^a[1][n>>>16&255])-a[2][n>>>8&255]+a[3][255&n]}function i(e,t,r){const i=t^e,n=i<>>32-r;return a[0][n>>>24]-a[1][n>>>16&255]+a[2][n>>>8&255]^a[3][255&n]}function n(e,t,r){const i=t-e,n=i<>>32-r;return(a[0][n>>>24]+a[1][n>>>16&255]^a[2][n>>>8&255])-a[3][255&n]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const i=[,,,,,,,,],n=Array(32);let s;for(let e=0;e<4;e++)s=4*e,i[e]=r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3];const o=[6,7,4,5];let c,u=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(s=0;s<4;s++){const t=e[r][s];c=i[t[1]],c^=a[4][i[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=a[5][i[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=a[6][i[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=a[7][i[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=a[o[s]][i[t[6]>>>2]>>>24-8*(3&t[6])&255],i[t[0]]=c}for(s=0;s<4;s++){const e=t[r][s];c=a[4][i[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=a[5][i[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=a[6][i[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=a[7][i[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=a[4+s][i[e[4]>>>2]>>>24-8*(3&e[4])&255],n[u]=c,u++}}for(let e=0;e<16;e++)this.masking[e]=n[e],this.rotate[e]=31&n[16+e]};const a=[,,,,,,,,];a[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],a[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],a[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],a[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],a[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],a[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],a[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],a[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Ve(e){this.cast5=new Ge,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}We.keySize=We.prototype.keySize=24,We.blockSize=We.prototype.blockSize=8,Ve.blockSize=Ve.prototype.blockSize=8,Ve.keySize=Ve.prototype.keySize=16;const $e=4294967295;function Ze(e,t){return(e<>>32-t)&$e}function Xe(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ye(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function Qe(e,t){return e>>>8*t&255}function Je(e){this.tf=function(){let e=null,t=null,r=-1,i=[],n=[[],[],[],[]];function a(e){return n[0][Qe(e,0)]^n[1][Qe(e,1)]^n[2][Qe(e,2)]^n[3][Qe(e,3)]}function s(e){return n[0][Qe(e,3)]^n[1][Qe(e,0)]^n[2][Qe(e,1)]^n[3][Qe(e,2)]}function o(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Ze(t[2]^r+n+i[4*e+8]&$e,31),t[3]=Ze(t[3],1)^r+2*n+i[4*e+9]&$e,r=a(t[2]),n=s(t[3]),t[0]=Ze(t[0]^r+n+i[4*e+10]&$e,31),t[1]=Ze(t[1],1)^r+2*n+i[4*e+11]&$e}function c(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Ze(t[2],1)^r+n+i[4*e+10]&$e,t[3]=Ze(t[3]^r+2*n+i[4*e+11]&$e,31),r=a(t[2]),n=s(t[3]),t[0]=Ze(t[0],1)^r+n+i[4*e+8]&$e,t[1]=Ze(t[1]^r+2*n+i[4*e+9]&$e,31)}return{name:"twofish",blocksize:16,open:function(t){let r,a,s,o,c;e=t;const u=[],h=[],d=[];let f;const l=[];let p,y,b;const g=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],m=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],w=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],v=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],_=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],k=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],A=[[],[]],S=[[],[],[],[]];function E(e){return e^e>>2^[0,90,180,238][3&e]}function P(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function x(e,t){let r,i,n;for(r=0;r<8;r++)i=t>>>24,t=t<<8&$e|e>>>24,e=e<<8&$e,n=i<<1,128&i&&(n^=333),t^=i^n<<16,n^=i>>>1,1&i&&(n^=166),t^=n<<24|n<<8;return t}function M(e,t){const r=t>>4,i=15&t,n=g[e][r^i],a=m[e][_[i]^k[r]];return v[e][_[a]^k[n]]<<4|w[e][n^a]}function K(e,t){let r=Qe(e,0),i=Qe(e,1),n=Qe(e,2),a=Qe(e,3);switch(f){case 4:r=A[1][r]^Qe(t[3],0),i=A[0][i]^Qe(t[3],1),n=A[0][n]^Qe(t[3],2),a=A[1][a]^Qe(t[3],3);case 3:r=A[1][r]^Qe(t[2],0),i=A[1][i]^Qe(t[2],1),n=A[0][n]^Qe(t[2],2),a=A[0][a]^Qe(t[2],3);case 2:r=A[0][A[0][r]^Qe(t[1],0)]^Qe(t[0],0),i=A[0][A[1][i]^Qe(t[1],1)]^Qe(t[0],1),n=A[1][A[0][n]^Qe(t[1],2)]^Qe(t[0],2),a=A[1][A[1][a]^Qe(t[1],3)]^Qe(t[0],3)}return S[0][r]^S[1][i]^S[2][n]^S[3][a]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Xe(e,r);for(r=0;r<256;r++)A[0][r]=M(0,r),A[1][r]=M(1,r);for(r=0;r<256;r++)p=A[1][r],y=E(p),b=P(p),S[0][r]=p+(y<<8)+(b<<16)+(b<<24),S[2][r]=y+(b<<8)+(p<<16)+(b<<24),p=A[0][r],y=E(p),b=P(p),S[1][r]=b+(b<<8)+(y<<16)+(p<<24),S[3][r]=y+(p<<8)+(b<<16)+(y<<24);for(f=d.length/2,r=0;r=0;e--)c(e,a);Ye(t,r,a[2]^i[0]),Ye(t,r+4,a[3]^i[1]),Ye(t,r+8,a[0]^i[2]),Ye(t,r+12,a[1]^i[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function et(){}function tt(e){this.bf=new et,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}Je.keySize=Je.prototype.keySize=32,Je.blockSize=Je.prototype.blockSize=16,et.prototype.BLOCKSIZE=8,et.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],et.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],et.prototype.NN=16,et.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},et.prototype._F=function(e){let t;const r=255&e,i=255&(e>>>=8),n=255&(e>>>=8),a=255&(e>>>=8);return t=this.sboxes[0][a]+this.sboxes[1][n],t^=this.sboxes[2][i],t+=this.sboxes[3][r],t},et.prototype._encryptBlock=function(e){let t,r=e[0],i=e[1];for(t=0;t>>24-8*t&255,n[t+i]=r[1]>>>24-8*t&255;return n},et.prototype._decryptBlock=function(e){let t,r=e[0],i=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],i=this._F(r)^i;const e=r;r=i,i=e}r^=this.parray[1],i^=this.parray[0],e[0]=this._clean(i),e[1]=this._clean(r)},et.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^i}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const i=[0,0];for(t=0;t>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=t+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=r+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=c+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=u+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=h+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k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|v[e|42]<<8|v[e|43],v[e|44]<<24|v[e|45]<<16|v[e|46]<<8|v[e|47],v[e|48]<<24|v[e|49]<<16|v[e|50]<<8|v[e|51],v[e|52]<<24|v[e|53]<<16|v[e|54]<<8|v[e|55],v[e|56]<<24|v[e|57]<<16|v[e|58]<<8|v[e|59],v[e|60]<<24|v[e|61]<<16|v[e|62]<<8|v[e|63])}function A(e){e=e|0;v[e|0]=i>>>24;v[e|1]=i>>>16&255;v[e|2]=i>>>8&255;v[e|3]=i&255;v[e|4]=n>>>24;v[e|5]=n>>>16&255;v[e|6]=n>>>8&255;v[e|7]=n&255;v[e|8]=a>>>24;v[e|9]=a>>>16&255;v[e|10]=a>>>8&255;v[e|11]=a&255;v[e|12]=s>>>24;v[e|13]=s>>>16&255;v[e|14]=s>>>8&255;v[e|15]=s&255;v[e|16]=o>>>24;v[e|17]=o>>>16&255;v[e|18]=o>>>8&255;v[e|19]=o&255}function S(){i=0x67452301;n=0xefcdab89;a=0x98badcfe;s=0x10325476;o=0xc3d2e1f0;c=u=0}function E(e,t,r,h,d,f,l){e=e|0;t=t|0;r=r|0;h=h|0;d=d|0;f=f|0;l=l|0;i=e;n=t;a=r;s=h;o=d;c=f;u=l}function P(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){k(e);e=e+64|0;t=t-64|0;r=r+64|0}c=c+r|0;if(c>>>0>>0)u=u+1|0;return r|0}function x(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=P(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;c=c+t|0;if(c>>>0>>0)u=u+1|0;v[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)v[e|n]=0x00;k(e);t=0;v[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)v[e|n]=0;v[e|56]=u>>>21&255;v[e|57]=u>>>13&255;v[e|58]=u>>>5&255;v[e|59]=u<<3&255|c>>>29;v[e|60]=c>>>21&255;v[e|61]=c>>>13&255;v[e|62]=c>>>5&255;v[e|63]=c<<3&255;k(e);if(~r)A(r);return i|0}function M(){i=h;n=d;a=f;s=l;o=p;c=64;u=0}function K(){i=y;n=b;a=g;s=m;o=w;c=64;u=0}function C(e,t,r,v,k,A,E,P,x,M,K,C,D,U,R,I){e=e|0;t=t|0;r=r|0;v=v|0;k=k|0;A=A|0;E=E|0;P=P|0;x=x|0;M=M|0;K=K|0;C=C|0;D=D|0;U=U|0;R=R|0;I=I|0;S();_(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,v^0x5c5c5c5c,k^0x5c5c5c5c,A^0x5c5c5c5c,E^0x5c5c5c5c,P^0x5c5c5c5c,x^0x5c5c5c5c,M^0x5c5c5c5c,K^0x5c5c5c5c,C^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,R^0x5c5c5c5c,I^0x5c5c5c5c);y=i;b=n;g=a;m=s;w=o;S();_(e^0x36363636,t^0x36363636,r^0x36363636,v^0x36363636,k^0x36363636,A^0x36363636,E^0x36363636,P^0x36363636,x^0x36363636,M^0x36363636,K^0x36363636,C^0x36363636,D^0x36363636,U^0x36363636,R^0x36363636,I^0x36363636);h=i;d=n;f=a;l=s;p=o;c=64;u=0}function D(e,t,r){e=e|0;t=t|0;r=r|0;var c=0,u=0,h=0,d=0,f=0,l=0;if(e&63)return-1;if(~r)if(r&31)return-1;l=x(e,t,-1)|0;c=i,u=n,h=a,d=s,f=o;K();_(c,u,h,d,f,0x80000000,0,0,0,0,0,0,0,0,0,672);if(~r)A(r);return l|0}function U(e,t,r,c,u){e=e|0;t=t|0;r=r|0;c=c|0;u=u|0;var h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;if(e&63)return-1;if(~u)if(u&31)return-1;v[e+t|0]=r>>>24;v[e+t+1|0]=r>>>16&255;v[e+t+2|0]=r>>>8&255;v[e+t+3|0]=r&255;D(e,t+4|0,-1)|0;h=y=i,d=b=n,f=g=a,l=m=s,p=w=o;c=c-1|0;while((c|0)>0){M();_(y,b,g,m,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,g=a,m=s,w=o;K();_(y,b,g,m,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,g=a,m=s,w=o;h=h^i;d=d^n;f=f^a;l=l^s;p=p^o;c=c-1|0}i=h;n=d;a=f;s=l;o=p;if(~u)A(u);return 0}return{reset:S,init:E,process:P,finish:x,hmac_reset:M,hmac_init:C,hmac_finish:D,pbkdf2_generate_block:U}};class ct{constructor(){this.pos=0,this.len=0}reset(){const{asm:e}=this.acquire_asm();return this.result=null,this.pos=0,this.len=0,e.reset(),this}process(e){if(null!==this.result)throw new Be("state must be reset before processing new data");const{asm:t,heap:r}=this.acquire_asm();let i=this.pos,n=this.len,a=0,s=e.length,o=0;for(;s>0;)o=Re(r,i+n,e,a,s),n+=o,a+=o,s-=o,o=t.process(i,n),i+=o,n-=o,n||(i=0);return this.pos=i,this.len=n,this}finish(){if(null!==this.result)throw new Be("state must be reset before processing new data");const{asm:e,heap:t}=this.acquire_asm();return e.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(t.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this.release_asm(),this}}const ut=[],ht=[];class dt extends ct{constructor(){super(),this.NAME="sha1",this.BLOCK_SIZE=64,this.HASH_SIZE=20,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=ut.pop()||Ue(),this.asm=ht.pop()||ot({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(ut.push(this.heap),ht.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new dt).process(e).finish().result}}dt.NAME="sha1",dt.heap_pool=[],dt.asm_pool=[],dt.asm_function=ot;const ft=[],lt=[];class pt extends ct{constructor(){super(),this.NAME="sha256",this.BLOCK_SIZE=64,this.HASH_SIZE=32,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=ft.pop()||Ue(),this.asm=lt.pop()||function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=new e.Uint8Array(r);function C(e,t,r,d,f,l,p,y,b,g,m,w,v,_,k,A){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;l=l|0;p=p|0;y=y|0;b=b|0;g=g|0;m=m|0;w=w|0;v=v|0;_=_|0;k=k|0;A=A|0;var S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0;S=i;E=n;P=a;x=s;M=o;K=c;C=u;D=h;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x428a2f98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x71374491|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb5c0fbcf|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xe9b5dba5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x3956c25b|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x59f111f1|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x923f82a4|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xab1c5ed5|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xd807aa98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x12835b01|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x243185be|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x550c7dc3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x72be5d74|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x80deb1fe|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x9bdc06a7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc19bf174|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xe49b69c1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xefbe4786|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x0fc19dc6|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x240ca1cc|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x2de92c6f|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4a7484aa|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5cb0a9dc|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x76f988da|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x983e5152|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa831c66d|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb00327c8|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xbf597fc7|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xc6e00bf3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd5a79147|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x06ca6351|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x14292967|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x27b70a85|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x2e1b2138|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x4d2c6dfc|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x53380d13|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x650a7354|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x766a0abb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x81c2c92e|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x92722c85|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xa2bfe8a1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa81a664b|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xc24b8b70|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xc76c51a3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xd192e819|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd6990624|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xf40e3585|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x106aa070|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x19a4c116|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x1e376c08|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x2748774c|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x34b0bcb5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x391c0cb3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4ed8aa4a|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5b9cca4f|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x682e6ff3|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x748f82ee|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x78a5636f|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x84c87814|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x8cc70208|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x90befffa|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xa4506ceb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xbef9a3f7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc67178f2|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;i=i+S|0;n=n+E|0;a=a+P|0;s=s+x|0;o=o+M|0;c=c+K|0;u=u+C|0;h=h+D|0}function D(e){e=e|0;C(K[e|0]<<24|K[e|1]<<16|K[e|2]<<8|K[e|3],K[e|4]<<24|K[e|5]<<16|K[e|6]<<8|K[e|7],K[e|8]<<24|K[e|9]<<16|K[e|10]<<8|K[e|11],K[e|12]<<24|K[e|13]<<16|K[e|14]<<8|K[e|15],K[e|16]<<24|K[e|17]<<16|K[e|18]<<8|K[e|19],K[e|20]<<24|K[e|21]<<16|K[e|22]<<8|K[e|23],K[e|24]<<24|K[e|25]<<16|K[e|26]<<8|K[e|27],K[e|28]<<24|K[e|29]<<16|K[e|30]<<8|K[e|31],K[e|32]<<24|K[e|33]<<16|K[e|34]<<8|K[e|35],K[e|36]<<24|K[e|37]<<16|K[e|38]<<8|K[e|39],K[e|40]<<24|K[e|41]<<16|K[e|42]<<8|K[e|43],K[e|44]<<24|K[e|45]<<16|K[e|46]<<8|K[e|47],K[e|48]<<24|K[e|49]<<16|K[e|50]<<8|K[e|51],K[e|52]<<24|K[e|53]<<16|K[e|54]<<8|K[e|55],K[e|56]<<24|K[e|57]<<16|K[e|58]<<8|K[e|59],K[e|60]<<24|K[e|61]<<16|K[e|62]<<8|K[e|63])}function U(e){e=e|0;K[e|0]=i>>>24;K[e|1]=i>>>16&255;K[e|2]=i>>>8&255;K[e|3]=i&255;K[e|4]=n>>>24;K[e|5]=n>>>16&255;K[e|6]=n>>>8&255;K[e|7]=n&255;K[e|8]=a>>>24;K[e|9]=a>>>16&255;K[e|10]=a>>>8&255;K[e|11]=a&255;K[e|12]=s>>>24;K[e|13]=s>>>16&255;K[e|14]=s>>>8&255;K[e|15]=s&255;K[e|16]=o>>>24;K[e|17]=o>>>16&255;K[e|18]=o>>>8&255;K[e|19]=o&255;K[e|20]=c>>>24;K[e|21]=c>>>16&255;K[e|22]=c>>>8&255;K[e|23]=c&255;K[e|24]=u>>>24;K[e|25]=u>>>16&255;K[e|26]=u>>>8&255;K[e|27]=u&255;K[e|28]=h>>>24;K[e|29]=h>>>16&255;K[e|30]=h>>>8&255;K[e|31]=h&255}function R(){i=0x6a09e667;n=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;h=0x5be0cd19;d=f=0}function I(e,t,r,l,p,y,b,g,m,w){e=e|0;t=t|0;r=r|0;l=l|0;p=p|0;y=y|0;b=b|0;g=g|0;m=m|0;w=w|0;i=e;n=t;a=r;s=l;o=p;c=y;u=b;h=g;d=m;f=w}function B(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){D(e);e=e+64|0;t=t-64|0;r=r+64|0}d=d+r|0;if(d>>>0>>0)f=f+1|0;return r|0}function T(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=B(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;d=d+t|0;if(d>>>0>>0)f=f+1|0;K[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)K[e|n]=0x00;D(e);t=0;K[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)K[e|n]=0;K[e|56]=f>>>21&255;K[e|57]=f>>>13&255;K[e|58]=f>>>5&255;K[e|59]=f<<3&255|d>>>29;K[e|60]=d>>>21&255;K[e|61]=d>>>13&255;K[e|62]=d>>>5&255;K[e|63]=d<<3&255;D(e);if(~r)U(r);return i|0}function z(){i=l;n=p;a=y;s=b;o=g;c=m;u=w;h=v;d=64;f=0}function q(){i=_;n=k;a=A;s=S;o=E;c=P;u=x;h=M;d=64;f=0}function F(e,t,r,K,D,U,I,B,T,z,q,F,O,L,N,j){e=e|0;t=t|0;r=r|0;K=K|0;D=D|0;U=U|0;I=I|0;B=B|0;T=T|0;z=z|0;q=q|0;F=F|0;O=O|0;L=L|0;N=N|0;j=j|0;R();C(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,K^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,I^0x5c5c5c5c,B^0x5c5c5c5c,T^0x5c5c5c5c,z^0x5c5c5c5c,q^0x5c5c5c5c,F^0x5c5c5c5c,O^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,j^0x5c5c5c5c);_=i;k=n;A=a;S=s;E=o;P=c;x=u;M=h;R();C(e^0x36363636,t^0x36363636,r^0x36363636,K^0x36363636,D^0x36363636,U^0x36363636,I^0x36363636,B^0x36363636,T^0x36363636,z^0x36363636,q^0x36363636,F^0x36363636,O^0x36363636,L^0x36363636,N^0x36363636,j^0x36363636);l=i;p=n;y=a;b=s;g=o;m=c;w=u;v=h;d=64;f=0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;if(e&63)return-1;if(~r)if(r&31)return-1;w=T(e,t,-1)|0;d=i,f=n,l=a,p=s,y=o,b=c,g=u,m=h;q();C(d,f,l,p,y,b,g,m,0x80000000,0,0,0,0,0,0,768);if(~r)U(r);return w|0}function L(e,t,r,d,f){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;var l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0;if(e&63)return-1;if(~f)if(f&31)return-1;K[e+t|0]=r>>>24;K[e+t+1|0]=r>>>16&255;K[e+t+2|0]=r>>>8&255;K[e+t+3|0]=r&255;O(e,t+4|0,-1)|0;l=_=i,p=k=n,y=A=a,b=S=s,g=E=o,m=P=c,w=x=u,v=M=h;d=d-1|0;while((d|0)>0){z();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;q();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;l=l^i;p=p^n;y=y^a;b=b^s;g=g^o;m=m^c;w=w^u;v=v^h;d=d-1|0}i=l;n=p;a=y;s=b;o=g;c=m;u=w;h=v;if(~f)U(f);return 0}return{reset:R,init:I,process:B,finish:T,hmac_reset:z,hmac_init:F,hmac_finish:O,pbkdf2_generate_block:L}}({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(ft.push(this.heap),lt.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new pt).process(e).finish().result}}pt.NAME="sha256";var yt=bt;function bt(e,t){if(!e)throw Error(t||"Assertion failed")}bt.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)};var gt=void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function mt(e,t){return e(t={exports:{}},t.exports),t.exports}function wt(){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var vt=mt((function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}})),_t=mt((function(e){try{var t=p.default;if("function"!=typeof t.inherits)throw"";e.exports=t.inherits}catch(t){e.exports=vt}}));var kt=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>8,s=255&n;a?r.push(a,s):r.push(s)}else for(i=0;i>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}var Et=function(e,t){for(var r="",i=0;i>>0}return a};var Kt=function(e,t){for(var r=Array(4*e.length),i=0,n=0;i>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r};var Ct={inherits:_t,toArray:kt,toHex:At,htonl:St,toHex32:Et,zero2:Pt,zero8:xt,join32:Mt,split32:Kt,rotr32:function(e,t){return e>>>t|e<<32-t},rotl32:function(e,t){return e<>>32-t},sum32:function(e,t){return e+t>>>0},sum32_3:function(e,t,r){return e+t+r>>>0},sum32_4:function(e,t,r,i){return e+t+r+i>>>0},sum32_5:function(e,t,r,i,n){return e+t+r+i+n>>>0},sum64:function(e,t,r,i){var n=e[t],a=i+e[t+1]>>>0,s=(a>>0,e[t+1]=a},sum64_hi:function(e,t,r,i){return(t+i>>>0>>0},sum64_lo:function(e,t,r,i){return t+i>>>0},sum64_4_hi:function(e,t,r,i,n,a,s,o){var c=0,u=t;return c+=(u=u+i>>>0)>>0)>>0)>>0},sum64_4_lo:function(e,t,r,i,n,a,s,o){return t+i+a+o>>>0},sum64_5_hi:function(e,t,r,i,n,a,s,o,c,u){var h=0,d=t;return h+=(d=d+i>>>0)>>0)>>0)>>0)>>0},sum64_5_lo:function(e,t,r,i,n,a,s,o,c,u){return t+i+a+o+u>>>0},rotr64_hi:function(e,t,r){return(t<<32-r|e>>>r)>>>0},rotr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0},shr64_hi:function(e,t,r){return e>>>r},shr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0}};function Dt(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var Ut=Dt;Dt.prototype.update=function(e,t){if(e=Ct.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=Ct.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,a=8;a>>3},g1_256:function(e){return It(e,17)^It(e,19)^e>>>10}},Ot=Ct.sum32,Lt=Ct.sum32_4,Nt=Ct.sum32_5,jt=Ft.ch32,Ht=Ft.maj32,Wt=Ft.s0_256,Gt=Ft.s1_256,Vt=Ft.g0_256,$t=Ft.g1_256,Zt=Rt.BlockHash,Xt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Yt(){if(!(this instanceof Yt))return new Yt;Zt.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=Xt,this.W=Array(64)}Ct.inherits(Yt,Zt);var Qt=Yt;function Jt(){if(!(this instanceof Jt))return new Jt;Qt.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Yt.blockSize=512,Yt.outSize=256,Yt.hmacStrength=192,Yt.padLength=64,Yt.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i>>32-n,r)}function Vr(e,t,r,i,n,a,s){return Gr(t&r|~t&i,e,t,n,a,s)}function $r(e,t,r,i,n,a,s){return Gr(t&i|r&~i,e,t,n,a,s)}function Zr(e,t,r,i,n,a,s){return Gr(t^r^i,e,t,n,a,s)}function Xr(e,t,r,i,n,a,s){return Gr(r^(t|~i),e,t,n,a,s)}function Yr(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const Qr="0123456789abcdef".split("");function Jr(e){let t="",r=0;for(;r<4;r++)t+=Qr[e>>8*r+4&15]+Qr[e>>8*r&15];return t}function ei(e,t){return e+t&4294967295}const ti=de.getWebCrypto(),ri=de.getNodeCrypto(),ii=ri&&ri.getHashes();function ni(e){if(ri&&ii.includes(e))return async function(t){const r=ri.createHash(e);return X(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function ai(e,t){return async function(r,i=we){if(_(r)&&(r=await ie(r)),!de.isStream(r)&&ti&&t&&r.length>=i.minBytesForWebCrypto)return new Uint8Array(await ti.digest(t,r));const n=e();return X(r,(e=>{n.update(e)}),(()=>new Uint8Array(n.digest())))}}function si(e,t){return async function(r,i=we){if(_(r)&&(r=await ie(r)),de.isStream(r)){const t=new e;return X(r,(e=>{t.process(e)}),(()=>t.finish().result))}return ti&&t&&r.length>=i.minBytesForWebCrypto?new Uint8Array(await ti.digest(t,r)):e.bytes(r)}}const oi={md5:ni("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let i;for(i=64;i<=e.length;i+=64)Wr(r,Yr(e.substring(i-64,i)));e=e.substring(i-64);const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i>2]|=e.charCodeAt(i)<<(i%4<<3);if(n[i>>2]|=128<<(i%4<<3),i>55)for(Wr(r,n),i=0;i<16;i++)n[i]=0;return n[14]=8*t,Wr(r,n),r}(de.uint8ArrayToString(e));return de.hexToUint8Array(function(e){for(let t=0;tnew Uint8Array(a.update(e))))}(e,t,r,i);if(de.isAES(e))return function(e,t,r,i,n){if(de.getWebCrypto()&&24!==t.length&&!de.isStream(r)&&r.length>=3e3*n.minBytesForWebCrypto)return async function(e,t,r,i){const n="AES-CBC",a=await di.importKey("raw",t,{name:n},!1,["encrypt"]),{blockSize:s}=hi(e),o=de.concatUint8Array([new Uint8Array(s),r]),c=new Uint8Array(await di.encrypt({name:n,iv:i},a,o)).subarray(0,r.length);return function(e,t){for(let r=0;ra.aes.AES_Encrypt_process(e)),(()=>a.aes.AES_Encrypt_finish()))}(e,t,r,i,n);const s=new(hi(e))(t),o=s.blockSize,c=i.slice();let u=new Uint8Array;const h=e=>{e&&(u=de.concatUint8Array([u,e]));const t=new Uint8Array(u.length);let r,i=0;for(;e?u.length>=o:u.length;){const e=s.encrypt(c);for(r=0;rnew Uint8Array(a.update(e))))}(e,t,r,i);if(de.isAES(e))return function(e,t,r,i){if(de.isStream(r)){const e=new ui(t,i);return X(r,(t=>e.aes.AES_Decrypt_process(t)),(()=>e.aes.AES_Decrypt_finish()))}return ui.decrypt(r,t,i)}(0,t,r,i);const a=new(hi(e))(t),s=a.blockSize;let o=i,c=new Uint8Array;const u=e=>{e&&(c=de.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,i=0;for(;e?c.length>=s:c.length;){const e=a.encrypt(o);for(o=c.subarray(0,s),r=0;r48)throw new Te("illegal counter size");let e=Math.pow(2,r)-1;i.set_mask(0,0,e/4294967296|0,0|e)}else r=48,i.set_mask(0,0,65535,4294967295);if(void 0===e)throw Error("nonce is required");{let t=e.length;if(!t||t>16)throw new Te("illegal nonce size");let r=new DataView(new ArrayBuffer(16));new Uint8Array(r.buffer).set(e),i.set_nonce(r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12))}if(void 0!==t){if(t<0||t>=Math.pow(2,r))throw new Te("illegal counter value");i.set_counter(0,0,t/4294967296|0,0|t)}}}class gi{static encrypt(e,t,r=!0,i){return new gi(t,i,r).encrypt(e)}static decrypt(e,t,r=!0,i){return new gi(t,i,r).decrypt(e)}constructor(e,t,r=!0,i){this.aes=i||new Oe(e,t,r,"CBC")}encrypt(e){return Ie(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return Ie(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}const mi=de.getWebCrypto(),wi=de.getNodeCrypto(),vi=16;function _i(e,t){const r=e.length-vi;for(let i=0;i>3),17+(u>>3)),8-(7&u)).subarray(1),l=new Uint8Array(Ti),p=new Uint8Array(t.length+qi);let y,b=0;for(y=0;y16)throw new Te("illegal tagSize value");const o=t.length||0,c=new Uint8Array(16);12!==o?(this._gcm_mac_process(t),s[0]=0,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=0,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=0,s[11]=o>>>29,s[12]=o>>>21&255,s[13]=o>>>13&255,s[14]=o>>>5&255,s[15]=o<<3&255,a.mac(Ce.MAC.GCM,Ce.HEAP_DATA,16),a.get_iv(Ce.HEAP_DATA),a.set_iv(0,0,0,0),c.set(s.subarray(0,16))):(c.set(t),c[15]=1);const u=new DataView(c.buffer);if(this.gamma0=u.getUint32(12),a.set_nonce(u.getUint32(0),u.getUint32(4),u.getUint32(8),0),a.set_mask(0,0,0,4294967295),void 0!==r){if(r.length>Wi)throw new Te("illegal adata length");r.length?(this.adata=r,this._gcm_mac_process(r)):this.adata=void 0}else this.adata=void 0;if(this.counter<1||this.counter>4294967295)throw new RangeError("counter must be a positive 32-bit integer");a.set_counter(0,0,0,this.gamma0+this.counter|0)}static encrypt(e,t,r,i,n){return new Gi(t,r,i,n).encrypt(e)}static decrypt(e,t,r,i,n){return new Gi(t,r,i,n).decrypt(e)}encrypt(e){return this.AES_GCM_encrypt(e)}decrypt(e){return this.AES_GCM_decrypt(e)}AES_GCM_Encrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.aes.pos,o=this.aes.len,c=0,u=o+r&-16,h=0;if((a-1<<4)+o+r>Wi)throw new RangeError("counter overflow");const d=new Uint8Array(u);for(;r>0;)h=Re(n,s+o,e,t,r),o+=h,t+=h,r-=h,h=i.cipher(Ce.ENC.CTR,Ce.HEAP_DATA+s,o),h=i.mac(Ce.MAC.GCM,Ce.HEAP_DATA+s,h),h&&d.set(n.subarray(s,s+h),c),a+=h>>>4,c+=h,h>>29,t[4]=u>>>21,t[5]=u>>>13&255,t[6]=u>>>5&255,t[7]=u<<3&255,t[8]=t[9]=t[10]=0,t[11]=h>>>29,t[12]=h>>>21&255,t[13]=h>>>13&255,t[14]=h>>>5&255,t[15]=h<<3&255,e.mac(Ce.MAC.GCM,Ce.HEAP_DATA,16),e.get_iv(Ce.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(Ce.ENC.CTR,Ce.HEAP_DATA,16),o.set(t.subarray(0,i),s),this.counter=1,this.aes.pos=0,this.aes.len=0,o}AES_GCM_Decrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.tagSize,o=this.aes.pos,c=this.aes.len,u=0,h=c+r>s?c+r-s&-16:0,d=c+r-h,f=0;if((a-1<<4)+c+r>Wi)throw new RangeError("counter overflow");const l=new Uint8Array(h);for(;r>d;)f=Re(n,o+c,e,t,r-d),c+=f,t+=f,r-=f,f=i.mac(Ce.MAC.GCM,Ce.HEAP_DATA+o,f),f=i.cipher(Ce.DEC.CTR,Ce.HEAP_DATA+o,f),f&&l.set(n.subarray(o,o+f),u),a+=f>>>4,u+=f,o=0,c=0;return r>0&&(c+=Re(n,0,e,t,r)),this.counter=a,this.aes.pos=o,this.aes.len=c,l}AES_GCM_Decrypt_finish(){let{asm:e,heap:t}=this.aes.acquire_asm(),r=this.tagSize,i=this.adata,n=this.counter,a=this.aes.pos,s=this.aes.len,o=s-r;if(s>>29,t[4]=d>>>21,t[5]=d>>>13&255,t[6]=d>>>5&255,t[7]=d<<3&255,t[8]=t[9]=t[10]=0,t[11]=f>>>29,t[12]=f>>>21&255,t[13]=f>>>13&255,t[14]=f>>>5&255,t[15]=f<<3&255,e.mac(Ce.MAC.GCM,Ce.HEAP_DATA,16),e.get_iv(Ce.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(Ce.ENC.CTR,Ce.HEAP_DATA,16);let l=0;for(let e=0;e0;){for(a=Re(r,0,e,i,n),i+=a,n-=a;15&a;)r[a++]=0;t.mac(Ce.MAC.GCM,Ce.HEAP_DATA,a)}}}const Vi=de.getWebCrypto(),$i=de.getNodeCrypto(),Zi=de.getNodeBuffer(),Xi=16,Yi="AES-GCM";async function Qi(e,t){if(e!==ue.symmetric.aes128&&e!==ue.symmetric.aes192&&e!==ue.symmetric.aes256)throw Error("GCM mode supports only AES cipher");if(de.getNodeCrypto())return{encrypt:async function(e,r,i=new Uint8Array){const n=new $i.createCipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i);const a=Zi.concat([n.update(e),n.final(),n.getAuthTag()]);return new Uint8Array(a)},decrypt:async function(e,r,i=new Uint8Array){const n=new $i.createDecipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i),n.setAuthTag(e.slice(e.length-Xi,e.length));const a=Zi.concat([n.update(e.slice(0,e.length-Xi)),n.final()]);return new Uint8Array(a)}};if(de.getWebCrypto()&&24!==t.length){const e=await Vi.importKey("raw",t,{name:Yi},!1,["encrypt","decrypt"]);return{encrypt:async function(r,i,n=new Uint8Array){if(!r.length)return Gi.encrypt(r,t,i,n);const a=await Vi.encrypt({name:Yi,iv:i,additionalData:n,tagLength:8*Xi},e,r);return new Uint8Array(a)},decrypt:async function(r,i,n=new Uint8Array){if(r.length===Xi)return Gi.decrypt(r,t,i,n);const a=await Vi.decrypt({name:Yi,iv:i,additionalData:n,tagLength:8*Xi},e,r);return new Uint8Array(a)}}}return{encrypt:async function(e,r,i){return Gi.encrypt(e,t,r,i)},decrypt:async function(e,r,i){return Gi.decrypt(e,t,r,i)}}}Qi.getNonce=function(e,t){const r=e.slice();for(let e=0;e>>8)-1}(e,t,r,i,32)}function p(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function y(e){var t,r,i=1;for(t=0;t<16;t++)r=e[t]+i+65535,i=Math.floor(r/65536),e[t]=r-65536*i;e[0]+=i-1+37*(i-1)}function b(e,t,r){for(var i,n=~(r-1),a=0;a<16;a++)i=n&(e[a]^t[a]),e[a]^=i,t[a]^=i}function g(e,r){var i,n,a,s=t(),o=t();for(i=0;i<16;i++)o[i]=r[i];for(y(o),y(o),y(o),n=0;n<2;n++){for(s[0]=o[0]-65517,i=1;i<15;i++)s[i]=o[i]-65535-(s[i-1]>>16&1),s[i-1]&=65535;s[15]=o[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,b(o,s,1-a)}for(i=0;i<16;i++)e[2*i]=255&o[i],e[2*i+1]=o[i]>>8}function m(e,t){var r=new Uint8Array(32),i=new Uint8Array(32);return g(r,e),g(i,t),l(r,0,i,0)}function w(e){var t=new Uint8Array(32);return g(t,e),1&t[0]}function v(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function _(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]+r[i]}function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$,U+=i*Z,R+=i*X,I+=i*Y,v+=(i=t[15])*T,s+=38*(k+=i*q),o+=38*(A+=i*F),c+=38*(S+=i*O),u+=38*(E+=i*L),h+=38*(P+=i*N),d+=38*(x+=i*j),f+=38*(M+=i*H),l+=38*(K+=i*W),p+=38*(C+=i*G),y+=38*(D+=i*V),b+=38*(U+=i*$),g+=38*(R+=i*Z),m+=38*(I+=i*X),w+=38*(B+=i*Y),a=(i=(a+=38*(_+=i*z))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a=(i=(a+=n-1+37*(n-1))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a+=n-1+37*(n-1),e[0]=a,e[1]=s,e[2]=o,e[3]=c,e[4]=u,e[5]=h,e[6]=d,e[7]=f,e[8]=l,e[9]=p,e[10]=y,e[11]=b,e[12]=g,e[13]=m,e[14]=w,e[15]=v}function S(e,t){A(e,t,t)}function E(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=253;i>=0;i--)S(n,n),2!==i&&4!==i&&A(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}function P(e,r,i){var n,a,o=new Uint8Array(32),c=new Float64Array(80),u=t(),h=t(),d=t(),f=t(),l=t(),p=t();for(a=0;a<31;a++)o[a]=r[a];for(o[31]=127&r[31]|64,o[0]&=248,v(c,i),a=0;a<16;a++)h[a]=c[a],f[a]=u[a]=d[a]=0;for(u[0]=f[0]=1,a=254;a>=0;--a)b(u,h,n=o[a>>>3]>>>(7&a)&1),b(d,f,n),_(l,u,d),k(u,u,d),_(d,h,f),k(h,h,f),S(f,l),S(p,u),A(u,d,u),A(d,h,l),_(l,u,d),k(u,u,d),S(h,u),k(d,f,p),A(u,d,s),_(u,u,f),A(d,d,u),A(u,f,p),A(f,h,c),S(h,l),b(u,h,n),b(d,f,n);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=d[a],c[a+48]=h[a],c[a+64]=f[a];var y=c.subarray(32),m=c.subarray(16);return E(y,y),A(m,m,y),g(e,m),0}function x(e,t){return P(e,t,i)}function M(e,r){var i=t(),n=t(),a=t(),s=t(),o=t(),u=t(),h=t(),d=t(),f=t();k(i,e[1],e[0]),k(f,r[1],r[0]),A(i,i,f),_(n,e[0],e[1]),_(f,r[0],r[1]),A(n,n,f),A(a,e[3],r[3]),A(a,a,c),A(s,e[2],r[2]),_(s,s,s),k(o,n,i),k(u,s,a),_(h,s,a),_(d,n,i),A(e[0],o,u),A(e[1],d,h),A(e[2],h,u),A(e[3],o,d)}function K(e,t,r){var i;for(i=0;i<4;i++)b(e[i],t[i],r)}function C(e,r){var i=t(),n=t(),a=t();E(a,r[2]),A(i,r[0],a),A(n,r[1],a),g(e,n),e[31]^=w(i)<<7}function D(e,t,r){var i,s;for(p(e[0],n),p(e[1],a),p(e[2],a),p(e[3],n),s=255;s>=0;--s)K(e,t,i=r[s/8|0]>>(7&s)&1),M(t,e),M(e,e),K(e,t,i)}function U(e,r){var i=[t(),t(),t(),t()];p(i[0],u),p(i[1],h),p(i[2],a),A(i[3],u,h),D(e,i,r)}function R(i,n,a){var s,o,c=[t(),t(),t(),t()];for(a||r(n,32),(s=e.hash(n.subarray(0,32)))[0]&=248,s[31]&=127,s[31]|=64,U(c,s),C(i,c),o=0;o<32;o++)n[o+32]=i[o];return 0}var I=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function B(e,t){var r,i,n,a;for(i=63;i>=32;--i){for(r=0,n=i-32,a=i-12;n>4)*I[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*I[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function T(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;B(e,r)}function z(e,r){var i=t(),s=t(),c=t(),u=t(),h=t(),d=t(),l=t();return p(e[2],a),v(e[1],r),S(c,e[1]),A(u,c,o),k(c,c,e[2]),_(u,e[2],u),S(h,u),S(d,h),A(l,d,h),A(i,l,c),A(i,i,u),function(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=250;i>=0;i--)S(n,n),1!==i&&A(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}(i,i),A(i,i,c),A(i,i,u),A(i,i,u),A(e[0],i,u),S(s,e[0]),A(s,s,u),m(s,c)&&A(e[0],e[0],f),S(s,e[0]),A(s,s,u),m(s,c)?-1:(w(e[0])===r[31]>>7&&k(e[0],n,e[0]),A(e[3],e[0],e[1]),0)}var q=64;function F(){for(var e=0;e=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return R(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(F(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;re&&(c.imod(a.leftShift(n)).iadd(a),u=c.mod(s).toNumber())}while(!await on(c,t,r));return c}async function on(e,t,r){return!(t&&!e.dec().gcd(t).isOne())&&(!!await async function(e){const t=await de.getBigInteger();return cn.every((r=>0!==e.mod(new t(r))))}(e)&&(!!await async function(e,t){const r=await de.getBigInteger();return t=t||new r(2),t.modExp(e.dec(),e).isOne()}(e)&&!!await async function(e,t,r){const i=await de.getBigInteger(),n=e.bitLength();t||(t=Math.max(1,n/48|0));const a=e.dec();let s=0;for(;!a.getBit(s);)s++;const o=e.rightShift(new i(s));for(;t>0;t--){let t,n=(r?r():await nn(new i(2),a)).modExp(o,e);if(!n.isOne()&&!n.equal(a)){for(t=1;tt-11)throw Error("Message too long");const i=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!i;if(t)return de.selectUint8Array(s,a,t);if(s)return a;throw Error("Decryption error")}async function fn(e,t,r){let i;if(t.length!==ci.getHashByteLength(e))throw Error("Invalid hash length");const n=new Uint8Array(un[e].length);for(i=0;i{yn.generateKeyPair("rsa",r,((r,i,n)=>{r?t(r):e(gn.decode(n,"der"))}))}));return{n:i.modulus.toArrayLike(Uint8Array),e:i.publicExponent.toArrayLike(Uint8Array),d:i.privateExponent.toArrayLike(Uint8Array),p:i.prime2.toArrayLike(Uint8Array),q:i.prime1.toArrayLike(Uint8Array),u:i.coefficient.toArrayLike(Uint8Array)}}let r,i,n;do{i=await sn(e-(e>>1),t,40),r=await sn(e>>1,t,40),n=r.mul(i)}while(n.bitLength()!==e);const a=r.dec().imul(i.dec());return i.lt(r)&&([r,i]=[i,r]),{n:n.toUint8Array(),e:t.toUint8Array(),d:t.modInv(a).toUint8Array(),p:r.toUint8Array(),q:i.toUint8Array(),u:r.modInv(i).toUint8Array()}},validateParams:async function(e,t,r,i,n,a){const s=await de.getBigInteger();if(e=new s(e),i=new s(i),n=new s(n),!i.mul(n).equal(e))return!1;const o=new s(2);if(a=new s(a),!i.mul(a).mod(n).isOne())return!1;t=new s(t),r=new s(r);const c=new s(Math.floor(e.bitLength()/3)),u=await nn(o,o.leftShift(c)),h=u.mul(r).mul(t);return!(!h.mod(i.dec()).equal(u)||!h.mod(n.dec()).equal(u))}});var vn=/*#__PURE__*/Object.freeze({__proto__:null,encrypt:async function(e,t,r,i){const n=await de.getBigInteger();t=new n(t),r=new n(r),i=new n(i);const a=new n(hn(e,t.byteLength())),s=await nn(new n(1),t.dec());return{c1:r.modExp(s,t).toUint8Array(),c2:i.modExp(s,t).imul(a).imod(t).toUint8Array()}},decrypt:async function(e,t,r,i,n){const a=await de.getBigInteger();return e=new a(e),t=new a(t),r=new a(r),i=new a(i),dn(e.modExp(i,r).modInv(r).imul(t).imod(r).toUint8Array("be",r.byteLength()),n)},validateParams:async function(e,t,r,i){const n=await de.getBigInteger();e=new n(e),t=new n(t),r=new n(r);const a=new n(1);if(t.lte(a)||t.gte(e))return!1;const s=new n(e.bitLength()),o=new n(1023);if(s.lt(o))return!1;if(!t.modExp(e.dec(),e).isOne())return!1;let c=t;const u=new n(1),h=new n(2).leftShift(new n(17));for(;u.lt(h);){if(c=c.mul(t).imod(e),c.isOne())return!1;u.iinc()}i=new n(i);const d=new n(2),f=await nn(d.leftShift(s.dec()),d.leftShift(s)),l=e.dec().imul(f).iadd(i);return!!r.equal(t.modExp(l,e))}});class _n{constructor(e){if(e instanceof _n)this.oid=e.oid;else if(de.isArray(e)||de.isUint8Array(e)){if(6===(e=new Uint8Array(e))[0]){if(e[1]!==e.length-2)throw Error("Length mismatch in DER encoded oid");e=e.subarray(2)}this.oid=e}else this.oid=""}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return de.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return de.uint8ArrayToHex(this.oid)}getName(){const e=this.toHex();if(ue.curve[e])return ue.write(ue.curve,e);throw Error("Unknown curve object identifier.")}}function kn(e,t){return e.keyPair({priv:t})}function An(e,t){const r=e.keyPair({pub:t});if(!0!==r.validate().result)throw Error("Invalid elliptic public key");return r}async function Sn(e){if(!we.useIndutnyElliptic)throw Error("This curve is only supported in the full build of OpenPGP.js");const{default:t}=await Promise.resolve().then((function(){return mb}));return new t.ec(e)}function En(e){let t,r=0;const i=e[0];return i<192?([r]=e,t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=de.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function Pn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):de.concatUint8Array([new Uint8Array([255]),de.writeNumber(e,4)])}function xn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function Mn(e){return new Uint8Array([192|e])}function Kn(e,t){return de.concatUint8Array([Mn(e),Pn(t)])}function Cn(e){return[ue.packet.literalData,ue.packet.compressedData,ue.packet.symmetricallyEncryptedData,ue.packet.symEncryptedIntegrityProtectedData,ue.packet.aeadEncryptedData].includes(e)}async function Dn(e,t){const r=W(e);let i,n;try{const a=await r.peekBytes(2);if(!a||a.length<2||0==(128&a[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const s=await r.readByte();let o,c,u=-1,h=-1;h=0,0!=(64&s)&&(h=1),h?u=63&s:(u=(63&s)>>2,c=3&s);const d=Cn(u);let f,l=null;if(d){if("array"===de.isStream(e)){const e=new v;i=G(e),l=e}else{const e=new F;i=G(e.writable),l=e.readable}n=t({tag:u,packet:l})}else l=[];do{if(h){const e=await r.readByte();if(f=!1,e<192)o=e;else if(e>=192&&e<224)o=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(o=1<<(31&e),f=!0,!d)throw new TypeError("This packet type does not support partial lengths.")}else o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(c){case 0:o=await r.readByte();break;case 1:o=await r.readByte()<<8|await r.readByte();break;case 2:o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:o=1/0}if(o>0){let e=0;for(;;){i&&await i.ready;const{done:t,value:n}=await r.read();if(t){if(o===1/0)break;throw Error("Unexpected end of packet")}const a=o===1/0?n:n.subarray(0,o-e);if(i?await i.write(a):l.push(a),e+=n.length,e>=o){r.unshift(n.subarray(o-e+n.length));break}}}}while(f);const p=await r.peekBytes(d?1/0:2);return i?(await i.ready,await i.close()):(l=de.concatUint8Array(l),await t({tag:u,packet:l})),!p||!p.length}catch(e){if(i)return await i.abort(e),!0;throw e}finally{i&&await n,r.releaseLock()}}class Un extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Un),this.name="UnsupportedError"}}class Rn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}const In=de.getWebCrypto(),Bn=de.getNodeCrypto(),Tn={p256:"P-256",p384:"P-384",p521:"P-521"},zn=Bn?Bn.getCurves():[],qn=Bn?{secp256k1:zn.includes("secp256k1")?"secp256k1":void 0,p256:zn.includes("prime256v1")?"prime256v1":void 0,p384:zn.includes("secp384r1")?"secp384r1":void 0,p521:zn.includes("secp521r1")?"secp521r1":void 0,ed25519:zn.includes("ED25519")?"ED25519":void 0,curve25519:zn.includes("X25519")?"X25519":void 0,brainpoolP256r1:zn.includes("brainpoolP256r1")?"brainpoolP256r1":void 0,brainpoolP384r1:zn.includes("brainpoolP384r1")?"brainpoolP384r1":void 0,brainpoolP512r1:zn.includes("brainpoolP512r1")?"brainpoolP512r1":void 0}:{},Fn={p256:{oid:[6,8,42,134,72,206,61,3,1,7],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha256,cipher:ue.symmetric.aes128,node:qn.p256,web:Tn.p256,payloadSize:32,sharedSize:256},p384:{oid:[6,5,43,129,4,0,34],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha384,cipher:ue.symmetric.aes192,node:qn.p384,web:Tn.p384,payloadSize:48,sharedSize:384},p521:{oid:[6,5,43,129,4,0,35],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha512,cipher:ue.symmetric.aes256,node:qn.p521,web:Tn.p521,payloadSize:66,sharedSize:528},secp256k1:{oid:[6,5,43,129,4,0,10],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha256,cipher:ue.symmetric.aes128,node:qn.secp256k1,payloadSize:32},ed25519:{oid:[6,9,43,6,1,4,1,218,71,15,1],keyType:ue.publicKey.eddsaLegacy,hash:ue.hash.sha512,node:!1,payloadSize:32},curve25519:{oid:[6,10,43,6,1,4,1,151,85,1,5,1],keyType:ue.publicKey.ecdh,hash:ue.hash.sha256,cipher:ue.symmetric.aes128,node:!1,payloadSize:32},brainpoolP256r1:{oid:[6,9,43,36,3,3,2,8,1,1,7],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha256,cipher:ue.symmetric.aes128,node:qn.brainpoolP256r1,payloadSize:32},brainpoolP384r1:{oid:[6,9,43,36,3,3,2,8,1,1,11],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha384,cipher:ue.symmetric.aes192,node:qn.brainpoolP384r1,payloadSize:48},brainpoolP512r1:{oid:[6,9,43,36,3,3,2,8,1,1,13],keyType:ue.publicKey.ecdsa,hash:ue.hash.sha512,cipher:ue.symmetric.aes256,node:qn.brainpoolP512r1,payloadSize:64}};class On{constructor(e,t){try{(de.isArray(e)||de.isUint8Array(e))&&(e=new _n(e)),e instanceof _n&&(e=e.getName()),this.name=ue.write(ue.curve,e)}catch(e){throw new Un("Unknown curve")}t=t||Fn[this.name],this.keyType=t.keyType,this.oid=t.oid,this.hash=t.hash,this.cipher=t.cipher,this.node=t.node&&Fn[this.name],this.web=t.web&&Fn[this.name],this.payloadSize=t.payloadSize,this.web&&de.getWebCrypto()?this.type="web":this.node&&de.getNodeCrypto()?this.type="node":"curve25519"===this.name?this.type="curve25519":"ed25519"===this.name&&(this.type="ed25519")}async genKeyPair(){let e;switch(this.type){case"web":try{return await async function(e){const t=await In.generateKey({name:"ECDSA",namedCurve:Tn[e]},!0,["sign","verify"]),r=await In.exportKey("jwk",t.privateKey),i=await In.exportKey("jwk",t.publicKey);return{publicKey:Nn(i),privateKey:ge(r.d)}}(this.name)}catch(e){de.printDebugError("Browser did not support generating ec key "+e.message);break}case"node":return async function(e){const t=Bn.createECDH(qn[e]);return await t.generateKeys(),{publicKey:new Uint8Array(t.getPublicKey()),privateKey:new Uint8Array(t.getPrivateKey())}}(this.name);case"curve25519":{const t=rn(32);t[0]=127&t[0]|64,t[31]&=248;const r=t.slice().reverse();e=en.box.keyPair.fromSecretKey(r);return{publicKey:de.concatUint8Array([new Uint8Array([64]),e.publicKey]),privateKey:t}}case"ed25519":{const e=rn(32),t=en.sign.keyPair.fromSeed(e);return{publicKey:de.concatUint8Array([new Uint8Array([64]),t.publicKey]),privateKey:e}}}const t=await Sn(this.name);return e=await t.genKeyPair({entropy:de.uint8ArrayToString(rn(32))}),{publicKey:new Uint8Array(e.getPublic("array",!1)),privateKey:e.getPrivate().toArrayLike(Uint8Array)}}}async function Ln(e,t,r,i){const n={p256:!0,p384:!0,p521:!0,secp256k1:!0,curve25519:e===ue.publicKey.ecdh,brainpoolP256r1:!0,brainpoolP384r1:!0,brainpoolP512r1:!0},a=t.getName();if(!n[a])return!1;if("curve25519"===a){i=i.slice().reverse();const{publicKey:e}=en.box.keyPair.fromSecretKey(i);r=new Uint8Array(r);const t=new Uint8Array([64,...e]);return!!de.equalsUint8Array(t,r)}const s=await Sn(a);try{r=An(s,r).getPublic()}catch(e){return!1}return!!kn(s,i).getPublic().eq(r)}function Nn(e){const t=ge(e.x),r=ge(e.y),i=new Uint8Array(t.length+r.length+1);return i[0]=4,i.set(t,1),i.set(r,t.length+1),i}function jn(e,t,r){const i=e,n=r.slice(1,i+1),a=r.slice(i+1,2*i+1);return{kty:"EC",crv:t,x:me(n,!0),y:me(a,!0),ext:!0}}function Hn(e,t,r,i){const n=jn(e,t,r);return n.d=me(i,!0),n}const Wn=de.getWebCrypto(),Gn=de.getNodeCrypto();async function Vn(e,t,r,i,n,a){const s=new On(e);if(r&&!de.isStream(r)){const e={publicKey:i,privateKey:n};switch(s.type){case"web":try{return await async function(e,t,r,i){const n=e.payloadSize,a=Hn(e.payloadSize,Tn[e.name],i.publicKey,i.privateKey),s=await Wn.importKey("jwk",a,{name:"ECDSA",namedCurve:Tn[e.name],hash:{name:ue.read(ue.webHash,e.hash)}},!1,["sign"]),o=new Uint8Array(await Wn.sign({name:"ECDSA",namedCurve:Tn[e.name],hash:{name:ue.read(ue.webHash,t)}},s,r));return{r:o.slice(0,n),s:o.slice(n,n<<1)}}(s,t,r,e)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;de.printDebugError("Browser did not support signing: "+e.message)}break;case"node":{const i=await async function(e,t,r,i){const n=Gn.createSign(ue.read(ue.hash,t));n.write(r),n.end();const a=Yn.encode({version:1,parameters:e.oid,privateKey:Array.from(i.privateKey),publicKey:{unused:0,data:Array.from(i.publicKey)}},"pem",{label:"EC PRIVATE KEY"});return Xn.decode(n.sign(a),"der")}(s,t,r,e);return{r:i.r.toArrayLike(Uint8Array),s:i.s.toArrayLike(Uint8Array)}}}}return async function(e,t,r){const i=await Sn(e.name),n=kn(i,r),a=n.sign(t);return{r:a.r.toArrayLike(Uint8Array),s:a.s.toArrayLike(Uint8Array)}}(s,a,n)}async function $n(e,t,r,i,n,a){const s=new On(e);if(i&&!de.isStream(i))switch(s.type){case"web":try{return await async function(e,t,{r,s:i},n,a){const s=jn(e.payloadSize,Tn[e.name],a),o=await Wn.importKey("jwk",s,{name:"ECDSA",namedCurve:Tn[e.name],hash:{name:ue.read(ue.webHash,e.hash)}},!1,["verify"]),c=de.concatUint8Array([r,i]).buffer;return Wn.verify({name:"ECDSA",namedCurve:Tn[e.name],hash:{name:ue.read(ue.webHash,t)}},o,c,n)}(s,t,r,i,n)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;de.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":return async function(e,t,{r,s:i},n,a){const{default:s}=await Promise.resolve().then((function(){return Jp})),o=Gn.createVerify(ue.read(ue.hash,t));o.write(n),o.end();const c=Jn.encode({algorithm:{algorithm:[1,2,840,10045,2,1],parameters:e.oid},subjectPublicKey:{unused:0,data:Array.from(a)}},"pem",{label:"PUBLIC KEY"}),u=Xn.encode({r:new s(r),s:new s(i)},"der");try{return o.verify(c,u)}catch(e){return!1}}(s,t,r,i,n)}return async function(e,t,r,i){const n=await Sn(e.name),a=An(n,i);return a.verify(r,t)}(s,r,void 0===t?i:a,n)}const Zn=Gn?y.default:void 0,Xn=Gn?Zn.define("ECDSASignature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())})):void 0,Yn=Gn?Zn.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().any(),this.key("publicKey").explicit(1).optional().bitstr())})):void 0,Qn=Gn?Zn.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().any())})):void 0,Jn=Gn?Zn.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(Qn),this.key("subjectPublicKey").bitstr())})):void 0;var ea=/*#__PURE__*/Object.freeze({__proto__:null,sign:Vn,verify:$n,validateParams:async function(e,t,r){const i=new On(e);if(i.keyType!==ue.publicKey.ecdsa)return!1;switch(i.type){case"web":case"node":{const i=rn(8),n=ue.hash.sha256,a=await ci.digest(n,i);try{const s=await Vn(e,n,i,t,r,a);return await $n(e,n,s,i,t,a)}catch(e){return!1}}default:return Ln(ue.publicKey.ecdsa,e,t,r)}}});en.hash=e=>new Uint8Array(yr().update(e).digest());var ta=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){if(ci.getHashByteLength(t)new Uint8Array(yr().update(e).digest());var ia=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===ue.publicKey.ed25519){const e=rn(32),{publicKey:t}=en.sign.keyPair.fromSeed(e);return{A:t,seed:e}}throw Error("Unsupported EdDSA algorithm")},sign:async function(e,t,r,i,n,a){if(ci.getHashByteLength(t)=0;--e)for(let t=o-1;t>=0;--t)c[1]=o*e+(t+1),u[0]=a[0]^c[0],u[1]=a[1]^c[1],u[2]=s[2*t],u[3]=s[2*t+1],u=sa(r.decrypt(oa(u))),a=u.subarray(0,2),s[2*t]=u[2],s[2*t+1]=u[3];if(a[0]===i[0]&&a[1]===i[1])return oa(s);throw Error("Key Data Integrity failed")}function sa(e){const{length:t}=e,r=function(e){if(de.isString(e)){const{length:t}=e,r=new ArrayBuffer(t),i=new Uint8Array(r);for(let r=0;r0){const r=e[t-1];if(r>=1){const i=e.subarray(t-r),n=new Uint8Array(r).fill(r);if(de.equalsUint8Array(i,n))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var da=/*#__PURE__*/Object.freeze({__proto__:null,encode:ua,decode:ha});const fa=de.getWebCrypto(),la=de.getNodeCrypto();function pa(e,t,r,i){return de.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),de.stringToUint8Array("Anonymous Sender "),i.subarray(0,20)])}async function ya(e,t,r,i,n=!1,a=!1){let s;if(n){for(s=0;s=0&&0===t[s];s--);t=t.subarray(0,s+1)}return(await ci.digest(e,de.concatUint8Array([new Uint8Array([0,0,0,1]),t,i]))).subarray(0,r)}async function ba(e,t){switch(e.type){case"curve25519":{const r=rn(32),{secretKey:i,sharedKey:n}=await ga(e,t,null,r);let{publicKey:a}=en.box.keyPair.fromSecretKey(i);return a=de.concatUint8Array([new Uint8Array([64]),a]),{publicKey:a,sharedKey:n}}case"web":if(e.web&&de.getWebCrypto())try{return await async function(e,t){const r=jn(e.payloadSize,e.web.web,t);let i=fa.generateKey({name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]),n=fa.importKey("jwk",r,{name:"ECDH",namedCurve:e.web.web},!1,[]);[i,n]=await Promise.all([i,n]);let a=fa.deriveBits({name:"ECDH",namedCurve:e.web.web,public:n},i.privateKey,e.web.sharedSize),s=fa.exportKey("jwk",i.publicKey);[a,s]=await Promise.all([a,s]);const o=new Uint8Array(a),c=new Uint8Array(Nn(s));return{publicKey:c,sharedKey:o}}(e,t)}catch(e){de.printDebugError(e)}break;case"node":return async function(e,t){const r=la.createECDH(e.node.node);r.generateKeys();const i=new Uint8Array(r.computeSecret(t)),n=new Uint8Array(r.getPublicKey());return{publicKey:n,sharedKey:i}}(e,t)}return async function(e,t){const r=await Sn(e.name),i=await e.genKeyPair();t=An(r,t);const n=kn(r,i.privateKey),a=i.publicKey,s=n.derive(t.getPublic()),o=r.curve.p.byteLength(),c=s.toArrayLike(Uint8Array,"be",o);return{publicKey:a,sharedKey:c}}(e,t)}async function ga(e,t,r,i){if(i.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(i,e.payloadSize-i.length),i=t}switch(e.type){case"curve25519":{const e=i.slice().reverse();return{secretKey:e,sharedKey:en.scalarMult(e,t.subarray(1))}}case"web":if(e.web&&de.getWebCrypto())try{return await async function(e,t,r,i){const n=Hn(e.payloadSize,e.web.web,r,i);let a=fa.importKey("jwk",n,{name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]);const s=jn(e.payloadSize,e.web.web,t);let o=fa.importKey("jwk",s,{name:"ECDH",namedCurve:e.web.web},!0,[]);[a,o]=await Promise.all([a,o]);let c=fa.deriveBits({name:"ECDH",namedCurve:e.web.web,public:o},a,e.web.sharedSize),u=fa.exportKey("jwk",a);[c,u]=await Promise.all([c,u]);const h=new Uint8Array(c);return{secretKey:ge(u.d),sharedKey:h}}(e,t,r,i)}catch(e){de.printDebugError(e)}break;case"node":return async function(e,t,r){const i=la.createECDH(e.node.node);i.setPrivateKey(r);const n=new Uint8Array(i.computeSecret(t));return{secretKey:new Uint8Array(i.getPrivateKey()),sharedKey:n}}(e,t,i)}return async function(e,t,r){const i=await Sn(e.name);t=An(i,t),r=kn(i,r);const n=new Uint8Array(r.getPrivate()),a=r.derive(t.getPublic()),s=i.curve.p.byteLength(),o=a.toArrayLike(Uint8Array,"be",s);return{secretKey:n,sharedKey:o}}(e,t,i)}var ma=/*#__PURE__*/Object.freeze({__proto__:null,validateParams:async function(e,t,r){return Ln(ue.publicKey.ecdh,e,t,r)},encrypt:async function(e,t,r,i,n){const a=ua(r),s=new On(e),{publicKey:o,sharedKey:c}=await ba(s,i),u=pa(ue.publicKey.ecdh,e,t,n),{keySize:h}=hi(t.cipher);return{publicKey:o,wrappedKey:na(await ya(t.hash,c,h,u),a)}},decrypt:async function(e,t,r,i,n,a,s){const o=new On(e),{sharedKey:c}=await ga(o,r,n,a),u=pa(ue.publicKey.ecdh,e,t,s),{keySize:h}=hi(t.cipher);let d;for(let e=0;e<3;e++)try{return ha(aa(await ya(t.hash,c,h,u,1===e,2===e),i))}catch(e){d=e}throw d}});const wa=de.getWebCrypto(),va=de.getNodeCrypto(),_a=va&&va.webcrypto&&va.webcrypto.subtle;async function ka(e,t,r,i,n){const a=ue.read(ue.webHash,e);if(!a)throw Error("Hash algo not supported with HKDF");if(wa||_a){const e=wa||_a,s=await e.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await e.deriveBits({name:"HKDF",hash:a,salt:r,info:i},s,8*n);return new Uint8Array(o)}if(va){const a=ue.read(ue.hash,e),s=(e,t)=>va.createHmac(a,e).update(t).digest(),o=s(r,t),c=o.length,u=Math.ceil(n/c),h=new Uint8Array(u*c),d=new Uint8Array(c+i.length+1);d.set(i,c);for(let e=0;e0?d:d.subarray(c));d.set(t,0),h.set(t,e*c)}return h.subarray(0,n)}throw Error("No HKDF implementation available")}const Aa={x25519:de.encodeUTF8("OpenPGP X25519")};var Sa=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===ue.publicKey.x25519){const e=rn(32),{publicKey:t}=en.box.keyPair.fromSecretKey(e);return{A:t,k:e}}throw Error("Unsupported ECDH algorithm")},validateParams:async function(e,t,r){if(e===ue.publicKey.x25519){const{publicKey:e}=en.box.keyPair.fromSecretKey(r);return de.equalsUint8Array(t,e)}return!1},encrypt:async function(e,t,r){if(e===ue.publicKey.x25519){const e=rn(32),i=en.scalarMult(e,r),{publicKey:n}=en.box.keyPair.fromSecretKey(e),a=de.concatUint8Array([n,r,i]),{keySize:s}=hi(ue.symmetric.aes128);return{ephemeralPublicKey:n,wrappedKey:na(await ka(ue.hash.sha256,a,new Uint8Array,Aa.x25519,s),t)}}throw Error("Unsupported ECDH algorithm")},decrypt:async function(e,t,r,i,n){if(e===ue.publicKey.x25519){const e=en.scalarMult(n,t),a=de.concatUint8Array([t,i,e]),{keySize:s}=hi(ue.symmetric.aes128);return aa(await ka(ue.hash.sha256,a,new Uint8Array,Aa.x25519,s),r)}throw Error("Unsupported ECDH algorithm")}}),Ea=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:On,ecdh:ma,ecdhX:Sa,ecdsa:ea,eddsaLegacy:ta,eddsa:ia,generate:async function(e){const t=await de.getBigInteger();e=new On(e);const r=await e.genKeyPair(),i=new t(r.publicKey).toUint8Array(),n=new t(r.privateKey).toUint8Array("be",e.payloadSize);return{oid:e.oid,Q:i,secret:n,hash:e.hash,cipher:e.cipher}},getPreferredHashAlgo:function(e){return Fn[ue.write(ue.curve,e.toHex())].hash}});var Pa=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){const s=await de.getBigInteger(),o=new s(1);let c,u,h,d;i=new s(i),n=new s(n),r=new s(r),a=new s(a),r=r.mod(i),a=a.mod(n);const f=new s(t.subarray(0,n.byteLength())).mod(n);for(;;){if(c=await nn(o,n),u=r.modExp(c,i).imod(n),u.isZero())continue;const e=a.mul(u).imod(n);if(d=f.add(e).imod(n),h=c.modInv(n).imul(d).imod(n),!h.isZero())break}return{r:u.toUint8Array("be",n.byteLength()),s:h.toUint8Array("be",n.byteLength())}},verify:async function(e,t,r,i,n,a,s,o){const c=await de.getBigInteger(),u=new c(0);if(t=new c(t),r=new c(r),a=new c(a),s=new c(s),n=new c(n),o=new c(o),t.lte(u)||t.gte(s)||r.lte(u)||r.gte(s))return de.printDebug("invalid DSA Signature"),!1;const h=new c(i.subarray(0,s.byteLength())).imod(s),d=r.modInv(s);if(d.isZero())return de.printDebug("invalid DSA Signature"),!1;n=n.mod(a),o=o.mod(a);const f=h.mul(d).imod(s),l=t.mul(d).imod(s),p=n.modExp(f,a),y=o.modExp(l,a);return p.mul(y).imod(a).imod(s).equal(t)},validateParams:async function(e,t,r,i,n){const a=await de.getBigInteger();e=new a(e),t=new a(t),r=new a(r),i=new a(i);const s=new a(1);if(r.lte(s)||r.gte(e))return!1;if(!e.dec().mod(t).isZero())return!1;if(!r.modExp(t,e).isOne())return!1;const o=new a(t.bitLength()),c=new a(150);if(o.lt(c)||!await on(t,null,32))return!1;n=new a(n);const u=new a(2),h=await nn(u.leftShift(o.dec()),u.leftShift(o)),d=t.mul(h).add(n);return!!i.equal(r.modExp(d,e))}}),xa={rsa:wn,elgamal:vn,elliptic:Ea,dsa:Pa,nacl:en};var Ma=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaSign:return{s:de.readMPI(t.subarray(r))};case ue.publicKey.dsa:case ue.publicKey.ecdsa:{const e=de.readMPI(t.subarray(r));r+=e.length+2;return{r:e,s:de.readMPI(t.subarray(r))}}case ue.publicKey.eddsaLegacy:{let e=de.readMPI(t.subarray(r));r+=e.length+2,e=de.leftPad(e,32);let i=de.readMPI(t.subarray(r));return i=de.leftPad(i,32),{r:e,s:i}}case ue.publicKey.ed25519:{const e=t.subarray(r,r+64);return r+=e.length,{RS:e}}default:throw new Un("Unknown signature algorithm.")}},verify:async function(e,t,r,i,n,a){switch(e){case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaSign:{const{n:e,e:s}=i,o=de.leftPad(r.s,e.length);return xa.rsa.verify(t,n,o,e,s,a)}case ue.publicKey.dsa:{const{g:e,p:n,q:s,y:o}=i,{r:c,s:u}=r;return xa.dsa.verify(t,c,u,a,e,n,s,o)}case ue.publicKey.ecdsa:{const{oid:e,Q:s}=i,o=new xa.elliptic.CurveWithOID(e).payloadSize,c=de.leftPad(r.r,o),u=de.leftPad(r.s,o);return xa.elliptic.ecdsa.verify(e,t,{r:c,s:u},n,s,a)}case ue.publicKey.eddsaLegacy:{const{oid:e,Q:s}=i;return xa.elliptic.eddsaLegacy.verify(e,t,r,n,s,a)}case ue.publicKey.ed25519:{const{A:s}=i;return xa.elliptic.eddsa.verify(e,t,r,n,s,a)}default:throw Error("Unknown signature algorithm.")}},sign:async function(e,t,r,i,n,a){if(!r||!i)throw Error("Missing key parameters");switch(e){case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaSign:{const{n:e,e:s}=r,{d:o,p:c,q:u,u:h}=i;return{s:await xa.rsa.sign(t,n,e,s,o,c,u,h,a)}}case ue.publicKey.dsa:{const{g:e,p:n,q:s}=r,{x:o}=i;return xa.dsa.sign(t,a,e,n,s,o)}case ue.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case ue.publicKey.ecdsa:{const{oid:e,Q:s}=r,{d:o}=i;return xa.elliptic.ecdsa.sign(e,t,n,s,o,a)}case ue.publicKey.eddsaLegacy:{const{oid:e,Q:s}=r,{seed:o}=i;return xa.elliptic.eddsaLegacy.sign(e,t,n,s,o,a)}case ue.publicKey.ed25519:{const{A:s}=r,{seed:o}=i;return xa.elliptic.eddsa.sign(e,t,n,s,o,a)}default:throw Error("Unknown signature algorithm.")}}});class Ka{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return de.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class Ca{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Un("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class Da{static fromObject({wrappedKey:e,algorithm:t}){const r=new Da;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=e.subarray(t,t+r),t+=r}write(){return de.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function Ua(e){try{e.getName()}catch(e){throw new Un("Unknown curve OID")}}var Ra=/*#__PURE__*/Object.freeze({__proto__:null,publicKeyEncrypt:async function(e,t,r,i,n){switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await xa.rsa.encrypt(i,e,t)}}case ue.publicKey.elgamal:{const{p:e,g:t,y:n}=r;return xa.elgamal.encrypt(i,e,t,n)}case ue.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:a}=r,{publicKey:s,wrappedKey:o}=await xa.elliptic.ecdh.encrypt(e,a,i,t,n);return{V:s,C:new Ka(o)}}case ue.publicKey.x25519:{if(!de.isAES(t))throw Error("X25519 keys can only encrypt AES session keys");const{A:n}=r,{ephemeralPublicKey:a,wrappedKey:s}=await xa.elliptic.ecdhX.encrypt(e,i,n);return{ephemeralPublicKey:a,C:Da.fromObject({algorithm:t,wrappedKey:s})}}default:return[]}},publicKeyDecrypt:async function(e,t,r,i,n,a){switch(e){case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaEncrypt:{const{c:e}=i,{n,e:s}=t,{d:o,p:c,q:u,u:h}=r;return xa.rsa.decrypt(e,n,s,o,c,u,h,a)}case ue.publicKey.elgamal:{const{c1:e,c2:n}=i,s=t.p,o=r.x;return xa.elgamal.decrypt(e,n,s,o,a)}case ue.publicKey.ecdh:{const{oid:e,Q:a,kdfParams:s}=t,{d:o}=r,{V:c,C:u}=i;return xa.elliptic.ecdh.decrypt(e,s,c,u.data,a,o,n)}case ue.publicKey.x25519:{const{A:n}=t,{k:a}=r,{ephemeralPublicKey:s,C:o}=i;if(!de.isAES(o.algorithm))throw Error("AES session key expected");return xa.elliptic.ecdhX.decrypt(e,s,o.wrappedKey,n,a)}default:throw Error("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaSign:{const e=de.readMPI(t.subarray(r));r+=e.length+2;const i=de.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{n:e,e:i}}}case ue.publicKey.dsa:{const e=de.readMPI(t.subarray(r));r+=e.length+2;const i=de.readMPI(t.subarray(r));r+=i.length+2;const n=de.readMPI(t.subarray(r));r+=n.length+2;const a=de.readMPI(t.subarray(r));return r+=a.length+2,{read:r,publicParams:{p:e,q:i,g:n,y:a}}}case ue.publicKey.elgamal:{const e=de.readMPI(t.subarray(r));r+=e.length+2;const i=de.readMPI(t.subarray(r));r+=i.length+2;const n=de.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{p:e,g:i,y:n}}}case ue.publicKey.ecdsa:{const e=new _n;r+=e.read(t),Ua(e);const i=de.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{oid:e,Q:i}}}case ue.publicKey.eddsaLegacy:{const e=new _n;r+=e.read(t),Ua(e);let i=de.readMPI(t.subarray(r));return r+=i.length+2,i=de.leftPad(i,33),{read:r,publicParams:{oid:e,Q:i}}}case ue.publicKey.ecdh:{const e=new _n;r+=e.read(t),Ua(e);const i=de.readMPI(t.subarray(r));r+=i.length+2;const n=new Ca;return r+=n.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:i,kdfParams:n}}}case ue.publicKey.ed25519:case ue.publicKey.x25519:{const e=t.subarray(r,r+32);return r+=e.length,{read:r,publicParams:{A:e}}}default:throw new Un("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let i=0;switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaSign:{const e=de.readMPI(t.subarray(i));i+=e.length+2;const r=de.readMPI(t.subarray(i));i+=r.length+2;const n=de.readMPI(t.subarray(i));i+=n.length+2;const a=de.readMPI(t.subarray(i));return i+=a.length+2,{read:i,privateParams:{d:e,p:r,q:n,u:a}}}case ue.publicKey.dsa:case ue.publicKey.elgamal:{const e=de.readMPI(t.subarray(i));return i+=e.length+2,{read:i,privateParams:{x:e}}}case ue.publicKey.ecdsa:case ue.publicKey.ecdh:{const e=new On(r.oid);let n=de.readMPI(t.subarray(i));return i+=n.length+2,n=de.leftPad(n,e.payloadSize),{read:i,privateParams:{d:n}}}case ue.publicKey.eddsaLegacy:{const e=new On(r.oid);let n=de.readMPI(t.subarray(i));return i+=n.length+2,n=de.leftPad(n,e.payloadSize),{read:i,privateParams:{seed:n}}}case ue.publicKey.ed25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{seed:e}}}case ue.publicKey.x25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{k:e}}}default:throw new Un("Unknown public key encryption algorithm.")}},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:return{c:de.readMPI(t.subarray(r))};case ue.publicKey.elgamal:{const e=de.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:de.readMPI(t.subarray(r))}}case ue.publicKey.ecdh:{const e=de.readMPI(t.subarray(r));r+=e.length+2;const i=new Ka;return i.read(t.subarray(r)),{V:e,C:i}}case ue.publicKey.x25519:{const e=t.subarray(r,r+32);r+=e.length;const i=new Da;return i.read(t.subarray(r)),{ephemeralPublicKey:e,C:i}}default:throw new Un("Unknown public key encryption algorithm.")}},serializeParams:function(e,t){const r=new Set([ue.publicKey.ed25519,ue.publicKey.x25519]),i=Object.keys(t).map((i=>{const n=t[i];return de.isUint8Array(n)?r.has(e)?n:de.uint8ArrayToMPI(n):n.write()}));return de.concatUint8Array(i)},generateParams:function(e,t,r){switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaSign:return xa.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:i,q:n,u:a})=>({privateParams:{d:r,p:i,q:n,u:a},publicParams:{n:e,e:t}})));case ue.publicKey.ecdsa:return xa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new _n(e),Q:t}})));case ue.publicKey.eddsaLegacy:return xa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new _n(e),Q:t}})));case ue.publicKey.ecdh:return xa.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:i,cipher:n})=>({privateParams:{d:r},publicParams:{oid:new _n(e),Q:t,kdfParams:new Ca({hash:i,cipher:n})}})));case ue.publicKey.ed25519:return xa.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case ue.publicKey.x25519:return xa.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case ue.publicKey.dsa:case ue.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaSign:{const{n:e,e:i}=t,{d:n,p:a,q:s,u:o}=r;return xa.rsa.validateParams(e,i,n,a,s,o)}case ue.publicKey.dsa:{const{p:e,q:i,g:n,y:a}=t,{x:s}=r;return xa.dsa.validateParams(e,i,n,a,s)}case ue.publicKey.elgamal:{const{p:e,g:i,y:n}=t,{x:a}=r;return xa.elgamal.validateParams(e,i,n,a)}case ue.publicKey.ecdsa:case ue.publicKey.ecdh:{const i=xa.elliptic[ue.read(ue.publicKey,e)],{oid:n,Q:a}=t,{d:s}=r;return i.validateParams(n,a,s)}case ue.publicKey.eddsaLegacy:{const{Q:e,oid:i}=t,{seed:n}=r;return xa.elliptic.eddsaLegacy.validateParams(i,e,n)}case ue.publicKey.ed25519:{const{A:i}=t,{seed:n}=r;return xa.elliptic.eddsa.validateParams(e,i,n)}case ue.publicKey.x25519:{const{A:i}=t,{k:n}=r;return xa.elliptic.ecdhX.validateParams(e,i,n)}default:throw Error("Unknown public key algorithm.")}},getPrefixRandom:async function(e){const{blockSize:t}=hi(e),r=await rn(t),i=new Uint8Array([r[r.length-2],r[r.length-1]]);return de.concat([r,i])},generateSessionKey:function(e){const{keySize:t}=hi(e);return rn(t)},getAEADMode:function(e){const t=ue.read(ue.aead,e);return Ji[t]},getCipher:hi,getPreferredCurveHashAlgo:function(e,t){switch(e){case ue.publicKey.ecdsa:case ue.publicKey.eddsaLegacy:return xa.elliptic.getPreferredHashAlgo(t);case ue.publicKey.ed25519:return xa.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}}});const Ia={cipher:st,hash:ci,mode:Ji,publicKey:xa,signature:Ma,random:an,pkcs1:ln,pkcs5:da,aesKW:ca};Object.assign(Ia,Ra);var Ba="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function Ta(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)}const za={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+i),n);else for(let a=0;a=0;)e[t]=0}const ls=0,ps=1,ys=2,bs=29,gs=256,ms=gs+1+bs,ws=30,vs=19,_s=2*ms+1,ks=15,As=16,Ss=7,Es=256,Ps=16,xs=17,Ms=18,Ks=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Cs=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ds=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Us=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Rs=Array(2*(ms+2));fs(Rs);const Is=Array(2*ws);fs(Is);const Bs=Array(512);fs(Bs);const Ts=Array(256);fs(Ts);const zs=Array(bs);fs(zs);const qs=Array(ws);function Fs(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}let Os,Ls,Ns;function js(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Hs(e){return e<256?Bs[e]:Bs[256+(e>>>7)]}function Ws(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Gs(e,t,r){e.bi_valid>As-r?(e.bi_buf|=t<>As-e.bi_valid,e.bi_valid+=r-As):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Zs(e,t,r){const i=Array(ks+1);let n,a,s=0;for(n=1;n<=ks;n++)i[n]=s=s+r[n-1]<<1;for(a=0;a<=t;a++){const t=e[2*a+1];0!==t&&(e[2*a]=$s(i[t]++,t))}}function Xs(e){let t;for(t=0;t8?Ws(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Qs(e,t,r,i){const n=2*t,a=2*r;return e[n]>1;s>=1;s--)Js(e,r,s);c=a;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Js(e,r,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,r[2*c]=r[2*s]+r[2*o],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,r[2*s+1]=r[2*o+1]=c,e.heap[1]=c++,Js(e,r,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){const r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let u,h,d,f,l,p,y=0;for(f=0;f<=ks;f++)e.bl_count[f]=0;for(r[2*e.heap[e.heap_max]+1]=0,u=e.heap_max+1;u<_s;u++)h=e.heap[u],f=r[2*r[2*h+1]+1]+1,f>c&&(f=c,y++),r[2*h+1]=f,h>i||(e.bl_count[f]++,l=0,h>=o&&(l=s[h-o]),p=r[2*h],e.opt_len+=p*(f+l),a&&(e.static_len+=p*(n[2*h+1]+l)));if(0!==y){do{for(f=c-1;0===e.bl_count[f];)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,y-=2}while(y>0);for(f=c;0!==f;f--)for(h=e.bl_count[f];0!==h;)d=e.heap[--u],d>i||(r[2*d+1]!==f&&(e.opt_len+=(f-r[2*d+1])*r[2*d],r[2*d+1]=f),h--)}}(e,t),Zs(r,u,e.bl_count)}function ro(e,t,r){let i,n,a=-1,s=t[1],o=0,c=7,u=4;for(0===s&&(c=138,u=3),t[2*(r+1)+1]=65535,i=0;i<=r;i++)n=s,s=t[2*(i+1)+1],++o>=7;i=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function co(e,t,r,i){let n,a,s=0;e.level>0?(e.strm.data_type===hs&&(e.strm.data_type=function(e){let t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return cs;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return us;for(t=32;t=3&&0===e.bl_tree[2*Us[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),n=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=n&&(n=a)):n=a=r+5,r+4<=n&&-1!==t?so(e,t,r,i):e.strategy===os||a===n?(Gs(e,(ps<<1)+(i?1:0),3),eo(e,Rs,Is)):(Gs(e,(ys<<1)+(i?1:0),3),function(e,t,r,i){let n;for(Gs(e,t-257,5),Gs(e,r-1,5),Gs(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(Ts[r]+gs+1)]++,e.dyn_dtree[2*Hs(t)]++),e.last_lit===e.lit_bufsize-1}function ho(e,t,r,i){let n=65535&e|0,a=e>>>16&65535|0,s=0;for(;0!==r;){s=r>2e3?2e3:r,r-=s;do{n=n+t[i++]|0,a=a+n|0}while(--s);n%=65521,a%=65521}return n|a<<16|0}const fo=function(){let e;const t=[];for(let r=0;r<256;r++){e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function lo(e,t,r,i){const n=fo,a=i+r;e^=-1;for(let r=i;r>>8^n[255&(e^t[r])];return-1^e}var po={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};const yo=9,bo=3,go=258,mo=go+bo+1,wo=32,vo=42,_o=69,ko=73,Ao=91,So=103,Eo=113,Po=666,xo=1,Mo=2,Ko=3,Co=4,Do=3;function Uo(e,t){return e.msg=po[t],t}function Ro(e){return(e<<1)-(e>4?9:0)}function Io(e){let t=e.length;for(;--t>=0;)e[t]=0}function Bo(e){const t=e.state;let r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(ja(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function To(e,t){co(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Bo(e.strm)}function zo(e,t){e.pending_buf[e.pending++]=t}function qo(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Fo(e,t,r,i){let n=e.avail_in;return n>i&&(n=i),0===n?0:(e.avail_in-=n,ja(t,e.input,e.next_in,n,r),1===e.state.wrap?e.adler=ho(e.adler,t,n,r):2===e.state.wrap&&(e.adler=lo(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function Oo(e,t){let r,i,n=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-mo?e.strstart-(e.w_size-mo):0,u=e.window,h=e.w_mask,d=e.prev,f=e.strstart+go;let l=u[a+s-1],p=u[a+s];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do{if(r=t,u[r+s]===p&&u[r+s-1]===l&&u[r]===u[a]&&u[++r]===u[a+1]){a+=2,r++;do{}while(u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&as){if(e.match_start=t,s=i,i>=o)break;l=u[a+s-1],p=u[a+s]}}}while((t=d[t&h])>c&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Lo(e){const t=e.w_size;let r,i,n,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-mo)){ja(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do{n=e.head[--r],e.head[r]=n>=t?n-t:0}while(--i);i=t,r=i;do{n=e.prev[--r],e.prev[r]=n>=t?n-t:0}while(--i);a+=t}if(0===e.strm.avail_in)break;if(i=Fo(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=i,e.lookahead+e.insert>=bo)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=bo&&(e.ins_h=(e.ins_h<=bo)if(i=uo(e,e.strstart-e.match_start,e.match_length-bo),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=bo){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=bo&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=bo-1)),e.prev_length>=bo&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-bo,i=uo(e,e.strstart-1-e.prev_match,e.prev_length-bo),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Lo(e),0===e.lookahead&&t===Ha)return xo;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;const i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,To(e,!1),0===e.strm.avail_out))return xo;if(e.strstart-e.block_start>=e.w_size-mo&&(To(e,!1),0===e.strm.avail_out))return xo}return e.insert=0,t===$a?(To(e,!0),0===e.strm.avail_out?Ko:Co):(e.strstart>e.block_start&&(To(e,!1),e.strm.avail_out),xo)})),new Ho(4,4,8,4,No),new Ho(4,5,16,8,No),new Ho(4,6,32,32,No),new Ho(4,4,16,16,jo),new Ho(8,16,32,32,jo),new Ho(8,16,128,128,jo),new Ho(8,32,128,256,jo),new Ho(32,128,258,1024,jo),new Ho(32,258,258,4096,jo)];class Go{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ds,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Oa(1146),this.dyn_dtree=new Oa(122),this.bl_tree=new Oa(78),Io(this.dyn_ltree),Io(this.dyn_dtree),Io(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Oa(16),this.heap=new Oa(573),Io(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Oa(573),Io(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}}function Vo(e){const t=function(e){let t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=hs,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?vo:Eo,e.adler=2===t.wrap?0:1,t.last_flush=Ha,ao(t),Ya):Uo(e,es)}(e);return t===Ya&&function(e){e.window_size=2*e.w_size,Io(e.head),e.max_lazy_match=Wo[e.level].max_lazy,e.good_match=Wo[e.level].good_length,e.nice_match=Wo[e.level].nice_length,e.max_chain_length=Wo[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=bo-1,e.match_available=0,e.ins_h=0}(e.state),t}function $o(e,t){let r,i,n,a;if(!e||!e.state||t>Za||t<0)return e?Uo(e,es):es;if(i=e.state,!e.output||!e.input&&0!==e.avail_in||i.status===Po&&t!==$a)return Uo(e,0===e.avail_out?rs:es);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===vo)if(2===i.wrap)e.adler=0,zo(i,31),zo(i,139),zo(i,8),i.gzhead?(zo(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),zo(i,255&i.gzhead.time),zo(i,i.gzhead.time>>8&255),zo(i,i.gzhead.time>>16&255),zo(i,i.gzhead.time>>24&255),zo(i,9===i.level?2:i.strategy>=as||i.level<2?4:0),zo(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(zo(i,255&i.gzhead.extra.length),zo(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=lo(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=_o):(zo(i,0),zo(i,0),zo(i,0),zo(i,0),zo(i,0),zo(i,9===i.level?2:i.strategy>=as||i.level<2?4:0),zo(i,Do),i.status=Eo);else{let t=ds+(i.w_bits-8<<4)<<8,r=-1;r=i.strategy>=as||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=wo),t+=31-t%31,i.status=Eo,qo(i,t),0!==i.strstart&&(qo(i,e.adler>>>16),qo(i,65535&e.adler)),e.adler=1}if(i.status===_o)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),Bo(e),n=i.pending,i.pending!==i.pending_buf_size));)zo(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=ko)}else i.status=ko;if(i.status===ko)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),Bo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.gzindex=0,i.status=Ao)}else i.status=Ao;if(i.status===Ao)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),Bo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=lo(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.status=So)}else i.status=So;if(i.status===So&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&Bo(e),i.pending+2<=i.pending_buf_size&&(zo(i,255&e.adler),zo(i,e.adler>>8&255),e.adler=0,i.status=Eo)):i.status=Eo),0!==i.pending){if(Bo(e),0===e.avail_out)return i.last_flush=-1,Ya}else if(0===e.avail_in&&Ro(t)<=Ro(r)&&t!==$a)return Uo(e,rs);if(i.status===Po&&0!==e.avail_in)return Uo(e,rs);if(0!==e.avail_in||0!==i.lookahead||t!==Ha&&i.status!==Po){var s=i.strategy===as?function(e,t){let r;for(;;){if(0===e.lookahead&&(Lo(e),0===e.lookahead)){if(t===Ha)return xo;break}if(e.match_length=0,r=uo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(To(e,!1),0===e.strm.avail_out))return xo}return e.insert=0,t===$a?(To(e,!0),0===e.strm.avail_out?Ko:Co):e.last_lit&&(To(e,!1),0===e.strm.avail_out)?xo:Mo}(i,t):i.strategy===ss?function(e,t){let r,i,n,a;const s=e.window;for(;;){if(e.lookahead<=go){if(Lo(e),e.lookahead<=go&&t===Ha)return xo;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=bo&&e.strstart>0&&(n=e.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){a=e.strstart+go;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&ne.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=bo?(r=uo(e,1,e.match_length-bo),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=uo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(To(e,!1),0===e.strm.avail_out))return xo}return e.insert=0,t===$a?(To(e,!0),0===e.strm.avail_out?Ko:Co):e.last_lit&&(To(e,!1),0===e.strm.avail_out)?xo:Mo}(i,t):Wo[i.level].func(i,t);if(s!==Ko&&s!==Co||(i.status=Po),s===xo||s===Ko)return 0===e.avail_out&&(i.last_flush=-1),Ya;if(s===Mo&&(t===Wa?oo(i):t!==Za&&(so(i,0,0,!1),t===Va&&(Io(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Bo(e),0===e.avail_out))return i.last_flush=-1,Ya}return t!==$a?Ya:i.wrap<=0?Qa:(2===i.wrap?(zo(i,255&e.adler),zo(i,e.adler>>8&255),zo(i,e.adler>>16&255),zo(i,e.adler>>24&255),zo(i,255&e.total_in),zo(i,e.total_in>>8&255),zo(i,e.total_in>>16&255),zo(i,e.total_in>>24&255)):(qo(i,e.adler>>>16),qo(i,65535&e.adler)),Bo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Ya:Qa)}try{String.fromCharCode.call(null,0)}catch(e){}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}const Zo=new Fa(256);for(let e=0;e<256;e++)Zo[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;function Xo(e){let t,r,i,n,a=0;const s=e.length;for(i=0;i>>6,o[n++]=128|63&t):t<65536?(o[n++]=224|t>>>12,o[n++]=128|t>>>6&63,o[n++]=128|63&t):(o[n++]=240|t>>>18,o[n++]=128|t>>>12&63,o[n++]=128|t>>>6&63,o[n++]=128|63&t);return o}Zo[254]=Zo[254]=1;class Yo{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}class Qo{constructor(e){this.options={level:is,method:ds,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,...e||{}};const t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Yo,this.strm.avail_out=0;var r,i,n=function(e,t,r,i,n,a){if(!e)return es;let s=1;if(t===is&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),n<1||n>yo||r!==ds||i<8||i>15||t<0||t>9||a<0||a>os)return Uo(e,es);8===i&&(i=9);const o=new Go;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=i,o.w_size=1<=r.w_size&&(0===a&&(Io(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new Fa(r.w_size),ja(u,t,h-r.w_size,r.w_size,0),t=u,h=r.w_size),s=e.avail_in,o=e.next_in,c=e.input,e.avail_in=h,e.next_in=0,e.input=t,Lo(r);r.lookahead>=bo;){i=r.strstart,n=r.lookahead-(bo-1);do{r.ins_h=(r.ins_h<0||0===r.avail_out)&&n!==Qa);return a===$a?(n=function(e){let t;return e&&e.state?(t=e.state.status,t!==vo&&t!==_o&&t!==ko&&t!==Ao&&t!==So&&t!==Eo&&t!==Po?Uo(e,es):(e.state=null,t===Eo?Uo(e,ts):Ya)):es}(this.strm),this.onEnd(n),this.ended=!0,n===Ya):a!==Ga||(this.onEnd(Ya),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ya&&(this.result=Na(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}const Jo=30,ec=12;function tc(e,t){let r,i,n,a,s,o,c,u,h,d;const f=e.state;r=e.next_in;const l=e.input,p=r+(e.avail_in-5);i=e.next_out;const y=e.output,b=i-(t-e.avail_out),g=i+(e.avail_out-257),m=f.dmax,w=f.wsize,v=f.whave,_=f.wnext,k=f.window;n=f.hold,a=f.bits;const A=f.lencode,S=f.distcode,E=(1<>>24,n>>>=o,a-=o,o=s>>>16&255,0===o)y[i++]=65535&s;else{if(!(16&o)){if(0==(64&o)){s=A[(65535&s)+(n&(1<>>=o,a-=o),a<15&&(n+=l[r++]<>>24,n>>>=o,a-=o,o=s>>>16&255,!(16&o)){if(0==(64&o)){s=S[(65535&s)+(n&(1<m){e.msg="invalid distance too far back",f.mode=Jo;break e}if(n>>>=o,a-=o,o=i-b,u>o){if(o=u-o,o>v&&f.sane){e.msg="invalid distance too far back",f.mode=Jo;break e}if(h=0,d=k,0===_){if(h+=w-o,o2;)y[i++]=d[h++],y[i++]=d[h++],y[i++]=d[h++],c-=3;c&&(y[i++]=d[h++],c>1&&(y[i++]=d[h++]))}else{h=i-u;do{y[i++]=y[h++],y[i++]=y[h++],y[i++]=y[h++],c-=3}while(c>2);c&&(y[i++]=y[h++],c>1&&(y[i++]=y[h++]))}break}}break}}while(r>3,r-=c,a-=c<<3,n&=(1<=1&&0===P[g];g--);if(m>g&&(m=g),0===g)return n[a++]=20971520,n[a++]=20971520,o.bits=1,0;for(b=1;b0&&(e===ac||1!==g))return-1;for(x[1]=0,p=1;pic||e===oc&&k>nc)return 1;for(;;){M=p-v,s[y]l?(K=D[U+s[y]],C=S[E+s[y]]):(K=96,C=0),u=1<>v)+h]=M<<24|K<<16|C|0}while(0!==h);for(u=1<>=1;if(0!==u?(A&=u-1,A+=u):A=0,y++,0==--P[p]){if(p===g)break;p=t[r+s[y]]}if(p>m&&(A&R)!==d){for(0===v&&(v=m),f+=b,w=p-v,_=1<ic||e===oc&&k>nc)return 1;d=A&R,n[d]=m<<24|w<<16|f-a|0}}return 0!==A&&(n[f+A]=p-v<<24|64<<16|0),o.bits=m,0}const lc=0,pc=1,yc=2,bc=1,gc=2,mc=3,wc=4,vc=5,_c=6,kc=7,Ac=8,Sc=9,Ec=10,Pc=11,xc=12,Mc=13,Kc=14,Cc=15,Dc=16,Uc=17,Rc=18,Ic=19,Bc=20,Tc=21,zc=22,qc=23,Fc=24,Oc=25,Lc=26,Nc=27,jc=28,Hc=29,Wc=30,Gc=852,Vc=592;function $c(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}class Zc{constructor(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Oa(320),this.work=new Oa(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}}function Xc(e){let t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,function(e){let t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=bc,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new La(Gc),t.distcode=t.distdyn=new La(Vc),t.sane=1,t.back=-1,Ya):es}(e)):es}function Yc(e,t){let r,i;return e?(i=new Zc,e.state=i,i.window=null,r=function(e,t){let r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?es:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,Xc(e))):es}(e,t),r!==Ya&&(e.state=null),r):es}let Qc,Jc,eu=!0;function tu(e){if(eu){let t;for(Qc=new La(512),Jc=new La(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(fc(pc,e.lens,0,288,Qc,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;fc(yc,e.lens,0,32,Jc,0,e.work,{bits:5}),eu=!1}e.lencode=Qc,e.lenbits=9,e.distcode=Jc,e.distbits=5}function ru(e,t,r,i){let n;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(ja(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>i&&(n=i),ja(a.window,t,r-i,n,a.wnext),(i-=n)?(ja(a.window,t,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=lo(r.check,x,2,0),u=0,h=0,r.mode=gc;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=Wc;break}if((15&u)!==ds){e.msg="unknown compression method",r.mode=Wc;break}if(u>>>=4,h-=4,k=8+(15&u),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=Wc;break}r.dmax=1<>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=lo(r.check,x,2,0)),u=0,h=0,r.mode=mc;case mc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=lo(r.check,x,4,0)),u=0,h=0,r.mode=wc;case wc:for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=lo(r.check,x,2,0)),u=0,h=0,r.mode=vc;case vc:if(1024&r.flags){for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>>8&255,r.check=lo(r.check,x,2,0)),u=0,h=0}else r.head&&(r.head.extra=null);r.mode=_c;case _c:if(1024&r.flags&&(l=r.length,l>o&&(l=o),l&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=Array(r.head.extra_len)),ja(r.head.extra,i,a,l,k)),512&r.flags&&(r.check=lo(r.check,i,l,a)),o-=l,a+=l,r.length-=l),r.length))break e;r.length=0,r.mode=kc;case kc:if(2048&r.flags){if(0===o)break e;l=0;do{k=i[a+l++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k))}while(k&&l>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=xc;break;case Ec:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>=7&h,h-=7&h,r.mode=Nc;break}for(;h<3;){if(0===o)break e;o--,u+=i[a++]<>>=1,h-=1,3&u){case 0:r.mode=Kc;break;case 1:if(tu(r),r.mode=Bc,t===Xa){u>>>=2,h-=2;break e}break;case 2:r.mode=Uc;break;case 3:e.msg="invalid block type",r.mode=Wc}u>>>=2,h-=2;break;case Kc:for(u>>>=7&h,h-=7&h;h<32;){if(0===o)break e;o--,u+=i[a++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=Wc;break}if(r.length=65535&u,u=0,h=0,r.mode=Cc,t===Xa)break e;case Cc:r.mode=Dc;case Dc:if(l=r.length,l){if(l>o&&(l=o),l>c&&(l=c),0===l)break e;ja(n,i,a,l,s),o-=l,a+=l,c-=l,s+=l,r.length-=l;break}r.mode=xc;break;case Uc:for(;h<14;){if(0===o)break e;o--,u+=i[a++]<>>=5,h-=5,r.ndist=1+(31&u),u>>>=5,h-=5,r.ncode=4+(15&u),u>>>=4,h-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Wc;break}r.have=0,r.mode=Rc;case Rc:for(;r.have>>=3,h-=3}for(;r.have<19;)r.lens[M[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},A=fc(lc,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid code lengths set",r.mode=Wc;break}r.have=0,r.mode=Ic;case Ic:for(;r.have>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=b,h-=b,r.lens[r.have++]=m;else{if(16===m){for(E=b+2;h>>=b,h-=b,0===r.have){e.msg="invalid bit length repeat",r.mode=Wc;break}k=r.lens[r.have-1],l=3+(3&u),u>>>=2,h-=2}else if(17===m){for(E=b+3;h>>=b,h-=b,k=0,l=3+(7&u),u>>>=3,h-=3}else{for(E=b+7;h>>=b,h-=b,k=0,l=11+(127&u),u>>>=7,h-=7}if(r.have+l>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Wc;break}for(;l--;)r.lens[r.have++]=k}}if(r.mode===Wc)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=Wc;break}if(r.lenbits=9,S={bits:r.lenbits},A=fc(pc,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid literal/lengths set",r.mode=Wc;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},A=fc(yc,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,A){e.msg="invalid distances set",r.mode=Wc;break}if(r.mode=Bc,t===Xa)break e;case Bc:r.mode=Tc;case Tc:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,r.hold=u,r.bits=h,tc(e,f),s=e.next_out,n=e.output,c=e.avail_out,a=e.next_in,i=e.input,o=e.avail_in,u=r.hold,h=r.bits,r.mode===xc&&(r.back=-1);break}for(r.back=0;P=r.lencode[u&(1<>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,g=P>>>16&255,m=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,r.length=m,0===g){r.mode=Lc;break}if(32&g){r.back=-1,r.mode=xc;break}if(64&g){e.msg="invalid literal/length code",r.mode=Wc;break}r.extra=15&g,r.mode=zc;case zc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=qc;case qc:for(;P=r.distcode[u&(1<>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,g=P>>>16&255,m=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,64&g){e.msg="invalid distance code",r.mode=Wc;break}r.offset=m,r.extra=15&g,r.mode=Fc;case Fc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Wc;break}r.mode=Oc;case Oc:if(0===c)break e;if(l=f-c,r.offset>l){if(l=r.offset-l,l>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Wc;break}l>r.wnext?(l-=r.wnext,p=r.wsize-l):p=r.wnext-l,l>r.length&&(l=r.length),y=r.window}else y=n,p=s-r.offset,l=r.length;l>c&&(l=c),c-=l,r.length-=l;do{n[s++]=y[p++]}while(--l);0===r.length&&(r.mode=Tc);break;case Lc:if(0===c)break e;n[s++]=r.length,c--,r.mode=Tc;break;case Nc:if(r.wrap){for(;h<32;){if(0===o)break e;o--,u|=i[a++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Yo,this.strm.avail_out=0;let r=Yc(this.strm,t.windowBits);if(r!==Ya)throw Error(po[r]);if(this.header=new au,function(e,t){let r;e&&e.state&&(r=e.state,0==(2&r.wrap)||(r.head=t,t.done=!1))}(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Xo(t.dictionary):t.dictionary instanceof ArrayBuffer&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=nu(this.strm,t.dictionary),r!==Ya)))throw Error(po[r])}push(e,t){const{strm:r,options:{chunkSize:i,dictionary:n}}=this;let a,s,o=!1;if(this.ended)return!1;s=t===~~t?t:!0===t?$a:Ha,"string"==typeof e?r.input=function(e){const t=new Fa(e.length);for(let r=0,i=t.length;r0||0===r.avail_out)&&a!==Qa);return a===Qa&&(s=$a),s===$a?(a=function(e){if(!e||!e.state)return es;const t=e.state;return t.window&&(t.window=null),e.state=null,Ya}(this.strm),this.onEnd(a),this.ended=!0,a===Ya):s!==Ga||(this.onEnd(Ya),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ya&&(this.result=Na(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}var ou=[0,1,3,7,15,31,63,127,255],cu=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};cu.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},cu.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=ou[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var i=r-e;t|=(this.curByte&ou[e]<>i,this.bitOffset+=e,e=0}}return t},cu.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},cu.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var uu=cu,hu=function(){};hu.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},hu.prototype.read=function(e,t,r){for(var i=0;i>>0},this.updateCRC=function(t){e=e<<8^du[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^du[255&(e>>>24^t)]}}),pu=function(e,t){var r,i=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=i,i},yu={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},bu={};bu[yu.LAST_BLOCK]="Bad file checksum",bu[yu.NOT_BZIP_DATA]="Not bzip data",bu[yu.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",bu[yu.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",bu[yu.DATA_ERROR]="Data error",bu[yu.OUT_OF_MEMORY]="Out of memory",bu[yu.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var gu=function(e,t){var r=bu[e]||"unknown error";t&&(r+=": "+t);var i=new TypeError(r);throw i.errorCode=e,i},mu=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};mu.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new lu,!0):(this.writeCount=-1,!1)},mu.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||gu(yu.NOT_BZIP_DATA,"bad magic");var i=r[3]-48;(i<1||i>9)&&gu(yu.NOT_BZIP_DATA,"level out of range"),this.reader=new uu(e),this.dbufSize=1e5*i,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},mu.prototype._get_next_block=function(){var e,t,r,i=this.reader,n=i.pi();if("177245385090"===n)return!1;"314159265359"!==n&&gu(yu.NOT_BZIP_DATA),this.targetBlockCRC=i.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,i.read(1)&&gu(yu.OBSOLETE_INPUT);var a=i.read(24);a>this.dbufSize&&gu(yu.DATA_ERROR,"initial position out of bounds");var s=i.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(s&1<<15-e){var u=16*e;for(r=i.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=u+t)}var h=i.read(3);(h<2||h>6)&&gu(yu.DATA_ERROR);var d=i.read(15);0===d&&gu(yu.DATA_ERROR);var f=new Uint8Array(256);for(e=0;e=h&&gu(yu.DATA_ERROR);l[e]=pu(f,t)}var p,y=c+2,b=[];for(t=0;t20)&&gu(yu.DATA_ERROR),i.read(1);)i.read(1)?s--:s++;w[e]=s}for(g=m=w[0],e=1;em?m=w[e]:w[e]=d&&gu(yu.DATA_ERROR),p=b[l[P++]]),e=p.minLen,t=i.read(e);e>p.maxLen&&gu(yu.DATA_ERROR),!(t<=p.limit[e]);e++)t=t<<1|i.read(1);((t-=p.base[e])<0||t>=258)&&gu(yu.DATA_ERROR);var M=p.permute[t];if(0!==M&&1!==M){if(S)for(S=0,E+s>this.dbufSize&&gu(yu.DATA_ERROR),k[A=o[f[0]]]+=s;s--;)x[E++]=A;if(M>c)break;E>=this.dbufSize&&gu(yu.DATA_ERROR),k[A=o[A=pu(f,e=M-1)]]++,x[E++]=A}else S||(S=1,s=0),s+=0===M?S:2*S,S<<=1}for((a<0||a>=E)&&gu(yu.DATA_ERROR),t=0,e=0;e<256;e++)r=t+k[e],k[e]=t,t=r;for(e=0;e>=8,D=-1),this.writePos=K,this.writeCurrent=C,this.writeCount=E,this.writeRun=D,!0},mu.prototype._read_bunzip=function(e,t){var r,i,n;if(this.writeCount<0)return 0;var a=this.dbuf,s=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var u=this.writeRun;c;){for(c--,i=o,o=255&(s=a[s]),s>>=8,3==u++?(r=o,n=i,o=-1):(r=1,n=o),this.blockCRC.updateCRCRun(n,r);r--;)this.outputStream.writeByte(n),this.nextoutput++;o!=i&&(u=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&gu(yu.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var wu=function(e){if("readByte"in e)return e;var t=new fu;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},vu=function(e){var t=new fu,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var _u=function(e,t,r){for(var i=wu(e),n=vu(t),a=new mu(i,n);!("eof"in i)||!i.eof();)if(a._init_block())a._read_bunzip();else{var s=a.reader.read(32)>>>0;if(s!==a.streamCRC&&gu(yu.DATA_ERROR,"Bad stream CRC (got "+a.streamCRC.toString(16)+" expected "+s.toString(16)+")"),!r||!("eof"in i)||i.eof())break;a._start_bunzip(i,n)}if("getBuffer"in n)return n.getBuffer()};class ku{static get tag(){return ue.packet.literalData}constructor(e=new Date){this.format=ue.literal.utf8,this.date=de.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=ue.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||de.isStream(this.text))&&(this.text=de.decodeUTF8(de.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=de.canonicalizeEOL(de.encodeUTF8(this.text))),e?ee(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await Q(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=de.decodeUTF8(await e.readBytes(r)),this.date=de.readDate(await e.readBytes(4));let i=e.remainder();_(i)&&(i=await ie(i)),this.setBytes(i,t)}))}writeHeader(){const e=de.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),i=de.writeDate(this.date);return de.concatUint8Array([r,t,e,i])}write(){const e=this.writeHeader(),t=this.getBytes();return de.concat([e,t])}}const Au=Symbol("verified"),Su=new Set([ue.signatureSubpacket.issuer,ue.signatureSubpacket.issuerFingerprint,ue.signatureSubpacket.embeddedSignature]);class Eu{static get tag(){return ue.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.signedHashValue=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new Ke,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.revoked=null,this[Au]=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version)throw new Un(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[t++],this.publicKeyAlgorithm=e[t++],this.hashAlgorithm=e[t++],t+=this.readSubPackets(e.subarray(t,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");this.signatureData=e.subarray(0,t),t+=this.readSubPackets(e.subarray(t,e.length),!1),this.signedHashValue=e.subarray(t,t+2),t+=2,this.params=Ia.signature.parseSignatureParams(this.publicKeyAlgorithm,e.subarray(t,e.length))}writeParams(){return this.params instanceof Promise?ae((async()=>Ia.serializeParams(this.publicKeyAlgorithm,await this.params))):Ia.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),e.push(this.writeParams()),de.concat(e)}async sign(e,t,r=new Date,i=!1){5===e.version?this.version=5:this.version=4;const n=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];this.created=de.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID(),n.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=de.concat(n);const a=this.toHash(this.signatureType,t,i),s=await this.hash(this.signatureType,t,a,i);this.signedHashValue=re(J(s),0,2);const o=async()=>Ia.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await ie(s));de.isStream(s)?this.params=o():(this.params=await o(),this[Au]=!0)}writeHashedSubPackets(){const e=ue.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(Pu(e.signatureCreationTime,!0,de.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(Pu(e.signatureExpirationTime,!0,de.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(Pu(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(Pu(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(Pu(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(Pu(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(Pu(e.keyExpirationTime,!0,de.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(Pu(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=de.concat([r,this.revocationKeyFingerprint]),t.push(Pu(e.revocationKey,!1,r))),this.issuerKeyID.isNull()||5===this.issuerKeyVersion||t.push(Pu(e.issuer,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:i,value:n,humanReadable:a,critical:s})=>{r=[new Uint8Array([a?128:0,0,0,0])];const o=de.encodeUTF8(i);r.push(de.writeNumber(o.length,2)),r.push(de.writeNumber(n.length,2)),r.push(o),r.push(n),r=de.concat(r),t.push(Pu(e.notationData,s,r))})),null!==this.preferredHashAlgorithms&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(Pu(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(Pu(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.keyServerPreferences)),t.push(Pu(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(Pu(e.preferredKeyServer,!1,de.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(Pu(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(Pu(e.policyURI,!1,de.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.keyFlags)),t.push(Pu(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(Pu(e.signersUserID,!1,de.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=de.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(Pu(e.reasonForRevocation,!0,r))),null!==this.features&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.features)),t.push(Pu(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(de.stringToUint8Array(this.signatureTargetHash)),r=de.concat(r),t.push(Pu(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(Pu(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=de.concat(r),t.push(Pu(e.issuerFingerprint,5===this.version,r))),null!==this.preferredAEADAlgorithms&&(r=de.stringToUint8Array(de.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(Pu(e.preferredAEADAlgorithms,!1,r)));const i=de.concat(t),n=de.writeNumber(i.length,2);return de.concat([n,i])}writeUnhashedSubPackets(){const e=[];this.unhashedSubpackets.forEach((t=>{e.push(Pn(t.length)),e.push(t)}));const t=de.concat(e),r=de.writeNumber(t.length,2);return de.concat([r,t])}readSubPacket(e,t=!0){let r=0;const i=!!(128&e[r]),n=127&e[r];if(t||(this.unhashedSubpackets.push(e.subarray(r,e.length)),Su.has(n)))switch(r++,n){case ue.signatureSubpacket.signatureCreationTime:this.created=de.readDate(e.subarray(r,e.length));break;case ue.signatureSubpacket.signatureExpirationTime:{const t=de.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case ue.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case ue.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case ue.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case ue.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case ue.signatureSubpacket.keyExpirationTime:{const t=de.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case ue.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case ue.signatureSubpacket.issuer:this.issuerKeyID.read(e.subarray(r,e.length));break;case ue.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const n=de.readNumber(e.subarray(r,r+2));r+=2;const a=de.readNumber(e.subarray(r,r+2));r+=2;const s=de.decodeUTF8(e.subarray(r,r+n)),o=e.subarray(r+n,r+n+a);this.rawNotations.push({name:s,humanReadable:t,value:o,critical:i}),t&&(this.notations[s]=de.decodeUTF8(o));break}case ue.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=de.decodeUTF8(e.subarray(r,e.length));break;case ue.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case ue.signatureSubpacket.policyURI:this.policyURI=de.decodeUTF8(e.subarray(r,e.length));break;case ue.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.signersUserID:this.signersUserID=de.decodeUTF8(e.subarray(r,e.length));break;case ue.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=de.decodeUTF8(e.subarray(r,e.length));break;case ue.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case ue.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=Ia.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=de.uint8ArrayToString(e.subarray(r,r+t));break}case ue.signatureSubpacket.embeddedSignature:this.embeddedSignature=new Eu,this.embeddedSignature.read(e.subarray(r,e.length));break;case ue.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),5===this.issuerKeyVersion?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case ue.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;default:{const e=Error("Unknown signature subpacket type "+n);if(i)throw e;de.printDebug(e)}}}readSubPackets(e,t=!0,r){const i=de.readNumber(e.subarray(0,2));let n=2;for(;n<2+i;){const i=En(e.subarray(n,e.length));n+=i.offset,this.readSubPacket(e.subarray(n,n+i.len),t,r),n+=i.len}return n}toSign(e,t){const r=ue.signature;switch(e){case r.binary:return null!==t.text?de.encodeUTF8(t.getText(!0)):t.getBytes(!0);case r.text:{const e=t.getBytes(!0);return de.canonicalizeEOL(e)}case r.standalone:return new Uint8Array(0);case r.certGeneric:case r.certPersona:case r.certCasual:case r.certPositive:case r.certRevocation:{let e,i;if(t.userID)i=180,e=t.userID;else{if(!t.userAttribute)throw Error("Either a userID or userAttribute packet needs to be supplied for certification.");i=209,e=t.userAttribute}const n=e.write();return de.concat([this.toSign(r.key,t),new Uint8Array([i]),de.writeNumber(n.length,4),n])}case r.subkeyBinding:case r.subkeyRevocation:case r.keyBinding:return de.concat([this.toSign(r.key,t),this.toSign(r.key,{key:t.bind})]);case r.key:if(void 0===t.key)throw Error("Key packet is required for this signature.");return t.key.writeForHash(this.version);case r.keyRevocation:return this.toSign(r.key,t);case r.timestamp:return new Uint8Array(0);case r.thirdParty:throw Error("Not implemented");default:throw Error("Unknown signature type.")}}calculateTrailer(e,t){let r=0;return X(J(this.signatureData),(e=>{r+=e.length}),(()=>{const i=[];return 5!==this.version||this.signatureType!==ue.signature.binary&&this.signatureType!==ue.signature.text||(t?i.push(new Uint8Array(6)):i.push(e.writeHeader())),i.push(new Uint8Array([this.version,255])),5===this.version&&i.push(new Uint8Array(4)),i.push(de.writeNumber(r,4)),de.concat(i)}))}toHash(e,t,r=!1){const i=this.toSign(e,t);return de.concat([i,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,i=!1){return r||(r=this.toHash(e,t,i)),Ia.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,i=new Date,n=!1,a=we){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const s=t===ue.signature.binary||t===ue.signature.text;if(!(this[Au]&&!s)){let i,a;if(this.hashed?a=await this.hashed:(i=this.toHash(t,r,n),a=await this.hash(t,r,i)),a=await ie(a),this.signedHashValue[0]!==a[0]||this.signedHashValue[1]!==a[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[Au]=await Ia.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,i,a),!this[Au])throw Error("Signature verification failed")}const o=de.normalizeDate(i);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(a.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+ue.read(ue.hash,this.hashAlgorithm).toUpperCase());if(a.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[ue.signature.binary,ue.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+ue.read(ue.hash,this.hashAlgorithm).toUpperCase());if(this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&a.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=de.normalizeDate(e);return null!==t&&!(this.created<=t&&tEu.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==ue.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function Mu(e,t){if(!t[e]){let t;try{t=ue.read(ue.packet,e)}catch(t){throw new Un("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}xu.prototype.hash=Eu.prototype.hash,xu.prototype.toHash=Eu.prototype.toHash,xu.prototype.toSign=Eu.prototype.toSign;class Ku extends Array{static async fromBinary(e,t,r=we){const i=new Ku;return await i.read(e,t,r),i}async read(e,t,r=we){r.additionalAllowedPackets.length&&(t={...t,...de.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=Y(e,(async(e,i)=>{const n=G(i);try{for(;;){await n.ready;if(await Dn(e,(async e=>{try{if(e.tag===ue.packet.marker||e.tag===ue.packet.trust)return;const i=Mu(e.tag,t);i.packets=new Ku,i.fromStream=de.isStream(e.packet),await i.read(e.packet,r),await n.write(i)}catch(t){const i=!r.ignoreUnsupportedPackets&&t instanceof Un,a=!(r.ignoreMalformedPackets||t instanceof Un);if(i||a||Cn(e.tag))await n.abort(t);else{const t=new Rn(e.tag,e.packet);await n.write(t)}de.printDebugError(t)}})))return await n.ready,void await n.close()}}catch(e){await n.abort(e)}}));const i=W(this.stream);for(;;){const{done:e,value:t}=await i.read();if(e?this.stream=null:this.push(t),e||Cn(t.constructor.tag))break}i.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),n+=e.length,n>=a){const e=Math.min(Math.log(n)/Math.LN2|0,30),r=2**e,i=de.concat([xn(e)].concat(t));return t=[i.subarray(1+r)],n=t[0].length,i.subarray(0,1+r)}}),(()=>de.concat([Pn(n)].concat(t)))))}else{if(de.isStream(i)){let t=0;e.push(X(J(i),(e=>{t+=e.length}),(()=>Kn(r,t))))}else e.push(Kn(r,i.length));e.push(i)}}return de.concat(e)}filterByTag(...e){const t=new Ku,r=e=>t=>e===t;for(let i=0;it.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,i=e=>t=>e===t;for(let n=0;n{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),de.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=we){const t=ue.read(ue.compression,this.algorithm),r=qu[t];if(!r)throw Error(t+" decompression not supported");this.packets=await Ku.fromBinary(r(this.compressed),Cu,e)}compress(){const e=ue.read(ue.compression,this.algorithm),t=zu[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write(),this.deflateLevel)}}const Uu=de.getNodeZlib();function Ru(e){return e}function Iu(e,t,r={}){return function(i){return!de.isStream(i)||_(i)?ae((()=>ie(i).then((t=>new Promise(((i,n)=>{e(t,r,((e,t)=>{if(e)return n(e);i(t)}))})))))):C(D(i).pipe(t(r)))}}function Bu(e,t={}){return function(r){const i=new e(t);return X(r,(e=>{if(e.length)return i.push(e,Ga),i.result}),(()=>{if(e===Qo)return i.push([],$a),i.result}))}}function Tu(e){return function(t){return ae((async()=>e(await ie(t))))}}const zu=Uu?{zip:/*#__PURE__*/(e,t)=>Iu(Uu.deflateRaw,Uu.createDeflateRaw,{level:t})(e),zlib:/*#__PURE__*/(e,t)=>Iu(Uu.deflate,Uu.createDeflate,{level:t})(e)}:{zip:/*#__PURE__*/(e,t)=>Bu(Qo,{raw:!0,level:t})(e),zlib:/*#__PURE__*/(e,t)=>Bu(Qo,{level:t})(e)},qu=Uu?{uncompressed:Ru,zip:/*#__PURE__*/Iu(Uu.inflateRaw,Uu.createInflateRaw),zlib:/*#__PURE__*/Iu(Uu.inflate,Uu.createInflate),bzip2:/*#__PURE__*/Tu(_u)}:{uncompressed:Ru,zip:/*#__PURE__*/Bu(su,{raw:!0}),zlib:/*#__PURE__*/Bu(su),bzip2:/*#__PURE__*/Tu(_u)},Fu=/*#__PURE__*/de.constructAllowedPackets([ku,Du,xu,Eu]);class Ou{static get tag(){return ue.packet.symEncryptedIntegrityProtectedData}constructor(){this.version=1,this.encrypted=null,this.packets=null}async read(e){await Q(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Un(`Version ${t} of the SEIP packet is unsupported.`);this.encrypted=e.remainder()}))}write(){return de.concat([new Uint8Array([1]),this.encrypted])}async encrypt(e,t,r=we){const{blockSize:i}=Ia.getCipher(e);let n=this.packets.write();_(n)&&(n=await ie(n));const a=await Ia.getPrefixRandom(e),s=new Uint8Array([211,20]),o=de.concat([a,n,s]),c=await Ia.hash.sha1(ee(o)),u=de.concat([o,c]);return this.encrypted=await Ia.mode.cfb.encrypt(e,t,u,new Uint8Array(i),r),!0}async decrypt(e,t,r=we){const{blockSize:i}=Ia.getCipher(e);let n=J(this.encrypted);_(n)&&(n=await ie(n));const a=await Ia.mode.cfb.decrypt(e,t,n,new Uint8Array(i)),s=re(ee(a),-20),o=re(a,0,-20),c=Promise.all([ie(await Ia.hash.sha1(ee(o))),ie(s)]).then((([e,t])=>{if(!de.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=re(o,i+2);let h=re(u,0,-2);return h=H([h,ae((()=>c))]),de.isStream(n)&&r.allowUnauthenticatedStream||(h=await ie(h)),this.packets=await Ku.fromBinary(h,Fu,r),!0}}const Lu=/*#__PURE__*/de.constructAllowedPackets([ku,Du,xu,Eu]);class Nu{static get tag(){return ue.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=ue.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await Q(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Un(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=Ia.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return de.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=we){this.packets=await Ku.fromBinary(await this.crypt("decrypt",t,J(this.encrypted)),Lu,r)}async encrypt(e,t,r=we){this.cipherAlgorithm=e;const{ivLength:i}=Ia.getAEADMode(this.aeadAlgorithm);this.iv=Ia.random.getRandomBytes(i),this.chunkSizeByte=r.aeadChunkSizeByte;const n=this.packets.write();this.encrypted=await this.crypt("encrypt",t,n)}async crypt(e,t,r){const i=Ia.getAEADMode(this.aeadAlgorithm),n=await i(this.cipherAlgorithm,t),a="decrypt"===e?i.tagLength:0,s="encrypt"===e?i.tagLength:0,o=2**(this.chunkSizeByte+6)+a,c=new ArrayBuffer(21),u=new Uint8Array(c,0,13),h=new Uint8Array(c),d=new DataView(c),f=new Uint8Array(c,5,8);u.set([192|Nu.tag,this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte],0);let l=0,p=Promise.resolve(),y=0,b=0;const g=this.iv;return Y(r,(async(t,r)=>{if("array"!==de.isStream(t)){const e=new F({},{highWaterMark:de.getHardwareConcurrency()*2**(this.chunkSizeByte+6),size:e=>e.length});V(e.readable,r),r=e.writable}const c=W(t),m=G(r);try{for(;;){let t=await c.readBytes(o+a)||new Uint8Array;const r=t.subarray(t.length-a);let w,v;if(t=t.subarray(0,t.length-a),!l||t.length?(c.unshift(r),w=n[e](t,i.getNonce(g,f),u),b+=t.length-a+s):(d.setInt32(17,y),w=n[e](r,i.getNonce(g,f),h),b+=s,v=!0),y+=t.length-a,p=p.then((()=>w)).then((async e=>{await m.ready,await m.write(e),b-=e.length})).catch((e=>m.abort(e))),(v||b>m.desiredSize)&&await p,v){await m.close();break}d.setInt32(9,++l)}}catch(e){await m.abort(e)}}))}}class ju{static get tag(){return ue.packet.publicKeyEncryptedSessionKey}constructor(){this.version=3,this.publicKeyID=new Ke,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}read(e){let t=0;if(this.version=e[t++],3!==this.version)throw new Un(`Version ${this.version} of the PKESK packet is unsupported.`);t+=this.publicKeyID.read(e.subarray(t)),this.publicKeyAlgorithm=e[t++],this.encrypted=Ia.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t),this.version),this.publicKeyAlgorithm===ue.publicKey.x25519&&(this.sessionKeyAlgorithm=ue.write(ue.symmetric,this.encrypted.C.algorithm))}write(){const e=[new Uint8Array([this.version]),this.publicKeyID.write(),new Uint8Array([this.publicKeyAlgorithm]),Ia.serializeParams(this.publicKeyAlgorithm,this.encrypted)];return de.concatUint8Array(e)}async encrypt(e){const t=ue.write(ue.publicKey,this.publicKeyAlgorithm),r=Hu(this.version,t,this.sessionKeyAlgorithm,this.sessionKey);this.encrypted=await Ia.publicKeyEncrypt(t,this.sessionKeyAlgorithm,e.publicParams,r,e.getFingerprintBytes())}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Hu(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,i=await Ia.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,e.getFingerprintBytes(),r),{sessionKey:n,sessionKeyAlgorithm:a}=function(e,t,r,i){switch(t){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.elgamal:case ue.publicKey.ecdh:{const e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=de.writeChecksum(e.subarray(e.length%8)),a=n[0]===t[0]&n[1]===t[1],s={sessionKeyAlgorithm:e[0],sessionKey:e.subarray(1)};if(i){const e=a&s.sessionKeyAlgorithm===i.sessionKeyAlgorithm&s.sessionKey.length===i.sessionKey.length;return{sessionKey:de.selectUint8Array(e,s.sessionKey,i.sessionKey),sessionKeyAlgorithm:de.selectUint8(e,s.sessionKeyAlgorithm,i.sessionKeyAlgorithm)}}if(a&&ue.read(ue.symmetric,s.sessionKeyAlgorithm))return s;throw Error("Decryption error")}case ue.publicKey.x25519:return{sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);this.publicKeyAlgorithm!==ue.publicKey.x25519&&(this.sessionKeyAlgorithm=a),this.sessionKey=n}}function Hu(e,t,r,i){switch(t){case ue.publicKey.rsaEncrypt:case ue.publicKey.rsaEncryptSign:case ue.publicKey.elgamal:case ue.publicKey.ecdh:return de.concatUint8Array([new Uint8Array([r]),i,de.writeChecksum(i.subarray(i.length%8))]);case ue.publicKey.x25519:return i;default:throw Error("Unsupported public key algorithm")}}class Wu{constructor(e=we){this.algorithm=ue.hash.sha256,this.type="iterated",this.c=e.s2kIterationCountByte,this.salt=null}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;try{this.type=ue.read(ue.s2k,e[t++])}catch(e){throw new Un("Unknown S2K type.")}switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==de.uint8ArrayToString(e.subarray(t,t+3)))throw new Un("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Un("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Un("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...de.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([ue.write(ue.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return de.concatUint8Array(e)}async produceKey(e,t){e=de.encodeUTF8(e);const r=[];let i=0,n=0;for(;i{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function Ju(e,t,r){const{keySize:i}=Ia.getCipher(r);return e.produceKey(t,i)}var eh=mt((function(e){!function(t){function r(e){function t(){return Ae0&&(t.semantic=" "),t}}function b(e,t){return function(){var i,a,o,u,h;for(u=r(),i=s("star"),o=0,h=void 0===t?0:t;null!==(a=e());)o+=1,c(i,a);return o>=h?i:(n(u),null)}}function g(e){return e.charCodeAt(0)>=128}function m(){return o("cr",h("\r")())}function w(){return o("crlf",d(m,k)())}function v(){return o("dquote",h('"')())}function _(){return o("htab",h("\t")())}function k(){return o("lf",h("\n")())}function A(){return o("sp",h(" ")())}function S(){return o("vchar",u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i})))}function E(){return o("wsp",f(A,_)())}function P(){var e=o("quoted-pair",f(d(h("\\"),f(S,E)),ie)());return null===e?null:(e.semantic=e.semantic[1],e)}function x(){return o("fws",f(ae,d(l(d(b(E),p(w))),b(E,1)))())}function M(){return o("ctext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=39||42<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),te)())}function K(){return o("ccontent",f(M,P,C)())}function C(){return o("comment",d(h("("),b(d(l(x),K)),l(x),h(")"))())}function D(){return o("cfws",f(d(b(d(l(x),C),1),l(x)),x)())}function U(){return o("atext",u((function(t){var r="a"<=t&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||["!","#","$","%","&","'","*","+","-","/","=","?","^","_","`","{","|","}","~"].indexOf(t)>=0;return e.rfc6532&&(r=r||g(t)),r})))}function R(){return o("atom",d(y(l(D)),b(U,1),y(l(D)))())}function I(){var e,t;return null===(e=o("dot-atom-text",b(U,1)()))||null!==(t=b(d(h("."),b(U,1)))())&&c(e,t),e}function B(){return o("dot-atom",d(p(l(D)),I,p(l(D)))())}function T(){return o("qtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33===r||35<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),re)())}function z(){return o("qcontent",f(T,P)())}function q(){return o("quoted-string",d(p(l(D)),p(v),b(d(l(y(x)),z)),l(p(x)),p(v),p(l(D)))())}function F(){return o("word",f(R,q)())}function O(){return o("address",f(L,H)())}function L(){return o("mailbox",f(N,J)())}function N(){return o("name-addr",d(l(W),j)())}function j(){return o("angle-addr",f(d(p(l(D)),h("<"),J,h(">"),p(l(D))),se)())}function H(){return o("group",d(W,h(":"),l($),h(";"),p(l(D)))())}function W(){return o("display-name",(null!==(e=o("phrase",f(ne,b(F,1))()))&&(e.semantic=function(e){return e.replace(/([ \t]|\r\n)+/g," ").replace(/^\s*/,"").replace(/\s*$/,"")}(e.semantic)),e));var e}function G(){return o("mailbox-list",f(d(L,b(d(h(","),L))),ue)())}function V(){return o("address-list",f(d(O,b(d(h(","),O))),he)())}function $(){return o("group-list",f(G,p(D),de)())}function Z(){return o("local-part",f(fe,B,q)())}function X(){return o("dtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=90||94<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),pe)())}function Y(){return o("domain-literal",d(p(l(D)),h("["),b(d(l(x),X)),l(x),h("]"),p(l(D)))())}function Q(){return o("domain",(t=f(le,B,Y)(),e.rejectTLD&&t&&t.semantic&&t.semantic.indexOf(".")<0?null:(t&&(t.semantic=t.semantic.replace(/\s+/g,"")),t)));var t}function J(){return o("addr-spec",d(Z,h("@"),Q)())}function ee(){return e.strict?null:o("obs-NO-WS-CTL",u((function(e){var t=e.charCodeAt(0);return 1<=t&&t<=8||11===t||12===t||14<=t&&t<=31||127===t})))}function te(){return e.strict?null:o("obs-ctext",ee())}function re(){return e.strict?null:o("obs-qtext",ee())}function ie(){return e.strict?null:o("obs-qp",d(h("\\"),f(h("\0"),ee,k,m))())}function ne(){return e.strict?null:e.atInDisplayName?o("obs-phrase",d(F,b(f(F,h("."),h("@"),y(D))))()):o("obs-phrase",d(F,b(f(F,h("."),y(D))))())}function ae(){return e.strict?null:o("obs-FWS",b(d(p(l(w)),E),1)())}function se(){return e.strict?null:o("obs-angle-addr",d(p(l(D)),h("<"),oe,J,h(">"),p(l(D)))())}function oe(){return e.strict?null:o("obs-route",d(ce,h(":"))())}function ce(){return e.strict?null:o("obs-domain-list",d(b(f(p(D),h(","))),h("@"),Q,b(d(h(","),p(l(D)),l(d(h("@"),Q)))))())}function ue(){return e.strict?null:o("obs-mbox-list",d(b(d(p(l(D)),h(","))),L,b(d(h(","),l(d(L,p(D))))))())}function he(){return e.strict?null:o("obs-addr-list",d(b(d(p(l(D)),h(","))),O,b(d(h(","),l(d(O,p(D))))))())}function de(){return e.strict?null:o("obs-group-list",d(b(d(p(l(D)),h(",")),1),p(l(D)))())}function fe(){return e.strict?null:o("obs-local-part",d(F,b(d(h("."),F)))())}function le(){return e.strict?null:o("obs-domain",d(R,b(d(h("."),R)))())}function pe(){return e.strict?null:o("obs-dtext",f(ee,P)())}function ye(e,t){var r,i,n;if(null==t)return null;for(i=[t];i.length>0;){if((n=i.pop()).name===e)return n;for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r])}return null}function be(e,t){var r,i,n,a,s;if(null==t)return null;for(i=[t],a=[],s={},r=0;r0;)if((n=i.pop()).name in s)a.push(n);else for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}function ge(t){var r,i,n,a,s;if(null===t)return null;for(r=[],i=be(["group","mailbox"],t),n=0;n1)return null;return t.addresses&&t.addresses[0]}(s):e.simple?s&&s.addresses:s}function me(e){var t,r=ye("display-name",e),i=[],n=be(["mailbox"],e);for(t=0;t0;)for((n=i.pop()).name===e&&a.push(n),r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}("cfws",e),n=be(["comment"],e),a=ye("local-part",r),s=ye("domain",r);return{node:e,parts:{name:t,address:r,local:a,domain:s,comments:i},type:e.name,name:ve(t),address:ve(r),local:ve(a),domain:ve(s),comments:_e(n),groupName:ve(e.groupName)}}function ve(e){return null!=e?e.semantic:null}function _e(e){var t="";if(e)for(var r=0;r`),t.userID=r.join(" "),t}read(e,t=we){const r=de.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");try{const{name:e,address:t,comments:i}=eh.parseOneAddress({input:r,atInDisplayName:!0});this.comment=i.replace(/^\(|\)$/g,""),this.name=e,this.email=t}catch(e){}this.userID=r}write(){return de.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class rh extends Qu{static get tag(){return ue.packet.secretSubkey}constructor(e=new Date,t=we){super(e,t)}}const ih=/*#__PURE__*/de.constructAllowedPackets([Eu]);class nh{constructor(e){this.packets=e||new Ku}write(){return this.packets.write()}armor(e=we){return Me(ue.armor.signature,this.write(),void 0,void 0,void 0,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function ah(e,t){const r=new rh(e.date,t);return r.packets=null,r.algorithm=ue.write(ue.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function sh(e,t){const r=new Qu(e.date,t);return r.packets=null,r.algorithm=ue.write(ue.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function oh(e,t,r,i,n=new Date,a){let s,o;for(let c=e.length-1;c>=0;c--)try{(!s||e[c].created>=s.created)&&(await e[c].verify(t,r,i,n,void 0,a),s=e[c])}catch(e){o=e}if(!s)throw de.wrapError(`Could not find valid ${ue.read(ue.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return s}function ch(e,t,r=new Date){const i=de.normalizeDate(r);if(null!==i){const r=yh(e,t);return!(e.created<=i&&i0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1);return await fh(n,null,t,a,r.date,void 0,void 0,void 0,i)}async function hh(e,t,r=new Date,i={},n){let a=n.preferredHashAlgorithm,s=a;if(e){const t=await e.getPrimaryUser(r,i,n);t.selfCertification.preferredHashAlgorithms&&([s]=t.selfCertification.preferredHashAlgorithms,a=Ia.hash.getHashByteLength(a)<=Ia.hash.getHashByteLength(s)?s:a)}switch(t.algorithm){case ue.publicKey.ecdsa:case ue.publicKey.eddsaLegacy:case ue.publicKey.ed25519:s=Ia.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid)}return Ia.hash.getHashByteLength(a)<=Ia.hash.getHashByteLength(s)?s:a}async function dh(e,t=[],r=new Date,i=[],n=we){const a={symmetric:ue.symmetric.aes128,aead:ue.aead.eax,compression:ue.compression.uncompressed}[e],s={symmetric:n.preferredSymmetricAlgorithm,aead:n.preferredAEADAlgorithm,compression:n.preferredCompressionAlgorithm}[e],o={symmetric:"preferredSymmetricAlgorithms",aead:"preferredAEADAlgorithms",compression:"preferredCompressionAlgorithms"}[e],c=await Promise.all(t.map((async function(e,t){const a=(await e.getPrimaryUser(r,i[t],n)).selfCertification[o];return!!a&&a.indexOf(s)>=0})));return c.every(Boolean)?s:a}async function fh(e,t,r,i,n,a,s=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const u=new Eu;return Object.assign(u,i),u.publicKeyAlgorithm=r.algorithm,u.hashAlgorithm=await hh(t,r,n,a,c),u.rawNotations=s,await u.sign(r,e,n,o),u}async function lh(e,t,r,i=new Date,n){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(i)||n&&!await n(e)||t[r].some((function(t){return de.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function ph(e,t,r,i,n,a,s=new Date,o){a=a||e;const c=[];return await Promise.all(i.map((async function(e){try{n&&!e.issuerKeyID.equals(n.issuerKeyID)||(await e.verify(a,t,r,o.revocationsExpire?s:null,!1,o),c.push(e.issuerKeyID))}catch(e){}}))),n?(n.revoked=!!c.some((e=>e.equals(n.issuerKeyID)))||(n.revoked||!1),n.revoked):c.length>0}function yh(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function bh(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=de.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=ue.write(ue.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==ue.curve.ed25519Legacy&&e.curve!==ue.curve.curve25519Legacy||(e.curve=e.sign?ue.curve.ed25519Legacy:ue.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===ue.curve.ed25519Legacy?ue.publicKey.eddsaLegacy:ue.publicKey.ecdsa:e.algorithm=ue.publicKey.ecdh;break;case"rsa":e.algorithm=ue.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function gh(e,t){const r=e.algorithm;return r!==ue.publicKey.rsaEncrypt&&r!==ue.publicKey.elgamal&&r!==ue.publicKey.ecdh&&r!==ue.publicKey.x25519&&(!t.keyFlags||0!=(t.keyFlags[0]&ue.keyFlags.signData))}function mh(e,t){const r=e.algorithm;return r!==ue.publicKey.dsa&&r!==ue.publicKey.rsaSign&&r!==ue.publicKey.ecdsa&&r!==ue.publicKey.eddsaLegacy&&r!==ue.publicKey.ed25519&&(!t.keyFlags||0!=(t.keyFlags[0]&ue.keyFlags.encryptCommunication)||0!=(t.keyFlags[0]&ue.keyFlags.encryptStorage))}function wh(e,t){return!!t.allowInsecureDecryptionWithSigningKeys||(!e.keyFlags||0!=(e.keyFlags[0]&ue.keyFlags.encryptCommunication)||0!=(e.keyFlags[0]&ue.keyFlags.encryptStorage))}function vh(e,t){const r=ue.write(ue.publicKey,e.algorithm),i=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(i.algorithm+" keys are considered too weak.");switch(r){case ue.publicKey.rsaEncryptSign:case ue.publicKey.rsaSign:case ue.publicKey.rsaEncrypt:if(i.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const a=await t.getSigningKey(o,e.created,void 0,i);if(e.revoked||await n.isRevoked(e,a.keyPacket,r,i))throw Error("User certificate is revoked");try{await e.verify(a.keyPacket,ue.signature.certGeneric,s,r,void 0,i)}catch(e){throw de.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const i=this,n=this.selfCertifications.concat(this.otherCertifications);return Promise.all(n.map((async n=>({keyID:n.issuerKeyID,valid:await i.verifyCertificate(n,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};let a;for(let s=this.selfCertifications.length-1;s>=0;s--)try{const a=this.selfCertifications[s];if(a.revoked||await r.isRevoked(a,void 0,e,t))throw Error("Self-certification is revoked");try{await a.verify(i,ue.signature.certGeneric,n,e,void 0,t)}catch(e){throw de.wrapError("Self-certification is invalid",e)}return!0}catch(e){a=e}throw a}async update(e,t,r){const i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};await lh(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(i,ue.signature.certGeneric,n,t,!1,r),!0}catch(e){return!1}})),await lh(e,this,"otherCertifications",t),await lh(e,this,"revocationSignatures",t,(function(e){return ph(i,ue.signature.certRevocation,n,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=ue.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=we){const a={userID:this.userID,userAttribute:this.userAttribute,key:e},s=new _h(a.userID||a.userAttribute,this.mainKey);return s.revocationSignatures.push(await fh(a,null,e,{signatureType:ue.signature.certRevocation,reasonForRevocationFlag:ue.write(ue.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}}class kh{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new Ku;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new kh(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,i=we){const n=this.mainKey.keyPacket;return ph(n,ue.signature.subkeyRevocation,{key:n,bind:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verify(e=new Date,t=we){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket},n=await oh(this.bindingSignatures,r,ue.signature.subkeyBinding,i,e,t);if(n.revoked||await this.isRevoked(n,null,e,t))throw Error("Subkey is revoked");if(ch(this.keyPacket,n,e))throw Error("Subkey is expired");return n}async getExpirationTime(e=new Date,t=we){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket};let n;try{n=await oh(this.bindingSignatures,r,ue.signature.subkeyBinding,i,e,t)}catch(e){return null}const a=yh(this.keyPacket,n),s=n.getExpirationTime();return an.bindingSignatures[t].created&&(n.bindingSignatures[t]=e),!1;try{return await e.verify(i,ue.signature.subkeyBinding,a,t,void 0,r),!0}catch(e){return!1}})),await lh(e,this,"revocationSignatures",t,(function(e){return ph(i,ue.signature.subkeyRevocation,a,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=ue.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=we){const a={key:e,bind:this.keyPacket},s=new kh(this.keyPacket,this.mainKey);return s.revocationSignatures.push(await fh(a,null,e,{signatureType:ue.signature.subkeyRevocation,reasonForRevocationFlag:ue.write(ue.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{kh.prototype[e]=function(){return this.keyPacket[e]()}}));const Ah=/*#__PURE__*/de.constructAllowedPackets([Eu]),Sh=new Set([ue.packet.publicKey,ue.packet.privateKey]),Eh=new Set([ue.packet.publicKey,ue.packet.privateKey,ue.packet.publicSubkey,ue.packet.privateSubkey]);class Ph{packetListToStructure(e,t=new Set){let r,i,n,a;for(const s of e){if(s instanceof Rn){Eh.has(s.tag)&&!a&&(a=Sh.has(s.tag)?Sh:Eh);continue}const e=s.constructor.tag;if(a){if(!a.has(e))continue;a=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case ue.packet.publicKey:case ue.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=s,i=this.getKeyID(),!i)throw Error("Missing Key ID");break;case ue.packet.userID:case ue.packet.userAttribute:r=new _h(s,this),this.users.push(r);break;case ue.packet.publicSubkey:case ue.packet.secretSubkey:r=null,n=new kh(s,this),this.subkeys.push(n);break;case ue.packet.signature:switch(s.signatureType){case ue.signature.certGeneric:case ue.signature.certPersona:case ue.signature.certCasual:case ue.signature.certPositive:if(!r){de.printDebug("Dropping certification signatures without preceding user packet");continue}s.issuerKeyID.equals(i)?r.selfCertifications.push(s):r.otherCertifications.push(s);break;case ue.signature.certRevocation:r?r.revocationSignatures.push(s):this.directSignatures.push(s);break;case ue.signature.key:this.directSignatures.push(s);break;case ue.signature.subkeyBinding:if(!n){de.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}n.bindingSignatures.push(s);break;case ue.signature.keyRevocation:this.revocationSignatures.push(s);break;case ue.signature.subkeyRevocation:if(!n){de.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}n.revocationSignatures.push(s)}}}}toPacketList(){const e=new Ku;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},i=we){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await oh(r.bindingSignatures,n,ue.signature.subkeyBinding,e,t,i);if(!gh(r.keyPacket,a))continue;if(!a.embeddedSignature)throw Error("Missing embedded signature");return await oh([a.embeddedSignature],r.keyPacket,ue.signature.keyBinding,e,t,i),vh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&gh(n,a.selfCertification))return vh(n,i),this}catch(e){s=e}throw de.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),s)}async getEncryptionKey(e,t=new Date,r={},i=we){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await oh(r.bindingSignatures,n,ue.signature.subkeyBinding,e,t,i);if(mh(r.keyPacket,a))return vh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&mh(n,a.selfCertification))return vh(n,i),this}catch(e){s=e}throw de.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),s)}async isRevoked(e,t,r=new Date,i=we){return ph(this.keyPacket,ue.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verifyPrimaryKey(e=new Date,t={},r=we){const i=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");const{selfCertification:n}=await this.getPrimaryUser(e,t,r);if(ch(i,n,e))throw Error("Primary key is expired");const a=await oh(this.directSignatures,i,ue.signature.key,{key:i},e,r).catch((()=>{}));if(a&&ch(i,a,e))throw Error("Primary key is expired")}async getExpirationTime(e,t=we){let r;try{const{selfCertification:i}=await this.getPrimaryUser(null,e,t),n=yh(this.keyPacket,i),a=i.getExpirationTime(),s=await oh(this.directSignatures,this.keyPacket,ue.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(s){const e=yh(this.keyPacket,s);r=Math.min(n,a,e)}else r=ne.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const i=this.clone();return await lh(e,i,"revocationSignatures",t,(n=>ph(i.keyPacket,ue.signature.keyRevocation,i,[n],null,e.keyPacket,t,r))),await lh(e,i,"directSignatures",t),await Promise.all(e.users.map((async e=>{const n=i.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const n=i.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.subkeys.push(t)}}))),i}async getRevocationCertificate(e=new Date,t=we){const r={key:this.keyPacket},i=await oh(this.revocationSignatures,this.keyPacket,ue.signature.keyRevocation,r,e,t),n=new Ku;return n.push(i),Me(ue.armor.publicKey,n.write(),null,null,"This is a revocation certificate")}async applyRevocationCertificate(e,t=new Date,r=we){const i=await xe(e,r),n=(await Ku.fromBinary(i.data,Ah,r)).findPacket(ue.packet.signature);if(!n||n.signatureType!==ue.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!n.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await n.verify(this.keyPacket,ue.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw de.wrapError("Could not verify revocation signature",e)}const a=this.clone();return a.revocationSignatures.push(n),a}async signPrimaryUser(e,t,r,i=we){const{index:n,user:a}=await this.getPrimaryUser(t,r,i),s=await a.certify(e,t,i),o=this.clone();return o.users[n]=s,o}async signAllUsers(e,t=new Date,r=we){const i=this.clone();return i.users=await Promise.all(this.users.map((function(i){return i.certify(e,t,r)}))),i}async verifyPrimaryUser(e,t=new Date,r,i=we){const n=this.keyPacket,{user:a}=await this.getPrimaryUser(t,r,i);return e?await a.verifyAllCertifications(e,t,i):[{keyID:n.getKeyID(),valid:await a.verify(t,i).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=we){const i=this.keyPacket,n=[];return await Promise.all(this.users.map((async a=>{const s=e?await a.verifyAllCertifications(e,t,r):[{keyID:i.getKeyID(),valid:await a.verify(t,r).catch((()=>!1))}];n.push(...s.map((e=>({userID:a.userID?a.userID.userID:null,userAttribute:a.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),n}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{Ph.prototype[e]=kh.prototype[e]}));class xh extends Ph{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([ue.packet.secretKey,ue.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=we){return Me(ue.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,e)}}class Mh extends xh{constructor(e){if(super(),this.packetListToStructure(e,new Set([ue.packet.publicKey,ue.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new Ku,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case ue.packet.secretKey:{const t=Vu.fromSecretKeyPacket(r);e.push(t);break}case ue.packet.secretSubkey:{const t=Xu.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new xh(e)}armor(e=we){return Me(ue.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,e)}async getDecryptionKeys(e,t=new Date,r={},i=we){const n=this.keyPacket,a=[];for(let r=0;re.isDecrypted()))}async validate(e=we){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys(),t=e.map((e=>e.keyPacket.isDummy())).every(Boolean);if(t)throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=ue.reasonForRevocation.noReason,string:t=""}={},r=new Date,i=we){if(!this.isPrivate())throw Error("Need private key for revoking");const n={key:this.keyPacket},a=this.clone();return a.revocationSignatures.push(await fh(n,null,this.keyPacket,{signatureType:ue.signature.keyRevocation,reasonForRevocationFlag:ue.write(ue.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,i)),a}async addSubkey(e={}){const t={...we,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}const s=th.fromObject(t),o={};o.userID=s,o.key=e;const c={};c.signatureType=ue.signature.certGeneric,c.keyFlags=[ue.keyFlags.certifyKeys|ue.keyFlags.signData],c.preferredSymmetricAlgorithms=a([ue.symmetric.aes256,ue.symmetric.aes128,ue.symmetric.aes192],i.preferredSymmetricAlgorithm),i.aeadProtect&&(c.preferredAEADAlgorithms=a([ue.aead.eax,ue.aead.ocb],i.preferredAEADAlgorithm)),c.preferredHashAlgorithms=a([ue.hash.sha256,ue.hash.sha512],i.preferredHashAlgorithm),c.preferredCompressionAlgorithms=a([ue.compression.zlib,ue.compression.zip,ue.compression.uncompressed],i.preferredCompressionAlgorithm),0===n&&(c.isPrimaryUserID=!0),c.features=[0],c.features[0]|=ue.features.modificationDetection,i.aeadProtect&&(c.features[0]|=ue.features.aead),i.v5Keys&&(c.features[0]|=ue.features.v5Keys),r.keyExpirationTime>0&&(c.keyExpirationTime=r.keyExpirationTime,c.keyNeverExpires=!1);return{userIDPacket:s,signaturePacket:await fh(o,null,e,c,r.date,void 0,void 0,void 0,i)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{n.push(e),n.push(t)}))})),await Promise.all(t.map((async function(t,n){const a=r.subkeys[n];return{secretSubkeyPacket:t,subkeySignaturePacket:await uh(t,e,a,i)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{n.push(e),n.push(t)}))}));const a={key:e};return n.push(await fh(a,null,e,{signatureType:ue.signature.keyRevocation,reasonForRevocationFlag:ue.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,i)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new Mh(n)}const Uh=/*#__PURE__*/de.constructAllowedPackets([ku,Du,Nu,Ou,Zu,ju,Gu,xu,Eu]),Rh=/*#__PURE__*/de.constructAllowedPackets([Gu]),Ih=/*#__PURE__*/de.constructAllowedPackets([Eu]);class Bh{constructor(e){this.packets=e||new Ku}getEncryptionKeyIDs(){const e=[];return this.packets.filterByTag(ue.packet.publicKeyEncryptedSessionKey).forEach((function(t){e.push(t.publicKeyID)})),e}getSigningKeyIDs(){const e=this.unwrapCompressed(),t=e.packets.filterByTag(ue.packet.onePassSignature);if(t.length>0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(ue.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,i=new Date,n=we){const a=r||await this.decryptSessionKeys(e,t,i,n),s=this.packets.filterByTag(ue.packet.symmetricallyEncryptedData,ue.packet.symEncryptedIntegrityProtectedData,ue.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const o=s[0];let c=null;const u=Promise.all(a.map((async({algorithm:e,data:t})=>{if(!de.isUint8Array(t)||!de.isString(e))throw Error("Invalid session key for decryption.");try{const r=ue.write(ue.symmetric,e);await o.decrypt(r,t,n)}catch(e){de.printDebugError(e),c=e}})));if(ne(o.encrypted),o.encrypted=null,await u,!o.packets||!o.packets.length)throw c||Error("Decryption failed.");const h=new Bh(o.packets);return o.packets=new Ku,h}async decryptSessionKeys(e,t,r=new Date,i=we){let n,a=[];if(t){const e=this.packets.filterByTag(ue.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await Ku.fromBinary(e.write(),Rh,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){de.printDebugError(e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(ue.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let s=[ue.symmetric.aes256,ue.symmetric.aes128,ue.symmetric.tripledes,ue.symmetric.cast5];try{const t=await e.getPrimaryUser(r,void 0,i);t.selfCertification.preferredSymmetricAlgorithms&&(s=s.concat(t.selfCertification.preferredSymmetricAlgorithms))}catch(e){}const o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket));await Promise.all(o.map((async function(e){if(!e||e.isDummy())return;if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===ue.publicKey.rsaEncrypt||t.publicKeyAlgorithm===ue.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===ue.publicKey.rsaSign||t.publicKeyAlgorithm===ue.publicKey.elgamal)){const r=t.write();await Promise.all(Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map((async t=>{const i=new ju;i.read(r);const s={sessionKeyAlgorithm:t,sessionKey:Ia.generateSessionKey(t)};try{await i.decrypt(e,s),a.push(i)}catch(e){de.printDebugError(e),n=e}})))}else try{if(await t.decrypt(e),!s.includes(ue.write(ue.symmetric,t.sessionKeyAlgorithm)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){de.printDebugError(e),n=e}})))}))),ne(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+de.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:ue.read(ue.symmetric,e.sessionKeyAlgorithm)})))}throw n||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(ue.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(ue.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(ue.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],i=we){const n=await dh("symmetric",e,t,r,i),a=ue.read(ue.symmetric,n),s=i.aeadProtect&&await async function(e,t=new Date,r=[],i=we){let n=!0;return await Promise.all(e.map((async function(e,a){const s=await e.getPrimaryUser(t,r[a],i);s.selfCertification.features&&s.selfCertification.features[0]&ue.features.aead||(n=!1)}))),n}(e,t,r,i)?ue.read(ue.aead,await dh("aead",e,t,r,i)):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&e.keyPacket.algorithm===ue.publicKey.x25519&&!de.isAES(n))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:Ia.generateSessionKey(n),algorithm:a,aeadAlgorithm:s}}async encrypt(e,t,r,i=!1,n=[],a=new Date,s=[],o=we){if(r){if(!de.isUint8Array(r.data)||!de.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Bh.generateSessionKey(e,a,s,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Bh.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:u,aeadAlgorithm:h}=r,d=await Bh.encryptSessionKey(c,u,h,e,t,i,n,a,s,o);let f;h?(f=new Nu,f.aeadAlgorithm=ue.write(ue.aead,h)):f=new Ou,f.packets=this.packets;const l=ue.write(ue.symmetric,u);return await f.encrypt(l,c,o),d.packets.push(f),f.packets=new Ku,d}static async encryptSessionKey(e,t,r,i,n,a=!1,s=[],o=new Date,c=[],u=we){const h=new Ku,d=ue.write(ue.symmetric,t),f=r&&ue.write(ue.aead,r);if(i){const t=await Promise.all(i.map((async function(t,r){const i=await t.getEncryptionKey(s[r],o,c,u),n=new ju;return n.publicKeyID=a?Ke.wildcard():i.getKeyID(),n.publicKeyAlgorithm=i.keyPacket.algorithm,n.sessionKey=e,n.sessionKeyAlgorithm=d,await n.encrypt(i.keyPacket),delete n.sessionKey,n})));h.push(...t)}if(n){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,i=async function(e,a,s,o){const c=new Gu(u);if(c.sessionKey=e,c.sessionKeyAlgorithm=a,s&&(c.aeadAlgorithm=s),await c.encrypt(o,u),u.passwordCollisionCheck){if(1!==(await Promise.all(n.map((e=>t(c,e))))).reduce(r))return i(e,a,o)}return delete c.sessionKey,c},a=await Promise.all(n.map((t=>i(e,d,f,t))));h.push(...a)}return new Bh(h)}async sign(e=[],t=null,r=[],i=new Date,n=[],a=[],s=we){const o=new Ku,c=this.packets.findPacket(ue.packet.literalData);if(!c)throw Error("No literal data packet to sign.");let u,h;const d=null===c.text?ue.signature.binary:ue.signature.text;if(t)for(h=t.packets.filterByTag(ue.packet.signature),u=h.length-1;u>=0;u--){const t=h[u],r=new xu;r.signatureType=t.signatureType,r.hashAlgorithm=t.hashAlgorithm,r.publicKeyAlgorithm=t.publicKeyAlgorithm,r.issuerKeyID=t.issuerKeyID,e.length||0!==u||(r.flags=1),o.push(r)}return await Promise.all(Array.from(e).reverse().map((async function(t,a){if(!t.isPrivate())throw Error("Need private key for signing");const o=r[e.length-1-a],c=await t.getSigningKey(o,i,n,s),u=new xu;return u.signatureType=d,u.hashAlgorithm=await hh(t,c.keyPacket,i,n,s),u.publicKeyAlgorithm=c.keyPacket.algorithm,u.issuerKeyID=c.getKeyID(),a===e.length-1&&(u.flags=1),u}))).then((e=>{e.forEach((e=>o.push(e)))})),o.push(c),o.push(...await Th(c,e,t,r,i,n,a,!1,s)),new Bh(o)}compress(e,t=we){if(e===ue.compression.uncompressed)return this;const r=new Du(t);r.algorithm=e,r.packets=this.packets;const i=new Ku;return i.push(r),new Bh(i)}async signDetached(e=[],t=null,r=[],i=new Date,n=[],a=[],s=we){const o=this.packets.findPacket(ue.packet.literalData);if(!o)throw Error("No literal data packet to sign.");return new nh(await Th(o,e,t,r,i,n,a,!0,s))}async verify(e,t=new Date,r=we){const i=this.unwrapCompressed(),n=i.packets.filterByTag(ue.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");_(i.packets.stream)&&i.packets.push(...await ie(i.packets.stream,(e=>e||[])));const a=i.packets.filterByTag(ue.packet.onePassSignature).reverse(),s=i.packets.filterByTag(ue.packet.signature);return a.length&&!s.length&&de.isStream(i.packets.stream)&&!_(i.packets.stream)?(await Promise.all(a.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=ae((async()=>(await e.correspondingSig).signatureData)),e.hashed=ie(await e.hash(e.signatureType,n[0],void 0,!1)),e.hashed.catch((()=>{}))}))),i.packets.stream=Y(i.packets.stream,(async(e,t)=>{const r=W(e),i=G(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await i.abort(e)}})),zh(a,n,e,t,!1,r)):zh(s,n,e,t,!1,r)}verifyDetached(e,t,r=new Date,i=we){const n=this.unwrapCompressed().packets.filterByTag(ue.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");return zh(e.packets.filterByTag(ue.packet.signature),n,t,r,!0,i)}unwrapCompressed(){const e=this.packets.filterByTag(ue.packet.compressedData);return e.length?new Bh(e[0].packets):this}async appendSignature(e,t=we){await this.packets.read(de.isUint8Array(e)?e:(await xe(e)).data,Ih,t)}write(){return this.packets.write()}armor(e=we){return Me(ue.armor.message,this.write(),null,null,null,e)}}async function Th(e,t,r=null,i=[],n=new Date,a=[],s=[],o=!1,c=we){const u=new Ku,h=null===e.text?ue.signature.binary:ue.signature.text;if(await Promise.all(t.map((async(t,r)=>{const u=a[r];if(!t.isPrivate())throw Error("Need private key for signing");const d=await t.getSigningKey(i[r],n,u,c);return fh(e,t,d.keyPacket,{signatureType:h},n,u,s,o,c)}))).then((e=>{u.push(...e)})),r){const e=r.packets.filterByTag(ue.packet.signature);u.push(...e)}return u}async function zh(e,t,r,i=new Date,n=!1,a=we){return Promise.all(e.filter((function(e){return["text","binary"].includes(ue.read(ue.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,i=new Date,n=!1,a=we){let s,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){s=t,o=r[0];break}}const c=e instanceof xu?e.correspondingSig:e,u={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],i,n,a);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await s.getSigningKey(o.getKeyID(),r.created,void 0,a)}catch(e){if(!a.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await s.getSigningKey(o.getKeyID(),i,void 0,a)}return!0})(),signature:(async()=>{const e=await c,t=new Ku;return e&&t.push(e),new nh(t)})()};return u.signature.catch((()=>{})),u.verified.catch((()=>{})),u}(e,t,r,i,n,a)})))}const qh=/*#__PURE__*/de.constructAllowedPackets([Eu]);class Fh{constructor(e,t){if(this.text=de.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof nh))throw Error("Invalid signature input");this.signature=t||new nh(new Ku)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=null,r=[],i=new Date,n=[],a=[],s=we){const o=new ku;o.setText(this.text);const c=new nh(await Th(o,e,t,r,i,n,a,!0,s));return new Fh(this.text,c)}verify(e,t=new Date,r=we){const i=this.signature.packets.filterByTag(ue.packet.signature),n=new ku;return n.setText(this.text),zh(i,[n],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=we){let t=this.signature.packets.map((function(e){return ue.read(ue.hash,e.hashAlgorithm).toUpperCase()}));t=t.filter((function(e,t,r){return r.indexOf(e)===t}));const r={hash:t.join(),text:this.text,data:this.signature.packets.write()};return Me(ue.armor.signed,r,void 0,void 0,void 0,e)}}function Oh(e){if(!(e instanceof Bh))throw Error("Parameter [message] needs to be of type Message")}function Lh(e){if(!(e instanceof Fh||e instanceof Bh))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Nh(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const jh=Object.keys(we).length;function Hh(e){const t=Object.keys(e);if(t.length!==jh)for(const e of t)if(void 0===we[e])throw Error("Unknown config property: "+e)}function Wh(e){return e&&!de.isArray(e)&&(e=[e]),e}async function Gh(e,t,r="utf8"){const i=de.isStream(e);return"array"===i?ie(e):"node"===t?(e=D(e),"binary"!==r&&e.setEncoding(r),e):"web"===t&&"ponyfill"===i?T(e):e}function Vh(e,t){e.data=Y(t.packets.stream,(async(t,r)=>{await V(e.data,r,{preventClose:!0});const i=G(r);try{await ie(t,(e=>e)),await i.close()}catch(e){await i.abort(e)}}))}function $h(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}const Zh="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function Xh(){}const Yh="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function Qh(e){return"object"==typeof e&&null!==e||"function"==typeof e}const Jh=Xh,ed=Promise,td=Promise.prototype.then,rd=Promise.resolve.bind(ed),id=Promise.reject.bind(ed);function nd(e){return new ed(e)}function ad(e){return rd(e)}function sd(e){return id(e)}function od(e,t,r){return td.call(e,t,r)}function cd(e,t,r){od(od(e,t,r),void 0,Jh)}function ud(e,t){cd(e,t)}function hd(e,t){cd(e,void 0,t)}function dd(e,t,r){return od(e,t,r)}function fd(e){od(e,void 0,Jh)}const ld=(()=>{const e=Yh&&Yh.queueMicrotask;if("function"==typeof e)return e;const t=ad(void 0);return e=>od(t,e)})();function pd(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function yd(e,t,r){try{return ad(pd(e,t,r))}catch(e){return sd(e)}}class bd{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let i=r+1;const n=e._elements,a=n[r];return 16384===i&&(t=e._next,i=0),--this._size,this._cursor=i,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,i=r._elements;for(;!(t===i.length&&void 0===r._next||t===i.length&&(r=r._next,i=r._elements,t=0,0===i.length));)e(i[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function gd(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?_d(e):"closed"===t._state?function(e){_d(e),Sd(e)}(e):kd(e,t._storedError)}function md(e,t){return rp(e._ownerReadableStream,t)}function wd(e){"readable"===e._ownerReadableStream._state?Ad(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){kd(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function vd(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function _d(e){e._closedPromise=nd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function kd(e,t){_d(e),Ad(e,t)}function Ad(e,t){void 0!==e._closedPromise_reject&&(fd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function Sd(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const Ed=Zh("[[AbortSteps]]"),Pd=Zh("[[ErrorSteps]]"),xd=Zh("[[CancelSteps]]"),Md=Zh("[[PullSteps]]"),Kd=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Cd=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Dd(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(t+" is not an object.");var r}function Ud(e,t){if("function"!=typeof e)throw new TypeError(t+" is not a function.")}function Rd(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(t+" is not an object.")}function Id(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function Bd(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Td(e){return Number(e)}function zd(e){return 0===e?0:e}function qd(e,t){const r=Number.MAX_SAFE_INTEGER;let i=Number(e);if(i=zd(i),!Kd(i))throw new TypeError(t+" is not a finite number");if(i=function(e){return zd(Cd(e))}(i),i<0||i>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return Kd(i)&&0!==i?i:0}function Fd(e,t){if(!ep(e))throw new TypeError(t+" is not a ReadableStream.")}function Od(e){return new Wd(e)}function Ld(e,t){e._reader._readRequests.push(t)}function Nd(e,t,r){const i=e._reader._readRequests.shift();r?i._closeSteps():i._chunkSteps(t)}function jd(e){return e._reader._readRequests.length}function Hd(e){const t=e._reader;return void 0!==t&&!!Gd(t)}class Wd{constructor(e){if(Id(e,1,"ReadableStreamDefaultReader"),Fd(e,"First parameter"),tp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");gd(this,e),this._readRequests=new bd}get closed(){return Gd(this)?this._closedPromise:sd($d("closed"))}cancel(e=undefined){return Gd(this)?void 0===this._ownerReadableStream?sd(vd("cancel")):md(this,e):sd($d("cancel"))}read(){if(!Gd(this))return sd($d("read"));if(void 0===this._ownerReadableStream)return sd(vd("read from"));let e,t;const r=nd(((r,i)=>{e=r,t=i}));return Vd(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!Gd(this))throw $d("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");wd(this)}}}function Gd(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function Vd(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[Md](t)}function $d(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let Zd;Object.defineProperties(Wd.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(Wd.prototype,Zh.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof Zh.asyncIterator&&(Zd={[Zh.asyncIterator](){return this}},Object.defineProperty(Zd,Zh.asyncIterator,{enumerable:!1}));class Xd{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?dd(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?dd(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return sd(vd("iterate"));let t,r;const i=nd(((e,i)=>{t=e,r=i}));return Vd(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,ld((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,wd(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,wd(e),r(t)}}),i}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return sd(vd("finish iterating"));if(!this._preventCancel){const r=md(t,e);return wd(t),dd(r,(()=>({value:e,done:!0})))}return wd(t),ad({value:e,done:!0})}}const Yd={next(){return Qd(this)?this._asyncIteratorImpl.next():sd(Jd("next"))},return(e){return Qd(this)?this._asyncIteratorImpl.return(e):sd(Jd("return"))}};function Qd(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl")}function Jd(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==Zd&&Object.setPrototypeOf(Yd,Zd);const ef=Number.isNaN||function(e){return e!=e};function tf(e){return!!function(e){if("number"!=typeof e)return!1;if(ef(e))return!1;if(e<0)return!1;return!0}(e)&&e!==1/0}function rf(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function nf(e,t,r){if(!tf(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function af(e){e._queue=new bd,e._queueTotalSize=0}function sf(e){return e.slice()}class of{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!hf(this))throw Pf("view");return this._view}respond(e){if(!hf(this))throw Pf("respond");if(Id(e,1,"respond"),e=qd(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(t=Number(t),!tf(t))throw new RangeError("bytesWritten must be a finite");vf(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!hf(this))throw Pf("respondWithNewView");if(Id(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");!function(e,t){const r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,vf(e,t.byteLength)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(of.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(of.prototype,Zh.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class cf{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!uf(this))throw xf("byobRequest");if(null===this._byobRequest&&this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(of.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest}get desiredSize(){if(!uf(this))throw xf("desiredSize");return Sf(this)}close(){if(!uf(this))throw xf("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Af(e,t),t}}kf(e),ip(t)}(this)}enqueue(e){if(!uf(this))throw xf("enqueue");if(Id(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const i=t.buffer,n=t.byteOffset,a=t.byteLength,s=i;if(Hd(r))if(0===jd(r))pf(e,s,n,a);else{Nd(r,new Uint8Array(s,n,a),!1)}else Cf(r)?(pf(e,s,n,a),wf(e)):pf(e,s,n,a);df(e)}(this,e)}error(e=undefined){if(!uf(this))throw xf("error");Af(this,e)}[xd](e){if(this._pendingPullIntos.length>0){this._pendingPullIntos.peek().bytesFilled=0}af(this);const t=this._cancelAlgorithm(e);return kf(this),t}[Md](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,gf(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const i={buffer:t,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}Ld(t,e),df(this)}}function uf(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function hf(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function df(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(Hd(t)&&jd(t)>0)return!0;if(Cf(t)&&Kf(t)>0)return!0;const r=Sf(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;cd(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,df(e))}),(t=>{Af(e,t)}))}function ff(e,t){let r=!1;"closed"===e._state&&(r=!0);const i=lf(t);"default"===t.readerType?Nd(e,i,r):function(e,t,r){const i=e._reader,n=i._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,i,r)}function lf(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function pf(e,t,r,i){e._queue.push({buffer:t,byteOffset:r,byteLength:i}),e._queueTotalSize+=i}function yf(e,t){const r=t.elementSize,i=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,s=a-a%r;let o=n,c=!1;s>i&&(o=s-t.bytesFilled,c=!0);const u=e._queue;for(;o>0;){const r=u.peek(),i=Math.min(o,r.byteLength),n=t.byteOffset+t.bytesFilled;h=t.buffer,d=n,f=r.buffer,l=r.byteOffset,p=i,new Uint8Array(h).set(new Uint8Array(f,l,p),d),r.byteLength===i?u.shift():(r.byteOffset+=i,r.byteLength-=i),e._queueTotalSize-=i,bf(e,i,t),o-=i}var h,d,f,l,p;return c}function bf(e,t,r){mf(e),r.bytesFilled+=t}function gf(e){0===e._queueTotalSize&&e._closeRequested?(kf(e),ip(e._controlledReadableByteStream)):df(e)}function mf(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function wf(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();yf(e,t)&&(_f(e),ff(e._controlledReadableByteStream,t))}}function vf(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;const r=e._controlledReadableByteStream;if(Cf(r))for(;Kf(r)>0;)ff(r,_f(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(bf(e,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=r.buffer.slice(t-i,t);pf(e,n,0,n.byteLength)}r.buffer=r.buffer,r.bytesFilled-=i,ff(e._controlledReadableByteStream,r),wf(e)}(e,t,r);df(e)}function _f(e){const t=e._pendingPullIntos.shift();return mf(e),t}function kf(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Af(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(!function(e){mf(e),e._pendingPullIntos=new bd}(e),af(e),kf(e),np(r,t))}function Sf(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ef(e,t,r){const i=Object.create(cf.prototype);let n=()=>{},a=()=>ad(void 0),s=()=>ad(void 0);void 0!==t.start&&(n=()=>t.start(i)),void 0!==t.pull&&(a=()=>t.pull(i)),void 0!==t.cancel&&(s=e=>t.cancel(e));const o=t.autoAllocateChunkSize;if(0===o)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,i,n,a,s){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,af(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,t._autoAllocateChunkSize=s,t._pendingPullIntos=new bd,e._readableStreamController=t,cd(ad(r()),(()=>{t._started=!0,df(t)}),(e=>{Af(t,e)}))}(e,i,n,a,s,r,o)}function Pf(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function xf(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Mf(e,t){e._reader._readIntoRequests.push(t)}function Kf(e){return e._reader._readIntoRequests.length}function Cf(e){const t=e._reader;return void 0!==t&&!!Uf(t)}Object.defineProperties(cf.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(cf.prototype,Zh.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class Df{constructor(e){if(Id(e,1,"ReadableStreamBYOBReader"),Fd(e,"First parameter"),tp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!uf(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");gd(this,e),this._readIntoRequests=new bd}get closed(){return Uf(this)?this._closedPromise:sd(Rf("closed"))}cancel(e=undefined){return Uf(this)?void 0===this._ownerReadableStream?sd(vd("cancel")):md(this,e):sd(Rf("cancel"))}read(e){if(!Uf(this))return sd(Rf("read"));if(!ArrayBuffer.isView(e))return sd(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return sd(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return sd(new TypeError("view's buffer must have non-zero byteLength"));if(void 0===this._ownerReadableStream)return sd(vd("read from"));let t,r;const i=nd(((e,i)=>{t=e,r=i}));return function(e,t,r){const i=e._ownerReadableStream;i._disturbed=!0,"errored"===i._state?r._errorSteps(i._storedError):function(e,t,r){const i=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,s={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(s),void Mf(i,r);if("closed"!==i._state){if(e._queueTotalSize>0){if(yf(e,s)){const t=lf(s);return gf(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Af(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(s),Mf(i,r),df(e)}else{const e=new a(s.buffer,s.byteOffset,0);r._closeSteps(e)}}(i._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),i}releaseLock(){if(!Uf(this))throw Rf("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");wd(this)}}}function Uf(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function Rf(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function If(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ef(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Bf(e){const{size:t}=e;return t||(()=>1)}function Tf(e,t){Dd(e,t);const r=null==e?void 0:e.highWaterMark,i=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Td(r),size:void 0===i?void 0:zf(i,t+" has member 'size' that")}}function zf(e,t){return Ud(e,t),t=>Td(e(t))}function qf(e,t,r){return Ud(e,r),r=>yd(e,t,[r])}function Ff(e,t,r){return Ud(e,r),()=>yd(e,t,[])}function Of(e,t,r){return Ud(e,r),r=>pd(e,t,[r])}function Lf(e,t,r){return Ud(e,r),(r,i)=>yd(e,t,[r,i])}function Nf(e,t){if(!Gf(e))throw new TypeError(t+" is not a WritableStream.")}Object.defineProperties(Df.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(Df.prototype,Zh.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});class jf{constructor(e={},t={}){void 0===e?e=null:Rd(e,"First parameter");const r=Tf(t,"Second parameter"),i=function(e,t){Dd(e,t);const r=null==e?void 0:e.abort,i=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,s=null==e?void 0:e.write;return{abort:void 0===r?void 0:qf(r,e,t+" has member 'abort' that"),close:void 0===i?void 0:Ff(i,e,t+" has member 'close' that"),start:void 0===n?void 0:Of(n,e,t+" has member 'start' that"),write:void 0===s?void 0:Lf(s,e,t+" has member 'write' that"),type:a}}(e,"First parameter");Wf(this);if(void 0!==i.type)throw new RangeError("Invalid type is specified");const n=Bf(r);!function(e,t,r,i){const n=Object.create(hl.prototype);let a=()=>{},s=()=>ad(void 0),o=()=>ad(void 0),c=()=>ad(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(s=e=>t.write(e,n));void 0!==t.close&&(o=()=>t.close());void 0!==t.abort&&(c=e=>t.abort(e));dl(e,n,a,s,o,c,r,i)}(this,i,If(r,1),n)}get locked(){if(!Gf(this))throw ml("locked");return Vf(this)}abort(e=undefined){return Gf(this)?Vf(this)?sd(new TypeError("Cannot abort a stream that already has a writer")):$f(this,e):sd(ml("abort"))}close(){return Gf(this)?Vf(this)?sd(new TypeError("Cannot close a stream that already has a writer")):Jf(this)?sd(new TypeError("Cannot close an already-closing stream")):Zf(this):sd(ml("close"))}getWriter(){if(!Gf(this))throw ml("getWriter");return Hf(this)}}function Hf(e){return new rl(e)}function Wf(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new bd,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Gf(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function Vf(e){return void 0!==e._writer}function $f(e,t){const r=e._state;if("closed"===r||"errored"===r)return ad(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let i=!1;"erroring"===r&&(i=!0,t=void 0);const n=nd(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:i}}));return e._pendingAbortRequest._promise=n,i||Yf(e,t),n}function Zf(e){const t=e._state;if("closed"===t||"errored"===t)return sd(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=nd(((t,r)=>{const i={_resolve:t,_reject:r};e._closeRequest=i})),i=e._writer;var n;return void 0!==i&&e._backpressure&&"writable"===t&&Kl(i),nf(n=e._writableStreamController,ul,0),pl(n),r}function Xf(e,t){"writable"!==e._state?Qf(e):Yf(e,t)}function Yf(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const i=e._writer;void 0!==i&&sl(i,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Qf(e)}function Qf(e){e._state="errored",e._writableStreamController[Pd]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new bd,void 0===e._pendingAbortRequest)return void el(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void el(e);cd(e._writableStreamController[Ed](r._reason),(()=>{r._resolve(),el(e)}),(t=>{r._reject(t),el(e)}))}function Jf(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function el(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Al(t,e._storedError)}function tl(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){El(e)}(r):Kl(r)),e._backpressure=t}Object.defineProperties(jf.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(jf.prototype,Zh.toStringTag,{value:"WritableStream",configurable:!0});class rl{constructor(e){if(Id(e,1,"WritableStreamDefaultWriter"),Nf(e,"First parameter"),Vf(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!Jf(e)&&e._backpressure?El(this):xl(this),_l(this);else if("erroring"===t)Pl(this,e._storedError),_l(this);else if("closed"===t)xl(this),_l(r=this),Sl(r);else{const t=e._storedError;Pl(this,t),kl(this,t)}var r}get closed(){return il(this)?this._closedPromise:sd(wl("closed"))}get desiredSize(){if(!il(this))throw wl("desiredSize");if(void 0===this._ownerWritableStream)throw vl("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ll(t._writableStreamController)}(this)}get ready(){return il(this)?this._readyPromise:sd(wl("ready"))}abort(e=undefined){return il(this)?void 0===this._ownerWritableStream?sd(vl("abort")):function(e,t){const r=e._ownerWritableStream;return $f(r,t)}(this,e):sd(wl("abort"))}close(){if(!il(this))return sd(wl("close"));const e=this._ownerWritableStream;return void 0===e?sd(vl("close")):Jf(e)?sd(new TypeError("Cannot close an already-closing stream")):nl(this)}releaseLock(){if(!il(this))throw wl("releaseLock");void 0!==this._ownerWritableStream&&ol(this)}write(e=undefined){return il(this)?void 0===this._ownerWritableStream?sd(vl("write to")):cl(this,e):sd(wl("write"))}}function il(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function nl(e){return Zf(e._ownerWritableStream)}function al(e,t){"pending"===e._closedPromiseState?Al(e,t):function(e,t){kl(e,t)}(e,t)}function sl(e,t){"pending"===e._readyPromiseState?Ml(e,t):function(e,t){Pl(e,t)}(e,t)}function ol(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");sl(e,r),al(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function cl(e,t){const r=e._ownerWritableStream,i=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return yl(e,t),1}}(i,t);if(r!==e._ownerWritableStream)return sd(vl("write to"));const a=r._state;if("errored"===a)return sd(r._storedError);if(Jf(r)||"closed"===a)return sd(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return sd(r._storedError);const s=function(e){return nd(((t,r)=>{const i={_resolve:t,_reject:r};e._writeRequests.push(i)}))}(r);return function(e,t,r){try{nf(e,t,r)}catch(t){return void yl(e,t)}const i=e._controlledWritableStream;if(!Jf(i)&&"writable"===i._state){tl(i,bl(e))}pl(e)}(i,t,n),s}Object.defineProperties(rl.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(rl.prototype,Zh.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const ul={};class hl{constructor(){throw new TypeError("Illegal constructor")}error(e=undefined){if(!function(e){if(!Qh(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream"))return!1;return!0}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&gl(this,e)}[Ed](e){const t=this._abortAlgorithm(e);return fl(this),t}[Pd](){af(this)}}function dl(e,t,r,i,n,a,s,o){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,af(t),t._started=!1,t._strategySizeAlgorithm=o,t._strategyHWM=s,t._writeAlgorithm=i,t._closeAlgorithm=n,t._abortAlgorithm=a;const c=bl(t);tl(e,c);cd(ad(r()),(()=>{t._started=!0,pl(t)}),(r=>{t._started=!0,Xf(e,r)}))}function fl(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ll(e){return e._strategyHWM-e._queueTotalSize}function pl(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Qf(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===ul?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),rf(e);const r=e._closeAlgorithm();fl(e),cd(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Sl(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Xf(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const i=e._writeAlgorithm(t);cd(i,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(rf(e),!Jf(r)&&"writable"===t){const t=bl(e);tl(r,t)}pl(e)}),(t=>{"writable"===r._state&&fl(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Xf(e,t)}(r,t)}))}(e,r)}function yl(e,t){"writable"===e._controlledWritableStream._state&&gl(e,t)}function bl(e){return ll(e)<=0}function gl(e,t){const r=e._controlledWritableStream;fl(e),Yf(r,t)}function ml(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function wl(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function vl(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function _l(e){e._closedPromise=nd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function kl(e,t){_l(e),Al(e,t)}function Al(e,t){void 0!==e._closedPromise_reject&&(fd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Sl(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function El(e){e._readyPromise=nd(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Pl(e,t){El(e),Ml(e,t)}function xl(e){El(e),Kl(e)}function Ml(e,t){void 0!==e._readyPromise_reject&&(fd(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Kl(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(hl.prototype,{error:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(hl.prototype,Zh.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Cl="undefined"!=typeof DOMException?DOMException:void 0;const Dl=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Cl)?Cl:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return Object.defineProperty(e.prototype=Object.create(Error.prototype),"constructor",{value:e,writable:!0,configurable:!0}),e}();function Ul(e,t,r,i,n,a){const s=Od(e),o=Hf(t);e._disturbed=!0;let c=!1,u=ad(void 0);return nd(((h,d)=>{let f;if(void 0!==a){if(f=()=>{const r=new Dl("Aborted","AbortError"),a=[];i||a.push((()=>"writable"===t._state?$f(t,r):ad(void 0))),n||a.push((()=>"readable"===e._state?rp(e,r):ad(void 0))),y((()=>Promise.all(a.map((e=>e())))),!0,r)},a.aborted)return void f();a.addEventListener("abort",f)}if(p(e,s._closedPromise,(e=>{i?b(!0,e):y((()=>$f(t,e)),!0,e)})),p(t,o._closedPromise,(t=>{n?b(!0,t):y((()=>rp(e,t)),!0,t)})),function(e,t,r){"closed"===e._state?r():ud(t,r)}(e,s._closedPromise,(()=>{r?b():y((()=>function(e){const t=e._ownerWritableStream,r=t._state;return Jf(t)||"closed"===r?ad(void 0):"errored"===r?sd(t._storedError):nl(e)}(o)))})),Jf(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");n?b(!0,t):y((()=>rp(e,t)),!0,t)}function l(){const e=u;return od(u,(()=>e!==u?l():void 0))}function p(e,t,r){"errored"===e._state?r(e._storedError):hd(t,r)}function y(e,r,i){function n(){cd(e(),(()=>g(r,i)),(e=>g(!0,e)))}c||(c=!0,"writable"!==t._state||Jf(t)?n():ud(l(),n))}function b(e,r){c||(c=!0,"writable"!==t._state||Jf(t)?g(e,r):ud(l(),(()=>g(e,r))))}function g(e,t){ol(o),wd(s),void 0!==a&&a.removeEventListener("abort",f),e?d(t):h(void 0)}fd(nd(((e,t)=>{!function r(i){i?e():od(c?ad(!0):od(o._readyPromise,(()=>nd(((e,t)=>{Vd(s,{_chunkSteps:t=>{u=od(cl(o,t),void 0,Xh),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),r,t)}(!1)})))}))}class Rl{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Il(this))throw Hl("desiredSize");return Ll(this)}close(){if(!Il(this))throw Hl("close");if(!Nl(this))throw new TypeError("The stream is not in a state that permits close");ql(this)}enqueue(e=undefined){if(!Il(this))throw Hl("enqueue");if(!Nl(this))throw new TypeError("The stream is not in a state that permits enqueue");return Fl(this,e)}error(e=undefined){if(!Il(this))throw Hl("error");Ol(this,e)}[xd](e){af(this);const t=this._cancelAlgorithm(e);return zl(this),t}[Md](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=rf(this);this._closeRequested&&0===this._queue.length?(zl(this),ip(t)):Bl(this),e._chunkSteps(r)}else Ld(t,e),Bl(this)}}function Il(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function Bl(e){if(!Tl(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;cd(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Bl(e))}),(t=>{Ol(e,t)}))}function Tl(e){const t=e._controlledReadableStream;if(!Nl(e))return!1;if(!e._started)return!1;if(tp(t)&&jd(t)>0)return!0;return Ll(e)>0}function zl(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ql(e){if(!Nl(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(zl(e),ip(t))}function Fl(e,t){if(!Nl(e))return;const r=e._controlledReadableStream;if(tp(r)&&jd(r)>0)Nd(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Ol(e,t),t}try{nf(e,t,r)}catch(t){throw Ol(e,t),t}}Bl(e)}function Ol(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(af(e),zl(e),np(r,t))}function Ll(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Nl(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function jl(e,t,r,i,n,a,s){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,af(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=s,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,e._readableStreamController=t;cd(ad(r()),(()=>{t._started=!0,Bl(t)}),(e=>{Ol(t,e)}))}function Hl(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Wl(e,t,r){return Ud(e,r),r=>yd(e,t,[r])}function Gl(e,t,r){return Ud(e,r),r=>yd(e,t,[r])}function Vl(e,t,r){return Ud(e,r),r=>pd(e,t,[r])}function $l(e,t){if("bytes"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Zl(e,t){if("byob"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Xl(e,t){Dd(e,t);const r=null==e?void 0:e.preventAbort,i=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(t+" is not an AbortSignal.")}(a,t+" has member 'signal' that"),{preventAbort:!!r,preventCancel:!!i,preventClose:!!n,signal:a}}Object.defineProperties(Rl.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(Rl.prototype,Zh.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class Yl{constructor(e={},t={}){void 0===e?e=null:Rd(e,"First parameter");const r=Tf(t,"Second parameter"),i=function(e,t){Dd(e,t);const r=e,i=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,s=null==r?void 0:r.start,o=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===i?void 0:qd(i,t+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:Wl(n,r,t+" has member 'cancel' that"),pull:void 0===a?void 0:Gl(a,r,t+" has member 'pull' that"),start:void 0===s?void 0:Vl(s,r,t+" has member 'start' that"),type:void 0===o?void 0:$l(o,t+" has member 'type' that")}}(e,"First parameter");if(Jl(this),"bytes"===i.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Ef(this,i,If(r,0))}else{const e=Bf(r);!function(e,t,r,i){const n=Object.create(Rl.prototype);let a=()=>{},s=()=>ad(void 0),o=()=>ad(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(s=()=>t.pull(n)),void 0!==t.cancel&&(o=e=>t.cancel(e)),jl(e,n,a,s,o,r,i)}(this,i,If(r,1),e)}}get locked(){if(!ep(this))throw ap("locked");return tp(this)}cancel(e=undefined){return ep(this)?tp(this)?sd(new TypeError("Cannot cancel a stream that already has a reader")):rp(this,e):sd(ap("cancel"))}getReader(e=undefined){if(!ep(this))throw ap("getReader");const t=function(e,t){Dd(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Zl(r,t+" has member 'mode' that")}}(e,"First parameter");return void 0===t.mode?Od(this):function(e){return new Df(e)}(this)}pipeThrough(e,t={}){if(!ep(this))throw ap("pipeThrough");Id(e,1,"pipeThrough");const r=function(e,t){Dd(e,t);const r=null==e?void 0:e.readable;Bd(r,"readable","ReadableWritablePair"),Fd(r,t+" has member 'readable' that");const i=null==e?void 0:e.writable;return Bd(i,"writable","ReadableWritablePair"),Nf(i,t+" has member 'writable' that"),{readable:r,writable:i}}(e,"First parameter"),i=Xl(t,"Second parameter");if(tp(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Vf(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return fd(Ul(this,r.writable,i.preventClose,i.preventAbort,i.preventCancel,i.signal)),r.readable}pipeTo(e,t={}){if(!ep(this))return sd(ap("pipeTo"));if(void 0===e)return sd("Parameter 1 is required in 'pipeTo'.");if(!Gf(e))return sd(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Xl(t,"Second parameter")}catch(e){return sd(e)}return tp(this)?sd(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Vf(e)?sd(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Ul(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!ep(this))throw ap("tee");const e=function(e,t){const r=Od(e);let i,n,a,s,o,c=!1,u=!1,h=!1;const d=nd((e=>{o=e}));function f(){return c||(c=!0,Vd(r,{_chunkSteps:e=>{ld((()=>{c=!1;const t=e,r=e;u||Fl(a._readableStreamController,t),h||Fl(s._readableStreamController,r)}))},_closeSteps:()=>{c=!1,u||ql(a._readableStreamController),h||ql(s._readableStreamController),u&&h||o(void 0)},_errorSteps:()=>{c=!1}})),ad(void 0)}function l(){}return a=Ql(l,f,(function(t){if(u=!0,i=t,h){const t=sf([i,n]),r=rp(e,t);o(r)}return d})),s=Ql(l,f,(function(t){if(h=!0,n=t,u){const t=sf([i,n]),r=rp(e,t);o(r)}return d})),hd(r._closedPromise,(e=>{Ol(a._readableStreamController,e),Ol(s._readableStreamController,e),u&&h||o(void 0)})),[a,s]}(this);return sf(e)}values(e=undefined){if(!ep(this))throw ap("values");return function(e,t){const r=Od(e),i=new Xd(r,t),n=Object.create(Yd);return n._asyncIteratorImpl=i,n}(this,function(e,t){return Dd(e,t),{preventCancel:!!(null==e?void 0:e.preventCancel)}}(e,"First parameter").preventCancel)}}function Ql(e,t,r,i=1,n=(()=>1)){const a=Object.create(Yl.prototype);Jl(a);return jl(a,Object.create(Rl.prototype),e,t,r,i,n),a}function Jl(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function ep(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function tp(e){return void 0!==e._reader}function rp(e,t){if(e._disturbed=!0,"closed"===e._state)return ad(void 0);if("errored"===e._state)return sd(e._storedError);ip(e);return dd(e._readableStreamController[xd](t),Xh)}function ip(e){e._state="closed";const t=e._reader;void 0!==t&&(Sd(t),Gd(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new bd))}function np(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(Ad(r,t),Gd(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new bd):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new bd))}function ap(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function sp(e,t){Dd(e,t);const r=null==e?void 0:e.highWaterMark;return Bd(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Td(r)}}Object.defineProperties(Yl.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(Yl.prototype,Zh.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof Zh.asyncIterator&&Object.defineProperty(Yl.prototype,Zh.asyncIterator,{value:Yl.prototype.values,writable:!0,configurable:!0});const op=function(e){return e.byteLength};class cp{constructor(e){Id(e,1,"ByteLengthQueuingStrategy"),e=sp(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!hp(this))throw up("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!hp(this))throw up("size");return op}}function up(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function hp(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")}Object.defineProperties(cp.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(cp.prototype,Zh.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const dp=function(){return 1};class fp{constructor(e){Id(e,1,"CountQueuingStrategy"),e=sp(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!pp(this))throw lp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!pp(this))throw lp("size");return dp}}function lp(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function pp(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")}function yp(e,t,r){return Ud(e,r),r=>yd(e,t,[r])}function bp(e,t,r){return Ud(e,r),r=>pd(e,t,[r])}function gp(e,t,r){return Ud(e,r),(r,i)=>yd(e,t,[r,i])}Object.defineProperties(fp.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(fp.prototype,Zh.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class mp{constructor(e={},t={},r={}){void 0===e&&(e=null);const i=Tf(t,"Second parameter"),n=Tf(r,"Third parameter"),a=function(e,t){Dd(e,t);const r=null==e?void 0:e.flush,i=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,s=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:yp(r,e,t+" has member 'flush' that"),readableType:i,start:void 0===n?void 0:bp(n,e,t+" has member 'start' that"),transform:void 0===a?void 0:gp(a,e,t+" has member 'transform' that"),writableType:s}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const s=If(n,0),o=Bf(n),c=If(i,1),u=Bf(i);let h;!function(e,t,r,i,n,a){function s(){return t}function o(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return dd(e._backpressureChangePromise,(()=>{const i=e._writable;if("erroring"===i._state)throw i._storedError;return xp(r,t)}))}return xp(r,t)}(e,t)}function c(t){return function(e,t){return vp(e,t),ad(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,i=r._flushAlgorithm();return Ep(r),dd(i,(()=>{if("errored"===t._state)throw t._storedError;ql(t._readableStreamController)}),(r=>{throw vp(e,r),t._storedError}))}(e)}function h(){return function(e){return kp(e,!1),e._backpressureChangePromise}(e)}function d(t){return _p(e,t),ad(void 0)}e._writable=function(e,t,r,i,n=1,a=(()=>1)){const s=Object.create(jf.prototype);return Wf(s),dl(s,Object.create(hl.prototype),e,t,r,i,n,a),s}(s,o,u,c,r,i),e._readable=Ql(s,h,d,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,kp(e,!0),e._transformStreamController=void 0}(this,nd((e=>{h=e})),c,u,s,o),function(e,t){const r=Object.create(Ap.prototype);let i=e=>{try{return Pp(r,e),ad(void 0)}catch(e){return sd(e)}},n=()=>ad(void 0);void 0!==t.transform&&(i=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,i){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=i}(e,r,i,n)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!wp(this))throw Kp("readable");return this._readable}get writable(){if(!wp(this))throw Kp("writable");return this._writable}}function wp(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function vp(e,t){Ol(e._readable._readableStreamController,t),_p(e,t)}function _p(e,t){Ep(e._transformStreamController),yl(e._writable._writableStreamController,t),e._backpressure&&kp(e,!1)}function kp(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=nd((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(mp.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(mp.prototype,Zh.toStringTag,{value:"TransformStream",configurable:!0});class Ap{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Sp(this))throw Mp("desiredSize");return Ll(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=undefined){if(!Sp(this))throw Mp("enqueue");Pp(this,e)}error(e=undefined){if(!Sp(this))throw Mp("error");var t;t=e,vp(this._controlledTransformStream,t)}terminate(){if(!Sp(this))throw Mp("terminate");!function(e){const t=e._controlledTransformStream,r=t._readable._readableStreamController;ql(r);_p(t,new TypeError("TransformStream terminated"))}(this)}}function Sp(e){return!!Qh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function Ep(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Pp(e,t){const r=e._controlledTransformStream,i=r._readable._readableStreamController;if(!Nl(i))throw new TypeError("Readable side is not in a state that permits enqueue");try{Fl(i,t)}catch(e){throw _p(r,e),r._readable._storedError}const n=function(e){return!Tl(e)}(i);n!==r._backpressure&&kp(r,!0)}function xp(e,t){return dd(e._transformAlgorithm(t),void 0,(t=>{throw vp(e._controlledTransformStream,t),t}))}function Mp(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Kp(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(Ap.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Zh.toStringTag&&Object.defineProperty(Ap.prototype,Zh.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Cp=/*#__PURE__*/Object.freeze({__proto__:null,ByteLengthQueuingStrategy:cp,CountQueuingStrategy:fp,ReadableByteStreamController:cf,ReadableStream:Yl,ReadableStreamBYOBReader:Df,ReadableStreamBYOBRequest:of,ReadableStreamDefaultController:Rl,ReadableStreamDefaultReader:Wd,TransformStream:mp,TransformStreamDefaultController:Ap,WritableStream:jf,WritableStreamDefaultController:hl,WritableStreamDefaultWriter:rl}),Dp=function(e,t){return Dp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Dp(e,t)}; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */function Up(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+t+" is not a constructor or null");function r(){this.constructor=e}Dp(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Rp(e){if(!e)throw new TypeError("Assertion failed")}function Ip(){}function Bp(e){return"object"==typeof e&&null!==e||"function"==typeof e}function Tp(e){if("function"!=typeof e)return!1;var t=!1;try{new e({start:function(){t=!0}})}catch(e){}return t}function zp(e){return!!Bp(e)&&"function"==typeof e.getReader}function qp(e){return!!Bp(e)&&"function"==typeof e.getWriter}function Fp(e){return!!Bp(e)&&(!!zp(e.readable)&&!!qp(e.writable))}function Op(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}function Lp(e,t){var r=(void 0===t?{}:t).type;return Rp(zp(e)),Rp(!1===e.locked),"bytes"===(r=Np(r))?new Gp(e):new Hp(e)}function Np(e){var t=e+"";if("bytes"===t)return t;if(void 0===e)return e;throw new RangeError("Invalid type is specified")}var jp=function(){function e(e){this._underlyingReader=void 0,this._readerMode=void 0,this._readableStreamController=void 0,this._pendingRead=void 0,this._underlyingStream=e,this._attachDefaultReader()}return e.prototype.start=function(e){this._readableStreamController=e},e.prototype.cancel=function(e){return Rp(void 0!==this._underlyingReader),this._underlyingReader.cancel(e)},e.prototype._attachDefaultReader=function(){if("default"!==this._readerMode){this._detachReader();var e=this._underlyingStream.getReader();this._readerMode="default",this._attachReader(e)}},e.prototype._attachReader=function(e){var t=this;Rp(void 0===this._underlyingReader),this._underlyingReader=e;var r=this._underlyingReader.closed;r&&r.then((function(){return t._finishPendingRead()})).then((function(){e===t._underlyingReader&&t._readableStreamController.close()}),(function(r){e===t._underlyingReader&&t._readableStreamController.error(r)})).catch(Ip)},e.prototype._detachReader=function(){void 0!==this._underlyingReader&&(this._underlyingReader.releaseLock(),this._underlyingReader=void 0,this._readerMode=void 0)},e.prototype._pullWithDefaultReader=function(){var e=this;this._attachDefaultReader();var t=this._underlyingReader.read().then((function(t){var r=e._readableStreamController;t.done?e._tryClose():r.enqueue(t.value)}));return this._setPendingRead(t),t},e.prototype._tryClose=function(){try{this._readableStreamController.close()}catch(e){}},e.prototype._setPendingRead=function(e){var t,r=this,i=function(){r._pendingRead===t&&(r._pendingRead=void 0)};this._pendingRead=t=e.then(i,i)},e.prototype._finishPendingRead=function(){var e=this;if(this._pendingRead){var t=function(){return e._finishPendingRead()};return this._pendingRead.then(t,t)}},e}(),Hp=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Up(t,e),t.prototype.pull=function(){return this._pullWithDefaultReader()},t}(jp);function Wp(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Gp=function(e){function t(t){var r=this,i=Op(t);return(r=e.call(this,t)||this)._supportsByob=i,r}return Up(t,e),Object.defineProperty(t.prototype,"type",{get:function(){return"bytes"},enumerable:!1,configurable:!0}),t.prototype._attachByobReader=function(){if("byob"!==this._readerMode){Rp(this._supportsByob),this._detachReader();var e=this._underlyingStream.getReader({mode:"byob"});this._readerMode="byob",this._attachReader(e)}},t.prototype.pull=function(){if(this._supportsByob){var e=this._readableStreamController.byobRequest;if(e)return this._pullWithByobRequest(e)}return this._pullWithDefaultReader()},t.prototype._pullWithByobRequest=function(e){var t=this;this._attachByobReader();var r=new Uint8Array(e.view.byteLength),i=this._underlyingReader.read(r).then((function(r){var i,n,a;t._readableStreamController,r.done?(t._tryClose(),e.respond(0)):(i=r.value,n=e.view,a=Wp(i),Wp(n).set(a,0),e.respond(r.value.byteLength))}));return this._setPendingRead(i),i},t}(jp);function Vp(e){Rp(qp(e)),Rp(!1===e.locked);var t=e.getWriter();return new $p(t)}var $p=function(){function e(e){var t=this;this._writableStreamController=void 0,this._pendingWrite=void 0,this._state="writable",this._storedError=void 0,this._underlyingWriter=e,this._errorPromise=new Promise((function(e,r){t._errorPromiseReject=r})),this._errorPromise.catch(Ip)}return e.prototype.start=function(e){var t=this;this._writableStreamController=e,this._underlyingWriter.closed.then((function(){t._state="closed"})).catch((function(e){return t._finishErroring(e)}))},e.prototype.write=function(e){var t=this,r=this._underlyingWriter;if(null===r.desiredSize)return r.ready;var i=r.write(e);i.catch((function(e){return t._finishErroring(e)})),r.ready.catch((function(e){return t._startErroring(e)}));var n=Promise.race([i,this._errorPromise]);return this._setPendingWrite(n),n},e.prototype.close=function(){var e=this;return void 0===this._pendingWrite?this._underlyingWriter.close():this._finishPendingWrite().then((function(){return e.close()}))},e.prototype.abort=function(e){if("errored"!==this._state)return this._underlyingWriter.abort(e)},e.prototype._setPendingWrite=function(e){var t,r=this,i=function(){r._pendingWrite===t&&(r._pendingWrite=void 0)};this._pendingWrite=t=e.then(i,i)},e.prototype._finishPendingWrite=function(){var e=this;if(void 0===this._pendingWrite)return Promise.resolve();var t=function(){return e._finishPendingWrite()};return this._pendingWrite.then(t,t)},e.prototype._startErroring=function(e){var t=this;if("writable"===this._state){this._state="erroring",this._storedError=e;var r=function(){return t._finishErroring(e)};void 0===this._pendingWrite?r():this._finishPendingWrite().then(r,r),this._writableStreamController.error(e)}},e.prototype._finishErroring=function(e){"writable"===this._state&&this._startErroring(e),"erroring"===this._state&&(this._state="errored",this._errorPromiseReject(this._storedError))},e}();function Zp(e){Rp(Fp(e));var t=e.readable,r=e.writable;Rp(!1===t.locked),Rp(!1===r.locked);var i,n=t.getReader();try{i=r.getWriter()}catch(e){throw n.releaseLock(),e}return new Xp(n,i)}var Xp=function(){function e(e,t){var r=this;this._transformStreamController=void 0,this._onRead=function(e){if(!e.done)return r._transformStreamController.enqueue(e.value),r._reader.read().then(r._onRead)},this._onError=function(e){r._flushReject(e),r._transformStreamController.error(e),r._reader.cancel(e).catch(Ip),r._writer.abort(e).catch(Ip)},this._onTerminate=function(){r._flushResolve(),r._transformStreamController.terminate();var e=new TypeError("TransformStream terminated");r._writer.abort(e).catch(Ip)},this._reader=e,this._writer=t,this._flushPromise=new Promise((function(e,t){r._flushResolve=e,r._flushReject=t}))}return e.prototype.start=function(e){this._transformStreamController=e,this._reader.read().then(this._onRead).then(this._onTerminate,this._onError);var t=this._reader.closed;t&&t.then(this._onTerminate,this._onError)},e.prototype.transform=function(e){return this._writer.write(e)},e.prototype.flush=function(){var e=this;return this._writer.close().then((function(){return e._flushPromise}))},e}(),Yp=/*#__PURE__*/Object.freeze({__proto__:null,createReadableStreamWrapper:function(e){Rp(function(e){return!!Tp(e)&&!!zp(new e)}(e));var t=function(e){try{return new e({type:"bytes"}),!0}catch(e){return!1}}(e);return function(r,i){var n=(void 0===i?{}:i).type;if("bytes"!==(n=Np(n))||t||(n=void 0),r.constructor===e&&("bytes"!==n||Op(r)))return r;if("bytes"===n){var a=Lp(r,{type:n});return new e(a)}a=Lp(r);return new e(a)}},createTransformStreamWrapper:function(e){return Rp(function(e){return!!Tp(e)&&!!Fp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=Zp(t);return new e(r)}},createWrappingReadableSource:Lp,createWrappingTransformer:Zp,createWrappingWritableSink:Vp,createWritableStreamWrapper:function(e){return Rp(function(e){return!!Tp(e)&&!!qp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=Vp(t);return new e(r)}}}),Qp=mt((function(e){!function(e,t){function r(e,t){if(!e)throw Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function n(e,t,r){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof e?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;try{a=u.default.Buffer}catch(e){}function s(e,t,r){for(var i=0,n=Math.min(e.length,r),a=t;a=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return i}function o(e,t,r,i){for(var n=0,a=Math.min(e.length,r),s=t;s=49?o-49+10:o>=17?o-17+10:o}return n}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return e.cmp(t)<0?e:t},n.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&n++,16===t?this._parseHex(e,n):this._parseBase(e,t,n),"-"===e[0]&&(this.negative=1),this.strip(),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initNumber=function(e,t,i){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initArray=function(e,t,i){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var n=0;n=0;n-=3)s=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[a]|=s<>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);else if("le"===i)for(n=0,a=0;n>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);return this.strip()},n.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var r=0;r=t;r-=6)n=s(e,r,r+6),this.words[i]|=n<>>26-a&4194303,(a+=24)>=26&&(a-=26,i++);r+6!==t&&(n=s(e,t,r+6),this.words[i]|=n<>>26-a&4194303),this.strip()},n.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var a=e.length-r,s=a%i,c=Math.min(a,a-s)+r,u=0,h=r;h1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],a=0|t.words[0],s=n*a,o=67108863&s,c=s/67108864|0;r.words[0]=o;for(var u=1;u>>26,d=67108863&c,f=Math.min(u,t.length-1),l=Math.max(0,u-e.length+1);l<=f;l++){var p=u-l|0;h+=(s=(n=0|e.words[p])*(a=0|t.words[l])+d)/67108864|0,d=67108863&s}r.words[u]=0|d,c=0|h}return 0!==c?r.words[u]=0|c:r.length--,r.strip()}n.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var n=0,a=0,s=0;s>>24-n&16777215)||s!==this.length-1?c[6-u.length]+u+i:u+i,(n+=2)>=26&&(n-=26,s--)}for(0!==a&&(i=a.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var f=h[e],l=d[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var y=p.modn(l).toString(e);i=(p=p.idivn(l)).isZero()?y+i:c[f-y.length]+y+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return r(void 0!==a),this.toArrayLike(a,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,i){var n=this.byteLength(),a=i||Math.max(1,n);r(n<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var s,o,c="le"===t,u=new e(a),h=this.clone();if(c){for(o=0;!h.isZero();o++)s=h.andln(255),h.iushrn(8),u[o]=s;for(;o=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-i),this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var i=e/26|0,n=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,a=0;a>>26;for(;0!==n&&a>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;ae.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var a=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==a&&s>26,this.words[s]=67108863&t;if(0===a&&s>>13,l=0|s[1],p=8191&l,y=l>>>13,b=0|s[2],g=8191&b,m=b>>>13,w=0|s[3],v=8191&w,_=w>>>13,k=0|s[4],A=8191&k,S=k>>>13,E=0|s[5],P=8191&E,x=E>>>13,M=0|s[6],K=8191&M,C=M>>>13,D=0|s[7],U=8191&D,R=D>>>13,I=0|s[8],B=8191&I,T=I>>>13,z=0|s[9],q=8191&z,F=z>>>13,O=0|o[0],L=8191&O,N=O>>>13,j=0|o[1],H=8191&j,W=j>>>13,G=0|o[2],V=8191&G,$=G>>>13,Z=0|o[3],X=8191&Z,Y=Z>>>13,Q=0|o[4],J=8191&Q,ee=Q>>>13,te=0|o[5],re=8191&te,ie=te>>>13,ne=0|o[6],ae=8191&ne,se=ne>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,he=0|o[8],de=8191&he,fe=he>>>13,le=0|o[9],pe=8191&le,ye=le>>>13;r.negative=e.negative^t.negative,r.length=19;var be=(u+(i=Math.imul(d,L))|0)+((8191&(n=(n=Math.imul(d,N))+Math.imul(f,L)|0))<<13)|0;u=((a=Math.imul(f,N))+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(p,L),n=(n=Math.imul(p,N))+Math.imul(y,L)|0,a=Math.imul(y,N);var ge=(u+(i=i+Math.imul(d,H)|0)|0)+((8191&(n=(n=n+Math.imul(d,W)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,W)|0)+(n>>>13)|0)+(ge>>>26)|0,ge&=67108863,i=Math.imul(g,L),n=(n=Math.imul(g,N))+Math.imul(m,L)|0,a=Math.imul(m,N),i=i+Math.imul(p,H)|0,n=(n=n+Math.imul(p,W)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,W)|0;var me=(u+(i=i+Math.imul(d,V)|0)|0)+((8191&(n=(n=n+Math.imul(d,$)|0)+Math.imul(f,V)|0))<<13)|0;u=((a=a+Math.imul(f,$)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(v,L),n=(n=Math.imul(v,N))+Math.imul(_,L)|0,a=Math.imul(_,N),i=i+Math.imul(g,H)|0,n=(n=n+Math.imul(g,W)|0)+Math.imul(m,H)|0,a=a+Math.imul(m,W)|0,i=i+Math.imul(p,V)|0,n=(n=n+Math.imul(p,$)|0)+Math.imul(y,V)|0,a=a+Math.imul(y,$)|0;var we=(u+(i=i+Math.imul(d,X)|0)|0)+((8191&(n=(n=n+Math.imul(d,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(A,L),n=(n=Math.imul(A,N))+Math.imul(S,L)|0,a=Math.imul(S,N),i=i+Math.imul(v,H)|0,n=(n=n+Math.imul(v,W)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,W)|0,i=i+Math.imul(g,V)|0,n=(n=n+Math.imul(g,$)|0)+Math.imul(m,V)|0,a=a+Math.imul(m,$)|0,i=i+Math.imul(p,X)|0,n=(n=n+Math.imul(p,Y)|0)+Math.imul(y,X)|0,a=a+Math.imul(y,Y)|0;var ve=(u+(i=i+Math.imul(d,J)|0)|0)+((8191&(n=(n=n+Math.imul(d,ee)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,ee)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(P,L),n=(n=Math.imul(P,N))+Math.imul(x,L)|0,a=Math.imul(x,N),i=i+Math.imul(A,H)|0,n=(n=n+Math.imul(A,W)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,W)|0,i=i+Math.imul(v,V)|0,n=(n=n+Math.imul(v,$)|0)+Math.imul(_,V)|0,a=a+Math.imul(_,$)|0,i=i+Math.imul(g,X)|0,n=(n=n+Math.imul(g,Y)|0)+Math.imul(m,X)|0,a=a+Math.imul(m,Y)|0,i=i+Math.imul(p,J)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,ee)|0;var _e=(u+(i=i+Math.imul(d,re)|0)|0)+((8191&(n=(n=n+Math.imul(d,ie)|0)+Math.imul(f,re)|0))<<13)|0;u=((a=a+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(K,L),n=(n=Math.imul(K,N))+Math.imul(C,L)|0,a=Math.imul(C,N),i=i+Math.imul(P,H)|0,n=(n=n+Math.imul(P,W)|0)+Math.imul(x,H)|0,a=a+Math.imul(x,W)|0,i=i+Math.imul(A,V)|0,n=(n=n+Math.imul(A,$)|0)+Math.imul(S,V)|0,a=a+Math.imul(S,$)|0,i=i+Math.imul(v,X)|0,n=(n=n+Math.imul(v,Y)|0)+Math.imul(_,X)|0,a=a+Math.imul(_,Y)|0,i=i+Math.imul(g,J)|0,n=(n=n+Math.imul(g,ee)|0)+Math.imul(m,J)|0,a=a+Math.imul(m,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(y,re)|0,a=a+Math.imul(y,ie)|0;var ke=(u+(i=i+Math.imul(d,ae)|0)|0)+((8191&(n=(n=n+Math.imul(d,se)|0)+Math.imul(f,ae)|0))<<13)|0;u=((a=a+Math.imul(f,se)|0)+(n>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(U,L),n=(n=Math.imul(U,N))+Math.imul(R,L)|0,a=Math.imul(R,N),i=i+Math.imul(K,H)|0,n=(n=n+Math.imul(K,W)|0)+Math.imul(C,H)|0,a=a+Math.imul(C,W)|0,i=i+Math.imul(P,V)|0,n=(n=n+Math.imul(P,$)|0)+Math.imul(x,V)|0,a=a+Math.imul(x,$)|0,i=i+Math.imul(A,X)|0,n=(n=n+Math.imul(A,Y)|0)+Math.imul(S,X)|0,a=a+Math.imul(S,Y)|0,i=i+Math.imul(v,J)|0,n=(n=n+Math.imul(v,ee)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,ee)|0,i=i+Math.imul(g,re)|0,n=(n=n+Math.imul(g,ie)|0)+Math.imul(m,re)|0,a=a+Math.imul(m,ie)|0,i=i+Math.imul(p,ae)|0,n=(n=n+Math.imul(p,se)|0)+Math.imul(y,ae)|0,a=a+Math.imul(y,se)|0;var Ae=(u+(i=i+Math.imul(d,ce)|0)|0)+((8191&(n=(n=n+Math.imul(d,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((a=a+Math.imul(f,ue)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(B,L),n=(n=Math.imul(B,N))+Math.imul(T,L)|0,a=Math.imul(T,N),i=i+Math.imul(U,H)|0,n=(n=n+Math.imul(U,W)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,W)|0,i=i+Math.imul(K,V)|0,n=(n=n+Math.imul(K,$)|0)+Math.imul(C,V)|0,a=a+Math.imul(C,$)|0,i=i+Math.imul(P,X)|0,n=(n=n+Math.imul(P,Y)|0)+Math.imul(x,X)|0,a=a+Math.imul(x,Y)|0,i=i+Math.imul(A,J)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,ee)|0,i=i+Math.imul(v,re)|0,n=(n=n+Math.imul(v,ie)|0)+Math.imul(_,re)|0,a=a+Math.imul(_,ie)|0,i=i+Math.imul(g,ae)|0,n=(n=n+Math.imul(g,se)|0)+Math.imul(m,ae)|0,a=a+Math.imul(m,se)|0,i=i+Math.imul(p,ce)|0,n=(n=n+Math.imul(p,ue)|0)+Math.imul(y,ce)|0,a=a+Math.imul(y,ue)|0;var Se=(u+(i=i+Math.imul(d,de)|0)|0)+((8191&(n=(n=n+Math.imul(d,fe)|0)+Math.imul(f,de)|0))<<13)|0;u=((a=a+Math.imul(f,fe)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(q,L),n=(n=Math.imul(q,N))+Math.imul(F,L)|0,a=Math.imul(F,N),i=i+Math.imul(B,H)|0,n=(n=n+Math.imul(B,W)|0)+Math.imul(T,H)|0,a=a+Math.imul(T,W)|0,i=i+Math.imul(U,V)|0,n=(n=n+Math.imul(U,$)|0)+Math.imul(R,V)|0,a=a+Math.imul(R,$)|0,i=i+Math.imul(K,X)|0,n=(n=n+Math.imul(K,Y)|0)+Math.imul(C,X)|0,a=a+Math.imul(C,Y)|0,i=i+Math.imul(P,J)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(x,J)|0,a=a+Math.imul(x,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(S,re)|0,a=a+Math.imul(S,ie)|0,i=i+Math.imul(v,ae)|0,n=(n=n+Math.imul(v,se)|0)+Math.imul(_,ae)|0,a=a+Math.imul(_,se)|0,i=i+Math.imul(g,ce)|0,n=(n=n+Math.imul(g,ue)|0)+Math.imul(m,ce)|0,a=a+Math.imul(m,ue)|0,i=i+Math.imul(p,de)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(y,de)|0,a=a+Math.imul(y,fe)|0;var Ee=(u+(i=i+Math.imul(d,pe)|0)|0)+((8191&(n=(n=n+Math.imul(d,ye)|0)+Math.imul(f,pe)|0))<<13)|0;u=((a=a+Math.imul(f,ye)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(q,H),n=(n=Math.imul(q,W))+Math.imul(F,H)|0,a=Math.imul(F,W),i=i+Math.imul(B,V)|0,n=(n=n+Math.imul(B,$)|0)+Math.imul(T,V)|0,a=a+Math.imul(T,$)|0,i=i+Math.imul(U,X)|0,n=(n=n+Math.imul(U,Y)|0)+Math.imul(R,X)|0,a=a+Math.imul(R,Y)|0,i=i+Math.imul(K,J)|0,n=(n=n+Math.imul(K,ee)|0)+Math.imul(C,J)|0,a=a+Math.imul(C,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(x,re)|0,a=a+Math.imul(x,ie)|0,i=i+Math.imul(A,ae)|0,n=(n=n+Math.imul(A,se)|0)+Math.imul(S,ae)|0,a=a+Math.imul(S,se)|0,i=i+Math.imul(v,ce)|0,n=(n=n+Math.imul(v,ue)|0)+Math.imul(_,ce)|0,a=a+Math.imul(_,ue)|0,i=i+Math.imul(g,de)|0,n=(n=n+Math.imul(g,fe)|0)+Math.imul(m,de)|0,a=a+Math.imul(m,fe)|0;var Pe=(u+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ye)|0)+Math.imul(y,pe)|0))<<13)|0;u=((a=a+Math.imul(y,ye)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,V),n=(n=Math.imul(q,$))+Math.imul(F,V)|0,a=Math.imul(F,$),i=i+Math.imul(B,X)|0,n=(n=n+Math.imul(B,Y)|0)+Math.imul(T,X)|0,a=a+Math.imul(T,Y)|0,i=i+Math.imul(U,J)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,ee)|0,i=i+Math.imul(K,re)|0,n=(n=n+Math.imul(K,ie)|0)+Math.imul(C,re)|0,a=a+Math.imul(C,ie)|0,i=i+Math.imul(P,ae)|0,n=(n=n+Math.imul(P,se)|0)+Math.imul(x,ae)|0,a=a+Math.imul(x,se)|0,i=i+Math.imul(A,ce)|0,n=(n=n+Math.imul(A,ue)|0)+Math.imul(S,ce)|0,a=a+Math.imul(S,ue)|0,i=i+Math.imul(v,de)|0,n=(n=n+Math.imul(v,fe)|0)+Math.imul(_,de)|0,a=a+Math.imul(_,fe)|0;var xe=(u+(i=i+Math.imul(g,pe)|0)|0)+((8191&(n=(n=n+Math.imul(g,ye)|0)+Math.imul(m,pe)|0))<<13)|0;u=((a=a+Math.imul(m,ye)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,X),n=(n=Math.imul(q,Y))+Math.imul(F,X)|0,a=Math.imul(F,Y),i=i+Math.imul(B,J)|0,n=(n=n+Math.imul(B,ee)|0)+Math.imul(T,J)|0,a=a+Math.imul(T,ee)|0,i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(R,re)|0,a=a+Math.imul(R,ie)|0,i=i+Math.imul(K,ae)|0,n=(n=n+Math.imul(K,se)|0)+Math.imul(C,ae)|0,a=a+Math.imul(C,se)|0,i=i+Math.imul(P,ce)|0,n=(n=n+Math.imul(P,ue)|0)+Math.imul(x,ce)|0,a=a+Math.imul(x,ue)|0,i=i+Math.imul(A,de)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(S,de)|0,a=a+Math.imul(S,fe)|0;var Me=(u+(i=i+Math.imul(v,pe)|0)|0)+((8191&(n=(n=n+Math.imul(v,ye)|0)+Math.imul(_,pe)|0))<<13)|0;u=((a=a+Math.imul(_,ye)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,J),n=(n=Math.imul(q,ee))+Math.imul(F,J)|0,a=Math.imul(F,ee),i=i+Math.imul(B,re)|0,n=(n=n+Math.imul(B,ie)|0)+Math.imul(T,re)|0,a=a+Math.imul(T,ie)|0,i=i+Math.imul(U,ae)|0,n=(n=n+Math.imul(U,se)|0)+Math.imul(R,ae)|0,a=a+Math.imul(R,se)|0,i=i+Math.imul(K,ce)|0,n=(n=n+Math.imul(K,ue)|0)+Math.imul(C,ce)|0,a=a+Math.imul(C,ue)|0,i=i+Math.imul(P,de)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(x,de)|0,a=a+Math.imul(x,fe)|0;var Ke=(u+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ye)|0)+Math.imul(S,pe)|0))<<13)|0;u=((a=a+Math.imul(S,ye)|0)+(n>>>13)|0)+(Ke>>>26)|0,Ke&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(F,re)|0,a=Math.imul(F,ie),i=i+Math.imul(B,ae)|0,n=(n=n+Math.imul(B,se)|0)+Math.imul(T,ae)|0,a=a+Math.imul(T,se)|0,i=i+Math.imul(U,ce)|0,n=(n=n+Math.imul(U,ue)|0)+Math.imul(R,ce)|0,a=a+Math.imul(R,ue)|0,i=i+Math.imul(K,de)|0,n=(n=n+Math.imul(K,fe)|0)+Math.imul(C,de)|0,a=a+Math.imul(C,fe)|0;var Ce=(u+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ye)|0)+Math.imul(x,pe)|0))<<13)|0;u=((a=a+Math.imul(x,ye)|0)+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(q,ae),n=(n=Math.imul(q,se))+Math.imul(F,ae)|0,a=Math.imul(F,se),i=i+Math.imul(B,ce)|0,n=(n=n+Math.imul(B,ue)|0)+Math.imul(T,ce)|0,a=a+Math.imul(T,ue)|0,i=i+Math.imul(U,de)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(R,de)|0,a=a+Math.imul(R,fe)|0;var De=(u+(i=i+Math.imul(K,pe)|0)|0)+((8191&(n=(n=n+Math.imul(K,ye)|0)+Math.imul(C,pe)|0))<<13)|0;u=((a=a+Math.imul(C,ye)|0)+(n>>>13)|0)+(De>>>26)|0,De&=67108863,i=Math.imul(q,ce),n=(n=Math.imul(q,ue))+Math.imul(F,ce)|0,a=Math.imul(F,ue),i=i+Math.imul(B,de)|0,n=(n=n+Math.imul(B,fe)|0)+Math.imul(T,de)|0,a=a+Math.imul(T,fe)|0;var Ue=(u+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ye)|0)+Math.imul(R,pe)|0))<<13)|0;u=((a=a+Math.imul(R,ye)|0)+(n>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,i=Math.imul(q,de),n=(n=Math.imul(q,fe))+Math.imul(F,de)|0,a=Math.imul(F,fe);var Re=(u+(i=i+Math.imul(B,pe)|0)|0)+((8191&(n=(n=n+Math.imul(B,ye)|0)+Math.imul(T,pe)|0))<<13)|0;u=((a=a+Math.imul(T,ye)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Ie=(u+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ye))+Math.imul(F,pe)|0))<<13)|0;return u=((a=Math.imul(F,ye))+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,c[0]=be,c[1]=ge,c[2]=me,c[3]=we,c[4]=ve,c[5]=_e,c[6]=ke,c[7]=Ae,c[8]=Se,c[9]=Ee,c[10]=Pe,c[11]=xe,c[12]=Me,c[13]=Ke,c[14]=Ce,c[15]=De,c[16]=Ue,c[17]=Re,c[18]=Ie,0!==u&&(c[19]=u,r.length++),r};function p(e,t,r){return(new y).mulp(e,t,r)}function y(e,t){this.x=e,this.y=t}Math.imul||(l=f),n.prototype.mulTo=function(e,t){var r,i=this.length+e.length;return r=10===this.length&&10===e.length?l(this,e,t):i<63?f(this,e,t):i<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,a=0;a>>26)|0)>>>26,s&=67108863}r.words[a]=o,i=s,s=n}return 0!==i?r.words[a]=i:r.length--,r.strip()}(this,e,t):p(this,e,t),r},y.prototype.makeRBT=function(e){for(var t=Array(e),r=n.prototype._countBits(e)-1,i=0;i>=1;return i},y.prototype.permute=function(e,t,r,i,n,a){for(var s=0;s>>=1)n++;return 1<>>=13,i[2*s+1]=8191&a,a>>>=13;for(s=2*t;s>=26,t+=n/67108864|0,t+=a>>>26,this.words[i]=67108863&a}return 0!==t&&(this.words[i]=t,this.length++),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r>>n}return t}(e);if(0===t.length)return new n(1);for(var r=this,i=0;i=0);var t,i=e%26,n=(e-i)/26,a=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var a=e%26,s=Math.min((e-a)/26,this.length),o=67108863^67108863>>>a<s)for(this.length-=s,u=0;u=0&&(0!==h||u>=n);u--){var d=0|this.words[u];this.words[u]=h<<26-a|d>>>a,h=d&o}return c&&0!==h&&(c.words[c.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,i){return r(0===this.negative),this.iushrn(e,t,i)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,n=1<=0);var t=e%26,i=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[n+i]=67108863&a}for(;n>26,this.words[n+i]=67108863&a;if(0===o)return this.strip();for(r(-1===o),o=0,n=0;n>26,this.words[n]=67108863&a;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),a=e,s=0|a.words[a.length-1];0!==(r=26-this._countBits(s))&&(a=a.ushln(r),i.iushln(r),s=0|a.words[a.length-1]);var o,c=i.length-a.length;if("mod"!==t){(o=new n(null)).length=c+1,o.words=Array(o.length);for(var u=0;u=0;d--){var f=67108864*(0|i.words[a.length+d])+(0|i.words[a.length+d-1]);for(f=Math.min(f/s|0,67108863),i._ishlnsubmul(a,f,d);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(a,1,d),i.isZero()||(i.negative^=1);o&&(o.words[d]=f)}return o&&o.strip(),i.strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:o||null,mod:i}},n.prototype.divmod=function(e,t,i){return r(!e.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(a=o.div.neg()),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:a,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(a=o.div.neg()),{div:a,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t);var a,s,o},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),a=r.cmp(i);return a<0||1===n&&0===a?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},n.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,i=0,n=this.length-1;n>=0;n--)i=(t*i+(0|this.words[n]))%e;return i},n.prototype.idivn=function(e){r(e<=67108863);for(var t=0,i=this.length-1;i>=0;i--){var n=(0|this.words[i])+67108864*t;this.words[i]=n/e|0,t=n%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new n(1),s=new n(0),o=new n(0),c=new n(1),u=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++u;for(var h=i.clone(),d=t.clone();!t.isZero();){for(var f=0,l=1;0==(t.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(a.isOdd()||s.isOdd())&&(a.iadd(h),s.isub(d)),a.iushrn(1),s.iushrn(1);for(var p=0,y=1;0==(i.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(h),c.isub(d)),o.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),a.isub(o),s.isub(c)):(i.isub(t),o.isub(a),c.isub(s))}return{a:o,b:c,gcd:i.iushln(u)}},n.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a,s=new n(1),o=new n(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var u=0,h=1;0==(t.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,f=1;0==(i.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(i.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(o)):(i.isub(t),o.isub(s))}return(a=0===t.cmpn(1)?s:o).cmpn(0)<0&&a.iadd(e),a},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var a=t;t=r,r=a}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,i=(e-t)/26,n=1<>>26,o&=67108863,this.words[s]=o}return 0!==a&&(this.words[s]=a,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this.strip(),this.length>1)t=1;else{i&&(e=-e),r(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return-1===this.cmpn(e)},n.prototype.lt=function(e){return-1===this.cmp(e)},n.prototype.lten=function(e){return this.cmpn(e)<=0},n.prototype.lte=function(e){return this.cmp(e)<=0},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new k(e)},n.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function g(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){g.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){g.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function v(){g.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){g.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function k(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function A(e){k.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}g.prototype._tmp=function(){var e=new n(null);return e.words=Array(Math.ceil(this.n/13)),e},g.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):r.strip(),r},g.prototype.split=function(e,t){e.iushrn(this.n,0,t)},g.prototype.imulK=function(e){return e.imul(this.k)},i(m,g),m.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,a=s}a>>>=22,e.words[n-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},m.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new m;else if("p224"===e)t=new w;else if("p192"===e)t=new v;else{if("p25519"!==e)throw Error("Unknown prime "+e);t=new _}return b[e]=t,t},k.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},k.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},k.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},k.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},k.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},k.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},k.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},k.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},k.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},k.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},k.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},k.prototype.isqr=function(e){return this.imul(e,e.clone())},k.prototype.sqr=function(e){return this.mul(e,e)},k.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var i=this.m.add(new n(1)).iushrn(2);return this.pow(e,i)}for(var a=this.m.subn(1),s=0;!a.isZero()&&0===a.andln(1);)s++,a.iushrn(1);r(!a.isZero());var o=new n(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),h=this.m.bitLength();for(h=new n(2*h*h).toRed(this);0!==this.pow(h,u).cmp(c);)h.redIAdd(c);for(var d=this.pow(h,a),f=this.pow(e,a.addn(1).iushrn(1)),l=this.pow(e,a),p=s;0!==l.cmp(o);){for(var y=l,b=0;0!==y.cmp(o);b++)y=y.redSqr();r(b=0;i--){for(var u=t.words[i],h=c-1;h>=0;h--){var d=u>>h&1;a!==r[0]&&(a=this.sqr(a)),0!==d||0!==s?(s<<=1,s|=d,(4===++o||0===i&&0===h)&&(a=this.mul(a,r[s]),o=0,s=0)):o=0}c=26}return a},k.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},k.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new A(e)},i(A,k),A.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},A.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},A.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.iadd(this.m)),a._forceRed(this)},A.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),s=a;return a.cmp(this.m)>=0?s=a.isub(this.m):a.cmpn(0)<0&&(s=a.iadd(this.m)),s._forceRed(this)},A.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,gt)})),Jp=/*#__PURE__*/Object.freeze({__proto__:null,default:Qp,__moduleExports:Qp});class ey{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");this.value=new Qp(e)}clone(){const e=new ey(null);return this.value.copy(e.value),e}iinc(){return this.value.iadd(new Qp(1)),this}inc(){return this.clone().iinc()}idec(){return this.value.isub(new Qp(1)),this}dec(){return this.clone().idec()}iadd(e){return this.value.iadd(e.value),this}add(e){return this.clone().iadd(e)}isub(e){return this.value.isub(e.value),this}sub(e){return this.clone().isub(e)}imul(e){return this.value.imul(e.value),this}mul(e){return this.clone().imul(e)}imod(e){return this.value=this.value.umod(e.value),this}mod(e){return this.clone().imod(e)}modExp(e,t){const r=t.isEven()?Qp.red(t.value):Qp.mont(t.value),i=this.clone();return i.value=i.value.toRed(r).redPow(e.value).fromRed(),i}modInv(e){if(!this.gcd(e).isOne())throw Error("Inverse does not exist");return new ey(this.value.invm(e.value))}gcd(e){return new ey(this.value.gcd(e.value))}ileftShift(e){return this.value.ishln(e.value.toNumber()),this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value.ishrn(e.value.toNumber()),this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value.eq(e.value)}lt(e){return this.value.lt(e.value)}lte(e){return this.value.lte(e.value)}gt(e){return this.value.gt(e.value)}gte(e){return this.value.gte(e.value)}isZero(){return this.value.isZero()}isOne(){return this.value.eq(new Qp(1))}isNegative(){return this.value.isNeg()}isEven(){return this.value.isEven()}abs(){const e=this.clone();return e.value=e.value.abs(),e}toString(){return this.value.toString()}toNumber(){return this.value.toNumber()}getBit(e){return this.value.testn(e)?1:0}bitLength(){return this.value.bitLength()}byteLength(){return this.value.byteLength()}toUint8Array(e="be",t){return this.value.toArrayLike(Uint8Array,e,t)}}var ty,ry=/*#__PURE__*/Object.freeze({__proto__:null,default:ey}),iy=mt((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,s=255&n;a?r.push(a,s):r.push(s)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),ny=mt((function(e,t){var r=t;r.assert=yt,r.toArray=iy.toArray,r.zero2=iy.zero2,r.toHex=iy.toHex,r.encode=iy.encode,r.getNAF=function(e,t){for(var r=[],i=1<=0;){var a;if(n.isOdd()){var s=n.andln(i-1);a=s>(i>>1)-1?(i>>1)-s:s,n.isubn(a)}else a=0;r.push(a);for(var o=0!==n.cmpn(0)&&0===n.andln(i-1)?t+1:1,c=1;c0||t.cmpn(-n)>0;){var a,s,o,c=e.andln(3)+i&3,u=t.andln(3)+n&3;if(3===c&&(c=-1),3===u&&(u=-1),0==(1&c))a=0;else a=3!==(o=e.andln(7)+i&7)&&5!==o||2!==u?c:-c;if(r[0].push(a),0==(1&u))s=0;else s=3!==(o=t.andln(7)+n&7)&&5!==o||2!==c?u:-u;r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new Qp(e,"hex","le")}})),ay=function(e){return ty||(ty=new sy(null)),ty.generate(e)};function sy(e){this.rand=e}var oy=sy;if(sy.prototype.generate=function(e){return this._rand(e)},sy.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ly=fy;function py(e,t){this.curve=e,this.type=t,this.precomputed=null}fy.prototype.point=function(){throw Error("Not implemented")},fy.prototype.validate=function(){throw Error("Not implemented")},fy.prototype._fixedNafMul=function(e,t){dy(e.precomputed);var r=e._getDoubles(),i=uy(t,1),n=(1<=s;t--)o=(o<<1)+i[t];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),h=n;h>0;h--){for(s=0;s=0;o--){for(t=0;o>=0&&0===a[o];o--)t++;if(o>=0&&t++,s=s.dblp(t),o<0)break;var c=a[o];dy(0!==c),s="affine"===e.type?c>0?s.mixedAdd(n[c-1>>1]):s.mixedAdd(n[-c-1>>1].neg()):c>0?s.add(n[c-1>>1]):s.add(n[-c-1>>1].neg())}return"affine"===e.type?s.toP():s},fy.prototype._wnafMulAdd=function(e,t,r,i,n){for(var a=this._wnafT1,s=this._wnafT2,o=this._wnafT3,c=0,u=0;u=1;u-=2){var d=u-1,f=u;if(1===a[d]&&1===a[f]){var l=[t[d],null,null,t[f]];0===t[d].y.cmp(t[f].y)?(l[1]=t[d].add(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg())):0===t[d].y.cmp(t[f].y.redNeg())?(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].add(t[f].neg())):(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg()));var p=[-3,-1,-5,-7,0,7,5,1,3],y=hy(r[d],r[f]);c=Math.max(y[0].length,c),o[d]=Array(c),o[f]=Array(c);for(var b=0;b=0;u--){for(var _=0;u>=0;){var k=!0;for(b=0;b=0&&_++,w=w.dblp(_),u<0)break;for(b=0;b0?A=s[b][S-1>>1]:S<0&&(A=s[b][-S-1>>1].neg()),w="affine"===A.type?w.mixedAdd(A):w.add(A))}}for(u=0;u=Math.ceil((e.bitLength()+1)/t.step)},py.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(a=t,s=r),i.negative&&(i=i.neg(),n=n.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a,b:s}]},by.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),u=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(u).neg()}},by.prototype.pointFromX=function(e,t){(e=new Qp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},by.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},by.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,a=0;a":""},my.prototype.isInfinity=function(){return this.inf},my.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},my.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),a=n.redSqr().redISub(this.x.redAdd(this.x)),s=n.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,s)},my.prototype.getX=function(){return this.x.fromRed()},my.prototype.getY=function(){return this.y.fromRed()},my.prototype.mul=function(e){return e=new Qp(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},my.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},my.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},my.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},my.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},my.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},_t(wy,ly.BasePoint),by.prototype.jpoint=function(e,t,r){return new wy(this,e,t,r)},wy.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},wy.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},wy.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=o.redSqr(),h=u.redMul(o),d=i.redMul(u),f=c.redSqr().redIAdd(h).redISub(d).redISub(d),l=c.redMul(d.redISub(f)).redISub(a.redMul(h)),p=this.z.redMul(e.z).redMul(o);return this.curve.jpoint(f,l,p)},wy.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))return 0!==o.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),u=c.redMul(s),h=r.redMul(c),d=o.redSqr().redIAdd(u).redISub(h).redISub(h),f=o.redMul(h.redISub(d)).redISub(n.redMul(u)),l=this.z.redMul(s);return this.curve.jpoint(d,f,l)},wy.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},wy.prototype.inspect=function(){return this.isInfinity()?"":""},wy.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},_t(vy,ly);var _y=vy;function ky(e,t,r){ly.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new Qp(t,16),this.z=new Qp(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}vy.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),i=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===i.redSqrt().redSqr().cmp(i)},_t(ky,ly.BasePoint),vy.prototype.decodePoint=function(e,t){if(33===(e=ny.toArray(e,t)).length&&64===e[0]&&(e=e.slice(1,33).reverse()),32!==e.length)throw Error("Unknown point compression format");return this.point(e,1)},vy.prototype.point=function(e,t){return new ky(this,e,t)},vy.prototype.pointFromJSON=function(e){return ky.fromJSON(this,e)},ky.prototype.precompute=function(){},ky.prototype._encode=function(e){var t=this.curve.p.byteLength();return e?[64].concat(this.getX().toArray("le",t)):this.getX().toArray("be",t)},ky.fromJSON=function(e,t){return new ky(e,t[0],t[1]||e.one)},ky.prototype.inspect=function(){return this.isInfinity()?"":""},ky.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ky.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),i=e.redMul(t),n=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(i,n)},ky.prototype.add=function(){throw Error("Not supported on Montgomery curve")},ky.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),i=this.x.redSub(this.z),n=e.x.redAdd(e.z),a=e.x.redSub(e.z).redMul(r),s=n.redMul(i),o=t.z.redMul(a.redAdd(s).redSqr()),c=t.x.redMul(a.redISub(s).redSqr());return this.curve.point(o,c)},ky.prototype.mul=function(e){for(var t=(e=new Qp(e,16)).clone(),r=this,i=this.curve.point(null,null),n=[];0!==t.cmpn(0);t.iushrn(1))n.push(t.andln(1));for(var a=n.length-1;a>=0;a--)0===n[a]?(r=r.diffAdd(i,this),i=i.dbl()):(i=r.diffAdd(i,this),r=r.dbl());return i},ky.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},ky.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},ky.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},ky.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ky.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Ay=ny.assert;function Sy(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,ly.call(this,"edwards",e),this.a=new Qp(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new Qp(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new Qp(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ay(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}_t(Sy,ly);var Ey=Sy;function Py(e,t,r,i,n){ly.BasePoint.call(this,e,"projective"),null===t&&null===r&&null===i?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new Qp(t,16),this.y=new Qp(r,16),this.z=i?new Qp(i,16):this.curve.one,this.t=n&&new Qp(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}Sy.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},Sy.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},Sy.prototype.jpoint=function(e,t,r,i){return this.point(e,t,r,i)},Sy.prototype.pointFromX=function(e,t){(e=new Qp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=this.c2.redSub(this.a.redMul(r)),n=this.one.redSub(this.c2.redMul(this.d).redMul(r)),a=i.redMul(n.redInvm()),s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");var o=s.fromRed().isOdd();return(t&&!o||!t&&o)&&(s=s.redNeg()),this.point(e,s)},Sy.prototype.pointFromY=function(e,t){(e=new Qp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=r.redSub(this.c2),n=r.redMul(this.d).redMul(this.c2).redSub(this.a),a=i.redMul(n.redInvm());if(0===a.cmp(this.zero)){if(t)throw Error("invalid point");return this.point(this.zero,e)}var s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");return s.fromRed().isOdd()!==t&&(s=s.redNeg()),this.point(s,e)},Sy.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),r=e.y.redSqr(),i=t.redMul(this.a).redAdd(r),n=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(r)));return 0===i.cmp(n)},_t(Py,ly.BasePoint),Sy.prototype.pointFromJSON=function(e){return Py.fromJSON(this,e)},Sy.prototype.point=function(e,t,r,i){return new Py(this,e,t,r,i)},Py.fromJSON=function(e,t){return new Py(e,t[0],t[1],t[2])},Py.prototype.inspect=function(){return this.isInfinity()?"":""},Py.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Py.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var i=this.curve._mulA(e),n=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=i.redAdd(t),s=a.redSub(r),o=i.redSub(t),c=n.redMul(s),u=a.redMul(o),h=n.redMul(o),d=s.redMul(a);return this.curve.point(c,u,d,h)},Py.prototype._projDbl=function(){var e,t,r,i=this.x.redAdd(this.y).redSqr(),n=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var s=(u=this.curve._mulA(n)).redAdd(a);if(this.zOne)e=i.redSub(n).redSub(a).redMul(s.redSub(this.curve.two)),t=s.redMul(u.redSub(a)),r=s.redSqr().redSub(s).redSub(s);else{var o=this.z.redSqr(),c=s.redSub(o).redISub(o);e=i.redSub(n).redISub(a).redMul(c),t=s.redMul(u.redSub(a)),r=s.redMul(c)}}else{var u=n.redAdd(a);o=this.curve._mulC(this.z).redSqr(),c=u.redSub(o).redSub(o);e=this.curve._mulC(i.redISub(u)).redMul(c),t=this.curve._mulC(u).redMul(n.redISub(a)),r=u.redMul(c)}return this.curve.point(e,t,r)},Py.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Py.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),i=this.t.redMul(this.curve.dd).redMul(e.t),n=this.z.redMul(e.z.redAdd(e.z)),a=r.redSub(t),s=n.redSub(i),o=n.redAdd(i),c=r.redAdd(t),u=a.redMul(s),h=o.redMul(c),d=a.redMul(c),f=s.redMul(o);return this.curve.point(u,h,f,d)},Py.prototype._projAdd=function(e){var t,r,i=this.z.redMul(e.z),n=i.redSqr(),a=this.x.redMul(e.x),s=this.y.redMul(e.y),o=this.curve.d.redMul(a).redMul(s),c=n.redSub(o),u=n.redAdd(o),h=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(a).redISub(s),d=i.redMul(c).redMul(h);return this.curve.twisted?(t=i.redMul(u).redMul(s.redSub(this.curve._mulA(a))),r=c.redMul(u)):(t=i.redMul(u).redMul(s.redSub(a)),r=this.curve._mulC(c).redMul(u)),this.curve.point(d,t,r)},Py.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},Py.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},Py.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},Py.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},Py.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},Py.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Py.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Py.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Py.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},Py.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),i=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(i),0===this.x.cmp(t))return!0}},Py.prototype.toP=Py.prototype.normalize,Py.prototype.mixedAdd=Py.prototype.add;var xy=mt((function(e,t){var r=t;r.base=ly,r.short=gy,r.mont=_y,r.edwards=Ey})),My=Ct.rotl32,Ky=Ct.sum32,Cy=Ct.sum32_5,Dy=Ft.ft_1,Uy=Rt.BlockHash,Ry=[1518500249,1859775393,2400959708,3395469782];function Iy(){if(!(this instanceof Iy))return new Iy;Uy.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}Ct.inherits(Iy,Uy);var By=Iy;Iy.blockSize=512,Iy.outSize=160,Iy.hmacStrength=80,Iy.padLength=64,Iy.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;ithis.blockSize&&(e=(new this.Hash).update(e).digest()),yt(e.length<=this.blockSize);for(var t=e.length;t=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var jy=Ny;Ny.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},Ny.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=iy.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var Vy=ny.assert;function $y(e,t){if(e instanceof $y)return e;this._importDER(e,t)||(Vy(e.r&&e.s,"Signature without r or s"),this.r=new Qp(e.r,16),this.s=new Qp(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var Zy=$y;function Xy(){this.place=0}function Yy(e,t){var r=e[t.place++];if(!(128&r))return r;for(var i=15&r,n=0,a=0,s=t.place;a>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}$y.prototype._importDER=function(e,t){e=ny.toArray(e,t);var r=new Xy;if(48!==e[r.place++])return!1;if(Yy(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var i=Yy(e,r),n=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])return!1;var a=Yy(e,r);if(e.length!==a+r.place)return!1;var s=e.slice(r.place,a+r.place);return 0===n[0]&&128&n[1]&&(n=n.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new Qp(n),this.s=new Qp(s),this.recoveryParam=null,!0},$y.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=Qy(t),r=Qy(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];Jy(i,t.length),(i=i.concat(t)).push(2),Jy(i,r.length);var n=i.concat(r),a=[48];return Jy(a,n.length),a=a.concat(n),ny.encode(a,e)};var eb=ny.assert;function tb(e){if(!(this instanceof tb))return new tb(e);"string"==typeof e&&(eb(Ly.hasOwnProperty(e),"Unknown curve "+e),e=Ly[e]),e instanceof Ly.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var rb=tb;tb.prototype.keyPair=function(e){return new Gy(this,e)},tb.prototype.keyFromPrivate=function(e,t){return Gy.fromPrivate(this,e,t)},tb.prototype.keyFromPublic=function(e,t){return Gy.fromPublic(this,e,t)},tb.prototype.genKeyPair=function(e){e||(e={});var t=new jy({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||ay(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()});if("mont"===this.curve.type){var r=new Qp(t.generate(32));return this.keyFromPrivate(r)}for(var i=this.n.byteLength(),n=this.n.sub(new Qp(2));;){if(!((r=new Qp(t.generate(i))).cmp(n)>0))return r.iaddn(1),this.keyFromPrivate(r)}},tb.prototype._truncateToN=function(e,t,r){var i=(r=r||8*e.byteLength())-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},tb.prototype.truncateMsg=function(e){var t;return e instanceof Uint8Array?(t=8*e.byteLength,e=this._truncateToN(new Qp(e,16),!1,t)):"string"==typeof e?(t=4*e.length,e=this._truncateToN(new Qp(e,16),!1,t)):e=this._truncateToN(new Qp(e,16)),e},tb.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this.truncateMsg(e);for(var n=this.n.byteLength(),a=t.getPrivate().toArray("be",n),s=e.toArray("be",n),o=new jy({hash:this.hash,entropy:a,nonce:s,pers:i.pers,persEnc:i.persEnc||"utf8"}),c=this.n.sub(new Qp(1)),u=0;;u++){var h=i.k?i.k(u):new Qp(o.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(c)>=0)){var d=this.g.mul(h);if(!d.isInfinity()){var f=d.getX(),l=f.umod(this.n);if(0!==l.cmpn(0)){var p=h.invm(this.n).mul(l.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var y=(d.getY().isOdd()?1:0)|(0!==f.cmp(l)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),y^=1),new Zy({r:l,s:p,recoveryParam:y})}}}}}},tb.prototype.verify=function(e,t,r,i){return r=this.keyFromPublic(r,i),t=new Zy(t,"hex"),this._verify(this.truncateMsg(e),t,r)||this._verify(this._truncateToN(new Qp(e,16)),t,r)},tb.prototype._verify=function(e,t,r){var i=t.r,n=t.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;var a,s=n.invm(this.n),o=s.mul(e).umod(this.n),c=s.mul(i).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(o,r.getPublic(),c)).isInfinity()&&a.eqXToP(i):!(a=this.g.mulAdd(o,r.getPublic(),c)).isInfinity()&&0===a.getX().umod(this.n).cmp(i)},tb.prototype.recoverPubKey=function(e,t,r,i){eb((3&r)===r,"The recovery param is more than two bits"),t=new Zy(t,i);var n=this.n,a=new Qp(e),s=t.r,o=t.s,c=1&r,u=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw Error("Unable to find sencond key candinate");s=u?this.curve.pointFromX(s.add(this.curve.n),c):this.curve.pointFromX(s,c);var h=t.r.invm(n),d=n.sub(a).mul(h).umod(n),f=o.mul(h).umod(n);return this.g.mulAdd(d,s,f)},tb.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new Zy(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(e,t,n)}catch(e){continue}if(a.eq(r))return n}throw Error("Unable to find valid recovery factor")};var ib=ny.assert,nb=ny.parseBytes,ab=ny.cachedProperty;function sb(e,t){if(this.eddsa=e,t.hasOwnProperty("secret")&&(this._secret=nb(t.secret)),e.isPoint(t.pub))this._pub=t.pub;else if(this._pubBytes=nb(t.pub),this._pubBytes&&33===this._pubBytes.length&&64===this._pubBytes[0]&&(this._pubBytes=this._pubBytes.slice(1,33)),this._pubBytes&&32!==this._pubBytes.length)throw Error("Unknown point compression format")}sb.fromPublic=function(e,t){return t instanceof sb?t:new sb(e,{pub:t})},sb.fromSecret=function(e,t){return t instanceof sb?t:new sb(e,{secret:t})},sb.prototype.secret=function(){return this._secret},ab(sb,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ab(sb,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ab(sb,"privBytes",(function(){var e=this.eddsa,t=this.hash(),r=e.encodingLength-1,i=t.slice(0,e.encodingLength);return i[0]&=248,i[r]&=127,i[r]|=64,i})),ab(sb,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ab(sb,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ab(sb,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),sb.prototype.sign=function(e){return ib(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},sb.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},sb.prototype.getSecret=function(e){return ib(this._secret,"KeyPair is public only"),ny.encode(this.secret(),e)},sb.prototype.getPublic=function(e,t){return ny.encode((t?[64]:[]).concat(this.pubBytes()),e)};var ob=sb,cb=ny.assert,ub=ny.cachedProperty,hb=ny.parseBytes;function db(e,t){this.eddsa=e,"object"!=typeof t&&(t=hb(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),cb(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof Qp&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}ub(db,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),ub(db,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),ub(db,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),ub(db,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),db.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},db.prototype.toHex=function(){return ny.encode(this.toBytes(),"hex").toUpperCase()};var fb=db,lb=ny.assert,pb=ny.parseBytes;function yb(e){if(lb("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof yb))return new yb(e);e=Ly[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=Fy.sha512}var bb=yb;yb.prototype.sign=function(e,t){e=pb(e);var r=this.keyFromSecret(t),i=this.hashInt(r.messagePrefix(),e),n=this.g.mul(i),a=this.encodePoint(n),s=this.hashInt(a,r.pubBytes(),e).mul(r.priv()),o=i.add(s).umod(this.curve.n);return this.makeSignature({R:n,S:o,Rencoded:a})},yb.prototype.verify=function(e,t,r){e=pb(e),t=this.makeSignature(t);var i=this.keyFromPublic(r),n=this.hashInt(t.Rencoded(),i.pubBytes(),e),a=this.g.mul(t.S());return t.R().add(i.pub().mul(n)).eq(a)},yb.prototype.hashInt=function(){for(var e=this.hash(),t=0;t0)throw Error("Unknown option: "+r.join(", "));return new Fh(e)},exports.createMessage=async function({text:e,binary:t,filename:r,date:i=new Date,format:n=(void 0!==e?"utf8":"binary"),...a}){let s=void 0!==e?e:t;if(void 0===s)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!de.isString(e)&&!de.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!de.isUint8Array(t)&&!de.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=de.isStream(s);c&&(await O(),s=N(s));const u=new ku(i);void 0!==e?u.setText(s,ue.write(ue.literal,n)):u.setBytes(s,ue.write(ue.literal,n)),void 0!==r&&u.setFilename(r);const h=new Ku;h.push(u);const d=new Bh(h);return d.fromStream=c,d},exports.decrypt=async function({message:e,decryptionKeys:t,passwords:r,sessionKeys:i,verificationKeys:n,expectSigned:a=!1,format:s="utf8",signature:o=null,date:c=new Date,config:u,...h}){if(Hh(u={...we,...u}),Oh(e),n=Wh(n),t=Wh(t),r=Wh(r),i=Wh(i),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(h.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));try{const h=await e.decrypt(t,r,i,c,u);n||(n=[]);const d={};if(d.signatures=o?await h.verifyDetached(o,n,c,u):await h.verify(n,c,u),d.data="binary"===s?h.getLiteralData():h.getText(),d.filename=h.getFilename(),Vh(d,e),a){if(0===n.length)throw Error("Verification keys are required to verify message signatures");if(0===d.signatures.length)throw Error("Message is not signed");d.data=H([d.data,ae((async()=>{await de.anyPromise(d.signatures.map((e=>e.verified)))}))])}return d.data=await Gh(d.data,e.fromStream,s),d}catch(e){throw de.wrapError("Error decrypting message",e)}},exports.decryptKey=async function({privateKey:e,passphrase:t,config:r,...i}){Hh(r={...we,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const a=e.clone(!0),s=de.isArray(t)?t:[t];try{return await Promise.all(a.getKeys().map((e=>de.anyPromise(s.map((t=>e.keyPacket.decrypt(t))))))),await a.validate(r),a}catch(e){throw a.clearPrivateParams(),de.wrapError("Error decrypting private key",e)}},exports.decryptSessionKeys=async function({message:e,decryptionKeys:t,passwords:r,date:i=new Date,config:n,...a}){if(Hh(n={...we,...n}),Oh(e),t=Wh(t),r=Wh(r),a.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const s=Object.keys(a);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await e.decryptSessionKeys(t,r,i,n)}catch(e){throw de.wrapError("Error decrypting session keys",e)}},exports.encrypt=async function({message:e,encryptionKeys:t,signingKeys:r,passwords:i,sessionKey:n,format:a="armored",signature:s=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:u=[],date:h=new Date,signingUserIDs:d=[],encryptionUserIDs:f=[],signatureNotations:l=[],config:p,...y}){if(Hh(p={...we,...p}),Oh(e),Nh(a),t=Wh(t),r=Wh(r),i=Wh(i),c=Wh(c),u=Wh(u),d=Wh(d),f=Wh(f),l=Wh(l),y.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(y.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(y.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==y.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const b=Object.keys(y);if(b.length>0)throw Error("Unknown option: "+b.join(", "));r||(r=[]);const g=e.fromStream;try{if((r.length||s)&&(e=await e.sign(r,s,c,h,d,l,p)),e=e.compress(await dh("compression",t,h,f,p),p),e=await e.encrypt(t,i,n,o,u,h,f,p),"object"===a)return e;const y="armored"===a;return Gh(y?e.armor(p):e.write(),g,y?"utf8":"binary")}catch(e){throw de.wrapError("Error encrypting message",e)}},exports.encryptKey=async function({privateKey:e,passphrase:t,config:r,...i}){Hh(r={...we,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const a=e.clone(!0),s=a.getKeys(),o=de.isArray(t)?t:Array(s.length).fill(t);if(o.length!==s.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(s.map((async(e,t)=>{const{keyPacket:i}=e;await i.encrypt(o[t],r),i.clearPrivateParams()}))),a}catch(e){throw a.clearPrivateParams(),de.wrapError("Error encrypting private key",e)}},exports.encryptSessionKey=async function({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:i,passwords:n,format:a="armored",wildcard:s=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:u=[],config:h,...d}){if(Hh(h={...we,...h}),function(e,t){if(!de.isUint8Array(e))throw Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(e),function(e,t){if(!de.isString(e))throw Error("Parameter ["+(t||"data")+"] must be of type String")}(t,"algorithm"),Nh(a),i=Wh(i),n=Wh(n),o=Wh(o),u=Wh(u),d.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const f=Object.keys(d);if(f.length>0)throw Error("Unknown option: "+f.join(", "));if(!(i&&0!==i.length||n&&0!==n.length))throw Error("No encryption keys or passwords provided.");try{return $h(await Bh.encryptSessionKey(e,t,r,i,n,s,o,c,u,h),a,h)}catch(e){throw de.wrapError("Error encrypting session key",e)}},exports.enums=ue,exports.generateKey=async function({userIDs:e=[],passphrase:t,type:r="ecc",rsaBits:i=4096,curve:n="curve25519",keyExpirationTime:a=0,date:s=new Date,subkeys:o=[{}],format:c="armored",config:u,...h}){Hh(u={...we,...u}),e=Wh(e);const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));if(0===e.length)throw Error("UserIDs are required for key generation");if("rsa"===r&&ibh(e.subkeys[r],e)));let r=[sh(e,t)];r=r.concat(e.subkeys.map((e=>ah(e,t))));const i=await Promise.all(r),n=await Dh(i[0],i.slice(1),e,t),a=await n.getRevocationCertificate(e.date,t);return n.revocationSignatures=[],{key:n,revocationCertificate:a}}(f,u);return e.getKeys().forEach((({keyPacket:e})=>vh(e,u))),{privateKey:$h(e,c,u),publicKey:$h(e.toPublic(),c,u),revocationCertificate:t}}catch(e){throw de.wrapError("Error generating keypair",e)}},exports.generateSessionKey=async function({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:i,...n}){if(Hh(i={...we,...i}),e=Wh(e),r=Wh(r),n.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await Bh.generateSessionKey(e,t,r,i)}catch(e){throw de.wrapError("Error generating session key",e)}},exports.readCleartextMessage=async function({cleartextMessage:e,config:t,...r}){if(t={...we,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!de.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const i=Object.keys(r);if(i.length>0)throw Error("Unknown option: "+i.join(", "));const n=await xe(e);if(n.type!==ue.armor.signed)throw Error("No cleartext signed message.");const a=await Ku.fromBinary(n.data,qh,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let i=0;i0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await xe(e,r);if(t!==ue.armor.publicKey&&t!==ue.armor.privateKey)throw Error("Armored text not of type key");a=i}else a=t;return Ch(await Ku.fromBinary(a,Kh,r))},exports.readKeys=async function({armoredKeys:e,binaryKeys:t,config:r,...i}){r={...we,...r};let n=e||t;if(!n)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!de.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!de.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:t,data:i}=await xe(e,r);if(t!==ue.armor.publicKey&&t!==ue.armor.privateKey)throw Error("Armored text not of type key");n=i}const s=[],o=await Ku.fromBinary(n,Kh,r),c=o.indexOfTag(ue.packet.publicKey,ue.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)throw Error("Unknown option: "+a.join(", "));const s=de.isStream(n);if(s&&(await O(),n=N(n)),e){const{type:e,data:t}=await xe(n,r);if(e!==ue.armor.message)throw Error("Armored text not of type message");n=t}const o=await Ku.fromBinary(n,Uh,r),c=new Bh(o);return c.fromStream=s,c},exports.readPrivateKey=async function({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...we,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!de.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!de.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await xe(e,r);if(t!==ue.armor.privateKey)throw Error("Armored text not of type private key");a=i}else a=t;const s=await Ku.fromBinary(a,Kh,r);return new Mh(s)},exports.readPrivateKeys=async function({armoredKeys:e,binaryKeys:t,config:r}){r={...we,...r};let i=e||t;if(!i)throw Error("readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!de.isString(e))throw Error("readPrivateKeys: options.armoredKeys must be a string");if(t&&!de.isUint8Array(t))throw Error("readPrivateKeys: options.binaryKeys must be a Uint8Array");if(e){const{type:t,data:n}=await xe(e,r);if(t!==ue.armor.privateKey)throw Error("Armored text not of type private key");i=n}const n=[],a=await Ku.fromBinary(i,Kh,r),s=a.indexOfTag(ue.packet.secretKey);if(0===s.length)throw Error("No secret key packet found");for(let e=0;e0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:e,data:t}=await xe(n,r);if(e!==ue.armor.signature)throw Error("Armored text not of type signature");n=t}const s=await Ku.fromBinary(n,ih,r);return new nh(s)},exports.reformatKey=async function({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:i=0,date:n,format:a="armored",config:s,...o}){Hh(s={...we,...s}),t=Wh(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length)throw Error("UserIDs are required for key reformat");const u={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:i,date:n};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const i=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,n={key:i,bind:r},a=await oh(e.bindingSignatures,i,ue.signature.subkeyBinding,n,null,t).catch((()=>({})));return{sign:a.keyFlags&&a.keyFlags[0]&ue.keyFlags.signData}}))));const n=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==n.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const a=await Dh(i,n,e,t),s=await a.getRevocationCertificate(e.date,t);return a.revocationSignatures=[],{key:a,revocationCertificate:s};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=de.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(u,s);return{privateKey:$h(e,a,s),publicKey:$h(e.toPublic(),a,s),revocationCertificate:t}}catch(e){throw de.wrapError("Error reformatting keypair",e)}},exports.revokeKey=async function({key:e,revocationCertificate:t,reasonForRevocation:r,date:i=new Date,format:n="armored",config:a,...s}){Hh(a={...we,...a});const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const s=t?await e.applyRevocationCertificate(t,i,a):await e.revoke(r,i,a);return s.isPrivate()?{privateKey:$h(s,n,a),publicKey:$h(s.toPublic(),n,a)}:{privateKey:null,publicKey:$h(s,n,a)}}catch(e){throw de.wrapError("Error revoking key",e)}},exports.sign=async function({message:e,signingKeys:t,format:r="armored",detached:i=!1,signingKeyIDs:n=[],date:a=new Date,signingUserIDs:s=[],signatureNotations:o=[],config:c,...u}){if(Hh(c={...we,...c}),Lh(e),Nh(r),t=Wh(t),n=Wh(n),s=Wh(s),o=Wh(o),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==u.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const h=Object.keys(u);if(h.length>0)throw Error("Unknown option: "+h.join(", "));if(e instanceof Fh&&"binary"===r)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Fh&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let u;if(u=i?await e.signDetached(t,void 0,n,a,s,o,c):await e.sign(t,void 0,n,a,s,o,c),"object"===r)return u;const h="armored"===r;return u=h?u.armor(c):u.write(),i&&(u=Y(e.packets.write(),(async(e,t)=>{await Promise.all([V(u,t),ie(e).catch((()=>{}))])}))),Gh(u,e.fromStream,h?"utf8":"binary")}catch(e){throw de.wrapError("Error signing message",e)}},exports.unarmor=xe,exports.verify=async function({message:e,verificationKeys:t,expectSigned:r=!1,format:i="utf8",signature:n=null,date:a=new Date,config:s,...o}){if(Hh(s={...we,...s}),Lh(e),t=Wh(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Fh&&"binary"===i)throw Error("Can't return cleartext message data as binary");if(e instanceof Fh&&n)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=n?await e.verifyDetached(n,t,a,s):await e.verify(t,a,s),o.data="binary"===i?e.getLiteralData():e.getText(),e.fromStream&&!n&&Vh(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=H([o.data,ae((async()=>{await de.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Gh(o.data,e.fromStream,i),o}catch(e){throw de.wrapError("Error verifying signed message",e)}}; -//# sourceMappingURL=openpgp.min.js.map diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.js.map b/app/node_modules/openpgp/dist/node/openpgp.min.js.map deleted file mode 100644 index 26c47365d..000000000 --- a/app/node_modules/openpgp/dist/node/openpgp.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"openpgp.min.js","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/node-conversions.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/biginteger/native.interface.js","../../src/biginteger/index.js","../../src/enums.js","../../src/util.js","../../src/encoding/base64.js","../../src/config/config.js","../../src/encoding/armor.js","../../src/type/keyid.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/utils.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/errors.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ecb.js","../../src/crypto/cipher/aes.js","../../src/crypto/cipher/des.js","../../src/crypto/cipher/cast5.js","../../src/crypto/cipher/twofish.js","../../src/crypto/cipher/blowfish.js","../../src/crypto/cipher/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/hash.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.asm.js","../../node_modules/minimalistic-assert/index.js","../../node_modules/inherits/inherits_browser.js","../../node_modules/inherits/inherits.js","../../node_modules/hash.js/lib/hash/utils.js","../../node_modules/hash.js/lib/hash/common.js","../../node_modules/hash.js/lib/hash/sha/common.js","../../node_modules/hash.js/lib/hash/sha/256.js","../../node_modules/hash.js/lib/hash/sha/224.js","../../node_modules/hash.js/lib/hash/sha/512.js","../../node_modules/hash.js/lib/hash/sha/384.js","../../node_modules/hash.js/lib/hash/ripemd.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cfb.js","../../src/crypto/cipher/getCipher.js","../../src/crypto/mode/cfb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ctr.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cbc.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/gcm.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../node_modules/@openpgp/tweetnacl/nacl-fast-light.js","../../src/crypto/random.js","../../src/crypto/public_key/prime.js","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../src/type/oid.js","../../src/crypto/public_key/elliptic/indutnyKey.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../node_modules/@openpgp/pako/lib/utils/common.js","../../node_modules/@openpgp/pako/lib/zlib/constants.js","../../node_modules/@openpgp/pako/lib/zlib/trees.js","../../node_modules/@openpgp/pako/lib/zlib/adler32.js","../../node_modules/@openpgp/pako/lib/zlib/crc32.js","../../node_modules/@openpgp/pako/lib/zlib/messages.js","../../node_modules/@openpgp/pako/lib/zlib/deflate.js","../../node_modules/@openpgp/pako/lib/utils/strings.js","../../node_modules/@openpgp/pako/lib/zlib/zstream.js","../../node_modules/@openpgp/pako/lib/deflate.js","../../node_modules/@openpgp/pako/lib/zlib/inffast.js","../../node_modules/@openpgp/pako/lib/zlib/inftrees.js","../../node_modules/@openpgp/pako/lib/zlib/inflate.js","../../node_modules/@openpgp/pako/lib/zlib/gzheader.js","../../node_modules/@openpgp/pako/lib/inflate.js","../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js","../../src/packet/literal_data.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/type/s2k.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../node_modules/email-addresses/lib/email-addresses.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js","../../node_modules/@openpgp/web-stream-tools/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs","../../node_modules/@mattiasbuelens/web-streams-adapter/dist/web-streams-adapter.mjs","../../node_modules/bn.js/lib/bn.js","../../src/biginteger/bn.interface.js","../../node_modules/brorand/index.js","../../node_modules/minimalistic-crypto-utils/lib/utils.js","../../node_modules/@openpgp/elliptic/lib/elliptic/utils.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/base.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/short.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/mont.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/edwards.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/index.js","../../node_modules/hash.js/lib/hash/sha/1.js","../../node_modules/hash.js/lib/hash/sha.js","../../node_modules/hash.js/lib/hash/hmac.js","../../node_modules/hash.js/lib/hash.js","../../node_modules/@openpgp/elliptic/lib/elliptic/precomputed/secp256k1.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curves.js","../../node_modules/hmac-drbg/lib/hmac-drbg.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/key.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/signature.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/index.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/key.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/signature.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/index.js","../../node_modules/@openpgp/elliptic/lib/elliptic.js","../../src/packet/marker.js","../../src/packet/trust.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","import * as streams from './streams';\nimport { isArrayStream } from './writer';\n\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n if (streams.ReadableStream && streams.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'ponyfill';\n }\n if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {\n return 'node';\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isNode } from './util';\nimport * as streams from './streams';\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Web / node stream conversion functions\n * From https://github.com/gwicke/node-web-streams\n */\n\nlet nodeToWeb;\nlet webToNode;\n\nif (NodeReadableStream) {\n\n /**\n * Convert a Node Readable Stream to a Web ReadableStream\n * @param {Readable} nodeStream\n * @returns {ReadableStream}\n */\n nodeToWeb = function(nodeStream) {\n let canceled = false;\n return new streams.ReadableStream({\n start(controller) {\n nodeStream.pause();\n nodeStream.on('data', chunk => {\n if (canceled) {\n return;\n }\n if (NodeBuffer.isBuffer(chunk)) {\n chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n controller.enqueue(chunk);\n nodeStream.pause();\n });\n nodeStream.on('end', () => {\n if (canceled) {\n return;\n }\n controller.close();\n });\n nodeStream.on('error', e => controller.error(e));\n },\n pull() {\n nodeStream.resume();\n },\n cancel(reason) {\n canceled = true;\n nodeStream.destroy(reason);\n }\n });\n };\n\n\n class NodeReadable extends NodeReadableStream {\n constructor(webStream, options) {\n super(options);\n this._reader = streams.getReader(webStream);\n }\n\n async _read(size) {\n try {\n while (true) {\n const { done, value } = await this._reader.read();\n if (done) {\n this.push(null);\n break;\n }\n if (!this.push(value)) {\n break;\n }\n }\n } catch (e) {\n this.destroy(e);\n }\n }\n\n async _destroy(error, callback) {\n this._reader.cancel(error).then(callback, callback);\n }\n }\n\n /**\n * Convert a Web ReadableStream to a Node Readable Stream\n * @param {ReadableStream} webStream\n * @param {Object} options\n * @returns {Readable}\n */\n webToNode = function(webStream, options) {\n return new NodeReadable(webStream, options);\n };\n\n}\n\nexport { nodeToWeb, webToNode };\n","import * as streams from './streams';\nimport { isUint8Array } from './util';\n\nconst doneReadingSet = new WeakSet();\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (streams.isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = async () => {};\n return;\n }\n let streamType = streams.isStream(input);\n if (streamType === 'node') {\n input = streams.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array } from './util';\nimport { nodeToWeb, webToNode } from './node-conversions';\nimport { Reader, externalBuffer } from './reader';\nimport { ArrayStream, Writer } from './writer';\n\nlet { ReadableStream, WritableStream, TransformStream } = globalThis;\n\nlet toPonyfillReadable, toNativeReadable;\n\nasync function loadStreamsPonyfill() {\n if (TransformStream) {\n return;\n }\n\n const [ponyfill, adapter] = await Promise.all([\n import('web-streams-polyfill/ponyfill/es6'),\n import('@mattiasbuelens/web-streams-adapter')\n ]);\n\n ({ ReadableStream, WritableStream, TransformStream } = ponyfill);\n\n const { createReadableStreamWrapper } = adapter;\n\n if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {\n toPonyfillReadable = createReadableStreamWrapper(ReadableStream);\n toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);\n }\n}\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType === 'node') {\n return nodeToWeb(input);\n }\n if (streamType === 'web' && toPonyfillReadable) {\n return toPonyfillReadable(input);\n }\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert data to ArrayStream\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {\n return NodeBuffer.concat(list);\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n } else {\n lastBytes = returnValue;\n }\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {\n if (end === Infinity) end = input.length;\n return input.subarray(begin, end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n return input.cancel(reason);\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n\nexport { ReadableStream, WritableStream, TransformStream, ArrayStream, loadStreamsPonyfill, isStream, isArrayStream, isUint8Array, toStream, toPonyfillReadable, toNativeReadable, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };\n","/* eslint-disable new-cap */\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * that wraps the native BigInt library.\n * Operations are not constant time,\n * but we try and limit timing leakage where we can\n * @module biginteger/native\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on null or undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n if (n instanceof Uint8Array) {\n const bytes = n;\n const hex = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n const hexByte = bytes[i].toString(16);\n hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;\n }\n this.value = BigInt('0x0' + hex.join(''));\n } else {\n this.value = BigInt(n);\n }\n }\n\n clone() {\n return new BigInteger(this.value);\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value++;\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value--;\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value += x.value;\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value -= x.value;\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value *= x.value;\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value %= m.value;\n if (this.isNegative()) {\n this.iadd(m);\n }\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation using square and multiply\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n if (n.isZero()) throw Error('Modulo cannot be zero');\n if (n.isOne()) return new BigInteger(0);\n if (e.isNegative()) throw Error('Unsopported negative exponent');\n\n let exp = e.value;\n let x = this.value;\n\n x %= n.value;\n let r = BigInt(1);\n while (exp > BigInt(0)) {\n const lsb = exp & BigInt(1);\n exp >>= BigInt(1); // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n.value;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n.value; // Square\n }\n return new BigInteger(r);\n }\n\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n const { gcd, x } = this._egcd(n);\n if (!gcd.isOne()) {\n throw new Error('Inverse does not exist');\n }\n return x.add(n).mod(n);\n }\n\n /**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)\n * @param {BigInteger} b - Second operand\n * @returns {{ gcd, x, y: BigInteger }}\n */\n _egcd(b) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n let a = this.value;\n b = b.value;\n\n while (b !== BigInt(0)) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: new BigInteger(xPrev),\n y: new BigInteger(yPrev),\n gcd: new BigInteger(a)\n };\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} b - Operand\n * @returns {BigInteger} gcd\n */\n gcd(b) {\n let a = this.value;\n b = b.value;\n while (b !== BigInt(0)) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return new BigInteger(a);\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value <<= x.value;\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value >>= x.value;\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value === x.value;\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value < x.value;\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value <= x.value;\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value > x.value;\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value >= x.value;\n }\n\n isZero() {\n return this.value === BigInt(0);\n }\n\n isOne() {\n return this.value === BigInt(1);\n }\n\n isNegative() {\n return this.value < BigInt(0);\n }\n\n isEven() {\n return !(this.value & BigInt(1));\n }\n\n abs() {\n const res = this.clone();\n if (this.isNegative()) {\n res.value = -res.value;\n }\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n const number = Number(this.value);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n const bit = (this.value >> BigInt(i)) & BigInt(1);\n return (bit === BigInt(0)) ? 0 : 1;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n const zero = new BigInteger(0);\n const one = new BigInteger(1);\n const negOne = new BigInteger(-1);\n\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = this.isNegative() ? negOne : zero;\n let bitlen = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(one).equal(target)) {\n bitlen++;\n }\n return bitlen;\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n const zero = new BigInteger(0);\n const negOne = new BigInteger(-1);\n\n const target = this.isNegative() ? negOne : zero;\n const eight = new BigInteger(8);\n let len = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(eight).equal(target)) {\n len++;\n }\n return len;\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = this.value.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? (length - rawLength) : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n }\n}\n","import BigInteger from './native.interface';\n\nconst detectBigInt = () => typeof BigInt !== 'undefined';\n\nasync function getBigInteger() {\n if (detectBigInt()) {\n return BigInteger;\n } else {\n const { default: BigInteger } = await import('./bn.interface');\n return BigInteger;\n }\n}\n\nexport { getBigInteger };\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'p256': 'p256',\n 'P-256': 'p256',\n 'secp256r1': 'p256',\n 'prime256v1': 'p256',\n '1.2.840.10045.3.1.7': 'p256',\n '2a8648ce3d030107': 'p256',\n '2A8648CE3D030107': 'p256',\n\n /** NIST P-384 Curve */\n 'p384': 'p384',\n 'P-384': 'p384',\n 'secp384r1': 'p384',\n '1.3.132.0.34': 'p384',\n '2b81040022': 'p384',\n '2B81040022': 'p384',\n\n /** NIST P-521 Curve */\n 'p521': 'p521',\n 'P-521': 'p521',\n 'secp521r1': 'p521',\n '1.3.132.0.35': 'p521',\n '2b81040023': 'p521',\n '2B81040023': 'p521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n '1.3.132.0.10': 'secp256k1',\n '2b8104000a': 'secp256k1',\n '2B8104000A': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519',\n 'ED25519': 'ed25519',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519',\n 'Ed25519': 'ed25519',\n '1.3.6.1.4.1.11591.15.1': 'ed25519',\n '2b06010401da470f01': 'ed25519',\n '2B06010401DA470F01': 'ed25519',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519',\n 'X25519': 'curve25519',\n 'cv25519': 'curve25519',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519',\n 'Curve25519': 'curve25519',\n '1.3.6.1.4.1.3029.1.5.1': 'curve25519',\n '2b060104019755010501': 'curve25519',\n '2B060104019755010501': 'curve25519',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',\n '2b2403030208010107': 'brainpoolP256r1',\n '2B2403030208010107': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',\n '2b240303020801010b': 'brainpoolP384r1',\n '2B240303020801010B': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1',\n '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',\n '2b240303020801010d': 'brainpoolP512r1',\n '2B240303020801010D': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility\n /** @deprecated use `eddsaLegacy` instead */\n ed25519Legacy: 22,\n /** @deprecated use `eddsaLegacy` instead */\n eddsa: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n plaintext: 0,\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuer: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { getBigInteger } from './biginteger';\nimport enums from './enums';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n return bytes.subarray(2, 2 + bytelen);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const r = [];\n const e = bytes.length;\n let c = 0;\n let h;\n while (c < e) {\n h = bytes[c++].toString(16);\n while (h.length < 2) {\n h = '0' + h;\n }\n r.push('' + h);\n }\n return r.join('');\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography api, only the current version of the spec.\n * @returns {Object} The SubtleCrypto api or 'undefined'.\n */\n getWebCrypto: function() {\n return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n },\n\n /**\n * Get BigInteger class\n * It wraps the native BigInt type if it's available\n * Otherwise it relies on bn.js\n * @returns {BigInteger}\n * @async\n */\n getBigInteger,\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return require('crypto');\n },\n\n getNodeZlib: function() {\n return require('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (require('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = require('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\\-0-9]+)))$/;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha256,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * @memberof module:config\n * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9\n */\n deflateLevel: 6,\n\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.eax,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use V5 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v5Keys\n */\n v5Keys: false,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:\n * Iteration Count Byte for S2K (String to Key)\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * @memberof module:config\n * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum\n */\n checksumRequired: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * @memberof module:config\n * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored\n */\n revocationsExpire: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n\n /**\n * @memberof module:config\n * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available\n */\n minBytesForWebCrypto: 1000,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * Note: the indutny/elliptic curve library is not designed to be constant time.\n * @memberof module:config\n * @property {Boolean} useIndutnyElliptic\n */\n useIndutnyElliptic: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n } else\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n } else\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n } else\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n } else\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n } else\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n } else\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Splits a message into two parts, the body and the checksum. This is an internal function\n * @param {String} text - OpenPGP armored message part\n * @returns {Object} An object with attribute \"body\" containing the body.\n * and an attribute \"checksum\" containing the checksum.\n * @private\n */\nfunction splitChecksum(text) {\n let body = text;\n let checksum = '';\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n checksum = text.slice(lastEquals + 1).substr(0, 4);\n }\n\n return { body: body, checksum: checksum };\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input, config = defaultConfig) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n let checksum;\n let data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== 2) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === 2) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const split = splitChecksum(parts[0].slice(0, -1));\n checksum = split.checksum;\n await writer.write(split.body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n data = stream.transformPair(data, async (readable, writable) => {\n const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));\n checksumVerified.catch(() => {});\n await stream.pipe(readable, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n const checksumVerifiedString = (await checksumVerified).replace('\\n', '');\n if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {\n throw new Error('Ascii armor integrity check failed');\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n const bodyClone = stream.passiveClone(body);\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push('Hash: ' + hash + '\\n\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n * @private\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","/**\n * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.\n * @author Artem S Vybornov \n * @license MIT\n */\nexport var AES_asm = function () {\n \"use strict\";\n\n /**\n * Galois Field stuff init flag\n */\n var ginit_done = false;\n\n /**\n * Galois Field exponentiation and logarithm tables for 3 (the generator)\n */\n var gexp3, glog3;\n\n /**\n * Init Galois Field tables\n */\n function ginit() {\n gexp3 = [],\n glog3 = [];\n\n var a = 1, c, d;\n for (c = 0; c < 255; c++) {\n gexp3[c] = a;\n\n // Multiply by three\n d = a & 0x80, a <<= 1, a &= 255;\n if (d === 0x80) a ^= 0x1b;\n a ^= gexp3[c];\n\n // Set the log table value\n glog3[gexp3[c]] = c;\n }\n gexp3[255] = gexp3[0];\n glog3[0] = 0;\n\n ginit_done = true;\n }\n\n /**\n * Galois Field multiplication\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\n function gmul(a, b) {\n var c = gexp3[(glog3[a] + glog3[b]) % 255];\n if (a === 0 || b === 0) c = 0;\n return c;\n }\n\n /**\n * Galois Field reciprocal\n * @param {number} a\n * @return {number}\n */\n function ginv(a) {\n var i = gexp3[255 - glog3[a]];\n if (a === 0) i = 0;\n return i;\n }\n\n /**\n * AES stuff init flag\n */\n var aes_init_done = false;\n\n /**\n * Encryption, Decryption, S-Box and KeyTransform tables\n *\n * @type {number[]}\n */\n var aes_sbox;\n\n /**\n * @type {number[]}\n */\n var aes_sinv;\n\n /**\n * @type {number[][]}\n */\n var aes_enc;\n\n /**\n * @type {number[][]}\n */\n var aes_dec;\n\n /**\n * Init AES tables\n */\n function aes_init() {\n if (!ginit_done) ginit();\n\n // Calculates AES S-Box value\n function _s(a) {\n var c, s, x;\n s = x = ginv(a);\n for (c = 0; c < 4; c++) {\n s = ((s << 1) | (s >>> 7)) & 255;\n x ^= s;\n }\n x ^= 99;\n return x;\n }\n\n // Tables\n aes_sbox = [],\n aes_sinv = [],\n aes_enc = [[], [], [], []],\n aes_dec = [[], [], [], []];\n\n for (var i = 0; i < 256; i++) {\n var s = _s(i);\n\n // S-Box and its inverse\n aes_sbox[i] = s;\n aes_sinv[s] = i;\n\n // Ecryption and Decryption tables\n aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);\n aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);\n // Rotate tables\n for (var t = 1; t < 4; t++) {\n aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);\n aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);\n }\n }\n\n aes_init_done = true;\n }\n\n /**\n * Asm.js module constructor.\n *\n *

\n * Heap buffer layout by offset:\n *

\n   * 0x0000   encryption key schedule\n   * 0x0400   decryption key schedule\n   * 0x0800   sbox\n   * 0x0c00   inv sbox\n   * 0x1000   encryption tables\n   * 0x2000   decryption tables\n   * 0x3000   reserved (future GCM multiplication lookup table)\n   * 0x4000   data\n   * 
\n * Don't touch anything before 0x400.\n *

\n *\n * @alias AES_asm\n * @class\n * @param foreign - ignored\n * @param buffer - heap buffer to link with\n */\n var wrapper = function (foreign, buffer) {\n // Init AES stuff for the first time\n if (!aes_init_done) aes_init();\n\n // Fill up AES tables\n var heap = new Uint32Array(buffer);\n heap.set(aes_sbox, 0x0800 >> 2);\n heap.set(aes_sinv, 0x0c00 >> 2);\n for (var i = 0; i < 4; i++) {\n heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);\n heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);\n }\n\n /**\n * Calculate AES key schedules.\n * @instance\n * @memberof AES_asm\n * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)\n * @param {number} k0 - key vector components\n * @param {number} k1 - key vector components\n * @param {number} k2 - key vector components\n * @param {number} k3 - key vector components\n * @param {number} k4 - key vector components\n * @param {number} k5 - key vector components\n * @param {number} k6 - key vector components\n * @param {number} k7 - key vector components\n */\n function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {\n var ekeys = heap.subarray(0x000, 60),\n dkeys = heap.subarray(0x100, 0x100 + 60);\n\n // Encryption key schedule\n ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);\n for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {\n var k = ekeys[i - 1];\n if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {\n k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];\n }\n if (i % ks === 0) {\n k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);\n }\n ekeys[i] = ekeys[i - ks] ^ k;\n }\n\n // Decryption key schedule\n for (var j = 0; j < i; j += 4) {\n for (var jj = 0; jj < 4; jj++) {\n var k = ekeys[i - (4 + j) + (4 - jj) % 4];\n if (j < 4 || j >= i - 4) {\n dkeys[j + jj] = k;\n } else {\n dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]\n ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]\n ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]\n ^ aes_dec[3][aes_sbox[k & 255]];\n }\n }\n }\n\n // Set rounds number\n asm.set_rounds(ks + 5);\n }\n\n // create library object with necessary properties\n var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};\n\n var asm = function (stdlib, foreign, buffer) {\n \"use asm\";\n\n var S0 = 0, S1 = 0, S2 = 0, S3 = 0,\n I0 = 0, I1 = 0, I2 = 0, I3 = 0,\n N0 = 0, N1 = 0, N2 = 0, N3 = 0,\n M0 = 0, M1 = 0, M2 = 0, M3 = 0,\n H0 = 0, H1 = 0, H2 = 0, H3 = 0,\n R = 0;\n\n var HEAP = new stdlib.Uint32Array(buffer),\n DATA = new stdlib.Uint8Array(buffer);\n\n /**\n * AES core\n * @param {number} k - precomputed key schedule offset\n * @param {number} s - precomputed sbox table offset\n * @param {number} t - precomputed round table offset\n * @param {number} r - number of inner rounds to perform\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _core(k, s, t, r, x0, x1, x2, x3) {\n k = k | 0;\n s = s | 0;\n t = t | 0;\n r = r | 0;\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t1 = 0, t2 = 0, t3 = 0,\n y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n i = 0;\n\n t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;\n\n // round 0\n x0 = x0 ^ HEAP[(k | 0) >> 2],\n x1 = x1 ^ HEAP[(k | 4) >> 2],\n x2 = x2 ^ HEAP[(k | 8) >> 2],\n x3 = x3 ^ HEAP[(k | 12) >> 2];\n\n // round 1..r\n for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {\n y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n x0 = y0, x1 = y1, x2 = y2, x3 = y3;\n }\n\n // final round\n S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n }\n\n /**\n * ECB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n x0,\n x1,\n x2,\n x3\n );\n }\n\n /**\n * ECB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n }\n\n\n /**\n * CBC mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0 ^ x0,\n I1 ^ x1,\n I2 ^ x2,\n I3 ^ x3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n }\n\n /**\n * CBC mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n\n S0 = S0 ^ I0,\n S1 = S1 ^ I1,\n S2 = S2 ^ I2,\n S3 = S3 ^ I3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * CFB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0 = S0 ^ x0,\n I1 = S1 = S1 ^ x1,\n I2 = S2 = S2 ^ x2,\n I3 = S3 = S3 ^ x3;\n }\n\n\n /**\n * CFB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * OFB mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ofb(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n }\n\n /**\n * CTR mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ctr(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n N0,\n N1,\n N2,\n N3\n );\n\n N3 = (~M3 & N3) | M3 & (N3 + 1);\n N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));\n N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));\n N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));\n\n S0 = S0 ^ x0;\n S1 = S1 ^ x1;\n S2 = S2 ^ x2;\n S3 = S3 ^ x3;\n }\n\n /**\n * GCM mode MAC calculation\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _gcm_mac(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n z0 = 0, z1 = 0, z2 = 0, z3 = 0,\n i = 0, c = 0;\n\n x0 = x0 ^ I0,\n x1 = x1 ^ I1,\n x2 = x2 ^ I2,\n x3 = x3 ^ I3;\n\n y0 = H0 | 0,\n y1 = H1 | 0,\n y2 = H2 | 0,\n y3 = H3 | 0;\n\n for (; (i | 0) < 128; i = (i + 1) | 0) {\n if (y0 >>> 31) {\n z0 = z0 ^ x0,\n z1 = z1 ^ x1,\n z2 = z2 ^ x2,\n z3 = z3 ^ x3;\n }\n\n y0 = (y0 << 1) | (y1 >>> 31),\n y1 = (y1 << 1) | (y2 >>> 31),\n y2 = (y2 << 1) | (y3 >>> 31),\n y3 = (y3 << 1);\n\n c = x3 & 1;\n\n x3 = (x3 >>> 1) | (x2 << 31),\n x2 = (x2 >>> 1) | (x1 << 31),\n x1 = (x1 >>> 1) | (x0 << 31),\n x0 = (x0 >>> 1);\n\n if (c) x0 = x0 ^ 0xe1000000;\n }\n\n I0 = z0,\n I1 = z1,\n I2 = z2,\n I3 = z3;\n }\n\n /**\n * Set the internal rounds number.\n * @instance\n * @memberof AES_asm\n * @param {number} r - number if inner AES rounds\n */\n function set_rounds(r) {\n r = r | 0;\n R = r;\n }\n\n /**\n * Populate the internal state of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} s0 - state vector\n * @param {number} s1 - state vector\n * @param {number} s2 - state vector\n * @param {number} s3 - state vector\n */\n function set_state(s0, s1, s2, s3) {\n s0 = s0 | 0;\n s1 = s1 | 0;\n s2 = s2 | 0;\n s3 = s3 | 0;\n\n S0 = s0,\n S1 = s1,\n S2 = s2,\n S3 = s3;\n }\n\n /**\n * Populate the internal iv of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} i0 - iv vector\n * @param {number} i1 - iv vector\n * @param {number} i2 - iv vector\n * @param {number} i3 - iv vector\n */\n function set_iv(i0, i1, i2, i3) {\n i0 = i0 | 0;\n i1 = i1 | 0;\n i2 = i2 | 0;\n i3 = i3 | 0;\n\n I0 = i0,\n I1 = i1,\n I2 = i2,\n I3 = i3;\n }\n\n /**\n * Set nonce for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} n0 - nonce vector\n * @param {number} n1 - nonce vector\n * @param {number} n2 - nonce vector\n * @param {number} n3 - nonce vector\n */\n function set_nonce(n0, n1, n2, n3) {\n n0 = n0 | 0;\n n1 = n1 | 0;\n n2 = n2 | 0;\n n3 = n3 | 0;\n\n N0 = n0,\n N1 = n1,\n N2 = n2,\n N3 = n3;\n }\n\n /**\n * Set counter mask for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} m0 - counter mask vector\n * @param {number} m1 - counter mask vector\n * @param {number} m2 - counter mask vector\n * @param {number} m3 - counter mask vector\n */\n function set_mask(m0, m1, m2, m3) {\n m0 = m0 | 0;\n m1 = m1 | 0;\n m2 = m2 | 0;\n m3 = m3 | 0;\n\n M0 = m0,\n M1 = m1,\n M2 = m2,\n M3 = m3;\n }\n\n /**\n * Set counter for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} c0 - counter vector\n * @param {number} c1 - counter vector\n * @param {number} c2 - counter vector\n * @param {number} c3 - counter vector\n */\n function set_counter(c0, c1, c2, c3) {\n c0 = c0 | 0;\n c1 = c1 | 0;\n c2 = c2 | 0;\n c3 = c3 | 0;\n\n N3 = (~M3 & N3) | M3 & c3,\n N2 = (~M2 & N2) | M2 & c2,\n N1 = (~M1 & N1) | M1 & c1,\n N0 = (~M0 & N0) | M0 & c0;\n }\n\n /**\n * Store the internal state vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_state(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n return 16;\n }\n\n /**\n * Store the internal iv vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_iv(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = I0 >>> 24,\n DATA[pos | 1] = I0 >>> 16 & 255,\n DATA[pos | 2] = I0 >>> 8 & 255,\n DATA[pos | 3] = I0 & 255,\n DATA[pos | 4] = I1 >>> 24,\n DATA[pos | 5] = I1 >>> 16 & 255,\n DATA[pos | 6] = I1 >>> 8 & 255,\n DATA[pos | 7] = I1 & 255,\n DATA[pos | 8] = I2 >>> 24,\n DATA[pos | 9] = I2 >>> 16 & 255,\n DATA[pos | 10] = I2 >>> 8 & 255,\n DATA[pos | 11] = I2 & 255,\n DATA[pos | 12] = I3 >>> 24,\n DATA[pos | 13] = I3 >>> 16 & 255,\n DATA[pos | 14] = I3 >>> 8 & 255,\n DATA[pos | 15] = I3 & 255;\n\n return 16;\n }\n\n /**\n * GCM initialization.\n * @instance\n * @memberof AES_asm\n */\n function gcm_init() {\n _ecb_enc(0, 0, 0, 0);\n H0 = S0,\n H1 = S1,\n H2 = S2,\n H3 = S3;\n }\n\n /**\n * Perform ciphering operation on the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function cipher(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _cipher_modes[mode & 7](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * Calculates MAC of the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function mac(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _mac_modes[mode & 1](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * AES cipher modes table (virual methods)\n */\n var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];\n\n /**\n * AES MAC modes table (virual methods)\n */\n var _mac_modes = [_cbc_enc, _gcm_mac];\n\n /**\n * Asm.js module exports\n */\n return {\n set_rounds: set_rounds,\n set_state: set_state,\n set_iv: set_iv,\n set_nonce: set_nonce,\n set_mask: set_mask,\n set_counter: set_counter,\n get_state: get_state,\n get_iv: get_iv,\n gcm_init: gcm_init,\n cipher: cipher,\n mac: mac,\n };\n }(stdlib, foreign, buffer);\n\n asm.set_key = set_key;\n\n return asm;\n };\n\n /**\n * AES enciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.ENC = {\n ECB: 0,\n CBC: 2,\n CFB: 4,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES deciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.DEC = {\n ECB: 1,\n CBC: 3,\n CFB: 5,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES MAC mode constants\n * @enum {number}\n * @const\n */\n wrapper.MAC = {\n CBC: 0,\n GCM: 1,\n };\n\n /**\n * Heap data offset\n * @type {number}\n * @const\n */\n wrapper.HEAP_DATA = 0x4000;\n\n return wrapper;\n}();\n","const local_atob = typeof atob === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'base64').toString('binary') : atob;\nconst local_btoa = typeof btoa === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'binary').toString('base64') : btoa;\nexport function string_to_bytes(str, utf8 = false) {\n var len = str.length, bytes = new Uint8Array(utf8 ? 4 * len : len);\n for (var i = 0, j = 0; i < len; i++) {\n var c = str.charCodeAt(i);\n if (utf8 && 0xd800 <= c && c <= 0xdbff) {\n if (++i >= len)\n throw new Error('Malformed string, low surrogate expected at position ' + i);\n c = ((c ^ 0xd800) << 10) | 0x10000 | (str.charCodeAt(i) ^ 0xdc00);\n }\n else if (!utf8 && c >>> 8) {\n throw new Error('Wide characters are not allowed.');\n }\n if (!utf8 || c <= 0x7f) {\n bytes[j++] = c;\n }\n else if (c <= 0x7ff) {\n bytes[j++] = 0xc0 | (c >> 6);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else if (c <= 0xffff) {\n bytes[j++] = 0xe0 | (c >> 12);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else {\n bytes[j++] = 0xf0 | (c >> 18);\n bytes[j++] = 0x80 | ((c >> 12) & 0x3f);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n }\n return bytes.subarray(0, j);\n}\nexport function hex_to_bytes(str) {\n var len = str.length;\n if (len & 1) {\n str = '0' + str;\n len++;\n }\n var bytes = new Uint8Array(len >> 1);\n for (var i = 0; i < len; i += 2) {\n bytes[i >> 1] = parseInt(str.substr(i, 2), 16);\n }\n return bytes;\n}\nexport function base64_to_bytes(str) {\n return string_to_bytes(local_atob(str));\n}\nexport function bytes_to_string(bytes, utf8 = false) {\n var len = bytes.length, chars = new Array(len);\n for (var i = 0, j = 0; i < len; i++) {\n var b = bytes[i];\n if (!utf8 || b < 128) {\n chars[j++] = b;\n }\n else if (b >= 192 && b < 224 && i + 1 < len) {\n chars[j++] = ((b & 0x1f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 224 && b < 240 && i + 2 < len) {\n chars[j++] = ((b & 0xf) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 240 && b < 248 && i + 3 < len) {\n var c = ((b & 7) << 18) | ((bytes[++i] & 0x3f) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n if (c <= 0xffff) {\n chars[j++] = c;\n }\n else {\n c ^= 0x10000;\n chars[j++] = 0xd800 | (c >> 10);\n chars[j++] = 0xdc00 | (c & 0x3ff);\n }\n }\n else {\n throw new Error('Malformed UTF8 character at byte offset ' + i);\n }\n }\n var str = '', bs = 16384;\n for (var i = 0; i < j; i += bs) {\n str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));\n }\n return str;\n}\nexport function bytes_to_hex(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var h = (arr[i] & 0xff).toString(16);\n if (h.length < 2)\n str += '0';\n str += h;\n }\n return str;\n}\nexport function bytes_to_base64(arr) {\n return local_btoa(bytes_to_string(arr));\n}\nexport function pow2_ceil(a) {\n a -= 1;\n a |= a >>> 1;\n a |= a >>> 2;\n a |= a >>> 4;\n a |= a >>> 8;\n a |= a >>> 16;\n a += 1;\n return a;\n}\nexport function is_number(a) {\n return typeof a === 'number';\n}\nexport function is_string(a) {\n return typeof a === 'string';\n}\nexport function is_buffer(a) {\n return a instanceof ArrayBuffer;\n}\nexport function is_bytes(a) {\n return a instanceof Uint8Array;\n}\nexport function is_typed_array(a) {\n return (a instanceof Int8Array ||\n a instanceof Uint8Array ||\n a instanceof Int16Array ||\n a instanceof Uint16Array ||\n a instanceof Int32Array ||\n a instanceof Uint32Array ||\n a instanceof Float32Array ||\n a instanceof Float64Array);\n}\nexport function _heap_init(heap, heapSize) {\n const size = heap ? heap.byteLength : heapSize || 65536;\n if (size & 0xfff || size <= 0)\n throw new Error('heap size must be a positive integer and a multiple of 4096');\n heap = heap || new Uint8Array(new ArrayBuffer(size));\n return heap;\n}\nexport function _heap_write(heap, hpos, data, dpos, dlen) {\n const hlen = heap.length - hpos;\n const wlen = hlen < dlen ? hlen : dlen;\n heap.set(data.subarray(dpos, dpos + wlen), hpos);\n return wlen;\n}\nexport function joinBytes(...arg) {\n const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);\n const ret = new Uint8Array(totalLenght);\n let cursor = 0;\n for (let i = 0; i < arg.length; i++) {\n ret.set(arg[i], cursor);\n cursor += arg[i].length;\n }\n return ret;\n}\n","export class IllegalStateError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });\n }\n}\nexport class IllegalArgumentError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });\n }\n}\nexport class SecurityError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'SecurityError' } });\n }\n}\n","import { AES_asm } from './aes.asm';\nimport { _heap_init, _heap_write, is_bytes } from '../other/utils';\nimport { IllegalArgumentError, SecurityError } from '../other/errors';\nconst heap_pool = [];\nconst asm_pool = [];\nexport class AES {\n constructor(key, iv, padding = true, mode, heap, asm) {\n this.pos = 0;\n this.len = 0;\n this.mode = mode;\n // The AES object state\n this.pos = 0;\n this.len = 0;\n this.key = key;\n this.iv = iv;\n this.padding = padding;\n // The AES \"worker\"\n this.acquire_asm(heap, asm);\n }\n acquire_asm(heap, asm) {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);\n this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);\n this.reset(this.key, this.iv);\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n reset(key, iv) {\n const { asm } = this.acquire_asm();\n // Key\n const keylen = key.length;\n if (keylen !== 16 && keylen !== 24 && keylen !== 32)\n throw new IllegalArgumentError('illegal key size');\n const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);\n asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);\n // IV\n if (iv !== undefined) {\n if (iv.length !== 16)\n throw new IllegalArgumentError('illegal iv size');\n let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));\n }\n else {\n asm.set_iv(0, 0, 0, 0);\n }\n }\n AES_Encrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n let result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Encrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let plen = 16 - (len % 16);\n let rlen = len;\n if (this.hasOwnProperty('padding')) {\n if (this.padding) {\n for (let p = 0; p < plen; ++p) {\n heap[pos + len + p] = plen;\n }\n len += plen;\n rlen = len;\n }\n else if (len % 16) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n }\n else {\n len += plen;\n }\n const result = new Uint8Array(rlen);\n if (len)\n asm.cipher(amode, hpos + pos, len);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n AES_Decrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let plen = 0;\n let wlen = 0;\n if (this.padding) {\n plen = len + dlen - rlen || 16;\n rlen -= plen;\n }\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Decrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let rlen = len;\n if (len > 0) {\n if (len % 16) {\n if (this.hasOwnProperty('padding')) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n else {\n len += 16 - (len % 16);\n }\n }\n asm.cipher(amode, hpos + pos, len);\n if (this.hasOwnProperty('padding') && this.padding) {\n let pad = heap[pos + rlen - 1];\n if (pad < 1 || pad > 16 || pad > rlen)\n throw new SecurityError('bad padding');\n let pcheck = 0;\n for (let i = pad; i > 1; i--)\n pcheck |= pad ^ heap[pos + rlen - i];\n if (pcheck)\n throw new SecurityError('bad padding');\n rlen -= pad;\n }\n }\n const result = new Uint8Array(rlen);\n if (rlen > 0) {\n result.set(heap.subarray(pos, pos + rlen));\n }\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_ECB {\n static encrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).encrypt(data);\n }\n static decrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).decrypt(data);\n }\n constructor(key, padding = false, aes) {\n this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';\n\n/**\n * Javascript AES implementation.\n * This is used as fallback if the native Crypto APIs are not available.\n */\nfunction aes(length) {\n const C = function(key) {\n const aesECB = new AES_ECB(key);\n\n this.encrypt = function(block) {\n return aesECB.encrypt(block);\n };\n\n this.decrypt = function(block) {\n return aesECB.decrypt(block);\n };\n };\n\n C.blockSize = C.prototype.blockSize = 16;\n C.keySize = C.prototype.keySize = length / 8;\n\n return C;\n}\n\nexport default aes;\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * @fileoverview Symmetric cryptography functions\n * @module crypto/cipher\n * @private\n */\n\nimport aes from './aes';\nimport { DES, TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TF from './twofish';\nimport BF from './blowfish';\n\n/**\n * AES-128 encryption and decryption (ID 7)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes128 = aes(128);\n/**\n * AES-128 Block Cipher (ID 8)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes192 = aes(192);\n/**\n * AES-128 Block Cipher (ID 9)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes256 = aes(256);\n// Not in OpenPGP specifications\nexport const des = DES;\n/**\n * Triple DES Block Cipher (ID 2)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}\n * @returns {Object}\n */\nexport const tripledes = TripleDES;\n/**\n * CAST-128 Block Cipher (ID 3)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}\n * @returns {Object}\n */\nexport const cast5 = CAST5;\n/**\n * Twofish Block Cipher (ID 10)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}\n * @returns {Object}\n */\nexport const twofish = TF;\n/**\n * Blowfish Block Cipher (ID 4)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}\n * @returns {Object}\n */\nexport const blowfish = BF;\n/**\n * Not implemented\n * @function\n * @throws {Error}\n */\nexport const idea = function() {\n throw new Error('IDEA symmetric-key algorithm not implemented');\n};\n","export var sha1_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,\n w16 = 0, w17 = 0, w18 = 0, w19 = 0,\n w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,\n w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,\n w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,\n w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,\n w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,\n w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n\n // 0\n t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 1\n t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 2\n t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 3\n t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 4\n t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 5\n t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 6\n t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 7\n t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 8\n t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 9\n t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 10\n t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 11\n t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 12\n t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 13\n t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 14\n t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 15\n t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 16\n n = w13 ^ w8 ^ w2 ^ w0;\n w16 = (n << 1) | (n >>> 31);\n t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 17\n n = w14 ^ w9 ^ w3 ^ w1;\n w17 = (n << 1) | (n >>> 31);\n t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 18\n n = w15 ^ w10 ^ w4 ^ w2;\n w18 = (n << 1) | (n >>> 31);\n t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 19\n n = w16 ^ w11 ^ w5 ^ w3;\n w19 = (n << 1) | (n >>> 31);\n t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 20\n n = w17 ^ w12 ^ w6 ^ w4;\n w20 = (n << 1) | (n >>> 31);\n t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 21\n n = w18 ^ w13 ^ w7 ^ w5;\n w21 = (n << 1) | (n >>> 31);\n t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 22\n n = w19 ^ w14 ^ w8 ^ w6;\n w22 = (n << 1) | (n >>> 31);\n t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 23\n n = w20 ^ w15 ^ w9 ^ w7;\n w23 = (n << 1) | (n >>> 31);\n t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 24\n n = w21 ^ w16 ^ w10 ^ w8;\n w24 = (n << 1) | (n >>> 31);\n t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 25\n n = w22 ^ w17 ^ w11 ^ w9;\n w25 = (n << 1) | (n >>> 31);\n t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 26\n n = w23 ^ w18 ^ w12 ^ w10;\n w26 = (n << 1) | (n >>> 31);\n t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 27\n n = w24 ^ w19 ^ w13 ^ w11;\n w27 = (n << 1) | (n >>> 31);\n t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 28\n n = w25 ^ w20 ^ w14 ^ w12;\n w28 = (n << 1) | (n >>> 31);\n t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 29\n n = w26 ^ w21 ^ w15 ^ w13;\n w29 = (n << 1) | (n >>> 31);\n t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 30\n n = w27 ^ w22 ^ w16 ^ w14;\n w30 = (n << 1) | (n >>> 31);\n t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 31\n n = w28 ^ w23 ^ w17 ^ w15;\n w31 = (n << 1) | (n >>> 31);\n t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 32\n n = w29 ^ w24 ^ w18 ^ w16;\n w32 = (n << 1) | (n >>> 31);\n t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 33\n n = w30 ^ w25 ^ w19 ^ w17;\n w33 = (n << 1) | (n >>> 31);\n t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 34\n n = w31 ^ w26 ^ w20 ^ w18;\n w34 = (n << 1) | (n >>> 31);\n t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 35\n n = w32 ^ w27 ^ w21 ^ w19;\n w35 = (n << 1) | (n >>> 31);\n t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 36\n n = w33 ^ w28 ^ w22 ^ w20;\n w36 = (n << 1) | (n >>> 31);\n t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 37\n n = w34 ^ w29 ^ w23 ^ w21;\n w37 = (n << 1) | (n >>> 31);\n t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 38\n n = w35 ^ w30 ^ w24 ^ w22;\n w38 = (n << 1) | (n >>> 31);\n t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 39\n n = w36 ^ w31 ^ w25 ^ w23;\n w39 = (n << 1) | (n >>> 31);\n t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 40\n n = w37 ^ w32 ^ w26 ^ w24;\n w40 = (n << 1) | (n >>> 31);\n t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 41\n n = w38 ^ w33 ^ w27 ^ w25;\n w41 = (n << 1) | (n >>> 31);\n t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 42\n n = w39 ^ w34 ^ w28 ^ w26;\n w42 = (n << 1) | (n >>> 31);\n t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 43\n n = w40 ^ w35 ^ w29 ^ w27;\n w43 = (n << 1) | (n >>> 31);\n t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 44\n n = w41 ^ w36 ^ w30 ^ w28;\n w44 = (n << 1) | (n >>> 31);\n t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 45\n n = w42 ^ w37 ^ w31 ^ w29;\n w45 = (n << 1) | (n >>> 31);\n t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 46\n n = w43 ^ w38 ^ w32 ^ w30;\n w46 = (n << 1) | (n >>> 31);\n t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 47\n n = w44 ^ w39 ^ w33 ^ w31;\n w47 = (n << 1) | (n >>> 31);\n t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 48\n n = w45 ^ w40 ^ w34 ^ w32;\n w48 = (n << 1) | (n >>> 31);\n t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 49\n n = w46 ^ w41 ^ w35 ^ w33;\n w49 = (n << 1) | (n >>> 31);\n t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 50\n n = w47 ^ w42 ^ w36 ^ w34;\n w50 = (n << 1) | (n >>> 31);\n t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 51\n n = w48 ^ w43 ^ w37 ^ w35;\n w51 = (n << 1) | (n >>> 31);\n t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 52\n n = w49 ^ w44 ^ w38 ^ w36;\n w52 = (n << 1) | (n >>> 31);\n t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 53\n n = w50 ^ w45 ^ w39 ^ w37;\n w53 = (n << 1) | (n >>> 31);\n t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 54\n n = w51 ^ w46 ^ w40 ^ w38;\n w54 = (n << 1) | (n >>> 31);\n t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 55\n n = w52 ^ w47 ^ w41 ^ w39;\n w55 = (n << 1) | (n >>> 31);\n t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 56\n n = w53 ^ w48 ^ w42 ^ w40;\n w56 = (n << 1) | (n >>> 31);\n t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 57\n n = w54 ^ w49 ^ w43 ^ w41;\n w57 = (n << 1) | (n >>> 31);\n t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 58\n n = w55 ^ w50 ^ w44 ^ w42;\n w58 = (n << 1) | (n >>> 31);\n t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 59\n n = w56 ^ w51 ^ w45 ^ w43;\n w59 = (n << 1) | (n >>> 31);\n t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 60\n n = w57 ^ w52 ^ w46 ^ w44;\n w60 = (n << 1) | (n >>> 31);\n t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 61\n n = w58 ^ w53 ^ w47 ^ w45;\n w61 = (n << 1) | (n >>> 31);\n t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 62\n n = w59 ^ w54 ^ w48 ^ w46;\n w62 = (n << 1) | (n >>> 31);\n t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 63\n n = w60 ^ w55 ^ w49 ^ w47;\n w63 = (n << 1) | (n >>> 31);\n t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 64\n n = w61 ^ w56 ^ w50 ^ w48;\n w64 = (n << 1) | (n >>> 31);\n t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 65\n n = w62 ^ w57 ^ w51 ^ w49;\n w65 = (n << 1) | (n >>> 31);\n t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 66\n n = w63 ^ w58 ^ w52 ^ w50;\n w66 = (n << 1) | (n >>> 31);\n t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 67\n n = w64 ^ w59 ^ w53 ^ w51;\n w67 = (n << 1) | (n >>> 31);\n t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 68\n n = w65 ^ w60 ^ w54 ^ w52;\n w68 = (n << 1) | (n >>> 31);\n t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 69\n n = w66 ^ w61 ^ w55 ^ w53;\n w69 = (n << 1) | (n >>> 31);\n t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 70\n n = w67 ^ w62 ^ w56 ^ w54;\n w70 = (n << 1) | (n >>> 31);\n t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 71\n n = w68 ^ w63 ^ w57 ^ w55;\n w71 = (n << 1) | (n >>> 31);\n t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 72\n n = w69 ^ w64 ^ w58 ^ w56;\n w72 = (n << 1) | (n >>> 31);\n t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 73\n n = w70 ^ w65 ^ w59 ^ w57;\n w73 = (n << 1) | (n >>> 31);\n t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 74\n n = w71 ^ w66 ^ w60 ^ w58;\n w74 = (n << 1) | (n >>> 31);\n t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 75\n n = w72 ^ w67 ^ w61 ^ w59;\n w75 = (n << 1) | (n >>> 31);\n t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 76\n n = w73 ^ w68 ^ w62 ^ w60;\n w76 = (n << 1) | (n >>> 31);\n t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 77\n n = w74 ^ w69 ^ w63 ^ w61;\n w77 = (n << 1) | (n >>> 31);\n t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 78\n n = w75 ^ w70 ^ w64 ^ w62;\n w78 = (n << 1) | (n >>> 31);\n t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 79\n n = w76 ^ w71 ^ w65 ^ w63;\n w79 = (n << 1) | (n >>> 31);\n t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n }\n\n function reset () {\n H0 = 0x67452301;\n H1 = 0xefcdab89;\n H2 = 0x98badcfe;\n H3 = 0x10325476;\n H4 = 0xc3d2e1f0;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA1\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA1\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA1\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","import { _heap_write } from '../other/utils';\nimport { IllegalStateError } from '../other/errors';\nexport class Hash {\n constructor() {\n this.pos = 0;\n this.len = 0;\n }\n reset() {\n const { asm } = this.acquire_asm();\n this.result = null;\n this.pos = 0;\n this.len = 0;\n asm.reset();\n return this;\n }\n process(data) {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n let hpos = this.pos;\n let hlen = this.len;\n let dpos = 0;\n let dlen = data.length;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);\n hlen += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.process(hpos, hlen);\n hpos += wlen;\n hlen -= wlen;\n if (!hlen)\n hpos = 0;\n }\n this.pos = hpos;\n this.len = hlen;\n return this;\n }\n finish() {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n asm.finish(this.pos, this.len, 0);\n this.result = new Uint8Array(this.HASH_SIZE);\n this.result.set(heap.subarray(0, this.HASH_SIZE));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return this;\n }\n}\n","import { sha1_asm } from './sha1.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha1_block_size = 64;\nexport const _sha1_hash_size = 20;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha1 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha1';\n this.BLOCK_SIZE = _sha1_block_size;\n this.HASH_SIZE = _sha1_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha1().process(data).finish().result;\n }\n}\nSha1.NAME = 'sha1';\nSha1.heap_pool = [];\nSha1.asm_pool = [];\nSha1.asm_function = sha1_asm;\n","import { sha256_asm } from './sha256.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha256_block_size = 64;\nexport const _sha256_hash_size = 32;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha256 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha256';\n this.BLOCK_SIZE = _sha256_block_size;\n this.HASH_SIZE = _sha256_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha256().process(data).finish().result;\n }\n}\nSha256.NAME = 'sha256';\n","export var sha256_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n f = H5;\n g = H6;\n h = H7;\n \n // 0\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 1\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 2\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 3\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 4\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 5\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 6\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 7\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 8\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 9\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 10\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 11\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 12\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 13\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 14\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 15\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 16\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 17\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 18\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 19\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 20\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 21\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 22\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 23\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 24\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 25\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 26\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 27\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 28\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 29\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 30\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 31\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 32\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 33\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 34\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 35\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 36\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 37\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 38\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 39\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 40\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 41\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 42\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 43\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 44\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 45\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 46\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 47\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 48\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 49\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 50\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 51\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 52\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 53\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 54\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 55\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 56\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 57\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 58\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 59\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 60\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 61\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 62\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 63\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n H5 = ( H5 + f )|0;\n H6 = ( H6 + g )|0;\n H7 = ( H7 + h )|0;\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n HEAP[output|20] = H5>>>24;\n HEAP[output|21] = H5>>>16&255;\n HEAP[output|22] = H5>>>8&255;\n HEAP[output|23] = H5&255;\n HEAP[output|24] = H6>>>24;\n HEAP[output|25] = H6>>>16&255;\n HEAP[output|26] = H6>>>8&255;\n HEAP[output|27] = H6&255;\n HEAP[output|28] = H7>>>24;\n HEAP[output|29] = H7>>>16&255;\n HEAP[output|30] = H7>>>8&255;\n HEAP[output|31] = H7&255;\n }\n\n function reset () {\n H0 = 0x6a09e667;\n H1 = 0xbb67ae85;\n H2 = 0x3c6ef372;\n H3 = 0xa54ff53a;\n H4 = 0x510e527f;\n H5 = 0x9b05688c;\n H6 = 0x1f83d9ab;\n H7 = 0x5be0cd19;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n h5 = h5|0;\n h6 = h6|0;\n h7 = h7|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n H5 = I5;\n H6 = I6;\n H7 = I7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n H5 = O5;\n H6 = O6;\n H7 = O7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n O5 = H5;\n O6 = H6;\n O7 = H7;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n I5 = H5;\n I6 = H6;\n I7 = H7;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n h5 = h5 ^ H5;\n h6 = h6 ^ H6;\n h7 = h7 ^ H7;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA256\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA256\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA256\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","try {\n var util = require('util');\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n * @private\n */\n\nimport { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1';\nimport { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256';\nimport sha224 from 'hash.js/lib/hash/sha/224';\nimport sha384 from 'hash.js/lib/hash/sha/384';\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport { ripemd160 } from 'hash.js/lib/hash/ripemd';\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport defaultConfig from '../../config';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction hashjsHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n }\n const hashInstance = hash();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => new Uint8Array(hashInstance.digest()));\n };\n}\n\nfunction asmcryptoHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hashInstance = new hash();\n return stream.transform(data, value => {\n hashInstance.process(value);\n }, () => hashInstance.finish().result);\n } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n } else {\n return hash.bytes(data);\n }\n };\n}\n\nconst hashFunctions = {\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),\n sha224: nodeHash('sha224') || hashjsHash(sha224),\n sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),\n sha384: nodeHash('sha384') || hashjsHash(sha384, 'SHA-384'),\n sha512: nodeHash('sha512') || hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge.\n ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)\n};\n\nexport default {\n\n /** @see module:md5 */\n md5: hashFunctions.md5,\n /** @see asmCrypto */\n sha1: hashFunctions.sha1,\n /** @see hash.js */\n sha224: hashFunctions.sha224,\n /** @see asmCrypto */\n sha256: hashFunctions.sha256,\n /** @see hash.js */\n sha384: hashFunctions.sha384,\n /** @see asmCrypto */\n sha512: hashFunctions.sha512,\n /** @see hash.js */\n ripemd: hashFunctions.ripemd,\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n default:\n throw new Error('Invalid hash function.');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CFB {\n static encrypt(data, key, iv) {\n return new AES_CFB(key, iv).encrypt(data);\n }\n static decrypt(data, key, iv) {\n return new AES_CFB(key, iv).decrypt(data);\n }\n constructor(key, iv, aes) {\n this.aes = aes ? aes : new AES(key, iv, true, 'CFB');\n delete this.aes.padding;\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import * as cipher from '.';\nimport enums from '../../enums';\n\n/**\n * Get implementation of the given cipher\n * @param {enums.symmetric} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport default function getCipher(algo) {\n const algoName = enums.read(enums.symmetric, algo);\n return cipher[algoName];\n}\n","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n * @private\n */\n\nimport { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb';\nimport * as stream from '@openpgp/web-stream-tools';\nimport getCipher from '../cipher/getCipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nfunction aesEncrypt(algo, key, pt, iv, config) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support\n !util.isStream(pt) &&\n pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2\n ) { // Web Crypto\n return webEncrypt(algo, key, pt, iv);\n }\n // asm.js fallback\n const cfb = new AES_CFB(key, iv);\n return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());\n}\n\nfunction aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new AES_CFB(key, iv);\n return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());\n }\n return AES_CFB.decrypt(ct, key, iv);\n}\n\nfunction xorMut(a, b) {\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nasync function webEncrypt(algo, key, pt, iv) {\n const ALGO = 'AES-CBC';\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);\n const { blockSize } = getCipher(algo);\n const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);\n const ct = new Uint8Array(await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);\n xorMut(ct, pt);\n return ct;\n}\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","import { AES } from './aes';\nimport { IllegalArgumentError } from '../other/errors';\nimport { joinBytes } from '../other/utils';\nexport class AES_CTR {\n static encrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n static decrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n constructor(key, nonce, aes) {\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n delete this.aes.padding;\n this.AES_CTR_set_options(nonce);\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n AES_CTR_set_options(nonce, counter, size) {\n let { asm } = this.aes.acquire_asm();\n if (size !== undefined) {\n if (size < 8 || size > 48)\n throw new IllegalArgumentError('illegal counter size');\n let mask = Math.pow(2, size) - 1;\n asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);\n }\n else {\n size = 48;\n asm.set_mask(0, 0, 0xffff, 0xffffffff);\n }\n if (nonce !== undefined) {\n let len = nonce.length;\n if (!len || len > 16)\n throw new IllegalArgumentError('illegal nonce size');\n let view = new DataView(new ArrayBuffer(16));\n new Uint8Array(view.buffer).set(nonce);\n asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));\n }\n else {\n throw new Error('nonce is required');\n }\n if (counter !== undefined) {\n if (counter < 0 || counter >= Math.pow(2, size))\n throw new IllegalArgumentError('illegal counter value');\n asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);\n }\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CBC {\n static encrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).encrypt(data);\n }\n static decrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).decrypt(data);\n }\n constructor(key, iv, padding = true, aes) {\n this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n * @private\n */\n\nimport { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt) {\n return AES_CBC.encrypt(pt, key, false, zeroBlock);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n * @private\n */\n\nimport { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n ) {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt, iv) {\n return AES_CTR.encrypt(pt, key, iv);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n * @private\n */\n\nimport * as ciphers from '../cipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n\n let maxNtz = 0;\n let encipher;\n let decipher;\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables(cipher, key) {\n const cipherName = enums.read(enums.symmetric, cipher);\n const aes = new ciphers[cipherName](key);\n encipher = aes.encrypt.bind(aes);\n decipher = aes.decrypt.bind(aes);\n\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors';\nimport { _heap_write } from '../other/utils';\nimport { AES } from './aes';\nimport { AES_asm } from './aes.asm';\nconst _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5\nexport class AES_GCM {\n constructor(key, nonce, adata, tagSize = 16, aes) {\n this.tagSize = tagSize;\n this.gamma0 = 0;\n this.counter = 1;\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n let { asm, heap } = this.aes.acquire_asm();\n // Init GCM\n asm.gcm_init();\n // Tag size\n if (this.tagSize < 4 || this.tagSize > 16)\n throw new IllegalArgumentError('illegal tagSize value');\n // Nonce\n const noncelen = nonce.length || 0;\n const noncebuf = new Uint8Array(16);\n if (noncelen !== 12) {\n this._gcm_mac_process(nonce);\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = 0;\n heap[4] = 0;\n heap[5] = 0;\n heap[6] = 0;\n heap[7] = 0;\n heap[8] = 0;\n heap[9] = 0;\n heap[10] = 0;\n heap[11] = noncelen >>> 29;\n heap[12] = (noncelen >>> 21) & 255;\n heap[13] = (noncelen >>> 13) & 255;\n heap[14] = (noncelen >>> 5) & 255;\n heap[15] = (noncelen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_iv(0, 0, 0, 0);\n noncebuf.set(heap.subarray(0, 16));\n }\n else {\n noncebuf.set(nonce);\n noncebuf[15] = 1;\n }\n const nonceview = new DataView(noncebuf.buffer);\n this.gamma0 = nonceview.getUint32(12);\n asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);\n asm.set_mask(0, 0, 0, 0xffffffff);\n // Associated data\n if (adata !== undefined) {\n if (adata.length > _AES_GCM_data_maxLength)\n throw new IllegalArgumentError('illegal adata length');\n if (adata.length) {\n this.adata = adata;\n this._gcm_mac_process(adata);\n }\n else {\n this.adata = undefined;\n }\n }\n else {\n this.adata = undefined;\n }\n // Counter\n if (this.counter < 1 || this.counter > 0xffffffff)\n throw new RangeError('counter must be a positive 32-bit integer');\n asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);\n }\n static encrypt(cleartext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);\n }\n static decrypt(ciphertext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);\n }\n encrypt(data) {\n return this.AES_GCM_encrypt(data);\n }\n decrypt(data) {\n return this.AES_GCM_decrypt(data);\n }\n AES_GCM_Encrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Encrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let adata = this.adata;\n let pos = this.aes.pos;\n let len = this.aes.len;\n const result = new Uint8Array(len + tagSize);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);\n if (len)\n result.set(heap.subarray(pos, pos + len));\n let i = len;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n result.set(heap.subarray(0, tagSize), len);\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_Decrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;\n let tlen = len + dlen - rlen;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > tlen) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n pos = 0;\n len = 0;\n }\n if (dlen > 0) {\n len += _heap_write(heap, 0, data, dpos, dlen);\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Decrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let tagSize = this.tagSize;\n let adata = this.adata;\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rlen = len - tagSize;\n if (len < tagSize)\n throw new IllegalStateError('authentication tag not found');\n const result = new Uint8Array(rlen);\n const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));\n let i = rlen;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len - tagSize;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n let acheck = 0;\n for (let i = 0; i < tagSize; ++i)\n acheck |= atag[i] ^ heap[i];\n if (acheck)\n throw new SecurityError('data integrity check failed');\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_decrypt(data) {\n const result1 = this.AES_GCM_Decrypt_process(data);\n const result2 = this.AES_GCM_Decrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n AES_GCM_encrypt(data) {\n const result1 = this.AES_GCM_Encrypt_process(data);\n const result2 = this.AES_GCM_Encrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n _gcm_mac_process(data) {\n let { asm, heap } = this.aes.acquire_asm();\n let dpos = 0;\n let dlen = data.length || 0;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, 0, data, dpos, dlen);\n dpos += wlen;\n dlen -= wlen;\n while (wlen & 15)\n heap[wlen++] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);\n }\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n * @private\n */\n\nimport { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.encrypt(pt, key, iv, adata);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (ct.length === tagLength) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n }\n };\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return AES_GCM.encrypt(pt, key, iv, adata);\n },\n\n decrypt: async function(ct, iv, adata) {\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n * @private\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","/*jshint bitwise: false*/\n\n(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d;\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d, h, r;\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n r = nacl.hash(sm.subarray(32, smlen));\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n h = nacl.hash(sm.subarray(0, smlen));\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h;\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n h = nacl.hash(m.subarray(0, n));\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n * @private\n */\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const buf = new Uint8Array(length);\n if (nodeCrypto) {\n const bytes = nodeCrypto.randomBytes(buf.length);\n buf.set(bytes);\n } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n return buf;\n}\n\n/**\n * Create a secure random BigInteger that is greater than or equal to min and less than max.\n * @param {module:BigInteger} min - Lower bound, included\n * @param {module:BigInteger} max - Upper bound, excluded\n * @returns {Promise} Random BigInteger.\n * @async\n */\nexport async function getRandomBigInteger(min, max) {\n const BigInteger = await util.getBigInteger();\n\n if (max.lt(min)) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max.sub(min);\n const bytes = modulus.byteLength();\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = new BigInteger(await getRandomBytes(bytes + 8));\n return r.mod(modulus).add(min);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\n\n/**\n * Generate a probably prime random number\n * @param {Integer} bits - Bit length of the prime\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns BigInteger\n * @async\n */\nexport async function randomProbablePrime(bits, e, k) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n const min = one.leftShift(new BigInteger(bits - 1));\n const thirty = new BigInteger(30);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n const n = await getRandomBigInteger(min, min.leftShift(one));\n let i = n.mod(thirty).toNumber();\n\n do {\n n.iadd(new BigInteger(adds[i]));\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (n.bitLength() > bits) {\n n.imod(min.leftShift(one)).iadd(min);\n i = n.mod(thirty).toNumber();\n }\n } while (!await isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns {boolean}\n * @async\n */\nexport async function isProbablePrime(n, e, k) {\n if (e && !n.dec().gcd(e).isOne()) {\n return false;\n }\n if (!await divisionTest(n)) {\n return false;\n }\n if (!await fermat(n)) {\n return false;\n }\n if (!await millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} b - Optional Fermat test base\n * @returns {boolean}\n */\nexport async function fermat(n, b) {\n const BigInteger = await util.getBigInteger();\n b = b || new BigInteger(2);\n return b.modExp(n.dec(), n).isOne();\n}\n\nexport async function divisionTest(n) {\n const BigInteger = await util.getBigInteger();\n return smallPrimes.every(m => {\n return n.mod(new BigInteger(m)) !== 0;\n });\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n];\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param {BigInteger} n - Number to test\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @param {Function} rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport async function millerRabin(n, k, rand) {\n const BigInteger = await util.getBigInteger();\n const len = n.bitLength();\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n.dec(); // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!n1.getBit(s)) { s++; }\n const d = n.rightShift(new BigInteger(s));\n\n for (; k > 0; k--) {\n const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);\n\n let x = a.modExp(d, n);\n if (x.isOne() || x.equal(n1)) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = x.mul(x).mod(n);\n\n if (x.isOne()) {\n return false;\n }\n if (x.equal(n1)) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n * @private\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport async function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n * @private\n */\n\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\n/* eslint-disable no-invalid-this */\nconst RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('version').int(), // 0\n this.key('modulus').int(), // n\n this.key('publicExponent').int(), // e\n this.key('privateExponent').int(), // d\n this.key('prime1').int(), // p\n this.key('prime2').int(), // q\n this.key('exponent1').int(), // dp\n this.key('exponent2').int(), // dq\n this.key('coefficient').int() // u\n );\n}) : undefined;\n\nconst RSAPublicKey = nodeCrypto ? asn1.define('RSAPubliceKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('modulus').int(), // n\n this.key('publicExponent').int() // e\n );\n}) : undefined;\n/* eslint-enable no-invalid-this */\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n const BigInteger = await util.getBigInteger();\n\n e = new BigInteger(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return {\n n: b64ToUint8Array(jwk.n),\n e: e.toUint8Array(),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {\n const opts = {\n modulusLength: bits,\n publicExponent: e.toNumber(),\n publicKeyEncoding: { type: 'pkcs1', format: 'der' },\n privateKeyEncoding: { type: 'pkcs1', format: 'der' }\n };\n const prv = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {\n if (err) {\n reject(err);\n } else {\n resolve(RSAPrivateKey.decode(der, 'der'));\n }\n });\n });\n /**\n * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.\n * @link https://tools.ietf.org/html/rfc3447#section-3.2\n * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1\n */\n return {\n n: prv.modulus.toArrayLike(Uint8Array),\n e: prv.publicExponent.toArrayLike(Uint8Array),\n d: prv.privateExponent.toArrayLike(Uint8Array),\n // switch p and q\n p: prv.prime2.toArrayLike(Uint8Array),\n q: prv.prime1.toArrayLike(Uint8Array),\n // Since p and q are switched in places, we can keep u as defined by DER\n u: prv.coefficient.toArrayLike(Uint8Array)\n };\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = await randomProbablePrime(bits - (bits >> 1), e, 40);\n p = await randomProbablePrime(bits >> 1, e, 40);\n n = p.mul(q);\n } while (n.bitLength() !== bits);\n\n const phi = p.dec().imul(q.dec());\n\n if (q.lt(p)) {\n [p, q] = [q, p];\n }\n\n return {\n n: n.toUint8Array(),\n e: e.toUint8Array(),\n d: e.modInv(phi).toUint8Array(),\n p: p.toUint8Array(),\n q: q.toUint8Array(),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: p.modInv(q).toUint8Array()\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n p = new BigInteger(p);\n q = new BigInteger(q);\n\n // expect pq = n\n if (!p.mul(q).equal(n)) {\n return false;\n }\n\n const two = new BigInteger(2);\n // expect p*u = 1 mod q\n u = new BigInteger(u);\n if (!p.mul(u).mod(q).isOne()) {\n return false;\n }\n\n e = new BigInteger(e);\n d = new BigInteger(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));\n const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r.mul(d).mul(e);\n\n const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));\n d = new BigInteger(d);\n if (m.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return m.modExp(d, n).toUint8Array('be', n.byteLength());\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPrivateKey.encode(keyObject, 'der');\n return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));\n }\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n return new Uint8Array(sign.sign(pem));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n s = new BigInteger(s);\n e = new BigInteger(e);\n if (s.gte(n)) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());\n const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1' };\n } else {\n key = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n }\n try {\n return await verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const { default: BN } = await import('bn.js');\n\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n data = new BigInteger(emeEncode(data, n.byteLength()));\n e = new BigInteger(e);\n if (data.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return data.modExp(e, n).toUint8Array('be', n.byteLength());\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPrivateKey.encode(keyObject, 'der');\n key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n const BigInteger = await util.getBigInteger();\n data = new BigInteger(data);\n n = new BigInteger(n);\n e = new BigInteger(e);\n d = new BigInteger(d);\n p = new BigInteger(p);\n q = new BigInteger(q);\n u = new BigInteger(u);\n if (data.gte(n)) {\n throw new Error('Data too large.');\n }\n const dq = d.mod(q.dec()); // d mod (q-1)\n const dp = d.mod(p.dec()); // d mod (p-1)\n\n const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);\n const blinder = unblinder.modInv(n).modExp(e, n);\n data = data.mul(blinder).mod(n);\n\n\n const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p\n const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q\n const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h.mul(p).add(mp); // result < n due to relations above\n\n result = result.mul(unblinder).mod(n);\n\n\n return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n const pNum = new BigInteger(p);\n const qNum = new BigInteger(q);\n const dNum = new BigInteger(d);\n\n let dq = dNum.mod(qNum.dec()); // d mod (q-1)\n let dp = dNum.mod(pNum.dec()); // d mod (p-1)\n dp = dp.toUint8Array();\n dq = dq.toUint8Array();\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const padded = emeEncode(data, p.byteLength());\n const m = new BigInteger(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = await getRandomBigInteger(new BigInteger(1), p.dec());\n return {\n c1: g.modExp(k, p).toUint8Array(),\n c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n const BigInteger = await util.getBigInteger();\n c1 = new BigInteger(c1);\n c2 = new BigInteger(c2);\n p = new BigInteger(p);\n x = new BigInteger(x);\n\n const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);\n return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = new BigInteger(p.bitLength());\n const n1023 = new BigInteger(1023);\n if (pSize.lt(n1023)) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (!g.modExp(p.dec(), p).isOne()) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n const i = new BigInteger(1);\n const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold\n while (i.lt(threshold)) {\n res = res.mul(g).imod(p);\n if (res.isOne()) {\n return false;\n }\n i.iinc();\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1\n const rqx = p.dec().imul(r).iadd(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n * @private\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {string} String with the canonical name of the curve.\n */\n getName() {\n const hex = this.toHex();\n if (enums.curve[hex]) {\n return enums.write(enums.curve, hex);\n } else {\n throw new Error('Unknown curve object identifier.');\n }\n }\n}\n\nexport default OID;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library\n * @module crypto/public_key/elliptic/indutnyKey\n * @private\n */\n\nimport config from '../../../config';\n\nexport function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}\n\nexport function keyFromPublic(indutnyCurve, pub) {\n const keyPair = indutnyCurve.keyPair({ pub: pub });\n if (keyPair.validate().result !== true) {\n throw new Error('Invalid elliptic public key');\n }\n return keyPair;\n}\n\nexport async function getIndutnyCurve(name) {\n if (!config.useIndutnyElliptic) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n const { default: elliptic } = await import('@openpgp/elliptic');\n return new elliptic.ec(name);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new stream.TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { getRandomBytes } from '../../random';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport { UnsupportedError } from '../../../packet/packet';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n 'p256': 'P-256',\n 'p384': 'P-384',\n 'p521': 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,\n brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n p256: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.p256,\n web: webCurves.p256,\n payloadSize: 32,\n sharedSize: 256\n },\n p384: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.p384,\n web: webCurves.p384,\n payloadSize: 48,\n sharedSize: 384\n },\n p521: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.p521,\n web: webCurves.p521,\n payloadSize: 66,\n sharedSize: 528\n },\n secp256k1: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.secp256k1,\n payloadSize: 32\n },\n ed25519: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32\n },\n curve25519: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32\n },\n brainpoolP256r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.brainpoolP256r1,\n payloadSize: 32\n },\n brainpoolP384r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.brainpoolP384r1,\n payloadSize: 48\n },\n brainpoolP512r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.brainpoolP512r1,\n payloadSize: 64\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName, params) {\n try {\n if (util.isArray(oidOrName) ||\n util.isUint8Array(oidOrName)) {\n // by oid byte array\n oidOrName = new OID(oidOrName);\n }\n if (oidOrName instanceof OID) {\n // by curve OID\n oidOrName = oidOrName.getName();\n }\n // by curve name or oid string\n this.name = enums.write(enums.curve, oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n params = params || curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node && curves[this.name];\n this.web = params.web && curves[this.name];\n this.payloadSize = params.payloadSize;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === 'curve25519') {\n this.type = 'curve25519';\n } else if (this.name === 'ed25519') {\n this.type = 'ed25519';\n }\n }\n\n async genKeyPair() {\n let keyPair;\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n break;\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519': {\n const privateKey = getRandomBytes(32);\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const secretKey = privateKey.slice().reverse();\n keyPair = nacl.box.keyPair.fromSecretKey(secretKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n case 'ed25519': {\n const privateKey = getRandomBytes(32);\n const keyPair = nacl.sign.keyPair.fromSeed(privateKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n }\n const indutnyCurve = await getIndutnyCurve(this.name);\n keyPair = await indutnyCurve.genKeyPair({\n entropy: util.uint8ArrayToString(getRandomBytes(32))\n });\n return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };\n }\n}\n\nasync function generate(curve) {\n const BigInteger = await util.getBigInteger();\n\n curve = new CurveWithOID(curve);\n const keyPair = await curve.genKeyPair();\n const Q = new BigInteger(keyPair.publicKey).toUint8Array();\n const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);\n return {\n oid: curve.oid,\n Q,\n secret,\n hash: curve.hash,\n cipher: curve.cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[enums.write(enums.curve, oid.toHex())].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n p256: true,\n p384: true,\n p521: true,\n secp256k1: true,\n curve25519: algo === enums.publicKey.ecdh,\n brainpoolP256r1: true,\n brainpoolP384r1: true,\n brainpoolP512r1: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === 'curve25519') {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const curve = await getIndutnyCurve(curveName);\n try {\n // Parse Q and check that it is on the curve but not at infinity\n Q = keyFromPublic(curve, Q).getPublic();\n } catch (validationErrors) {\n return false;\n }\n\n /**\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = keyFromPrivate(curve, d).getPublic();\n if (!dG.eq(Q)) {\n return false;\n }\n\n return true;\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nasync function webGenKeyPair(name) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = 0x04;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n * @private\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './oid_curves';\nimport { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web': {\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n }\n case 'node': {\n const signature = await nodeSign(curve, hashAlgo, message, keyPair);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n }\n }\n }\n return ellipticSign(curve, hashed, privateKey);\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n return await webVerify(curve, hashAlgo, signature, message, publicKey);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node':\n return nodeVerify(curve, hashAlgo, signature, message, publicKey);\n }\n }\n const digest = (typeof hashAlgo === 'undefined') ? message : hashed;\n return ellipticVerify(curve, signature, digest, publicKey);\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\nasync function ellipticSign(curve, hashed, privateKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPrivate(indutnyCurve, privateKey);\n const signature = key.sign(hashed);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n}\n\nasync function ellipticVerify(curve, signature, digest, publicKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPublic(indutnyCurve, publicKey);\n return key.verify(digest, signature);\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, keyPair) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n const key = ECPrivateKey.encode({\n version: 1,\n parameters: curve.oid,\n privateKey: Array.from(keyPair.privateKey),\n publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }\n }, 'pem', {\n label: 'EC PRIVATE KEY'\n });\n\n return ECDSASignature.decode(sign.sign(key), 'der');\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n const key = SubjectPublicKeyInfo.encode({\n algorithm: {\n algorithm: [1, 2, 840, 10045, 2, 1],\n parameters: curve.oid\n },\n subjectPublicKey: { unused: 0, data: Array.from(publicKey) }\n }, 'pem', {\n label: 'PUBLIC KEY'\n });\n const signature = ECDSASignature.encode({\n r: new BN(r), s: new BN(s)\n }, 'der');\n\n try {\n return verify.verify(key, signature);\n } catch (err) {\n return false;\n }\n}\n\n// Originally written by Owen Smith https://github.com/omsmith\n// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/\n\n/* eslint-disable no-invalid-this */\n\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\nconst ECDSASignature = nodeCrypto ?\n asn1.define('ECDSASignature', function() {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n );\n }) : undefined;\n\nconst ECPrivateKey = nodeCrypto ?\n asn1.define('ECPrivateKey', function() {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').explicit(0).optional().any(),\n this.key('publicKey').explicit(1).optional().bitstr()\n );\n }) : undefined;\n\nconst AlgorithmIdentifier = nodeCrypto ?\n asn1.define('AlgorithmIdentifier', function() {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional().any()\n );\n }) : undefined;\n\nconst SubjectPublicKeyInfo = nodeCrypto ?\n asn1.define('SubjectPublicKeyInfo', function() {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n );\n }) : undefined;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);\n const signature = nacl.sign.detached(hashed, secretKey);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const signature = util.concatUint8Array([r, s]);\n return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1));\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== 'ed25519') {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const seed = getRandomBytes(32);\n const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = nacl.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n return nacl.sign.detached.verify(hashed, RS, publicKey);\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: // unsupported\n default:\n return false;\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n * @private\n */\n\nimport * as cipher from './cipher';\nimport util from '../util';\n\n/**\n * AES key wrap\n * @function\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nexport function wrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const P = unpack(data);\n let A = IV;\n const R = P;\n const n = P.length / 2;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 0; j <= 5; ++j) {\n for (let i = 0; i < n; ++i) {\n t[1] = n * j + (1 + i);\n // B = A\n B[0] = A[0];\n B[1] = A[1];\n // B = A || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES(K, B)\n B = unpack(aes.encrypt(pack(B)));\n // A = MSB(64, B) ^ t\n A = B.subarray(0, 2);\n A[0] ^= t[0];\n A[1] ^= t[1];\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n return pack(A, R);\n}\n\n/**\n * AES key unwrap\n * @function\n * @param {String} key\n * @param {String} data\n * @returns {Uint8Array}\n * @throws {Error}\n */\nexport function unwrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const C = unpack(data);\n let A = C.subarray(0, 2);\n const R = C.subarray(2);\n const n = C.length / 2 - 1;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 5; j >= 0; --j) {\n for (let i = n - 1; i >= 0; --i) {\n t[1] = n * j + (i + 1);\n // B = A ^ t\n B[0] = A[0] ^ t[0];\n B[1] = A[1] ^ t[1];\n // B = (A ^ t) || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES-1(B)\n B = unpack(aes.decrypt(pack(B)));\n // A = MSB(64, B)\n A = B.subarray(0, 2);\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n if (A[0] === IV[0] && A[1] === IV[1]) {\n return pack(R);\n }\n throw new Error('Key Data Integrity failed');\n}\n\nfunction createArrayBuffer(data) {\n if (util.isString(data)) {\n const { length } = data;\n const buffer = new ArrayBuffer(length);\n const view = new Uint8Array(buffer);\n for (let j = 0; j < length; ++j) {\n view[j] = data.charCodeAt(j);\n }\n return buffer;\n }\n return new Uint8Array(data).buffer;\n}\n\nfunction unpack(data) {\n const { length } = data;\n const buffer = createArrayBuffer(data);\n const view = new DataView(buffer);\n const arr = new Uint32Array(length / 4);\n for (let i = 0; i < length / 4; ++i) {\n arr[i] = view.getUint32(4 * i);\n }\n return arr;\n}\n\nfunction pack() {\n let length = 0;\n for (let k = 0; k < arguments.length; ++k) {\n length += 4 * arguments[k].length;\n }\n const buffer = new ArrayBuffer(length);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < arguments.length; ++i) {\n for (let j = 0; j < arguments[i].length; ++j) {\n view.setUint32(offset + 4 * j, arguments[i][j]);\n }\n offset += 4 * arguments[i].length;\n }\n return new Uint8Array(buffer);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport getCipher from '../../cipher/getCipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint.subarray(0, 20)\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519': {\n const d = getRandomBytes(32);\n const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);\n let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);\n publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n }\n return ellipticPublicEphemeralKey(curve, Q);\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = aesKW.wrap(Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519': {\n const secretKey = d.slice().reverse();\n const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n }\n return ellipticPrivateEphemeralKey(curve, V, d);\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(aesKW.unwrap(Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: sender\n },\n privateKey,\n curve.web.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.web.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPrivateEphemeralKey(curve, V, d) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n V = keyFromPublic(indutnyCurve, V);\n d = keyFromPrivate(indutnyCurve, d);\n const secretKey = new Uint8Array(d.getPrivate());\n const S = d.derive(V.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPublicEphemeralKey(curve, Q) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const v = await curve.genKeyPair();\n Q = keyFromPublic(indutnyCurve, Q);\n const V = keyFromPrivate(indutnyCurve, v.privateKey);\n const publicKey = v.publicKey;\n const S = V.derive(Q.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeSubtleCrypto = nodeCrypto && nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle;\n\nexport default async function HKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n if (webCrypto || nodeSubtleCrypto) {\n const crypto = webCrypto || nodeSubtleCrypto;\n const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n }\n\n if (nodeCrypto) {\n const hashAlgoName = enums.read(enums.hash, hashAlgo);\n // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869\n\n const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();\n // Step 1: Extract\n // PRK = HMAC-Hash(salt, IKM)\n const pseudoRandomKey = computeHMAC(salt, inputKey);\n\n const hashLen = pseudoRandomKey.length;\n\n // Step 2: Expand\n // HKDF-Expand(PRK, info, L) -> OKM\n const n = Math.ceil(outLen / hashLen);\n const outputKeyingMaterial = new Uint8Array(n * hashLen);\n\n // HMAC input buffer updated at each iteration\n const roundInput = new Uint8Array(hashLen + info.length + 1);\n // T_i and last byte are updated at each iteration, but `info` remains constant\n roundInput.set(info, hashLen);\n\n for (let i = 0; i < n; i++) {\n // T(0) = empty string (zero length)\n // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)\n roundInput[roundInput.length - 1] = i + 1;\n // t = T(i+1)\n const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));\n roundInput.set(t, 0);\n\n outputKeyingMaterial.set(t, i * hashLen);\n }\n\n return outputKeyingMaterial.subarray(0, outLen);\n }\n\n throw new Error('No HKDF implementation available');\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport getCipher from '../../cipher/getCipher';\nimport computeHKDF from '../../hkdf';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(32);\n const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA);\n const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = aesKW.wrap(encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n * @private\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n x = new BigInteger(x);\n\n let k;\n let r;\n let s;\n let t;\n g = g.mod(p);\n x = x.mod(q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = await getRandomBigInteger(one, q); // returns in [1, q-1]\n r = g.modExp(k, p).imod(q); // (g**k mod p) mod q\n if (r.isZero()) {\n continue;\n }\n const xr = x.mul(r).imod(q);\n t = h.add(xr).imod(q); // H(m) + x*r mod q\n s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q\n if (s.isZero()) {\n continue;\n }\n break;\n }\n return {\n r: r.toUint8Array('be', q.byteLength()),\n s: s.toUint8Array('be', q.byteLength())\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n const BigInteger = await util.getBigInteger();\n const zero = new BigInteger(0);\n r = new BigInteger(r);\n s = new BigInteger(s);\n\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n if (r.lte(zero) || r.gte(q) ||\n s.lte(zero) || s.gte(q)) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);\n const w = s.modInv(q); // s**-1 mod q\n if (w.isZero()) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = g.mod(p);\n y = y.mod(p);\n const u1 = h.mul(w).imod(q); // H(m) * w mod q\n const u2 = r.mul(w).imod(q); // r * w mod q\n const t1 = g.modExp(u1, p); // g**u1 mod p\n const t2 = y.modExp(u2, p); // y**u2 mod p\n const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q\n return v.equal(r);\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (!p.dec().mod(q).isZero()) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (!g.modExp(q, p).isOne()) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = new BigInteger(q.bitLength());\n const n150 = new BigInteger(150);\n if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q\n const rqx = q.mul(r).add(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa,\n /** @see tweetnacl */\n nacl: nacl\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n * @private\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read));\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { s };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read));\n return { r, s };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n let r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n r = util.leftPad(r, 32);\n let s = util.readMPI(signature.subarray(read));\n s = util.leftPad(s, 32);\n return { r, s };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n case enums.publicKey.ed25519: {\n const RS = signature.subarray(read, read + 64); read += RS.length;\n return { RS };\n }\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n // signature already padded on parsing\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal: {\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n * @private\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n * @private\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport getCipher from './cipher/getCipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { CurveWithOID } from './public_key/elliptic/oid_curves';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519: {\n if (!util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (!util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.x25519: {\n const A = bytes.subarray(read, read + 32); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const curve = new CurveWithOID(publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, curve.payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const curve = new CurveWithOID(publicParams.oid);\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, curve.payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519: {\n const seed = bytes.subarray(read, read + 32); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519: {\n const k = bytes.subarray(read, read + 32); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key.\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519: {\n const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n }\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipher(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipher(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\nexport { getCipher };\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get preferred hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n * @private\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","\n\n\nvar TYPED_OK = typeof Uint8Array !== \"undefined\" &&\n typeof Uint16Array !== \"undefined\" &&\n typeof Int32Array !== \"undefined\";\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function assign(obj /*...args obj, from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue; \n }\n\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n //return Object.assign(...args);\n}\n\n\n// reduce buffer size, avoiding mem copy\nexport function shrinkBuf(buf, size) {\n if (buf.length === size) {\n return buf; \n }\n if (buf.subarray) {\n return buf.subarray(0, size); \n }\n buf.length = size;\n return buf;\n}\n\n\nconst fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n let i, l, len, pos, chunk;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nconst fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\n\nexport let Buf8 = TYPED_OK ? Uint8Array : Array;\nexport let Buf16 = TYPED_OK ? Uint16Array : Array;\nexport let Buf32 = TYPED_OK ? Int32Array : Array;\nexport let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;\nexport let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;\nexport function setTyped(on) {\n if (on) {\n Buf8 = Uint8Array;\n Buf16 = Uint16Array;\n Buf32 = Int32Array;\n ({ flattenChunks, arraySet } = fnTyped);\n } else {\n Buf8 = Array;\n Buf16 = Array;\n Buf32 = Array;\n ({ flattenChunks, arraySet } = fnUntyped);\n }\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nexport const Z_NO_FLUSH = 0;\nexport const Z_PARTIAL_FLUSH = 1;\nexport const Z_SYNC_FLUSH = 2;\nexport const Z_FULL_FLUSH = 3;\nexport const Z_FINISH = 4;\nexport const Z_BLOCK = 5;\nexport const Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nexport const Z_OK = 0;\nexport const Z_STREAM_END = 1;\nexport const Z_NEED_DICT = 2;\nexport const Z_ERRNO = -1;\nexport const Z_STREAM_ERROR = -2;\nexport const Z_DATA_ERROR = -3;\n//export const Z_MEM_ERROR = -4;\nexport const Z_BUF_ERROR = -5;\n//export const Z_VERSION_ERROR = -6;\n\n /* compression levels */\nexport const Z_NO_COMPRESSION = 0;\nexport const Z_BEST_SPEED = 1;\nexport const Z_BEST_COMPRESSION = 9;\nexport const Z_DEFAULT_COMPRESSION = -1;\n\n\nexport const Z_FILTERED = 1;\nexport const Z_HUFFMAN_ONLY = 2;\nexport const Z_RLE = 3;\nexport const Z_FIXED = 4;\nexport const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nexport const Z_BINARY = 0;\nexport const Z_TEXT = 1;\n//export const Z_ASCII = 1; // = Z_TEXT (deprecated)\nexport const Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nexport const Z_DEFLATED = 8;\n//export const Z_NULL = null // Use -1 or null inline, depending on var type\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nimport * as utils from \"../utils/common.js\";\nimport {\n Z_FIXED,\n Z_BINARY,\n Z_TEXT,\n Z_UNKNOWN\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nfunction zero(buf) {\n let len = buf.length; while (--len >= 0) {\n buf[len] = 0; \n } \n}\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nconst extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nconst extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nconst bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = w & 0xff;\n s.pending_buf[s.pending++] = w >>> 8 & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) {\n continue; \n } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) {\n return; \n }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--; \n }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue; \n }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2]/*.Freq*/ = 0; \n }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n // while (len--) {\n // put_byte(s, *buf++);\n // }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n const _n2 = n * 2;\n const _m2 = m * 2;\n return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break; \n }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {\n pqdownheap(s, tree, n); \n }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]/*.Freq*/++; \n }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree); \n } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb; \n }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n\n //#ifdef TRUNCATE_BLOCK\n // /* Try to guess if it is profitable to stop the current block here */\n // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n // /* Compute an upper bound for the compressed length */\n // out_length = s.last_lit*8;\n // in_length = s.strstart - s.block_start;\n //\n // for (dcode = 0; dcode < D_CODES; dcode++) {\n // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n // }\n // out_length >>>= 3;\n // //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n // // s->last_lit, in_length, out_length,\n // // 100L - out_length*100L/in_length));\n // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n // return true;\n // }\n // }\n //#endif\n\n return s.last_lit === s.lit_bufsize - 1;\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexport {\n _tr_init,\n _tr_stored_block,\n _tr_flush_block,\n _tr_tally,\n _tr_align\n};","\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default function adler32(adler, buf, len, pos) {\n let s1 = adler & 0xffff |0,\n s2 = adler >>> 16 & 0xffff |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = s1 + buf[pos++] |0;\n s2 = s2 + s1 |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return s1 | s2 << 16 |0;\n}\n","\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n let c;\n const table = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = makeTable();\n\n\nexport default function crc32(crc, buf, len, pos) {\n const t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return crc ^ -1; // >>> 0;\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default {\n 2: \"need dictionary\", /* Z_NEED_DICT 2 */\n 1: \"stream end\", /* Z_STREAM_END 1 */\n 0: \"\", /* Z_OK 0 */\n \"-1\": \"file error\", /* Z_ERRNO (-1) */\n \"-2\": \"stream error\", /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\", /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\", /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\", /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\" /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport * as trees from \"./trees.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport msg from \"./messages.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_NO_FLUSH,\n Z_PARTIAL_FLUSH,\n Z_FULL_FLUSH,\n Z_FINISH,\n Z_BLOCK,\n Z_OK,\n Z_STREAM_END,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED,\n Z_HUFFMAN_ONLY,\n Z_RLE,\n Z_FIXED,\n Z_DEFAULT_STRATEGY,\n Z_UNKNOWN,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n // put_byte(s, (Byte)(b >> 8));\n // put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n //#if MIN_MATCH != 3\n // Call update_hash() MIN_MATCH-3 more times\n //#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n // if (s.high_water < s.window_size) {\n // var curr = s.strstart + s.lookahead;\n // var init = 0;\n //\n // if (s.high_water < curr) {\n // /* Previous high water mark below current data -- zero WIN_INIT\n // * bytes or up to end of window, whichever is less.\n // */\n // init = s.window_size - curr;\n // if (init > WIN_INIT)\n // init = WIN_INIT;\n // zmemzero(s->window + curr, (unsigned)init);\n // s->high_water = curr + init;\n // }\n // else if (s->high_water < (ulg)curr + WIN_INIT) {\n // /* High water mark at or above current data, but below current data\n // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n // * to end of window, whichever is less.\n // */\n // init = (ulg)curr + WIN_INIT - s->high_water;\n // if (init > s->window_size - s->high_water)\n // init = s->window_size - s->high_water;\n // zmemzero(s->window + s->high_water, (unsigned)init);\n // s->high_water += init;\n // }\n // }\n //\n // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n // \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (; ;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n // s.block_start >= s.w_size)) {\n // throw new Error(\"slide too late\");\n // }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n // if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n //#if MIN_MATCH != 3\n // Call UPDATE_HASH() MIN_MATCH-3 more times\n //#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nclass Config {\n constructor(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n};\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\nclass DeflateState {\n constructor() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n }\n}\n\nfunction deflateResetKeep(strm) {\n let s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n let old_flush, s;\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n //#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n //#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n let status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n let dictLength = dictionary.length;\n\n let s;\n let str, n;\n let wrap;\n let avail;\n let next;\n let input;\n let tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\nconst deflateInfo = 'pako deflate (from Nodeca project)';\nexport {\n deflateInit,\n deflateInit2,\n deflateReset,\n deflateResetKeep,\n deflateSetHeader,\n deflate,\n deflateEnd,\n deflateSetDictionary,\n deflateInfo\n};\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n\n\n\nimport * as utils from \"./common.js\";\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_OK = true;\nlet STR_APPLY_UIA_OK = true;\n\ntry {\n String.fromCharCode.apply(null, [ 0 ]); \n} catch (__) {\n STR_APPLY_OK = false; \n}\ntry {\n String.fromCharCode.apply(null, new Uint8Array(1)); \n} catch (__) {\n STR_APPLY_UIA_OK = false; \n}\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new utils.Buf8(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexport function string2buf (str) {\n let c, c2, m_pos, i, buf_len = 0;\n const str_len = str.length;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n const buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | c >>> 6;\n buf[i++] = 0x80 | c & 0x3f;\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | c >>> 12;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | c >>> 18;\n buf[i++] = 0x80 | c >>> 12 & 0x3f;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n let result = \"\";\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexport function buf2binstring (buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nexport function binstring2buf (str) {\n const buf = new utils.Buf8(str.length);\n for (let i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nexport function buf2string (buf, max) {\n let i, out, c, c_len;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n // var utf16buf = new Array(len * 2);\n // try Uint16Array\n const utf16buf = new Uint16Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) {\n utf16buf[out++] = c; continue; \n }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) {\n utf16buf[out++] = 0xfffd; i += c_len - 1; continue; \n }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 0x3f;\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) {\n utf16buf[out++] = 0xfffd; continue; \n }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;\n utf16buf[out++] = 0xdc00 | c & 0x3ff;\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexport function utf8border (buf, max) {\n let pos;\n\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length; \n }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {\n pos--; \n }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) {\n return max; \n }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) {\n return max; \n }\n\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class ZStream {\n constructor() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n }\n}","'use strict';\n\nimport * as zlib_deflate from \"./zlib/deflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\nimport { Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED } from \"./zlib/constants.js\"\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\n\nclass Deflate {\n constructor(options) {\n this.options = {\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n ...(options || {})\n };\n\n const opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n }\n\n /**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize } } = this;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n /**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n /**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw new Error(deflator.msg || msg[deflator.err]); }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\nexport { Deflate, deflate, deflateRaw, gzip };\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nexport default function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let _out; /* local strm.output */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n const input = strm.input;\n const last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n const output = strm.output;\n const beg = _out - (start - strm.avail_out);\n const end = _out + (strm.avail_out - 257);\n //#ifdef INFLATE_STRICT\n const dmax = state.dmax;\n //#endif\n const wsize = state.wsize;\n const whave = state.whave;\n const wnext = state.wnext;\n const s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n const lcode = state.lencode;\n const dcode = state.distcode;\n const lmask = (1 << state.lenbits) - 1;\n const dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n } else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n //#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n //#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n // if (len <= op - whave) {\n // do {\n // output[_out++] = 0;\n // } while (--len);\n // continue top;\n // }\n // len -= op - whave;\n // do {\n // output[_out++] = 0;\n // } while (--op > whave);\n // if (op === 0) {\n // from = _out - dist;\n // do {\n // output[_out++] = output[from++];\n // } while (--len);\n // continue top;\n // }\n //#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n } else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n } else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nconst lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nconst dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nconst dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nexport default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n // var shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break; \n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break; \n }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n const mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break; \n }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break; \n }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = root << 24 | curr << 16 | next - table_index |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = len - drop << 24 | 64 << 16 |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport inflate_fast from \"./inffast.js\";\nimport inflate_table from \"./inftrees.js\";\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_FINISH,\n Z_BLOCK,\n Z_TREES,\n Z_OK,\n Z_STREAM_END,\n Z_NEED_DICT,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\n//const MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nclass InflateState {\n constructor() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n }\n}\n\nfunction inflateResetKeep(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n let wrap;\n let state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n let ret;\n let state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n let sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n let hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary var for NEED_BITS\n\n const order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n // case MEM:\n // return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n const state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n let state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n // if (ret) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n // }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nconst inflateInfo = 'pako inflate (from Nodeca project)';\n\nexport {\n inflateReset,\n inflateReset2,\n inflateResetKeep,\n inflateInit,\n inflateInit2,\n inflate,\n inflateEnd,\n inflateGetHeader,\n inflateSetDictionary,\n inflateInfo\n};\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class GZheader {\n constructor() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n }\n}","'use strict';\n\nimport * as zlib_inflate from \"./zlib/inflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport * as c from \"./zlib/constants.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\nimport GZheader from \"./zlib/gzheader.js\";\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nclass Inflate {\n constructor(options) {\n this.options = {\n chunkSize: 16384,\n windowBits: 0,\n ...(options || {})\n };\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n let status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n }\n /**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize, dictionary } } = this;\n let status, _mode;\n let next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n let allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n\n /**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n\n\n /**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === c.Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw new Error(inflator.msg || msg[inflator.err]); }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\nexport { Inflate, inflate, inflateRaw, inflate as ungzip };\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuer,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.signedHashValue = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n this.params = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false) {\n if (key.version === 5) {\n this.version = 5;\n } else {\n this.version = 4;\n }\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = [];\n this.unhashedSubpackets.forEach(data => {\n arr.push(writeSimpleLength(data.length));\n arr.push(data);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n // V4 signature sub packets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n if (!hashed) {\n this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n mypos++;\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuer:\n // Issuer\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion === 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n default: {\n const err = new Error(`Unknown signature subpacket type ${type}`);\n if (critical) {\n throw err;\n } else {\n util.printDebug(err);\n }\n }\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, 2));\n\n let i = 2;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n constructor() {\n /** A one-octet version number. The current version is 3. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** An eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current version is 3.\n this.version = bytes[mypos++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n // An eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);\n\n const end = new Uint8Array([this.flags]);\n\n return util.concatUint8Array([start, this.issuerKeyID.write(), end]);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID)\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Deflate } from '@openpgp/pako/lib/deflate';\nimport { Inflate } from '@openpgp/pako/lib/inflate';\nimport { Z_SYNC_FLUSH, Z_FINISH } from '@openpgp/pako/lib/zlib/constants';\nimport { decode as BunzipDecode } from '@openpgp/seek-bzip';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n\n /**\n * zip/zlib compression level, between 1 and 9\n */\n this.deflateLevel = config.deflateLevel;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName];\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write(), this.deflateLevel);\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nconst nodeZlib = util.getNodeZlib();\n\nfunction uncompressed(data) {\n return data;\n}\n\nfunction node_zlib(func, create, options = {}) {\n return function (data) {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(data => {\n return new Promise((resolve, reject) => {\n func(data, options, (err, result) => {\n if (err) return reject(err);\n resolve(result);\n });\n });\n }));\n }\n return stream.nodeToWeb(stream.webToNode(data).pipe(create(options)));\n };\n}\n\nfunction pako_zlib(constructor, options = {}) {\n return function(data) {\n const obj = new constructor(options);\n return stream.transform(data, value => {\n if (value.length) {\n obj.push(value, Z_SYNC_FLUSH);\n return obj.result;\n }\n }, () => {\n if (constructor === Deflate) {\n obj.push([], Z_FINISH);\n return obj.result;\n }\n });\n };\n}\n\nfunction bzip2(func) {\n return function(data) {\n return stream.fromAsync(async () => func(await stream.readToEnd(data)));\n };\n}\n\nconst compress_fns = nodeZlib ? {\n zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)\n} : {\n zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)\n};\n\nconst decompress_fns = nodeZlib ? {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),\n zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n} : {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),\n zlib: /*#__PURE__*/ pako_zlib(Inflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n constructor() {\n this.version = VERSION;\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n // - A one-octet version number. The only currently defined value is 1.\n if (version !== VERSION) {\n throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);\n }\n\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n return util.concat([new Uint8Array([VERSION]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await this.crypt('decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await this.crypt('encrypt', key, data);\n }\n\n /**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\n async crypt(fn, key, data) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const modeInstance = await mode(this.cipherAlgorithm, key);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const adataBuffer = new ArrayBuffer(21);\n const adataArray = new Uint8Array(adataBuffer, 0, 13);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n const iv = this.iv;\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new stream.TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)\n cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = 3;\n\n this.publicKeyID = new KeyID();\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n i += this.publicKeyID.read(bytes.subarray(i));\n this.publicKeyAlgorithm = bytes[i++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);\n if (this.publicKeyAlgorithm === enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version]),\n this.publicKeyID.write(),\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n // v3 Montgomery curves have cleartext cipher algo\n if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = sessionKeyAlgorithm;\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // add checksum\n return util.concatUint8Array([\n new Uint8Array([cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n }\n case enums.publicKey.x25519:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n return {\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n * @private\n */\n\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport { UnsupportedError } from '../packet/packet';\nimport util from '../util';\n\nclass S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = 'iterated';\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n try {\n this.type = enums.read(enums.s2k, bytes[i++]);\n } catch (err) {\n throw new UnsupportedError('Unknown S2K type.');\n }\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport S2K from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 5 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = enums.symmetric.aes256;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number. The only currently defined version is 4.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version === 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n this.s2k = new S2K();\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version === 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, key);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n } else {\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const encryptionKey = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v5Keys ? 5 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes) {\n let pos = 0;\n // A one-octet version number (3, 4 or 5).\n this.version = bytes[pos++];\n\n if (this.version === 4 || this.version === 5) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version === 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version === 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n if (version === 5) {\n return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);\n }\n return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version === 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version === 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport S2K from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n this.s2k = new S2K();\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipher(this.symmetric).blockSize\n );\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n const cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...this.s2k.write());\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = new S2K(config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n\n const { blockSize } = crypto.getCipher(this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = enums.aead.eax;\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } else {\n this.s2kUsage = 254;\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\nasync function produceEncryptionKey(s2k, passphrase, algorithm) {\n const { keySize } = crypto.getCipher(algorithm);\n return s2k.produceKey(passphrase, keySize);\n}\n\nexport default SecretKeyPacket;\n","\n// email-addresses.js - RFC 5322 email address parser\n// v 3.1.0\n//\n// http://tools.ietf.org/html/rfc5322\n//\n// This library does not validate email addresses.\n// emailAddresses attempts to parse addresses using the (fairly liberal)\n// grammar specified in RFC 5322.\n//\n// email-addresses returns {\n// ast: ,\n// addresses: [{\n// node: ,\n// name: ,\n// address: ,\n// local: ,\n// domain: \n// }, ...]\n// }\n//\n// emailAddresses.parseOneAddress and emailAddresses.parseAddressList\n// work as you might expect. Try it out.\n//\n// Many thanks to Dominic Sayers and his documentation on the is_email function,\n// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.\n\n(function (global) {\n\"use strict\";\n\nfunction parse5322(opts) {\n\n // tokenizing functions\n\n function inStr() { return pos < len; }\n function curTok() { return parseString[pos]; }\n function getPos() { return pos; }\n function setPos(i) { pos = i; }\n function nextTok() { pos += 1; }\n function initialize() {\n pos = 0;\n len = parseString.length;\n }\n\n // parser helper functions\n\n function o(name, value) {\n return {\n name: name,\n tokens: value || \"\",\n semantic: value || \"\",\n children: []\n };\n }\n\n function wrap(name, ast) {\n var n;\n if (ast === null) { return null; }\n n = o(name);\n n.tokens = ast.tokens;\n n.semantic = ast.semantic;\n n.children.push(ast);\n return n;\n }\n\n function add(parent, child) {\n if (child !== null) {\n parent.tokens += child.tokens;\n parent.semantic += child.semantic;\n }\n parent.children.push(child);\n return parent;\n }\n\n function compareToken(fxnCompare) {\n var tok;\n if (!inStr()) { return null; }\n tok = curTok();\n if (fxnCompare(tok)) {\n nextTok();\n return o('token', tok);\n }\n return null;\n }\n\n function literal(lit) {\n return function literalFunc() {\n return wrap('literal', compareToken(function (tok) {\n return tok === lit;\n }));\n };\n }\n\n function and() {\n var args = arguments;\n return function andFunc() {\n var i, s, result, start;\n start = getPos();\n s = o('and');\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result === null) {\n setPos(start);\n return null;\n }\n add(s, result);\n }\n return s;\n };\n }\n\n function or() {\n var args = arguments;\n return function orFunc() {\n var i, result, start;\n start = getPos();\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result !== null) {\n return result;\n }\n setPos(start);\n }\n return null;\n };\n }\n\n function opt(prod) {\n return function optFunc() {\n var result, start;\n start = getPos();\n result = prod();\n if (result !== null) {\n return result;\n }\n else {\n setPos(start);\n return o('opt');\n }\n };\n }\n\n function invis(prod) {\n return function invisFunc() {\n var result = prod();\n if (result !== null) {\n result.semantic = \"\";\n }\n return result;\n };\n }\n\n function colwsp(prod) {\n return function collapseSemanticWhitespace() {\n var result = prod();\n if (result !== null && result.semantic.length > 0) {\n result.semantic = \" \";\n }\n return result;\n };\n }\n\n function star(prod, minimum) {\n return function starFunc() {\n var s, result, count, start, min;\n start = getPos();\n s = o('star');\n count = 0;\n min = minimum === undefined ? 0 : minimum;\n while ((result = prod()) !== null) {\n count = count + 1;\n add(s, result);\n }\n if (count >= min) {\n return s;\n }\n else {\n setPos(start);\n return null;\n }\n };\n }\n\n // One expects names to get normalized like this:\n // \" First Last \" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n function collapseWhitespace(s) {\n return s.replace(/([ \\t]|\\r\\n)+/g, ' ').replace(/^\\s*/, '').replace(/\\s*$/, '');\n }\n\n // UTF-8 pseudo-production (RFC 6532)\n // RFC 6532 extends RFC 5322 productions to include UTF-8\n // using the following productions:\n // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4\n // UTF8-2 = \n // UTF8-3 = \n // UTF8-4 = \n //\n // For reference, the extended RFC 5322 productions are:\n // VCHAR =/ UTF8-non-ascii\n // ctext =/ UTF8-non-ascii\n // atext =/ UTF8-non-ascii\n // qtext =/ UTF8-non-ascii\n // dtext =/ UTF8-non-ascii\n function isUTF8NonAscii(tok) {\n // In JavaScript, we just deal directly with Unicode code points,\n // so we aren't checking individual bytes for UTF-8 encoding.\n // Just check that the character is non-ascii.\n return tok.charCodeAt(0) >= 128;\n }\n\n\n // common productions (RFC 5234)\n // http://tools.ietf.org/html/rfc5234\n // B.1. Core Rules\n\n // CR = %x0D\n // ; carriage return\n function cr() { return wrap('cr', literal('\\r')()); }\n\n // CRLF = CR LF\n // ; Internet standard newline\n function crlf() { return wrap('crlf', and(cr, lf)()); }\n\n // DQUOTE = %x22\n // ; \" (Double Quote)\n function dquote() { return wrap('dquote', literal('\"')()); }\n\n // HTAB = %x09\n // ; horizontal tab\n function htab() { return wrap('htab', literal('\\t')()); }\n\n // LF = %x0A\n // ; linefeed\n function lf() { return wrap('lf', literal('\\n')()); }\n\n // SP = %x20\n function sp() { return wrap('sp', literal(' ')()); }\n\n // VCHAR = %x21-7E\n // ; visible (printing) characters\n function vchar() {\n return wrap('vchar', compareToken(function vcharFunc(tok) {\n var code = tok.charCodeAt(0);\n var accept = (0x21 <= code && code <= 0x7E);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // WSP = SP / HTAB\n // ; white space\n function wsp() { return wrap('wsp', or(sp, htab)()); }\n\n\n // email productions (RFC 5322)\n // http://tools.ietf.org/html/rfc5322\n // 3.2.1. Quoted characters\n\n // quoted-pair = (\"\\\" (VCHAR / WSP)) / obs-qp\n function quotedPair() {\n var qp = wrap('quoted-pair',\n or(\n and(literal('\\\\'), or(vchar, wsp)),\n obsQP\n )());\n if (qp === null) { return null; }\n // a quoted pair will be two characters, and the \"\\\" character\n // should be semantically \"invisible\" (RFC 5322 3.2.1)\n qp.semantic = qp.semantic[1];\n return qp;\n }\n\n // 3.2.2. Folding White Space and Comments\n\n // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS\n function fws() {\n return wrap('fws', or(\n obsFws,\n and(\n opt(and(\n star(wsp),\n invis(crlf)\n )),\n star(wsp, 1)\n )\n )());\n }\n\n // ctext = %d33-39 / ; Printable US-ASCII\n // %d42-91 / ; characters not including\n // %d93-126 / ; \"(\", \")\", or \"\\\"\n // obs-ctext\n function ctext() {\n return wrap('ctext', or(\n function ctextFunc1() {\n return compareToken(function ctextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 39) ||\n (42 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsCtext\n )());\n }\n\n // ccontent = ctext / quoted-pair / comment\n function ccontent() {\n return wrap('ccontent', or(ctext, quotedPair, comment)());\n }\n\n // comment = \"(\" *([FWS] ccontent) [FWS] \")\"\n function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }\n\n // CFWS = (1*([FWS] comment) [FWS]) / FWS\n function cfws() {\n return wrap('cfws', or(\n and(\n star(\n and(opt(fws), comment),\n 1\n ),\n opt(fws)\n ),\n fws\n )());\n }\n\n // 3.2.3. Atom\n\n //atext = ALPHA / DIGIT / ; Printable US-ASCII\n // \"!\" / \"#\" / ; characters not including\n // \"$\" / \"%\" / ; specials. Used for atoms.\n // \"&\" / \"'\" /\n // \"*\" / \"+\" /\n // \"-\" / \"/\" /\n // \"=\" / \"?\" /\n // \"^\" / \"_\" /\n // \"`\" / \"{\" /\n // \"|\" / \"}\" /\n // \"~\"\n function atext() {\n return wrap('atext', compareToken(function atextFunc(tok) {\n var accept =\n ('a' <= tok && tok <= 'z') ||\n ('A' <= tok && tok <= 'Z') ||\n ('0' <= tok && tok <= '9') ||\n (['!', '#', '$', '%', '&', '\\'', '*', '+', '-', '/',\n '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // atom = [CFWS] 1*atext [CFWS]\n function atom() {\n return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());\n }\n\n // dot-atom-text = 1*atext *(\".\" 1*atext)\n function dotAtomText() {\n var s, maybeText;\n s = wrap('dot-atom-text', star(atext, 1)());\n if (s === null) { return s; }\n maybeText = star(and(literal('.'), star(atext, 1)))();\n if (maybeText !== null) {\n add(s, maybeText);\n }\n return s;\n }\n\n // dot-atom = [CFWS] dot-atom-text [CFWS]\n function dotAtom() {\n return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());\n }\n\n // 3.2.4. Quoted Strings\n\n // qtext = %d33 / ; Printable US-ASCII\n // %d35-91 / ; characters not including\n // %d93-126 / ; \"\\\" or the quote character\n // obs-qtext\n function qtext() {\n return wrap('qtext', or(\n function qtextFunc1() {\n return compareToken(function qtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 === code) ||\n (35 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsQtext\n )());\n }\n\n // qcontent = qtext / quoted-pair\n function qcontent() {\n return wrap('qcontent', or(qtext, quotedPair)());\n }\n\n // quoted-string = [CFWS]\n // DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n // [CFWS]\n function quotedString() {\n return wrap('quoted-string', and(\n invis(opt(cfws)),\n invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),\n invis(opt(cfws))\n )());\n }\n\n // 3.2.5 Miscellaneous Tokens\n\n // word = atom / quoted-string\n function word() {\n return wrap('word', or(atom, quotedString)());\n }\n\n // phrase = 1*word / obs-phrase\n function phrase() {\n return wrap('phrase', or(obsPhrase, star(word, 1))());\n }\n\n // 3.4. Address Specification\n // address = mailbox / group\n function address() {\n return wrap('address', or(mailbox, group)());\n }\n\n // mailbox = name-addr / addr-spec\n function mailbox() {\n return wrap('mailbox', or(nameAddr, addrSpec)());\n }\n\n // name-addr = [display-name] angle-addr\n function nameAddr() {\n return wrap('name-addr', and(opt(displayName), angleAddr)());\n }\n\n // angle-addr = [CFWS] \"<\" addr-spec \">\" [CFWS] /\n // obs-angle-addr\n function angleAddr() {\n return wrap('angle-addr', or(\n and(\n invis(opt(cfws)),\n literal('<'),\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n ),\n obsAngleAddr\n )());\n }\n\n // group = display-name \":\" [group-list] \";\" [CFWS]\n function group() {\n return wrap('group', and(\n displayName,\n literal(':'),\n opt(groupList),\n literal(';'),\n invis(opt(cfws))\n )());\n }\n\n // display-name = phrase\n function displayName() {\n return wrap('display-name', function phraseFixedSemantic() {\n var result = phrase();\n if (result !== null) {\n result.semantic = collapseWhitespace(result.semantic);\n }\n return result;\n }());\n }\n\n // mailbox-list = (mailbox *(\",\" mailbox)) / obs-mbox-list\n function mailboxList() {\n return wrap('mailbox-list', or(\n and(\n mailbox,\n star(and(literal(','), mailbox))\n ),\n obsMboxList\n )());\n }\n\n // address-list = (address *(\",\" address)) / obs-addr-list\n function addressList() {\n return wrap('address-list', or(\n and(\n address,\n star(and(literal(','), address))\n ),\n obsAddrList\n )());\n }\n\n // group-list = mailbox-list / CFWS / obs-group-list\n function groupList() {\n return wrap('group-list', or(\n mailboxList,\n invis(cfws),\n obsGroupList\n )());\n }\n\n // 3.4.1 Addr-Spec Specification\n\n // local-part = dot-atom / quoted-string / obs-local-part\n function localPart() {\n // note: quoted-string, dotAtom are proper subsets of obs-local-part\n // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree\n return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());\n }\n\n // dtext = %d33-90 / ; Printable US-ASCII\n // %d94-126 / ; characters not including\n // obs-dtext ; \"[\", \"]\", or \"\\\"\n function dtext() {\n return wrap('dtext', or(\n function dtextFunc1() {\n return compareToken(function dtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 90) ||\n (94 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsDtext\n )()\n );\n }\n\n // domain-literal = [CFWS] \"[\" *([FWS] dtext) [FWS] \"]\" [CFWS]\n function domainLiteral() {\n return wrap('domain-literal', and(\n invis(opt(cfws)),\n literal('['),\n star(and(opt(fws), dtext)),\n opt(fws),\n literal(']'),\n invis(opt(cfws))\n )());\n }\n\n // domain = dot-atom / domain-literal / obs-domain\n function domain() {\n return wrap('domain', function domainCheckTLD() {\n var result = or(obsDomain, dotAtom, domainLiteral)();\n if (opts.rejectTLD) {\n if (result && result.semantic && result.semantic.indexOf('.') < 0) {\n return null;\n }\n }\n // strip all whitespace from domains\n if (result) {\n result.semantic = result.semantic.replace(/\\s+/g, '');\n }\n return result;\n }());\n }\n\n // addr-spec = local-part \"@\" domain\n function addrSpec() {\n return wrap('addr-spec', and(\n localPart, literal('@'), domain\n )());\n }\n\n // 3.6.2 Originator Fields\n // Below we only parse the field body, not the name of the field\n // like \"From:\", \"Sender:\", or \"Reply-To:\". Other libraries that\n // parse email headers can parse those and defer to these productions\n // for the \"RFC 5322\" part.\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // from = \"From:\" (mailbox-list / address-list) CRLF\n function fromSpec() {\n return wrap('from', or(\n mailboxList,\n addressList\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // sender = \"Sender:\" (mailbox / address) CRLF\n function senderSpec() {\n return wrap('sender', or(\n mailbox,\n address\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // reply-to = \"Reply-To:\" address-list CRLF\n function replyToSpec() {\n return wrap('reply-to', addressList());\n }\n\n // 4.1. Miscellaneous Obsolete Tokens\n\n // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control\n // %d11 / ; characters that do not\n // %d12 / ; include the carriage\n // %d14-31 / ; return, line feed, and\n // %d127 ; white space characters\n function obsNoWsCtl() {\n return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {\n var code = tok.charCodeAt(0);\n return ((1 <= code && code <= 8) ||\n (11 === code || 12 === code) ||\n (14 <= code && code <= 31) ||\n (127 === code));\n }));\n }\n\n // obs-ctext = obs-NO-WS-CTL\n function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }\n\n // obs-qtext = obs-NO-WS-CTL\n function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }\n\n // obs-qp = \"\\\" (%d0 / obs-NO-WS-CTL / LF / CR)\n function obsQP() {\n return opts.strict ? null : wrap('obs-qp', and(\n literal('\\\\'),\n or(literal('\\0'), obsNoWsCtl, lf, cr)\n )());\n }\n\n // obs-phrase = word *(word / \".\" / CFWS)\n function obsPhrase() {\n if (opts.strict ) return null;\n return opts.atInDisplayName ? wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), literal('@'), colwsp(cfws)))\n )()) :\n wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), colwsp(cfws)))\n )());\n }\n\n // 4.2. Obsolete Folding White Space\n\n // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908\n // obs-FWS = 1*([CRLF] WSP)\n function obsFws() {\n return opts.strict ? null : wrap('obs-FWS', star(\n and(invis(opt(crlf)), wsp),\n 1\n )());\n }\n\n // 4.4. Obsolete Addressing\n\n // obs-angle-addr = [CFWS] \"<\" obs-route addr-spec \">\" [CFWS]\n function obsAngleAddr() {\n return opts.strict ? null : wrap('obs-angle-addr', and(\n invis(opt(cfws)),\n literal('<'),\n obsRoute,\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n )());\n }\n\n // obs-route = obs-domain-list \":\"\n function obsRoute() {\n return opts.strict ? null : wrap('obs-route', and(\n obsDomainList,\n literal(':')\n )());\n }\n\n // obs-domain-list = *(CFWS / \",\") \"@\" domain\n // *(\",\" [CFWS] [\"@\" domain])\n function obsDomainList() {\n return opts.strict ? null : wrap('obs-domain-list', and(\n star(or(invis(cfws), literal(','))),\n literal('@'),\n domain,\n star(and(\n literal(','),\n invis(opt(cfws)),\n opt(and(literal('@'), domain))\n ))\n )());\n }\n\n // obs-mbox-list = *([CFWS] \",\") mailbox *(\",\" [mailbox / CFWS])\n function obsMboxList() {\n return opts.strict ? null : wrap('obs-mbox-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n mailbox,\n star(and(\n literal(','),\n opt(and(\n mailbox,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-addr-list = *([CFWS] \",\") address *(\",\" [address / CFWS])\n function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n address,\n star(and(\n literal(','),\n opt(and(\n address,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-group-list = 1*([CFWS] \",\") [CFWS]\n function obsGroupList() {\n return opts.strict ? null : wrap('obs-group-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n ), 1),\n invis(opt(cfws))\n )());\n }\n\n // obs-local-part = word *(\".\" word)\n function obsLocalPart() {\n return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());\n }\n\n // obs-domain = atom *(\".\" atom)\n function obsDomain() {\n return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());\n }\n\n // obs-dtext = obs-NO-WS-CTL / quoted-pair\n function obsDtext() {\n return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());\n }\n\n /////////////////////////////////////////////////////\n\n // ast analysis\n\n function findNode(name, root) {\n var i, stack, node;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n return node;\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return null;\n }\n\n function findAllNodes(name, root) {\n var i, stack, node, result;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n result.push(node);\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return result;\n }\n\n function findAllNodesNoChildren(names, root) {\n var i, stack, node, result, namesLookup;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n namesLookup = {};\n for (i = 0; i < names.length; i += 1) {\n namesLookup[names[i]] = true;\n }\n\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name in namesLookup) {\n result.push(node);\n // don't look at children (hence findAllNodesNoChildren)\n } else {\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n }\n return result;\n }\n\n function giveResult(ast) {\n var addresses, groupsAndMailboxes, i, groupOrMailbox, result;\n if (ast === null) {\n return null;\n }\n addresses = [];\n\n // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.\n groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);\n for (i = 0; i < groupsAndMailboxes.length; i += 1) {\n groupOrMailbox = groupsAndMailboxes[i];\n if (groupOrMailbox.name === 'group') {\n addresses.push(giveResultGroup(groupOrMailbox));\n } else if (groupOrMailbox.name === 'mailbox') {\n addresses.push(giveResultMailbox(groupOrMailbox));\n }\n }\n\n result = {\n ast: ast,\n addresses: addresses,\n };\n if (opts.simple) {\n result = simplifyResult(result);\n }\n if (opts.oneResult) {\n return oneResult(result);\n }\n if (opts.simple) {\n return result && result.addresses;\n } else {\n return result;\n }\n }\n\n function giveResultGroup(group) {\n var i;\n var groupName = findNode('display-name', group);\n var groupResultMailboxes = [];\n var mailboxes = findAllNodesNoChildren(['mailbox'], group);\n for (i = 0; i < mailboxes.length; i += 1) {\n groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));\n }\n return {\n node: group,\n parts: {\n name: groupName,\n },\n type: group.name, // 'group'\n name: grabSemantic(groupName),\n addresses: groupResultMailboxes,\n };\n }\n\n function giveResultMailbox(mailbox) {\n var name = findNode('display-name', mailbox);\n var aspec = findNode('addr-spec', mailbox);\n var cfws = findAllNodes('cfws', mailbox);\n var comments = findAllNodesNoChildren(['comment'], mailbox);\n\n\n var local = findNode('local-part', aspec);\n var domain = findNode('domain', aspec);\n return {\n node: mailbox,\n parts: {\n name: name,\n address: aspec,\n local: local,\n domain: domain,\n comments: cfws\n },\n type: mailbox.name, // 'mailbox'\n name: grabSemantic(name),\n address: grabSemantic(aspec),\n local: grabSemantic(local),\n domain: grabSemantic(domain),\n comments: concatComments(comments),\n groupName: grabSemantic(mailbox.groupName),\n };\n }\n\n function grabSemantic(n) {\n return n !== null && n !== undefined ? n.semantic : null;\n }\n\n function simplifyResult(result) {\n var i;\n if (result && result.addresses) {\n for (i = 0; i < result.addresses.length; i += 1) {\n delete result.addresses[i].node;\n }\n }\n return result;\n }\n\n function concatComments(comments) {\n var result = '';\n if (comments) {\n for (var i = 0; i < comments.length; i += 1) {\n result += grabSemantic(comments[i]);\n }\n }\n return result;\n }\n\n function oneResult(result) {\n if (!result) { return null; }\n if (!opts.partial && result.addresses.length > 1) { return null; }\n return result.addresses && result.addresses[0];\n }\n\n /////////////////////////////////////////////////////\n\n var parseString, pos, len, parsed, startProduction;\n\n opts = handleOpts(opts, {});\n if (opts === null) { return null; }\n\n parseString = opts.input;\n\n startProduction = {\n 'address': address,\n 'address-list': addressList,\n 'angle-addr': angleAddr,\n 'from': fromSpec,\n 'group': group,\n 'mailbox': mailbox,\n 'mailbox-list': mailboxList,\n 'reply-to': replyToSpec,\n 'sender': senderSpec,\n }[opts.startAt] || addressList;\n\n if (!opts.strict) {\n initialize();\n opts.strict = true;\n parsed = startProduction(parseString);\n if (opts.partial || !inStr()) {\n return giveResult(parsed);\n }\n opts.strict = false;\n }\n\n initialize();\n parsed = startProduction(parseString);\n if (!opts.partial && inStr()) { return null; }\n return giveResult(parsed);\n}\n\nfunction parseOneAddressSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseAddressListSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseFromSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'from',\n }));\n}\n\nfunction parseSenderSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'sender',\n }));\n}\n\nfunction parseReplyToSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'reply-to',\n }));\n}\n\nfunction handleOpts(opts, defs) {\n function isString(str) {\n return Object.prototype.toString.call(str) === '[object String]';\n }\n\n function isObject(o) {\n return o === Object(o);\n }\n\n function isNullUndef(o) {\n return o === null || o === undefined;\n }\n\n var defaults, o;\n\n if (isString(opts)) {\n opts = { input: opts };\n } else if (!isObject(opts)) {\n return null;\n }\n\n if (!isString(opts.input)) { return null; }\n if (!defs) { return null; }\n\n defaults = {\n oneResult: false,\n partial: false,\n rejectTLD: false,\n rfc6532: false,\n simple: false,\n startAt: 'address-list',\n strict: false,\n atInDisplayName: false\n };\n\n for (o in defaults) {\n if (isNullUndef(opts[o])) {\n opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];\n }\n }\n return opts;\n}\n\nparse5322.parseOneAddress = parseOneAddressSimple;\nparse5322.parseAddressList = parseAddressListSimple;\nparse5322.parseFrom = parseFromSimple;\nparse5322.parseSender = parseSenderSimple;\nparse5322.parseReplyTo = parseReplyToSimple;\n\nif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = parse5322;\n} else {\n global.emailAddresses = parse5322;\n}\n\n}(this));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport emailAddresses from 'email-addresses';\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n try {\n const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });\n this.comment = comments.replace(/^\\(|\\)$/g, '');\n this.name = name;\n this.email = email;\n } catch (e) {}\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n * @private\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm of a key\n * @param {Key} [key] - The key to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) {\n let hashAlgo = config.preferredHashAlgorithm;\n let prefAlgo = hashAlgo;\n if (key) {\n const primaryUser = await key.getPrimaryUser(date, userID, config);\n if (primaryUser.selfCertification.preferredHashAlgorithms) {\n [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;\n hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n }\n }\n switch (keyPacket.algorithm) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n prefAlgo = crypto.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);\n }\n return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n}\n\n/**\n * Returns the preferred symmetric/aead/compression algorithm for a set of keys\n * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred algorithm\n * @async\n */\nexport async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = { // these are all must-implement in rfc4880bis\n 'symmetric': enums.symmetric.aes128,\n 'aead': enums.aead.eax,\n 'compression': enums.compression.uncompressed\n }[type];\n const preferredSenderAlgo = {\n 'symmetric': config.preferredSymmetricAlgorithm,\n 'aead': config.preferredAEADAlgorithm,\n 'compression': config.preferredCompressionAlgorithm\n }[type];\n const prefPropertyName = {\n 'symmetric': 'preferredSymmetricAlgorithms',\n 'aead': 'preferredAEADAlgorithms',\n 'compression': 'preferredCompressionAlgorithms'\n }[type];\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n const recipientPrefs = primaryUser.selfCertification[prefPropertyName];\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {PrivateKey} privateKey - key to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config);\n signaturePacket.rawNotations = notations;\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n await revocationSignature.verify(\n key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\n/**\n * Returns whether aead is supported by all keys in the set\n * @param {Array} keys - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {\n let supported = true;\n // TODO replace when Promise.some or Promise.any are implemented\n await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n if (!primaryUser.selfCertification.features ||\n !(primaryUser.selfCertification.features[0] & enums.features.aead)) {\n supported = false;\n }\n }));\n return supported;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc':\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function isValidSigningKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.rsaEncrypt &&\n keyAlgo !== enums.publicKey.elgamal &&\n keyAlgo !== enums.publicKey.ecdh &&\n keyAlgo !== enums.publicKey.x25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);\n}\n\nexport function isValidEncryptionKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.dsa &&\n keyAlgo !== enums.publicKey.rsaSign &&\n keyAlgo !== enums.publicKey.ecdsa &&\n keyAlgo !== enums.publicKey.eddsaLegacy &&\n keyAlgo !== enums.publicKey.ed25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);\n}\n\nexport function isValidDecryptionKeyPacket(signature, config) {\n if (config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n * @private\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n // check for expiration time in direct signatures\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const { selfCertification } = await this.getPrimaryUser(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidDecryptionKeyPacket(bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {}\n }\n }\n\n // evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&\n helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {\n keys.push(this);\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n const keyPacket = await helper.generateSecretSubkey(options);\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {};\n dataToSign.userID = userIDPacket;\n dataToSign.key = secretKeyPacket;\n\n const signatureProperties = {};\n signatureProperties.signatureType = enums.signature.certGeneric;\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128,\n enums.symmetric.aes192\n ], config.preferredSymmetricAlgorithm);\n if (config.aeadProtect) {\n signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.zlib,\n enums.compression.zip,\n enums.compression.uncompressed\n ], config.preferredCompressionAlgorithm);\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.aead;\n }\n if (config.v5Keys) {\n signatureProperties.features[0] |= enums.features.v5Keys;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return createKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No secret key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport KeyID from './type/keyid';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);\n\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || !util.isString(algorithmName)) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.\n if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n // do not check key expiration to allow decryption of old messages\n const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {\n return;\n }\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);\n const algorithmName = enums.read(enums.symmetric, algo);\n const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?\n enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :\n undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(algo);\n return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n let symEncryptedPacket;\n if (aeadAlgorithmName) {\n symEncryptedPacket = new AEADEncryptedDataPacket();\n symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);\n } else {\n symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();\n }\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const algorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();\n pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();\n pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;\n pkESKeyPacket.sessionKey = sessionKey;\n pkESKeyPacket.sessionKeyAlgorithm = algorithm;\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n let i;\n let existingSigPacketlist;\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n if (signature) {\n existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n for (i = existingSigPacketlist.length - 1; i >= 0; i--) {\n const signaturePacket = existingSigPacketlist[i];\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n if (!signingKeys.length && i === 0) {\n onePassSig.flags = 1;\n }\n packetlist.push(onePassSig);\n }\n }\n\n await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];\n const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signatureType;\n onePassSig.hashAlgorithm = await getPreferredHashAlgo(primaryKey, signingKey.keyPacket, date, userIDs, config);\n onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;\n onePassSig.issuerKeyID = signingKey.getKeyID();\n if (i === signingKeys.length - 1) {\n onePassSig.flags = 1;\n }\n return onePassSig;\n })).then(onePassSignatureList => {\n onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));\n });\n\n packetlist.push(literalDataPacket);\n packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config)));\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.message, this.write(), null, null, null, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const userID = userIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);\n return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n let input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} privateKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n let hashes = this.signature.packets.map(function(packet) {\n return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();\n });\n hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });\n const body = {\n hash: hashes.join(),\n text: this.text,\n data: this.signature.packets.write()\n };\n return armor(enums.armor.signed, body, undefined, undefined, undefined, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n let oneHeader = null;\n let hashAlgos = [];\n headers.forEach(function(header) {\n oneHeader = header.match(/^Hash: (.+)$/); // get header value\n if (oneHeader) {\n oneHeader = oneHeader[1].replace(/\\s/g, ''); // remove whitespace\n oneHeader = oneHeader.split(',');\n oneHeader = oneHeader.map(function(hash) {\n hash = hash.toLowerCase();\n try {\n return enums.write(enums.hash, hash);\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hash);\n }\n });\n hashAlgos = hashAlgos.concat(oneHeader);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {\n throw new Error('If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed');\n } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:\n * curve25519 (default), p256, p384, p521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key generation');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key reformat');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n const streaming = message.fromStream;\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return convertStream(data, streaming, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type\n * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data, streaming, encoding = 'utf8') {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n if (streaming === 'node') {\n data = stream.webToNode(data);\n if (encoding !== 'binary') data.setEncoding(encoding);\n return data;\n }\n if (streaming === 'web' && streamType === 'ponyfill') {\n return stream.toNativeReadable(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","/**\n * web-streams-polyfill v3.0.3\n */\n/// \nconst SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})`;\n\n/// \nfunction noop() {\n return undefined;\n}\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n }\n else if (typeof window !== 'undefined') {\n return window;\n }\n else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\nconst globals = getGlobals();\n\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nconst rethrowAssertionErrorRejection = noop;\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\nfunction newPromise(executor) {\n return new originalPromise(executor);\n}\nfunction promiseResolvedWith(value) {\n return originalPromiseResolve(value);\n}\nfunction promiseRejectedWith(reason) {\n return originalPromiseReject(reason);\n}\nfunction PerformPromiseThen(promise, onFulfilled, onRejected) {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected);\n}\nfunction uponPromise(promise, onFulfilled, onRejected) {\n PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);\n}\nfunction uponFulfillment(promise, onFulfilled) {\n uponPromise(promise, onFulfilled);\n}\nfunction uponRejection(promise, onRejected) {\n uponPromise(promise, undefined, onRejected);\n}\nfunction transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\nfunction setPromiseIsHandledToTrue(promise) {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\nconst queueMicrotask = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn) => PerformPromiseThen(resolvedPromise, fn);\n})();\nfunction reflectCall(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\nfunction promiseCall(F, V, args) {\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n }\n catch (value) {\n return promiseRejectedWith(value);\n }\n}\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nclass SimpleQueue {\n constructor() {\n this._cursor = 0;\n this._size = 0;\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n get length() {\n return this._size;\n }\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback) {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n node = node._next;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n }\n else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n }\n else {\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n const stream = reader._ownerReadableStream;\n return ReadableStreamCancel(stream, reason);\n}\nfunction ReadableStreamReaderGenericRelease(reader) {\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n// Helper functions for the readers.\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\nfunction defaultReaderClosedPromiseResolve(reader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nconst AbortSteps = SymbolPolyfill('[[AbortSteps]]');\nconst ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');\nconst CancelSteps = SymbolPolyfill('[[CancelSteps]]');\nconst PullSteps = SymbolPolyfill('[[PullSteps]]');\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nfunction isDictionary(x) {\n return typeof x === 'object' || typeof x === 'function';\n}\nfunction assertDictionary(obj, context) {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-callback-functions\nfunction assertFunction(x, context) {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-object\nfunction isObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nfunction assertObject(x, context) {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\nfunction assertRequiredArgument(x, position, context) {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\nfunction assertRequiredField(x, field, context) {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nfunction convertUnrestrictedDouble(value) {\n return Number(value);\n}\nfunction censorNegativeZero(x) {\n return x === 0 ? 0 : x;\n}\nfunction integerPart(x) {\n return censorNegativeZero(MathTrunc(x));\n}\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nfunction convertUnsignedLongLongWithEnforceRange(value, context) {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n let x = Number(value);\n x = censorNegativeZero(x);\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n x = integerPart(x);\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n return x;\n}\n\nfunction assertReadableStream(x, context) {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadRequest(stream, readRequest) {\n stream._reader._readRequests.push(readRequest);\n}\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readRequest = reader._readRequests.shift();\n if (done) {\n readRequest._closeSteps();\n }\n else {\n readRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\nfunction ReadableStreamHasDefaultReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamDefaultReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultReaderRead(reader, readRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n }\n else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n }\n else {\n stream._readableStreamController[PullSteps](readRequest);\n }\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n\n/// \nlet AsyncIteratorPrototype;\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolPolyfill.asyncIterator]() {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });\n}\n\n/// \nclass ReadableStreamAsyncIteratorImpl {\n constructor(reader, preventCancel) {\n this._ongoingPromise = undefined;\n this._isFinished = false;\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n next() {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n return(value) {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n _nextSteps() {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n _returnSteps(value) {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\nconst ReadableStreamAsyncIteratorPrototype = {\n next() {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n return(value) {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n};\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamAsyncIterator(stream, preventCancel) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\nfunction IsReadableStreamAsyncIterator(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n return true;\n}\n// Helper functions for the ReadableStream.\nfunction streamAsyncIteratorBrandCheckException(name) {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nfunction IsFiniteNonNegativeNumber(v) {\n if (!IsNonNegativeNumber(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n return true;\n}\nfunction IsNonNegativeNumber(v) {\n if (typeof v !== 'number') {\n return false;\n }\n if (NumberIsNaN(v)) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n return true;\n}\n\nfunction DequeueValue(container) {\n const pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n return pair.value;\n}\nfunction EnqueueValueWithSize(container, value, size) {\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\nfunction PeekQueueValue(container) {\n const pair = container._queue.peek();\n return pair.value;\n}\nfunction ResetQueue(container) {\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n\nfunction CreateArrayFromList(elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n}\nfunction CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n// Not implemented correctly\nfunction TransferArrayBuffer(O) {\n return O;\n}\n// Not implemented correctly\nfunction IsDetachedBuffer(O) {\n return false;\n}\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nclass ReadableStreamBYOBRequest {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view() {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n return this._view;\n }\n respond(bytesWritten) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n if (IsDetachedBuffer(this._view.buffer)) ;\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n respondWithNewView(view) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n if (view.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (view.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableByteStreamController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n if (this._byobRequest === null && this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, this, view);\n this._byobRequest = byobRequest;\n }\n return this._byobRequest;\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n ReadableByteStreamControllerClose(this);\n }\n enqueue(chunk) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n ReadableByteStreamControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n if (this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n firstDescriptor.bytesFilled = 0;\n }\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableByteStream;\n if (this._queueTotalSize > 0) {\n const entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n ReadableByteStreamControllerHandleQueueDrain(this);\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view);\n return;\n }\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n }\n catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n const pullIntoDescriptor = {\n buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableByteStreamController.\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n return true;\n}\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableByteStreamControllerError(controller, e);\n });\n}\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n let done = false;\n if (stream._state === 'closed') {\n done = true;\n }\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n }\n else {\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n const queue = controller._queue;\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n }\n else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n return ready;\n}\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n }\n else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === null) {\n return;\n }\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = null;\n controller._byobRequest = null;\n}\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {\n const stream = controller._controlledReadableByteStream;\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n const ctor = view.constructor;\n const buffer = TransferArrayBuffer(view.buffer);\n const pullIntoDescriptor = {\n buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n ReadableByteStreamControllerHandleQueueDrain(controller);\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n controller._pendingPullIntos.push(pullIntoDescriptor);\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n }\n else {\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n const descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return false;\n }\n if (controller._closeRequested) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableByteStreamControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n}\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\nfunction ReadableByteStreamControllerClose(controller) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n return;\n }\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n throw e;\n }\n }\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n const transferredBuffer = TransferArrayBuffer(buffer);\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n else {\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n }\n else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n }\n else {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerError(controller, e) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return;\n }\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableByteStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (!IsFiniteNonNegativeNumber(bytesWritten)) {\n throw new RangeError('bytesWritten must be a finite');\n }\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n firstDescriptor.buffer = view.buffer;\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\nfunction SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {\n controller._controlledReadableByteStream = stream;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._byobRequest = null;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._closeRequested = false;\n controller._started = false;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n controller._pendingPullIntos = new SimpleQueue();\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableByteStreamControllerError(controller, r);\n });\n}\nfunction SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {\n const controller = Object.create(ReadableByteStreamController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel(reason);\n }\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);\n}\nfunction SetUpReadableStreamBYOBRequest(request, controller, view) {\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n// Helper functions for the ReadableStreamBYOBRequest.\nfunction byobRequestBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n// Helper functions for the ReadableByteStreamController.\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {\n stream._reader._readIntoRequests.push(readIntoRequest);\n}\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readIntoRequest = reader._readIntoRequests.shift();\n if (done) {\n readIntoRequest._closeSteps(chunk);\n }\n else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\nfunction ReadableStreamHasBYOBReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamBYOBReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readIntoRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n }\n else {\n ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);\n }\n}\n// Helper functions for the ReadableStreamBYOBReader.\nfunction byobReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n\nfunction ExtractHighWaterMark(strategy, defaultHWM) {\n const { highWaterMark } = strategy;\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n return highWaterMark;\n}\nfunction ExtractSizeAlgorithm(strategy) {\n const { size } = strategy;\n if (!size) {\n return () => 1;\n }\n return size;\n}\n\nfunction convertQueuingStrategy(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n const size = init === null || init === void 0 ? void 0 : init.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\nfunction convertQueuingStrategySize(fn, context) {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n\nfunction convertUnderlyingSink(original, context) {\n assertDictionary(original, context);\n const abort = original === null || original === void 0 ? void 0 : original.abort;\n const close = original === null || original === void 0 ? void 0 : original.close;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n const write = original === null || original === void 0 ? void 0 : original.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),\n type\n };\n}\nfunction convertUnderlyingSinkAbortCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSinkCloseCallback(fn, original, context) {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\nfunction convertUnderlyingSinkStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSinkWriteCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction assertWritableStream(x, context) {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n constructor(rawUnderlyingSink = {}, rawStrategy = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n }\n else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n InitializeWritableStream(this);\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('locked');\n }\n return IsWritableStreamLocked(this);\n }\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason = undefined) {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('abort'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n return WritableStreamAbort(this, reason);\n }\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('close'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamClose(this);\n }\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('getWriter');\n }\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n// Abstract operations for the WritableStream.\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n const controller = Object.create(WritableStreamDefaultController.prototype);\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeWritableStream(stream) {\n stream._state = 'writable';\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n stream._writer = undefined;\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined;\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsWritableStreamLocked(stream) {\n if (stream._writer === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamAbort(stream, reason) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest._promise = promise;\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n return promise;\n}\nfunction WritableStreamClose(stream) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n const promise = newPromise((resolve, reject) => {\n const closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._closeRequest = closeRequest;\n });\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n return promise;\n}\n// WritableStream API exposed for controllers.\nfunction WritableStreamAddWriteRequest(stream) {\n const promise = newPromise((resolve, reject) => {\n const writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._writeRequests.push(writeRequest);\n });\n return promise;\n}\nfunction WritableStreamDealWithRejection(stream, error) {\n const state = stream._state;\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n WritableStreamFinishErroring(stream);\n}\nfunction WritableStreamStartErroring(stream, reason) {\n const controller = stream._writableStreamController;\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\nfunction WritableStreamFinishErroring(stream) {\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(promise, () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, (reason) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\nfunction WritableStreamFinishInFlightWrite(stream) {\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n WritableStreamDealWithRejection(stream, error);\n}\nfunction WritableStreamFinishInFlightClose(stream) {\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n const state = stream._state;\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n stream._state = 'closed';\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n}\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n if (stream._closeRequest !== undefined) {\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n }\n else {\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n stream._backpressure = backpressure;\n}\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nclass WritableStreamDefaultWriter {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n this._ownerWritableStream = stream;\n stream._writer = this;\n const state = stream._state;\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n }\n else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n }\n else {\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n return this._readyPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamDefaultWriterClose(this);\n }\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return;\n }\n WritableStreamDefaultWriterRelease(this);\n }\n write(chunk = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n// Abstract operations for the WritableStreamDefaultWriter.\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n return true;\n}\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n const stream = writer._ownerWritableStream;\n return WritableStreamAbort(stream, reason);\n}\nfunction WritableStreamDefaultWriterClose(writer) {\n const stream = writer._ownerWritableStream;\n return WritableStreamClose(stream);\n}\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n return WritableStreamDefaultWriterClose(writer);\n}\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n }\n else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n }\n else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\nfunction WritableStreamDefaultWriterRelease(writer) {\n const stream = writer._ownerWritableStream;\n const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n const stream = writer._ownerWritableStream;\n const controller = stream._writableStreamController;\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n const promise = WritableStreamAddWriteRequest(stream);\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n return promise;\n}\nconst closeSentinel = {};\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nclass WritableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e = undefined) {\n if (!IsWritableStreamDefaultController(this)) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n WritableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [AbortSteps](reason) {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n error: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations implementing interface required by the WritableStream.\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(startPromise, () => {\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, r => {\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n });\n}\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let writeAlgorithm = () => promiseResolvedWith(undefined);\n let closeAlgorithm = () => promiseResolvedWith(undefined);\n let abortAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort(reason);\n }\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller) {\n controller._writeAlgorithm = undefined;\n controller._closeAlgorithm = undefined;\n controller._abortAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n try {\n return controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n// Abstract operations for the WritableStreamDefaultController.\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n const stream = controller._controlledWritableStream;\n if (!controller._started) {\n return;\n }\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n const state = stream._state;\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n if (controller._queue.length === 0) {\n return;\n }\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n }\n else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkCloseRequestInFlight(stream);\n DequeueValue(controller);\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(sinkClosePromise, () => {\n WritableStreamFinishInFlightClose(stream);\n }, reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(sinkWritePromise, () => {\n WritableStreamFinishInFlightWrite(stream);\n const state = stream._state;\n DequeueValue(controller);\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\nfunction WritableStreamDefaultControllerError(controller, error) {\n const stream = controller._controlledWritableStream;\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n// Helper functions for the WritableStream.\nfunction streamBrandCheckException$2(name) {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n// Helper functions for the WritableStreamDefaultWriter.\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterClosedPromiseResolve(writer) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\nfunction defaultWriterReadyPromiseReset(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n}\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterReadyPromiseResolve(writer) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction isAbortSignal(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof value.aborted === 'boolean';\n }\n catch (_a) {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/// \nconst NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;\n\n/// \nfunction isDOMExceptionConstructor(ctor) {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new ctor();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createDOMExceptionPolyfill() {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(message, name) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n };\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n// eslint-disable-next-line no-redeclare\nconst DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nfunction ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n source._disturbed = true;\n let shuttingDown = false;\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n return newPromise((resolve, reject) => {\n let abortAlgorithm;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException$1('Aborted', 'AbortError');\n const actions = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n signal.addEventListener('abort', abortAlgorithm);\n }\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done) {\n if (done) {\n resolveLoop();\n }\n else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n next(false);\n });\n }\n function pipeStep() {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(reader, {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n });\n });\n });\n }\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n }\n else {\n shutdown();\n }\n });\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n }\n else {\n shutdown(true, destClosed);\n }\n }\n setPromiseIsHandledToTrue(pipeLoop());\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);\n }\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n }\n else {\n uponRejection(promise, action);\n }\n }\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n }\n else {\n uponFulfillment(promise, action);\n }\n }\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n }\n else {\n doTheRest();\n }\n function doTheRest() {\n uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));\n }\n }\n function shutdown(isError, error) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n }\n else {\n finalize(isError, error);\n }\n }\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n }\n else {\n resolve(undefined);\n }\n }\n });\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('desiredSize');\n }\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('close');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n ReadableStreamDefaultControllerClose(this);\n }\n enqueue(chunk = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('enqueue');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('error');\n }\n ReadableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableStream;\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n }\n else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n readRequest._chunkSteps(chunk);\n }\n else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableStreamDefaultController.\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableStreamDefaultControllerError(controller, e);\n });\n}\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableStream;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\nfunction ReadableStreamDefaultControllerClose(controller) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n controller._closeRequested = true;\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n }\n else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\nfunction ReadableStreamDefaultControllerError(controller, e) {\n const stream = controller._controlledReadableStream;\n if (stream._state !== 'readable') {\n return;\n }\n ResetQueue(controller);\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\n// This is used in the implementation of TransformStream.\nfunction ReadableStreamDefaultControllerHasBackpressure(controller) {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {\n const state = controller._controlledReadableStream._state;\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n return false;\n}\nfunction SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledReadableStream = stream;\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableStreamDefaultControllerError(controller, r);\n });\n}\nfunction SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel(reason);\n }\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// Helper functions for the ReadableStreamDefaultController.\nfunction defaultControllerBrandCheckException$1(name) {\n return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let branch1;\n let branch2;\n let resolveCancelPromise;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n function pullAlgorithm() {\n if (reading) {\n return promiseResolvedWith(undefined);\n }\n reading = true;\n const readRequest = {\n _chunkSteps: value => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n reading = false;\n const value1 = value;\n const value2 = value;\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promiseResolvedWith(undefined);\n }\n function cancel1Algorithm(reason) {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function cancel2Algorithm(reason) {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function startAlgorithm() {\n // do nothing\n }\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n uponRejection(reader._closedPromise, (r) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n return [branch1, branch2];\n}\n\nfunction convertUnderlyingDefaultOrByteSource(source, context) {\n assertDictionary(source, context);\n const original = source;\n const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;\n const cancel = original === null || original === void 0 ? void 0 : original.cancel;\n const pull = original === null || original === void 0 ? void 0 : original.pull;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\nfunction convertUnderlyingSourceCancelCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSourcePullCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSourceStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertReadableStreamType(type, context) {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n\nfunction convertReaderOptions(options, context) {\n assertDictionary(options, context);\n const mode = options === null || options === void 0 ? void 0 : options.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\nfunction convertReadableStreamReaderMode(mode, context) {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nfunction convertIteratorOptions(options, context) {\n assertDictionary(options, context);\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n\nfunction convertPipeOptions(options, context) {\n assertDictionary(options, context);\n const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;\n const signal = options === null || options === void 0 ? void 0 : options.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\nfunction assertAbortSignal(signal, context) {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n\nfunction convertReadableWritablePair(pair, context) {\n assertDictionary(pair, context);\n const readable = pair === null || pair === void 0 ? void 0 : pair.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n const writable = pair === null || pair === void 0 ? void 0 : pair.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n return { readable, writable };\n}\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nclass ReadableStream {\n constructor(rawUnderlyingSource = {}, rawStrategy = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n }\n else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n InitializeReadableStream(this);\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);\n }\n else {\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);\n }\n }\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('locked');\n }\n return IsReadableStreamLocked(this);\n }\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason = undefined) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('cancel'));\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n return ReadableStreamCancel(this, reason);\n }\n getReader(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('getReader');\n }\n const options = convertReaderOptions(rawOptions, 'First parameter');\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n return AcquireReadableStreamBYOBReader(this);\n }\n pipeThrough(rawTransform, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n setPromiseIsHandledToTrue(promise);\n return transform.readable;\n }\n pipeTo(destination, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));\n }\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));\n }\n let options;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n }\n catch (e) {\n return promiseRejectedWith(e);\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n }\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('tee');\n }\n const branches = ReadableStreamTee(this);\n return CreateArrayFromList(branches);\n }\n values(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('values');\n }\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n}\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n// Abstract operations for the ReadableStream.\n// Throws if and only if startAlgorithm throws.\nfunction CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeReadableStream(stream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamLocked(stream) {\n if (stream._reader === undefined) {\n return false;\n }\n return true;\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n ReadableStreamClose(stream);\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\nfunction ReadableStreamClose(stream) {\n stream._state = 'closed';\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseResolve(reader);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\nfunction ReadableStreamError(stream, e) {\n stream._state = 'errored';\n stream._storedError = e;\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseReject(reader, e);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n reader._readRequests = new SimpleQueue();\n }\n else {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n// Helper functions for the ReadableStream.\nfunction streamBrandCheckException$1(name) {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n\nfunction convertQueuingStrategyInit(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n\nconst byteLengthSizeFunction = function size(chunk) {\n return chunk.byteLength;\n};\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nclass ByteLengthQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the ByteLengthQueuingStrategy.\nfunction byteLengthBrandCheckException(name) {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\nfunction IsByteLengthQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nconst countSizeFunction = function size() {\n return 1;\n};\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nclass CountQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the CountQueuingStrategy.\nfunction countBrandCheckException(name) {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\nfunction IsCountQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nfunction convertTransformer(original, context) {\n assertDictionary(original, context);\n const flush = original === null || original === void 0 ? void 0 : original.flush;\n const readableType = original === null || original === void 0 ? void 0 : original.readableType;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const transform = original === null || original === void 0 ? void 0 : original.transform;\n const writableType = original === null || original === void 0 ? void 0 : original.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),\n writableType\n };\n}\nfunction convertTransformerFlushCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertTransformerStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertTransformerTransformCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\n// Class TransformStream\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nclass TransformStream {\n constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n let startPromise_resolve;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n }\n else {\n startPromise_resolve(undefined);\n }\n }\n /**\n * The readable side of the transform stream.\n */\n get readable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n return this._readable;\n }\n /**\n * The writable side of the transform stream.\n */\n get writable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n return this._writable;\n }\n}\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\nfunction InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {\n function startAlgorithm() {\n return startPromise;\n }\n function writeAlgorithm(chunk) {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n function abortAlgorithm(reason) {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n function closeAlgorithm() {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);\n function pullAlgorithm() {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n function cancelAlgorithm(reason) {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined;\n stream._backpressureChangePromise = undefined;\n stream._backpressureChangePromise_resolve = undefined;\n TransformStreamSetBackpressure(stream, true);\n stream._transformStreamController = undefined;\n}\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n return true;\n}\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream, e) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\nfunction TransformStreamErrorWritableAndUnblockWrite(stream, e) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\nfunction TransformStreamSetBackpressure(stream, backpressure) {\n // Passes also when called during construction.\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n stream._backpressure = backpressure;\n}\n// Class TransformStreamDefaultController\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nclass TransformStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n enqueue(chunk = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n TransformStreamDefaultControllerError(this, reason);\n }\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n TransformStreamDefaultControllerTerminate(this);\n }\n}\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n// Transform Stream Default Controller Abstract Operations\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {\n const controller = Object.create(TransformStreamDefaultController.prototype);\n let transformAlgorithm = (chunk) => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk);\n return promiseResolvedWith(undefined);\n }\n catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n let flushAlgorithm = () => promiseResolvedWith(undefined);\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush(controller);\n }\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\nfunction TransformStreamDefaultControllerClearAlgorithms(controller) {\n controller._transformAlgorithm = undefined;\n controller._flushAlgorithm = undefined;\n}\nfunction TransformStreamDefaultControllerEnqueue(controller, chunk) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n }\n catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n throw stream._readable._storedError;\n }\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n TransformStreamSetBackpressure(stream, true);\n }\n}\nfunction TransformStreamDefaultControllerError(controller, e) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\nfunction TransformStreamDefaultControllerPerformTransform(controller, chunk) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\nfunction TransformStreamDefaultControllerTerminate(controller) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n ReadableStreamDefaultControllerClose(readableController);\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n// TransformStreamDefaultSink Algorithms\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {\n const controller = stream._transformStreamController;\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream) {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n// TransformStreamDefaultSource Algorithms\nfunction TransformStreamDefaultSourcePullAlgorithm(stream) {\n // Invariant. Enforced by the promises returned by start() and pull().\n TransformStreamSetBackpressure(stream, false);\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n// Helper functions for the TransformStreamDefaultController.\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n// Helper functions for the TransformStream.\nfunction streamBrandCheckException(name) {\n return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n\nexport { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };\n//# sourceMappingURL=ponyfill.es6.mjs.map\n","/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nfunction assert(test) {\n if (!test) {\n throw new TypeError('Assertion failed');\n }\n}\n\nfunction noop() {\n return;\n}\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nfunction isStreamConstructor(ctor) {\n if (typeof ctor !== 'function') {\n return false;\n }\n var startCalled = false;\n try {\n new ctor({\n start: function () {\n startCalled = true;\n }\n });\n }\n catch (e) {\n // ignore\n }\n return startCalled;\n}\nfunction isReadableStream(readable) {\n if (!typeIsObject(readable)) {\n return false;\n }\n if (typeof readable.getReader !== 'function') {\n return false;\n }\n return true;\n}\nfunction isReadableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isReadableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isWritableStream(writable) {\n if (!typeIsObject(writable)) {\n return false;\n }\n if (typeof writable.getWriter !== 'function') {\n return false;\n }\n return true;\n}\nfunction isWritableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isWritableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isTransformStream(transform) {\n if (!typeIsObject(transform)) {\n return false;\n }\n if (!isReadableStream(transform.readable)) {\n return false;\n }\n if (!isWritableStream(transform.writable)) {\n return false;\n }\n return true;\n}\nfunction isTransformStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isTransformStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction supportsByobReader(readable) {\n try {\n var reader = readable.getReader({ mode: 'byob' });\n reader.releaseLock();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction supportsByteSource(ctor) {\n try {\n new ctor({ type: 'bytes' });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\nfunction createReadableStreamWrapper(ctor) {\n assert(isReadableStreamConstructor(ctor));\n var byteSourceSupported = supportsByteSource(ctor);\n return function (readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n type = parseReadableType(type);\n if (type === 'bytes' && !byteSourceSupported) {\n type = undefined;\n }\n if (readable.constructor === ctor) {\n if (type !== 'bytes' || supportsByobReader(readable)) {\n return readable;\n }\n }\n if (type === 'bytes') {\n var source = createWrappingReadableSource(readable, { type: type });\n return new ctor(source);\n }\n else {\n var source = createWrappingReadableSource(readable);\n return new ctor(source);\n }\n };\n}\nfunction createWrappingReadableSource(readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n assert(isReadableStream(readable));\n assert(readable.locked === false);\n type = parseReadableType(type);\n var source;\n if (type === 'bytes') {\n source = new WrappingReadableByteStreamSource(readable);\n }\n else {\n source = new WrappingReadableStreamDefaultSource(readable);\n }\n return source;\n}\nfunction parseReadableType(type) {\n var typeString = String(type);\n if (typeString === 'bytes') {\n return typeString;\n }\n else if (type === undefined) {\n return type;\n }\n else {\n throw new RangeError('Invalid type is specified');\n }\n}\nvar AbstractWrappingReadableStreamSource = /** @class */ (function () {\n function AbstractWrappingReadableStreamSource(underlyingStream) {\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n this._readableStreamController = undefined;\n this._pendingRead = undefined;\n this._underlyingStream = underlyingStream;\n // always keep a reader attached to detect close/error\n this._attachDefaultReader();\n }\n AbstractWrappingReadableStreamSource.prototype.start = function (controller) {\n this._readableStreamController = controller;\n };\n AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {\n assert(this._underlyingReader !== undefined);\n return this._underlyingReader.cancel(reason);\n };\n AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {\n if (this._readerMode === \"default\" /* DEFAULT */) {\n return;\n }\n this._detachReader();\n var reader = this._underlyingStream.getReader();\n this._readerMode = \"default\" /* DEFAULT */;\n this._attachReader(reader);\n };\n AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {\n var _this = this;\n assert(this._underlyingReader === undefined);\n this._underlyingReader = reader;\n var closed = this._underlyingReader.closed;\n if (!closed) {\n return;\n }\n closed\n .then(function () { return _this._finishPendingRead(); })\n .then(function () {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.close();\n }\n }, function (reason) {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.error(reason);\n }\n })\n .catch(noop);\n };\n AbstractWrappingReadableStreamSource.prototype._detachReader = function () {\n if (this._underlyingReader === undefined) {\n return;\n }\n this._underlyingReader.releaseLock();\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n };\n AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {\n var _this = this;\n this._attachDefaultReader();\n // TODO Backpressure?\n var read = this._underlyingReader.read()\n .then(function (result) {\n var controller = _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n }\n else {\n controller.enqueue(result.value);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n AbstractWrappingReadableStreamSource.prototype._tryClose = function () {\n try {\n this._readableStreamController.close();\n }\n catch (_a) {\n // already errored or closed\n }\n };\n AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {\n var _this = this;\n var pendingRead;\n var finishRead = function () {\n if (_this._pendingRead === pendingRead) {\n _this._pendingRead = undefined;\n }\n };\n this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);\n };\n AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {\n var _this = this;\n if (!this._pendingRead) {\n return undefined;\n }\n var afterRead = function () { return _this._finishPendingRead(); };\n return this._pendingRead.then(afterRead, afterRead);\n };\n return AbstractWrappingReadableStreamSource;\n}());\nvar WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {\n __extends(WrappingReadableStreamDefaultSource, _super);\n function WrappingReadableStreamDefaultSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WrappingReadableStreamDefaultSource.prototype.pull = function () {\n return this._pullWithDefaultReader();\n };\n return WrappingReadableStreamDefaultSource;\n}(AbstractWrappingReadableStreamSource));\nfunction toUint8Array(view) {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\nfunction copyArrayBufferView(from, to) {\n var fromArray = toUint8Array(from);\n var toArray = toUint8Array(to);\n toArray.set(fromArray, 0);\n}\nvar WrappingReadableByteStreamSource = /** @class */ (function (_super) {\n __extends(WrappingReadableByteStreamSource, _super);\n function WrappingReadableByteStreamSource(underlyingStream) {\n var _this = this;\n var supportsByob = supportsByobReader(underlyingStream);\n _this = _super.call(this, underlyingStream) || this;\n _this._supportsByob = supportsByob;\n return _this;\n }\n Object.defineProperty(WrappingReadableByteStreamSource.prototype, \"type\", {\n get: function () {\n return 'bytes';\n },\n enumerable: false,\n configurable: true\n });\n WrappingReadableByteStreamSource.prototype._attachByobReader = function () {\n if (this._readerMode === \"byob\" /* BYOB */) {\n return;\n }\n assert(this._supportsByob);\n this._detachReader();\n var reader = this._underlyingStream.getReader({ mode: 'byob' });\n this._readerMode = \"byob\" /* BYOB */;\n this._attachReader(reader);\n };\n WrappingReadableByteStreamSource.prototype.pull = function () {\n if (this._supportsByob) {\n var byobRequest = this._readableStreamController.byobRequest;\n if (byobRequest) {\n return this._pullWithByobRequest(byobRequest);\n }\n }\n return this._pullWithDefaultReader();\n };\n WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {\n var _this = this;\n this._attachByobReader();\n // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly\n // create a separate buffer to read into, then copy that to byobRequest.view\n var buffer = new Uint8Array(byobRequest.view.byteLength);\n // TODO Backpressure?\n var read = this._underlyingReader.read(buffer)\n .then(function (result) {\n _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n byobRequest.respond(0);\n }\n else {\n copyArrayBufferView(result.value, byobRequest.view);\n byobRequest.respond(result.value.byteLength);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n return WrappingReadableByteStreamSource;\n}(AbstractWrappingReadableStreamSource));\n\nfunction createWritableStreamWrapper(ctor) {\n assert(isWritableStreamConstructor(ctor));\n return function (writable) {\n if (writable.constructor === ctor) {\n return writable;\n }\n var sink = createWrappingWritableSink(writable);\n return new ctor(sink);\n };\n}\nfunction createWrappingWritableSink(writable) {\n assert(isWritableStream(writable));\n assert(writable.locked === false);\n var writer = writable.getWriter();\n return new WrappingWritableStreamSink(writer);\n}\nvar WrappingWritableStreamSink = /** @class */ (function () {\n function WrappingWritableStreamSink(underlyingWriter) {\n var _this = this;\n this._writableStreamController = undefined;\n this._pendingWrite = undefined;\n this._state = \"writable\" /* WRITABLE */;\n this._storedError = undefined;\n this._underlyingWriter = underlyingWriter;\n this._errorPromise = new Promise(function (resolve, reject) {\n _this._errorPromiseReject = reject;\n });\n this._errorPromise.catch(noop);\n }\n WrappingWritableStreamSink.prototype.start = function (controller) {\n var _this = this;\n this._writableStreamController = controller;\n this._underlyingWriter.closed\n .then(function () {\n _this._state = \"closed\" /* CLOSED */;\n })\n .catch(function (reason) { return _this._finishErroring(reason); });\n };\n WrappingWritableStreamSink.prototype.write = function (chunk) {\n var _this = this;\n var writer = this._underlyingWriter;\n // Detect past errors\n if (writer.desiredSize === null) {\n return writer.ready;\n }\n var writeRequest = writer.write(chunk);\n // Detect future errors\n writeRequest.catch(function (reason) { return _this._finishErroring(reason); });\n writer.ready.catch(function (reason) { return _this._startErroring(reason); });\n // Reject write when errored\n var write = Promise.race([writeRequest, this._errorPromise]);\n this._setPendingWrite(write);\n return write;\n };\n WrappingWritableStreamSink.prototype.close = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return this._underlyingWriter.close();\n }\n return this._finishPendingWrite().then(function () { return _this.close(); });\n };\n WrappingWritableStreamSink.prototype.abort = function (reason) {\n if (this._state === \"errored\" /* ERRORED */) {\n return undefined;\n }\n var writer = this._underlyingWriter;\n return writer.abort(reason);\n };\n WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {\n var _this = this;\n var pendingWrite;\n var finishWrite = function () {\n if (_this._pendingWrite === pendingWrite) {\n _this._pendingWrite = undefined;\n }\n };\n this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);\n };\n WrappingWritableStreamSink.prototype._finishPendingWrite = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return Promise.resolve();\n }\n var afterWrite = function () { return _this._finishPendingWrite(); };\n return this._pendingWrite.then(afterWrite, afterWrite);\n };\n WrappingWritableStreamSink.prototype._startErroring = function (reason) {\n var _this = this;\n if (this._state === \"writable\" /* WRITABLE */) {\n this._state = \"erroring\" /* ERRORING */;\n this._storedError = reason;\n var afterWrite = function () { return _this._finishErroring(reason); };\n if (this._pendingWrite === undefined) {\n afterWrite();\n }\n else {\n this._finishPendingWrite().then(afterWrite, afterWrite);\n }\n this._writableStreamController.error(reason);\n }\n };\n WrappingWritableStreamSink.prototype._finishErroring = function (reason) {\n if (this._state === \"writable\" /* WRITABLE */) {\n this._startErroring(reason);\n }\n if (this._state === \"erroring\" /* ERRORING */) {\n this._state = \"errored\" /* ERRORED */;\n this._errorPromiseReject(this._storedError);\n }\n };\n return WrappingWritableStreamSink;\n}());\n\nfunction createTransformStreamWrapper(ctor) {\n assert(isTransformStreamConstructor(ctor));\n return function (transform) {\n if (transform.constructor === ctor) {\n return transform;\n }\n var transformer = createWrappingTransformer(transform);\n return new ctor(transformer);\n };\n}\nfunction createWrappingTransformer(transform) {\n assert(isTransformStream(transform));\n var readable = transform.readable, writable = transform.writable;\n assert(readable.locked === false);\n assert(writable.locked === false);\n var reader = readable.getReader();\n var writer;\n try {\n writer = writable.getWriter();\n }\n catch (e) {\n reader.releaseLock(); // do not leak reader\n throw e;\n }\n return new WrappingTransformStreamTransformer(reader, writer);\n}\nvar WrappingTransformStreamTransformer = /** @class */ (function () {\n function WrappingTransformStreamTransformer(reader, writer) {\n var _this = this;\n this._transformStreamController = undefined;\n this._onRead = function (result) {\n if (result.done) {\n return;\n }\n _this._transformStreamController.enqueue(result.value);\n return _this._reader.read().then(_this._onRead);\n };\n this._onError = function (reason) {\n _this._flushReject(reason);\n _this._transformStreamController.error(reason);\n _this._reader.cancel(reason).catch(noop);\n _this._writer.abort(reason).catch(noop);\n };\n this._onTerminate = function () {\n _this._flushResolve();\n _this._transformStreamController.terminate();\n var error = new TypeError('TransformStream terminated');\n _this._writer.abort(error).catch(noop);\n };\n this._reader = reader;\n this._writer = writer;\n this._flushPromise = new Promise(function (resolve, reject) {\n _this._flushResolve = resolve;\n _this._flushReject = reject;\n });\n }\n WrappingTransformStreamTransformer.prototype.start = function (controller) {\n this._transformStreamController = controller;\n this._reader.read()\n .then(this._onRead)\n .then(this._onTerminate, this._onError);\n var readerClosed = this._reader.closed;\n if (readerClosed) {\n readerClosed\n .then(this._onTerminate, this._onError);\n }\n };\n WrappingTransformStreamTransformer.prototype.transform = function (chunk) {\n return this._writer.write(chunk);\n };\n WrappingTransformStreamTransformer.prototype.flush = function () {\n var _this = this;\n return this._writer.close()\n .then(function () { return _this._flushPromise; });\n };\n return WrappingTransformStreamTransformer;\n}());\n\nexport { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper };\n//# sourceMappingURL=web-streams-adapter.mjs.map\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n r.strip();\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)\n * @module biginteger/bn\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n this.value = new BN(n);\n }\n\n clone() {\n const clone = new BigInteger(null);\n this.value.copy(clone.value);\n return clone;\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value.iadd(new BN(1));\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value.isub(new BN(1));\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value.iadd(x.value);\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value.isub(x.value);\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value.imul(x.value);\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value = this.value.umod(m.value);\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation\n * Much faster than this.exp(e).mod(n)\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n // We use either Montgomery or normal reduction context\n // Montgomery requires coprime n and R (montogmery multiplier)\n // bn.js picks R as power of 2, so n must be odd\n const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);\n const x = this.clone();\n x.value = x.value.toRed(nred).redPow(e.value).fromRed();\n return x;\n }\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n // invm returns a wrong result if the inverse does not exist\n if (!this.gcd(n).isOne()) {\n throw new Error('Inverse does not exist');\n }\n return new BigInteger(this.value.invm(n.value));\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} n - Operand\n * @returns {BigInteger} gcd\n */\n gcd(n) {\n return new BigInteger(this.value.gcd(n.value));\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value.ishln(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value.ishrn(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value.eq(x.value);\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value.lt(x.value);\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value.lte(x.value);\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value.gt(x.value);\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value.gte(x.value);\n }\n\n isZero() {\n return this.value.isZero();\n }\n\n isOne() {\n return this.value.eq(new BN(1));\n }\n\n isNegative() {\n return this.value.isNeg();\n }\n\n isEven() {\n return this.value.isEven();\n }\n\n abs() {\n const res = this.clone();\n res.value = res.value.abs();\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n return this.value.toNumber();\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n return this.value.testn(i) ? 1 : 0;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n return this.value.bitLength();\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n return this.value.byteLength();\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n return this.value.toArrayLike(Uint8Array, endian, length);\n }\n}\n","var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n","'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w) {\n var naf = [];\n var ws = 1 << (w + 1);\n var k = num.clone();\n while (k.cmpn(1) >= 0) {\n var z;\n if (k.isOdd()) {\n var mod = k.andln(ws - 1);\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n naf.push(z);\n\n // Optimization, shift by word if possible\n var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;\n for (var i = 1; i < shift; i++)\n naf.push(0);\n k.iushrn(shift);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n []\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n var m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n var m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n for (var j = 0; j < naf.length; j += doubles.step) {\n var nafW = 0;\n for (var k = j + doubles.step - 1; k >= j; k--)\n nafW = (nafW << 1) + naf[k];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (var j = 0; j < repr.length; j++) {\n var nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var k = 0; i >= 0 && naf[i] === 0; i--)\n k++;\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n for (var i = 0; i < len; i++) {\n var p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (var i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a]);\n naf[b] = getNAF(coeffs[b], wndWidth[b]);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b] /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3 /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (var j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (var i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (var j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (var j = 0; j < len; j++) {\n var z = tmp[j];\n var p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (var i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16)\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n};\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point))\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point))\n }\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate)\n }\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (var i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (var i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n // Note: this implementation is according to the original paper\n // by P. Montgomery, NOT the one by D. J. Bernstein.\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n var bytes = utils.toArray(bytes, enc);\n\n // TODO Curve448\n // Montgomery curve points must be represented in the compressed format\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (bytes.length === 33 && bytes[0] === 0x40)\n bytes = bytes.slice(1, 33).reverse(); // point must be little-endian\n if (bytes.length !== 32)\n throw new Error('Unknown point compression format');\n return this.point(bytes, 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n\n // Note: the output should always be little-endian\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (compact) {\n return [ 0x40 ].concat(this.getX().toArray('le', len));\n } else {\n return this.getX().toArray('be', len);\n }\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n if (this.curve.twisted) {\n // E = a * C\n var e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n var h = this.z.redSqr();\n // J = F - 2 * H\n var j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n var e = c.redAdd(d);\n // H = (c * Z1)^2\n var h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n var j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else if (options.type === 'mont')\n this.curve = new curve.mont(options);\n else throw new Error('Unknown curve type.');\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve\n });\n return curve;\n }\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'\n ]\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'\n ]\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'\n ]\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'\n ]\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650'\n ]\n});\n\n// https://tools.ietf.org/html/rfc7748#section-4.1\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9'\n ]\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.4\ndefineCurve('brainpoolP256r1', {\n type: 'short',\n prime: null,\n p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',\n a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',\n b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',\n n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',\n hash: hash.sha256, // or 384, or 512\n gRed: false,\n g: [\n '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',\n '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.6\ndefineCurve('brainpoolP384r1', {\n type: 'short',\n prime: null,\n p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +\n 'ACD3A729 901D1A71 87470013 3107EC53',\n a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +\n '8AA5814A 503AD4EB 04A8C7DD 22CE2826',\n b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +\n '7CB43902 95DBC994 3AB78696 FA504C11',\n n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +\n 'CF3AB6AF 6B7FC310 3B883202 E9046565',\n hash: hash.sha384, // or 512\n gRed: false,\n g: [\n '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +\n 'E8E826E03436D646AAEF87B2E247D4AF1E',\n '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +\n '280E4646217791811142820341263C5315'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.7\ndefineCurve('brainpoolP512r1', {\n type: 'short',\n prime: null,\n p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +\n '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',\n a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +\n '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',\n b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +\n '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',\n n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +\n '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',\n hash: hash.sha512,\n gRed: false,\n g: [\n '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +\n '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',\n '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +\n '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'\n ]\n});\n\n// https://en.bitcoin.it/wiki/Secp256k1\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre\n ]\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc\n });\n};\n\n// TODO: should not validate for X25519\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // For Curve25519/Curve448 we have a specific procedure.\n // TODO Curve448\n if (this.ec.curve.type === 'mont') {\n var one = this.ec.curve.one;\n var mask = one.ushln(255 - 3).sub(one).ushln(3);\n this.priv = this.priv.or(one.ushln(255 - 1));\n this.priv = this.priv.and(mask);\n } else\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n }\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0 && (r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] === 0 && (s[1] & 0x80)) {\n s = s.slice(1);\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray()\n });\n\n // Key generation for curve25519 is simpler\n if (this.curve.type === 'mont') {\n var priv = new BN(drbg.generate(32));\n return this.keyFromPrivate(priv);\n }\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n do {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n } while (true);\n};\n\nEC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {\n bitSize = bitSize || msg.byteLength() * 8;\n var delta = bitSize - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.truncateMsg = function truncateMSG(msg) {\n // Bit size is only determined correctly for Uint8Arrays and hex strings\n var bitSize;\n if (msg instanceof Uint8Array) {\n bitSize = msg.byteLength * 8;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else if (typeof msg === 'string') {\n bitSize = msg.length * 4;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else {\n msg = this._truncateToN(new BN(msg, 16));\n }\n return msg;\n}\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this.truncateMsg(msg);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8'\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; true; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n // Fallback to the old code\n var ret = this._verify(this.truncateMsg(msg), signature, key) ||\n this._verify(this._truncateToN(new BN(msg, 16)), signature, key);\n return ret;\n};\n\nEC.prototype._verify = function _verify(msg, signature, key) {\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n\n if (!this.curve._maxwellTrick) {\n var p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n var p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n if (params.hasOwnProperty('secret'))\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else {\n this._pubBytes = parseBytes(params.pub);\n if (this._pubBytes && this._pubBytes.length === 33 &&\n this._pubBytes[0] === 0x40)\n this._pubBytes = this._pubBytes.slice(1, 33);\n if (this._pubBytes && this._pubBytes.length !== 32)\n throw new Error('Unknown point compression format');\n }\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n // https://tools.ietf.org/html/rfc8032#section-5.1.5\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength)\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar HmacDRBG = require('hmac-drbg');\nvar rand = require('brorand');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n var curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.curve.n.toArray()\n });\n\n return this.keyFromSecret(drbg.generate(32));\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","this","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","prototype","undefined","read","async","length","value","done","readToEnd","join","result","slice","clone","then","push","write","chunk","close","abort","reason","isNode","globalThis","process","versions","NodeReadableStream","require$$0","Readable","isStream","ReadableStream","isPrototypeOf","streams.ReadableStream","isUint8Array","Uint8Array","concatUint8Array","arrays","totalLength","i","Error","pos","forEach","element","set","NodeBuffer","Buffer","require$$1","nodeToWeb","webToNode","nodeStream","canceled","start","controller","pause","on","isBuffer","buffer","byteOffset","byteLength","enqueue","e","error","pull","resume","cancel","destroy","NodeReadable","webStream","options","_reader","streams.getReader","size","callback","doneReadingSet","WeakSet","externalBuffer","Reader","streams.isArrayStream","reader","_read","bind","_releaseLock","_cancel","streamType","streams.isStream","streams.nodeToWeb","doneReading","has","add","shift","readLine","returnVal","streams.concat","lineEndIndex","indexOf","concat","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","filter","toPonyfillReadable","toNativeReadable","WritableStream","TransformStream","loadStreamsPonyfill","ponyfill","adapter","all","createReadableStreamWrapper","toStream","toArrayStream","list","some","map","transform","transformWithCancel","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","transformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","highWaterMark","finish","output","data","result1","result2","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","Object","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","arrayStream","BigInteger","n","hex","hexByte","toString","BigInt","iinc","inc","idec","dec","iadd","x","isub","sub","imul","mul","imod","m","isNegative","mod","modExp","isZero","isOne","exp","r","lsb","rx","modInv","gcd","_egcd","b","y","xPrev","yPrev","a","q","tmp","ileftShift","leftShift","irightShift","rightShift","equal","lt","lte","gt","gte","isEven","abs","res","toNumber","number","Number","MAX_SAFE_INTEGER","getBit","bitLength","zero","one","negOne","bitlen","eight","len","toUint8Array","endian","rawLength","offset","parseInt","reverse","detectBigInt","byValue","curve","p256","secp256r1","prime256v1","p384","secp384r1","p521","secp521r1","secp256k1","ed25519Legacy","ED25519","ed25519","Ed25519","curve25519Legacy","X25519","cv25519","curve25519","Curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","eddsa","aedh","aedsa","x25519","x448","ed448","symmetric","plaintext","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","webHash","aead","eax","ocb","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuer","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","type","debugMode","env","NODE_ENV","util","isString","String","stream.isUint8Array","stream.isStream","readNumber","writeNumber","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","leftPad","padded","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","k","uint8ArrayToHex","h","c","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","s","printDebug","log","printDebugError","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","crypto","subtle","getBigInteger","default","getNodeCrypto","getNodeZlib","getNodeBuffer","require$$2","getHardwareConcurrency","navigator","hardwareConcurrency","require$$3","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","selectUint8","isAES","cipherAlgo","enums","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","from","btoa","atob","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","deflateLevel","aeadProtect","preferredAEADAlgorithm","aeadChunkSizeByte","s2kIterationCountByte","allowUnauthenticatedMessages","allowUnauthenticatedStream","checksumRequired","minRSABits","passwordCollisionCheck","revocationsExpire","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","minBytesForWebCrypto","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","useIndutnyElliptic","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","getType","header","match","addheader","customComment","config","getCheckSum","base64.encode","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","splitChecksum","body","checksum","lastEquals","lastIndexOf","unarmor","defaultConfig","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","checksumVerified","stream.readToEnd","stream.passiveClone","stream.pipe","checksumVerifiedString","stream.isArrayStream","messageType","partIndex","partTotal","bodyClone","KeyID","toHex","equals","keyID","matchWildcard","isWildcard","isNull","static","AES_asm","gexp3","glog3","ginit_done","gmul","aes_sbox","aes_sinv","aes_enc","aes_dec","aes_init_done","aes_init","_s","ginv","d","ginit","wrapper","foreign","heap","asm","stdlib","S0","S1","S2","S3","I0","I1","I2","I3","N0","N1","N2","N3","M0","M1","M2","M3","H0","H1","H2","H3","R","HEAP","DATA","_core","x0","x1","x2","x3","t1","t2","t3","y0","y1","y2","y3","_ecb_enc","_ecb_dec","_cbc_enc","_cbc_dec","_cfb_enc","_cfb_dec","_ofb","_ctr","_gcm_mac","z0","z1","z2","z3","set_rounds","set_state","s0","s1","s2","s3","set_iv","i0","i1","i2","i3","set_nonce","n0","n1","n2","n3","set_mask","m0","m1","m2","m3","set_counter","c0","c1","c2","c3","get_state","get_iv","gcm_init","cipher","mode","ret","_cipher_modes","mac","_mac_modes","set_key","ks","k0","k1","k2","k3","k4","k5","k6","k7","ekeys","dkeys","rcon","jj","ENC","ECB","CBC","CFB","OFB","CTR","DEC","MAC","GCM","HEAP_DATA","is_bytes","_heap_init","heapSize","_heap_write","hpos","dpos","dlen","hlen","wlen","joinBytes","arg","totalLenght","reduce","sum","curr","cursor","IllegalStateError","args","IllegalArgumentError","SecurityError","heap_pool","asm_pool","AES","iv","padding","acquire_asm","pop","reset","release_asm","keylen","keyview","getUint32","ivview","AES_Encrypt_process","TypeError","amode","rpos","AES_Encrypt_finish","plen","rlen","hasOwnProperty","p","AES_Decrypt_process","AES_Decrypt_finish","pad","pcheck","AES_ECB","encrypt","decrypt","aes","C","aesECB","block","blockSize","keySize","des","keys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","left","right","looping","cbcleft","cbcleft2","cbcright","cbcright2","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","src","dst","l","f1","f2","f3","scheduleA","scheduleB","I","sBox","inn","w","ki","half","round","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","u","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","vector","off","_decryptBlock","kk","sha1_asm","H4","TOTAL0","TOTAL1","I4","O0","O1","O2","O3","O4","w0","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32","w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61","w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","_core_heap","_state_to_heap","h0","h1","h2","h3","h4","total0","total1","hashed","hmac_reset","_hmac_opad","hmac_init","p0","p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","hmac_finish","t0","t4","pbkdf2_generate_block","count","Hash","HASH_SIZE","Sha1","NAME","BLOCK_SIZE","asm_function","Sha256","H5","H6","H7","I5","I6","I7","O5","O6","O7","f","g","h5","h6","h7","t5","t6","t7","sha256_asm","assert","val","msg","module","create","ctor","superCtor","super_","enumerable","configurable","TempCtor","inherits","enc","hi","lo","zero2","htonl","zero8","word","ah","al","bh","bl","ch","cl","dh","dl","carry","eh","el","num","BlockHash","pending","pendingTotal","outSize","hmacStrength","_delta8","_delta32","update","utils","toArray","join32","_update","digest","_pad","_digest","rotr32","z","ch32","p32","maj32","sum32","sum32_4","sum32_5","shaCommon","s0_256","s1_256","g0_256","g1_256","common","sha256_K","SHA256","W","SHA224","T1","T2","toHex32","split32","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","SHA512","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","SHA384","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotl32","sum32_3","RIPEMD160","K","Kh","A","B","D","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","md5cycle","ff","gg","add32","cmn","md5blk","md5blks","hex_chr","rhex","webCrypto","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","hashjsHash","webCryptoHash","hashInstance","asmcryptoHash","hashFunctions","entree","state","substring","tail","md51","ripemd160","algo","getHashByteLength","AES_CFB","getCipher","algoName","knownAlgos","getCiphers","nodeAlgos","pt","cipherObj","createCipheriv","nodeEncrypt","ALGO","_key","importKey","cbc_pt","ct","xorMut","webEncrypt","cfb","aesEncrypt","cipherfn","block_size","blockc","ciphertext","encblock","decipherObj","createDecipheriv","nodeDecrypt","aesDecrypt","blockp","decblock","AES_CTR","nonce","AES_CTR_set_options","counter","mask","pow","view","AES_CBC","blockLength","rightXORMut","zeroBlock","CMAC","cbc","padding2","ivLength","tagLength","two","OMAC","cmac","en","final","EAX","omac","ctr","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","xor","OCB","encipher","decipher","maxNtz","crypt","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","xorInput","$","cipherInput","cipherName","ciphers","mask_x","mask_$","constructKeyVariables","crypted","_AES_GCM_data_maxLength","AES_GCM","tagSize","gamma0","noncelen","noncebuf","_gcm_mac_process","nonceview","RangeError","cleartext","tagsize","AES_GCM_encrypt","AES_GCM_decrypt","AES_GCM_Encrypt_process","AES_GCM_Encrypt_finish","alen","clen","AES_GCM_Decrypt_process","tlen","AES_GCM_Decrypt_finish","atag","acheck","setAAD","getAuthTag","de","setAuthTag","additionalData","gcm","nacl","gf","Float64Array","randombytes","_9","gf0","gf1","_121665","D2","X","Y","crypto_verify_32","xi","yi","vn","set25519","car25519","o","v","sel25519","pack25519","neq25519","par25519","unpack25519","Z","M","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","x32","x16","crypto_scalarmult_base","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","cleanup","arr","scalarMult","box","keyPair","fromSecretKey","sign","signedMsg","sm","smlen","crypto_sign","detached","sig","verify","crypto_sign_open","fromSeed","seed","setPRNG","self","msCrypto","getRandomValues","min","require","randomBytes","exports","getRandomBytes","getRandomBigInteger","modulus","randomProbablePrime","thirty","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","rand","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","emLen","hashPrefix","tLen","fill","EM","asn1","RSAPrivateKey","define","seq","obj","int","RSAPublicKey","hashAlgo","hashName","jwk","pNum","qNum","dNum","dq","dp","kty","qi","ext","privateToJWK","webSign","err","BN","pBNum","qBNum","dBNum","subn","createSign","keyObject","version","publicExponent","privateExponent","prime1","prime2","exponent1","exponent2","coefficient","createPrivateKey","der","format","pem","label","nodeSign","bnSign","publicToJWK","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","constants","RSA_PKCS1_PADDING","publicEncrypt","bnEncrypt","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","keyGenOpt","modulusLength","generateKey","exportKey","generateKeyPair","opts","publicKeyEncoding","privateKeyEncoding","prv","_","toArrayLike","phi","nSizeOver3","rde","pSize","n1023","threshold","rqx","OID","oid","getName","keyFromPrivate","indutnyCurve","priv","keyFromPublic","pub","validate","getIndutnyCurve","elliptic","ec","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","stream.TransformStream","lengthByte","nextPacket","UnsupportedError","params","captureStackTrace","UnparseablePacket","rawContent","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","CurveWithOID","oidOrName","webCryptoKey","namedCurve","jwkToRawPublic","webGenKeyPair","createECDH","generateKeys","getPublicKey","getPrivateKey","nodeGenKeyPair","genKeyPair","entropy","getPublic","getPrivate","validateStandardParams","Q","supportedCurves","curveName","dG","validationErrors","eq","bufX","bufY","rawPublicToJWK","crv","ECPrivateKey","parameters","unused","ECDSASignature","ellipticSign","SubjectPublicKeyInfo","algorithm","subjectPublicKey","ellipticVerify","octstr","explicit","optional","any","bitstr","AlgorithmIdentifier","objid","use","getPreferredHashAlgo","RS","wrap","IV","P","unpack","unwrap","createArrayBuffer","setUint32","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","genPrivateEphemeralKey","recipient","deriveBits","public","webPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","V","derive","ellipticPublicEphemeralKey","secret","webPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","ellipticPrivateEphemeralKey","pkcs5.encode","wrappedKey","aesKW.wrap","pkcs5.decode","aesKW.unwrap","nodeSubtleCrypto","webcrypto","HKDF","inputKey","salt","info","outLen","importedKey","hashAlgoName","computeHMAC","hmacKey","hmacMessage","createHmac","pseudoRandomKey","hashLen","outputKeyingMaterial","roundInput","HKDF_INFO","recipientA","ephemeralSecretKey","sharedSecret","ephemeralPublicKey","hkdfInput","computeHKDF","xr","u1","u2","qSize","n150","rsa","publicParams","curveSize","publicKeyParams","privateKeyParams","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","instance","followLength","checkSupportedCurve","keyAlgo","symmetricAlgo","ECDHSymkey","ecdhX","fromObject","sessionKeyParams","privateParams","algosWithNativeRepresentation","orderedParams","generate","validateParams","algoModule","prefixrandom","repeat","random","pkcs1","pkcs5","aesKW","assign","TYPED_OK","Uint16Array","Int32Array","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","fnUntyped","Buf8","Buf16","Buf32","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","STORED_BLOCK","STATIC_TREES","DYN_TREES","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","MAX_MATCH","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","max_code","d_code","dist","put_short","pending_buf","send_bits","bi_valid","bi_buf","send_code","tree","bi_reverse","code","gen_codes","bl_count","next_code","init_block","dyn_ltree","dyn_dtree","bl_tree","opt_len","static_len","last_lit","matches","bi_windup","smaller","depth","_n2","_m2","pqdownheap","heap_len","compress_block","ltree","dtree","lc","extra","lx","d_buf","l_buf","build_tree","desc","stree","heap_max","base","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","_tr_init","tr_static_init","l_desc","d_desc","bl_desc","_tr_stored_block","stored_len","utils.arraySet","window","copy_block","_tr_align","bi_flush","_tr_flush_block","opt_lenb","static_lenb","max_blindex","level","strm","data_type","black_mask","detect_data_type","build_bl_tree","strategy","lcodes","dcodes","blcodes","rank","send_all_trees","_tr_tally","lit_bufsize","adler32","adler","crcTable","table","makeTable","crc32","MAX_MEM_LEVEL","MIN_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","errorCode","flush_pending","avail_out","pending_out","next_out","total_out","flush_block_only","trees._tr_flush_block","block_start","strstart","put_byte","putShortMSB","read_buf","avail_in","next_in","total_in","longest_match","cur_match","chain_length","max_chain_length","scan","best_len","prev_length","nice_match","limit","w_size","_win","wmask","w_mask","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","_w_size","more","window_size","hash_size","head","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","trees._tr_tally","max_lazy_match","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","max_block_size","pending_buf_size","max_start","DeflateState","status","gzhead","gzindex","method","last_flush","w_bits","hash_bits","utils.Buf16","deflateReset","trees._tr_init","deflateResetKeep","lm_init","deflate","old_flush","beg","hcrc","comment","os","level_flags","bstate","deflate_huff","deflate_rle","trees._tr_align","trees._tr_stored_block","__","_utf8len","utils.Buf8","string2buf","m_pos","buf_len","str_len","ZStream","Deflate","chunkSize","windowBits","memLevel","opt","raw","gzip","ended","zlib_deflate.deflateInit2","dictionary","dict","strings.string2buf","avail","next","tmpDict","dictLength","zlib_deflate.deflateSetDictionary","_dict_set","_mode","zlib_deflate.deflate","onEnd","onData","utils.shrinkBuf","zlib_deflate.deflateEnd","utils.flattenChunks","BAD","TYPE","inflate_fast","_in","_out","hold","here","op","from_source","dmax","wsize","whave","wnext","s_window","lcode","lencode","dcode","distcode","lmask","lenbits","dmask","distbits","top","dolen","dodist","sane","MAXBITS","ENOUGH_LENS","ENOUGH_DISTS","CODES","LENS","DISTS","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","incr","low","sym","root","drop","used","huff","base_index","offs","here_bits","here_op","here_val","extra_index","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","zswap32","InflateState","havedict","flags","check","total","wbits","ncode","nlen","ndist","have","lendyn","distdyn","back","was","inflateReset","utils.Buf32","inflateResetKeep","inflateInit2","inflateReset2","lenfix","distfix","virgin","fixedtables","updatewindow","copy","inflate","put","last_bits","last_op","last_val","hbuf","order","inf_leave","xflags","extra_len","inflateSetDictionary","dictid","GZheader","Inflate","zlib_inflate.inflateInit2","c.Z_OK","zlib_inflate.inflateGetHeader","zlib_inflate.inflateSetDictionary","allowBufError","c.Z_FINISH","c.Z_NO_FLUSH","strings.binstring2buf","zlib_inflate.inflate","c.Z_NEED_DICT","c.Z_BUF_ERROR","c.Z_STREAM_END","c.Z_SYNC_FLUSH","zlib_inflate.inflateEnd","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","remaining","seek","n_bit","n_byte","pi","bufToHex","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","getCRC","updateCRC","updateCRCRun","mtf","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","optDetail","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","CRC32","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","MAX_HUFCODE_BITS","permute","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","multistream","bz","targetStreamCRC","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","verified","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","issuerKeyID","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","writeHashedSubPackets","toHash","stream.slice","stream.clone","writeSubPacket","humanReadable","critical","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","fromBinary","compressionFn","compress_fns","nodeZlib","node_zlib","stream.nodeToWeb","stream.webToNode","pako_zlib","deflateRaw","createDeflateRaw","createDeflate","inflateRaw","createInflateRaw","createInflate","BunzipDecode","SymEncryptedIntegrityProtectedDataPacket","encrypted","sessionKeyAlgorithm","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","AEADEncryptedDataPacket","cipherAlgorithm","aeadAlgorithm","chunkSizeByte","getAEADMode","modeInstance","tagLengthIfDecrypting","tagLengthIfEncrypting","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","latestPromise","cryptedBytes","queuedBytes","finalChunk","cryptedPromise","setInt32","desiredSize","PublicKeyEncryptedSessionKeyPacket","publicKeyID","sessionKey","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","sessionKeyData","S2K","getCount","passphrase","numBytes","rlength","prefixlen","datalen","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","produceKey","encryptionKey","generateSessionKey","associatedData","toEncrypt","PublicKeyPacket","expirationTimeV3","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","PublicSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","startOfSecretKeyData","unparseableKeyMaterial","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","produceEncryptionKey","cleartextWithHash","validParams","generateParams","global","parse5322","inStr","getPos","setPos","initialize","parseString","tokens","semantic","children","ast","parent","child","compareToken","fxnCompare","tok","lit","and","or","prod","invis","colwsp","star","minimum","isUTF8NonAscii","cr","crlf","lf","dquote","htab","sp","vchar","accept","rfc6532","wsp","quotedPair","obsQP","fws","obsFws","ctext","obsCtext","ccontent","cfws","atext","atom","dotAtomText","maybeText","dotAtom","qtext","obsQtext","qcontent","quotedString","address","mailbox","group","nameAddr","addrSpec","displayName","angleAddr","obsAngleAddr","groupList","obsPhrase","collapseWhitespace","mailboxList","obsMboxList","addressList","obsAddrList","obsGroupList","localPart","obsLocalPart","dtext","obsDtext","domainLiteral","domain","obsDomain","rejectTLD","obsNoWsCtl","strict","atInDisplayName","obsRoute","obsDomainList","findNode","stack","findAllNodesNoChildren","names","namesLookup","giveResult","addresses","groupsAndMailboxes","groupOrMailbox","giveResultGroup","giveResultMailbox","simplifyResult","oneResult","partial","groupName","groupResultMailboxes","mailboxes","grabSemantic","aspec","findAllNodes","comments","local","concatComments","startProduction","handleOpts","startAt","defs","isNullUndef","defaults","isObject","parseOneAddress","parseAddressList","parseFrom","parseSender","parseReplyTo","UserIDPacket","email","components","emailAddresses","otherUserID","SecretSubkeyPacket","Signature","packetlist","getSigningKeyIDs","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","prefAlgo","primaryUser","getPrimaryUser","selfCertification","getPreferredCurveHashAlgo","getPreferredAlgo","userIDs","defaultAlgo","preferredSenderAlgo","prefPropertyName","senderAlgoSupport","recipientPrefs","Boolean","signingKeyPacket","signaturePacket","mergeSignatures","source","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","sanitizeKeyOptions","subkeyDefaults","isValidSigningKeyPacket","isValidEncryptionKeyPacket","isValidDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","signingKeys","isPrivate","signingKey","getSigningKey","certificate","verificationKeys","issuerKeys","getKeys","isRevoked","certifications","certification","valid","verifyCertificate","sourceUser","srcSelfSig","srcRevSig","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","sort","helper.isValidSigningKeyPacket","helper.checkKeyRequirements","helper.isValidEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","revocationCertificate","privateKeys","userSign","certify","verifyAllCertifications","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","fromSecretKeyPacket","pubSubkeyPacket","fromSecretSubkeyPacket","helper.isValidDecryptionKeyPacket","allDummies","defaultOptions","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","userIDPacket","subkeyOptions","subkeySignaturePacket","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","sessionKeyObjects","decryptSessionKeys","symEncryptedPacketlist","symEncryptedPacket","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","password","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","getDecryptionKeys","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgorithmName","supported","isAEADSupported","getEncryptionKey","maybeKey","wildcard","encryptionKeyIDs","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","literalDataPacket","existingSigPacketlist","onePassSig","signingKeyID","onePassSignatureList","createSignaturePackets","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","detachedSignature","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","CleartextMessage","newSignature","hashes","ar","checkMessage","checkCleartextOrMessage","checkOutputMessageFormat","defaultConfigPropsCount","checkConfig","inputConfigProps","inputProp","convertStream","streaming","encoding","setEncoding","stream.toNativeReadable","linkStreams","formatObject","object","SymbolPolyfill","iterator","description","noop","globals","typeIsObject","rethrowAssertionErrorRejection","originalPromise","originalPromiseThen","originalPromiseResolve","originalPromiseReject","newPromise","executor","promiseResolvedWith","promiseRejectedWith","PerformPromiseThen","onFulfilled","onRejected","uponPromise","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","reflectCall","F","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","peek","front","ReadableStreamReaderGenericInitialize","_ownerReadableStream","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","isFinite","MathTrunc","trunc","assertDictionary","context","assertFunction","assertObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","toStringTag","asyncIterator","ReadableStreamAsyncIteratorImpl","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","return","returnSteps","_returnSteps","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","IsFiniteNonNegativeNumber","IsNonNegativeNumber","DequeueValue","container","pair","_queue","_queueTotalSize","EnqueueValueWithSize","ResetQueue","CreateArrayFromList","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespond","respondWithNewView","isView","firstDescriptor","_pendingPullIntos","bytesFilled","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","_byobRequest","request","SetUpReadableStreamBYOBRequest","ReadableByteStreamControllerGetDesiredSize","_closeRequested","_controlledReadableByteStream","ReadableByteStreamControllerError","ReadableByteStreamControllerClearAlgorithms","ReadableStreamClose","ReadableByteStreamControllerClose","transferredBuffer","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableStreamHasBYOBReader","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerEnqueue","_cancelAlgorithm","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","elementSize","viewConstructor","readerType","shouldPull","_started","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","queue","headOfQueue","bytesToCopy","destStart","destOffset","srcOffset","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","ReadableByteStreamControllerClearPendingPullIntos","ReadableStreamError","_strategyHWM","SetUpReadableByteStreamControllerFromUnderlyingSource","underlyingByteSource","startAlgorithm","pullAlgorithm","cancelAlgorithm","SetUpReadableByteStreamController","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","ReadableStreamBYOBReader","byobReaderBrandCheckException","BYTES_PER_ELEMENT","emptyView","ReadableByteStreamControllerPullInto","ReadableStreamBYOBReaderRead","ExtractHighWaterMark","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException$2","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","DOMException$1","_a","isDOMExceptionConstructor","createDOMExceptionPolyfill","ReadableStreamPipeTo","signal","shuttingDown","currentWrite","actions","shutdownWithAction","action","aborted","addEventListener","isOrBecomesErrored","shutdown","isOrBecomesClosed","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","defaultControllerBrandCheckException$1","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","convertPipeOptions","isAbortSignal","assertAbortSignal","rawUnderlyingSource","underlyingSource","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","SetUpReadableStreamDefaultControllerFromUnderlyingSource","streamBrandCheckException$1","rawOptions","convertReaderOptions","AcquireReadableStreamBYOBReader","pipeThrough","rawTransform","convertReadableWritablePair","destination","branches","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","canceled1","canceled2","cancelPromise","value1","value2","CreateReadableStream","compositeReason","cancelResult","ReadableStreamTee","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","streamBrandCheckException","IsTransformStreamDefaultController","defaultControllerBrandCheckException","readableController","TransformStreamDefaultControllerTerminate","ReadableStreamDefaultControllerHasBackpressure","extendStatics","__proto__","__extends","isStreamConstructor","startCalled","isReadableStream","isWritableStream","isTransformStream","supportsByobReader","createWrappingReadableSource","parseReadableType","WrappingReadableByteStreamSource","WrappingReadableStreamDefaultSource","typeString","AbstractWrappingReadableStreamSource","underlyingStream","_underlyingReader","_readerMode","_pendingRead","_underlyingStream","_attachDefaultReader","_detachReader","_attachReader","_this","_finishPendingRead","_pullWithDefaultReader","_tryClose","_setPendingRead","readPromise","pendingRead","finishRead","afterRead","_super","supportsByob","_supportsByob","_attachByobReader","_pullWithByobRequest","to","fromArray","createWrappingWritableSink","WrappingWritableStreamSink","underlyingWriter","_pendingWrite","_underlyingWriter","_errorPromise","_errorPromiseReject","_finishErroring","_startErroring","race","_setPendingWrite","_finishPendingWrite","writePromise","pendingWrite","finishWrite","afterWrite","createWrappingTransformer","WrappingTransformStreamTransformer","_onRead","_onError","_flushReject","_onTerminate","_flushResolve","_flushPromise","readerClosed","isReadableStreamConstructor","byteSourceSupported","supportsByteSource","isTransformStreamConstructor","isWritableStreamConstructor","sink","isBN","negative","words","red","_init","wordSize","parseHex","parseBase","cmp","_initNumber","_initArray","_parseHex","_parseBase","strip","limbLen","limbPow","imuln","_iaddn","_expand","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","out","ncarry","rword","maxJ","groupSize","groupBase","modn","idivn","toJSON","toBuffer","ArrayType","reqLength","littleEndian","andln","iushrn","_countBits","clz32","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","uor","iuand","iand","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","comb10MulTo","mid","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","bl7","bh7","bl8","bh8","bl9","bh9","jumboMulTo","FFTM","mulp","mulTo","hncarry","bigMulTo","makeRBT","N","revBin","rb","rbt","rws","iws","rtws","itws","rtwdf","cos","PI","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","carryMask","newCarry","ishln","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","iabs","_ishlnsubmul","_wordDiv","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","r2","acc","egcd","yp","xp","im","isOdd","jm","_invmp","delta","cmpn","invm","bincn","ucmp","gtn","gten","ltn","lten","eqn","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","rinv","minv","ireduce","imulK","mod3","nOne","lpow","inv","wnd","currentLen","mont","nred","minAssert","minUtils","getNAF","naf","getJSF","jsf","d1","d2","m8","m14","m24","cachedProperty","computer","parseBytes","intFromLE","Rand","_rand","getByte","BaseCurve","conf","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","adjustCount","redN","_maxwellTrick","BasePoint","precomputed","point","_fixedNafMul","doubles","_getDoubles","step","repr","nafW","jpoint","mixedAdd","points","toP","_wnafMul","nafPoints","_getNAFPoints","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","comb","toJ","ja","jb","decodePoint","pointFromX","encodeCompressed","_encode","compact","getX","getY","precompute","beta","_getBeta","_hasDoubles","dbl","ShortCurve","Base","tinv","zeroA","threeA","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","Point","isRed","inf","JPoint","zOne","MontCurve","i4","a24","lambda","betas","_getEndoRoots","lambdas","basis","vec","_getEndoBasis","ntinv","prevR","aprxSqrt","len1","_endoSplit","v1","v2","ax","rhs","_endoWnafMulAdd","npoints","ncoeffs","fromJSON","pre","endoMul","JSON","obj2point","isInfinity","nx","ny","ys1","dyinv","mulAdd","jmulAdd","_precompute","negate","zinv","zinv2","ay","pz2","nz","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","dny","_zeroDbl","_threeDbl","_dbl","yyyy","yyyy8","c8","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","pz3","eqXToP","zs","xc","normalize","diffAdd","da","cb","jumlAdd","EdwardsCurve","twisted","mOneA","oneC","_mulA","_mulC","lhs","pointFromY","_extDbl","nt","_projDbl","_extAdd","_projAdd","short","edwards","ft_1","sha1_K","SHA1","require$$4","Hmac","inner","outer","sha","hmac","PresetCurve","defineCurve","cofactor","HmacDRBG","predResist","minEntropy","_reseed","reseedInterval","entropyEnc","nonceEnc","pers","persEnc","_hmac","kmac","reseed","addEnc","KeyPair","_importPrivate","privEnc","_importPublic","pubEnc","fromPublic","fromPrivate","_importDER","recoveryParam","Position","place","getLength","initial","octetLen","rmPadding","constructLength","octets","slen","toDER","backHalf","EC","nh","drbg","ns2","_truncateToN","truncOnly","truncateMsg","bkey","ns1","iter","kp","kpX","canonical","_verify","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Qprime","_secret","isPoint","_pub","_pubBytes","fromSecret","encodePoint","lastIx","encodingLength","decodeInt","privBytes","getSecret","pubBytes","_R","_S","_Rencoded","Rencoded","_Sencoded","Sencoded","encodeInt","toBytes","EDDSA","pointClass","keyFromSecret","hashInt","messagePrefix","s_","makeSignature","SG","normed","xIsOdd","require$$5","rest","unknownOptions","stream.loadStreamsPonyfill","stream.toStream","literalDataPacketlist","expectSigned","publicKeys","clonedPrivateKey","passphrases","signingUserIDs","encryptionUserIDs","signatureNotations","checkBinary","checkString","helper.generateSecretKey","getRevocationCertificate","cleartextMessage","checkHashAlgos","hashAlgos","oneHeader","armoredKey","binaryKey","armoredKeys","binaryKeys","keyIndex","newKey","armoredMessage","binaryMessage","oneKeyList","armoredSignature","binarySignature","reformattedKey","sanitize","reformat","revokedKey","applyRevocationCertificate","revoke","signDetached"],"mappings":";khBAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxBC,cACEC,QACAC,KAAKT,GAAsB,IAAIU,SAAQ,CAACC,EAASC,KAC/CH,KAAKP,GAAsBS,EAC3BF,KAAKN,GAAqBS,CAAM,IAElCH,KAAKT,GAAoBa,OAAM,UAuCnC,SAASC,EAAcC,GACrB,OAAOA,GAASA,EAAMC,WAAaV,MAAMW,QAAQF,EACnD,CAOA,SAASG,EAAOH,GACd,IAAKD,EAAcC,GAAQ,CACzB,MAAMI,EAASJ,EAAMK,YACfC,EAAcF,EAAOE,YAK3B,OAJAF,EAAOE,YAAc,KACnBF,EAAOG,OAAOT,OAAM,eACpBQ,EAAYE,KAAKJ,EAAO,EAEnBA,EAETV,KAAKe,OAAST,CAChB,CAvDAV,EAAYoB,UAAUT,UAAY,WAIhC,YAH2BU,IAAvBjB,KAAKL,KACPK,KAAKL,GAAgB,GAEhB,CACLuB,KAAMC,gBACEnB,KAAKT,GACPS,KAAKL,KAAkBK,KAAKoB,OACvB,CAAEC,WAAOJ,EAAWK,MAAM,GAE5B,CAAED,MAAOrB,KAAKA,KAAKL,MAAkB2B,MAAM,IAGxD,EAEA1B,EAAYoB,UAAUO,UAAYJ,eAAeK,SACzCxB,KAAKT,GACX,MAAMkC,EAASD,EAAKxB,KAAK0B,MAAM1B,KA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EF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAINrC,IAAK,CACHP,IAAK,EACL4C,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE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F,EAAQkY,GACtD8iH,EAAc,CAChB,GAAiC,IAA7Bh7H,EAAO0mF,WAAW/mF,OACpB,MAAUgC,MAAM,yBAElB3B,EAAOyI,KAAOyT,EAAc,CAC1Blc,EAAOyI,KACPorE,IAAiBn0E,gBACTqZ,GAAKmG,WAAWlf,EAAO0mF,WAAW7/E,KAAIm1C,GAAOA,EAAI61B,WAAU,MAKvE,OADA7xE,EAAOyI,WAAa8sF,GAAcv1F,EAAOyI,KAAMyP,EAAQ69D,WAAY70B,GAC5DlhD,EACP,MAAOggD,GACP,MAAMjnC,GAAK8F,UAAU,iCAAkCmhC,GAE3D"} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.mjs b/app/node_modules/openpgp/dist/node/openpgp.min.mjs index 0588c5434..a0f30cda7 100644 --- a/app/node_modules/openpgp/dist/node/openpgp.min.mjs +++ b/app/node_modules/openpgp/dist/node/openpgp.min.mjs @@ -1,17 +1,16 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};import t from"buffer";import r from"stream";import i from"crypto";import n from"zlib";import a from"os";import s from"util";import o from"asn1.js";const c=Symbol("doneWritingPromise"),u=Symbol("doneWritingResolve"),h=Symbol("doneWritingReject"),d=Symbol("readingIndex");class f extends Array{constructor(){super(),this[c]=new Promise(((e,t)=>{this[u]=e,this[h]=t})),this[c].catch((()=>{}))}}function l(e){return e&&e.getReader&&Array.isArray(e)}function p(e){if(!l(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}f.prototype.getReader=function(){return void 0===this[d]&&(this[d]=0),{read:async()=>(await this[c],this[d]===this.length?{value:void 0,done:!0}:{value:this[this[d]++],done:!1})}},f.prototype.readToEnd=async function(e){await this[c];const t=e(this.slice(this[d]));return this.length=0,t},f.prototype.clone=function(){const e=new f;return e[c]=this[c].then((()=>{e.push(...this)})),e},p.prototype.write=async function(e){this.stream.push(e)},p.prototype.close=async function(){this.stream[u]()},p.prototype.abort=async function(e){return this.stream[h](e),e},p.prototype.releaseLock=function(){};const y="object"==typeof e.process&&"object"==typeof e.process.versions,b=y&&r.Readable;function m(t){return l(t)?"array":e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t)?"web":K&&K.prototype.isPrototypeOf(t)?"ponyfill":b&&b.prototype.isPrototypeOf(t)?"node":!(!t||!t.getReader)&&"web-like"}function g(e){return Uint8Array.prototype.isPrototypeOf(e)}function w(e){if(1===e.length)return e[0];let t=0;for(let r=0;r{t||(v.isBuffer(i)&&(i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),r.enqueue(i),e.pause())})),e.on("end",(()=>{t||r.close()})),e.on("error",(e=>r.error(e)))},pull(){e.resume()},cancel(r){t=!0,e.destroy(r)}})};class e extends _{constructor(e,t){super(t),this._reader=z(e)}async _read(e){try{for(;;){const{done:e,value:t}=await this._reader.read();if(e){this.push(null);break}if(!this.push(t))break}}catch(e){this.destroy(e)}}async _destroy(e,t){this._reader.cancel(e).then(t,t)}}A=function(t,r){return new e(t,r)}}const S=new WeakSet,E=Symbol("externalBuffer");function P(e){if(this.stream=e,e[E]&&(this[E]=e[E].slice()),l(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=async()=>{})}let t=m(e);if("node"===t&&(e=k(e)),t){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let r=!1;this._read=async()=>r||S.has(e)?{value:void 0,done:!0}:(r=!0,{value:e,done:!1}),this._releaseLock=()=>{if(r)try{S.add(e)}catch(e){}}}P.prototype.read=async function(){if(this[E]&&this[E].length){return{done:!1,value:this[E].shift()}}return this._read()},P.prototype.releaseLock=function(){this[E]&&(this.stream[E]=this[E]),this._releaseLock()},P.prototype.cancel=function(e){return this._cancel(e)},P.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:i}=await this.read();if(i+="",r)return t.length?T(t):void 0;const n=i.indexOf("\n")+1;n&&(e=T(t.concat(i.substr(0,n))),t=[]),n!==i.length&&t.push(i.substr(n))}return this.unshift(...t),e},P.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift($(t,1)),r},P.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:i,value:n}=await this.read();if(i)return t.length?T(t):void 0;if(t.push(n),r+=n.length,r>=e){const r=T(t);return this.unshift($(r,e)),$(r,0,e)}}},P.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},P.prototype.unshift=function(...e){this[E]||(this[E]=[]),1===e.length&&g(e[0])&&this[E].length&&e[0].length&&this[E][0].byteOffset>=e[0].length?this[E][0]=new Uint8Array(this[E][0].buffer,this[E][0].byteOffset-e[0].length,this[E][0].byteLength+e[0].length):this[E].unshift(...e.filter((e=>e&&e.length)))},P.prototype.readToEnd=async function(e=T){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};let x,M,{ReadableStream:K,WritableStream:C,TransformStream:D}=e;async function U(){if(D)return;const[t,r]=await Promise.all([Promise.resolve().then((function(){return Wp})),Promise.resolve().then((function(){return fy}))]);({ReadableStream:K,WritableStream:C,TransformStream:D}=t);const{createReadableStreamWrapper:i}=r;e.ReadableStream&&K!==e.ReadableStream&&(x=i(K),M=i(e.ReadableStream))}const R=y&&t.Buffer;function I(e){let t=m(e);return"node"===t?k(e):"web"===t&&x?x(e):t?e:new K({start(t){t.enqueue(e),t.close()}})}function B(e){if(m(e))return e;const t=new f;return(async()=>{const r=q(t);await r.write(e),await r.close()})(),t}function T(e){return e.some((e=>m(e)&&!l(e)))?function(e){e=e.map(I);const t=L((async function(e){await Promise.all(i.map((t=>X(t,e))))}));let r=Promise.resolve();const i=e.map(((i,n)=>j(i,((i,a)=>(r=r.then((()=>F(i,t.writable,{preventClose:n!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>l(e)))?function(e){const t=new f;let r=Promise.resolve();return e.forEach(((i,n)=>(r=r.then((()=>F(i,t,{preventClose:n!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):R&&R.isBuffer(e[0])?R.concat(e):w(e)}function z(e){return new P(e)}function q(e){return new p(e)}async function F(e,t,{preventClose:r=!1,preventAbort:i=!1,preventCancel:n=!1}={}){if(m(e)&&!l(e)){e=I(e);try{if(e[E]){const r=q(t);for(let t=0;t{t=e,r=i})),t=null,r=null)},close:i.close.bind(i),abort:i.error.bind(i)})}}function N(e,t=(()=>{}),r=(()=>{})){if(l(e)){const i=new f;return(async()=>{const n=q(i);try{const i=await Z(e),a=t(i),s=r();let o;o=void 0!==a&&void 0!==s?T([a,s]):void 0!==a?a:s,await n.write(o),await n.close()}catch(e){await n.abort(e)}})(),i}if(m(e))return O(e,{async transform(e,r){try{const i=await t(e);void 0!==i&&r.enqueue(i)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const i=t(e),n=r();return void 0!==i&&void 0!==n?T([i,n]):void 0!==i?i:n}function j(e,t){if(m(e)&&!l(e)){let r;const i=new D({start(e){r=e}}),n=F(e,i.writable),a=L((async function(e){r.error(e),await n,await new Promise(setTimeout)}));return t(i.readable,a.writable),a.readable}e=B(e);const r=new f;return t(e,r),r}function H(e,t){let r;const i=j(e,((e,n)=>{const a=z(e);a.remainder=()=>(a.releaseLock(),F(e,n),i),r=t(a)}));return r}function W(e){if(l(e))return e.clone();if(m(e)){const t=function(e){if(l(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(m(e)){const t=I(e).tee();return t[0][E]=t[1][E]=e[E],t}return[$(e),$(e)]}(e);return V(e,t[0]),t[1]}return $(e)}function G(e){return l(e)?W(e):m(e)?new K({start(t){const r=j(e,(async(e,r)=>{const i=z(e),n=q(r);try{for(;;){await n.ready;const{done:e,value:r}=await i.read();if(e){try{t.close()}catch(e){}return void await n.close()}try{t.enqueue(r)}catch(e){}await n.write(r)}}catch(e){t.error(e),await n.abort(e)}}));V(e,r)}}):$(e)}function V(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,i])=>{"constructor"!==r&&(i.value?i.value=i.value.bind(t):i.get=i.get.bind(t),Object.defineProperty(e,r,i))}))}function $(e,t=0,r=1/0){if(l(e))throw Error("Not implemented");if(m(e)){if(t>=0&&r>=0){let i=0;return O(e,{transform(e,n){i=t&&n.enqueue($(e,Math.max(t-i,0),r-i)),i+=e.length):n.terminate()}})}if(t<0&&(r<0||r===1/0)){let i=[];return N(e,(e=>{e.length>=-t?i=[e]:i.push(e)}),(()=>$(T(i),t,r)))}if(0===t&&r<0){let i;return N(e,(e=>{const n=i?T([i,e]):e;if(n.length>=-r)return i=$(n,r),$(n,t,r);i=n}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),Y((async()=>$(await Z(e),t,r)))}return e[E]&&(e=T(e[E].concat([e]))),!g(e)||R&&R.isBuffer(e)?e.slice(t,r):(r===1/0&&(r=e.length),e.subarray(t,r))}async function Z(e,t=T){return l(e)?e.readToEnd(t):m(e)?z(e).readToEnd(t):e}async function X(e,t){if(m(e)){if(e.cancel)return e.cancel(t);if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function Y(e){const t=new f;return(async()=>{const r=q(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}class Q{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");if(e instanceof Uint8Array){const t=e,r=Array(t.length);for(let e=0;eBigInt(0);){const e=r&BigInt(1);r>>=BigInt(1);const a=n*i%t.value;n=e?a:n,i=i*i%t.value}return new Q(n)}modInv(e){const{gcd:t,x:r}=this._egcd(e);if(!t.isOne())throw Error("Inverse does not exist");return r.add(e).mod(e)}_egcd(e){let t=BigInt(0),r=BigInt(1),i=BigInt(1),n=BigInt(0),a=this.value;for(e=e.value;e!==BigInt(0);){const s=a/e;let o=t;t=i-s*t,i=o,o=r,r=n-s*r,n=o,o=e,e=a%e,a=o}return{x:new Q(i),y:new Q(n),gcd:new Q(a)}}gcd(e){let t=this.value;for(e=e.value;e!==BigInt(0);){const r=e;e=t%e,t=r}return new Q(t)}ileftShift(e){return this.value<<=e.value,this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value>>=e.value,this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value===e.value}lt(e){return this.valuee.value}gte(e){return this.value>=e.value}isZero(){return this.value===BigInt(0)}isOne(){return this.value===BigInt(1)}isNegative(){return this.valueNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return e}getBit(e){return(this.value>>BigInt(e)&BigInt(1))===BigInt(0)?0:1}bitLength(){const e=new Q(0),t=new Q(1),r=new Q(-1),i=this.isNegative()?r:e;let n=1;const a=this.clone();for(;!a.irightShift(t).equal(i);)n++;return n}byteLength(){const e=new Q(0),t=new Q(-1),r=this.isNegative()?t:e,i=new Q(8);let n=1;const a=this.clone();for(;!a.irightShift(i).equal(r);)n++;return n}toUint8Array(e="be",t){let r=this.value.toString(16);r.length%2==1&&(r="0"+r);const i=r.length/2,n=new Uint8Array(t||i),a=t?t-i:0;let s=0;for(;s"undefined"!=typeof BigInt;const ee=Symbol("byValue");var te={curve:{p256:"p256","P-256":"p256",secp256r1:"p256",prime256v1:"p256","1.2.840.10045.3.1.7":"p256","2a8648ce3d030107":"p256","2A8648CE3D030107":"p256",p384:"p384","P-384":"p384",secp384r1:"p384","1.3.132.0.34":"p384","2b81040022":"p384","2B81040022":"p384",p521:"p521","P-521":"p521",secp521r1:"p521","1.3.132.0.35":"p521","2b81040023":"p521","2B81040023":"p521",secp256k1:"secp256k1","1.3.132.0.10":"secp256k1","2b8104000a":"secp256k1","2B8104000A":"secp256k1",ed25519Legacy:"ed25519",ED25519:"ed25519",ed25519:"ed25519",Ed25519:"ed25519","1.3.6.1.4.1.11591.15.1":"ed25519","2b06010401da470f01":"ed25519","2B06010401DA470F01":"ed25519",curve25519Legacy:"curve25519",X25519:"curve25519",cv25519:"curve25519",curve25519:"curve25519",Curve25519:"curve25519","1.3.6.1.4.1.3029.1.5.1":"curve25519","2b060104019755010501":"curve25519","2B060104019755010501":"curve25519",brainpoolP256r1:"brainpoolP256r1","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1","2b2403030208010107":"brainpoolP256r1","2B2403030208010107":"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1","2b240303020801010b":"brainpoolP384r1","2B240303020801010B":"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1","2b240303020801010d":"brainpoolP512r1","2B240303020801010D":"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,ed25519Legacy:22,eddsa:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuer:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[ee]||(e[ee]=[],Object.entries(e).forEach((([t,r])=>{e[ee][r]=t}))),void 0!==e[ee][t])return e[ee][t];throw Error("Invalid enum value.")}};const re=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),ie={isString:function(e){return"string"==typeof e||e instanceof String},isArray:function(e){return e instanceof Array},isUint8Array:g,isStream:m,readNumber:function(e){let t=0;for(let r=0;r>8*(t-i-1)&255;return r},readDate:function(e){const t=ie.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return ie.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return e.subarray(2,2+t)},leftPad(e,t){const r=new Uint8Array(t),i=t-e.length;return r.set(e,i),r},uint8ArrayToMPI:function(e){const t=ie.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),i=new Uint8Array([(65280&t)>>8,255&t]);return ie.concatUint8Array([i,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t=[],r=e.length;let i,n=0;for(;n{if(!ie.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return N(e,r,(()=>r(new Uint8Array,!0)))},concat:T,concatUint8Array:w,equalsUint8Array:function(e,t){if(!ie.isUint8Array(e)||!ie.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let i=0;i>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){return void 0!==e&&e.crypto&&e.crypto.subtle},getBigInteger:async function(){if(J())return Q;{const{default:e}=await Promise.resolve().then((function(){return my}));return e}},getNodeCrypto:function(){return i},getNodeZlib:function(){return n},getNodeBuffer:function(){return(t||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return a.cpus().length},isEmailAddress:function(e){if(!ie.isString(e))return!1;return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/.test(e)},canonicalizeEOL:function(e){let t=!1;return N(e,(e=>{let r;t&&(e=ie.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const i=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&i.push(r);if(!i.length)return e;const n=new Uint8Array(e.length+i.length);let a=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return N(e,(e=>{let r;13===(e=t&&10!==e[0]?ie.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let i=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const n=r-(10===e[r]?1:0);t&&e.copyWithin(i,t,n),i+=n-t}return e.subarray(0,i)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let i;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){i=e}}))),r(i)}))},selectUint8Array:function(e,t,r){const i=Math.max(t.length,r.length),n=new Uint8Array(i);let a=0;for(let i=0;i{t=ie.concatUint8Array([t,e]);const r=[],i=Math.floor(t.length/45),n=45*i,a=ae(t.subarray(0,n));for(let e=0;et.length?ae(t)+"\n":""))}function ce(e){let t="";return N(e,(e=>{t+=e;let r=0;const i=[" ","\t","\r","\n"];for(let e=0;e0&&(n-r)%4!=0;n--)i.includes(t[n])&&r--;const a=se(t.substr(0,n));return t=t.substr(n),a}),(()=>se(t)))}function ue(e){return ce(e.replace(/-/g,"+").replace(/_/g,"/"))}function he(e,t){let r=oe(e).replace(/[\r\n]/g,"");return t&&(r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,"")),r}ne?(ae=e=>ne.from(e).toString("base64"),se=e=>{const t=ne.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(ae=e=>btoa(ie.uint8ArrayToString(e)),se=e=>ie.stringToUint8Array(atob(e)));var de={preferredHashAlgorithm:te.hash.sha256,preferredSymmetricAlgorithm:te.symmetric.aes256,preferredCompressionAlgorithm:te.compression.uncompressed,deflateLevel:6,aeadProtect:!1,preferredAEADAlgorithm:te.aead.eax,aeadChunkSizeByte:12,v5Keys:!1,s2kIterationCountByte:224,allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,checksumRequired:!1,minRSABits:2047,passwordCollisionCheck:!1,revocationsExpire:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([te.symmetric.aes128,te.symmetric.aes192,te.symmetric.aes256]),minBytesForWebCrypto:1e3,ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 5.11.2",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],useIndutnyElliptic:!0,rejectHashAlgorithms:new Set([te.hash.md5,te.hash.ripemd]),rejectMessageHashAlgorithms:new Set([te.hash.md5,te.hash.ripemd,te.hash.sha1]),rejectPublicKeyAlgorithms:new Set([te.publicKey.elgamal,te.publicKey.dsa]),rejectCurves:new Set([te.curve.secp256k1])};function fe(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?te.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?te.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?te.armor.signed:/MESSAGE/.test(t[1])?te.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?te.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?te.armor.privateKey:/SIGNATURE/.test(t[1])?te.armor.signature:void 0}function le(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function pe(e){return oe(function(e){let t=13501623;return N(e,(e=>{const r=be?Math.floor(e.length/4):0,i=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^ye[1][t>>16&255]^ye[2][t>>8&255]^ye[3][t>>0&255];for(let i=4*r;i>8^ye[0][255&t^e[i]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e))}const ye=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(0!=(8388608&t)?8801531:0);ye[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)ye[1][e]=ye[0][e]>>8^ye[0][255&ye[0][e]];for(let e=0;e<=255;e++)ye[2][e]=ye[1][e]>>8^ye[0][255&ye[1][e]];for(let e=0;e<=255;e++)ye[3][e]=ye[2][e]>>8^ye[0][255&ye[2][e]];const be=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function me(e){for(let t=0;t=0&&i!==e.length-1&&(t=e.slice(0,i),r=e.slice(i+1).substr(0,4)),{body:t,checksum:r}}function we(e,t=de){return new Promise((async(r,i)=>{try{const n=/^-----[^-]+-----$/m,a=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const o=[];let c,u,h,d=o,f=[],l=ce(j(e,(async(e,t)=>{const p=z(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=ie.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(c)u||2!==s||(n.test(e)?(f=f.join("\r\n"),u=!0,me(d),d=[],c=!1):f.push(e.replace(/^- /,"")));else if(n.test(e)&&i(Error("Mandatory blank line missing between armor headers and armor data")),a.test(e)){if(me(d),c=!0,u||2!==s){r({text:f,data:l,headers:o,type:s});break}}else d.push(e);else n.test(e)&&(s=fe(e))}}catch(e){return void i(e)}const y=q(t);try{for(;;){await y.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=ie.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=ge(t[0].slice(0,-1));h=i.checksum,await y.write(i.body);break}await y.write(r)}await y.ready,await y.close()}catch(e){await y.abort(e)}})));l=j(l,(async(e,r)=>{const i=Z(pe(G(e)));i.catch((()=>{})),await F(e,r,{preventClose:!0});const n=q(r);try{const e=(await i).replace("\n","");if(h!==e&&(h||t.checksumRequired))throw Error("Ascii armor integrity check failed");await n.ready,await n.close()}catch(e){await n.abort(e)}}))}catch(e){i(e)}})).then((async e=>(l(e.data)&&(e.data=await Z(e.data)),e)))}function ve(e,t,r,i,n,a=de){let s,o;e===te.armor.signed&&(s=t.text,o=t.hash,t=t.data);const c=G(t),u=[];switch(e){case te.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+i+"-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP MESSAGE, PART "+r+"/"+i+"-----\n");break;case te.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case te.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push("Hash: "+o+"\n\n"),u.push(s.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP SIGNATURE-----\n");break;case te.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP MESSAGE-----\n");break;case te.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case te.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case te.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(le(n,a)),u.push(oe(t)),u.push("=",pe(c)),u.push("-----END PGP SIGNATURE-----\n")}return ie.concat(u)}class _e{constructor(){this.bytes=""}read(e){return this.bytes=ie.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return ie.stringToUint8Array(this.bytes)}toHex(){return ie.uint8ArrayToHex(ie.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new _e;return t.read(ie.hexToUint8Array(e)),t}static wildcard(){const e=new _e;return e.read(new Uint8Array(8)),e}}var ke=function(){var e,t,r=!1;function i(r,i){var n=e[(t[r]+t[i])%255];return 0!==r&&0!==i||(n=0),n}var n,a,s,o,c=!1;function u(){function u(r){var i,n,a;for(n=a=function(r){var i=e[255-t[r]];return 0===r&&(i=0),i}(r),i=0;i<4;i++)a^=n=255&(n<<1|n>>>7);return a^=99}r||function(){e=[],t=[];var i,n,a=1;for(i=0;i<255;i++)e[i]=a,n=128&a,a<<=1,a&=255,128===n&&(a^=27),a^=e[i],t[e[i]]=i;e[255]=e[0],t[0]=0,r=!0}(),n=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var h=0;h<256;h++){var d=u(h);n[h]=d,a[d]=h,s[0][h]=i(2,d)<<24|d<<16|d<<8|i(3,d),o[0][d]=i(14,h)<<24|i(9,h)<<16|i(13,h)<<8|i(11,h);for(var f=1;f<4;f++)s[f][h]=s[f-1][h]>>>8|s[f-1][h]<<24,o[f][d]=o[f-1][d]>>>8|o[f-1][d]<<24}c=!0}var h=function(e,t){c||u();var r=new Uint32Array(t);r.set(n,512),r.set(a,768);for(var i=0;i<4;i++)r.set(s[i],4096+1024*i>>2),r.set(o[i],8192+1024*i>>2);var h=function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0;var S=new e.Uint32Array(r),E=new e.Uint8Array(r);function P(e,t,r,o,c,u,h,d){e=e|0;t=t|0;r=r|0;o=o|0;c=c|0;u=u|0;h=h|0;d=d|0;var f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;f=r|0x400,l=r|0x800,p=r|0xc00;c=c^S[(e|0)>>2],u=u^S[(e|4)>>2],h=h^S[(e|8)>>2],d=d^S[(e|12)>>2];for(w=16;(w|0)<=o<<4;w=w+16|0){y=S[(r|c>>22&1020)>>2]^S[(f|u>>14&1020)>>2]^S[(l|h>>6&1020)>>2]^S[(p|d<<2&1020)>>2]^S[(e|w|0)>>2],b=S[(r|u>>22&1020)>>2]^S[(f|h>>14&1020)>>2]^S[(l|d>>6&1020)>>2]^S[(p|c<<2&1020)>>2]^S[(e|w|4)>>2],m=S[(r|h>>22&1020)>>2]^S[(f|d>>14&1020)>>2]^S[(l|c>>6&1020)>>2]^S[(p|u<<2&1020)>>2]^S[(e|w|8)>>2],g=S[(r|d>>22&1020)>>2]^S[(f|c>>14&1020)>>2]^S[(l|u>>6&1020)>>2]^S[(p|h<<2&1020)>>2]^S[(e|w|12)>>2];c=y,u=b,h=m,d=g}i=S[(t|c>>22&1020)>>2]<<24^S[(t|u>>14&1020)>>2]<<16^S[(t|h>>6&1020)>>2]<<8^S[(t|d<<2&1020)>>2]^S[(e|w|0)>>2],n=S[(t|u>>22&1020)>>2]<<24^S[(t|h>>14&1020)>>2]<<16^S[(t|d>>6&1020)>>2]<<8^S[(t|c<<2&1020)>>2]^S[(e|w|4)>>2],a=S[(t|h>>22&1020)>>2]<<24^S[(t|d>>14&1020)>>2]<<16^S[(t|c>>6&1020)>>2]<<8^S[(t|u<<2&1020)>>2]^S[(e|w|8)>>2],s=S[(t|d>>22&1020)>>2]<<24^S[(t|c>>14&1020)>>2]<<16^S[(t|u>>6&1020)>>2]<<8^S[(t|h<<2&1020)>>2]^S[(e|w|12)>>2]}function x(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;P(0x0000,0x0800,0x1000,A,e,t,r,i)}function M(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var a=0;P(0x0400,0x0c00,0x2000,A,e,i,r,t);a=n,n=s,s=a}function K(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o^e,c^t,u^r,h^d);o=i,c=n,u=a,h=s}function C(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;var f=0;P(0x0400,0x0c00,0x2000,A,e,d,r,t);f=n,n=s,s=f;i=i^o,n=n^c,a=a^u,s=s^h;o=e,c=t,u=r,h=d}function D(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i=i^e,c=n=n^t,u=a=a^r,h=s=s^d}function U(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);i=i^e,n=n^t,a=a^r,s=s^d;o=e,c=t,u=r,h=d}function R(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i,c=n,u=a,h=s;i=i^e,n=n^t,a=a^r,s=s^d}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;P(0x0000,0x0800,0x1000,A,d,f,l,p);p=~g&p|g&p+1;l=~m&l|m&l+((p|0)==0);f=~b&f|b&f+((l|0)==0);d=~y&d|y&d+((f|0)==0);i=i^e;n=n^t;a=a^r;s=s^o}function B(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,a=0,s=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0;e=e^o,t=t^c,r=r^u,i=i^h;n=w|0,a=v|0,s=_|0,d=k|0;for(;(b|0)<128;b=b+1|0){if(n>>>31){f=f^e,l=l^t,p=p^r,y=y^i}n=n<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|d>>>31,d=d<<1;m=i&1;i=i>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(m)e=e^0xe1000000}o=f,c=l,u=p,h=y}function T(e){e=e|0;A=e}function z(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;i=e,n=t,a=r,s=o}function q(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;o=e,c=t,u=r,h=i}function F(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;d=e,f=t,l=r,p=i}function O(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;y=e,b=t,m=r,g=i}function L(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;p=~g&p|g&i,l=~m&l|m&r,f=~b&f|b&t,d=~y&d|y&e}function N(e){e=e|0;if(e&15)return-1;E[e|0]=i>>>24,E[e|1]=i>>>16&255,E[e|2]=i>>>8&255,E[e|3]=i&255,E[e|4]=n>>>24,E[e|5]=n>>>16&255,E[e|6]=n>>>8&255,E[e|7]=n&255,E[e|8]=a>>>24,E[e|9]=a>>>16&255,E[e|10]=a>>>8&255,E[e|11]=a&255,E[e|12]=s>>>24,E[e|13]=s>>>16&255,E[e|14]=s>>>8&255,E[e|15]=s&255;return 16}function j(e){e=e|0;if(e&15)return-1;E[e|0]=o>>>24,E[e|1]=o>>>16&255,E[e|2]=o>>>8&255,E[e|3]=o&255,E[e|4]=c>>>24,E[e|5]=c>>>16&255,E[e|6]=c>>>8&255,E[e|7]=c&255,E[e|8]=u>>>24,E[e|9]=u>>>16&255,E[e|10]=u>>>8&255,E[e|11]=u&255,E[e|12]=h>>>24,E[e|13]=h>>>16&255,E[e|14]=h>>>8&255,E[e|15]=h&255;return 16}function H(){x(0,0,0,0);w=i,v=n,_=a,k=s}function W(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){V[e&7](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);E[t|0]=i>>>24,E[t|1]=i>>>16&255,E[t|2]=i>>>8&255,E[t|3]=i&255,E[t|4]=n>>>24,E[t|5]=n>>>16&255,E[t|6]=n>>>8&255,E[t|7]=n&255,E[t|8]=a>>>24,E[t|9]=a>>>16&255,E[t|10]=a>>>8&255,E[t|11]=a&255,E[t|12]=s>>>24,E[t|13]=s>>>16&255,E[t|14]=s>>>8&255,E[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function G(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t&15)return-1;while((r|0)>=16){$[e&1](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);i=i+16|0,t=t+16|0,r=r-16|0}return i|0}var V=[x,M,K,C,D,U,R,I];var $=[K,B];return{set_rounds:T,set_state:z,set_iv:q,set_nonce:F,set_mask:O,set_counter:L,get_state:N,get_iv:j,gcm_init:H,cipher:W,mac:G}}({Uint8Array,Uint32Array},e,t);return h.set_key=function(e,t,i,a,s,c,u,d,f){var l=r.subarray(0,60),p=r.subarray(256,316);l.set([t,i,a,s,c,u,d,f]);for(var y=e,b=1;y<4*e+28;y++){var m=l[y-1];(y%e==0||8===e&&y%e==4)&&(m=n[m>>>24]<<24^n[m>>>16&255]<<16^n[m>>>8&255]<<8^n[255&m]),y%e==0&&(m=m<<8^m>>>24^b<<24,b=b<<1^(128&b?27:0)),l[y]=l[y-e]^m}for(var g=0;g=y-4?m:o[0][n[m>>>24]]^o[1][n[m>>>16&255]]^o[2][n[m>>>8&255]]^o[3][n[255&m]]}h.set_rounds(e+5)},h};return h.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},h.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},h.MAC={CBC:0,GCM:1},h.HEAP_DATA=16384,h}();function Ae(e){return e instanceof Uint8Array}function Se(e,t){const r=e?e.byteLength:t||65536;if(4095&r||r<=0)throw Error("heap size must be a positive integer and a multiple of 4096");return e=e||new Uint8Array(new ArrayBuffer(r))}function Ee(e,t,r,i,n){const a=e.length-t,s=ae+t.length),0),r=new Uint8Array(t);let i=0;for(let t=0;t>2,n.getUint32(0),n.getUint32(4),n.getUint32(8),n.getUint32(12),i>16?n.getUint32(16):0,i>16?n.getUint32(20):0,i>24?n.getUint32(24):0,i>24?n.getUint32(28):0),void 0!==t){if(16!==t.length)throw new Me("illegal iv size");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);r.set_iv(e.getUint32(0),e.getUint32(4),e.getUint32(8),e.getUint32(12))}else r.set_iv(0,0,0,0)}AES_Encrypt_process(e){if(!Ae(e))throw new TypeError("data isn't of expected type");let{heap:t,asm:r}=this.acquire_asm(),i=ke.ENC[this.mode],n=ke.HEAP_DATA,a=this.pos,s=this.len,o=0,c=e.length||0,u=0,h=0,d=new Uint8Array(s+c&-16);for(;c>0;)h=Ee(t,a+s,e,o,c),s+=h,o+=h,c-=h,h=r.cipher(i,n+a,s),h&&d.set(t.subarray(a,a+h),u),u+=h,h0;)f=Ee(t,a+s,e,o,c),s+=f,o+=f,c-=f,f=r.cipher(i,n+a,s-(c?0:d)),f&&l.set(t.subarray(a,a+f),u),u+=f,f0){if(a%16){if(this.hasOwnProperty("padding"))throw new Me("data length must be a multiple of the block size");a+=16-a%16}if(t.cipher(r,i+n,a),this.hasOwnProperty("padding")&&this.padding){let t=e[n+s-1];if(t<1||t>16||t>s)throw new Ke("bad padding");let r=0;for(let i=t;i>1;i--)r|=t^e[n+s-i];if(r)throw new Ke("bad padding");s-=t}}const o=new Uint8Array(s);return s>0&&o.set(e.subarray(n,n+s)),this.pos=0,this.len=0,this.release_asm(),o}}class Re{static encrypt(e,t,r=!1){return new Re(t,r).encrypt(e)}static decrypt(e,t,r=!1){return new Re(t,r).decrypt(e)}constructor(e,t=!1,r){this.aes=r||new Ue(e,void 0,t,"ECB")}encrypt(e){return Pe(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return Pe(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}function Ie(e){const t=function(e){const t=new Re(e);this.encrypt=function(e){return t.encrypt(e)},this.decrypt=function(e){return t.decrypt(e)}};return t.blockSize=t.prototype.blockSize=16,t.keySize=t.prototype.keySize=e/8,t}function Be(e,t,r,i,n,a){const s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],u=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],h=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],d=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],f=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],l=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,y,b,m,g,w,v,_,k,A,S,E,P,x,M=0,K=t.length;const C=32===e.length?3:9;_=3===C?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e,t){const r=8-e.length%8;let i;if(2===t&&r<8)i=32;else if(1===t)i=r;else{if(t||!(r<8)){if(8===r)return e;throw Error("des: invalid padding")}i=0}const n=new Uint8Array(e.length+r);for(let t=0;t>>4^v),v^=b,w^=b<<4,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,w=w<<1|w>>>31,v=v<<1|v>>>31,y=0;y>>4|v<<28)^e[p+1],b=w,w=v,v=b^(o[m>>>24&63]|u[m>>>16&63]|d[m>>>8&63]|l[63&m]|s[g>>>24&63]|c[g>>>16&63]|h[g>>>8&63]|f[63&g]);b=w,w=v,v=b}w=w>>>1|w<<31,v=v>>>1|v<<31,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=252645135&(w>>>4^v),v^=b,w^=b<<4,1===i&&(r?(k=w,S=v):(w^=A,v^=E)),D[U++]=w>>>24,D[U++]=w>>>16&255,D[U++]=w>>>8&255,D[U++]=255&w,D[U++]=v>>>24,D[U++]=v>>>16&255,D[U++]=v>>>8&255,D[U++]=255&v}return r||(D=function(e,t){let r,i=null;if(2===t)r=32;else if(1===t)i=e[e.length-1];else{if(t)throw Error("des: invalid padding");r=0}if(!i){for(i=1;e[e.length-i]===r;)i++;i--}return e.subarray(0,e.length-i)}(D,a)),D}function Te(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],l=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length>8?3:1,b=Array(32*y),m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let g,w,v,_=0,k=0;for(let A=0;A>>4^A),A^=v,y^=v<<4,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=858993459&(y>>>2^A),A^=v,y^=v<<2,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=16711935&(A>>>8^y),y^=v,A^=v<<8,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=y<<8|A>>>20&240,y=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=v;for(let e=0;e<16;e++)m[e]?(y=y<<2|y>>>26,A=A<<2|A>>>26):(y=y<<1|y>>>27,A=A<<1|A>>>27),y&=-15,A&=-15,g=t[y>>>28]|r[y>>>24&15]|i[y>>>20&15]|n[y>>>16&15]|a[y>>>12&15]|s[y>>>8&15]|o[y>>>4&15],w=c[A>>>28]|u[A>>>24&15]|h[A>>>20&15]|d[A>>>16&15]|f[A>>>12&15]|l[A>>>8&15]|p[A>>>4&15],v=65535&(w>>>16^g),b[k++]=g^v,b[k++]=w^v<<16}return b}function ze(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Be(Te(this.key[2]),Be(Te(this.key[1]),Be(Te(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}function qe(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>>16&255,t[a+6]=o>>>8&255,t[a+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>16&255,t[a+6]=o>>8&255,t[a+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const i=t+e,n=i<>>32-r;return(a[0][n>>>24]^a[1][n>>>16&255])-a[2][n>>>8&255]+a[3][255&n]}function i(e,t,r){const i=t^e,n=i<>>32-r;return a[0][n>>>24]-a[1][n>>>16&255]+a[2][n>>>8&255]^a[3][255&n]}function n(e,t,r){const i=t-e,n=i<>>32-r;return(a[0][n>>>24]+a[1][n>>>16&255]^a[2][n>>>8&255])-a[3][255&n]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const i=[,,,,,,,,],n=Array(32);let s;for(let e=0;e<4;e++)s=4*e,i[e]=r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3];const o=[6,7,4,5];let c,u=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(s=0;s<4;s++){const t=e[r][s];c=i[t[1]],c^=a[4][i[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=a[5][i[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=a[6][i[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=a[7][i[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=a[o[s]][i[t[6]>>>2]>>>24-8*(3&t[6])&255],i[t[0]]=c}for(s=0;s<4;s++){const e=t[r][s];c=a[4][i[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=a[5][i[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=a[6][i[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=a[7][i[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=a[4+s][i[e[4]>>>2]>>>24-8*(3&e[4])&255],n[u]=c,u++}}for(let e=0;e<16;e++)this.masking[e]=n[e],this.rotate[e]=31&n[16+e]};const a=[,,,,,,,,];a[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],a[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],a[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],a[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],a[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],a[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],a[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],a[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Fe(e){this.cast5=new qe,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}ze.keySize=ze.prototype.keySize=24,ze.blockSize=ze.prototype.blockSize=8,Fe.blockSize=Fe.prototype.blockSize=8,Fe.keySize=Fe.prototype.keySize=16;const Oe=4294967295;function Le(e,t){return(e<>>32-t)&Oe}function Ne(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function je(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function He(e,t){return e>>>8*t&255}function We(e){this.tf=function(){let e=null,t=null,r=-1,i=[],n=[[],[],[],[]];function a(e){return n[0][He(e,0)]^n[1][He(e,1)]^n[2][He(e,2)]^n[3][He(e,3)]}function s(e){return n[0][He(e,3)]^n[1][He(e,0)]^n[2][He(e,1)]^n[3][He(e,2)]}function o(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Le(t[2]^r+n+i[4*e+8]&Oe,31),t[3]=Le(t[3],1)^r+2*n+i[4*e+9]&Oe,r=a(t[2]),n=s(t[3]),t[0]=Le(t[0]^r+n+i[4*e+10]&Oe,31),t[1]=Le(t[1],1)^r+2*n+i[4*e+11]&Oe}function c(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Le(t[2],1)^r+n+i[4*e+10]&Oe,t[3]=Le(t[3]^r+2*n+i[4*e+11]&Oe,31),r=a(t[2]),n=s(t[3]),t[0]=Le(t[0],1)^r+n+i[4*e+8]&Oe,t[1]=Le(t[1]^r+2*n+i[4*e+9]&Oe,31)}return{name:"twofish",blocksize:16,open:function(t){let r,a,s,o,c;e=t;const u=[],h=[],d=[];let f;const l=[];let p,y,b;const m=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],g=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],w=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],v=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],_=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],k=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],A=[[],[]],S=[[],[],[],[]];function E(e){return e^e>>2^[0,90,180,238][3&e]}function P(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function x(e,t){let r,i,n;for(r=0;r<8;r++)i=t>>>24,t=t<<8&Oe|e>>>24,e=e<<8&Oe,n=i<<1,128&i&&(n^=333),t^=i^n<<16,n^=i>>>1,1&i&&(n^=166),t^=n<<24|n<<8;return t}function M(e,t){const r=t>>4,i=15&t,n=m[e][r^i],a=g[e][_[i]^k[r]];return v[e][_[a]^k[n]]<<4|w[e][n^a]}function K(e,t){let r=He(e,0),i=He(e,1),n=He(e,2),a=He(e,3);switch(f){case 4:r=A[1][r]^He(t[3],0),i=A[0][i]^He(t[3],1),n=A[0][n]^He(t[3],2),a=A[1][a]^He(t[3],3);case 3:r=A[1][r]^He(t[2],0),i=A[1][i]^He(t[2],1),n=A[0][n]^He(t[2],2),a=A[0][a]^He(t[2],3);case 2:r=A[0][A[0][r]^He(t[1],0)]^He(t[0],0),i=A[0][A[1][i]^He(t[1],1)]^He(t[0],1),n=A[1][A[0][n]^He(t[1],2)]^He(t[0],2),a=A[1][A[1][a]^He(t[1],3)]^He(t[0],3)}return S[0][r]^S[1][i]^S[2][n]^S[3][a]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Ne(e,r);for(r=0;r<256;r++)A[0][r]=M(0,r),A[1][r]=M(1,r);for(r=0;r<256;r++)p=A[1][r],y=E(p),b=P(p),S[0][r]=p+(y<<8)+(b<<16)+(b<<24),S[2][r]=y+(b<<8)+(p<<16)+(b<<24),p=A[0][r],y=E(p),b=P(p),S[1][r]=b+(b<<8)+(y<<16)+(p<<24),S[3][r]=y+(p<<8)+(b<<16)+(y<<24);for(f=d.length/2,r=0;r=0;e--)c(e,a);je(t,r,a[2]^i[0]),je(t,r+4,a[3]^i[1]),je(t,r+8,a[0]^i[2]),je(t,r+12,a[1]^i[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Ge(){}function Ve(e){this.bf=new Ge,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}We.keySize=We.prototype.keySize=32,We.blockSize=We.prototype.blockSize=16,Ge.prototype.BLOCKSIZE=8,Ge.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Ge.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Ge.prototype.NN=16,Ge.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Ge.prototype._F=function(e){let t;const r=255&e,i=255&(e>>>=8),n=255&(e>>>=8),a=255&(e>>>=8);return t=this.sboxes[0][a]+this.sboxes[1][n],t^=this.sboxes[2][i],t+=this.sboxes[3][r],t},Ge.prototype._encryptBlock=function(e){let t,r=e[0],i=e[1];for(t=0;t>>24-8*t&255,n[t+i]=r[1]>>>24-8*t&255;return n},Ge.prototype._decryptBlock=function(e){let t,r=e[0],i=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],i=this._F(r)^i;const e=r;r=i,i=e}r^=this.parray[1],i^=this.parray[0],e[0]=this._clean(i),e[1]=this._clean(r)},Ge.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^i}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const i=[0,0];for(t=0;t>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=t+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=r+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=c+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=u+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=h+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=d+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=f+(_<<5|_>>>27)+E+(k&A|~k&S)+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^we^me;Re=P<<1|P>>>31;x=Re+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=De^Pe^ve^ge;Ie=P<<1|P>>>31;x=Ie+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=Ue^xe^_e^we;Be=P<<1|P>>>31;x=Be+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=Re^Me^ke^ve;Te=P<<1|P>>>31;x=Te+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=Ie^Ke^Ae^_e;ze=P<<1|P>>>31;x=ze+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;i=i+_|0;n=n+k|0;a=a+A|0;s=s+S|0;o=o+E|0}function k(e){e=e|0;_(v[e|0]<<24|v[e|1]<<16|v[e|2]<<8|v[e|3],v[e|4]<<24|v[e|5]<<16|v[e|6]<<8|v[e|7],v[e|8]<<24|v[e|9]<<16|v[e|10]<<8|v[e|11],v[e|12]<<24|v[e|13]<<16|v[e|14]<<8|v[e|15],v[e|16]<<24|v[e|17]<<16|v[e|18]<<8|v[e|19],v[e|20]<<24|v[e|21]<<16|v[e|22]<<8|v[e|23],v[e|24]<<24|v[e|25]<<16|v[e|26]<<8|v[e|27],v[e|28]<<24|v[e|29]<<16|v[e|30]<<8|v[e|31],v[e|32]<<24|v[e|33]<<16|v[e|34]<<8|v[e|35],v[e|36]<<24|v[e|37]<<16|v[e|38]<<8|v[e|39],v[e|40]<<24|v[e|41]<<16|v[e|42]<<8|v[e|43],v[e|44]<<24|v[e|45]<<16|v[e|46]<<8|v[e|47],v[e|48]<<24|v[e|49]<<16|v[e|50]<<8|v[e|51],v[e|52]<<24|v[e|53]<<16|v[e|54]<<8|v[e|55],v[e|56]<<24|v[e|57]<<16|v[e|58]<<8|v[e|59],v[e|60]<<24|v[e|61]<<16|v[e|62]<<8|v[e|63])}function A(e){e=e|0;v[e|0]=i>>>24;v[e|1]=i>>>16&255;v[e|2]=i>>>8&255;v[e|3]=i&255;v[e|4]=n>>>24;v[e|5]=n>>>16&255;v[e|6]=n>>>8&255;v[e|7]=n&255;v[e|8]=a>>>24;v[e|9]=a>>>16&255;v[e|10]=a>>>8&255;v[e|11]=a&255;v[e|12]=s>>>24;v[e|13]=s>>>16&255;v[e|14]=s>>>8&255;v[e|15]=s&255;v[e|16]=o>>>24;v[e|17]=o>>>16&255;v[e|18]=o>>>8&255;v[e|19]=o&255}function S(){i=0x67452301;n=0xefcdab89;a=0x98badcfe;s=0x10325476;o=0xc3d2e1f0;c=u=0}function E(e,t,r,h,d,f,l){e=e|0;t=t|0;r=r|0;h=h|0;d=d|0;f=f|0;l=l|0;i=e;n=t;a=r;s=h;o=d;c=f;u=l}function P(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){k(e);e=e+64|0;t=t-64|0;r=r+64|0}c=c+r|0;if(c>>>0>>0)u=u+1|0;return r|0}function x(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=P(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;c=c+t|0;if(c>>>0>>0)u=u+1|0;v[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)v[e|n]=0x00;k(e);t=0;v[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)v[e|n]=0;v[e|56]=u>>>21&255;v[e|57]=u>>>13&255;v[e|58]=u>>>5&255;v[e|59]=u<<3&255|c>>>29;v[e|60]=c>>>21&255;v[e|61]=c>>>13&255;v[e|62]=c>>>5&255;v[e|63]=c<<3&255;k(e);if(~r)A(r);return i|0}function M(){i=h;n=d;a=f;s=l;o=p;c=64;u=0}function K(){i=y;n=b;a=m;s=g;o=w;c=64;u=0}function C(e,t,r,v,k,A,E,P,x,M,K,C,D,U,R,I){e=e|0;t=t|0;r=r|0;v=v|0;k=k|0;A=A|0;E=E|0;P=P|0;x=x|0;M=M|0;K=K|0;C=C|0;D=D|0;U=U|0;R=R|0;I=I|0;S();_(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,v^0x5c5c5c5c,k^0x5c5c5c5c,A^0x5c5c5c5c,E^0x5c5c5c5c,P^0x5c5c5c5c,x^0x5c5c5c5c,M^0x5c5c5c5c,K^0x5c5c5c5c,C^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,R^0x5c5c5c5c,I^0x5c5c5c5c);y=i;b=n;m=a;g=s;w=o;S();_(e^0x36363636,t^0x36363636,r^0x36363636,v^0x36363636,k^0x36363636,A^0x36363636,E^0x36363636,P^0x36363636,x^0x36363636,M^0x36363636,K^0x36363636,C^0x36363636,D^0x36363636,U^0x36363636,R^0x36363636,I^0x36363636);h=i;d=n;f=a;l=s;p=o;c=64;u=0}function D(e,t,r){e=e|0;t=t|0;r=r|0;var c=0,u=0,h=0,d=0,f=0,l=0;if(e&63)return-1;if(~r)if(r&31)return-1;l=x(e,t,-1)|0;c=i,u=n,h=a,d=s,f=o;K();_(c,u,h,d,f,0x80000000,0,0,0,0,0,0,0,0,0,672);if(~r)A(r);return l|0}function U(e,t,r,c,u){e=e|0;t=t|0;r=r|0;c=c|0;u=u|0;var h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;if(e&63)return-1;if(~u)if(u&31)return-1;v[e+t|0]=r>>>24;v[e+t+1|0]=r>>>16&255;v[e+t+2|0]=r>>>8&255;v[e+t+3|0]=r&255;D(e,t+4|0,-1)|0;h=y=i,d=b=n,f=m=a,l=g=s,p=w=o;c=c-1|0;while((c|0)>0){M();_(y,b,m,g,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,m=a,g=s,w=o;K();_(y,b,m,g,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,m=a,g=s,w=o;h=h^i;d=d^n;f=f^a;l=l^s;p=p^o;c=c-1|0}i=h;n=d;a=f;s=l;o=p;if(~u)A(u);return 0}return{reset:S,init:E,process:P,finish:x,hmac_reset:M,hmac_init:C,hmac_finish:D,pbkdf2_generate_block:U}};class et{constructor(){this.pos=0,this.len=0}reset(){const{asm:e}=this.acquire_asm();return this.result=null,this.pos=0,this.len=0,e.reset(),this}process(e){if(null!==this.result)throw new xe("state must be reset before processing new data");const{asm:t,heap:r}=this.acquire_asm();let i=this.pos,n=this.len,a=0,s=e.length,o=0;for(;s>0;)o=Ee(r,i+n,e,a,s),n+=o,a+=o,s-=o,o=t.process(i,n),i+=o,n-=o,n||(i=0);return this.pos=i,this.len=n,this}finish(){if(null!==this.result)throw new xe("state must be reset before processing new data");const{asm:e,heap:t}=this.acquire_asm();return e.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(t.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this.release_asm(),this}}const tt=[],rt=[];class it extends et{constructor(){super(),this.NAME="sha1",this.BLOCK_SIZE=64,this.HASH_SIZE=20,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=tt.pop()||Se(),this.asm=rt.pop()||Je({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(tt.push(this.heap),rt.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new it).process(e).finish().result}}it.NAME="sha1",it.heap_pool=[],it.asm_pool=[],it.asm_function=Je;const nt=[],at=[];class st extends et{constructor(){super(),this.NAME="sha256",this.BLOCK_SIZE=64,this.HASH_SIZE=32,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=nt.pop()||Se(),this.asm=at.pop()||function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=new e.Uint8Array(r);function C(e,t,r,d,f,l,p,y,b,m,g,w,v,_,k,A){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;l=l|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;w=w|0;v=v|0;_=_|0;k=k|0;A=A|0;var S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0;S=i;E=n;P=a;x=s;M=o;K=c;C=u;D=h;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x428a2f98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x71374491|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb5c0fbcf|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xe9b5dba5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x3956c25b|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x59f111f1|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x923f82a4|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xab1c5ed5|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xd807aa98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x12835b01|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x243185be|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x550c7dc3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x72be5d74|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x80deb1fe|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x9bdc06a7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc19bf174|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xe49b69c1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xefbe4786|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x0fc19dc6|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x240ca1cc|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x2de92c6f|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4a7484aa|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5cb0a9dc|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x76f988da|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x983e5152|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa831c66d|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb00327c8|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xbf597fc7|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xc6e00bf3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd5a79147|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x06ca6351|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x14292967|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x27b70a85|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x2e1b2138|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x4d2c6dfc|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x53380d13|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x650a7354|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x766a0abb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x81c2c92e|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x92722c85|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xa2bfe8a1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa81a664b|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xc24b8b70|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xc76c51a3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xd192e819|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd6990624|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xf40e3585|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x106aa070|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x19a4c116|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x1e376c08|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x2748774c|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x34b0bcb5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x391c0cb3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4ed8aa4a|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5b9cca4f|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x682e6ff3|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x748f82ee|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x78a5636f|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x84c87814|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x8cc70208|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x90befffa|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xa4506ceb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xbef9a3f7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc67178f2|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;i=i+S|0;n=n+E|0;a=a+P|0;s=s+x|0;o=o+M|0;c=c+K|0;u=u+C|0;h=h+D|0}function D(e){e=e|0;C(K[e|0]<<24|K[e|1]<<16|K[e|2]<<8|K[e|3],K[e|4]<<24|K[e|5]<<16|K[e|6]<<8|K[e|7],K[e|8]<<24|K[e|9]<<16|K[e|10]<<8|K[e|11],K[e|12]<<24|K[e|13]<<16|K[e|14]<<8|K[e|15],K[e|16]<<24|K[e|17]<<16|K[e|18]<<8|K[e|19],K[e|20]<<24|K[e|21]<<16|K[e|22]<<8|K[e|23],K[e|24]<<24|K[e|25]<<16|K[e|26]<<8|K[e|27],K[e|28]<<24|K[e|29]<<16|K[e|30]<<8|K[e|31],K[e|32]<<24|K[e|33]<<16|K[e|34]<<8|K[e|35],K[e|36]<<24|K[e|37]<<16|K[e|38]<<8|K[e|39],K[e|40]<<24|K[e|41]<<16|K[e|42]<<8|K[e|43],K[e|44]<<24|K[e|45]<<16|K[e|46]<<8|K[e|47],K[e|48]<<24|K[e|49]<<16|K[e|50]<<8|K[e|51],K[e|52]<<24|K[e|53]<<16|K[e|54]<<8|K[e|55],K[e|56]<<24|K[e|57]<<16|K[e|58]<<8|K[e|59],K[e|60]<<24|K[e|61]<<16|K[e|62]<<8|K[e|63])}function U(e){e=e|0;K[e|0]=i>>>24;K[e|1]=i>>>16&255;K[e|2]=i>>>8&255;K[e|3]=i&255;K[e|4]=n>>>24;K[e|5]=n>>>16&255;K[e|6]=n>>>8&255;K[e|7]=n&255;K[e|8]=a>>>24;K[e|9]=a>>>16&255;K[e|10]=a>>>8&255;K[e|11]=a&255;K[e|12]=s>>>24;K[e|13]=s>>>16&255;K[e|14]=s>>>8&255;K[e|15]=s&255;K[e|16]=o>>>24;K[e|17]=o>>>16&255;K[e|18]=o>>>8&255;K[e|19]=o&255;K[e|20]=c>>>24;K[e|21]=c>>>16&255;K[e|22]=c>>>8&255;K[e|23]=c&255;K[e|24]=u>>>24;K[e|25]=u>>>16&255;K[e|26]=u>>>8&255;K[e|27]=u&255;K[e|28]=h>>>24;K[e|29]=h>>>16&255;K[e|30]=h>>>8&255;K[e|31]=h&255}function R(){i=0x6a09e667;n=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;h=0x5be0cd19;d=f=0}function I(e,t,r,l,p,y,b,m,g,w){e=e|0;t=t|0;r=r|0;l=l|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;w=w|0;i=e;n=t;a=r;s=l;o=p;c=y;u=b;h=m;d=g;f=w}function B(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){D(e);e=e+64|0;t=t-64|0;r=r+64|0}d=d+r|0;if(d>>>0>>0)f=f+1|0;return r|0}function T(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=B(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;d=d+t|0;if(d>>>0>>0)f=f+1|0;K[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)K[e|n]=0x00;D(e);t=0;K[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)K[e|n]=0;K[e|56]=f>>>21&255;K[e|57]=f>>>13&255;K[e|58]=f>>>5&255;K[e|59]=f<<3&255|d>>>29;K[e|60]=d>>>21&255;K[e|61]=d>>>13&255;K[e|62]=d>>>5&255;K[e|63]=d<<3&255;D(e);if(~r)U(r);return i|0}function z(){i=l;n=p;a=y;s=b;o=m;c=g;u=w;h=v;d=64;f=0}function q(){i=_;n=k;a=A;s=S;o=E;c=P;u=x;h=M;d=64;f=0}function F(e,t,r,K,D,U,I,B,T,z,q,F,O,L,N,j){e=e|0;t=t|0;r=r|0;K=K|0;D=D|0;U=U|0;I=I|0;B=B|0;T=T|0;z=z|0;q=q|0;F=F|0;O=O|0;L=L|0;N=N|0;j=j|0;R();C(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,K^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,I^0x5c5c5c5c,B^0x5c5c5c5c,T^0x5c5c5c5c,z^0x5c5c5c5c,q^0x5c5c5c5c,F^0x5c5c5c5c,O^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,j^0x5c5c5c5c);_=i;k=n;A=a;S=s;E=o;P=c;x=u;M=h;R();C(e^0x36363636,t^0x36363636,r^0x36363636,K^0x36363636,D^0x36363636,U^0x36363636,I^0x36363636,B^0x36363636,T^0x36363636,z^0x36363636,q^0x36363636,F^0x36363636,O^0x36363636,L^0x36363636,N^0x36363636,j^0x36363636);l=i;p=n;y=a;b=s;m=o;g=c;w=u;v=h;d=64;f=0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;if(e&63)return-1;if(~r)if(r&31)return-1;w=T(e,t,-1)|0;d=i,f=n,l=a,p=s,y=o,b=c,m=u,g=h;q();C(d,f,l,p,y,b,m,g,0x80000000,0,0,0,0,0,0,768);if(~r)U(r);return w|0}function L(e,t,r,d,f){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;var l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0;if(e&63)return-1;if(~f)if(f&31)return-1;K[e+t|0]=r>>>24;K[e+t+1|0]=r>>>16&255;K[e+t+2|0]=r>>>8&255;K[e+t+3|0]=r&255;O(e,t+4|0,-1)|0;l=_=i,p=k=n,y=A=a,b=S=s,m=E=o,g=P=c,w=x=u,v=M=h;d=d-1|0;while((d|0)>0){z();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;q();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;l=l^i;p=p^n;y=y^a;b=b^s;m=m^o;g=g^c;w=w^u;v=v^h;d=d-1|0}i=l;n=p;a=y;s=b;o=m;c=g;u=w;h=v;if(~f)U(f);return 0}return{reset:R,init:I,process:B,finish:T,hmac_reset:z,hmac_init:F,hmac_finish:O,pbkdf2_generate_block:L}}({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(nt.push(this.heap),at.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new st).process(e).finish().result}}st.NAME="sha256";var ot=ct;function ct(e,t){if(!e)throw Error(t||"Assertion failed")}ct.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)};var ut=void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ht(e,t){return e(t={exports:{}},t.exports),t.exports}function dt(){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var ft=ht((function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}})),lt=ht((function(e){try{var t=s;if("function"!=typeof t.inherits)throw"";e.exports=t.inherits}catch(t){e.exports=ft}}));var pt=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>8,s=255&n;a?r.push(a,s):r.push(s)}else for(i=0;i>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}var mt=function(e,t){for(var r="",i=0;i>>0}return a};var _t=function(e,t){for(var r=Array(4*e.length),i=0,n=0;i>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r};var kt={inherits:lt,toArray:pt,toHex:yt,htonl:bt,toHex32:mt,zero2:gt,zero8:wt,join32:vt,split32:_t,rotr32:function(e,t){return e>>>t|e<<32-t},rotl32:function(e,t){return e<>>32-t},sum32:function(e,t){return e+t>>>0},sum32_3:function(e,t,r){return e+t+r>>>0},sum32_4:function(e,t,r,i){return e+t+r+i>>>0},sum32_5:function(e,t,r,i,n){return e+t+r+i+n>>>0},sum64:function(e,t,r,i){var n=e[t],a=i+e[t+1]>>>0,s=(a>>0,e[t+1]=a},sum64_hi:function(e,t,r,i){return(t+i>>>0>>0},sum64_lo:function(e,t,r,i){return t+i>>>0},sum64_4_hi:function(e,t,r,i,n,a,s,o){var c=0,u=t;return c+=(u=u+i>>>0)>>0)>>0)>>0},sum64_4_lo:function(e,t,r,i,n,a,s,o){return t+i+a+o>>>0},sum64_5_hi:function(e,t,r,i,n,a,s,o,c,u){var h=0,d=t;return h+=(d=d+i>>>0)>>0)>>0)>>0)>>0},sum64_5_lo:function(e,t,r,i,n,a,s,o,c,u){return t+i+a+o+u>>>0},rotr64_hi:function(e,t,r){return(t<<32-r|e>>>r)>>>0},rotr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0},shr64_hi:function(e,t,r){return e>>>r},shr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0}};function At(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var St=At;At.prototype.update=function(e,t){if(e=kt.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=kt.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,a=8;a>>3},g1_256:function(e){return Pt(e,17)^Pt(e,19)^e>>>10}},Ut=kt.sum32,Rt=kt.sum32_4,It=kt.sum32_5,Bt=Dt.ch32,Tt=Dt.maj32,zt=Dt.s0_256,qt=Dt.s1_256,Ft=Dt.g0_256,Ot=Dt.g1_256,Lt=Et.BlockHash,Nt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function jt(){if(!(this instanceof jt))return new jt;Lt.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=Nt,this.W=Array(64)}kt.inherits(jt,Lt);var Ht=jt;function Wt(){if(!(this instanceof Wt))return new Wt;Ht.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}jt.blockSize=512,jt.outSize=256,jt.hmacStrength=192,jt.padLength=64,jt.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i>>32-n,r)}function Fr(e,t,r,i,n,a,s){return qr(t&r|~t&i,e,t,n,a,s)}function Or(e,t,r,i,n,a,s){return qr(t&i|r&~i,e,t,n,a,s)}function Lr(e,t,r,i,n,a,s){return qr(t^r^i,e,t,n,a,s)}function Nr(e,t,r,i,n,a,s){return qr(r^(t|~i),e,t,n,a,s)}function jr(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const Hr="0123456789abcdef".split("");function Wr(e){let t="",r=0;for(;r<4;r++)t+=Hr[e>>8*r+4&15]+Hr[e>>8*r&15];return t}function Gr(e,t){return e+t&4294967295}const Vr=ie.getWebCrypto(),$r=ie.getNodeCrypto(),Zr=$r&&$r.getHashes();function Xr(e){if($r&&Zr.includes(e))return async function(t){const r=$r.createHash(e);return N(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function Yr(e,t){return async function(r,i=de){if(l(r)&&(r=await Z(r)),!ie.isStream(r)&&Vr&&t&&r.length>=i.minBytesForWebCrypto)return new Uint8Array(await Vr.digest(t,r));const n=e();return N(r,(e=>{n.update(e)}),(()=>new Uint8Array(n.digest())))}}function Qr(e,t){return async function(r,i=de){if(l(r)&&(r=await Z(r)),ie.isStream(r)){const t=new e;return N(r,(e=>{t.process(e)}),(()=>t.finish().result))}return Vr&&t&&r.length>=i.minBytesForWebCrypto?new Uint8Array(await Vr.digest(t,r)):e.bytes(r)}}const Jr={md5:Xr("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let i;for(i=64;i<=e.length;i+=64)zr(r,jr(e.substring(i-64,i)));e=e.substring(i-64);const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i>2]|=e.charCodeAt(i)<<(i%4<<3);if(n[i>>2]|=128<<(i%4<<3),i>55)for(zr(r,n),i=0;i<16;i++)n[i]=0;return n[14]=8*t,zr(r,n),r}(ie.uint8ArrayToString(e));return ie.hexToUint8Array(function(e){for(let t=0;tnew Uint8Array(a.update(e))))}(e,t,r,i);if(ie.isAES(e))return function(e,t,r,i,n){if(ie.getWebCrypto()&&24!==t.length&&!ie.isStream(r)&&r.length>=3e3*n.minBytesForWebCrypto)return async function(e,t,r,i){const n="AES-CBC",a=await ii.importKey("raw",t,{name:n},!1,["encrypt"]),{blockSize:s}=ri(e),o=ie.concatUint8Array([new Uint8Array(s),r]),c=new Uint8Array(await ii.encrypt({name:n,iv:i},a,o)).subarray(0,r.length);return function(e,t){for(let r=0;ra.aes.AES_Encrypt_process(e)),(()=>a.aes.AES_Encrypt_finish()))}(e,t,r,i,n);const s=new(ri(e))(t),o=s.blockSize,c=i.slice();let u=new Uint8Array;const h=e=>{e&&(u=ie.concatUint8Array([u,e]));const t=new Uint8Array(u.length);let r,i=0;for(;e?u.length>=o:u.length;){const e=s.encrypt(c);for(r=0;rnew Uint8Array(a.update(e))))}(e,t,r,i);if(ie.isAES(e))return function(e,t,r,i){if(ie.isStream(r)){const e=new ti(t,i);return N(r,(t=>e.aes.AES_Decrypt_process(t)),(()=>e.aes.AES_Decrypt_finish()))}return ti.decrypt(r,t,i)}(0,t,r,i);const a=new(ri(e))(t),s=a.blockSize;let o=i,c=new Uint8Array;const u=e=>{e&&(c=ie.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,i=0;for(;e?c.length>=s:c.length;){const e=a.encrypt(o);for(o=c.subarray(0,s),r=0;r48)throw new Me("illegal counter size");let e=Math.pow(2,r)-1;i.set_mask(0,0,e/4294967296|0,0|e)}else r=48,i.set_mask(0,0,65535,4294967295);if(void 0===e)throw Error("nonce is required");{let t=e.length;if(!t||t>16)throw new Me("illegal nonce size");let r=new DataView(new ArrayBuffer(16));new Uint8Array(r.buffer).set(e),i.set_nonce(r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12))}if(void 0!==t){if(t<0||t>=Math.pow(2,r))throw new Me("illegal counter value");i.set_counter(0,0,t/4294967296|0,0|t)}}}class ui{static encrypt(e,t,r=!0,i){return new ui(t,i,r).encrypt(e)}static decrypt(e,t,r=!0,i){return new ui(t,i,r).decrypt(e)}constructor(e,t,r=!0,i){this.aes=i||new Ue(e,t,r,"CBC")}encrypt(e){return Pe(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return Pe(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}const hi=ie.getWebCrypto(),di=ie.getNodeCrypto(),fi=16;function li(e,t){const r=e.length-fi;for(let i=0;i>3),17+(u>>3)),8-(7&u)).subarray(1),l=new Uint8Array(Mi),p=new Uint8Array(t.length+Ci);let y,b=0;for(y=0;y16)throw new Me("illegal tagSize value");const o=t.length||0,c=new Uint8Array(16);12!==o?(this._gcm_mac_process(t),s[0]=0,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=0,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=0,s[11]=o>>>29,s[12]=o>>>21&255,s[13]=o>>>13&255,s[14]=o>>>5&255,s[15]=o<<3&255,a.mac(ke.MAC.GCM,ke.HEAP_DATA,16),a.get_iv(ke.HEAP_DATA),a.set_iv(0,0,0,0),c.set(s.subarray(0,16))):(c.set(t),c[15]=1);const u=new DataView(c.buffer);if(this.gamma0=u.getUint32(12),a.set_nonce(u.getUint32(0),u.getUint32(4),u.getUint32(8),0),a.set_mask(0,0,0,4294967295),void 0!==r){if(r.length>zi)throw new Me("illegal adata length");r.length?(this.adata=r,this._gcm_mac_process(r)):this.adata=void 0}else this.adata=void 0;if(this.counter<1||this.counter>4294967295)throw new RangeError("counter must be a positive 32-bit integer");a.set_counter(0,0,0,this.gamma0+this.counter|0)}static encrypt(e,t,r,i,n){return new qi(t,r,i,n).encrypt(e)}static decrypt(e,t,r,i,n){return new qi(t,r,i,n).decrypt(e)}encrypt(e){return this.AES_GCM_encrypt(e)}decrypt(e){return this.AES_GCM_decrypt(e)}AES_GCM_Encrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.aes.pos,o=this.aes.len,c=0,u=o+r&-16,h=0;if((a-1<<4)+o+r>zi)throw new RangeError("counter overflow");const d=new Uint8Array(u);for(;r>0;)h=Ee(n,s+o,e,t,r),o+=h,t+=h,r-=h,h=i.cipher(ke.ENC.CTR,ke.HEAP_DATA+s,o),h=i.mac(ke.MAC.GCM,ke.HEAP_DATA+s,h),h&&d.set(n.subarray(s,s+h),c),a+=h>>>4,c+=h,h>>29,t[4]=u>>>21,t[5]=u>>>13&255,t[6]=u>>>5&255,t[7]=u<<3&255,t[8]=t[9]=t[10]=0,t[11]=h>>>29,t[12]=h>>>21&255,t[13]=h>>>13&255,t[14]=h>>>5&255,t[15]=h<<3&255,e.mac(ke.MAC.GCM,ke.HEAP_DATA,16),e.get_iv(ke.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(ke.ENC.CTR,ke.HEAP_DATA,16),o.set(t.subarray(0,i),s),this.counter=1,this.aes.pos=0,this.aes.len=0,o}AES_GCM_Decrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.tagSize,o=this.aes.pos,c=this.aes.len,u=0,h=c+r>s?c+r-s&-16:0,d=c+r-h,f=0;if((a-1<<4)+c+r>zi)throw new RangeError("counter overflow");const l=new Uint8Array(h);for(;r>d;)f=Ee(n,o+c,e,t,r-d),c+=f,t+=f,r-=f,f=i.mac(ke.MAC.GCM,ke.HEAP_DATA+o,f),f=i.cipher(ke.DEC.CTR,ke.HEAP_DATA+o,f),f&&l.set(n.subarray(o,o+f),u),a+=f>>>4,u+=f,o=0,c=0;return r>0&&(c+=Ee(n,0,e,t,r)),this.counter=a,this.aes.pos=o,this.aes.len=c,l}AES_GCM_Decrypt_finish(){let{asm:e,heap:t}=this.aes.acquire_asm(),r=this.tagSize,i=this.adata,n=this.counter,a=this.aes.pos,s=this.aes.len,o=s-r;if(s>>29,t[4]=d>>>21,t[5]=d>>>13&255,t[6]=d>>>5&255,t[7]=d<<3&255,t[8]=t[9]=t[10]=0,t[11]=f>>>29,t[12]=f>>>21&255,t[13]=f>>>13&255,t[14]=f>>>5&255,t[15]=f<<3&255,e.mac(ke.MAC.GCM,ke.HEAP_DATA,16),e.get_iv(ke.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(ke.ENC.CTR,ke.HEAP_DATA,16);let l=0;for(let e=0;e0;){for(a=Ee(r,0,e,i,n),i+=a,n-=a;15&a;)r[a++]=0;t.mac(ke.MAC.GCM,ke.HEAP_DATA,a)}}}const Fi=ie.getWebCrypto(),Oi=ie.getNodeCrypto(),Li=ie.getNodeBuffer(),Ni=16,ji="AES-GCM";async function Hi(e,t){if(e!==te.symmetric.aes128&&e!==te.symmetric.aes192&&e!==te.symmetric.aes256)throw Error("GCM mode supports only AES cipher");if(ie.getNodeCrypto())return{encrypt:async function(e,r,i=new Uint8Array){const n=new Oi.createCipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i);const a=Li.concat([n.update(e),n.final(),n.getAuthTag()]);return new Uint8Array(a)},decrypt:async function(e,r,i=new Uint8Array){const n=new Oi.createDecipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i),n.setAuthTag(e.slice(e.length-Ni,e.length));const a=Li.concat([n.update(e.slice(0,e.length-Ni)),n.final()]);return new Uint8Array(a)}};if(ie.getWebCrypto()&&24!==t.length){const e=await Fi.importKey("raw",t,{name:ji},!1,["encrypt","decrypt"]);return{encrypt:async function(r,i,n=new Uint8Array){if(!r.length)return qi.encrypt(r,t,i,n);const a=await Fi.encrypt({name:ji,iv:i,additionalData:n,tagLength:8*Ni},e,r);return new Uint8Array(a)},decrypt:async function(r,i,n=new Uint8Array){if(r.length===Ni)return qi.decrypt(r,t,i,n);const a=await Fi.decrypt({name:ji,iv:i,additionalData:n,tagLength:8*Ni},e,r);return new Uint8Array(a)}}}return{encrypt:async function(e,r,i){return qi.encrypt(e,t,r,i)},decrypt:async function(e,r,i){return qi.decrypt(e,t,r,i)}}}Hi.getNonce=function(e,t){const r=e.slice();for(let e=0;e>>8)-1}(e,t,r,i,32)}function p(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function y(e){var t,r,i=1;for(t=0;t<16;t++)r=e[t]+i+65535,i=Math.floor(r/65536),e[t]=r-65536*i;e[0]+=i-1+37*(i-1)}function b(e,t,r){for(var i,n=~(r-1),a=0;a<16;a++)i=n&(e[a]^t[a]),e[a]^=i,t[a]^=i}function m(e,r){var i,n,a,s=t(),o=t();for(i=0;i<16;i++)o[i]=r[i];for(y(o),y(o),y(o),n=0;n<2;n++){for(s[0]=o[0]-65517,i=1;i<15;i++)s[i]=o[i]-65535-(s[i-1]>>16&1),s[i-1]&=65535;s[15]=o[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,b(o,s,1-a)}for(i=0;i<16;i++)e[2*i]=255&o[i],e[2*i+1]=o[i]>>8}function g(e,t){var r=new Uint8Array(32),i=new Uint8Array(32);return m(r,e),m(i,t),l(r,0,i,0)}function w(e){var t=new Uint8Array(32);return m(t,e),1&t[0]}function v(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function _(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]+r[i]}function k(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]-r[i]}function A(e,t,r){var i,n,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0,U=0,R=0,I=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+=38*(U+=i*$),m+=38*(R+=i*Z),g+=38*(I+=i*X),w+=38*(B+=i*Y),a=(i=(a+=38*(_+=i*z))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a=(i=(a+=n-1+37*(n-1))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a+=n-1+37*(n-1),e[0]=a,e[1]=s,e[2]=o,e[3]=c,e[4]=u,e[5]=h,e[6]=d,e[7]=f,e[8]=l,e[9]=p,e[10]=y,e[11]=b,e[12]=m,e[13]=g,e[14]=w,e[15]=v}function S(e,t){A(e,t,t)}function E(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=253;i>=0;i--)S(n,n),2!==i&&4!==i&&A(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}function P(e,r,i){var n,a,s=new Uint8Array(32),c=new Float64Array(80),u=t(),h=t(),d=t(),f=t(),l=t(),p=t();for(a=0;a<31;a++)s[a]=r[a];for(s[31]=127&r[31]|64,s[0]&=248,v(c,i),a=0;a<16;a++)h[a]=c[a],f[a]=u[a]=d[a]=0;for(u[0]=f[0]=1,a=254;a>=0;--a)b(u,h,n=s[a>>>3]>>>(7&a)&1),b(d,f,n),_(l,u,d),k(u,u,d),_(d,h,f),k(h,h,f),S(f,l),S(p,u),A(u,d,u),A(d,h,l),_(l,u,d),k(u,u,d),S(h,u),k(d,f,p),A(u,d,o),_(u,u,f),A(d,d,u),A(u,f,p),A(f,h,c),S(h,l),b(u,h,n),b(d,f,n);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=d[a],c[a+48]=h[a],c[a+64]=f[a];var y=c.subarray(32),g=c.subarray(16);return E(y,y),A(g,g,y),m(e,g),0}function x(e,t){return P(e,t,n)}function M(e,r){var i=t(),n=t(),a=t(),s=t(),o=t(),c=t(),h=t(),d=t(),f=t();k(i,e[1],e[0]),k(f,r[1],r[0]),A(i,i,f),_(n,e[0],e[1]),_(f,r[0],r[1]),A(n,n,f),A(a,e[3],r[3]),A(a,a,u),A(s,e[2],r[2]),_(s,s,s),k(o,n,i),k(c,s,a),_(h,s,a),_(d,n,i),A(e[0],o,c),A(e[1],d,h),A(e[2],h,c),A(e[3],o,d)}function K(e,t,r){var i;for(i=0;i<4;i++)b(e[i],t[i],r)}function C(e,r){var i=t(),n=t(),a=t();E(a,r[2]),A(i,r[0],a),A(n,r[1],a),m(e,n),e[31]^=w(i)<<7}function D(e,t,r){var i,n;for(p(e[0],a),p(e[1],s),p(e[2],s),p(e[3],a),n=255;n>=0;--n)K(e,t,i=r[n/8|0]>>(7&n)&1),M(t,e),M(e,e),K(e,t,i)}function U(e,r){var i=[t(),t(),t(),t()];p(i[0],h),p(i[1],d),p(i[2],s),A(i[3],h,d),D(e,i,r)}function R(i,n,a){var s,o,c=[t(),t(),t(),t()];for(a||r(n,32),(s=e.hash(n.subarray(0,32)))[0]&=248,s[31]&=127,s[31]|=64,U(c,s),C(i,c),o=0;o<32;o++)n[o+32]=i[o];return 0}var I=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function B(e,t){var r,i,n,a;for(i=63;i>=32;--i){for(r=0,n=i-32,a=i-12;n>4)*I[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*I[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function T(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;B(e,r)}function z(e,r){var i=t(),n=t(),o=t(),u=t(),h=t(),d=t(),l=t();return p(e[2],s),v(e[1],r),S(o,e[1]),A(u,o,c),k(o,o,e[2]),_(u,e[2],u),S(h,u),S(d,h),A(l,d,h),A(i,l,o),A(i,i,u),function(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=250;i>=0;i--)S(n,n),1!==i&&A(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}(i,i),A(i,i,o),A(i,i,u),A(i,i,u),A(e[0],i,u),S(n,e[0]),A(n,n,u),g(n,o)&&A(e[0],e[0],f),S(n,e[0]),A(n,n,u),g(n,o)?-1:(w(e[0])===r[31]>>7&&k(e[0],a,e[0]),A(e[3],e[0],e[1]),0)}var q=64;function F(){for(var e=0;e=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return R(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(F(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;re&&(c.imod(a.leftShift(n)).iadd(a),u=c.mod(s).toNumber())}while(!await Qi(c,t,r));return c}async function Qi(e,t,r){return!(t&&!e.dec().gcd(t).isOne())&&(!!await async function(e){const t=await ie.getBigInteger();return Ji.every((r=>0!==e.mod(new t(r))))}(e)&&(!!await async function(e,t){const r=await ie.getBigInteger();return t=t||new r(2),t.modExp(e.dec(),e).isOne()}(e)&&!!await async function(e,t,r){const i=await ie.getBigInteger(),n=e.bitLength();t||(t=Math.max(1,n/48|0));const a=e.dec();let s=0;for(;!a.getBit(s);)s++;const o=e.rightShift(new i(s));for(;t>0;t--){let t,n=(r?r():await Zi(new i(2),a)).modExp(o,e);if(!n.isOne()&&!n.equal(a)){for(t=1;tt-11)throw Error("Message too long");const i=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!i;if(t)return ie.selectUint8Array(s,a,t);if(s)return a;throw Error("Decryption error")}async function nn(e,t,r){let i;if(t.length!==ei.getHashByteLength(e))throw Error("Invalid hash length");const n=new Uint8Array(en[e].length);for(i=0;i{on.generateKeyPair("rsa",r,((r,i,n)=>{r?t(r):e(un.decode(n,"der"))}))}));return{n:i.modulus.toArrayLike(Uint8Array),e:i.publicExponent.toArrayLike(Uint8Array),d:i.privateExponent.toArrayLike(Uint8Array),p:i.prime2.toArrayLike(Uint8Array),q:i.prime1.toArrayLike(Uint8Array),u:i.coefficient.toArrayLike(Uint8Array)}}let r,i,n;do{i=await Yi(e-(e>>1),t,40),r=await Yi(e>>1,t,40),n=r.mul(i)}while(n.bitLength()!==e);const a=r.dec().imul(i.dec());return i.lt(r)&&([r,i]=[i,r]),{n:n.toUint8Array(),e:t.toUint8Array(),d:t.modInv(a).toUint8Array(),p:r.toUint8Array(),q:i.toUint8Array(),u:r.modInv(i).toUint8Array()}},validateParams:async function(e,t,r,i,n,a){const s=await ie.getBigInteger();if(e=new s(e),i=new s(i),n=new s(n),!i.mul(n).equal(e))return!1;const o=new s(2);if(a=new s(a),!i.mul(a).mod(n).isOne())return!1;t=new s(t),r=new s(r);const c=new s(Math.floor(e.bitLength()/3)),u=await Zi(o,o.leftShift(c)),h=u.mul(r).mul(t);return!(!h.mod(i.dec()).equal(u)||!h.mod(n.dec()).equal(u))}});var fn=/*#__PURE__*/Object.freeze({__proto__:null,encrypt:async function(e,t,r,i){const n=await ie.getBigInteger();t=new n(t),r=new n(r),i=new n(i);const a=new n(tn(e,t.byteLength())),s=await Zi(new n(1),t.dec());return{c1:r.modExp(s,t).toUint8Array(),c2:i.modExp(s,t).imul(a).imod(t).toUint8Array()}},decrypt:async function(e,t,r,i,n){const a=await ie.getBigInteger();return e=new a(e),t=new a(t),r=new a(r),i=new a(i),rn(e.modExp(i,r).modInv(r).imul(t).imod(r).toUint8Array("be",r.byteLength()),n)},validateParams:async function(e,t,r,i){const n=await ie.getBigInteger();e=new n(e),t=new n(t),r=new n(r);const a=new n(1);if(t.lte(a)||t.gte(e))return!1;const s=new n(e.bitLength()),o=new n(1023);if(s.lt(o))return!1;if(!t.modExp(e.dec(),e).isOne())return!1;let c=t;const u=new n(1),h=new n(2).leftShift(new n(17));for(;u.lt(h);){if(c=c.mul(t).imod(e),c.isOne())return!1;u.iinc()}i=new n(i);const d=new n(2),f=await Zi(d.leftShift(s.dec()),d.leftShift(s)),l=e.dec().imul(f).iadd(i);return!!r.equal(t.modExp(l,e))}});class ln{constructor(e){if(e instanceof ln)this.oid=e.oid;else if(ie.isArray(e)||ie.isUint8Array(e)){if(6===(e=new Uint8Array(e))[0]){if(e[1]!==e.length-2)throw Error("Length mismatch in DER encoded oid");e=e.subarray(2)}this.oid=e}else this.oid=""}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return ie.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return ie.uint8ArrayToHex(this.oid)}getName(){const e=this.toHex();if(te.curve[e])return te.write(te.curve,e);throw Error("Unknown curve object identifier.")}}function pn(e,t){return e.keyPair({priv:t})}function yn(e,t){const r=e.keyPair({pub:t});if(!0!==r.validate().result)throw Error("Invalid elliptic public key");return r}async function bn(e){if(!de.useIndutnyElliptic)throw Error("This curve is only supported in the full build of OpenPGP.js");const{default:t}=await Promise.resolve().then((function(){return Rb}));return new t.ec(e)}function mn(e){let t,r=0;const i=e[0];return i<192?([r]=e,t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=ie.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function gn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):ie.concatUint8Array([new Uint8Array([255]),ie.writeNumber(e,4)])}function wn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function vn(e){return new Uint8Array([192|e])}function _n(e,t){return ie.concatUint8Array([vn(e),gn(t)])}function kn(e){return[te.packet.literalData,te.packet.compressedData,te.packet.symmetricallyEncryptedData,te.packet.symEncryptedIntegrityProtectedData,te.packet.aeadEncryptedData].includes(e)}async function An(e,t){const r=z(e);let i,n;try{const a=await r.peekBytes(2);if(!a||a.length<2||0==(128&a[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const s=await r.readByte();let o,c,u=-1,h=-1;h=0,0!=(64&s)&&(h=1),h?u=63&s:(u=(63&s)>>2,c=3&s);const d=kn(u);let l,p=null;if(d){if("array"===ie.isStream(e)){const e=new f;i=q(e),p=e}else{const e=new D;i=q(e.writable),p=e.readable}n=t({tag:u,packet:p})}else p=[];do{if(h){const e=await r.readByte();if(l=!1,e<192)o=e;else if(e>=192&&e<224)o=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(o=1<<(31&e),l=!0,!d)throw new TypeError("This packet type does not support partial lengths.")}else o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(c){case 0:o=await r.readByte();break;case 1:o=await r.readByte()<<8|await r.readByte();break;case 2:o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:o=1/0}if(o>0){let e=0;for(;;){i&&await i.ready;const{done:t,value:n}=await r.read();if(t){if(o===1/0)break;throw Error("Unexpected end of packet")}const a=o===1/0?n:n.subarray(0,o-e);if(i?await i.write(a):p.push(a),e+=n.length,e>=o){r.unshift(n.subarray(o-e+n.length));break}}}}while(l);const y=await r.peekBytes(d?1/0:2);return i?(await i.ready,await i.close()):(p=ie.concatUint8Array(p),await t({tag:u,packet:p})),!y||!y.length}catch(e){if(i)return await i.abort(e),!0;throw e}finally{i&&await n,r.releaseLock()}}class Sn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Sn),this.name="UnsupportedError"}}class En{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}const Pn=ie.getWebCrypto(),xn=ie.getNodeCrypto(),Mn={p256:"P-256",p384:"P-384",p521:"P-521"},Kn=xn?xn.getCurves():[],Cn=xn?{secp256k1:Kn.includes("secp256k1")?"secp256k1":void 0,p256:Kn.includes("prime256v1")?"prime256v1":void 0,p384:Kn.includes("secp384r1")?"secp384r1":void 0,p521:Kn.includes("secp521r1")?"secp521r1":void 0,ed25519:Kn.includes("ED25519")?"ED25519":void 0,curve25519:Kn.includes("X25519")?"X25519":void 0,brainpoolP256r1:Kn.includes("brainpoolP256r1")?"brainpoolP256r1":void 0,brainpoolP384r1:Kn.includes("brainpoolP384r1")?"brainpoolP384r1":void 0,brainpoolP512r1:Kn.includes("brainpoolP512r1")?"brainpoolP512r1":void 0}:{},Dn={p256:{oid:[6,8,42,134,72,206,61,3,1,7],keyType:te.publicKey.ecdsa,hash:te.hash.sha256,cipher:te.symmetric.aes128,node:Cn.p256,web:Mn.p256,payloadSize:32,sharedSize:256},p384:{oid:[6,5,43,129,4,0,34],keyType:te.publicKey.ecdsa,hash:te.hash.sha384,cipher:te.symmetric.aes192,node:Cn.p384,web:Mn.p384,payloadSize:48,sharedSize:384},p521:{oid:[6,5,43,129,4,0,35],keyType:te.publicKey.ecdsa,hash:te.hash.sha512,cipher:te.symmetric.aes256,node:Cn.p521,web:Mn.p521,payloadSize:66,sharedSize:528},secp256k1:{oid:[6,5,43,129,4,0,10],keyType:te.publicKey.ecdsa,hash:te.hash.sha256,cipher:te.symmetric.aes128,node:Cn.secp256k1,payloadSize:32},ed25519:{oid:[6,9,43,6,1,4,1,218,71,15,1],keyType:te.publicKey.eddsaLegacy,hash:te.hash.sha512,node:!1,payloadSize:32},curve25519:{oid:[6,10,43,6,1,4,1,151,85,1,5,1],keyType:te.publicKey.ecdh,hash:te.hash.sha256,cipher:te.symmetric.aes128,node:!1,payloadSize:32},brainpoolP256r1:{oid:[6,9,43,36,3,3,2,8,1,1,7],keyType:te.publicKey.ecdsa,hash:te.hash.sha256,cipher:te.symmetric.aes128,node:Cn.brainpoolP256r1,payloadSize:32},brainpoolP384r1:{oid:[6,9,43,36,3,3,2,8,1,1,11],keyType:te.publicKey.ecdsa,hash:te.hash.sha384,cipher:te.symmetric.aes192,node:Cn.brainpoolP384r1,payloadSize:48},brainpoolP512r1:{oid:[6,9,43,36,3,3,2,8,1,1,13],keyType:te.publicKey.ecdsa,hash:te.hash.sha512,cipher:te.symmetric.aes256,node:Cn.brainpoolP512r1,payloadSize:64}};class Un{constructor(e,t){try{(ie.isArray(e)||ie.isUint8Array(e))&&(e=new ln(e)),e instanceof ln&&(e=e.getName()),this.name=te.write(te.curve,e)}catch(e){throw new Sn("Unknown curve")}t=t||Dn[this.name],this.keyType=t.keyType,this.oid=t.oid,this.hash=t.hash,this.cipher=t.cipher,this.node=t.node&&Dn[this.name],this.web=t.web&&Dn[this.name],this.payloadSize=t.payloadSize,this.web&&ie.getWebCrypto()?this.type="web":this.node&&ie.getNodeCrypto()?this.type="node":"curve25519"===this.name?this.type="curve25519":"ed25519"===this.name&&(this.type="ed25519")}async genKeyPair(){let e;switch(this.type){case"web":try{return await async function(e){const t=await Pn.generateKey({name:"ECDSA",namedCurve:Mn[e]},!0,["sign","verify"]),r=await Pn.exportKey("jwk",t.privateKey),i=await Pn.exportKey("jwk",t.publicKey);return{publicKey:In(i),privateKey:ue(r.d)}}(this.name)}catch(e){ie.printDebugError("Browser did not support generating ec key "+e.message);break}case"node":return async function(e){const t=xn.createECDH(Cn[e]);return await t.generateKeys(),{publicKey:new Uint8Array(t.getPublicKey()),privateKey:new Uint8Array(t.getPrivateKey())}}(this.name);case"curve25519":{const t=$i(32);t[0]=127&t[0]|64,t[31]&=248;const r=t.slice().reverse();e=Gi.box.keyPair.fromSecretKey(r);return{publicKey:ie.concatUint8Array([new Uint8Array([64]),e.publicKey]),privateKey:t}}case"ed25519":{const e=$i(32),t=Gi.sign.keyPair.fromSeed(e);return{publicKey:ie.concatUint8Array([new Uint8Array([64]),t.publicKey]),privateKey:e}}}const t=await bn(this.name);return e=await t.genKeyPair({entropy:ie.uint8ArrayToString($i(32))}),{publicKey:new Uint8Array(e.getPublic("array",!1)),privateKey:e.getPrivate().toArrayLike(Uint8Array)}}}async function Rn(e,t,r,i){const n={p256:!0,p384:!0,p521:!0,secp256k1:!0,curve25519:e===te.publicKey.ecdh,brainpoolP256r1:!0,brainpoolP384r1:!0,brainpoolP512r1:!0},a=t.getName();if(!n[a])return!1;if("curve25519"===a){i=i.slice().reverse();const{publicKey:e}=Gi.box.keyPair.fromSecretKey(i);r=new Uint8Array(r);const t=new Uint8Array([64,...e]);return!!ie.equalsUint8Array(t,r)}const s=await bn(a);try{r=yn(s,r).getPublic()}catch(e){return!1}return!!pn(s,i).getPublic().eq(r)}function In(e){const t=ue(e.x),r=ue(e.y),i=new Uint8Array(t.length+r.length+1);return i[0]=4,i.set(t,1),i.set(r,t.length+1),i}function Bn(e,t,r){const i=e,n=r.slice(1,i+1),a=r.slice(i+1,2*i+1);return{kty:"EC",crv:t,x:he(n,!0),y:he(a,!0),ext:!0}}function Tn(e,t,r,i){const n=Bn(e,t,r);return n.d=he(i,!0),n}const zn=ie.getWebCrypto(),qn=ie.getNodeCrypto();async function Fn(e,t,r,i,n,a){const s=new Un(e);if(r&&!ie.isStream(r)){const e={publicKey:i,privateKey:n};switch(s.type){case"web":try{return await async function(e,t,r,i){const n=e.payloadSize,a=Tn(e.payloadSize,Mn[e.name],i.publicKey,i.privateKey),s=await zn.importKey("jwk",a,{name:"ECDSA",namedCurve:Mn[e.name],hash:{name:te.read(te.webHash,e.hash)}},!1,["sign"]),o=new Uint8Array(await zn.sign({name:"ECDSA",namedCurve:Mn[e.name],hash:{name:te.read(te.webHash,t)}},s,r));return{r:o.slice(0,n),s:o.slice(n,n<<1)}}(s,t,r,e)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;ie.printDebugError("Browser did not support signing: "+e.message)}break;case"node":{const i=await async function(e,t,r,i){const n=qn.createSign(te.read(te.hash,t));n.write(r),n.end();const a=jn.encode({version:1,parameters:e.oid,privateKey:Array.from(i.privateKey),publicKey:{unused:0,data:Array.from(i.publicKey)}},"pem",{label:"EC PRIVATE KEY"});return Nn.decode(n.sign(a),"der")}(s,t,r,e);return{r:i.r.toArrayLike(Uint8Array),s:i.s.toArrayLike(Uint8Array)}}}}return async function(e,t,r){const i=await bn(e.name),n=pn(i,r),a=n.sign(t);return{r:a.r.toArrayLike(Uint8Array),s:a.s.toArrayLike(Uint8Array)}}(s,a,n)}async function On(e,t,r,i,n,a){const s=new Un(e);if(i&&!ie.isStream(i))switch(s.type){case"web":try{return await async function(e,t,{r,s:i},n,a){const s=Bn(e.payloadSize,Mn[e.name],a),o=await zn.importKey("jwk",s,{name:"ECDSA",namedCurve:Mn[e.name],hash:{name:te.read(te.webHash,e.hash)}},!1,["verify"]),c=ie.concatUint8Array([r,i]).buffer;return zn.verify({name:"ECDSA",namedCurve:Mn[e.name],hash:{name:te.read(te.webHash,t)}},o,c,n)}(s,t,r,i,n)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;ie.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":return async function(e,t,{r,s:i},n,a){const{default:s}=await Promise.resolve().then((function(){return py})),o=qn.createVerify(te.read(te.hash,t));o.write(n),o.end();const c=Wn.encode({algorithm:{algorithm:[1,2,840,10045,2,1],parameters:e.oid},subjectPublicKey:{unused:0,data:Array.from(a)}},"pem",{label:"PUBLIC KEY"}),u=Nn.encode({r:new s(r),s:new s(i)},"der");try{return o.verify(c,u)}catch(e){return!1}}(s,t,r,i,n)}return async function(e,t,r,i){const n=await bn(e.name),a=yn(n,i);return a.verify(r,t)}(s,r,void 0===t?i:a,n)}const Ln=qn?o:void 0,Nn=qn?Ln.define("ECDSASignature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())})):void 0,jn=qn?Ln.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().any(),this.key("publicKey").explicit(1).optional().bitstr())})):void 0,Hn=qn?Ln.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().any())})):void 0,Wn=qn?Ln.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(Hn),this.key("subjectPublicKey").bitstr())})):void 0;var Gn=/*#__PURE__*/Object.freeze({__proto__:null,sign:Fn,verify:On,validateParams:async function(e,t,r){const i=new Un(e);if(i.keyType!==te.publicKey.ecdsa)return!1;switch(i.type){case"web":case"node":{const i=$i(8),n=te.hash.sha256,a=await ei.digest(n,i);try{const s=await Fn(e,n,i,t,r,a);return await On(e,n,s,i,t,a)}catch(e){return!1}}default:return Rn(te.publicKey.ecdsa,e,t,r)}}});Gi.hash=e=>new Uint8Array(or().update(e).digest());var Vn=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){if(ei.getHashByteLength(t)new Uint8Array(or().update(e).digest());var Zn=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===te.publicKey.ed25519){const e=$i(32),{publicKey:t}=Gi.sign.keyPair.fromSeed(e);return{A:t,seed:e}}throw Error("Unsupported EdDSA algorithm")},sign:async function(e,t,r,i,n,a){if(ei.getHashByteLength(t)=0;--e)for(let t=o-1;t>=0;--t)c[1]=o*e+(t+1),u[0]=a[0]^c[0],u[1]=a[1]^c[1],u[2]=s[2*t],u[3]=s[2*t+1],u=Qn(r.decrypt(Jn(u))),a=u.subarray(0,2),s[2*t]=u[2],s[2*t+1]=u[3];if(a[0]===i[0]&&a[1]===i[1])return Jn(s);throw Error("Key Data Integrity failed")}function Qn(e){const{length:t}=e,r=function(e){if(ie.isString(e)){const{length:t}=e,r=new ArrayBuffer(t),i=new Uint8Array(r);for(let r=0;r0){const r=e[t-1];if(r>=1){const i=e.subarray(t-r),n=new Uint8Array(r).fill(r);if(ie.equalsUint8Array(i,n))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var ia=/*#__PURE__*/Object.freeze({__proto__:null,encode:ta,decode:ra});const na=ie.getWebCrypto(),aa=ie.getNodeCrypto();function sa(e,t,r,i){return ie.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),ie.stringToUint8Array("Anonymous Sender "),i.subarray(0,20)])}async function oa(e,t,r,i,n=!1,a=!1){let s;if(n){for(s=0;s=0&&0===t[s];s--);t=t.subarray(0,s+1)}return(await ei.digest(e,ie.concatUint8Array([new Uint8Array([0,0,0,1]),t,i]))).subarray(0,r)}async function ca(e,t){switch(e.type){case"curve25519":{const r=$i(32),{secretKey:i,sharedKey:n}=await ua(e,t,null,r);let{publicKey:a}=Gi.box.keyPair.fromSecretKey(i);return a=ie.concatUint8Array([new Uint8Array([64]),a]),{publicKey:a,sharedKey:n}}case"web":if(e.web&&ie.getWebCrypto())try{return await async function(e,t){const r=Bn(e.payloadSize,e.web.web,t);let i=na.generateKey({name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]),n=na.importKey("jwk",r,{name:"ECDH",namedCurve:e.web.web},!1,[]);[i,n]=await Promise.all([i,n]);let a=na.deriveBits({name:"ECDH",namedCurve:e.web.web,public:n},i.privateKey,e.web.sharedSize),s=na.exportKey("jwk",i.publicKey);[a,s]=await Promise.all([a,s]);const o=new Uint8Array(a),c=new Uint8Array(In(s));return{publicKey:c,sharedKey:o}}(e,t)}catch(e){ie.printDebugError(e)}break;case"node":return async function(e,t){const r=aa.createECDH(e.node.node);r.generateKeys();const i=new Uint8Array(r.computeSecret(t)),n=new Uint8Array(r.getPublicKey());return{publicKey:n,sharedKey:i}}(e,t)}return async function(e,t){const r=await bn(e.name),i=await e.genKeyPair();t=yn(r,t);const n=pn(r,i.privateKey),a=i.publicKey,s=n.derive(t.getPublic()),o=r.curve.p.byteLength(),c=s.toArrayLike(Uint8Array,"be",o);return{publicKey:a,sharedKey:c}}(e,t)}async function ua(e,t,r,i){if(i.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(i,e.payloadSize-i.length),i=t}switch(e.type){case"curve25519":{const e=i.slice().reverse();return{secretKey:e,sharedKey:Gi.scalarMult(e,t.subarray(1))}}case"web":if(e.web&&ie.getWebCrypto())try{return await async function(e,t,r,i){const n=Tn(e.payloadSize,e.web.web,r,i);let a=na.importKey("jwk",n,{name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]);const s=Bn(e.payloadSize,e.web.web,t);let o=na.importKey("jwk",s,{name:"ECDH",namedCurve:e.web.web},!0,[]);[a,o]=await Promise.all([a,o]);let c=na.deriveBits({name:"ECDH",namedCurve:e.web.web,public:o},a,e.web.sharedSize),u=na.exportKey("jwk",a);[c,u]=await Promise.all([c,u]);const h=new Uint8Array(c);return{secretKey:ue(u.d),sharedKey:h}}(e,t,r,i)}catch(e){ie.printDebugError(e)}break;case"node":return async function(e,t,r){const i=aa.createECDH(e.node.node);i.setPrivateKey(r);const n=new Uint8Array(i.computeSecret(t));return{secretKey:new Uint8Array(i.getPrivateKey()),sharedKey:n}}(e,t,i)}return async function(e,t,r){const i=await bn(e.name);t=yn(i,t),r=pn(i,r);const n=new Uint8Array(r.getPrivate()),a=r.derive(t.getPublic()),s=i.curve.p.byteLength(),o=a.toArrayLike(Uint8Array,"be",s);return{secretKey:n,sharedKey:o}}(e,t,i)}var ha=/*#__PURE__*/Object.freeze({__proto__:null,validateParams:async function(e,t,r){return Rn(te.publicKey.ecdh,e,t,r)},encrypt:async function(e,t,r,i,n){const a=ta(r),s=new Un(e),{publicKey:o,sharedKey:c}=await ca(s,i),u=sa(te.publicKey.ecdh,e,t,n),{keySize:h}=ri(t.cipher);return{publicKey:o,wrappedKey:Xn(await oa(t.hash,c,h,u),a)}},decrypt:async function(e,t,r,i,n,a,s){const o=new Un(e),{sharedKey:c}=await ua(o,r,n,a),u=sa(te.publicKey.ecdh,e,t,s),{keySize:h}=ri(t.cipher);let d;for(let e=0;e<3;e++)try{return ra(Yn(await oa(t.hash,c,h,u,1===e,2===e),i))}catch(e){d=e}throw d}});const da=ie.getWebCrypto(),fa=ie.getNodeCrypto(),la=fa&&fa.webcrypto&&fa.webcrypto.subtle;async function pa(e,t,r,i,n){const a=te.read(te.webHash,e);if(!a)throw Error("Hash algo not supported with HKDF");if(da||la){const e=da||la,s=await e.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await e.deriveBits({name:"HKDF",hash:a,salt:r,info:i},s,8*n);return new Uint8Array(o)}if(fa){const a=te.read(te.hash,e),s=(e,t)=>fa.createHmac(a,e).update(t).digest(),o=s(r,t),c=o.length,u=Math.ceil(n/c),h=new Uint8Array(u*c),d=new Uint8Array(c+i.length+1);d.set(i,c);for(let e=0;e0?d:d.subarray(c));d.set(t,0),h.set(t,e*c)}return h.subarray(0,n)}throw Error("No HKDF implementation available")}const ya={x25519:ie.encodeUTF8("OpenPGP X25519")};var ba=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===te.publicKey.x25519){const e=$i(32),{publicKey:t}=Gi.box.keyPair.fromSecretKey(e);return{A:t,k:e}}throw Error("Unsupported ECDH algorithm")},validateParams:async function(e,t,r){if(e===te.publicKey.x25519){const{publicKey:e}=Gi.box.keyPair.fromSecretKey(r);return ie.equalsUint8Array(t,e)}return!1},encrypt:async function(e,t,r){if(e===te.publicKey.x25519){const e=$i(32),i=Gi.scalarMult(e,r),{publicKey:n}=Gi.box.keyPair.fromSecretKey(e),a=ie.concatUint8Array([n,r,i]),{keySize:s}=ri(te.symmetric.aes128);return{ephemeralPublicKey:n,wrappedKey:Xn(await pa(te.hash.sha256,a,new Uint8Array,ya.x25519,s),t)}}throw Error("Unsupported ECDH algorithm")},decrypt:async function(e,t,r,i,n){if(e===te.publicKey.x25519){const e=Gi.scalarMult(n,t),a=ie.concatUint8Array([t,i,e]),{keySize:s}=ri(te.symmetric.aes128);return Yn(await pa(te.hash.sha256,a,new Uint8Array,ya.x25519,s),r)}throw Error("Unsupported ECDH algorithm")}}),ma=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:Un,ecdh:ha,ecdhX:ba,ecdsa:Gn,eddsaLegacy:Vn,eddsa:Zn,generate:async function(e){const t=await ie.getBigInteger();e=new Un(e);const r=await e.genKeyPair(),i=new t(r.publicKey).toUint8Array(),n=new t(r.privateKey).toUint8Array("be",e.payloadSize);return{oid:e.oid,Q:i,secret:n,hash:e.hash,cipher:e.cipher}},getPreferredHashAlgo:function(e){return Dn[te.write(te.curve,e.toHex())].hash}});var ga=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){const s=await ie.getBigInteger(),o=new s(1);let c,u,h,d;i=new s(i),n=new s(n),r=new s(r),a=new s(a),r=r.mod(i),a=a.mod(n);const f=new s(t.subarray(0,n.byteLength())).mod(n);for(;;){if(c=await Zi(o,n),u=r.modExp(c,i).imod(n),u.isZero())continue;const e=a.mul(u).imod(n);if(d=f.add(e).imod(n),h=c.modInv(n).imul(d).imod(n),!h.isZero())break}return{r:u.toUint8Array("be",n.byteLength()),s:h.toUint8Array("be",n.byteLength())}},verify:async function(e,t,r,i,n,a,s,o){const c=await ie.getBigInteger(),u=new c(0);if(t=new c(t),r=new c(r),a=new c(a),s=new c(s),n=new c(n),o=new c(o),t.lte(u)||t.gte(s)||r.lte(u)||r.gte(s))return ie.printDebug("invalid DSA Signature"),!1;const h=new c(i.subarray(0,s.byteLength())).imod(s),d=r.modInv(s);if(d.isZero())return ie.printDebug("invalid DSA Signature"),!1;n=n.mod(a),o=o.mod(a);const f=h.mul(d).imod(s),l=t.mul(d).imod(s),p=n.modExp(f,a),y=o.modExp(l,a);return p.mul(y).imod(a).imod(s).equal(t)},validateParams:async function(e,t,r,i,n){const a=await ie.getBigInteger();e=new a(e),t=new a(t),r=new a(r),i=new a(i);const s=new a(1);if(r.lte(s)||r.gte(e))return!1;if(!e.dec().mod(t).isZero())return!1;if(!r.modExp(t,e).isOne())return!1;const o=new a(t.bitLength()),c=new a(150);if(o.lt(c)||!await Qi(t,null,32))return!1;n=new a(n);const u=new a(2),h=await Zi(u.leftShift(o.dec()),u.leftShift(o)),d=t.mul(h).add(n);return!!i.equal(r.modExp(d,e))}}),wa={rsa:dn,elgamal:fn,elliptic:ma,dsa:ga,nacl:Gi};var va=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case te.publicKey.rsaEncryptSign:case te.publicKey.rsaEncrypt:case te.publicKey.rsaSign:return{s:ie.readMPI(t.subarray(r))};case te.publicKey.dsa:case te.publicKey.ecdsa:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;return{r:e,s:ie.readMPI(t.subarray(r))}}case te.publicKey.eddsaLegacy:{let e=ie.readMPI(t.subarray(r));r+=e.length+2,e=ie.leftPad(e,32);let i=ie.readMPI(t.subarray(r));return i=ie.leftPad(i,32),{r:e,s:i}}case te.publicKey.ed25519:{const e=t.subarray(r,r+64);return r+=e.length,{RS:e}}default:throw new Sn("Unknown signature algorithm.")}},verify:async function(e,t,r,i,n,a){switch(e){case te.publicKey.rsaEncryptSign:case te.publicKey.rsaEncrypt:case te.publicKey.rsaSign:{const{n:e,e:s}=i,o=ie.leftPad(r.s,e.length);return wa.rsa.verify(t,n,o,e,s,a)}case te.publicKey.dsa:{const{g:e,p:n,q:s,y:o}=i,{r:c,s:u}=r;return wa.dsa.verify(t,c,u,a,e,n,s,o)}case te.publicKey.ecdsa:{const{oid:e,Q:s}=i,o=new wa.elliptic.CurveWithOID(e).payloadSize,c=ie.leftPad(r.r,o),u=ie.leftPad(r.s,o);return wa.elliptic.ecdsa.verify(e,t,{r:c,s:u},n,s,a)}case te.publicKey.eddsaLegacy:{const{oid:e,Q:s}=i;return wa.elliptic.eddsaLegacy.verify(e,t,r,n,s,a)}case te.publicKey.ed25519:{const{A:s}=i;return wa.elliptic.eddsa.verify(e,t,r,n,s,a)}default:throw Error("Unknown signature algorithm.")}},sign:async function(e,t,r,i,n,a){if(!r||!i)throw Error("Missing key parameters");switch(e){case te.publicKey.rsaEncryptSign:case te.publicKey.rsaEncrypt:case te.publicKey.rsaSign:{const{n:e,e:s}=r,{d:o,p:c,q:u,u:h}=i;return{s:await wa.rsa.sign(t,n,e,s,o,c,u,h,a)}}case te.publicKey.dsa:{const{g:e,p:n,q:s}=r,{x:o}=i;return wa.dsa.sign(t,a,e,n,s,o)}case te.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case te.publicKey.ecdsa:{const{oid:e,Q:s}=r,{d:o}=i;return wa.elliptic.ecdsa.sign(e,t,n,s,o,a)}case te.publicKey.eddsaLegacy:{const{oid:e,Q:s}=r,{seed:o}=i;return wa.elliptic.eddsaLegacy.sign(e,t,n,s,o,a)}case te.publicKey.ed25519:{const{A:s}=r,{seed:o}=i;return wa.elliptic.eddsa.sign(e,t,n,s,o,a)}default:throw Error("Unknown signature algorithm.")}}});class _a{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return ie.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class ka{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Sn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class Aa{static fromObject({wrappedKey:e,algorithm:t}){const r=new Aa;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=e.subarray(t,t+r),t+=r}write(){return ie.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function Sa(e){try{e.getName()}catch(e){throw new Sn("Unknown curve OID")}}var Ea=/*#__PURE__*/Object.freeze({__proto__:null,publicKeyEncrypt:async function(e,t,r,i,n){switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await wa.rsa.encrypt(i,e,t)}}case te.publicKey.elgamal:{const{p:e,g:t,y:n}=r;return wa.elgamal.encrypt(i,e,t,n)}case te.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:a}=r,{publicKey:s,wrappedKey:o}=await wa.elliptic.ecdh.encrypt(e,a,i,t,n);return{V:s,C:new _a(o)}}case te.publicKey.x25519:{if(!ie.isAES(t))throw Error("X25519 keys can only encrypt AES session keys");const{A:n}=r,{ephemeralPublicKey:a,wrappedKey:s}=await wa.elliptic.ecdhX.encrypt(e,i,n);return{ephemeralPublicKey:a,C:Aa.fromObject({algorithm:t,wrappedKey:s})}}default:return[]}},publicKeyDecrypt:async function(e,t,r,i,n,a){switch(e){case te.publicKey.rsaEncryptSign:case te.publicKey.rsaEncrypt:{const{c:e}=i,{n,e:s}=t,{d:o,p:c,q:u,u:h}=r;return wa.rsa.decrypt(e,n,s,o,c,u,h,a)}case te.publicKey.elgamal:{const{c1:e,c2:n}=i,s=t.p,o=r.x;return wa.elgamal.decrypt(e,n,s,o,a)}case te.publicKey.ecdh:{const{oid:e,Q:a,kdfParams:s}=t,{d:o}=r,{V:c,C:u}=i;return wa.elliptic.ecdh.decrypt(e,s,c,u.data,a,o,n)}case te.publicKey.x25519:{const{A:n}=t,{k:a}=r,{ephemeralPublicKey:s,C:o}=i;if(!ie.isAES(o.algorithm))throw Error("AES session key expected");return wa.elliptic.ecdhX.decrypt(e,s,o.wrappedKey,n,a)}default:throw Error("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.rsaSign:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;const i=ie.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{n:e,e:i}}}case te.publicKey.dsa:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;const i=ie.readMPI(t.subarray(r));r+=i.length+2;const n=ie.readMPI(t.subarray(r));r+=n.length+2;const a=ie.readMPI(t.subarray(r));return r+=a.length+2,{read:r,publicParams:{p:e,q:i,g:n,y:a}}}case te.publicKey.elgamal:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;const i=ie.readMPI(t.subarray(r));r+=i.length+2;const n=ie.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{p:e,g:i,y:n}}}case te.publicKey.ecdsa:{const e=new ln;r+=e.read(t),Sa(e);const i=ie.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{oid:e,Q:i}}}case te.publicKey.eddsaLegacy:{const e=new ln;r+=e.read(t),Sa(e);let i=ie.readMPI(t.subarray(r));return r+=i.length+2,i=ie.leftPad(i,33),{read:r,publicParams:{oid:e,Q:i}}}case te.publicKey.ecdh:{const e=new ln;r+=e.read(t),Sa(e);const i=ie.readMPI(t.subarray(r));r+=i.length+2;const n=new ka;return r+=n.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:i,kdfParams:n}}}case te.publicKey.ed25519:case te.publicKey.x25519:{const e=t.subarray(r,r+32);return r+=e.length,{read:r,publicParams:{A:e}}}default:throw new Sn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let i=0;switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.rsaSign:{const e=ie.readMPI(t.subarray(i));i+=e.length+2;const r=ie.readMPI(t.subarray(i));i+=r.length+2;const n=ie.readMPI(t.subarray(i));i+=n.length+2;const a=ie.readMPI(t.subarray(i));return i+=a.length+2,{read:i,privateParams:{d:e,p:r,q:n,u:a}}}case te.publicKey.dsa:case te.publicKey.elgamal:{const e=ie.readMPI(t.subarray(i));return i+=e.length+2,{read:i,privateParams:{x:e}}}case te.publicKey.ecdsa:case te.publicKey.ecdh:{const e=new Un(r.oid);let n=ie.readMPI(t.subarray(i));return i+=n.length+2,n=ie.leftPad(n,e.payloadSize),{read:i,privateParams:{d:n}}}case te.publicKey.eddsaLegacy:{const e=new Un(r.oid);let n=ie.readMPI(t.subarray(i));return i+=n.length+2,n=ie.leftPad(n,e.payloadSize),{read:i,privateParams:{seed:n}}}case te.publicKey.ed25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{seed:e}}}case te.publicKey.x25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{k:e}}}default:throw new Sn("Unknown public key encryption algorithm.")}},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:return{c:ie.readMPI(t.subarray(r))};case te.publicKey.elgamal:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:ie.readMPI(t.subarray(r))}}case te.publicKey.ecdh:{const e=ie.readMPI(t.subarray(r));r+=e.length+2;const i=new _a;return i.read(t.subarray(r)),{V:e,C:i}}case te.publicKey.x25519:{const e=t.subarray(r,r+32);r+=e.length;const i=new Aa;return i.read(t.subarray(r)),{ephemeralPublicKey:e,C:i}}default:throw new Sn("Unknown public key encryption algorithm.")}},serializeParams:function(e,t){const r=new Set([te.publicKey.ed25519,te.publicKey.x25519]),i=Object.keys(t).map((i=>{const n=t[i];return ie.isUint8Array(n)?r.has(e)?n:ie.uint8ArrayToMPI(n):n.write()}));return ie.concatUint8Array(i)},generateParams:function(e,t,r){switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.rsaSign:return wa.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:i,q:n,u:a})=>({privateParams:{d:r,p:i,q:n,u:a},publicParams:{n:e,e:t}})));case te.publicKey.ecdsa:return wa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new ln(e),Q:t}})));case te.publicKey.eddsaLegacy:return wa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new ln(e),Q:t}})));case te.publicKey.ecdh:return wa.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:i,cipher:n})=>({privateParams:{d:r},publicParams:{oid:new ln(e),Q:t,kdfParams:new ka({hash:i,cipher:n})}})));case te.publicKey.ed25519:return wa.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case te.publicKey.x25519:return wa.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case te.publicKey.dsa:case te.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.rsaSign:{const{n:e,e:i}=t,{d:n,p:a,q:s,u:o}=r;return wa.rsa.validateParams(e,i,n,a,s,o)}case te.publicKey.dsa:{const{p:e,q:i,g:n,y:a}=t,{x:s}=r;return wa.dsa.validateParams(e,i,n,a,s)}case te.publicKey.elgamal:{const{p:e,g:i,y:n}=t,{x:a}=r;return wa.elgamal.validateParams(e,i,n,a)}case te.publicKey.ecdsa:case te.publicKey.ecdh:{const i=wa.elliptic[te.read(te.publicKey,e)],{oid:n,Q:a}=t,{d:s}=r;return i.validateParams(n,a,s)}case te.publicKey.eddsaLegacy:{const{Q:e,oid:i}=t,{seed:n}=r;return wa.elliptic.eddsaLegacy.validateParams(i,e,n)}case te.publicKey.ed25519:{const{A:i}=t,{seed:n}=r;return wa.elliptic.eddsa.validateParams(e,i,n)}case te.publicKey.x25519:{const{A:i}=t,{k:n}=r;return wa.elliptic.ecdhX.validateParams(e,i,n)}default:throw Error("Unknown public key algorithm.")}},getPrefixRandom:async function(e){const{blockSize:t}=ri(e),r=await $i(t),i=new Uint8Array([r[r.length-2],r[r.length-1]]);return ie.concat([r,i])},generateSessionKey:function(e){const{keySize:t}=ri(e);return $i(t)},getAEADMode:function(e){const t=te.read(te.aead,e);return Wi[t]},getCipher:ri,getPreferredCurveHashAlgo:function(e,t){switch(e){case te.publicKey.ecdsa:case te.publicKey.eddsaLegacy:return wa.elliptic.getPreferredHashAlgo(t);case te.publicKey.ed25519:return wa.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}}});const Pa={cipher:Qe,hash:ei,mode:Wi,publicKey:wa,signature:va,random:Xi,pkcs1:an,pkcs5:ia,aesKW:ea};Object.assign(Pa,Ea);var xa="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function Ma(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)}const Ka={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+i),n);else for(let a=0;a=0;)e[t]=0}const as=0,ss=1,os=2,cs=29,us=256,hs=us+1+cs,ds=30,fs=19,ls=2*hs+1,ps=15,ys=16,bs=7,ms=256,gs=16,ws=17,vs=18,_s=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ks=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],As=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Ss=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Es=Array(2*(hs+2));ns(Es);const Ps=Array(2*ds);ns(Ps);const xs=Array(512);ns(xs);const Ms=Array(256);ns(Ms);const Ks=Array(cs);ns(Ks);const Cs=Array(ds);function Ds(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}let Us,Rs,Is;function Bs(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Ts(e){return e<256?xs[e]:xs[256+(e>>>7)]}function zs(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function qs(e,t,r){e.bi_valid>ys-r?(e.bi_buf|=t<>ys-e.bi_valid,e.bi_valid+=r-ys):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Ls(e,t,r){const i=Array(ps+1);let n,a,s=0;for(n=1;n<=ps;n++)i[n]=s=s+r[n-1]<<1;for(a=0;a<=t;a++){const t=e[2*a+1];0!==t&&(e[2*a]=Os(i[t]++,t))}}function Ns(e){let t;for(t=0;t8?zs(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Hs(e,t,r,i){const n=2*t,a=2*r;return e[n]>1;s>=1;s--)Ws(e,r,s);c=a;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Ws(e,r,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,r[2*c]=r[2*s]+r[2*o],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,r[2*s+1]=r[2*o+1]=c,e.heap[1]=c++,Ws(e,r,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){const r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let u,h,d,f,l,p,y=0;for(f=0;f<=ps;f++)e.bl_count[f]=0;for(r[2*e.heap[e.heap_max]+1]=0,u=e.heap_max+1;uc&&(f=c,y++),r[2*h+1]=f,h>i||(e.bl_count[f]++,l=0,h>=o&&(l=s[h-o]),p=r[2*h],e.opt_len+=p*(f+l),a&&(e.static_len+=p*(n[2*h+1]+l)));if(0!==y){do{for(f=c-1;0===e.bl_count[f];)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,y-=2}while(y>0);for(f=c;0!==f;f--)for(h=e.bl_count[f];0!==h;)d=e.heap[--u],d>i||(r[2*d+1]!==f&&(e.opt_len+=(f-r[2*d+1])*r[2*d],r[2*d+1]=f),h--)}}(e,t),Ls(r,u,e.bl_count)}function $s(e,t,r){let i,n,a=-1,s=t[1],o=0,c=7,u=4;for(0===s&&(c=138,u=3),t[2*(r+1)+1]=65535,i=0;i<=r;i++)n=s,s=t[2*(i+1)+1],++o>=7;i=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function eo(e,t,r,i){let n,a,s=0;e.level>0?(e.strm.data_type===rs&&(e.strm.data_type=function(e){let t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return es;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return ts;for(t=32;t=3&&0===e.bl_tree[2*Ss[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),n=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=n&&(n=a)):n=a=r+5,r+4<=n&&-1!==t?Qs(e,t,r,i):e.strategy===Ja||a===n?(qs(e,(ss<<1)+(i?1:0),3),Gs(e,Es,Ps)):(qs(e,(os<<1)+(i?1:0),3),function(e,t,r,i){let n;for(qs(e,t-257,5),qs(e,r-1,5),qs(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(Ms[r]+us+1)]++,e.dyn_dtree[2*Ts(t)]++),e.last_lit===e.lit_bufsize-1}function ro(e,t,r,i){let n=65535&e|0,a=e>>>16&65535|0,s=0;for(;0!==r;){s=r>2e3?2e3:r,r-=s;do{n=n+t[i++]|0,a=a+n|0}while(--s);n%=65521,a%=65521}return n|a<<16|0}const io=function(){let e;const t=[];for(let r=0;r<256;r++){e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function no(e,t,r,i){const n=io,a=i+r;e^=-1;for(let r=i;r>>8^n[255&(e^t[r])];return-1^e}var ao={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};const so=9,oo=3,co=258,uo=co+oo+1,ho=32,fo=42,lo=69,po=73,yo=91,bo=103,mo=113,go=666,wo=1,vo=2,_o=3,ko=4,Ao=3;function So(e,t){return e.msg=ao[t],t}function Eo(e){return(e<<1)-(e>4?9:0)}function Po(e){let t=e.length;for(;--t>=0;)e[t]=0}function xo(e){const t=e.state;let r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(Ba(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function Mo(e,t){eo(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,xo(e.strm)}function Ko(e,t){e.pending_buf[e.pending++]=t}function Co(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Do(e,t,r,i){let n=e.avail_in;return n>i&&(n=i),0===n?0:(e.avail_in-=n,Ba(t,e.input,e.next_in,n,r),1===e.state.wrap?e.adler=ro(e.adler,t,n,r):2===e.state.wrap&&(e.adler=no(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function Uo(e,t){let r,i,n=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-uo?e.strstart-(e.w_size-uo):0,u=e.window,h=e.w_mask,d=e.prev,f=e.strstart+co;let l=u[a+s-1],p=u[a+s];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do{if(r=t,u[r+s]===p&&u[r+s-1]===l&&u[r]===u[a]&&u[++r]===u[a+1]){a+=2,r++;do{}while(u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&as){if(e.match_start=t,s=i,i>=o)break;l=u[a+s-1],p=u[a+s]}}}while((t=d[t&h])>c&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Ro(e){const t=e.w_size;let r,i,n,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-uo)){Ba(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do{n=e.head[--r],e.head[r]=n>=t?n-t:0}while(--i);i=t,r=i;do{n=e.prev[--r],e.prev[r]=n>=t?n-t:0}while(--i);a+=t}if(0===e.strm.avail_in)break;if(i=Do(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=i,e.lookahead+e.insert>=oo)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=oo&&(e.ins_h=(e.ins_h<=oo)if(i=to(e,e.strstart-e.match_start,e.match_length-oo),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=oo){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=oo&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=oo-1)),e.prev_length>=oo&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-oo,i=to(e,e.strstart-1-e.prev_match,e.prev_length-oo),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Ro(e),0===e.lookahead&&t===Ta)return wo;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;const i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,Mo(e,!1),0===e.strm.avail_out))return wo;if(e.strstart-e.block_start>=e.w_size-uo&&(Mo(e,!1),0===e.strm.avail_out))return wo}return e.insert=0,t===Oa?(Mo(e,!0),0===e.strm.avail_out?_o:ko):(e.strstart>e.block_start&&(Mo(e,!1),e.strm.avail_out),wo)})),new To(4,4,8,4,Io),new To(4,5,16,8,Io),new To(4,6,32,32,Io),new To(4,4,16,16,Bo),new To(8,16,32,32,Bo),new To(8,16,128,128,Bo),new To(8,32,128,256,Bo),new To(32,128,258,1024,Bo),new To(32,258,258,4096,Bo)];class qo{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=is,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Ua(1146),this.dyn_dtree=new Ua(122),this.bl_tree=new Ua(78),Po(this.dyn_ltree),Po(this.dyn_dtree),Po(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Ua(16),this.heap=new Ua(573),Po(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Ua(573),Po(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}}function Fo(e){const t=function(e){let t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=rs,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?fo:mo,e.adler=2===t.wrap?0:1,t.last_flush=Ta,Ys(t),ja):So(e,Ga)}(e);return t===ja&&function(e){e.window_size=2*e.w_size,Po(e.head),e.max_lazy_match=zo[e.level].max_lazy,e.good_match=zo[e.level].good_length,e.nice_match=zo[e.level].nice_length,e.max_chain_length=zo[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=oo-1,e.match_available=0,e.ins_h=0}(e.state),t}function Oo(e,t){let r,i,n,a;if(!e||!e.state||t>La||t<0)return e?So(e,Ga):Ga;if(i=e.state,!e.output||!e.input&&0!==e.avail_in||i.status===go&&t!==Oa)return So(e,0===e.avail_out?$a:Ga);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===fo)if(2===i.wrap)e.adler=0,Ko(i,31),Ko(i,139),Ko(i,8),i.gzhead?(Ko(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Ko(i,255&i.gzhead.time),Ko(i,i.gzhead.time>>8&255),Ko(i,i.gzhead.time>>16&255),Ko(i,i.gzhead.time>>24&255),Ko(i,9===i.level?2:i.strategy>=Ya||i.level<2?4:0),Ko(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Ko(i,255&i.gzhead.extra.length),Ko(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=no(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=lo):(Ko(i,0),Ko(i,0),Ko(i,0),Ko(i,0),Ko(i,0),Ko(i,9===i.level?2:i.strategy>=Ya||i.level<2?4:0),Ko(i,Ao),i.status=mo);else{let t=is+(i.w_bits-8<<4)<<8,r=-1;r=i.strategy>=Ya||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=ho),t+=31-t%31,i.status=mo,Co(i,t),0!==i.strstart&&(Co(i,e.adler>>>16),Co(i,65535&e.adler)),e.adler=1}if(i.status===lo)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),xo(e),n=i.pending,i.pending!==i.pending_buf_size));)Ko(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=po)}else i.status=po;if(i.status===po)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),xo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.gzindex=0,i.status=yo)}else i.status=yo;if(i.status===yo)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),xo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=no(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.status=bo)}else i.status=bo;if(i.status===bo&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&xo(e),i.pending+2<=i.pending_buf_size&&(Ko(i,255&e.adler),Ko(i,e.adler>>8&255),e.adler=0,i.status=mo)):i.status=mo),0!==i.pending){if(xo(e),0===e.avail_out)return i.last_flush=-1,ja}else if(0===e.avail_in&&Eo(t)<=Eo(r)&&t!==Oa)return So(e,$a);if(i.status===go&&0!==e.avail_in)return So(e,$a);if(0!==e.avail_in||0!==i.lookahead||t!==Ta&&i.status!==go){var s=i.strategy===Ya?function(e,t){let r;for(;;){if(0===e.lookahead&&(Ro(e),0===e.lookahead)){if(t===Ta)return wo;break}if(e.match_length=0,r=to(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Mo(e,!1),0===e.strm.avail_out))return wo}return e.insert=0,t===Oa?(Mo(e,!0),0===e.strm.avail_out?_o:ko):e.last_lit&&(Mo(e,!1),0===e.strm.avail_out)?wo:vo}(i,t):i.strategy===Qa?function(e,t){let r,i,n,a;const s=e.window;for(;;){if(e.lookahead<=co){if(Ro(e),e.lookahead<=co&&t===Ta)return wo;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=oo&&e.strstart>0&&(n=e.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){a=e.strstart+co;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&ne.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=oo?(r=to(e,1,e.match_length-oo),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=to(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Mo(e,!1),0===e.strm.avail_out))return wo}return e.insert=0,t===Oa?(Mo(e,!0),0===e.strm.avail_out?_o:ko):e.last_lit&&(Mo(e,!1),0===e.strm.avail_out)?wo:vo}(i,t):zo[i.level].func(i,t);if(s!==_o&&s!==ko||(i.status=go),s===wo||s===_o)return 0===e.avail_out&&(i.last_flush=-1),ja;if(s===vo&&(t===za?Js(i):t!==La&&(Qs(i,0,0,!1),t===Fa&&(Po(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),xo(e),0===e.avail_out))return i.last_flush=-1,ja}return t!==Oa?ja:i.wrap<=0?Ha:(2===i.wrap?(Ko(i,255&e.adler),Ko(i,e.adler>>8&255),Ko(i,e.adler>>16&255),Ko(i,e.adler>>24&255),Ko(i,255&e.total_in),Ko(i,e.total_in>>8&255),Ko(i,e.total_in>>16&255),Ko(i,e.total_in>>24&255)):(Co(i,e.adler>>>16),Co(i,65535&e.adler)),xo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ja:Ha)}try{String.fromCharCode.call(null,0)}catch(e){}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}const Lo=new Da(256);for(let e=0;e<256;e++)Lo[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;function No(e){let t,r,i,n,a=0;const s=e.length;for(i=0;i>>6,o[n++]=128|63&t):t<65536?(o[n++]=224|t>>>12,o[n++]=128|t>>>6&63,o[n++]=128|63&t):(o[n++]=240|t>>>18,o[n++]=128|t>>>12&63,o[n++]=128|t>>>6&63,o[n++]=128|63&t);return o}Lo[254]=Lo[254]=1;class jo{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}class Ho{constructor(e){this.options={level:Za,method:is,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,...e||{}};const t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new jo,this.strm.avail_out=0;var r,i,n=function(e,t,r,i,n,a){if(!e)return Ga;let s=1;if(t===Za&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),n<1||n>so||r!==is||i<8||i>15||t<0||t>9||a<0||a>Ja)return So(e,Ga);8===i&&(i=9);const o=new qo;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=i,o.w_size=1<=r.w_size&&(0===a&&(Po(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new Da(r.w_size),Ba(u,t,h-r.w_size,r.w_size,0),t=u,h=r.w_size),s=e.avail_in,o=e.next_in,c=e.input,e.avail_in=h,e.next_in=0,e.input=t,Ro(r);r.lookahead>=oo;){i=r.strstart,n=r.lookahead-(oo-1);do{r.ins_h=(r.ins_h<0||0===r.avail_out)&&n!==Ha);return a===Oa?(n=function(e){let t;return e&&e.state?(t=e.state.status,t!==fo&&t!==lo&&t!==po&&t!==yo&&t!==bo&&t!==mo&&t!==go?So(e,Ga):(e.state=null,t===mo?So(e,Va):ja)):Ga}(this.strm),this.onEnd(n),this.ended=!0,n===ja):a!==qa||(this.onEnd(ja),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===ja&&(this.result=Ia(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}const Wo=30,Go=12;function Vo(e,t){let r,i,n,a,s,o,c,u,h,d;const f=e.state;r=e.next_in;const l=e.input,p=r+(e.avail_in-5);i=e.next_out;const y=e.output,b=i-(t-e.avail_out),m=i+(e.avail_out-257),g=f.dmax,w=f.wsize,v=f.whave,_=f.wnext,k=f.window;n=f.hold,a=f.bits;const A=f.lencode,S=f.distcode,E=(1<>>24,n>>>=o,a-=o,o=s>>>16&255,0===o)y[i++]=65535&s;else{if(!(16&o)){if(0==(64&o)){s=A[(65535&s)+(n&(1<>>=o,a-=o),a<15&&(n+=l[r++]<>>24,n>>>=o,a-=o,o=s>>>16&255,!(16&o)){if(0==(64&o)){s=S[(65535&s)+(n&(1<g){e.msg="invalid distance too far back",f.mode=Wo;break e}if(n>>>=o,a-=o,o=i-b,u>o){if(o=u-o,o>v&&f.sane){e.msg="invalid distance too far back",f.mode=Wo;break e}if(h=0,d=k,0===_){if(h+=w-o,o2;)y[i++]=d[h++],y[i++]=d[h++],y[i++]=d[h++],c-=3;c&&(y[i++]=d[h++],c>1&&(y[i++]=d[h++]))}else{h=i-u;do{y[i++]=y[h++],y[i++]=y[h++],y[i++]=y[h++],c-=3}while(c>2);c&&(y[i++]=y[h++],c>1&&(y[i++]=y[h++]))}break}}break}}while(r>3,r-=c,a-=c<<3,n&=(1<=1&&0===P[m];m--);if(g>m&&(g=m),0===m)return n[a++]=20971520,n[a++]=20971520,o.bits=1,0;for(b=1;b0&&(e===Yo||1!==m))return-1;for(x[1]=0,p=1;p<$o;p++)x[p+1]=x[p]+P[p];for(y=0;yZo||e===Jo&&k>Xo)return 1;for(;;){M=p-v,s[y]l?(K=D[U+s[y]],C=S[E+s[y]]):(K=96,C=0),u=1<>v)+h]=M<<24|K<<16|C|0}while(0!==h);for(u=1<>=1;if(0!==u?(A&=u-1,A+=u):A=0,y++,0==--P[p]){if(p===m)break;p=t[r+s[y]]}if(p>g&&(A&R)!==d){for(0===v&&(v=g),f+=b,w=p-v,_=1<Zo||e===Jo&&k>Xo)return 1;d=A&R,n[d]=g<<24|w<<16|f-a|0}}return 0!==A&&(n[f+A]=p-v<<24|64<<16|0),o.bits=g,0}const ac=0,sc=1,oc=2,cc=1,uc=2,hc=3,dc=4,fc=5,lc=6,pc=7,yc=8,bc=9,mc=10,gc=11,wc=12,vc=13,_c=14,kc=15,Ac=16,Sc=17,Ec=18,Pc=19,xc=20,Mc=21,Kc=22,Cc=23,Dc=24,Uc=25,Rc=26,Ic=27,Bc=28,Tc=29,zc=30,qc=852,Fc=592;function Oc(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}class Lc{constructor(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Ua(320),this.work=new Ua(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}}function Nc(e){let t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,function(e){let t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=cc,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Ra(qc),t.distcode=t.distdyn=new Ra(Fc),t.sane=1,t.back=-1,ja):Ga}(e)):Ga}function jc(e,t){let r,i;return e?(i=new Lc,e.state=i,i.window=null,r=function(e,t){let r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ga:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,Nc(e))):Ga}(e,t),r!==ja&&(e.state=null),r):Ga}let Hc,Wc,Gc=!0;function Vc(e){if(Gc){let t;for(Hc=new Ra(512),Wc=new Ra(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(nc(sc,e.lens,0,288,Hc,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;nc(oc,e.lens,0,32,Wc,0,e.work,{bits:5}),Gc=!1}e.lencode=Hc,e.lenbits=9,e.distcode=Wc,e.distbits=5}function $c(e,t,r,i){let n;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(Ba(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>i&&(n=i),Ba(a.window,t,r-i,n,a.wnext),(i-=n)?(Ba(a.window,t,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=no(r.check,x,2,0),u=0,h=0,r.mode=uc;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=zc;break}if((15&u)!==is){e.msg="unknown compression method",r.mode=zc;break}if(u>>>=4,h-=4,k=8+(15&u),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=zc;break}r.dmax=1<>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=no(r.check,x,2,0)),u=0,h=0,r.mode=hc;case hc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=no(r.check,x,4,0)),u=0,h=0,r.mode=dc;case dc:for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=no(r.check,x,2,0)),u=0,h=0,r.mode=fc;case fc:if(1024&r.flags){for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>>8&255,r.check=no(r.check,x,2,0)),u=0,h=0}else r.head&&(r.head.extra=null);r.mode=lc;case lc:if(1024&r.flags&&(l=r.length,l>o&&(l=o),l&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=Array(r.head.extra_len)),Ba(r.head.extra,i,a,l,k)),512&r.flags&&(r.check=no(r.check,i,l,a)),o-=l,a+=l,r.length-=l),r.length))break e;r.length=0,r.mode=pc;case pc:if(2048&r.flags){if(0===o)break e;l=0;do{k=i[a+l++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k))}while(k&&l>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=wc;break;case mc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>=7&h,h-=7&h,r.mode=Ic;break}for(;h<3;){if(0===o)break e;o--,u+=i[a++]<>>=1,h-=1,3&u){case 0:r.mode=_c;break;case 1:if(Vc(r),r.mode=xc,t===Na){u>>>=2,h-=2;break e}break;case 2:r.mode=Sc;break;case 3:e.msg="invalid block type",r.mode=zc}u>>>=2,h-=2;break;case _c:for(u>>>=7&h,h-=7&h;h<32;){if(0===o)break e;o--,u+=i[a++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=zc;break}if(r.length=65535&u,u=0,h=0,r.mode=kc,t===Na)break e;case kc:r.mode=Ac;case Ac:if(l=r.length,l){if(l>o&&(l=o),l>c&&(l=c),0===l)break e;Ba(n,i,a,l,s),o-=l,a+=l,c-=l,s+=l,r.length-=l;break}r.mode=wc;break;case Sc:for(;h<14;){if(0===o)break e;o--,u+=i[a++]<>>=5,h-=5,r.ndist=1+(31&u),u>>>=5,h-=5,r.ncode=4+(15&u),u>>>=4,h-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=zc;break}r.have=0,r.mode=Ec;case Ec:for(;r.have>>=3,h-=3}for(;r.have<19;)r.lens[M[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},A=nc(ac,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid code lengths set",r.mode=zc;break}r.have=0,r.mode=Pc;case Pc:for(;r.have>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=b,h-=b,r.lens[r.have++]=g;else{if(16===g){for(E=b+2;h>>=b,h-=b,0===r.have){e.msg="invalid bit length repeat",r.mode=zc;break}k=r.lens[r.have-1],l=3+(3&u),u>>>=2,h-=2}else if(17===g){for(E=b+3;h>>=b,h-=b,k=0,l=3+(7&u),u>>>=3,h-=3}else{for(E=b+7;h>>=b,h-=b,k=0,l=11+(127&u),u>>>=7,h-=7}if(r.have+l>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=zc;break}for(;l--;)r.lens[r.have++]=k}}if(r.mode===zc)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=zc;break}if(r.lenbits=9,S={bits:r.lenbits},A=nc(sc,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid literal/lengths set",r.mode=zc;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},A=nc(oc,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,A){e.msg="invalid distances set",r.mode=zc;break}if(r.mode=xc,t===Na)break e;case xc:r.mode=Mc;case Mc:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,r.hold=u,r.bits=h,Vo(e,f),s=e.next_out,n=e.output,c=e.avail_out,a=e.next_in,i=e.input,o=e.avail_in,u=r.hold,h=r.bits,r.mode===wc&&(r.back=-1);break}for(r.back=0;P=r.lencode[u&(1<>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,m=P>>>16&255,g=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,r.length=g,0===m){r.mode=Rc;break}if(32&m){r.back=-1,r.mode=wc;break}if(64&m){e.msg="invalid literal/length code",r.mode=zc;break}r.extra=15&m,r.mode=Kc;case Kc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=Cc;case Cc:for(;P=r.distcode[u&(1<>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,m=P>>>16&255,g=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,64&m){e.msg="invalid distance code",r.mode=zc;break}r.offset=g,r.extra=15&m,r.mode=Dc;case Dc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=zc;break}r.mode=Uc;case Uc:if(0===c)break e;if(l=f-c,r.offset>l){if(l=r.offset-l,l>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=zc;break}l>r.wnext?(l-=r.wnext,p=r.wsize-l):p=r.wnext-l,l>r.length&&(l=r.length),y=r.window}else y=n,p=s-r.offset,l=r.length;l>c&&(l=c),c-=l,r.length-=l;do{n[s++]=y[p++]}while(--l);0===r.length&&(r.mode=Mc);break;case Rc:if(0===c)break e;n[s++]=r.length,c--,r.mode=Mc;break;case Ic:if(r.wrap){for(;h<32;){if(0===o)break e;o--,u|=i[a++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new jo,this.strm.avail_out=0;let r=jc(this.strm,t.windowBits);if(r!==ja)throw Error(ao[r]);if(this.header=new Yc,function(e,t){let r;e&&e.state&&(r=e.state,0==(2&r.wrap)||(r.head=t,t.done=!1))}(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=No(t.dictionary):t.dictionary instanceof ArrayBuffer&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=Xc(this.strm,t.dictionary),r!==ja)))throw Error(ao[r])}push(e,t){const{strm:r,options:{chunkSize:i,dictionary:n}}=this;let a,s,o=!1;if(this.ended)return!1;s=t===~~t?t:!0===t?Oa:Ta,"string"==typeof e?r.input=function(e){const t=new Da(e.length);for(let r=0,i=t.length;r0||0===r.avail_out)&&a!==Ha);return a===Ha&&(s=Oa),s===Oa?(a=function(e){if(!e||!e.state)return Ga;const t=e.state;return t.window&&(t.window=null),e.state=null,ja}(this.strm),this.onEnd(a),this.ended=!0,a===ja):s!==qa||(this.onEnd(ja),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===ja&&(this.result=Ia(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}var Jc=[0,1,3,7,15,31,63,127,255],eu=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};eu.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},eu.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Jc[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var i=r-e;t|=(this.curByte&Jc[e]<>i,this.bitOffset+=e,e=0}}return t},eu.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},eu.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var tu=eu,ru=function(){};ru.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},ru.prototype.read=function(e,t,r){for(var i=0;i>>0},this.updateCRC=function(t){e=e<<8^iu[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^iu[255&(e>>>24^t)]}}),su=function(e,t){var r,i=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=i,i},ou={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},cu={};cu[ou.LAST_BLOCK]="Bad file checksum",cu[ou.NOT_BZIP_DATA]="Not bzip data",cu[ou.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",cu[ou.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",cu[ou.DATA_ERROR]="Data error",cu[ou.OUT_OF_MEMORY]="Out of memory",cu[ou.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var uu=function(e,t){var r=cu[e]||"unknown error";t&&(r+=": "+t);var i=new TypeError(r);throw i.errorCode=e,i},hu=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};hu.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new au,!0):(this.writeCount=-1,!1)},hu.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||uu(ou.NOT_BZIP_DATA,"bad magic");var i=r[3]-48;(i<1||i>9)&&uu(ou.NOT_BZIP_DATA,"level out of range"),this.reader=new tu(e),this.dbufSize=1e5*i,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},hu.prototype._get_next_block=function(){var e,t,r,i=this.reader,n=i.pi();if("177245385090"===n)return!1;"314159265359"!==n&&uu(ou.NOT_BZIP_DATA),this.targetBlockCRC=i.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,i.read(1)&&uu(ou.OBSOLETE_INPUT);var a=i.read(24);a>this.dbufSize&&uu(ou.DATA_ERROR,"initial position out of bounds");var s=i.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(s&1<<15-e){var u=16*e;for(r=i.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=u+t)}var h=i.read(3);(h<2||h>6)&&uu(ou.DATA_ERROR);var d=i.read(15);0===d&&uu(ou.DATA_ERROR);var f=new Uint8Array(256);for(e=0;e=h&&uu(ou.DATA_ERROR);l[e]=su(f,t)}var p,y=c+2,b=[];for(t=0;t20)&&uu(ou.DATA_ERROR),i.read(1);)i.read(1)?s--:s++;w[e]=s}for(m=g=w[0],e=1;eg?g=w[e]:w[e]=d&&uu(ou.DATA_ERROR),p=b[l[P++]]),e=p.minLen,t=i.read(e);e>p.maxLen&&uu(ou.DATA_ERROR),!(t<=p.limit[e]);e++)t=t<<1|i.read(1);((t-=p.base[e])<0||t>=258)&&uu(ou.DATA_ERROR);var M=p.permute[t];if(0!==M&&1!==M){if(S)for(S=0,E+s>this.dbufSize&&uu(ou.DATA_ERROR),k[A=o[f[0]]]+=s;s--;)x[E++]=A;if(M>c)break;E>=this.dbufSize&&uu(ou.DATA_ERROR),k[A=o[A=su(f,e=M-1)]]++,x[E++]=A}else S||(S=1,s=0),s+=0===M?S:2*S,S<<=1}for((a<0||a>=E)&&uu(ou.DATA_ERROR),t=0,e=0;e<256;e++)r=t+k[e],k[e]=t,t=r;for(e=0;e>=8,D=-1),this.writePos=K,this.writeCurrent=C,this.writeCount=E,this.writeRun=D,!0},hu.prototype._read_bunzip=function(e,t){var r,i,n;if(this.writeCount<0)return 0;var a=this.dbuf,s=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var u=this.writeRun;c;){for(c--,i=o,o=255&(s=a[s]),s>>=8,3==u++?(r=o,n=i,o=-1):(r=1,n=o),this.blockCRC.updateCRCRun(n,r);r--;)this.outputStream.writeByte(n),this.nextoutput++;o!=i&&(u=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&uu(ou.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var du=function(e){if("readByte"in e)return e;var t=new nu;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},fu=function(e){var t=new nu,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var lu=function(e,t,r){for(var i=du(e),n=fu(t),a=new hu(i,n);!("eof"in i)||!i.eof();)if(a._init_block())a._read_bunzip();else{var s=a.reader.read(32)>>>0;if(s!==a.streamCRC&&uu(ou.DATA_ERROR,"Bad stream CRC (got "+a.streamCRC.toString(16)+" expected "+s.toString(16)+")"),!r||!("eof"in i)||i.eof())break;a._start_bunzip(i,n)}if("getBuffer"in n)return n.getBuffer()};class pu{static get tag(){return te.packet.literalData}constructor(e=new Date){this.format=te.literal.utf8,this.date=ie.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=te.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||ie.isStream(this.text))&&(this.text=ie.decodeUTF8(ie.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=ie.canonicalizeEOL(ie.encodeUTF8(this.text))),e?G(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await H(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=ie.decodeUTF8(await e.readBytes(r)),this.date=ie.readDate(await e.readBytes(4));let i=e.remainder();l(i)&&(i=await Z(i)),this.setBytes(i,t)}))}writeHeader(){const e=ie.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),i=ie.writeDate(this.date);return ie.concatUint8Array([r,t,e,i])}write(){const e=this.writeHeader(),t=this.getBytes();return ie.concat([e,t])}}const yu=Symbol("verified"),bu=new Set([te.signatureSubpacket.issuer,te.signatureSubpacket.issuerFingerprint,te.signatureSubpacket.embeddedSignature]);class mu{static get tag(){return te.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.signedHashValue=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new _e,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.revoked=null,this[yu]=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version)throw new Sn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[t++],this.publicKeyAlgorithm=e[t++],this.hashAlgorithm=e[t++],t+=this.readSubPackets(e.subarray(t,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");this.signatureData=e.subarray(0,t),t+=this.readSubPackets(e.subarray(t,e.length),!1),this.signedHashValue=e.subarray(t,t+2),t+=2,this.params=Pa.signature.parseSignatureParams(this.publicKeyAlgorithm,e.subarray(t,e.length))}writeParams(){return this.params instanceof Promise?Y((async()=>Pa.serializeParams(this.publicKeyAlgorithm,await this.params))):Pa.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),e.push(this.writeParams()),ie.concat(e)}async sign(e,t,r=new Date,i=!1){5===e.version?this.version=5:this.version=4;const n=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];this.created=ie.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID(),n.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=ie.concat(n);const a=this.toHash(this.signatureType,t,i),s=await this.hash(this.signatureType,t,a,i);this.signedHashValue=$(W(s),0,2);const o=async()=>Pa.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await Z(s));ie.isStream(s)?this.params=o():(this.params=await o(),this[yu]=!0)}writeHashedSubPackets(){const e=te.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(gu(e.signatureCreationTime,!0,ie.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(gu(e.signatureExpirationTime,!0,ie.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(gu(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(gu(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(gu(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(gu(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(gu(e.keyExpirationTime,!0,ie.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(gu(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=ie.concat([r,this.revocationKeyFingerprint]),t.push(gu(e.revocationKey,!1,r))),this.issuerKeyID.isNull()||5===this.issuerKeyVersion||t.push(gu(e.issuer,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:i,value:n,humanReadable:a,critical:s})=>{r=[new Uint8Array([a?128:0,0,0,0])];const o=ie.encodeUTF8(i);r.push(ie.writeNumber(o.length,2)),r.push(ie.writeNumber(n.length,2)),r.push(o),r.push(n),r=ie.concat(r),t.push(gu(e.notationData,s,r))})),null!==this.preferredHashAlgorithms&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(gu(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(gu(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.keyServerPreferences)),t.push(gu(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(gu(e.preferredKeyServer,!1,ie.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(gu(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(gu(e.policyURI,!1,ie.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.keyFlags)),t.push(gu(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(gu(e.signersUserID,!1,ie.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=ie.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(gu(e.reasonForRevocation,!0,r))),null!==this.features&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.features)),t.push(gu(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(ie.stringToUint8Array(this.signatureTargetHash)),r=ie.concat(r),t.push(gu(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(gu(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=ie.concat(r),t.push(gu(e.issuerFingerprint,5===this.version,r))),null!==this.preferredAEADAlgorithms&&(r=ie.stringToUint8Array(ie.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(gu(e.preferredAEADAlgorithms,!1,r)));const i=ie.concat(t),n=ie.writeNumber(i.length,2);return ie.concat([n,i])}writeUnhashedSubPackets(){const e=[];this.unhashedSubpackets.forEach((t=>{e.push(gn(t.length)),e.push(t)}));const t=ie.concat(e),r=ie.writeNumber(t.length,2);return ie.concat([r,t])}readSubPacket(e,t=!0){let r=0;const i=!!(128&e[r]),n=127&e[r];if(t||(this.unhashedSubpackets.push(e.subarray(r,e.length)),bu.has(n)))switch(r++,n){case te.signatureSubpacket.signatureCreationTime:this.created=ie.readDate(e.subarray(r,e.length));break;case te.signatureSubpacket.signatureExpirationTime:{const t=ie.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case te.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case te.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case te.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case te.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case te.signatureSubpacket.keyExpirationTime:{const t=ie.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case te.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case te.signatureSubpacket.issuer:this.issuerKeyID.read(e.subarray(r,e.length));break;case te.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const n=ie.readNumber(e.subarray(r,r+2));r+=2;const a=ie.readNumber(e.subarray(r,r+2));r+=2;const s=ie.decodeUTF8(e.subarray(r,r+n)),o=e.subarray(r+n,r+n+a);this.rawNotations.push({name:s,humanReadable:t,value:o,critical:i}),t&&(this.notations[s]=ie.decodeUTF8(o));break}case te.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=ie.decodeUTF8(e.subarray(r,e.length));break;case te.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case te.signatureSubpacket.policyURI:this.policyURI=ie.decodeUTF8(e.subarray(r,e.length));break;case te.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.signersUserID:this.signersUserID=ie.decodeUTF8(e.subarray(r,e.length));break;case te.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=ie.decodeUTF8(e.subarray(r,e.length));break;case te.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case te.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=Pa.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=ie.uint8ArrayToString(e.subarray(r,r+t));break}case te.signatureSubpacket.embeddedSignature:this.embeddedSignature=new mu,this.embeddedSignature.read(e.subarray(r,e.length));break;case te.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),5===this.issuerKeyVersion?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case te.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;default:{const e=Error("Unknown signature subpacket type "+n);if(i)throw e;ie.printDebug(e)}}}readSubPackets(e,t=!0,r){const i=ie.readNumber(e.subarray(0,2));let n=2;for(;n<2+i;){const i=mn(e.subarray(n,e.length));n+=i.offset,this.readSubPacket(e.subarray(n,n+i.len),t,r),n+=i.len}return n}toSign(e,t){const r=te.signature;switch(e){case r.binary:return null!==t.text?ie.encodeUTF8(t.getText(!0)):t.getBytes(!0);case r.text:{const e=t.getBytes(!0);return ie.canonicalizeEOL(e)}case r.standalone:return new Uint8Array(0);case r.certGeneric:case r.certPersona:case r.certCasual:case r.certPositive:case r.certRevocation:{let e,i;if(t.userID)i=180,e=t.userID;else{if(!t.userAttribute)throw Error("Either a userID or userAttribute packet needs to be supplied for certification.");i=209,e=t.userAttribute}const n=e.write();return ie.concat([this.toSign(r.key,t),new Uint8Array([i]),ie.writeNumber(n.length,4),n])}case r.subkeyBinding:case r.subkeyRevocation:case r.keyBinding:return ie.concat([this.toSign(r.key,t),this.toSign(r.key,{key:t.bind})]);case r.key:if(void 0===t.key)throw Error("Key packet is required for this signature.");return t.key.writeForHash(this.version);case r.keyRevocation:return this.toSign(r.key,t);case r.timestamp:return new Uint8Array(0);case r.thirdParty:throw Error("Not implemented");default:throw Error("Unknown signature type.")}}calculateTrailer(e,t){let r=0;return N(W(this.signatureData),(e=>{r+=e.length}),(()=>{const i=[];return 5!==this.version||this.signatureType!==te.signature.binary&&this.signatureType!==te.signature.text||(t?i.push(new Uint8Array(6)):i.push(e.writeHeader())),i.push(new Uint8Array([this.version,255])),5===this.version&&i.push(new Uint8Array(4)),i.push(ie.writeNumber(r,4)),ie.concat(i)}))}toHash(e,t,r=!1){const i=this.toSign(e,t);return ie.concat([i,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,i=!1){return r||(r=this.toHash(e,t,i)),Pa.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,i=new Date,n=!1,a=de){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const s=t===te.signature.binary||t===te.signature.text;if(!(this[yu]&&!s)){let i,a;if(this.hashed?a=await this.hashed:(i=this.toHash(t,r,n),a=await this.hash(t,r,i)),a=await Z(a),this.signedHashValue[0]!==a[0]||this.signedHashValue[1]!==a[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[yu]=await Pa.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,i,a),!this[yu])throw Error("Signature verification failed")}const o=ie.normalizeDate(i);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(a.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+te.read(te.hash,this.hashAlgorithm).toUpperCase());if(a.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[te.signature.binary,te.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+te.read(te.hash,this.hashAlgorithm).toUpperCase());if(this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&a.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=ie.normalizeDate(e);return null!==t&&!(this.created<=t&&tmu.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==te.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function vu(e,t){if(!t[e]){let t;try{t=te.read(te.packet,e)}catch(t){throw new Sn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}wu.prototype.hash=mu.prototype.hash,wu.prototype.toHash=mu.prototype.toHash,wu.prototype.toSign=mu.prototype.toSign;class _u extends Array{static async fromBinary(e,t,r=de){const i=new _u;return await i.read(e,t,r),i}async read(e,t,r=de){r.additionalAllowedPackets.length&&(t={...t,...ie.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=j(e,(async(e,i)=>{const n=q(i);try{for(;;){await n.ready;if(await An(e,(async e=>{try{if(e.tag===te.packet.marker||e.tag===te.packet.trust)return;const i=vu(e.tag,t);i.packets=new _u,i.fromStream=ie.isStream(e.packet),await i.read(e.packet,r),await n.write(i)}catch(t){const i=!r.ignoreUnsupportedPackets&&t instanceof Sn,a=!(r.ignoreMalformedPackets||t instanceof Sn);if(i||a||kn(e.tag))await n.abort(t);else{const t=new En(e.tag,e.packet);await n.write(t)}ie.printDebugError(t)}})))return await n.ready,void await n.close()}}catch(e){await n.abort(e)}}));const i=z(this.stream);for(;;){const{done:e,value:t}=await i.read();if(e?this.stream=null:this.push(t),e||kn(t.constructor.tag))break}i.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),n+=e.length,n>=a){const e=Math.min(Math.log(n)/Math.LN2|0,30),r=2**e,i=ie.concat([wn(e)].concat(t));return t=[i.subarray(1+r)],n=t[0].length,i.subarray(0,1+r)}}),(()=>ie.concat([gn(n)].concat(t)))))}else{if(ie.isStream(i)){let t=0;e.push(N(W(i),(e=>{t+=e.length}),(()=>_n(r,t))))}else e.push(_n(r,i.length));e.push(i)}}return ie.concat(e)}filterByTag(...e){const t=new _u,r=e=>t=>e===t;for(let i=0;it.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,i=e=>t=>e===t;for(let n=0;n{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),ie.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=de){const t=te.read(te.compression,this.algorithm),r=Cu[t];if(!r)throw Error(t+" decompression not supported");this.packets=await _u.fromBinary(r(this.compressed),ku,e)}compress(){const e=te.read(te.compression,this.algorithm),t=Ku[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write(),this.deflateLevel)}}const Su=ie.getNodeZlib();function Eu(e){return e}function Pu(e,t,r={}){return function(i){return!ie.isStream(i)||l(i)?Y((()=>Z(i).then((t=>new Promise(((i,n)=>{e(t,r,((e,t)=>{if(e)return n(e);i(t)}))})))))):k(A(i).pipe(t(r)))}}function xu(e,t={}){return function(r){const i=new e(t);return N(r,(e=>{if(e.length)return i.push(e,qa),i.result}),(()=>{if(e===Ho)return i.push([],Oa),i.result}))}}function Mu(e){return function(t){return Y((async()=>e(await Z(t))))}}const Ku=Su?{zip:/*#__PURE__*/(e,t)=>Pu(Su.deflateRaw,Su.createDeflateRaw,{level:t})(e),zlib:/*#__PURE__*/(e,t)=>Pu(Su.deflate,Su.createDeflate,{level:t})(e)}:{zip:/*#__PURE__*/(e,t)=>xu(Ho,{raw:!0,level:t})(e),zlib:/*#__PURE__*/(e,t)=>xu(Ho,{level:t})(e)},Cu=Su?{uncompressed:Eu,zip:/*#__PURE__*/Pu(Su.inflateRaw,Su.createInflateRaw),zlib:/*#__PURE__*/Pu(Su.inflate,Su.createInflate),bzip2:/*#__PURE__*/Mu(lu)}:{uncompressed:Eu,zip:/*#__PURE__*/xu(Qc,{raw:!0}),zlib:/*#__PURE__*/xu(Qc),bzip2:/*#__PURE__*/Mu(lu)},Du=/*#__PURE__*/ie.constructAllowedPackets([pu,Au,wu,mu]);class Uu{static get tag(){return te.packet.symEncryptedIntegrityProtectedData}constructor(){this.version=1,this.encrypted=null,this.packets=null}async read(e){await H(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Sn(`Version ${t} of the SEIP packet is unsupported.`);this.encrypted=e.remainder()}))}write(){return ie.concat([new Uint8Array([1]),this.encrypted])}async encrypt(e,t,r=de){const{blockSize:i}=Pa.getCipher(e);let n=this.packets.write();l(n)&&(n=await Z(n));const a=await Pa.getPrefixRandom(e),s=new Uint8Array([211,20]),o=ie.concat([a,n,s]),c=await Pa.hash.sha1(G(o)),u=ie.concat([o,c]);return this.encrypted=await Pa.mode.cfb.encrypt(e,t,u,new Uint8Array(i),r),!0}async decrypt(e,t,r=de){const{blockSize:i}=Pa.getCipher(e);let n=W(this.encrypted);l(n)&&(n=await Z(n));const a=await Pa.mode.cfb.decrypt(e,t,n,new Uint8Array(i)),s=$(G(a),-20),o=$(a,0,-20),c=Promise.all([Z(await Pa.hash.sha1(G(o))),Z(s)]).then((([e,t])=>{if(!ie.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=$(o,i+2);let h=$(u,0,-2);return h=T([h,Y((()=>c))]),ie.isStream(n)&&r.allowUnauthenticatedStream||(h=await Z(h)),this.packets=await _u.fromBinary(h,Du,r),!0}}const Ru=/*#__PURE__*/ie.constructAllowedPackets([pu,Au,wu,mu]);class Iu{static get tag(){return te.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=te.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await H(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Sn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=Pa.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return ie.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=de){this.packets=await _u.fromBinary(await this.crypt("decrypt",t,W(this.encrypted)),Ru,r)}async encrypt(e,t,r=de){this.cipherAlgorithm=e;const{ivLength:i}=Pa.getAEADMode(this.aeadAlgorithm);this.iv=Pa.random.getRandomBytes(i),this.chunkSizeByte=r.aeadChunkSizeByte;const n=this.packets.write();this.encrypted=await this.crypt("encrypt",t,n)}async crypt(e,t,r){const i=Pa.getAEADMode(this.aeadAlgorithm),n=await i(this.cipherAlgorithm,t),a="decrypt"===e?i.tagLength:0,s="encrypt"===e?i.tagLength:0,o=2**(this.chunkSizeByte+6)+a,c=new ArrayBuffer(21),u=new Uint8Array(c,0,13),h=new Uint8Array(c),d=new DataView(c),f=new Uint8Array(c,5,8);u.set([192|Iu.tag,this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte],0);let l=0,p=Promise.resolve(),y=0,b=0;const m=this.iv;return j(r,(async(t,r)=>{if("array"!==ie.isStream(t)){const e=new D({},{highWaterMark:ie.getHardwareConcurrency()*2**(this.chunkSizeByte+6),size:e=>e.length});F(e.readable,r),r=e.writable}const c=z(t),g=q(r);try{for(;;){let t=await c.readBytes(o+a)||new Uint8Array;const r=t.subarray(t.length-a);let w,v;if(t=t.subarray(0,t.length-a),!l||t.length?(c.unshift(r),w=n[e](t,i.getNonce(m,f),u),b+=t.length-a+s):(d.setInt32(17,y),w=n[e](r,i.getNonce(m,f),h),b+=s,v=!0),y+=t.length-a,p=p.then((()=>w)).then((async e=>{await g.ready,await g.write(e),b-=e.length})).catch((e=>g.abort(e))),(v||b>g.desiredSize)&&await p,v){await g.close();break}d.setInt32(9,++l)}}catch(e){await g.abort(e)}}))}}class Bu{static get tag(){return te.packet.publicKeyEncryptedSessionKey}constructor(){this.version=3,this.publicKeyID=new _e,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}read(e){let t=0;if(this.version=e[t++],3!==this.version)throw new Sn(`Version ${this.version} of the PKESK packet is unsupported.`);t+=this.publicKeyID.read(e.subarray(t)),this.publicKeyAlgorithm=e[t++],this.encrypted=Pa.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t),this.version),this.publicKeyAlgorithm===te.publicKey.x25519&&(this.sessionKeyAlgorithm=te.write(te.symmetric,this.encrypted.C.algorithm))}write(){const e=[new Uint8Array([this.version]),this.publicKeyID.write(),new Uint8Array([this.publicKeyAlgorithm]),Pa.serializeParams(this.publicKeyAlgorithm,this.encrypted)];return ie.concatUint8Array(e)}async encrypt(e){const t=te.write(te.publicKey,this.publicKeyAlgorithm),r=Tu(this.version,t,this.sessionKeyAlgorithm,this.sessionKey);this.encrypted=await Pa.publicKeyEncrypt(t,this.sessionKeyAlgorithm,e.publicParams,r,e.getFingerprintBytes())}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Tu(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,i=await Pa.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,e.getFingerprintBytes(),r),{sessionKey:n,sessionKeyAlgorithm:a}=function(e,t,r,i){switch(t){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.elgamal:case te.publicKey.ecdh:{const e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=ie.writeChecksum(e.subarray(e.length%8)),a=n[0]===t[0]&n[1]===t[1],s={sessionKeyAlgorithm:e[0],sessionKey:e.subarray(1)};if(i){const e=a&s.sessionKeyAlgorithm===i.sessionKeyAlgorithm&s.sessionKey.length===i.sessionKey.length;return{sessionKey:ie.selectUint8Array(e,s.sessionKey,i.sessionKey),sessionKeyAlgorithm:ie.selectUint8(e,s.sessionKeyAlgorithm,i.sessionKeyAlgorithm)}}if(a&&te.read(te.symmetric,s.sessionKeyAlgorithm))return s;throw Error("Decryption error")}case te.publicKey.x25519:return{sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);this.publicKeyAlgorithm!==te.publicKey.x25519&&(this.sessionKeyAlgorithm=a),this.sessionKey=n}}function Tu(e,t,r,i){switch(t){case te.publicKey.rsaEncrypt:case te.publicKey.rsaEncryptSign:case te.publicKey.elgamal:case te.publicKey.ecdh:return ie.concatUint8Array([new Uint8Array([r]),i,ie.writeChecksum(i.subarray(i.length%8))]);case te.publicKey.x25519:return i;default:throw Error("Unsupported public key algorithm")}}class zu{constructor(e=de){this.algorithm=te.hash.sha256,this.type="iterated",this.c=e.s2kIterationCountByte,this.salt=null}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;try{this.type=te.read(te.s2k,e[t++])}catch(e){throw new Sn("Unknown S2K type.")}switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==ie.uint8ArrayToString(e.subarray(t,t+3)))throw new Sn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Sn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Sn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...ie.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([te.write(te.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return ie.concatUint8Array(e)}async produceKey(e,t){e=ie.encodeUTF8(e);const r=[];let i=0,n=0;for(;i{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function Gu(e,t,r){const{keySize:i}=Pa.getCipher(r);return e.produceKey(t,i)}var Vu=ht((function(e){!function(t){function r(e){function t(){return Ae0&&(t.semantic=" "),t}}function b(e,t){return function(){var i,a,o,u,h;for(u=r(),i=s("star"),o=0,h=void 0===t?0:t;null!==(a=e());)o+=1,c(i,a);return o>=h?i:(n(u),null)}}function m(e){return e.charCodeAt(0)>=128}function g(){return o("cr",h("\r")())}function w(){return o("crlf",d(g,k)())}function v(){return o("dquote",h('"')())}function _(){return o("htab",h("\t")())}function k(){return o("lf",h("\n")())}function A(){return o("sp",h(" ")())}function S(){return o("vchar",u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i})))}function E(){return o("wsp",f(A,_)())}function P(){var e=o("quoted-pair",f(d(h("\\"),f(S,E)),ie)());return null===e?null:(e.semantic=e.semantic[1],e)}function x(){return o("fws",f(ae,d(l(d(b(E),p(w))),b(E,1)))())}function M(){return o("ctext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=39||42<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),te)())}function K(){return o("ccontent",f(M,P,C)())}function C(){return o("comment",d(h("("),b(d(l(x),K)),l(x),h(")"))())}function D(){return o("cfws",f(d(b(d(l(x),C),1),l(x)),x)())}function U(){return o("atext",u((function(t){var r="a"<=t&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||["!","#","$","%","&","'","*","+","-","/","=","?","^","_","`","{","|","}","~"].indexOf(t)>=0;return e.rfc6532&&(r=r||m(t)),r})))}function R(){return o("atom",d(y(l(D)),b(U,1),y(l(D)))())}function I(){var e,t;return null===(e=o("dot-atom-text",b(U,1)()))||null!==(t=b(d(h("."),b(U,1)))())&&c(e,t),e}function B(){return o("dot-atom",d(p(l(D)),I,p(l(D)))())}function T(){return o("qtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33===r||35<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),re)())}function z(){return o("qcontent",f(T,P)())}function q(){return o("quoted-string",d(p(l(D)),p(v),b(d(l(y(x)),z)),l(p(x)),p(v),p(l(D)))())}function F(){return o("word",f(R,q)())}function O(){return o("address",f(L,H)())}function L(){return o("mailbox",f(N,J)())}function N(){return o("name-addr",d(l(W),j)())}function j(){return o("angle-addr",f(d(p(l(D)),h("<"),J,h(">"),p(l(D))),se)())}function H(){return o("group",d(W,h(":"),l($),h(";"),p(l(D)))())}function W(){return o("display-name",(null!==(e=o("phrase",f(ne,b(F,1))()))&&(e.semantic=function(e){return e.replace(/([ \t]|\r\n)+/g," ").replace(/^\s*/,"").replace(/\s*$/,"")}(e.semantic)),e));var e}function G(){return o("mailbox-list",f(d(L,b(d(h(","),L))),ue)())}function V(){return o("address-list",f(d(O,b(d(h(","),O))),he)())}function $(){return o("group-list",f(G,p(D),de)())}function Z(){return o("local-part",f(fe,B,q)())}function X(){return o("dtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=90||94<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),pe)())}function Y(){return o("domain-literal",d(p(l(D)),h("["),b(d(l(x),X)),l(x),h("]"),p(l(D)))())}function Q(){return o("domain",(t=f(le,B,Y)(),e.rejectTLD&&t&&t.semantic&&t.semantic.indexOf(".")<0?null:(t&&(t.semantic=t.semantic.replace(/\s+/g,"")),t)));var t}function J(){return o("addr-spec",d(Z,h("@"),Q)())}function ee(){return e.strict?null:o("obs-NO-WS-CTL",u((function(e){var t=e.charCodeAt(0);return 1<=t&&t<=8||11===t||12===t||14<=t&&t<=31||127===t})))}function te(){return e.strict?null:o("obs-ctext",ee())}function re(){return e.strict?null:o("obs-qtext",ee())}function ie(){return e.strict?null:o("obs-qp",d(h("\\"),f(h("\0"),ee,k,g))())}function ne(){return e.strict?null:e.atInDisplayName?o("obs-phrase",d(F,b(f(F,h("."),h("@"),y(D))))()):o("obs-phrase",d(F,b(f(F,h("."),y(D))))())}function ae(){return e.strict?null:o("obs-FWS",b(d(p(l(w)),E),1)())}function se(){return e.strict?null:o("obs-angle-addr",d(p(l(D)),h("<"),oe,J,h(">"),p(l(D)))())}function oe(){return e.strict?null:o("obs-route",d(ce,h(":"))())}function ce(){return e.strict?null:o("obs-domain-list",d(b(f(p(D),h(","))),h("@"),Q,b(d(h(","),p(l(D)),l(d(h("@"),Q)))))())}function ue(){return e.strict?null:o("obs-mbox-list",d(b(d(p(l(D)),h(","))),L,b(d(h(","),l(d(L,p(D))))))())}function he(){return e.strict?null:o("obs-addr-list",d(b(d(p(l(D)),h(","))),O,b(d(h(","),l(d(O,p(D))))))())}function de(){return e.strict?null:o("obs-group-list",d(b(d(p(l(D)),h(",")),1),p(l(D)))())}function fe(){return e.strict?null:o("obs-local-part",d(F,b(d(h("."),F)))())}function le(){return e.strict?null:o("obs-domain",d(R,b(d(h("."),R)))())}function pe(){return e.strict?null:o("obs-dtext",f(ee,P)())}function ye(e,t){var r,i,n;if(null==t)return null;for(i=[t];i.length>0;){if((n=i.pop()).name===e)return n;for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r])}return null}function be(e,t){var r,i,n,a,s;if(null==t)return null;for(i=[t],a=[],s={},r=0;r0;)if((n=i.pop()).name in s)a.push(n);else for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}function me(t){var r,i,n,a,s;if(null===t)return null;for(r=[],i=be(["group","mailbox"],t),n=0;n1)return null;return t.addresses&&t.addresses[0]}(s):e.simple?s&&s.addresses:s}function ge(e){var t,r=ye("display-name",e),i=[],n=be(["mailbox"],e);for(t=0;t0;)for((n=i.pop()).name===e&&a.push(n),r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}("cfws",e),n=be(["comment"],e),a=ye("local-part",r),s=ye("domain",r);return{node:e,parts:{name:t,address:r,local:a,domain:s,comments:i},type:e.name,name:ve(t),address:ve(r),local:ve(a),domain:ve(s),comments:_e(n),groupName:ve(e.groupName)}}function ve(e){return null!=e?e.semantic:null}function _e(e){var t="";if(e)for(var r=0;r`),t.userID=r.join(" "),t}read(e,t=de){const r=ie.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");try{const{name:e,address:t,comments:i}=Vu.parseOneAddress({input:r,atInDisplayName:!0});this.comment=i.replace(/^\(|\)$/g,""),this.name=e,this.email=t}catch(e){}this.userID=r}write(){return ie.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Zu extends Wu{static get tag(){return te.packet.secretSubkey}constructor(e=new Date,t=de){super(e,t)}}class Xu{static get tag(){return te.packet.trust}read(){throw new Sn("Trust packets are not supported")}write(){throw new Sn("Trust packets are not supported")}}const Yu=/*#__PURE__*/ie.constructAllowedPackets([mu]);class Qu{constructor(e){this.packets=e||new _u}write(){return this.packets.write()}armor(e=de){return ve(te.armor.signature,this.write(),void 0,void 0,void 0,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Ju({armoredSignature:e,binarySignature:t,config:r,...i}){r={...de,...r};let n=e||t;if(!n)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!ie.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!ie.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:e,data:t}=await we(n,r);if(e!==te.armor.signature)throw Error("Armored text not of type signature");n=t}const s=await _u.fromBinary(n,Yu,r);return new Qu(s)}async function eh(e,t){const r=new Zu(e.date,t);return r.packets=null,r.algorithm=te.write(te.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function th(e,t){const r=new Wu(e.date,t);return r.packets=null,r.algorithm=te.write(te.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function rh(e,t,r,i,n=new Date,a){let s,o;for(let c=e.length-1;c>=0;c--)try{(!s||e[c].created>=s.created)&&(await e[c].verify(t,r,i,n,void 0,a),s=e[c])}catch(e){o=e}if(!s)throw ie.wrapError(`Could not find valid ${te.read(te.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return s}function ih(e,t,r=new Date){const i=ie.normalizeDate(r);if(null!==i){const r=hh(e,t);return!(e.created<=i&&i0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1);return await oh(n,null,t,a,r.date,void 0,void 0,void 0,i)}async function ah(e,t,r=new Date,i={},n){let a=n.preferredHashAlgorithm,s=a;if(e){const t=await e.getPrimaryUser(r,i,n);t.selfCertification.preferredHashAlgorithms&&([s]=t.selfCertification.preferredHashAlgorithms,a=Pa.hash.getHashByteLength(a)<=Pa.hash.getHashByteLength(s)?s:a)}switch(t.algorithm){case te.publicKey.ecdsa:case te.publicKey.eddsaLegacy:case te.publicKey.ed25519:s=Pa.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid)}return Pa.hash.getHashByteLength(a)<=Pa.hash.getHashByteLength(s)?s:a}async function sh(e,t=[],r=new Date,i=[],n=de){const a={symmetric:te.symmetric.aes128,aead:te.aead.eax,compression:te.compression.uncompressed}[e],s={symmetric:n.preferredSymmetricAlgorithm,aead:n.preferredAEADAlgorithm,compression:n.preferredCompressionAlgorithm}[e],o={symmetric:"preferredSymmetricAlgorithms",aead:"preferredAEADAlgorithms",compression:"preferredCompressionAlgorithms"}[e],c=await Promise.all(t.map((async function(e,t){const a=(await e.getPrimaryUser(r,i[t],n)).selfCertification[o];return!!a&&a.indexOf(s)>=0})));return c.every(Boolean)?s:a}async function oh(e,t,r,i,n,a,s=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const u=new mu;return Object.assign(u,i),u.publicKeyAlgorithm=r.algorithm,u.hashAlgorithm=await ah(t,r,n,a,c),u.rawNotations=s,await u.sign(r,e,n,o),u}async function ch(e,t,r,i=new Date,n){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(i)||n&&!await n(e)||t[r].some((function(t){return ie.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function uh(e,t,r,i,n,a,s=new Date,o){a=a||e;const c=[];return await Promise.all(i.map((async function(e){try{n&&!e.issuerKeyID.equals(n.issuerKeyID)||(await e.verify(a,t,r,o.revocationsExpire?s:null,!1,o),c.push(e.issuerKeyID))}catch(e){}}))),n?(n.revoked=!!c.some((e=>e.equals(n.issuerKeyID)))||(n.revoked||!1),n.revoked):c.length>0}function hh(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function dh(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=ie.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=te.write(te.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==te.curve.ed25519Legacy&&e.curve!==te.curve.curve25519Legacy||(e.curve=e.sign?te.curve.ed25519Legacy:te.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===te.curve.ed25519Legacy?te.publicKey.eddsaLegacy:te.publicKey.ecdsa:e.algorithm=te.publicKey.ecdh;break;case"rsa":e.algorithm=te.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function fh(e,t){const r=e.algorithm;return r!==te.publicKey.rsaEncrypt&&r!==te.publicKey.elgamal&&r!==te.publicKey.ecdh&&r!==te.publicKey.x25519&&(!t.keyFlags||0!=(t.keyFlags[0]&te.keyFlags.signData))}function lh(e,t){const r=e.algorithm;return r!==te.publicKey.dsa&&r!==te.publicKey.rsaSign&&r!==te.publicKey.ecdsa&&r!==te.publicKey.eddsaLegacy&&r!==te.publicKey.ed25519&&(!t.keyFlags||0!=(t.keyFlags[0]&te.keyFlags.encryptCommunication)||0!=(t.keyFlags[0]&te.keyFlags.encryptStorage))}function ph(e,t){return!!t.allowInsecureDecryptionWithSigningKeys||(!e.keyFlags||0!=(e.keyFlags[0]&te.keyFlags.encryptCommunication)||0!=(e.keyFlags[0]&te.keyFlags.encryptStorage))}function yh(e,t){const r=te.write(te.publicKey,e.algorithm),i=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(i.algorithm+" keys are considered too weak.");switch(r){case te.publicKey.rsaEncryptSign:case te.publicKey.rsaSign:case te.publicKey.rsaEncrypt:if(i.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const a=await t.getSigningKey(o,e.created,void 0,i);if(e.revoked||await n.isRevoked(e,a.keyPacket,r,i))throw Error("User certificate is revoked");try{await e.verify(a.keyPacket,te.signature.certGeneric,s,r,void 0,i)}catch(e){throw ie.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const i=this,n=this.selfCertifications.concat(this.otherCertifications);return Promise.all(n.map((async n=>({keyID:n.issuerKeyID,valid:await i.verifyCertificate(n,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};let a;for(let s=this.selfCertifications.length-1;s>=0;s--)try{const a=this.selfCertifications[s];if(a.revoked||await r.isRevoked(a,void 0,e,t))throw Error("Self-certification is revoked");try{await a.verify(i,te.signature.certGeneric,n,e,void 0,t)}catch(e){throw ie.wrapError("Self-certification is invalid",e)}return!0}catch(e){a=e}throw a}async update(e,t,r){const i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};await ch(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(i,te.signature.certGeneric,n,t,!1,r),!0}catch(e){return!1}})),await ch(e,this,"otherCertifications",t),await ch(e,this,"revocationSignatures",t,(function(e){return uh(i,te.signature.certRevocation,n,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=te.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=de){const a={userID:this.userID,userAttribute:this.userAttribute,key:e},s=new bh(a.userID||a.userAttribute,this.mainKey);return s.revocationSignatures.push(await oh(a,null,e,{signatureType:te.signature.certRevocation,reasonForRevocationFlag:te.write(te.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}}class mh{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new _u;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new mh(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,i=de){const n=this.mainKey.keyPacket;return uh(n,te.signature.subkeyRevocation,{key:n,bind:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verify(e=new Date,t=de){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket},n=await rh(this.bindingSignatures,r,te.signature.subkeyBinding,i,e,t);if(n.revoked||await this.isRevoked(n,null,e,t))throw Error("Subkey is revoked");if(ih(this.keyPacket,n,e))throw Error("Subkey is expired");return n}async getExpirationTime(e=new Date,t=de){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket};let n;try{n=await rh(this.bindingSignatures,r,te.signature.subkeyBinding,i,e,t)}catch(e){return null}const a=hh(this.keyPacket,n),s=n.getExpirationTime();return an.bindingSignatures[t].created&&(n.bindingSignatures[t]=e),!1;try{return await e.verify(i,te.signature.subkeyBinding,a,t,void 0,r),!0}catch(e){return!1}})),await ch(e,this,"revocationSignatures",t,(function(e){return uh(i,te.signature.subkeyRevocation,a,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=te.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=de){const a={key:e,bind:this.keyPacket},s=new mh(this.keyPacket,this.mainKey);return s.revocationSignatures.push(await oh(a,null,e,{signatureType:te.signature.subkeyRevocation,reasonForRevocationFlag:te.write(te.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{mh.prototype[e]=function(){return this.keyPacket[e]()}}));const gh=/*#__PURE__*/ie.constructAllowedPackets([mu]),wh=new Set([te.packet.publicKey,te.packet.privateKey]),vh=new Set([te.packet.publicKey,te.packet.privateKey,te.packet.publicSubkey,te.packet.privateSubkey]);class _h{packetListToStructure(e,t=new Set){let r,i,n,a;for(const s of e){if(s instanceof En){vh.has(s.tag)&&!a&&(a=wh.has(s.tag)?wh:vh);continue}const e=s.constructor.tag;if(a){if(!a.has(e))continue;a=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case te.packet.publicKey:case te.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=s,i=this.getKeyID(),!i)throw Error("Missing Key ID");break;case te.packet.userID:case te.packet.userAttribute:r=new bh(s,this),this.users.push(r);break;case te.packet.publicSubkey:case te.packet.secretSubkey:r=null,n=new mh(s,this),this.subkeys.push(n);break;case te.packet.signature:switch(s.signatureType){case te.signature.certGeneric:case te.signature.certPersona:case te.signature.certCasual:case te.signature.certPositive:if(!r){ie.printDebug("Dropping certification signatures without preceding user packet");continue}s.issuerKeyID.equals(i)?r.selfCertifications.push(s):r.otherCertifications.push(s);break;case te.signature.certRevocation:r?r.revocationSignatures.push(s):this.directSignatures.push(s);break;case te.signature.key:this.directSignatures.push(s);break;case te.signature.subkeyBinding:if(!n){ie.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}n.bindingSignatures.push(s);break;case te.signature.keyRevocation:this.revocationSignatures.push(s);break;case te.signature.subkeyRevocation:if(!n){ie.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}n.revocationSignatures.push(s)}}}}toPacketList(){const e=new _u;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},i=de){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await rh(r.bindingSignatures,n,te.signature.subkeyBinding,e,t,i);if(!fh(r.keyPacket,a))continue;if(!a.embeddedSignature)throw Error("Missing embedded signature");return await rh([a.embeddedSignature],r.keyPacket,te.signature.keyBinding,e,t,i),yh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&fh(n,a.selfCertification))return yh(n,i),this}catch(e){s=e}throw ie.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),s)}async getEncryptionKey(e,t=new Date,r={},i=de){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await rh(r.bindingSignatures,n,te.signature.subkeyBinding,e,t,i);if(lh(r.keyPacket,a))return yh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&lh(n,a.selfCertification))return yh(n,i),this}catch(e){s=e}throw ie.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),s)}async isRevoked(e,t,r=new Date,i=de){return uh(this.keyPacket,te.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verifyPrimaryKey(e=new Date,t={},r=de){const i=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");const{selfCertification:n}=await this.getPrimaryUser(e,t,r);if(ih(i,n,e))throw Error("Primary key is expired");const a=await rh(this.directSignatures,i,te.signature.key,{key:i},e,r).catch((()=>{}));if(a&&ih(i,a,e))throw Error("Primary key is expired")}async getExpirationTime(e,t=de){let r;try{const{selfCertification:i}=await this.getPrimaryUser(null,e,t),n=hh(this.keyPacket,i),a=i.getExpirationTime(),s=await rh(this.directSignatures,this.keyPacket,te.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(s){const e=hh(this.keyPacket,s);r=Math.min(n,a,e)}else r=ne.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const i=this.clone();return await ch(e,i,"revocationSignatures",t,(n=>uh(i.keyPacket,te.signature.keyRevocation,i,[n],null,e.keyPacket,t,r))),await ch(e,i,"directSignatures",t),await Promise.all(e.users.map((async e=>{const n=i.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const n=i.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.subkeys.push(t)}}))),i}async getRevocationCertificate(e=new Date,t=de){const r={key:this.keyPacket},i=await rh(this.revocationSignatures,this.keyPacket,te.signature.keyRevocation,r,e,t),n=new _u;return n.push(i),ve(te.armor.publicKey,n.write(),null,null,"This is a revocation certificate")}async applyRevocationCertificate(e,t=new Date,r=de){const i=await we(e,r),n=(await _u.fromBinary(i.data,gh,r)).findPacket(te.packet.signature);if(!n||n.signatureType!==te.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!n.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await n.verify(this.keyPacket,te.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw ie.wrapError("Could not verify revocation signature",e)}const a=this.clone();return a.revocationSignatures.push(n),a}async signPrimaryUser(e,t,r,i=de){const{index:n,user:a}=await this.getPrimaryUser(t,r,i),s=await a.certify(e,t,i),o=this.clone();return o.users[n]=s,o}async signAllUsers(e,t=new Date,r=de){const i=this.clone();return i.users=await Promise.all(this.users.map((function(i){return i.certify(e,t,r)}))),i}async verifyPrimaryUser(e,t=new Date,r,i=de){const n=this.keyPacket,{user:a}=await this.getPrimaryUser(t,r,i);return e?await a.verifyAllCertifications(e,t,i):[{keyID:n.getKeyID(),valid:await a.verify(t,i).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=de){const i=this.keyPacket,n=[];return await Promise.all(this.users.map((async a=>{const s=e?await a.verifyAllCertifications(e,t,r):[{keyID:i.getKeyID(),valid:await a.verify(t,r).catch((()=>!1))}];n.push(...s.map((e=>({userID:a.userID?a.userID.userID:null,userAttribute:a.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),n}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{_h.prototype[e]=mh.prototype[e]}));class kh extends _h{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([te.packet.secretKey,te.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=de){return ve(te.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,e)}}class Ah extends kh{constructor(e){if(super(),this.packetListToStructure(e,new Set([te.packet.publicKey,te.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new _u,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case te.packet.secretKey:{const t=Fu.fromSecretKeyPacket(r);e.push(t);break}case te.packet.secretSubkey:{const t=ju.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new kh(e)}armor(e=de){return ve(te.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,e)}async getDecryptionKeys(e,t=new Date,r={},i=de){const n=this.keyPacket,a=[];for(let r=0;re.isDecrypted()))}async validate(e=de){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys(),t=e.map((e=>e.keyPacket.isDummy())).every(Boolean);if(t)throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=te.reasonForRevocation.noReason,string:t=""}={},r=new Date,i=de){if(!this.isPrivate())throw Error("Need private key for revoking");const n={key:this.keyPacket},a=this.clone();return a.revocationSignatures.push(await oh(n,null,this.keyPacket,{signatureType:te.signature.keyRevocation,reasonForRevocationFlag:te.write(te.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,i)),a}async addSubkey(e={}){const t={...de,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}const s=$u.fromObject(t),o={};o.userID=s,o.key=e;const c={};c.signatureType=te.signature.certGeneric,c.keyFlags=[te.keyFlags.certifyKeys|te.keyFlags.signData],c.preferredSymmetricAlgorithms=a([te.symmetric.aes256,te.symmetric.aes128,te.symmetric.aes192],i.preferredSymmetricAlgorithm),i.aeadProtect&&(c.preferredAEADAlgorithms=a([te.aead.eax,te.aead.ocb],i.preferredAEADAlgorithm)),c.preferredHashAlgorithms=a([te.hash.sha256,te.hash.sha512],i.preferredHashAlgorithm),c.preferredCompressionAlgorithms=a([te.compression.zlib,te.compression.zip,te.compression.uncompressed],i.preferredCompressionAlgorithm),0===n&&(c.isPrimaryUserID=!0),c.features=[0],c.features[0]|=te.features.modificationDetection,i.aeadProtect&&(c.features[0]|=te.features.aead),i.v5Keys&&(c.features[0]|=te.features.v5Keys),r.keyExpirationTime>0&&(c.keyExpirationTime=r.keyExpirationTime,c.keyNeverExpires=!1);return{userIDPacket:s,signaturePacket:await oh(o,null,e,c,r.date,void 0,void 0,void 0,i)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{n.push(e),n.push(t)}))})),await Promise.all(t.map((async function(t,n){const a=r.subkeys[n];return{secretSubkeyPacket:t,subkeySignaturePacket:await nh(t,e,a,i)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{n.push(e),n.push(t)}))}));const a={key:e};return n.push(await oh(a,null,e,{signatureType:te.signature.keyRevocation,reasonForRevocationFlag:te.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,i)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new Ah(n)}async function xh({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...de,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!ie.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!ie.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await we(e,r);if(t!==te.armor.publicKey&&t!==te.armor.privateKey)throw Error("Armored text not of type key");a=i}else a=t;return Eh(await _u.fromBinary(a,Sh,r))}async function Mh({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...de,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!ie.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!ie.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await we(e,r);if(t!==te.armor.privateKey)throw Error("Armored text not of type private key");a=i}else a=t;const s=await _u.fromBinary(a,Sh,r);return new Ah(s)}async function Kh({armoredKeys:e,binaryKeys:t,config:r,...i}){r={...de,...r};let n=e||t;if(!n)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!ie.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!ie.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:t,data:i}=await we(e,r);if(t!==te.armor.publicKey&&t!==te.armor.privateKey)throw Error("Armored text not of type key");n=i}const s=[],o=await _u.fromBinary(n,Sh,r),c=o.indexOfTag(te.packet.publicKey,te.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(te.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,i=new Date,n=de){const a=r||await this.decryptSessionKeys(e,t,i,n),s=this.packets.filterByTag(te.packet.symmetricallyEncryptedData,te.packet.symEncryptedIntegrityProtectedData,te.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const o=s[0];let c=null;const u=Promise.all(a.map((async({algorithm:e,data:t})=>{if(!ie.isUint8Array(t)||!ie.isString(e))throw Error("Invalid session key for decryption.");try{const r=te.write(te.symmetric,e);await o.decrypt(r,t,n)}catch(e){ie.printDebugError(e),c=e}})));if(X(o.encrypted),o.encrypted=null,await u,!o.packets||!o.packets.length)throw c||Error("Decryption failed.");const h=new Ih(o.packets);return o.packets=new _u,h}async decryptSessionKeys(e,t,r=new Date,i=de){let n,a=[];if(t){const e=this.packets.filterByTag(te.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await _u.fromBinary(e.write(),Uh,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){ie.printDebugError(e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(te.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let s=[te.symmetric.aes256,te.symmetric.aes128,te.symmetric.tripledes,te.symmetric.cast5];try{const t=await e.getPrimaryUser(r,void 0,i);t.selfCertification.preferredSymmetricAlgorithms&&(s=s.concat(t.selfCertification.preferredSymmetricAlgorithms))}catch(e){}const o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket));await Promise.all(o.map((async function(e){if(!e||e.isDummy())return;if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===te.publicKey.rsaEncrypt||t.publicKeyAlgorithm===te.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===te.publicKey.rsaSign||t.publicKeyAlgorithm===te.publicKey.elgamal)){const r=t.write();await Promise.all(Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map((async t=>{const i=new Bu;i.read(r);const s={sessionKeyAlgorithm:t,sessionKey:Pa.generateSessionKey(t)};try{await i.decrypt(e,s),a.push(i)}catch(e){ie.printDebugError(e),n=e}})))}else try{if(await t.decrypt(e),!s.includes(te.write(te.symmetric,t.sessionKeyAlgorithm)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){ie.printDebugError(e),n=e}})))}))),X(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+ie.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:te.read(te.symmetric,e.sessionKeyAlgorithm)})))}throw n||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(te.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(te.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(te.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],i=de){const n=await sh("symmetric",e,t,r,i),a=te.read(te.symmetric,n),s=i.aeadProtect&&await async function(e,t=new Date,r=[],i=de){let n=!0;return await Promise.all(e.map((async function(e,a){const s=await e.getPrimaryUser(t,r[a],i);s.selfCertification.features&&s.selfCertification.features[0]&te.features.aead||(n=!1)}))),n}(e,t,r,i)?te.read(te.aead,await sh("aead",e,t,r,i)):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&e.keyPacket.algorithm===te.publicKey.x25519&&!ie.isAES(n))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:Pa.generateSessionKey(n),algorithm:a,aeadAlgorithm:s}}async encrypt(e,t,r,i=!1,n=[],a=new Date,s=[],o=de){if(r){if(!ie.isUint8Array(r.data)||!ie.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Ih.generateSessionKey(e,a,s,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Ih.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:u,aeadAlgorithm:h}=r,d=await Ih.encryptSessionKey(c,u,h,e,t,i,n,a,s,o);let f;h?(f=new Iu,f.aeadAlgorithm=te.write(te.aead,h)):f=new Uu,f.packets=this.packets;const l=te.write(te.symmetric,u);return await f.encrypt(l,c,o),d.packets.push(f),f.packets=new _u,d}static async encryptSessionKey(e,t,r,i,n,a=!1,s=[],o=new Date,c=[],u=de){const h=new _u,d=te.write(te.symmetric,t),f=r&&te.write(te.aead,r);if(i){const t=await Promise.all(i.map((async function(t,r){const i=await t.getEncryptionKey(s[r],o,c,u),n=new Bu;return n.publicKeyID=a?_e.wildcard():i.getKeyID(),n.publicKeyAlgorithm=i.keyPacket.algorithm,n.sessionKey=e,n.sessionKeyAlgorithm=d,await n.encrypt(i.keyPacket),delete n.sessionKey,n})));h.push(...t)}if(n){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,i=async function(e,a,s,o){const c=new qu(u);if(c.sessionKey=e,c.sessionKeyAlgorithm=a,s&&(c.aeadAlgorithm=s),await c.encrypt(o,u),u.passwordCollisionCheck){if(1!==(await Promise.all(n.map((e=>t(c,e))))).reduce(r))return i(e,a,o)}return delete c.sessionKey,c},a=await Promise.all(n.map((t=>i(e,d,f,t))));h.push(...a)}return new Ih(h)}async sign(e=[],t=null,r=[],i=new Date,n=[],a=[],s=de){const o=new _u,c=this.packets.findPacket(te.packet.literalData);if(!c)throw Error("No literal data packet to sign.");let u,h;const d=null===c.text?te.signature.binary:te.signature.text;if(t)for(h=t.packets.filterByTag(te.packet.signature),u=h.length-1;u>=0;u--){const t=h[u],r=new wu;r.signatureType=t.signatureType,r.hashAlgorithm=t.hashAlgorithm,r.publicKeyAlgorithm=t.publicKeyAlgorithm,r.issuerKeyID=t.issuerKeyID,e.length||0!==u||(r.flags=1),o.push(r)}return await Promise.all(Array.from(e).reverse().map((async function(t,a){if(!t.isPrivate())throw Error("Need private key for signing");const o=r[e.length-1-a],c=await t.getSigningKey(o,i,n,s),u=new wu;return u.signatureType=d,u.hashAlgorithm=await ah(t,c.keyPacket,i,n,s),u.publicKeyAlgorithm=c.keyPacket.algorithm,u.issuerKeyID=c.getKeyID(),a===e.length-1&&(u.flags=1),u}))).then((e=>{e.forEach((e=>o.push(e)))})),o.push(c),o.push(...await Bh(c,e,t,r,i,n,a,!1,s)),new Ih(o)}compress(e,t=de){if(e===te.compression.uncompressed)return this;const r=new Au(t);r.algorithm=e,r.packets=this.packets;const i=new _u;return i.push(r),new Ih(i)}async signDetached(e=[],t=null,r=[],i=new Date,n=[],a=[],s=de){const o=this.packets.findPacket(te.packet.literalData);if(!o)throw Error("No literal data packet to sign.");return new Qu(await Bh(o,e,t,r,i,n,a,!0,s))}async verify(e,t=new Date,r=de){const i=this.unwrapCompressed(),n=i.packets.filterByTag(te.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");l(i.packets.stream)&&i.packets.push(...await Z(i.packets.stream,(e=>e||[])));const a=i.packets.filterByTag(te.packet.onePassSignature).reverse(),s=i.packets.filterByTag(te.packet.signature);return a.length&&!s.length&&ie.isStream(i.packets.stream)&&!l(i.packets.stream)?(await Promise.all(a.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=Y((async()=>(await e.correspondingSig).signatureData)),e.hashed=Z(await e.hash(e.signatureType,n[0],void 0,!1)),e.hashed.catch((()=>{}))}))),i.packets.stream=j(i.packets.stream,(async(e,t)=>{const r=z(e),i=q(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await i.abort(e)}})),Th(a,n,e,t,!1,r)):Th(s,n,e,t,!1,r)}verifyDetached(e,t,r=new Date,i=de){const n=this.unwrapCompressed().packets.filterByTag(te.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");return Th(e.packets.filterByTag(te.packet.signature),n,t,r,!0,i)}unwrapCompressed(){const e=this.packets.filterByTag(te.packet.compressedData);return e.length?new Ih(e[0].packets):this}async appendSignature(e,t=de){await this.packets.read(ie.isUint8Array(e)?e:(await we(e)).data,Rh,t)}write(){return this.packets.write()}armor(e=de){return ve(te.armor.message,this.write(),null,null,null,e)}}async function Bh(e,t,r=null,i=[],n=new Date,a=[],s=[],o=!1,c=de){const u=new _u,h=null===e.text?te.signature.binary:te.signature.text;if(await Promise.all(t.map((async(t,r)=>{const u=a[r];if(!t.isPrivate())throw Error("Need private key for signing");const d=await t.getSigningKey(i[r],n,u,c);return oh(e,t,d.keyPacket,{signatureType:h},n,u,s,o,c)}))).then((e=>{u.push(...e)})),r){const e=r.packets.filterByTag(te.packet.signature);u.push(...e)}return u}async function Th(e,t,r,i=new Date,n=!1,a=de){return Promise.all(e.filter((function(e){return["text","binary"].includes(te.read(te.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,i=new Date,n=!1,a=de){let s,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){s=t,o=r[0];break}}const c=e instanceof wu?e.correspondingSig:e,u={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],i,n,a);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await s.getSigningKey(o.getKeyID(),r.created,void 0,a)}catch(e){if(!a.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await s.getSigningKey(o.getKeyID(),i,void 0,a)}return!0})(),signature:(async()=>{const e=await c,t=new _u;return e&&t.push(e),new Qu(t)})()};return u.signature.catch((()=>{})),u.verified.catch((()=>{})),u}(e,t,r,i,n,a)})))}async function zh({armoredMessage:e,binaryMessage:t,config:r,...i}){r={...de,...r};let n=e||t;if(!n)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!ie.isString(e)&&!ie.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!ie.isUint8Array(t)&&!ie.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));const s=ie.isStream(n);if(s&&(await U(),n=I(n)),e){const{type:e,data:t}=await we(n,r);if(e!==te.armor.message)throw Error("Armored text not of type message");n=t}const o=await _u.fromBinary(n,Dh,r),c=new Ih(o);return c.fromStream=s,c}async function qh({text:e,binary:t,filename:r,date:i=new Date,format:n=(void 0!==e?"utf8":"binary"),...a}){let s=void 0!==e?e:t;if(void 0===s)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!ie.isString(e)&&!ie.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!ie.isUint8Array(t)&&!ie.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=ie.isStream(s);c&&(await U(),s=I(s));const u=new pu(i);void 0!==e?u.setText(s,te.write(te.literal,n)):u.setBytes(s,te.write(te.literal,n)),void 0!==r&&u.setFilename(r);const h=new _u;h.push(u);const d=new Ih(h);return d.fromStream=c,d}const Fh=/*#__PURE__*/ie.constructAllowedPackets([mu]);class Oh{constructor(e,t){if(this.text=ie.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof Qu))throw Error("Invalid signature input");this.signature=t||new Qu(new _u)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=null,r=[],i=new Date,n=[],a=[],s=de){const o=new pu;o.setText(this.text);const c=new Qu(await Bh(o,e,t,r,i,n,a,!0,s));return new Oh(this.text,c)}verify(e,t=new Date,r=de){const i=this.signature.packets.filterByTag(te.packet.signature),n=new pu;return n.setText(this.text),Th(i,[n],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=de){let t=this.signature.packets.map((function(e){return te.read(te.hash,e.hashAlgorithm).toUpperCase()}));t=t.filter((function(e,t,r){return r.indexOf(e)===t}));const r={hash:t.join(),text:this.text,data:this.signature.packets.write()};return ve(te.armor.signed,r,void 0,void 0,void 0,e)}}async function Lh({cleartextMessage:e,config:t,...r}){if(t={...de,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!ie.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const i=Object.keys(r);if(i.length>0)throw Error("Unknown option: "+i.join(", "));const n=await we(e);if(n.type!==te.armor.signed)throw Error("No cleartext signed message.");const a=await _u.fromBinary(n.data,Fh,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let i=0;i0)throw Error("Unknown option: "+r.join(", "));return new Oh(e)}async function jh({userIDs:e=[],passphrase:t,type:r="ecc",rsaBits:i=4096,curve:n="curve25519",keyExpirationTime:a=0,date:s=new Date,subkeys:o=[{}],format:c="armored",config:u,...h}){ad(u={...de,...u}),e=sd(e);const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));if(0===e.length)throw Error("UserIDs are required for key generation");if("rsa"===r&&idh(e.subkeys[r],e)));let r=[th(e,t)];r=r.concat(e.subkeys.map((e=>eh(e,t))));const i=await Promise.all(r),n=await Ph(i[0],i.slice(1),e,t),a=await n.getRevocationCertificate(e.date,t);return n.revocationSignatures=[],{key:n,revocationCertificate:a}}(f,u);return e.getKeys().forEach((({keyPacket:e})=>yh(e,u))),{privateKey:ud(e,c,u),publicKey:ud(e.toPublic(),c,u),revocationCertificate:t}}catch(e){throw ie.wrapError("Error generating keypair",e)}}async function Hh({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:i=0,date:n,format:a="armored",config:s,...o}){ad(s={...de,...s}),t=sd(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length)throw Error("UserIDs are required for key reformat");const u={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:i,date:n};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const i=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,n={key:i,bind:r},a=await rh(e.bindingSignatures,i,te.signature.subkeyBinding,n,null,t).catch((()=>({})));return{sign:a.keyFlags&&a.keyFlags[0]&te.keyFlags.signData}}))));const n=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==n.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const a=await Ph(i,n,e,t),s=await a.getRevocationCertificate(e.date,t);return a.revocationSignatures=[],{key:a,revocationCertificate:s};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=ie.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(u,s);return{privateKey:ud(e,a,s),publicKey:ud(e.toPublic(),a,s),revocationCertificate:t}}catch(e){throw ie.wrapError("Error reformatting keypair",e)}}async function Wh({key:e,revocationCertificate:t,reasonForRevocation:r,date:i=new Date,format:n="armored",config:a,...s}){ad(a={...de,...a});const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const s=t?await e.applyRevocationCertificate(t,i,a):await e.revoke(r,i,a);return s.isPrivate()?{privateKey:ud(s,n,a),publicKey:ud(s.toPublic(),n,a)}:{privateKey:null,publicKey:ud(s,n,a)}}catch(e){throw ie.wrapError("Error revoking key",e)}}async function Gh({privateKey:e,passphrase:t,config:r,...i}){ad(r={...de,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const a=e.clone(!0),s=ie.isArray(t)?t:[t];try{return await Promise.all(a.getKeys().map((e=>ie.anyPromise(s.map((t=>e.keyPacket.decrypt(t))))))),await a.validate(r),a}catch(e){throw a.clearPrivateParams(),ie.wrapError("Error decrypting private key",e)}}async function Vh({privateKey:e,passphrase:t,config:r,...i}){ad(r={...de,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const a=e.clone(!0),s=a.getKeys(),o=ie.isArray(t)?t:Array(s.length).fill(t);if(o.length!==s.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(s.map((async(e,t)=>{const{keyPacket:i}=e;await i.encrypt(o[t],r),i.clearPrivateParams()}))),a}catch(e){throw a.clearPrivateParams(),ie.wrapError("Error encrypting private key",e)}}async function $h({message:e,encryptionKeys:t,signingKeys:r,passwords:i,sessionKey:n,format:a="armored",signature:s=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:u=[],date:h=new Date,signingUserIDs:d=[],encryptionUserIDs:f=[],signatureNotations:l=[],config:p,...y}){if(ad(p={...de,...p}),td(e),id(a),t=sd(t),r=sd(r),i=sd(i),c=sd(c),u=sd(u),d=sd(d),f=sd(f),l=sd(l),y.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(y.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(y.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==y.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const b=Object.keys(y);if(b.length>0)throw Error("Unknown option: "+b.join(", "));r||(r=[]);const m=e.fromStream;try{if((r.length||s)&&(e=await e.sign(r,s,c,h,d,l,p)),e=e.compress(await sh("compression",t,h,f,p),p),e=await e.encrypt(t,i,n,o,u,h,f,p),"object"===a)return e;const y="armored"===a;return od(y?e.armor(p):e.write(),m,y?"utf8":"binary")}catch(e){throw ie.wrapError("Error encrypting message",e)}}async function Zh({message:e,decryptionKeys:t,passwords:r,sessionKeys:i,verificationKeys:n,expectSigned:a=!1,format:s="utf8",signature:o=null,date:c=new Date,config:u,...h}){if(ad(u={...de,...u}),td(e),n=sd(n),t=sd(t),r=sd(r),i=sd(i),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(h.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));try{const h=await e.decrypt(t,r,i,c,u);n||(n=[]);const d={};if(d.signatures=o?await h.verifyDetached(o,n,c,u):await h.verify(n,c,u),d.data="binary"===s?h.getLiteralData():h.getText(),d.filename=h.getFilename(),cd(d,e),a){if(0===n.length)throw Error("Verification keys are required to verify message signatures");if(0===d.signatures.length)throw Error("Message is not signed");d.data=T([d.data,Y((async()=>{await ie.anyPromise(d.signatures.map((e=>e.verified)))}))])}return d.data=await od(d.data,e.fromStream,s),d}catch(e){throw ie.wrapError("Error decrypting message",e)}}async function Xh({message:e,signingKeys:t,format:r="armored",detached:i=!1,signingKeyIDs:n=[],date:a=new Date,signingUserIDs:s=[],signatureNotations:o=[],config:c,...u}){if(ad(c={...de,...c}),rd(e),id(r),t=sd(t),n=sd(n),s=sd(s),o=sd(o),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==u.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const h=Object.keys(u);if(h.length>0)throw Error("Unknown option: "+h.join(", "));if(e instanceof Oh&&"binary"===r)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Oh&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let u;if(u=i?await e.signDetached(t,void 0,n,a,s,o,c):await e.sign(t,void 0,n,a,s,o,c),"object"===r)return u;const h="armored"===r;return u=h?u.armor(c):u.write(),i&&(u=j(e.packets.write(),(async(e,t)=>{await Promise.all([F(u,t),Z(e).catch((()=>{}))])}))),od(u,e.fromStream,h?"utf8":"binary")}catch(e){throw ie.wrapError("Error signing message",e)}}async function Yh({message:e,verificationKeys:t,expectSigned:r=!1,format:i="utf8",signature:n=null,date:a=new Date,config:s,...o}){if(ad(s={...de,...s}),rd(e),t=sd(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Oh&&"binary"===i)throw Error("Can't return cleartext message data as binary");if(e instanceof Oh&&n)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=n?await e.verifyDetached(n,t,a,s):await e.verify(t,a,s),o.data="binary"===i?e.getLiteralData():e.getText(),e.fromStream&&!n&&cd(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=T([o.data,Y((async()=>{await ie.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await od(o.data,e.fromStream,i),o}catch(e){throw ie.wrapError("Error verifying signed message",e)}}async function Qh({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:i,...n}){if(ad(i={...de,...i}),e=sd(e),r=sd(r),n.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await Ih.generateSessionKey(e,t,r,i)}catch(e){throw ie.wrapError("Error generating session key",e)}}async function Jh({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:i,passwords:n,format:a="armored",wildcard:s=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:u=[],config:h,...d}){if(ad(h={...de,...h}),function(e,t){if(!ie.isUint8Array(e))throw Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(e),function(e,t){if(!ie.isString(e))throw Error("Parameter ["+(t||"data")+"] must be of type String")}(t,"algorithm"),id(a),i=sd(i),n=sd(n),o=sd(o),u=sd(u),d.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const f=Object.keys(d);if(f.length>0)throw Error("Unknown option: "+f.join(", "));if(!(i&&0!==i.length||n&&0!==n.length))throw Error("No encryption keys or passwords provided.");try{return ud(await Ih.encryptSessionKey(e,t,r,i,n,s,o,c,u,h),a,h)}catch(e){throw ie.wrapError("Error encrypting session key",e)}}async function ed({message:e,decryptionKeys:t,passwords:r,date:i=new Date,config:n,...a}){if(ad(n={...de,...n}),td(e),t=sd(t),r=sd(r),a.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const s=Object.keys(a);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await e.decryptSessionKeys(t,r,i,n)}catch(e){throw ie.wrapError("Error decrypting session keys",e)}}function td(e){if(!(e instanceof Ih))throw Error("Parameter [message] needs to be of type Message")}function rd(e){if(!(e instanceof Oh||e instanceof Ih))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function id(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const nd=Object.keys(de).length;function ad(e){const t=Object.keys(e);if(t.length!==nd)for(const e of t)if(void 0===de[e])throw Error("Unknown config property: "+e)}function sd(e){return e&&!ie.isArray(e)&&(e=[e]),e}async function od(e,t,r="utf8"){const i=ie.isStream(e);return"array"===i?Z(e):"node"===t?(e=A(e),"binary"!==r&&e.setEncoding(r),e):"web"===t&&"ponyfill"===i?M(e):e}function cd(e,t){e.data=j(t.packets.stream,(async(t,r)=>{await F(e.data,r,{preventClose:!0});const i=q(r);try{await Z(t,(e=>e)),await i.close()}catch(e){await i.abort(e)}}))}function ud(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}const hd="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function dd(){}const fd="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function ld(e){return"object"==typeof e&&null!==e||"function"==typeof e}const pd=dd,yd=Promise,bd=Promise.prototype.then,md=Promise.resolve.bind(yd),gd=Promise.reject.bind(yd);function wd(e){return new yd(e)}function vd(e){return md(e)}function _d(e){return gd(e)}function kd(e,t,r){return bd.call(e,t,r)}function Ad(e,t,r){kd(kd(e,t,r),void 0,pd)}function Sd(e,t){Ad(e,t)}function Ed(e,t){Ad(e,void 0,t)}function Pd(e,t,r){return kd(e,t,r)}function xd(e){kd(e,void 0,pd)}const Md=(()=>{const e=fd&&fd.queueMicrotask;if("function"==typeof e)return e;const t=vd(void 0);return e=>kd(t,e)})();function Kd(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function Cd(e,t,r){try{return vd(Kd(e,t,r))}catch(e){return _d(e)}}class Dd{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let i=r+1;const n=e._elements,a=n[r];return 16384===i&&(t=e._next,i=0),--this._size,this._cursor=i,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,i=r._elements;for(;!(t===i.length&&void 0===r._next||t===i.length&&(r=r._next,i=r._elements,t=0,0===i.length));)e(i[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function Ud(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?Td(e):"closed"===t._state?function(e){Td(e),Fd(e)}(e):zd(e,t._storedError)}function Rd(e,t){return mp(e._ownerReadableStream,t)}function Id(e){"readable"===e._ownerReadableStream._state?qd(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){zd(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function Bd(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function Td(e){e._closedPromise=wd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function zd(e,t){Td(e),qd(e,t)}function qd(e,t){void 0!==e._closedPromise_reject&&(xd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function Fd(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const Od=hd("[[AbortSteps]]"),Ld=hd("[[ErrorSteps]]"),Nd=hd("[[CancelSteps]]"),jd=hd("[[PullSteps]]"),Hd=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Wd=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Gd(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(t+" is not an object.");var r}function Vd(e,t){if("function"!=typeof e)throw new TypeError(t+" is not a function.")}function $d(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(t+" is not an object.")}function Zd(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function Xd(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Yd(e){return Number(e)}function Qd(e){return 0===e?0:e}function Jd(e,t){const r=Number.MAX_SAFE_INTEGER;let i=Number(e);if(i=Qd(i),!Hd(i))throw new TypeError(t+" is not a finite number");if(i=function(e){return Qd(Wd(e))}(i),i<0||i>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return Hd(i)&&0!==i?i:0}function ef(e,t){if(!yp(e))throw new TypeError(t+" is not a ReadableStream.")}function tf(e){return new of(e)}function rf(e,t){e._reader._readRequests.push(t)}function nf(e,t,r){const i=e._reader._readRequests.shift();r?i._closeSteps():i._chunkSteps(t)}function af(e){return e._reader._readRequests.length}function sf(e){const t=e._reader;return void 0!==t&&!!cf(t)}class of{constructor(e){if(Zd(e,1,"ReadableStreamDefaultReader"),ef(e,"First parameter"),bp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");Ud(this,e),this._readRequests=new Dd}get closed(){return cf(this)?this._closedPromise:_d(hf("closed"))}cancel(e=undefined){return cf(this)?void 0===this._ownerReadableStream?_d(Bd("cancel")):Rd(this,e):_d(hf("cancel"))}read(){if(!cf(this))return _d(hf("read"));if(void 0===this._ownerReadableStream)return _d(Bd("read from"));let e,t;const r=wd(((r,i)=>{e=r,t=i}));return uf(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!cf(this))throw hf("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");Id(this)}}}function cf(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function uf(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[jd](t)}function hf(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let df;Object.defineProperties(of.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(of.prototype,hd.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof hd.asyncIterator&&(df={[hd.asyncIterator](){return this}},Object.defineProperty(df,hd.asyncIterator,{enumerable:!1}));class ff{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?Pd(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?Pd(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return _d(Bd("iterate"));let t,r;const i=wd(((e,i)=>{t=e,r=i}));return uf(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,Md((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Id(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,Id(e),r(t)}}),i}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return _d(Bd("finish iterating"));if(!this._preventCancel){const r=Rd(t,e);return Id(t),Pd(r,(()=>({value:e,done:!0})))}return Id(t),vd({value:e,done:!0})}}const lf={next(){return pf(this)?this._asyncIteratorImpl.next():_d(yf("next"))},return(e){return pf(this)?this._asyncIteratorImpl.return(e):_d(yf("return"))}};function pf(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl")}function yf(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==df&&Object.setPrototypeOf(lf,df);const bf=Number.isNaN||function(e){return e!=e};function mf(e){return!!function(e){if("number"!=typeof e)return!1;if(bf(e))return!1;if(e<0)return!1;return!0}(e)&&e!==1/0}function gf(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function wf(e,t,r){if(!mf(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function vf(e){e._queue=new Dd,e._queueTotalSize=0}function _f(e){return e.slice()}class kf{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ef(this))throw Lf("view");return this._view}respond(e){if(!Ef(this))throw Lf("respond");if(Zd(e,1,"respond"),e=Jd(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(t=Number(t),!mf(t))throw new RangeError("bytesWritten must be a finite");Bf(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Ef(this))throw Lf("respondWithNewView");if(Zd(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");!function(e,t){const r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,Bf(e,t.byteLength)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(kf.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(kf.prototype,hd.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Af{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Sf(this))throw Nf("byobRequest");if(null===this._byobRequest&&this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(kf.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest}get desiredSize(){if(!Sf(this))throw Nf("desiredSize");return Ff(this)}close(){if(!Sf(this))throw Nf("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw qf(e,t),t}}zf(e),gp(t)}(this)}enqueue(e){if(!Sf(this))throw Nf("enqueue");if(Zd(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const i=t.buffer,n=t.byteOffset,a=t.byteLength,s=i;if(sf(r))if(0===af(r))Kf(e,s,n,a);else{nf(r,new Uint8Array(s,n,a),!1)}else Wf(r)?(Kf(e,s,n,a),If(e)):Kf(e,s,n,a);Pf(e)}(this,e)}error(e=undefined){if(!Sf(this))throw Nf("error");qf(this,e)}[Nd](e){if(this._pendingPullIntos.length>0){this._pendingPullIntos.peek().bytesFilled=0}vf(this);const t=this._cancelAlgorithm(e);return zf(this),t}[jd](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,Uf(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const i={buffer:t,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}rf(t,e),Pf(this)}}function Sf(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function Ef(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function Pf(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(sf(t)&&af(t)>0)return!0;if(Wf(t)&&Hf(t)>0)return!0;const r=Ff(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;Ad(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Pf(e))}),(t=>{qf(e,t)}))}function xf(e,t){let r=!1;"closed"===e._state&&(r=!0);const i=Mf(t);"default"===t.readerType?nf(e,i,r):function(e,t,r){const i=e._reader,n=i._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,i,r)}function Mf(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Kf(e,t,r,i){e._queue.push({buffer:t,byteOffset:r,byteLength:i}),e._queueTotalSize+=i}function Cf(e,t){const r=t.elementSize,i=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,s=a-a%r;let o=n,c=!1;s>i&&(o=s-t.bytesFilled,c=!0);const u=e._queue;for(;o>0;){const r=u.peek(),i=Math.min(o,r.byteLength),n=t.byteOffset+t.bytesFilled;h=t.buffer,d=n,f=r.buffer,l=r.byteOffset,p=i,new Uint8Array(h).set(new Uint8Array(f,l,p),d),r.byteLength===i?u.shift():(r.byteOffset+=i,r.byteLength-=i),e._queueTotalSize-=i,Df(e,i,t),o-=i}var h,d,f,l,p;return c}function Df(e,t,r){Rf(e),r.bytesFilled+=t}function Uf(e){0===e._queueTotalSize&&e._closeRequested?(zf(e),gp(e._controlledReadableByteStream)):Pf(e)}function Rf(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function If(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Cf(e,t)&&(Tf(e),xf(e._controlledReadableByteStream,t))}}function Bf(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;const r=e._controlledReadableByteStream;if(Wf(r))for(;Hf(r)>0;)xf(r,Tf(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(Df(e,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=r.buffer.slice(t-i,t);Kf(e,n,0,n.byteLength)}r.buffer=r.buffer,r.bytesFilled-=i,xf(e._controlledReadableByteStream,r),If(e)}(e,t,r);Pf(e)}function Tf(e){const t=e._pendingPullIntos.shift();return Rf(e),t}function zf(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function qf(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(!function(e){Rf(e),e._pendingPullIntos=new Dd}(e),vf(e),zf(e),wp(r,t))}function Ff(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Of(e,t,r){const i=Object.create(Af.prototype);let n=()=>{},a=()=>vd(void 0),s=()=>vd(void 0);void 0!==t.start&&(n=()=>t.start(i)),void 0!==t.pull&&(a=()=>t.pull(i)),void 0!==t.cancel&&(s=e=>t.cancel(e));const o=t.autoAllocateChunkSize;if(0===o)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,i,n,a,s){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,vf(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,t._autoAllocateChunkSize=s,t._pendingPullIntos=new Dd,e._readableStreamController=t,Ad(vd(r()),(()=>{t._started=!0,Pf(t)}),(e=>{qf(t,e)}))}(e,i,n,a,s,r,o)}function Lf(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Nf(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function jf(e,t){e._reader._readIntoRequests.push(t)}function Hf(e){return e._reader._readIntoRequests.length}function Wf(e){const t=e._reader;return void 0!==t&&!!Vf(t)}Object.defineProperties(Af.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(Af.prototype,hd.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class Gf{constructor(e){if(Zd(e,1,"ReadableStreamBYOBReader"),ef(e,"First parameter"),bp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Sf(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");Ud(this,e),this._readIntoRequests=new Dd}get closed(){return Vf(this)?this._closedPromise:_d($f("closed"))}cancel(e=undefined){return Vf(this)?void 0===this._ownerReadableStream?_d(Bd("cancel")):Rd(this,e):_d($f("cancel"))}read(e){if(!Vf(this))return _d($f("read"));if(!ArrayBuffer.isView(e))return _d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return _d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return _d(new TypeError("view's buffer must have non-zero byteLength"));if(void 0===this._ownerReadableStream)return _d(Bd("read from"));let t,r;const i=wd(((e,i)=>{t=e,r=i}));return function(e,t,r){const i=e._ownerReadableStream;i._disturbed=!0,"errored"===i._state?r._errorSteps(i._storedError):function(e,t,r){const i=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,s={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(s),void jf(i,r);if("closed"!==i._state){if(e._queueTotalSize>0){if(Cf(e,s)){const t=Mf(s);return Uf(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return qf(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(s),jf(i,r),Pf(e)}else{const e=new a(s.buffer,s.byteOffset,0);r._closeSteps(e)}}(i._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),i}releaseLock(){if(!Vf(this))throw $f("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");Id(this)}}}function Vf(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function $f(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Zf(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(bf(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Xf(e){const{size:t}=e;return t||(()=>1)}function Yf(e,t){Gd(e,t);const r=null==e?void 0:e.highWaterMark,i=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Yd(r),size:void 0===i?void 0:Qf(i,t+" has member 'size' that")}}function Qf(e,t){return Vd(e,t),t=>Yd(e(t))}function Jf(e,t,r){return Vd(e,r),r=>Cd(e,t,[r])}function el(e,t,r){return Vd(e,r),()=>Cd(e,t,[])}function tl(e,t,r){return Vd(e,r),r=>Kd(e,t,[r])}function rl(e,t,r){return Vd(e,r),(r,i)=>Cd(e,t,[r,i])}function il(e,t){if(!ol(e))throw new TypeError(t+" is not a WritableStream.")}Object.defineProperties(Gf.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(Gf.prototype,hd.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});class nl{constructor(e={},t={}){void 0===e?e=null:$d(e,"First parameter");const r=Yf(t,"Second parameter"),i=function(e,t){Gd(e,t);const r=null==e?void 0:e.abort,i=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,s=null==e?void 0:e.write;return{abort:void 0===r?void 0:Jf(r,e,t+" has member 'abort' that"),close:void 0===i?void 0:el(i,e,t+" has member 'close' that"),start:void 0===n?void 0:tl(n,e,t+" has member 'start' that"),write:void 0===s?void 0:rl(s,e,t+" has member 'write' that"),type:a}}(e,"First parameter");sl(this);if(void 0!==i.type)throw new RangeError("Invalid type is specified");const n=Xf(r);!function(e,t,r,i){const n=Object.create(El.prototype);let a=()=>{},s=()=>vd(void 0),o=()=>vd(void 0),c=()=>vd(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(s=e=>t.write(e,n));void 0!==t.close&&(o=()=>t.close());void 0!==t.abort&&(c=e=>t.abort(e));Pl(e,n,a,s,o,c,r,i)}(this,i,Zf(r,1),n)}get locked(){if(!ol(this))throw Rl("locked");return cl(this)}abort(e=undefined){return ol(this)?cl(this)?_d(new TypeError("Cannot abort a stream that already has a writer")):ul(this,e):_d(Rl("abort"))}close(){return ol(this)?cl(this)?_d(new TypeError("Cannot close a stream that already has a writer")):pl(this)?_d(new TypeError("Cannot close an already-closing stream")):hl(this):_d(Rl("close"))}getWriter(){if(!ol(this))throw Rl("getWriter");return al(this)}}function al(e){return new ml(e)}function sl(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new Dd,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function ol(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function cl(e){return void 0!==e._writer}function ul(e,t){const r=e._state;if("closed"===r||"errored"===r)return vd(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let i=!1;"erroring"===r&&(i=!0,t=void 0);const n=wd(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:i}}));return e._pendingAbortRequest._promise=n,i||fl(e,t),n}function hl(e){const t=e._state;if("closed"===t||"errored"===t)return _d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=wd(((t,r)=>{const i={_resolve:t,_reject:r};e._closeRequest=i})),i=e._writer;var n;return void 0!==i&&e._backpressure&&"writable"===t&&Hl(i),wf(n=e._writableStreamController,Sl,0),Kl(n),r}function dl(e,t){"writable"!==e._state?ll(e):fl(e,t)}function fl(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const i=e._writer;void 0!==i&&_l(i,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&ll(e)}function ll(e){e._state="errored",e._writableStreamController[Ld]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new Dd,void 0===e._pendingAbortRequest)return void yl(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void yl(e);Ad(e._writableStreamController[Od](r._reason),(()=>{r._resolve(),yl(e)}),(t=>{r._reject(t),yl(e)}))}function pl(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function yl(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&ql(t,e._storedError)}function bl(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Ol(e)}(r):Hl(r)),e._backpressure=t}Object.defineProperties(nl.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(nl.prototype,hd.toStringTag,{value:"WritableStream",configurable:!0});class ml{constructor(e){if(Zd(e,1,"WritableStreamDefaultWriter"),il(e,"First parameter"),cl(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!pl(e)&&e._backpressure?Ol(this):Nl(this),Tl(this);else if("erroring"===t)Ll(this,e._storedError),Tl(this);else if("closed"===t)Nl(this),Tl(r=this),Fl(r);else{const t=e._storedError;Ll(this,t),zl(this,t)}var r}get closed(){return gl(this)?this._closedPromise:_d(Il("closed"))}get desiredSize(){if(!gl(this))throw Il("desiredSize");if(void 0===this._ownerWritableStream)throw Bl("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Ml(t._writableStreamController)}(this)}get ready(){return gl(this)?this._readyPromise:_d(Il("ready"))}abort(e=undefined){return gl(this)?void 0===this._ownerWritableStream?_d(Bl("abort")):function(e,t){const r=e._ownerWritableStream;return ul(r,t)}(this,e):_d(Il("abort"))}close(){if(!gl(this))return _d(Il("close"));const e=this._ownerWritableStream;return void 0===e?_d(Bl("close")):pl(e)?_d(new TypeError("Cannot close an already-closing stream")):wl(this)}releaseLock(){if(!gl(this))throw Il("releaseLock");void 0!==this._ownerWritableStream&&kl(this)}write(e=undefined){return gl(this)?void 0===this._ownerWritableStream?_d(Bl("write to")):Al(this,e):_d(Il("write"))}}function gl(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function wl(e){return hl(e._ownerWritableStream)}function vl(e,t){"pending"===e._closedPromiseState?ql(e,t):function(e,t){zl(e,t)}(e,t)}function _l(e,t){"pending"===e._readyPromiseState?jl(e,t):function(e,t){Ll(e,t)}(e,t)}function kl(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");_l(e,r),vl(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Al(e,t){const r=e._ownerWritableStream,i=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Cl(e,t),1}}(i,t);if(r!==e._ownerWritableStream)return _d(Bl("write to"));const a=r._state;if("errored"===a)return _d(r._storedError);if(pl(r)||"closed"===a)return _d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return _d(r._storedError);const s=function(e){return wd(((t,r)=>{const i={_resolve:t,_reject:r};e._writeRequests.push(i)}))}(r);return function(e,t,r){try{wf(e,t,r)}catch(t){return void Cl(e,t)}const i=e._controlledWritableStream;if(!pl(i)&&"writable"===i._state){bl(i,Dl(e))}Kl(e)}(i,t,n),s}Object.defineProperties(ml.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(ml.prototype,hd.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Sl={};class El{constructor(){throw new TypeError("Illegal constructor")}error(e=undefined){if(!function(e){if(!ld(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream"))return!1;return!0}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&Ul(this,e)}[Od](e){const t=this._abortAlgorithm(e);return xl(this),t}[Ld](){vf(this)}}function Pl(e,t,r,i,n,a,s,o){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,vf(t),t._started=!1,t._strategySizeAlgorithm=o,t._strategyHWM=s,t._writeAlgorithm=i,t._closeAlgorithm=n,t._abortAlgorithm=a;const c=Dl(t);bl(e,c);Ad(vd(r()),(()=>{t._started=!0,Kl(t)}),(r=>{t._started=!0,dl(e,r)}))}function xl(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Ml(e){return e._strategyHWM-e._queueTotalSize}function Kl(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void ll(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Sl?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),gf(e);const r=e._closeAlgorithm();xl(e),Ad(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Fl(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),dl(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const i=e._writeAlgorithm(t);Ad(i,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(gf(e),!pl(r)&&"writable"===t){const t=Dl(e);bl(r,t)}Kl(e)}),(t=>{"writable"===r._state&&xl(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,dl(e,t)}(r,t)}))}(e,r)}function Cl(e,t){"writable"===e._controlledWritableStream._state&&Ul(e,t)}function Dl(e){return Ml(e)<=0}function Ul(e,t){const r=e._controlledWritableStream;xl(e),fl(r,t)}function Rl(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Il(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Bl(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Tl(e){e._closedPromise=wd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function zl(e,t){Tl(e),ql(e,t)}function ql(e,t){void 0!==e._closedPromise_reject&&(xd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Fl(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Ol(e){e._readyPromise=wd(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Ll(e,t){Ol(e),jl(e,t)}function Nl(e){Ol(e),Hl(e)}function jl(e,t){void 0!==e._readyPromise_reject&&(xd(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Hl(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(El.prototype,{error:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(El.prototype,hd.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Wl="undefined"!=typeof DOMException?DOMException:void 0;const Gl=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Wl)?Wl:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return Object.defineProperty(e.prototype=Object.create(Error.prototype),"constructor",{value:e,writable:!0,configurable:!0}),e}();function Vl(e,t,r,i,n,a){const s=tf(e),o=al(t);e._disturbed=!0;let c=!1,u=vd(void 0);return wd(((h,d)=>{let f;if(void 0!==a){if(f=()=>{const r=new Gl("Aborted","AbortError"),a=[];i||a.push((()=>"writable"===t._state?ul(t,r):vd(void 0))),n||a.push((()=>"readable"===e._state?mp(e,r):vd(void 0))),y((()=>Promise.all(a.map((e=>e())))),!0,r)},a.aborted)return void f();a.addEventListener("abort",f)}if(p(e,s._closedPromise,(e=>{i?b(!0,e):y((()=>ul(t,e)),!0,e)})),p(t,o._closedPromise,(t=>{n?b(!0,t):y((()=>mp(e,t)),!0,t)})),function(e,t,r){"closed"===e._state?r():Sd(t,r)}(e,s._closedPromise,(()=>{r?b():y((()=>function(e){const t=e._ownerWritableStream,r=t._state;return pl(t)||"closed"===r?vd(void 0):"errored"===r?_d(t._storedError):wl(e)}(o)))})),pl(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");n?b(!0,t):y((()=>mp(e,t)),!0,t)}function l(){const e=u;return kd(u,(()=>e!==u?l():void 0))}function p(e,t,r){"errored"===e._state?r(e._storedError):Ed(t,r)}function y(e,r,i){function n(){Ad(e(),(()=>m(r,i)),(e=>m(!0,e)))}c||(c=!0,"writable"!==t._state||pl(t)?n():Sd(l(),n))}function b(e,r){c||(c=!0,"writable"!==t._state||pl(t)?m(e,r):Sd(l(),(()=>m(e,r))))}function m(e,t){kl(o),Id(s),void 0!==a&&a.removeEventListener("abort",f),e?d(t):h(void 0)}xd(wd(((e,t)=>{!function r(i){i?e():kd(c?vd(!0):kd(o._readyPromise,(()=>wd(((e,t)=>{uf(s,{_chunkSteps:t=>{u=kd(Al(o,t),void 0,dd),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),r,t)}(!1)})))}))}class $l{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Zl(this))throw ap("desiredSize");return rp(this)}close(){if(!Zl(this))throw ap("close");if(!ip(this))throw new TypeError("The stream is not in a state that permits close");Jl(this)}enqueue(e=undefined){if(!Zl(this))throw ap("enqueue");if(!ip(this))throw new TypeError("The stream is not in a state that permits enqueue");return ep(this,e)}error(e=undefined){if(!Zl(this))throw ap("error");tp(this,e)}[Nd](e){vf(this);const t=this._cancelAlgorithm(e);return Ql(this),t}[jd](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=gf(this);this._closeRequested&&0===this._queue.length?(Ql(this),gp(t)):Xl(this),e._chunkSteps(r)}else rf(t,e),Xl(this)}}function Zl(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function Xl(e){if(!Yl(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;Ad(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Xl(e))}),(t=>{tp(e,t)}))}function Yl(e){const t=e._controlledReadableStream;if(!ip(e))return!1;if(!e._started)return!1;if(bp(t)&&af(t)>0)return!0;return rp(e)>0}function Ql(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Jl(e){if(!ip(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Ql(e),gp(t))}function ep(e,t){if(!ip(e))return;const r=e._controlledReadableStream;if(bp(r)&&af(r)>0)nf(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw tp(e,t),t}try{wf(e,t,r)}catch(t){throw tp(e,t),t}}Xl(e)}function tp(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(vf(e),Ql(e),wp(r,t))}function rp(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function ip(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function np(e,t,r,i,n,a,s){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,vf(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=s,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,e._readableStreamController=t;Ad(vd(r()),(()=>{t._started=!0,Xl(t)}),(e=>{tp(t,e)}))}function ap(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function sp(e,t,r){return Vd(e,r),r=>Cd(e,t,[r])}function op(e,t,r){return Vd(e,r),r=>Cd(e,t,[r])}function cp(e,t,r){return Vd(e,r),r=>Kd(e,t,[r])}function up(e,t){if("bytes"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function hp(e,t){if("byob"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function dp(e,t){Gd(e,t);const r=null==e?void 0:e.preventAbort,i=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(t+" is not an AbortSignal.")}(a,t+" has member 'signal' that"),{preventAbort:!!r,preventCancel:!!i,preventClose:!!n,signal:a}}Object.defineProperties($l.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty($l.prototype,hd.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class fp{constructor(e={},t={}){void 0===e?e=null:$d(e,"First parameter");const r=Yf(t,"Second parameter"),i=function(e,t){Gd(e,t);const r=e,i=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,s=null==r?void 0:r.start,o=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===i?void 0:Jd(i,t+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:sp(n,r,t+" has member 'cancel' that"),pull:void 0===a?void 0:op(a,r,t+" has member 'pull' that"),start:void 0===s?void 0:cp(s,r,t+" has member 'start' that"),type:void 0===o?void 0:up(o,t+" has member 'type' that")}}(e,"First parameter");if(pp(this),"bytes"===i.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Of(this,i,Zf(r,0))}else{const e=Xf(r);!function(e,t,r,i){const n=Object.create($l.prototype);let a=()=>{},s=()=>vd(void 0),o=()=>vd(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(s=()=>t.pull(n)),void 0!==t.cancel&&(o=e=>t.cancel(e)),np(e,n,a,s,o,r,i)}(this,i,Zf(r,1),e)}}get locked(){if(!yp(this))throw vp("locked");return bp(this)}cancel(e=undefined){return yp(this)?bp(this)?_d(new TypeError("Cannot cancel a stream that already has a reader")):mp(this,e):_d(vp("cancel"))}getReader(e=undefined){if(!yp(this))throw vp("getReader");const t=function(e,t){Gd(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:hp(r,t+" has member 'mode' that")}}(e,"First parameter");return void 0===t.mode?tf(this):function(e){return new Gf(e)}(this)}pipeThrough(e,t={}){if(!yp(this))throw vp("pipeThrough");Zd(e,1,"pipeThrough");const r=function(e,t){Gd(e,t);const r=null==e?void 0:e.readable;Xd(r,"readable","ReadableWritablePair"),ef(r,t+" has member 'readable' that");const i=null==e?void 0:e.writable;return Xd(i,"writable","ReadableWritablePair"),il(i,t+" has member 'writable' that"),{readable:r,writable:i}}(e,"First parameter"),i=dp(t,"Second parameter");if(bp(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(cl(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return xd(Vl(this,r.writable,i.preventClose,i.preventAbort,i.preventCancel,i.signal)),r.readable}pipeTo(e,t={}){if(!yp(this))return _d(vp("pipeTo"));if(void 0===e)return _d("Parameter 1 is required in 'pipeTo'.");if(!ol(e))return _d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=dp(t,"Second parameter")}catch(e){return _d(e)}return bp(this)?_d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):cl(e)?_d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Vl(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!yp(this))throw vp("tee");const e=function(e,t){const r=tf(e);let i,n,a,s,o,c=!1,u=!1,h=!1;const d=wd((e=>{o=e}));function f(){return c||(c=!0,uf(r,{_chunkSteps:e=>{Md((()=>{c=!1;const t=e,r=e;u||ep(a._readableStreamController,t),h||ep(s._readableStreamController,r)}))},_closeSteps:()=>{c=!1,u||Jl(a._readableStreamController),h||Jl(s._readableStreamController),u&&h||o(void 0)},_errorSteps:()=>{c=!1}})),vd(void 0)}function l(){}return a=lp(l,f,(function(t){if(u=!0,i=t,h){const t=_f([i,n]),r=mp(e,t);o(r)}return d})),s=lp(l,f,(function(t){if(h=!0,n=t,u){const t=_f([i,n]),r=mp(e,t);o(r)}return d})),Ed(r._closedPromise,(e=>{tp(a._readableStreamController,e),tp(s._readableStreamController,e),u&&h||o(void 0)})),[a,s]}(this);return _f(e)}values(e=undefined){if(!yp(this))throw vp("values");return function(e,t){const r=tf(e),i=new ff(r,t),n=Object.create(lf);return n._asyncIteratorImpl=i,n}(this,function(e,t){return Gd(e,t),{preventCancel:!!(null==e?void 0:e.preventCancel)}}(e,"First parameter").preventCancel)}}function lp(e,t,r,i=1,n=(()=>1)){const a=Object.create(fp.prototype);pp(a);return np(a,Object.create($l.prototype),e,t,r,i,n),a}function pp(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function yp(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function bp(e){return void 0!==e._reader}function mp(e,t){if(e._disturbed=!0,"closed"===e._state)return vd(void 0);if("errored"===e._state)return _d(e._storedError);gp(e);return Pd(e._readableStreamController[Nd](t),dd)}function gp(e){e._state="closed";const t=e._reader;void 0!==t&&(Fd(t),cf(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new Dd))}function wp(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(qd(r,t),cf(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new Dd):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new Dd))}function vp(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function _p(e,t){Gd(e,t);const r=null==e?void 0:e.highWaterMark;return Xd(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Yd(r)}}Object.defineProperties(fp.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(fp.prototype,hd.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof hd.asyncIterator&&Object.defineProperty(fp.prototype,hd.asyncIterator,{value:fp.prototype.values,writable:!0,configurable:!0});const kp=function(e){return e.byteLength};class Ap{constructor(e){Zd(e,1,"ByteLengthQueuingStrategy"),e=_p(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Ep(this))throw Sp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Ep(this))throw Sp("size");return kp}}function Sp(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Ep(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")}Object.defineProperties(Ap.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(Ap.prototype,hd.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Pp=function(){return 1};class xp{constructor(e){Zd(e,1,"CountQueuingStrategy"),e=_p(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Kp(this))throw Mp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Kp(this))throw Mp("size");return Pp}}function Mp(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Kp(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")}function Cp(e,t,r){return Vd(e,r),r=>Cd(e,t,[r])}function Dp(e,t,r){return Vd(e,r),r=>Kd(e,t,[r])}function Up(e,t,r){return Vd(e,r),(r,i)=>Cd(e,t,[r,i])}Object.defineProperties(xp.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(xp.prototype,hd.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class Rp{constructor(e={},t={},r={}){void 0===e&&(e=null);const i=Yf(t,"Second parameter"),n=Yf(r,"Third parameter"),a=function(e,t){Gd(e,t);const r=null==e?void 0:e.flush,i=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,s=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Cp(r,e,t+" has member 'flush' that"),readableType:i,start:void 0===n?void 0:Dp(n,e,t+" has member 'start' that"),transform:void 0===a?void 0:Up(a,e,t+" has member 'transform' that"),writableType:s}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const s=Zf(n,0),o=Xf(n),c=Zf(i,1),u=Xf(i);let h;!function(e,t,r,i,n,a){function s(){return t}function o(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return Pd(e._backpressureChangePromise,(()=>{const i=e._writable;if("erroring"===i._state)throw i._storedError;return Np(r,t)}))}return Np(r,t)}(e,t)}function c(t){return function(e,t){return Bp(e,t),vd(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,i=r._flushAlgorithm();return Op(r),Pd(i,(()=>{if("errored"===t._state)throw t._storedError;Jl(t._readableStreamController)}),(r=>{throw Bp(e,r),t._storedError}))}(e)}function h(){return function(e){return zp(e,!1),e._backpressureChangePromise}(e)}function d(t){return Tp(e,t),vd(void 0)}e._writable=function(e,t,r,i,n=1,a=(()=>1)){const s=Object.create(nl.prototype);return sl(s),Pl(s,Object.create(El.prototype),e,t,r,i,n,a),s}(s,o,u,c,r,i),e._readable=lp(s,h,d,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,zp(e,!0),e._transformStreamController=void 0}(this,wd((e=>{h=e})),c,u,s,o),function(e,t){const r=Object.create(qp.prototype);let i=e=>{try{return Lp(r,e),vd(void 0)}catch(e){return _d(e)}},n=()=>vd(void 0);void 0!==t.transform&&(i=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,i){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=i}(e,r,i,n)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!Ip(this))throw Hp("readable");return this._readable}get writable(){if(!Ip(this))throw Hp("writable");return this._writable}}function Ip(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function Bp(e,t){tp(e._readable._readableStreamController,t),Tp(e,t)}function Tp(e,t){Op(e._transformStreamController),Cl(e._writable._writableStreamController,t),e._backpressure&&zp(e,!1)}function zp(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=wd((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(Rp.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(Rp.prototype,hd.toStringTag,{value:"TransformStream",configurable:!0});class qp{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Fp(this))throw jp("desiredSize");return rp(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=undefined){if(!Fp(this))throw jp("enqueue");Lp(this,e)}error(e=undefined){if(!Fp(this))throw jp("error");var t;t=e,Bp(this._controlledTransformStream,t)}terminate(){if(!Fp(this))throw jp("terminate");!function(e){const t=e._controlledTransformStream,r=t._readable._readableStreamController;Jl(r);Tp(t,new TypeError("TransformStream terminated"))}(this)}}function Fp(e){return!!ld(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function Op(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Lp(e,t){const r=e._controlledTransformStream,i=r._readable._readableStreamController;if(!ip(i))throw new TypeError("Readable side is not in a state that permits enqueue");try{ep(i,t)}catch(e){throw Tp(r,e),r._readable._storedError}const n=function(e){return!Yl(e)}(i);n!==r._backpressure&&zp(r,!0)}function Np(e,t){return Pd(e._transformAlgorithm(t),void 0,(t=>{throw Bp(e._controlledTransformStream,t),t}))}function jp(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Hp(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(qp.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof hd.toStringTag&&Object.defineProperty(qp.prototype,hd.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Wp=/*#__PURE__*/Object.freeze({__proto__:null,ByteLengthQueuingStrategy:Ap,CountQueuingStrategy:xp,ReadableByteStreamController:Af,ReadableStream:fp,ReadableStreamBYOBReader:Gf,ReadableStreamBYOBRequest:kf,ReadableStreamDefaultController:$l,ReadableStreamDefaultReader:of,TransformStream:Rp,TransformStreamDefaultController:qp,WritableStream:nl,WritableStreamDefaultController:El,WritableStreamDefaultWriter:ml}),Gp=function(e,t){return Gp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Gp(e,t)}; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */function Vp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+t+" is not a constructor or null");function r(){this.constructor=e}Gp(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function $p(e){if(!e)throw new TypeError("Assertion failed")}function Zp(){}function Xp(e){return"object"==typeof e&&null!==e||"function"==typeof e}function Yp(e){if("function"!=typeof e)return!1;var t=!1;try{new e({start:function(){t=!0}})}catch(e){}return t}function Qp(e){return!!Xp(e)&&"function"==typeof e.getReader}function Jp(e){return!!Xp(e)&&"function"==typeof e.getWriter}function ey(e){return!!Xp(e)&&(!!Qp(e.readable)&&!!Jp(e.writable))}function ty(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}function ry(e,t){var r=(void 0===t?{}:t).type;return $p(Qp(e)),$p(!1===e.locked),"bytes"===(r=iy(r))?new oy(e):new ay(e)}function iy(e){var t=e+"";if("bytes"===t)return t;if(void 0===e)return e;throw new RangeError("Invalid type is specified")}var ny=function(){function e(e){this._underlyingReader=void 0,this._readerMode=void 0,this._readableStreamController=void 0,this._pendingRead=void 0,this._underlyingStream=e,this._attachDefaultReader()}return e.prototype.start=function(e){this._readableStreamController=e},e.prototype.cancel=function(e){return $p(void 0!==this._underlyingReader),this._underlyingReader.cancel(e)},e.prototype._attachDefaultReader=function(){if("default"!==this._readerMode){this._detachReader();var e=this._underlyingStream.getReader();this._readerMode="default",this._attachReader(e)}},e.prototype._attachReader=function(e){var t=this;$p(void 0===this._underlyingReader),this._underlyingReader=e;var r=this._underlyingReader.closed;r&&r.then((function(){return t._finishPendingRead()})).then((function(){e===t._underlyingReader&&t._readableStreamController.close()}),(function(r){e===t._underlyingReader&&t._readableStreamController.error(r)})).catch(Zp)},e.prototype._detachReader=function(){void 0!==this._underlyingReader&&(this._underlyingReader.releaseLock(),this._underlyingReader=void 0,this._readerMode=void 0)},e.prototype._pullWithDefaultReader=function(){var e=this;this._attachDefaultReader();var t=this._underlyingReader.read().then((function(t){var r=e._readableStreamController;t.done?e._tryClose():r.enqueue(t.value)}));return this._setPendingRead(t),t},e.prototype._tryClose=function(){try{this._readableStreamController.close()}catch(e){}},e.prototype._setPendingRead=function(e){var t,r=this,i=function(){r._pendingRead===t&&(r._pendingRead=void 0)};this._pendingRead=t=e.then(i,i)},e.prototype._finishPendingRead=function(){var e=this;if(this._pendingRead){var t=function(){return e._finishPendingRead()};return this._pendingRead.then(t,t)}},e}(),ay=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Vp(t,e),t.prototype.pull=function(){return this._pullWithDefaultReader()},t}(ny);function sy(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var oy=function(e){function t(t){var r=this,i=ty(t);return(r=e.call(this,t)||this)._supportsByob=i,r}return Vp(t,e),Object.defineProperty(t.prototype,"type",{get:function(){return"bytes"},enumerable:!1,configurable:!0}),t.prototype._attachByobReader=function(){if("byob"!==this._readerMode){$p(this._supportsByob),this._detachReader();var e=this._underlyingStream.getReader({mode:"byob"});this._readerMode="byob",this._attachReader(e)}},t.prototype.pull=function(){if(this._supportsByob){var e=this._readableStreamController.byobRequest;if(e)return this._pullWithByobRequest(e)}return this._pullWithDefaultReader()},t.prototype._pullWithByobRequest=function(e){var t=this;this._attachByobReader();var r=new Uint8Array(e.view.byteLength),i=this._underlyingReader.read(r).then((function(r){var i,n,a;t._readableStreamController,r.done?(t._tryClose(),e.respond(0)):(i=r.value,n=e.view,a=sy(i),sy(n).set(a,0),e.respond(r.value.byteLength))}));return this._setPendingRead(i),i},t}(ny);function cy(e){$p(Jp(e)),$p(!1===e.locked);var t=e.getWriter();return new uy(t)}var uy=function(){function e(e){var t=this;this._writableStreamController=void 0,this._pendingWrite=void 0,this._state="writable",this._storedError=void 0,this._underlyingWriter=e,this._errorPromise=new Promise((function(e,r){t._errorPromiseReject=r})),this._errorPromise.catch(Zp)}return e.prototype.start=function(e){var t=this;this._writableStreamController=e,this._underlyingWriter.closed.then((function(){t._state="closed"})).catch((function(e){return t._finishErroring(e)}))},e.prototype.write=function(e){var t=this,r=this._underlyingWriter;if(null===r.desiredSize)return r.ready;var i=r.write(e);i.catch((function(e){return t._finishErroring(e)})),r.ready.catch((function(e){return t._startErroring(e)}));var n=Promise.race([i,this._errorPromise]);return this._setPendingWrite(n),n},e.prototype.close=function(){var e=this;return void 0===this._pendingWrite?this._underlyingWriter.close():this._finishPendingWrite().then((function(){return e.close()}))},e.prototype.abort=function(e){if("errored"!==this._state)return this._underlyingWriter.abort(e)},e.prototype._setPendingWrite=function(e){var t,r=this,i=function(){r._pendingWrite===t&&(r._pendingWrite=void 0)};this._pendingWrite=t=e.then(i,i)},e.prototype._finishPendingWrite=function(){var e=this;if(void 0===this._pendingWrite)return Promise.resolve();var t=function(){return e._finishPendingWrite()};return this._pendingWrite.then(t,t)},e.prototype._startErroring=function(e){var t=this;if("writable"===this._state){this._state="erroring",this._storedError=e;var r=function(){return t._finishErroring(e)};void 0===this._pendingWrite?r():this._finishPendingWrite().then(r,r),this._writableStreamController.error(e)}},e.prototype._finishErroring=function(e){"writable"===this._state&&this._startErroring(e),"erroring"===this._state&&(this._state="errored",this._errorPromiseReject(this._storedError))},e}();function hy(e){$p(ey(e));var t=e.readable,r=e.writable;$p(!1===t.locked),$p(!1===r.locked);var i,n=t.getReader();try{i=r.getWriter()}catch(e){throw n.releaseLock(),e}return new dy(n,i)}var dy=function(){function e(e,t){var r=this;this._transformStreamController=void 0,this._onRead=function(e){if(!e.done)return r._transformStreamController.enqueue(e.value),r._reader.read().then(r._onRead)},this._onError=function(e){r._flushReject(e),r._transformStreamController.error(e),r._reader.cancel(e).catch(Zp),r._writer.abort(e).catch(Zp)},this._onTerminate=function(){r._flushResolve(),r._transformStreamController.terminate();var e=new TypeError("TransformStream terminated");r._writer.abort(e).catch(Zp)},this._reader=e,this._writer=t,this._flushPromise=new Promise((function(e,t){r._flushResolve=e,r._flushReject=t}))}return e.prototype.start=function(e){this._transformStreamController=e,this._reader.read().then(this._onRead).then(this._onTerminate,this._onError);var t=this._reader.closed;t&&t.then(this._onTerminate,this._onError)},e.prototype.transform=function(e){return this._writer.write(e)},e.prototype.flush=function(){var e=this;return this._writer.close().then((function(){return e._flushPromise}))},e}(),fy=/*#__PURE__*/Object.freeze({__proto__:null,createReadableStreamWrapper:function(e){$p(function(e){return!!Yp(e)&&!!Qp(new e)}(e));var t=function(e){try{return new e({type:"bytes"}),!0}catch(e){return!1}}(e);return function(r,i){var n=(void 0===i?{}:i).type;if("bytes"!==(n=iy(n))||t||(n=void 0),r.constructor===e&&("bytes"!==n||ty(r)))return r;if("bytes"===n){var a=ry(r,{type:n});return new e(a)}a=ry(r);return new e(a)}},createTransformStreamWrapper:function(e){return $p(function(e){return!!Yp(e)&&!!ey(new e)}(e)),function(t){if(t.constructor===e)return t;var r=hy(t);return new e(r)}},createWrappingReadableSource:ry,createWrappingTransformer:hy,createWrappingWritableSink:cy,createWritableStreamWrapper:function(e){return $p(function(e){return!!Yp(e)&&!!Jp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=cy(t);return new e(r)}}}),ly=ht((function(e){!function(e,r){function i(e,t){if(!e)throw Error(t||"Assertion failed")}function n(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function a(e,t,r){if(a.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var s;"object"==typeof e?e.exports=a:r.BN=a,a.BN=a,a.wordSize=26;try{s=t.Buffer}catch(e){}function o(e,t,r){for(var i=0,n=Math.min(e.length,r),a=t;a=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return i}function c(e,t,r,i){for(var n=0,a=Math.min(e.length,r),s=t;s=49?o-49+10:o>=17?o-17+10:o}return n}a.isBN=function(e){return e instanceof a||null!==e&&"object"==typeof e&&e.constructor.wordSize===a.wordSize&&Array.isArray(e.words)},a.max=function(e,t){return e.cmp(t)>0?e:t},a.min=function(e,t){return e.cmp(t)<0?e:t},a.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&n++,16===t?this._parseHex(e,n):this._parseBase(e,t,n),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},a.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(i(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},a.prototype._initArray=function(e,t,r){if(i("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var n=0;n=0;n-=3)s=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[a]|=s<>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);else if("le"===r)for(n=0,a=0;n>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);return this.strip()},a.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var r=0;r=t;r-=6)n=o(e,r,r+6),this.words[i]|=n<>>26-a&4194303,(a+=24)>=26&&(a-=26,i++);r+6!==t&&(n=o(e,t,r+6),this.words[i]|=n<>>26-a&4194303),this.strip()},a.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var a=e.length-r,s=a%i,o=Math.min(a,a-s)+r,u=0,h=r;h1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],a=0|t.words[0],s=n*a,o=67108863&s,c=s/67108864|0;r.words[0]=o;for(var u=1;u>>26,d=67108863&c,f=Math.min(u,t.length-1),l=Math.max(0,u-e.length+1);l<=f;l++){var p=u-l|0;h+=(s=(n=0|e.words[p])*(a=0|t.words[l])+d)/67108864|0,d=67108863&s}r.words[u]=0|d,c=0|h}return 0!==c?r.words[u]=0|c:r.length--,r.strip()}a.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var n=0,a=0,s=0;s>>24-n&16777215)||s!==this.length-1?u[6-c.length]+c+r:c+r,(n+=2)>=26&&(n-=26,s--)}for(0!==a&&(r=a.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var f=h[e],l=d[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var y=p.modn(l).toString(e);r=(p=p.idivn(l)).isZero()?y+r:u[f-y.length]+y+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}i(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(e,t){return i(void 0!==s),this.toArrayLike(s,e,t)},a.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},a.prototype.toArrayLike=function(e,t,r){var n=this.byteLength(),a=r||Math.max(1,n);i(n<=a,"byte array longer than desired length"),i(a>0,"Requested array length <= 0"),this.strip();var s,o,c="le"===t,u=new e(a),h=this.clone();if(c){for(o=0;!h.isZero();o++)s=h.andln(255),h.iushrn(8),u[o]=s;for(;o=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},a.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},a.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},a.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},a.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},a.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},a.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},a.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},a.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-r),this.strip()},a.prototype.notn=function(e){return this.clone().inotn(e)},a.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var r=e/26|0,n=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,a=0;a>>26;for(;0!==n&&a>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;ae.length?this.clone().iadd(e):e.clone().iadd(this)},a.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var a=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==a&&s>26,this.words[s]=67108863&t;if(0===a&&s>>13,l=0|s[1],p=8191&l,y=l>>>13,b=0|s[2],m=8191&b,g=b>>>13,w=0|s[3],v=8191&w,_=w>>>13,k=0|s[4],A=8191&k,S=k>>>13,E=0|s[5],P=8191&E,x=E>>>13,M=0|s[6],K=8191&M,C=M>>>13,D=0|s[7],U=8191&D,R=D>>>13,I=0|s[8],B=8191&I,T=I>>>13,z=0|s[9],q=8191&z,F=z>>>13,O=0|o[0],L=8191&O,N=O>>>13,j=0|o[1],H=8191&j,W=j>>>13,G=0|o[2],V=8191&G,$=G>>>13,Z=0|o[3],X=8191&Z,Y=Z>>>13,Q=0|o[4],J=8191&Q,ee=Q>>>13,te=0|o[5],re=8191&te,ie=te>>>13,ne=0|o[6],ae=8191&ne,se=ne>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,he=0|o[8],de=8191&he,fe=he>>>13,le=0|o[9],pe=8191&le,ye=le>>>13;r.negative=e.negative^t.negative,r.length=19;var be=(u+(i=Math.imul(d,L))|0)+((8191&(n=(n=Math.imul(d,N))+Math.imul(f,L)|0))<<13)|0;u=((a=Math.imul(f,N))+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(p,L),n=(n=Math.imul(p,N))+Math.imul(y,L)|0,a=Math.imul(y,N);var me=(u+(i=i+Math.imul(d,H)|0)|0)+((8191&(n=(n=n+Math.imul(d,W)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,W)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(m,L),n=(n=Math.imul(m,N))+Math.imul(g,L)|0,a=Math.imul(g,N),i=i+Math.imul(p,H)|0,n=(n=n+Math.imul(p,W)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,W)|0;var ge=(u+(i=i+Math.imul(d,V)|0)|0)+((8191&(n=(n=n+Math.imul(d,$)|0)+Math.imul(f,V)|0))<<13)|0;u=((a=a+Math.imul(f,$)|0)+(n>>>13)|0)+(ge>>>26)|0,ge&=67108863,i=Math.imul(v,L),n=(n=Math.imul(v,N))+Math.imul(_,L)|0,a=Math.imul(_,N),i=i+Math.imul(m,H)|0,n=(n=n+Math.imul(m,W)|0)+Math.imul(g,H)|0,a=a+Math.imul(g,W)|0,i=i+Math.imul(p,V)|0,n=(n=n+Math.imul(p,$)|0)+Math.imul(y,V)|0,a=a+Math.imul(y,$)|0;var we=(u+(i=i+Math.imul(d,X)|0)|0)+((8191&(n=(n=n+Math.imul(d,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(A,L),n=(n=Math.imul(A,N))+Math.imul(S,L)|0,a=Math.imul(S,N),i=i+Math.imul(v,H)|0,n=(n=n+Math.imul(v,W)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,W)|0,i=i+Math.imul(m,V)|0,n=(n=n+Math.imul(m,$)|0)+Math.imul(g,V)|0,a=a+Math.imul(g,$)|0,i=i+Math.imul(p,X)|0,n=(n=n+Math.imul(p,Y)|0)+Math.imul(y,X)|0,a=a+Math.imul(y,Y)|0;var ve=(u+(i=i+Math.imul(d,J)|0)|0)+((8191&(n=(n=n+Math.imul(d,ee)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,ee)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(P,L),n=(n=Math.imul(P,N))+Math.imul(x,L)|0,a=Math.imul(x,N),i=i+Math.imul(A,H)|0,n=(n=n+Math.imul(A,W)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,W)|0,i=i+Math.imul(v,V)|0,n=(n=n+Math.imul(v,$)|0)+Math.imul(_,V)|0,a=a+Math.imul(_,$)|0,i=i+Math.imul(m,X)|0,n=(n=n+Math.imul(m,Y)|0)+Math.imul(g,X)|0,a=a+Math.imul(g,Y)|0,i=i+Math.imul(p,J)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,ee)|0;var _e=(u+(i=i+Math.imul(d,re)|0)|0)+((8191&(n=(n=n+Math.imul(d,ie)|0)+Math.imul(f,re)|0))<<13)|0;u=((a=a+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(K,L),n=(n=Math.imul(K,N))+Math.imul(C,L)|0,a=Math.imul(C,N),i=i+Math.imul(P,H)|0,n=(n=n+Math.imul(P,W)|0)+Math.imul(x,H)|0,a=a+Math.imul(x,W)|0,i=i+Math.imul(A,V)|0,n=(n=n+Math.imul(A,$)|0)+Math.imul(S,V)|0,a=a+Math.imul(S,$)|0,i=i+Math.imul(v,X)|0,n=(n=n+Math.imul(v,Y)|0)+Math.imul(_,X)|0,a=a+Math.imul(_,Y)|0,i=i+Math.imul(m,J)|0,n=(n=n+Math.imul(m,ee)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(y,re)|0,a=a+Math.imul(y,ie)|0;var ke=(u+(i=i+Math.imul(d,ae)|0)|0)+((8191&(n=(n=n+Math.imul(d,se)|0)+Math.imul(f,ae)|0))<<13)|0;u=((a=a+Math.imul(f,se)|0)+(n>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(U,L),n=(n=Math.imul(U,N))+Math.imul(R,L)|0,a=Math.imul(R,N),i=i+Math.imul(K,H)|0,n=(n=n+Math.imul(K,W)|0)+Math.imul(C,H)|0,a=a+Math.imul(C,W)|0,i=i+Math.imul(P,V)|0,n=(n=n+Math.imul(P,$)|0)+Math.imul(x,V)|0,a=a+Math.imul(x,$)|0,i=i+Math.imul(A,X)|0,n=(n=n+Math.imul(A,Y)|0)+Math.imul(S,X)|0,a=a+Math.imul(S,Y)|0,i=i+Math.imul(v,J)|0,n=(n=n+Math.imul(v,ee)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,ee)|0,i=i+Math.imul(m,re)|0,n=(n=n+Math.imul(m,ie)|0)+Math.imul(g,re)|0,a=a+Math.imul(g,ie)|0,i=i+Math.imul(p,ae)|0,n=(n=n+Math.imul(p,se)|0)+Math.imul(y,ae)|0,a=a+Math.imul(y,se)|0;var Ae=(u+(i=i+Math.imul(d,ce)|0)|0)+((8191&(n=(n=n+Math.imul(d,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((a=a+Math.imul(f,ue)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(B,L),n=(n=Math.imul(B,N))+Math.imul(T,L)|0,a=Math.imul(T,N),i=i+Math.imul(U,H)|0,n=(n=n+Math.imul(U,W)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,W)|0,i=i+Math.imul(K,V)|0,n=(n=n+Math.imul(K,$)|0)+Math.imul(C,V)|0,a=a+Math.imul(C,$)|0,i=i+Math.imul(P,X)|0,n=(n=n+Math.imul(P,Y)|0)+Math.imul(x,X)|0,a=a+Math.imul(x,Y)|0,i=i+Math.imul(A,J)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,ee)|0,i=i+Math.imul(v,re)|0,n=(n=n+Math.imul(v,ie)|0)+Math.imul(_,re)|0,a=a+Math.imul(_,ie)|0,i=i+Math.imul(m,ae)|0,n=(n=n+Math.imul(m,se)|0)+Math.imul(g,ae)|0,a=a+Math.imul(g,se)|0,i=i+Math.imul(p,ce)|0,n=(n=n+Math.imul(p,ue)|0)+Math.imul(y,ce)|0,a=a+Math.imul(y,ue)|0;var Se=(u+(i=i+Math.imul(d,de)|0)|0)+((8191&(n=(n=n+Math.imul(d,fe)|0)+Math.imul(f,de)|0))<<13)|0;u=((a=a+Math.imul(f,fe)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(q,L),n=(n=Math.imul(q,N))+Math.imul(F,L)|0,a=Math.imul(F,N),i=i+Math.imul(B,H)|0,n=(n=n+Math.imul(B,W)|0)+Math.imul(T,H)|0,a=a+Math.imul(T,W)|0,i=i+Math.imul(U,V)|0,n=(n=n+Math.imul(U,$)|0)+Math.imul(R,V)|0,a=a+Math.imul(R,$)|0,i=i+Math.imul(K,X)|0,n=(n=n+Math.imul(K,Y)|0)+Math.imul(C,X)|0,a=a+Math.imul(C,Y)|0,i=i+Math.imul(P,J)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(x,J)|0,a=a+Math.imul(x,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(S,re)|0,a=a+Math.imul(S,ie)|0,i=i+Math.imul(v,ae)|0,n=(n=n+Math.imul(v,se)|0)+Math.imul(_,ae)|0,a=a+Math.imul(_,se)|0,i=i+Math.imul(m,ce)|0,n=(n=n+Math.imul(m,ue)|0)+Math.imul(g,ce)|0,a=a+Math.imul(g,ue)|0,i=i+Math.imul(p,de)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(y,de)|0,a=a+Math.imul(y,fe)|0;var Ee=(u+(i=i+Math.imul(d,pe)|0)|0)+((8191&(n=(n=n+Math.imul(d,ye)|0)+Math.imul(f,pe)|0))<<13)|0;u=((a=a+Math.imul(f,ye)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(q,H),n=(n=Math.imul(q,W))+Math.imul(F,H)|0,a=Math.imul(F,W),i=i+Math.imul(B,V)|0,n=(n=n+Math.imul(B,$)|0)+Math.imul(T,V)|0,a=a+Math.imul(T,$)|0,i=i+Math.imul(U,X)|0,n=(n=n+Math.imul(U,Y)|0)+Math.imul(R,X)|0,a=a+Math.imul(R,Y)|0,i=i+Math.imul(K,J)|0,n=(n=n+Math.imul(K,ee)|0)+Math.imul(C,J)|0,a=a+Math.imul(C,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(x,re)|0,a=a+Math.imul(x,ie)|0,i=i+Math.imul(A,ae)|0,n=(n=n+Math.imul(A,se)|0)+Math.imul(S,ae)|0,a=a+Math.imul(S,se)|0,i=i+Math.imul(v,ce)|0,n=(n=n+Math.imul(v,ue)|0)+Math.imul(_,ce)|0,a=a+Math.imul(_,ue)|0,i=i+Math.imul(m,de)|0,n=(n=n+Math.imul(m,fe)|0)+Math.imul(g,de)|0,a=a+Math.imul(g,fe)|0;var Pe=(u+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ye)|0)+Math.imul(y,pe)|0))<<13)|0;u=((a=a+Math.imul(y,ye)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,V),n=(n=Math.imul(q,$))+Math.imul(F,V)|0,a=Math.imul(F,$),i=i+Math.imul(B,X)|0,n=(n=n+Math.imul(B,Y)|0)+Math.imul(T,X)|0,a=a+Math.imul(T,Y)|0,i=i+Math.imul(U,J)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,ee)|0,i=i+Math.imul(K,re)|0,n=(n=n+Math.imul(K,ie)|0)+Math.imul(C,re)|0,a=a+Math.imul(C,ie)|0,i=i+Math.imul(P,ae)|0,n=(n=n+Math.imul(P,se)|0)+Math.imul(x,ae)|0,a=a+Math.imul(x,se)|0,i=i+Math.imul(A,ce)|0,n=(n=n+Math.imul(A,ue)|0)+Math.imul(S,ce)|0,a=a+Math.imul(S,ue)|0,i=i+Math.imul(v,de)|0,n=(n=n+Math.imul(v,fe)|0)+Math.imul(_,de)|0,a=a+Math.imul(_,fe)|0;var xe=(u+(i=i+Math.imul(m,pe)|0)|0)+((8191&(n=(n=n+Math.imul(m,ye)|0)+Math.imul(g,pe)|0))<<13)|0;u=((a=a+Math.imul(g,ye)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,X),n=(n=Math.imul(q,Y))+Math.imul(F,X)|0,a=Math.imul(F,Y),i=i+Math.imul(B,J)|0,n=(n=n+Math.imul(B,ee)|0)+Math.imul(T,J)|0,a=a+Math.imul(T,ee)|0,i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(R,re)|0,a=a+Math.imul(R,ie)|0,i=i+Math.imul(K,ae)|0,n=(n=n+Math.imul(K,se)|0)+Math.imul(C,ae)|0,a=a+Math.imul(C,se)|0,i=i+Math.imul(P,ce)|0,n=(n=n+Math.imul(P,ue)|0)+Math.imul(x,ce)|0,a=a+Math.imul(x,ue)|0,i=i+Math.imul(A,de)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(S,de)|0,a=a+Math.imul(S,fe)|0;var Me=(u+(i=i+Math.imul(v,pe)|0)|0)+((8191&(n=(n=n+Math.imul(v,ye)|0)+Math.imul(_,pe)|0))<<13)|0;u=((a=a+Math.imul(_,ye)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,J),n=(n=Math.imul(q,ee))+Math.imul(F,J)|0,a=Math.imul(F,ee),i=i+Math.imul(B,re)|0,n=(n=n+Math.imul(B,ie)|0)+Math.imul(T,re)|0,a=a+Math.imul(T,ie)|0,i=i+Math.imul(U,ae)|0,n=(n=n+Math.imul(U,se)|0)+Math.imul(R,ae)|0,a=a+Math.imul(R,se)|0,i=i+Math.imul(K,ce)|0,n=(n=n+Math.imul(K,ue)|0)+Math.imul(C,ce)|0,a=a+Math.imul(C,ue)|0,i=i+Math.imul(P,de)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(x,de)|0,a=a+Math.imul(x,fe)|0;var Ke=(u+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ye)|0)+Math.imul(S,pe)|0))<<13)|0;u=((a=a+Math.imul(S,ye)|0)+(n>>>13)|0)+(Ke>>>26)|0,Ke&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(F,re)|0,a=Math.imul(F,ie),i=i+Math.imul(B,ae)|0,n=(n=n+Math.imul(B,se)|0)+Math.imul(T,ae)|0,a=a+Math.imul(T,se)|0,i=i+Math.imul(U,ce)|0,n=(n=n+Math.imul(U,ue)|0)+Math.imul(R,ce)|0,a=a+Math.imul(R,ue)|0,i=i+Math.imul(K,de)|0,n=(n=n+Math.imul(K,fe)|0)+Math.imul(C,de)|0,a=a+Math.imul(C,fe)|0;var Ce=(u+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ye)|0)+Math.imul(x,pe)|0))<<13)|0;u=((a=a+Math.imul(x,ye)|0)+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(q,ae),n=(n=Math.imul(q,se))+Math.imul(F,ae)|0,a=Math.imul(F,se),i=i+Math.imul(B,ce)|0,n=(n=n+Math.imul(B,ue)|0)+Math.imul(T,ce)|0,a=a+Math.imul(T,ue)|0,i=i+Math.imul(U,de)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(R,de)|0,a=a+Math.imul(R,fe)|0;var De=(u+(i=i+Math.imul(K,pe)|0)|0)+((8191&(n=(n=n+Math.imul(K,ye)|0)+Math.imul(C,pe)|0))<<13)|0;u=((a=a+Math.imul(C,ye)|0)+(n>>>13)|0)+(De>>>26)|0,De&=67108863,i=Math.imul(q,ce),n=(n=Math.imul(q,ue))+Math.imul(F,ce)|0,a=Math.imul(F,ue),i=i+Math.imul(B,de)|0,n=(n=n+Math.imul(B,fe)|0)+Math.imul(T,de)|0,a=a+Math.imul(T,fe)|0;var Ue=(u+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ye)|0)+Math.imul(R,pe)|0))<<13)|0;u=((a=a+Math.imul(R,ye)|0)+(n>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,i=Math.imul(q,de),n=(n=Math.imul(q,fe))+Math.imul(F,de)|0,a=Math.imul(F,fe);var Re=(u+(i=i+Math.imul(B,pe)|0)|0)+((8191&(n=(n=n+Math.imul(B,ye)|0)+Math.imul(T,pe)|0))<<13)|0;u=((a=a+Math.imul(T,ye)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Ie=(u+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ye))+Math.imul(F,pe)|0))<<13)|0;return u=((a=Math.imul(F,ye))+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,c[0]=be,c[1]=me,c[2]=ge,c[3]=we,c[4]=ve,c[5]=_e,c[6]=ke,c[7]=Ae,c[8]=Se,c[9]=Ee,c[10]=Pe,c[11]=xe,c[12]=Me,c[13]=Ke,c[14]=Ce,c[15]=De,c[16]=Ue,c[17]=Re,c[18]=Ie,0!==u&&(c[19]=u,r.length++),r};function p(e,t,r){return(new y).mulp(e,t,r)}function y(e,t){this.x=e,this.y=t}Math.imul||(l=f),a.prototype.mulTo=function(e,t){var r,i=this.length+e.length;return r=10===this.length&&10===e.length?l(this,e,t):i<63?f(this,e,t):i<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,a=0;a>>26)|0)>>>26,s&=67108863}r.words[a]=o,i=s,s=n}return 0!==i?r.words[a]=i:r.length--,r.strip()}(this,e,t):p(this,e,t),r},y.prototype.makeRBT=function(e){for(var t=Array(e),r=a.prototype._countBits(e)-1,i=0;i>=1;return i},y.prototype.permute=function(e,t,r,i,n,a){for(var s=0;s>>=1)n++;return 1<>>=13,r[2*s+1]=8191&a,a>>>=13;for(s=2*t;s>=26,t+=n/67108864|0,t+=a>>>26,this.words[r]=67108863&a}return 0!==t&&(this.words[r]=t,this.length++),this},a.prototype.muln=function(e){return this.clone().imuln(e)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r>>n}return t}(e);if(0===t.length)return new a(1);for(var r=this,i=0;i=0);var t,r=e%26,n=(e-r)/26,a=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var a=e%26,s=Math.min((e-a)/26,this.length),o=67108863^67108863>>>a<s)for(this.length-=s,u=0;u=0&&(0!==h||u>=n);u--){var d=0|this.words[u];this.words[u]=h<<26-a|d>>>a,h=d&o}return c&&0!==h&&(c.words[c.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(e,t,r){return i(0===this.negative),this.iushrn(e,t,r)},a.prototype.shln=function(e){return this.clone().ishln(e)},a.prototype.ushln=function(e){return this.clone().iushln(e)},a.prototype.shrn=function(e){return this.clone().ishrn(e)},a.prototype.ushrn=function(e){return this.clone().iushrn(e)},a.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,n=1<=0);var t=e%26,r=(e-t)/26;if(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},a.prototype.isubn=function(e){if(i("number"==typeof e),i(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[n+r]=67108863&a}for(;n>26,this.words[n+r]=67108863&a;if(0===o)return this.strip();for(i(-1===o),o=0,n=0;n>26,this.words[n]=67108863&a;return this.negative=1,this.strip()},a.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),n=e,s=0|n.words[n.length-1];0!==(r=26-this._countBits(s))&&(n=n.ushln(r),i.iushln(r),s=0|n.words[n.length-1]);var o,c=i.length-n.length;if("mod"!==t){(o=new a(null)).length=c+1,o.words=Array(o.length);for(var u=0;u=0;d--){var f=67108864*(0|i.words[n.length+d])+(0|i.words[n.length+d-1]);for(f=Math.min(f/s|0,67108863),i._ishlnsubmul(n,f,d);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(n,1,d),i.isZero()||(i.negative^=1);o&&(o.words[d]=f)}return o&&o.strip(),i.strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:o||null,mod:i}},a.prototype.divmod=function(e,t,r){return i(!e.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(n=o.div.neg()),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:n,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(n=o.div.neg()),{div:n,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new a(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new a(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new a(this.modn(e.words[0]))}:this._wordDiv(e,t);var n,s,o},a.prototype.div=function(e){return this.divmod(e,"div",!1).div},a.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},a.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},a.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),a=r.cmp(i);return a<0||1===n&&0===a?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},a.prototype.modn=function(e){i(e<=67108863);for(var t=(1<<26)%e,r=0,n=this.length-1;n>=0;n--)r=(t*r+(0|this.words[n]))%e;return r},a.prototype.idivn=function(e){i(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var n=(0|this.words[r])+67108864*t;this.words[r]=n/e|0,t=n%e}return this.strip()},a.prototype.divn=function(e){return this.clone().idivn(e)},a.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n=new a(1),s=new a(0),o=new a(0),c=new a(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var h=r.clone(),d=t.clone();!t.isZero();){for(var f=0,l=1;0==(t.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(n.isOdd()||s.isOdd())&&(n.iadd(h),s.isub(d)),n.iushrn(1),s.iushrn(1);for(var p=0,y=1;0==(r.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(h),c.isub(d)),o.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),n.isub(o),s.isub(c)):(r.isub(t),o.isub(n),c.isub(s))}return{a:o,b:c,gcd:r.iushln(u)}},a.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var n,s=new a(1),o=new a(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,h=1;0==(t.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,f=1;0==(r.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(r.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(o)):(r.isub(t),o.isub(s))}return(n=0===t.cmpn(1)?s:o).cmpn(0)<0&&n.iadd(e),n},a.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var a=t;t=r,r=a}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},a.prototype.invm=function(e){return this.egcd(e).a.umod(e)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(e){return this.words[0]&e},a.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,r=(e-t)/26,n=1<>>26,o&=67108863,this.words[s]=o}return 0!==a&&(this.words[s]=a,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),i(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},a.prototype.gtn=function(e){return 1===this.cmpn(e)},a.prototype.gt=function(e){return 1===this.cmp(e)},a.prototype.gten=function(e){return this.cmpn(e)>=0},a.prototype.gte=function(e){return this.cmp(e)>=0},a.prototype.ltn=function(e){return-1===this.cmpn(e)},a.prototype.lt=function(e){return-1===this.cmp(e)},a.prototype.lten=function(e){return this.cmpn(e)<=0},a.prototype.lte=function(e){return this.cmp(e)<=0},a.prototype.eqn=function(e){return 0===this.cmpn(e)},a.prototype.eq=function(e){return 0===this.cmp(e)},a.red=function(e){return new k(e)},a.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},a.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(e){return this.red=e,this},a.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},a.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},a.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},a.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},a.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},a.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},a.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},a.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},a.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new a(t,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function v(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function k(e){if("string"==typeof e){var t=a._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function A(e){k.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var e=new a(null);return e.words=Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},n(g,m),g.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,a=s}a>>>=22,e.words[n-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},g.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},a._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new g;else if("p224"===e)t=new w;else if("p192"===e)t=new v;else{if("p25519"!==e)throw Error("Unknown prime "+e);t=new _}return b[e]=t,t},k.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},k.prototype._verify2=function(e,t){i(0==(e.negative|t.negative),"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},k.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},k.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},k.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},k.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},k.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},k.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},k.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},k.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},k.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},k.prototype.isqr=function(e){return this.imul(e,e.clone())},k.prototype.sqr=function(e){return this.mul(e,e)},k.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var r=this.m.add(new a(1)).iushrn(2);return this.pow(e,r)}for(var n=this.m.subn(1),s=0;!n.isZero()&&0===n.andln(1);)s++,n.iushrn(1);i(!n.isZero());var o=new a(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),h=this.m.bitLength();for(h=new a(2*h*h).toRed(this);0!==this.pow(h,u).cmp(c);)h.redIAdd(c);for(var d=this.pow(h,n),f=this.pow(e,n.addn(1).iushrn(1)),l=this.pow(e,n),p=s;0!==l.cmp(o);){for(var y=l,b=0;0!==y.cmp(o);b++)y=y.redSqr();i(b=0;i--){for(var u=t.words[i],h=c-1;h>=0;h--){var d=u>>h&1;n!==r[0]&&(n=this.sqr(n)),0!==d||0!==s?(s<<=1,s|=d,(4===++o||0===i&&0===h)&&(n=this.mul(n,r[s]),o=0,s=0)):o=0}c=26}return n},k.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},k.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},a.mont=function(e){return new A(e)},n(A,k),A.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},A.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},A.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.iadd(this.m)),a._forceRed(this)},A.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new a(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s._forceRed(this)},A.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,ut)})),py=/*#__PURE__*/Object.freeze({__proto__:null,default:ly,__moduleExports:ly});class yy{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");this.value=new ly(e)}clone(){const e=new yy(null);return this.value.copy(e.value),e}iinc(){return this.value.iadd(new ly(1)),this}inc(){return this.clone().iinc()}idec(){return this.value.isub(new ly(1)),this}dec(){return this.clone().idec()}iadd(e){return this.value.iadd(e.value),this}add(e){return this.clone().iadd(e)}isub(e){return this.value.isub(e.value),this}sub(e){return this.clone().isub(e)}imul(e){return this.value.imul(e.value),this}mul(e){return this.clone().imul(e)}imod(e){return this.value=this.value.umod(e.value),this}mod(e){return this.clone().imod(e)}modExp(e,t){const r=t.isEven()?ly.red(t.value):ly.mont(t.value),i=this.clone();return i.value=i.value.toRed(r).redPow(e.value).fromRed(),i}modInv(e){if(!this.gcd(e).isOne())throw Error("Inverse does not exist");return new yy(this.value.invm(e.value))}gcd(e){return new yy(this.value.gcd(e.value))}ileftShift(e){return this.value.ishln(e.value.toNumber()),this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value.ishrn(e.value.toNumber()),this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value.eq(e.value)}lt(e){return this.value.lt(e.value)}lte(e){return this.value.lte(e.value)}gt(e){return this.value.gt(e.value)}gte(e){return this.value.gte(e.value)}isZero(){return this.value.isZero()}isOne(){return this.value.eq(new ly(1))}isNegative(){return this.value.isNeg()}isEven(){return this.value.isEven()}abs(){const e=this.clone();return e.value=e.value.abs(),e}toString(){return this.value.toString()}toNumber(){return this.value.toNumber()}getBit(e){return this.value.testn(e)?1:0}bitLength(){return this.value.bitLength()}byteLength(){return this.value.byteLength()}toUint8Array(e="be",t){return this.value.toArrayLike(Uint8Array,e,t)}}var by,my=/*#__PURE__*/Object.freeze({__proto__:null,default:yy}),gy=ht((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,s=255&n;a?r.push(a,s):r.push(s)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),wy=ht((function(e,t){var r=t;r.assert=ot,r.toArray=gy.toArray,r.zero2=gy.zero2,r.toHex=gy.toHex,r.encode=gy.encode,r.getNAF=function(e,t){for(var r=[],i=1<=0;){var a;if(n.isOdd()){var s=n.andln(i-1);a=s>(i>>1)-1?(i>>1)-s:s,n.isubn(a)}else a=0;r.push(a);for(var o=0!==n.cmpn(0)&&0===n.andln(i-1)?t+1:1,c=1;c0||t.cmpn(-n)>0;){var a,s,o,c=e.andln(3)+i&3,u=t.andln(3)+n&3;if(3===c&&(c=-1),3===u&&(u=-1),0==(1&c))a=0;else a=3!==(o=e.andln(7)+i&7)&&5!==o||2!==u?c:-c;if(r[0].push(a),0==(1&u))s=0;else s=3!==(o=t.andln(7)+n&7)&&5!==o||2!==c?u:-u;r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new ly(e,"hex","le")}})),vy=function(e){return by||(by=new _y(null)),by.generate(e)};function _y(e){this.rand=e}var ky=_y;if(_y.prototype.generate=function(e){return this._rand(e)},_y.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var My=xy;function Ky(e,t){this.curve=e,this.type=t,this.precomputed=null}xy.prototype.point=function(){throw Error("Not implemented")},xy.prototype.validate=function(){throw Error("Not implemented")},xy.prototype._fixedNafMul=function(e,t){Py(e.precomputed);var r=e._getDoubles(),i=Sy(t,1),n=(1<=s;t--)o=(o<<1)+i[t];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),h=n;h>0;h--){for(s=0;s=0;o--){for(t=0;o>=0&&0===a[o];o--)t++;if(o>=0&&t++,s=s.dblp(t),o<0)break;var c=a[o];Py(0!==c),s="affine"===e.type?c>0?s.mixedAdd(n[c-1>>1]):s.mixedAdd(n[-c-1>>1].neg()):c>0?s.add(n[c-1>>1]):s.add(n[-c-1>>1].neg())}return"affine"===e.type?s.toP():s},xy.prototype._wnafMulAdd=function(e,t,r,i,n){for(var a=this._wnafT1,s=this._wnafT2,o=this._wnafT3,c=0,u=0;u=1;u-=2){var d=u-1,f=u;if(1===a[d]&&1===a[f]){var l=[t[d],null,null,t[f]];0===t[d].y.cmp(t[f].y)?(l[1]=t[d].add(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg())):0===t[d].y.cmp(t[f].y.redNeg())?(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].add(t[f].neg())):(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg()));var p=[-3,-1,-5,-7,0,7,5,1,3],y=Ey(r[d],r[f]);c=Math.max(y[0].length,c),o[d]=Array(c),o[f]=Array(c);for(var b=0;b=0;u--){for(var _=0;u>=0;){var k=!0;for(b=0;b=0&&_++,w=w.dblp(_),u<0)break;for(b=0;b0?A=s[b][S-1>>1]:S<0&&(A=s[b][-S-1>>1].neg()),w="affine"===A.type?w.mixedAdd(A):w.add(A))}}for(u=0;u=Math.ceil((e.bitLength()+1)/t.step)},Ky.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(a=t,s=r),i.negative&&(i=i.neg(),n=n.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a,b:s}]},Dy.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),u=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(u).neg()}},Dy.prototype.pointFromX=function(e,t){(e=new ly(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},Dy.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},Dy.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,a=0;a":""},Ry.prototype.isInfinity=function(){return this.inf},Ry.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},Ry.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),a=n.redSqr().redISub(this.x.redAdd(this.x)),s=n.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,s)},Ry.prototype.getX=function(){return this.x.fromRed()},Ry.prototype.getY=function(){return this.y.fromRed()},Ry.prototype.mul=function(e){return e=new ly(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},Ry.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},Ry.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},Ry.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},Ry.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},Ry.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},lt(Iy,My.BasePoint),Dy.prototype.jpoint=function(e,t,r){return new Iy(this,e,t,r)},Iy.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},Iy.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Iy.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=o.redSqr(),h=u.redMul(o),d=i.redMul(u),f=c.redSqr().redIAdd(h).redISub(d).redISub(d),l=c.redMul(d.redISub(f)).redISub(a.redMul(h)),p=this.z.redMul(e.z).redMul(o);return this.curve.jpoint(f,l,p)},Iy.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))return 0!==o.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),u=c.redMul(s),h=r.redMul(c),d=o.redSqr().redIAdd(u).redISub(h).redISub(h),f=o.redMul(h.redISub(d)).redISub(n.redMul(u)),l=this.z.redMul(s);return this.curve.jpoint(d,f,l)},Iy.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},Iy.prototype.inspect=function(){return this.isInfinity()?"":""},Iy.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},lt(By,My);var Ty=By;function zy(e,t,r){My.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new ly(t,16),this.z=new ly(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}By.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),i=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===i.redSqrt().redSqr().cmp(i)},lt(zy,My.BasePoint),By.prototype.decodePoint=function(e,t){if(33===(e=wy.toArray(e,t)).length&&64===e[0]&&(e=e.slice(1,33).reverse()),32!==e.length)throw Error("Unknown point compression format");return this.point(e,1)},By.prototype.point=function(e,t){return new zy(this,e,t)},By.prototype.pointFromJSON=function(e){return zy.fromJSON(this,e)},zy.prototype.precompute=function(){},zy.prototype._encode=function(e){var t=this.curve.p.byteLength();return e?[64].concat(this.getX().toArray("le",t)):this.getX().toArray("be",t)},zy.fromJSON=function(e,t){return new zy(e,t[0],t[1]||e.one)},zy.prototype.inspect=function(){return this.isInfinity()?"":""},zy.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},zy.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),i=e.redMul(t),n=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(i,n)},zy.prototype.add=function(){throw Error("Not supported on Montgomery curve")},zy.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),i=this.x.redSub(this.z),n=e.x.redAdd(e.z),a=e.x.redSub(e.z).redMul(r),s=n.redMul(i),o=t.z.redMul(a.redAdd(s).redSqr()),c=t.x.redMul(a.redISub(s).redSqr());return this.curve.point(o,c)},zy.prototype.mul=function(e){for(var t=(e=new ly(e,16)).clone(),r=this,i=this.curve.point(null,null),n=[];0!==t.cmpn(0);t.iushrn(1))n.push(t.andln(1));for(var a=n.length-1;a>=0;a--)0===n[a]?(r=r.diffAdd(i,this),i=i.dbl()):(i=r.diffAdd(i,this),r=r.dbl());return i},zy.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},zy.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},zy.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},zy.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},zy.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var qy=wy.assert;function Fy(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,My.call(this,"edwards",e),this.a=new ly(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new ly(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new ly(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),qy(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}lt(Fy,My);var Oy=Fy;function Ly(e,t,r,i,n){My.BasePoint.call(this,e,"projective"),null===t&&null===r&&null===i?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new ly(t,16),this.y=new ly(r,16),this.z=i?new ly(i,16):this.curve.one,this.t=n&&new ly(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}Fy.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},Fy.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},Fy.prototype.jpoint=function(e,t,r,i){return this.point(e,t,r,i)},Fy.prototype.pointFromX=function(e,t){(e=new ly(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=this.c2.redSub(this.a.redMul(r)),n=this.one.redSub(this.c2.redMul(this.d).redMul(r)),a=i.redMul(n.redInvm()),s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");var o=s.fromRed().isOdd();return(t&&!o||!t&&o)&&(s=s.redNeg()),this.point(e,s)},Fy.prototype.pointFromY=function(e,t){(e=new ly(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=r.redSub(this.c2),n=r.redMul(this.d).redMul(this.c2).redSub(this.a),a=i.redMul(n.redInvm());if(0===a.cmp(this.zero)){if(t)throw Error("invalid point");return this.point(this.zero,e)}var s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");return s.fromRed().isOdd()!==t&&(s=s.redNeg()),this.point(s,e)},Fy.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),r=e.y.redSqr(),i=t.redMul(this.a).redAdd(r),n=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(r)));return 0===i.cmp(n)},lt(Ly,My.BasePoint),Fy.prototype.pointFromJSON=function(e){return Ly.fromJSON(this,e)},Fy.prototype.point=function(e,t,r,i){return new Ly(this,e,t,r,i)},Ly.fromJSON=function(e,t){return new Ly(e,t[0],t[1],t[2])},Ly.prototype.inspect=function(){return this.isInfinity()?"":""},Ly.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ly.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var i=this.curve._mulA(e),n=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=i.redAdd(t),s=a.redSub(r),o=i.redSub(t),c=n.redMul(s),u=a.redMul(o),h=n.redMul(o),d=s.redMul(a);return this.curve.point(c,u,d,h)},Ly.prototype._projDbl=function(){var e,t,r,i=this.x.redAdd(this.y).redSqr(),n=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var s=(u=this.curve._mulA(n)).redAdd(a);if(this.zOne)e=i.redSub(n).redSub(a).redMul(s.redSub(this.curve.two)),t=s.redMul(u.redSub(a)),r=s.redSqr().redSub(s).redSub(s);else{var o=this.z.redSqr(),c=s.redSub(o).redISub(o);e=i.redSub(n).redISub(a).redMul(c),t=s.redMul(u.redSub(a)),r=s.redMul(c)}}else{var u=n.redAdd(a);o=this.curve._mulC(this.z).redSqr(),c=u.redSub(o).redSub(o);e=this.curve._mulC(i.redISub(u)).redMul(c),t=this.curve._mulC(u).redMul(n.redISub(a)),r=u.redMul(c)}return this.curve.point(e,t,r)},Ly.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ly.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),i=this.t.redMul(this.curve.dd).redMul(e.t),n=this.z.redMul(e.z.redAdd(e.z)),a=r.redSub(t),s=n.redSub(i),o=n.redAdd(i),c=r.redAdd(t),u=a.redMul(s),h=o.redMul(c),d=a.redMul(c),f=s.redMul(o);return this.curve.point(u,h,f,d)},Ly.prototype._projAdd=function(e){var t,r,i=this.z.redMul(e.z),n=i.redSqr(),a=this.x.redMul(e.x),s=this.y.redMul(e.y),o=this.curve.d.redMul(a).redMul(s),c=n.redSub(o),u=n.redAdd(o),h=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(a).redISub(s),d=i.redMul(c).redMul(h);return this.curve.twisted?(t=i.redMul(u).redMul(s.redSub(this.curve._mulA(a))),r=c.redMul(u)):(t=i.redMul(u).redMul(s.redSub(a)),r=this.curve._mulC(c).redMul(u)),this.curve.point(d,t,r)},Ly.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},Ly.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},Ly.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},Ly.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},Ly.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},Ly.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ly.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ly.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ly.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},Ly.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),i=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(i),0===this.x.cmp(t))return!0}},Ly.prototype.toP=Ly.prototype.normalize,Ly.prototype.mixedAdd=Ly.prototype.add;var Ny=ht((function(e,t){var r=t;r.base=My,r.short=Uy,r.mont=Ty,r.edwards=Oy})),jy=kt.rotl32,Hy=kt.sum32,Wy=kt.sum32_5,Gy=Dt.ft_1,Vy=Et.BlockHash,$y=[1518500249,1859775393,2400959708,3395469782];function Zy(){if(!(this instanceof Zy))return new Zy;Vy.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}kt.inherits(Zy,Vy);var Xy=Zy;Zy.blockSize=512,Zy.outSize=160,Zy.hmacStrength=80,Zy.padLength=64,Zy.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;ithis.blockSize&&(e=(new this.Hash).update(e).digest()),ot(e.length<=this.blockSize);for(var t=e.length;t=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var nb=ib;ib.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},ib.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=gy.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var cb=wy.assert;function ub(e,t){if(e instanceof ub)return e;this._importDER(e,t)||(cb(e.r&&e.s,"Signature without r or s"),this.r=new ly(e.r,16),this.s=new ly(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var hb=ub;function db(){this.place=0}function fb(e,t){var r=e[t.place++];if(!(128&r))return r;for(var i=15&r,n=0,a=0,s=t.place;a>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}ub.prototype._importDER=function(e,t){e=wy.toArray(e,t);var r=new db;if(48!==e[r.place++])return!1;if(fb(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var i=fb(e,r),n=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])return!1;var a=fb(e,r);if(e.length!==a+r.place)return!1;var s=e.slice(r.place,a+r.place);return 0===n[0]&&128&n[1]&&(n=n.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new ly(n),this.s=new ly(s),this.recoveryParam=null,!0},ub.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=lb(t),r=lb(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];pb(i,t.length),(i=i.concat(t)).push(2),pb(i,r.length);var n=i.concat(r),a=[48];return pb(a,n.length),a=a.concat(n),wy.encode(a,e)};var yb=wy.assert;function bb(e){if(!(this instanceof bb))return new bb(e);"string"==typeof e&&(yb(rb.hasOwnProperty(e),"Unknown curve "+e),e=rb[e]),e instanceof rb.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var mb=bb;bb.prototype.keyPair=function(e){return new ob(this,e)},bb.prototype.keyFromPrivate=function(e,t){return ob.fromPrivate(this,e,t)},bb.prototype.keyFromPublic=function(e,t){return ob.fromPublic(this,e,t)},bb.prototype.genKeyPair=function(e){e||(e={});var t=new nb({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||vy(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()});if("mont"===this.curve.type){var r=new ly(t.generate(32));return this.keyFromPrivate(r)}for(var i=this.n.byteLength(),n=this.n.sub(new ly(2));;){if(!((r=new ly(t.generate(i))).cmp(n)>0))return r.iaddn(1),this.keyFromPrivate(r)}},bb.prototype._truncateToN=function(e,t,r){var i=(r=r||8*e.byteLength())-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},bb.prototype.truncateMsg=function(e){var t;return e instanceof Uint8Array?(t=8*e.byteLength,e=this._truncateToN(new ly(e,16),!1,t)):"string"==typeof e?(t=4*e.length,e=this._truncateToN(new ly(e,16),!1,t)):e=this._truncateToN(new ly(e,16)),e},bb.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this.truncateMsg(e);for(var n=this.n.byteLength(),a=t.getPrivate().toArray("be",n),s=e.toArray("be",n),o=new nb({hash:this.hash,entropy:a,nonce:s,pers:i.pers,persEnc:i.persEnc||"utf8"}),c=this.n.sub(new ly(1)),u=0;;u++){var h=i.k?i.k(u):new ly(o.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(c)>=0)){var d=this.g.mul(h);if(!d.isInfinity()){var f=d.getX(),l=f.umod(this.n);if(0!==l.cmpn(0)){var p=h.invm(this.n).mul(l.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var y=(d.getY().isOdd()?1:0)|(0!==f.cmp(l)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),y^=1),new hb({r:l,s:p,recoveryParam:y})}}}}}},bb.prototype.verify=function(e,t,r,i){return r=this.keyFromPublic(r,i),t=new hb(t,"hex"),this._verify(this.truncateMsg(e),t,r)||this._verify(this._truncateToN(new ly(e,16)),t,r)},bb.prototype._verify=function(e,t,r){var i=t.r,n=t.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;var a,s=n.invm(this.n),o=s.mul(e).umod(this.n),c=s.mul(i).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(o,r.getPublic(),c)).isInfinity()&&a.eqXToP(i):!(a=this.g.mulAdd(o,r.getPublic(),c)).isInfinity()&&0===a.getX().umod(this.n).cmp(i)},bb.prototype.recoverPubKey=function(e,t,r,i){yb((3&r)===r,"The recovery param is more than two bits"),t=new hb(t,i);var n=this.n,a=new ly(e),s=t.r,o=t.s,c=1&r,u=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw Error("Unable to find sencond key candinate");s=u?this.curve.pointFromX(s.add(this.curve.n),c):this.curve.pointFromX(s,c);var h=t.r.invm(n),d=n.sub(a).mul(h).umod(n),f=o.mul(h).umod(n);return this.g.mulAdd(d,s,f)},bb.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new hb(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(e,t,n)}catch(e){continue}if(a.eq(r))return n}throw Error("Unable to find valid recovery factor")};var gb=wy.assert,wb=wy.parseBytes,vb=wy.cachedProperty;function _b(e,t){if(this.eddsa=e,t.hasOwnProperty("secret")&&(this._secret=wb(t.secret)),e.isPoint(t.pub))this._pub=t.pub;else if(this._pubBytes=wb(t.pub),this._pubBytes&&33===this._pubBytes.length&&64===this._pubBytes[0]&&(this._pubBytes=this._pubBytes.slice(1,33)),this._pubBytes&&32!==this._pubBytes.length)throw Error("Unknown point compression format")}_b.fromPublic=function(e,t){return t instanceof _b?t:new _b(e,{pub:t})},_b.fromSecret=function(e,t){return t instanceof _b?t:new _b(e,{secret:t})},_b.prototype.secret=function(){return this._secret},vb(_b,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),vb(_b,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),vb(_b,"privBytes",(function(){var e=this.eddsa,t=this.hash(),r=e.encodingLength-1,i=t.slice(0,e.encodingLength);return i[0]&=248,i[r]&=127,i[r]|=64,i})),vb(_b,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),vb(_b,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),vb(_b,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),_b.prototype.sign=function(e){return gb(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},_b.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},_b.prototype.getSecret=function(e){return gb(this._secret,"KeyPair is public only"),wy.encode(this.secret(),e)},_b.prototype.getPublic=function(e,t){return wy.encode((t?[64]:[]).concat(this.pubBytes()),e)};var kb=_b,Ab=wy.assert,Sb=wy.cachedProperty,Eb=wy.parseBytes;function Pb(e,t){this.eddsa=e,"object"!=typeof t&&(t=Eb(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),Ab(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof ly&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}Sb(Pb,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),Sb(Pb,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),Sb(Pb,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),Sb(Pb,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),Pb.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Pb.prototype.toHex=function(){return wy.encode(this.toBytes(),"hex").toUpperCase()};var xb=Pb,Mb=wy.assert,Kb=wy.parseBytes;function Cb(e){if(Mb("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof Cb))return new Cb(e);e=rb[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=eb.sha512}var Db=Cb;Cb.prototype.sign=function(e,t){e=Kb(e);var r=this.keyFromSecret(t),i=this.hashInt(r.messagePrefix(),e),n=this.g.mul(i),a=this.encodePoint(n),s=this.hashInt(a,r.pubBytes(),e).mul(r.priv()),o=i.add(s).umod(this.curve.n);return this.makeSignature({R:n,S:o,Rencoded:a})},Cb.prototype.verify=function(e,t,r){e=Kb(e),t=this.makeSignature(t);var i=this.keyFromPublic(r),n=this.hashInt(t.Rencoded(),i.pubBytes(),e),a=this.g.mul(t.S());return t.R().add(i.pub().mul(n)).eq(a)},Cb.prototype.hashInt=function(){for(var e=this.hash(),t=0;t{this[s]=e,this[a]=t})),this[i].catch((()=>{}))}}function h(e){return e&&e.getReader&&Array.isArray(e)}function u(e){if(!h(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}function l(t){if(h(t))return"array";if(e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t))return"web";if(t&&!(e.ReadableStream&&t instanceof e.ReadableStream)&&"function"==typeof t._read&&"object"==typeof t._readableState)throw Error("Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`");return!(!t||!t.getReader)&&"web-like"}function y(e){return Uint8Array.prototype.isPrototypeOf(e)}function f(e){if(1===e.length)return e[0];let t=0;for(let r=0;r(await this[i],this[o]===this.length?{value:void 0,done:!0}:{value:this[this[o]++],done:!1})}},c.prototype.readToEnd=async function(e){await this[i];const t=e(this.slice(this[o]));return this.length=0,t},c.prototype.clone=function(){const e=new c;return e[i]=this[i].then((()=>{e.push(...this)})),e},u.prototype.write=async function(e){this.stream.push(e)},u.prototype.close=async function(){this.stream[s]()},u.prototype.abort=async function(e){return this.stream[a](e),e},u.prototype.releaseLock=function(){},"object"==typeof e.process&&e.process.versions;const g=new WeakSet,p=Symbol("externalBuffer");function d(e){if(this.stream=e,e[p]&&(this[p]=e[p].slice()),h(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=()=>{})}if(l(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let t=!1;this._read=async()=>t||g.has(e)?{value:void 0,done:!0}:(t=!0,{value:e,done:!1}),this._releaseLock=()=>{if(t)try{g.add(e)}catch(e){}}}function A(e){return l(e)?e:new ReadableStream({start(t){t.enqueue(e),t.close()}})}function w(e){if(l(e))return e;const t=new c;return(async()=>{const r=R(t);await r.write(e),await r.close()})(),t}function m(e){return e.some((e=>l(e)&&!h(e)))?function(e){e=e.map(A);const t=E((async function(e){await Promise.all(n.map((t=>U(t,e))))}));let r=Promise.resolve();const n=e.map(((n,i)=>B(n,((n,s)=>(r=r.then((()=>b(n,t.writable,{preventClose:i!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>h(e)))?function(e){const t=new c;let r=Promise.resolve();return e.forEach(((n,i)=>(r=r.then((()=>b(n,t,{preventClose:i!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):f(e)}async function b(e,t,{preventClose:r=!1,preventAbort:n=!1,preventCancel:i=!1}={}){if(l(e)&&!h(e)){e=A(e);try{if(e[p]){const r=R(t);for(let t=0;t{t=e,r=n})),t=null,r=null)},close:n.close.bind(n),abort:n.error.bind(n)})}}function v(e,t=()=>{},r=()=>{}){if(h(e)){const n=new c;return(async()=>{const i=R(n);try{const n=await P(e),s=t(n),a=r();let o;o=void 0!==s&&void 0!==a?m([s,a]):void 0!==s?s:a,await i.write(o),await i.close()}catch(e){await i.abort(e)}})(),n}if(l(e))return k(e,{async transform(e,r){try{const n=await t(e);void 0!==n&&r.enqueue(n)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const n=t(e),i=r();return void 0!==n&&void 0!==i?m([n,i]):void 0!==n?n:i}function B(e,t){if(l(e)&&!h(e)){let r;const n=new TransformStream({start(e){r=e}}),i=b(e,n.writable),s=E((async function(e){r.error(e),await i,await new Promise(setTimeout)}));return t(n.readable,s.writable),s.readable}e=w(e);const r=new c;return t(e,r),r}function I(e,t){let r;const n=B(e,((e,i)=>{const s=Q(e);s.remainder=()=>(s.releaseLock(),b(e,i),n),r=t(s)}));return r}function S(e){if(h(e))return e.clone();if(l(e)){const t=function(e){if(h(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(l(e)){const t=A(e).tee();return t[0][p]=t[1][p]=e[p],t}return[D(e),D(e)]}(e);return C(e,t[0]),t[1]}return D(e)}function K(e){return h(e)?S(e):l(e)?new ReadableStream({start(t){const r=B(e,(async(e,r)=>{const n=Q(e),i=R(r);try{for(;;){await i.ready;const{done:e,value:r}=await n.read();if(e){try{t.close()}catch(e){}return void await i.close()}try{t.enqueue(r)}catch(e){}await i.write(r)}}catch(e){t.error(e),await i.abort(e)}}));C(e,r)}}):D(e)}function C(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,n])=>{"constructor"!==r&&(n.value?n.value=n.value.bind(t):n.get=n.get.bind(t),Object.defineProperty(e,r,n))}))}function D(e,t=0,r=1/0){if(h(e))throw Error("Not implemented");if(l(e)){if(t>=0&&r>=0){let n=0;return k(e,{transform(e,i){n=t&&i.enqueue(D(e,Math.max(t-n,0),r-n)),n+=e.length):i.terminate()}})}if(t<0&&(r<0||r===1/0)){let n=[];return v(e,(e=>{e.length>=-t?n=[e]:n.push(e)}),(()=>D(m(n),t,r)))}if(0===t&&r<0){let n;return v(e,(e=>{const i=n?m([n,e]):e;if(i.length>=-r)return n=D(i,r),D(i,t,r);n=i}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),x((async()=>D(await P(e),t,r)))}return e[p]&&(e=m(e[p].concat([e]))),y(e)?e.subarray(t,r===1/0?e.length:r):e.slice(t,r)}async function P(e,t=m){return h(e)?e.readToEnd(t):l(e)?Q(e).readToEnd(t):e}async function U(e,t){if(l(e)){if(e.cancel){const r=await e.cancel(t);return await new Promise(setTimeout),r}if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function x(e){const t=new c;return(async()=>{const r=R(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}function Q(e){return new d(e)}function R(e){return new u(e)}d.prototype.read=async function(){if(this[p]&&this[p].length){return{done:!1,value:this[p].shift()}}return this._read()},d.prototype.releaseLock=function(){this[p]&&(this.stream[p]=this[p]),this._releaseLock()},d.prototype.cancel=function(e){return this._cancel(e)},d.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:n}=await this.read();if(n+="",r)return t.length?m(t):void 0;const i=n.indexOf("\n")+1;i&&(e=m(t.concat(n.substr(0,i))),t=[]),i!==n.length&&t.push(n.substr(i))}return this.unshift(...t),e},d.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(D(t,1)),r},d.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:n,value:i}=await this.read();if(n)return t.length?m(t):void 0;if(t.push(i),r+=i.length,r>=e){const r=m(t);return this.unshift(D(r,e)),D(r,0,e)}}},d.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},d.prototype.unshift=function(...e){this[p]||(this[p]=[]),1===e.length&&y(e[0])&&this[p].length&&e[0].length&&this[p][0].byteOffset>=e[0].length?this[p][0]=new Uint8Array(this[p][0].buffer,this[p][0].byteOffset-e[0].length,this[p][0].byteLength+e[0].length):this[p].unshift(...e.filter((e=>e&&e.length)))},d.prototype.readToEnd=async function(e=m){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};const L=Symbol("byValue");var T={curve:{nistP256:"nistP256",p256:"nistP256",nistP384:"nistP384",p384:"nistP384",nistP521:"nistP521",p521:"nistP521",secp256k1:"secp256k1",ed25519Legacy:"ed25519Legacy",ed25519:"ed25519Legacy",curve25519Legacy:"curve25519Legacy",curve25519:"curve25519Legacy",brainpoolP256r1:"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,argon2:4,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11,sha3_256:12,sha3_512:14},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,gcm:3,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20,padding:21},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuerKeyID:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34,preferredCipherSuites:39},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4,seipdv2:8},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[L]||(e[L]=[],Object.entries(e).forEach((([t,r])=>{e[L][r]=t}))),void 0!==e[L][t])return e[L][t];throw Error("Invalid enum value.")}},M={preferredHashAlgorithm:T.hash.sha512,preferredSymmetricAlgorithm:T.symmetric.aes256,preferredCompressionAlgorithm:T.compression.uncompressed,aeadProtect:!1,parseAEADEncryptedV4KeysAsLegacy:!1,preferredAEADAlgorithm:T.aead.gcm,aeadChunkSizeByte:12,v6Keys:!1,enableParsingV5Entities:!1,s2kType:T.s2k.iterated,s2kIterationCountByte:224,s2kArgon2Params:{passes:3,parallelism:4,memoryExponent:16},allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,minRSABits:2047,passwordCollisionCheck:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,allowMissingKeyFlags:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([T.symmetric.aes128,T.symmetric.aes192,T.symmetric.aes256]),ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 6.0.0",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],nonDeterministicSignaturesViaNotation:!0,useEllipticFallback:!0,rejectHashAlgorithms:new Set([T.hash.md5,T.hash.ripemd]),rejectMessageHashAlgorithms:new Set([T.hash.md5,T.hash.ripemd,T.hash.sha1]),rejectPublicKeyAlgorithms:new Set([T.publicKey.elgamal,T.publicKey.dsa]),rejectCurves:new Set([T.curve.secp256k1])};const N=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),F={isString:function(e){return"string"==typeof e||e instanceof String},nodeRequire:t(import.meta.url),isArray:function(e){return e instanceof Array},isUint8Array:y,isStream:l,getNobleCurve:async(e,t)=>{if(!M.useEllipticFallback)throw Error("This curve is only supported in the full build of OpenPGP.js");const{nobleCurves:r}=await Promise.resolve().then((function(){return ml}));switch(e){case T.publicKey.ecdh:case T.publicKey.ecdsa:{const e=r.get(t);if(!e)throw Error("Unsupported curve");return e}case T.publicKey.x448:return r.get("x448");case T.publicKey.ed448:return r.get("ed448");default:throw Error("Unsupported curve")}},readNumber:function(e){let t=0;for(let r=0;r>8*(t-n-1)&255;return r},readDate:function(e){const t=F.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return F.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return F.readExactSubarray(e,2,2+t)},readExactSubarray:function(e,t,r){if(e.lengtht)throw Error("Input array too long");const r=new Uint8Array(t),n=t-e.length;return r.set(e,n),r},uint8ArrayToMPI:function(e){const t=F.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),n=new Uint8Array([(65280&t)>>8,255&t]);return F.concatUint8Array([n,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t="0123456789abcdef";let r="";return e.forEach((e=>{r+=t[e>>4]+t[15&e]})),r},stringToUint8Array:function(e){return v(e,(e=>{if(!F.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return v(e,r,(()=>r(new Uint8Array,!0)))},concat:m,concatUint8Array:f,equalsUint8Array:function(e,t){if(!F.isUint8Array(e)||!F.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let n=0;n>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){const t=void 0!==e&&e.crypto&&e.crypto.subtle||this.getNodeCrypto()?.webcrypto.subtle;if(!t)throw Error("The WebCrypto API is not available");return t},getNodeCrypto:function(){return this.nodeRequire("crypto")},getNodeZlib:function(){return this.nodeRequire("zlib")},getNodeBuffer:function(){return(this.nodeRequire("buffer")||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return this.nodeRequire("os").cpus().length},isEmailAddress:function(e){if(!F.isString(e))return!1;return/^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u.test(e)},canonicalizeEOL:function(e){let t=!1;return v(e,(e=>{let r;t&&(e=F.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const n=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&n.push(r);if(!n.length)return e;const i=new Uint8Array(e.length+n.length);let s=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return v(e,(e=>{let r;13===(e=t&&10!==e[0]?F.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let n=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const i=r-(10===e[r]?1:0);t&&e.copyWithin(n,t,i),n+=i-t}return e.subarray(0,n)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let n;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){n=e}}))),r(n)}))},selectUint8Array:function(e,t,r){const n=Math.max(t.length,r.length),i=new Uint8Array(n);let s=0;for(let n=0;n{t=F.concatUint8Array([t,e]);const r=[],n=Math.floor(t.length/45),i=45*n,s=O(t.subarray(0,i));for(let e=0;et.length?O(t)+"\n":""))}function G(e){let t="";return v(e,(e=>{t+=e;let r=0;const n=[" ","\t","\r","\n"];for(let e=0;e0&&(i-r)%4!=0;i--)n.includes(t[i])&&r--;const s=z(t.substr(0,i));return t=t.substr(i),s}),(()=>z(t)))}function j(e){return G(e.replace(/-/g,"+").replace(/_/g,"/"))}function q(e,t){let r=_(e).replace(/[\r\n]/g,"");return r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,""),r}function V(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?T.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?T.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?T.armor.signed:/MESSAGE/.test(t[1])?T.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?T.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?T.armor.privateKey:/SIGNATURE/.test(t[1])?T.armor.signature:void 0}function J(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function Y(e){const t=function(e){let t=13501623;return v(e,(e=>{const r=Z?Math.floor(e.length/4):0,n=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^W[1][t>>16&255]^W[2][t>>8&255]^W[3][255&t];for(let n=4*r;n>8^W[0][255&t^e[n]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e);return _(t)}H?(O=e=>H.from(e).toString("base64"),z=e=>{const t=H.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(O=e=>btoa(F.uint8ArrayToString(e)),z=e=>F.stringToUint8Array(atob(e)));const W=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(8388608&t?8801531:0);W[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)W[1][e]=W[0][e]>>8^W[0][255&W[0][e]];for(let e=0;e<=255;e++)W[2][e]=W[1][e]>>8^W[0][255&W[1][e]];for(let e=0;e<=255;e++)W[3][e]=W[2][e]>>8^W[0][255&W[2][e]];const Z=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function $(e){for(let t=0;t=0&&r!==e.length-1&&(t=e.slice(0,r)),t}function ee(e){return new Promise((async(t,r)=>{try{const n=/^-----[^-]+-----$/m,i=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const a=[];let o,c,h=a,u=[];const l=G(B(e,(async(e,y)=>{const f=Q(e);try{for(;;){let e=await f.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=F.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(o)c||s!==T.armor.signed||(n.test(e)?(u=u.join("\r\n"),c=!0,$(h),h=[],o=!1):u.push(e.replace(/^- /,"")));else if(n.test(e)&&r(Error("Mandatory blank line missing between armor headers and armor data")),i.test(e)){if($(h),o=!0,c||s!==T.armor.signed){t({text:u,data:l,headers:a,type:s});break}}else h.push(e);else n.test(e)&&(s=V(e))}}catch(e){return void r(e)}const g=R(y);try{for(;;){await g.ready;const{done:e,value:t}=await f.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await f.readToEnd();e.length||(e=""),e=r+e,e=F.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=X(t[0].slice(0,-1));await g.write(i);break}await g.write(r)}await g.ready,await g.close()}catch(e){await g.abort(e)}})))}catch(e){r(e)}})).then((async e=>(h(e.data)&&(e.data=await P(e.data)),e)))}function te(e,t,r,n,i,s=!1,a=M){let o,c;e===T.armor.signed&&(o=t.text,c=t.hash,t=t.data);const h=s&&K(t),u=[];switch(e){case T.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+n+"-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP MESSAGE, PART "+r+"/"+n+"-----\n");break;case T.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case T.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push(c?`Hash: ${c}\n\n`:"\n"),u.push(o.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP SIGNATURE-----\n");break;case T.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP MESSAGE-----\n");break;case T.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case T.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case T.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(J(i,a)),u.push(_(t)),h&&u.push("=",Y(h)),u.push("-----END PGP SIGNATURE-----\n")}return F.concat(u)}async function re(e){switch(e){case T.symmetric.aes128:case T.symmetric.aes192:case T.symmetric.aes256:throw Error("Not a legacy cipher");case T.symmetric.cast5:case T.symmetric.blowfish:case T.symmetric.twofish:case T.symmetric.tripledes:{const{legacyCiphers:t}=await Promise.resolve().then((function(){return Rl})),r=t.get(e);if(!r)throw Error("Unsupported cipher algorithm");return r}default:throw Error("Unsupported cipher algorithm")}}function ne(e){switch(e){case T.symmetric.aes128:case T.symmetric.aes192:case T.symmetric.aes256:case T.symmetric.twofish:return 16;case T.symmetric.blowfish:case T.symmetric.cast5:case T.symmetric.tripledes:return 8;default:throw Error("Unsupported cipher")}}function ie(e){switch(e){case T.symmetric.aes128:case T.symmetric.blowfish:case T.symmetric.cast5:return 16;case T.symmetric.aes192:case T.symmetric.tripledes:return 24;case T.symmetric.aes256:case T.symmetric.twofish:return 32;default:throw Error("Unsupported cipher")}}function se(e){return{keySize:ie(e),blockSize:ne(e)}}var ae=/*#__PURE__*/Object.freeze({__proto__:null,getCipherParams:se,getLegacyCipher:re});function oe(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r=he(r,n,i,s,t[0],7,-680876936),s=he(s,r,n,i,t[1],12,-389564586),i=he(i,s,r,n,t[2],17,606105819),n=he(n,i,s,r,t[3],22,-1044525330),r=he(r,n,i,s,t[4],7,-176418897),s=he(s,r,n,i,t[5],12,1200080426),i=he(i,s,r,n,t[6],17,-1473231341),n=he(n,i,s,r,t[7],22,-45705983),r=he(r,n,i,s,t[8],7,1770035416),s=he(s,r,n,i,t[9],12,-1958414417),i=he(i,s,r,n,t[10],17,-42063),n=he(n,i,s,r,t[11],22,-1990404162),r=he(r,n,i,s,t[12],7,1804603682),s=he(s,r,n,i,t[13],12,-40341101),i=he(i,s,r,n,t[14],17,-1502002290),n=he(n,i,s,r,t[15],22,1236535329),r=ue(r,n,i,s,t[1],5,-165796510),s=ue(s,r,n,i,t[6],9,-1069501632),i=ue(i,s,r,n,t[11],14,643717713),n=ue(n,i,s,r,t[0],20,-373897302),r=ue(r,n,i,s,t[5],5,-701558691),s=ue(s,r,n,i,t[10],9,38016083),i=ue(i,s,r,n,t[15],14,-660478335),n=ue(n,i,s,r,t[4],20,-405537848),r=ue(r,n,i,s,t[9],5,568446438),s=ue(s,r,n,i,t[14],9,-1019803690),i=ue(i,s,r,n,t[3],14,-187363961),n=ue(n,i,s,r,t[8],20,1163531501),r=ue(r,n,i,s,t[13],5,-1444681467),s=ue(s,r,n,i,t[2],9,-51403784),i=ue(i,s,r,n,t[7],14,1735328473),n=ue(n,i,s,r,t[12],20,-1926607734),r=le(r,n,i,s,t[5],4,-378558),s=le(s,r,n,i,t[8],11,-2022574463),i=le(i,s,r,n,t[11],16,1839030562),n=le(n,i,s,r,t[14],23,-35309556),r=le(r,n,i,s,t[1],4,-1530992060),s=le(s,r,n,i,t[4],11,1272893353),i=le(i,s,r,n,t[7],16,-155497632),n=le(n,i,s,r,t[10],23,-1094730640),r=le(r,n,i,s,t[13],4,681279174),s=le(s,r,n,i,t[0],11,-358537222),i=le(i,s,r,n,t[3],16,-722521979),n=le(n,i,s,r,t[6],23,76029189),r=le(r,n,i,s,t[9],4,-640364487),s=le(s,r,n,i,t[12],11,-421815835),i=le(i,s,r,n,t[15],16,530742520),n=le(n,i,s,r,t[2],23,-995338651),r=ye(r,n,i,s,t[0],6,-198630844),s=ye(s,r,n,i,t[7],10,1126891415),i=ye(i,s,r,n,t[14],15,-1416354905),n=ye(n,i,s,r,t[5],21,-57434055),r=ye(r,n,i,s,t[12],6,1700485571),s=ye(s,r,n,i,t[3],10,-1894986606),i=ye(i,s,r,n,t[10],15,-1051523),n=ye(n,i,s,r,t[1],21,-2054922799),r=ye(r,n,i,s,t[8],6,1873313359),s=ye(s,r,n,i,t[15],10,-30611744),i=ye(i,s,r,n,t[6],15,-1560198380),n=ye(n,i,s,r,t[13],21,1309151649),r=ye(r,n,i,s,t[4],6,-145523070),s=ye(s,r,n,i,t[11],10,-1120210379),i=ye(i,s,r,n,t[2],15,718787259),n=ye(n,i,s,r,t[9],21,-343485551),e[0]=de(r,e[0]),e[1]=de(n,e[1]),e[2]=de(i,e[2]),e[3]=de(s,e[3])}function ce(e,t,r,n,i,s){return t=de(de(t,e),de(n,s)),de(t<>>32-i,r)}function he(e,t,r,n,i,s,a){return ce(t&r|~t&n,e,t,i,s,a)}function ue(e,t,r,n,i,s,a){return ce(t&n|r&~n,e,t,i,s,a)}function le(e,t,r,n,i,s,a){return ce(t^r^n,e,t,i,s,a)}function ye(e,t,r,n,i,s,a){return ce(r^(t|~n),e,t,i,s,a)}function fe(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const ge="0123456789abcdef".split("");function pe(e){let t="",r=0;for(;r<4;r++)t+=ge[e>>8*r+4&15]+ge[e>>8*r&15];return t}function de(e,t){return e+t&4294967295}const Ae=F.getWebCrypto(),we=F.getNodeCrypto(),me=we&&we.getHashes();function be(e){if(we&&me.includes(e))return async function(t){const r=we.createHash(e);return v(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function ke(e,t){const r=async()=>{const{nobleHashes:t}=await Promise.resolve().then((function(){return Xl})),r=t.get(e);if(!r)throw Error("Unsupported hash");return r};return async function(e){if(h(e)&&(e=await P(e)),F.isStream(e)){const t=(await r()).create();return v(e,(e=>{t.update(e)}),(()=>t.digest()))}if(Ae&&t)return new Uint8Array(await Ae.digest(t,e));return(await r())(e)}}var Ee={md5:be("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let n;for(n=64;n<=e.length;n+=64)oe(r,fe(e.substring(n-64,n)));e=e.substring(n-64);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(oe(r,i),n=0;n<16;n++)i[n]=0;return i[14]=8*t,oe(r,i),r}(F.uint8ArrayToString(e));return F.hexToUint8Array(function(e){for(let t=0;t0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ie(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Se(e,t){Be(e);const r=t.outputLen;if(e.lengthnew Uint8Array(e.buffer,e.byteOffset,e.byteLength),Ce=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),De=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw Error("Non little-endian hardware is not supported");function Pe(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!ve(e))throw Error("Uint8Array expected, got "+typeof e);e=Le(e)}return e}function Ue(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t);function Qe(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s);e.setUint32(t+0,a,n),e.setUint32(t+4,o,n)}function Re(e){return e.byteOffset%4==0}function Le(e){return Uint8Array.from(e)}function Te(...e){for(let t=0;t(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Oe{constructor(e,t){this.blockLen=Me,this.outputLen=Me,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Be(e=Pe(e),16);const r=De(e);let n=r.getUint32(0,!1),i=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:He(n),s1:He(i),s2:He(s),s3:He(a)}),({s0:n,s1:i,s2:s,s3:a}={s3:(u=s)<<31|(l=a)>>>1,s2:(h=i)<<31|u>>>1,s1:(c=n)<<31|h>>>1,s0:c>>>1^225<<24&-(1&l)});var c,h,u,l;const y=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(y))throw Error(`ghash: wrong window size=${y}, should be 2, 4 or 8`);this.W=y;const f=128/y,g=this.windowSize=2**y,p=[];for(let e=0;e>>y-a-1&1))continue;const{s0:c,s1:h,s2:u,s3:l}=o[y*e+a];r^=c,n^=h,i^=u,s^=l}p.push({s0:r,s1:n,s2:i,s3:s})}this.t=p}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:i,t:s,windowSize:a}=this;let o=0,c=0,h=0,u=0;const l=(1<>>8*e&255;for(let e=8/i-1;e>=0;e--){const r=t>>>i*e&l,{s0:n,s1:f,s2:g,s3:p}=s[y*a+r];o^=n,c^=f,h^=g,u^=p,y+=1}}this.s0=o,this.s1=c,this.s2=h,this.s3=u}update(e){e=Pe(e),Ie(this);const t=Ce(e),r=Math.floor(e.length/Me),n=e.length%Me;for(let e=0;e>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Le(e=Pe(e)));super(r,t),Te(r)}update(e){e=Pe(e),Ie(this);const t=Ce(e),r=e.length%Me,n=Math.floor(e.length/Me);for(let e=0;ee(r,t.length).update(Pe(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const Ge=_e(((e,t)=>new Oe(e,t)));_e(((e,t)=>new ze(e,t)));const je=16,qe=new Uint8Array(je),Ve=283;function Je(e){return e<<1^Ve&-(e>>7)}function Ye(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Je(e);return r}const We=/* @__PURE__ */(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Je(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Te(e),t})(),Ze=/* @__PURE__ */We.map(((e,t)=>We.indexOf(t))),$e=e=>e<<24|e>>>8,Xe=e=>e<<8|e>>>24,et=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function tt(e,t){if(256!==e.length)throw Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,n)=>t(e[n]))),n=r.map(Xe),i=n.map(Xe),s=i.map(Xe),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let h=0;h<256;h++){const u=256*t+h;a[u]=r[t]^n[h],o[u]=i[t]^s[h],c[u]=e[t]<<8|e[h]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:i,T3:s,T01:a,T23:o}}const rt=/* @__PURE__ */tt(We,(e=>Ye(e,3)<<24|e<<16|e<<8|Ye(e,2))),nt=/* @__PURE__ */tt(Ze,(e=>Ye(e,11)<<24|Ye(e,13)<<16|Ye(e,9)<<8|Ye(e,14))),it=/* @__PURE__ */(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Je(r))e[t]=r;return e})();function st(e){Be(e);const t=e.length;if(![16,24,32].includes(t))throw Error("aes: wrong key size: should be 16, 24 or 32, got: "+t);const{sbox2:r}=rt,n=[];Re(e)||n.push(e=Le(e));const i=Ce(e),s=i.length,a=e=>ct(r,e,e,e,e),o=new Uint32Array(t+28);o.set(i);for(let e=s;e6&&e%s==4&&(t=a(t)),o[e]=o[e-s]^t}return Te(...n),o}function at(e){const t=st(e),r=t.slice(),n=t.length,{sbox2:i}=rt,{T0:s,T1:a,T2:o,T3:c}=nt;for(let e=0;e>>8&255]^o[n>>>16&255]^c[n>>>24]}return r}function ot(e,t,r,n,i,s){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|s>>>24&255]}function ct(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function ht(e,t,r,n,i){const{sbox2:s,T01:a,T23:o}=rt;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],i^=e[c++];const h=e.length/4-2;for(let s=0;s=0;e--)r=r+(255&s[e])|0,s[e]=255&r,r>>>=8;({s0:o,s1:c,s2:h,s3:u}=ht(e,a[0],a[1],a[2],a[3]))}const f=je*Math.floor(l.length/4);if(f>>0,o.setUint32(u,y,t),({s0:f,s1:g,s2:p,s3:d}=ht(e,a[0],a[1],a[2],a[3]));const A=je*Math.floor(c.length/4);if(Ar(e,t),decrypt:(e,t)=>r(e,t)}}));const pt=xe({blockSize:16,nonceLength:16},(function(e,t,r={}){Be(e),Be(t,16);const n=!r.disablePadding;return{encrypt(r,i){const s=st(e),{b:a,o,out:c}=function(e,t,r){Be(e);let n=e.length;const i=n%je;if(!t&&0!==i)throw Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Re(e)||(e=Le(e));const s=Ce(e);if(t){let e=je-i;e||(e=je),n+=e}const a=lt(n,r);return{b:s,o:Ce(a),out:a}}(r,n,i);let h=t;const u=[s];Re(h)||u.push(h=Le(h));const l=Ce(h);let y=l[0],f=l[1],g=l[2],p=l[3],d=0;for(;d+4<=a.length;)y^=a[d+0],f^=a[d+1],g^=a[d+2],p^=a[d+3],({s0:y,s1:f,s2:g,s3:p}=ht(s,y,f,g,p)),o[d++]=y,o[d++]=f,o[d++]=g,o[d++]=p;if(n){const e=function(e){const t=new Uint8Array(16),r=Ce(t);t.set(e);const n=je-e.length;for(let e=je-n;e16)throw Error("aes/pcks5: wrong padding");const i=e.subarray(0,-n);for(let t=0;tr(e,!0,t),decrypt:(e,t)=>r(e,!1,t)}}));const At=xe({blockSize:16,nonceLength:12,tagLength:16},(function(e,t,r){if(Be(e),Be(t),void 0!==r&&Be(r),t.length<8)throw Error("aes/gcm: invalid nonce length");const n=16;function i(e,t,n){const i=function(e,t,r,n,i){const s=null==i?0:i.length,a=e.create(r,n.length+s);i&&a.update(i),a.update(n);const o=new Uint8Array(16),c=De(o);i&&Qe(c,0,BigInt(8*s),t),Qe(c,8,BigInt(8*n.length),t),a.update(o);const h=a.digest();return Te(o),h}(Ge,!1,e,n,r);for(let e=0;e=2**32)throw Error("plaintext should be less than 4gb");const r=st(e);if(16===t.length)mt(r,t);else{const e=Ce(t);let n=e[0],i=e[1];for(let t=0,s=1;t<6;t++)for(let t=2;t=2**32)throw Error("ciphertext should be less than 4gb");const r=at(e),n=t.length/8-1;if(1===n)bt(r,t);else{const e=Ce(t);let i=e[0],s=e[1];for(let t=0,a=6*n;t<6;t++)for(let t=2*n;t>=1;t-=2,a--){s^=et(a);const{s0:n,s1:o,s2:c,s3:h}=ut(r,i,s,e[t],e[t+1]);i=n,s=o,e[t]=c,e[t+1]=h}e[0]=i,e[1]=s}r.fill(0)}},Et=new Uint8Array(8).fill(166),vt=xe({blockSize:8},(e=>({encrypt(t){if(Be(t),!t.length||t.length%8!=0)throw Error("invalid plaintext length");if(8===t.length)throw Error("8-byte keys not allowed in AESKW, use AESKWP instead");const r=function(...e){let t=0;for(let r=0;r!0),(()=>!1))}async _runCBC(e,t){const r="AES-CBC";this.keyRef=this.keyRef||await It.importKey("raw",this.key,r,!1,["encrypt"]);const n=await It.encrypt({name:r,iv:t||this.zeroBlock},this.keyRef,e);return new Uint8Array(n).subarray(0,e.length)}async encryptChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=F.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=F.concatUint8Array([this.prevBlock,n.subarray(0,n.length-this.blockSize)]),s=await this._runCBC(i);return Ut(s,n),this.prevBlock=s.slice(-this.blockSize),r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,s}let n;if(this.i+=r.length,this.i===this.nextBlock.length){const t=this.nextBlock;n=await this._runCBC(this.prevBlock),Ut(n,t),this.prevBlock=n.slice(),this.i=0;const i=e.subarray(r.length);this.nextBlock.set(i,this.i),this.i+=i.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{this.nextBlock=this.nextBlock.subarray(0,this.i);const t=this.nextBlock,r=await this._runCBC(this.prevBlock);Ut(r,t),e=r.subarray(0,t.length)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.keyRef=null,this.key=null}async encrypt(e){const t=(await this._runCBC(F.concatUint8Array([new Uint8Array(this.blockSize),e]),this.iv)).subarray(0,e.length);return Ut(t,e),this.clearSensitiveData(),t}}class Pt{constructor(e,t,r,n){this.forEncryption=e;const{blockSize:i}=se(t);this.key=Bt.expandKeyLE(r),n.byteOffset%4!=0&&(n=n.slice()),this.prevBlock=xt(n),this.nextBlock=new Uint8Array(i),this.i=0,this.blockSize=i}_runCFB(e){const t=xt(e),r=new Uint8Array(e.length),n=xt(r);for(let e=0;e+4<=n.length;e+=4){const{s0:r,s1:i,s2:s,s3:a}=Bt.encrypt(this.key,this.prevBlock[0],this.prevBlock[1],this.prevBlock[2],this.prevBlock[3]);n[e+0]=t[e+0]^r,n[e+1]=t[e+1]^i,n[e+2]=t[e+2]^s,n[e+3]=t[e+3]^a,this.prevBlock=(this.forEncryption?n:t).slice(e,e+4)}return r}async processChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=F.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=this._runCFB(n);return r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,i}let n;if(this.i+=r.length,this.i===this.nextBlock.length){n=this._runCFB(this.nextBlock),this.i=0;const t=e.subarray(r.length);this.nextBlock.set(t,this.i),this.i+=t.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{e=this._runCFB(this.nextBlock).subarray(0,this.i)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.key.fill(0)}}function Ut(e,t){const r=Math.min(e.length,t.length);for(let n=0;nnew Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));var Qt=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n){const i=T.read(T.symmetric,e);if(St&&Ct[i])return function(e,t,r,n){const i=T.read(T.symmetric,e),s=new St.createDecipheriv(Ct[i],t,n);return v(r,(e=>new Uint8Array(s.update(e))))}(e,t,r,n);if(F.isAES(e))return async function(e,t,r,n){if(F.isStream(r)){const i=new Pt(!1,e,t,n);return v(r,(e=>i.processChunk(e)),(()=>i.finish()))}return dt(t,n).decrypt(r)}(e,t,r,n);const s=new(await re(e))(t),a=s.blockSize;let o=n,c=new Uint8Array;const h=e=>{e&&(c=F.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,n=0;for(;e?c.length>=a:c.length;){const e=s.encrypt(o);for(o=c.subarray(0,a),r=0;rnew Uint8Array(s.update(e))))}(e,t,r,n);if(F.isAES(e))return async function(e,t,r,n){if(It&&await Dt.isSupported(e)){const i=new Dt(e,t,n);return F.isStream(r)?v(r,(e=>i.encryptChunk(e)),(()=>i.finish())):i.encrypt(r)}if(F.isStream(r)){const i=new Pt(!0,e,t,n);return v(r,(e=>i.processChunk(e)),(()=>i.finish()))}return dt(t,n).encrypt(r)}(e,t,r,n);const a=new(await re(e))(t),o=a.blockSize,c=n.slice();let h=new Uint8Array;const u=e=>{e&&(h=F.concatUint8Array([h,e]));const t=new Uint8Array(h.length);let r,n=0;for(;e?h.length>=o:h.length;){const e=a.encrypt(c);for(r=0;ri.encrypt(e),a=e=>i.decrypt(e);let o;function c(e,t,r,i){const a=t.length/Xt|0;!function(e,t){const r=F.nbits(Math.max(e.length,t.length)/Xt|0)-1;for(let e=n+1;e<=r;e++)o[e]=F.double(o[e-1]);n=r}(t,i);const c=F.concatUint8Array([ir.subarray(0,15-r.length),sr,r]),h=63&c[15];c[15]&=192;const u=s(c),l=F.concatUint8Array([u,nr(u.subarray(0,8),u.subarray(1,9))]),y=F.shiftRight(l.subarray(0+(h>>3),17+(h>>3)),8-(7&h)).subarray(1),f=new Uint8Array(Xt),g=new Uint8Array(t.length+er);let p,d=0;for(p=0;p{r+=t[e>>4]+t[15&e]})),BigInt("0x0"+r)}function Ar(e,t){const r=e%t;return rgr;){const e=n≺n>>=pr;s=e?s*i%r:s,i=i*i%r}return s}function mr(e){return e>=gr?e:-e}function br(e,t){const{gcd:r,x:n}=function(e,t){let r=BigInt(0),n=BigInt(1),i=BigInt(1),s=BigInt(0),a=mr(e),o=mr(t);const c=eNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return t}function Er(e,t){return(e>>BigInt(t)&pr)===gr?0:1}function vr(e){const t=e>=pr)!==t;)r++;return r}function Br(e){const t=e>=r)!==t;)n++;return n}function Ir(e,t="be",r){let n=e.toString(16);n.length%2==1&&(n="0"+n);const i=n.length/2,s=new Uint8Array(r||i),a=r?r-i:0;let o=0;for(;oe&&(a=Ar(a,i<Ar(e,r)!==t))}(e)&&(!!function(e,t=BigInt(2)){return wr(t,e-Pr,e)===Pr}(e)&&!!function(e,t){const r=vr(e);t||(t=Math.max(1,r/48|0));const n=e-Pr;let i=0;for(;!Er(n,i);)i++;const s=e>>BigInt(i);for(;t>0;t--){let t,r=wr(Cr(BigInt(2),n),s,e);if(r!==Pr&&r!==n){for(t=1;tBigInt(e)));const Rr=[];function Lr(e,t){const r=e.length;if(r>t-11)throw Error("Message too long");const n=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!n;if(t)return F.selectUint8Array(a,s,t);if(a)return s;throw Error("Decryption error")}function Mr(e,t,r){let n;if(t.length!==Ee.getHashByteLength(e))throw Error("Invalid hash length");const i=new Uint8Array(Rr[e].length);for(n=0;n=t)throw Error("Data too large.");const c=Ar(n,s-Or),h=Ar(n,i-Or),u=Cr(BigInt(2),t),l=wr(br(u,t),r,t);e=Ar(e*l,t);const y=wr(e,h,i),f=wr(e,c,s),g=Ar(a*(f-y),s);let p=g*i+y;return p=Ar(p*u,t),Tr(Ir(p,"be",Br(t)),o)}(e,t,r,n,i,s,a,o)},encrypt:async function(e,t,r){return F.getNodeCrypto()?async function(e,t,r){const n=_r(t,r),i={key:n,format:"jwk",type:"pkcs1",padding:Hr.constants.RSA_PKCS1_PADDING};return new Uint8Array(Hr.publicEncrypt(i,e))}(e,t,r):async function(e,t,r){if(t=dr(t),e=dr(Lr(e,Br(t))),r=dr(r),e>=t)throw Error("Message size cannot exceed modulus size");return Ir(wr(e,r,t),"be",Br(t))}(e,t,r)},generate:async function(e,t){if(t=BigInt(t),F.getWebCrypto()){const r={name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ir(t),hash:{name:"SHA-1"}},n=await Fr.generateKey(r,!0,["sign","verify"]);return Gr(await Fr.exportKey("jwk",n.privateKey),t)}if(F.getNodeCrypto()){const r={modulusLength:e,publicExponent:kr(t),publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}},n=await new Promise(((e,t)=>{Hr.generateKeyPair("rsa",r,((r,n,i)=>{r?t(r):e(i)}))}));return Gr(n,t)}let r,n,i;do{n=Ur(e-(e>>1),t,40),r=Ur(e>>1,t,40),i=r*n}while(vr(i)!==e);const s=(r-Or)*(n-Or);return n=r.length)throw Error("Digest size cannot exceed key modulus size");if(t&&!F.isStream(t))if(F.getWebCrypto())try{return await async function(e,t,r,n,i,s,a,o){const c=await zr(r,n,i,s,a,o),h={name:"RSASSA-PKCS1-v1_5",hash:{name:e}},u=await Fr.importKey("jwk",c,h,!1,["sign"]);return new Uint8Array(await Fr.sign("RSASSA-PKCS1-v1_5",u,t))}(T.read(T.webHash,e),t,r,n,i,s,a,o)}catch(e){F.printDebugError(e)}else if(F.getNodeCrypto())return async function(e,t,r,n,i,s,a,o){const c=Hr.createSign(T.read(T.hash,e));c.write(t),c.end();const h=await zr(r,n,i,s,a,o);return new Uint8Array(c.sign({key:h,format:"jwk",type:"pkcs1"}))}(e,t,r,n,i,s,a,o);return async function(e,t,r,n){t=dr(t);const i=dr(Mr(e,n,Br(t)));return r=dr(r),Ir(wr(i,r,t),"be",Br(t))}(e,r,i,c)},validateParams:async function(e,t,r,n,i,s){if(e=dr(e),(n=dr(n))*(i=dr(i))!==e)return!1;const a=BigInt(2);if(Ar(n*(s=dr(s)),i)!==BigInt(1))return!1;t=dr(t),r=dr(r);const o=Cr(a,a<=r)throw Error("Signature size cannot exceed modulus size");const s=Ir(wr(t,n,r),"be",Br(r)),a=Mr(e,i,Br(r));return F.equalsUint8Array(s,a)}(e,r,n,i,s)}});const qr=BigInt(1);var Vr=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i){return e=dr(e),t=dr(t),r=dr(r),Tr(Ir(Ar(br(wr(e,n=dr(n),r),r)*t,r),"be",Br(r)),i)},encrypt:async function(e,t,r,n){t=dr(t),r=dr(r),n=dr(n);const i=dr(Lr(e,Br(t))),s=Cr(qr,t-qr);return{c1:Ir(wr(r,s,t)),c2:Ir(Ar(wr(n,s,t)*i,t))}},validateParams:async function(e,t,r,n){if(e=dr(e),t=dr(t),r=dr(r),t<=qr||t>=e)return!1;const i=BigInt(vr(e));if(i>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function hn(e,t,r,n){return function(e,t,r,n,i){var s,a=0;for(s=0;s>>8)-1}(e,t,r,n,32)}function un(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function ln(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function yn(e,t,r){for(var n,i=~(r-1),s=0;s<16;s++)n=i&(e[s]^t[s]),e[s]^=n,t[s]^=n}function fn(e,t){var r,n,i,s=Wr(),a=Wr();for(r=0;r<16;r++)a[r]=t[r];for(ln(a),ln(a),ln(a),n=0;n<2;n++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,yn(a,s,1-i)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function gn(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return fn(r,e),fn(n,t),hn(r,0,n,0)}function pn(e){var t=new Uint8Array(32);return fn(t,e),1&t[0]}function dn(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function An(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function wn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function mn(e,t,r){var n,i,s=0,a=0,o=0,c=0,h=0,u=0,l=0,y=0,f=0,g=0,p=0,d=0,A=0,w=0,m=0,b=0,k=0,E=0,v=0,B=0,I=0,S=0,K=0,C=0,D=0,P=0,U=0,x=0,Q=0,R=0,L=0,T=r[0],M=r[1],N=r[2],F=r[3],H=r[4],O=r[5],z=r[6],_=r[7],G=r[8],j=r[9],q=r[10],V=r[11],J=r[12],Y=r[13],W=r[14],Z=r[15];s+=(n=t[0])*T,a+=n*M,o+=n*N,c+=n*F,h+=n*H,u+=n*O,l+=n*z,y+=n*_,f+=n*G,g+=n*j,p+=n*q,d+=n*V,A+=n*J,w+=n*Y,m+=n*W,b+=n*Z,a+=(n=t[1])*T,o+=n*M,c+=n*N,h+=n*F,u+=n*H,l+=n*O,y+=n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*Z,p+=(n=t[10])*T,d+=n*M,A+=n*N,w+=n*F,m+=n*H,b+=n*O,k+=n*z,E+=n*_,v+=n*G,B+=n*j,I+=n*q,S+=n*V,K+=n*J,C+=n*Y,D+=n*W,P+=n*Z,d+=(n=t[11])*T,A+=n*M,w+=n*N,m+=n*F,b+=n*H,k+=n*O,E+=n*z,v+=n*_,B+=n*G,I+=n*j,S+=n*q,K+=n*V,C+=n*J,D+=n*Y,P+=n*W,U+=n*Z,A+=(n=t[12])*T,w+=n*M,m+=n*N,b+=n*F,k+=n*H,E+=n*O,v+=n*z,B+=n*_,I+=n*G,S+=n*j,K+=n*q,C+=n*V,D+=n*J,P+=n*Y,U+=n*W,x+=n*Z,w+=(n=t[13])*T,m+=n*M,b+=n*N,k+=n*F,E+=n*H,v+=n*O,B+=n*z,I+=n*_,S+=n*G,K+=n*j,C+=n*q,D+=n*V,P+=n*J,U+=n*Y,x+=n*W,Q+=n*Z,m+=(n=t[14])*T,b+=n*M,k+=n*N,E+=n*F,v+=n*H,B+=n*O,I+=n*z,S+=n*_,K+=n*G,C+=n*j,D+=n*q,P+=n*V,U+=n*J,x+=n*Y,Q+=n*W,R+=n*Z,b+=(n=t[15])*T,a+=38*(E+=n*N),o+=38*(v+=n*F),c+=38*(B+=n*H),h+=38*(I+=n*O),u+=38*(S+=n*z),l+=38*(K+=n*_),y+=38*(C+=n*G),f+=38*(D+=n*j),g+=38*(P+=n*q),p+=38*(U+=n*V),d+=38*(x+=n*J),A+=38*(Q+=n*Y),w+=38*(R+=n*W),m+=38*(L+=n*Z),s=(n=(s+=38*(k+=n*M))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=(s+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=c,e[4]=h,e[5]=u,e[6]=l,e[7]=y,e[8]=f,e[9]=g,e[10]=p,e[11]=d,e[12]=A,e[13]=w,e[14]=m,e[15]=b}function bn(e,t){mn(e,t,t)}function kn(e,t){var r,n=Wr();for(r=0;r<16;r++)n[r]=t[r];for(r=253;r>=0;r--)bn(n,n),2!==r&&4!==r&&mn(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}function En(e,t,r){var n,i,s=new Uint8Array(32),a=new Float64Array(80),o=Wr(),c=Wr(),h=Wr(),u=Wr(),l=Wr(),y=Wr();for(i=0;i<31;i++)s[i]=t[i];for(s[31]=127&t[31]|64,s[0]&=248,dn(a,r),i=0;i<16;i++)c[i]=a[i],u[i]=o[i]=h[i]=0;for(o[0]=u[0]=1,i=254;i>=0;--i)yn(o,c,n=s[i>>>3]>>>(7&i)&1),yn(h,u,n),An(l,o,h),wn(o,o,h),An(h,c,u),wn(c,c,u),bn(u,l),bn(y,o),mn(o,h,o),mn(h,c,l),An(l,o,h),wn(o,o,h),bn(c,o),wn(h,u,y),mn(o,h,tn),An(o,o,u),mn(h,h,o),mn(o,u,y),mn(u,c,a),bn(c,l),yn(o,c,n),yn(h,u,n);for(i=0;i<16;i++)a[i+16]=o[i],a[i+32]=h[i],a[i+48]=c[i],a[i+64]=u[i];var f=a.subarray(32),g=a.subarray(16);return kn(f,f),mn(g,g,f),fn(e,g),0}function vn(e,t){return En(e,t,$r)}var Bn=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function In(e,t,r,n){for(var i,s,a,o,c,h,u,l,y,f,g,p,d,A,w,m,b,k,E,v,B,I,S,K,C,D,P=new Int32Array(16),U=new Int32Array(16),x=e[0],Q=e[1],R=e[2],L=e[3],T=e[4],M=e[5],N=e[6],F=e[7],H=t[0],O=t[1],z=t[2],_=t[3],G=t[4],j=t[5],q=t[6],V=t[7],J=0;n>=128;){for(E=0;E<16;E++)v=8*E+J,P[E]=r[v+0]<<24|r[v+1]<<16|r[v+2]<<8|r[v+3],U[E]=r[v+4]<<24|r[v+5]<<16|r[v+6]<<8|r[v+7];for(E=0;E<80;E++)if(i=x,s=Q,a=R,o=L,c=T,h=M,u=N,F,y=H,f=O,g=z,p=_,d=G,A=j,w=q,V,S=65535&(I=V),K=I>>>16,C=65535&(B=F),D=B>>>16,S+=65535&(I=(G>>>14|T<<18)^(G>>>18|T<<14)^(T>>>9|G<<23)),K+=I>>>16,C+=65535&(B=(T>>>14|G<<18)^(T>>>18|G<<14)^(G>>>9|T<<23)),D+=B>>>16,S+=65535&(I=G&j^~G&q),K+=I>>>16,C+=65535&(B=T&M^~T&N),D+=B>>>16,B=Bn[2*E],S+=65535&(I=Bn[2*E+1]),K+=I>>>16,C+=65535&B,D+=B>>>16,B=P[E%16],K+=(I=U[E%16])>>>16,C+=65535&B,D+=B>>>16,C+=(K+=(S+=65535&I)>>>16)>>>16,S=65535&(I=k=65535&S|K<<16),K=I>>>16,C=65535&(B=b=65535&C|(D+=C>>>16)<<16),D=B>>>16,S+=65535&(I=(H>>>28|x<<4)^(x>>>2|H<<30)^(x>>>7|H<<25)),K+=I>>>16,C+=65535&(B=(x>>>28|H<<4)^(H>>>2|x<<30)^(H>>>7|x<<25)),D+=B>>>16,K+=(I=H&O^H&z^O&z)>>>16,C+=65535&(B=x&Q^x&R^Q&R),D+=B>>>16,l=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(D+=C>>>16)<<16,m=65535&S|K<<16,S=65535&(I=p),K=I>>>16,C=65535&(B=o),D=B>>>16,K+=(I=k)>>>16,C+=65535&(B=b),D+=B>>>16,Q=i,R=s,L=a,T=o=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(D+=C>>>16)<<16,M=c,N=h,F=u,x=l,O=y,z=f,_=g,G=p=65535&S|K<<16,j=d,q=A,V=w,H=m,E%16==15)for(v=0;v<16;v++)B=P[v],S=65535&(I=U[v]),K=I>>>16,C=65535&B,D=B>>>16,B=P[(v+9)%16],S+=65535&(I=U[(v+9)%16]),K+=I>>>16,C+=65535&B,D+=B>>>16,b=P[(v+1)%16],S+=65535&(I=((k=U[(v+1)%16])>>>1|b<<31)^(k>>>8|b<<24)^(k>>>7|b<<25)),K+=I>>>16,C+=65535&(B=(b>>>1|k<<31)^(b>>>8|k<<24)^b>>>7),D+=B>>>16,b=P[(v+14)%16],K+=(I=((k=U[(v+14)%16])>>>19|b<<13)^(b>>>29|k<<3)^(k>>>6|b<<26))>>>16,C+=65535&(B=(b>>>19|k<<13)^(k>>>29|b<<3)^b>>>6),D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,P[v]=65535&C|D<<16,U[v]=65535&S|K<<16;S=65535&(I=H),K=I>>>16,C=65535&(B=x),D=B>>>16,B=e[0],K+=(I=t[0])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[0]=x=65535&C|D<<16,t[0]=H=65535&S|K<<16,S=65535&(I=O),K=I>>>16,C=65535&(B=Q),D=B>>>16,B=e[1],K+=(I=t[1])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[1]=Q=65535&C|D<<16,t[1]=O=65535&S|K<<16,S=65535&(I=z),K=I>>>16,C=65535&(B=R),D=B>>>16,B=e[2],K+=(I=t[2])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[2]=R=65535&C|D<<16,t[2]=z=65535&S|K<<16,S=65535&(I=_),K=I>>>16,C=65535&(B=L),D=B>>>16,B=e[3],K+=(I=t[3])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[3]=L=65535&C|D<<16,t[3]=_=65535&S|K<<16,S=65535&(I=G),K=I>>>16,C=65535&(B=T),D=B>>>16,B=e[4],K+=(I=t[4])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[4]=T=65535&C|D<<16,t[4]=G=65535&S|K<<16,S=65535&(I=j),K=I>>>16,C=65535&(B=M),D=B>>>16,B=e[5],K+=(I=t[5])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[5]=M=65535&C|D<<16,t[5]=j=65535&S|K<<16,S=65535&(I=q),K=I>>>16,C=65535&(B=N),D=B>>>16,B=e[6],K+=(I=t[6])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[6]=N=65535&C|D<<16,t[6]=q=65535&S|K<<16,S=65535&(I=V),K=I>>>16,C=65535&(B=F),D=B>>>16,B=e[7],K+=(I=t[7])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[7]=F=65535&C|D<<16,t[7]=V=65535&S|K<<16,J+=128,n-=128}return n}function Sn(e,t,r){var n,i=new Int32Array(8),s=new Int32Array(8),a=new Uint8Array(256),o=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,In(i,s,t,r),r%=128,n=0;n=0;--i)Cn(e,t,n=r[i/8|0]>>(7&i)&1),Kn(t,e),Kn(e,e),Cn(e,t,n)}function Un(e,t){var r=[Wr(),Wr(),Wr(),Wr()];un(r[0],sn),un(r[1],an),un(r[2],en),mn(r[3],sn,an),Pn(e,r,t)}function xn(e,t,r){var n,i=new Uint8Array(64),s=[Wr(),Wr(),Wr(),Wr()];for(r||Zr(t,32),Sn(i,t,32),i[0]&=248,i[31]&=127,i[31]|=64,Un(s,i),Dn(e,s),n=0;n<32;n++)t[n+32]=e[n];return 0}var Qn=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Rn(e,t){var r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*Qn[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*Qn[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function Ln(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;Rn(e,r)}function Tn(e,t){var r=Wr(),n=Wr(),i=Wr(),s=Wr(),a=Wr(),o=Wr(),c=Wr();return un(e[2],en),dn(e[1],t),bn(i,e[1]),mn(s,i,rn),wn(i,i,e[2]),An(s,e[2],s),bn(a,s),bn(o,a),mn(c,o,a),mn(r,c,i),mn(r,r,s),function(e,t){var r,n=Wr();for(r=0;r<16;r++)n[r]=t[r];for(r=250;r>=0;r--)bn(n,n),1!==r&&mn(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}(r,r),mn(r,r,i),mn(r,r,s),mn(r,r,s),mn(e[0],r,s),bn(n,e[0]),mn(n,n,s),gn(n,i)&&mn(e[0],e[0],on),bn(n,e[0]),mn(n,n,s),gn(n,i)?-1:(pn(e[0])===t[31]>>7&&wn(e[0],Xr,e[0]),mn(e[3],e[0],e[1]),0)}var Mn=64;function Nn(){for(var e=0;e=0},Yr.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return xn(e,t),{publicKey:e,secretKey:t}},Yr.sign.keyPair.fromSecretKey=function(e){if(Nn(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;r=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return F.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return F.uint8ArrayToHex(this.oid)}getName(){const e=Fn[this.toHex()];if(!e)throw Error("Unknown curve object identifier.");return e}}function On(e){let t,r=0;const n=e[0];return n<192?([r]=e,t=1):n<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===n&&(r=F.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function zn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):F.concatUint8Array([new Uint8Array([255]),F.writeNumber(e,4)])}function _n(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function Gn(e){return new Uint8Array([192|e])}function jn(e,t){return F.concatUint8Array([Gn(e),zn(t)])}function qn(e){return[T.packet.literalData,T.packet.compressedData,T.packet.symmetricallyEncryptedData,T.packet.symEncryptedIntegrityProtectedData,T.packet.aeadEncryptedData].includes(e)}async function Vn(e,t){const r=Q(e);let n,i;try{const s=await r.peekBytes(2);if(!s||s.length<2||!(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const a=await r.readByte();let o,h,u=-1,l=-1;l=0,64&a&&(l=1),l?u=63&a:(u=(63&a)>>2,h=3&a);const y=qn(u);let f,g=null;if(y){if("array"===F.isStream(e)){const e=new c;n=R(e),g=e}else{const e=new TransformStream;n=R(e.writable),g=e.readable}i=t({tag:u,packet:g})}else g=[];do{if(l){const e=await r.readByte();if(f=!1,e<192)o=e;else if(e>=192&&e<224)o=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(o=1<<(31&e),f=!0,!y)throw new TypeError("This packet type does not support partial lengths.")}else o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(h){case 0:o=await r.readByte();break;case 1:o=await r.readByte()<<8|await r.readByte();break;case 2:o=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:o=1/0}if(o>0){let e=0;for(;;){n&&await n.ready;const{done:t,value:i}=await r.read();if(t){if(o===1/0)break;throw Error("Unexpected end of packet")}const s=o===1/0?i:i.subarray(0,o-e);if(n?await n.write(s):g.push(s),e+=i.length,e>=o){r.unshift(i.subarray(o-e+i.length));break}}}}while(f);const p=await r.peekBytes(y?1/0:2);return n?(await n.ready,await n.close()):(g=F.concatUint8Array(g),await t({tag:u,packet:g})),!p||!p.length}catch(e){if(n)return await n.abort(e),!0;throw e}finally{n&&await i,r.releaseLock()}}class Jn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Jn),this.name="UnsupportedError"}}class Yn extends Jn{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Jn),this.name="UnknownPacketError"}}class Wn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}async function Zn(e){switch(e){case T.publicKey.ed25519:try{const e=F.getWebCrypto(),t=await e.generateKey("Ed25519",!0,["sign","verify"]),r=await e.exportKey("jwk",t.privateKey),n=await e.exportKey("jwk",t.publicKey);return{A:new Uint8Array(j(n.x)),seed:j(r.d)}}catch(t){if("NotSupportedError"!==t.name&&"OperationError"!==t.name)throw t;const r=Kr(ei(e)),{publicKey:n}=Yr.sign.keyPair.fromSeed(r);return{A:n,seed:r}}case T.publicKey.ed448:{const e=await F.getNobleCurve(T.publicKey.ed448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),seed:t}}default:throw Error("Unsupported EdDSA algorithm")}}async function $n(e,t,r,n,i,s){if(Ee.getHashByteLength(t){if(e===T.publicKey.ed25519){return{kty:"OKP",crv:"Ed25519",x:q(t),ext:!0}}throw Error("Unsupported EdDSA algorithm")},ni=(e,t,r)=>{if(e===T.publicKey.ed25519){const n=ri(e,t);return n.d=q(r),n}throw Error("Unsupported EdDSA algorithm")};var ii=/*#__PURE__*/Object.freeze({__proto__:null,generate:Zn,getPayloadSize:ei,getPreferredHashAlgo:ti,sign:$n,validateParams:async function(e,t,r){switch(e){case T.publicKey.ed25519:{const{publicKey:e}=Yr.sign.keyPair.fromSeed(r);return F.equalsUint8Array(t,e)}case T.publicKey.ed448:{const e=(await F.getNobleCurve(T.publicKey.ed448)).getPublicKey(r);return F.equalsUint8Array(t,e)}default:return!1}},verify:Xn});const si=F.getWebCrypto();async function ai(e,t,r){const{keySize:n}=se(e);if(!F.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");try{const e=await si.importKey("raw",t,{name:"AES-KW"},!1,["wrapKey"]),n=await si.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!0,["sign"]),i=await si.wrapKey("raw",n,e,{name:"AES-KW"});return new Uint8Array(i)}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;F.printDebugError("Browser did not support operation: "+e.message)}return vt(t).encrypt(r)}async function oi(e,t,r){const{keySize:n}=se(e);if(!F.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");let i;try{i=await si.importKey("raw",t,{name:"AES-KW"},!1,["unwrapKey"])}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;return F.printDebugError("Browser did not support operation: "+e.message),vt(t).decrypt(r)}try{const e=await si.unwrapKey("raw",r,i,{name:"AES-KW"},{name:"HMAC",hash:"SHA-256"},!0,["sign"]);return new Uint8Array(await si.exportKey("raw",e))}catch(e){if("OperationError"===e.name)throw Error("Key Data Integrity failed");throw e}}var ci=/*#__PURE__*/Object.freeze({__proto__:null,unwrap:oi,wrap:ai});const hi=F.getWebCrypto();async function ui(e,t,r,n,i){const s=T.read(T.webHash,e);if(!s)throw Error("Hash algo not supported with HKDF");const a=await hi.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await hi.deriveBits({name:"HKDF",hash:s,salt:r,info:n},a,8*i);return new Uint8Array(o)}const li={x25519:F.encodeUTF8("OpenPGP X25519"),x448:F.encodeUTF8("OpenPGP X448")};async function yi(e){switch(e){case T.publicKey.x25519:{const e=Kr(32),{publicKey:t}=Yr.box.keyPair.fromSecretKey(e);return{A:t,k:e}}case T.publicKey.x448:{const e=await F.getNobleCurve(T.publicKey.x448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),k:t}}default:throw Error("Unsupported ECDH algorithm")}}function fi(e){switch(e){case T.publicKey.x25519:return 32;case T.publicKey.x448:return 56;default:throw Error("Unsupported ECDH algorithm")}}async function gi(e,t){switch(e){case T.publicKey.x25519:{const r=Kr(fi(e)),n=Yr.scalarMult(r,t);di(n);const{publicKey:i}=Yr.box.keyPair.fromSecretKey(r);return{ephemeralPublicKey:i,sharedSecret:n}}case T.publicKey.x448:{const e=await F.getNobleCurve(T.publicKey.x448),r=e.utils.randomPrivateKey(),n=e.getSharedSecret(r,t);di(n);return{ephemeralPublicKey:e.getPublicKey(r),sharedSecret:n}}default:throw Error("Unsupported ECDH algorithm")}}async function pi(e,t,r,n){switch(e){case T.publicKey.x25519:{const e=Yr.scalarMult(n,t);return di(e),e}case T.publicKey.x448:{const e=(await F.getNobleCurve(T.publicKey.x448)).getSharedSecret(n,t);return di(e),e}default:throw Error("Unsupported ECDH algorithm")}}function di(e){let t=0;for(let r=0;r0===s[0]&&Li(a,r,s.subarray(1),i);if(n&&!F.isStream(n))switch(a.type){case"web":try{const e=await async function(e,t,{r,s:n},i,s){const a=Di(e.payloadSize,bi[e.name],s),o=await Ui.importKey("jwk",a,{name:"ECDSA",namedCurve:bi[e.name],hash:{name:T.read(T.webHash,e.hash)}},!1,["verify"]),c=F.concatUint8Array([r,n]).buffer;return Ui.verify({name:"ECDSA",namedCurve:bi[e.name],hash:{name:T.read(T.webHash,t)}},o,c,i)}(a,t,r,n,i);return e||o()}catch(e){if("nistP521"!==a.name&&("DataError"===e.name||"OperationError"===e.name))throw e;F.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":{const e=await async function(e,t,{r,s:n},i,s){const a=F.nodeRequire("eckey-utils"),o=F.getNodeBuffer(),{publicKey:c}=a.generateDer({curveName:Ei[e.name],publicKey:o.from(s)}),h=xi.createVerify(T.read(T.hash,t));h.write(i),h.end();const u=F.concatUint8Array([r,n]);try{return h.verify({key:c,format:"der",type:"spki",dsaEncoding:"ieee-p1363"},u)}catch(e){return!1}}(a,t,r,n,i);return e||o()}}return await Li(a,r,s,i)||o()}async function Li(e,t,r,n){return(await F.getNobleCurve(T.publicKey.ecdsa,e.name)).verify(F.concatUint8Array([t.r,t.s]),r,n,{lowS:!1})}var Ti=/*#__PURE__*/Object.freeze({__proto__:null,sign:Qi,validateParams:async function(e,t,r){const n=new Bi(e);if(n.keyType!==T.publicKey.ecdsa)return!1;switch(n.type){case"web":case"node":{const n=Kr(8),i=T.hash.sha256,s=await Ee.digest(i,n);try{const a=await Qi(e,i,n,t,r,s);return await Ri(e,i,a,n,t,s)}catch(e){return!1}}default:return Ii(T.publicKey.ecdsa,e,t,r)}},verify:Ri});var Mi=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){if(Si(new Bi(e),n),Ee.getHashByteLength(t)0){const r=e[t-1];if(r>=1){const n=e.subarray(t-r),i=new Uint8Array(r).fill(r);if(F.equalsUint8Array(n,i))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Hi=/*#__PURE__*/Object.freeze({__proto__:null,decode:Fi,encode:Ni});const Oi=F.getWebCrypto(),zi=F.getNodeCrypto();function _i(e,t,r,n){return F.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),F.stringToUint8Array("Anonymous Sender "),n])}async function Gi(e,t,r,n,i=!1,s=!1){let a;if(i){for(a=0;a=0&&0===t[a];a--);t=t.subarray(0,a+1)}return(await Ee.digest(e,F.concatUint8Array([new Uint8Array([0,0,0,1]),t,n]))).subarray(0,r)}async function ji(e,t){switch(e.type){case"curve25519Legacy":{const{sharedSecret:r,ephemeralPublicKey:n}=await gi(T.publicKey.x25519,t.subarray(1));return{publicKey:F.concatUint8Array([new Uint8Array([e.wireFormatLeadingByte]),n]),sharedKey:r}}case"web":if(e.web&&F.getWebCrypto())try{return await async function(e,t){const r=Di(e.payloadSize,e.web,t);let n=Oi.generateKey({name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]),i=Oi.importKey("jwk",r,{name:"ECDH",namedCurve:e.web},!1,[]);[n,i]=await Promise.all([n,i]);let s=Oi.deriveBits({name:"ECDH",namedCurve:e.web,public:i},n.privateKey,e.sharedSize),a=Oi.exportKey("jwk",n.publicKey);[s,a]=await Promise.all([s,a]);const o=new Uint8Array(s),c=new Uint8Array(Ci(a,e.wireFormatLeadingByte));return{publicKey:c,sharedKey:o}}(e,t)}catch(r){return F.printDebugError(r),Ji(e,t)}break;case"node":return async function(e,t){const r=zi.createECDH(e.node);r.generateKeys();const n=new Uint8Array(r.computeSecret(t)),i=new Uint8Array(r.getPublicKey());return{publicKey:i,sharedKey:n}}(e,t);default:return Ji(e,t)}}async function qi(e,t,r,n){if(n.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(n,e.payloadSize-n.length),n=t}switch(e.type){case"curve25519Legacy":{const e=n.slice().reverse();return{secretKey:e,sharedKey:await pi(T.publicKey.x25519,t.subarray(1),r.subarray(1),e)}}case"web":if(e.web&&F.getWebCrypto())try{return await async function(e,t,r,n){const i=Pi(e.payloadSize,e.web,r,n);let s=Oi.importKey("jwk",i,{name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]);const a=Di(e.payloadSize,e.web,t);let o=Oi.importKey("jwk",a,{name:"ECDH",namedCurve:e.web},!0,[]);[s,o]=await Promise.all([s,o]);let c=Oi.deriveBits({name:"ECDH",namedCurve:e.web,public:o},s,e.sharedSize),h=Oi.exportKey("jwk",s);[c,h]=await Promise.all([c,h]);const u=new Uint8Array(c);return{secretKey:j(h.d),sharedKey:u}}(e,t,r,n)}catch(r){return F.printDebugError(r),Vi(e,t,n)}break;case"node":return async function(e,t,r){const n=zi.createECDH(e.node);n.setPrivateKey(r);const i=new Uint8Array(n.computeSecret(t));return{secretKey:new Uint8Array(n.getPrivateKey()),sharedKey:i}}(e,t,n);default:return Vi(e,t,n)}}async function Vi(e,t,r){return{secretKey:r,sharedKey:(await F.getNobleCurve(T.publicKey.ecdh,e.name)).getSharedSecret(r,t).subarray(1)}}async function Ji(e,t){const r=await F.getNobleCurve(T.publicKey.ecdh,e.name),{publicKey:n,privateKey:i}=await e.genKeyPair();return{publicKey:n,sharedKey:r.getSharedSecret(i,t).subarray(1)}}var Yi=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i,s,a){const o=new Bi(e);Si(o,i),Si(o,r);const{sharedKey:c}=await qi(o,r,i,s),h=_i(T.publicKey.ecdh,e,t,a),{keySize:u}=se(t.cipher);let l;for(let e=0;e<3;e++)try{const r=await Gi(t.hash,c,u,h,1===e,2===e);return Fi(await oi(t.cipher,r,n))}catch(e){l=e}throw l},encrypt:async function(e,t,r,n,i){const s=Ni(r),a=new Bi(e);Si(a,n);const{publicKey:o,sharedKey:c}=await ji(a,n),h=_i(T.publicKey.ecdh,e,t,i),{keySize:u}=se(t.cipher),l=await Gi(t.hash,c,u,h);return{publicKey:o,wrappedKey:await ai(t.cipher,l,s)}},validateParams:async function(e,t,r){return Ii(T.publicKey.ecdh,e,t,r)}}),Wi=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:Bi,ecdh:Yi,ecdhX:Ai,ecdsa:Ti,eddsa:ii,eddsaLegacy:Mi,generate:async function(e){const t=new Bi(e),{oid:r,hash:n,cipher:i}=t,s=await t.genKeyPair();return{oid:r,Q:s.publicKey,secret:F.leftPad(s.privateKey,t.payloadSize),hash:n,cipher:i}},getPreferredHashAlgo:function(e){return vi[e.getName()].hash}});const Zi=BigInt(0),$i=BigInt(1);var Xi=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){const a=BigInt(0);let o,c,h,u;n=dr(n),i=dr(i),r=dr(r),s=dr(s),r=Ar(r,n),s=Ar(s,i);const l=Ar(dr(t.subarray(0,Br(i))),i);for(;;){if(o=Cr($i,i),c=Ar(wr(r,o,n),i),c===a)continue;const e=Ar(s*c,i);if(u=Ar(l+e,i),h=Ar(br(o,i)*u,i),h!==a)break}return{r:Ir(c,"be",Br(n)),s:Ir(h,"be",Br(n))}},validateParams:async function(e,t,r,n,i){if(e=dr(e),t=dr(t),r=dr(r),n=dr(n),r<=$i||r>=e)return!1;if(Ar(e-$i,t)!==Zi)return!1;if(wr(r,t,e)!==$i)return!1;const s=BigInt(vr(t));if(s=a||r<=Zi||r>=a)return F.printDebug("invalid DSA Signature"),!1;const c=Ar(dr(n.subarray(0,Br(a))),a),h=br(r,a);if(h===Zi)return F.printDebug("invalid DSA Signature"),!1;i=Ar(i,s),o=Ar(o,s);const u=Ar(c*h,a),l=Ar(t*h,a);return Ar(Ar(wr(i,u,s)*wr(o,l,s),s),a)===t}}),es={rsa:jr,elgamal:Vr,elliptic:Wi,dsa:Xi};var ts=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(r));return r+=e.length+2,{read:r,signatureParams:{s:e}}}case T.publicKey.dsa:case T.publicKey.ecdsa:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=F.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case T.publicKey.eddsaLegacy:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=F.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case T.publicKey.ed25519:case T.publicKey.ed448:{const n=2*es.elliptic.eddsa.getPayloadSize(e),i=F.readExactSubarray(t,r,r+n);return r+=i.length,{read:r,signatureParams:{RS:i}}}default:throw new Jn("Unknown signature algorithm.")}},sign:async function(e,t,r,n,i,s){if(!r||!n)throw Error("Missing key parameters");switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const{n:e,e:a}=r,{d:o,p:c,q:h,u}=n;return{s:await es.rsa.sign(t,i,e,a,o,c,h,u,s)}}case T.publicKey.dsa:{const{g:e,p:i,q:a}=r,{x:o}=n;return es.dsa.sign(t,s,e,i,a,o)}case T.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case T.publicKey.ecdsa:{const{oid:e,Q:a}=r,{d:o}=n;return es.elliptic.ecdsa.sign(e,t,i,a,o,s)}case T.publicKey.eddsaLegacy:{const{oid:e,Q:a}=r,{seed:o}=n;return es.elliptic.eddsaLegacy.sign(e,t,i,a,o,s)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:a}=r,{seed:o}=n;return es.elliptic.eddsa.sign(e,t,i,a,o,s)}default:throw Error("Unknown signature algorithm.")}},verify:async function(e,t,r,n,i,s){switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.rsaSign:{const{n:e,e:a}=n,o=F.leftPad(r.s,e.length);return es.rsa.verify(t,i,o,e,a,s)}case T.publicKey.dsa:{const{g:e,p:i,q:a,y:o}=n,{r:c,s:h}=r;return es.dsa.verify(t,c,h,s,e,i,a,o)}case T.publicKey.ecdsa:{const{oid:e,Q:a}=n,o=new es.elliptic.CurveWithOID(e).payloadSize,c=F.leftPad(r.r,o),h=F.leftPad(r.s,o);return es.elliptic.ecdsa.verify(e,t,{r:c,s:h},i,a,s)}case T.publicKey.eddsaLegacy:{const{oid:e,Q:a}=n,o=new es.elliptic.CurveWithOID(e).payloadSize,c=F.leftPad(r.r,o),h=F.leftPad(r.s,o);return es.elliptic.eddsaLegacy.verify(e,t,{r:c,s:h},i,a,s)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:a}=n;return es.elliptic.eddsa.verify(e,t,r,i,a,s)}default:throw Error("Unknown signature algorithm.")}}});class rs{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return F.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class ns{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Jn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class is{static fromObject({wrappedKey:e,algorithm:t}){const r=new is;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=F.readExactSubarray(e,t,t+r),t+=r}write(){return F.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function ss(e){try{e.getName()}catch(e){throw new Jn("Unknown curve OID")}}function as(e,t){switch(e){case T.publicKey.ecdsa:case T.publicKey.ecdh:case T.publicKey.eddsaLegacy:return new es.elliptic.CurveWithOID(t).payloadSize;case T.publicKey.ed25519:case T.publicKey.ed448:return es.elliptic.eddsa.getPayloadSize(e);case T.publicKey.x25519:case T.publicKey.x448:return es.elliptic.ecdhX.getPayloadSize(e);default:throw Error("Unknown elliptic algo")}}var os=/*#__PURE__*/Object.freeze({__proto__:null,generateParams:function(e,t,r){switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:return es.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:n,q:i,u:s})=>({privateParams:{d:r,p:n,q:i,u:s},publicParams:{n:e,e:t}})));case T.publicKey.ecdsa:return es.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new Hn(e),Q:t}})));case T.publicKey.eddsaLegacy:return es.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new Hn(e),Q:t}})));case T.publicKey.ecdh:return es.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:n,cipher:i})=>({privateParams:{d:r},publicParams:{oid:new Hn(e),Q:t,kdfParams:new ns({hash:n,cipher:i})}})));case T.publicKey.ed25519:case T.publicKey.ed448:return es.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case T.publicKey.x25519:case T.publicKey.x448:return es.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case T.publicKey.dsa:case T.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},generateSessionKey:function(e){const{keySize:t}=se(e);return Kr(t)},getAEADMode:function(e){const t=T.read(T.aead,e);return fr[t]},getCipherParams:se,getCurvePayloadSize:as,getPreferredCurveHashAlgo:function(e,t){switch(e){case T.publicKey.ecdsa:case T.publicKey.eddsaLegacy:return es.elliptic.getPreferredHashAlgo(t);case T.publicKey.ed25519:case T.publicKey.ed448:return es.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}},getPrefixRandom:async function(e){const{blockSize:t}=se(e),r=await Kr(t),n=new Uint8Array([r[r.length-2],r[r.length-1]]);return F.concat([r,n])},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:return{c:F.readMPI(t.subarray(r))};case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:F.readMPI(t.subarray(r))}}case T.publicKey.ecdh:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=new rs;return n.read(t.subarray(r)),{V:e,C:n}}case T.publicKey.x25519:case T.publicKey.x448:{const n=as(e),i=F.readExactSubarray(t,r,r+n);r+=i.length;const s=new is;return s.read(t.subarray(r)),{ephemeralPublicKey:i,C:s}}default:throw new Jn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let n=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(n));n+=e.length+2;const r=F.readMPI(t.subarray(n));n+=r.length+2;const i=F.readMPI(t.subarray(n));n+=i.length+2;const s=F.readMPI(t.subarray(n));return n+=s.length+2,{read:n,privateParams:{d:e,p:r,q:i,u:s}}}case T.publicKey.dsa:case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(n));return n+=e.length+2,{read:n,privateParams:{x:e}}}case T.publicKey.ecdsa:case T.publicKey.ecdh:{const i=as(e,r.oid);let s=F.readMPI(t.subarray(n));return n+=s.length+2,s=F.leftPad(s,i),{read:n,privateParams:{d:s}}}case T.publicKey.eddsaLegacy:{const i=as(e,r.oid);if(r.oid.getName()!==T.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let s=F.readMPI(t.subarray(n));return n+=s.length+2,s=F.leftPad(s,i),{read:n,privateParams:{seed:s}}}case T.publicKey.ed25519:case T.publicKey.ed448:{const r=as(e),i=F.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{seed:i}}}case T.publicKey.x25519:case T.publicKey.x448:{const r=as(e),i=F.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{k:i}}}default:throw new Jn("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=F.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{n:e,e:n}}}case T.publicKey.dsa:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=F.readMPI(t.subarray(r));r+=n.length+2;const i=F.readMPI(t.subarray(r));r+=i.length+2;const s=F.readMPI(t.subarray(r));return r+=s.length+2,{read:r,publicParams:{p:e,q:n,g:i,y:s}}}case T.publicKey.elgamal:{const e=F.readMPI(t.subarray(r));r+=e.length+2;const n=F.readMPI(t.subarray(r));r+=n.length+2;const i=F.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{p:e,g:n,y:i}}}case T.publicKey.ecdsa:{const e=new Hn;r+=e.read(t),ss(e);const n=F.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{oid:e,Q:n}}}case T.publicKey.eddsaLegacy:{const e=new Hn;if(r+=e.read(t),ss(e),e.getName()!==T.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let n=F.readMPI(t.subarray(r));return r+=n.length+2,n=F.leftPad(n,33),{read:r,publicParams:{oid:e,Q:n}}}case T.publicKey.ecdh:{const e=new Hn;r+=e.read(t),ss(e);const n=F.readMPI(t.subarray(r));r+=n.length+2;const i=new ns;return r+=i.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:n,kdfParams:i}}}case T.publicKey.ed25519:case T.publicKey.ed448:case T.publicKey.x25519:case T.publicKey.x448:{const n=F.readExactSubarray(t,r,r+as(e));return r+=n.length,{read:r,publicParams:{A:n}}}default:throw new Jn("Unknown public key encryption algorithm.")}},publicKeyDecrypt:async function(e,t,r,n,i,s){switch(e){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:{const{c:e}=n,{n:i,e:a}=t,{d:o,p:c,q:h,u}=r;return es.rsa.decrypt(e,i,a,o,c,h,u,s)}case T.publicKey.elgamal:{const{c1:e,c2:i}=n,a=t.p,o=r.x;return es.elgamal.decrypt(e,i,a,o,s)}case T.publicKey.ecdh:{const{oid:e,Q:s,kdfParams:a}=t,{d:o}=r,{V:c,C:h}=n;return es.elliptic.ecdh.decrypt(e,a,c,h.data,s,o,i)}case T.publicKey.x25519:case T.publicKey.x448:{const{A:i}=t,{k:s}=r,{ephemeralPublicKey:a,C:o}=n;if(null!==o.algorithm&&!F.isAES(o.algorithm))throw Error("AES session key expected");return es.elliptic.ecdhX.decrypt(e,a,o.wrappedKey,i,s)}default:throw Error("Unknown public key encryption algorithm.")}},publicKeyEncrypt:async function(e,t,r,n,i){switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await es.rsa.encrypt(n,e,t)}}case T.publicKey.elgamal:{const{p:e,g:t,y:i}=r;return es.elgamal.encrypt(n,e,t,i)}case T.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:s}=r,{publicKey:a,wrappedKey:o}=await es.elliptic.ecdh.encrypt(e,s,n,t,i);return{V:a,C:new rs(o)}}case T.publicKey.x25519:case T.publicKey.x448:{if(t&&!F.isAES(t))throw Error("X25519 and X448 keys can only encrypt AES session keys");const{A:i}=r,{ephemeralPublicKey:s,wrappedKey:a}=await es.elliptic.ecdhX.encrypt(e,n,i);return{ephemeralPublicKey:s,C:is.fromObject({algorithm:t,wrappedKey:a})}}default:return[]}},serializeParams:function(e,t){const r=new Set([T.publicKey.ed25519,T.publicKey.x25519,T.publicKey.ed448,T.publicKey.x448]),n=Object.keys(t).map((n=>{const i=t[n];return F.isUint8Array(i)?r.has(e)?i:F.uint8ArrayToMPI(i):i.write()}));return F.concatUint8Array(n)},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:{const{n:e,e:n}=t,{d:i,p:s,q:a,u:o}=r;return es.rsa.validateParams(e,n,i,s,a,o)}case T.publicKey.dsa:{const{p:e,q:n,g:i,y:s}=t,{x:a}=r;return es.dsa.validateParams(e,n,i,s,a)}case T.publicKey.elgamal:{const{p:e,g:n,y:i}=t,{x:s}=r;return es.elgamal.validateParams(e,n,i,s)}case T.publicKey.ecdsa:case T.publicKey.ecdh:{const n=es.elliptic[T.read(T.publicKey,e)],{oid:i,Q:s}=t,{d:a}=r;return n.validateParams(i,s,a)}case T.publicKey.eddsaLegacy:{const{Q:e,oid:n}=t,{seed:i}=r;return es.elliptic.eddsaLegacy.validateParams(n,e,i)}case T.publicKey.ed25519:case T.publicKey.ed448:{const{A:n}=t,{seed:i}=r;return es.elliptic.eddsa.validateParams(e,n,i)}case T.publicKey.x25519:case T.publicKey.x448:{const{A:n}=t,{k:i}=r;return es.elliptic.ecdhX.validateParams(e,n,i)}default:throw Error("Unknown public key algorithm.")}}});const cs={cipher:ae,hash:Ee,mode:fr,publicKey:es,signature:ts,random:Dr,pkcs1:Nr,pkcs5:Hi,aesKW:ci};Object.assign(cs,os);class hs extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,hs),this.name="Argon2OutOfMemoryError"}}let us,ls;class ys{constructor(e=M){const{passes:t,parallelism:r,memoryExponent:n}=e.s2kArgon2Params;this.type="argon2",this.salt=null,this.t=t,this.p=r,this.encodedM=n}generateSalt(){this.salt=cs.random.getRandomBytes(16)}read(e){let t=0;return this.salt=e.subarray(t,t+16),t+=16,this.t=e[t++],this.p=e[t++],this.encodedM=e[t++],t}write(){const e=[new Uint8Array([T.write(T.s2k,this.type)]),this.salt,new Uint8Array([this.t,this.p,this.encodedM])];return F.concatUint8Array(e)}async produceKey(e,t){const r=2<1048576&&(ls=us(),ls.catch((()=>{}))),i}catch(e){throw e.message&&(e.message.includes("Unable to grow instance memory")||e.message.includes("failed to grow memory")||e.message.includes("WebAssembly.Memory.grow")||e.message.includes("Out of memory"))?new hs("Could not allocate required memory for Argon2"):e}}}class fs{constructor(e,t=M){this.algorithm=T.hash.sha256,this.type=T.read(T.s2k,e),this.c=t.s2kIterationCountByte,this.salt=null}generateSalt(){switch(this.type){case"salted":case"iterated":this.salt=cs.random.getRandomBytes(8)}}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==F.uint8ArrayToString(e.subarray(t,t+3)))throw new Jn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Jn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Jn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...F.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([T.write(T.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return F.concatUint8Array(e)}async produceKey(e,t){e=F.encodeUTF8(e);const r=[];let n=0,i=0;for(;n>>1|(21845&xs)<<1;Qs=(61680&(Qs=(52428&Qs)>>>2|(13107&Qs)<<2))>>>4|(3855&Qs)<<4,Us[xs]=((65280&Qs)>>>8|(255&Qs)<<8)>>>1}var Rs=function(e,t,r){for(var n=e.length,i=0,s=new ms(t);i>>c]=h}else for(a=new ms(n),i=0;i>>15-e[i]);return a},Ls=new ws(288);for(xs=0;xs<144;++xs)Ls[xs]=8;for(xs=144;xs<256;++xs)Ls[xs]=9;for(xs=256;xs<280;++xs)Ls[xs]=7;for(xs=280;xs<288;++xs)Ls[xs]=8;var Ts=new ws(32);for(xs=0;xs<32;++xs)Ts[xs]=5;var Ms=/*#__PURE__*/Rs(Ls,9,0),Ns=/*#__PURE__*/Rs(Ls,9,1),Fs=/*#__PURE__*/Rs(Ts,5,0),Hs=/*#__PURE__*/Rs(Ts,5,1),Os=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},zs=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},_s=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Gs=function(e){return(e+7)/8|0},js=function(e,t,r){(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length);var n=new(2==e.BYTES_PER_ELEMENT?ms:4==e.BYTES_PER_ELEMENT?bs:ws)(r-t);return n.set(e.subarray(t,r)),n},qs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Vs=function(e,t,r){var n=Error(t||qs[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Vs),!r)throw n;return n},Js=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8},Ys=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Ws=function(e,t){for(var r=[],n=0;ny&&(y=s[n].s);var f=new ms(y+1),g=Zs(r[u-1],f,0);if(g>t){n=0;var p=0,d=g-t,A=1<t))break;p+=A-(1<>>=d;p>0;){var m=s[n].s;f[m]=0&&p;--n){var b=s[n].s;f[b]==t&&(--f[b],++p)}g=t}return[new ws(f),g]},Zs=function(e,t,r){return-1==e.s?Math.max(Zs(e.l,t,r+1),Zs(e.r,t,r+1)):t[e.s]=r},$s=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new ms(++t),n=0,i=e[0],s=1,a=function(e){r[n++]=e},o=1;o<=t;++o)if(e[o]==i&&o!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(i),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(i);s=1,i=e[o]}return[r.subarray(0,n),t]},Xs=function(e,t){for(var r=0,n=0;n>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;s4&&!S[vs[C-1]];--C);var D,P,U,x,Q=h+5<<3,R=Xs(i,Ls)+Xs(s,Ts)+a,L=Xs(i,y)+Xs(s,p)+a+14+3*C+Xs(v,S)+(2*v[16]+3*v[17]+7*v[18]);if(Q<=R&&Q<=L)return ea(t,u,e.subarray(c,c+h));if(Js(t,u,1+(L15&&(Js(t,u,F[B]>>>5&127),u+=F[B]>>>12)}}}else D=Ms,P=Ls,U=Fs,x=Ts;for(B=0;B255){H=n[B]>>>18&31;Ys(t,u,D[H+257]),u+=P[H+257],H>7&&(Js(t,u,n[B]>>>23&31),u+=ks[H]);var O=31&n[B];Ys(t,u,U[O]),u+=x[O],O>3&&(Ys(t,u,n[B]>>>5&8191),u+=Es[O])}else Ys(t,u,D[n[B]]),u+=P[n[B]];return Ys(t,u,D[256]),u+P[256]},ra=/*#__PURE__*/new bs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),na=/*#__PURE__*/new ws(0),ia=function(e,t,r,n,i){return function(e,t,r,n,i,s){var a=e.length,o=new ws(n+a+5*(1+Math.ceil(a/7e3))+i),c=o.subarray(n,o.length-i),h=0;if(!t||a<8)for(var u=0;u<=a;u+=65535){var l=u+65535;l>=a&&(c[h>>3]=s),h=ea(c,h+1,e.subarray(u,l))}else{for(var y=ra[t-1],f=y>>>13,g=8191&y,p=(1<7e3||S>24576)&&x>423){h=ta(e,c,0,k,E,v,I,S,C,u-C,h),S=B=I=0,C=u;for(var Q=0;Q<286;++Q)E[Q]=0;for(Q=0;Q<30;++Q)v[Q]=0}var R=2,L=0,T=g,M=P-U&32767;if(x>2&&D==b(u-M))for(var N=Math.min(f,x)-1,F=Math.min(32767,u),H=Math.min(258,x);M<=F&&--T&&P!=U;){if(e[u+R]==e[u+R-M]){for(var O=0;OR){if(R=O,L=M,O>N)break;var z=Math.min(M,O-2),_=0;for(Q=0;Q_&&(_=j,U=G)}}}M+=(P=U)-(U=d[P])+32768&32767}if(L){k[S++]=268435456|Ks[R]<<18|Ps[L];var q=31&Ks[R],V=31&Ps[L];I+=ks[q]+Es[V],++E[257+q],++v[V],K=u+R,++B}else k[S++]=e[u],++E[e[u]]}}h=ta(e,c,s,k,E,v,I,S,C,u-C,h),!s&&7&h&&(h=ea(c,h+1,na))}return js(o,0,n+Gs(h)+i)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,r,n,!i)},sa=/*#__PURE__*/function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(ia(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||Vs(5),this.d&&Vs(4),this.d=t,this.p(e,t||!1)},e}(),aa=/*#__PURE__*/function(){function e(e){this.s={},this.p=new ws(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||Vs(5),this.d&&Vs(4);var t=this.p.length,r=new ws(t+e.length);r.set(this.p),r.set(e,t),this.p=r},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,r=function(e,t,r){var n=e.length;if(!n||r&&r.f&&!r.l)return t||new ws(0);var i=!t||r,s=!r||r.i;r||(r={}),t||(t=new ws(3*n));var a=function(e){var r=t.length;if(e>r){var n=new ws(Math.max(2*r,e));n.set(t),t=n}},o=r.f||0,c=r.p||0,h=r.b||0,u=r.l,l=r.d,y=r.m,f=r.n,g=8*n;do{if(!u){o=zs(e,c,1);var p=zs(e,c+1,3);if(c+=3,!p){var d=e[(K=Gs(c)+4)-4]|e[K-3]<<8,A=K+d;if(A>n){s&&Vs(0);break}i&&a(h+d),t.set(e.subarray(K,A),h),r.b=h+=d,r.p=c=8*A,r.f=o;continue}if(1==p)u=Ns,l=Hs,y=9,f=5;else if(2==p){var w=zs(e,c,31)+257,m=zs(e,c+10,15)+4,b=w+zs(e,c+5,31)+1;c+=14;for(var k=new ws(b),E=new ws(19),v=0;v>>4)<16)k[v++]=K;else{var D=0,P=0;for(16==K?(P=3+zs(e,c,3),c+=2,D=k[v-1]):17==K?(P=3+zs(e,c,7),c+=3):18==K&&(P=11+zs(e,c,127),c+=7);P--;)k[v++]=D}}var U=k.subarray(0,w),x=k.subarray(w);y=Os(U),f=Os(x),u=Rs(U,y,1),l=Rs(x,f,1)}else Vs(1);if(c>g){s&&Vs(0);break}}i&&a(h+131072);for(var Q=(1<>>4;if((c+=15&D)>g){s&&Vs(0);break}if(D||Vs(2),T<256)t[h++]=T;else{if(256==T){L=c,u=null;break}var M=T-254;if(T>264){var N=ks[v=T-257];M=zs(e,c,(1<>>4;if(F||Vs(3),c+=15&F,x=Ds[H],H>3&&(N=Es[H],x+=_s(e,c)&(1<g){s&&Vs(0);break}i&&a(h+131072);for(var O=h+M;h>16),i=(65535&i)+15*(i>>16)}r=t,n=i},d:function(){return(255&(r%=65521))<<24|r>>>8<<16|(255&(n%=65521))<<8|n>>>8}}),this.v=1,sa.call(this,e,t)}return e.prototype.push=function(e,t){sa.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var r=ia(e,this.o,this.v&&2,t&&4,!t);this.v&&(function(e,t){var r=t.level,n=0==r?0:r<6?1:9==r?3:2;e[0]=120,e[1]=n<<6|(n?32-2*n:1)}(r,this.o),this.v=0),t&&function(e,t,r){for(;r;++t)e[t]=r,r>>>=8}(r,r.length-4,this.c.d()),this.ondata(r,t)},e}(),ca=/*#__PURE__*/function(){function e(e){this.v=1,aa.call(this,e)}return e.prototype.push=function(e,t){if(aa.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&Vs(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),aa.prototype.c.call(this,t)},e}(),ha="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{ha.decode(na,{stream:!0}),1}catch(e){}class ua{static get tag(){return T.packet.literalData}constructor(e=new Date){this.format=T.literal.utf8,this.date=F.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=T.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||F.isStream(this.text))&&(this.text=F.decodeUTF8(F.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=F.canonicalizeEOL(F.encodeUTF8(this.text))),e?K(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await I(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=F.decodeUTF8(await e.readBytes(r)),this.date=F.readDate(await e.readBytes(4));let n=e.remainder();h(n)&&(n=await P(n)),this.setBytes(n,t)}))}writeHeader(){const e=F.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),n=F.writeDate(this.date);return F.concatUint8Array([r,t,e,n])}write(){const e=this.writeHeader(),t=this.getBytes();return F.concat([e,t])}}class la{constructor(){this.bytes=""}read(e){return this.bytes=F.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return F.stringToUint8Array(this.bytes)}toHex(){return F.uint8ArrayToHex(F.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new la;return t.read(F.hexToUint8Array(e)),t}static wildcard(){const e=new la;return e.read(new Uint8Array(8)),e}}const ya=Symbol("verified"),fa="salt@notations.openpgpjs.org",ga=new Set([T.signatureSubpacket.issuerKeyID,T.signatureSubpacket.issuerFingerprint,T.signatureSubpacket.embeddedSignature]);class pa{static get tag(){return T.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.unknownSubpackets=[],this.signedHashValue=null,this.salt=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new la,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.preferredCipherSuites=null,this.revoked=null,this[ya]=null}read(e,t=M){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Jn("Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4!==this.version&&5!==this.version&&6!==this.version)throw new Jn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[r++],this.publicKeyAlgorithm=e[r++],this.hashAlgorithm=e[r++],r+=this.readSubPackets(e.subarray(r,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");if(this.signatureData=e.subarray(0,r),r+=this.readSubPackets(e.subarray(r,e.length),!1),this.signedHashValue=e.subarray(r,r+2),r+=2,6===this.version){const t=e[r++];this.salt=e.subarray(r,r+t),r+=t}const n=e.subarray(r,e.length),{read:i,signatureParams:s}=cs.signature.parseSignatureParams(this.publicKeyAlgorithm,n);if(ics.serializeParams(this.publicKeyAlgorithm,await this.params))):cs.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),6===this.version&&(e.push(new Uint8Array([this.salt.length])),e.push(this.salt)),e.push(this.writeParams()),F.concat(e)}async sign(e,t,r=new Date,n=!1,i){this.version=e.version,this.created=F.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID();const s=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];if(6===this.version){const e=Aa(this.hashAlgorithm);if(null===this.salt)this.salt=cs.random.getRandomBytes(e);else if(e!==this.salt.length)throw Error("Provided salt does not have the required length")}else if(i.nonDeterministicSignaturesViaNotation){if(0!==this.rawNotations.filter((({name:e})=>e===fa)).length)throw Error("Unexpected existing salt notation");{const e=cs.random.getRandomBytes(Aa(this.hashAlgorithm));this.rawNotations.push({name:fa,value:e,humanReadable:!1,critical:!1})}}s.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=F.concat(s);const a=this.toHash(this.signatureType,t,n),o=await this.hash(this.signatureType,t,a,n);this.signedHashValue=D(S(o),0,2);const c=async()=>cs.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await P(o));F.isStream(o)?this.params=c():(this.params=await c(),this[ya]=!0)}writeHashedSubPackets(){const e=T.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(da(e.signatureCreationTime,!0,F.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(da(e.signatureExpirationTime,!0,F.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(da(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(da(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(da(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(da(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(da(e.keyExpirationTime,!0,F.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(da(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=F.concat([r,this.revocationKeyFingerprint]),t.push(da(e.revocationKey,!1,r))),!this.issuerKeyID.isNull()&&this.issuerKeyVersion<5&&t.push(da(e.issuerKeyID,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:n,value:i,humanReadable:s,critical:a})=>{r=[new Uint8Array([s?128:0,0,0,0])];const o=F.encodeUTF8(n);r.push(F.writeNumber(o.length,2)),r.push(F.writeNumber(i.length,2)),r.push(o),r.push(i),r=F.concat(r),t.push(da(e.notationData,a,r))})),null!==this.preferredHashAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(da(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(da(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.keyServerPreferences)),t.push(da(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(da(e.preferredKeyServer,!1,F.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(da(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(da(e.policyURI,!1,F.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.keyFlags)),t.push(da(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(da(e.signersUserID,!1,F.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=F.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(da(e.reasonForRevocation,!0,r))),null!==this.features&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.features)),t.push(da(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(F.stringToUint8Array(this.signatureTargetHash)),r=F.concat(r),t.push(da(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(da(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=F.concat(r),t.push(da(e.issuerFingerprint,this.version>=5,r))),null!==this.preferredAEADAlgorithms&&(r=F.stringToUint8Array(F.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(da(e.preferredAEADAlgorithms,!1,r))),null!==this.preferredCipherSuites&&(r=new Uint8Array([].concat(...this.preferredCipherSuites)),t.push(da(e.preferredCipherSuites,!1,r)));const n=F.concat(t),i=F.writeNumber(n.length,6===this.version?4:2);return F.concat([i,n])}writeUnhashedSubPackets(){const e=this.unhashedSubpackets.map((({type:e,critical:t,body:r})=>da(e,t,r))),t=F.concat(e),r=F.writeNumber(t.length,6===this.version?4:2);return F.concat([r,t])}readSubPacket(e,t=!0){let r=0;const n=!!(128&e[r]),i=127&e[r];if(r++,t||(this.unhashedSubpackets.push({type:i,critical:n,body:e.subarray(r,e.length)}),ga.has(i)))switch(i){case T.signatureSubpacket.signatureCreationTime:this.created=F.readDate(e.subarray(r,e.length));break;case T.signatureSubpacket.signatureExpirationTime:{const t=F.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case T.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case T.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case T.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case T.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case T.signatureSubpacket.keyExpirationTime:{const t=F.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case T.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case T.signatureSubpacket.issuerKeyID:if(4===this.version)this.issuerKeyID.read(e.subarray(r,e.length));else if(t)throw Error("Unexpected Issuer Key ID subpacket");break;case T.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const i=F.readNumber(e.subarray(r,r+2));r+=2;const s=F.readNumber(e.subarray(r,r+2));r+=2;const a=F.decodeUTF8(e.subarray(r,r+i)),o=e.subarray(r+i,r+i+s);this.rawNotations.push({name:a,humanReadable:t,value:o,critical:n}),t&&(this.notations[a]=F.decodeUTF8(o));break}case T.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case T.signatureSubpacket.policyURI:this.policyURI=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.signersUserID:this.signersUserID=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=F.decodeUTF8(e.subarray(r,e.length));break;case T.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=cs.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=F.uint8ArrayToString(e.subarray(r,r+t));break}case T.signatureSubpacket.embeddedSignature:this.embeddedSignature=new pa,this.embeddedSignature.read(e.subarray(r,e.length));break;case T.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),this.issuerKeyVersion>=5?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case T.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;case T.signatureSubpacket.preferredCipherSuites:this.preferredCipherSuites=[];for(let t=r;t{r+=e.length}),(()=>{const n=[];return 5!==this.version||this.signatureType!==T.signature.binary&&this.signatureType!==T.signature.text||(t?n.push(new Uint8Array(6)):n.push(e.writeHeader())),n.push(new Uint8Array([this.version,255])),5===this.version&&n.push(new Uint8Array(4)),n.push(F.writeNumber(r,4)),F.concat(n)}))}toHash(e,t,r=!1){const n=this.toSign(e,t);return F.concat([this.salt||new Uint8Array,n,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,n=!1){if(6===this.version&&this.salt.length!==Aa(this.hashAlgorithm))throw Error("Signature salt does not have the expected length");return r||(r=this.toHash(e,t,n)),cs.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,n=new Date,i=!1,s=M){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const a=t===T.signature.binary||t===T.signature.text;if(!(this[ya]&&!a)){let n,s;if(this.hashed?s=await this.hashed:(n=this.toHash(t,r,i),s=await this.hash(t,r,n)),s=await P(s),this.signedHashValue[0]!==s[0]||this.signedHashValue[1]!==s[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[ya]=await cs.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,n,s),!this[ya])throw Error("Signature verification failed")}const o=F.normalizeDate(n);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(s.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+T.read(T.hash,this.hashAlgorithm).toUpperCase());if(s.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[T.signature.binary,T.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+T.read(T.hash,this.hashAlgorithm).toUpperCase());if(this.unknownSubpackets.forEach((({type:e,critical:t})=>{if(t)throw Error("Unknown critical signature subpacket type "+e)})),this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&s.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=F.normalizeDate(e);return null!==t&&!(this.created<=t&&tpa.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==T.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID)||3===this.version&&6===e.version||6===this.version&&6!==e.version||6===this.version&&!F.equalsUint8Array(e.issuerFingerprint,this.issuerFingerprint)||6===this.version&&!F.equalsUint8Array(e.salt,this.salt))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function ma(e,t){if(!t[e]){let t;try{t=T.read(T.packet,e)}catch(t){throw new Yn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}wa.prototype.hash=pa.prototype.hash,wa.prototype.toHash=pa.prototype.toHash,wa.prototype.toSign=pa.prototype.toSign;class ba extends Array{static async fromBinary(e,t,r=M){const n=new ba;return await n.read(e,t,r),n}async read(e,t,r=M){r.additionalAllowedPackets.length&&(t={...t,...F.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=B(e,(async(e,n)=>{const i=R(n);try{for(;;){await i.ready;if(await Vn(e,(async e=>{try{if(e.tag===T.packet.marker||e.tag===T.packet.trust||e.tag===T.packet.padding)return;const n=ma(e.tag,t);n.packets=new ba,n.fromStream=F.isStream(e.packet),await n.read(e.packet,r),await i.write(n)}catch(t){if(t instanceof Yn){if(!(e.tag<=39))return;await i.abort(t)}const n=!r.ignoreUnsupportedPackets&&t instanceof Jn,s=!(r.ignoreMalformedPackets||t instanceof Jn);if(n||s||qn(e.tag))await i.abort(t);else{const t=new Wn(e.tag,e.packet);await i.write(t)}F.printDebugError(t)}})))return await i.ready,void await i.close()}}catch(e){await i.abort(e)}}));const n=Q(this.stream);for(;;){const{done:e,value:t}=await n.read();if(e?this.stream=null:this.push(t),e||qn(t.constructor.tag))break}n.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),i+=e.length,i>=s){const e=Math.min(Math.log(i)/Math.LN2|0,30),r=2**e,n=F.concat([_n(e)].concat(t));return t=[n.subarray(1+r)],i=t[0].length,n.subarray(0,1+r)}}),(()=>F.concat([zn(i)].concat(t)))))}else{if(F.isStream(n)){let t=0;e.push(v(S(n),(e=>{t+=e.length}),(()=>jn(r,t))))}else e.push(jn(r,n.length));e.push(n)}}return F.concat(e)}filterByTag(...e){const t=new ba,r=e=>t=>e===t;for(let n=0;nt.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,n=e=>t=>e===t;for(let i=0;i{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),F.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=M){const t=T.read(T.compression,this.algorithm),r=Ka[t];if(!r)throw Error(t+" decompression not supported");this.packets=await ba.fromBinary(await r(this.compressed),ka,e)}compress(){const e=T.read(T.compression,this.algorithm),t=Sa[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write())}}function va(e,t){return r=>{if(!F.isStream(r)||h(r))return x((()=>P(r).then((e=>new Promise(((r,n)=>{const i=new t;i.ondata=e=>{r(e)};try{i.push(e,!0)}catch(e){n(e)}}))))));if(e)try{const t=e();return r.pipeThrough(t)}catch(e){if("TypeError"!==e.name)throw e}const n=r.getReader(),i=new t;return new ReadableStream({async start(e){for(i.ondata=async(t,r)=>{e.enqueue(t),r&&e.close()};;){const{done:e,value:t}=await n.read();if(e)return void i.push(new Uint8Array,!0);t.length&&i.push(t)}}})}}function Ba(){return async function(e){const{decode:t}=await Promise.resolve().then((function(){return rf}));return x((async()=>t(await P(e))))}}const Ia=e=>({compressor:"undefined"!=typeof CompressionStream&&(()=>new CompressionStream(e)),decompressor:"undefined"!=typeof DecompressionStream&&(()=>new DecompressionStream(e))}),Sa={zip:/*#__PURE__*/va(Ia("deflate-raw").compressor,sa),zlib:/*#__PURE__*/va(Ia("deflate").compressor,oa)},Ka={uncompressed:e=>e,zip:/*#__PURE__*/va(Ia("deflate-raw").decompressor,aa),zlib:/*#__PURE__*/va(Ia("deflate").decompressor,ca),bzip2:/*#__PURE__*/Ba()},Ca=/*#__PURE__*/F.constructAllowedPackets([ua,Ea,wa,pa]);class Da{static get tag(){return T.packet.symEncryptedIntegrityProtectedData}static fromObject({version:e,aeadAlgorithm:t}){if(1!==e&&2!==e)throw Error("Unsupported SEIPD version");const r=new Da;return r.version=e,2===e&&(r.aeadAlgorithm=t),r}constructor(){this.version=null,this.cipherAlgorithm=null,this.aeadAlgorithm=null,this.chunkSizeByte=null,this.salt=null,this.encrypted=null,this.packets=null}async read(e){await I(e,(async e=>{if(this.version=await e.readByte(),1!==this.version&&2!==this.version)throw new Jn(`Version ${this.version} of the SEIP packet is unsupported.`);2===this.version&&(this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte(),this.salt=await e.readBytes(32)),this.encrypted=e.remainder()}))}write(){return 2===this.version?F.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.salt,this.encrypted]):F.concat([new Uint8Array([this.version]),this.encrypted])}async encrypt(e,t,r=M){const{blockSize:n,keySize:i}=cs.getCipherParams(e);if(t.length!==i)throw Error("Unexpected session key size");let s=this.packets.write();if(h(s)&&(s=await P(s)),2===this.version)this.cipherAlgorithm=e,this.salt=cs.random.getRandomBytes(32),this.chunkSizeByte=r.aeadChunkSizeByte,this.encrypted=await Pa(this,"encrypt",t,s);else{const i=await cs.getPrefixRandom(e),a=new Uint8Array([211,20]),o=F.concat([i,s,a]),c=await cs.hash.sha1(K(o)),h=F.concat([o,c]);this.encrypted=await cs.mode.cfb.encrypt(e,t,h,new Uint8Array(n),r)}return!0}async decrypt(e,t,r=M){if(t.length!==cs.getCipherParams(e).keySize)throw Error("Unexpected session key size");let n,i=S(this.encrypted);if(h(i)&&(i=await P(i)),2===this.version){if(this.cipherAlgorithm!==e)throw Error("Unexpected session key algorithm");n=await Pa(this,"decrypt",t,i)}else{const{blockSize:s}=cs.getCipherParams(e),a=await cs.mode.cfb.decrypt(e,t,i,new Uint8Array(s)),o=D(K(a),-20),c=D(a,0,-20),h=Promise.all([P(await cs.hash.sha1(K(c))),P(o)]).then((([e,t])=>{if(!F.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=D(c,s+2);n=D(u,0,-2),n=m([n,x((()=>h))]),F.isStream(i)&&r.allowUnauthenticatedStream||(n=await P(n))}return this.packets=await ba.fromBinary(n,Ca,r),!0}}async function Pa(e,t,r,n){const i=e instanceof Da&&2===e.version,s=!i&&e.constructor.tag===T.packet.aeadEncryptedData;if(!i&&!s)throw Error("Unexpected packet type");const a=cs.getAEADMode(e.aeadAlgorithm),o="decrypt"===t?a.tagLength:0,c="encrypt"===t?a.tagLength:0,h=2**(e.chunkSizeByte+6)+o,u=s?8:0,l=new ArrayBuffer(13+u),y=new Uint8Array(l,0,5+u),f=new Uint8Array(l),g=new DataView(l),p=new Uint8Array(l,5,8);y.set([192|e.constructor.tag,e.version,e.cipherAlgorithm,e.aeadAlgorithm,e.chunkSizeByte],0);let d,A,w=0,m=Promise.resolve(),k=0,E=0;if(i){const{keySize:t}=cs.getCipherParams(e.cipherAlgorithm),{ivLength:n}=a,i=new Uint8Array(l,0,5),s=await ui(T.hash.sha256,r,e.salt,i,t+n);r=s.subarray(0,t),d=s.subarray(t),d.fill(0,d.length-8),A=new DataView(d.buffer,d.byteOffset,d.byteLength)}else d=e.iv;const v=await a(e.cipherAlgorithm,r);return B(n,(async(r,n)=>{if("array"!==F.isStream(r)){const t=new TransformStream({},{highWaterMark:F.getHardwareConcurrency()*2**(e.chunkSizeByte+6),size:e=>e.length});b(t.readable,n),n=t.writable}const s=Q(r),a=R(n);try{for(;;){let e=await s.readBytes(h+o)||new Uint8Array;const r=e.subarray(e.length-o);let n,l,b;if(e=e.subarray(0,e.length-o),i)b=d;else{b=d.slice();for(let e=0;e<8;e++)b[d.length-8+e]^=p[e]}if(!w||e.length?(s.unshift(r),n=v[t](e,b,y),n.catch((()=>{})),E+=e.length-o+c):(g.setInt32(5+u+4,k),n=v[t](r,b,f),n.catch((()=>{})),E+=c,l=!0),k+=e.length-o,m=m.then((()=>n)).then((async e=>{await a.ready,await a.write(e),E-=e.length})).catch((e=>a.abort(e))),(l||E>a.desiredSize)&&await m,l){await a.close();break}i?A.setInt32(d.length-4,++w):g.setInt32(9,++w)}}catch(e){await a.ready.catch((()=>{})),await a.abort(e)}}))}const Ua=/*#__PURE__*/F.constructAllowedPackets([ua,Ea,wa,pa]);class xa{static get tag(){return T.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=T.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await I(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Jn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=cs.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return F.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=M){this.packets=await ba.fromBinary(await Pa(this,"decrypt",t,S(this.encrypted)),Ua,r)}async encrypt(e,t,r=M){this.cipherAlgorithm=e;const{ivLength:n}=cs.getAEADMode(this.aeadAlgorithm);this.iv=cs.random.getRandomBytes(n),this.chunkSizeByte=r.aeadChunkSizeByte;const i=this.packets.write();this.encrypted=await Pa(this,"encrypt",t,i)}}class Qa{static get tag(){return T.packet.publicKeyEncryptedSessionKey}constructor(){this.version=null,this.publicKeyID=new la,this.publicKeyVersion=null,this.publicKeyFingerprint=null,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}static fromObject({version:e,encryptionKeyPacket:t,anonymousRecipient:r,sessionKey:n,sessionKeyAlgorithm:i}){const s=new Qa;if(3!==e&&6!==e)throw Error("Unsupported PKESK version");return s.version=e,6===e&&(s.publicKeyVersion=r?null:t.version,s.publicKeyFingerprint=r?null:t.getFingerprintBytes()),s.publicKeyID=r?la.wildcard():t.getKeyID(),s.publicKeyAlgorithm=t.algorithm,s.sessionKey=n,s.sessionKeyAlgorithm=i,s}read(e){let t=0;if(this.version=e[t++],3!==this.version&&6!==this.version)throw new Jn(`Version ${this.version} of the PKESK packet is unsupported.`);if(6===this.version){const r=e[t++];if(r){this.publicKeyVersion=e[t++];const n=r-1;this.publicKeyFingerprint=e.subarray(t,t+n),t+=n,this.publicKeyVersion>=5?this.publicKeyID.read(this.publicKeyFingerprint):this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8))}else this.publicKeyID=la.wildcard()}else t+=this.publicKeyID.read(e.subarray(t,t+8));if(this.publicKeyAlgorithm=e[t++],this.encrypted=cs.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t)),this.publicKeyAlgorithm===T.publicKey.x25519||this.publicKeyAlgorithm===T.publicKey.x448)if(3===this.version)this.sessionKeyAlgorithm=T.write(T.symmetric,this.encrypted.C.algorithm);else if(null!==this.encrypted.C.algorithm)throw Error("Unexpected cleartext symmetric algorithm")}write(){const e=[new Uint8Array([this.version])];return 6===this.version?null!==this.publicKeyFingerprint?(e.push(new Uint8Array([this.publicKeyFingerprint.length+1,this.publicKeyVersion])),e.push(this.publicKeyFingerprint)):e.push(new Uint8Array([0])):e.push(this.publicKeyID.write()),e.push(new Uint8Array([this.publicKeyAlgorithm]),cs.serializeParams(this.publicKeyAlgorithm,this.encrypted)),F.concatUint8Array(e)}async encrypt(e){const t=T.write(T.publicKey,this.publicKeyAlgorithm),r=3===this.version?this.sessionKeyAlgorithm:null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=Ra(this.version,t,r,this.sessionKey);this.encrypted=await cs.publicKeyEncrypt(t,r,e.publicParams,i,n)}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Ra(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=await cs.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,n,r),{sessionKey:s,sessionKeyAlgorithm:a}=function(e,t,r,n){switch(t){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.elgamal:case T.publicKey.ecdh:{const t=r.subarray(0,r.length-2),i=r.subarray(r.length-2),s=F.writeChecksum(t.subarray(t.length%8)),a=s[0]===i[0]&s[1]===i[1],o=6===e?{sessionKeyAlgorithm:null,sessionKey:t}:{sessionKeyAlgorithm:t[0],sessionKey:t.subarray(1)};if(n){const t=a&o.sessionKeyAlgorithm===n.sessionKeyAlgorithm&o.sessionKey.length===n.sessionKey.length;return{sessionKey:F.selectUint8Array(t,o.sessionKey,n.sessionKey),sessionKeyAlgorithm:6===e?null:F.selectUint8(t,o.sessionKeyAlgorithm,n.sessionKeyAlgorithm)}}if(a&&(6===e||T.read(T.symmetric,o.sessionKeyAlgorithm)))return o;throw Error("Decryption error")}case T.publicKey.x25519:case T.publicKey.x448:return{sessionKeyAlgorithm:null,sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);if(3===this.version){const e=this.publicKeyAlgorithm!==T.publicKey.x25519&&this.publicKeyAlgorithm!==T.publicKey.x448;if(this.sessionKeyAlgorithm=e?a:this.sessionKeyAlgorithm,s.length!==cs.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}this.sessionKey=s}}function Ra(e,t,r,n){switch(t){case T.publicKey.rsaEncrypt:case T.publicKey.rsaEncryptSign:case T.publicKey.elgamal:case T.publicKey.ecdh:return F.concatUint8Array([new Uint8Array(6===e?[]:[r]),n,F.writeChecksum(n.subarray(n.length%8))]);case T.publicKey.x25519:case T.publicKey.x448:return n;default:throw Error("Unsupported public key algorithm")}}class La{static get tag(){return T.packet.symEncryptedSessionKey}constructor(e=M){this.version=e.aeadProtect?6:4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm=null,this.aeadAlgorithm=T.write(T.aead,e.preferredAEADAlgorithm),this.encrypted=null,this.s2k=null,this.iv=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version&&6!==this.version)throw new Jn(`Version ${this.version} of the SKESK packet is unsupported.`);6===this.version&&t++;const r=e[t++];this.version>=5&&(this.aeadAlgorithm=e[t++],6===this.version&&t++);const n=e[t++];if(this.s2k=ps(n),t+=this.s2k.read(e.subarray(t,e.length)),this.version>=5){const r=cs.getAEADMode(this.aeadAlgorithm);this.iv=e.subarray(t,t+=r.ivLength)}this.version>=5||t=5){const e=cs.getAEADMode(this.aeadAlgorithm),r=new Uint8Array([192|La.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),s=6===this.version?await ui(T.hash.sha256,i,new Uint8Array,r,n):i,a=await e(t,s);this.sessionKey=await a.decrypt(this.encrypted,this.iv,r)}else if(null!==this.encrypted){const e=await cs.mode.cfb.decrypt(t,i,this.encrypted,new Uint8Array(r));if(this.sessionKeyAlgorithm=T.write(T.symmetric,e[0]),this.sessionKey=e.subarray(1,e.length),this.sessionKey.length!==cs.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}else this.sessionKey=i}async encrypt(e,t=M){const r=null!==this.sessionKeyEncryptionAlgorithm?this.sessionKeyEncryptionAlgorithm:this.sessionKeyAlgorithm;this.sessionKeyEncryptionAlgorithm=r,this.s2k=ds(t),this.s2k.generateSalt();const{blockSize:n,keySize:i}=cs.getCipherParams(r),s=await this.s2k.produceKey(e,i);if(null===this.sessionKey&&(this.sessionKey=cs.generateSessionKey(this.sessionKeyAlgorithm)),this.version>=5){const e=cs.getAEADMode(this.aeadAlgorithm);this.iv=cs.random.getRandomBytes(e.ivLength);const t=new Uint8Array([192|La.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),n=6===this.version?await ui(T.hash.sha256,s,new Uint8Array,t,i):s,a=await e(r,n);this.encrypted=await a.encrypt(this.sessionKey,this.iv,t)}else{const e=F.concatUint8Array([new Uint8Array([this.sessionKeyAlgorithm]),this.sessionKey]);this.encrypted=await cs.mode.cfb.encrypt(r,s,e,new Uint8Array(n),t)}}}class Ta{static get tag(){return T.packet.publicKey}constructor(e=new Date,t=M){this.version=t.v6Keys?6:4,this.created=F.normalizeDate(e),this.algorithm=null,this.publicParams=null,this.expirationTimeV3=0,this.fingerprint=null,this.keyID=null}static fromSecretKeyPacket(e){const t=new Ta,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}async read(e,t=M){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Jn("Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4===this.version||5===this.version||6===this.version){this.created=F.readDate(e.subarray(r,r+4)),r+=4,this.algorithm=e[r++],this.version>=5&&(r+=4);const{read:t,publicParams:n}=cs.parsePublicKeyParams(this.algorithm,e.subarray(r));if(6===this.version&&n.oid&&(n.oid.getName()===T.curve.curve25519Legacy||n.oid.getName()===T.curve.ed25519Legacy))throw Error("Legacy curve25519 cannot be used with v6 keys");return this.publicParams=n,r+=t,await this.computeFingerprintAndKeyID(),r}throw new Jn(`Version ${this.version} of the key packet is unsupported.`)}write(){const e=[];e.push(new Uint8Array([this.version])),e.push(F.writeDate(this.created)),e.push(new Uint8Array([this.algorithm]));const t=cs.serializeParams(this.algorithm,this.publicParams);return this.version>=5&&e.push(F.writeNumber(t.length,4)),e.push(t),F.concatUint8Array(e)}writeForHash(e){const t=this.writePublicKey(),r=149+e,n=e>=5?4:2;return F.concatUint8Array([new Uint8Array([r]),F.writeNumber(t.length,n),t])}isDecrypted(){return null}getCreationTime(){return this.created}getKeyID(){return this.keyID}async computeFingerprintAndKeyID(){if(await this.computeFingerprint(),this.keyID=new la,this.version>=5)this.keyID.read(this.fingerprint.subarray(0,8));else{if(4!==this.version)throw Error("Unsupported key version");this.keyID.read(this.fingerprint.subarray(12,20))}}async computeFingerprint(){const e=this.writeForHash(this.version);if(this.version>=5)this.fingerprint=await cs.hash.sha256(e);else{if(4!==this.version)throw Error("Unsupported key version");this.fingerprint=await cs.hash.sha1(e)}}getFingerprintBytes(){return this.fingerprint}getFingerprint(){return F.uint8ArrayToHex(this.getFingerprintBytes())}hasSameFingerprintAs(e){return this.version===e.version&&F.equalsUint8Array(this.writePublicKey(),e.writePublicKey())}getAlgorithmInfo(){const e={};e.algorithm=T.read(T.publicKey,this.algorithm);const t=this.publicParams.n||this.publicParams.p;return t?e.bits=F.uint8ArrayBitLength(t):this.publicParams.oid&&(e.curve=this.publicParams.oid.getName()),e}}Ta.prototype.readPublicKey=Ta.prototype.read,Ta.prototype.writePublicKey=Ta.prototype.write;const Ma=/*#__PURE__*/F.constructAllowedPackets([ua,Ea,wa,pa]);class Na{static get tag(){return T.packet.symmetricallyEncryptedData}constructor(){this.encrypted=null,this.packets=null}read(e){this.encrypted=e}write(){return this.encrypted}async decrypt(e,t,r=M){if(!r.allowUnauthenticatedMessages)throw Error("Message is not authenticated.");const{blockSize:n}=cs.getCipherParams(e),i=await P(S(this.encrypted)),s=await cs.mode.cfb.decrypt(e,t,i.subarray(n+2),i.subarray(2,n+2));this.packets=await ba.fromBinary(s,Ma,r)}async encrypt(e,t,r=M){const n=this.packets.write(),{blockSize:i}=cs.getCipherParams(e),s=await cs.getPrefixRandom(e),a=await cs.mode.cfb.encrypt(e,t,s,new Uint8Array(i),r),o=await cs.mode.cfb.encrypt(e,t,n,a.subarray(2),r);this.encrypted=F.concat([a,o])}}class Fa{static get tag(){return T.packet.marker}read(e){return 80===e[0]&&71===e[1]&&80===e[2]}write(){return new Uint8Array([80,71,80])}}class Ha extends Ta{static get tag(){return T.packet.publicSubkey}constructor(e,t){super(e,t)}static fromSecretSubkeyPacket(e){const t=new Ha,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}}class Oa{static get tag(){return T.packet.userAttribute}constructor(){this.attributes=[]}read(e){let t=0;for(;t{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function _a(e,t,r,n,i,s,a){if("argon2"===t.type&&!i)throw Error("Using Argon2 S2K without AEAD is not allowed");if("simple"===t.type&&6===e)throw Error("Using Simple S2K with version 6 keys is not allowed");const{keySize:o}=cs.getCipherParams(n),c=await t.produceKey(r,o);if(!i||5===e||a)return c;const h=F.concatUint8Array([s,new Uint8Array([e,n,i])]);return ui(T.hash.sha256,c,new Uint8Array,h,o)}class Ga{static get tag(){return T.packet.userID}constructor(){this.userID="",this.name="",this.email="",this.comment=""}static fromObject(e){if(F.isString(e)||e.name&&!F.isString(e.name)||e.email&&!F.isEmailAddress(e.email)||e.comment&&!F.isString(e.comment))throw Error("Invalid user ID format");const t=new Ga;Object.assign(t,e);const r=[];return t.name&&r.push(t.name),t.comment&&r.push(`(${t.comment})`),t.email&&r.push(`<${t.email}>`),t.userID=r.join(" "),t}read(e,t=M){const r=F.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");const n=/^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/.exec(r);if(null!==n){const{name:e,comment:t,email:r}=n.groups;this.comment=t?.replace(/^\(|\)|\s$/g,"").trim()||"",this.name=e?.trim()||"",this.email=r.substring(1,r.length-1)}else/^[^\s@]+@[^\s@]+$/.test(r)&&(this.email=r);this.userID=r}write(){return F.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class ja extends za{static get tag(){return T.packet.secretSubkey}constructor(e=new Date,t=M){super(e,t)}}class qa{static get tag(){return T.packet.trust}read(){throw new Jn("Trust packets are not supported")}write(){throw new Jn("Trust packets are not supported")}}class Va{static get tag(){return T.packet.padding}constructor(){this.padding=null}read(e){}write(){return this.padding}async createPadding(e){this.padding=await cs.random.getRandomBytes(e)}}const Ja=/*#__PURE__*/F.constructAllowedPackets([pa]);class Ya{constructor(e){this.packets=e||new ba}write(){return this.packets.write()}armor(e=M){const t=this.packets.some((e=>e.constructor.tag===pa.tag&&6!==e.version));return te(T.armor.signature,this.write(),void 0,void 0,void 0,t,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Wa({armoredSignature:e,binarySignature:t,config:r,...n}){r={...M,...r};let i=e||t;if(!i)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!F.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!F.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:e,data:t}=await ee(i);if(e!==T.armor.signature)throw Error("Armored text not of type signature");i=t}const a=await ba.fromBinary(i,Ja,r);return new Ya(a)}async function Za(e,t){const r=new ja(e.date,t);return r.packets=null,r.algorithm=T.write(T.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function $a(e,t){const r=new za(e.date,t);return r.packets=null,r.algorithm=T.write(T.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Xa(e,t,r,n,i=new Date,s){let a,o;for(let c=e.length-1;c>=0;c--)try{(!a||e[c].created>=a.created)&&(await e[c].verify(t,r,n,i,void 0,s),a=e[c])}catch(e){o=e}if(!a)throw F.wrapError(`Could not find valid ${T.read(T.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return a}function eo(e,t,r=new Date){const n=F.normalizeDate(r);if(null!==n){const r=so(e,t);return!(e.created<=n&&n0&&(s.keyExpirationTime=r.keyExpirationTime,s.keyNeverExpires=!1);return await ro(i,[],t,s,r.date,void 0,void 0,void 0,n)}async function ro(e,t,r,n,i,s,a=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const h=new pa;return Object.assign(h,n),h.publicKeyAlgorithm=r.algorithm,h.hashAlgorithm=await async function(e,t,r=new Date,n=[],i){const s=T.hash.sha256,a=i.preferredHashAlgorithm,o=await Promise.all(e.map((async(e,t)=>(await e.getPrimarySelfSignature(r,n[t],i)).preferredHashAlgorithms))),c=new Map;for(const e of o)for(const t of e)try{const e=T.write(T.hash,t);c.set(e,c.has(e)?c.get(e)+1:1)}catch{}const h=t=>0===e.length||c.get(t)===e.length||t===s,u=()=>{if(0===c.size)return s;const e=Array.from(c.keys()).filter((e=>h(e))).sort(((e,t)=>cs.hash.getHashByteLength(e)-cs.hash.getHashByteLength(t)))[0];return cs.hash.getHashByteLength(e)>=cs.hash.getHashByteLength(s)?e:s};if(new Set([T.publicKey.ecdsa,T.publicKey.eddsaLegacy,T.publicKey.ed25519,T.publicKey.ed448]).has(t.algorithm)){const e=cs.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid),r=h(a),n=cs.hash.getHashByteLength(a)>=cs.hash.getHashByteLength(e);if(r&&n)return a;{const t=u();return cs.hash.getHashByteLength(t)>=cs.hash.getHashByteLength(e)?t:e}}return h(a)?a:u()}(t,r,i,s,c),h.rawNotations=[...a],await h.sign(r,e,i,o,c),h}async function no(e,t,r,n=new Date,i){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(n)||i&&!await i(e)||t[r].some((function(t){return F.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function io(e,t,r,n,i,s,a=new Date,o){s=s||e;const c=[];return await Promise.all(n.map((async function(e){try{if(!i||e.issuerKeyID.equals(i.issuerKeyID)){const n=![T.reasonForRevocation.keyRetired,T.reasonForRevocation.keySuperseded,T.reasonForRevocation.userIDInvalid].includes(e.reasonForRevocationFlag);await e.verify(s,t,r,n?null:a,!1,o),c.push(e.issuerKeyID)}}catch(e){}}))),i?(i.revoked=!!c.some((e=>e.equals(i.issuerKeyID)))||(i.revoked||!1),i.revoked):c.length>0}function so(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function ao(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=F.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=T.write(T.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==T.curve.ed25519Legacy&&e.curve!==T.curve.curve25519Legacy&&"ed25519"!==e.curve&&"curve25519"!==e.curve||(e.curve=e.sign?T.curve.ed25519Legacy:T.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===T.curve.ed25519Legacy?T.publicKey.eddsaLegacy:T.publicKey.ecdsa:e.algorithm=T.publicKey.ecdh;break;case"curve25519":e.algorithm=e.sign?T.publicKey.ed25519:T.publicKey.x25519;break;case"curve448":e.algorithm=e.sign?T.publicKey.ed448:T.publicKey.x448;break;case"rsa":e.algorithm=T.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function oo(e,t,r){switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:case T.publicKey.dsa:case T.publicKey.ecdsa:case T.publicKey.eddsaLegacy:case T.publicKey.ed25519:case T.publicKey.ed448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.signData);default:return!1}}function co(e,t,r){switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.elgamal:case T.publicKey.ecdh:case T.publicKey.x25519:case T.publicKey.x448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&T.keyFlags.encryptStorage);default:return!1}}function ho(e,t,r){if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");switch(e.algorithm){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaEncrypt:case T.publicKey.elgamal:case T.publicKey.ecdh:case T.publicKey.x25519:case T.publicKey.x448:return!(!(!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.signData))||!r.allowInsecureDecryptionWithSigningKeys)||(!t.keyFlags||!!(t.keyFlags[0]&T.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&T.keyFlags.encryptStorage));default:return!1}}function uo(e,t){const r=T.write(T.publicKey,e.algorithm),n=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(n.algorithm+" keys are considered too weak.");switch(r){case T.publicKey.rsaEncryptSign:case T.publicKey.rsaSign:case T.publicKey.rsaEncrypt:if(n.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const s=await t.getSigningKey(o,e.created,void 0,n);if(e.revoked||await i.isRevoked(e,s.keyPacket,r,n))throw Error("User certificate is revoked");try{await e.verify(s.keyPacket,T.signature.certGeneric,a,r,void 0,n)}catch(e){throw F.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const n=this,i=this.selfCertifications.concat(this.otherCertifications);return Promise.all(i.map((async i=>({keyID:i.issuerKeyID,valid:await n.verifyCertificate(i,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};let s;for(let a=this.selfCertifications.length-1;a>=0;a--)try{const s=this.selfCertifications[a];if(s.revoked||await r.isRevoked(s,void 0,e,t))throw Error("Self-certification is revoked");try{await s.verify(n,T.signature.certGeneric,i,e,void 0,t)}catch(e){throw F.wrapError("Self-certification is invalid",e)}return!0}catch(e){s=e}throw s}async update(e,t,r){const n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};await no(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(n,T.signature.certGeneric,i,t,!1,r),!0}catch(e){return!1}})),await no(e,this,"otherCertifications",t),await no(e,this,"revocationSignatures",t,(function(e){return io(n,T.signature.certRevocation,i,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=T.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=M){const s={userID:this.userID,userAttribute:this.userAttribute,key:e},a=new lo(s.userID||s.userAttribute,this.mainKey);return a.revocationSignatures.push(await ro(s,[],e,{signatureType:T.signature.certRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}}class yo{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new ba;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new yo(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,n=M){const i=this.mainKey.keyPacket;return io(i,T.signature.subkeyRevocation,{key:i,bind:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verify(e=new Date,t=M){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket},i=await Xa(this.bindingSignatures,r,T.signature.subkeyBinding,n,e,t);if(i.revoked||await this.isRevoked(i,null,e,t))throw Error("Subkey is revoked");if(eo(this.keyPacket,i,e))throw Error("Subkey is expired");return i}async getExpirationTime(e=new Date,t=M){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket};let i;try{i=await Xa(this.bindingSignatures,r,T.signature.subkeyBinding,n,e,t)}catch(e){return null}const s=so(this.keyPacket,i),a=i.getExpirationTime();return si.bindingSignatures[t].created&&(i.bindingSignatures[t]=e),!1;try{return await e.verify(n,T.signature.subkeyBinding,s,t,void 0,r),!0}catch(e){return!1}})),await no(e,this,"revocationSignatures",t,(function(e){return io(n,T.signature.subkeyRevocation,s,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=T.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=M){const s={key:e,bind:this.keyPacket},a=new yo(this.keyPacket,this.mainKey);return a.revocationSignatures.push(await ro(s,[],e,{signatureType:T.signature.subkeyRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{yo.prototype[e]=function(){return this.keyPacket[e]()}}));const fo=/*#__PURE__*/F.constructAllowedPackets([pa]),go=new Set([T.packet.publicKey,T.packet.privateKey]),po=new Set([T.packet.publicKey,T.packet.privateKey,T.packet.publicSubkey,T.packet.privateSubkey]);class Ao{packetListToStructure(e,t=new Set){let r,n,i,s;for(const a of e){if(a instanceof Wn){po.has(a.tag)&&!s&&(s=go.has(a.tag)?go:po);continue}const e=a.constructor.tag;if(s){if(!s.has(e))continue;s=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case T.packet.publicKey:case T.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=a,n=this.getKeyID(),!n)throw Error("Missing Key ID");break;case T.packet.userID:case T.packet.userAttribute:r=new lo(a,this),this.users.push(r);break;case T.packet.publicSubkey:case T.packet.secretSubkey:r=null,i=new yo(a,this),this.subkeys.push(i);break;case T.packet.signature:switch(a.signatureType){case T.signature.certGeneric:case T.signature.certPersona:case T.signature.certCasual:case T.signature.certPositive:if(!r){F.printDebug("Dropping certification signatures without preceding user packet");continue}a.issuerKeyID.equals(n)?r.selfCertifications.push(a):r.otherCertifications.push(a);break;case T.signature.certRevocation:r?r.revocationSignatures.push(a):this.directSignatures.push(a);break;case T.signature.key:this.directSignatures.push(a);break;case T.signature.subkeyBinding:if(!i){F.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}i.bindingSignatures.push(a);break;case T.signature.keyRevocation:this.revocationSignatures.push(a);break;case T.signature.subkeyRevocation:if(!i){F.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}i.revocationSignatures.push(a)}}}}toPacketList(){const e=new ba;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},n=M){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{uo(i,n)}catch(e){throw F.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Xa(r.bindingSignatures,i,T.signature.subkeyBinding,e,t,n);if(!oo(r.keyPacket,s,n))continue;if(!s.embeddedSignature)throw Error("Missing embedded signature");return await Xa([s.embeddedSignature],r.keyPacket,T.signature.keyBinding,e,t,n),uo(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&oo(i,s,n))return uo(i,n),this}catch(e){a=e}throw F.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),a)}async getEncryptionKey(e,t=new Date,r={},n=M){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{uo(i,n)}catch(e){throw F.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Xa(r.bindingSignatures,i,T.signature.subkeyBinding,e,t,n);if(co(r.keyPacket,s,n))return uo(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&co(i,s,n))return uo(i,n),this}catch(e){a=e}throw F.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),a)}async isRevoked(e,t,r=new Date,n=M){return io(this.keyPacket,T.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verifyPrimaryKey(e=new Date,t={},r=M){const n=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");if(eo(n,await this.getPrimarySelfSignature(e,t,r),e))throw Error("Primary key is expired");if(6!==n.version){const t=await Xa(this.directSignatures,n,T.signature.key,{key:n},e,r).catch((()=>{}));if(t&&eo(n,t,e))throw Error("Primary key is expired")}}async getExpirationTime(e,t=M){let r;try{const n=await this.getPrimarySelfSignature(null,e,t),i=so(this.keyPacket,n),s=n.getExpirationTime(),a=6!==this.keyPacket.version&&await Xa(this.directSignatures,this.keyPacket,T.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(a){const e=so(this.keyPacket,a);r=Math.min(i,s,e)}else r=ie.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const n=this.clone();return await no(e,n,"revocationSignatures",t,(i=>io(n.keyPacket,T.signature.keyRevocation,n,[i],null,e.keyPacket,t,r))),await no(e,n,"directSignatures",t),await Promise.all(e.users.map((async e=>{const i=n.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const i=n.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.subkeys.push(t)}}))),n}async getRevocationCertificate(e=new Date,t=M){const r={key:this.keyPacket},n=await Xa(this.revocationSignatures,this.keyPacket,T.signature.keyRevocation,r,e,t),i=new ba;i.push(n);const s=6!==this.keyPacket.version;return te(T.armor.publicKey,i.write(),null,null,"This is a revocation certificate",s,t)}async applyRevocationCertificate(e,t=new Date,r=M){const n=await ee(e),i=(await ba.fromBinary(n.data,fo,r)).findPacket(T.packet.signature);if(!i||i.signatureType!==T.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!i.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await i.verify(this.keyPacket,T.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw F.wrapError("Could not verify revocation signature",e)}const s=this.clone();return s.revocationSignatures.push(i),s}async signPrimaryUser(e,t,r,n=M){const{index:i,user:s}=await this.getPrimaryUser(t,r,n),a=await s.certify(e,t,n),o=this.clone();return o.users[i]=a,o}async signAllUsers(e,t=new Date,r=M){const n=this.clone();return n.users=await Promise.all(this.users.map((function(n){return n.certify(e,t,r)}))),n}async verifyPrimaryUser(e,t=new Date,r,n=M){const i=this.keyPacket,{user:s}=await this.getPrimaryUser(t,r,n);return e?await s.verifyAllCertifications(e,t,n):[{keyID:i.getKeyID(),valid:await s.verify(t,n).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=M){const n=this.keyPacket,i=[];return await Promise.all(this.users.map((async s=>{const a=e?await s.verifyAllCertifications(e,t,r):[{keyID:n.getKeyID(),valid:await s.verify(t,r).catch((()=>!1))}];i.push(...a.map((e=>({userID:s.userID?s.userID.userID:null,userAttribute:s.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),i}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{Ao.prototype[e]=yo.prototype[e]}));class wo extends Ao{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([T.packet.secretKey,T.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=M){const t=6!==this.keyPacket.version;return te(T.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}}class mo extends wo{constructor(e){if(super(),this.packetListToStructure(e,new Set([T.packet.publicKey,T.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new ba,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case T.packet.secretKey:{const t=Ta.fromSecretKeyPacket(r);e.push(t);break}case T.packet.secretSubkey:{const t=Ha.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new wo(e)}armor(e=M){const t=6!==this.keyPacket.version;return te(T.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}async getDecryptionKeys(e,t=new Date,r={},n=M){const i=this.keyPacket,s=[];let a=null;for(let r=0;re.isDecrypted()))}async validate(e=M){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=T.reasonForRevocation.noReason,string:t=""}={},r=new Date,n=M){if(!this.isPrivate())throw Error("Need private key for revoking");const i={key:this.keyPacket},s=this.clone();return s.revocationSignatures.push(await ro(i,[],this.keyPacket,{signatureType:T.signature.keyRevocation,reasonForRevocationFlag:T.write(T.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,n)),s}async addSubkey(e={}){const t={...M,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}function a(){const e={};e.keyFlags=[T.keyFlags.certifyKeys|T.keyFlags.signData];const t=s([T.symmetric.aes256,T.symmetric.aes128],n.preferredSymmetricAlgorithm);if(e.preferredSymmetricAlgorithms=t,n.aeadProtect){const r=s([T.aead.gcm,T.aead.eax,T.aead.ocb],n.preferredAEADAlgorithm);e.preferredCipherSuites=r.flatMap((e=>t.map((t=>[t,e]))))}return e.preferredHashAlgorithms=s([T.hash.sha256,T.hash.sha512,T.hash.sha3_256,T.hash.sha3_512],n.preferredHashAlgorithm),e.preferredCompressionAlgorithms=s([T.compression.uncompressed,T.compression.zlib,T.compression.zip],n.preferredCompressionAlgorithm),e.features=[0],e.features[0]|=T.features.modificationDetection,n.aeadProtect&&(e.features[0]|=T.features.seipdv2),r.keyExpirationTime>0&&(e.keyExpirationTime=r.keyExpirationTime,e.keyNeverExpires=!1),e}if(i.push(e),6===e.version){const t={key:e},s=a();s.signatureType=T.signature.key;const o=await ro(t,[],e,s,r.date,void 0,void 0,void 0,n);i.push(o)}await Promise.all(r.userIDs.map((async function(t,i){const s=Ga.fromObject(t),o={userID:s,key:e},c=6!==e.version?a():{};c.signatureType=T.signature.certPositive,0===i&&(c.isPrimaryUserID=!0);return{userIDPacket:s,signaturePacket:await ro(o,[],e,c,r.date,void 0,void 0,void 0,n)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{i.push(e),i.push(t)}))})),await Promise.all(t.map((async function(t,i){const s=r.subkeys[i];return{secretSubkeyPacket:t,subkeySignaturePacket:await to(t,e,s,n)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{i.push(e),i.push(t)}))}));const o={key:e};return i.push(await ro(o,[],e,{signatureType:T.signature.keyRevocation,reasonForRevocationFlag:T.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,n)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new mo(i)}async function vo({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...M,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!F.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!F.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await ee(e);if(t!==T.armor.publicKey&&t!==T.armor.privateKey)throw Error("Armored text not of type key");s=r}else s=t;const a=await ba.fromBinary(s,bo,r),o=a.indexOfTag(T.packet.publicKey,T.packet.secretKey);if(0===o.length)throw Error("No key packet found");return ko(a.slice(o[0],o[1]))}async function Bo({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...M,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!F.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!F.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await ee(e);if(t!==T.armor.privateKey)throw Error("Armored text not of type private key");s=r}else s=t;const a=await ba.fromBinary(s,bo,r),o=a.indexOfTag(T.packet.publicKey,T.packet.secretKey);for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:t,data:r}=await ee(e);if(t!==T.armor.publicKey&&t!==T.armor.privateKey)throw Error("Armored text not of type key");i=r}const a=[],o=await ba.fromBinary(i,bo,r),c=o.indexOfTag(T.packet.publicKey,T.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(T.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,n=new Date,i=M){const s=this.packets.filterByTag(T.packet.symmetricallyEncryptedData,T.packet.symEncryptedIntegrityProtectedData,T.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const a=s[0],o=a.cipherAlgorithm,c=r||await this.decryptSessionKeys(e,t,o,n,i);let h=null;const u=Promise.all(c.map((async({algorithm:e,data:t})=>{if(!F.isUint8Array(t)||!a.cipherAlgorithm&&!F.isString(e))throw Error("Invalid session key for decryption.");try{const r=a.cipherAlgorithm||T.write(T.symmetric,e);await a.decrypt(r,t,i)}catch(e){F.printDebugError(e),h=e}})));if(U(a.encrypted),a.encrypted=null,await u,!a.packets||!a.packets.length)throw h||Error("Decryption failed.");const l=new Po(a.packets);return a.packets=new ba,l}async decryptSessionKeys(e,t,r,n=new Date,i=M){let s,a=[];if(t){const e=this.packets.filterByTag(T.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await ba.fromBinary(e.write(),Co,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){F.printDebugError(e),e instanceof hs&&(s=e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(T.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let o;try{o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket))}catch(e){return void(s=e)}let c=[T.symmetric.aes256,T.symmetric.aes128,T.symmetric.tripledes,T.symmetric.cast5];try{const t=await e.getPrimarySelfSignature(n,void 0,i);t.preferredSymmetricAlgorithms&&(c=c.concat(t.preferredSymmetricAlgorithms))}catch(e){}await Promise.all(o.map((async function(e){if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===T.publicKey.rsaEncrypt||t.publicKeyAlgorithm===T.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===T.publicKey.rsaSign||t.publicKeyAlgorithm===T.publicKey.elgamal)){const n=t.write();await Promise.all((r?[r]:Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map((async t=>{const r=new Qa;r.read(n);const i={sessionKeyAlgorithm:t,sessionKey:cs.generateSessionKey(t)};try{await r.decrypt(e,i),a.push(r)}catch(e){F.printDebugError(e),s=e}})))}else try{await t.decrypt(e);const n=r||t.sessionKeyAlgorithm;if(n&&!c.includes(T.write(T.symmetric,n)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){F.printDebugError(e),s=e}})))}))),U(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+F.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:e.sessionKeyAlgorithm&&T.read(T.symmetric,e.sessionKeyAlgorithm)})))}throw s||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(T.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],n=M){const{symmetricAlgo:i,aeadAlgo:s}=await async function(e=[],t=new Date,r=[],n=M){const i=await Promise.all(e.map(((e,i)=>e.getPrimarySelfSignature(t,r[i],n))));if(e.length?i.every((e=>e.features&&e.features[0]&T.features.seipdv2)):n.aeadProtect){const e={symmetricAlgo:T.symmetric.aes128,aeadAlgo:T.aead.ocb},t=[{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:n.preferredAEADAlgorithm},{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:T.aead.ocb},{symmetricAlgo:T.symmetric.aes128,aeadAlgo:n.preferredAEADAlgorithm}];for(const e of t)if(i.every((t=>t.preferredCipherSuites&&t.preferredCipherSuites.some((t=>t[0]===e.symmetricAlgo&&t[1]===e.aeadAlgo)))))return e;return e}const s=T.symmetric.aes128,a=n.preferredSymmetricAlgorithm;return{symmetricAlgo:i.every((e=>e.preferredSymmetricAlgorithms&&e.preferredSymmetricAlgorithms.includes(a)))?a:s,aeadAlgo:void 0}}(e,t,r,n),a=T.read(T.symmetric,i),o=s?T.read(T.aead,s):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&(e.keyPacket.algorithm===T.publicKey.x25519||e.keyPacket.algorithm===T.publicKey.x448)&&!o&&!F.isAES(i))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:cs.generateSessionKey(i),algorithm:a,aeadAlgorithm:o}}async encrypt(e,t,r,n=!1,i=[],s=new Date,a=[],o=M){if(r){if(!F.isUint8Array(r.data)||!F.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Po.generateSessionKey(e,s,a,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Po.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:h,aeadAlgorithm:u}=r,l=await Po.encryptSessionKey(c,h,u,e,t,n,i,s,a,o),y=Da.fromObject({version:u?2:1,aeadAlgorithm:u?T.write(T.aead,u):null});y.packets=this.packets;const f=T.write(T.symmetric,h);return await y.encrypt(f,c,o),l.packets.push(y),y.packets=new ba,l}static async encryptSessionKey(e,t,r,n,i,s=!1,a=[],o=new Date,c=[],h=M){const u=new ba,l=T.write(T.symmetric,t),y=r&&T.write(T.aead,r);if(n){const t=await Promise.all(n.map((async function(t,r){const n=await t.getEncryptionKey(a[r],o,c,h),i=Qa.fromObject({version:y?6:3,encryptionKeyPacket:n.keyPacket,anonymousRecipient:s,sessionKey:e,sessionKeyAlgorithm:l});return await i.encrypt(n.keyPacket),delete i.sessionKey,i})));u.push(...t)}if(i){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,n=async function(e,s,a,o){const c=new La(h);if(c.sessionKey=e,c.sessionKeyAlgorithm=s,a&&(c.aeadAlgorithm=a),await c.encrypt(o,h),h.passwordCollisionCheck){if(1!==(await Promise.all(i.map((e=>t(c,e))))).reduce(r))return n(e,s,o)}return delete c.sessionKey,c},s=await Promise.all(i.map((t=>n(e,l,y,t))));u.push(...s)}return new Po(u)}async sign(e=[],t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=M){const h=new ba,u=this.packets.findPacket(T.packet.literalData);if(!u)throw Error("No literal data packet to sign.");const l=await Uo(u,e,t,r,n,i,s,a,o,!1,c),y=l.map(((e,t)=>wa.fromSignaturePacket(e,0===t))).reverse();return h.push(...y),h.push(u),h.push(...l),new Po(h)}compress(e,t=M){if(e===T.compression.uncompressed)return this;const r=new Ea(t);r.algorithm=e,r.packets=this.packets;const n=new ba;return n.push(r),new Po(n)}async signDetached(e=[],t=[],r=null,n=[],i=[],s=new Date,a=[],o=[],c=M){const h=this.packets.findPacket(T.packet.literalData);if(!h)throw Error("No literal data packet to sign.");return new Ya(await Uo(h,e,t,r,n,i,s,a,o,!0,c))}async verify(e,t=new Date,r=M){const n=this.unwrapCompressed(),i=n.packets.filterByTag(T.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");h(n.packets.stream)&&n.packets.push(...await P(n.packets.stream,(e=>e||[])));const s=n.packets.filterByTag(T.packet.onePassSignature).reverse(),a=n.packets.filterByTag(T.packet.signature);return s.length&&!a.length&&F.isStream(n.packets.stream)&&!h(n.packets.stream)?(await Promise.all(s.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=x((async()=>(await e.correspondingSig).signatureData)),e.hashed=P(await e.hash(e.signatureType,i[0],void 0,!1)),e.hashed.catch((()=>{}))}))),n.packets.stream=B(n.packets.stream,(async(e,t)=>{const r=Q(e),n=R(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await n.abort(e)}})),xo(s,i,e,t,!1,r)):xo(a,i,e,t,!1,r)}verifyDetached(e,t,r=new Date,n=M){const i=this.unwrapCompressed().packets.filterByTag(T.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");return xo(e.packets.filterByTag(T.packet.signature),i,t,r,!0,n)}unwrapCompressed(){const e=this.packets.filterByTag(T.packet.compressedData);return e.length?new Po(e[0].packets):this}async appendSignature(e,t=M){await this.packets.read(F.isUint8Array(e)?e:(await ee(e)).data,Do,t)}write(){return this.packets.write()}armor(e=M){const t=this.packets[this.packets.length-1],r=t.constructor.tag===Da.tag?2!==t.version:this.packets.some((e=>e.constructor.tag===pa.tag&&6!==e.version));return te(T.armor.message,this.write(),null,null,null,r,e)}}async function Uo(e,t,r=[],n=null,i=[],s=new Date,a=[],o=[],c=[],h=!1,u=M){const l=new ba,y=null===e.text?T.signature.binary:T.signature.text;if(await Promise.all(t.map((async(t,n)=>{const l=a[n];if(!t.isPrivate())throw Error("Need private key for signing");const f=await t.getSigningKey(i[n],s,l,u);return ro(e,r.length?r:[t],f.keyPacket,{signatureType:y},s,o,c,h,u)}))).then((e=>{l.push(...e)})),n){const e=n.packets.filterByTag(T.packet.signature);l.push(...e)}return l}async function xo(e,t,r,n=new Date,i=!1,s=M){return Promise.all(e.filter((function(e){return["text","binary"].includes(T.read(T.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,n=new Date,i=!1,s=M){let a,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){a=t,o=r[0];break}}const c=e instanceof wa?e.correspondingSig:e,h={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],n,i,s);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await a.getSigningKey(o.getKeyID(),r.created,void 0,s)}catch(e){if(!s.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await a.getSigningKey(o.getKeyID(),n,void 0,s)}return!0})(),signature:(async()=>{const e=await c,t=new ba;return e&&t.push(e),new Ya(t)})()};return h.signature.catch((()=>{})),h.verified.catch((()=>{})),h}(e,t,r,n,i,s)})))}async function Qo({armoredMessage:e,binaryMessage:t,config:r,...n}){r={...M,...r};let i=e||t;if(!i)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!F.isString(e)&&!F.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!F.isUint8Array(t)&&!F.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));const a=F.isStream(i);if(e){const{type:e,data:t}=await ee(i);if(e!==T.armor.message)throw Error("Armored text not of type message");i=t}const o=await ba.fromBinary(i,Ko,r),c=new Po(o);return c.fromStream=a,c}async function Ro({text:e,binary:t,filename:r,date:n=new Date,format:i=(void 0!==e?"utf8":"binary"),...s}){const a=void 0!==e?e:t;if(void 0===a)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!F.isString(e)&&!F.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!F.isUint8Array(t)&&!F.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=F.isStream(a),h=new ua(n);void 0!==e?h.setText(a,T.write(T.literal,i)):h.setBytes(a,T.write(T.literal,i)),void 0!==r&&h.setFilename(r);const u=new ba;u.push(h);const l=new Po(u);return l.fromStream=c,l}const Lo=/*#__PURE__*/F.constructAllowedPackets([pa]);class To{constructor(e,t){if(this.text=F.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof Ya))throw Error("Invalid signature input");this.signature=t||new Ya(new ba)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=M){const h=new ua;h.setText(this.text);const u=new Ya(await Uo(h,e,t,r,n,i,s,a,o,!0,c));return new To(this.text,u)}verify(e,t=new Date,r=M){const n=this.signature.packets.filterByTag(T.packet.signature),i=new ua;return i.setText(this.text),xo(n,[i],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=M){const t=this.signature.packets.some((e=>6!==e.version)),r={hash:t?Array.from(new Set(this.signature.packets.map((e=>T.read(T.hash,e.hashAlgorithm).toUpperCase())))).join():null,text:this.text,data:this.signature.packets.write()};return te(T.armor.signed,r,void 0,void 0,void 0,t,e)}}async function Mo({cleartextMessage:e,config:t,...r}){if(t={...M,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!F.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const n=Object.keys(r);if(n.length>0)throw Error("Unknown option: "+n.join(", "));const i=await ee(e);if(i.type!==T.armor.signed)throw Error("No cleartext signed message.");const s=await ba.fromBinary(i.data,Lo,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let n=0;n{const t=e.match(/^Hash: (.+)$/);if(!t)throw Error('Only "Hash" header allowed in cleartext signed message');{const e=t[1].replace(/\s/g,"").split(",").map((e=>{try{return T.write(T.hash,e.toLowerCase())}catch(t){throw Error("Unknown hash algorithm in armor header: "+e.toLowerCase())}}));n.push(...e)}})),n.length&&!r(n))throw Error("Hash algorithm mismatch in armor header and signature")}(i.headers,s);const a=new Ya(s);return new To(i.text,a)}async function No({text:e,...t}){if(!e)throw Error("createCleartextMessage: must pass options object containing `text`");if(!F.isString(e))throw Error("createCleartextMessage: options.text must be a string");const r=Object.keys(t);if(r.length>0)throw Error("Unknown option: "+r.join(", "));return new To(e)}async function Fo({userIDs:e=[],passphrase:t,type:r,curve:n,rsaBits:i=4096,keyExpirationTime:s=0,date:a=new Date,subkeys:o=[{}],format:c="armored",config:h,...u}){tc(h={...M,...h}),r||n?(r=r||"ecc",n=n||"curve25519Legacy"):(r=h.v6Keys?"curve25519":"ecc",n="curve25519Legacy"),e=rc(e);const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(0===e.length&&!h.v6Keys)throw Error("UserIDs are required for V4 keys");if("rsa"===r&&iao(e.subkeys[r],e)));let r=[$a(e,t)];r=r.concat(e.subkeys.map((e=>Za(e,t))));const n=await Promise.all(r),i=await Eo(n[0],n.slice(1),e,t),s=await i.getRevocationCertificate(e.date,t);return i.revocationSignatures=[],{key:i,revocationCertificate:s}}(y,h);return e.getKeys().forEach((({keyPacket:e})=>uo(e,h))),{privateKey:sc(e,c,h),publicKey:sc(e.toPublic(),c,h),revocationCertificate:t}}catch(e){throw F.wrapError("Error generating keypair",e)}}async function Ho({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:n=0,date:i,format:s="armored",config:a,...o}){tc(a={...M,...a}),t=rc(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length&&6!==e.keyPacket.version)throw Error("UserIDs are required for V4 keys");const h={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:n,date:i};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const n=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,i={key:n,bind:r},s=await Xa(e.bindingSignatures,n,T.signature.subkeyBinding,i,null,t).catch((()=>({})));return{sign:s.keyFlags&&s.keyFlags[0]&T.keyFlags.signData}}))));const i=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==i.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const s=await Eo(n,i,e,t),a=await s.getRevocationCertificate(e.date,t);return s.revocationSignatures=[],{key:s,revocationCertificate:a};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=F.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(h,a);return{privateKey:sc(e,s,a),publicKey:sc(e.toPublic(),s,a),revocationCertificate:t}}catch(e){throw F.wrapError("Error reformatting keypair",e)}}async function Oo({key:e,revocationCertificate:t,reasonForRevocation:r,date:n=new Date,format:i="armored",config:s,...a}){tc(s={...M,...s});const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const a=t?await e.applyRevocationCertificate(t,n,s):await e.revoke(r,n,s);return a.isPrivate()?{privateKey:sc(a,i,s),publicKey:sc(a.toPublic(),i,s)}:{privateKey:null,publicKey:sc(a,i,s)}}catch(e){throw F.wrapError("Error revoking key",e)}}async function zo({privateKey:e,passphrase:t,config:r,...n}){tc(r={...M,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const s=e.clone(!0),a=F.isArray(t)?t:[t];try{return await Promise.all(s.getKeys().map((e=>F.anyPromise(a.map((t=>e.keyPacket.decrypt(t))))))),await s.validate(r),s}catch(e){throw s.clearPrivateParams(),F.wrapError("Error decrypting private key",e)}}async function _o({privateKey:e,passphrase:t,config:r,...n}){tc(r={...M,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const s=e.clone(!0),a=s.getKeys(),o=F.isArray(t)?t:Array(a.length).fill(t);if(o.length!==a.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(a.map((async(e,t)=>{const{keyPacket:n}=e;await n.encrypt(o[t],r),n.clearPrivateParams()}))),s}catch(e){throw s.clearPrivateParams(),F.wrapError("Error encrypting private key",e)}}async function Go({message:e,encryptionKeys:t,signingKeys:r,passwords:n,sessionKey:i,format:s="armored",signature:a=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:h=[],date:u=new Date,signingUserIDs:l=[],encryptionUserIDs:y=[],signatureNotations:f=[],config:g,...p}){if(tc(g={...M,...g}),Zo(e),Xo(s),t=rc(t),r=rc(r),n=rc(n),c=rc(c),h=rc(h),l=rc(l),y=rc(y),f=rc(f),p.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(p.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(p.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==p.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const d=Object.keys(p);if(d.length>0)throw Error("Unknown option: "+d.join(", "));r||(r=[]);try{if((r.length||a)&&(e=await e.sign(r,t,a,c,u,l,h,f,g)),e=e.compress(await async function(e=[],t=new Date,r=[],n=M){const i=T.compression.uncompressed,s=n.preferredCompressionAlgorithm,a=await Promise.all(e.map((async function(e,i){const a=(await e.getPrimarySelfSignature(t,r[i],n)).preferredCompressionAlgorithms;return!!a&&a.indexOf(s)>=0})));return a.every(Boolean)?s:i}(t,u,y,g),g),e=await e.encrypt(t,n,i,o,h,u,y,g),"object"===s)return e;const p="armored"===s?e.armor(g):e.write();return await nc(p)}catch(e){throw F.wrapError("Error encrypting message",e)}}async function jo({message:e,decryptionKeys:t,passwords:r,sessionKeys:n,verificationKeys:i,expectSigned:s=!1,format:a="utf8",signature:o=null,date:c=new Date,config:h,...u}){if(tc(h={...M,...h}),Zo(e),i=rc(i),t=rc(t),r=rc(r),n=rc(n),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(u.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));try{const u=await e.decrypt(t,r,n,c,h);i||(i=[]);const l={};if(l.signatures=o?await u.verifyDetached(o,i,c,h):await u.verify(i,c,h),l.data="binary"===a?u.getLiteralData():u.getText(),l.filename=u.getFilename(),ic(l,e),s){if(0===i.length)throw Error("Verification keys are required to verify message signatures");if(0===l.signatures.length)throw Error("Message is not signed");l.data=m([l.data,x((async()=>{await F.anyPromise(l.signatures.map((e=>e.verified)))}))])}return l.data=await nc(l.data),l}catch(e){throw F.wrapError("Error decrypting message",e)}}async function qo({message:e,signingKeys:t,recipientKeys:r=[],format:n="armored",detached:i=!1,signingKeyIDs:s=[],date:a=new Date,signingUserIDs:o=[],recipientUserIDs:c=[],signatureNotations:h=[],config:u,...l}){if(tc(u={...M,...u}),$o(e),Xo(n),t=rc(t),s=rc(s),o=rc(o),r=rc(r),c=rc(c),h=rc(h),l.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==l.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(e instanceof To&&"binary"===n)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof To&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let l;if(l=i?await e.signDetached(t,r,void 0,s,a,o,c,h,u):await e.sign(t,r,void 0,s,a,o,c,h,u),"object"===n)return l;return l="armored"===n?l.armor(u):l.write(),i&&(l=B(e.packets.write(),(async(e,t)=>{await Promise.all([b(l,t),P(e).catch((()=>{}))])}))),await nc(l)}catch(e){throw F.wrapError("Error signing message",e)}}async function Vo({message:e,verificationKeys:t,expectSigned:r=!1,format:n="utf8",signature:i=null,date:s=new Date,config:a,...o}){if(tc(a={...M,...a}),$o(e),t=rc(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof To&&"binary"===n)throw Error("Can't return cleartext message data as binary");if(e instanceof To&&i)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=i?await e.verifyDetached(i,t,s,a):await e.verify(t,s,a),o.data="binary"===n?e.getLiteralData():e.getText(),e.fromStream&&!i&&ic(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=m([o.data,x((async()=>{await F.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await nc(o.data),o}catch(e){throw F.wrapError("Error verifying signed message",e)}}async function Jo({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:n,...i}){if(tc(n={...M,...n}),e=rc(e),r=rc(r),i.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await Po.generateSessionKey(e,t,r,n)}catch(e){throw F.wrapError("Error generating session key",e)}}async function Yo({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:n,passwords:i,format:s="armored",wildcard:a=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:h=[],config:u,...l}){if(tc(u={...M,...u}),function(e){if(!F.isUint8Array(e))throw Error("Parameter [data] must be of type Uint8Array")}(e),function(e,t){if(!F.isString(e))throw Error("Parameter ["+t+"] must be of type String")}(t,"algorithm"),Xo(s),n=rc(n),i=rc(i),o=rc(o),h=rc(h),l.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(!(n&&0!==n.length||i&&0!==i.length))throw Error("No encryption keys or passwords provided.");try{return sc(await Po.encryptSessionKey(e,t,r,n,i,a,o,c,h,u),s,u)}catch(e){throw F.wrapError("Error encrypting session key",e)}}async function Wo({message:e,decryptionKeys:t,passwords:r,date:n=new Date,config:i,...s}){if(tc(i={...M,...i}),Zo(e),t=rc(t),r=rc(r),s.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const a=Object.keys(s);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await e.decryptSessionKeys(t,r,void 0,n,i)}catch(e){throw F.wrapError("Error decrypting session keys",e)}}function Zo(e){if(!(e instanceof Po))throw Error("Parameter [message] needs to be of type Message")}function $o(e){if(!(e instanceof To||e instanceof Po))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Xo(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const ec=Object.keys(M).length;function tc(e){const t=Object.keys(e);if(t.length!==ec)for(const e of t)if(void 0===M[e])throw Error("Unknown config property: "+e)}function rc(e){return e&&!F.isArray(e)&&(e=[e]),e}async function nc(e){return"array"===F.isStream(e)?P(e):e}function ic(e,t){e.data=B(t.packets.stream,(async(t,r)=>{await b(e.data,r,{preventClose:!0});const n=R(r);try{await P(t,(e=>e)),await n.close()}catch(e){await n.abort(e)}}))}function sc(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}function ac(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, not "+e)}function oc(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function cc(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function hc(e,t){oc(e);const r=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),yc=(e,t)=>e<<32-t|e>>>t,fc=(e,t)=>e<>>32-t>>>0,gc=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pc(e){for(let r=0;r>>8&65280|t>>>24&255;var t}function dc(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Ac(e){return"string"==typeof e&&(e=dc(e)),oc(e),e}function wc(...e){let t=0;for(let r=0;re().update(Ac(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function kc(e=32){if(uc&&"function"==typeof uc.getRandomValues)return uc.getRandomValues(new Uint8Array(e));if(uc&&"function"==typeof uc.randomBytes)return uc.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}const Ec=(e,t,r)=>e&t^~e&r,vc=(e,t,r)=>e&t^e&r^t&r;class Bc extends mc{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=lc(this.buffer)}update(e){cc(this);const{view:t,buffer:r,blockLen:n}=this,i=(e=Ac(e)).length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let e=s;e>i&s),o=Number(r&s),c=n?4:0,h=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+h,o,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const a=lc(e),o=this.outputLen;if(o%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=yc(r,17)^yc(r,19)^r>>>10;Kc[e]=i+Kc[e-7]+n+Kc[e-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(yc(a,6)^yc(a,11)^yc(a,25))+Ec(a,o,c)+Ic[e]+Kc[e]|0,u=(yc(r,2)^yc(r,13)^yc(r,22))+vc(r,n,i)|0;h=c,c=o,o=a,a=s+t|0,s=i,i=n,n=r,r=t+u|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(r,n,i,s,a,o,c,h)}roundClean(){Kc.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Dc extends Cc{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Pc=/* @__PURE__ */bc((()=>new Cc)),Uc=/* @__PURE__ */bc((()=>new Dc));class xc extends mc{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.wrapConstructor");ac(e.outputLen),ac(e.blockLen)}(e);const r=Ac(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew xc(e,t).update(r).digest();Qc.create=(e,t)=>new xc(e,t) +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const Rc=/* @__PURE__ */BigInt(0),Lc=/* @__PURE__ */BigInt(1),Tc=/* @__PURE__ */BigInt(2);function Mc(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Nc(e){if(!Mc(e))throw Error("Uint8Array expected")}function Fc(e,t){if("boolean"!=typeof t)throw Error(`${e} must be valid boolean, got "${t}".`)}const Hc=/* @__PURE__ */Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Oc(e){Nc(e);let t="";for(let r=0;r=Gc._0&&e<=Gc._9?e-Gc._0:e>=Gc._A&&e<=Gc._F?e-(Gc._A-10):e>=Gc._a&&e<=Gc._f?e-(Gc._a-10):void 0}function qc(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t"bigint"==typeof e&&Rc<=e;function eh(e,t,r){return Xc(e)&&Xc(t)&&Xc(r)&&t<=e&&eRc;e>>=Lc,t+=1);return t}const nh=e=>(Tc<new Uint8Array(e),sh=e=>Uint8Array.from(e);function ah(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");let n=ih(e),i=ih(e),s=0;const a=()=>{n.fill(1),i.fill(0),s=0},o=(...e)=>r(i,n,...e),c=(e=ih())=>{i=o(sh([0]),e),n=o(),0!==e.length&&(i=o(sh([1]),e),n=o())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(a(),c(e);!(r=t(h()));)c();return a(),r}}const oh={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Mc(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function ch(e,t,r={}){const n=(t,r,n)=>{const i=oh[r];if("function"!=typeof i)throw Error(`Invalid validator "${r}", expected function`);const s=e[t];if(!(n&&void 0===s||i(s,e)))throw Error(`Invalid param ${t+""}=${s} (${typeof s}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function hh(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}var uh=/*#__PURE__*/Object.freeze({__proto__:null,aInRange:th,abool:Fc,abytes:Nc,bitGet:function(e,t){return e>>BigInt(t)&Lc},bitLen:rh,bitMask:nh,bitSet:function(e,t,r){return e|(r?Lc:Rc)<{throw Error("not implemented")},numberToBytesBE:Yc,numberToBytesLE:Wc,numberToHexUnpadded:zc,numberToVarBytesBE:function(e){return qc(zc(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:ch}); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const lh=BigInt(0),yh=BigInt(1),fh=BigInt(2),gh=BigInt(3),ph=BigInt(4),dh=BigInt(5),Ah=BigInt(8);function wh(e,t){const r=e%t;return r>=lh?r:t+r}function mh(e,t,r){if(r<=lh||t 0");if(r===yh)return lh;let n=yh;for(;t>lh;)t&yh&&(n=n*e%r),e=e*e%r,t>>=yh;return n}function bh(e,t,r){let n=e;for(;t-- >lh;)n*=n,n%=r;return n}function kh(e,t){if(e===lh||t<=lh)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=wh(e,t),n=t,i=lh,s=yh;for(;r!==lh;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==yh)throw Error("invert: does not exist");return wh(i,t)}function Eh(e){if(e%ph===gh){const t=(e+yh)/ph;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}if(e%Ah===dh){const t=(e-dh)/Ah;return function(e,r){const n=e.mul(r,fh),i=e.pow(n,t),s=e.mul(r,i),a=e.mul(e.mul(s,fh),i),o=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),r))throw Error("Cannot find square root");return o}}return function(e){const t=(e-yh)/fh;let r,n,i;for(r=e-yh,n=0;r%fh===lh;r/=fh,n++);for(i=fh;i 0, got "+e);const{nBitLength:i,nByteLength:s}=Bh(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const a=Eh(e),o=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:nh(i),ZERO:lh,ONE:yh,create:t=>wh(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("Invalid field element: expected bigint, got "+typeof t);return lh<=t&&te===lh,isOdd:e=>(e&yh)===yh,neg:t=>wh(-t,e),eql:(e,t)=>e===t,sqr:t=>wh(t*t,e),add:(t,r)=>wh(t+r,e),sub:(t,r)=>wh(t-r,e),mul:(t,r)=>wh(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===lh)return e.ONE;if(r===yh)return t;let n=e.ONE,i=t;for(;r>lh;)r&yh&&(n=e.mul(n,i)),i=e.sqr(i),r>>=yh;return n}(o,e,t),div:(t,r)=>wh(t*kh(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>kh(t,e),sqrt:n.sqrt||(e=>a(o,e)),invertBatch:e=>function(e,t){const r=Array(t.length),n=t.reduce(((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n))),e.ONE),i=e.inv(n);return t.reduceRight(((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n))),i),r}(o,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Wc(e,s):Yc(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?Jc(e):Vc(e)}});return Object.freeze(o)}function Sh(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Kh(e){const t=Sh(e);return t+Math.ceil(t/2)} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const Ch=BigInt(0),Dh=BigInt(1),Ph=new WeakMap,Uh=new WeakMap;function xh(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`Wrong window size=${e}, should be [1..${t}]`)},i=e=>{n(e);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}};return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,i=t;for(;r>Ch;)r&Dh&&(n=n.add(i)),i=i.double(),r>>=Dh;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=i(t),s=[];let a=e,o=a;for(let e=0;e>=y,i>o&&(i-=l,s+=Dh);const a=t,f=t+Math.abs(i)-1,g=e%2!=0,p=i<0;0===i?h=h.add(r(g,n[a])):c=c.add(r(p,n[f]))}return{p:c,f:h}},wNAFCached(e,t,r){const n=Uh.get(e)||1;let i=Ph.get(e);return i||(i=this.precomputeWindow(e,n),1!==n&&Ph.set(e,r(i))),this.wNAF(n,i,t)},setWindowSize(e,t){n(t),Uh.set(e,t),Ph.delete(e)}}}function Qh(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw Error("wrong scalar at index "+r)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw Error("wrong point at index "+r)}));const i=rh(BigInt(r.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<=0;t-=s){o.fill(e.ZERO);for(let e=0;e>BigInt(t)&BigInt(a));o[s]=o[s].add(r[e])}let i=e.ZERO;for(let t=o.length-1,r=e.ZERO;t>0;t--)r=r.add(o[t]),i=i.add(r);if(h=h.add(i),0!==t)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),ch(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bh(e.n,e.nBitLength),...e,p:e.Fp.ORDER})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lh(e){void 0!==e.lowS&&Fc("lowS",e.lowS),void 0!==e.prehash&&Fc("prehash",e.prehash)}const{bytesToNumberBE:Th,hexToBytes:Mh}=uh,Nh={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=Nh;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=zc(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?zc(i.length/2|128):"";return`${zc(e)}${s}${i}${t}`},decode(e,t){const{Err:r}=Nh;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let s=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const a=t.subarray(n,n+e);if(a.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=Nh;if(e{const i=t.toAffine();return $c(Uint8Array.from([4]),r.toBytes(i.x),r.toBytes(i.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function a(e){const{a:n,b:i}=t,s=r.sqr(e),a=r.mul(s,e);return r.add(r.add(a,r.mul(e,n)),i)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:i,n:s}=t;if(r&&"bigint"!=typeof e){if(Mc(e)&&(e=Oc(e)),"string"!=typeof e||!r.includes(e.length))throw Error("Invalid key");e=e.padStart(2*n,"0")}let a;try{a="bigint"==typeof e?e:Vc(Zc("private key",e,n))}catch(t){throw Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return i&&(a=wh(a,s)),th("private key",a,Hh,s),a}function c(e){if(!(e instanceof l))throw Error("ProjectivePoint expected")}const h=hh(((e,t)=>{const{px:n,py:i,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),c=r.mul(i,t),h=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(h,r.ONE))throw Error("invZ was invalid");return{x:o,y:c}})),u=hh((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error("bad point: x or y not FE");const s=r.sqr(i),o=a(n);if(!r.eql(s,o))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));class l{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t))throw Error("y required");if(null==n||!r.isValid(n))throw Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error("invalid affine point");if(e instanceof l)throw Error("projective point not allowed");const i=e=>r.eql(e,r.ZERO);return i(t)&&i(n)?l.ZERO:new l(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(l.fromAffine)}static fromHex(e){const t=l.fromAffine(s(Zc("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return l.BASE.multiply(o(e))}static msm(e,t){return Qh(l,n,e,t)}_setWindowSize(e){f.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:i}=this,{px:s,py:a,pz:o}=e,h=r.eql(r.mul(t,o),r.mul(s,i)),u=r.eql(r.mul(n,o),r.mul(a,i));return h&&u}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,i=r.mul(n,Oh),{px:s,py:a,pz:o}=this;let c=r.ZERO,h=r.ZERO,u=r.ZERO,y=r.mul(s,s),f=r.mul(a,a),g=r.mul(o,o),p=r.mul(s,a);return p=r.add(p,p),u=r.mul(s,o),u=r.add(u,u),c=r.mul(e,u),h=r.mul(i,g),h=r.add(c,h),c=r.sub(f,h),h=r.add(f,h),h=r.mul(c,h),c=r.mul(p,c),u=r.mul(i,u),g=r.mul(e,g),p=r.sub(y,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(y,y),y=r.add(u,y),y=r.add(y,g),y=r.mul(y,p),h=r.add(h,y),g=r.mul(a,o),g=r.add(g,g),y=r.mul(g,p),c=r.sub(c,y),u=r.mul(g,f),u=r.add(u,u),u=r.add(u,u),new l(c,h,u)}add(e){c(e);const{px:n,py:i,pz:s}=this,{px:a,py:o,pz:h}=e;let u=r.ZERO,y=r.ZERO,f=r.ZERO;const g=t.a,p=r.mul(t.b,Oh);let d=r.mul(n,a),A=r.mul(i,o),w=r.mul(s,h),m=r.add(n,i),b=r.add(a,o);m=r.mul(m,b),b=r.add(d,A),m=r.sub(m,b),b=r.add(n,s);let k=r.add(a,h);return b=r.mul(b,k),k=r.add(d,w),b=r.sub(b,k),k=r.add(i,s),u=r.add(o,h),k=r.mul(k,u),u=r.add(A,w),k=r.sub(k,u),f=r.mul(g,b),u=r.mul(p,w),f=r.add(u,f),u=r.sub(A,f),f=r.add(A,f),y=r.mul(u,f),A=r.add(d,d),A=r.add(A,d),w=r.mul(g,w),b=r.mul(p,b),A=r.add(A,w),w=r.sub(d,w),w=r.mul(g,w),b=r.add(b,w),d=r.mul(A,b),y=r.add(y,d),d=r.mul(k,b),u=r.mul(m,u),u=r.sub(u,d),d=r.mul(m,A),f=r.mul(k,f),f=r.add(f,d),new l(u,y,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(l.ZERO)}wNAF(e){return f.wNAFCached(this,e,l.normalizeZ)}multiplyUnsafe(e){th("scalar",e,Fh,t.n);const n=l.ZERO;if(e===Fh)return n;if(e===Hh)return this;const{endo:i}=t;if(!i)return f.unsafeLadder(this,e);let{k1neg:s,k1:a,k2neg:o,k2:c}=i.splitScalar(e),h=n,u=n,y=this;for(;a>Fh||c>Fh;)a&Hh&&(h=h.add(y)),c&Hh&&(u=u.add(y)),y=y.double(),a>>=Hh,c>>=Hh;return s&&(h=h.negate()),o&&(u=u.negate()),u=new l(r.mul(u.px,i.beta),u.py,u.pz),h.add(u)}multiply(e){const{endo:n,n:i}=t;let s,a;if(th("scalar",e,Hh,i),n){const{k1neg:t,k1:i,k2neg:o,k2:c}=n.splitScalar(e);let{p:h,f:u}=this.wNAF(i),{p:y,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),y=f.constTimeNegate(o,y),y=new l(r.mul(y.px,n.beta),y.py,y.pz),s=h.add(y),a=u.add(g)}else{const{p:t,f:r}=this.wNAF(e);s=t,a=r}return l.normalizeZ([s,a])[0]}multiplyAndAddUnsafe(e,t,r){const n=l.BASE,i=(e,t)=>t!==Fh&&t!==Hh&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=i(this,t).add(i(e,r));return s.is0()?void 0:s}toAffine(e){return h(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Hh)return!0;if(r)return r(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===Hh?this:r?r(l,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Fc("isCompressed",e),this.assertValidity(),i(l,this,e)}toHex(e=!0){return Fc("isCompressed",e),Oc(this.toRawBytes(e))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);const y=t.nBitLength,f=xh(l,t.endo?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:o,weierstrassEquation:a,isWithinCurveOrder:function(e){return eh(e,Hh,t.n)}}}function _h(e){const t=function(e){const t=Rh(e);return ch(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,i=r.BYTES+1,s=2*r.BYTES+1;function a(e){return wh(e,n)}function o(e){return kh(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:l}=zh({...t,toBytes(e,t,n){const i=t.toAffine(),s=r.toBytes(i.x),a=$c;return Fc("isCompressed",n),n?a(Uint8Array.from([t.hasEvenY()?2:3]),s):a(Uint8Array.from([4]),s,r.toBytes(i.y))},fromBytes(e){const t=e.length,n=e[0],a=e.subarray(1);if(t!==i||2!==n&&3!==n){if(t===s&&4===n){return{x:r.fromBytes(a.subarray(0,r.BYTES)),y:r.fromBytes(a.subarray(r.BYTES,2*r.BYTES))}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const e=Vc(a);if(!eh(e,Hh,r.ORDER))throw Error("Point is not on curve");const t=u(e);let i;try{i=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+t)}return!(1&~n)!==((i&Hh)===Hh)&&(i=r.neg(i)),{x:e,y:i}}}}),y=e=>Oc(Yc(e,t.nByteLength));function f(e){return e>n>>Hh}const g=(e,t,r)=>Vc(e.slice(t,r));class p{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Zc("compactSignature",e,2*r),new p(g(e,0,r),g(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Nh.toSig(Zc("DER",e));return new p(t,r)}assertValidity(){th("r",this.r,Hh,n),th("s",this.s,Hh,n)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:i,recovery:s}=this,h=m(Zc("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+y(u)),g=o(u),p=a(-h*g),d=a(i*g),A=c.BASE.multiplyAndAddUnsafe(f,p,d);if(!A)throw Error("point at infinify");return A.assertValidity(),A}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return qc(this.toDERHex())}toDERHex(){return Nh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qc(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}const d={isValidPrivateKey(e){try{return h(e),!0}catch(e){return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const e=Kh(t.n);return function(e,t,r=!1){const n=e.length,i=Sh(t),s=Kh(t);if(n<16||n1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);const a=wh(r?Vc(e):Jc(e),t-yh)+yh;return r?Wc(a,i):Yc(a,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function A(e){const t=Mc(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===i||n===s:r?n===2*i||n===2*s:e instanceof c}const w=t.bits2int||function(e){const r=Vc(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},m=t.bits2int_modN||function(e){return a(w(e))},b=nh(t.nBitLength);function k(e){return th("num < 2^"+t.nBitLength,e,Fh,b),Yc(e,t.nByteLength)}function E(e,n,i=v){if(["recovered","canonical"].some((e=>e in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:y,prehash:g,extraEntropy:d}=i;null==y&&(y=!0),e=Zc("msgHash",e),Lh(i),g&&(e=Zc("prehashed msgHash",s(e)));const A=m(e),b=h(n),E=[k(b),k(A)];if(null!=d&&!1!==d){const e=!0===d?u(r.BYTES):d;E.push(Zc("extraEntropy",e))}const B=$c(...E),I=A;return{seed:B,k2sig:function(e){const t=w(e);if(!l(t))return;const r=o(t),n=c.BASE.multiply(t).toAffine(),i=a(n.x);if(i===Fh)return;const s=a(r*a(I+i*b));if(s===Fh)return;let h=(n.x===i?0:2)|Number(n.y&Hh),u=s;return y&&f(s)&&(u=function(e){return f(e)?a(-e):e}(s),h^=1),new p(i,u,h)}}}const v={lowS:t.lowS,prehash:!1},B={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(A(e))throw Error("first arg must be private key");if(!A(t))throw Error("second arg must be public key");return c.fromHex(t).multiply(h(e)).toRawBytes(r)},sign:function(e,r,n=v){const{seed:i,k2sig:s}=E(e,r,n),a=t;return ah(a.hash.outputLen,a.nByteLength,a.hmac)(i,s)},verify:function(e,r,n,i=B){const s=e;if(r=Zc("msgHash",r),n=Zc("publicKey",n),"strict"in i)throw Error("options.strict was renamed to lowS");Lh(i);const{lowS:h,prehash:u}=i;let l,y;try{if("string"==typeof s||Mc(s))try{l=p.fromDER(s)}catch(e){if(!(e instanceof Nh.Err))throw e;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:e,s:t}=s;l=new p(e,t)}}y=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;u&&(r=t.hash(r));const{r:f,s:g}=l,d=m(r),A=o(g),w=a(d*A),b=a(f*A),k=c.BASE.multiplyAndAddUnsafe(y,w,b)?.toAffine();return!!k&&a(k.x)===f},ProjectivePoint:c,Signature:p,utils:d}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gh(e){return{hash:e,hmac:(t,...r)=>Qc(e,t,wc(...r)),randomBytes:kc}}function jh(e,t){const r=t=>_h({...e,...Gh(t)});return Object.freeze({...r(t),create:r})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const qh=Ih(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Vh=jh({a:qh.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:qh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Pc),Jh=/* @__PURE__ */BigInt(2**32-1),Yh=/* @__PURE__ */BigInt(32);function Wh(e,t=!1){return t?{h:Number(e&Jh),l:Number(e>>Yh&Jh)}:{h:0|Number(e>>Yh&Jh),l:0|Number(e&Jh)}}function Zh(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;ie<>>32-r,Xh=(e,t,r)=>t<>>32-r,eu=(e,t,r)=>t<>>64-r,tu=(e,t,r)=>e<>>64-r;const ru={fromBig:Wh,split:Zh,toBig:(e,t)=>BigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:$h,rotlSL:Xh,rotlBH:eu,rotlBL:tu,add:function(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,add5H:(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},[nu,iu]=/* @__PURE__ */(()=>ru.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),su=/* @__PURE__ */new Uint32Array(80),au=/* @__PURE__ */new Uint32Array(80);class ou extends Bc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:l,Gh:y,Gl:f,Hh:g,Hl:p}=this;return[e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p]}set(e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|l,this.Gh=0|y,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(e,t){for(let r=0;r<16;r++,t+=4)su[r]=e.getUint32(t),au[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|su[e-15],r=0|au[e-15],n=ru.rotrSH(t,r,1)^ru.rotrSH(t,r,8)^ru.shrSH(t,r,7),i=ru.rotrSL(t,r,1)^ru.rotrSL(t,r,8)^ru.shrSL(t,r,7),s=0|su[e-2],a=0|au[e-2],o=ru.rotrSH(s,a,19)^ru.rotrBH(s,a,61)^ru.shrSH(s,a,6),c=ru.rotrSL(s,a,19)^ru.rotrBL(s,a,61)^ru.shrSL(s,a,6),h=ru.add4L(i,c,au[e-7],au[e-16]),u=ru.add4H(h,n,o,su[e-7],su[e-16]);su[e]=0|u,au[e]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:l,Fh:y,Fl:f,Gh:g,Gl:p,Hh:d,Hl:A}=this;for(let e=0;e<80;e++){const t=ru.rotrSH(u,l,14)^ru.rotrSH(u,l,18)^ru.rotrBH(u,l,41),w=ru.rotrSL(u,l,14)^ru.rotrSL(u,l,18)^ru.rotrBL(u,l,41),m=u&y^~u&g,b=l&f^~l&p,k=ru.add5L(A,w,b,iu[e],au[e]),E=ru.add5H(k,d,t,m,nu[e],su[e]),v=0|k,B=ru.rotrSH(r,n,28)^ru.rotrBH(r,n,34)^ru.rotrBH(r,n,39),I=ru.rotrSL(r,n,28)^ru.rotrBL(r,n,34)^ru.rotrBL(r,n,39),S=r&i^r&a^i&a,K=n&s^n&o^s&o;d=0|g,A=0|p,g=0|y,p=0|f,y=0|u,f=0|l,({h:u,l}=ru.add(0|c,0|h,0|E,0|v)),c=0|a,h=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const C=ru.add3L(v,I,K);r=ru.add3H(C,E,B,S),n=0|C}({h:r,l:n}=ru.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=ru.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=ru.add(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:h}=ru.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:u,l}=ru.add(0|this.Eh,0|this.El,0|u,0|l)),({h:y,l:f}=ru.add(0|this.Fh,0|this.Fl,0|y,0|f)),({h:g,l:p}=ru.add(0|this.Gh,0|this.Gl,0|g,0|p)),({h:d,l:A}=ru.add(0|this.Hh,0|this.Hl,0|d,0|A)),this.set(r,n,i,s,a,o,c,h,u,l,y,f,g,p,d,A)}roundClean(){su.fill(0),au.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class cu extends ou{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const hu=/* @__PURE__ */bc((()=>new ou)),uu=/* @__PURE__ */bc((()=>new cu)),lu=Ih(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),yu=jh({a:lu.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:lu,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},uu),fu=Ih(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),gu={a:fu.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:fu,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1)},pu=jh({a:gu.a,b:gu.b,Fp:fu,n:gu.n,Gx:gu.Gx,Gy:gu.Gy,h:gu.h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},hu),du=[],Au=[],wu=[],mu=/* @__PURE__ */BigInt(0),bu=/* @__PURE__ */BigInt(1),ku=/* @__PURE__ */BigInt(2),Eu=/* @__PURE__ */BigInt(7),vu=/* @__PURE__ */BigInt(256),Bu=/* @__PURE__ */BigInt(113);for(let e=0,t=bu,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],du.push(2*(5*n+r)),Au.push((e+1)*(e+2)/2%64);let i=mu;for(let e=0;e<7;e++)t=(t<>Eu)*Bu)%vu,t&ku&&(i^=bu<<(bu<r>32?eu(e,t,r):$h(e,t,r),Cu=(e,t,r)=>r>32?tu(e,t,r):Xh(e,t,r);class Du extends mc{constructor(e,t,r,n=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ac(r),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}keccak(){gc||pc(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,i=(t+2)%10,s=r[i],a=r[i+1],o=Ku(s,a,1)^r[n],c=Cu(s,a,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=Au[r],s=Ku(t,i,n),a=Cu(t,i,n),o=du[r];t=e[o],i=e[o+1],e[o]=s,e[o+1]=a}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=Iu[n],e[1]^=Su[n]}r.fill(0)}(this.state32,this.rounds),gc||pc(this.state32),this.posOut=0,this.pos=0}update(e){cc(this);const{blockLen:t,state:r}=this,n=(e=Ac(e)).length;for(let i=0;i=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ac(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(hc(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return e||(e=new Du(t,r,n,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=s,e.destroyed=this.destroyed,e}}const Pu=(e,t,r)=>bc((()=>new Du(t,e,r))),Uu=/* @__PURE__ */Pu(6,136,32),xu=/* @__PURE__ */Pu(6,72,64),Qu=/* @__PURE__ */((e,t,r)=>function(e){const t=(t,r)=>e(r).update(Ac(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(((n={})=>new Du(t,e,void 0===n.dkLen?r:n.dkLen,!0))))(31,136,32),Ru=BigInt(0),Lu=BigInt(1),Tu=BigInt(2),Mu=BigInt(8),Nu={zip215:!0};function Fu(e){const t=function(e){const t=Rh(e);return ch(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:i,hash:s,randomBytes:a,nByteLength:o,h:c}=t,h=Tu<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:Ru}}}),f=t.adjustScalarBytes||(e=>e),g=t.domain||((e,t,r)=>{if(Fc("phflag",r),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function p(e,t){th("coordinate "+e,t,Ru,h)}function d(e){if(!(e instanceof m))throw Error("ExtendedPoint expected")}const A=hh(((e,t)=>{const{ex:n,ey:i,ez:s}=e,a=e.is0();null==t&&(t=a?Mu:r.inv(s));const o=u(n*t),c=u(i*t),h=u(s*t);if(a)return{x:Ru,y:Lu};if(h!==Lu)throw Error("invZ was invalid");return{x:o,y:c}})),w=hh((e=>{const{a:r,d:n}=t;if(e.is0())throw Error("bad point: ZERO");const{ex:i,ey:s,ez:a,et:o}=e,c=u(i*i),h=u(s*s),l=u(a*a),y=u(l*l),f=u(c*r);if(u(l*u(f+h))!==u(y+u(n*u(c*h))))throw Error("bad point: equation left != right (1)");if(u(i*s)!==u(a*o))throw Error("bad point: equation left != right (2)");return!0}));class m{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,p("x",e),p("y",t),p("z",r),p("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof m)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return p("x",t),p("y",r),new m(t,r,Lu,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(m.fromAffine)}static msm(e,t){return Qh(m,l,e,t)}_setWindowSize(e){E.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){d(e);const{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:a}=e,o=u(t*a),c=u(i*n),h=u(r*a),l=u(s*n);return o===c&&h===l}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:i}=this,s=u(r*r),a=u(n*n),o=u(Tu*u(i*i)),c=u(e*s),h=r+n,l=u(u(h*h)-s-a),y=c+a,f=y-o,g=c-a,p=u(l*f),d=u(y*g),A=u(l*g),w=u(f*y);return new m(p,d,w,A)}add(e){d(e);const{a:r,d:n}=t,{ex:i,ey:s,ez:a,et:o}=this,{ex:c,ey:h,ez:l,et:y}=e;if(r===BigInt(-1)){const e=u((s-i)*(h+c)),t=u((s+i)*(h-c)),r=u(t-e);if(r===Ru)return this.double();const n=u(a*Tu*y),f=u(o*Tu*l),g=f+n,p=t+e,d=f-n,A=u(g*r),w=u(p*d),b=u(g*d),k=u(r*p);return new m(A,w,k,b)}const f=u(i*c),g=u(s*h),p=u(o*n*y),A=u(a*l),w=u((i+s)*(c+h)-f-g),b=A-p,k=A+p,E=u(g-r*f),v=u(w*b),B=u(k*E),I=u(w*E),S=u(b*k);return new m(v,B,S,I)}subtract(e){return this.add(e.negate())}wNAF(e){return E.wNAFCached(this,e,m.normalizeZ)}multiply(e){const t=e;th("scalar",t,Lu,n);const{p:r,f:i}=this.wNAF(t);return m.normalizeZ([r,i])[0]}multiplyUnsafe(e){const t=e;return th("scalar",t,Ru,n),t===Ru?k:this.equals(k)||t===Lu?this:this.equals(b)?this.wNAF(t).p:E.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(e){return A(this,e)}clearCofactor(){const{h:e}=t;return e===Lu?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:i,a:s}=t,a=r.BYTES;e=Zc("pointHex",e,a),Fc("zip215",n);const o=e.slice(),c=e[a-1];o[a-1]=-129&c;const l=Jc(o),f=n?h:r.ORDER;th("pointHex.y",l,Ru,f);const g=u(l*l),p=u(g-Lu),d=u(i*g-s);let{isValid:A,value:w}=y(p,d);if(!A)throw Error("Point.fromHex: invalid y coordinate");const b=(w&Lu)===Lu,k=!!(128&c);if(!n&&w===Ru&&k)throw Error("Point.fromHex: x=0 and x_0=1");return k!==b&&(w=u(-w)),m.fromAffine({x:w,y:l})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Wc(t,r.BYTES);return n[n.length-1]|=e&Lu?128:0,n}toHex(){return Oc(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Lu,u(t.Gx*t.Gy)),m.ZERO=new m(Ru,Lu,Lu,Ru);const{BASE:b,ZERO:k}=m,E=xh(m,8*o);function v(e){return wh(e,n)}function B(e){return v(Jc(e))}function I(e){const t=o;e=Zc("private key",e,t);const r=Zc("hashed private key",s(e),2*t),n=f(r.slice(0,t)),i=r.slice(t,2*t),a=B(n),c=b.multiply(a),h=c.toRawBytes();return{head:n,prefix:i,scalar:a,point:c,pointBytes:h}}function S(e=new Uint8Array,...t){const r=$c(...t);return B(s(g(r,Zc("context",e),!!i)))}const K=Nu;b._setWindowSize(8);return{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Zc("message",e),i&&(e=i(e));const{prefix:a,scalar:c,pointBytes:h}=I(t),u=S(s.context,a,e),l=b.multiply(u).toRawBytes(),y=v(u+S(s.context,l,h,e)*c);return th("signature.s",y,Ru,n),Zc("result",$c(l,Wc(y,r.BYTES)),2*o)},verify:function(e,t,n,s=K){const{context:a,zip215:o}=s,c=r.BYTES;e=Zc("signature",e,2*c),t=Zc("message",t),void 0!==o&&Fc("zip215",o),i&&(t=i(t));const h=Jc(e.slice(c,2*c));let u,l,y;try{u=m.fromHex(n,o),l=m.fromHex(e.slice(0,c),o),y=b.multiplyUnsafe(h)}catch(e){return!1}if(!o&&u.isSmallOrder())return!1;const f=S(a,l.toRawBytes(),u.toRawBytes(),t);return l.add(u.multiplyUnsafe(f)).subtract(y).clearCofactor().equals(m.ZERO)},ExtendedPoint:m,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>a(r.BYTES),precompute:(e=8,t=m.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hu=BigInt(0),Ou=BigInt(1);function zu(e){const t=(ch(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,i=e=>wh(e,n),s=t.montgomeryBits,a=Math.ceil(s/8),o=t.nByteLength,c=t.adjustScalarBytes||(e=>e),h=t.powPminus2||(e=>mh(e,n-BigInt(2),n));function u(e,t,r){const n=i(e*(t-r));return[t=i(t-n),r=i(r+n)]}const l=(t.a-BigInt(2))/BigInt(4);function y(e){return Wc(i(e),a)}function f(e,t){const r=function(e){const t=Zc("u coordinate",e,a);return 32===o&&(t[31]&=127),Jc(t)}(t),f=function(e){const t=Zc("scalar",e),r=t.length;if(r!==a&&r!==o)throw Error(`Expected ${a} or ${o} bytes, got ${r}`);return Jc(c(t))}(e),g=function(e,t){th("u",e,Hu,n),th("scalar",t,Hu,n);const r=t,a=e;let o,c=Ou,y=Hu,f=e,g=Ou,p=Hu;for(let e=BigInt(s-1);e>=Hu;e--){const t=r>>e&Ou;p^=t,o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1],p=t;const n=c+y,s=i(n*n),h=c-y,d=i(h*h),A=s-d,w=f+g,m=i((f-g)*n),b=i(w*h),k=m+b,E=m-b;f=i(k*k),g=i(a*i(E*E)),c=i(s*d),y=i(A*(s+i(l*A)))}o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1];const d=h(y);return i(c*d)}(r,f);if(g===Hu)throw Error("Invalid private or public key received");return y(g)}const g=y(t.Gu);function p(e){return f(e,g)}return{scalarMult:f,scalarMultBase:p,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>p(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _u=bc((()=>Qu.create({dkLen:114}))),Gu=(bc((()=>Qu.create({dkLen:64}))),BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439")),ju=BigInt(1),qu=BigInt(2),Vu=BigInt(3);BigInt(4);const Ju=BigInt(11),Yu=BigInt(22),Wu=BigInt(44),Zu=BigInt(88),$u=BigInt(223);function Xu(e){const t=Gu,r=e*e*e%t,n=r*r*e%t,i=bh(n,Vu,t)*n%t,s=bh(i,Vu,t)*n%t,a=bh(s,qu,t)*r%t,o=bh(a,Ju,t)*a%t,c=bh(o,Yu,t)*o%t,h=bh(c,Wu,t)*c%t,u=bh(h,Zu,t)*h%t,l=bh(u,Wu,t)*c%t,y=bh(l,qu,t)*r%t,f=bh(y,ju,t)*e%t;return bh(f,$u,t)*y%t}function el(e){return e[0]&=252,e[55]|=128,e[56]=0,e}const tl=Ih(Gu,456,!0),rl={a:BigInt(1),d:BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"),Fp:tl,n:BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"),nBitLength:456,h:BigInt(4),Gx:BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"),Gy:BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"),hash:_u,randomBytes:kc,adjustScalarBytes:el,domain:(e,t,r)=>{if(t.length>255)throw Error("Context is too big: "+t.length);return wc(dc("SigEd448"),new Uint8Array([r?1:0,t.length]),t,e)},uvRatio:function(e,t){const r=Gu,n=wh(e*e*t,r),i=wh(n*e,r),s=wh(i*n*t,r),a=wh(i*Xu(s),r),o=wh(a*a,r);return{isValid:wh(o*t,r)===e,value:a}}},nl=/* @__PURE__ */Fu(rl),il=/* @__PURE__ */(()=>zu({a:BigInt(156326),montgomeryBits:448,nByteLength:56,P:Gu,Gu:BigInt(5),powPminus2:e=>{const t=Gu;return wh(bh(Xu(e),BigInt(2),t)*e,t)},adjustScalarBytes:el,randomBytes:kc}))();tl.ORDER,BigInt(3),BigInt(4),BigInt(156326),BigInt("39082"),BigInt("78163"),BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"),BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"),BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const sl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),al=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ol=BigInt(1),cl=BigInt(2),hl=(e,t)=>(e+t/cl)/t;const ul=Ih(sl,void 0,void 0,{sqrt:function(e){const t=sl,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),h=e*e*e%t,u=h*h*e%t,l=bh(u,r,t)*u%t,y=bh(l,r,t)*u%t,f=bh(y,cl,t)*h%t,g=bh(f,i,t)*f%t,p=bh(g,s,t)*g%t,d=bh(p,o,t)*p%t,A=bh(d,c,t)*d%t,w=bh(A,o,t)*p%t,m=bh(w,r,t)*u%t,b=bh(m,a,t)*g%t,k=bh(b,n,t)*h%t,E=bh(k,cl,t);if(!ul.eql(ul.sqr(E),e))throw Error("Cannot find square root");return E}}),ll=jh({a:BigInt(0),b:BigInt(7),Fp:ul,n:al,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=al,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ol*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,a=BigInt("0x100000000000000000000000000000000"),o=hl(s*e,t),c=hl(-n*e,t);let h=wh(e-o*r-c*i,t),u=wh(-o*n-c*s,t);const l=h>a,y=u>a;if(l&&(h=t-h),y&&(u=t-u),h>a||u>a)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:h,k2neg:y,k2:u}}}},Pc);BigInt(0),ll.ProjectivePoint;const yl=Ih(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377")),fl=jh({a:yl.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),b:BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),Fp:yl,n:BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),Gx:BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),Gy:BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),h:BigInt(1),lowS:!1},Pc),gl=Ih(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53")),pl=jh({a:gl.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),b:BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),Fp:gl,n:BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),Gx:BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),Gy:BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),h:BigInt(1),lowS:!1},uu),dl=Ih(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3")),Al=jh({a:dl.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),b:BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),Fp:dl,n:BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),Gx:BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),Gy:BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),h:BigInt(1),lowS:!1},hu),wl=new Map(Object.entries({nistP256:Vh,nistP384:yu,nistP521:pu,brainpoolP256r1:fl,brainpoolP384r1:pl,brainpoolP512r1:Al,secp256k1:ll,x448:il,ed448:nl}));var ml=/*#__PURE__*/Object.freeze({__proto__:null,nobleCurves:wl});function bl(e,t,r,n,i,s){const a=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],h=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],y=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let g,p,d,A,w,m,b,k,E,v,B=0,I=t.length;const S=32===e.length?3:9;k=3===S?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e){const t=8-e.length%8;let r;if(!(t<8)){if(8===t)return e;throw Error("des: invalid padding")}r=0;const n=new Uint8Array(e.length+t);for(let t=0;t>>4^b),b^=d,m^=d<<4,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,m=m<<1|m>>>31,b=b<<1|b>>>31,p=0;p>>4|b<<28)^e[g+1],d=m,m=b,b=d^(o[A>>>24&63]|h[A>>>16&63]|l[A>>>8&63]|f[63&A]|a[w>>>24&63]|c[w>>>16&63]|u[w>>>8&63]|y[63&w]);d=m,m=b,b=d}m=m>>>1|m<<31,b=b>>>1|b<<31,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=252645135&(m>>>4^b),b^=d,m^=d<<4,K[C++]=m>>>24,K[C++]=m>>>16&255,K[C++]=m>>>8&255,K[C++]=255&m,K[C++]=b>>>24,K[C++]=b>>>16&255,K[C++]=b>>>8&255,K[C++]=255&b}return r||(K=function(e){let t,r=null;if(t=0,!r){for(r=1;e[e.length-r]===t;)r++;r--}return e.subarray(0,e.length-r)}(K)),K}function kl(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],h=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],p=e.length>8?3:1,d=Array(32*p),A=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let w,m,b,k=0,E=0;for(let v=0;v>>4^v),v^=b,p^=b<<4,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=858993459&(p>>>2^v),v^=b,p^=b<<2,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=16711935&(v>>>8^p),p^=b,v^=b<<8,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=p<<8|v>>>20&240,p=v<<24|v<<8&16711680|v>>>8&65280|v>>>24&240,v=b;for(let e=0;e<16;e++)A[e]?(p=p<<2|p>>>26,v=v<<2|v>>>26):(p=p<<1|p>>>27,v=v<<1|v>>>27),p&=-15,v&=-15,w=t[p>>>28]|r[p>>>24&15]|n[p>>>20&15]|i[p>>>16&15]|s[p>>>12&15]|a[p>>>8&15]|o[p>>>4&15],m=c[v>>>28]|h[v>>>24&15]|u[v>>>20&15]|l[v>>>16&15]|y[v>>>12&15]|f[v>>>8&15]|g[v>>>4&15],b=65535&(m>>>16^w),d[E++]=w^b,d[E++]=m^b<<16}return d}function El(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return bl(kl(this.key[2]),bl(kl(this.key[1]),bl(kl(this.key[0]),e,!0),!1),!0)}}function vl(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>>16&255,t[s+6]=o>>>8&255,t[s+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>16&255,t[s+6]=o>>8&255,t[s+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const n=t+e,i=n<>>32-r;return(s[0][i>>>24]^s[1][i>>>16&255])-s[2][i>>>8&255]+s[3][255&i]}function n(e,t,r){const n=t^e,i=n<>>32-r;return s[0][i>>>24]-s[1][i>>>16&255]+s[2][i>>>8&255]^s[3][255&i]}function i(e,t,r){const n=t-e,i=n<>>32-r;return(s[0][i>>>24]+s[1][i>>>16&255]^s[2][i>>>8&255])-s[3][255&i]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const n=[,,,,,,,,],i=Array(32);let a;for(let e=0;e<4;e++)a=4*e,n[e]=r[a]<<24|r[a+1]<<16|r[a+2]<<8|r[a+3];const o=[6,7,4,5];let c,h=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(a=0;a<4;a++){const t=e[r][a];c=n[t[1]],c^=s[4][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=s[5][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=s[6][n[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=s[7][n[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=s[o[a]][n[t[6]>>>2]>>>24-8*(3&t[6])&255],n[t[0]]=c}for(a=0;a<4;a++){const e=t[r][a];c=s[4][n[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=s[5][n[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=s[6][n[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=s[7][n[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=s[4+a][n[e[4]>>>2]>>>24-8*(3&e[4])&255],i[h]=c,h++}}for(let e=0;e<16;e++)this.masking[e]=i[e],this.rotate[e]=31&i[16+e]};const s=[,,,,,,,,];s[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],s[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],s[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],s[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],s[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],s[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],s[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],s[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Bl(e){this.cast5=new vl,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}El.keySize=El.prototype.keySize=24,El.blockSize=El.prototype.blockSize=8,Bl.blockSize=Bl.prototype.blockSize=8,Bl.keySize=Bl.prototype.keySize=16;const Il=4294967295;function Sl(e,t){return(e<>>32-t)&Il}function Kl(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Cl(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function Dl(e,t){return e>>>8*t&255}function Pl(e){this.tf=function(){let e=null,t=null,r=-1,n=[],i=[[],[],[],[]];function s(e){return i[0][Dl(e,0)]^i[1][Dl(e,1)]^i[2][Dl(e,2)]^i[3][Dl(e,3)]}function a(e){return i[0][Dl(e,3)]^i[1][Dl(e,0)]^i[2][Dl(e,1)]^i[3][Dl(e,2)]}function o(e,t){let r=s(t[0]),i=a(t[1]);t[2]=Sl(t[2]^r+i+n[4*e+8]&Il,31),t[3]=Sl(t[3],1)^r+2*i+n[4*e+9]&Il,r=s(t[2]),i=a(t[3]),t[0]=Sl(t[0]^r+i+n[4*e+10]&Il,31),t[1]=Sl(t[1],1)^r+2*i+n[4*e+11]&Il}function c(e,t){let r=s(t[0]),i=a(t[1]);t[2]=Sl(t[2],1)^r+i+n[4*e+10]&Il,t[3]=Sl(t[3]^r+2*i+n[4*e+11]&Il,31),r=s(t[2]),i=a(t[3]),t[0]=Sl(t[0],1)^r+i+n[4*e+8]&Il,t[1]=Sl(t[1]^r+2*i+n[4*e+9]&Il,31)}return{name:"twofish",blocksize:16,open:function(t){let r,s,a,o,c;e=t;const h=[],u=[],l=[];let y;const f=[];let g,p,d;const A=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],m=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],b=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],k=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],E=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],v=[[],[]],B=[[],[],[],[]];function I(e){return e^e>>2^[0,90,180,238][3&e]}function S(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function K(e,t){let r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&Il|e>>>24,e=e<<8&Il,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function C(e,t){const r=t>>4,n=15&t,i=A[e][r^n],s=w[e][k[n]^E[r]];return b[e][k[s]^E[i]]<<4|m[e][i^s]}function D(e,t){let r=Dl(e,0),n=Dl(e,1),i=Dl(e,2),s=Dl(e,3);switch(y){case 4:r=v[1][r]^Dl(t[3],0),n=v[0][n]^Dl(t[3],1),i=v[0][i]^Dl(t[3],2),s=v[1][s]^Dl(t[3],3);case 3:r=v[1][r]^Dl(t[2],0),n=v[1][n]^Dl(t[2],1),i=v[0][i]^Dl(t[2],2),s=v[0][s]^Dl(t[2],3);case 2:r=v[0][v[0][r]^Dl(t[1],0)]^Dl(t[0],0),n=v[0][v[1][n]^Dl(t[1],1)]^Dl(t[0],1),i=v[1][v[0][i]^Dl(t[1],2)]^Dl(t[0],2),s=v[1][v[1][s]^Dl(t[1],3)]^Dl(t[0],3)}return B[0][r]^B[1][n]^B[2][i]^B[3][s]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Kl(e,r);for(r=0;r<256;r++)v[0][r]=C(0,r),v[1][r]=C(1,r);for(r=0;r<256;r++)g=v[1][r],p=I(g),d=S(g),B[0][r]=g+(p<<8)+(d<<16)+(d<<24),B[2][r]=p+(d<<8)+(g<<16)+(d<<24),g=v[0][r],p=I(g),d=S(g),B[1][r]=d+(d<<8)+(p<<16)+(g<<24),B[3][r]=p+(g<<8)+(d<<16)+(p<<24);for(y=l.length/2,r=0;r=0;e--)c(e,s);Cl(t,r,s[2]^n[0]),Cl(t,r+4,s[3]^n[1]),Cl(t,r+8,s[0]^n[2]),Cl(t,r+12,s[1]^n[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Ul(){}function xl(e){this.bf=new Ul,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}Pl.keySize=Pl.prototype.keySize=32,Pl.blockSize=Pl.prototype.blockSize=16,Ul.prototype.BLOCKSIZE=8,Ul.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Ul.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Ul.prototype.NN=16,Ul.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Ul.prototype._F=function(e){let t;const r=255&e,n=255&(e>>>=8),i=255&(e>>>=8),s=255&(e>>>=8);return t=this.sboxes[0][s]+this.sboxes[1][i],t^=this.sboxes[2][n],t+=this.sboxes[3][r],t},Ul.prototype._encryptBlock=function(e){let t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},Ul.prototype._decryptBlock=function(e){let t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],n=this._F(r)^n;const e=r;r=n,n=e}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},Ul.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^n}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const n=[0,0];for(t=0;tnew Ml)),Fl=/* @__PURE__ */new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Hl=/* @__PURE__ */new Uint8Array(Array(16).fill(0).map(((e,t)=>t))),Ol=/* @__PURE__ */Hl.map((e=>(9*e+5)%16));let zl=[Hl],_l=[Ol];for(let e=0;e<4;e++)for(let t of[zl,_l])t.push(t[e].map((e=>Fl[e])));const Gl=/* @__PURE__ */[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>new Uint8Array(e))),jl=/* @__PURE__ */zl.map(((e,t)=>e.map((e=>Gl[t][e])))),ql=/* @__PURE__ */_l.map(((e,t)=>e.map((e=>Gl[t][e])))),Vl=/* @__PURE__ */new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Jl=/* @__PURE__ */new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function Yl(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}const Wl=/* @__PURE__ */new Uint32Array(16);class Zl extends Bc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)Wl[r]=e.getUint32(t,!0);let r=0|this.h0,n=r,i=0|this.h1,s=i,a=0|this.h2,o=a,c=0|this.h3,h=c,u=0|this.h4,l=u;for(let e=0;e<5;e++){const t=4-e,y=Vl[e],f=Jl[e],g=zl[e],p=_l[e],d=jl[e],A=ql[e];for(let t=0;t<16;t++){const n=fc(r+Yl(e,i,a,c)+Wl[g[t]]+y,d[t])+u|0;r=u,u=c,c=0|fc(a,10),a=i,i=n}for(let e=0;e<16;e++){const r=fc(n+Yl(t,s,o,h)+Wl[p[e]]+f,A[e])+l|0;n=l,l=h,h=0|fc(o,10),o=s,s=r}}this.set(this.h1+a+h|0,this.h2+c+l|0,this.h3+u+n|0,this.h4+r+s|0,this.h0+i+o|0)}roundClean(){Wl.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const $l=new Map(Object.entries({sha1:Nl,sha224:Uc,sha256:Pc,sha384:uu,sha512:hu,sha3_256:Uu,sha3_512:xu,ripemd160:/* @__PURE__ */bc((()=>new Zl))}));var Xl=/*#__PURE__*/Object.freeze({__proto__:null,nobleHashes:$l});function ey(e,t,r,n){e[t]+=r[n],e[t+1]+=r[n+1]+(e[t]>>24^h<<8,e[n+1]=h>>>24^c<<8,ey(e,r,e,n),ey(e,r,t,o),c=e[s]^e[r],h=e[s+1]^e[r+1],e[s]=c>>>16^h<<16,e[s+1]=h>>>16^c<<16,ey(e,i,e,s),c=e[n]^e[i],h=e[n+1]^e[i+1],e[n]=h>>>31^c<<1,e[n+1]=c>>>31^h<<1}const ny=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),iy=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((e=>2*e)));function sy(e,t){const r=new Uint32Array(32),n=new Uint32Array(e.b.buffer,e.b.byteOffset,32);for(let t=0;t<16;t++)r[t]=e.h[t],r[t+16]=ny[t];r[24]^=e.t0[0],r[25]^=e.t0[1];const i=t?4294967295:0;r[28]^=i,r[29]^=i;for(let e=0;e<12;e++){const t=e<<4;ry(r,n,0,8,16,24,iy[t+0],iy[t+1]),ry(r,n,2,10,18,26,iy[t+2],iy[t+3]),ry(r,n,4,12,20,28,iy[t+4],iy[t+5]),ry(r,n,6,14,22,30,iy[t+6],iy[t+7]),ry(r,n,0,10,20,30,iy[t+8],iy[t+9]),ry(r,n,2,12,22,24,iy[t+10],iy[t+11]),ry(r,n,4,14,16,26,iy[t+12],iy[t+13]),ry(r,n,6,8,18,28,iy[t+14],iy[t+15])}for(let t=0;t<16;t++)e.h[t]^=r[t]^r[t+16]}class ay{constructor(e,t,r,n){const i=new Uint8Array(64);this.S={b:new Uint8Array(hy),h:new Uint32Array(cy/4),t0:new Uint32Array(2),c:0,outlen:e},i[0]=e,t&&(i[1]=t.length),i[2]=1,i[3]=1,r&&i.set(r,32),n&&i.set(n,48);const s=new Uint32Array(i.buffer,i.byteOffset,i.length/Uint32Array.BYTES_PER_ELEMENT);for(let e=0;e<16;e++)this.S.h[e]=ny[e]^s[e];if(t){const e=new Uint8Array(hy);e.set(t),this.update(e)}}update(e){if(!(e instanceof Uint8Array))throw Error("Input must be Uint8Array or Buffer");let t=0;for(;t>2]>>8*(3&e);return this.S.h=null,t.buffer}}function oy(e,t,r,n){if(e>cy)throw Error(`outlen must be at most ${cy} (given: ${e})`);return new ay(e,t,r,n)}const cy=64,hy=128,uy=2,ly=19,yy=4294967295,fy=4,gy=4294967295,py=8,dy=4294967295,Ay=8,wy=4294967295,my=4294967295,by=32,ky=1024,Ey=64,vy=205===new Uint8Array(new Uint16Array([43981]).buffer)[0];function By(e,t,r){return e[r+0]=t,e[r+1]=t>>8,e[r+2]=t>>16,e[r+3]=t>>24,e}function Iy(e,t,r){if(t>Number.MAX_SAFE_INTEGER)throw Error("LE64: large numbers unsupported");let n=t;for(let t=r;t{if(tn)throw Error(`${e} size should be between ${r} and ${n} bytes`)};if(e!==uy||t!==ly)throw Error("Unsupported type or version");return u("password",n,Ay,dy),u("salt",i,py,gy),u("tag",r,fy,yy),u("memory",c,8*o,wy),s&&u("associated data",s,0,my),a&&u("secret",a,0,by),{type:e,version:t,tagLength:r,password:n,salt:i,ad:s,secret:a,lanes:o,memorySize:c,passes:h}}({type:uy,version:ly,...e}),{G:i,G2:s,xor:a,getLZ:o}=r.exports,c={},h={};h.G=i,h.G2=s,h.XOR=a;const u=4*n.lanes*Math.floor(n.memorySize/(4*n.lanes)),l=u*ky+10*Uy;if(t.buffer.byteLength{r.set(e,n),n+=e.length})),r}(i));const s=t.digest();return new Uint8Array(s)}(n),m=u/n.lanes,b=Array(n.lanes).fill(null).map((()=>Array(m))),k=(e,t)=>(b[e][t]=d.subarray(e*m*1024+1024*t,e*m*1024+1024*t+ky),b[e][t]);for(let e=0;e0?b[i][c-1]:b[i][m-1],u=r?a.next().value:h;o(f.byteOffset,u.byteOffset,i,n.lanes,e,t,s,4,E);const l=f[0],y=f[1];0===e&&k(i,c),Cy(g,h,b[l][y],e>0?p:b[i][c]),e>0&&Ky(g,b[i][c],p,b[i][c])}}}const v=b[0][m-1];for(let e=1;eQy(e,{instance:n.instance,memory:r})}function Ty(e,t,r,n){return function(e,t){var r=WebAssembly.instantiate,n=WebAssembly.compile;return t?r(e,t):n(e)}(Buffer.from(r,"base64"),n)}var My=/*#__PURE__*/Object.freeze({__proto__:null,default:async()=>Ly((e=>Ty(0,0,"AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bm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/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL",e)),(e=>Ty(0,0,"AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==",e)))}),Ny=[0,1,3,7,15,31,63,127,255],Fy=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};Fy.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},Fy.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Ny[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var n=r-e;t|=(this.curByte&Ny[e]<>n,this.bitOffset+=e,e=0}}return t},Fy.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},Fy.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var Hy=Fy,Oy=function(){};Oy.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},Oy.prototype.read=function(e,t,r){for(var n=0;n>>0},this.updateCRC=function(t){e=e<<8^zy[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^zy[255&(e>>>24^t)]}}),jy=Hy,qy=_y,Vy=Gy,Jy=function(e,t){var r,n=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=n,n},Yy={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},Wy={};Wy[Yy.LAST_BLOCK]="Bad file checksum",Wy[Yy.NOT_BZIP_DATA]="Not bzip data",Wy[Yy.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",Wy[Yy.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",Wy[Yy.DATA_ERROR]="Data error",Wy[Yy.OUT_OF_MEMORY]="Out of memory",Wy[Yy.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var Zy=function(e,t){var r=Wy[e]||"unknown error";t&&(r+=": "+t);var n=new TypeError(r);throw n.errorCode=e,n},$y=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};$y.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Vy,!0):(this.writeCount=-1,!1)},$y.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||Zy(Yy.NOT_BZIP_DATA,"bad magic");var n=r[3]-48;(n<1||n>9)&&Zy(Yy.NOT_BZIP_DATA,"level out of range"),this.reader=new jy(e),this.dbufSize=1e5*n,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},$y.prototype._get_next_block=function(){var e,t,r,n=this.reader,i=n.pi();if("177245385090"===i)return!1;"314159265359"!==i&&Zy(Yy.NOT_BZIP_DATA),this.targetBlockCRC=n.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,n.read(1)&&Zy(Yy.OBSOLETE_INPUT);var s=n.read(24);s>this.dbufSize&&Zy(Yy.DATA_ERROR,"initial position out of bounds");var a=n.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(a&1<<15-e){var h=16*e;for(r=n.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=h+t)}var u=n.read(3);(u<2||u>6)&&Zy(Yy.DATA_ERROR);var l=n.read(15);0===l&&Zy(Yy.DATA_ERROR);var y=new Uint8Array(256);for(e=0;e=u&&Zy(Yy.DATA_ERROR);f[e]=Jy(y,t)}var g,p=c+2,d=[];for(t=0;t20)&&Zy(Yy.DATA_ERROR),n.read(1);)n.read(1)?a--:a++;m[e]=a}for(A=w=m[0],e=1;ew?w=m[e]:m[e]=l&&Zy(Yy.DATA_ERROR),g=d[f[S++]]),e=g.minLen,t=n.read(e);e>g.maxLen&&Zy(Yy.DATA_ERROR),!(t<=g.limit[e]);e++)t=t<<1|n.read(1);((t-=g.base[e])<0||t>=258)&&Zy(Yy.DATA_ERROR);var C=g.permute[t];if(0!==C&&1!==C){if(B)for(B=0,I+a>this.dbufSize&&Zy(Yy.DATA_ERROR),E[v=o[y[0]]]+=a;a--;)K[I++]=v;if(C>c)break;I>=this.dbufSize&&Zy(Yy.DATA_ERROR),E[v=o[v=Jy(y,e=C-1)]]++,K[I++]=v}else B||(B=1,a=0),a+=0===C?B:2*B,B<<=1}for((s<0||s>=I)&&Zy(Yy.DATA_ERROR),t=0,e=0;e<256;e++)r=t+E[e],E[e]=t,t=r;for(e=0;e>=8,U=-1),this.writePos=D,this.writeCurrent=P,this.writeCount=I,this.writeRun=U,!0},$y.prototype._read_bunzip=function(e,t){var r,n,i;if(this.writeCount<0)return 0;var s=this.dbuf,a=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var h=this.writeRun;c;){for(c--,n=o,o=255&(a=s[a]),a>>=8,3==h++?(r=o,i=n,o=-1):(r=1,i=o),this.blockCRC.updateCRCRun(i,r);r--;)this.outputStream.writeByte(i),this.nextoutput++;o!=n&&(h=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&Zy(Yy.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var Xy=function(e){if("readByte"in e)return e;var t=new qy;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},ef=function(e){var t=new qy,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var tf={Bunzip:$y,Stream:qy,Err:Yy,decode:function(e,t,r){for(var n=Xy(e),i=ef(t),s=new $y(n,i);!("eof"in n)||!n.eof();)if(s._init_block())s._read_bunzip();else{var a=s.reader.read(32)>>>0;if(a!==s.streamCRC&&Zy(Yy.DATA_ERROR,"Bad stream CRC (got "+s.streamCRC.toString(16)+" expected "+a.toString(16)+")"),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i)}if("getBuffer"in i)return i.getBuffer()},decodeBlock:function(e,t,r){var n=Xy(e),i=ef(r),s=new $y(n,i);if(s.reader.seek(t),s._get_next_block()&&(s.blockCRC=new Vy,s.writeCopies=0,s._read_bunzip()),"getBuffer"in i)return i.getBuffer()},table:function(e,t,r){var n=new qy;n.delegate=Xy(e),n.pos=0,n.readByte=function(){return this.pos++,this.delegate.readByte()},n.delegate.eof&&(n.eof=n.delegate.eof.bind(n.delegate));var i=new qy;i.pos=0,i.writeByte=function(){this.pos++};for(var s=new $y(n,i),a=s.dbufSize;!("eof"in n)||!n.eof();){var o=8*n.pos+s.reader.bitOffset;if(s.reader.hasByte&&(o-=8),s._init_block()){var c=i.pos;s._read_bunzip(),t(o,i.pos-c)}else{if(s.reader.read(32),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i),console.assert(s.dbufSize===a,"shouldn't change block size within multistream file")}}}},rf=/*#__PURE__*/n({__proto__:null},[tf]);export{xa as AEADEncryptedDataPacket,To as CleartextMessage,Ea as CompressedDataPacket,ua as LiteralDataPacket,Fa as MarkerPacket,Po as Message,wa as OnePassSignaturePacket,ba as PacketList,Va as PaddingPacket,mo as PrivateKey,wo as PublicKey,Qa as PublicKeyEncryptedSessionKeyPacket,Ta as PublicKeyPacket,Ha as PublicSubkeyPacket,za as SecretKeyPacket,ja as SecretSubkeyPacket,Ya as Signature,pa as SignaturePacket,yo as Subkey,Da as SymEncryptedIntegrityProtectedDataPacket,La as SymEncryptedSessionKeyPacket,Na as SymmetricallyEncryptedDataPacket,qa as TrustPacket,Wn as UnparseablePacket,Oa as UserAttributePacket,Ga as UserIDPacket,te as armor,M as config,No as createCleartextMessage,Ro as createMessage,jo as decrypt,zo as decryptKey,Wo as decryptSessionKeys,Go as encrypt,_o as encryptKey,Yo as encryptSessionKey,T as enums,Fo as generateKey,Jo as generateSessionKey,Mo as readCleartextMessage,vo as readKey,Io as readKeys,Qo as readMessage,Bo as readPrivateKey,So as readPrivateKeys,Wa as readSignature,Ho as reformatKey,Oo as revokeKey,qo as sign,ee as unarmor,Vo as verify}; //# sourceMappingURL=openpgp.min.mjs.map diff --git a/app/node_modules/openpgp/dist/node/openpgp.min.mjs.map b/app/node_modules/openpgp/dist/node/openpgp.min.mjs.map index 84b6bcadd..322862aac 100644 --- a/app/node_modules/openpgp/dist/node/openpgp.min.mjs.map +++ b/app/node_modules/openpgp/dist/node/openpgp.min.mjs.map @@ -1 +1 @@ -{"version":3,"file":"openpgp.min.mjs","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/node-conversions.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/biginteger/native.interface.js","../../src/biginteger/index.js","../../src/enums.js","../../src/util.js","../../src/encoding/base64.js","../../src/config/config.js","../../src/encoding/armor.js","../../src/type/keyid.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/utils.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/other/errors.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ecb.js","../../src/crypto/cipher/aes.js","../../src/crypto/cipher/des.js","../../src/crypto/cipher/cast5.js","../../src/crypto/cipher/twofish.js","../../src/crypto/cipher/blowfish.js","../../src/crypto/cipher/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.asm.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/hash.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.asm.js","../../node_modules/minimalistic-assert/index.js","../../node_modules/inherits/inherits_browser.js","../../node_modules/inherits/inherits.js","../../node_modules/hash.js/lib/hash/utils.js","../../node_modules/hash.js/lib/hash/common.js","../../node_modules/hash.js/lib/hash/sha/common.js","../../node_modules/hash.js/lib/hash/sha/256.js","../../node_modules/hash.js/lib/hash/sha/224.js","../../node_modules/hash.js/lib/hash/sha/512.js","../../node_modules/hash.js/lib/hash/sha/384.js","../../node_modules/hash.js/lib/hash/ripemd.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cfb.js","../../src/crypto/cipher/getCipher.js","../../src/crypto/mode/cfb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ctr.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cbc.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/gcm.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../node_modules/@openpgp/tweetnacl/nacl-fast-light.js","../../src/crypto/random.js","../../src/crypto/public_key/prime.js","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../src/type/oid.js","../../src/crypto/public_key/elliptic/indutnyKey.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../node_modules/@openpgp/pako/lib/utils/common.js","../../node_modules/@openpgp/pako/lib/zlib/constants.js","../../node_modules/@openpgp/pako/lib/zlib/trees.js","../../node_modules/@openpgp/pako/lib/zlib/adler32.js","../../node_modules/@openpgp/pako/lib/zlib/crc32.js","../../node_modules/@openpgp/pako/lib/zlib/messages.js","../../node_modules/@openpgp/pako/lib/zlib/deflate.js","../../node_modules/@openpgp/pako/lib/utils/strings.js","../../node_modules/@openpgp/pako/lib/zlib/zstream.js","../../node_modules/@openpgp/pako/lib/deflate.js","../../node_modules/@openpgp/pako/lib/zlib/inffast.js","../../node_modules/@openpgp/pako/lib/zlib/inftrees.js","../../node_modules/@openpgp/pako/lib/zlib/inflate.js","../../node_modules/@openpgp/pako/lib/zlib/gzheader.js","../../node_modules/@openpgp/pako/lib/inflate.js","../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js","../../src/packet/literal_data.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/type/s2k.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/marker.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../node_modules/email-addresses/lib/email-addresses.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/packet/trust.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js","../../node_modules/@openpgp/web-stream-tools/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs","../../node_modules/@mattiasbuelens/web-streams-adapter/dist/web-streams-adapter.mjs","../../node_modules/bn.js/lib/bn.js","../../src/biginteger/bn.interface.js","../../node_modules/brorand/index.js","../../node_modules/minimalistic-crypto-utils/lib/utils.js","../../node_modules/@openpgp/elliptic/lib/elliptic/utils.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/base.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/short.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/mont.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/edwards.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curve/index.js","../../node_modules/hash.js/lib/hash/sha/1.js","../../node_modules/hash.js/lib/hash/sha.js","../../node_modules/hash.js/lib/hash/hmac.js","../../node_modules/hash.js/lib/hash.js","../../node_modules/@openpgp/elliptic/lib/elliptic/precomputed/secp256k1.js","../../node_modules/@openpgp/elliptic/lib/elliptic/curves.js","../../node_modules/hmac-drbg/lib/hmac-drbg.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/key.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/signature.js","../../node_modules/@openpgp/elliptic/lib/elliptic/ec/index.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/key.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/signature.js","../../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/index.js","../../node_modules/@openpgp/elliptic/lib/elliptic.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","import * as streams from './streams';\nimport { isArrayStream } from './writer';\n\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n if (streams.ReadableStream && streams.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'ponyfill';\n }\n if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {\n return 'node';\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isNode } from './util';\nimport * as streams from './streams';\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Web / node stream conversion functions\n * From https://github.com/gwicke/node-web-streams\n */\n\nlet nodeToWeb;\nlet webToNode;\n\nif (NodeReadableStream) {\n\n /**\n * Convert a Node Readable Stream to a Web ReadableStream\n * @param {Readable} nodeStream\n * @returns {ReadableStream}\n */\n nodeToWeb = function(nodeStream) {\n let canceled = false;\n return new streams.ReadableStream({\n start(controller) {\n nodeStream.pause();\n nodeStream.on('data', chunk => {\n if (canceled) {\n return;\n }\n if (NodeBuffer.isBuffer(chunk)) {\n chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n controller.enqueue(chunk);\n nodeStream.pause();\n });\n nodeStream.on('end', () => {\n if (canceled) {\n return;\n }\n controller.close();\n });\n nodeStream.on('error', e => controller.error(e));\n },\n pull() {\n nodeStream.resume();\n },\n cancel(reason) {\n canceled = true;\n nodeStream.destroy(reason);\n }\n });\n };\n\n\n class NodeReadable extends NodeReadableStream {\n constructor(webStream, options) {\n super(options);\n this._reader = streams.getReader(webStream);\n }\n\n async _read(size) {\n try {\n while (true) {\n const { done, value } = await this._reader.read();\n if (done) {\n this.push(null);\n break;\n }\n if (!this.push(value)) {\n break;\n }\n }\n } catch (e) {\n this.destroy(e);\n }\n }\n\n async _destroy(error, callback) {\n this._reader.cancel(error).then(callback, callback);\n }\n }\n\n /**\n * Convert a Web ReadableStream to a Node Readable Stream\n * @param {ReadableStream} webStream\n * @param {Object} options\n * @returns {Readable}\n */\n webToNode = function(webStream, options) {\n return new NodeReadable(webStream, options);\n };\n\n}\n\nexport { nodeToWeb, webToNode };\n","import * as streams from './streams';\nimport { isUint8Array } from './util';\n\nconst doneReadingSet = new WeakSet();\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (streams.isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = async () => {};\n return;\n }\n let streamType = streams.isStream(input);\n if (streamType === 'node') {\n input = streams.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array } from './util';\nimport { nodeToWeb, webToNode } from './node-conversions';\nimport { Reader, externalBuffer } from './reader';\nimport { ArrayStream, Writer } from './writer';\n\nlet { ReadableStream, WritableStream, TransformStream } = globalThis;\n\nlet toPonyfillReadable, toNativeReadable;\n\nasync function loadStreamsPonyfill() {\n if (TransformStream) {\n return;\n }\n\n const [ponyfill, adapter] = await Promise.all([\n import('web-streams-polyfill/ponyfill/es6'),\n import('@mattiasbuelens/web-streams-adapter')\n ]);\n\n ({ ReadableStream, WritableStream, TransformStream } = ponyfill);\n\n const { createReadableStreamWrapper } = adapter;\n\n if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {\n toPonyfillReadable = createReadableStreamWrapper(ReadableStream);\n toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);\n }\n}\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType === 'node') {\n return nodeToWeb(input);\n }\n if (streamType === 'web' && toPonyfillReadable) {\n return toPonyfillReadable(input);\n }\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert data to ArrayStream\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {\n return NodeBuffer.concat(list);\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n } else {\n lastBytes = returnValue;\n }\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {\n if (end === Infinity) end = input.length;\n return input.subarray(begin, end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n return input.cancel(reason);\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n\nexport { ReadableStream, WritableStream, TransformStream, ArrayStream, loadStreamsPonyfill, isStream, isArrayStream, isUint8Array, toStream, toPonyfillReadable, toNativeReadable, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };\n","/* eslint-disable new-cap */\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * that wraps the native BigInt library.\n * Operations are not constant time,\n * but we try and limit timing leakage where we can\n * @module biginteger/native\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on null or undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n if (n instanceof Uint8Array) {\n const bytes = n;\n const hex = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n const hexByte = bytes[i].toString(16);\n hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;\n }\n this.value = BigInt('0x0' + hex.join(''));\n } else {\n this.value = BigInt(n);\n }\n }\n\n clone() {\n return new BigInteger(this.value);\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value++;\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value--;\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value += x.value;\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value -= x.value;\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value *= x.value;\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value %= m.value;\n if (this.isNegative()) {\n this.iadd(m);\n }\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation using square and multiply\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n if (n.isZero()) throw Error('Modulo cannot be zero');\n if (n.isOne()) return new BigInteger(0);\n if (e.isNegative()) throw Error('Unsopported negative exponent');\n\n let exp = e.value;\n let x = this.value;\n\n x %= n.value;\n let r = BigInt(1);\n while (exp > BigInt(0)) {\n const lsb = exp & BigInt(1);\n exp >>= BigInt(1); // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n.value;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n.value; // Square\n }\n return new BigInteger(r);\n }\n\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n const { gcd, x } = this._egcd(n);\n if (!gcd.isOne()) {\n throw new Error('Inverse does not exist');\n }\n return x.add(n).mod(n);\n }\n\n /**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)\n * @param {BigInteger} b - Second operand\n * @returns {{ gcd, x, y: BigInteger }}\n */\n _egcd(b) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n let a = this.value;\n b = b.value;\n\n while (b !== BigInt(0)) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: new BigInteger(xPrev),\n y: new BigInteger(yPrev),\n gcd: new BigInteger(a)\n };\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} b - Operand\n * @returns {BigInteger} gcd\n */\n gcd(b) {\n let a = this.value;\n b = b.value;\n while (b !== BigInt(0)) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return new BigInteger(a);\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value <<= x.value;\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value >>= x.value;\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value === x.value;\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value < x.value;\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value <= x.value;\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value > x.value;\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value >= x.value;\n }\n\n isZero() {\n return this.value === BigInt(0);\n }\n\n isOne() {\n return this.value === BigInt(1);\n }\n\n isNegative() {\n return this.value < BigInt(0);\n }\n\n isEven() {\n return !(this.value & BigInt(1));\n }\n\n abs() {\n const res = this.clone();\n if (this.isNegative()) {\n res.value = -res.value;\n }\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n const number = Number(this.value);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n const bit = (this.value >> BigInt(i)) & BigInt(1);\n return (bit === BigInt(0)) ? 0 : 1;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n const zero = new BigInteger(0);\n const one = new BigInteger(1);\n const negOne = new BigInteger(-1);\n\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = this.isNegative() ? negOne : zero;\n let bitlen = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(one).equal(target)) {\n bitlen++;\n }\n return bitlen;\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n const zero = new BigInteger(0);\n const negOne = new BigInteger(-1);\n\n const target = this.isNegative() ? negOne : zero;\n const eight = new BigInteger(8);\n let len = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(eight).equal(target)) {\n len++;\n }\n return len;\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = this.value.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? (length - rawLength) : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n }\n}\n","import BigInteger from './native.interface';\n\nconst detectBigInt = () => typeof BigInt !== 'undefined';\n\nasync function getBigInteger() {\n if (detectBigInt()) {\n return BigInteger;\n } else {\n const { default: BigInteger } = await import('./bn.interface');\n return BigInteger;\n }\n}\n\nexport { getBigInteger };\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'p256': 'p256',\n 'P-256': 'p256',\n 'secp256r1': 'p256',\n 'prime256v1': 'p256',\n '1.2.840.10045.3.1.7': 'p256',\n '2a8648ce3d030107': 'p256',\n '2A8648CE3D030107': 'p256',\n\n /** NIST P-384 Curve */\n 'p384': 'p384',\n 'P-384': 'p384',\n 'secp384r1': 'p384',\n '1.3.132.0.34': 'p384',\n '2b81040022': 'p384',\n '2B81040022': 'p384',\n\n /** NIST P-521 Curve */\n 'p521': 'p521',\n 'P-521': 'p521',\n 'secp521r1': 'p521',\n '1.3.132.0.35': 'p521',\n '2b81040023': 'p521',\n '2B81040023': 'p521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n '1.3.132.0.10': 'secp256k1',\n '2b8104000a': 'secp256k1',\n '2B8104000A': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519',\n 'ED25519': 'ed25519',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519',\n 'Ed25519': 'ed25519',\n '1.3.6.1.4.1.11591.15.1': 'ed25519',\n '2b06010401da470f01': 'ed25519',\n '2B06010401DA470F01': 'ed25519',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519',\n 'X25519': 'curve25519',\n 'cv25519': 'curve25519',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519',\n 'Curve25519': 'curve25519',\n '1.3.6.1.4.1.3029.1.5.1': 'curve25519',\n '2b060104019755010501': 'curve25519',\n '2B060104019755010501': 'curve25519',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',\n '2b2403030208010107': 'brainpoolP256r1',\n '2B2403030208010107': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',\n '2b240303020801010b': 'brainpoolP384r1',\n '2B240303020801010B': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1',\n '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',\n '2b240303020801010d': 'brainpoolP512r1',\n '2B240303020801010D': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility\n /** @deprecated use `eddsaLegacy` instead */\n ed25519Legacy: 22,\n /** @deprecated use `eddsaLegacy` instead */\n eddsa: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n plaintext: 0,\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuer: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { getBigInteger } from './biginteger';\nimport enums from './enums';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n return bytes.subarray(2, 2 + bytelen);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const r = [];\n const e = bytes.length;\n let c = 0;\n let h;\n while (c < e) {\n h = bytes[c++].toString(16);\n while (h.length < 2) {\n h = '0' + h;\n }\n r.push('' + h);\n }\n return r.join('');\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography api, only the current version of the spec.\n * @returns {Object} The SubtleCrypto api or 'undefined'.\n */\n getWebCrypto: function() {\n return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n },\n\n /**\n * Get BigInteger class\n * It wraps the native BigInt type if it's available\n * Otherwise it relies on bn.js\n * @returns {BigInteger}\n * @async\n */\n getBigInteger,\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return require('crypto');\n },\n\n getNodeZlib: function() {\n return require('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (require('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = require('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\\-0-9]+)))$/;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha256,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * @memberof module:config\n * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9\n */\n deflateLevel: 6,\n\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.eax,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use V5 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v5Keys\n */\n v5Keys: false,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:\n * Iteration Count Byte for S2K (String to Key)\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * @memberof module:config\n * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum\n */\n checksumRequired: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * @memberof module:config\n * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored\n */\n revocationsExpire: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n\n /**\n * @memberof module:config\n * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available\n */\n minBytesForWebCrypto: 1000,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * Note: the indutny/elliptic curve library is not designed to be constant time.\n * @memberof module:config\n * @property {Boolean} useIndutnyElliptic\n */\n useIndutnyElliptic: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n } else\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n } else\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n } else\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n } else\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n } else\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n } else\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Splits a message into two parts, the body and the checksum. This is an internal function\n * @param {String} text - OpenPGP armored message part\n * @returns {Object} An object with attribute \"body\" containing the body.\n * and an attribute \"checksum\" containing the checksum.\n * @private\n */\nfunction splitChecksum(text) {\n let body = text;\n let checksum = '';\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n checksum = text.slice(lastEquals + 1).substr(0, 4);\n }\n\n return { body: body, checksum: checksum };\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input, config = defaultConfig) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n let checksum;\n let data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== 2) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === 2) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const split = splitChecksum(parts[0].slice(0, -1));\n checksum = split.checksum;\n await writer.write(split.body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n data = stream.transformPair(data, async (readable, writable) => {\n const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));\n checksumVerified.catch(() => {});\n await stream.pipe(readable, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n const checksumVerifiedString = (await checksumVerified).replace('\\n', '');\n if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {\n throw new Error('Ascii armor integrity check failed');\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n const bodyClone = stream.passiveClone(body);\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push('Hash: ' + hash + '\\n\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n * @private\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","/**\n * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.\n * @author Artem S Vybornov \n * @license MIT\n */\nexport var AES_asm = function () {\n \"use strict\";\n\n /**\n * Galois Field stuff init flag\n */\n var ginit_done = false;\n\n /**\n * Galois Field exponentiation and logarithm tables for 3 (the generator)\n */\n var gexp3, glog3;\n\n /**\n * Init Galois Field tables\n */\n function ginit() {\n gexp3 = [],\n glog3 = [];\n\n var a = 1, c, d;\n for (c = 0; c < 255; c++) {\n gexp3[c] = a;\n\n // Multiply by three\n d = a & 0x80, a <<= 1, a &= 255;\n if (d === 0x80) a ^= 0x1b;\n a ^= gexp3[c];\n\n // Set the log table value\n glog3[gexp3[c]] = c;\n }\n gexp3[255] = gexp3[0];\n glog3[0] = 0;\n\n ginit_done = true;\n }\n\n /**\n * Galois Field multiplication\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\n function gmul(a, b) {\n var c = gexp3[(glog3[a] + glog3[b]) % 255];\n if (a === 0 || b === 0) c = 0;\n return c;\n }\n\n /**\n * Galois Field reciprocal\n * @param {number} a\n * @return {number}\n */\n function ginv(a) {\n var i = gexp3[255 - glog3[a]];\n if (a === 0) i = 0;\n return i;\n }\n\n /**\n * AES stuff init flag\n */\n var aes_init_done = false;\n\n /**\n * Encryption, Decryption, S-Box and KeyTransform tables\n *\n * @type {number[]}\n */\n var aes_sbox;\n\n /**\n * @type {number[]}\n */\n var aes_sinv;\n\n /**\n * @type {number[][]}\n */\n var aes_enc;\n\n /**\n * @type {number[][]}\n */\n var aes_dec;\n\n /**\n * Init AES tables\n */\n function aes_init() {\n if (!ginit_done) ginit();\n\n // Calculates AES S-Box value\n function _s(a) {\n var c, s, x;\n s = x = ginv(a);\n for (c = 0; c < 4; c++) {\n s = ((s << 1) | (s >>> 7)) & 255;\n x ^= s;\n }\n x ^= 99;\n return x;\n }\n\n // Tables\n aes_sbox = [],\n aes_sinv = [],\n aes_enc = [[], [], [], []],\n aes_dec = [[], [], [], []];\n\n for (var i = 0; i < 256; i++) {\n var s = _s(i);\n\n // S-Box and its inverse\n aes_sbox[i] = s;\n aes_sinv[s] = i;\n\n // Ecryption and Decryption tables\n aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);\n aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);\n // Rotate tables\n for (var t = 1; t < 4; t++) {\n aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);\n aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);\n }\n }\n\n aes_init_done = true;\n }\n\n /**\n * Asm.js module constructor.\n *\n *

\n * Heap buffer layout by offset:\n *

\n   * 0x0000   encryption key schedule\n   * 0x0400   decryption key schedule\n   * 0x0800   sbox\n   * 0x0c00   inv sbox\n   * 0x1000   encryption tables\n   * 0x2000   decryption tables\n   * 0x3000   reserved (future GCM multiplication lookup table)\n   * 0x4000   data\n   * 
\n * Don't touch anything before 0x400.\n *

\n *\n * @alias AES_asm\n * @class\n * @param foreign - ignored\n * @param buffer - heap buffer to link with\n */\n var wrapper = function (foreign, buffer) {\n // Init AES stuff for the first time\n if (!aes_init_done) aes_init();\n\n // Fill up AES tables\n var heap = new Uint32Array(buffer);\n heap.set(aes_sbox, 0x0800 >> 2);\n heap.set(aes_sinv, 0x0c00 >> 2);\n for (var i = 0; i < 4; i++) {\n heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);\n heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);\n }\n\n /**\n * Calculate AES key schedules.\n * @instance\n * @memberof AES_asm\n * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)\n * @param {number} k0 - key vector components\n * @param {number} k1 - key vector components\n * @param {number} k2 - key vector components\n * @param {number} k3 - key vector components\n * @param {number} k4 - key vector components\n * @param {number} k5 - key vector components\n * @param {number} k6 - key vector components\n * @param {number} k7 - key vector components\n */\n function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {\n var ekeys = heap.subarray(0x000, 60),\n dkeys = heap.subarray(0x100, 0x100 + 60);\n\n // Encryption key schedule\n ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);\n for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {\n var k = ekeys[i - 1];\n if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {\n k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];\n }\n if (i % ks === 0) {\n k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);\n }\n ekeys[i] = ekeys[i - ks] ^ k;\n }\n\n // Decryption key schedule\n for (var j = 0; j < i; j += 4) {\n for (var jj = 0; jj < 4; jj++) {\n var k = ekeys[i - (4 + j) + (4 - jj) % 4];\n if (j < 4 || j >= i - 4) {\n dkeys[j + jj] = k;\n } else {\n dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]\n ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]\n ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]\n ^ aes_dec[3][aes_sbox[k & 255]];\n }\n }\n }\n\n // Set rounds number\n asm.set_rounds(ks + 5);\n }\n\n // create library object with necessary properties\n var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};\n\n var asm = function (stdlib, foreign, buffer) {\n \"use asm\";\n\n var S0 = 0, S1 = 0, S2 = 0, S3 = 0,\n I0 = 0, I1 = 0, I2 = 0, I3 = 0,\n N0 = 0, N1 = 0, N2 = 0, N3 = 0,\n M0 = 0, M1 = 0, M2 = 0, M3 = 0,\n H0 = 0, H1 = 0, H2 = 0, H3 = 0,\n R = 0;\n\n var HEAP = new stdlib.Uint32Array(buffer),\n DATA = new stdlib.Uint8Array(buffer);\n\n /**\n * AES core\n * @param {number} k - precomputed key schedule offset\n * @param {number} s - precomputed sbox table offset\n * @param {number} t - precomputed round table offset\n * @param {number} r - number of inner rounds to perform\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _core(k, s, t, r, x0, x1, x2, x3) {\n k = k | 0;\n s = s | 0;\n t = t | 0;\n r = r | 0;\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t1 = 0, t2 = 0, t3 = 0,\n y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n i = 0;\n\n t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;\n\n // round 0\n x0 = x0 ^ HEAP[(k | 0) >> 2],\n x1 = x1 ^ HEAP[(k | 4) >> 2],\n x2 = x2 ^ HEAP[(k | 8) >> 2],\n x3 = x3 ^ HEAP[(k | 12) >> 2];\n\n // round 1..r\n for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {\n y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n x0 = y0, x1 = y1, x2 = y2, x3 = y3;\n }\n\n // final round\n S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n }\n\n /**\n * ECB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n x0,\n x1,\n x2,\n x3\n );\n }\n\n /**\n * ECB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n }\n\n\n /**\n * CBC mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0 ^ x0,\n I1 ^ x1,\n I2 ^ x2,\n I3 ^ x3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n }\n\n /**\n * CBC mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n\n S0 = S0 ^ I0,\n S1 = S1 ^ I1,\n S2 = S2 ^ I2,\n S3 = S3 ^ I3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * CFB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0 = S0 ^ x0,\n I1 = S1 = S1 ^ x1,\n I2 = S2 = S2 ^ x2,\n I3 = S3 = S3 ^ x3;\n }\n\n\n /**\n * CFB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * OFB mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ofb(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n }\n\n /**\n * CTR mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ctr(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n N0,\n N1,\n N2,\n N3\n );\n\n N3 = (~M3 & N3) | M3 & (N3 + 1);\n N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));\n N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));\n N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));\n\n S0 = S0 ^ x0;\n S1 = S1 ^ x1;\n S2 = S2 ^ x2;\n S3 = S3 ^ x3;\n }\n\n /**\n * GCM mode MAC calculation\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _gcm_mac(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n z0 = 0, z1 = 0, z2 = 0, z3 = 0,\n i = 0, c = 0;\n\n x0 = x0 ^ I0,\n x1 = x1 ^ I1,\n x2 = x2 ^ I2,\n x3 = x3 ^ I3;\n\n y0 = H0 | 0,\n y1 = H1 | 0,\n y2 = H2 | 0,\n y3 = H3 | 0;\n\n for (; (i | 0) < 128; i = (i + 1) | 0) {\n if (y0 >>> 31) {\n z0 = z0 ^ x0,\n z1 = z1 ^ x1,\n z2 = z2 ^ x2,\n z3 = z3 ^ x3;\n }\n\n y0 = (y0 << 1) | (y1 >>> 31),\n y1 = (y1 << 1) | (y2 >>> 31),\n y2 = (y2 << 1) | (y3 >>> 31),\n y3 = (y3 << 1);\n\n c = x3 & 1;\n\n x3 = (x3 >>> 1) | (x2 << 31),\n x2 = (x2 >>> 1) | (x1 << 31),\n x1 = (x1 >>> 1) | (x0 << 31),\n x0 = (x0 >>> 1);\n\n if (c) x0 = x0 ^ 0xe1000000;\n }\n\n I0 = z0,\n I1 = z1,\n I2 = z2,\n I3 = z3;\n }\n\n /**\n * Set the internal rounds number.\n * @instance\n * @memberof AES_asm\n * @param {number} r - number if inner AES rounds\n */\n function set_rounds(r) {\n r = r | 0;\n R = r;\n }\n\n /**\n * Populate the internal state of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} s0 - state vector\n * @param {number} s1 - state vector\n * @param {number} s2 - state vector\n * @param {number} s3 - state vector\n */\n function set_state(s0, s1, s2, s3) {\n s0 = s0 | 0;\n s1 = s1 | 0;\n s2 = s2 | 0;\n s3 = s3 | 0;\n\n S0 = s0,\n S1 = s1,\n S2 = s2,\n S3 = s3;\n }\n\n /**\n * Populate the internal iv of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} i0 - iv vector\n * @param {number} i1 - iv vector\n * @param {number} i2 - iv vector\n * @param {number} i3 - iv vector\n */\n function set_iv(i0, i1, i2, i3) {\n i0 = i0 | 0;\n i1 = i1 | 0;\n i2 = i2 | 0;\n i3 = i3 | 0;\n\n I0 = i0,\n I1 = i1,\n I2 = i2,\n I3 = i3;\n }\n\n /**\n * Set nonce for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} n0 - nonce vector\n * @param {number} n1 - nonce vector\n * @param {number} n2 - nonce vector\n * @param {number} n3 - nonce vector\n */\n function set_nonce(n0, n1, n2, n3) {\n n0 = n0 | 0;\n n1 = n1 | 0;\n n2 = n2 | 0;\n n3 = n3 | 0;\n\n N0 = n0,\n N1 = n1,\n N2 = n2,\n N3 = n3;\n }\n\n /**\n * Set counter mask for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} m0 - counter mask vector\n * @param {number} m1 - counter mask vector\n * @param {number} m2 - counter mask vector\n * @param {number} m3 - counter mask vector\n */\n function set_mask(m0, m1, m2, m3) {\n m0 = m0 | 0;\n m1 = m1 | 0;\n m2 = m2 | 0;\n m3 = m3 | 0;\n\n M0 = m0,\n M1 = m1,\n M2 = m2,\n M3 = m3;\n }\n\n /**\n * Set counter for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} c0 - counter vector\n * @param {number} c1 - counter vector\n * @param {number} c2 - counter vector\n * @param {number} c3 - counter vector\n */\n function set_counter(c0, c1, c2, c3) {\n c0 = c0 | 0;\n c1 = c1 | 0;\n c2 = c2 | 0;\n c3 = c3 | 0;\n\n N3 = (~M3 & N3) | M3 & c3,\n N2 = (~M2 & N2) | M2 & c2,\n N1 = (~M1 & N1) | M1 & c1,\n N0 = (~M0 & N0) | M0 & c0;\n }\n\n /**\n * Store the internal state vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_state(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n return 16;\n }\n\n /**\n * Store the internal iv vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_iv(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = I0 >>> 24,\n DATA[pos | 1] = I0 >>> 16 & 255,\n DATA[pos | 2] = I0 >>> 8 & 255,\n DATA[pos | 3] = I0 & 255,\n DATA[pos | 4] = I1 >>> 24,\n DATA[pos | 5] = I1 >>> 16 & 255,\n DATA[pos | 6] = I1 >>> 8 & 255,\n DATA[pos | 7] = I1 & 255,\n DATA[pos | 8] = I2 >>> 24,\n DATA[pos | 9] = I2 >>> 16 & 255,\n DATA[pos | 10] = I2 >>> 8 & 255,\n DATA[pos | 11] = I2 & 255,\n DATA[pos | 12] = I3 >>> 24,\n DATA[pos | 13] = I3 >>> 16 & 255,\n DATA[pos | 14] = I3 >>> 8 & 255,\n DATA[pos | 15] = I3 & 255;\n\n return 16;\n }\n\n /**\n * GCM initialization.\n * @instance\n * @memberof AES_asm\n */\n function gcm_init() {\n _ecb_enc(0, 0, 0, 0);\n H0 = S0,\n H1 = S1,\n H2 = S2,\n H3 = S3;\n }\n\n /**\n * Perform ciphering operation on the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function cipher(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _cipher_modes[mode & 7](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * Calculates MAC of the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function mac(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _mac_modes[mode & 1](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * AES cipher modes table (virual methods)\n */\n var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];\n\n /**\n * AES MAC modes table (virual methods)\n */\n var _mac_modes = [_cbc_enc, _gcm_mac];\n\n /**\n * Asm.js module exports\n */\n return {\n set_rounds: set_rounds,\n set_state: set_state,\n set_iv: set_iv,\n set_nonce: set_nonce,\n set_mask: set_mask,\n set_counter: set_counter,\n get_state: get_state,\n get_iv: get_iv,\n gcm_init: gcm_init,\n cipher: cipher,\n mac: mac,\n };\n }(stdlib, foreign, buffer);\n\n asm.set_key = set_key;\n\n return asm;\n };\n\n /**\n * AES enciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.ENC = {\n ECB: 0,\n CBC: 2,\n CFB: 4,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES deciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.DEC = {\n ECB: 1,\n CBC: 3,\n CFB: 5,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES MAC mode constants\n * @enum {number}\n * @const\n */\n wrapper.MAC = {\n CBC: 0,\n GCM: 1,\n };\n\n /**\n * Heap data offset\n * @type {number}\n * @const\n */\n wrapper.HEAP_DATA = 0x4000;\n\n return wrapper;\n}();\n","const local_atob = typeof atob === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'base64').toString('binary') : atob;\nconst local_btoa = typeof btoa === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'binary').toString('base64') : btoa;\nexport function string_to_bytes(str, utf8 = false) {\n var len = str.length, bytes = new Uint8Array(utf8 ? 4 * len : len);\n for (var i = 0, j = 0; i < len; i++) {\n var c = str.charCodeAt(i);\n if (utf8 && 0xd800 <= c && c <= 0xdbff) {\n if (++i >= len)\n throw new Error('Malformed string, low surrogate expected at position ' + i);\n c = ((c ^ 0xd800) << 10) | 0x10000 | (str.charCodeAt(i) ^ 0xdc00);\n }\n else if (!utf8 && c >>> 8) {\n throw new Error('Wide characters are not allowed.');\n }\n if (!utf8 || c <= 0x7f) {\n bytes[j++] = c;\n }\n else if (c <= 0x7ff) {\n bytes[j++] = 0xc0 | (c >> 6);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else if (c <= 0xffff) {\n bytes[j++] = 0xe0 | (c >> 12);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else {\n bytes[j++] = 0xf0 | (c >> 18);\n bytes[j++] = 0x80 | ((c >> 12) & 0x3f);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n }\n return bytes.subarray(0, j);\n}\nexport function hex_to_bytes(str) {\n var len = str.length;\n if (len & 1) {\n str = '0' + str;\n len++;\n }\n var bytes = new Uint8Array(len >> 1);\n for (var i = 0; i < len; i += 2) {\n bytes[i >> 1] = parseInt(str.substr(i, 2), 16);\n }\n return bytes;\n}\nexport function base64_to_bytes(str) {\n return string_to_bytes(local_atob(str));\n}\nexport function bytes_to_string(bytes, utf8 = false) {\n var len = bytes.length, chars = new Array(len);\n for (var i = 0, j = 0; i < len; i++) {\n var b = bytes[i];\n if (!utf8 || b < 128) {\n chars[j++] = b;\n }\n else if (b >= 192 && b < 224 && i + 1 < len) {\n chars[j++] = ((b & 0x1f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 224 && b < 240 && i + 2 < len) {\n chars[j++] = ((b & 0xf) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 240 && b < 248 && i + 3 < len) {\n var c = ((b & 7) << 18) | ((bytes[++i] & 0x3f) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n if (c <= 0xffff) {\n chars[j++] = c;\n }\n else {\n c ^= 0x10000;\n chars[j++] = 0xd800 | (c >> 10);\n chars[j++] = 0xdc00 | (c & 0x3ff);\n }\n }\n else {\n throw new Error('Malformed UTF8 character at byte offset ' + i);\n }\n }\n var str = '', bs = 16384;\n for (var i = 0; i < j; i += bs) {\n str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));\n }\n return str;\n}\nexport function bytes_to_hex(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var h = (arr[i] & 0xff).toString(16);\n if (h.length < 2)\n str += '0';\n str += h;\n }\n return str;\n}\nexport function bytes_to_base64(arr) {\n return local_btoa(bytes_to_string(arr));\n}\nexport function pow2_ceil(a) {\n a -= 1;\n a |= a >>> 1;\n a |= a >>> 2;\n a |= a >>> 4;\n a |= a >>> 8;\n a |= a >>> 16;\n a += 1;\n return a;\n}\nexport function is_number(a) {\n return typeof a === 'number';\n}\nexport function is_string(a) {\n return typeof a === 'string';\n}\nexport function is_buffer(a) {\n return a instanceof ArrayBuffer;\n}\nexport function is_bytes(a) {\n return a instanceof Uint8Array;\n}\nexport function is_typed_array(a) {\n return (a instanceof Int8Array ||\n a instanceof Uint8Array ||\n a instanceof Int16Array ||\n a instanceof Uint16Array ||\n a instanceof Int32Array ||\n a instanceof Uint32Array ||\n a instanceof Float32Array ||\n a instanceof Float64Array);\n}\nexport function _heap_init(heap, heapSize) {\n const size = heap ? heap.byteLength : heapSize || 65536;\n if (size & 0xfff || size <= 0)\n throw new Error('heap size must be a positive integer and a multiple of 4096');\n heap = heap || new Uint8Array(new ArrayBuffer(size));\n return heap;\n}\nexport function _heap_write(heap, hpos, data, dpos, dlen) {\n const hlen = heap.length - hpos;\n const wlen = hlen < dlen ? hlen : dlen;\n heap.set(data.subarray(dpos, dpos + wlen), hpos);\n return wlen;\n}\nexport function joinBytes(...arg) {\n const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);\n const ret = new Uint8Array(totalLenght);\n let cursor = 0;\n for (let i = 0; i < arg.length; i++) {\n ret.set(arg[i], cursor);\n cursor += arg[i].length;\n }\n return ret;\n}\n","export class IllegalStateError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });\n }\n}\nexport class IllegalArgumentError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });\n }\n}\nexport class SecurityError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'SecurityError' } });\n }\n}\n","import { AES_asm } from './aes.asm';\nimport { _heap_init, _heap_write, is_bytes } from '../other/utils';\nimport { IllegalArgumentError, SecurityError } from '../other/errors';\nconst heap_pool = [];\nconst asm_pool = [];\nexport class AES {\n constructor(key, iv, padding = true, mode, heap, asm) {\n this.pos = 0;\n this.len = 0;\n this.mode = mode;\n // The AES object state\n this.pos = 0;\n this.len = 0;\n this.key = key;\n this.iv = iv;\n this.padding = padding;\n // The AES \"worker\"\n this.acquire_asm(heap, asm);\n }\n acquire_asm(heap, asm) {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);\n this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);\n this.reset(this.key, this.iv);\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n reset(key, iv) {\n const { asm } = this.acquire_asm();\n // Key\n const keylen = key.length;\n if (keylen !== 16 && keylen !== 24 && keylen !== 32)\n throw new IllegalArgumentError('illegal key size');\n const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);\n asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);\n // IV\n if (iv !== undefined) {\n if (iv.length !== 16)\n throw new IllegalArgumentError('illegal iv size');\n let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));\n }\n else {\n asm.set_iv(0, 0, 0, 0);\n }\n }\n AES_Encrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n let result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Encrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let plen = 16 - (len % 16);\n let rlen = len;\n if (this.hasOwnProperty('padding')) {\n if (this.padding) {\n for (let p = 0; p < plen; ++p) {\n heap[pos + len + p] = plen;\n }\n len += plen;\n rlen = len;\n }\n else if (len % 16) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n }\n else {\n len += plen;\n }\n const result = new Uint8Array(rlen);\n if (len)\n asm.cipher(amode, hpos + pos, len);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n AES_Decrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let plen = 0;\n let wlen = 0;\n if (this.padding) {\n plen = len + dlen - rlen || 16;\n rlen -= plen;\n }\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Decrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let rlen = len;\n if (len > 0) {\n if (len % 16) {\n if (this.hasOwnProperty('padding')) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n else {\n len += 16 - (len % 16);\n }\n }\n asm.cipher(amode, hpos + pos, len);\n if (this.hasOwnProperty('padding') && this.padding) {\n let pad = heap[pos + rlen - 1];\n if (pad < 1 || pad > 16 || pad > rlen)\n throw new SecurityError('bad padding');\n let pcheck = 0;\n for (let i = pad; i > 1; i--)\n pcheck |= pad ^ heap[pos + rlen - i];\n if (pcheck)\n throw new SecurityError('bad padding');\n rlen -= pad;\n }\n }\n const result = new Uint8Array(rlen);\n if (rlen > 0) {\n result.set(heap.subarray(pos, pos + rlen));\n }\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_ECB {\n static encrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).encrypt(data);\n }\n static decrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).decrypt(data);\n }\n constructor(key, padding = false, aes) {\n this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';\n\n/**\n * Javascript AES implementation.\n * This is used as fallback if the native Crypto APIs are not available.\n */\nfunction aes(length) {\n const C = function(key) {\n const aesECB = new AES_ECB(key);\n\n this.encrypt = function(block) {\n return aesECB.encrypt(block);\n };\n\n this.decrypt = function(block) {\n return aesECB.decrypt(block);\n };\n };\n\n C.blockSize = C.prototype.blockSize = 16;\n C.keySize = C.prototype.keySize = length / 8;\n\n return C;\n}\n\nexport default aes;\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * @fileoverview Symmetric cryptography functions\n * @module crypto/cipher\n * @private\n */\n\nimport aes from './aes';\nimport { DES, TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TF from './twofish';\nimport BF from './blowfish';\n\n/**\n * AES-128 encryption and decryption (ID 7)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes128 = aes(128);\n/**\n * AES-128 Block Cipher (ID 8)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes192 = aes(192);\n/**\n * AES-128 Block Cipher (ID 9)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes256 = aes(256);\n// Not in OpenPGP specifications\nexport const des = DES;\n/**\n * Triple DES Block Cipher (ID 2)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}\n * @returns {Object}\n */\nexport const tripledes = TripleDES;\n/**\n * CAST-128 Block Cipher (ID 3)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}\n * @returns {Object}\n */\nexport const cast5 = CAST5;\n/**\n * Twofish Block Cipher (ID 10)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}\n * @returns {Object}\n */\nexport const twofish = TF;\n/**\n * Blowfish Block Cipher (ID 4)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}\n * @returns {Object}\n */\nexport const blowfish = BF;\n/**\n * Not implemented\n * @function\n * @throws {Error}\n */\nexport const idea = function() {\n throw new Error('IDEA symmetric-key algorithm not implemented');\n};\n","export var sha1_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,\n w16 = 0, w17 = 0, w18 = 0, w19 = 0,\n w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,\n w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,\n w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,\n w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,\n w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,\n w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n\n // 0\n t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 1\n t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 2\n t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 3\n t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 4\n t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 5\n t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 6\n t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 7\n t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 8\n t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 9\n t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 10\n t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 11\n t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 12\n t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 13\n t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 14\n t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 15\n t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 16\n n = w13 ^ w8 ^ w2 ^ w0;\n w16 = (n << 1) | (n >>> 31);\n t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 17\n n = w14 ^ w9 ^ w3 ^ w1;\n w17 = (n << 1) | (n >>> 31);\n t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 18\n n = w15 ^ w10 ^ w4 ^ w2;\n w18 = (n << 1) | (n >>> 31);\n t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 19\n n = w16 ^ w11 ^ w5 ^ w3;\n w19 = (n << 1) | (n >>> 31);\n t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 20\n n = w17 ^ w12 ^ w6 ^ w4;\n w20 = (n << 1) | (n >>> 31);\n t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 21\n n = w18 ^ w13 ^ w7 ^ w5;\n w21 = (n << 1) | (n >>> 31);\n t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 22\n n = w19 ^ w14 ^ w8 ^ w6;\n w22 = (n << 1) | (n >>> 31);\n t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 23\n n = w20 ^ w15 ^ w9 ^ w7;\n w23 = (n << 1) | (n >>> 31);\n t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 24\n n = w21 ^ w16 ^ w10 ^ w8;\n w24 = (n << 1) | (n >>> 31);\n t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 25\n n = w22 ^ w17 ^ w11 ^ w9;\n w25 = (n << 1) | (n >>> 31);\n t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 26\n n = w23 ^ w18 ^ w12 ^ w10;\n w26 = (n << 1) | (n >>> 31);\n t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 27\n n = w24 ^ w19 ^ w13 ^ w11;\n w27 = (n << 1) | (n >>> 31);\n t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 28\n n = w25 ^ w20 ^ w14 ^ w12;\n w28 = (n << 1) | (n >>> 31);\n t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 29\n n = w26 ^ w21 ^ w15 ^ w13;\n w29 = (n << 1) | (n >>> 31);\n t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 30\n n = w27 ^ w22 ^ w16 ^ w14;\n w30 = (n << 1) | (n >>> 31);\n t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 31\n n = w28 ^ w23 ^ w17 ^ w15;\n w31 = (n << 1) | (n >>> 31);\n t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 32\n n = w29 ^ w24 ^ w18 ^ w16;\n w32 = (n << 1) | (n >>> 31);\n t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 33\n n = w30 ^ w25 ^ w19 ^ w17;\n w33 = (n << 1) | (n >>> 31);\n t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 34\n n = w31 ^ w26 ^ w20 ^ w18;\n w34 = (n << 1) | (n >>> 31);\n t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 35\n n = w32 ^ w27 ^ w21 ^ w19;\n w35 = (n << 1) | (n >>> 31);\n t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 36\n n = w33 ^ w28 ^ w22 ^ w20;\n w36 = (n << 1) | (n >>> 31);\n t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 37\n n = w34 ^ w29 ^ w23 ^ w21;\n w37 = (n << 1) | (n >>> 31);\n t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 38\n n = w35 ^ w30 ^ w24 ^ w22;\n w38 = (n << 1) | (n >>> 31);\n t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 39\n n = w36 ^ w31 ^ w25 ^ w23;\n w39 = (n << 1) | (n >>> 31);\n t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 40\n n = w37 ^ w32 ^ w26 ^ w24;\n w40 = (n << 1) | (n >>> 31);\n t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 41\n n = w38 ^ w33 ^ w27 ^ w25;\n w41 = (n << 1) | (n >>> 31);\n t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 42\n n = w39 ^ w34 ^ w28 ^ w26;\n w42 = (n << 1) | (n >>> 31);\n t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 43\n n = w40 ^ w35 ^ w29 ^ w27;\n w43 = (n << 1) | (n >>> 31);\n t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 44\n n = w41 ^ w36 ^ w30 ^ w28;\n w44 = (n << 1) | (n >>> 31);\n t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 45\n n = w42 ^ w37 ^ w31 ^ w29;\n w45 = (n << 1) | (n >>> 31);\n t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 46\n n = w43 ^ w38 ^ w32 ^ w30;\n w46 = (n << 1) | (n >>> 31);\n t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 47\n n = w44 ^ w39 ^ w33 ^ w31;\n w47 = (n << 1) | (n >>> 31);\n t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 48\n n = w45 ^ w40 ^ w34 ^ w32;\n w48 = (n << 1) | (n >>> 31);\n t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 49\n n = w46 ^ w41 ^ w35 ^ w33;\n w49 = (n << 1) | (n >>> 31);\n t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 50\n n = w47 ^ w42 ^ w36 ^ w34;\n w50 = (n << 1) | (n >>> 31);\n t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 51\n n = w48 ^ w43 ^ w37 ^ w35;\n w51 = (n << 1) | (n >>> 31);\n t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 52\n n = w49 ^ w44 ^ w38 ^ w36;\n w52 = (n << 1) | (n >>> 31);\n t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 53\n n = w50 ^ w45 ^ w39 ^ w37;\n w53 = (n << 1) | (n >>> 31);\n t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 54\n n = w51 ^ w46 ^ w40 ^ w38;\n w54 = (n << 1) | (n >>> 31);\n t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 55\n n = w52 ^ w47 ^ w41 ^ w39;\n w55 = (n << 1) | (n >>> 31);\n t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 56\n n = w53 ^ w48 ^ w42 ^ w40;\n w56 = (n << 1) | (n >>> 31);\n t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 57\n n = w54 ^ w49 ^ w43 ^ w41;\n w57 = (n << 1) | (n >>> 31);\n t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 58\n n = w55 ^ w50 ^ w44 ^ w42;\n w58 = (n << 1) | (n >>> 31);\n t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 59\n n = w56 ^ w51 ^ w45 ^ w43;\n w59 = (n << 1) | (n >>> 31);\n t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 60\n n = w57 ^ w52 ^ w46 ^ w44;\n w60 = (n << 1) | (n >>> 31);\n t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 61\n n = w58 ^ w53 ^ w47 ^ w45;\n w61 = (n << 1) | (n >>> 31);\n t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 62\n n = w59 ^ w54 ^ w48 ^ w46;\n w62 = (n << 1) | (n >>> 31);\n t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 63\n n = w60 ^ w55 ^ w49 ^ w47;\n w63 = (n << 1) | (n >>> 31);\n t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 64\n n = w61 ^ w56 ^ w50 ^ w48;\n w64 = (n << 1) | (n >>> 31);\n t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 65\n n = w62 ^ w57 ^ w51 ^ w49;\n w65 = (n << 1) | (n >>> 31);\n t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 66\n n = w63 ^ w58 ^ w52 ^ w50;\n w66 = (n << 1) | (n >>> 31);\n t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 67\n n = w64 ^ w59 ^ w53 ^ w51;\n w67 = (n << 1) | (n >>> 31);\n t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 68\n n = w65 ^ w60 ^ w54 ^ w52;\n w68 = (n << 1) | (n >>> 31);\n t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 69\n n = w66 ^ w61 ^ w55 ^ w53;\n w69 = (n << 1) | (n >>> 31);\n t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 70\n n = w67 ^ w62 ^ w56 ^ w54;\n w70 = (n << 1) | (n >>> 31);\n t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 71\n n = w68 ^ w63 ^ w57 ^ w55;\n w71 = (n << 1) | (n >>> 31);\n t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 72\n n = w69 ^ w64 ^ w58 ^ w56;\n w72 = (n << 1) | (n >>> 31);\n t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 73\n n = w70 ^ w65 ^ w59 ^ w57;\n w73 = (n << 1) | (n >>> 31);\n t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 74\n n = w71 ^ w66 ^ w60 ^ w58;\n w74 = (n << 1) | (n >>> 31);\n t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 75\n n = w72 ^ w67 ^ w61 ^ w59;\n w75 = (n << 1) | (n >>> 31);\n t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 76\n n = w73 ^ w68 ^ w62 ^ w60;\n w76 = (n << 1) | (n >>> 31);\n t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 77\n n = w74 ^ w69 ^ w63 ^ w61;\n w77 = (n << 1) | (n >>> 31);\n t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 78\n n = w75 ^ w70 ^ w64 ^ w62;\n w78 = (n << 1) | (n >>> 31);\n t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 79\n n = w76 ^ w71 ^ w65 ^ w63;\n w79 = (n << 1) | (n >>> 31);\n t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n }\n\n function reset () {\n H0 = 0x67452301;\n H1 = 0xefcdab89;\n H2 = 0x98badcfe;\n H3 = 0x10325476;\n H4 = 0xc3d2e1f0;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA1\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA1\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA1\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","import { _heap_write } from '../other/utils';\nimport { IllegalStateError } from '../other/errors';\nexport class Hash {\n constructor() {\n this.pos = 0;\n this.len = 0;\n }\n reset() {\n const { asm } = this.acquire_asm();\n this.result = null;\n this.pos = 0;\n this.len = 0;\n asm.reset();\n return this;\n }\n process(data) {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n let hpos = this.pos;\n let hlen = this.len;\n let dpos = 0;\n let dlen = data.length;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);\n hlen += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.process(hpos, hlen);\n hpos += wlen;\n hlen -= wlen;\n if (!hlen)\n hpos = 0;\n }\n this.pos = hpos;\n this.len = hlen;\n return this;\n }\n finish() {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n asm.finish(this.pos, this.len, 0);\n this.result = new Uint8Array(this.HASH_SIZE);\n this.result.set(heap.subarray(0, this.HASH_SIZE));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return this;\n }\n}\n","import { sha1_asm } from './sha1.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha1_block_size = 64;\nexport const _sha1_hash_size = 20;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha1 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha1';\n this.BLOCK_SIZE = _sha1_block_size;\n this.HASH_SIZE = _sha1_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha1().process(data).finish().result;\n }\n}\nSha1.NAME = 'sha1';\nSha1.heap_pool = [];\nSha1.asm_pool = [];\nSha1.asm_function = sha1_asm;\n","import { sha256_asm } from './sha256.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha256_block_size = 64;\nexport const _sha256_hash_size = 32;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha256 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha256';\n this.BLOCK_SIZE = _sha256_block_size;\n this.HASH_SIZE = _sha256_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha256().process(data).finish().result;\n }\n}\nSha256.NAME = 'sha256';\n","export var sha256_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n f = H5;\n g = H6;\n h = H7;\n \n // 0\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 1\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 2\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 3\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 4\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 5\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 6\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 7\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 8\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 9\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 10\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 11\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 12\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 13\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 14\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 15\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 16\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 17\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 18\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 19\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 20\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 21\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 22\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 23\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 24\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 25\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 26\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 27\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 28\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 29\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 30\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 31\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 32\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 33\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 34\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 35\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 36\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 37\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 38\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 39\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 40\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 41\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 42\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 43\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 44\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 45\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 46\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 47\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 48\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 49\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 50\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 51\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 52\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 53\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 54\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 55\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 56\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 57\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 58\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 59\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 60\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 61\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 62\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 63\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n H5 = ( H5 + f )|0;\n H6 = ( H6 + g )|0;\n H7 = ( H7 + h )|0;\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n HEAP[output|20] = H5>>>24;\n HEAP[output|21] = H5>>>16&255;\n HEAP[output|22] = H5>>>8&255;\n HEAP[output|23] = H5&255;\n HEAP[output|24] = H6>>>24;\n HEAP[output|25] = H6>>>16&255;\n HEAP[output|26] = H6>>>8&255;\n HEAP[output|27] = H6&255;\n HEAP[output|28] = H7>>>24;\n HEAP[output|29] = H7>>>16&255;\n HEAP[output|30] = H7>>>8&255;\n HEAP[output|31] = H7&255;\n }\n\n function reset () {\n H0 = 0x6a09e667;\n H1 = 0xbb67ae85;\n H2 = 0x3c6ef372;\n H3 = 0xa54ff53a;\n H4 = 0x510e527f;\n H5 = 0x9b05688c;\n H6 = 0x1f83d9ab;\n H7 = 0x5be0cd19;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n h5 = h5|0;\n h6 = h6|0;\n h7 = h7|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n H5 = I5;\n H6 = I6;\n H7 = I7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n H5 = O5;\n H6 = O6;\n H7 = O7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n O5 = H5;\n O6 = H6;\n O7 = H7;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n I5 = H5;\n I6 = H6;\n I7 = H7;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n h5 = h5 ^ H5;\n h6 = h6 ^ H6;\n h7 = h7 ^ H7;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA256\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA256\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA256\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","try {\n var util = require('util');\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n * @private\n */\n\nimport { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1';\nimport { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256';\nimport sha224 from 'hash.js/lib/hash/sha/224';\nimport sha384 from 'hash.js/lib/hash/sha/384';\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport { ripemd160 } from 'hash.js/lib/hash/ripemd';\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport defaultConfig from '../../config';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction hashjsHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n }\n const hashInstance = hash();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => new Uint8Array(hashInstance.digest()));\n };\n}\n\nfunction asmcryptoHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hashInstance = new hash();\n return stream.transform(data, value => {\n hashInstance.process(value);\n }, () => hashInstance.finish().result);\n } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n } else {\n return hash.bytes(data);\n }\n };\n}\n\nconst hashFunctions = {\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),\n sha224: nodeHash('sha224') || hashjsHash(sha224),\n sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),\n sha384: nodeHash('sha384') || hashjsHash(sha384, 'SHA-384'),\n sha512: nodeHash('sha512') || hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge.\n ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)\n};\n\nexport default {\n\n /** @see module:md5 */\n md5: hashFunctions.md5,\n /** @see asmCrypto */\n sha1: hashFunctions.sha1,\n /** @see hash.js */\n sha224: hashFunctions.sha224,\n /** @see asmCrypto */\n sha256: hashFunctions.sha256,\n /** @see hash.js */\n sha384: hashFunctions.sha384,\n /** @see asmCrypto */\n sha512: hashFunctions.sha512,\n /** @see hash.js */\n ripemd: hashFunctions.ripemd,\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n default:\n throw new Error('Invalid hash function.');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CFB {\n static encrypt(data, key, iv) {\n return new AES_CFB(key, iv).encrypt(data);\n }\n static decrypt(data, key, iv) {\n return new AES_CFB(key, iv).decrypt(data);\n }\n constructor(key, iv, aes) {\n this.aes = aes ? aes : new AES(key, iv, true, 'CFB');\n delete this.aes.padding;\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import * as cipher from '.';\nimport enums from '../../enums';\n\n/**\n * Get implementation of the given cipher\n * @param {enums.symmetric} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport default function getCipher(algo) {\n const algoName = enums.read(enums.symmetric, algo);\n return cipher[algoName];\n}\n","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n * @private\n */\n\nimport { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb';\nimport * as stream from '@openpgp/web-stream-tools';\nimport getCipher from '../cipher/getCipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nfunction aesEncrypt(algo, key, pt, iv, config) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support\n !util.isStream(pt) &&\n pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2\n ) { // Web Crypto\n return webEncrypt(algo, key, pt, iv);\n }\n // asm.js fallback\n const cfb = new AES_CFB(key, iv);\n return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());\n}\n\nfunction aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new AES_CFB(key, iv);\n return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());\n }\n return AES_CFB.decrypt(ct, key, iv);\n}\n\nfunction xorMut(a, b) {\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nasync function webEncrypt(algo, key, pt, iv) {\n const ALGO = 'AES-CBC';\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);\n const { blockSize } = getCipher(algo);\n const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);\n const ct = new Uint8Array(await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);\n xorMut(ct, pt);\n return ct;\n}\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","import { AES } from './aes';\nimport { IllegalArgumentError } from '../other/errors';\nimport { joinBytes } from '../other/utils';\nexport class AES_CTR {\n static encrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n static decrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n constructor(key, nonce, aes) {\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n delete this.aes.padding;\n this.AES_CTR_set_options(nonce);\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n AES_CTR_set_options(nonce, counter, size) {\n let { asm } = this.aes.acquire_asm();\n if (size !== undefined) {\n if (size < 8 || size > 48)\n throw new IllegalArgumentError('illegal counter size');\n let mask = Math.pow(2, size) - 1;\n asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);\n }\n else {\n size = 48;\n asm.set_mask(0, 0, 0xffff, 0xffffffff);\n }\n if (nonce !== undefined) {\n let len = nonce.length;\n if (!len || len > 16)\n throw new IllegalArgumentError('illegal nonce size');\n let view = new DataView(new ArrayBuffer(16));\n new Uint8Array(view.buffer).set(nonce);\n asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));\n }\n else {\n throw new Error('nonce is required');\n }\n if (counter !== undefined) {\n if (counter < 0 || counter >= Math.pow(2, size))\n throw new IllegalArgumentError('illegal counter value');\n asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);\n }\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CBC {\n static encrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).encrypt(data);\n }\n static decrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).decrypt(data);\n }\n constructor(key, iv, padding = true, aes) {\n this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n * @private\n */\n\nimport { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt) {\n return AES_CBC.encrypt(pt, key, false, zeroBlock);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n * @private\n */\n\nimport { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n ) {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt, iv) {\n return AES_CTR.encrypt(pt, key, iv);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n * @private\n */\n\nimport * as ciphers from '../cipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n\n let maxNtz = 0;\n let encipher;\n let decipher;\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables(cipher, key) {\n const cipherName = enums.read(enums.symmetric, cipher);\n const aes = new ciphers[cipherName](key);\n encipher = aes.encrypt.bind(aes);\n decipher = aes.decrypt.bind(aes);\n\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors';\nimport { _heap_write } from '../other/utils';\nimport { AES } from './aes';\nimport { AES_asm } from './aes.asm';\nconst _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5\nexport class AES_GCM {\n constructor(key, nonce, adata, tagSize = 16, aes) {\n this.tagSize = tagSize;\n this.gamma0 = 0;\n this.counter = 1;\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n let { asm, heap } = this.aes.acquire_asm();\n // Init GCM\n asm.gcm_init();\n // Tag size\n if (this.tagSize < 4 || this.tagSize > 16)\n throw new IllegalArgumentError('illegal tagSize value');\n // Nonce\n const noncelen = nonce.length || 0;\n const noncebuf = new Uint8Array(16);\n if (noncelen !== 12) {\n this._gcm_mac_process(nonce);\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = 0;\n heap[4] = 0;\n heap[5] = 0;\n heap[6] = 0;\n heap[7] = 0;\n heap[8] = 0;\n heap[9] = 0;\n heap[10] = 0;\n heap[11] = noncelen >>> 29;\n heap[12] = (noncelen >>> 21) & 255;\n heap[13] = (noncelen >>> 13) & 255;\n heap[14] = (noncelen >>> 5) & 255;\n heap[15] = (noncelen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_iv(0, 0, 0, 0);\n noncebuf.set(heap.subarray(0, 16));\n }\n else {\n noncebuf.set(nonce);\n noncebuf[15] = 1;\n }\n const nonceview = new DataView(noncebuf.buffer);\n this.gamma0 = nonceview.getUint32(12);\n asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);\n asm.set_mask(0, 0, 0, 0xffffffff);\n // Associated data\n if (adata !== undefined) {\n if (adata.length > _AES_GCM_data_maxLength)\n throw new IllegalArgumentError('illegal adata length');\n if (adata.length) {\n this.adata = adata;\n this._gcm_mac_process(adata);\n }\n else {\n this.adata = undefined;\n }\n }\n else {\n this.adata = undefined;\n }\n // Counter\n if (this.counter < 1 || this.counter > 0xffffffff)\n throw new RangeError('counter must be a positive 32-bit integer');\n asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);\n }\n static encrypt(cleartext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);\n }\n static decrypt(ciphertext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);\n }\n encrypt(data) {\n return this.AES_GCM_encrypt(data);\n }\n decrypt(data) {\n return this.AES_GCM_decrypt(data);\n }\n AES_GCM_Encrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Encrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let adata = this.adata;\n let pos = this.aes.pos;\n let len = this.aes.len;\n const result = new Uint8Array(len + tagSize);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);\n if (len)\n result.set(heap.subarray(pos, pos + len));\n let i = len;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n result.set(heap.subarray(0, tagSize), len);\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_Decrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;\n let tlen = len + dlen - rlen;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > tlen) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n pos = 0;\n len = 0;\n }\n if (dlen > 0) {\n len += _heap_write(heap, 0, data, dpos, dlen);\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Decrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let tagSize = this.tagSize;\n let adata = this.adata;\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rlen = len - tagSize;\n if (len < tagSize)\n throw new IllegalStateError('authentication tag not found');\n const result = new Uint8Array(rlen);\n const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));\n let i = rlen;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len - tagSize;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n let acheck = 0;\n for (let i = 0; i < tagSize; ++i)\n acheck |= atag[i] ^ heap[i];\n if (acheck)\n throw new SecurityError('data integrity check failed');\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_decrypt(data) {\n const result1 = this.AES_GCM_Decrypt_process(data);\n const result2 = this.AES_GCM_Decrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n AES_GCM_encrypt(data) {\n const result1 = this.AES_GCM_Encrypt_process(data);\n const result2 = this.AES_GCM_Encrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n _gcm_mac_process(data) {\n let { asm, heap } = this.aes.acquire_asm();\n let dpos = 0;\n let dlen = data.length || 0;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, 0, data, dpos, dlen);\n dpos += wlen;\n dlen -= wlen;\n while (wlen & 15)\n heap[wlen++] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);\n }\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n * @private\n */\n\nimport { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.encrypt(pt, key, iv, adata);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (ct.length === tagLength) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n }\n };\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return AES_GCM.encrypt(pt, key, iv, adata);\n },\n\n decrypt: async function(ct, iv, adata) {\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n * @private\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","/*jshint bitwise: false*/\n\n(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d;\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d, h, r;\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n r = nacl.hash(sm.subarray(32, smlen));\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n h = nacl.hash(sm.subarray(0, smlen));\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h;\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n h = nacl.hash(m.subarray(0, n));\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n * @private\n */\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const buf = new Uint8Array(length);\n if (nodeCrypto) {\n const bytes = nodeCrypto.randomBytes(buf.length);\n buf.set(bytes);\n } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n return buf;\n}\n\n/**\n * Create a secure random BigInteger that is greater than or equal to min and less than max.\n * @param {module:BigInteger} min - Lower bound, included\n * @param {module:BigInteger} max - Upper bound, excluded\n * @returns {Promise} Random BigInteger.\n * @async\n */\nexport async function getRandomBigInteger(min, max) {\n const BigInteger = await util.getBigInteger();\n\n if (max.lt(min)) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max.sub(min);\n const bytes = modulus.byteLength();\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = new BigInteger(await getRandomBytes(bytes + 8));\n return r.mod(modulus).add(min);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\n\n/**\n * Generate a probably prime random number\n * @param {Integer} bits - Bit length of the prime\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns BigInteger\n * @async\n */\nexport async function randomProbablePrime(bits, e, k) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n const min = one.leftShift(new BigInteger(bits - 1));\n const thirty = new BigInteger(30);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n const n = await getRandomBigInteger(min, min.leftShift(one));\n let i = n.mod(thirty).toNumber();\n\n do {\n n.iadd(new BigInteger(adds[i]));\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (n.bitLength() > bits) {\n n.imod(min.leftShift(one)).iadd(min);\n i = n.mod(thirty).toNumber();\n }\n } while (!await isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns {boolean}\n * @async\n */\nexport async function isProbablePrime(n, e, k) {\n if (e && !n.dec().gcd(e).isOne()) {\n return false;\n }\n if (!await divisionTest(n)) {\n return false;\n }\n if (!await fermat(n)) {\n return false;\n }\n if (!await millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} b - Optional Fermat test base\n * @returns {boolean}\n */\nexport async function fermat(n, b) {\n const BigInteger = await util.getBigInteger();\n b = b || new BigInteger(2);\n return b.modExp(n.dec(), n).isOne();\n}\n\nexport async function divisionTest(n) {\n const BigInteger = await util.getBigInteger();\n return smallPrimes.every(m => {\n return n.mod(new BigInteger(m)) !== 0;\n });\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n];\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param {BigInteger} n - Number to test\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @param {Function} rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport async function millerRabin(n, k, rand) {\n const BigInteger = await util.getBigInteger();\n const len = n.bitLength();\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n.dec(); // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!n1.getBit(s)) { s++; }\n const d = n.rightShift(new BigInteger(s));\n\n for (; k > 0; k--) {\n const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);\n\n let x = a.modExp(d, n);\n if (x.isOne() || x.equal(n1)) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = x.mul(x).mod(n);\n\n if (x.isOne()) {\n return false;\n }\n if (x.equal(n1)) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n * @private\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport async function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n * @private\n */\n\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\n/* eslint-disable no-invalid-this */\nconst RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('version').int(), // 0\n this.key('modulus').int(), // n\n this.key('publicExponent').int(), // e\n this.key('privateExponent').int(), // d\n this.key('prime1').int(), // p\n this.key('prime2').int(), // q\n this.key('exponent1').int(), // dp\n this.key('exponent2').int(), // dq\n this.key('coefficient').int() // u\n );\n}) : undefined;\n\nconst RSAPublicKey = nodeCrypto ? asn1.define('RSAPubliceKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('modulus').int(), // n\n this.key('publicExponent').int() // e\n );\n}) : undefined;\n/* eslint-enable no-invalid-this */\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n const BigInteger = await util.getBigInteger();\n\n e = new BigInteger(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return {\n n: b64ToUint8Array(jwk.n),\n e: e.toUint8Array(),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {\n const opts = {\n modulusLength: bits,\n publicExponent: e.toNumber(),\n publicKeyEncoding: { type: 'pkcs1', format: 'der' },\n privateKeyEncoding: { type: 'pkcs1', format: 'der' }\n };\n const prv = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {\n if (err) {\n reject(err);\n } else {\n resolve(RSAPrivateKey.decode(der, 'der'));\n }\n });\n });\n /**\n * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.\n * @link https://tools.ietf.org/html/rfc3447#section-3.2\n * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1\n */\n return {\n n: prv.modulus.toArrayLike(Uint8Array),\n e: prv.publicExponent.toArrayLike(Uint8Array),\n d: prv.privateExponent.toArrayLike(Uint8Array),\n // switch p and q\n p: prv.prime2.toArrayLike(Uint8Array),\n q: prv.prime1.toArrayLike(Uint8Array),\n // Since p and q are switched in places, we can keep u as defined by DER\n u: prv.coefficient.toArrayLike(Uint8Array)\n };\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = await randomProbablePrime(bits - (bits >> 1), e, 40);\n p = await randomProbablePrime(bits >> 1, e, 40);\n n = p.mul(q);\n } while (n.bitLength() !== bits);\n\n const phi = p.dec().imul(q.dec());\n\n if (q.lt(p)) {\n [p, q] = [q, p];\n }\n\n return {\n n: n.toUint8Array(),\n e: e.toUint8Array(),\n d: e.modInv(phi).toUint8Array(),\n p: p.toUint8Array(),\n q: q.toUint8Array(),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: p.modInv(q).toUint8Array()\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n p = new BigInteger(p);\n q = new BigInteger(q);\n\n // expect pq = n\n if (!p.mul(q).equal(n)) {\n return false;\n }\n\n const two = new BigInteger(2);\n // expect p*u = 1 mod q\n u = new BigInteger(u);\n if (!p.mul(u).mod(q).isOne()) {\n return false;\n }\n\n e = new BigInteger(e);\n d = new BigInteger(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));\n const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r.mul(d).mul(e);\n\n const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));\n d = new BigInteger(d);\n if (m.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return m.modExp(d, n).toUint8Array('be', n.byteLength());\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPrivateKey.encode(keyObject, 'der');\n return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));\n }\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n return new Uint8Array(sign.sign(pem));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n s = new BigInteger(s);\n e = new BigInteger(e);\n if (s.gte(n)) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());\n const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1' };\n } else {\n key = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n }\n try {\n return await verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const { default: BN } = await import('bn.js');\n\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n data = new BigInteger(emeEncode(data, n.byteLength()));\n e = new BigInteger(e);\n if (data.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return data.modExp(e, n).toUint8Array('be', n.byteLength());\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPrivateKey.encode(keyObject, 'der');\n key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n const BigInteger = await util.getBigInteger();\n data = new BigInteger(data);\n n = new BigInteger(n);\n e = new BigInteger(e);\n d = new BigInteger(d);\n p = new BigInteger(p);\n q = new BigInteger(q);\n u = new BigInteger(u);\n if (data.gte(n)) {\n throw new Error('Data too large.');\n }\n const dq = d.mod(q.dec()); // d mod (q-1)\n const dp = d.mod(p.dec()); // d mod (p-1)\n\n const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);\n const blinder = unblinder.modInv(n).modExp(e, n);\n data = data.mul(blinder).mod(n);\n\n\n const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p\n const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q\n const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h.mul(p).add(mp); // result < n due to relations above\n\n result = result.mul(unblinder).mod(n);\n\n\n return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n const pNum = new BigInteger(p);\n const qNum = new BigInteger(q);\n const dNum = new BigInteger(d);\n\n let dq = dNum.mod(qNum.dec()); // d mod (q-1)\n let dp = dNum.mod(pNum.dec()); // d mod (p-1)\n dp = dp.toUint8Array();\n dq = dq.toUint8Array();\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const padded = emeEncode(data, p.byteLength());\n const m = new BigInteger(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = await getRandomBigInteger(new BigInteger(1), p.dec());\n return {\n c1: g.modExp(k, p).toUint8Array(),\n c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n const BigInteger = await util.getBigInteger();\n c1 = new BigInteger(c1);\n c2 = new BigInteger(c2);\n p = new BigInteger(p);\n x = new BigInteger(x);\n\n const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);\n return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = new BigInteger(p.bitLength());\n const n1023 = new BigInteger(1023);\n if (pSize.lt(n1023)) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (!g.modExp(p.dec(), p).isOne()) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n const i = new BigInteger(1);\n const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold\n while (i.lt(threshold)) {\n res = res.mul(g).imod(p);\n if (res.isOne()) {\n return false;\n }\n i.iinc();\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1\n const rqx = p.dec().imul(r).iadd(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n * @private\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {string} String with the canonical name of the curve.\n */\n getName() {\n const hex = this.toHex();\n if (enums.curve[hex]) {\n return enums.write(enums.curve, hex);\n } else {\n throw new Error('Unknown curve object identifier.');\n }\n }\n}\n\nexport default OID;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library\n * @module crypto/public_key/elliptic/indutnyKey\n * @private\n */\n\nimport config from '../../../config';\n\nexport function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}\n\nexport function keyFromPublic(indutnyCurve, pub) {\n const keyPair = indutnyCurve.keyPair({ pub: pub });\n if (keyPair.validate().result !== true) {\n throw new Error('Invalid elliptic public key');\n }\n return keyPair;\n}\n\nexport async function getIndutnyCurve(name) {\n if (!config.useIndutnyElliptic) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n const { default: elliptic } = await import('@openpgp/elliptic');\n return new elliptic.ec(name);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new stream.TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { getRandomBytes } from '../../random';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport { UnsupportedError } from '../../../packet/packet';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n 'p256': 'P-256',\n 'p384': 'P-384',\n 'p521': 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,\n brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n p256: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.p256,\n web: webCurves.p256,\n payloadSize: 32,\n sharedSize: 256\n },\n p384: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.p384,\n web: webCurves.p384,\n payloadSize: 48,\n sharedSize: 384\n },\n p521: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.p521,\n web: webCurves.p521,\n payloadSize: 66,\n sharedSize: 528\n },\n secp256k1: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.secp256k1,\n payloadSize: 32\n },\n ed25519: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32\n },\n curve25519: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32\n },\n brainpoolP256r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.brainpoolP256r1,\n payloadSize: 32\n },\n brainpoolP384r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.brainpoolP384r1,\n payloadSize: 48\n },\n brainpoolP512r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.brainpoolP512r1,\n payloadSize: 64\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName, params) {\n try {\n if (util.isArray(oidOrName) ||\n util.isUint8Array(oidOrName)) {\n // by oid byte array\n oidOrName = new OID(oidOrName);\n }\n if (oidOrName instanceof OID) {\n // by curve OID\n oidOrName = oidOrName.getName();\n }\n // by curve name or oid string\n this.name = enums.write(enums.curve, oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n params = params || curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node && curves[this.name];\n this.web = params.web && curves[this.name];\n this.payloadSize = params.payloadSize;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === 'curve25519') {\n this.type = 'curve25519';\n } else if (this.name === 'ed25519') {\n this.type = 'ed25519';\n }\n }\n\n async genKeyPair() {\n let keyPair;\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n break;\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519': {\n const privateKey = getRandomBytes(32);\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const secretKey = privateKey.slice().reverse();\n keyPair = nacl.box.keyPair.fromSecretKey(secretKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n case 'ed25519': {\n const privateKey = getRandomBytes(32);\n const keyPair = nacl.sign.keyPair.fromSeed(privateKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n }\n const indutnyCurve = await getIndutnyCurve(this.name);\n keyPair = await indutnyCurve.genKeyPair({\n entropy: util.uint8ArrayToString(getRandomBytes(32))\n });\n return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };\n }\n}\n\nasync function generate(curve) {\n const BigInteger = await util.getBigInteger();\n\n curve = new CurveWithOID(curve);\n const keyPair = await curve.genKeyPair();\n const Q = new BigInteger(keyPair.publicKey).toUint8Array();\n const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);\n return {\n oid: curve.oid,\n Q,\n secret,\n hash: curve.hash,\n cipher: curve.cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[enums.write(enums.curve, oid.toHex())].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n p256: true,\n p384: true,\n p521: true,\n secp256k1: true,\n curve25519: algo === enums.publicKey.ecdh,\n brainpoolP256r1: true,\n brainpoolP384r1: true,\n brainpoolP512r1: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === 'curve25519') {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const curve = await getIndutnyCurve(curveName);\n try {\n // Parse Q and check that it is on the curve but not at infinity\n Q = keyFromPublic(curve, Q).getPublic();\n } catch (validationErrors) {\n return false;\n }\n\n /**\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = keyFromPrivate(curve, d).getPublic();\n if (!dG.eq(Q)) {\n return false;\n }\n\n return true;\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nasync function webGenKeyPair(name) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = 0x04;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n * @private\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './oid_curves';\nimport { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web': {\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n }\n case 'node': {\n const signature = await nodeSign(curve, hashAlgo, message, keyPair);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n }\n }\n }\n return ellipticSign(curve, hashed, privateKey);\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n return await webVerify(curve, hashAlgo, signature, message, publicKey);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node':\n return nodeVerify(curve, hashAlgo, signature, message, publicKey);\n }\n }\n const digest = (typeof hashAlgo === 'undefined') ? message : hashed;\n return ellipticVerify(curve, signature, digest, publicKey);\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\nasync function ellipticSign(curve, hashed, privateKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPrivate(indutnyCurve, privateKey);\n const signature = key.sign(hashed);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n}\n\nasync function ellipticVerify(curve, signature, digest, publicKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPublic(indutnyCurve, publicKey);\n return key.verify(digest, signature);\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, keyPair) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n const key = ECPrivateKey.encode({\n version: 1,\n parameters: curve.oid,\n privateKey: Array.from(keyPair.privateKey),\n publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }\n }, 'pem', {\n label: 'EC PRIVATE KEY'\n });\n\n return ECDSASignature.decode(sign.sign(key), 'der');\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n const key = SubjectPublicKeyInfo.encode({\n algorithm: {\n algorithm: [1, 2, 840, 10045, 2, 1],\n parameters: curve.oid\n },\n subjectPublicKey: { unused: 0, data: Array.from(publicKey) }\n }, 'pem', {\n label: 'PUBLIC KEY'\n });\n const signature = ECDSASignature.encode({\n r: new BN(r), s: new BN(s)\n }, 'der');\n\n try {\n return verify.verify(key, signature);\n } catch (err) {\n return false;\n }\n}\n\n// Originally written by Owen Smith https://github.com/omsmith\n// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/\n\n/* eslint-disable no-invalid-this */\n\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\nconst ECDSASignature = nodeCrypto ?\n asn1.define('ECDSASignature', function() {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n );\n }) : undefined;\n\nconst ECPrivateKey = nodeCrypto ?\n asn1.define('ECPrivateKey', function() {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').explicit(0).optional().any(),\n this.key('publicKey').explicit(1).optional().bitstr()\n );\n }) : undefined;\n\nconst AlgorithmIdentifier = nodeCrypto ?\n asn1.define('AlgorithmIdentifier', function() {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional().any()\n );\n }) : undefined;\n\nconst SubjectPublicKeyInfo = nodeCrypto ?\n asn1.define('SubjectPublicKeyInfo', function() {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n );\n }) : undefined;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);\n const signature = nacl.sign.detached(hashed, secretKey);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const signature = util.concatUint8Array([r, s]);\n return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1));\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== 'ed25519') {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const seed = getRandomBytes(32);\n const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = nacl.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n return nacl.sign.detached.verify(hashed, RS, publicKey);\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: // unsupported\n default:\n return false;\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n * @private\n */\n\nimport * as cipher from './cipher';\nimport util from '../util';\n\n/**\n * AES key wrap\n * @function\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nexport function wrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const P = unpack(data);\n let A = IV;\n const R = P;\n const n = P.length / 2;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 0; j <= 5; ++j) {\n for (let i = 0; i < n; ++i) {\n t[1] = n * j + (1 + i);\n // B = A\n B[0] = A[0];\n B[1] = A[1];\n // B = A || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES(K, B)\n B = unpack(aes.encrypt(pack(B)));\n // A = MSB(64, B) ^ t\n A = B.subarray(0, 2);\n A[0] ^= t[0];\n A[1] ^= t[1];\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n return pack(A, R);\n}\n\n/**\n * AES key unwrap\n * @function\n * @param {String} key\n * @param {String} data\n * @returns {Uint8Array}\n * @throws {Error}\n */\nexport function unwrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const C = unpack(data);\n let A = C.subarray(0, 2);\n const R = C.subarray(2);\n const n = C.length / 2 - 1;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 5; j >= 0; --j) {\n for (let i = n - 1; i >= 0; --i) {\n t[1] = n * j + (i + 1);\n // B = A ^ t\n B[0] = A[0] ^ t[0];\n B[1] = A[1] ^ t[1];\n // B = (A ^ t) || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES-1(B)\n B = unpack(aes.decrypt(pack(B)));\n // A = MSB(64, B)\n A = B.subarray(0, 2);\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n if (A[0] === IV[0] && A[1] === IV[1]) {\n return pack(R);\n }\n throw new Error('Key Data Integrity failed');\n}\n\nfunction createArrayBuffer(data) {\n if (util.isString(data)) {\n const { length } = data;\n const buffer = new ArrayBuffer(length);\n const view = new Uint8Array(buffer);\n for (let j = 0; j < length; ++j) {\n view[j] = data.charCodeAt(j);\n }\n return buffer;\n }\n return new Uint8Array(data).buffer;\n}\n\nfunction unpack(data) {\n const { length } = data;\n const buffer = createArrayBuffer(data);\n const view = new DataView(buffer);\n const arr = new Uint32Array(length / 4);\n for (let i = 0; i < length / 4; ++i) {\n arr[i] = view.getUint32(4 * i);\n }\n return arr;\n}\n\nfunction pack() {\n let length = 0;\n for (let k = 0; k < arguments.length; ++k) {\n length += 4 * arguments[k].length;\n }\n const buffer = new ArrayBuffer(length);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < arguments.length; ++i) {\n for (let j = 0; j < arguments[i].length; ++j) {\n view.setUint32(offset + 4 * j, arguments[i][j]);\n }\n offset += 4 * arguments[i].length;\n }\n return new Uint8Array(buffer);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport getCipher from '../../cipher/getCipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint.subarray(0, 20)\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519': {\n const d = getRandomBytes(32);\n const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);\n let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);\n publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n }\n return ellipticPublicEphemeralKey(curve, Q);\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = aesKW.wrap(Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519': {\n const secretKey = d.slice().reverse();\n const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n }\n return ellipticPrivateEphemeralKey(curve, V, d);\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(aesKW.unwrap(Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: sender\n },\n privateKey,\n curve.web.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.web.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPrivateEphemeralKey(curve, V, d) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n V = keyFromPublic(indutnyCurve, V);\n d = keyFromPrivate(indutnyCurve, d);\n const secretKey = new Uint8Array(d.getPrivate());\n const S = d.derive(V.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPublicEphemeralKey(curve, Q) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const v = await curve.genKeyPair();\n Q = keyFromPublic(indutnyCurve, Q);\n const V = keyFromPrivate(indutnyCurve, v.privateKey);\n const publicKey = v.publicKey;\n const S = V.derive(Q.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeSubtleCrypto = nodeCrypto && nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle;\n\nexport default async function HKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n if (webCrypto || nodeSubtleCrypto) {\n const crypto = webCrypto || nodeSubtleCrypto;\n const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n }\n\n if (nodeCrypto) {\n const hashAlgoName = enums.read(enums.hash, hashAlgo);\n // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869\n\n const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();\n // Step 1: Extract\n // PRK = HMAC-Hash(salt, IKM)\n const pseudoRandomKey = computeHMAC(salt, inputKey);\n\n const hashLen = pseudoRandomKey.length;\n\n // Step 2: Expand\n // HKDF-Expand(PRK, info, L) -> OKM\n const n = Math.ceil(outLen / hashLen);\n const outputKeyingMaterial = new Uint8Array(n * hashLen);\n\n // HMAC input buffer updated at each iteration\n const roundInput = new Uint8Array(hashLen + info.length + 1);\n // T_i and last byte are updated at each iteration, but `info` remains constant\n roundInput.set(info, hashLen);\n\n for (let i = 0; i < n; i++) {\n // T(0) = empty string (zero length)\n // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)\n roundInput[roundInput.length - 1] = i + 1;\n // t = T(i+1)\n const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));\n roundInput.set(t, 0);\n\n outputKeyingMaterial.set(t, i * hashLen);\n }\n\n return outputKeyingMaterial.subarray(0, outLen);\n }\n\n throw new Error('No HKDF implementation available');\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport getCipher from '../../cipher/getCipher';\nimport computeHKDF from '../../hkdf';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(32);\n const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA);\n const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = aesKW.wrap(encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n * @private\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n x = new BigInteger(x);\n\n let k;\n let r;\n let s;\n let t;\n g = g.mod(p);\n x = x.mod(q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = await getRandomBigInteger(one, q); // returns in [1, q-1]\n r = g.modExp(k, p).imod(q); // (g**k mod p) mod q\n if (r.isZero()) {\n continue;\n }\n const xr = x.mul(r).imod(q);\n t = h.add(xr).imod(q); // H(m) + x*r mod q\n s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q\n if (s.isZero()) {\n continue;\n }\n break;\n }\n return {\n r: r.toUint8Array('be', q.byteLength()),\n s: s.toUint8Array('be', q.byteLength())\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n const BigInteger = await util.getBigInteger();\n const zero = new BigInteger(0);\n r = new BigInteger(r);\n s = new BigInteger(s);\n\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n if (r.lte(zero) || r.gte(q) ||\n s.lte(zero) || s.gte(q)) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);\n const w = s.modInv(q); // s**-1 mod q\n if (w.isZero()) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = g.mod(p);\n y = y.mod(p);\n const u1 = h.mul(w).imod(q); // H(m) * w mod q\n const u2 = r.mul(w).imod(q); // r * w mod q\n const t1 = g.modExp(u1, p); // g**u1 mod p\n const t2 = y.modExp(u2, p); // y**u2 mod p\n const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q\n return v.equal(r);\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (!p.dec().mod(q).isZero()) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (!g.modExp(q, p).isOne()) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = new BigInteger(q.bitLength());\n const n150 = new BigInteger(150);\n if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q\n const rqx = q.mul(r).add(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa,\n /** @see tweetnacl */\n nacl: nacl\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n * @private\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read));\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { s };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read));\n return { r, s };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n let r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n r = util.leftPad(r, 32);\n let s = util.readMPI(signature.subarray(read));\n s = util.leftPad(s, 32);\n return { r, s };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n case enums.publicKey.ed25519: {\n const RS = signature.subarray(read, read + 64); read += RS.length;\n return { RS };\n }\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n // signature already padded on parsing\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal: {\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n * @private\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n * @private\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport getCipher from './cipher/getCipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { CurveWithOID } from './public_key/elliptic/oid_curves';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519: {\n if (!util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (!util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.x25519: {\n const A = bytes.subarray(read, read + 32); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const curve = new CurveWithOID(publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, curve.payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const curve = new CurveWithOID(publicParams.oid);\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, curve.payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519: {\n const seed = bytes.subarray(read, read + 32); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519: {\n const k = bytes.subarray(read, read + 32); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key.\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519: {\n const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n }\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipher(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipher(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\nexport { getCipher };\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get preferred hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n * @private\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","\n\n\nvar TYPED_OK = typeof Uint8Array !== \"undefined\" &&\n typeof Uint16Array !== \"undefined\" &&\n typeof Int32Array !== \"undefined\";\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function assign(obj /*...args obj, from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue; \n }\n\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n //return Object.assign(...args);\n}\n\n\n// reduce buffer size, avoiding mem copy\nexport function shrinkBuf(buf, size) {\n if (buf.length === size) {\n return buf; \n }\n if (buf.subarray) {\n return buf.subarray(0, size); \n }\n buf.length = size;\n return buf;\n}\n\n\nconst fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n let i, l, len, pos, chunk;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nconst fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\n\nexport let Buf8 = TYPED_OK ? Uint8Array : Array;\nexport let Buf16 = TYPED_OK ? Uint16Array : Array;\nexport let Buf32 = TYPED_OK ? Int32Array : Array;\nexport let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;\nexport let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;\nexport function setTyped(on) {\n if (on) {\n Buf8 = Uint8Array;\n Buf16 = Uint16Array;\n Buf32 = Int32Array;\n ({ flattenChunks, arraySet } = fnTyped);\n } else {\n Buf8 = Array;\n Buf16 = Array;\n Buf32 = Array;\n ({ flattenChunks, arraySet } = fnUntyped);\n }\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nexport const Z_NO_FLUSH = 0;\nexport const Z_PARTIAL_FLUSH = 1;\nexport const Z_SYNC_FLUSH = 2;\nexport const Z_FULL_FLUSH = 3;\nexport const Z_FINISH = 4;\nexport const Z_BLOCK = 5;\nexport const Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nexport const Z_OK = 0;\nexport const Z_STREAM_END = 1;\nexport const Z_NEED_DICT = 2;\nexport const Z_ERRNO = -1;\nexport const Z_STREAM_ERROR = -2;\nexport const Z_DATA_ERROR = -3;\n//export const Z_MEM_ERROR = -4;\nexport const Z_BUF_ERROR = -5;\n//export const Z_VERSION_ERROR = -6;\n\n /* compression levels */\nexport const Z_NO_COMPRESSION = 0;\nexport const Z_BEST_SPEED = 1;\nexport const Z_BEST_COMPRESSION = 9;\nexport const Z_DEFAULT_COMPRESSION = -1;\n\n\nexport const Z_FILTERED = 1;\nexport const Z_HUFFMAN_ONLY = 2;\nexport const Z_RLE = 3;\nexport const Z_FIXED = 4;\nexport const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nexport const Z_BINARY = 0;\nexport const Z_TEXT = 1;\n//export const Z_ASCII = 1; // = Z_TEXT (deprecated)\nexport const Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nexport const Z_DEFLATED = 8;\n//export const Z_NULL = null // Use -1 or null inline, depending on var type\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nimport * as utils from \"../utils/common.js\";\nimport {\n Z_FIXED,\n Z_BINARY,\n Z_TEXT,\n Z_UNKNOWN\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nfunction zero(buf) {\n let len = buf.length; while (--len >= 0) {\n buf[len] = 0; \n } \n}\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nconst extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nconst extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nconst bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = w & 0xff;\n s.pending_buf[s.pending++] = w >>> 8 & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) {\n continue; \n } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) {\n return; \n }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--; \n }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue; \n }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2]/*.Freq*/ = 0; \n }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n // while (len--) {\n // put_byte(s, *buf++);\n // }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n const _n2 = n * 2;\n const _m2 = m * 2;\n return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break; \n }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {\n pqdownheap(s, tree, n); \n }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]/*.Freq*/++; \n }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree); \n } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb; \n }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n\n //#ifdef TRUNCATE_BLOCK\n // /* Try to guess if it is profitable to stop the current block here */\n // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n // /* Compute an upper bound for the compressed length */\n // out_length = s.last_lit*8;\n // in_length = s.strstart - s.block_start;\n //\n // for (dcode = 0; dcode < D_CODES; dcode++) {\n // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n // }\n // out_length >>>= 3;\n // //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n // // s->last_lit, in_length, out_length,\n // // 100L - out_length*100L/in_length));\n // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n // return true;\n // }\n // }\n //#endif\n\n return s.last_lit === s.lit_bufsize - 1;\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexport {\n _tr_init,\n _tr_stored_block,\n _tr_flush_block,\n _tr_tally,\n _tr_align\n};","\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default function adler32(adler, buf, len, pos) {\n let s1 = adler & 0xffff |0,\n s2 = adler >>> 16 & 0xffff |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = s1 + buf[pos++] |0;\n s2 = s2 + s1 |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return s1 | s2 << 16 |0;\n}\n","\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n let c;\n const table = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = makeTable();\n\n\nexport default function crc32(crc, buf, len, pos) {\n const t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return crc ^ -1; // >>> 0;\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default {\n 2: \"need dictionary\", /* Z_NEED_DICT 2 */\n 1: \"stream end\", /* Z_STREAM_END 1 */\n 0: \"\", /* Z_OK 0 */\n \"-1\": \"file error\", /* Z_ERRNO (-1) */\n \"-2\": \"stream error\", /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\", /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\", /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\", /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\" /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport * as trees from \"./trees.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport msg from \"./messages.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_NO_FLUSH,\n Z_PARTIAL_FLUSH,\n Z_FULL_FLUSH,\n Z_FINISH,\n Z_BLOCK,\n Z_OK,\n Z_STREAM_END,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED,\n Z_HUFFMAN_ONLY,\n Z_RLE,\n Z_FIXED,\n Z_DEFAULT_STRATEGY,\n Z_UNKNOWN,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n // put_byte(s, (Byte)(b >> 8));\n // put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n //#if MIN_MATCH != 3\n // Call update_hash() MIN_MATCH-3 more times\n //#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n // if (s.high_water < s.window_size) {\n // var curr = s.strstart + s.lookahead;\n // var init = 0;\n //\n // if (s.high_water < curr) {\n // /* Previous high water mark below current data -- zero WIN_INIT\n // * bytes or up to end of window, whichever is less.\n // */\n // init = s.window_size - curr;\n // if (init > WIN_INIT)\n // init = WIN_INIT;\n // zmemzero(s->window + curr, (unsigned)init);\n // s->high_water = curr + init;\n // }\n // else if (s->high_water < (ulg)curr + WIN_INIT) {\n // /* High water mark at or above current data, but below current data\n // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n // * to end of window, whichever is less.\n // */\n // init = (ulg)curr + WIN_INIT - s->high_water;\n // if (init > s->window_size - s->high_water)\n // init = s->window_size - s->high_water;\n // zmemzero(s->window + s->high_water, (unsigned)init);\n // s->high_water += init;\n // }\n // }\n //\n // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n // \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (; ;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n // s.block_start >= s.w_size)) {\n // throw new Error(\"slide too late\");\n // }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n // if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n //#if MIN_MATCH != 3\n // Call UPDATE_HASH() MIN_MATCH-3 more times\n //#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nclass Config {\n constructor(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n};\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\nclass DeflateState {\n constructor() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n }\n}\n\nfunction deflateResetKeep(strm) {\n let s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n let old_flush, s;\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n //#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n //#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n let status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n let dictLength = dictionary.length;\n\n let s;\n let str, n;\n let wrap;\n let avail;\n let next;\n let input;\n let tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\nconst deflateInfo = 'pako deflate (from Nodeca project)';\nexport {\n deflateInit,\n deflateInit2,\n deflateReset,\n deflateResetKeep,\n deflateSetHeader,\n deflate,\n deflateEnd,\n deflateSetDictionary,\n deflateInfo\n};\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n\n\n\nimport * as utils from \"./common.js\";\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_OK = true;\nlet STR_APPLY_UIA_OK = true;\n\ntry {\n String.fromCharCode.apply(null, [ 0 ]); \n} catch (__) {\n STR_APPLY_OK = false; \n}\ntry {\n String.fromCharCode.apply(null, new Uint8Array(1)); \n} catch (__) {\n STR_APPLY_UIA_OK = false; \n}\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new utils.Buf8(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexport function string2buf (str) {\n let c, c2, m_pos, i, buf_len = 0;\n const str_len = str.length;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n const buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | c >>> 6;\n buf[i++] = 0x80 | c & 0x3f;\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | c >>> 12;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | c >>> 18;\n buf[i++] = 0x80 | c >>> 12 & 0x3f;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n let result = \"\";\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexport function buf2binstring (buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nexport function binstring2buf (str) {\n const buf = new utils.Buf8(str.length);\n for (let i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nexport function buf2string (buf, max) {\n let i, out, c, c_len;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n // var utf16buf = new Array(len * 2);\n // try Uint16Array\n const utf16buf = new Uint16Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) {\n utf16buf[out++] = c; continue; \n }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) {\n utf16buf[out++] = 0xfffd; i += c_len - 1; continue; \n }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 0x3f;\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) {\n utf16buf[out++] = 0xfffd; continue; \n }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;\n utf16buf[out++] = 0xdc00 | c & 0x3ff;\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexport function utf8border (buf, max) {\n let pos;\n\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length; \n }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {\n pos--; \n }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) {\n return max; \n }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) {\n return max; \n }\n\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class ZStream {\n constructor() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n }\n}","'use strict';\n\nimport * as zlib_deflate from \"./zlib/deflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\nimport { Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED } from \"./zlib/constants.js\"\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\n\nclass Deflate {\n constructor(options) {\n this.options = {\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n ...(options || {})\n };\n\n const opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n }\n\n /**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize } } = this;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n /**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n /**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw new Error(deflator.msg || msg[deflator.err]); }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\nexport { Deflate, deflate, deflateRaw, gzip };\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nexport default function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let _out; /* local strm.output */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n const input = strm.input;\n const last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n const output = strm.output;\n const beg = _out - (start - strm.avail_out);\n const end = _out + (strm.avail_out - 257);\n //#ifdef INFLATE_STRICT\n const dmax = state.dmax;\n //#endif\n const wsize = state.wsize;\n const whave = state.whave;\n const wnext = state.wnext;\n const s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n const lcode = state.lencode;\n const dcode = state.distcode;\n const lmask = (1 << state.lenbits) - 1;\n const dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n } else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n //#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n //#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n // if (len <= op - whave) {\n // do {\n // output[_out++] = 0;\n // } while (--len);\n // continue top;\n // }\n // len -= op - whave;\n // do {\n // output[_out++] = 0;\n // } while (--op > whave);\n // if (op === 0) {\n // from = _out - dist;\n // do {\n // output[_out++] = output[from++];\n // } while (--len);\n // continue top;\n // }\n //#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n } else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n } else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nconst lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nconst dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nconst dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nexport default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n // var shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break; \n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break; \n }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n const mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break; \n }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break; \n }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = root << 24 | curr << 16 | next - table_index |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = len - drop << 24 | 64 << 16 |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport inflate_fast from \"./inffast.js\";\nimport inflate_table from \"./inftrees.js\";\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_FINISH,\n Z_BLOCK,\n Z_TREES,\n Z_OK,\n Z_STREAM_END,\n Z_NEED_DICT,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\n//const MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nclass InflateState {\n constructor() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n }\n}\n\nfunction inflateResetKeep(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n let wrap;\n let state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n let ret;\n let state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n let sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n let hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary var for NEED_BITS\n\n const order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n // case MEM:\n // return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n const state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n let state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n // if (ret) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n // }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nconst inflateInfo = 'pako inflate (from Nodeca project)';\n\nexport {\n inflateReset,\n inflateReset2,\n inflateResetKeep,\n inflateInit,\n inflateInit2,\n inflate,\n inflateEnd,\n inflateGetHeader,\n inflateSetDictionary,\n inflateInfo\n};\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class GZheader {\n constructor() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n }\n}","'use strict';\n\nimport * as zlib_inflate from \"./zlib/inflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport * as c from \"./zlib/constants.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\nimport GZheader from \"./zlib/gzheader.js\";\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nclass Inflate {\n constructor(options) {\n this.options = {\n chunkSize: 16384,\n windowBits: 0,\n ...(options || {})\n };\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n let status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n }\n /**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize, dictionary } } = this;\n let status, _mode;\n let next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n let allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n\n /**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n\n\n /**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === c.Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw new Error(inflator.msg || msg[inflator.err]); }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\nexport { Inflate, inflate, inflateRaw, inflate as ungzip };\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuer,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.signedHashValue = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n this.params = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false) {\n if (key.version === 5) {\n this.version = 5;\n } else {\n this.version = 4;\n }\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = [];\n this.unhashedSubpackets.forEach(data => {\n arr.push(writeSimpleLength(data.length));\n arr.push(data);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n // V4 signature sub packets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n if (!hashed) {\n this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n mypos++;\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuer:\n // Issuer\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion === 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n default: {\n const err = new Error(`Unknown signature subpacket type ${type}`);\n if (critical) {\n throw err;\n } else {\n util.printDebug(err);\n }\n }\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, 2));\n\n let i = 2;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n constructor() {\n /** A one-octet version number. The current version is 3. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** An eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current version is 3.\n this.version = bytes[mypos++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n // An eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);\n\n const end = new Uint8Array([this.flags]);\n\n return util.concatUint8Array([start, this.issuerKeyID.write(), end]);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID)\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Deflate } from '@openpgp/pako/lib/deflate';\nimport { Inflate } from '@openpgp/pako/lib/inflate';\nimport { Z_SYNC_FLUSH, Z_FINISH } from '@openpgp/pako/lib/zlib/constants';\nimport { decode as BunzipDecode } from '@openpgp/seek-bzip';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n\n /**\n * zip/zlib compression level, between 1 and 9\n */\n this.deflateLevel = config.deflateLevel;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName];\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write(), this.deflateLevel);\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nconst nodeZlib = util.getNodeZlib();\n\nfunction uncompressed(data) {\n return data;\n}\n\nfunction node_zlib(func, create, options = {}) {\n return function (data) {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(data => {\n return new Promise((resolve, reject) => {\n func(data, options, (err, result) => {\n if (err) return reject(err);\n resolve(result);\n });\n });\n }));\n }\n return stream.nodeToWeb(stream.webToNode(data).pipe(create(options)));\n };\n}\n\nfunction pako_zlib(constructor, options = {}) {\n return function(data) {\n const obj = new constructor(options);\n return stream.transform(data, value => {\n if (value.length) {\n obj.push(value, Z_SYNC_FLUSH);\n return obj.result;\n }\n }, () => {\n if (constructor === Deflate) {\n obj.push([], Z_FINISH);\n return obj.result;\n }\n });\n };\n}\n\nfunction bzip2(func) {\n return function(data) {\n return stream.fromAsync(async () => func(await stream.readToEnd(data)));\n };\n}\n\nconst compress_fns = nodeZlib ? {\n zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)\n} : {\n zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)\n};\n\nconst decompress_fns = nodeZlib ? {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),\n zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n} : {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),\n zlib: /*#__PURE__*/ pako_zlib(Inflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n constructor() {\n this.version = VERSION;\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n // - A one-octet version number. The only currently defined value is 1.\n if (version !== VERSION) {\n throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);\n }\n\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n return util.concat([new Uint8Array([VERSION]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await this.crypt('decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await this.crypt('encrypt', key, data);\n }\n\n /**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\n async crypt(fn, key, data) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const modeInstance = await mode(this.cipherAlgorithm, key);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const adataBuffer = new ArrayBuffer(21);\n const adataArray = new Uint8Array(adataBuffer, 0, 13);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n const iv = this.iv;\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new stream.TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)\n cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = 3;\n\n this.publicKeyID = new KeyID();\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n i += this.publicKeyID.read(bytes.subarray(i));\n this.publicKeyAlgorithm = bytes[i++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);\n if (this.publicKeyAlgorithm === enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version]),\n this.publicKeyID.write(),\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n // v3 Montgomery curves have cleartext cipher algo\n if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = sessionKeyAlgorithm;\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // add checksum\n return util.concatUint8Array([\n new Uint8Array([cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n }\n case enums.publicKey.x25519:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n return {\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n * @private\n */\n\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport { UnsupportedError } from '../packet/packet';\nimport util from '../util';\n\nclass S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = 'iterated';\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n try {\n this.type = enums.read(enums.s2k, bytes[i++]);\n } catch (err) {\n throw new UnsupportedError('Unknown S2K type.');\n }\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport S2K from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 5 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = enums.symmetric.aes256;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number. The only currently defined version is 4.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version === 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n this.s2k = new S2K();\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version === 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, key);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n } else {\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const encryptionKey = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v5Keys ? 5 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes) {\n let pos = 0;\n // A one-octet version number (3, 4 or 5).\n this.version = bytes[pos++];\n\n if (this.version === 4 || this.version === 5) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version === 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version === 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n if (version === 5) {\n return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);\n }\n return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version === 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version === 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport S2K from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n this.s2k = new S2K();\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipher(this.symmetric).blockSize\n );\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n const cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...this.s2k.write());\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = new S2K(config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n\n const { blockSize } = crypto.getCipher(this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = enums.aead.eax;\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } else {\n this.s2kUsage = 254;\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\nasync function produceEncryptionKey(s2k, passphrase, algorithm) {\n const { keySize } = crypto.getCipher(algorithm);\n return s2k.produceKey(passphrase, keySize);\n}\n\nexport default SecretKeyPacket;\n","\n// email-addresses.js - RFC 5322 email address parser\n// v 3.1.0\n//\n// http://tools.ietf.org/html/rfc5322\n//\n// This library does not validate email addresses.\n// emailAddresses attempts to parse addresses using the (fairly liberal)\n// grammar specified in RFC 5322.\n//\n// email-addresses returns {\n// ast: ,\n// addresses: [{\n// node: ,\n// name: ,\n// address: ,\n// local: ,\n// domain: \n// }, ...]\n// }\n//\n// emailAddresses.parseOneAddress and emailAddresses.parseAddressList\n// work as you might expect. Try it out.\n//\n// Many thanks to Dominic Sayers and his documentation on the is_email function,\n// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.\n\n(function (global) {\n\"use strict\";\n\nfunction parse5322(opts) {\n\n // tokenizing functions\n\n function inStr() { return pos < len; }\n function curTok() { return parseString[pos]; }\n function getPos() { return pos; }\n function setPos(i) { pos = i; }\n function nextTok() { pos += 1; }\n function initialize() {\n pos = 0;\n len = parseString.length;\n }\n\n // parser helper functions\n\n function o(name, value) {\n return {\n name: name,\n tokens: value || \"\",\n semantic: value || \"\",\n children: []\n };\n }\n\n function wrap(name, ast) {\n var n;\n if (ast === null) { return null; }\n n = o(name);\n n.tokens = ast.tokens;\n n.semantic = ast.semantic;\n n.children.push(ast);\n return n;\n }\n\n function add(parent, child) {\n if (child !== null) {\n parent.tokens += child.tokens;\n parent.semantic += child.semantic;\n }\n parent.children.push(child);\n return parent;\n }\n\n function compareToken(fxnCompare) {\n var tok;\n if (!inStr()) { return null; }\n tok = curTok();\n if (fxnCompare(tok)) {\n nextTok();\n return o('token', tok);\n }\n return null;\n }\n\n function literal(lit) {\n return function literalFunc() {\n return wrap('literal', compareToken(function (tok) {\n return tok === lit;\n }));\n };\n }\n\n function and() {\n var args = arguments;\n return function andFunc() {\n var i, s, result, start;\n start = getPos();\n s = o('and');\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result === null) {\n setPos(start);\n return null;\n }\n add(s, result);\n }\n return s;\n };\n }\n\n function or() {\n var args = arguments;\n return function orFunc() {\n var i, result, start;\n start = getPos();\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result !== null) {\n return result;\n }\n setPos(start);\n }\n return null;\n };\n }\n\n function opt(prod) {\n return function optFunc() {\n var result, start;\n start = getPos();\n result = prod();\n if (result !== null) {\n return result;\n }\n else {\n setPos(start);\n return o('opt');\n }\n };\n }\n\n function invis(prod) {\n return function invisFunc() {\n var result = prod();\n if (result !== null) {\n result.semantic = \"\";\n }\n return result;\n };\n }\n\n function colwsp(prod) {\n return function collapseSemanticWhitespace() {\n var result = prod();\n if (result !== null && result.semantic.length > 0) {\n result.semantic = \" \";\n }\n return result;\n };\n }\n\n function star(prod, minimum) {\n return function starFunc() {\n var s, result, count, start, min;\n start = getPos();\n s = o('star');\n count = 0;\n min = minimum === undefined ? 0 : minimum;\n while ((result = prod()) !== null) {\n count = count + 1;\n add(s, result);\n }\n if (count >= min) {\n return s;\n }\n else {\n setPos(start);\n return null;\n }\n };\n }\n\n // One expects names to get normalized like this:\n // \" First Last \" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n function collapseWhitespace(s) {\n return s.replace(/([ \\t]|\\r\\n)+/g, ' ').replace(/^\\s*/, '').replace(/\\s*$/, '');\n }\n\n // UTF-8 pseudo-production (RFC 6532)\n // RFC 6532 extends RFC 5322 productions to include UTF-8\n // using the following productions:\n // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4\n // UTF8-2 = \n // UTF8-3 = \n // UTF8-4 = \n //\n // For reference, the extended RFC 5322 productions are:\n // VCHAR =/ UTF8-non-ascii\n // ctext =/ UTF8-non-ascii\n // atext =/ UTF8-non-ascii\n // qtext =/ UTF8-non-ascii\n // dtext =/ UTF8-non-ascii\n function isUTF8NonAscii(tok) {\n // In JavaScript, we just deal directly with Unicode code points,\n // so we aren't checking individual bytes for UTF-8 encoding.\n // Just check that the character is non-ascii.\n return tok.charCodeAt(0) >= 128;\n }\n\n\n // common productions (RFC 5234)\n // http://tools.ietf.org/html/rfc5234\n // B.1. Core Rules\n\n // CR = %x0D\n // ; carriage return\n function cr() { return wrap('cr', literal('\\r')()); }\n\n // CRLF = CR LF\n // ; Internet standard newline\n function crlf() { return wrap('crlf', and(cr, lf)()); }\n\n // DQUOTE = %x22\n // ; \" (Double Quote)\n function dquote() { return wrap('dquote', literal('\"')()); }\n\n // HTAB = %x09\n // ; horizontal tab\n function htab() { return wrap('htab', literal('\\t')()); }\n\n // LF = %x0A\n // ; linefeed\n function lf() { return wrap('lf', literal('\\n')()); }\n\n // SP = %x20\n function sp() { return wrap('sp', literal(' ')()); }\n\n // VCHAR = %x21-7E\n // ; visible (printing) characters\n function vchar() {\n return wrap('vchar', compareToken(function vcharFunc(tok) {\n var code = tok.charCodeAt(0);\n var accept = (0x21 <= code && code <= 0x7E);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // WSP = SP / HTAB\n // ; white space\n function wsp() { return wrap('wsp', or(sp, htab)()); }\n\n\n // email productions (RFC 5322)\n // http://tools.ietf.org/html/rfc5322\n // 3.2.1. Quoted characters\n\n // quoted-pair = (\"\\\" (VCHAR / WSP)) / obs-qp\n function quotedPair() {\n var qp = wrap('quoted-pair',\n or(\n and(literal('\\\\'), or(vchar, wsp)),\n obsQP\n )());\n if (qp === null) { return null; }\n // a quoted pair will be two characters, and the \"\\\" character\n // should be semantically \"invisible\" (RFC 5322 3.2.1)\n qp.semantic = qp.semantic[1];\n return qp;\n }\n\n // 3.2.2. Folding White Space and Comments\n\n // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS\n function fws() {\n return wrap('fws', or(\n obsFws,\n and(\n opt(and(\n star(wsp),\n invis(crlf)\n )),\n star(wsp, 1)\n )\n )());\n }\n\n // ctext = %d33-39 / ; Printable US-ASCII\n // %d42-91 / ; characters not including\n // %d93-126 / ; \"(\", \")\", or \"\\\"\n // obs-ctext\n function ctext() {\n return wrap('ctext', or(\n function ctextFunc1() {\n return compareToken(function ctextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 39) ||\n (42 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsCtext\n )());\n }\n\n // ccontent = ctext / quoted-pair / comment\n function ccontent() {\n return wrap('ccontent', or(ctext, quotedPair, comment)());\n }\n\n // comment = \"(\" *([FWS] ccontent) [FWS] \")\"\n function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }\n\n // CFWS = (1*([FWS] comment) [FWS]) / FWS\n function cfws() {\n return wrap('cfws', or(\n and(\n star(\n and(opt(fws), comment),\n 1\n ),\n opt(fws)\n ),\n fws\n )());\n }\n\n // 3.2.3. Atom\n\n //atext = ALPHA / DIGIT / ; Printable US-ASCII\n // \"!\" / \"#\" / ; characters not including\n // \"$\" / \"%\" / ; specials. Used for atoms.\n // \"&\" / \"'\" /\n // \"*\" / \"+\" /\n // \"-\" / \"/\" /\n // \"=\" / \"?\" /\n // \"^\" / \"_\" /\n // \"`\" / \"{\" /\n // \"|\" / \"}\" /\n // \"~\"\n function atext() {\n return wrap('atext', compareToken(function atextFunc(tok) {\n var accept =\n ('a' <= tok && tok <= 'z') ||\n ('A' <= tok && tok <= 'Z') ||\n ('0' <= tok && tok <= '9') ||\n (['!', '#', '$', '%', '&', '\\'', '*', '+', '-', '/',\n '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // atom = [CFWS] 1*atext [CFWS]\n function atom() {\n return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());\n }\n\n // dot-atom-text = 1*atext *(\".\" 1*atext)\n function dotAtomText() {\n var s, maybeText;\n s = wrap('dot-atom-text', star(atext, 1)());\n if (s === null) { return s; }\n maybeText = star(and(literal('.'), star(atext, 1)))();\n if (maybeText !== null) {\n add(s, maybeText);\n }\n return s;\n }\n\n // dot-atom = [CFWS] dot-atom-text [CFWS]\n function dotAtom() {\n return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());\n }\n\n // 3.2.4. Quoted Strings\n\n // qtext = %d33 / ; Printable US-ASCII\n // %d35-91 / ; characters not including\n // %d93-126 / ; \"\\\" or the quote character\n // obs-qtext\n function qtext() {\n return wrap('qtext', or(\n function qtextFunc1() {\n return compareToken(function qtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 === code) ||\n (35 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsQtext\n )());\n }\n\n // qcontent = qtext / quoted-pair\n function qcontent() {\n return wrap('qcontent', or(qtext, quotedPair)());\n }\n\n // quoted-string = [CFWS]\n // DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n // [CFWS]\n function quotedString() {\n return wrap('quoted-string', and(\n invis(opt(cfws)),\n invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),\n invis(opt(cfws))\n )());\n }\n\n // 3.2.5 Miscellaneous Tokens\n\n // word = atom / quoted-string\n function word() {\n return wrap('word', or(atom, quotedString)());\n }\n\n // phrase = 1*word / obs-phrase\n function phrase() {\n return wrap('phrase', or(obsPhrase, star(word, 1))());\n }\n\n // 3.4. Address Specification\n // address = mailbox / group\n function address() {\n return wrap('address', or(mailbox, group)());\n }\n\n // mailbox = name-addr / addr-spec\n function mailbox() {\n return wrap('mailbox', or(nameAddr, addrSpec)());\n }\n\n // name-addr = [display-name] angle-addr\n function nameAddr() {\n return wrap('name-addr', and(opt(displayName), angleAddr)());\n }\n\n // angle-addr = [CFWS] \"<\" addr-spec \">\" [CFWS] /\n // obs-angle-addr\n function angleAddr() {\n return wrap('angle-addr', or(\n and(\n invis(opt(cfws)),\n literal('<'),\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n ),\n obsAngleAddr\n )());\n }\n\n // group = display-name \":\" [group-list] \";\" [CFWS]\n function group() {\n return wrap('group', and(\n displayName,\n literal(':'),\n opt(groupList),\n literal(';'),\n invis(opt(cfws))\n )());\n }\n\n // display-name = phrase\n function displayName() {\n return wrap('display-name', function phraseFixedSemantic() {\n var result = phrase();\n if (result !== null) {\n result.semantic = collapseWhitespace(result.semantic);\n }\n return result;\n }());\n }\n\n // mailbox-list = (mailbox *(\",\" mailbox)) / obs-mbox-list\n function mailboxList() {\n return wrap('mailbox-list', or(\n and(\n mailbox,\n star(and(literal(','), mailbox))\n ),\n obsMboxList\n )());\n }\n\n // address-list = (address *(\",\" address)) / obs-addr-list\n function addressList() {\n return wrap('address-list', or(\n and(\n address,\n star(and(literal(','), address))\n ),\n obsAddrList\n )());\n }\n\n // group-list = mailbox-list / CFWS / obs-group-list\n function groupList() {\n return wrap('group-list', or(\n mailboxList,\n invis(cfws),\n obsGroupList\n )());\n }\n\n // 3.4.1 Addr-Spec Specification\n\n // local-part = dot-atom / quoted-string / obs-local-part\n function localPart() {\n // note: quoted-string, dotAtom are proper subsets of obs-local-part\n // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree\n return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());\n }\n\n // dtext = %d33-90 / ; Printable US-ASCII\n // %d94-126 / ; characters not including\n // obs-dtext ; \"[\", \"]\", or \"\\\"\n function dtext() {\n return wrap('dtext', or(\n function dtextFunc1() {\n return compareToken(function dtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 90) ||\n (94 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsDtext\n )()\n );\n }\n\n // domain-literal = [CFWS] \"[\" *([FWS] dtext) [FWS] \"]\" [CFWS]\n function domainLiteral() {\n return wrap('domain-literal', and(\n invis(opt(cfws)),\n literal('['),\n star(and(opt(fws), dtext)),\n opt(fws),\n literal(']'),\n invis(opt(cfws))\n )());\n }\n\n // domain = dot-atom / domain-literal / obs-domain\n function domain() {\n return wrap('domain', function domainCheckTLD() {\n var result = or(obsDomain, dotAtom, domainLiteral)();\n if (opts.rejectTLD) {\n if (result && result.semantic && result.semantic.indexOf('.') < 0) {\n return null;\n }\n }\n // strip all whitespace from domains\n if (result) {\n result.semantic = result.semantic.replace(/\\s+/g, '');\n }\n return result;\n }());\n }\n\n // addr-spec = local-part \"@\" domain\n function addrSpec() {\n return wrap('addr-spec', and(\n localPart, literal('@'), domain\n )());\n }\n\n // 3.6.2 Originator Fields\n // Below we only parse the field body, not the name of the field\n // like \"From:\", \"Sender:\", or \"Reply-To:\". Other libraries that\n // parse email headers can parse those and defer to these productions\n // for the \"RFC 5322\" part.\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // from = \"From:\" (mailbox-list / address-list) CRLF\n function fromSpec() {\n return wrap('from', or(\n mailboxList,\n addressList\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // sender = \"Sender:\" (mailbox / address) CRLF\n function senderSpec() {\n return wrap('sender', or(\n mailbox,\n address\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // reply-to = \"Reply-To:\" address-list CRLF\n function replyToSpec() {\n return wrap('reply-to', addressList());\n }\n\n // 4.1. Miscellaneous Obsolete Tokens\n\n // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control\n // %d11 / ; characters that do not\n // %d12 / ; include the carriage\n // %d14-31 / ; return, line feed, and\n // %d127 ; white space characters\n function obsNoWsCtl() {\n return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {\n var code = tok.charCodeAt(0);\n return ((1 <= code && code <= 8) ||\n (11 === code || 12 === code) ||\n (14 <= code && code <= 31) ||\n (127 === code));\n }));\n }\n\n // obs-ctext = obs-NO-WS-CTL\n function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }\n\n // obs-qtext = obs-NO-WS-CTL\n function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }\n\n // obs-qp = \"\\\" (%d0 / obs-NO-WS-CTL / LF / CR)\n function obsQP() {\n return opts.strict ? null : wrap('obs-qp', and(\n literal('\\\\'),\n or(literal('\\0'), obsNoWsCtl, lf, cr)\n )());\n }\n\n // obs-phrase = word *(word / \".\" / CFWS)\n function obsPhrase() {\n if (opts.strict ) return null;\n return opts.atInDisplayName ? wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), literal('@'), colwsp(cfws)))\n )()) :\n wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), colwsp(cfws)))\n )());\n }\n\n // 4.2. Obsolete Folding White Space\n\n // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908\n // obs-FWS = 1*([CRLF] WSP)\n function obsFws() {\n return opts.strict ? null : wrap('obs-FWS', star(\n and(invis(opt(crlf)), wsp),\n 1\n )());\n }\n\n // 4.4. Obsolete Addressing\n\n // obs-angle-addr = [CFWS] \"<\" obs-route addr-spec \">\" [CFWS]\n function obsAngleAddr() {\n return opts.strict ? null : wrap('obs-angle-addr', and(\n invis(opt(cfws)),\n literal('<'),\n obsRoute,\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n )());\n }\n\n // obs-route = obs-domain-list \":\"\n function obsRoute() {\n return opts.strict ? null : wrap('obs-route', and(\n obsDomainList,\n literal(':')\n )());\n }\n\n // obs-domain-list = *(CFWS / \",\") \"@\" domain\n // *(\",\" [CFWS] [\"@\" domain])\n function obsDomainList() {\n return opts.strict ? null : wrap('obs-domain-list', and(\n star(or(invis(cfws), literal(','))),\n literal('@'),\n domain,\n star(and(\n literal(','),\n invis(opt(cfws)),\n opt(and(literal('@'), domain))\n ))\n )());\n }\n\n // obs-mbox-list = *([CFWS] \",\") mailbox *(\",\" [mailbox / CFWS])\n function obsMboxList() {\n return opts.strict ? null : wrap('obs-mbox-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n mailbox,\n star(and(\n literal(','),\n opt(and(\n mailbox,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-addr-list = *([CFWS] \",\") address *(\",\" [address / CFWS])\n function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n address,\n star(and(\n literal(','),\n opt(and(\n address,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-group-list = 1*([CFWS] \",\") [CFWS]\n function obsGroupList() {\n return opts.strict ? null : wrap('obs-group-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n ), 1),\n invis(opt(cfws))\n )());\n }\n\n // obs-local-part = word *(\".\" word)\n function obsLocalPart() {\n return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());\n }\n\n // obs-domain = atom *(\".\" atom)\n function obsDomain() {\n return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());\n }\n\n // obs-dtext = obs-NO-WS-CTL / quoted-pair\n function obsDtext() {\n return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());\n }\n\n /////////////////////////////////////////////////////\n\n // ast analysis\n\n function findNode(name, root) {\n var i, stack, node;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n return node;\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return null;\n }\n\n function findAllNodes(name, root) {\n var i, stack, node, result;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n result.push(node);\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return result;\n }\n\n function findAllNodesNoChildren(names, root) {\n var i, stack, node, result, namesLookup;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n namesLookup = {};\n for (i = 0; i < names.length; i += 1) {\n namesLookup[names[i]] = true;\n }\n\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name in namesLookup) {\n result.push(node);\n // don't look at children (hence findAllNodesNoChildren)\n } else {\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n }\n return result;\n }\n\n function giveResult(ast) {\n var addresses, groupsAndMailboxes, i, groupOrMailbox, result;\n if (ast === null) {\n return null;\n }\n addresses = [];\n\n // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.\n groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);\n for (i = 0; i < groupsAndMailboxes.length; i += 1) {\n groupOrMailbox = groupsAndMailboxes[i];\n if (groupOrMailbox.name === 'group') {\n addresses.push(giveResultGroup(groupOrMailbox));\n } else if (groupOrMailbox.name === 'mailbox') {\n addresses.push(giveResultMailbox(groupOrMailbox));\n }\n }\n\n result = {\n ast: ast,\n addresses: addresses,\n };\n if (opts.simple) {\n result = simplifyResult(result);\n }\n if (opts.oneResult) {\n return oneResult(result);\n }\n if (opts.simple) {\n return result && result.addresses;\n } else {\n return result;\n }\n }\n\n function giveResultGroup(group) {\n var i;\n var groupName = findNode('display-name', group);\n var groupResultMailboxes = [];\n var mailboxes = findAllNodesNoChildren(['mailbox'], group);\n for (i = 0; i < mailboxes.length; i += 1) {\n groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));\n }\n return {\n node: group,\n parts: {\n name: groupName,\n },\n type: group.name, // 'group'\n name: grabSemantic(groupName),\n addresses: groupResultMailboxes,\n };\n }\n\n function giveResultMailbox(mailbox) {\n var name = findNode('display-name', mailbox);\n var aspec = findNode('addr-spec', mailbox);\n var cfws = findAllNodes('cfws', mailbox);\n var comments = findAllNodesNoChildren(['comment'], mailbox);\n\n\n var local = findNode('local-part', aspec);\n var domain = findNode('domain', aspec);\n return {\n node: mailbox,\n parts: {\n name: name,\n address: aspec,\n local: local,\n domain: domain,\n comments: cfws\n },\n type: mailbox.name, // 'mailbox'\n name: grabSemantic(name),\n address: grabSemantic(aspec),\n local: grabSemantic(local),\n domain: grabSemantic(domain),\n comments: concatComments(comments),\n groupName: grabSemantic(mailbox.groupName),\n };\n }\n\n function grabSemantic(n) {\n return n !== null && n !== undefined ? n.semantic : null;\n }\n\n function simplifyResult(result) {\n var i;\n if (result && result.addresses) {\n for (i = 0; i < result.addresses.length; i += 1) {\n delete result.addresses[i].node;\n }\n }\n return result;\n }\n\n function concatComments(comments) {\n var result = '';\n if (comments) {\n for (var i = 0; i < comments.length; i += 1) {\n result += grabSemantic(comments[i]);\n }\n }\n return result;\n }\n\n function oneResult(result) {\n if (!result) { return null; }\n if (!opts.partial && result.addresses.length > 1) { return null; }\n return result.addresses && result.addresses[0];\n }\n\n /////////////////////////////////////////////////////\n\n var parseString, pos, len, parsed, startProduction;\n\n opts = handleOpts(opts, {});\n if (opts === null) { return null; }\n\n parseString = opts.input;\n\n startProduction = {\n 'address': address,\n 'address-list': addressList,\n 'angle-addr': angleAddr,\n 'from': fromSpec,\n 'group': group,\n 'mailbox': mailbox,\n 'mailbox-list': mailboxList,\n 'reply-to': replyToSpec,\n 'sender': senderSpec,\n }[opts.startAt] || addressList;\n\n if (!opts.strict) {\n initialize();\n opts.strict = true;\n parsed = startProduction(parseString);\n if (opts.partial || !inStr()) {\n return giveResult(parsed);\n }\n opts.strict = false;\n }\n\n initialize();\n parsed = startProduction(parseString);\n if (!opts.partial && inStr()) { return null; }\n return giveResult(parsed);\n}\n\nfunction parseOneAddressSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseAddressListSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseFromSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'from',\n }));\n}\n\nfunction parseSenderSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'sender',\n }));\n}\n\nfunction parseReplyToSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'reply-to',\n }));\n}\n\nfunction handleOpts(opts, defs) {\n function isString(str) {\n return Object.prototype.toString.call(str) === '[object String]';\n }\n\n function isObject(o) {\n return o === Object(o);\n }\n\n function isNullUndef(o) {\n return o === null || o === undefined;\n }\n\n var defaults, o;\n\n if (isString(opts)) {\n opts = { input: opts };\n } else if (!isObject(opts)) {\n return null;\n }\n\n if (!isString(opts.input)) { return null; }\n if (!defs) { return null; }\n\n defaults = {\n oneResult: false,\n partial: false,\n rejectTLD: false,\n rfc6532: false,\n simple: false,\n startAt: 'address-list',\n strict: false,\n atInDisplayName: false\n };\n\n for (o in defaults) {\n if (isNullUndef(opts[o])) {\n opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];\n }\n }\n return opts;\n}\n\nparse5322.parseOneAddress = parseOneAddressSimple;\nparse5322.parseAddressList = parseAddressListSimple;\nparse5322.parseFrom = parseFromSimple;\nparse5322.parseSender = parseSenderSimple;\nparse5322.parseReplyTo = parseReplyToSimple;\n\nif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = parse5322;\n} else {\n global.emailAddresses = parse5322;\n}\n\n}(this));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport emailAddresses from 'email-addresses';\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n try {\n const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });\n this.comment = comments.replace(/^\\(|\\)$/g, '');\n this.name = name;\n this.email = email;\n } catch (e) {}\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n * @private\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm of a key\n * @param {Key} [key] - The key to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) {\n let hashAlgo = config.preferredHashAlgorithm;\n let prefAlgo = hashAlgo;\n if (key) {\n const primaryUser = await key.getPrimaryUser(date, userID, config);\n if (primaryUser.selfCertification.preferredHashAlgorithms) {\n [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;\n hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n }\n }\n switch (keyPacket.algorithm) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n prefAlgo = crypto.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);\n }\n return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n}\n\n/**\n * Returns the preferred symmetric/aead/compression algorithm for a set of keys\n * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred algorithm\n * @async\n */\nexport async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = { // these are all must-implement in rfc4880bis\n 'symmetric': enums.symmetric.aes128,\n 'aead': enums.aead.eax,\n 'compression': enums.compression.uncompressed\n }[type];\n const preferredSenderAlgo = {\n 'symmetric': config.preferredSymmetricAlgorithm,\n 'aead': config.preferredAEADAlgorithm,\n 'compression': config.preferredCompressionAlgorithm\n }[type];\n const prefPropertyName = {\n 'symmetric': 'preferredSymmetricAlgorithms',\n 'aead': 'preferredAEADAlgorithms',\n 'compression': 'preferredCompressionAlgorithms'\n }[type];\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n const recipientPrefs = primaryUser.selfCertification[prefPropertyName];\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {PrivateKey} privateKey - key to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config);\n signaturePacket.rawNotations = notations;\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n await revocationSignature.verify(\n key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\n/**\n * Returns whether aead is supported by all keys in the set\n * @param {Array} keys - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {\n let supported = true;\n // TODO replace when Promise.some or Promise.any are implemented\n await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n if (!primaryUser.selfCertification.features ||\n !(primaryUser.selfCertification.features[0] & enums.features.aead)) {\n supported = false;\n }\n }));\n return supported;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc':\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function isValidSigningKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.rsaEncrypt &&\n keyAlgo !== enums.publicKey.elgamal &&\n keyAlgo !== enums.publicKey.ecdh &&\n keyAlgo !== enums.publicKey.x25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);\n}\n\nexport function isValidEncryptionKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.dsa &&\n keyAlgo !== enums.publicKey.rsaSign &&\n keyAlgo !== enums.publicKey.ecdsa &&\n keyAlgo !== enums.publicKey.eddsaLegacy &&\n keyAlgo !== enums.publicKey.ed25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);\n}\n\nexport function isValidDecryptionKeyPacket(signature, config) {\n if (config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n * @private\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n // check for expiration time in direct signatures\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const { selfCertification } = await this.getPrimaryUser(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidDecryptionKeyPacket(bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {}\n }\n }\n\n // evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&\n helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {\n keys.push(this);\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n const keyPacket = await helper.generateSecretSubkey(options);\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {};\n dataToSign.userID = userIDPacket;\n dataToSign.key = secretKeyPacket;\n\n const signatureProperties = {};\n signatureProperties.signatureType = enums.signature.certGeneric;\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128,\n enums.symmetric.aes192\n ], config.preferredSymmetricAlgorithm);\n if (config.aeadProtect) {\n signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.zlib,\n enums.compression.zip,\n enums.compression.uncompressed\n ], config.preferredCompressionAlgorithm);\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.aead;\n }\n if (config.v5Keys) {\n signatureProperties.features[0] |= enums.features.v5Keys;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return createKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No secret key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport KeyID from './type/keyid';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);\n\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || !util.isString(algorithmName)) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.\n if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n // do not check key expiration to allow decryption of old messages\n const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {\n return;\n }\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);\n const algorithmName = enums.read(enums.symmetric, algo);\n const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?\n enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :\n undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(algo);\n return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n let symEncryptedPacket;\n if (aeadAlgorithmName) {\n symEncryptedPacket = new AEADEncryptedDataPacket();\n symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);\n } else {\n symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();\n }\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const algorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();\n pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();\n pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;\n pkESKeyPacket.sessionKey = sessionKey;\n pkESKeyPacket.sessionKeyAlgorithm = algorithm;\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n let i;\n let existingSigPacketlist;\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n if (signature) {\n existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n for (i = existingSigPacketlist.length - 1; i >= 0; i--) {\n const signaturePacket = existingSigPacketlist[i];\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n if (!signingKeys.length && i === 0) {\n onePassSig.flags = 1;\n }\n packetlist.push(onePassSig);\n }\n }\n\n await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];\n const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signatureType;\n onePassSig.hashAlgorithm = await getPreferredHashAlgo(primaryKey, signingKey.keyPacket, date, userIDs, config);\n onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;\n onePassSig.issuerKeyID = signingKey.getKeyID();\n if (i === signingKeys.length - 1) {\n onePassSig.flags = 1;\n }\n return onePassSig;\n })).then(onePassSignatureList => {\n onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));\n });\n\n packetlist.push(literalDataPacket);\n packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config)));\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.message, this.write(), null, null, null, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const userID = userIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);\n return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n let input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} privateKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n let hashes = this.signature.packets.map(function(packet) {\n return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();\n });\n hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });\n const body = {\n hash: hashes.join(),\n text: this.text,\n data: this.signature.packets.write()\n };\n return armor(enums.armor.signed, body, undefined, undefined, undefined, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n let oneHeader = null;\n let hashAlgos = [];\n headers.forEach(function(header) {\n oneHeader = header.match(/^Hash: (.+)$/); // get header value\n if (oneHeader) {\n oneHeader = oneHeader[1].replace(/\\s/g, ''); // remove whitespace\n oneHeader = oneHeader.split(',');\n oneHeader = oneHeader.map(function(hash) {\n hash = hash.toLowerCase();\n try {\n return enums.write(enums.hash, hash);\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hash);\n }\n });\n hashAlgos = hashAlgos.concat(oneHeader);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {\n throw new Error('If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed');\n } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:\n * curve25519 (default), p256, p384, p521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key generation');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key reformat');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n const streaming = message.fromStream;\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return convertStream(data, streaming, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type\n * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data, streaming, encoding = 'utf8') {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n if (streaming === 'node') {\n data = stream.webToNode(data);\n if (encoding !== 'binary') data.setEncoding(encoding);\n return data;\n }\n if (streaming === 'web' && streamType === 'ponyfill') {\n return stream.toNativeReadable(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","/**\n * web-streams-polyfill v3.0.3\n */\n/// \nconst SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})`;\n\n/// \nfunction noop() {\n return undefined;\n}\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n }\n else if (typeof window !== 'undefined') {\n return window;\n }\n else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\nconst globals = getGlobals();\n\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nconst rethrowAssertionErrorRejection = noop;\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\nfunction newPromise(executor) {\n return new originalPromise(executor);\n}\nfunction promiseResolvedWith(value) {\n return originalPromiseResolve(value);\n}\nfunction promiseRejectedWith(reason) {\n return originalPromiseReject(reason);\n}\nfunction PerformPromiseThen(promise, onFulfilled, onRejected) {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected);\n}\nfunction uponPromise(promise, onFulfilled, onRejected) {\n PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);\n}\nfunction uponFulfillment(promise, onFulfilled) {\n uponPromise(promise, onFulfilled);\n}\nfunction uponRejection(promise, onRejected) {\n uponPromise(promise, undefined, onRejected);\n}\nfunction transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\nfunction setPromiseIsHandledToTrue(promise) {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\nconst queueMicrotask = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn) => PerformPromiseThen(resolvedPromise, fn);\n})();\nfunction reflectCall(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\nfunction promiseCall(F, V, args) {\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n }\n catch (value) {\n return promiseRejectedWith(value);\n }\n}\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nclass SimpleQueue {\n constructor() {\n this._cursor = 0;\n this._size = 0;\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n get length() {\n return this._size;\n }\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback) {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n node = node._next;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n }\n else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n }\n else {\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n const stream = reader._ownerReadableStream;\n return ReadableStreamCancel(stream, reason);\n}\nfunction ReadableStreamReaderGenericRelease(reader) {\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n// Helper functions for the readers.\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\nfunction defaultReaderClosedPromiseResolve(reader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nconst AbortSteps = SymbolPolyfill('[[AbortSteps]]');\nconst ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');\nconst CancelSteps = SymbolPolyfill('[[CancelSteps]]');\nconst PullSteps = SymbolPolyfill('[[PullSteps]]');\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nfunction isDictionary(x) {\n return typeof x === 'object' || typeof x === 'function';\n}\nfunction assertDictionary(obj, context) {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-callback-functions\nfunction assertFunction(x, context) {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-object\nfunction isObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nfunction assertObject(x, context) {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\nfunction assertRequiredArgument(x, position, context) {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\nfunction assertRequiredField(x, field, context) {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nfunction convertUnrestrictedDouble(value) {\n return Number(value);\n}\nfunction censorNegativeZero(x) {\n return x === 0 ? 0 : x;\n}\nfunction integerPart(x) {\n return censorNegativeZero(MathTrunc(x));\n}\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nfunction convertUnsignedLongLongWithEnforceRange(value, context) {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n let x = Number(value);\n x = censorNegativeZero(x);\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n x = integerPart(x);\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n return x;\n}\n\nfunction assertReadableStream(x, context) {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadRequest(stream, readRequest) {\n stream._reader._readRequests.push(readRequest);\n}\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readRequest = reader._readRequests.shift();\n if (done) {\n readRequest._closeSteps();\n }\n else {\n readRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\nfunction ReadableStreamHasDefaultReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamDefaultReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultReaderRead(reader, readRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n }\n else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n }\n else {\n stream._readableStreamController[PullSteps](readRequest);\n }\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n\n/// \nlet AsyncIteratorPrototype;\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolPolyfill.asyncIterator]() {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });\n}\n\n/// \nclass ReadableStreamAsyncIteratorImpl {\n constructor(reader, preventCancel) {\n this._ongoingPromise = undefined;\n this._isFinished = false;\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n next() {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n return(value) {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n _nextSteps() {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n _returnSteps(value) {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\nconst ReadableStreamAsyncIteratorPrototype = {\n next() {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n return(value) {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n};\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamAsyncIterator(stream, preventCancel) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\nfunction IsReadableStreamAsyncIterator(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n return true;\n}\n// Helper functions for the ReadableStream.\nfunction streamAsyncIteratorBrandCheckException(name) {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nfunction IsFiniteNonNegativeNumber(v) {\n if (!IsNonNegativeNumber(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n return true;\n}\nfunction IsNonNegativeNumber(v) {\n if (typeof v !== 'number') {\n return false;\n }\n if (NumberIsNaN(v)) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n return true;\n}\n\nfunction DequeueValue(container) {\n const pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n return pair.value;\n}\nfunction EnqueueValueWithSize(container, value, size) {\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\nfunction PeekQueueValue(container) {\n const pair = container._queue.peek();\n return pair.value;\n}\nfunction ResetQueue(container) {\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n\nfunction CreateArrayFromList(elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n}\nfunction CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n// Not implemented correctly\nfunction TransferArrayBuffer(O) {\n return O;\n}\n// Not implemented correctly\nfunction IsDetachedBuffer(O) {\n return false;\n}\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nclass ReadableStreamBYOBRequest {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view() {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n return this._view;\n }\n respond(bytesWritten) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n if (IsDetachedBuffer(this._view.buffer)) ;\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n respondWithNewView(view) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n if (view.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (view.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableByteStreamController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n if (this._byobRequest === null && this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, this, view);\n this._byobRequest = byobRequest;\n }\n return this._byobRequest;\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n ReadableByteStreamControllerClose(this);\n }\n enqueue(chunk) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n ReadableByteStreamControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n if (this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n firstDescriptor.bytesFilled = 0;\n }\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableByteStream;\n if (this._queueTotalSize > 0) {\n const entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n ReadableByteStreamControllerHandleQueueDrain(this);\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view);\n return;\n }\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n }\n catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n const pullIntoDescriptor = {\n buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableByteStreamController.\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n return true;\n}\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableByteStreamControllerError(controller, e);\n });\n}\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n let done = false;\n if (stream._state === 'closed') {\n done = true;\n }\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n }\n else {\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n const queue = controller._queue;\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n }\n else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n return ready;\n}\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n }\n else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === null) {\n return;\n }\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = null;\n controller._byobRequest = null;\n}\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {\n const stream = controller._controlledReadableByteStream;\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n const ctor = view.constructor;\n const buffer = TransferArrayBuffer(view.buffer);\n const pullIntoDescriptor = {\n buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n ReadableByteStreamControllerHandleQueueDrain(controller);\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n controller._pendingPullIntos.push(pullIntoDescriptor);\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n }\n else {\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n const descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return false;\n }\n if (controller._closeRequested) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableByteStreamControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n}\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\nfunction ReadableByteStreamControllerClose(controller) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n return;\n }\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n throw e;\n }\n }\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n const transferredBuffer = TransferArrayBuffer(buffer);\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n else {\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n }\n else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n }\n else {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerError(controller, e) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return;\n }\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableByteStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (!IsFiniteNonNegativeNumber(bytesWritten)) {\n throw new RangeError('bytesWritten must be a finite');\n }\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n firstDescriptor.buffer = view.buffer;\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\nfunction SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {\n controller._controlledReadableByteStream = stream;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._byobRequest = null;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._closeRequested = false;\n controller._started = false;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n controller._pendingPullIntos = new SimpleQueue();\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableByteStreamControllerError(controller, r);\n });\n}\nfunction SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {\n const controller = Object.create(ReadableByteStreamController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel(reason);\n }\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);\n}\nfunction SetUpReadableStreamBYOBRequest(request, controller, view) {\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n// Helper functions for the ReadableStreamBYOBRequest.\nfunction byobRequestBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n// Helper functions for the ReadableByteStreamController.\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {\n stream._reader._readIntoRequests.push(readIntoRequest);\n}\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readIntoRequest = reader._readIntoRequests.shift();\n if (done) {\n readIntoRequest._closeSteps(chunk);\n }\n else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\nfunction ReadableStreamHasBYOBReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamBYOBReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readIntoRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n }\n else {\n ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);\n }\n}\n// Helper functions for the ReadableStreamBYOBReader.\nfunction byobReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n\nfunction ExtractHighWaterMark(strategy, defaultHWM) {\n const { highWaterMark } = strategy;\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n return highWaterMark;\n}\nfunction ExtractSizeAlgorithm(strategy) {\n const { size } = strategy;\n if (!size) {\n return () => 1;\n }\n return size;\n}\n\nfunction convertQueuingStrategy(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n const size = init === null || init === void 0 ? void 0 : init.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\nfunction convertQueuingStrategySize(fn, context) {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n\nfunction convertUnderlyingSink(original, context) {\n assertDictionary(original, context);\n const abort = original === null || original === void 0 ? void 0 : original.abort;\n const close = original === null || original === void 0 ? void 0 : original.close;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n const write = original === null || original === void 0 ? void 0 : original.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),\n type\n };\n}\nfunction convertUnderlyingSinkAbortCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSinkCloseCallback(fn, original, context) {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\nfunction convertUnderlyingSinkStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSinkWriteCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction assertWritableStream(x, context) {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n constructor(rawUnderlyingSink = {}, rawStrategy = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n }\n else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n InitializeWritableStream(this);\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('locked');\n }\n return IsWritableStreamLocked(this);\n }\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason = undefined) {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('abort'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n return WritableStreamAbort(this, reason);\n }\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('close'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamClose(this);\n }\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('getWriter');\n }\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n// Abstract operations for the WritableStream.\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n const controller = Object.create(WritableStreamDefaultController.prototype);\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeWritableStream(stream) {\n stream._state = 'writable';\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n stream._writer = undefined;\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined;\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsWritableStreamLocked(stream) {\n if (stream._writer === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamAbort(stream, reason) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest._promise = promise;\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n return promise;\n}\nfunction WritableStreamClose(stream) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n const promise = newPromise((resolve, reject) => {\n const closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._closeRequest = closeRequest;\n });\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n return promise;\n}\n// WritableStream API exposed for controllers.\nfunction WritableStreamAddWriteRequest(stream) {\n const promise = newPromise((resolve, reject) => {\n const writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._writeRequests.push(writeRequest);\n });\n return promise;\n}\nfunction WritableStreamDealWithRejection(stream, error) {\n const state = stream._state;\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n WritableStreamFinishErroring(stream);\n}\nfunction WritableStreamStartErroring(stream, reason) {\n const controller = stream._writableStreamController;\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\nfunction WritableStreamFinishErroring(stream) {\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(promise, () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, (reason) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\nfunction WritableStreamFinishInFlightWrite(stream) {\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n WritableStreamDealWithRejection(stream, error);\n}\nfunction WritableStreamFinishInFlightClose(stream) {\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n const state = stream._state;\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n stream._state = 'closed';\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n}\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n if (stream._closeRequest !== undefined) {\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n }\n else {\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n stream._backpressure = backpressure;\n}\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nclass WritableStreamDefaultWriter {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n this._ownerWritableStream = stream;\n stream._writer = this;\n const state = stream._state;\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n }\n else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n }\n else {\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n return this._readyPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamDefaultWriterClose(this);\n }\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return;\n }\n WritableStreamDefaultWriterRelease(this);\n }\n write(chunk = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n// Abstract operations for the WritableStreamDefaultWriter.\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n return true;\n}\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n const stream = writer._ownerWritableStream;\n return WritableStreamAbort(stream, reason);\n}\nfunction WritableStreamDefaultWriterClose(writer) {\n const stream = writer._ownerWritableStream;\n return WritableStreamClose(stream);\n}\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n return WritableStreamDefaultWriterClose(writer);\n}\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n }\n else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n }\n else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\nfunction WritableStreamDefaultWriterRelease(writer) {\n const stream = writer._ownerWritableStream;\n const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n const stream = writer._ownerWritableStream;\n const controller = stream._writableStreamController;\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n const promise = WritableStreamAddWriteRequest(stream);\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n return promise;\n}\nconst closeSentinel = {};\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nclass WritableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e = undefined) {\n if (!IsWritableStreamDefaultController(this)) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n WritableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [AbortSteps](reason) {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n error: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations implementing interface required by the WritableStream.\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(startPromise, () => {\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, r => {\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n });\n}\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let writeAlgorithm = () => promiseResolvedWith(undefined);\n let closeAlgorithm = () => promiseResolvedWith(undefined);\n let abortAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort(reason);\n }\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller) {\n controller._writeAlgorithm = undefined;\n controller._closeAlgorithm = undefined;\n controller._abortAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n try {\n return controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n// Abstract operations for the WritableStreamDefaultController.\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n const stream = controller._controlledWritableStream;\n if (!controller._started) {\n return;\n }\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n const state = stream._state;\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n if (controller._queue.length === 0) {\n return;\n }\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n }\n else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkCloseRequestInFlight(stream);\n DequeueValue(controller);\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(sinkClosePromise, () => {\n WritableStreamFinishInFlightClose(stream);\n }, reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(sinkWritePromise, () => {\n WritableStreamFinishInFlightWrite(stream);\n const state = stream._state;\n DequeueValue(controller);\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\nfunction WritableStreamDefaultControllerError(controller, error) {\n const stream = controller._controlledWritableStream;\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n// Helper functions for the WritableStream.\nfunction streamBrandCheckException$2(name) {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n// Helper functions for the WritableStreamDefaultWriter.\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterClosedPromiseResolve(writer) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\nfunction defaultWriterReadyPromiseReset(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n}\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterReadyPromiseResolve(writer) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction isAbortSignal(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof value.aborted === 'boolean';\n }\n catch (_a) {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/// \nconst NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;\n\n/// \nfunction isDOMExceptionConstructor(ctor) {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new ctor();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createDOMExceptionPolyfill() {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(message, name) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n };\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n// eslint-disable-next-line no-redeclare\nconst DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nfunction ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n source._disturbed = true;\n let shuttingDown = false;\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n return newPromise((resolve, reject) => {\n let abortAlgorithm;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException$1('Aborted', 'AbortError');\n const actions = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n signal.addEventListener('abort', abortAlgorithm);\n }\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done) {\n if (done) {\n resolveLoop();\n }\n else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n next(false);\n });\n }\n function pipeStep() {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(reader, {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n });\n });\n });\n }\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n }\n else {\n shutdown();\n }\n });\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n }\n else {\n shutdown(true, destClosed);\n }\n }\n setPromiseIsHandledToTrue(pipeLoop());\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);\n }\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n }\n else {\n uponRejection(promise, action);\n }\n }\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n }\n else {\n uponFulfillment(promise, action);\n }\n }\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n }\n else {\n doTheRest();\n }\n function doTheRest() {\n uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));\n }\n }\n function shutdown(isError, error) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n }\n else {\n finalize(isError, error);\n }\n }\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n }\n else {\n resolve(undefined);\n }\n }\n });\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('desiredSize');\n }\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('close');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n ReadableStreamDefaultControllerClose(this);\n }\n enqueue(chunk = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('enqueue');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('error');\n }\n ReadableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableStream;\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n }\n else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n readRequest._chunkSteps(chunk);\n }\n else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableStreamDefaultController.\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableStreamDefaultControllerError(controller, e);\n });\n}\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableStream;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\nfunction ReadableStreamDefaultControllerClose(controller) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n controller._closeRequested = true;\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n }\n else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\nfunction ReadableStreamDefaultControllerError(controller, e) {\n const stream = controller._controlledReadableStream;\n if (stream._state !== 'readable') {\n return;\n }\n ResetQueue(controller);\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\n// This is used in the implementation of TransformStream.\nfunction ReadableStreamDefaultControllerHasBackpressure(controller) {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {\n const state = controller._controlledReadableStream._state;\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n return false;\n}\nfunction SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledReadableStream = stream;\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableStreamDefaultControllerError(controller, r);\n });\n}\nfunction SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel(reason);\n }\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// Helper functions for the ReadableStreamDefaultController.\nfunction defaultControllerBrandCheckException$1(name) {\n return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let branch1;\n let branch2;\n let resolveCancelPromise;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n function pullAlgorithm() {\n if (reading) {\n return promiseResolvedWith(undefined);\n }\n reading = true;\n const readRequest = {\n _chunkSteps: value => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n reading = false;\n const value1 = value;\n const value2 = value;\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promiseResolvedWith(undefined);\n }\n function cancel1Algorithm(reason) {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function cancel2Algorithm(reason) {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function startAlgorithm() {\n // do nothing\n }\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n uponRejection(reader._closedPromise, (r) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n return [branch1, branch2];\n}\n\nfunction convertUnderlyingDefaultOrByteSource(source, context) {\n assertDictionary(source, context);\n const original = source;\n const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;\n const cancel = original === null || original === void 0 ? void 0 : original.cancel;\n const pull = original === null || original === void 0 ? void 0 : original.pull;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\nfunction convertUnderlyingSourceCancelCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSourcePullCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSourceStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertReadableStreamType(type, context) {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n\nfunction convertReaderOptions(options, context) {\n assertDictionary(options, context);\n const mode = options === null || options === void 0 ? void 0 : options.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\nfunction convertReadableStreamReaderMode(mode, context) {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nfunction convertIteratorOptions(options, context) {\n assertDictionary(options, context);\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n\nfunction convertPipeOptions(options, context) {\n assertDictionary(options, context);\n const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;\n const signal = options === null || options === void 0 ? void 0 : options.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\nfunction assertAbortSignal(signal, context) {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n\nfunction convertReadableWritablePair(pair, context) {\n assertDictionary(pair, context);\n const readable = pair === null || pair === void 0 ? void 0 : pair.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n const writable = pair === null || pair === void 0 ? void 0 : pair.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n return { readable, writable };\n}\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nclass ReadableStream {\n constructor(rawUnderlyingSource = {}, rawStrategy = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n }\n else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n InitializeReadableStream(this);\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);\n }\n else {\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);\n }\n }\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('locked');\n }\n return IsReadableStreamLocked(this);\n }\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason = undefined) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('cancel'));\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n return ReadableStreamCancel(this, reason);\n }\n getReader(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('getReader');\n }\n const options = convertReaderOptions(rawOptions, 'First parameter');\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n return AcquireReadableStreamBYOBReader(this);\n }\n pipeThrough(rawTransform, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n setPromiseIsHandledToTrue(promise);\n return transform.readable;\n }\n pipeTo(destination, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));\n }\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));\n }\n let options;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n }\n catch (e) {\n return promiseRejectedWith(e);\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n }\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('tee');\n }\n const branches = ReadableStreamTee(this);\n return CreateArrayFromList(branches);\n }\n values(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('values');\n }\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n}\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n// Abstract operations for the ReadableStream.\n// Throws if and only if startAlgorithm throws.\nfunction CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeReadableStream(stream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamLocked(stream) {\n if (stream._reader === undefined) {\n return false;\n }\n return true;\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n ReadableStreamClose(stream);\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\nfunction ReadableStreamClose(stream) {\n stream._state = 'closed';\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseResolve(reader);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\nfunction ReadableStreamError(stream, e) {\n stream._state = 'errored';\n stream._storedError = e;\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseReject(reader, e);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n reader._readRequests = new SimpleQueue();\n }\n else {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n// Helper functions for the ReadableStream.\nfunction streamBrandCheckException$1(name) {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n\nfunction convertQueuingStrategyInit(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n\nconst byteLengthSizeFunction = function size(chunk) {\n return chunk.byteLength;\n};\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nclass ByteLengthQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the ByteLengthQueuingStrategy.\nfunction byteLengthBrandCheckException(name) {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\nfunction IsByteLengthQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nconst countSizeFunction = function size() {\n return 1;\n};\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nclass CountQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the CountQueuingStrategy.\nfunction countBrandCheckException(name) {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\nfunction IsCountQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nfunction convertTransformer(original, context) {\n assertDictionary(original, context);\n const flush = original === null || original === void 0 ? void 0 : original.flush;\n const readableType = original === null || original === void 0 ? void 0 : original.readableType;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const transform = original === null || original === void 0 ? void 0 : original.transform;\n const writableType = original === null || original === void 0 ? void 0 : original.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),\n writableType\n };\n}\nfunction convertTransformerFlushCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertTransformerStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertTransformerTransformCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\n// Class TransformStream\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nclass TransformStream {\n constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n let startPromise_resolve;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n }\n else {\n startPromise_resolve(undefined);\n }\n }\n /**\n * The readable side of the transform stream.\n */\n get readable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n return this._readable;\n }\n /**\n * The writable side of the transform stream.\n */\n get writable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n return this._writable;\n }\n}\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\nfunction InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {\n function startAlgorithm() {\n return startPromise;\n }\n function writeAlgorithm(chunk) {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n function abortAlgorithm(reason) {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n function closeAlgorithm() {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);\n function pullAlgorithm() {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n function cancelAlgorithm(reason) {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined;\n stream._backpressureChangePromise = undefined;\n stream._backpressureChangePromise_resolve = undefined;\n TransformStreamSetBackpressure(stream, true);\n stream._transformStreamController = undefined;\n}\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n return true;\n}\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream, e) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\nfunction TransformStreamErrorWritableAndUnblockWrite(stream, e) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\nfunction TransformStreamSetBackpressure(stream, backpressure) {\n // Passes also when called during construction.\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n stream._backpressure = backpressure;\n}\n// Class TransformStreamDefaultController\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nclass TransformStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n enqueue(chunk = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n TransformStreamDefaultControllerError(this, reason);\n }\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n TransformStreamDefaultControllerTerminate(this);\n }\n}\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n// Transform Stream Default Controller Abstract Operations\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {\n const controller = Object.create(TransformStreamDefaultController.prototype);\n let transformAlgorithm = (chunk) => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk);\n return promiseResolvedWith(undefined);\n }\n catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n let flushAlgorithm = () => promiseResolvedWith(undefined);\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush(controller);\n }\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\nfunction TransformStreamDefaultControllerClearAlgorithms(controller) {\n controller._transformAlgorithm = undefined;\n controller._flushAlgorithm = undefined;\n}\nfunction TransformStreamDefaultControllerEnqueue(controller, chunk) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n }\n catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n throw stream._readable._storedError;\n }\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n TransformStreamSetBackpressure(stream, true);\n }\n}\nfunction TransformStreamDefaultControllerError(controller, e) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\nfunction TransformStreamDefaultControllerPerformTransform(controller, chunk) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\nfunction TransformStreamDefaultControllerTerminate(controller) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n ReadableStreamDefaultControllerClose(readableController);\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n// TransformStreamDefaultSink Algorithms\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {\n const controller = stream._transformStreamController;\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream) {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n// TransformStreamDefaultSource Algorithms\nfunction TransformStreamDefaultSourcePullAlgorithm(stream) {\n // Invariant. Enforced by the promises returned by start() and pull().\n TransformStreamSetBackpressure(stream, false);\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n// Helper functions for the TransformStreamDefaultController.\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n// Helper functions for the TransformStream.\nfunction streamBrandCheckException(name) {\n return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n\nexport { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };\n//# sourceMappingURL=ponyfill.es6.mjs.map\n","/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nfunction assert(test) {\n if (!test) {\n throw new TypeError('Assertion failed');\n }\n}\n\nfunction noop() {\n return;\n}\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nfunction isStreamConstructor(ctor) {\n if (typeof ctor !== 'function') {\n return false;\n }\n var startCalled = false;\n try {\n new ctor({\n start: function () {\n startCalled = true;\n }\n });\n }\n catch (e) {\n // ignore\n }\n return startCalled;\n}\nfunction isReadableStream(readable) {\n if (!typeIsObject(readable)) {\n return false;\n }\n if (typeof readable.getReader !== 'function') {\n return false;\n }\n return true;\n}\nfunction isReadableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isReadableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isWritableStream(writable) {\n if (!typeIsObject(writable)) {\n return false;\n }\n if (typeof writable.getWriter !== 'function') {\n return false;\n }\n return true;\n}\nfunction isWritableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isWritableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isTransformStream(transform) {\n if (!typeIsObject(transform)) {\n return false;\n }\n if (!isReadableStream(transform.readable)) {\n return false;\n }\n if (!isWritableStream(transform.writable)) {\n return false;\n }\n return true;\n}\nfunction isTransformStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isTransformStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction supportsByobReader(readable) {\n try {\n var reader = readable.getReader({ mode: 'byob' });\n reader.releaseLock();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction supportsByteSource(ctor) {\n try {\n new ctor({ type: 'bytes' });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\nfunction createReadableStreamWrapper(ctor) {\n assert(isReadableStreamConstructor(ctor));\n var byteSourceSupported = supportsByteSource(ctor);\n return function (readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n type = parseReadableType(type);\n if (type === 'bytes' && !byteSourceSupported) {\n type = undefined;\n }\n if (readable.constructor === ctor) {\n if (type !== 'bytes' || supportsByobReader(readable)) {\n return readable;\n }\n }\n if (type === 'bytes') {\n var source = createWrappingReadableSource(readable, { type: type });\n return new ctor(source);\n }\n else {\n var source = createWrappingReadableSource(readable);\n return new ctor(source);\n }\n };\n}\nfunction createWrappingReadableSource(readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n assert(isReadableStream(readable));\n assert(readable.locked === false);\n type = parseReadableType(type);\n var source;\n if (type === 'bytes') {\n source = new WrappingReadableByteStreamSource(readable);\n }\n else {\n source = new WrappingReadableStreamDefaultSource(readable);\n }\n return source;\n}\nfunction parseReadableType(type) {\n var typeString = String(type);\n if (typeString === 'bytes') {\n return typeString;\n }\n else if (type === undefined) {\n return type;\n }\n else {\n throw new RangeError('Invalid type is specified');\n }\n}\nvar AbstractWrappingReadableStreamSource = /** @class */ (function () {\n function AbstractWrappingReadableStreamSource(underlyingStream) {\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n this._readableStreamController = undefined;\n this._pendingRead = undefined;\n this._underlyingStream = underlyingStream;\n // always keep a reader attached to detect close/error\n this._attachDefaultReader();\n }\n AbstractWrappingReadableStreamSource.prototype.start = function (controller) {\n this._readableStreamController = controller;\n };\n AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {\n assert(this._underlyingReader !== undefined);\n return this._underlyingReader.cancel(reason);\n };\n AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {\n if (this._readerMode === \"default\" /* DEFAULT */) {\n return;\n }\n this._detachReader();\n var reader = this._underlyingStream.getReader();\n this._readerMode = \"default\" /* DEFAULT */;\n this._attachReader(reader);\n };\n AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {\n var _this = this;\n assert(this._underlyingReader === undefined);\n this._underlyingReader = reader;\n var closed = this._underlyingReader.closed;\n if (!closed) {\n return;\n }\n closed\n .then(function () { return _this._finishPendingRead(); })\n .then(function () {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.close();\n }\n }, function (reason) {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.error(reason);\n }\n })\n .catch(noop);\n };\n AbstractWrappingReadableStreamSource.prototype._detachReader = function () {\n if (this._underlyingReader === undefined) {\n return;\n }\n this._underlyingReader.releaseLock();\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n };\n AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {\n var _this = this;\n this._attachDefaultReader();\n // TODO Backpressure?\n var read = this._underlyingReader.read()\n .then(function (result) {\n var controller = _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n }\n else {\n controller.enqueue(result.value);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n AbstractWrappingReadableStreamSource.prototype._tryClose = function () {\n try {\n this._readableStreamController.close();\n }\n catch (_a) {\n // already errored or closed\n }\n };\n AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {\n var _this = this;\n var pendingRead;\n var finishRead = function () {\n if (_this._pendingRead === pendingRead) {\n _this._pendingRead = undefined;\n }\n };\n this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);\n };\n AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {\n var _this = this;\n if (!this._pendingRead) {\n return undefined;\n }\n var afterRead = function () { return _this._finishPendingRead(); };\n return this._pendingRead.then(afterRead, afterRead);\n };\n return AbstractWrappingReadableStreamSource;\n}());\nvar WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {\n __extends(WrappingReadableStreamDefaultSource, _super);\n function WrappingReadableStreamDefaultSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WrappingReadableStreamDefaultSource.prototype.pull = function () {\n return this._pullWithDefaultReader();\n };\n return WrappingReadableStreamDefaultSource;\n}(AbstractWrappingReadableStreamSource));\nfunction toUint8Array(view) {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\nfunction copyArrayBufferView(from, to) {\n var fromArray = toUint8Array(from);\n var toArray = toUint8Array(to);\n toArray.set(fromArray, 0);\n}\nvar WrappingReadableByteStreamSource = /** @class */ (function (_super) {\n __extends(WrappingReadableByteStreamSource, _super);\n function WrappingReadableByteStreamSource(underlyingStream) {\n var _this = this;\n var supportsByob = supportsByobReader(underlyingStream);\n _this = _super.call(this, underlyingStream) || this;\n _this._supportsByob = supportsByob;\n return _this;\n }\n Object.defineProperty(WrappingReadableByteStreamSource.prototype, \"type\", {\n get: function () {\n return 'bytes';\n },\n enumerable: false,\n configurable: true\n });\n WrappingReadableByteStreamSource.prototype._attachByobReader = function () {\n if (this._readerMode === \"byob\" /* BYOB */) {\n return;\n }\n assert(this._supportsByob);\n this._detachReader();\n var reader = this._underlyingStream.getReader({ mode: 'byob' });\n this._readerMode = \"byob\" /* BYOB */;\n this._attachReader(reader);\n };\n WrappingReadableByteStreamSource.prototype.pull = function () {\n if (this._supportsByob) {\n var byobRequest = this._readableStreamController.byobRequest;\n if (byobRequest) {\n return this._pullWithByobRequest(byobRequest);\n }\n }\n return this._pullWithDefaultReader();\n };\n WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {\n var _this = this;\n this._attachByobReader();\n // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly\n // create a separate buffer to read into, then copy that to byobRequest.view\n var buffer = new Uint8Array(byobRequest.view.byteLength);\n // TODO Backpressure?\n var read = this._underlyingReader.read(buffer)\n .then(function (result) {\n _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n byobRequest.respond(0);\n }\n else {\n copyArrayBufferView(result.value, byobRequest.view);\n byobRequest.respond(result.value.byteLength);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n return WrappingReadableByteStreamSource;\n}(AbstractWrappingReadableStreamSource));\n\nfunction createWritableStreamWrapper(ctor) {\n assert(isWritableStreamConstructor(ctor));\n return function (writable) {\n if (writable.constructor === ctor) {\n return writable;\n }\n var sink = createWrappingWritableSink(writable);\n return new ctor(sink);\n };\n}\nfunction createWrappingWritableSink(writable) {\n assert(isWritableStream(writable));\n assert(writable.locked === false);\n var writer = writable.getWriter();\n return new WrappingWritableStreamSink(writer);\n}\nvar WrappingWritableStreamSink = /** @class */ (function () {\n function WrappingWritableStreamSink(underlyingWriter) {\n var _this = this;\n this._writableStreamController = undefined;\n this._pendingWrite = undefined;\n this._state = \"writable\" /* WRITABLE */;\n this._storedError = undefined;\n this._underlyingWriter = underlyingWriter;\n this._errorPromise = new Promise(function (resolve, reject) {\n _this._errorPromiseReject = reject;\n });\n this._errorPromise.catch(noop);\n }\n WrappingWritableStreamSink.prototype.start = function (controller) {\n var _this = this;\n this._writableStreamController = controller;\n this._underlyingWriter.closed\n .then(function () {\n _this._state = \"closed\" /* CLOSED */;\n })\n .catch(function (reason) { return _this._finishErroring(reason); });\n };\n WrappingWritableStreamSink.prototype.write = function (chunk) {\n var _this = this;\n var writer = this._underlyingWriter;\n // Detect past errors\n if (writer.desiredSize === null) {\n return writer.ready;\n }\n var writeRequest = writer.write(chunk);\n // Detect future errors\n writeRequest.catch(function (reason) { return _this._finishErroring(reason); });\n writer.ready.catch(function (reason) { return _this._startErroring(reason); });\n // Reject write when errored\n var write = Promise.race([writeRequest, this._errorPromise]);\n this._setPendingWrite(write);\n return write;\n };\n WrappingWritableStreamSink.prototype.close = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return this._underlyingWriter.close();\n }\n return this._finishPendingWrite().then(function () { return _this.close(); });\n };\n WrappingWritableStreamSink.prototype.abort = function (reason) {\n if (this._state === \"errored\" /* ERRORED */) {\n return undefined;\n }\n var writer = this._underlyingWriter;\n return writer.abort(reason);\n };\n WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {\n var _this = this;\n var pendingWrite;\n var finishWrite = function () {\n if (_this._pendingWrite === pendingWrite) {\n _this._pendingWrite = undefined;\n }\n };\n this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);\n };\n WrappingWritableStreamSink.prototype._finishPendingWrite = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return Promise.resolve();\n }\n var afterWrite = function () { return _this._finishPendingWrite(); };\n return this._pendingWrite.then(afterWrite, afterWrite);\n };\n WrappingWritableStreamSink.prototype._startErroring = function (reason) {\n var _this = this;\n if (this._state === \"writable\" /* WRITABLE */) {\n this._state = \"erroring\" /* ERRORING */;\n this._storedError = reason;\n var afterWrite = function () { return _this._finishErroring(reason); };\n if (this._pendingWrite === undefined) {\n afterWrite();\n }\n else {\n this._finishPendingWrite().then(afterWrite, afterWrite);\n }\n this._writableStreamController.error(reason);\n }\n };\n WrappingWritableStreamSink.prototype._finishErroring = function (reason) {\n if (this._state === \"writable\" /* WRITABLE */) {\n this._startErroring(reason);\n }\n if (this._state === \"erroring\" /* ERRORING */) {\n this._state = \"errored\" /* ERRORED */;\n this._errorPromiseReject(this._storedError);\n }\n };\n return WrappingWritableStreamSink;\n}());\n\nfunction createTransformStreamWrapper(ctor) {\n assert(isTransformStreamConstructor(ctor));\n return function (transform) {\n if (transform.constructor === ctor) {\n return transform;\n }\n var transformer = createWrappingTransformer(transform);\n return new ctor(transformer);\n };\n}\nfunction createWrappingTransformer(transform) {\n assert(isTransformStream(transform));\n var readable = transform.readable, writable = transform.writable;\n assert(readable.locked === false);\n assert(writable.locked === false);\n var reader = readable.getReader();\n var writer;\n try {\n writer = writable.getWriter();\n }\n catch (e) {\n reader.releaseLock(); // do not leak reader\n throw e;\n }\n return new WrappingTransformStreamTransformer(reader, writer);\n}\nvar WrappingTransformStreamTransformer = /** @class */ (function () {\n function WrappingTransformStreamTransformer(reader, writer) {\n var _this = this;\n this._transformStreamController = undefined;\n this._onRead = function (result) {\n if (result.done) {\n return;\n }\n _this._transformStreamController.enqueue(result.value);\n return _this._reader.read().then(_this._onRead);\n };\n this._onError = function (reason) {\n _this._flushReject(reason);\n _this._transformStreamController.error(reason);\n _this._reader.cancel(reason).catch(noop);\n _this._writer.abort(reason).catch(noop);\n };\n this._onTerminate = function () {\n _this._flushResolve();\n _this._transformStreamController.terminate();\n var error = new TypeError('TransformStream terminated');\n _this._writer.abort(error).catch(noop);\n };\n this._reader = reader;\n this._writer = writer;\n this._flushPromise = new Promise(function (resolve, reject) {\n _this._flushResolve = resolve;\n _this._flushReject = reject;\n });\n }\n WrappingTransformStreamTransformer.prototype.start = function (controller) {\n this._transformStreamController = controller;\n this._reader.read()\n .then(this._onRead)\n .then(this._onTerminate, this._onError);\n var readerClosed = this._reader.closed;\n if (readerClosed) {\n readerClosed\n .then(this._onTerminate, this._onError);\n }\n };\n WrappingTransformStreamTransformer.prototype.transform = function (chunk) {\n return this._writer.write(chunk);\n };\n WrappingTransformStreamTransformer.prototype.flush = function () {\n var _this = this;\n return this._writer.close()\n .then(function () { return _this._flushPromise; });\n };\n return WrappingTransformStreamTransformer;\n}());\n\nexport { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper };\n//# sourceMappingURL=web-streams-adapter.mjs.map\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n r.strip();\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)\n * @module biginteger/bn\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n this.value = new BN(n);\n }\n\n clone() {\n const clone = new BigInteger(null);\n this.value.copy(clone.value);\n return clone;\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value.iadd(new BN(1));\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value.isub(new BN(1));\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value.iadd(x.value);\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value.isub(x.value);\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value.imul(x.value);\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value = this.value.umod(m.value);\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation\n * Much faster than this.exp(e).mod(n)\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n // We use either Montgomery or normal reduction context\n // Montgomery requires coprime n and R (montogmery multiplier)\n // bn.js picks R as power of 2, so n must be odd\n const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);\n const x = this.clone();\n x.value = x.value.toRed(nred).redPow(e.value).fromRed();\n return x;\n }\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n // invm returns a wrong result if the inverse does not exist\n if (!this.gcd(n).isOne()) {\n throw new Error('Inverse does not exist');\n }\n return new BigInteger(this.value.invm(n.value));\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} n - Operand\n * @returns {BigInteger} gcd\n */\n gcd(n) {\n return new BigInteger(this.value.gcd(n.value));\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value.ishln(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value.ishrn(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value.eq(x.value);\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value.lt(x.value);\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value.lte(x.value);\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value.gt(x.value);\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value.gte(x.value);\n }\n\n isZero() {\n return this.value.isZero();\n }\n\n isOne() {\n return this.value.eq(new BN(1));\n }\n\n isNegative() {\n return this.value.isNeg();\n }\n\n isEven() {\n return this.value.isEven();\n }\n\n abs() {\n const res = this.clone();\n res.value = res.value.abs();\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n return this.value.toNumber();\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n return this.value.testn(i) ? 1 : 0;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n return this.value.bitLength();\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n return this.value.byteLength();\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n return this.value.toArrayLike(Uint8Array, endian, length);\n }\n}\n","var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n","'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w) {\n var naf = [];\n var ws = 1 << (w + 1);\n var k = num.clone();\n while (k.cmpn(1) >= 0) {\n var z;\n if (k.isOdd()) {\n var mod = k.andln(ws - 1);\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n naf.push(z);\n\n // Optimization, shift by word if possible\n var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;\n for (var i = 1; i < shift; i++)\n naf.push(0);\n k.iushrn(shift);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n []\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n var m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n var m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n for (var j = 0; j < naf.length; j += doubles.step) {\n var nafW = 0;\n for (var k = j + doubles.step - 1; k >= j; k--)\n nafW = (nafW << 1) + naf[k];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (var j = 0; j < repr.length; j++) {\n var nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var k = 0; i >= 0 && naf[i] === 0; i--)\n k++;\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n for (var i = 0; i < len; i++) {\n var p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (var i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a]);\n naf[b] = getNAF(coeffs[b], wndWidth[b]);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b] /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3 /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (var j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (var i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (var j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (var j = 0; j < len; j++) {\n var z = tmp[j];\n var p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (var i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16)\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n};\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point))\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point))\n }\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate)\n }\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (var i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (var i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n // Note: this implementation is according to the original paper\n // by P. Montgomery, NOT the one by D. J. Bernstein.\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n var bytes = utils.toArray(bytes, enc);\n\n // TODO Curve448\n // Montgomery curve points must be represented in the compressed format\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (bytes.length === 33 && bytes[0] === 0x40)\n bytes = bytes.slice(1, 33).reverse(); // point must be little-endian\n if (bytes.length !== 32)\n throw new Error('Unknown point compression format');\n return this.point(bytes, 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n\n // Note: the output should always be little-endian\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (compact) {\n return [ 0x40 ].concat(this.getX().toArray('le', len));\n } else {\n return this.getX().toArray('be', len);\n }\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n if (this.curve.twisted) {\n // E = a * C\n var e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n var h = this.z.redSqr();\n // J = F - 2 * H\n var j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n var e = c.redAdd(d);\n // H = (c * Z1)^2\n var h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n var j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else if (options.type === 'mont')\n this.curve = new curve.mont(options);\n else throw new Error('Unknown curve type.');\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve\n });\n return curve;\n }\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'\n ]\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'\n ]\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'\n ]\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'\n ]\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650'\n ]\n});\n\n// https://tools.ietf.org/html/rfc7748#section-4.1\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9'\n ]\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.4\ndefineCurve('brainpoolP256r1', {\n type: 'short',\n prime: null,\n p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',\n a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',\n b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',\n n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',\n hash: hash.sha256, // or 384, or 512\n gRed: false,\n g: [\n '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',\n '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.6\ndefineCurve('brainpoolP384r1', {\n type: 'short',\n prime: null,\n p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +\n 'ACD3A729 901D1A71 87470013 3107EC53',\n a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +\n '8AA5814A 503AD4EB 04A8C7DD 22CE2826',\n b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +\n '7CB43902 95DBC994 3AB78696 FA504C11',\n n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +\n 'CF3AB6AF 6B7FC310 3B883202 E9046565',\n hash: hash.sha384, // or 512\n gRed: false,\n g: [\n '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +\n 'E8E826E03436D646AAEF87B2E247D4AF1E',\n '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +\n '280E4646217791811142820341263C5315'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.7\ndefineCurve('brainpoolP512r1', {\n type: 'short',\n prime: null,\n p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +\n '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',\n a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +\n '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',\n b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +\n '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',\n n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +\n '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',\n hash: hash.sha512,\n gRed: false,\n g: [\n '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +\n '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',\n '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +\n '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'\n ]\n});\n\n// https://en.bitcoin.it/wiki/Secp256k1\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre\n ]\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc\n });\n};\n\n// TODO: should not validate for X25519\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // For Curve25519/Curve448 we have a specific procedure.\n // TODO Curve448\n if (this.ec.curve.type === 'mont') {\n var one = this.ec.curve.one;\n var mask = one.ushln(255 - 3).sub(one).ushln(3);\n this.priv = this.priv.or(one.ushln(255 - 1));\n this.priv = this.priv.and(mask);\n } else\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n }\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0 && (r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] === 0 && (s[1] & 0x80)) {\n s = s.slice(1);\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray()\n });\n\n // Key generation for curve25519 is simpler\n if (this.curve.type === 'mont') {\n var priv = new BN(drbg.generate(32));\n return this.keyFromPrivate(priv);\n }\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n do {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n } while (true);\n};\n\nEC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {\n bitSize = bitSize || msg.byteLength() * 8;\n var delta = bitSize - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.truncateMsg = function truncateMSG(msg) {\n // Bit size is only determined correctly for Uint8Arrays and hex strings\n var bitSize;\n if (msg instanceof Uint8Array) {\n bitSize = msg.byteLength * 8;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else if (typeof msg === 'string') {\n bitSize = msg.length * 4;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else {\n msg = this._truncateToN(new BN(msg, 16));\n }\n return msg;\n}\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this.truncateMsg(msg);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8'\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; true; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n // Fallback to the old code\n var ret = this._verify(this.truncateMsg(msg), signature, key) ||\n this._verify(this._truncateToN(new BN(msg, 16)), signature, key);\n return ret;\n};\n\nEC.prototype._verify = function _verify(msg, signature, key) {\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n\n if (!this.curve._maxwellTrick) {\n var p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n var p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n if (params.hasOwnProperty('secret'))\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else {\n this._pubBytes = parseBytes(params.pub);\n if (this._pubBytes && this._pubBytes.length === 33 &&\n this._pubBytes[0] === 0x40)\n this._pubBytes = this._pubBytes.slice(1, 33);\n if (this._pubBytes && this._pubBytes.length !== 32)\n throw new Error('Unknown point compression format');\n }\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n // https://tools.ietf.org/html/rfc8032#section-5.1.5\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength)\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar HmacDRBG = require('hmac-drbg');\nvar rand = require('brorand');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n var curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.curve.n.toArray()\n });\n\n return this.keyFromSecret(drbg.generate(32));\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","this","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","prototype","undefined","read","async","length","value","done","readToEnd","join","result","slice","clone","then","push","write","chunk","close","abort","reason","isNode","globalThis","process","versions","NodeReadableStream","require$$0","Readable","isStream","ReadableStream","isPrototypeOf","streams.ReadableStream","isUint8Array","Uint8Array","concatUint8Array","arrays","totalLength","i","Error","pos","forEach","element","set","NodeBuffer","Buffer","require$$1","nodeToWeb","webToNode","nodeStream","canceled","start","controller","pause","on","isBuffer","buffer","byteOffset","byteLength","enqueue","e","error","pull","resume","cancel","destroy","NodeReadable","webStream","options","_reader","streams.getReader","size","callback","doneReadingSet","WeakSet","externalBuffer","Reader","streams.isArrayStream","reader","_read","bind","_releaseLock","_cancel","streamType","streams.isStream","streams.nodeToWeb","doneReading","has","add","shift","readLine","returnVal","streams.concat","lineEndIndex","indexOf","concat","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","filter","toPonyfillReadable","toNativeReadable","WritableStream","TransformStream","loadStreamsPonyfill","ponyfill","adapter","all","createReadableStreamWrapper","toStream","toArrayStream","list","some","map","transform","transformWithCancel","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","transformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","highWaterMark","finish","output","data","result1","result2","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","Object","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","arrayStream","BigInteger","n","hex","hexByte","toString","BigInt","iinc","inc","idec","dec","iadd","x","isub","sub","imul","mul","imod","m","isNegative","mod","modExp","isZero","isOne","exp","r","lsb","rx","modInv","gcd","_egcd","b","y","xPrev","yPrev","a","q","tmp","ileftShift","leftShift","irightShift","rightShift","equal","lt","lte","gt","gte","isEven","abs","res","toNumber","number","Number","MAX_SAFE_INTEGER","getBit","bitLength","zero","one","negOne","bitlen","eight","len","toUint8Array","endian","rawLength","offset","parseInt","reverse","detectBigInt","byValue","curve","p256","secp256r1","prime256v1","p384","secp384r1","p521","secp521r1","secp256k1","ed25519Legacy","ED25519","ed25519","Ed25519","curve25519Legacy","X25519","cv25519","curve25519","Curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","eddsa","aedh","aedsa","x25519","x448","ed448","symmetric","plaintext","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","webHash","aead","eax","ocb","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuer","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","type","debugMode","env","NODE_ENV","util","isString","String","stream.isUint8Array","stream.isStream","readNumber","writeNumber","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","leftPad","padded","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","k","uint8ArrayToHex","h","c","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","s","printDebug","log","printDebugError","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","crypto","subtle","getBigInteger","default","getNodeCrypto","getNodeZlib","getNodeBuffer","require$$2","getHardwareConcurrency","navigator","hardwareConcurrency","require$$3","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","selectUint8","isAES","cipherAlgo","enums","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","from","btoa","atob","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","deflateLevel","aeadProtect","preferredAEADAlgorithm","aeadChunkSizeByte","s2kIterationCountByte","allowUnauthenticatedMessages","allowUnauthenticatedStream","checksumRequired","minRSABits","passwordCollisionCheck","revocationsExpire","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","minBytesForWebCrypto","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","useIndutnyElliptic","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","getType","header","match","addheader","customComment","config","getCheckSum","base64.encode","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","splitChecksum","body","checksum","lastEquals","lastIndexOf","unarmor","defaultConfig","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","checksumVerified","stream.readToEnd","stream.passiveClone","stream.pipe","checksumVerifiedString","stream.isArrayStream","messageType","partIndex","partTotal","bodyClone","KeyID","toHex","equals","keyID","matchWildcard","isWildcard","isNull","static","AES_asm","gexp3","glog3","ginit_done","gmul","aes_sbox","aes_sinv","aes_enc","aes_dec","aes_init_done","aes_init","_s","ginv","d","ginit","wrapper","foreign","heap","asm","stdlib","S0","S1","S2","S3","I0","I1","I2","I3","N0","N1","N2","N3","M0","M1","M2","M3","H0","H1","H2","H3","R","HEAP","DATA","_core","x0","x1","x2","x3","t1","t2","t3","y0","y1","y2","y3","_ecb_enc","_ecb_dec","_cbc_enc","_cbc_dec","_cfb_enc","_cfb_dec","_ofb","_ctr","_gcm_mac","z0","z1","z2","z3","set_rounds","set_state","s0","s1","s2","s3","set_iv","i0","i1","i2","i3","set_nonce","n0","n1","n2","n3","set_mask","m0","m1","m2","m3","set_counter","c0","c1","c2","c3","get_state","get_iv","gcm_init","cipher","mode","ret","_cipher_modes","mac","_mac_modes","set_key","ks","k0","k1","k2","k3","k4","k5","k6","k7","ekeys","dkeys","rcon","jj","ENC","ECB","CBC","CFB","OFB","CTR","DEC","MAC","GCM","HEAP_DATA","is_bytes","_heap_init","heapSize","_heap_write","hpos","dpos","dlen","hlen","wlen","joinBytes","arg","totalLenght","reduce","sum","curr","cursor","IllegalStateError","args","IllegalArgumentError","SecurityError","heap_pool","asm_pool","AES","iv","padding","acquire_asm","pop","reset","release_asm","keylen","keyview","getUint32","ivview","AES_Encrypt_process","TypeError","amode","rpos","AES_Encrypt_finish","plen","rlen","hasOwnProperty","p","AES_Decrypt_process","AES_Decrypt_finish","pad","pcheck","AES_ECB","encrypt","decrypt","aes","C","aesECB","block","blockSize","keySize","des","keys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","left","right","looping","cbcleft","cbcleft2","cbcright","cbcright2","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","src","dst","l","f1","f2","f3","scheduleA","scheduleB","I","sBox","inn","w","ki","half","round","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","u","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","vector","off","_decryptBlock","kk","sha1_asm","H4","TOTAL0","TOTAL1","I4","O0","O1","O2","O3","O4","w0","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32","w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61","w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","_core_heap","_state_to_heap","h0","h1","h2","h3","h4","total0","total1","hashed","hmac_reset","_hmac_opad","hmac_init","p0","p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","hmac_finish","t0","t4","pbkdf2_generate_block","count","Hash","HASH_SIZE","Sha1","NAME","BLOCK_SIZE","asm_function","Sha256","H5","H6","H7","I5","I6","I7","O5","O6","O7","f","g","h5","h6","h7","t5","t6","t7","sha256_asm","assert","val","msg","module","create","ctor","superCtor","super_","enumerable","configurable","TempCtor","inherits","enc","hi","lo","zero2","htonl","zero8","word","ah","al","bh","bl","ch","cl","dh","dl","carry","eh","el","num","BlockHash","pending","pendingTotal","outSize","hmacStrength","_delta8","_delta32","update","utils","toArray","join32","_update","digest","_pad","_digest","rotr32","z","ch32","p32","maj32","sum32","sum32_4","sum32_5","shaCommon","s0_256","s1_256","g0_256","g1_256","common","sha256_K","SHA256","W","SHA224","T1","T2","toHex32","split32","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","SHA512","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","SHA384","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotl32","sum32_3","RIPEMD160","K","Kh","A","B","D","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","md5cycle","ff","gg","add32","cmn","md5blk","md5blks","hex_chr","rhex","webCrypto","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","hashjsHash","webCryptoHash","hashInstance","asmcryptoHash","hashFunctions","entree","state","substring","tail","md51","ripemd160","algo","getHashByteLength","AES_CFB","getCipher","algoName","knownAlgos","getCiphers","nodeAlgos","pt","cipherObj","createCipheriv","nodeEncrypt","ALGO","_key","importKey","cbc_pt","ct","xorMut","webEncrypt","cfb","aesEncrypt","cipherfn","block_size","blockc","ciphertext","encblock","decipherObj","createDecipheriv","nodeDecrypt","aesDecrypt","blockp","decblock","AES_CTR","nonce","AES_CTR_set_options","counter","mask","pow","view","AES_CBC","blockLength","rightXORMut","zeroBlock","CMAC","cbc","padding2","ivLength","tagLength","two","OMAC","cmac","en","final","EAX","omac","ctr","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","xor","OCB","encipher","decipher","maxNtz","crypt","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","xorInput","$","cipherInput","cipherName","ciphers","mask_x","mask_$","constructKeyVariables","crypted","_AES_GCM_data_maxLength","AES_GCM","tagSize","gamma0","noncelen","noncebuf","_gcm_mac_process","nonceview","RangeError","cleartext","tagsize","AES_GCM_encrypt","AES_GCM_decrypt","AES_GCM_Encrypt_process","AES_GCM_Encrypt_finish","alen","clen","AES_GCM_Decrypt_process","tlen","AES_GCM_Decrypt_finish","atag","acheck","setAAD","getAuthTag","de","setAuthTag","additionalData","gcm","nacl","gf","Float64Array","randombytes","_9","gf0","gf1","_121665","D2","X","Y","crypto_verify_32","xi","yi","vn","set25519","car25519","o","v","sel25519","pack25519","neq25519","par25519","unpack25519","Z","M","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","x32","x16","crypto_scalarmult_base","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","cleanup","arr","scalarMult","box","keyPair","fromSecretKey","sign","signedMsg","sm","smlen","crypto_sign","detached","sig","verify","crypto_sign_open","fromSeed","seed","setPRNG","self","msCrypto","getRandomValues","min","require","randomBytes","exports","getRandomBytes","getRandomBigInteger","modulus","randomProbablePrime","thirty","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","rand","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","emLen","hashPrefix","tLen","fill","EM","asn1","RSAPrivateKey","define","seq","obj","int","RSAPublicKey","hashAlgo","hashName","jwk","pNum","qNum","dNum","dq","dp","kty","qi","ext","privateToJWK","webSign","err","BN","pBNum","qBNum","dBNum","subn","createSign","keyObject","version","publicExponent","privateExponent","prime1","prime2","exponent1","exponent2","coefficient","createPrivateKey","der","format","pem","label","nodeSign","bnSign","publicToJWK","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","constants","RSA_PKCS1_PADDING","publicEncrypt","bnEncrypt","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","keyGenOpt","modulusLength","generateKey","exportKey","generateKeyPair","opts","publicKeyEncoding","privateKeyEncoding","prv","_","toArrayLike","phi","nSizeOver3","rde","pSize","n1023","threshold","rqx","OID","oid","getName","keyFromPrivate","indutnyCurve","priv","keyFromPublic","pub","validate","getIndutnyCurve","elliptic","ec","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","stream.TransformStream","lengthByte","nextPacket","UnsupportedError","params","captureStackTrace","UnparseablePacket","rawContent","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","CurveWithOID","oidOrName","webCryptoKey","namedCurve","jwkToRawPublic","webGenKeyPair","createECDH","generateKeys","getPublicKey","getPrivateKey","nodeGenKeyPair","genKeyPair","entropy","getPublic","getPrivate","validateStandardParams","Q","supportedCurves","curveName","dG","validationErrors","eq","bufX","bufY","rawPublicToJWK","crv","ECPrivateKey","parameters","unused","ECDSASignature","ellipticSign","SubjectPublicKeyInfo","algorithm","subjectPublicKey","ellipticVerify","octstr","explicit","optional","any","bitstr","AlgorithmIdentifier","objid","use","getPreferredHashAlgo","RS","wrap","IV","P","unpack","unwrap","createArrayBuffer","setUint32","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","genPrivateEphemeralKey","recipient","deriveBits","public","webPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","V","derive","ellipticPublicEphemeralKey","secret","webPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","ellipticPrivateEphemeralKey","pkcs5.encode","wrappedKey","aesKW.wrap","pkcs5.decode","aesKW.unwrap","nodeSubtleCrypto","webcrypto","HKDF","inputKey","salt","info","outLen","importedKey","hashAlgoName","computeHMAC","hmacKey","hmacMessage","createHmac","pseudoRandomKey","hashLen","outputKeyingMaterial","roundInput","HKDF_INFO","recipientA","ephemeralSecretKey","sharedSecret","ephemeralPublicKey","hkdfInput","computeHKDF","xr","u1","u2","qSize","n150","rsa","publicParams","curveSize","publicKeyParams","privateKeyParams","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","instance","followLength","checkSupportedCurve","keyAlgo","symmetricAlgo","ECDHSymkey","ecdhX","fromObject","sessionKeyParams","privateParams","algosWithNativeRepresentation","orderedParams","generate","validateParams","algoModule","prefixrandom","repeat","random","pkcs1","pkcs5","aesKW","assign","TYPED_OK","Uint16Array","Int32Array","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","fnUntyped","Buf8","Buf16","Buf32","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","STORED_BLOCK","STATIC_TREES","DYN_TREES","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","MAX_MATCH","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","max_code","d_code","dist","put_short","pending_buf","send_bits","bi_valid","bi_buf","send_code","tree","bi_reverse","code","gen_codes","bl_count","next_code","init_block","dyn_ltree","dyn_dtree","bl_tree","opt_len","static_len","last_lit","matches","bi_windup","smaller","depth","_n2","_m2","pqdownheap","heap_len","compress_block","ltree","dtree","lc","extra","lx","d_buf","l_buf","build_tree","desc","stree","heap_max","base","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","_tr_init","tr_static_init","l_desc","d_desc","bl_desc","_tr_stored_block","stored_len","utils.arraySet","window","copy_block","_tr_align","bi_flush","_tr_flush_block","opt_lenb","static_lenb","max_blindex","level","strm","data_type","black_mask","detect_data_type","build_bl_tree","strategy","lcodes","dcodes","blcodes","rank","send_all_trees","_tr_tally","lit_bufsize","adler32","adler","crcTable","table","makeTable","crc32","MAX_MEM_LEVEL","MIN_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","errorCode","flush_pending","avail_out","pending_out","next_out","total_out","flush_block_only","trees._tr_flush_block","block_start","strstart","put_byte","putShortMSB","read_buf","avail_in","next_in","total_in","longest_match","cur_match","chain_length","max_chain_length","scan","best_len","prev_length","nice_match","limit","w_size","_win","wmask","w_mask","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","_w_size","more","window_size","hash_size","head","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","trees._tr_tally","max_lazy_match","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","max_block_size","pending_buf_size","max_start","DeflateState","status","gzhead","gzindex","method","last_flush","w_bits","hash_bits","utils.Buf16","deflateReset","trees._tr_init","deflateResetKeep","lm_init","deflate","old_flush","beg","hcrc","comment","os","level_flags","bstate","deflate_huff","deflate_rle","trees._tr_align","trees._tr_stored_block","__","_utf8len","utils.Buf8","string2buf","m_pos","buf_len","str_len","ZStream","Deflate","chunkSize","windowBits","memLevel","opt","raw","gzip","ended","zlib_deflate.deflateInit2","dictionary","dict","strings.string2buf","avail","next","tmpDict","dictLength","zlib_deflate.deflateSetDictionary","_dict_set","_mode","zlib_deflate.deflate","onEnd","onData","utils.shrinkBuf","zlib_deflate.deflateEnd","utils.flattenChunks","BAD","TYPE","inflate_fast","_in","_out","hold","here","op","from_source","dmax","wsize","whave","wnext","s_window","lcode","lencode","dcode","distcode","lmask","lenbits","dmask","distbits","top","dolen","dodist","sane","MAXBITS","ENOUGH_LENS","ENOUGH_DISTS","CODES","LENS","DISTS","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","incr","low","sym","root","drop","used","huff","base_index","offs","here_bits","here_op","here_val","extra_index","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","zswap32","InflateState","havedict","flags","check","total","wbits","ncode","nlen","ndist","have","lendyn","distdyn","back","was","inflateReset","utils.Buf32","inflateResetKeep","inflateInit2","inflateReset2","lenfix","distfix","virgin","fixedtables","updatewindow","copy","inflate","put","last_bits","last_op","last_val","hbuf","order","inf_leave","xflags","extra_len","inflateSetDictionary","dictid","GZheader","Inflate","zlib_inflate.inflateInit2","c.Z_OK","zlib_inflate.inflateGetHeader","zlib_inflate.inflateSetDictionary","allowBufError","c.Z_FINISH","c.Z_NO_FLUSH","strings.binstring2buf","zlib_inflate.inflate","c.Z_NEED_DICT","c.Z_BUF_ERROR","c.Z_STREAM_END","c.Z_SYNC_FLUSH","zlib_inflate.inflateEnd","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","remaining","seek","n_bit","n_byte","pi","bufToHex","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","getCRC","updateCRC","updateCRCRun","mtf","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","optDetail","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","CRC32","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","MAX_HUFCODE_BITS","permute","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","multistream","bz","targetStreamCRC","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","verified","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","issuerKeyID","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","writeHashedSubPackets","toHash","stream.slice","stream.clone","writeSubPacket","humanReadable","critical","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","fromBinary","compressionFn","compress_fns","nodeZlib","node_zlib","stream.nodeToWeb","stream.webToNode","pako_zlib","deflateRaw","createDeflateRaw","createDeflate","inflateRaw","createInflateRaw","createInflate","BunzipDecode","SymEncryptedIntegrityProtectedDataPacket","encrypted","sessionKeyAlgorithm","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","AEADEncryptedDataPacket","cipherAlgorithm","aeadAlgorithm","chunkSizeByte","getAEADMode","modeInstance","tagLengthIfDecrypting","tagLengthIfEncrypting","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","latestPromise","cryptedBytes","queuedBytes","finalChunk","cryptedPromise","setInt32","desiredSize","PublicKeyEncryptedSessionKeyPacket","publicKeyID","sessionKey","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","sessionKeyData","S2K","getCount","passphrase","numBytes","rlength","prefixlen","datalen","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","produceKey","encryptionKey","generateSessionKey","associatedData","toEncrypt","PublicKeyPacket","expirationTimeV3","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","startOfSecretKeyData","unparseableKeyMaterial","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","produceEncryptionKey","cleartextWithHash","validParams","generateParams","global","parse5322","inStr","getPos","setPos","initialize","parseString","tokens","semantic","children","ast","parent","child","compareToken","fxnCompare","tok","lit","and","or","prod","invis","colwsp","star","minimum","isUTF8NonAscii","cr","crlf","lf","dquote","htab","sp","vchar","accept","rfc6532","wsp","quotedPair","obsQP","fws","obsFws","ctext","obsCtext","ccontent","cfws","atext","atom","dotAtomText","maybeText","dotAtom","qtext","obsQtext","qcontent","quotedString","address","mailbox","group","nameAddr","addrSpec","displayName","angleAddr","obsAngleAddr","groupList","obsPhrase","collapseWhitespace","mailboxList","obsMboxList","addressList","obsAddrList","obsGroupList","localPart","obsLocalPart","dtext","obsDtext","domainLiteral","domain","obsDomain","rejectTLD","obsNoWsCtl","strict","atInDisplayName","obsRoute","obsDomainList","findNode","stack","findAllNodesNoChildren","names","namesLookup","giveResult","addresses","groupsAndMailboxes","groupOrMailbox","giveResultGroup","giveResultMailbox","simplifyResult","oneResult","partial","groupName","groupResultMailboxes","mailboxes","grabSemantic","aspec","findAllNodes","comments","local","concatComments","startProduction","handleOpts","startAt","defs","isNullUndef","defaults","isObject","parseOneAddress","parseAddressList","parseFrom","parseSender","parseReplyTo","UserIDPacket","email","components","emailAddresses","otherUserID","SecretSubkeyPacket","TrustPacket","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","prefAlgo","primaryUser","getPrimaryUser","selfCertification","getPreferredCurveHashAlgo","getPreferredAlgo","userIDs","defaultAlgo","preferredSenderAlgo","prefPropertyName","senderAlgoSupport","recipientPrefs","Boolean","signingKeyPacket","signaturePacket","mergeSignatures","source","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","sanitizeKeyOptions","subkeyDefaults","isValidSigningKeyPacket","isValidEncryptionKeyPacket","isValidDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","signingKeys","isPrivate","signingKey","getSigningKey","certificate","verificationKeys","issuerKeys","getKeys","isRevoked","certifications","certification","valid","verifyCertificate","sourceUser","srcSelfSig","srcRevSig","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","sort","helper.isValidSigningKeyPacket","helper.checkKeyRequirements","helper.isValidEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","revocationCertificate","privateKeys","userSign","certify","verifyAllCertifications","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","fromSecretKeyPacket","pubSubkeyPacket","fromSecretSubkeyPacket","helper.isValidDecryptionKeyPacket","allDummies","defaultOptions","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","readPrivateKey","readKeys","armoredKeys","binaryKeys","keyIndex","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","sessionKeyObjects","decryptSessionKeys","symEncryptedPacketlist","symEncryptedPacket","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","password","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","getDecryptionKeys","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgorithmName","supported","isAEADSupported","getEncryptionKey","maybeKey","wildcard","encryptionKeyIDs","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","literalDataPacket","existingSigPacketlist","onePassSig","signingKeyID","onePassSignatureList","createSignaturePackets","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","detachedSignature","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","stream.loadStreamsPonyfill","stream.toStream","createMessage","literalDataPacketlist","CleartextMessage","newSignature","hashes","ar","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","oneHeader","createCleartextMessage","checkConfig","helper.generateSecretKey","getRevocationCertificate","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","applyRevocationCertificate","revoke","decryptKey","clonedPrivateKey","passphrases","encryptKey","signingUserIDs","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","streaming","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","signDetached","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","encoding","setEncoding","stream.toNativeReadable","object","SymbolPolyfill","iterator","description","noop","globals","typeIsObject","rethrowAssertionErrorRejection","originalPromise","originalPromiseThen","originalPromiseResolve","originalPromiseReject","newPromise","executor","promiseResolvedWith","promiseRejectedWith","PerformPromiseThen","onFulfilled","onRejected","uponPromise","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","reflectCall","F","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","peek","front","ReadableStreamReaderGenericInitialize","_ownerReadableStream","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","isFinite","MathTrunc","trunc","assertDictionary","context","assertFunction","assertObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","toStringTag","asyncIterator","ReadableStreamAsyncIteratorImpl","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","return","returnSteps","_returnSteps","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","IsFiniteNonNegativeNumber","IsNonNegativeNumber","DequeueValue","container","pair","_queue","_queueTotalSize","EnqueueValueWithSize","ResetQueue","CreateArrayFromList","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespond","respondWithNewView","isView","firstDescriptor","_pendingPullIntos","bytesFilled","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","_byobRequest","request","SetUpReadableStreamBYOBRequest","ReadableByteStreamControllerGetDesiredSize","_closeRequested","_controlledReadableByteStream","ReadableByteStreamControllerError","ReadableByteStreamControllerClearAlgorithms","ReadableStreamClose","ReadableByteStreamControllerClose","transferredBuffer","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableStreamHasBYOBReader","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerEnqueue","_cancelAlgorithm","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","elementSize","viewConstructor","readerType","shouldPull","_started","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","queue","headOfQueue","bytesToCopy","destStart","destOffset","srcOffset","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","ReadableByteStreamControllerClearPendingPullIntos","ReadableStreamError","_strategyHWM","SetUpReadableByteStreamControllerFromUnderlyingSource","underlyingByteSource","startAlgorithm","pullAlgorithm","cancelAlgorithm","SetUpReadableByteStreamController","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","ReadableStreamBYOBReader","byobReaderBrandCheckException","BYTES_PER_ELEMENT","emptyView","ReadableByteStreamControllerPullInto","ReadableStreamBYOBReaderRead","ExtractHighWaterMark","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException$2","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","DOMException$1","_a","isDOMExceptionConstructor","createDOMExceptionPolyfill","ReadableStreamPipeTo","signal","shuttingDown","currentWrite","actions","shutdownWithAction","action","aborted","addEventListener","isOrBecomesErrored","shutdown","isOrBecomesClosed","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","defaultControllerBrandCheckException$1","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","convertPipeOptions","isAbortSignal","assertAbortSignal","rawUnderlyingSource","underlyingSource","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","SetUpReadableStreamDefaultControllerFromUnderlyingSource","streamBrandCheckException$1","rawOptions","convertReaderOptions","AcquireReadableStreamBYOBReader","pipeThrough","rawTransform","convertReadableWritablePair","destination","branches","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","canceled1","canceled2","cancelPromise","value1","value2","CreateReadableStream","compositeReason","cancelResult","ReadableStreamTee","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","streamBrandCheckException","IsTransformStreamDefaultController","defaultControllerBrandCheckException","readableController","TransformStreamDefaultControllerTerminate","ReadableStreamDefaultControllerHasBackpressure","extendStatics","__proto__","__extends","isStreamConstructor","startCalled","isReadableStream","isWritableStream","isTransformStream","supportsByobReader","createWrappingReadableSource","parseReadableType","WrappingReadableByteStreamSource","WrappingReadableStreamDefaultSource","typeString","AbstractWrappingReadableStreamSource","underlyingStream","_underlyingReader","_readerMode","_pendingRead","_underlyingStream","_attachDefaultReader","_detachReader","_attachReader","_this","_finishPendingRead","_pullWithDefaultReader","_tryClose","_setPendingRead","readPromise","pendingRead","finishRead","afterRead","_super","supportsByob","_supportsByob","_attachByobReader","_pullWithByobRequest","to","fromArray","createWrappingWritableSink","WrappingWritableStreamSink","underlyingWriter","_pendingWrite","_underlyingWriter","_errorPromise","_errorPromiseReject","_finishErroring","_startErroring","race","_setPendingWrite","_finishPendingWrite","writePromise","pendingWrite","finishWrite","afterWrite","createWrappingTransformer","WrappingTransformStreamTransformer","_onRead","_onError","_flushReject","_onTerminate","_flushResolve","_flushPromise","readerClosed","isReadableStreamConstructor","byteSourceSupported","supportsByteSource","isTransformStreamConstructor","isWritableStreamConstructor","sink","isBN","negative","words","red","_init","wordSize","parseHex","parseBase","cmp","_initNumber","_initArray","_parseHex","_parseBase","strip","limbLen","limbPow","imuln","_iaddn","_expand","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","out","ncarry","rword","maxJ","groupSize","groupBase","modn","idivn","toJSON","toBuffer","ArrayType","reqLength","littleEndian","andln","iushrn","_countBits","clz32","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","uor","iuand","iand","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","comb10MulTo","mid","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","bl7","bh7","bl8","bh8","bl9","bh9","jumboMulTo","FFTM","mulp","mulTo","hncarry","bigMulTo","makeRBT","N","revBin","rb","rbt","rws","iws","rtws","itws","rtwdf","cos","PI","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","carryMask","newCarry","ishln","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","iabs","_ishlnsubmul","_wordDiv","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","r2","acc","egcd","yp","xp","im","isOdd","jm","_invmp","delta","cmpn","invm","bincn","ucmp","gtn","gten","ltn","lten","eqn","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","rinv","minv","ireduce","imulK","mod3","nOne","lpow","inv","wnd","currentLen","mont","nred","minAssert","minUtils","getNAF","naf","getJSF","jsf","d1","d2","m8","m14","m24","cachedProperty","computer","parseBytes","intFromLE","Rand","_rand","getByte","BaseCurve","conf","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","adjustCount","redN","_maxwellTrick","BasePoint","precomputed","point","_fixedNafMul","doubles","_getDoubles","step","repr","nafW","jpoint","mixedAdd","points","toP","_wnafMul","nafPoints","_getNAFPoints","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","comb","toJ","ja","jb","decodePoint","pointFromX","encodeCompressed","_encode","compact","getX","getY","precompute","beta","_getBeta","_hasDoubles","dbl","ShortCurve","Base","tinv","zeroA","threeA","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","Point","isRed","inf","JPoint","zOne","MontCurve","i4","a24","lambda","betas","_getEndoRoots","lambdas","basis","vec","_getEndoBasis","ntinv","prevR","aprxSqrt","len1","_endoSplit","v1","v2","ax","rhs","_endoWnafMulAdd","npoints","ncoeffs","fromJSON","pre","endoMul","JSON","obj2point","isInfinity","nx","ny","ys1","dyinv","mulAdd","jmulAdd","_precompute","negate","zinv","zinv2","ay","pz2","nz","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","dny","_zeroDbl","_threeDbl","_dbl","yyyy","yyyy8","c8","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","pz3","eqXToP","zs","xc","normalize","diffAdd","da","cb","jumlAdd","EdwardsCurve","twisted","mOneA","oneC","_mulA","_mulC","lhs","pointFromY","_extDbl","nt","_projDbl","_extAdd","_projAdd","short","edwards","ft_1","sha1_K","SHA1","require$$4","Hmac","inner","outer","sha","hmac","PresetCurve","defineCurve","cofactor","HmacDRBG","predResist","minEntropy","_reseed","reseedInterval","entropyEnc","nonceEnc","pers","persEnc","_hmac","kmac","reseed","addEnc","KeyPair","_importPrivate","privEnc","_importPublic","pubEnc","fromPublic","fromPrivate","_importDER","recoveryParam","Position","place","getLength","initial","octetLen","rmPadding","constructLength","octets","slen","toDER","backHalf","EC","nh","drbg","ns2","_truncateToN","truncOnly","truncateMsg","bkey","ns1","iter","kp","kpX","canonical","_verify","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Qprime","_secret","isPoint","_pub","_pubBytes","fromSecret","encodePoint","lastIx","encodingLength","decodeInt","privBytes","getSecret","pubBytes","_R","_S","_Rencoded","Rencoded","_Sencoded","Sencoded","encodeInt","toBytes","EDDSA","pointClass","keyFromSecret","hashInt","messagePrefix","s_","makeSignature","SG","normed","xIsOdd","require$$5"],"mappings":";gQAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxBC,cACEC,QACAC,KAAKT,GAAsB,IAAIU,SAAQ,CAACC,EAASC,KAC/CH,KAAKP,GAAsBS,EAC3BF,KAAKN,GAAqBS,CAAM,IAElCH,KAAKT,GAAoBa,OAAM,UAuCnC,SAASC,EAAcC,GACrB,OAAOA,GAASA,EAAMC,WAAaV,MAAMW,QAAQF,EACnD,CAOA,SAASG,EAAOH,GACd,IAAKD,EAAcC,GAAQ,CACzB,MAAMI,EAASJ,EAAMK,YACfC,EAAcF,EAAOE,YAK3B,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mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAINrC,IAAK,CACHP,IAAK,EACL4C,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,4FCrwBR,IAsOIgE,EAtOArtE,EAASvJ,EAMT7Y,EAASuC,GAAMvC,OAEnB,SAASy0F,EAAYh1H,GACnB,GAAqB,UAAjBA,EAAQmV,KACVpa,KAAK4Q,MAAQ,IAAIA,GAAM0oH,MAAMr0H,QAC1B,GAAqB,YAAjBA,EAAQmV,KACfpa,KAAK4Q,MAAQ,IAAIA,GAAM2oH,QAAQt0H,OAC5B,I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AAeqqC,GACVrqC,EACF,IAAIqqC,GAAU9nF,KAAMy9C,EAC7B,EAUAqhF,GAAM99H,UAAU+8H,YAAc,SAAqBvN,GACjD,IAAIpqF,EAAMoqF,EAAM8B,OAAOtqF,QAAQ,KAAMhoC,KAAKi+H,gBAE1C,OADA73F,EAAIpmC,KAAKi+H,eAAiB,IAAMzN,EAAM6B,OAAO5H,QAAU,IAAO,EACvDrkF,CACT,EAEA04F,GAAM99H,UAAUgxH,YAAc,SAAqB1qH,GAGjD,IAAI02H,GAFJ12H,EAAQygC,GAAMunF,WAAWhoH,IAENlG,OAAS,EACxBk+H,EAASh4H,EAAM5F,MAAM,EAAGs8H,GAAQp3H,QAAuB,IAAhBU,EAAM02H,IAC7CuB,EAAoC,IAAV,IAAhBj4H,EAAM02H,IAEhB1vH,EAAIy5B,GAAMwnF,UAAU+P,GACxB,OAAOt/H,KAAK4Q,MAAMooH,WAAW1qH,EAAGixH,EAClC,EAEAT,GAAM99H,UAAU49H,UAAY,SAAmBt3F,GAC7C,OAAOA,EAAIU,QAAQ,KAAMhoC,KAAKi+H,eAChC,EAEAa,GAAM99H,UAAUk9H,UAAY,SAAmB52H,GAC7C,OAAOygC,GAAMwnF,UAAUjoH,EACzB,EAEAw3H,GAAM99H,UAAU28H,QAAU,SAAiBl4F,GACzC,OAAOA,aAAezlC,KAAK++H,UAC7B,2BC1IA,IAAIl5E,EAAWxH,EAEfwH,EAAS9d,MAAQvlC,GACjBqjD,EAAS5G,KAAOt7C,GAChBkiD,EAASj1C,MAAQwO,GACjBymC,EAAS+B,OAASpoC,GAGlBqmC,EAASC,GAAK6zE,GACd9zE,EAAS9yC,MAAQysH"} \ No newline at end of file +{"version":3,"file":"openpgp.min.mjs","sources":["../../node_modules/@openpgp/web-stream-tools/lib/writer.js","../../node_modules/@openpgp/web-stream-tools/lib/util.js","../../node_modules/@openpgp/web-stream-tools/lib/reader.js","../../node_modules/@openpgp/web-stream-tools/lib/streams.js","../../src/enums.js","../../src/config/config.js","../../src/util.js","../../src/encoding/base64.js","../../src/encoding/armor.js","../../src/crypto/cipher/index.js","../../src/crypto/hash/md5.js","../../src/crypto/hash/index.js","../../node_modules/@noble/ciphers/esm/_assert.js","../../node_modules/@noble/ciphers/esm/utils.js","../../node_modules/@noble/ciphers/esm/_polyval.js","../../node_modules/@noble/ciphers/esm/aes.js","../../src/crypto/mode/cfb.js","../../src/crypto/cmac.js","../../src/crypto/mode/eax.js","../../src/crypto/mode/ocb.js","../../src/crypto/mode/gcm.js","../../src/crypto/mode/index.js","../../../../src/crypto/biginteger.ts","../../src/crypto/random.js","../../../../src/crypto/public_key/prime.ts","../../src/crypto/pkcs1.js","../../src/crypto/public_key/rsa.js","../../src/crypto/public_key/elgamal.js","../../node_modules/@openpgp/tweetnacl/crypto.js","../../node_modules/@openpgp/tweetnacl/nacl-fast.js","../../src/type/oid.js","../../src/packet/packet.js","../../src/crypto/public_key/elliptic/eddsa.js","../../src/crypto/aes_kw.js","../../src/crypto/hkdf.js","../../src/crypto/public_key/elliptic/ecdh_x.js","../../src/crypto/public_key/elliptic/oid_curves.js","../../src/crypto/public_key/elliptic/ecdsa.js","../../src/crypto/public_key/elliptic/eddsa_legacy.js","../../src/crypto/pkcs5.js","../../src/crypto/public_key/elliptic/ecdh.js","../../src/crypto/public_key/dsa.js","../../src/crypto/public_key/index.js","../../src/crypto/signature.js","../../src/type/ecdh_symkey.js","../../src/type/kdf_params.js","../../src/type/ecdh_x_symkey.js","../../src/crypto/crypto.js","../../src/crypto/index.js","../../src/type/s2k/argon2.js","../../src/type/s2k/generic.js","../../src/type/s2k/index.js","../../node_modules/fflate/esm/index.mjs","../../src/packet/literal_data.js","../../src/type/keyid.js","../../src/packet/signature.js","../../src/packet/one_pass_signature.js","../../src/packet/packetlist.js","../../src/packet/compressed_data.js","../../src/packet/sym_encrypted_integrity_protected_data.js","../../src/packet/aead_encrypted_data.js","../../src/packet/public_key_encrypted_session_key.js","../../src/packet/sym_encrypted_session_key.js","../../src/packet/public_key.js","../../src/packet/symmetrically_encrypted_data.js","../../src/packet/marker.js","../../src/packet/public_subkey.js","../../src/packet/user_attribute.js","../../src/packet/secret_key.js","../../src/packet/userid.js","../../src/packet/secret_subkey.js","../../src/packet/trust.js","../../src/packet/padding.js","../../src/signature.js","../../src/key/helper.js","../../src/key/user.js","../../src/key/subkey.js","../../src/key/key.js","../../src/key/public_key.js","../../src/key/private_key.js","../../src/key/factory.js","../../src/message.js","../../src/cleartext.js","../../src/openpgp.js","../../node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/hashes/esm/cryptoNode.js","../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_md.js","../../node_modules/@noble/hashes/esm/sha256.js","../../node_modules/@noble/hashes/esm/hmac.js","../../node_modules/@noble/curves/esm/abstract/utils.js","../../node_modules/@noble/curves/esm/abstract/modular.js","../../node_modules/@noble/curves/esm/abstract/curve.js","../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../node_modules/@noble/curves/esm/_shortw_utils.js","../../node_modules/@noble/curves/esm/p256.js","../../node_modules/@noble/hashes/esm/_u64.js","../../node_modules/@noble/hashes/esm/sha512.js","../../node_modules/@noble/curves/esm/p384.js","../../node_modules/@noble/curves/esm/p521.js","../../node_modules/@noble/hashes/esm/sha3.js","../../node_modules/@noble/curves/esm/abstract/edwards.js","../../node_modules/@noble/curves/esm/abstract/montgomery.js","../../node_modules/@noble/curves/esm/ed448.js","../../node_modules/@noble/curves/esm/secp256k1.js","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP256r1.ts","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP384r1.ts","../../../../src/crypto/public_key/elliptic/brainpool/brainpoolP512r1.ts","../../src/crypto/public_key/elliptic/noble_curves.js","../../src/crypto/cipher/des.js","../../src/crypto/cipher/cast5.js","../../src/crypto/cipher/twofish.js","../../src/crypto/cipher/blowfish.js","../../src/crypto/cipher/legacy_ciphers.js","../../node_modules/@noble/hashes/esm/sha1.js","../../node_modules/@noble/hashes/esm/ripemd160.js","../../src/crypto/hash/noble_hashes.js","../../node_modules/argon2id/lib/blake2b.js","../../node_modules/argon2id/lib/argon2id.js","../../node_modules/argon2id/lib/setup.js","../../node_modules/argon2id/index.js","../../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../../node_modules/@openpgp/seek-bzip/lib/stream.js","../../node_modules/@openpgp/seek-bzip/lib/crc32.js","../../node_modules/@openpgp/seek-bzip/lib/index.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n Object.setPrototypeOf(this, ArrayStream.prototype);\n\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","/* eslint-disable no-prototype-builtins */\nimport { isArrayStream } from './writer.js';\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n // try and detect a node native stream without having to import its class\n if (input &&\n !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&\n typeof input._read === 'function' && typeof input._readableState === 'object') {\n throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isUint8Array, isStream, isArrayStream } from './util.js';\nimport * as streams from './streams.js';\n\nconst doneReadingSet = new WeakSet();\n/**\n * The external buffer is used to store values that have been peeked or unshifted from the original stream.\n * Because of how streams are implemented, such values cannot be \"put back\" in the original stream,\n * but they need to be returned first when reading from the input again.\n */\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = () => {};\n return;\n }\n let streamType = isStream(input);\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isStream, isArrayStream, isUint8Array, concatUint8Array } from './util.js';\nimport { Reader, externalBuffer } from './reader.js';\nimport { ArrayStream, Writer } from './writer.js';\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n }\n lastBytes = returnValue;\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input)) {\n return input.subarray(begin, end === Infinity ? input.length : end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n const cancelled = await input.cancel(reason);\n // the stream is not always cancelled at this point, so we wait some more\n await new Promise(setTimeout);\n return cancelled;\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n\nexport {\n ArrayStream,\n toStream,\n concatStream,\n concat,\n getReader,\n getWriter,\n pipe,\n transformRaw,\n transform,\n transformPair,\n parse,\n clone,\n passiveClone,\n slice,\n readToEnd,\n cancel,\n fromAsync\n};\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'nistP256': 'nistP256',\n /** @deprecated use `nistP256` instead */\n 'p256': 'nistP256',\n\n /** NIST P-384 Curve */\n 'nistP384': 'nistP384',\n /** @deprecated use `nistP384` instead */\n 'p384': 'nistP384',\n\n /** NIST P-521 Curve */\n 'nistP521': 'nistP521',\n /** @deprecated use `nistP521` instead */\n 'p521': 'nistP521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519Legacy',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519Legacy',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519Legacy',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519Legacy',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n argon2: 4,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11,\n sha3_256: 12,\n sha3_512: 14\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n gcm: 3,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n padding: 21\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuerKeyID: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34,\n preferredCipherSuites: 39\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4,\n seipdv2: 8\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha512,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * This option is applicable to:\n * - key generation (encryption key preferences),\n * - password-based message encryption, and\n * - private key encryption.\n * In the case of message encryption using public keys, the encryption key preferences are respected instead.\n * Note: not all OpenPGP implementations are compatible with this option.\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)\n * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,\n * this option must be set, otherwise key parsing and/or key decryption will fail.\n * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys\n * will be processed incorrectly.\n */\n parseAEADEncryptedV4KeysAsLegacy: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.gcm,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use v6 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v6Keys\n */\n v6Keys: false,\n /**\n * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).\n * These are non-standard entities, which in the crypto-refresh have been superseded\n * by v6 keys and v6 signatures, respectively.\n * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,\n * hence parsing them might be necessary in some cases.\n */\n enableParsingV5Entities: false,\n /**\n * S2K (String to Key) type, used for key derivation in the context of secret key encryption\n * and password-encrypted data. Weaker s2k options are not allowed.\n * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it\n * (pending standardisation).\n * @memberof module:config\n * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}\n */\n s2kType: enums.s2k.iterated,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:\n * Iteration Count Byte for Iterated and Salted S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.\n * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:\n * Argon2 parameters for S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.\n * Default settings correspond to the second recommendation from RFC9106 (\"uniformly safe option\"),\n * to ensure compatibility with memory-constrained environments.\n * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.\n * @memberof module:config\n * @property {Object} params\n * @property {Integer} params.passes - number of iterations t\n * @property {Integer} params.parallelism - degree of parallelism p\n * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.\n */\n s2kArgon2Params: {\n passes: 3,\n parallelism: 4, // lanes\n memoryExponent: 16 // 64 MiB of RAM\n },\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:\n * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL\n * (see https://efail.de/).\n * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.\n *\n * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n /**\n * Allow using keys that do not have any key flags set.\n * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages\n * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).\n * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.\n * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.\n */\n allowMissingKeyFlags: false,\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).\n * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur\n * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of\n * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.\n * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.\n */\n nonDeterministicSignaturesViaNotation: true,\n /**\n * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * @memberof module:config\n * @property {Boolean} useEllipticFallback\n */\n useEllipticFallback: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { createRequire } from 'module'; // Must be stripped in browser built\nimport enums from './enums';\nimport defaultConfig from './config';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n nodeRequire: createRequire(import.meta.url),\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n /**\n * Load noble-curves lib on demand and return the requested curve function\n * @param {enums.publicKey} publicKeyAlgo\n * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)\n * @returns curve implementation\n * @throws on unrecognized curve, or curve not implemented by noble-curve\n */\n getNobleCurve: async (publicKeyAlgo, curveName) => {\n if (!defaultConfig.useEllipticFallback) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n\n const { nobleCurves } = await import('./crypto/public_key/elliptic/noble_curves');\n switch (publicKeyAlgo) {\n case enums.publicKey.ecdh:\n case enums.publicKey.ecdsa: {\n const curve = nobleCurves.get(curveName);\n if (!curve) throw new Error('Unsupported curve');\n return curve;\n }\n case enums.publicKey.x448:\n return nobleCurves.get('x448');\n case enums.publicKey.ed448:\n return nobleCurves.get('ed448');\n default:\n throw new Error('Unsupported curve');\n }\n },\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,\n // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed\n // has not been authenticated (yet).\n // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.\n // Also, AEAD is also not affected.\n return util.readExactSubarray(bytes, 2, 2 + bytelen);\n },\n\n /**\n * Read exactly `end - start` bytes from input.\n * This is a stricter version of `.subarray`.\n * @param {Uint8Array} input - Input data to parse\n * @returns {Uint8Array} subarray of size always equal to `end - start`\n * @throws if the input array is too short.\n */\n readExactSubarray: function (input, start, end) {\n if (input.length < (end - start)) {\n throw new Error('Input array too short');\n }\n return input.subarray(start, end);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n if (bytes.length > length) {\n throw new Error('Input array too long');\n }\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const hexAlphabet = '0123456789abcdef';\n let s = '';\n bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });\n return s;\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography API.\n * @returns {Object} The SubtleCrypto API\n * @throws if the API is not available\n */\n getWebCrypto: function() {\n const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n // Fallback for Node 16, which does not expose WebCrypto as a global\n const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;\n if (!webCrypto) {\n throw new Error('The WebCrypto API is not available');\n }\n return webCrypto;\n },\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return this.nodeRequire('crypto');\n },\n\n getNodeZlib: function() {\n return this.nodeRequire('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (this.nodeRequire('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = this.nodeRequire('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n /**\n * Test email format to ensure basic compliance:\n * - must include a single @\n * - no control or space unicode chars allowed\n * - no backslash and square brackets (as the latter can mess with the userID parsing)\n * - cannot end with a punctuation char\n * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,\n * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).\n */\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^[^\\p{C}\\p{Z}@<>\\\\]+@[^\\p{C}\\p{Z}@<>\\\\]+[^\\p{C}\\p{Z}\\p{P}]$/u;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n }\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n }\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n }\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n }\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n }\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n }\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Remove the (optional) checksum from an armored message.\n * @param {String} text - OpenPGP armored message\n * @returns {String} The body of the armored message.\n * @private\n */\nfunction removeChecksum(text) {\n let body = text;\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n }\n\n return body;\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n const data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== enums.armor.signed) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === enums.armor.signed) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const body = removeChecksum(parts[0].slice(0, -1));\n await writer.write(body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum\n * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug\n // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)\n const maybeBodyClone = emitChecksum && stream.passiveClone(body);\n\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push(hash ? `Hash: ${hash}\\n\\n` : '\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","import enums from '../../enums';\n\nexport async function getLegacyCipher(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n throw new Error('Not a legacy cipher');\n case enums.symmetric.cast5:\n case enums.symmetric.blowfish:\n case enums.symmetric.twofish:\n case enums.symmetric.tripledes: {\n const { legacyCiphers } = await import('./legacy_ciphers');\n const cipher = legacyCiphers.get(algo);\n if (!cipher) {\n throw new Error('Unsupported cipher algorithm');\n }\n return cipher;\n }\n default:\n throw new Error('Unsupported cipher algorithm');\n }\n}\n\n/**\n * Get block size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherBlockSize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 16;\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n case enums.symmetric.tripledes:\n return 8;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherKeySize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n return 16;\n case enums.symmetric.aes192:\n case enums.symmetric.tripledes:\n return 24;\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 32;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get block and key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nexport function getCipherParams(algo) {\n return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };\n}\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction nobleHash(nobleHashName, webCryptoHashName) {\n const getNobleHash = async () => {\n const { nobleHashes } = await import('./noble_hashes');\n const hash = nobleHashes.get(nobleHashName);\n if (!hash) throw new Error('Unsupported hash');\n return hash;\n };\n\n return async function(data) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hash = await getNobleHash();\n\n const hashInstance = hash.create();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => hashInstance.digest());\n } else if (webCrypto && webCryptoHashName) {\n return new Uint8Array(await webCrypto.digest(webCryptoHashName, data));\n } else {\n const hash = await getNobleHash();\n\n return hash(data);\n }\n };\n}\n\nexport default {\n\n /** @see module:md5 */\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'),\n sha224: nodeHash('sha224') || nobleHash('sha224'),\n sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'),\n sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'),\n sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'),\n ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'),\n sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'),\n sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'),\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n case enums.hash.sha3_256:\n return this.sha3_256(data);\n case enums.hash.sha3_512:\n return this.sha3_512(data);\n default:\n throw new Error('Unsupported hash function');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n case enums.hash.sha3_256:\n return 32;\n case enums.hash.sha3_512:\n return 64;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, copyBytes, createView, toBytes, u32 } from './utils.js';\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\nclass GHASH {\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n this.blockLen = BLOCK_SIZE;\n this.outputLen = BLOCK_SIZE;\n this.s0 = 0;\n this.s1 = 0;\n this.s2 = 0;\n this.s3 = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\nclass Polyval extends GHASH {\n constructor(key, expectedLength) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\nfunction wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key, expectedLength) => hashCons(key, expectedLength);\n return hashC;\n}\nexport const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));\nexport const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));\n//# sourceMappingURL=_polyval.js.map","// prettier-ignore\nimport { bytes as abytes } from './_assert.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { clean, concatBytes, copyBytes, createView, equalBytes, isAligned32, setBigUint64, u32, u8, wrapCipher, } from './utils.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (dst === undefined)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n if (!isAligned32(dst))\n throw new Error('unaligned dst');\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n const out = getDst(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD == null ? 0 : AAD.length;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(aadLength * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(key);\n abytes(nonce);\n if (AAD !== undefined)\n abytes(AAD);\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\n// Private, unsafe low-level methods. Can change at any time.\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n */\n\nimport { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../../util';\nimport enums from '../../enums';\nimport { getLegacyCipher, getCipherParams } from '../cipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (nodeCrypto && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nclass WebCryptoEncryptor {\n constructor(algo, key, iv) {\n const { blockSize } = getCipherParams(algo);\n this.key = key;\n this.prevBlock = iv;\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n this.zeroBlock = new Uint8Array(this.blockSize);\n }\n\n static async isSupported(algo) {\n const { keySize } = getCipherParams(algo);\n return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])\n .then(() => true, () => false);\n }\n\n async _runCBC(plaintext, nonZeroIV) {\n const mode = 'AES-CBC';\n this.keyRef = this.keyRef || await webCrypto.importKey('raw', this.key, mode, false, ['encrypt']);\n const ciphertext = await webCrypto.encrypt(\n { name: mode, iv: nonZeroIV || this.zeroBlock },\n this.keyRef,\n plaintext\n );\n return new Uint8Array(ciphertext).subarray(0, plaintext.length);\n }\n\n async encryptChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const plaintext = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n const toEncrypt = util.concatUint8Array([\n this.prevBlock,\n plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block \"early\", since we only need to xor the plaintext and pass it over as prevBlock\n ]);\n\n const encryptedBlocks = await this._runCBC(toEncrypt);\n xorMut(encryptedBlocks, plaintext);\n this.prevBlock = encryptedBlocks.slice(-this.blockSize);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return encryptedBlocks;\n }\n\n this.i += added.length;\n let encryptedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n const curBlock = this.nextBlock;\n encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n this.prevBlock = encryptedBlock.slice();\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n encryptedBlock = new Uint8Array();\n }\n\n return encryptedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n this.nextBlock = this.nextBlock.subarray(0, this.i);\n const curBlock = this.nextBlock;\n const encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n result = encryptedBlock.subarray(0, curBlock.length);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.keyRef = null;\n this.key = null;\n }\n\n async encrypt(plaintext) {\n // plaintext is internally padded to block length before encryption\n const encryptedWithPadding = await this._runCBC(\n util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]),\n this.iv\n );\n // drop encrypted padding\n const ct = encryptedWithPadding.subarray(0, plaintext.length);\n xorMut(ct, plaintext);\n this.clearSensitiveData();\n return ct;\n }\n}\n\nclass NobleStreamProcessor {\n constructor(forEncryption, algo, key, iv) {\n this.forEncryption = forEncryption;\n const { blockSize } = getCipherParams(algo);\n this.key = nobleAesHelpers.expandKeyLE(key);\n\n if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers\n this.prevBlock = getUint32Array(iv);\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n }\n\n _runCFB(src) {\n const src32 = getUint32Array(src);\n const dst = new Uint8Array(src.length);\n const dst32 = getUint32Array(dst);\n for (let i = 0; i + 4 <= dst32.length; i += 4) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);\n }\n return dst;\n }\n\n async processChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const toProcess = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n\n const processedBlocks = this._runCFB(toProcess);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return processedBlocks;\n }\n\n this.i += added.length;\n\n let processedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n processedBlock = this._runCFB(this.nextBlock);\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n processedBlock = new Uint8Array();\n }\n\n return processedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n const processedBlock = this._runCFB(this.nextBlock);\n\n result = processedBlock.subarray(0, this.i);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.key.fill(0);\n }\n}\n\n\nasync function aesEncrypt(algo, key, pt, iv) {\n if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys\n const cfb = new WebCryptoEncryptor(algo, key, iv);\n return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);\n } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream\n const cfb = new NobleStreamProcessor(true, algo, key, iv);\n return stream.transform(pt, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).encrypt(pt);\n}\n\nasync function aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new NobleStreamProcessor(false, algo, key, iv);\n return stream.transform(ct, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).decrypt(ct);\n}\n\nfunction xorMut(a, b) {\n const aLength = Math.min(a.length, b.length);\n for (let i = 0; i < aLength; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nconst getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt) {\n return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n */\n\nimport { ctr as nobleAesCtr } from '@noble/ciphers/aes';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const keyRef = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, keyRef, pt);\n return new Uint8Array(ct);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt, iv) {\n return nobleAesCtr(key, iv).encrypt(pt);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport { getCipherParams } from '../cipher';\nimport util from '../../util';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n const { keySize } = getCipherParams(cipher);\n // sanity checks\n if (!util.isAES(cipher) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let maxNtz = 0;\n\n // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,\n // hence its execution cannot be broken up.\n // As a result, WebCrypto cannot currently be used for `encipher`.\n const aes = nobleAesCbc(key, zeroBlock, { disablePadding: true });\n const encipher = block => aes.encrypt(block);\n const decipher = block => aes.decrypt(block);\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables() {\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n */\n\nimport { gcm as nobleAesGcm } from '@noble/ciphers/aes';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages\n const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\\/13\\.\\d(\\.\\d)* Safari/) ||\n navigator.userAgent.match(/Version\\/(13|14)\\.\\d(\\.\\d)* Mobile\\/\\S* Safari/);\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && !pt.length) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n try {\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n } catch (e) {\n if (e.name === 'OperationError') {\n throw new Error('Authentication tag mismatch');\n }\n }\n }\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n },\n\n decrypt: async function(ct, iv, adata) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","// Operations are not constant time, but we try and limit timing leakage where we can\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport function uint8ArrayToBigInt(bytes: Uint8Array) {\n const hexAlphabet = '0123456789ABCDEF';\n let s = '';\n bytes.forEach(v => {\n s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];\n });\n return BigInt('0x0' + s);\n}\n\nexport function mod(a: bigint, m: bigint) {\n const reduced = a % m;\n return reduced < _0n ? reduced + m : reduced;\n}\n\n/**\n * Compute modular exponentiation using square and multiply\n * @param {BigInt} a - Base\n * @param {BigInt} e - Exponent\n * @param {BigInt} n - Modulo\n * @returns {BigInt} b ** e mod n.\n */\nexport function modExp(b: bigint, e: bigint, n: bigint) {\n if (n === _0n) throw Error('Modulo cannot be zero');\n if (n === _1n) return BigInt(0);\n if (e < _0n) throw Error('Unsopported negative exponent');\n\n let exp = e;\n let x = b;\n\n x %= n;\n let r = BigInt(1);\n while (exp > _0n) {\n const lsb = exp & _1n;\n exp >>= _1n; // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n; // Square\n }\n return r;\n}\n\n\nfunction abs(x: bigint) {\n return x >= _0n ? x : -x;\n}\n\n/**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a and b, compute (x, y) such that ax + by = gdc(a, b).\n * Negative numbers are also supported.\n * @param {BigInt} a - First operand\n * @param {BigInt} b - Second operand\n * @returns {{ gcd, x, y: bigint }}\n */\nfunction _egcd(aInput: bigint, bInput: bigint) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n // Deal with negative numbers: run algo over absolute values,\n // and \"move\" the sign to the returned x and/or y.\n // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers\n let a = abs(aInput);\n let b = abs(bInput);\n const aNegated = aInput < _0n;\n const bNegated = bInput < _0n;\n\n while (b !== _0n) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: aNegated ? -xPrev : xPrev,\n y: bNegated ? -yPrev : yPrev,\n gcd: a\n };\n}\n\n/**\n * Compute the inverse of `a` modulo `n`\n * Note: `a` and and `n` must be relatively prime\n * @param {BigInt} a\n * @param {BigInt} n - Modulo\n * @returns {BigInt} x such that a*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\nexport function modInv(a: bigint, n: bigint) {\n const { gcd, x } = _egcd(a, n);\n if (gcd !== _1n) {\n throw new Error('Inverse does not exist');\n }\n return mod(x + n, n);\n}\n\n/**\n * Compute greatest common divisor between this and n\n * @param {BigInt} aInput - Operand\n * @param {BigInt} bInput - Operand\n * @returns {BigInt} gcd\n */\nexport function gcd(aInput: bigint, bInput: bigint) {\n let a = aInput;\n let b = bInput;\n while (b !== _0n) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\n/**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\nexport function bigIntToNumber(x: bigint) {\n const number = Number(x);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n}\n\n/**\n * Get value of i-th bit\n * @param {BigInt} x\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\nexport function getBit(x:bigint, i: number) {\n const bit = (x >> BigInt(i)) & _1n;\n return bit === _0n ? 0 : 1;\n}\n\n/**\n * Compute bit length\n */\nexport function bitLength(x: bigint) {\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = x < _0n ? BigInt(-1) : _0n;\n let bitlen = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _1n) !== target) {\n bitlen++;\n }\n return bitlen;\n}\n\n/**\n * Compute byte length\n */\nexport function byteLength(x: bigint) {\n const target = x < _0n ? BigInt(-1) : _0n;\n const _8n = BigInt(8);\n let len = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _8n) !== target) {\n len++;\n }\n return len;\n}\n\n/**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\nexport function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = x.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? length - rawLength : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n */\nimport { byteLength, mod, uint8ArrayToBigInt } from './biginteger';\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto?.webcrypto;\n if (webcrypto?.getRandomValues) {\n const buf = new Uint8Array(length);\n return webcrypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n}\n\n/**\n * Create a secure random BigInt that is greater than or equal to min and less than max.\n * @param {bigint} min - Lower bound, included\n * @param {bigint} max - Upper bound, excluded\n * @returns {bigint} Random BigInt.\n * @async\n */\nexport function getRandomBigInteger(min, max) {\n if (max < min) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max - min;\n const bytes = byteLength(modulus);\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));\n return mod(r, modulus) + min;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n */\nimport { bigIntToNumber, bitLength, gcd, getBit, mod, modExp } from '../biginteger';\nimport { getRandomBigInteger } from '../random';\n\nconst _1n = BigInt(1);\n\n/**\n * Generate a probably prime random number\n * @param bits - Bit length of the prime\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function randomProbablePrime(bits: number, e: bigint, k: number) {\n const _30n = BigInt(30);\n const min = _1n << BigInt(bits - 1);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n let n = getRandomBigInteger(min, min << _1n);\n let i = bigIntToNumber(mod(n, _30n));\n\n do {\n n += BigInt(adds[i]);\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (bitLength(n) > bits) {\n n = mod(n, min << _1n); n += min;\n i = bigIntToNumber(mod(n, _30n));\n }\n } while (!isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param n - Number to test\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function isProbablePrime(n: bigint, e: bigint, k: number) {\n if (e && gcd(n - _1n, e) !== _1n) {\n return false;\n }\n if (!divisionTest(n)) {\n return false;\n }\n if (!fermat(n)) {\n return false;\n }\n if (!millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param n - Number to test\n * @param b - Optional Fermat test base\n */\nexport function fermat(n: bigint, b = BigInt(2)) {\n return modExp(b, n - _1n, n) === _1n;\n}\n\nexport function divisionTest(n: bigint) {\n const _0n = BigInt(0);\n return smallPrimes.every(m => mod(n, m) !== _0n);\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n].map(n => BigInt(n));\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param n - Number to test\n * @param k - Optional number of iterations of Miller-Rabin test\n * @param rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport function millerRabin(n: bigint, k: number, rand?: () => bigint) {\n const len = bitLength(n);\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n - _1n; // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!getBit(n1, s)) { s++; }\n const d = n >> BigInt(s);\n\n for (; k > 0; k--) {\n const a = rand ? rand() : getRandomBigInteger(BigInt(2), n1);\n\n let x = modExp(a, d, n);\n if (x === _1n || x === n1) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = mod(x * x, n);\n\n if (x === _1n) {\n return false;\n }\n if (x === n1) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n */\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\nimport { bigIntToNumber, bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\nimport hash from '../hash';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst _1n = BigInt(1);\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (hash.getHashByteLength(hashAlgo) >= n.length) {\n // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error\n // e.g. if a 512-bit RSA key is used with a SHA-512 digest.\n // The size limit is actually slightly different but here we only care about throwing\n // on common key sizes.\n throw new Error('Digest size cannot exceed key modulus size');\n }\n\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n e = BigInt(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return jwkToPrivate(jwk, e);\n } else if (util.getNodeCrypto()) {\n const opts = {\n modulusLength: bits,\n publicExponent: bigIntToNumber(e),\n publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },\n privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }\n };\n const jwk = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {\n if (err) {\n reject(err);\n } else {\n resolve(jwkPrivateKey);\n }\n });\n });\n return jwkToPrivate(jwk, e);\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = randomProbablePrime(bits - (bits >> 1), e, 40);\n p = randomProbablePrime(bits >> 1, e, 40);\n n = p * q;\n } while (bitLength(n) !== bits);\n\n const phi = (p - _1n) * (q - _1n);\n\n if (q < p) {\n [p, q] = [q, p];\n }\n\n return {\n n: bigIntToUint8Array(n),\n e: bigIntToUint8Array(e),\n d: bigIntToUint8Array(modInv(e, phi)),\n p: bigIntToUint8Array(p),\n q: bigIntToUint8Array(q),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: bigIntToUint8Array(modInv(p, q))\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n n = uint8ArrayToBigInt(n);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n\n // expect pq = n\n if ((p * q) !== n) {\n return false;\n }\n\n const _2n = BigInt(2);\n // expect p*u = 1 mod q\n u = uint8ArrayToBigInt(u);\n if (mod(p * u, q) !== BigInt(1)) {\n return false;\n }\n\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));\n const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r * d * e;\n\n const areInverses = mod(rde, p - _1n) === r && mod(rde, q - _1n) === r;\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n n = uint8ArrayToBigInt(n);\n const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));\n d = uint8ArrayToBigInt(d);\n return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n\n const jwk = await privateToJWK(n, e, d, p, q, u);\n return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n n = uint8ArrayToBigInt(n);\n s = uint8ArrayToBigInt(s);\n e = uint8ArrayToBigInt(e);\n if (s >= n) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));\n const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1' };\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n\n try {\n return verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n n = uint8ArrayToBigInt(n);\n data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));\n e = uint8ArrayToBigInt(e);\n if (data >= n) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n data = uint8ArrayToBigInt(data);\n n = uint8ArrayToBigInt(n);\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n u = uint8ArrayToBigInt(u);\n if (data >= n) {\n throw new Error('Data too large.');\n }\n const dq = mod(d, q - _1n); // d mod (q-1)\n const dp = mod(d, p - _1n); // d mod (p-1)\n\n const unblinder = getRandomBigInteger(BigInt(2), n);\n const blinder = modExp(modInv(unblinder, n), e, n);\n data = mod(data * blinder, n);\n\n const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p\n const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q\n const h = mod(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h * p + mp; // result < n due to relations above\n\n result = mod(result * unblinder, n);\n\n return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const pNum = uint8ArrayToBigInt(p);\n const qNum = uint8ArrayToBigInt(q);\n const dNum = uint8ArrayToBigInt(d);\n\n let dq = mod(dNum, qNum - _1n); // d mod (q-1)\n let dp = mod(dNum, pNum - _1n); // d mod (p-1)\n dp = bigIntToUint8Array(dp);\n dq = bigIntToUint8Array(dq);\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n\n/** Convert JWK private key to OpenPGP private key params */\nfunction jwkToPrivate(jwk, e) {\n return {\n n: b64ToUint8Array(jwk.n),\n e: bigIntToUint8Array(e),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n */\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\nconst _1n = BigInt(1);\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n const padded = emeEncode(data, byteLength(p));\n const m = uint8ArrayToBigInt(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = getRandomBigInteger(_1n, p - _1n);\n return {\n c1: bigIntToUint8Array(modExp(g, k, p)),\n c2: bigIntToUint8Array(mod(modExp(y, k, p) * m, p))\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n c1 = uint8ArrayToBigInt(c1);\n c2 = uint8ArrayToBigInt(c2);\n p = uint8ArrayToBigInt(p);\n x = uint8ArrayToBigInt(x);\n\n const padded = mod(modInv(modExp(c1, x, p), p) * c2, p);\n return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = BigInt(bitLength(p));\n const _1023n = BigInt(1023);\n if (pSize < _1023n) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (modExp(g, p - _1n, p) !== _1n) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n let i = BigInt(1);\n const _2n = BigInt(2);\n const threshold = _2n << BigInt(17); // we want order > threshold\n while (i < threshold) {\n res = mod(res * g, p);\n if (res === _1n) {\n return false;\n }\n i++;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const r = getRandomBigInteger(_2n << (pSize - _1n), _2n << pSize); // draw r of same size as p-1\n const rqx = (p - _1n) * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined;\n","import { crypto } from './crypto.js';\n\n'use strict';\nconst nacl = {};\nexport default nacl;\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n if (crypto && crypto.getRandomValues) {\n // Browsers and Node v16+\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n})();\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nconst knownOIDs = {\n '2a8648ce3d030107': enums.curve.nistP256,\n '2b81040022': enums.curve.nistP384,\n '2b81040023': enums.curve.nistP521,\n '2b8104000a': enums.curve.secp256k1,\n '2b06010401da470f01': enums.curve.ed25519Legacy,\n '2b060104019755010501': enums.curve.curve25519Legacy,\n '2b2403030208010107': enums.curve.brainpoolP256r1,\n '2b240303020801010b': enums.curve.brainpoolP384r1,\n '2b240303020801010d': enums.curve.brainpoolP512r1\n};\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {enums.curve} String with the canonical name of the curve\n * @throws if unknown\n */\n getName() {\n const name = knownOIDs[this.toHex()];\n if (!name) {\n throw new Error('Unknown curve object identifier.');\n }\n\n return name;\n }\n}\n\nexport default OID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\n// unknown packet types are handled differently depending on the packet criticality\nexport class UnknownPacketError extends UnsupportedError {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnknownPacketError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n */\n\nimport ed25519 from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\nimport { b64ToUint8Array, uint8ArrayToB64 } from '../../../encoding/base64';\n\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n A: new Uint8Array(b64ToUint8Array(publicKey.x)),\n seed: b64ToUint8Array(privateKey.d, true)\n };\n } catch (err) {\n if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux\n throw err;\n }\n const seed = getRandomBytes(getPayloadSize(algo));\n const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const seed = ed448.utils.randomPrivateKey();\n const A = ed448.getPublicKey(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = privateKeyToJWK(algo, publicKey, privateKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);\n\n const signature = new Uint8Array(\n await webCrypto.sign('Ed25519', key, hashed)\n );\n\n return { RS: signature };\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = ed25519.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const signature = ed448.sign(hashed, privateKey);\n return { RS: signature };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = publicKeyToJWK(algo, publicKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);\n const verified = await webCrypto.verify('Ed25519', key, RS, hashed);\n return verified;\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n return ed25519.sign.detached.verify(hashed, RS, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n return ed448.verify(RS, hashed, publicKey);\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented\n */\n const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n\n const publicKey = ed448.getPublicKey(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n default:\n return false;\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return 32;\n\n case enums.publicKey.ed448:\n return 57;\n\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n case enums.publicKey.ed448:\n return enums.hash.sha512;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n\nconst publicKeyToJWK = (algo, publicKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = {\n kty: 'OKP',\n crv: 'Ed25519',\n x: uint8ArrayToB64(publicKey, true),\n ext: true\n };\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n\nconst privateKeyToJWK = (algo, publicKey, privateKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = publicKeyToJWK(algo, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n */\n\nimport { aeskw as nobleAesKW } from '@noble/ciphers/aes';\nimport { getCipherParams } from './cipher';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n/**\n * AES key wrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} dataToWrap\n * @returns {Uint8Array} wrapped key\n */\nexport async function wrap(algo, key, dataToWrap) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n try {\n const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);\n // Import data as HMAC key, as it has no key length requirements\n const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });\n return new Uint8Array(wrapped);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n\n return nobleAesKW(key).encrypt(dataToWrap);\n}\n\n/**\n * AES key unwrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} wrappedData\n * @returns {Uint8Array} unwrapped data\n */\nexport async function unwrap(algo, key, wrappedData) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let wrappingKey;\n try {\n wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n return nobleAesKW(key).decrypt(wrappedData);\n }\n\n try {\n const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));\n } catch (err) {\n if (err.name === 'OperationError') {\n throw new Error('Key Data Integrity failed');\n }\n throw err;\n }\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n\nexport default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport x25519 from '@openpgp/tweetnacl';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport computeHKDF from '../../hkdf';\nimport { getCipherParams } from '../../cipher';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519'),\n x448: util.encodeUTF8('OpenPGP X448')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = x25519.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const k = x448.utils.randomPrivateKey();\n const A = x448.getPublicKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = x25519.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const publicKey = x448.getPublicKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.x25519:\n return 32;\n\n case enums.publicKey.x448:\n return 56;\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Generate shared secret and ephemeral public key for encryption\n * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret\n * @async\n */\nexport async function generateEphemeralEncryptionMaterial(algo, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo));\n const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const { publicKey: ephemeralPublicKey } = x25519.box.keyPair.fromSecretKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const ephemeralSecretKey = x448.utils.randomPrivateKey();\n const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * x25519 and x448 produce an all-zero value when given as input a point with small order.\n * This does not lead to a security issue in the context of ECDH, but it is still unexpected,\n * hence we throw.\n * @param {Uint8Array} sharedSecret\n */\nfunction assertNonZeroArray(sharedSecret) {\n let acc = 0;\n for (let i = 0; i < sharedSecret.length; i++) {\n acc |= sharedSecret[i];\n }\n if (acc === 0) {\n throw new Error('Unexpected low order point');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n */\nimport nacl from '@openpgp/tweetnacl';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { UnsupportedError } from '../../../packet/packet';\nimport { generate as eddsaGenerate } from './eddsa';\nimport { generate as ecdhXGenerate } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n [enums.curve.nistP256]: 'P-256',\n [enums.curve.nistP384]: 'P-384',\n [enums.curve.nistP521]: 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,\n [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n [enums.curve.nistP256]: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.nistP256],\n web: webCurves[enums.curve.nistP256],\n payloadSize: 32,\n sharedSize: 256,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP384]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.nistP384],\n web: webCurves[enums.curve.nistP384],\n payloadSize: 48,\n sharedSize: 384,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP521]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.nistP521],\n web: webCurves[enums.curve.nistP521],\n payloadSize: 66,\n sharedSize: 528,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.secp256k1]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.secp256k1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.ed25519Legacy]: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.curve25519Legacy]: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.brainpoolP256r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.brainpoolP256r1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP384r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.brainpoolP384r1],\n payloadSize: 48,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP512r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.brainpoolP512r1],\n payloadSize: 64,\n wireFormatLeadingByte: 0x04\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName) {\n try {\n this.name = oidOrName instanceof OID ?\n oidOrName.getName() :\n enums.write(enums.curve,oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n const params = curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node;\n this.web = params.web;\n this.payloadSize = params.payloadSize;\n this.sharedSize = params.sharedSize;\n this.wireFormatLeadingByte = params.wireFormatLeadingByte;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === enums.curve.curve25519Legacy) {\n this.type = 'curve25519Legacy';\n } else if (this.name === enums.curve.ed25519Legacy) {\n this.type = 'ed25519Legacy';\n }\n }\n\n async genKeyPair() {\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name, this.wireFormatLeadingByte);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n return jsGenKeyPair(this.name);\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519Legacy': {\n // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3\n const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);\n const privateKey = k.slice().reverse();\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n case 'ed25519Legacy': {\n const { seed: privateKey, A } = await eddsaGenerate(enums.publicKey.ed25519);\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n default:\n return jsGenKeyPair(this.name);\n }\n }\n}\n\nasync function generate(curveName) {\n const curve = new CurveWithOID(curveName);\n const { oid, hash, cipher } = curve;\n const keyPair = await curve.genKeyPair();\n return {\n oid,\n Q: keyPair.publicKey,\n secret: util.leftPad(keyPair.privateKey, curve.payloadSize),\n hash,\n cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[oid.getName()].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n [enums.curve.nistP256]: true,\n [enums.curve.nistP384]: true,\n [enums.curve.nistP521]: true,\n [enums.curve.secp256k1]: true,\n [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,\n [enums.curve.brainpoolP256r1]: true,\n [enums.curve.brainpoolP384r1]: true,\n [enums.curve.brainpoolP512r1]: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === enums.curve.curve25519Legacy) {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n /*\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = nobleCurve.getPublicKey(d, false);\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check whether the public point has a valid encoding.\n * NB: this function does not check e.g. whether the point belongs to the curve.\n */\nfunction checkPublicPointEnconding(curve, V) {\n const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;\n\n const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;\n\n if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {\n throw new Error('Invalid point encoding');\n }\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\nasync function jsGenKeyPair(name) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n const privateKey = nobleCurve.utils.randomPrivateKey();\n const publicKey = nobleCurve.getPublicKey(privateKey, false);\n return { publicKey, privateKey };\n}\n\nasync function webGenKeyPair(name, wireFormatLeadingByte) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk, wireFormatLeadingByte) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = wireFormatLeadingByte;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams, nodeCurves, checkPublicPointEnconding } from './oid_curves';\nimport { bigIntToUint8Array } from '../../biginteger';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web':\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n case 'node':\n return nodeSign(curve, hashAlgo, message, privateKey);\n }\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });\n return {\n r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),\n s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)\n };\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n // See https://github.com/openpgpjs/openpgpjs/pull/948.\n // NB: the impact was more likely limited to Brainpool curves, since thanks\n // to WebCrypto availability, NIST curve should not have been affected.\n // Similarly, secp256k1 should have been used rarely enough.\n // However, we implement the fix for all curves, since it's only needed in case of\n // verification failure, which is unexpected, hence a minor slowdown is acceptable.\n const tryFallbackVerificationForOldBug = async () => (\n hashed[0] === 0 ?\n jsVerify(curve, signature, hashed.subarray(1), publicKey) :\n false\n );\n\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node': {\n const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n }\n }\n }\n\n const verified = await jsVerify(curve, signature, hashed, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n // eslint-disable-next-line @typescript-eslint/return-await\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Fallback javascript implementation of ECDSA verification.\n * To be used if no native implementation is available for the given curve/operation.\n */\nasync function jsVerify(curve, signature, hashed, publicKey) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, privateKey) {\n // JWT encoding cannot be used for now, as Brainpool curves are not supported\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n privateKey: nodeBuffer.from(privateKey)\n });\n\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n\n const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));\n const len = curve.payloadSize;\n\n return {\n r: signature.subarray(0, len),\n s: signature.subarray(len, len << 1)\n };\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { publicKey: derPublicKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n publicKey: nodeBuffer.from(publicKey)\n });\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n\n const signature = util.concatUint8Array([r, s]);\n\n try {\n return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);\n } catch (err) {\n return false;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n */\n\nimport nacl from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { CurveWithOID, checkPublicPointEnconding } from './oid_curves';\nimport { sign as eddsaSign, verify as eddsaVerify } from './eddsa';\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const { RS: signature } = await eddsaSign(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const RS = util.concatUint8Array([r, s]);\n return eddsaVerify(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { getCipherParams } from '../../cipher';\nimport { generateEphemeralEncryptionMaterial as ecdhXGenerateEphemeralEncryptionMaterial, recomputeSharedSecret as ecdhXRecomputeSharedSecret } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519Legacy': {\n const { sharedSecret: sharedKey, ephemeralPublicKey } = await ecdhXGenerateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));\n const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n return jsPublicEphemeralKey(curve, Q);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n default:\n return jsPublicEphemeralKey(curve, Q);\n\n }\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = await aesKW.wrap(kdfParams.cipher, Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519Legacy': {\n const secretKey = d.slice().reverse();\n const sharedKey = await ecdhXRecomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n return jsPrivateEphemeralKey(curve, V, d);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n default:\n return jsPrivateEphemeralKey(curve, V, d);\n }\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n checkPublicPointEnconding(curve, V);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(await aesKW.unwrap(kdfParams.cipher, Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\nasync function jsPrivateEphemeralKey(curve, V, d) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { secretKey: d, sharedKey };\n}\n\nasync function jsPublicEphemeralKey(curve, Q) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n const { publicKey: V, privateKey: v } = await curve.genKeyPair();\n\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { publicKey: V, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: sender\n },\n privateKey,\n curve.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const _0n = BigInt(0);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n x = uint8ArrayToBigInt(x);\n\n let k;\n let r;\n let s;\n let t;\n g = mod(g, p);\n x = mod(x, q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = getRandomBigInteger(_1n, q); // returns in [1, q-1]\n r = mod(modExp(g, k, p), q); // (g**k mod p) mod q\n if (r === _0n) {\n continue;\n }\n const xr = mod(x * r, q);\n t = mod(h + xr, q); // H(m) + x*r mod q\n s = mod(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q\n if (s === _0n) {\n continue;\n }\n break;\n }\n return {\n r: bigIntToUint8Array(r, 'be', byteLength(p)),\n s: bigIntToUint8Array(s, 'be', byteLength(p))\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n r = uint8ArrayToBigInt(r);\n s = uint8ArrayToBigInt(s);\n\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n if (r <= _0n || r >= q ||\n s <= _0n || s >= q) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n const w = modInv(s, q); // s**-1 mod q\n if (w === _0n) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = mod(g, p);\n y = mod(y, p);\n const u1 = mod(h * w, q); // H(m) * w mod q\n const u2 = mod(r * w, q); // r * w mod q\n const t1 = modExp(g, u1, p); // g**u1 mod p\n const t2 = modExp(y, u2, p); // y**u2 mod p\n const v = mod(mod(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q\n return v === r;\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (mod(p - _1n, q) !== _0n) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (modExp(g, q, p) !== _1n) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = BigInt(bitLength(q));\n const _150n = BigInt(150);\n if (qSize < _150n || !isProbablePrime(q, null, 32)) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const _2n = BigInt(2);\n const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q\n const rqx = q * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n */\n\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { read, signatureParams: { s } };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n // If the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature\n // verification: if the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n // Algorithm-Specific Fields for Ed448 signatures:\n // - 114 octets of the native signature\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo);\n const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length;\n return { read, signatureParams: { RS } };\n }\n\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal:\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport { getCipherParams } from './cipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n if (symmetricAlgo && !util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 and X448 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (C.algorithm !== null && !util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const payloadSize = getCurvePayloadSize(algo);\n const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const payloadSize = getCurvePayloadSize(algo);\n const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 or X448 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const pointSize = getCurvePayloadSize(algo);\n const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([\n enums.publicKey.ed25519,\n enums.publicKey.x25519,\n enums.publicKey.ed448,\n enums.publicKey.x448\n ]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipherParams(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipherParams(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get encoded secret size for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getCurvePayloadSize(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh:\n case enums.publicKey.eddsaLegacy:\n return new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPayloadSize(algo);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.getPayloadSize(algo);\n default:\n throw new Error('Unknown elliptic algo');\n }\n}\n\n/**\n * Get preferred signing hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n\n\nexport { getCipherParams };\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","import defaultConfig from '../../config';\nimport enums from '../../enums';\nimport util from '../../util';\nimport crypto from '../../crypto';\n\nconst ARGON2_TYPE = 0x02; // id\nconst ARGON2_VERSION = 0x13;\nconst ARGON2_SALT_SIZE = 16;\n\nexport class Argon2OutOfMemoryError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Argon2OutOfMemoryError);\n }\n\n this.name = 'Argon2OutOfMemoryError';\n }\n}\n\n// cache argon wasm module\nlet loadArgonWasmModule;\nlet argon2Promise;\n// reload wasm module above this treshold, to deallocated used memory\nconst ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;\n\nclass Argon2S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n const { passes, parallelism, memoryExponent } = config.s2kArgon2Params;\n\n this.type = 'argon2';\n /**\n * 16 bytes of salt\n * @type {Uint8Array}\n */\n this.salt = null;\n /**\n * number of passes\n * @type {Integer}\n */\n this.t = passes;\n /**\n * degree of parallelism (lanes)\n * @type {Integer}\n */\n this.p = parallelism;\n /**\n * exponent indicating memory size\n * @type {Integer}\n */\n this.encodedM = memoryExponent;\n }\n\n generateSalt() {\n this.salt = crypto.random.getRandomBytes(ARGON2_SALT_SIZE);\n }\n\n /**\n * Parsing function for argon2 string-to-key specifier.\n * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n\n this.salt = bytes.subarray(i, i + 16);\n i += 16;\n\n this.t = bytes[i++];\n this.p = bytes[i++];\n this.encodedM = bytes[i++]; // memory size exponent, one-octect\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n const arr = [\n new Uint8Array([enums.write(enums.s2k, this.type)]),\n this.salt,\n new Uint8Array([this.t, this.p, this.encodedM])\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to `keySize`\n * @throws {Argon2OutOfMemoryError|Errors}\n * @async\n */\n async produceKey(passphrase, keySize) {\n const decodedM = 2 << (this.encodedM - 1);\n\n try {\n // on first load, the argon2 lib is imported and the WASM module is initialized.\n // the two steps need to be atomic to avoid race conditions causing multiple wasm modules\n // being loaded when `argon2Promise` is not initialized.\n loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;\n argon2Promise = argon2Promise || loadArgonWasmModule();\n\n // important to keep local ref to argon2 in case the module is reloaded by another instance\n const argon2 = await argon2Promise;\n\n const passwordBytes = util.encodeUTF8(passphrase);\n const hash = argon2({\n version: ARGON2_VERSION,\n type: ARGON2_TYPE,\n password: passwordBytes,\n salt: this.salt,\n tagLength: keySize,\n memorySize: decodedM,\n parallelism: this.p,\n passes: this.t\n });\n\n // a lot of memory was used, reload to deallocate\n if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {\n // it will be awaited if needed at the next `produceKey` invocation\n argon2Promise = loadArgonWasmModule();\n argon2Promise.catch(() => {});\n }\n return hash;\n } catch (e) {\n if (e.message && (\n e.message.includes('Unable to grow instance memory') || // Chrome\n e.message.includes('failed to grow memory') || // Firefox\n e.message.includes('WebAssembly.Memory.grow') || // Safari\n e.message.includes('Out of memory') // Safari iOS\n )) {\n throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');\n } else {\n throw e;\n }\n }\n }\n}\n\nexport default Argon2S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n */\n\nimport defaultConfig from '../../config';\nimport crypto from '../../crypto';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\nimport util from '../../util';\n\nclass GenericS2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(s2kType, config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = enums.read(enums.s2k, s2kType);\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n generateSalt() {\n switch (this.type) {\n case 'salted':\n case 'iterated':\n this.salt = crypto.random.getRandomBytes(8);\n }\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default GenericS2K;\n","import defaultConfig from '../../config';\nimport Argon2S2K, { Argon2OutOfMemoryError } from './argon2';\nimport GenericS2K from './generic';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\n\nconst allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);\n\n/**\n * Instantiate a new S2K instance of the given type\n * @param {module:enums.s2k} type\n * @oaram {Object} [config]\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromType(type, config = defaultConfig) {\n switch (type) {\n case enums.s2k.argon2:\n return new Argon2S2K(config);\n case enums.s2k.iterated:\n case enums.s2k.gnu:\n case enums.s2k.salted:\n case enums.s2k.simple:\n return new GenericS2K(type, config);\n default:\n throw new UnsupportedError('Unsupported S2K type');\n }\n}\n\n/**\n * Instantiate a new S2K instance based on the config settings\n * @oaram {Object} config\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromConfig(config) {\n const { s2kType } = config;\n\n if (!allowedS2KTypesForEncryption.has(s2kType)) {\n throw new Error('The provided `config.s2kType` value is not allowed');\n }\n\n return newS2KFromType(s2kType, config);\n}\n\nexport { Argon2OutOfMemoryError };\n","import { createRequire } from 'module';\nvar require = createRequire('/');\n// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\n// Mediocre shim\nvar Worker;\nvar workerAdd = \";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global\";\ntry {\n Worker = require('worker_threads').Worker;\n}\ncatch (e) {\n}\nvar wk = Worker ? function (c, _, msg, transfer, cb) {\n var done = false;\n var w = new Worker(c + workerAdd, { eval: true })\n .on('error', function (e) { return cb(e, null); })\n .on('message', function (m) { return cb(null, m); })\n .on('exit', function (c) {\n if (c && !done)\n cb(new Error('exited with code ' + c), null);\n });\n w.postMessage(msg, transfer);\n w.terminate = function () {\n done = true;\n return Worker.prototype.terminate.call(w);\n };\n return w;\n} : function (_, __, ___, ____, cb) {\n setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); });\n var NOP = function () { };\n return {\n terminate: NOP,\n postMessage: NOP\n };\n};\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n ,\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && st.f && !st.l))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[pos >> 3] = lst;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if (d[1] & 32)\n err(6, 'invalid zlib data: preset dictionaries not supported');\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n err(6, 'invalid gzip data');\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (val instanceof u8)\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n err(8);\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n err(8);\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this_1.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this_1.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_3 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// A salt notation is used to randomize signatures.\n// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks\n// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).\n// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.\n// some chosen-prefix attacks.\n// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.\nconst SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuerKeyID,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.unknownSubpackets = [];\n this.signedHashValue = null;\n this.salt = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n this.preferredCipherSuites = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes, config = defaultConfig) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n // Only for v6 signatures, a variable-length field containing:\n if (this.version === 6) {\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[i++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(i, i + saltLength);\n i += saltLength;\n }\n\n const signatureMaterial = bytes.subarray(i, bytes.length);\n const { read, signatureParams } = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);\n if (read < signatureMaterial.length) {\n throw new Error('Error reading MPIs');\n }\n this.params = signatureParams;\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n if (this.version === 6) {\n arr.push(new Uint8Array([this.salt.length]));\n arr.push(this.salt);\n }\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false, config) {\n this.version = key.version;\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n // add randomness to the signature\n if (this.version === 6) {\n const saltLength = saltLengthForHash(this.hashAlgorithm);\n if (this.salt === null) {\n this.salt = crypto.random.getRandomBytes(saltLength);\n } else if (saltLength !== this.salt.length) {\n throw new Error('Provided salt does not have the required length');\n }\n } else if (config.nonDeterministicSignaturesViaNotation) {\n const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));\n // since re-signing the same object is not supported, it's not expected to have multiple salt notations,\n // but we guard against it as a sanity check\n if (saltNotations.length === 0) {\n const saltValue = crypto.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm));\n this.rawNotations.push({\n name: SALT_NOTATION_NAME,\n value: saltValue,\n humanReadable: false,\n critical: false\n });\n } else {\n throw new Error('Unexpected existing salt notation');\n }\n }\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n if (this.preferredCipherSuites !== null) {\n bytes = new Uint8Array([].concat(...this.preferredCipherSuites));\n arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {\n return writeSubPacket(type, critical, body);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n // Signature subpackets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n mypos++;\n\n if (!hashed) {\n this.unhashedSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuerKeyID:\n // Issuer\n if (this.version === 4) {\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n } else if (hashed) {\n // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,\n // since the Issuer Fingerprint subpacket is to be used instead.\n // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.\n // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,\n // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)\n // issuerFingerprint.\n // If the packet is hashed, then we reject the signature, to avoid verifying data different from\n // what was parsed.\n throw new Error('Unexpected Issuer Key ID subpacket');\n }\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion >= 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCipherSuites:\n // Preferred AEAD Cipher Suites\n this.preferredCipherSuites = [];\n for (let i = mypos; i < bytes.length; i += 2) {\n this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);\n }\n break;\n default:\n this.unknownSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n break;\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n const subpacketLengthBytes = this.version === 6 ? 4 : 2;\n\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));\n\n let i = subpacketLengthBytes;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {\n // avoid hashing unexpected salt size\n throw new Error('Signature salt does not have the expected length');\n }\n\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.unknownSubpackets.forEach(({ type, critical }) => {\n if (critical) {\n throw new Error(`Unknown critical signature subpacket type ${type}`);\n }\n });\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n\n/**\n * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}\n * @param {enums.hash} hashAlgorithm - Hash algorithm.\n * @returns {Integer} Salt length.\n * @private\n */\nfunction saltLengthForHash(hashAlgorithm) {\n switch (hashAlgorithm) {\n case enums.hash.sha256: return 16;\n case enums.hash.sha384: return 24;\n case enums.hash.sha512: return 32;\n case enums.hash.sha224: return 16;\n case enums.hash.sha3_256: return 16;\n case enums.hash.sha3_512: return 32;\n default: throw new Error('Unsupported hash function');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n static fromSignaturePacket(signaturePacket, isLast) {\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.version = signaturePacket.version === 6 ? 6 : 3;\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n onePassSig.salt = signaturePacket.salt; // v6 only\n onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only\n\n onePassSig.flags = isLast ? 1 : 0;\n return onePassSig;\n }\n\n constructor() {\n /** A one-octet version number. The current versions are 3 and 6. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** Only for v6, a variable-length field containing the salt. */\n this.salt = null;\n /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */\n this.issuerFingerprint = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current versions are 3 or 6.\n this.version = bytes[mypos++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n if (this.version === 6) {\n // Only for v6 signatures, a variable-length field containing:\n\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[mypos++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(mypos, mypos + saltLength);\n mypos += saltLength;\n\n // Only for v6 packets, 32 octets of the fingerprint of the signing key.\n this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);\n mypos += 32;\n this.issuerKeyID = new KeyID();\n // For v6 the Key ID is the high-order 64 bits of the fingerprint.\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n }\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const arr = [new Uint8Array([\n this.version,\n this.signatureType,\n this.hashAlgorithm,\n this.publicKeyAlgorithm\n ])];\n if (this.version === 6) {\n arr.push(\n new Uint8Array([this.salt.length]),\n this.salt,\n this.issuerFingerprint\n );\n } else {\n arr.push(this.issuerKeyID.write());\n }\n arr.push(new Uint8Array([this.flags]));\n return util.concatUint8Array(arr);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||\n (this.version === 3 && correspondingSig.version === 6) ||\n (this.version === 6 && correspondingSig.version !== 6) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError,\n UnknownPacketError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,\n // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.\n // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.\n if (e instanceof UnknownPacketError) {\n if (parsed.tag <= 39) {\n await writer.abort(e);\n } else {\n return;\n }\n }\n\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Inflate, Deflate, Zlib, Unzlib } from 'fflate';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write());\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.\n * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator\n * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor\n * @returns {ReadableStream} compressed or decompressed data\n */\nfunction zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {\n return data => {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(inputData => {\n return new Promise((resolve, reject) => {\n const zlibStream = new ZlibStreamedConstructor();\n zlibStream.ondata = processedData => {\n resolve(processedData);\n };\n try {\n zlibStream.push(inputData, true); // only one chunk to push\n } catch (err) {\n reject(err);\n }\n });\n }));\n }\n\n // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)\n if (compressionStreamInstantiator) {\n try {\n const compressorOrDecompressor = compressionStreamInstantiator();\n return data.pipeThrough(compressorOrDecompressor);\n } catch (err) {\n // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate.\n if (err.name !== 'TypeError') {\n throw err;\n }\n }\n }\n\n // JS fallback\n const inputReader = data.getReader();\n const zlibStream = new ZlibStreamedConstructor();\n\n return new ReadableStream({\n async start(controller) {\n zlibStream.ondata = async (value, isLast) => {\n controller.enqueue(value);\n if (isLast) {\n controller.close();\n }\n };\n\n while (true) {\n const { done, value } = await inputReader.read();\n if (done) {\n zlibStream.push(new Uint8Array(), true);\n return;\n } else if (value.length) {\n zlibStream.push(value);\n }\n }\n }\n });\n };\n}\n\nfunction bzip2Decompress() {\n return async function(data) {\n const { decode: bunzipDecode } = await import('@openpgp/seek-bzip');\n return stream.fromAsync(async () => bunzipDecode(await stream.readToEnd(data)));\n };\n}\n\n/**\n * Get Compression Stream API instatiators if the constructors are implemented.\n * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported\n * (supported formats cannot be determined in advance).\n * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat\n * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}\n */\nconst getCompressionStreamInstantiators = compressionFormat => ({\n compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),\n decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))\n});\n\nconst compress_fns = {\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)\n};\n\nconst decompress_fns = {\n uncompressed: data => data,\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),\n bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n static fromObject({ version, aeadAlgorithm }) {\n if (version !== 1 && version !== 2) {\n throw new Error('Unsupported SEIPD version');\n }\n\n const seip = new SymEncryptedIntegrityProtectedDataPacket();\n seip.version = version;\n if (version === 2) {\n seip.aeadAlgorithm = aeadAlgorithm;\n }\n\n return seip;\n }\n\n constructor() {\n this.version = null;\n\n // The following 4 fields are for V2 only.\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = null;\n this.chunkSizeByte = null;\n this.salt = null;\n\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n this.version = await reader.readByte();\n // - A one-octet version number with value 1 or 2.\n if (this.version !== 1 && this.version !== 2) {\n throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);\n }\n\n if (this.version === 2) {\n // - A one-octet cipher algorithm.\n this.cipherAlgorithm = await reader.readByte();\n // - A one-octet AEAD algorithm.\n this.aeadAlgorithm = await reader.readByte();\n // - A one-octet chunk size.\n this.chunkSizeByte = await reader.readByte();\n // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.\n this.salt = await reader.readBytes(32);\n }\n\n // For V1:\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n // For V2:\n // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.\n // - A final, summary authentication tag for the AEAD mode.\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n if (this.version === 2) {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);\n }\n return util.concat([new Uint8Array([this.version]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n const { blockSize, keySize } = crypto.getCipherParams(sessionKeyAlgorithm);\n if (key.length !== keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n\n if (this.version === 2) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n this.salt = crypto.random.getRandomBytes(32);\n this.chunkSizeByte = config.aeadChunkSizeByte;\n this.encrypted = await runAEAD(this, 'encrypt', key, bytes);\n } else {\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n }\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n if (key.length !== crypto.getCipherParams(sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n\n let packetbytes;\n if (this.version === 2) {\n if (this.cipherAlgorithm !== sessionKeyAlgorithm) {\n // sanity check\n throw new Error('Unexpected session key algorithm');\n }\n packetbytes = await runAEAD(this, 'decrypt', key, encrypted);\n } else {\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n }\n\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n\n/**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\nexport async function runAEAD(packet, fn, key, data) {\n const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;\n const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)\n if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type');\n\n const mode = crypto.getAEADMode(packet.aeadAlgorithm);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;\n const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);\n const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n let iv;\n let ivView;\n if (isSEIPDv2) {\n const { keySize } = crypto.getCipherParams(packet.cipherAlgorithm);\n const { ivLength } = mode;\n const info = new Uint8Array(adataBuffer, 0, 5);\n const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);\n key = derived.subarray(0, keySize);\n iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.\n iv.fill(0, iv.length - 8);\n ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n } else { // AEADEncryptedDataPacket\n iv = packet.iv;\n // ivView is unused in this case\n }\n const modeInstance = await mode(packet.cipherAlgorithm, key);\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n let nonce;\n if (isSEIPDv2) { // SEIPD V2\n nonce = iv;\n } else { // AEADEncryptedDataPacket\n nonce = iv.slice();\n for (let i = 0; i < 8; i++) {\n nonce[iv.length - 8 + i] ^= chunkIndexArray[i];\n }\n }\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);\n cryptedPromise.catch(() => {});\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...)\n cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);\n cryptedPromise.catch(() => {});\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n if (isSEIPDv2) { // SEIPD V2\n ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...)\n } else { // AEADEncryptedDataPacket\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n }\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.ready.catch(() => {});\n await writer.abort(e);\n }\n });\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\nimport { runAEAD } from './sym_encrypted_integrity_protected_data';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await runAEAD(this, 'decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await runAEAD(this, 'encrypt', key, data);\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = null;\n\n // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`\n this.publicKeyID = new KeyID();\n\n // For version 6:\n this.publicKeyVersion = null;\n this.publicKeyFingerprint = null;\n\n // For all versions:\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n static fromObject({\n version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm\n }) {\n const pkesk = new PublicKeyEncryptedSessionKeyPacket();\n\n if (version !== 3 && version !== 6) {\n throw new Error('Unsupported PKESK version');\n }\n\n pkesk.version = version;\n\n if (version === 6) {\n pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;\n pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();\n }\n\n pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();\n pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;\n pkesk.sessionKey = sessionKey;\n pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;\n\n return pkesk;\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let offset = 0;\n this.version = bytes[offset++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n if (this.version === 6) {\n // A one-octet size of the following two fields:\n // - A one octet key version number.\n // - The fingerprint of the public key or subkey to which the session key is encrypted.\n // The size may also be zero.\n const versionAndFingerprintLength = bytes[offset++];\n if (versionAndFingerprintLength) {\n this.publicKeyVersion = bytes[offset++];\n const fingerprintLength = versionAndFingerprintLength - 1;\n this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength;\n if (this.publicKeyVersion >= 5) {\n // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint);\n } else {\n // For v4 The Key ID is the low-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));\n }\n } else {\n // The size may also be zero, and the key version and\n // fingerprint omitted for an \"anonymous recipient\"\n this.publicKeyID = KeyID.wildcard();\n }\n } else {\n offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));\n }\n this.publicKeyAlgorithm = bytes[offset++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));\n if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {\n if (this.version === 3) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n } else if (this.encrypted.C.algorithm !== null) {\n throw new Error('Unexpected cleartext symmetric algorithm');\n }\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version])\n ];\n\n if (this.version === 6) {\n if (this.publicKeyFingerprint !== null) {\n arr.push(new Uint8Array([\n this.publicKeyFingerprint.length + 1,\n this.publicKeyVersion]\n ));\n arr.push(this.publicKeyFingerprint);\n } else {\n arr.push(new Uint8Array([0]));\n }\n } else {\n arr.push(this.publicKeyID.write());\n }\n\n arr.push(\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n );\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a\n // v6 PKESK packet, as it is included in the v2 SEIPD packet.\n const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n if (this.version === 3) {\n // v3 Montgomery curves have cleartext cipher algo\n const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;\n this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;\n\n if (sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n // add checksum\n return util.concatUint8Array([\n new Uint8Array(version === 6 ? [] : [cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = version === 6 ?\n { sessionKeyAlgorithm: null, sessionKey: result } :\n { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && (\n version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return {\n sessionKeyAlgorithm: null,\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 6 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number with value 4, 5 or 6.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following 5 fields.\n offset++;\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version >= 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following field.\n offset++;\n }\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n const s2kType = bytes[offset++];\n this.s2k = newS2KFromType(s2kType);\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version >= 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n const s2k = this.s2k.write();\n if (this.version === 6) {\n const s2kLen = s2k.length;\n const fieldsLen = 3 + s2kLen + this.iv.length;\n bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);\n } else if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n if (this.sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n } else {\n // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v6Keys ? 6 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes, config = defaultConfig) {\n let pos = 0;\n // A one-octet version number (4, 5 or 6).\n this.version = bytes[pos++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version === 4 || this.version === 5 || this.version === 6) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version >= 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (\n this.version === 6 &&\n publicParams.oid && (\n publicParams.oid.getName() === enums.curve.curve25519Legacy ||\n publicParams.oid.getName() === enums.curve.ed25519Legacy\n )\n ) {\n throw new Error('Legacy curve25519 cannot be used with v6 keys');\n }\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version >= 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n const versionOctet = 0x95 + version;\n const lengthOctets = version >= 5 ? 4 : 2;\n return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version >= 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version >= 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError, writeTag } from './packet';\nimport computeHKDF from '../crypto/hkdf';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis\n * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).\n * This value is only relevant to know how to decrypt the key:\n * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.\n * @type {Boolean}\n * @private\n */\n this.isLegacyAEAD = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n /**\n * `true` for keys whose integrity is already confirmed, based on\n * the AEAD encryption mechanism\n * @type {Boolean}\n * @private\n */\n this.usedModernAEAD = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes, config = defaultConfig) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes, config);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n // - Only for a version 6 packet where the secret key material is\n // encrypted (that is, where the previous octet is not zero), a one-\n // octet scalar octet count of the cumulative length of all the\n // following optional string-to-key parameter fields.\n if (this.version === 6 && this.s2kUsage) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n i++;\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n const s2kType = bytes[i++];\n this.s2k = newS2KFromType(s2kType);\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n\n if (this.s2kUsage) {\n // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).\n // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).\n // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always\n // fail if the key was parsed according to the wrong format, since the keys are processed differently.\n // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.\n this.isLegacyAEAD = this.s2kUsage === 253 && (\n this.version === 5 || (this.version === 4 && config.parseAEADEncryptedV4KeysAsLegacy));\n // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)\n // of the same length as the cipher's block size.\n // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the\n // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.\n // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero\n if (this.s2kUsage !== 253 || this.isLegacyAEAD) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipherParams(this.symmetric).blockSize\n );\n this.usedModernAEAD = false;\n } else {\n // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),\n // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which\n // is used as the nonce for the AEAD algorithm.\n this.iv = bytes.subarray(\n i,\n i + crypto.getAEADMode(this.aead).ivLength\n );\n // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.\n this.usedModernAEAD = true;\n }\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n let cleartext;\n if (this.version === 6) {\n cleartext = this.keyMaterial;\n } else {\n cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n }\n try {\n const { read, privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n if (read < cleartext.length) {\n throw new Error('Error reading MPIs');\n }\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n const s2k = this.s2k.write();\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n optionalFieldsArr.push(s2k.length);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...s2k);\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage && this.version !== 6) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = newS2KFromType(enums.s2k.gnu, config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n this.isLegacyAEAD = null;\n this.usedModernAEAD = null;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n\n const { blockSize } = crypto.getCipherParams(this.symmetric);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = config.preferredAEADAlgorithm;\n const mode = crypto.getAEADMode(this.aead);\n this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.\n this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material\n\n const serializedPacketTag = writeTag(this.constructor.tag);\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n\n const modeInstance = await mode(this.symmetric, key);\n this.iv = this.isLegacyAEAD ? crypto.random.getRandomBytes(blockSize) : crypto.random.getRandomBytes(mode.ivLength);\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);\n } else {\n this.s2kUsage = 254;\n this.usedModernAEAD = false;\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(\n this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n this.aead = null;\n this.symmetric = null;\n this.isLegacyAEAD = null;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n if (this.usedModernAEAD) {\n // key integrity confirmed by successful AEAD decryption\n return;\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (this.version === 6 && (\n (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||\n this.algorithm === enums.publicKey.eddsaLegacy\n )) {\n throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);\n }\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\n/**\n * Derive encryption key\n * @param {Number} keyVersion - key derivation differs for v5 keys\n * @param {module:type/s2k} s2k\n * @param {String} passphrase\n * @param {module:enums.symmetric} cipherAlgo\n * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)\n * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)\n * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)\n * @returns encryption key\n */\nasync function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) {\n if (s2k.type === 'argon2' && !aeadMode) {\n throw new Error('Using Argon2 S2K without AEAD is not allowed');\n }\n if (s2k.type === 'simple' && keyVersion === 6) {\n throw new Error('Using Simple S2K with version 6 keys is not allowed');\n }\n const { keySize } = crypto.getCipherParams(cipherAlgo);\n const derivedKey = await s2k.produceKey(passphrase, keySize);\n if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {\n return derivedKey;\n }\n const info = util.concatUint8Array([\n serializedPacketTag,\n new Uint8Array([keyVersion, cipherAlgo, aeadMode])\n ]);\n return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);\n}\n\nexport default SecretKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n\n /**\n * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,\n * as well comments placed between the name (if present) and the bracketed email address:\n * - name (comment) \n * - email\n * In the first case, the `email` is the only required part, and it must contain the `@` symbol.\n * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,\n * since they interfere with `comment` parsing.\n */\n const re = /^(?[^()]+\\s+)?(?\\([^()]+\\)\\s+)?(?<\\S+@\\S+>)$/;\n const matches = re.exec(userID);\n if (matches !== null) {\n const { name, comment, email } = matches.groups;\n this.comment = comment?.replace(/^\\(|\\)|\\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace\n this.name = name?.trim() || '';\n this.email = email.substring(1, email.length - 1); // remove brackets\n } else if (/^[^\\s@]+@[^\\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace\n this.email = userID;\n }\n\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2022 Proton AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport crypto from '../crypto';\nimport enums from '../enums';\n\n/**\n * Implementation of the Padding Packet\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:\n * Padding Packet\n */\nclass PaddingPacket {\n static get tag() {\n return enums.packet.padding;\n }\n\n constructor() {\n this.padding = null;\n }\n\n /**\n * Read a padding packet\n * @param {Uint8Array | ReadableStream} bytes\n */\n read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars\n // Padding packets are ignored, so this function is never called.\n }\n\n /**\n * Write the padding packet\n * @returns {Uint8Array} The padding packet.\n */\n write() {\n return this.padding;\n }\n\n /**\n * Create random padding.\n * @param {Number} length - The length of padding to be generated.\n * @throws {Error} if padding generation was not successful\n * @async\n */\n async createPadding(length) {\n this.padding = await crypto.random.getRandomBytes(length);\n }\n}\n\nexport default PaddingPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,\n * `enums.signatures.certGeneric` should be given regardless of the actual trust level)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm for a set of keys.\n * @param {Array} [targetKeys] - The keys to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {\n /**\n * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the\n * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).\n * if no keys are available, `preferredSenderAlgo` is returned.\n * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).\n */\n const defaultAlgo = enums.hash.sha256; // MUST implement\n const preferredSenderAlgo = config.preferredHashAlgorithm;\n\n const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {\n const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);\n const targetPrefs = selfCertification.preferredHashAlgorithms;\n return targetPrefs;\n }));\n const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys\n for (const supportedAlgos of supportedAlgosPerTarget) {\n for (const hashAlgo of supportedAlgos) {\n try {\n // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on\n const supportedAlgo = enums.write(enums.hash, hashAlgo);\n supportedAlgosMap.set(\n supportedAlgo,\n supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1\n );\n } catch {}\n }\n }\n const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;\n const getStrongestSupportedHashAlgo = () => {\n if (supportedAlgosMap.size === 0) {\n return defaultAlgo;\n }\n const sortedHashAlgos = Array.from(supportedAlgosMap.keys())\n .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))\n .sort((algoA, algoB) => crypto.hash.getHashByteLength(algoA) - crypto.hash.getHashByteLength(algoB));\n const strongestHashAlgo = sortedHashAlgos[0];\n // defaultAlgo is always implicilty supported, and might be stronger than the rest\n return crypto.hash.getHashByteLength(strongestHashAlgo) >= crypto.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;\n };\n\n const eccAlgos = new Set([\n enums.publicKey.ecdsa,\n enums.publicKey.eddsaLegacy,\n enums.publicKey.ed25519,\n enums.publicKey.ed448\n ]);\n\n if (eccAlgos.has(signingKeyPacket.algorithm)) {\n // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:\n // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5\n // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;\n // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve\n // preferred algo, even if not supported by all targets.\n const preferredCurveAlgo = crypto.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);\n\n const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);\n const preferredSenderAlgoStrongerThanCurveAlgo = crypto.hash.getHashByteLength(preferredSenderAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo);\n\n if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {\n return preferredSenderAlgo;\n } else {\n const strongestSupportedAlgo = getStrongestSupportedHashAlgo();\n return crypto.hash.getHashByteLength(strongestSupportedAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo) ?\n strongestSupportedAlgo :\n preferredCurveAlgo;\n }\n }\n\n // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,\n // since it was manually set by the sender.\n return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();\n}\n\n/**\n * Returns the preferred compression algorithm for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred compression algorithm\n * @async\n */\nexport async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = enums.compression.uncompressed;\n const preferredSenderAlgo = config.preferredCompressionAlgorithm;\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config);\n const recipientPrefs = selfCertification.preferredCompressionAlgorithms;\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred\n * @async\n */\nexport async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config)));\n const withAEAD = keys.length ?\n selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :\n config.aeadProtect;\n\n if (withAEAD) {\n const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };\n const desiredCipherSuites = [\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: config.preferredAEADAlgorithm },\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },\n { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config.preferredAEADAlgorithm }\n ];\n for (const desiredCipherSuite of desiredCipherSuites) {\n if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(\n cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo\n ))) {\n return desiredCipherSuite;\n }\n }\n return defaultCipherSuite;\n }\n const defaultSymAlgo = enums.symmetric.aes128;\n const desiredSymAlgo = config.preferredSymmetricAlgorithm;\n return {\n symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?\n desiredSymAlgo :\n defaultSymAlgo,\n aeadAlgo: undefined\n };\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {Array} recipientKeys - keys to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);\n signaturePacket.rawNotations = [...notations];\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n const isHardRevocation = ![\n enums.reasonForRevocation.keyRetired,\n enums.reasonForRevocation.keySuperseded,\n enums.reasonForRevocation.userIDInvalid\n ].includes(revocationSignature.reasonForRevocationFlag);\n\n await revocationSignature.verify(\n key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||\n options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'curve25519':\n options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;\n break;\n case 'curve448':\n options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function validateSigningKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateEncryptionKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateDecryptionKeyPacket(keyPacket, signature, config) {\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateSigningKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateEncryptionKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n if (primaryKey.version !== 6) {\n // check for expiration time in direct signatures (for V6 keys, the above already did so)\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const selfCertification = await this.getPrimarySelfSignature(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.\n await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * For V4 keys, returns the self-signature of the primary user.\n * For V5 keys, returns the latest valid direct-key self-signature.\n * This self-signature is to be used to check the key expiration,\n * algorithm preferences, and so on.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} The primary self-signature\n * @async\n */\n async getPrimarySelfSignature(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n if (primaryKey.version === 6) {\n return helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n );\n }\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n return selfCertification;\n }\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config);\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @throws {Error} if no decryption key is found\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n let exception = null;\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n if (this.subkeys[i].keyPacket.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n continue;\n }\n\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n // evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.validateDecryptionKeyPacket(primaryKey, selfCertification, config)) {\n if (primaryKey.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n } else {\n keys.push(this);\n }\n }\n\n if (keys.length === 0) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('No decryption key packets found');\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.\n * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).\n * Note: Curve448 and Curve25519 are not widely supported yet.\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n // Every subkey for a v4 primary key MUST be a v4 subkey.\n // Every subkey for a v6 primary key MUST be a v6 subkey.\n // For v5 keys, since we dropped generation support, a v4 subkey is added.\n // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.\n const keyPacket = await helper.generateSecretSubkey(options, { ...config, v6Keys: this.keyPacket.version === 6 });\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nfunction getDefaultSubkeyType(algoName) {\n const algo = enums.write(enums.publicKey, algoName);\n // NB: no encryption-only algos, since they cannot be in primary keys\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n return 'rsa';\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return 'ecc';\n case enums.publicKey.ed25519:\n return 'curve25519';\n case enums.publicKey.ed448:\n return 'curve448';\n default:\n throw new Error('Unsupported algorithm');\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n function getKeySignatureProperties() {\n const signatureProperties = {};\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n const symmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128\n ], config.preferredSymmetricAlgorithm);\n signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;\n if (config.aeadProtect) {\n const aeadAlgorithms = createPreferredAlgos([\n enums.aead.gcm,\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {\n return symmetricAlgorithms.map(symmetricAlgorithm => {\n return [symmetricAlgorithm, aeadAlgorithm];\n });\n });\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512,\n enums.hash.sha3_256,\n enums.hash.sha3_512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.uncompressed,\n enums.compression.zlib,\n enums.compression.zip\n ], config.preferredCompressionAlgorithm);\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.seipdv2;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n return signatureProperties;\n }\n\n if (secretKeyPacket.version === 6) { // add direct key signature with key prefs\n const dataToSign = {\n key: secretKeyPacket\n };\n\n const signatureProperties = getKeySignatureProperties();\n signatureProperties.signatureType = enums.signature.key;\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n packetlist.push(signaturePacket);\n }\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {\n userID: userIDPacket,\n key: secretKeyPacket\n };\n const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};\n signatureProperties.signatureType = enums.signature.certPositive;\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);\n return createKey(firstKeyPacketList);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n return new PrivateKey(firstPrivateKeyList);\n }\n throw new Error('No secret key packet found');\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n if (keys.length === 0) {\n throw new Error('No secret key packet found');\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport { Argon2OutOfMemoryError } from './type/s2k';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredCipherSuite, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;\n\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config);\n\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n if (err instanceof Argon2OutOfMemoryError) {\n exception = err;\n }\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let decryptionKeyPackets;\n try {\n // do not check key expiration to allow decryption of old messages\n decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n } catch (err) {\n exception = err;\n return;\n }\n\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config); // TODO: Pass userID from somewhere.\n if (selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all((\n expectedSymmetricAlgorithm ?\n [expectedSymmetricAlgorithm] :\n Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)\n ).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;\n if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config);\n const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);\n const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&\n !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(symmetricAlgo);\n return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({\n version: aeadAlgorithmName ? 2 : 1,\n aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null\n });\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n\n const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({\n version: aeadAlgorithm ? 6 : 3,\n encryptionKeyPacket: encryptionKey.keyPacket,\n anonymousRecipient: wildcard,\n sessionKey,\n sessionKeyAlgorithm: symmetricAlgorithm\n });\n\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config); // this returns the existing signature packets as well\n const onePassSignaturePackets = signaturePackets.map(\n (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))\n .reverse(); // innermost OPS refers to the first signature packet\n\n packetlist.push(...onePassSignaturePackets);\n packetlist.push(literalDataPacket);\n packetlist.push(...signaturePackets);\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n const trailingPacket = this.packets[this.packets.length - 1];\n // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?\n trailingPacket.version !== 2 :\n this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const signingUserID = signingUserIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config);\n return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n const input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // emit header and checksum if one of the signatures has a version not 6\n const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);\n const hash = emitHeaderAndChecksum ?\n Array.from(new Set(this.signature.packets.map(\n packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()\n ))).join() :\n null;\n\n const body = {\n hash,\n text: this.text,\n data: this.signature.packets.write()\n };\n\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n const hashAlgos = [];\n headers.forEach(header => {\n const hashHeader = header.match(/^Hash: (.+)$/); // get header value\n if (hashHeader) {\n const parsedHashIDs = hashHeader[1]\n .replace(/\\s/g, '') // remove whitespace\n .split(',')\n .map(hashName => {\n try {\n return enums.write(enums.hash, hashName.toLowerCase());\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());\n }\n });\n hashAlgos.push(...parsedHashIDs);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredCompressionAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).\n * Note: Curve448 and Curve25519 (new format) are not widely supported yet.\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:\n * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n if (!type && !curve) {\n type = config.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)\n curve = 'curve25519Legacy'; // unused with type != 'ecc'\n } else {\n type = type || 'ecc';\n curve = curve || 'curve25519Legacy';\n }\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && !config.v6Keys) {\n throw new Error('UserIDs are required for V4 keys');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {\n throw new Error('UserIDs are required for V4 keys');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return await convertStream(data);\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return await convertStream(signature);\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data) {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n// Falls back to Node.js built-in crypto for Node.js <=v14\n// See utils.ts for details.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc\n ? nc.webcrypto\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n//# sourceMappingURL=cryptoNode.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\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// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n}, sha256);\nexport const secp256r1 = p256;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha384 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp384r1 aka p384\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');\nconst Fp = Field(P);\nconst CURVE_A = Fp.create(BigInt('-3'));\n// prettier-ignore\nconst CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n// prettier-ignore\nexport const p384 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\n // Curve order, total count of valid points in the field.\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n // Base (generator) point (x, y)\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n h: BigInt(1),\n lowS: false,\n}, sha384);\nexport const secp384r1 = p384;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-12')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p384.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp521r1 aka p521\n// Note that it's 521, which differs from 512 of its hash function.\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst Fp = Field(P);\nconst CURVE = {\n a: Fp.create(BigInt('-3')),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Fp,\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n h: BigInt(1),\n};\n// prettier-ignore\nexport const p521 = createCurve({\n a: CURVE.a, // Equation params: a, b\n b: CURVE.b,\n Fp, // Field: 2n**521n - 1n\n // Curve order, total count of valid points in the field\n n: CURVE.n,\n Gx: CURVE.Gx, // Base point (x, y) aka generator point\n Gy: CURVE.Gy,\n h: CURVE.h,\n lowS: false,\n allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\nexport const secp521r1 = p521;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE.a,\n B: CURVE.b,\n Z: Fp.create(BigInt('-4')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p521.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3';\nimport { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xof } from './abstract/hash-to-curve.js';\nimport { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * Edwards448 (not Ed448-Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n */\nconst shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));\nconst ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');\n// prettier-ignore\nconst _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);\n// prettier-ignore\nconst _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448P;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most\n // significant bit of the last byte to 1.\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.\n// Uses algo from RFC8032 5.1.3.\nfunction uvRatio(u, v) {\n const P = ed448P;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u²v\n const u3v = mod(u2v * u, P); // u³v\n const u5v3 = mod(u3v * u2v * v, P); // u⁵v³\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x²\n // If vx² = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\nconst Fp = Field(ed448P, 456, true);\nconst ED448_DEF = {\n // Param: a\n a: BigInt(1),\n // -39081. Negative number is P - number\n d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'),\n // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n\n Fp,\n // Subgroup order: how many points curve has;\n // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\n n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n nBitLength: 456,\n // Cofactor\n h: BigInt(4),\n // Base point (x, y) aka generator point\n Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'),\n Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'),\n // SHAKE256(dom4(phflag,context)||x, 114)\n hash: shake256_114,\n randomBytes,\n adjustScalarBytes,\n // dom4\n domain: (data, ctx, phflag) => {\n if (ctx.length > 255)\n throw new Error(`Context is too big: ${ctx.length}`);\n return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n },\n uvRatio,\n};\nexport const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF);\n// NOTE: there is no ed448ctx, since ed448 supports ctx by default\nexport const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 });\nexport const x448 = /* @__PURE__ */ (() => montgomery({\n a: BigInt(156326),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n montgomeryBits: 448,\n nByteLength: 56,\n P: ed448P,\n Gu: BigInt(5),\n powPminus2: (x) => {\n const P = ed448P;\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, BigInt(2), P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts edwards448 public key to x448 public key. Uses formula:\n * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n * @example\n * const aPub = ed448.getPublicKey(utils.randomPrivateKey());\n * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed448.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version\n// Hash To Curve Elligator2 Map\nconst ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic\nconst ELL2_J = BigInt(156326);\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\nfunction map_to_curve_elligator2_edwards448(u) {\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = Fp.invertBatch([xEd, yEd]); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertDcfPoint(other) {\n if (!(other instanceof DcfPoint))\n throw new Error('DecafPoint expected');\n}\n// 1-d\nconst ONE_MINUS_D = BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = BigInt('78163');\n// √(-d)\nconst SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / √(-d)\nconst INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B);\n// Computes Elligator map for Decaf\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const r = mod(-(r0 * r0)); // 1\n const u0 = mod(d * (r - _1n)); // 2\n const u1 = mod((u0 + _1n) * (u0 - r)); // 3\n const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = mod(r0 * v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = mod(-_1n);\n const s = mod(v_prime * (r + _1n)); // 7\n let s_abs = s;\n if (isNegativeLE(s, P))\n s_abs = mod(-s);\n const s2 = s * s;\n const W0 = mod(s_abs * _2n); // 8\n const W1 = mod(s2 + _1n); // 9\n const W2 = mod(s2 - _1n); // 10\n const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11\n return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed448/ExtendedPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass DcfPoint {\n // Private property to discourage combining ExtendedPoint + DecafPoint\n // Always use Decaf encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\n * @param hex 112-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('decafHash', hex, 112);\n const r1 = bytes448ToNumberLE(hex.slice(0, 56));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = bytes448ToNumberLE(hex.slice(56, 112));\n const R2 = calcElligatorDecafMap(r2);\n return new DcfPoint(R1.add(R2));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2\n * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('decafHex', hex, 56);\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint';\n const s = bytes448ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s); // 1\n const u1 = mod(_1n + s2); // 2\n const u1sq = mod(u1 * u1);\n const u2 = mod(u1sq - _4n * d * s2); // 3\n const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4\n let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5\n if (isNegativeLE(u3, P))\n u3 = mod(-u3);\n const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6\n const y = mod((_1n - s2) * invsqrt * u1); // 7\n const t = mod(x * y); // 8\n if (!isValid)\n throw new Error(emsg);\n return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2\n */\n toRawBytes() {\n let { ex: x, ey: _y, ez: z, et: t } = this.ep;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const u1 = mod(mod(x + t) * mod(x - t)); // 1\n const x2 = mod(x * x);\n const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2\n let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3\n if (isNegativeLE(ratio, P))\n ratio = mod(-ratio);\n const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4\n let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 56);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2\n equals(other) {\n assertDcfPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed448.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2)\n return mod(X1 * Y2) === mod(Y1 * X2);\n }\n add(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new DcfPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new DcfPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new DcfPoint(this.ep.double());\n }\n negate() {\n return new DcfPoint(this.ep.negate());\n }\n}\nexport const DecafPoint = /* @__PURE__ */ (() => {\n // decaf448 base point is ed448 base x 2\n // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699\n if (!DcfPoint.BASE)\n DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n);\n if (!DcfPoint.ZERO)\n DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO);\n return DcfPoint;\n})();\n// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C\nexport const hashToDecaf448 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256);\n const P = DcfPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_decaf448 = hashToDecaf448; // legacy\n//# sourceMappingURL=ed448.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));\nconst CURVE_A = Fp.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));\nconst CURVE_B = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');\n\n// prettier-ignore\nexport const brainpoolP256r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),\n Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),\n h: BigInt(1),\n lowS: false\n} as const, sha256);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha384 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));\nconst CURVE_A = Fp.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));\nconst CURVE_B = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');\n\n// prettier-ignore\nexport const brainpoolP384r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),\n Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),\n h: BigInt(1),\n lowS: false\n} as const, sha384);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));\nconst CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));\nconst CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');\n\n// prettier-ignore\nexport const brainpoolP512r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),\n Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),\n h: BigInt(1),\n lowS: false\n} as const, sha512);\n","/**\n * This file is needed to dynamic import the noble-curves.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { p256 as nistP256 } from '@noble/curves/p256';\nimport { p384 as nistP384 } from '@noble/curves/p384';\nimport { p521 as nistP521 } from '@noble/curves/p521';\nimport { x448, ed448 } from '@noble/curves/ed448';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { brainpoolP256r1 } from './brainpool/brainpoolP256r1';\nimport { brainpoolP384r1 } from './brainpool/brainpoolP384r1';\nimport { brainpoolP512r1 } from './brainpool/brainpoolP512r1';\n\nexport const nobleCurves = new Map(Object.entries({\n nistP256,\n nistP384,\n nistP521,\n brainpoolP256r1,\n brainpoolP384r1,\n brainpoolP512r1,\n secp256k1,\n x448,\n ed448\n}));\n\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * This file is needed to dynamic import the legacy ciphers.\n * Separate dynamic imports are not convenient as they result in multiple chunks.\n */\n\nimport { TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TwoFish from './twofish';\nimport BlowFish from './blowfish';\nimport enums from '../../enums';\n\nexport const legacyCiphers = new Map([\n [enums.symmetric.tripledes, TripleDES],\n [enums.symmetric.cast5, CAST5],\n [enums.symmetric.blowfish, BlowFish],\n [enums.symmetric.twofish, TwoFish]\n]);\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms.\n// Initial state\nconst SHA1_IV = /* @__PURE__ */ new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n SHA1_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * SHA1 (RFC 3174) hash function.\n * It was cryptographically broken: prefer newer algorithms.\n * @param message - data that would be hashed\n */\nexport const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());\n//# sourceMappingURL=sha1.js.map","import { HashMD } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n R_BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.js.map","/**\n * This file is needed to dynamic import the noble-hashes.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { sha1 } from '@noble/hashes/sha1';\nimport { sha224, sha256 } from '@noble/hashes/sha256';\nimport { sha384, sha512 } from '@noble/hashes/sha512';\nimport { sha3_256, sha3_512 } from '@noble/hashes/sha3';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\n\nexport const nobleHashes = new Map(Object.entries({\n sha1,\n sha224,\n sha256,\n sha384,\n sha512,\n sha3_256,\n sha3_512,\n ripemd160\n}));\n","// Adapted from the reference implementation in RFC7693\n// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes\n\n// Uint64 values are represented using two Uint32s, stored as little endian\n// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays\n// need to be manually handled\n\n// 64-bit unsigned addition (little endian, in place)\n// Sets a[i,i+1] += b[j,j+1]\n// `a` and `b` must be Uint32Array(2)\nfunction ADD64 (a, i, b, j) {\n a[i] += b[j];\n a[i+1] += b[j+1] + (a[i] < b[j]); // add carry\n}\n\n// Increment 64-bit little-endian unsigned value by `c` (in place)\n// `a` must be Uint32Array(2)\nfunction INC64 (a, c) {\n a[0] += c;\n a[1] += (a[0] < c);\n}\n\n// G Mixing function\n// The ROTRs are inlined for speed\nfunction G (v, m, a, b, c, d, ix, iy) {\n ADD64(v, a, v, b) // v[a,a+1] += v[b,b+1]\n ADD64(v, a, m, ix) // v[a, a+1] += x ... x0\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n let xor0 = v[d] ^ v[a]\n let xor1 = v[d + 1] ^ v[a + 1]\n v[d] = xor1\n v[d + 1] = xor0\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor0 >>> 24) ^ (xor1 << 8)\n v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)\n\n ADD64(v, a, v, b)\n ADD64(v, a, m, iy)\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = v[d] ^ v[a]\n xor1 = v[d + 1] ^ v[a + 1]\n v[d] = (xor0 >>> 16) ^ (xor1 << 16)\n v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor1 >>> 31) ^ (xor0 << 1)\n v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)\n}\n\n// Initialization Vector\nconst BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n])\n\n// These are offsets into a Uint64 buffer.\n// Multiply them all by 2 to make them offsets into a Uint32 buffer\nconst SIGMA = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n].map(x => x * 2))\n\n// Compression function. 'last' flag indicates last block.\n// Note: we're representing 16 uint64s as 32 uint32s\nfunction compress(S, last) {\n const v = new Uint32Array(32)\n const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32)\n\n // init work variables\n for (let i = 0; i < 16; i++) {\n v[i] = S.h[i]\n v[i + 16] = BLAKE2B_IV32[i]\n }\n\n // low 64 bits of offset\n v[24] ^= S.t0[0]\n v[25] ^= S.t0[1]\n // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1\n\n // if last block\n const f0 = last ? 0xFFFFFFFF : 0;\n v[28] ^= f0;\n v[29] ^= f0;\n\n // twelve rounds of mixing\n for (let i = 0; i < 12; i++) {\n // ROUND(r)\n const i16 = i << 4;\n G(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1])\n G(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3])\n G(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5])\n G(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7])\n G(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9])\n G(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11])\n G(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13])\n G(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15])\n }\n\n for (let i = 0; i < 16; i++) {\n S.h[i] ^= v[i] ^ v[i + 16]\n }\n}\n\n// Creates a BLAKE2b hashing context\n// Requires an output length between 1 and 64 bytes\n// Takes an optional Uint8Array key\nclass Blake2b {\n constructor(outlen, key, salt, personal) {\n const params = new Uint8Array(64)\n // 0: outlen, keylen, fanout, depth\n // 4: leaf length, sequential mode\n // 8: node offset\n // 12: node offset\n // 16: node depth, inner length, rfu\n // 20: rfu\n // 24: rfu\n // 28: rfu\n // 32: salt\n // 36: salt\n // 40: salt\n // 44: salt\n // 48: personal\n // 52: personal\n // 56: personal\n // 60: personal\n\n // init internal state\n this.S = {\n b: new Uint8Array(BLOCKBYTES),\n h: new Uint32Array(OUTBYTES_MAX / 4),\n t0: new Uint32Array(2), // input counter `t`, lower 64-bits only\n c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`\n outlen // output length in bytes\n }\n\n // init parameter block\n params[0] = outlen\n if (key) params[1] = key.length\n params[2] = 1 // fanout\n params[3] = 1 // depth\n if (salt) params.set(salt, 32)\n if (personal) params.set(personal, 48)\n const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];\n }\n\n // key the hash, if applicable\n if (key) {\n const block = new Uint8Array(BLOCKBYTES)\n block.set(key)\n this.update(block)\n }\n }\n\n // Updates a BLAKE2b streaming hash\n // Requires Uint8Array (byte array)\n update(input) {\n if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')\n // for (let i = 0; i < input.length; i++) {\n // if (this.S.c === BLOCKBYTES) { // buffer full\n // INC64(this.S.t0, this.S.c) // add counters\n // compress(this.S, false)\n // this.S.c = 0 // empty buffer\n // }\n // this.S.b[this.S.c++] = input[i]\n // }\n let i = 0\n while(i < input.length) {\n if (this.S.c === BLOCKBYTES) { // buffer full\n INC64(this.S.t0, this.S.c) // add counters\n compress(this.S, false)\n this.S.c = 0 // empty buffer\n }\n let left = BLOCKBYTES - this.S.c\n this.S.b.set(input.subarray(i, i + left), this.S.c) // end index can be out of bounds\n const fill = Math.min(left, input.length - i)\n this.S.c += fill\n i += fill\n }\n return this\n }\n\n /**\n * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one\n * @param {Uint8Array} [prealloc] - optional preallocated buffer\n * @returns {ArrayBuffer} message digest\n */\n digest(prealloc) {\n INC64(this.S.t0, this.S.c) // mark last block offset\n\n // final block, padded\n this.S.b.fill(0, this.S.c);\n this.S.c = BLOCKBYTES;\n compress(this.S, true)\n\n const out = prealloc || new Uint8Array(this.S.outlen);\n for (let i = 0; i < this.S.outlen; i++) {\n // must be loaded individually since default Uint32 endianness is platform dependant\n out[i] = this.S.h[i >> 2] >> (8 * (i & 3))\n }\n this.S.h = null; // prevent calling `update` after `digest`\n return out.buffer;\n }\n}\n\n\nexport default function createHash(outlen, key, salt, personal) {\n if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)\n if (key) {\n if (!(key instanceof Uint8Array)) throw new Error('key must be Uint8Array or Buffer')\n if (key.length > KEYBYTES_MAX) throw new Error(`key size must be at most ${KEYBYTES_MAX} (given: ${key.length})`)\n }\n if (salt) {\n if (!(salt instanceof Uint8Array)) throw new Error('salt must be Uint8Array or Buffer')\n if (salt.length !== SALTBYTES) throw new Error(`salt must be exactly ${SALTBYTES} (given: ${salt.length}`)\n }\n if (personal) {\n if (!(personal instanceof Uint8Array)) throw new Error('personal must be Uint8Array or Buffer')\n if (personal.length !== PERSONALBYTES) throw new Error(`salt must be exactly ${PERSONALBYTES} (given: ${personal.length}`)\n }\n\n return new Blake2b(outlen, key, salt, personal)\n}\n\nconst OUTBYTES_MAX = 64;\nconst KEYBYTES_MAX = 64;\nconst SALTBYTES = 16;\nconst PERSONALBYTES = 16;\nconst BLOCKBYTES = 128;\n\n","import blake2b from \"./blake2b.js\"\nconst TYPE = 2; // Argon2id\nconst VERSION = 0x13;\nconst TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MIN = 8;\nconst passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst passwordBYTES_MIN = 8;\nconst MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)\nconst SECRETBYTES_MAX = 32; // key (optional)\n\nconst ARGON2_BLOCK_SIZE = 1024;\nconst ARGON2_PREHASH_DIGEST_LENGTH = 64;\n\nconst isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;\n\n// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])\nfunction LE32(buf, n, i) {\n buf[i+0] = n;\n buf[i+1] = n >> 8;\n buf[i+2] = n >> 16;\n buf[i+3] = n >> 24;\n return buf;\n}\n\n/**\n * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])\n * @param {Uint8Array} buf\n * @param {Number} n\n * @param {Number} i\n */\nfunction LE64(buf, n, i) {\n if (n > Number.MAX_SAFE_INTEGER) throw new Error(\"LE64: large numbers unsupported\");\n // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations\n // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)\n // so we manually extract each byte\n let remainder = n;\n for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER\n buf[offset] = remainder; // implicit & 0xff\n remainder = (remainder - buf[offset]) / 256;\n }\n return buf;\n}\n\n/**\n * Variable-Length Hash Function H'\n * @param {Number} outlen - T\n * @param {Uint8Array} X - value to hash\n * @param {Uint8Array} res - output buffer, of length `outlength` or larger\n */\nfunction H_(outlen, X, res) {\n const V = new Uint8Array(64); // no need to keep around all V_i\n\n const V1_in = new Uint8Array(4 + X.length);\n LE32(V1_in, outlen, 0);\n V1_in.set(X, 4);\n if (outlen <= 64) {\n // H'^T(A) = H^T(LE32(T)||A)\n blake2b(outlen).update(V1_in).digest(res);\n return res\n }\n\n const r = Math.ceil(outlen / 32) - 2;\n\n // Let V_i be a 64-byte block and W_i be its first 32 bytes.\n // V_1 = H^(64)(LE32(T)||A)\n // V_2 = H^(64)(V_1)\n // ...\n // V_r = H^(64)(V_{r-1})\n // V_{r+1} = H^(T-32*r)(V_{r})\n // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}\n for (let i = 0; i < r; i++) {\n blake2b(64).update(i === 0 ? V1_in : V).digest(V);\n // store W_i in result buffer already\n res.set(V.subarray(0, 32), i*32)\n }\n // V_{r+1}\n const V_r1 = new Uint8Array(blake2b(outlen - 32*r).update(V).digest());\n res.set(V_r1, r*32);\n\n return res;\n}\n\n// compute buf = xs ^ ys\nfunction XOR(wasmContext, buf, xs, ys) {\n wasmContext.fn.XOR(\n buf.byteOffset,\n xs.byteOffset,\n ys.byteOffset,\n );\n return buf\n}\n\n/**\n * @param {Uint8Array} X (read-only)\n * @param {Uint8Array} Y (read-only)\n * @param {Uint8Array} R - output buffer\n * @returns\n */\nfunction G(wasmContext, X, Y, R) {\n wasmContext.fn.G(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\nfunction G2(wasmContext, X, Y, R) {\n wasmContext.fn.G2(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\n// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.\nfunction* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {\n // For each segment, we do the following. First, we compute the value Z as:\n // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )\n wasmContext.refs.prngTmp.fill(0);\n const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);\n LE64(Z, pass, 0);\n LE64(Z, lane, 8);\n LE64(Z, slice, 16);\n LE64(Z, m_, 24);\n LE64(Z, totalPasses, 32);\n LE64(Z, TYPE, 40);\n\n // Then we compute q/(128*SL) 1024-byte values\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),\n // ...,\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),\n for(let i = 1; i <= segmentLength; i++) {\n // tmp.set(Z); // no need to re-copy\n LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed\n const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );\n\n // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2\n // NB: the first generated pair must be used for the first block of the segment, and so on.\n // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.\n for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {\n yield g2.subarray(k, k+8);\n }\n }\n return [];\n}\n\nfunction validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {\n const assertLength = (name, value, min, max) => {\n if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }\n }\n\n if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');\n assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);\n assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);\n assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);\n assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);\n // optional fields\n ad && assertLength('associated data', ad, 0, ADBYTES_MAX);\n secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);\n\n return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };\n}\n\nconst KB = 1024;\nconst WASM_PAGE_SIZE = 64 * KB;\n\nexport default function argon2id(params, { memory, instance: wasmInstance }) {\n if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system\n\n const ctx = validateParams({ type: TYPE, version: VERSION, ...params });\n\n const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;\n const wasmRefs = {};\n const wasmFn = {};\n wasmFn.G = wasmG;\n wasmFn.G2 = wasmG2;\n wasmFn.XOR = wasmXOR;\n\n // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.\n const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));\n const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references\n if (memory.buffer.byteLength < requiredMemory) {\n const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE)\n // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.\n // Otherwise, the operation fails, and the original memory can still be used.\n memory.grow(missing)\n }\n\n let offset = 0;\n // Init wasm memory needed in other functions\n wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;\n wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;\n wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;\n wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;\n // Init wasm memory needed locally\n const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;\n const wasmContext = { fn: wasmFn, refs: wasmRefs };\n const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;\n const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);\n const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);\n\n // 1. Establish H_0\n const H0 = getH0(ctx);\n\n // 2. Allocate the memory as m' 1024-byte blocks\n // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.\n const q = m_ / ctx.lanes;\n const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));\n const initBlock = (i, j) => {\n B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);\n return B[i][j];\n }\n\n for (let i = 0; i < ctx.lanes; i++) {\n // const LEi = LE0; // since p = 1 for us\n const tmp = new Uint8Array(H0.length + 8);\n // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p\n // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))\n tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));\n // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p\n // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))\n LE32(tmp, 1, H0.length);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));\n }\n\n // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2\n // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes\n // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.\n const SL = 4; // vertical slices\n const segmentLength = q / SL;\n for (let pass = 0; pass < ctx.passes; pass++) {\n // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel\n for (let sl = 0; sl < SL; sl++) {\n const isDataIndependent = pass === 0 && sl <= 1;\n for (let i = 0; i < ctx.lanes; i++) { // lane\n // On the first slice of the first pass, blocks 0 and 1 are already filled\n let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;\n // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)\n const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;\n for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {\n const j = sl * segmentLength + segmentOffset;\n const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]\n\n // we can assume the PRNG is never done\n const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength)\n const l = lz[0]; const z = lz[1];\n // for (let i = 0; i < p; i++ )\n // B[i][j] = G(B[i][j-1], B[l][z])\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n if (pass === 0) initBlock(i, j);\n G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);\n\n // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one\n if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j])\n }\n }\n }\n }\n\n // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:\n // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]\n const C = B[0][q-1];\n for(let i = 1; i < ctx.lanes; i++) {\n XOR(wasmContext, C, C, B[i][q-1])\n }\n\n const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));\n // clear memory since the module might be cached\n allocatedMemory.fill(0) // clear sensitive contents\n memory.grow(0) // allow deallocation\n // 8. The output tag is computed as H'^T(C).\n return tag;\n\n}\n\nfunction getH0(ctx) {\n const H = blake2b(ARGON2_PREHASH_DIGEST_LENGTH);\n const ZERO32 = new Uint8Array(4);\n const params = new Uint8Array(24);\n LE32(params, ctx.lanes, 0);\n LE32(params, ctx.tagLength, 4);\n LE32(params, ctx.memorySize, 8);\n LE32(params, ctx.passes, 12);\n LE32(params, ctx.version, 16);\n LE32(params, ctx.type, 20);\n\n const toHash = [params];\n if (ctx.password) {\n toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0))\n toHash.push(ctx.password)\n } else {\n toHash.push(ZERO32) // context.password.length\n }\n\n if (ctx.salt) {\n toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0))\n toHash.push(ctx.salt)\n } else {\n toHash.push(ZERO32) // context.salt.length\n }\n\n if (ctx.secret) {\n toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0))\n toHash.push(ctx.secret)\n // todo clear secret?\n } else {\n toHash.push(ZERO32) // context.secret.length\n }\n\n if (ctx.ad) {\n toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0))\n toHash.push(ctx.ad)\n } else {\n toHash.push(ZERO32) // context.ad.length\n }\n H.update(concatArrays(toHash))\n\n const outputBuffer = H.digest();\n return new Uint8Array(outputBuffer);\n}\n\nfunction concatArrays(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!(arrays[i] instanceof Uint8Array)) {\n throw new Error('concatArrays: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach((element) => {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n","import argon2id from \"./argon2id.js\";\n\nlet isSIMDSupported;\nasync function wasmLoader(memory, getSIMD, getNonSIMD) {\n const importObject = { env: { memory } };\n if (isSIMDSupported === undefined) {\n try {\n const loaded = await getSIMD(importObject);\n isSIMDSupported = true;\n return loaded;\n } catch(e) {\n isSIMDSupported = false;\n }\n }\n\n const loader = isSIMDSupported ? getSIMD : getNonSIMD;\n return loader(importObject);\n}\n\nexport default async function setupWasm(getSIMD, getNonSIMD) {\n const memory = new WebAssembly.Memory({\n // in pages of 64KiB each\n // these values need to be compatible with those declared when building in `build-wasm`\n initial: 1040, // 65MB\n maximum: 65536, // 4GB\n });\n const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);\n\n /**\n * Argon2id hash function\n * @callback computeHash\n * @param {Object} params\n * @param {Uint8Array} params.password - password\n * @param {Uint8Array} params.salt - salt\n * @param {Integer} params.parallelism\n * @param {Integer} params.passes\n * @param {Integer} params.memorySize - in kibibytes\n * @param {Integer} params.tagLength - output tag length\n * @param {Uint8Array} [params.ad] - associated data (optional)\n * @param {Uint8Array} [params.secret] - secret data (optional)\n * @return {Uint8Array} argon2id hash\n */\n const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });\n\n return computeHash;\n}\n","import setupWasm from './lib/setup.js';\nimport wasmSIMD from './dist/simd.wasm';\nimport wasmNonSIMD from './dist/no-simd.wasm';\n\nconst loadWasm = async () => setupWasm(\n (instanceObject) => wasmSIMD(instanceObject),\n (instanceObject) => wasmNonSIMD(instanceObject),\n);\n\nexport default loadWasm;\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","Object","setPrototypeOf","this","prototype","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","isStream","globalThis","ReadableStream","isPrototypeOf","_read","_readableState","Error","isUint8Array","Uint8Array","concatUint8Array","arrays","length","totalLength","i","result","pos","forEach","element","set","undefined","read","async","value","done","readToEnd","join","slice","clone","then","push","write","chunk","close","abort","reason","process","versions","doneReadingSet","WeakSet","externalBuffer","Reader","reader","bind","_releaseLock","_cancel","cancel","doneReading","has","add","e","toStream","start","controller","enqueue","toArrayStream","concat","list","some","map","transform","transformWithCancel","all","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","options","transformStream","TransformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","pull","highWaterMark","WritableStream","error","finish","output","data","result1","result2","flush","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","destroy","arrayStream","shift","readLine","returnVal","buffer","streams.concat","lineEndIndex","indexOf","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","byteOffset","byteLength","filter","byValue","enums","curve","nistP256","p256","nistP384","p384","nistP521","p521","secp256k1","ed25519Legacy","ed25519","curve25519Legacy","curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","argon2","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","aedh","aedsa","x25519","x448","ed448","symmetric","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","sha3_256","sha3_512","webHash","aead","eax","ocb","gcm","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","padding","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuerKeyID","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","preferredCipherSuites","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","seipdv2","type","config","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","aeadProtect","parseAEADEncryptedV4KeysAsLegacy","preferredAEADAlgorithm","aeadChunkSizeByte","v6Keys","enableParsingV5Entities","s2kType","s2kIterationCountByte","s2kArgon2Params","passes","parallelism","memoryExponent","allowUnauthenticatedMessages","allowUnauthenticatedStream","minRSABits","passwordCollisionCheck","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","allowMissingKeyFlags","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","nonDeterministicSignaturesViaNotation","useEllipticFallback","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","debugMode","env","NODE_ENV","util","isString","String","nodeRequire","createRequire","url","stream.isUint8Array","stream.isStream","getNobleCurve","publicKeyAlgo","curveName","defaultConfig","nobleCurves","noble_curves","readNumber","n","writeNumber","b","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","readExactSubarray","leftPad","padded","offset","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","hex","k","parseInt","uint8ArrayToHex","hexAlphabet","s","v","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","printDebug","log","printDebugError","x","r","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","webCrypto","crypto","subtle","getNodeCrypto","webcrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","sub","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","a","selectUint8","isAES","cipherAlgo","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","getType","header","match","addheader","customComment","getCheckSum","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","base64.encode","from","toString","btoa","atob","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","removeChecksum","body","lastEquals","lastIndexOf","unarmor","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","stream.isArrayStream","stream.readToEnd","messageType","partIndex","partTotal","emitChecksum","maybeBodyClone","stream.passiveClone","getLegacyCipher","algo","legacyCiphers","legacy_ciphers","cipher","getCipherBlockSize","getCipherKeySize","getCipherParams","keySize","blockSize","md5cycle","c","d","ff","gg","hh","ii","add32","cmn","q","md5blk","md5blks","hex_chr","rhex","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","update","digest","nobleHash","nobleHashName","webCryptoHashName","getNobleHash","nobleHashes","noble_hashes","hashInstance","create","hash$1","entree","state","substring","tail","md51","getHashByteLength","isBytes","lengths","exists","instance","checkFinished","destroyed","finished","out","min","outputLen","u8","arr","u32","createView","toBytes","utf8ToBytes","copyBytes","equalBytes","diff","wrapCipher","params","assign","setBigUint64","view","isLE","_32n","BigInt","_u32_max","wh","Number","wl","setUint32","isAligned32","clean","fill","BLOCK_SIZE","ZEROS16","ZEROS32","swapLE","GHASH","expectedLength","blockLen","s0","s1","s2","s3","abytes","kView","k0","getUint32","k1","k2","k3","doubles","W","estimateWindow","windows","windowSize","items","w","d0","d1","d2","d3","_updateBlock","o0","o1","o2","o3","mask","num","bytePos","bitPos","bit","e0","e1","e2","e3","aexists","b32","blocks","left","elm","digestInto","aoutput","o32","res","Polyval","ghKey","reverse","hiBit","carry","_toGHASHKey","wrapConstructorWithKey","hashCons","hashC","msg","tmp","ghash","EMPTY_BLOCK","POLY","mul2","mul","sbox","box","invSbox","_","rotr32_8","rotl32_8","byteSwap","word","genTtable","T0","T1","T2","T3","T01","T23","sbox2","Uint16Array","idx","tableEncoding","tableDecoding","xPowers","p","expandKeyLE","len","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","encrypt","rounds","t0","t1","t2","t3","decrypt","getDst","dst","ctrCounter","nonce","src","srcLen","ctr","c32","src32","dst32","ctr32","ctrPos","ctrNum","nonceLength","processCtr","plaintext","ciphertext","cbc","iv","opts","pcks5","disablePadding","o","_out","outLen","remaining","validateBlockEncrypt","_iv","n32","tmp32","paddingByte","padPCKS","validateBlockDecrypt","ps0","ps1","ps2","ps3","lastByte","validatePCKS","cfb","processCfb","isEncrypt","next32","tagLength","AAD","_computeTag","authKey","tagMask","aadLength","h","computeTag","deriveKeys","counter","nonceLen","g","passedTag","isBytes32","encryptBlock","block","decryptBlock","AESW","kek","a0","a1","chunks","AESKW_IV","aeskw","sum","pad","concatBytes","unsafe","knownAlgos","getCiphers","nodeAlgos","WebCryptoEncryptor","prevBlock","nextBlock","zeroBlock","isSupported","importKey","_runCBC","nonZeroIV","mode","keyRef","encryptChunk","missing","added","leftover","toEncrypt","encryptedBlocks","xorMut","encryptedBlock","curBlock","clearSensitiveData","ct","NobleStreamProcessor","forEncryption","nobleAesHelpers","getUint32Array","_runCFB","processChunk","toProcess","processedBlocks","processedBlock","aLength","algoName","decipherObj","createDecipheriv","nodeDecrypt","nobleAesCfb","aesDecrypt","cipherfn","block_size","blockp","decblock","pt","cipherObj","createCipheriv","nodeEncrypt","aesEncrypt","blockc","encblock","blockLength","rightXORMut","CMAC","CBC","padding2","err","nobleAesCbc","ivLength","zero","one","two","OMAC","cmac","CTR","en","final","nobleAesCtr","EAX","omac","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","T","xor","OCB","maxNtz","aes","encipher","decipher","crypt","m","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","checksum","xorInput","$","cipherInput","mask_x","mask_$","constructKeyVariables","crypted","ALGO","GCM","setAAD","getAuthTag","de","setAuthTag","_key","webcryptoEmptyMessagesUnsupported","userAgent","nobleAesGcm","additionalData","_0n","_1n","uint8ArrayToBigInt","mod","reduced","modExp","exp","lsb","abs","modInv","gcd","aInput","bInput","y","xPrev","yPrev","aNegated","bNegated","_egcd","bigIntToNumber","number","MAX_SAFE_INTEGER","getBit","bitLength","bitlen","_8n","bigIntToUint8Array","endian","rawLength","getRandomBytes","getRandomValues","getRandomBigInteger","modulus","randomProbablePrime","_30n","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","n1","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","count","randomBytes","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","hashed","emLen","hashPrefix","tLen","EM","privateToJWK","u","pNum","qNum","dNum","dq","dp","kty","qi","ext","publicToJWK","jwkToPrivate","jwk","format","constants","RSA_PKCS1_PADDING","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","publicEncrypt","bnEncrypt","keyGenOpt","modulusLength","publicExponent","keyPair","generateKey","exportKey","publicKeyEncoding","privateKeyEncoding","generateKeyPair","jwkPrivateKey","phi","hashAlgo","hashName","sign","webSign","createSign","nodeSign","bnSign","_2n","rde","verify","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","c1","c2","pSize","threshold","nc","nacl","gf","init","Float64Array","randombytes","_9","gf0","gf1","_121665","D","D2","X","Y","I","ts64","l","crypto_verify_32","xi","yi","vn","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","A","Z","M","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","z","f","x32","x16","crypto_scalarmult_base","K","crypto_hashblocks_hl","hl","bh0","bh1","bh2","bh3","bh4","bh5","bh6","bh7","bl0","bl1","bl2","bl3","bl4","bl5","bl6","bl7","th","tl","Int32Array","ah0","ah1","ah2","ah3","ah4","ah5","ah6","ah7","al0","al1","al2","al3","al4","al5","al6","al7","crypto_hash","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","reduce","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","TypeError","scalarMult","crypto_box_keypair","fromSecretKey","signedMsg","sm","smlen","crypto_sign","detached","sig","crypto_sign_open","fromSeed","seed","setPRNG","cleanup","knownOIDs","OID","oid","toHex","getName","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callback","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","lengthByte","nextPacket","UnsupportedError","captureStackTrace","UnknownPacketError","UnparseablePacket","rawContent","generate","webCryptoKey","getPayloadSize","utils","randomPrivateKey","getPublicKey","getPreferredHashAlgo","privateKeyToJWK","RS","publicKeyToJWK","crv","wrap","dataToWrap","wrappingKey","keyToWrap","wrapped","wrapKey","nobleAesKW","unwrap","wrappedData","unwrapped","unwrapKey","computeHKDF","inputKey","salt","info","importedKey","deriveBits","HKDF_INFO","generateEphemeralEncryptionMaterial","recipientA","ephemeralSecretKey","sharedSecret","assertNonZeroArray","ephemeralPublicKey","getSharedSecret","recomputeSharedSecret","acc","wrappedKey","hkdfInput","aesKW.unwrap","encryptionKey","aesKW.wrap","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","wireFormatLeadingByte","CurveWithOID","oidOrName","genKeyPair","namedCurve","jwkToRawPublic","webGenKeyPair","jsGenKeyPair","createECDH","generateKeys","getPrivateKey","nodeGenKeyPair","ecdhXGenerate","eddsaGenerate","validateStandardParams","Q","supportedCurves","dG","checkPublicPointEnconding","V","pointSize","nobleCurve","bufX","bufY","rawPublicToJWK","ecKeyUtils","nodeBuffer","derPrivateKey","generateDer","dsaEncoding","lowS","tryFallbackVerificationForOldBug","jsVerify","verified","derPublicKey","eddsaSign","eddsaVerify","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","ecdhXGenerateEphemeralEncryptionMaterial","recipient","public","webPublicEphemeralKey","jsPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","genPrivateEphemeralKey","ecdhXRecomputeSharedSecret","secret","webPrivateEphemeralKey","jsPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","C","pkcs5.decode","pkcs5.encode","xr","qSize","u1","u2","rsa","elliptic","signatureParams","rsSize","eddsa","publicKeyParams","privateKeyParams","publicParams","curveSize","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","fromObject","algorithm","followLength","checkSupportedCurve","getCurvePayloadSize","ecdhX","privateParams","prefixrandom","repeat","ECDHSymkey","sessionKeyParams","keyAlgo","symmetricAlgo","algosWithNativeRepresentation","orderedParams","keys","validateParams","algoModule","random","pkcs1","pkcs5","aesKW","Argon2OutOfMemoryError","loadArgonWasmModule","argon2Promise","Argon2S2K","encodedM","generateSalt","produceKey","passphrase","decodedM","index$1","default","version","password","memorySize","GenericS2K","getCount","numBytes","rlength","prefixlen","toHash","datalen","allowedS2KTypesForEncryption","newS2KFromType","newS2KFromConfig","require","Worker","u16","fleb","fdeb","clim","freb","eb","_a","fl","revfl","_b","fd","revfd","rev","hMap","cd","mb","co","le","rvb","sv","r_1","flt","fdt","flm","flrm","fdm","fdrm","bits16","shft","slc","BYTES_PER_ELEMENT","ec","ind","nt","code","wbits","wbits16","hTree","et","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","cl","cli","cln","cls","clen","cf","wfblk","dat","wblk","syms","lf","df","li","bl","dlt","mlb","ddt","mdb","_c","lclt","nlc","_d","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","deo","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","head","bs1_1","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","level","mem","Deflate","cb","ondata","Inflate","bts","sl","noBuf","noSt","cbuf","nbuf","bt","lbt","dbt","tbts","hLit","hcLen","ldt","clt","clb","clbmsk","clm","lt","lms","dms","lpos","sym","dsym","inflt","Zlib","raw","lv","zlh","wbytes","Unzlib","td","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","KeyID","equals","keyID","matchWildcard","isWildcard","isNull","mapToHex","fromID","wildcard","SALT_NOTATION_NAME","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","unknownSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","saltLength","signatureMaterial","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","saltLengthForHash","saltValue","humanReadable","critical","writeHashedSubPackets","stream.slice","stream.clone","writeSubPacket","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLengthBytes","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","fromSignaturePacket","signaturePacket","isLast","onePassSig","flags","args","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","fromBinary","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","chunkSize","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","compressionFn","compress_fns","compressionStreamInstantiator","ZlibStreamedConstructor","inputData","zlibStream","processedData","compressorOrDecompressor","pipeThrough","inputReader","bzip2Decompress","bunzipDecode","getCompressionStreamInstantiators","compressionFormat","compressor","CompressionStream","decompressor","DecompressionStream","SymEncryptedIntegrityProtectedDataPacket","aeadAlgorithm","seip","cipherAlgorithm","chunkSizeByte","encrypted","sessionKeyAlgorithm","runAEAD","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","isSEIPDv2","isAEADP","getAEADMode","tagLengthIfDecrypting","tagLengthIfEncrypting","chunkIndexSizeIfAEADEP","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","ivView","latestPromise","cryptedBytes","queuedBytes","derived","modeInstance","size","stream.pipe","finalChunk","cryptedPromise","setInt32","desiredSize","AEADEncryptedDataPacket","PublicKeyEncryptedSessionKeyPacket","publicKeyID","publicKeyVersion","publicKeyFingerprint","sessionKey","encryptionKeyPacket","anonymousRecipient","pkesk","versionAndFingerprintLength","fingerprintLength","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","hasEncryptedAlgo","sessionKeyData","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","s2kLen","fieldsLen","generateSessionKey","PublicKeyPacket","expirationTimeV3","fromSecretKeyPacket","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","versionOctet","lengthOctets","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","fromSecretSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","isLegacyAEAD","usedModernAEAD","startOfSecretKeyData","unparseableKeyMaterial","cleartext","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","serializedPacketTag","produceEncryptionKey","associateData","cleartextWithHash","validate","validParams","generateParams","keyVersion","aeadMode","derivedKey","UserIDPacket","email","comment","components","matches","exec","groups","trim","otherUserID","SecretSubkeyPacket","TrustPacket","PaddingPacket","createPadding","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","recipientKeys","signingKeyPacket","recipientUserIDs","targetKeys","targetUserIDs","defaultAlgo","preferredSenderAlgo","supportedAlgosPerTarget","getPrimarySelfSignature","supportedAlgosMap","Map","supportedAlgos","supportedAlgo","isSupportedHashAlgo","getStrongestSupportedHashAlgo","strongestHashAlgo","algoA","algoB","preferredCurveAlgo","getPreferredCurveHashAlgo","preferredSenderAlgoIsSupported","preferredSenderAlgoStrongerThanCurveAlgo","strongestSupportedAlgo","mergeSignatures","source","dest","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","isHardRevocation","sanitizeKeyOptions","subkeyDefaults","validateSigningKeyPacket","validateEncryptionKeyPacket","validateDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","certify","signingKeys","isPrivate","signingKey","getSigningKey","isRevoked","certificate","verifyCertificate","verificationKeys","issuerKeys","getKeys","verifyAllCertifications","certifications","certification","valid","selfCertification","sourceUser","srcSelfSig","srcRevSig","revoke","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","helper.checkKeyRequirements","helper.validateSigningKeyPacket","getEncryptionKey","helper.validateEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","getPrimaryUser","primaryUser","B","pop","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","getRevocationCertificate","applyRevocationCertificate","revocationCertificate","signPrimaryUser","privateKeys","userSign","signAllUsers","verifyPrimaryUser","verifyAllUsers","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","pubSubkeyPacket","getDecryptionKeys","helper.validateDecryptionKeyPacket","Boolean","addSubkey","defaultOptions","getDefaultSubkeyType","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","getKeySignatureProperties","symmetricAlgorithms","aeadAlgorithms","flatMap","symmetricAlgorithm","userIDs","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","keyIndex","readPrivateKey","firstPrivateKeyList","readKeys","armoredKeys","binaryKeys","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","symEncryptedPacketlist","symEncryptedPacket","expectedSymmetricAlgorithm","sessionKeyObjects","decryptSessionKeys","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgo","selfSigs","selfSig","defaultCipherSuite","desiredCipherSuites","desiredCipherSuite","cipherSuite","defaultSymAlgo","desiredSymAlgo","getPreferredCipherSuite","symmetricAlgoName","aeadAlgoName","maybeKey","encryptionKeyIDs","aeadAlgorithmName","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","signingUserIDs","literalDataPacket","signaturePackets","createSignaturePackets","onePassSignaturePackets","signDetached","recipientKeyIDs","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","appendSignature","detachedSignature","trailingPacket","signingUserID","existingSigPacketlist","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","streamType","createMessage","literalDataPacketlist","CleartextMessage","newSignature","emitHeaderAndChecksum","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","check","hashHeader","parsedHashIDs","createCleartextMessage","checkConfig","toArray","helper.generateSecretKey","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","decryptKey","clonedPrivateKey","passphrases","encryptKey","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","senderAlgoSupport","recipientPrefs","getPreferredCompressionAlgo","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","object","isSafeInteger","rotr","rotl","byteSwap32","Hash","_cloneInto","wrapConstructor","bytesLength","Chi","Maj","HashMD","padOffset","take","dataView","roundClean","oview","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","E","F","G","H","W15","W2","SHA224","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","hmac","abool","title","hexes","padStart","bytesToHex","numberToHexUnpadded","hexToNumber","asciis","_0","_A","_F","_f","asciiToBase16","char","hexToBytes","al","ai","hi","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","isPosBig","inRange","aInRange","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reset","reseed","gen","pred","validatorFns","bigint","val","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","memoized","WeakMap","arg","_3n","_4n","_5n","pow","pow2","invert","FpSqrt","P","p1div4","root","eql","sqr","nv","ONE","legendreC","Q1div2","neg","ZERO","ge","tonelliShanks","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","freeze","MASK","is0","isOdd","lhs","rhs","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","constTimeNegate","condition","negate","validateW","unsafeLadder","precomputeWindow","points","base","window","precomputes","BASE","maxNumber","shiftBy","offset1","offset2","cond1","cond2","wNAFCached","comp","setWindowSize","delete","pippenger","scalars","buckets","lastBits","scalar","resI","sumI","validateBasic","Gx","Gy","validateSigVerOpts","prehash","b2n","h2b","ut","DER","Err","_tlv","dataLen","ut.numberToHexUnpadded","lenLen","first","lengthBytes","_int","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","point","_isCompressed","toAffine","ut.concatBytes","weierstrassEquation","x2","x3","normPrivateKeyToScalar","N","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","ut.aInRange","assertPrjPoint","Point","toAffineMemo","iz","px","py","pz","ax","ay","zz","assertValidMemo","right","fromAffine","normalizeZ","toInv","fromHex","assertValidity","fromPrivateKey","multiply","msm","_setWindowSize","wnaf","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","subtract","multiplyUnsafe","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","cofactor","toRawBytes","isCompressed","_bits","ProjectivePoint","isWithinCurveOrder","ut.inRange","weierstrass","curveDef","bits2int","bits2int_modN","validateOpts","compressedLen","uncompressedLen","modN","CURVE_ORDER","invN","mod.invert","cat","y2","sqrtError","suffix","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","R","ir","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","mod.getMinHashLength","fieldLen","minLen","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","privateA","publicB","privKey","ut.createHmacDrbg","drbg","sg","_sig","derError","is","getHash","msgs","createCurve","defHash","U32_MASK64","fromBig","Ah","Al","rotlSH","rotlSL","rotlBH","rotlBL","u64","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","SHA384","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_7n","_256n","_0x71n","round","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","enableXOF","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","writeInto","bufferOut","xofInto","xof","shake256","wrapXOFConstructorWithOpts","dkLen","genShake","VERIFY_DEFAULT","zip215","twistedEdwards","adjustScalarBytes","domain","uvRatio","mapToCurve","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","isSmallOrder","normed","ut.bytesToNumberLE","isXOdd","isLastByteOdd","getExtendedPublicKey","ut.numberToBytesLE","modN_LE","pointBytes","hashDomainToScalar","context","verifyOpts","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","swap","x_2","x_3","dummy","a24","encodeUCoordinate","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","shake256_114","ed448P","_11n","_22n","_44n","_88n","_223n","ed448_pow_Pminus3div4","b22","b44","b88","b176","b220","b222","b223","ED448_DEF","u2v","u3v","u5v3","secp256k1P","secp256k1N","divNearest","_6n","_23n","a2","POW_2_128","des","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","looping","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","f1","f2","f3","scheduleA","scheduleB","sBox","inn","ki","half","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","dataL","dataR","parray","vector","off","ret","_decryptBlock","jj","kk","BlowFish","TwoFish","SHA1_IV","SHA1_W","SHA1","Rho","Id","Pi","idxL","idxR","shiftsL","shiftsR","Kl","Kr","group","R_BUF","RIPEMD160","h0","h1","h2","h3","h4","ar","br","cr","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","ripemd160","ADD64","INC64","ix","iy","xor0","xor1","BLAKE2B_IV32","SIGMA","f0","i16","Blake2b","outlen","personal","BLOCKBYTES","OUTBYTES_MAX","params32","prealloc","TYPE","VERSION","TAGBYTES_MAX","TAGBYTES_MIN","SALTBYTES_MAX","SALTBYTES_MIN","passwordBYTES_MAX","passwordBYTES_MIN","MEMBYTES_MAX","ADBYTES_MAX","SECRETBYTES_MAX","ARGON2_BLOCK_SIZE","ARGON2_PREHASH_DIGEST_LENGTH","LE32","LE64","H_","V1_in","blake2b","V_r1","XOR","wasmContext","xs","ys","refs","gZ","G2","makePRNG","pass","lane","m_","totalPasses","segmentLength","segmentOffset","prngTmp","g2","ZERO1024","prngR","KB","WASM_PAGE_SIZE","argon2id","memory","wasmInstance","ad","assertLength","lanes","wasmG","wasmG2","wasmXOR","getLZ","wasmLZ","exports","wasmRefs","wasmFn","requiredMemory","grow","lz","newBlock","blockMemory","allocatedMemory","H0","ZERO32","concatArrays","outputBuffer","getH0","initBlock","isDataIndependent","PRNG","J1J2","next","isSIMDSupported","setupWasm","getSIMD","getNonSIMD","WebAssembly","Memory","initial","maximum","wasmModule","importObject","loaded","wasmLoader","instanceObject","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","seek","n_bit","n_byte","pi","bufToHex","bitreader","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","crc32","getCRC","updateCRC","updateCRCRun","require$$0","require$$1","CRC32","require$$2","mtf","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","status","optDetail","errorCode","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","maxLen","MAX_HUFCODE_BITS","permute","limit","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","lib","multistream","bz","targetStreamCRC","decodeBlock","writeCopies","table","delegate","position","assert"],"mappings":";6dAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxB,WAAAC,GACEC,QAEAC,OAAOC,eAAeC,KAAMN,EAAYO,WAExCD,KAAKX,GAAsB,IAAIa,SAAQ,CAACC,EAASC,KAC/CJ,KAAKT,GAAsBY,EAC3BH,KAAKR,GAAqBY,CAAM,IAElCJ,KA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8E,EAChB,sDAEvB,CACA,CACA","x_google_ignoreList":[0,1,2,3,12,13,14,15,28,29,52,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,114,115,117,118,119,120,121,122,123,124]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/node/openpgp.mjs b/app/node_modules/openpgp/dist/node/openpgp.mjs index 6139df836..fdf4e8398 100644 --- a/app/node_modules/openpgp/dist/node/openpgp.mjs +++ b/app/node_modules/openpgp/dist/node/openpgp.mjs @@ -1,13 +1,23 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -import buffer from 'buffer'; -import stream$1 from 'stream'; -import crypto$3 from 'crypto'; -import zlib from 'zlib'; -import os from 'os'; -import util$1 from 'util'; -import asn1$2 from 'asn1.js'; +import { createRequire } from 'module'; +import * as nc from 'node:crypto'; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} const doneWritingPromise = Symbol('doneWritingPromise'); const doneWritingResolve = Symbol('doneWritingResolve'); @@ -18,6 +28,9 @@ const readingIndex = Symbol('readingIndex'); class ArrayStream extends Array { constructor() { super(); + // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work + Object.setPrototypeOf(this, ArrayStream.prototype); + this[doneWritingPromise] = new Promise((resolve, reject) => { this[doneWritingResolve] = resolve; this[doneWritingReject] = reject; @@ -118,15 +131,14 @@ Writer.prototype.abort = async function(reason) { */ Writer.prototype.releaseLock = function() {}; -const isNode = typeof globalThis.process === 'object' && +/* eslint-disable no-prototype-builtins */ +typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; -const NodeReadableStream = isNode && stream$1.Readable; - /** * Check whether data is a Stream, and if so of which type * @param {Any} input data to check - * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false} + * @returns {'web'|'node'|'array'|'web-like'|false} */ function isStream(input) { if (isArrayStream(input)) { @@ -135,11 +147,11 @@ function isStream(input) { if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { return 'web'; } - if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) { - return 'ponyfill'; - } - if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) { - return 'node'; + // try and detect a node native stream without having to import its class + if (input && + !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) && + typeof input._read === 'function' && typeof input._readableState === 'object') { + throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`'); } if (input && input.getReader) { return 'web-like'; @@ -183,99 +195,12 @@ function concatUint8Array(arrays) { return result; } -const NodeBuffer = isNode && buffer.Buffer; -const NodeReadableStream$1 = isNode && stream$1.Readable; - +const doneReadingSet = new WeakSet(); /** - * Web / node stream conversion functions - * From https://github.com/gwicke/node-web-streams + * The external buffer is used to store values that have been peeked or unshifted from the original stream. + * Because of how streams are implemented, such values cannot be "put back" in the original stream, + * but they need to be returned first when reading from the input again. */ - -let nodeToWeb; -let webToNode; - -if (NodeReadableStream$1) { - - /** - * Convert a Node Readable Stream to a Web ReadableStream - * @param {Readable} nodeStream - * @returns {ReadableStream} - */ - nodeToWeb = function(nodeStream) { - let canceled = false; - return new ReadableStream({ - start(controller) { - nodeStream.pause(); - nodeStream.on('data', chunk => { - if (canceled) { - return; - } - if (NodeBuffer.isBuffer(chunk)) { - chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - controller.enqueue(chunk); - nodeStream.pause(); - }); - nodeStream.on('end', () => { - if (canceled) { - return; - } - controller.close(); - }); - nodeStream.on('error', e => controller.error(e)); - }, - pull() { - nodeStream.resume(); - }, - cancel(reason) { - canceled = true; - nodeStream.destroy(reason); - } - }); - }; - - - class NodeReadable extends NodeReadableStream$1 { - constructor(webStream, options) { - super(options); - this._reader = getReader(webStream); - } - - async _read(size) { - try { - while (true) { - const { done, value } = await this._reader.read(); - if (done) { - this.push(null); - break; - } - if (!this.push(value)) { - break; - } - } - } catch (e) { - this.destroy(e); - } - } - - async _destroy(error, callback) { - this._reader.cancel(error).then(callback, callback); - } - } - - /** - * Convert a Web ReadableStream to a Node Readable Stream - * @param {ReadableStream} webStream - * @param {Object} options - * @returns {Readable} - */ - webToNode = function(webStream, options) { - return new NodeReadable(webStream, options); - }; - -} - -const doneReadingSet = new WeakSet(); const externalBuffer = Symbol('externalBuffer'); /** @@ -294,13 +219,10 @@ function Reader(input) { const reader = input.getReader(); this._read = reader.read.bind(reader); this._releaseLock = () => {}; - this._cancel = async () => {}; + this._cancel = () => {}; return; } let streamType = isStream(input); - if (streamType === 'node') { - input = nodeToWeb(input); - } if (streamType) { const reader = input.getReader(); this._read = reader.read.bind(reader); @@ -407,6 +329,7 @@ Reader.prototype.readByte = async function() { Reader.prototype.readBytes = async function(length) { const buffer = []; let bufferLength = 0; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) { @@ -466,6 +389,7 @@ Reader.prototype.unshift = function(...values) { */ Reader.prototype.readToEnd = async function(join=concat) { const result = []; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) break; @@ -474,32 +398,6 @@ Reader.prototype.readToEnd = async function(join=concat) { return join(result); }; -let { ReadableStream, WritableStream, TransformStream } = globalThis; - -let toPonyfillReadable, toNativeReadable; - -async function loadStreamsPonyfill() { - if (TransformStream) { - return; - } - - const [ponyfill, adapter] = await Promise.all([ - Promise.resolve().then(function () { return ponyfill_es6; }), - Promise.resolve().then(function () { return webStreamsAdapter; }) - ]); - - ({ ReadableStream, WritableStream, TransformStream } = ponyfill); - - const { createReadableStreamWrapper } = adapter; - - if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) { - toPonyfillReadable = createReadableStreamWrapper(ReadableStream); - toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream); - } -} - -const NodeBuffer$1 = isNode && buffer.Buffer; - /** * Convert data to Stream * @param {ReadableStream|Uint8array|String} input data to convert @@ -507,12 +405,6 @@ const NodeBuffer$1 = isNode && buffer.Buffer; */ function toStream(input) { let streamType = isStream(input); - if (streamType === 'node') { - return nodeToWeb(input); - } - if (streamType === 'web' && toPonyfillReadable) { - return toPonyfillReadable(input); - } if (streamType) { return input; } @@ -525,7 +417,7 @@ function toStream(input) { } /** - * Convert data to ArrayStream + * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream. * @param {Object} input data to convert * @returns {ArrayStream} Converted data */ @@ -558,9 +450,6 @@ function concat(list) { if (typeof list[0] === 'string') { return list.join(''); } - if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) { - return NodeBuffer$1.concat(list); - } return concatUint8Array(list); } @@ -601,24 +490,6 @@ function concatArrayStream(list) { return result; } -/** - * Get a Reader - * @param {ReadableStream|Uint8array|String} input - * @returns {Reader} - */ -function getReader(input) { - return new Reader(input); -} - -/** - * Get a Writer - * @param {WritableStream} input - * @returns {Writer} - */ -function getWriter(input) { - return new Writer(input); -} - /** * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. * @param {ReadableStream|Uint8array|String} input @@ -655,6 +526,7 @@ async function pipe(input, target, { const reader = getReader(input); const writer = getWriter(target); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -906,6 +778,7 @@ function passiveClone(input) { const reader = getReader(readable); const writer = getWriter(writable); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -989,9 +862,8 @@ function slice(input, begin=0, end=Infinity) { if (returnValue.length >= -end) { lastBytes = slice(returnValue, end); return slice(returnValue, begin, end); - } else { - lastBytes = returnValue; } + lastBytes = returnValue; }); } console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); @@ -1000,9 +872,8 @@ function slice(input, begin=0, end=Infinity) { if (input[externalBuffer]) { input = concat(input[externalBuffer].concat([input])); } - if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) { - if (end === Infinity) end = input.length; - return input.subarray(begin, end); + if (isUint8Array(input)) { + return input.subarray(begin, end === Infinity ? input.length : end); } return input.slice(begin, end); } @@ -1034,7 +905,10 @@ async function readToEnd(input, join=concat) { async function cancel(input, reason) { if (isStream(input)) { if (input.cancel) { - return input.cancel(reason); + const cancelled = await input.cancel(reason); + // the stream is not always cancelled at this point, so we wait some more + await new Promise(setTimeout); + return cancelled; } if (input.destroy) { input.destroy(reason); @@ -1063,636 +937,152 @@ function fromAsync(fn) { return arrayStream; } -/* eslint-disable new-cap */ +/** + * Get a Reader + * @param {ReadableStream|Uint8array|String} input + * @returns {Reader} + */ +function getReader(input) { + return new Reader(input); +} /** - * @fileoverview - * BigInteger implementation of basic operations - * that wraps the native BigInt library. - * Operations are not constant time, - * but we try and limit timing leakage where we can - * @module biginteger/native - * @private + * Get a Writer + * @param {WritableStream} input + * @returns {Writer} */ +function getWriter(input) { + return new Writer(input); +} /** - * @private + * @module enums */ -class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on null or undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - if (n instanceof Uint8Array) { - const bytes = n; - const hex = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - const hexByte = bytes[i].toString(16); - hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte; - } - this.value = BigInt('0x0' + hex.join('')); - } else { - this.value = BigInt(n); - } - } +const byValue = Symbol('byValue'); - clone() { - return new BigInteger(this.value); - } +var enums = { - /** - * BigInteger increment in place + /** Maps curve names under various standards to one + * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} + * @enum {String} + * @readonly */ - iinc() { - this.value++; - return this; - } + curve: { + /** NIST P-256 Curve */ + 'nistP256': 'nistP256', + /** @deprecated use `nistP256` instead */ + 'p256': 'nistP256', - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } + /** NIST P-384 Curve */ + 'nistP384': 'nistP384', + /** @deprecated use `nistP384` instead */ + 'p384': 'nistP384', - /** - * BigInteger decrement in place - */ - idec() { - this.value--; - return this; - } + /** NIST P-521 Curve */ + 'nistP521': 'nistP521', + /** @deprecated use `nistP521` instead */ + 'p521': 'nistP521', - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + /** SECG SECP256k1 Curve */ + 'secp256k1': 'secp256k1', - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value += x.value; - return this; - } + /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ + 'ed25519Legacy': 'ed25519Legacy', + /** @deprecated use `ed25519Legacy` instead */ + 'ed25519': 'ed25519Legacy', - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ + 'curve25519Legacy': 'curve25519Legacy', + /** @deprecated use `curve25519Legacy` instead */ + 'curve25519': 'curve25519Legacy', - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value -= x.value; - return this; - } + /** BrainpoolP256r1 Curve */ + 'brainpoolP256r1': 'brainpoolP256r1', - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } + /** BrainpoolP384r1 Curve */ + 'brainpoolP384r1': 'brainpoolP384r1', - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value *= x.value; - return this; - } + /** BrainpoolP512r1 Curve */ + 'brainpoolP512r1': 'brainpoolP512r1' + }, - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. + /** A string to key specifier type + * @enum {Integer} + * @readonly */ - mul(x) { - return this.clone().imul(x); - } + s2k: { + simple: 0, + salted: 1, + iterated: 3, + argon2: 4, + gnu: 101 + }, - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} + * @enum {Integer} + * @readonly */ - imod(m) { - this.value %= m.value; - if (this.isNegative()) { - this.iadd(m); - } - return this; - } + publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ + rsaEncryptSign: 1, + /** RSA (Encrypt only) [HAC] */ + rsaEncrypt: 2, + /** RSA (Sign only) [HAC] */ + rsaSign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ + elgamal: 16, + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsaLegacy: 22, + /** Reserved for AEDH */ + aedh: 23, + /** Reserved for AEDSA */ + aedsa: 24, + /** X25519 (Encrypt only) */ + x25519: 25, + /** X448 (Encrypt only) */ + x448: 26, + /** Ed25519 (Sign only) */ + ed25519: 27, + /** Ed448 (Sign only) */ + ed448: 28 + }, - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + * @enum {Integer} + * @readonly */ - mod(m) { - return this.clone().imod(m); - } + symmetric: { + /** Not implemented! */ + idea: 1, + tripledes: 2, + cast5: 3, + blowfish: 4, + aes128: 7, + aes192: 8, + aes256: 9, + twofish: 10 + }, - /** - * Compute modular exponentiation using square and multiply - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + * @enum {Integer} + * @readonly */ - modExp(e, n) { - if (n.isZero()) throw Error('Modulo cannot be zero'); - if (n.isOne()) return new BigInteger(0); - if (e.isNegative()) throw Error('Unsopported negative exponent'); - - let exp = e.value; - let x = this.value; - - x %= n.value; - let r = BigInt(1); - while (exp > BigInt(0)) { - const lsb = exp & BigInt(1); - exp >>= BigInt(1); // e / 2 - // Always compute multiplication step, to reduce timing leakage - const rx = (r * x) % n.value; - // Update r only if lsb is 1 (odd exponent) - r = lsb ? rx : r; - x = (x * x) % n.value; // Square - } - return new BigInteger(r); - } - - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - const { gcd, x } = this._egcd(n); - if (!gcd.isOne()) { - throw new Error('Inverse does not exist'); - } - return x.add(n).mod(n); - } - - /** - * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) - * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b) - * @param {BigInteger} b - Second operand - * @returns {{ gcd, x, y: BigInteger }} - */ - _egcd(b) { - let x = BigInt(0); - let y = BigInt(1); - let xPrev = BigInt(1); - let yPrev = BigInt(0); - - let a = this.value; - b = b.value; - - while (b !== BigInt(0)) { - const q = a / b; - let tmp = x; - x = xPrev - q * x; - xPrev = tmp; - - tmp = y; - y = yPrev - q * y; - yPrev = tmp; - - tmp = b; - b = a % b; - a = tmp; - } - - return { - x: new BigInteger(xPrev), - y: new BigInteger(yPrev), - gcd: new BigInteger(a) - }; - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} b - Operand - * @returns {BigInteger} gcd - */ - gcd(b) { - let a = this.value; - b = b.value; - while (b !== BigInt(0)) { - const tmp = b; - b = a % b; - a = tmp; - } - return new BigInteger(a); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value <<= x.value; - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value >>= x.value; - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value === x.value; - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value < x.value; - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value <= x.value; - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value > x.value; - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value >= x.value; - } - - isZero() { - return this.value === BigInt(0); - } - - isOne() { - return this.value === BigInt(1); - } - - isNegative() { - return this.value < BigInt(0); - } - - isEven() { - return !(this.value & BigInt(1)); - } - - abs() { - const res = this.clone(); - if (this.isNegative()) { - res.value = -res.value; - } - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - const number = Number(this.value); - if (number > Number.MAX_SAFE_INTEGER) { - // We throw and error to conform with the bn.js implementation - throw new Error('Number can only safely store up to 53 bits'); - } - return number; - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - const bit = (this.value >> BigInt(i)) & BigInt(1); - return (bit === BigInt(0)) ? 0 : 1; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - const zero = new BigInteger(0); - const one = new BigInteger(1); - const negOne = new BigInteger(-1); - - // -1n >> -1n is -1n - // 1n >> 1n is 0n - const target = this.isNegative() ? negOne : zero; - let bitlen = 1; - const tmp = this.clone(); - while (!tmp.irightShift(one).equal(target)) { - bitlen++; - } - return bitlen; - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - const zero = new BigInteger(0); - const negOne = new BigInteger(-1); - - const target = this.isNegative() ? negOne : zero; - const eight = new BigInteger(8); - let len = 1; - const tmp = this.clone(); - while (!tmp.irightShift(eight).equal(target)) { - len++; - } - return len; - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) - // this is faster than shift+mod iterations - let hex = this.value.toString(16); - if (hex.length % 2 === 1) { - hex = '0' + hex; - } - - const rawLength = hex.length / 2; - const bytes = new Uint8Array(length || rawLength); - // parse hex - const offset = length ? (length - rawLength) : 0; - let i = 0; - while (i < rawLength) { - bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); - i++; - } - - if (endian !== 'be') { - bytes.reverse(); - } - - return bytes; - } -} - -const detectBigInt = () => typeof BigInt !== 'undefined'; - -async function getBigInteger() { - if (detectBigInt()) { - return BigInteger; - } else { - const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; }); - return BigInteger; - } -} - -/** - * @module enums - */ - -const byValue = Symbol('byValue'); - -var enums = { - - /** Maps curve names under various standards to one - * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} - * @enum {String} - * @readonly - */ - curve: { - /** NIST P-256 Curve */ - 'p256': 'p256', - 'P-256': 'p256', - 'secp256r1': 'p256', - 'prime256v1': 'p256', - '1.2.840.10045.3.1.7': 'p256', - '2a8648ce3d030107': 'p256', - '2A8648CE3D030107': 'p256', - - /** NIST P-384 Curve */ - 'p384': 'p384', - 'P-384': 'p384', - 'secp384r1': 'p384', - '1.3.132.0.34': 'p384', - '2b81040022': 'p384', - '2B81040022': 'p384', - - /** NIST P-521 Curve */ - 'p521': 'p521', - 'P-521': 'p521', - 'secp521r1': 'p521', - '1.3.132.0.35': 'p521', - '2b81040023': 'p521', - '2B81040023': 'p521', - - /** SECG SECP256k1 Curve */ - 'secp256k1': 'secp256k1', - '1.3.132.0.10': 'secp256k1', - '2b8104000a': 'secp256k1', - '2B8104000A': 'secp256k1', - - /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ - 'ed25519Legacy': 'ed25519', - 'ED25519': 'ed25519', - /** @deprecated use `ed25519Legacy` instead */ - 'ed25519': 'ed25519', - 'Ed25519': 'ed25519', - '1.3.6.1.4.1.11591.15.1': 'ed25519', - '2b06010401da470f01': 'ed25519', - '2B06010401DA470F01': 'ed25519', - - /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ - 'curve25519Legacy': 'curve25519', - 'X25519': 'curve25519', - 'cv25519': 'curve25519', - /** @deprecated use `curve25519Legacy` instead */ - 'curve25519': 'curve25519', - 'Curve25519': 'curve25519', - '1.3.6.1.4.1.3029.1.5.1': 'curve25519', - '2b060104019755010501': 'curve25519', - '2B060104019755010501': 'curve25519', - - /** BrainpoolP256r1 Curve */ - 'brainpoolP256r1': 'brainpoolP256r1', - '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1', - '2b2403030208010107': 'brainpoolP256r1', - '2B2403030208010107': 'brainpoolP256r1', - - /** BrainpoolP384r1 Curve */ - 'brainpoolP384r1': 'brainpoolP384r1', - '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1', - '2b240303020801010b': 'brainpoolP384r1', - '2B240303020801010B': 'brainpoolP384r1', - - /** BrainpoolP512r1 Curve */ - 'brainpoolP512r1': 'brainpoolP512r1', - '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1', - '2b240303020801010d': 'brainpoolP512r1', - '2B240303020801010D': 'brainpoolP512r1' - }, - - /** A string to key specifier type - * @enum {Integer} - * @readonly - */ - s2k: { - simple: 0, - salted: 1, - iterated: 3, - gnu: 101 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} - * @enum {Integer} - * @readonly - */ - publicKey: { - /** RSA (Encrypt or Sign) [HAC] */ - rsaEncryptSign: 1, - /** RSA (Encrypt only) [HAC] */ - rsaEncrypt: 2, - /** RSA (Sign only) [HAC] */ - rsaSign: 3, - /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ - elgamal: 16, - /** DSA (Sign only) [FIPS186] [HAC] */ - dsa: 17, - /** ECDH (Encrypt only) [RFC6637] */ - ecdh: 18, - /** ECDSA (Sign only) [RFC6637] */ - ecdsa: 19, - /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) - * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ - eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility - /** @deprecated use `eddsaLegacy` instead */ - ed25519Legacy: 22, - /** @deprecated use `eddsaLegacy` instead */ - eddsa: 22, - /** Reserved for AEDH */ - aedh: 23, - /** Reserved for AEDSA */ - aedsa: 24, - /** X25519 (Encrypt only) */ - x25519: 25, - /** X448 (Encrypt only) */ - x448: 26, - /** Ed25519 (Sign only) */ - ed25519: 27, - /** Ed448 (Sign only) */ - ed448: 28 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - * @enum {Integer} - * @readonly - */ - symmetric: { - plaintext: 0, - /** Not implemented! */ - idea: 1, - tripledes: 2, - cast5: 3, - blowfish: 4, - aes128: 7, - aes192: 8, - aes256: 9, - twofish: 10 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - * @enum {Integer} - * @readonly - */ - compression: { - uncompressed: 0, - /** RFC1951 */ - zip: 1, - /** RFC1950 */ - zlib: 2, - bzip2: 3 - }, + compression: { + uncompressed: 0, + /** RFC1951 */ + zip: 1, + /** RFC1950 */ + zlib: 2, + bzip2: 3 + }, /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} * @enum {Integer} @@ -1705,7 +1095,9 @@ var enums = { sha256: 8, sha384: 9, sha512: 10, - sha224: 11 + sha224: 11, + sha3_256: 12, + sha3_512: 14 }, /** A list of hash names as accepted by webCrypto functions. @@ -1726,6 +1118,7 @@ var enums = { aead: { eax: 1, ocb: 2, + gcm: 3, experimentalGCM: 100 // Private algorithm }, @@ -1751,7 +1144,8 @@ var enums = { userAttribute: 17, symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + padding: 21 }, /** Data types in the literal packet @@ -1907,7 +1301,7 @@ var enums = { placeholderBackwardsCompatibility: 10, preferredSymmetricAlgorithms: 11, revocationKey: 12, - issuer: 16, + issuerKeyID: 16, notationData: 20, preferredHashAlgorithms: 21, preferredCompressionAlgorithms: 22, @@ -1922,7 +1316,8 @@ var enums = { signatureTarget: 31, embeddedSignature: 32, issuerFingerprint: 33, - preferredAEADAlgorithms: 34 + preferredAEADAlgorithms: 34, + preferredCipherSuites: 39 }, /** Key flags @@ -1991,7 +1386,8 @@ var enums = { aead: 2, /** 0x04 - Version 5 Public-Key Packet format and corresponding new * fingerprint format */ - v5Keys: 4 + v5Keys: 4, + seipdv2: 8 }, /** @@ -2036,10 +1432,330 @@ var enums = { } }; -const debugMode = (() => { - try { - return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env - } catch (e) {} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +var config = { + /** + * @memberof module:config + * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} + */ + preferredHashAlgorithm: enums.hash.sha512, + /** + * @memberof module:config + * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} + */ + preferredSymmetricAlgorithm: enums.symmetric.aes256, + /** + * @memberof module:config + * @property {Integer} compression Default compression algorithm {@link module:enums.compression} + */ + preferredCompressionAlgorithm: enums.compression.uncompressed, + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * This option is applicable to: + * - key generation (encryption key preferences), + * - password-based message encryption, and + * - private key encryption. + * In the case of message encryption using public keys, the encryption key preferences are respected instead. + * Note: not all OpenPGP implementations are compatible with this option. + * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10} + * @memberof module:config + * @property {Boolean} aeadProtect + */ + aeadProtect: false, + /** + * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`) + * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`, + * this option must be set, otherwise key parsing and/or key decryption will fail. + * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys + * will be processed incorrectly. + */ + parseAEADEncryptedV4KeysAsLegacy: false, + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aeadProtect is set to true. + * @memberof module:config + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} + */ + preferredAEADAlgorithm: enums.aead.gcm, + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aeadProtect is set to true. + * Must be an integer value from 0 to 56. + * @memberof module:config + * @property {Integer} aeadChunkSizeByte + */ + aeadChunkSizeByte: 12, + /** + * Use v6 keys. + * Note: not all OpenPGP implementations are compatible with this option. + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + * @memberof module:config + * @property {Boolean} v6Keys + */ + v6Keys: false, + /** + * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet). + * These are non-standard entities, which in the crypto-refresh have been superseded + * by v6 keys and v6 signatures, respectively. + * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries, + * hence parsing them might be necessary in some cases. + */ + enableParsingV5Entities: false, + /** + * S2K (String to Key) type, used for key derivation in the context of secret key encryption + * and password-encrypted data. Weaker s2k options are not allowed. + * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it + * (pending standardisation). + * @memberof module:config + * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k} + */ + s2kType: enums.s2k.iterated, + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}: + * Iteration Count Byte for Iterated and Salted S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`. + * Note: this is the exponent value, not the final number of iterations (refer to specs for more details). + * @memberof module:config + * @property {Integer} s2kIterationCountByte + */ + s2kIterationCountByte: 224, + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}: + * Argon2 parameters for S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`. + * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"), + * to ensure compatibility with memory-constrained environments. + * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4. + * @memberof module:config + * @property {Object} params + * @property {Integer} params.passes - number of iterations t + * @property {Integer} params.parallelism - degree of parallelism p + * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes. + */ + s2kArgon2Params: { + passes: 3, + parallelism: 4, // lanes + memoryExponent: 16 // 64 MiB of RAM + }, + /** + * Allow decryption of messages without integrity protection. + * This is an **insecure** setting: + * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. + * - it enables downgrade attacks against integrity-protected messages. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedMessages + */ + allowUnauthenticatedMessages: false, + /** + * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to + * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible + * and deferring checking their integrity until the decrypted stream has been read in full. + * + * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity: + * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL + * (see https://efail.de/). + * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data. + * + * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedStream + */ + allowUnauthenticatedStream: false, + /** + * Minimum RSA key size allowed for key generation and message signing, verification and encryption. + * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. + * @memberof module:config + * @property {Number} minRSABits + */ + minRSABits: 2047, + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + * @memberof module:config + * @property {Boolean} passwordCollisionCheck + */ + passwordCollisionCheck: false, + /** + * Allow decryption using RSA keys without `encrypt` flag. + * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug + * where key flags were ignored when selecting a key for encryption. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureDecryptionWithSigningKeys: false, + /** + * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. + * Instead, a verification key will also be consider valid as long as it is valid at the current time. + * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, + * and have self-signature's creation date that does not match the primary key creation date. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureVerificationWithReformattedKeys: false, + /** + * Allow using keys that do not have any key flags set. + * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages + * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29). + * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation. + * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm. + */ + allowMissingKeyFlags: false, + /** + * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). + * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: + * - new/incoming messages are automatically decrypted (without user interaction); + * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). + * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. + * @memberof module:config + * @property {Boolean} constantTimePKCS1Decryption + */ + constantTimePKCS1Decryption: false, + /** + * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. + * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. + * However, the more algorithms are added, the slower the decryption procedure becomes. + * @memberof module:config + * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} + */ + constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), + /** + * @memberof module:config + * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error + */ + ignoreUnsupportedPackets: true, + /** + * @memberof module:config + * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error + */ + ignoreMalformedPackets: false, + /** + * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only + * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable + * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). + * @memberof module:config + * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] + */ + additionalAllowedPackets: [], + /** + * @memberof module:config + * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages + */ + showVersion: false, + /** + * @memberof module:config + * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages + */ + showComment: false, + /** + * @memberof module:config + * @property {String} versionString A version string to be included in armored messages + */ + versionString: 'OpenPGP.js 6.0.0', + /** + * @memberof module:config + * @property {String} commentString A comment string to be included in armored messages + */ + commentString: 'https://openpgpjs.org', + + /** + * Max userID string length (used for parsing) + * @memberof module:config + * @property {Integer} maxUserIDLength + */ + maxUserIDLength: 1024 * 5, + /** + * Contains notatations that are considered "known". Known notations do not trigger + * validation error when the notation is marked as critical. + * @memberof module:config + * @property {Array} knownNotations + */ + knownNotations: [], + /** + * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design). + * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur + * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of + * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks. + * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases. + */ + nonDeterministicSignaturesViaNotation: true, + /** + * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API. + * When false, certain standard curves will not be supported (depending on the platform). + * @memberof module:config + * @property {Boolean} useEllipticFallback + */ + useEllipticFallback: true, + /** + * Reject insecure hash algorithms + * @memberof module:config + * @property {Set} rejectHashAlgorithms {@link module:enums.hash} + */ + rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), + /** + * Reject insecure message hash algorithms + * @memberof module:config + * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} + */ + rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), + /** + * Reject insecure public key algorithms for key generation and message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} + */ + rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), + /** + * Reject non-standard curves for key generation, message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectCurves {@link module:enums.curve} + */ + rejectCurves: new Set([enums.curve.secp256k1]) +}; + +/** + * @fileoverview This object contains global configuration values. + * @see module:config/config + * @module config + */ + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const debugMode = (() => { + try { + return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env + } catch (e) {} return false; })(); @@ -2048,6 +1764,8 @@ const util = { return typeof data === 'string' || data instanceof String; }, + nodeRequire: createRequire(import.meta.url), + isArray: function(data) { return data instanceof Array; }, @@ -2056,6 +1774,35 @@ const util = { isStream: isStream, + /** + * Load noble-curves lib on demand and return the requested curve function + * @param {enums.publicKey} publicKeyAlgo + * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA) + * @returns curve implementation + * @throws on unrecognized curve, or curve not implemented by noble-curve + */ + getNobleCurve: async (publicKeyAlgo, curveName) => { + if (!config.useEllipticFallback) { + throw new Error('This curve is only supported in the full build of OpenPGP.js'); + } + + const { nobleCurves } = await Promise.resolve().then(function () { return noble_curves; }); + switch (publicKeyAlgo) { + case enums.publicKey.ecdh: + case enums.publicKey.ecdsa: { + const curve = nobleCurves.get(curveName); + if (!curve) throw new Error('Unsupported curve'); + return curve; + } + case enums.publicKey.x448: + return nobleCurves.get('x448'); + case enums.publicKey.ed448: + return nobleCurves.get('ed448'); + default: + throw new Error('Unsupported curve'); + } + }, + readNumber: function (bytes) { let n = 0; for (let i = 0; i < bytes.length; i++) { @@ -2097,7 +1844,26 @@ const util = { readMPI: function (bytes) { const bits = (bytes[0] << 8) | bytes[1]; const bytelen = (bits + 7) >>> 3; - return bytes.subarray(2, 2 + bytelen); + // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures, + // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed + // has not been authenticated (yet). + // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues. + // Also, AEAD is also not affected. + return util.readExactSubarray(bytes, 2, 2 + bytelen); + }, + + /** + * Read exactly `end - start` bytes from input. + * This is a stricter version of `.subarray`. + * @param {Uint8Array} input - Input data to parse + * @returns {Uint8Array} subarray of size always equal to `end - start` + * @throws if the input array is too short. + */ + readExactSubarray: function (input, start, end) { + if (input.length < (end - start)) { + throw new Error('Input array too short'); + } + return input.subarray(start, end); }, /** @@ -2107,6 +1873,9 @@ const util = { * @returns {Uint8Array} Padded bytes. */ leftPad(bytes, length) { + if (bytes.length > length) { + throw new Error('Input array too long'); + } const padded = new Uint8Array(length); const offset = length - bytes.length; padded.set(bytes, offset); @@ -2162,18 +1931,10 @@ const util = { * @returns {String} Hexadecimal representation of the array. */ uint8ArrayToHex: function (bytes) { - const r = []; - const e = bytes.length; - let c = 0; - let h; - while (c < e) { - h = bytes[c++].toString(16); - while (h.length < 2) { - h = '0' + h; - } - r.push('' + h); - } - return r.join(''); + const hexAlphabet = '0123456789abcdef'; + let s = ''; + bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; }); + return s; }, /** @@ -2384,32 +2145,30 @@ const util = { }, /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available */ getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; }, - /** - * Get BigInteger class - * It wraps the native BigInt type if it's available - * Otherwise it relies on bn.js - * @returns {BigInteger} - * @async - */ - getBigInteger, - /** * Get native Node.js crypto api. * @returns {Object} The crypto module or 'undefined'. */ getNodeCrypto: function() { - return crypto$3; + return this.nodeRequire('crypto'); }, getNodeZlib: function() { - return zlib; + return this.nodeRequire('zlib'); }, /** @@ -2418,7 +2177,7 @@ const util = { * @returns {Function} The Buffer constructor or 'undefined'. */ getNodeBuffer: function() { - return (buffer || {}).Buffer; + return (this.nodeRequire('buffer') || {}).Buffer; }, getHardwareConcurrency: function() { @@ -2426,15 +2185,24 @@ const util = { return navigator.hardwareConcurrency || 1; } - const os$1 = os; // Assume we're on Node.js. - return os$1.cpus().length; + const os = this.nodeRequire('os'); // Assume we're on Node.js. + return os.cpus().length; }, + /** + * Test email format to ensure basic compliance: + * - must include a single @ + * - no control or space unicode chars allowed + * - no backslash and square brackets (as the latter can mess with the userID parsing) + * - cannot end with a punctuation char + * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation, + * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)). + */ isEmailAddress: function(data) { if (!util.isString(data)) { return false; } - const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/; + const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u; return re.test(data); }, @@ -2637,14 +2405,15 @@ const util = { * provided with the application or distribution. */ -const Buffer = util.getNodeBuffer(); + +const Buffer$3 = util.getNodeBuffer(); let encodeChunk; let decodeChunk; -if (Buffer) { - encodeChunk = buf => Buffer.from(buf).toString('base64'); +if (Buffer$3) { + encodeChunk = buf => Buffer$3.from(buf).toString('base64'); decodeChunk = str => { - const b = Buffer.from(str, 'base64'); + const b = Buffer$3.from(str, 'base64'); return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); }; } else { @@ -2658,7 +2427,7 @@ if (Buffer) { * @returns {String | ReadableStream} Radix-64 version of input string. * @static */ -function encode(data) { +function encode$1(data) { let buf = new Uint8Array(); return transform(data, value => { buf = util.concatUint8Array([buf, value]); @@ -2682,7 +2451,7 @@ function encode(data) { * @returns {Uint8Array | ReadableStream} Binary array version of input string. * @static */ -function decode(data) { +function decode$2(data) { let buf = ''; return transform(data, value => { buf += value; @@ -2718,7 +2487,7 @@ function decode(data) { * @returns {Uint8Array} An array of 8-bit integers. */ function b64ToUint8Array(base64) { - return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); + return decode$2(base64.replace(/-/g, '+').replace(/_/g, '/')); } /** @@ -2728,254 +2497,30 @@ function b64ToUint8Array(base64) { * @returns {String} Base-64 encoded string. */ function uint8ArrayToB64(bytes, url) { - let encoded = encode(bytes).replace(/[\r\n]/g, ''); - if (url) { + let encoded = encode$1(bytes).replace(/[\r\n]/g, ''); + { encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); } return encoded; } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -var config = { - /** - * @memberof module:config - * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} - */ - preferredHashAlgorithm: enums.hash.sha256, - /** - * @memberof module:config - * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} - */ - preferredSymmetricAlgorithm: enums.symmetric.aes256, - /** - * @memberof module:config - * @property {Integer} compression Default compression algorithm {@link module:enums.compression} - */ - preferredCompressionAlgorithm: enums.compression.uncompressed, - /** - * @memberof module:config - * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9 - */ - deflateLevel: 6, - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} - * @memberof module:config - * @property {Boolean} aeadProtect - */ - aeadProtect: false, - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. - * @memberof module:config - * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} - */ - preferredAEADAlgorithm: enums.aead.eax, - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. - * Must be an integer value from 0 to 56. - * @memberof module:config - * @property {Integer} aeadChunkSizeByte - */ - aeadChunkSizeByte: 12, - /** - * Use V5 keys. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @memberof module:config - * @property {Boolean} v5Keys - */ - v5Keys: false, - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - * @memberof module:config - * @property {Integer} s2kIterationCountByte - */ - s2kIterationCountByte: 224, - /** - * Allow decryption of messages without integrity protection. - * This is an **insecure** setting: - * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. - * - it enables downgrade attacks against integrity-protected messages. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedMessages - */ - allowUnauthenticatedMessages: false, - /** - * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to - * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible - * and deferring checking their integrity until the decrypted stream has been read in full. - * - * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedStream - */ - allowUnauthenticatedStream: false, - /** - * @memberof module:config - * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum - */ - checksumRequired: false, - /** - * Minimum RSA key size allowed for key generation and message signing, verification and encryption. - * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. - * @memberof module:config - * @property {Number} minRSABits - */ - minRSABits: 2047, - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - * @memberof module:config - * @property {Boolean} passwordCollisionCheck - */ - passwordCollisionCheck: false, - /** - * @memberof module:config - * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored - */ - revocationsExpire: false, - /** - * Allow decryption using RSA keys without `encrypt` flag. - * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug - * where key flags were ignored when selecting a key for encryption. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureDecryptionWithSigningKeys: false, - /** - * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. - * Instead, a verification key will also be consider valid as long as it is valid at the current time. - * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, - * and have self-signature's creation date that does not match the primary key creation date. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureVerificationWithReformattedKeys: false, - - /** - * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). - * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: - * - new/incoming messages are automatically decrypted (without user interaction); - * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). - * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. - * @memberof module:config - * @property {Boolean} constantTimePKCS1Decryption - */ - constantTimePKCS1Decryption: false, - /** - * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. - * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. - * However, the more algorithms are added, the slower the decryption procedure becomes. - * @memberof module:config - * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} - */ - constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), - - /** - * @memberof module:config - * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available - */ - minBytesForWebCrypto: 1000, - /** - * @memberof module:config - * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error - */ - ignoreUnsupportedPackets: true, - /** - * @memberof module:config - * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error - */ - ignoreMalformedPackets: false, - /** - * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only - * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable - * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). - * @memberof module:config - * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] - */ - additionalAllowedPackets: [], - /** - * @memberof module:config - * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages - */ - showVersion: false, - /** - * @memberof module:config - * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages - */ - showComment: false, - /** - * @memberof module:config - * @property {String} versionString A version string to be included in armored messages - */ - versionString: 'OpenPGP.js 5.11.2', - /** - * @memberof module:config - * @property {String} commentString A comment string to be included in armored messages - */ - commentString: 'https://openpgpjs.org', - - /** - * Max userID string length (used for parsing) - * @memberof module:config - * @property {Integer} maxUserIDLength - */ - maxUserIDLength: 1024 * 5, - /** - * Contains notatations that are considered "known". Known notations do not trigger - * validation error when the notation is marked as critical. - * @memberof module:config - * @property {Array} knownNotations - */ - knownNotations: [], - /** - * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. - * When false, certain standard curves will not be supported (depending on the platform). - * Note: the indutny/elliptic curve library is not designed to be constant time. - * @memberof module:config - * @property {Boolean} useIndutnyElliptic - */ - useIndutnyElliptic: true, - /** - * Reject insecure hash algorithms - * @memberof module:config - * @property {Set} rejectHashAlgorithms {@link module:enums.hash} - */ - rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), - /** - * Reject insecure message hash algorithms - * @memberof module:config - * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} - */ - rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), - /** - * Reject insecure public key algorithms for key generation and message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} - */ - rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), - /** - * Reject non-standard curves for key generation, message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectCurves {@link module:enums.curve} - */ - rejectCurves: new Set([enums.curve.secp256k1]) -}; - -/** - * @fileoverview This object contains global configuration values. - * @see module:config/config - * @module config - */ - -// GPG4Browsers - An OpenPGP implementation in javascript /** * Finds out which Ascii Armoring type is used. Throws error if unknown type. @@ -3003,33 +2548,33 @@ function getType(text) { // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipartSection; - } else + } // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipartLast; - } else + } // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; - } else + } // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; - } else + } // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.publicKey; - } else + } // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.privateKey; - } else + } // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE @@ -3063,7 +2608,6 @@ function addheader(customComment, config) { return result; } - /** * Calculates a checksum over the given data and returns it base64 encoded * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for @@ -3072,7 +2616,7 @@ function addheader(customComment, config) { */ function getCheckSum(data) { const crc = createcrc24(data); - return encode(crc); + return encode$1(crc); } // https://create.stephan-brumme.com/crc32/#slicing-by-8-overview @@ -3105,7 +2649,7 @@ for (let i = 0; i <= 0xFF; i++) { } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness -const isLittleEndian = (function() { +const isLittleEndian$1 = (function() { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */); // Int16Array uses the platform's endianness. @@ -3121,7 +2665,7 @@ const isLittleEndian = (function() { function createcrc24(input) { let crc = 0xCE04B7; return transform(input, value => { - const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0; + const len32 = isLittleEndian$1 ? Math.floor(value.length / 4) : 0; const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32); for (let i = 0; i < len32; i++) { crc ^= arr32[i]; @@ -3145,7 +2689,7 @@ function createcrc24(input) { * @private * @param {Array} headers - Armor headers */ -function verifyHeaders(headers) { +function verifyHeaders$1(headers) { for (let i = 0; i < headers.length; i++) { if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); @@ -3157,24 +2701,21 @@ function verifyHeaders(headers) { } /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param {String} text - OpenPGP armored message part - * @returns {Object} An object with attribute "body" containing the body. - * and an attribute "checksum" containing the checksum. + * Remove the (optional) checksum from an armored message. + * @param {String} text - OpenPGP armored message + * @returns {String} The body of the armored message. * @private */ -function splitChecksum(text) { +function removeChecksum(text) { let body = text; - let checksum = ''; const lastEquals = text.lastIndexOf('='); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); - checksum = text.slice(lastEquals + 1).substr(0, 4); } - return { body: body, checksum: checksum }; + return body; } /** @@ -3186,7 +2727,7 @@ function splitChecksum(text) { * @async * @static */ -function unarmor(input, config$1 = config) { +function unarmor(input) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { @@ -3199,8 +2740,7 @@ function unarmor(input, config$1 = config) { let headersDone; let text = []; let textDone; - let checksum; - let data = decode(transformPair(input, async (readable, writable) => { + const data = decode$2(transformPair(input, async (readable, writable) => { const reader = getReader(readable); try { while (true) { @@ -3221,21 +2761,21 @@ function unarmor(input, config$1 = config) { if (!reEmptyLine.test(line)) { lastHeaders.push(line); } else { - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); headersDone = true; - if (textDone || type !== 2) { + if (textDone || type !== enums.armor.signed) { resolve({ text, data, headers, type }); break; } } - } else if (!textDone && type === 2) { + } else if (!textDone && type === enums.armor.signed) { if (!reSplit.test(line)) { // Reverse dash-escaping for msg text.push(line.replace(/^- /, '')); } else { text = text.join('\r\n'); textDone = true; - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); lastHeaders = []; headersDone = false; } @@ -3265,9 +2805,8 @@ function unarmor(input, config$1 = config) { if (parts.length === 1) { throw new Error('Misformed armored text'); } - const split = splitChecksum(parts[0].slice(0, -1)); - checksum = split.checksum; - await writer.write(split.body); + const body = removeChecksum(parts[0].slice(0, -1)); + await writer.write(body); break; } } @@ -3277,24 +2816,6 @@ function unarmor(input, config$1 = config) { await writer.abort(e); } })); - data = transformPair(data, async (readable, writable) => { - const checksumVerified = readToEnd(getCheckSum(passiveClone(readable))); - checksumVerified.catch(() => {}); - await pipe(readable, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - const checksumVerifiedString = (await checksumVerified).replace('\n', ''); - if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) { - throw new Error('Ascii armor integrity check failed'); - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); } catch (e) { reject(e); } @@ -3314,10 +2835,13 @@ function unarmor(input, config$1 = config) { * @param {Integer} [partIndex] * @param {Integer} [partTotal] * @param {String} [customComment] - Additional comment to add to the armored string + * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum + * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks) + * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {String | ReadableStream} Armored text. * @static */ -function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) { +function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) { let text; let hash; if (messageType === enums.armor.signed) { @@ -3325,59 +2849,62 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 hash = body.hash; body = body.data; } - const bodyClone = passiveClone(body); + // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug + // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071) + const maybeBodyClone = emitChecksum && passiveClone(body); + const result = []; switch (messageType) { case enums.armor.multipartSection: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); break; case enums.armor.multipartLast: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); break; case enums.armor.signed: result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); - result.push('Hash: ' + hash + '\n\n'); + result.push(hash ? `Hash: ${hash}\n\n` : '\n'); result.push(text.replace(/^-/mg, '- -')); result.push('\n-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; case enums.armor.message: result.push('-----BEGIN PGP MESSAGE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE-----\n'); break; case enums.armor.publicKey: result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); break; case enums.armor.privateKey: result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); break; case enums.armor.signature: result.push('-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; } @@ -3385,40695 +2912,25668 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 return util.concat(result); } -// GPG4Browsers - An OpenPGP implementation in javascript +async function getLegacyCipher(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + throw new Error('Not a legacy cipher'); + case enums.symmetric.cast5: + case enums.symmetric.blowfish: + case enums.symmetric.twofish: + case enums.symmetric.tripledes: { + const { legacyCiphers } = await Promise.resolve().then(function () { return legacy_ciphers; }); + const cipher = legacyCiphers.get(algo); + if (!cipher) { + throw new Error('Unsupported cipher algorithm'); + } + return cipher; + } + default: + throw new Error('Unsupported cipher algorithm'); + } +} /** - * Implementation of type key id - * - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. + * Get block size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -class KeyID { - constructor() { - this.bytes = ''; - } - - /** - * Parsing method for a key id - * @param {Uint8Array} bytes - Input to read the key id from - */ - read(bytes) { - this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); - return this.bytes.length; - } - - /** - * Serializes the Key ID - * @returns {Uint8Array} Key ID as a Uint8Array. - */ - write() { - return util.stringToUint8Array(this.bytes); - } - - /** - * Returns the Key ID represented as a hexadecimal string - * @returns {String} Key ID as a hexadecimal string. - */ - toHex() { - return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); - } - - /** - * Checks equality of Key ID's - * @param {KeyID} keyID - * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard - */ - equals(keyID, matchWildcard = false) { - return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; - } - - /** - * Checks to see if the Key ID is unset - * @returns {Boolean} True if the Key ID is null. - */ - isNull() { - return this.bytes === ''; - } - - /** - * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) - * @returns {Boolean} True if this is a wildcard Key ID. - */ - isWildcard() { - return /^0+$/.test(this.toHex()); - } - - static mapToHex(keyID) { - return keyID.toHex(); - } - - static fromID(hex) { - const keyID = new KeyID(); - keyID.read(util.hexToUint8Array(hex)); - return keyID; +function getCipherBlockSize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 16; + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + case enums.symmetric.tripledes: + return 8; + default: + throw new Error('Unsupported cipher'); } +} - static wildcard() { - const keyID = new KeyID(); - keyID.read(new Uint8Array(8)); - return keyID; +/** + * Get key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherKeySize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + return 16; + case enums.symmetric.aes192: + case enums.symmetric.tripledes: + return 24; + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 32; + default: + throw new Error('Unsupported cipher'); } } /** - * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. - * @author Artem S Vybornov - * @license MIT + * Get block and key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -var AES_asm = function () { - - /** - * Galois Field stuff init flag - */ - var ginit_done = false; +function getCipherParams(algo) { + return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) }; +} - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; +var cipher = /*#__PURE__*/Object.freeze({ + __proto__: null, + getCipherParams: getCipherParams, + getLegacyCipher: getLegacyCipher +}); - /** - * Init Galois Field tables - */ - function ginit() { - gexp3 = [], - glog3 = []; +/** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ - var a = 1, c, d; - for (c = 0; c < 255; c++) { - gexp3[c] = a; - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if (d === 0x80) a ^= 0x1b; - a ^= gexp3[c]; +// MD5 Digest +async function md5(entree) { + const digest = md51(util.uint8ArrayToString(entree)); + return util.hexToUint8Array(hex(digest)); +} - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; +function md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; - ginit_done = true; - } + a = ff(a, b, c, d, k[0], 7, -680876936); + d = ff(d, a, b, c, k[1], 12, -389564586); + c = ff(c, d, a, b, k[2], 17, 606105819); + b = ff(b, c, d, a, k[3], 22, -1044525330); + a = ff(a, b, c, d, k[4], 7, -176418897); + d = ff(d, a, b, c, k[5], 12, 1200080426); + c = ff(c, d, a, b, k[6], 17, -1473231341); + b = ff(b, c, d, a, k[7], 22, -45705983); + a = ff(a, b, c, d, k[8], 7, 1770035416); + d = ff(d, a, b, c, k[9], 12, -1958414417); + c = ff(c, d, a, b, k[10], 17, -42063); + b = ff(b, c, d, a, k[11], 22, -1990404162); + a = ff(a, b, c, d, k[12], 7, 1804603682); + d = ff(d, a, b, c, k[13], 12, -40341101); + c = ff(c, d, a, b, k[14], 17, -1502002290); + b = ff(b, c, d, a, k[15], 22, 1236535329); - /** - * Galois Field multiplication - * @param {number} a - * @param {number} b - * @return {number} - */ - function gmul(a, b) { - var c = gexp3[(glog3[a] + glog3[b]) % 255]; - if (a === 0 || b === 0) c = 0; - return c; - } + a = gg(a, b, c, d, k[1], 5, -165796510); + d = gg(d, a, b, c, k[6], 9, -1069501632); + c = gg(c, d, a, b, k[11], 14, 643717713); + b = gg(b, c, d, a, k[0], 20, -373897302); + a = gg(a, b, c, d, k[5], 5, -701558691); + d = gg(d, a, b, c, k[10], 9, 38016083); + c = gg(c, d, a, b, k[15], 14, -660478335); + b = gg(b, c, d, a, k[4], 20, -405537848); + a = gg(a, b, c, d, k[9], 5, 568446438); + d = gg(d, a, b, c, k[14], 9, -1019803690); + c = gg(c, d, a, b, k[3], 14, -187363961); + b = gg(b, c, d, a, k[8], 20, 1163531501); + a = gg(a, b, c, d, k[13], 5, -1444681467); + d = gg(d, a, b, c, k[2], 9, -51403784); + c = gg(c, d, a, b, k[7], 14, 1735328473); + b = gg(b, c, d, a, k[12], 20, -1926607734); - /** - * Galois Field reciprocal - * @param {number} a - * @return {number} - */ - function ginv(a) { - var i = gexp3[255 - glog3[a]]; - if (a === 0) i = 0; - return i; - } + a = hh(a, b, c, d, k[5], 4, -378558); + d = hh(d, a, b, c, k[8], 11, -2022574463); + c = hh(c, d, a, b, k[11], 16, 1839030562); + b = hh(b, c, d, a, k[14], 23, -35309556); + a = hh(a, b, c, d, k[1], 4, -1530992060); + d = hh(d, a, b, c, k[4], 11, 1272893353); + c = hh(c, d, a, b, k[7], 16, -155497632); + b = hh(b, c, d, a, k[10], 23, -1094730640); + a = hh(a, b, c, d, k[13], 4, 681279174); + d = hh(d, a, b, c, k[0], 11, -358537222); + c = hh(c, d, a, b, k[3], 16, -722521979); + b = hh(b, c, d, a, k[6], 23, 76029189); + a = hh(a, b, c, d, k[9], 4, -640364487); + d = hh(d, a, b, c, k[12], 11, -421815835); + c = hh(c, d, a, b, k[15], 16, 530742520); + b = hh(b, c, d, a, k[2], 23, -995338651); - /** - * AES stuff init flag - */ - var aes_init_done = false; + a = ii(a, b, c, d, k[0], 6, -198630844); + d = ii(d, a, b, c, k[7], 10, 1126891415); + c = ii(c, d, a, b, k[14], 15, -1416354905); + b = ii(b, c, d, a, k[5], 21, -57434055); + a = ii(a, b, c, d, k[12], 6, 1700485571); + d = ii(d, a, b, c, k[3], 10, -1894986606); + c = ii(c, d, a, b, k[10], 15, -1051523); + b = ii(b, c, d, a, k[1], 21, -2054922799); + a = ii(a, b, c, d, k[8], 6, 1873313359); + d = ii(d, a, b, c, k[15], 10, -30611744); + c = ii(c, d, a, b, k[6], 15, -1560198380); + b = ii(b, c, d, a, k[13], 21, 1309151649); + a = ii(a, b, c, d, k[4], 6, -145523070); + d = ii(d, a, b, c, k[11], 10, -1120210379); + c = ii(c, d, a, b, k[2], 15, 718787259); + b = ii(b, c, d, a, k[9], 21, -343485551); - /** - * Encryption, Decryption, S-Box and KeyTransform tables - * - * @type {number[]} - */ - var aes_sbox; + x[0] = add32(a, x[0]); + x[1] = add32(b, x[1]); + x[2] = add32(c, x[2]); + x[3] = add32(d, x[3]); +} - /** - * @type {number[]} - */ - var aes_sinv; +function cmn(q, a, b, x, s, t) { + a = add32(add32(a, q), add32(x, t)); + return add32((a << s) | (a >>> (32 - s)), b); +} - /** - * @type {number[][]} - */ - var aes_enc; +function ff(a, b, c, d, x, s, t) { + return cmn((b & c) | ((~b) & d), a, b, x, s, t); +} - /** - * @type {number[][]} - */ - var aes_dec; +function gg(a, b, c, d, x, s, t) { + return cmn((b & d) | (c & (~d)), a, b, x, s, t); +} - /** - * Init AES tables - */ - function aes_init() { - if (!ginit_done) ginit(); +function hh(a, b, c, d, x, s, t) { + return cmn(b ^ c ^ d, a, b, x, s, t); +} - // Calculates AES S-Box value - function _s(a) { - var c, s, x; - s = x = ginv(a); - for (c = 0; c < 4; c++) { - s = ((s << 1) | (s >>> 7)) & 255; - x ^= s; - } - x ^= 99; - return x; - } - - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [[], [], [], []], - aes_dec = [[], [], [], []]; - - for (var i = 0; i < 256; i++) { - var s = _s(i); - - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; - - // Ecryption and Decryption tables - aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s); - aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i); - // Rotate tables - for (var t = 1; t < 4; t++) { - aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24); - aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24); - } - } +function ii(a, b, c, d, x, s, t) { + return cmn(c ^ (b | (~d)), a, b, x, s, t); +} - aes_init_done = true; +function md51(s) { + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; + for (i = 64; i <= s.length; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); } - - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-   * 0x0000   encryption key schedule
-   * 0x0400   decryption key schedule
-   * 0x0800   sbox
-   * 0x0c00   inv sbox
-   * 0x1000   encryption tables
-   * 0x2000   decryption tables
-   * 0x3000   reserved (future GCM multiplication lookup table)
-   * 0x4000   data
-   * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param foreign - ignored - * @param buffer - heap buffer to link with - */ - var wrapper = function (foreign, buffer) { - // Init AES stuff for the first time - if (!aes_init_done) aes_init(); - - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set(aes_sbox, 0x0800 >> 2); - heap.set(aes_sinv, 0x0c00 >> 2); - for (var i = 0; i < 4; i++) { - heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2); - heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2); + s = s.substring(i - 64); + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < s.length; i++) { + tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + } + tail[i >> 2] |= 0x80 << ((i % 4) << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i++) { + tail[i] = 0; } + } + tail[14] = n * 8; + md5cycle(state, tail); + return state; +} - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {number} k0 - key vector components - * @param {number} k1 - key vector components - * @param {number} k2 - key vector components - * @param {number} k3 - key vector components - * @param {number} k4 - key vector components - * @param {number} k5 - key vector components - * @param {number} k6 - key vector components - * @param {number} k7 - key vector components - */ - function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { - var ekeys = heap.subarray(0x000, 60), - dkeys = heap.subarray(0x100, 0x100 + 60); - - // Encryption key schedule - ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); - for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { - var k = ekeys[i - 1]; - if ((i % ks === 0) || (ks === 8 && i % ks === 4)) { - k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; - } - if (i % ks === 0) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0); - } - ekeys[i] = ekeys[i - ks] ^ k; - } - - // Decryption key schedule - for (var j = 0; j < i; j += 4) { - for (var jj = 0; jj < 4; jj++) { - var k = ekeys[i - (4 + j) + (4 - jj) % 4]; - if (j < 4 || j >= i - 4) { - dkeys[j + jj] = k; - } else { - dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] - ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] - ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] - ^ aes_dec[3][aes_sbox[k & 255]]; - } - } - } - - // Set rounds number - asm.set_rounds(ks + 5); - } - - // create library object with necessary properties - var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array}; - - var asm = function (stdlib, foreign, buffer) { - "use asm"; - - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); - - /** - * AES core - * @param {number} k - precomputed key schedule offset - * @param {number} s - precomputed sbox table offset - * @param {number} t - precomputed round table offset - * @param {number} r - number of inner rounds to perform - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _core(k, s, t, r, x0, x1, x2, x3) { - k = k | 0; - s = s | 0; - t = t | 0; - r = r | 0; - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k | 0) >> 2], - x1 = x1 ^ HEAP[(k | 4) >> 2], - x2 = x2 ^ HEAP[(k | 8) >> 2], - x3 = x3 ^ HEAP[(k | 12) >> 2]; - - // round 1..r - for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) { - y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } - - // final round - S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - } - - /** - * ECB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } - - /** - * ECB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - } - - - /** - * CBC mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } - - /** - * CBC mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * CFB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } - - - /** - * CFB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * OFB mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ofb(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * CTR mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ctr(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); - - N3 = (~M3 & N3) | M3 & (N3 + 1); - N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0)); - N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0)); - N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0)); - - S0 = S0 ^ x0; - S1 = S1 ^ x1; - S2 = S2 ^ x2; - S3 = S3 ^ x3; - } - - /** - * GCM mode MAC calculation - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _gcm_mac(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0 | 0, - y1 = H1 | 0, - y2 = H2 | 0, - y3 = H3 | 0; - - for (; (i | 0) < 128; i = (i + 1) | 0) { - if (y0 >>> 31) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } - - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); - - c = x3 & 1; - - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); - - if (c) x0 = x0 ^ 0xe1000000; - } - - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } - - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {number} r - number if inner AES rounds - */ - function set_rounds(r) { - r = r | 0; - R = r; - } - - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {number} s0 - state vector - * @param {number} s1 - state vector - * @param {number} s2 - state vector - * @param {number} s3 - state vector - */ - function set_state(s0, s1, s2, s3) { - s0 = s0 | 0; - s1 = s1 | 0; - s2 = s2 | 0; - s3 = s3 | 0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } - - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {number} i0 - iv vector - * @param {number} i1 - iv vector - * @param {number} i2 - iv vector - * @param {number} i3 - iv vector - */ - function set_iv(i0, i1, i2, i3) { - i0 = i0 | 0; - i1 = i1 | 0; - i2 = i2 | 0; - i3 = i3 | 0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } - - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} n0 - nonce vector - * @param {number} n1 - nonce vector - * @param {number} n2 - nonce vector - * @param {number} n3 - nonce vector - */ - function set_nonce(n0, n1, n2, n3) { - n0 = n0 | 0; - n1 = n1 | 0; - n2 = n2 | 0; - n3 = n3 | 0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } - - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} m0 - counter mask vector - * @param {number} m1 - counter mask vector - * @param {number} m2 - counter mask vector - * @param {number} m3 - counter mask vector - */ - function set_mask(m0, m1, m2, m3) { - m0 = m0 | 0; - m1 = m1 | 0; - m2 = m2 | 0; - m3 = m3 | 0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } - - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} c0 - counter vector - * @param {number} c1 - counter vector - * @param {number} c2 - counter vector - * @param {number} c3 - counter vector - */ - function set_counter(c0, c1, c2, c3) { - c0 = c0 | 0; - c1 = c1 | 0; - c2 = c2 | 0; - c3 = c3 | 0; - - N3 = (~M3 & N3) | M3 & c3, - N2 = (~M2 & N2) | M2 & c2, - N1 = (~M1 & N1) | M1 & c1, - N0 = (~M0 & N0) | M0 & c0; - } - - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_state(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - return 16; - } - - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_iv(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = I0 >>> 24, - DATA[pos | 1] = I0 >>> 16 & 255, - DATA[pos | 2] = I0 >>> 8 & 255, - DATA[pos | 3] = I0 & 255, - DATA[pos | 4] = I1 >>> 24, - DATA[pos | 5] = I1 >>> 16 & 255, - DATA[pos | 6] = I1 >>> 8 & 255, - DATA[pos | 7] = I1 & 255, - DATA[pos | 8] = I2 >>> 24, - DATA[pos | 9] = I2 >>> 16 & 255, - DATA[pos | 10] = I2 >>> 8 & 255, - DATA[pos | 11] = I2 & 255, - DATA[pos | 12] = I3 >>> 24, - DATA[pos | 13] = I3 >>> 16 & 255, - DATA[pos | 14] = I3 >>> 8 & 255, - DATA[pos | 15] = I3 & 255; - - return 16; - } - - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init() { - _ecb_enc(0, 0, 0, 0); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } - - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function cipher(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; - - var ret = 0; +/* there needs to be support for Unicode here, + * unless we pretend that we can redefine the MD-5 + * algorithm for multi-byte characters (perhaps + * by adding every four 16-bit characters and + * shortening the sum to 32 bits). Otherwise + * I suggest performing MD-5 as if every character + * was two bytes--e.g., 0040 0025 = @%--but then + * how will an ordinary MD-5 sum be matched? + * There is no way to standardize text to something + * like UTF-8 before transformation; speed cost is + * utterly prohibitive. The JavaScript standard + * itself needs to look at this: it should start + * providing access to strings as preformed UTF-8 + * 8-bit unsigned value arrays. + */ +function md5blk(s) { /* I figured global was faster. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << + 24); + } + return md5blks; +} - if (pos & 15) return -1; +const hex_chr = '0123456789abcdef'.split(''); - while ((len | 0) >= 16) { - _cipher_modes[mode & 7]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); +function rhex(n) { + let s = ''; + let j = 0; + for (; j < 4; j++) { + s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; + } + return s; +} - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } +function hex(x) { + for (let i = 0; i < x.length; i++) { + x[i] = rhex(x[i]); + } + return x.join(''); +} - return ret | 0; - } +/* this function is much faster, +so if possible we use it. Some IEs +are the only ones I know of that +need the idiotic second function, +generated by an if clause. */ - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function mac(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; +function add32(a, b) { + return (a + b) & 0xFFFFFFFF; +} - var ret = 0; +/** + * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. + * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} + * @see {@link https://github.com/indutny/hash.js|hash.js} + * @module crypto/hash + */ - if (pos & 15) return -1; - while ((len | 0) >= 16) { - _mac_modes[mode & 1]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); +const webCrypto$a = util.getWebCrypto(); +const nodeCrypto$9 = util.getNodeCrypto(); +const nodeCryptoHashes = nodeCrypto$9 && nodeCrypto$9.getHashes(); - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } +function nodeHash(type) { + if (!nodeCrypto$9 || !nodeCryptoHashes.includes(type)) { + return; + } + return async function (data) { + const shasum = nodeCrypto$9.createHash(type); + return transform(data, value => { + shasum.update(value); + }, () => new Uint8Array(shasum.digest())); + }; +} - return ret | 0; - } +function nobleHash(nobleHashName, webCryptoHashName) { + const getNobleHash = async () => { + const { nobleHashes } = await Promise.resolve().then(function () { return noble_hashes; }); + const hash = nobleHashes.get(nobleHashName); + if (!hash) throw new Error('Unsupported hash'); + return hash; + }; - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; + return async function(data) { + if (isArrayStream(data)) { + data = await readToEnd(data); + } + if (util.isStream(data)) { + const hash = await getNobleHash(); - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [_cbc_enc, _gcm_mac]; + const hashInstance = hash.create(); + return transform(data, value => { + hashInstance.update(value); + }, () => hashInstance.digest()); + } else if (webCrypto$a && webCryptoHashName) { + return new Uint8Array(await webCrypto$a.digest(webCryptoHashName, data)); + } else { + const hash = await getNobleHash(); - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter: set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac, - }; - }(stdlib, foreign, buffer); + return hash(data); + } + }; +} - asm.set_key = set_key; +var hash$1 = { - return asm; - }; + /** @see module:md5 */ + md5: nodeHash('md5') || md5, + sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'), + sha224: nodeHash('sha224') || nobleHash('sha224'), + sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'), + sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'), + sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'), + ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'), + sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'), + sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'), /** - * AES enciphering mode constants - * @enum {number} - * @const + * Create a hash on the specified data using the specified algorithm + * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param {Uint8Array} data - Data to be hashed + * @returns {Promise} Hash value. */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7, + digest: function(algo, data) { + switch (algo) { + case enums.hash.md5: + return this.md5(data); + case enums.hash.sha1: + return this.sha1(data); + case enums.hash.ripemd: + return this.ripemd(data); + case enums.hash.sha256: + return this.sha256(data); + case enums.hash.sha384: + return this.sha384(data); + case enums.hash.sha512: + return this.sha512(data); + case enums.hash.sha224: + return this.sha224(data); + case enums.hash.sha3_256: + return this.sha3_256(data); + case enums.hash.sha3_512: + return this.sha3_512(data); + default: + throw new Error('Unsupported hash function'); + } }, - /** - * AES deciphering mode constants - * @enum {number} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7, - }, - - /** - * AES MAC mode constants - * @enum {number} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1, - }; - /** - * Heap data offset - * @type {number} - * @const + * Returns the hash size in bytes of the specified hash algorithm type + * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns {Integer} Size in bytes of the resulting hash. */ - wrapper.HEAP_DATA = 0x4000; - - return wrapper; -}(); - -function is_bytes(a) { - return a instanceof Uint8Array; -} -function _heap_init(heap, heapSize) { - const size = heap ? heap.byteLength : heapSize || 65536; - if (size & 0xfff || size <= 0) - throw new Error('heap size must be a positive integer and a multiple of 4096'); - heap = heap || new Uint8Array(new ArrayBuffer(size)); - return heap; -} -function _heap_write(heap, hpos, data, dpos, dlen) { - const hlen = heap.length - hpos; - const wlen = hlen < dlen ? hlen : dlen; - heap.set(data.subarray(dpos, dpos + wlen), hpos); - return wlen; -} -function joinBytes(...arg) { - const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0); - const ret = new Uint8Array(totalLenght); - let cursor = 0; - for (let i = 0; i < arg.length; i++) { - ret.set(arg[i], cursor); - cursor += arg[i].length; - } - return ret; -} - -class IllegalStateError extends Error { - constructor(...args) { - super(...args); + getHashByteLength: function(algo) { + switch (algo) { + case enums.hash.md5: + return 16; + case enums.hash.sha1: + case enums.hash.ripemd: + return 20; + case enums.hash.sha256: + return 32; + case enums.hash.sha384: + return 48; + case enums.hash.sha512: + return 64; + case enums.hash.sha224: + return 28; + case enums.hash.sha3_256: + return 32; + case enums.hash.sha3_512: + return 64; + default: + throw new Error('Invalid hash algorithm.'); } + } +}; + +function isBytes$2(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } -class IllegalArgumentError extends Error { - constructor(...args) { - super(...args); - } +function bytes$1(b, ...lengths) { + if (!isBytes$2(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); } -class SecurityError extends Error { - constructor(...args) { - super(...args); +function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output$1(out, instance) { + bytes$1(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } -const heap_pool = []; -const asm_pool = []; -class AES { - constructor(key, iv, padding = true, mode, heap, asm) { - this.pos = 0; - this.len = 0; - this.mode = mode; - // The AES object state - this.pos = 0; - this.len = 0; - this.key = key; - this.iv = iv; - this.padding = padding; - // The AES "worker" - this.acquire_asm(heap, asm); - } - acquire_asm(heap, asm) { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA); - this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer); - this.reset(this.key, this.iv); - } - return { heap: this.heap, asm: this.asm }; +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// Cast array to different type +const u8$1 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32$2 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE$1) + throw new Error('Non little-endian hardware is not supported'); +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$2(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes$1(data) { + if (typeof data === 'string') + data = utf8ToBytes$2(data); + else if (isBytes$2(data)) + data = copyBytes(data); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes$1(a); + sum += a.length; } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool.push(this.heap); - asm_pool.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - reset(key, iv) { - const { asm } = this.acquire_asm(); - // Key - const keylen = key.length; - if (keylen !== 16 && keylen !== 24 && keylen !== 32) - throw new IllegalArgumentError('illegal key size'); - const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); - asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0); - // IV - if (iv !== undefined) { - if (iv.length !== 16) - throw new IllegalArgumentError('illegal iv size'); - let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); - asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); - } - else { - asm.set_iv(0, 0, 0, 0); - } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; } - AES_Encrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - let result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes$1(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +// Polyfill for Safari 14 +function setBigUint64$1(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = 0; + const l = 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +// copy bytes to new u8a (aligned). Because Buffer.slice is broken. +function copyBytes(bytes) { + return Uint8Array.from(bytes); +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE$1 = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32$2(ZEROS16); +const POLY$1 = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2$1 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE$1; + this.outputLen = BLOCK_SIZE$1; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes$1(key); + bytes$1(key, 16); + const kView = createView$1(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); } } - this.pos = pos; - this.len = len; - return result; - } - AES_Encrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let plen = 16 - (len % 16); - let rlen = len; - if (this.hasOwnProperty('padding')) { - if (this.padding) { - for (let p = 0; p < plen; ++p) { - heap[pos + len + p] = plen; + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; } - len += plen; - rlen = len; - } - else if (len % 16) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); } } - else { - len += plen; + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + const left = data.length % BLOCK_SIZE$1; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + clean(ZEROS32); // clean tmp buffer } - const result = new Uint8Array(rlen); - if (len) - asm.cipher(amode, hpos + pos, len); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - AES_Decrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let plen = 0; - let wlen = 0; - if (this.padding) { - plen = len + dlen - rlen || 16; - rlen -= plen; + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE$1); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes$1(key); + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const left = data.length % BLOCK_SIZE$1; + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + clean(ZEROS32); } - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; + return this; + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes$1(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + +// prettier-ignore +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// The byte swap operation for uint32 (LE<->BE) +const byteSwap$1 = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +function expandKeyLE(key) { + bytes$1(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const toClean = []; + if (!isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = u32$2(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; +} +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (dst === undefined) + return new Uint8Array(len); + bytes$1(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + if (!isAligned32(dst)) + throw new Error('unaligned dst'); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32$2(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32$2(ctr); + const view = createView$1(ctr); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + bytes$1(key); + bytes$1(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + bytes$1(buf); + if (dst !== undefined) { + bytes$1(dst); + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + bytes$1(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + bytes$1(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (!isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32$2(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32$2(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error('aes/pcks5: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error('aes/pcks5: wrong padding'); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error('aes/pcks5: wrong padding'); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32$2(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + bytes$1(key); + bytes$1(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); } - else { - pos = 0; - len = 0; + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + const out = getDst(ciphertext.length, dst); + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32$2(ciphertext); + const o = u32$2(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$6(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); } + clean(...toClean); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +const cfb$1 = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + bytes$1(key); + bytes$1(iv, 16); + function processCfb(src, isEncrypt, dst) { + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$6(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + const buf = u8$1(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD == null ? 0 : AAD.length; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView$1(num); + if (AAD) + setBigUint64$1(view, 0, BigInt(aadLength * 8), isLE); + setBigUint64$1(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} +/** + * GCM: Galois/Counter Mode. + * Modern, parallel version of CTR, with MAC. + * Be careful: MACs can be forged. + * Unsafe to use random nonces under the same key, due to collision chance. + * As for nonce size, prefer 12-byte, instead of 8-byte. + */ +const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + bytes$1(key); + bytes$1(nonce); + if (AAD !== undefined) + bytes$1(AAD); + // NIST 800-38d doesn't enforce minimum nonce length. + // We enforce 8 bytes for compat with openssl. + // 12 bytes are recommended. More than 12 bytes would be converted into 12. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); } - this.pos = pos; - this.len = len; - return result; - } - AES_Decrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let rlen = len; - if (len > 0) { - if (len % 16) { - if (this.hasOwnProperty('padding')) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - else { - len += 16 - (len % 16); + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView$1(nonceLen); + setBigUint64$1(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + bytes$1(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + if (!equalBytes$1(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = encrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = decrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +/** + * AES-W (base for AESKW/AESKWP). + * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf), + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/). + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints. + // If you need it larger, open an issue. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i + (a0 = s0), (a1 = s1 ^ byteSwap$1(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3); } } - asm.cipher(amode, hpos + pos, len); - if (this.hasOwnProperty('padding') && this.padding) { - let pad = heap[pos + rlen - 1]; - if (pad < 1 || pad > 16 || pad > rlen) - throw new SecurityError('bad padding'); - let pcheck = 0; - for (let i = pad; i > 1; i--) - pcheck |= pad ^ heap[pos + rlen - i]; - if (pcheck) - throw new SecurityError('bad padding'); - rlen -= pad; - } + (o32[0] = a0), (o32[1] = a1); // out = A || out } - const result = new Uint8Array(rlen); - if (rlen > 0) { - result.set(heap.subarray(pos, pos + rlen)); + xk.fill(0); + }, + decrypt(kek, out) { + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap$1(ctr); + const { s0, s1, s2, s3 } = decrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); } - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } -} + xk.fill(0); + }, +}; +const AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * For padded version, use aeskwp. + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf). + */ +const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + bytes$1(plaintext); + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes$2(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes$1(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, +})); +// Private, unsafe low-level methods. Can change at any time. +const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt: encrypt$6, + decrypt: decrypt$6, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; -class AES_ECB { - static encrypt(data, key, padding = false) { - return new AES_ECB(key, padding).encrypt(data); - } - static decrypt(data, key, padding = false) { - return new AES_ECB(key, padding).decrypt(data); - } - constructor(key, padding = false, aes) { - this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); +// Modified by ProtonTech AG + + +const webCrypto$9 = util.getWebCrypto(); +const nodeCrypto$8 = util.getNodeCrypto(); + +const knownAlgos = nodeCrypto$8 ? nodeCrypto$8.getCiphers() : []; +const nodeAlgos = { + idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ + tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, + cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, + blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, + aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, + aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, + aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined + /* twofish is not implemented in OpenSSL */ +}; + +/** + * CFB encryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} plaintext + * @param {Uint8Array} iv + * @param {Object} config - full configuration, defaults to openpgp.config + * @returns MaybeStream + */ +async function encrypt$5(algo, key, plaintext, iv, config) { + const algoName = enums.read(enums.symmetric, algo); + if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. + return nodeEncrypt$1(algo, key, plaintext, iv); + } + if (util.isAES(algo)) { + return aesEncrypt(algo, key, plaintext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; + + const blockc = iv.slice(); + let pt = new Uint8Array(); + const process = chunk => { + if (chunk) { + pt = util.concatUint8Array([pt, chunk]); } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); + const ciphertext = new Uint8Array(pt.length); + let i; + let j = 0; + while (chunk ? pt.length >= block_size : pt.length) { + const encblock = cipherfn.encrypt(blockc); + for (i = 0; i < block_size; i++) { + blockc[i] = pt[i] ^ encblock[i]; + ciphertext[j++] = blockc[i]; + } + pt = pt.subarray(block_size); } + return ciphertext.subarray(0, j); + }; + return transform(plaintext, process, process); } /** - * Javascript AES implementation. - * This is used as fallback if the native Crypto APIs are not available. + * CFB decryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} ciphertext + * @param {Uint8Array} iv + * @returns MaybeStream */ -function aes(length) { - const C = function(key) { - const aesECB = new AES_ECB(key); +async function decrypt$5(algo, key, ciphertext, iv) { + const algoName = enums.read(enums.symmetric, algo); + if (nodeCrypto$8 && nodeAlgos[algoName]) { // Node crypto library. + return nodeDecrypt$1(algo, key, ciphertext, iv); + } + if (util.isAES(algo)) { + return aesDecrypt(algo, key, ciphertext, iv); + } - this.encrypt = function(block) { - return aesECB.encrypt(block); - }; + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; - this.decrypt = function(block) { - return aesECB.decrypt(block); - }; + let blockp = iv; + let ct = new Uint8Array(); + const process = chunk => { + if (chunk) { + ct = util.concatUint8Array([ct, chunk]); + } + const plaintext = new Uint8Array(ct.length); + let i; + let j = 0; + while (chunk ? ct.length >= block_size : ct.length) { + const decblock = cipherfn.encrypt(blockp); + blockp = ct.subarray(0, block_size); + for (i = 0; i < block_size; i++) { + plaintext[j++] = blockp[i] ^ decblock[i]; + } + ct = ct.subarray(block_size); + } + return plaintext.subarray(0, j); }; + return transform(ciphertext, process, process); +} - C.blockSize = C.prototype.blockSize = 16; - C.keySize = C.prototype.keySize = length / 8; +class WebCryptoEncryptor { + constructor(algo, key, iv) { + const { blockSize } = getCipherParams(algo); + this.key = key; + this.prevBlock = iv; + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + this.zeroBlock = new Uint8Array(this.blockSize); + } - return C; -} + static async isSupported(algo) { + const { keySize } = getCipherParams(algo); + return webCrypto$9.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt']) + .then(() => true, () => false); + } -//Paul Tero, July 2001 -//http://www.tero.co.uk/des/ -// -//Optimised for performance with large blocks by Michael Hayworth, November 2001 -//http://www.netdealing.com -// -// Modified by Recurity Labs GmbH + async _runCBC(plaintext, nonZeroIV) { + const mode = 'AES-CBC'; + this.keyRef = this.keyRef || await webCrypto$9.importKey('raw', this.key, mode, false, ['encrypt']); + const ciphertext = await webCrypto$9.encrypt( + { name: mode, iv: nonZeroIV || this.zeroBlock }, + this.keyRef, + plaintext + ); + return new Uint8Array(ciphertext).subarray(0, plaintext.length); + } + + async encryptChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const plaintext = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + const toEncrypt = util.concatUint8Array([ + this.prevBlock, + plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock + ]); -//THIS SOFTWARE IS PROVIDED "AS IS" AND -//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -//SUCH DAMAGE. + const encryptedBlocks = await this._runCBC(toEncrypt); + xorMut$1(encryptedBlocks, plaintext); + this.prevBlock = encryptedBlocks.slice(-this.blockSize); -//des -//this takes the key, the message, and whether to encrypt or decrypt + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; -function des(keys, message, encrypt, mode, iv, padding) { - //declaring this locally speeds things up a bit - const spfunction1 = [ - 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, - 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, - 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, - 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, - 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 - ]; - const spfunction2 = [ - -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, - -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, - -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, - -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, - -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, - 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000 - ]; - const spfunction3 = [ - 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, - 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, - 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, - 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, - 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 - ]; - const spfunction4 = [ - 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, - 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, - 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, - 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 - ]; - const spfunction5 = [ - 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, - 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, - 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, - 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, - 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, - 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100 - ]; - const spfunction6 = [ - 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, - 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, - 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, - 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, - 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 - ]; - const spfunction7 = [ - 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, - 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, - 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, - 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, - 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 - ]; - const spfunction8 = [ - 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, - 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, - 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, - 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, - 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 - ]; + return encryptedBlocks; + } - //create the 16 or 48 subkeys we will need - let m = 0; - let i; - let j; - let temp; - let right1; - let right2; - let left; - let right; - let looping; - let cbcleft; - let cbcleft2; - let cbcright; - let cbcright2; - let endloop; - let loopinc; - let len = message.length; + this.i += added.length; + let encryptedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + const curBlock = this.nextBlock; + encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + this.prevBlock = encryptedBlock.slice(); + this.i = 0; - //set up the loops for single and triple des - const iterations = keys.length === 32 ? 3 : 9; //single or triple des - if (iterations === 3) { - looping = encrypt ? [0, 32, 2] : [30, -2, -2]; - } else { - looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + encryptedBlock = new Uint8Array(); + } + + return encryptedBlock; } - //pad the message depending on the padding parameter - //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt - if (encrypt) { - message = desAddPadding(message, padding); - len = message.length; + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + this.nextBlock = this.nextBlock.subarray(0, this.i); + const curBlock = this.nextBlock; + const encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + result = encryptedBlock.subarray(0, curBlock.length); + } + + this.clearSensitiveData(); + return result; } - //store the result here - let result = new Uint8Array(len); - let k = 0; + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.keyRef = null; + this.key = null; + } - if (mode === 1) { //CBC mode - cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - m = 0; + async encrypt(plaintext) { + // plaintext is internally padded to block length before encryption + const encryptedWithPadding = await this._runCBC( + util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), + this.iv + ); + // drop encrypted padding + const ct = encryptedWithPadding.subarray(0, plaintext.length); + xorMut$1(ct, plaintext); + this.clearSensitiveData(); + return ct; } +} - //loop through each 64 bit chunk of the message - while (m < len) { - left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; +class NobleStreamProcessor { + constructor(forEncryption, algo, key, iv) { + this.forEncryption = forEncryption; + const { blockSize } = getCipherParams(algo); + this.key = unsafe.expandKeyLE(key); - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - left ^= cbcleft; - right ^= cbcright; - } else { - cbcleft2 = cbcleft; - cbcright2 = cbcright; - cbcleft = left; - cbcright = right; - } + if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers + this.prevBlock = getUint32Array(iv); + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + } + + _runCFB(src) { + const src32 = getUint32Array(src); + const dst = new Uint8Array(src.length); + const dst32 = getUint32Array(dst); + for (let i = 0; i + 4 <= dst32.length; i += 4) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4); } + return dst; + } - //first each 64 but chunk of the message must be permuted according to IP - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); + async processChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const toProcess = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); - //do this either 1 or 3 times for each chunk of the message - for (j = 0; j < iterations; j += 3) { - endloop = looping[j + 1]; - loopinc = looping[j + 2]; - //now go through and perform the encryption or decryption - for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency - right1 = right ^ keys[i]; - right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - //the result is attained by passing these bytes through the S selection functions - temp = left; - left = right; - right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> - 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & - 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); - } - temp = left; - left = right; - right = temp; //unreverse left and right - } //for either 1 or 3 iterations + const processedBlocks = this._runCFB(toProcess); - //move then each one bit to the right - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - //now perform IP-1, which is IP in the opposite direction - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); + return processedBlocks; + } - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - cbcleft = left; - cbcright = right; - } else { - left ^= cbcleft2; - right ^= cbcright2; - } + this.i += added.length; + + let processedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + processedBlock = this._runCFB(this.nextBlock); + this.i = 0; + + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + processedBlock = new Uint8Array(); } - result[k++] = (left >>> 24); - result[k++] = ((left >>> 16) & 0xff); - result[k++] = ((left >>> 8) & 0xff); - result[k++] = (left & 0xff); - result[k++] = (right >>> 24); - result[k++] = ((right >>> 16) & 0xff); - result[k++] = ((right >>> 8) & 0xff); - result[k++] = (right & 0xff); - } //for every 8 characters, or 64 bits in the message + return processedBlock; + } - //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt - if (!encrypt) { - result = desRemovePadding(result, padding); + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + const processedBlock = this._runCFB(this.nextBlock); + + result = processedBlock.subarray(0, this.i); + } + + this.clearSensitiveData(); + return result; } - return result; -} //end of des + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.key.fill(0); + } +} -//desCreateKeys -//this takes as input a 64 bit key (even though only 56 bits are used) -//as an array of 2 integers, and returns 16 48 bit keys +async function aesEncrypt(algo, key, pt, iv) { + if (webCrypto$9 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys + const cfb = new WebCryptoEncryptor(algo, key, iv); + return util.isStream(pt) ? transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt); + } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream + const cfb = new NobleStreamProcessor(true, algo, key, iv); + return transform(pt, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).encrypt(pt); +} -function desCreateKeys(key) { - //declaring this locally speeds things up a bit - const pc2bytes0 = [ - 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 - ]; - const pc2bytes1 = [ - 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 - ]; - const pc2bytes2 = [ - 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808 - ]; - const pc2bytes3 = [ - 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 - ]; - const pc2bytes4 = [ - 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010 - ]; - const pc2bytes5 = [ - 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420 - ]; - const pc2bytes6 = [ - 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 - ]; - const pc2bytes7 = [ - 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 - ]; - const pc2bytes8 = [ - 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002 - ]; - const pc2bytes9 = [ - 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 - ]; - const pc2bytes10 = [ - 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020 - ]; - const pc2bytes11 = [ - 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 - ]; - const pc2bytes12 = [ - 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 - ]; - const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; +async function aesDecrypt(algo, key, ct, iv) { + if (util.isStream(ct)) { + const cfb = new NobleStreamProcessor(false, algo, key, iv); + return transform(ct, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).decrypt(ct); +} - //how many iterations (1 for des, 3 for triple des) - const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - //stores the return keys - const keys = new Array(32 * iterations); - //now define the left shifts which need to be done - const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - //other variables - let lefttemp; - let righttemp; - let m = 0; - let n = 0; - let temp; +function xorMut$1(a, b) { + const aLength = Math.min(a.length, b.length); + for (let i = 0; i < aLength; i++) { + a[i] = a[i] ^ b[i]; + } +} - for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations - let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; +const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 2) ^ right) & 0x33333333; - right ^= temp; - left ^= (temp << 2); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); +function nodeEncrypt$1(algo, key, pt, iv) { + const algoName = enums.read(enums.symmetric, algo); + const cipherObj = new nodeCrypto$8.createCipheriv(nodeAlgos[algoName], key, iv); + return transform(pt, value => new Uint8Array(cipherObj.update(value))); +} - //the right side needs to be shifted and to get the last four bits of the left side - temp = (left << 8) | ((right >>> 20) & 0x000000f0); - //left needs to be put upside down - left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); - right = temp; +function nodeDecrypt$1(algo, key, ct, iv) { + const algoName = enums.read(enums.symmetric, algo); + const decipherObj = new nodeCrypto$8.createDecipheriv(nodeAlgos[algoName], key, iv); + return transform(ct, value => new Uint8Array(decipherObj.update(value))); +} - //now go through and perform these shifts on the left and right keys - for (let i = 0; i < shifts.length; i++) { - //shift the keys either one or two bits to the left - if (shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; +var cfb = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$5, + encrypt: encrypt$5 +}); - //now apply PC-2, in such a way that E is easier when encrypting or decrypting - //this conversion will look like PC-2 except only the last 6 bits of each byte are used - //rather than 48 consecutive bits and the order of lines will be according to - //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 - lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( - left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & - 0xf]; - righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | - pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]; - temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; - keys[n++] = lefttemp ^ temp; - keys[n++] = righttemp ^ (temp << 16); - } - } //for each iterations - //return the keys we've created - return keys; -} //end of desCreateKeys +/** + * @fileoverview This module implements AES-CMAC on top of + * native AES-CBC using either the WebCrypto API or Node.js' crypto API. + * @module crypto/cmac + */ -function desAddPadding(message, padding) { - const padLength = 8 - (message.length % 8); +const webCrypto$8 = util.getWebCrypto(); +const nodeCrypto$7 = util.getNodeCrypto(); - let pad; - if (padding === 2 && (padLength < 8)) { //pad the message with spaces - pad = ' '.charCodeAt(0); - } else if (padding === 1) { //PKCS7 padding - pad = padLength; - } else if (!padding && (padLength < 8)) { //pad the message out with null bytes - pad = 0; - } else if (padLength === 8) { - return message; - } else { - throw new Error('des: invalid padding'); - } - const paddedMessage = new Uint8Array(message.length + padLength); - for (let i = 0; i < message.length; i++) { - paddedMessage[i] = message[i]; - } - for (let j = 0; j < padLength; j++) { - paddedMessage[message.length + j] = pad; - } +/** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ - return paddedMessage; -} +const blockLength$3 = 16; -function desRemovePadding(message, padding) { - let padLength = null; - let pad; - if (padding === 2) { // space padded - pad = ' '.charCodeAt(0); - } else if (padding === 1) { // PKCS7 - padLength = message[message.length - 1]; - } else if (!padding) { // null padding - pad = 0; - } else { - throw new Error('des: invalid padding'); - } - if (!padLength) { - padLength = 1; - while (message[message.length - padLength] === pad) { - padLength++; - } - padLength--; +/** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param {Uint8Array} data + * @param {Uint8Array} padding + */ +function rightXORMut(data, padding) { + const offset = data.length - blockLength$3; + for (let i = 0; i < blockLength$3; i++) { + data[i + offset] ^= padding[i]; } + return data; +} - return message.subarray(0, message.length - padLength); +function pad(data, padding, padding2) { + // if |M| in {n, 2n, 3n, ...} + if (data.length && data.length % blockLength$3 === 0) { + // then return M xor→ B, + return rightXORMut(data, padding); + } + // else return (M || 10^(n−1−(|M| mod n))) xor→ P + const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3))); + padded.set(data); + padded[data.length] = 0b10000000; + return rightXORMut(padded, padding2); } -// added by Recurity Labs +const zeroBlock$1 = new Uint8Array(blockLength$3); -function TripleDES(key) { - this.key = []; +async function CMAC(key) { + const cbc = await CBC(key); - for (let i = 0; i < 3; i++) { - this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); - } + // L ← E_K(0^n); B ← 2L; P ← 4L + const padding = util.double(await cbc(zeroBlock$1)); + const padding2 = util.double(padding); - this.encrypt = function(block) { - return des( - desCreateKeys(this.key[2]), - des( - desCreateKeys(this.key[1]), - des( - desCreateKeys(this.key[0]), - block, true, 0, null, null - ), - false, 0, null, null - ), true, 0, null, null - ); + return async function(data) { + // return CBC_K(pad(M; B, P)) + return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3); }; } -TripleDES.keySize = TripleDES.prototype.keySize = 24; -TripleDES.blockSize = TripleDES.prototype.blockSize = 8; - -// This is "original" DES - -function DES(key) { - this.key = key; +async function CBC(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt) { + const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1); + const ct = en.update(pt); + return new Uint8Array(ct); + }; + } - this.encrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, true, 0, null, padding); - }; + if (util.getWebCrypto()) { + try { + key = await webCrypto$8.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); + return async function(pt) { + const ct = await webCrypto$8.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt); + return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - this.decrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, false, 0, null, padding); + return async function(pt) { + return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt); }; } -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Copyright 2010 pjacobs@xeekr.com . All rights reserved. - -// Modified by Recurity Labs GmbH +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// fixed/modified by Herbert Hanewinkel, www.haneWIN.de -// check www.haneWIN.de for the latest version -// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. -// CAST-128 is a common OpenPGP cipher. +const webCrypto$7 = util.getWebCrypto(); +const nodeCrypto$6 = util.getNodeCrypto(); +const Buffer$2 = util.getNodeBuffer(); -// CAST5 constructor +const blockLength$2 = 16; +const ivLength$2 = blockLength$2; +const tagLength$2 = blockLength$2; -function OpenPGPSymEncCAST5() { - this.BlockSize = 8; - this.KeySize = 16; +const zero = new Uint8Array(blockLength$2); +const one$1 = new Uint8Array(blockLength$2); one$1[blockLength$2 - 1] = 1; +const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2; - this.setKey = function(key) { - this.masking = new Array(16); - this.rotate = new Array(16); +async function OMAC(key) { + const cmac = await CMAC(key); + return function(t, message) { + return cmac(util.concatUint8Array([t, message])); + }; +} - this.reset(); +async function CTR(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt, iv) { + const en = new nodeCrypto$6.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); + const ct = Buffer$2.concat([en.update(pt), en.final()]); + return new Uint8Array(ct); + }; + } - if (key.length === this.KeySize) { - this.keySchedule(key); - } else { - throw new Error('CAST-128: keys must be 16 bytes'); + if (util.getWebCrypto()) { + try { + const keyRef = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); + return async function(pt, iv) { + const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt); + return new Uint8Array(ct); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); } - return true; + } + + return async function(pt, iv) { + return ctr(key, iv).encrypt(pt); }; +} - this.reset = function() { - for (let i = 0; i < 16; i++) { - this.masking[i] = 0; - this.rotate[i] = 0; + +/** + * Class to en/decrypt using EAX mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function EAX(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('EAX mode supports only AES cipher'); + } + + const [ + omac, + ctr + ] = await Promise.all([ + OMAC(key), + CTR(key) + ]); + + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + const [ + omacNonce, + omacAdata + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata) + ]); + const ciphered = await ctr(plaintext, omacNonce); + const omacCiphered = await omac(two, ciphered); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + return util.concatUint8Array([ciphered, tag]); + }, + + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to verify + * @returns {Promise} The plaintext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$2) throw new Error('Invalid EAX ciphertext'); + const ciphered = ciphertext.subarray(0, -tagLength$2); + const ctTag = ciphertext.subarray(-tagLength$2); + const [ + omacNonce, + omacAdata, + omacCiphered + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata), + omac(two, ciphered) + ]); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); + const plaintext = await ctr(ciphered, omacNonce); + return plaintext; } }; +} - this.getBlockSize = function() { - return this.BlockSize; - }; - this.encrypt = function(src) { - const dst = new Array(src.length); +/** + * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. + * @param {Uint8Array} iv - The initialization vector (16 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +EAX.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[8 + i] ^= chunkIndex[i]; + } + return nonce; +}; - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; +EAX.blockLength = blockLength$2; +EAX.ivLength = ivLength$2; +EAX.tagLength = tagLength$2; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; +const blockLength$1 = 16; +const ivLength$1 = 15; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; +// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: +// While OCB [RFC7253] allows the authentication tag length to be of any +// number up to 128 bits long, this document requires a fixed +// authentication tag length of 128 bits (16 octets) for simplicity. +const tagLength$1 = 16; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >>> 16) & 255; - dst[i + 6] = (l >>> 8) & 255; - dst[i + 7] = l & 255; - } - return dst; - }; +function ntz(n) { + let ntz = 0; + for (let i = 1; (n & i) === 0; i <<= 1) { + ntz++; + } + return ntz; +} - this.decrypt = function(src) { - const dst = new Array(src.length); +function xorMut(S, T) { + for (let i = 0; i < S.length; i++) { + S[i] ^= T[i]; + } + return S; +} - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; +function xor(S, T) { + return xorMut(S.slice(), T); +} - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; +const zeroBlock = new Uint8Array(blockLength$1); +const one = new Uint8Array([1]); - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; +/** + * Class to en/decrypt using OCB mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function OCB(cipher, key) { + const { keySize } = getCipherParams(cipher); + // sanity checks + if (!util.isAES(cipher) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; + let maxNtz = 0; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; + // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls, + // hence its execution cannot be broken up. + // As a result, WebCrypto cannot currently be used for `encipher`. + const aes = cbc(key, zeroBlock, { disablePadding: true }); + const encipher = block => aes.encrypt(block); + const decipher = block => aes.decrypt(block); + let mask; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >> 16) & 255; - dst[i + 6] = (l >> 8) & 255; - dst[i + 7] = l & 255; - } + constructKeyVariables(); - return dst; - }; - const scheduleA = new Array(4); + function constructKeyVariables() { + const mask_x = encipher(zeroBlock); + const mask_$ = util.double(mask_x); + mask = []; + mask[0] = util.double(mask_$); - scheduleA[0] = new Array(4); - scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; - scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - scheduleA[1] = new Array(4); - scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + mask.x = mask_x; + mask.$ = mask_$; + } - scheduleA[2] = new Array(4); - scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; - scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + function extendKeyVariables(text, adata) { + const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1; + for (let i = maxNtz + 1; i <= newMaxNtz; i++) { + mask[i] = util.double(mask[i - 1]); + } + maxNtz = newMaxNtz; + } + function hash(adata) { + if (!adata.length) { + // Fast path + return zeroBlock; + } - scheduleA[3] = new Array(4); - scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + // + // Consider A as a sequence of 128-bit blocks + // + const m = adata.length / blockLength$1 | 0; - const scheduleB = new Array(4); + const offset = new Uint8Array(blockLength$1); + const sum = new Uint8Array(blockLength$1); + for (let i = 0; i < m; i++) { + xorMut(offset, mask[ntz(i + 1)]); + xorMut(sum, encipher(xor(offset, adata))); + adata = adata.subarray(blockLength$1); + } - scheduleB[0] = new Array(4); - scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; - scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; - scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; - scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; + // + // Process any final partial block; compute final hash value + // + if (adata.length) { + xorMut(offset, mask.x); - scheduleB[1] = new Array(4); - scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; - scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; - scheduleB[1][2] = [7, 6, 8, 9, 3]; - scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; + const cipherInput = new Uint8Array(blockLength$1); + cipherInput.set(adata, 0); + cipherInput[adata.length] = 0b10000000; + xorMut(cipherInput, offset); + xorMut(sum, encipher(cipherInput)); + } - scheduleB[2] = new Array(4); - scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; - scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; - scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; - scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; + return sum; + } + + /** + * Encrypt/decrypt data. + * @param {encipher|decipher} fn - Encryption/decryption block cipher function + * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. + */ + function crypt(fn, text, nonce, adata) { + // + // Consider P as a sequence of 128-bit blocks + // + const m = text.length / blockLength$1 | 0; + // + // Key-dependent variables + // + extendKeyVariables(text, adata); - scheduleB[3] = new Array(4); - scheduleB[3][0] = [8, 9, 7, 6, 3]; - scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; - scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; - scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; + // + // Nonce-dependent and per-encryption variables + // + // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + // Note: We assume here that tagLength mod 16 == 0. + const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]); + // bottom = str2num(Nonce[123..128]) + const bottom = paddedNonce[blockLength$1 - 1] & 0b111111; + // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + paddedNonce[blockLength$1 - 1] &= 0b11000000; + const kTop = encipher(paddedNonce); + // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); + // Offset_0 = Stretch[1+bottom..128+bottom] + const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); + // Checksum_0 = zeros(128) + const checksum = new Uint8Array(blockLength$1); - // changed 'in' to 'inn' (in javascript 'in' is a reserved word) - this.keySchedule = function(inn) { - const t = new Array(8); - const k = new Array(32); + const ct = new Uint8Array(text.length + tagLength$1); - let j; + // + // Process any whole blocks + // + let i; + let pos = 0; + for (i = 0; i < m; i++) { + // Offset_i = Offset_{i-1} xor L_{ntz(i)} + xorMut(offset, mask[ntz(i + 1)]); + // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + ct.set(xorMut(fn(xor(offset, text)), offset), pos); + // Checksum_i = Checksum_{i-1} xor P_i + xorMut(checksum, fn === encipher ? text : ct.subarray(pos)); - for (let i = 0; i < 4; i++) { - j = i * 4; - t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + text = text.subarray(blockLength$1); + pos += blockLength$1; } - const x = [6, 7, 4, 5]; - let ki = 0; - let w; + // + // Process any final partial block and compute raw tag + // + if (text.length) { + // Offset_* = Offset_m xor L_* + xorMut(offset, mask.x); + // Pad = ENCIPHER(K, Offset_*) + const padding = encipher(offset); + // C_* = P_* xor Pad[1..bitlen(P_*)] + ct.set(xor(text, padding), pos); - for (let half = 0; half < 2; half++) { - for (let round = 0; round < 4; round++) { - for (j = 0; j < 4; j++) { - const a = scheduleA[round][j]; - w = t[a[1]]; + // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) + const xorInput = new Uint8Array(blockLength$1); + xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); + xorInput[text.length] = 0b10000000; + xorMut(checksum, xorInput); + pos += text.length; + } + // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata)); - w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; - w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; - w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; - w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; - w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; - t[a[0]] = w; - } + // + // Assemble ciphertext + // + // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] + ct.set(tag, pos); + return ct; + } - for (j = 0; j < 4; j++) { - const b = scheduleB[round][j]; - w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; - w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; - w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; - w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; - k[ki] = w; - ki++; - } - } - } + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + return crypt(encipher, plaintext, nonce, adata); + }, - for (let i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); + + const tag = ciphertext.subarray(-tagLength$1); + ciphertext = ciphertext.subarray(0, -tagLength$1); + + const crypted = crypt(decipher, ciphertext, nonce, adata); + // if (Tag[1..TAGLEN] == T) + if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { + return crypted.subarray(0, -tagLength$1); + } + throw new Error('Authentication tag mismatch'); } }; +} - // These are the three 'f' functions. See RFC 2144, section 2.2. - function f1(d, m, r) { - const t = m + d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; +/** + * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. + * @param {Uint8Array} iv - The initialization vector (15 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +OCB.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[7 + i] ^= chunkIndex[i]; } + return nonce; +}; - function f2(d, m, r) { - const t = m ^ d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; - } +OCB.blockLength = blockLength$1; +OCB.ivLength = ivLength$1; +OCB.tagLength = tagLength$1; - function f3(d, m, r) { - const t = m - d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$6 = util.getWebCrypto(); +const nodeCrypto$5 = util.getNodeCrypto(); +const Buffer$1 = util.getNodeBuffer(); + +const blockLength = 16; +const ivLength = 12; // size of the IV in bytes +const tagLength = 16; // size of the tag in bytes +const ALGO = 'AES-GCM'; + +/** + * Class to en/decrypt using GCM mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function GCM(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('GCM mode supports only AES cipher'); } - const sBox = new Array(8); - sBox[0] = [ - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf - ]; + if (util.getNodeCrypto()) { // Node crypto library + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + const en = new nodeCrypto$5.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + en.setAAD(adata); + const ct = Buffer$1.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext + return new Uint8Array(ct); + }, - sBox[1] = [ - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + const de = new nodeCrypto$5.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + de.setAAD(adata); + de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext + const pt = Buffer$1.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]); + return new Uint8Array(pt); + } + }; + } - sBox[2] = [ - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 - ]; + if (util.getWebCrypto()) { + try { + const _key = await webCrypto$6.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); + // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages + const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) || + navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/); + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && !pt.length) { + return gcm(key, iv, adata).encrypt(pt); + } + const ct = await webCrypto$6.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt); + return new Uint8Array(ct); + }, - sBox[3] = [ - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) { + return gcm(key, iv, adata).decrypt(ct); + } + try { + const pt = await webCrypto$6.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct); + return new Uint8Array(pt); + } catch (e) { + if (e.name === 'OperationError') { + throw new Error('Authentication tag mismatch'); + } + } + } + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - sBox[4] = [ - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 - ]; + return { + encrypt: async function(pt, iv, adata) { + return gcm(key, iv, adata).encrypt(pt); + }, - sBox[5] = [ - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f - ]; + decrypt: async function(ct, iv, adata) { + return gcm(key, iv, adata).decrypt(ct); + } + }; +} - sBox[6] = [ - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 - ]; - - sBox[7] = [ - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e - ]; -} - -function CAST5(key) { - this.cast5 = new OpenPGPSymEncCAST5(); - this.cast5.setKey(key); - - this.encrypt = function(block) { - return this.cast5.encrypt(block); - }; -} - -CAST5.blockSize = CAST5.prototype.blockSize = 8; -CAST5.keySize = CAST5.prototype.keySize = 16; -/* eslint-disable no-mixed-operators, no-fallthrough */ +/** + * Get GCM nonce. Note: this operation is not defined by the standard. + * A future version of the standard may define GCM mode differently, + * hopefully under a different ID (we use Private/Experimental algorithm + * ID 100) so that we can maintain backwards compatibility. + * @param {Uint8Array} iv - The initialization vector (12 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +GCM.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[4 + i] ^= chunkIndex[i]; + } + return nonce; +}; +GCM.blockLength = blockLength; +GCM.ivLength = ivLength; +GCM.tagLength = tagLength; -/* Modified by Recurity Labs GmbH - * - * Cipher.js - * A block-cipher algorithm implementation on JavaScript - * See Cipher.readme.txt for further information. - * - * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] - * This script file is distributed under the LGPL - * - * ACKNOWLEDGMENT - * - * The main subroutines are written by Michiel van Everdingen. - * - * Michiel van Everdingen - * http://home.versatel.nl/MAvanEverdingen/index.html - * - * All rights for these routines are reserved to Michiel van Everdingen. - * +/** + * @fileoverview Cipher modes + * @module crypto/mode */ -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Math -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -const MAXINT = 0xFFFFFFFF; +var mode = { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: GCM, + experimentalGCM: GCM, + /** @see module:crypto/mode/eax */ + eax: EAX, + /** @see module:crypto/mode/ocb */ + ocb: OCB +}; -function rotw(w, n) { - return (w << n | w >>> (32 - n)) & MAXINT; +// Operations are not constant time, but we try and limit timing leakage where we can +const _0n$8 = BigInt(0); +const _1n$d = BigInt(1); +function uint8ArrayToBigInt(bytes) { + const hexAlphabet = '0123456789ABCDEF'; + let s = ''; + bytes.forEach(v => { + s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; + }); + return BigInt('0x0' + s); +} +function mod$2(a, m) { + const reduced = a % m; + return reduced < _0n$8 ? reduced + m : reduced; +} +/** + * Compute modular exponentiation using square and multiply + * @param {BigInt} a - Base + * @param {BigInt} e - Exponent + * @param {BigInt} n - Modulo + * @returns {BigInt} b ** e mod n. + */ +function modExp(b, e, n) { + if (n === _0n$8) + throw Error('Modulo cannot be zero'); + if (n === _1n$d) + return BigInt(0); + if (e < _0n$8) + throw Error('Unsopported negative exponent'); + let exp = e; + let x = b; + x %= n; + let r = BigInt(1); + while (exp > _0n$8) { + const lsb = exp & _1n$d; + exp >>= _1n$d; // e / 2 + // Always compute multiplication step, to reduce timing leakage + const rx = (r * x) % n; + // Update r only if lsb is 1 (odd exponent) + r = lsb ? rx : r; + x = (x * x) % n; // Square + } + return r; } - -function getW(a, i) { - return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +function abs(x) { + return x >= _0n$8 ? x : -x; } - -function setW(a, i, w) { - a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +/** + * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) + * Given a and b, compute (x, y) such that ax + by = gdc(a, b). + * Negative numbers are also supported. + * @param {BigInt} a - First operand + * @param {BigInt} b - Second operand + * @returns {{ gcd, x, y: bigint }} + */ +function _egcd(aInput, bInput) { + let x = BigInt(0); + let y = BigInt(1); + let xPrev = BigInt(1); + let yPrev = BigInt(0); + // Deal with negative numbers: run algo over absolute values, + // and "move" the sign to the returned x and/or y. + // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers + let a = abs(aInput); + let b = abs(bInput); + const aNegated = aInput < _0n$8; + const bNegated = bInput < _0n$8; + while (b !== _0n$8) { + const q = a / b; + let tmp = x; + x = xPrev - q * x; + xPrev = tmp; + tmp = y; + y = yPrev - q * y; + yPrev = tmp; + tmp = b; + b = a % b; + a = tmp; + } + return { + x: aNegated ? -xPrev : xPrev, + y: bNegated ? -yPrev : yPrev, + gcd: a + }; +} +/** + * Compute the inverse of `a` modulo `n` + * Note: `a` and and `n` must be relatively prime + * @param {BigInt} a + * @param {BigInt} n - Modulo + * @returns {BigInt} x such that a*x = 1 mod n + * @throws {Error} if the inverse does not exist + */ +function modInv(a, n) { + const { gcd, x } = _egcd(a, n); + if (gcd !== _1n$d) { + throw new Error('Inverse does not exist'); + } + return mod$2(x + n, n); +} +/** + * Compute greatest common divisor between this and n + * @param {BigInt} aInput - Operand + * @param {BigInt} bInput - Operand + * @returns {BigInt} gcd + */ +function gcd(aInput, bInput) { + let a = aInput; + let b = bInput; + while (b !== _0n$8) { + const tmp = b; + b = a % b; + a = tmp; + } + return a; +} +/** + * Get this value as an exact Number (max 53 bits) + * Fails if this value is too large + * @returns {Number} + */ +function bigIntToNumber(x) { + const number = Number(x); + if (number > Number.MAX_SAFE_INTEGER) { + // We throw and error to conform with the bn.js implementation + throw new Error('Number can only safely store up to 53 bits'); + } + return number; +} +/** + * Get value of i-th bit + * @param {BigInt} x + * @param {Number} i - Bit index + * @returns {Number} Bit value. + */ +function getBit(x, i) { + const bit = (x >> BigInt(i)) & _1n$d; + return bit === _0n$8 ? 0 : 1; +} +/** + * Compute bit length + */ +function bitLength(x) { + // -1n >> -1n is -1n + // 1n >> 1n is 0n + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + let bitlen = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _1n$d) !== target) { + bitlen++; + } + return bitlen; +} +/** + * Compute byte length + */ +function byteLength(x) { + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + const _8n = BigInt(8); + let len = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _8n) !== target) { + len++; + } + return len; +} +/** + * Get Uint8Array representation of this number + * @param {String} endian - Endianess of output array (defaults to 'be') + * @param {Number} length - Of output array + * @returns {Uint8Array} + */ +function bigIntToUint8Array(x, endian = 'be', length) { + // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) + // this is faster than shift+mod iterations + let hex = x.toString(16); + if (hex.length % 2 === 1) { + hex = '0' + hex; + } + const rawLength = hex.length / 2; + const bytes = new Uint8Array(length || rawLength); + // parse hex + const offset = length ? length - rawLength : 0; + let i = 0; + while (i < rawLength) { + bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + i++; + } + if (endian !== 'be') { + bytes.reverse(); + } + return bytes; } -function getB(x, n) { - return (x >>> (n * 8)) & 0xFF; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const nodeCrypto$4 = util.getNodeCrypto(); + +/** + * Retrieve secure random byte array of the specified length + * @param {Integer} length - Length in bytes to generate + * @returns {Uint8Array} Random byte array. + */ +function getRandomBytes(length) { + const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$4?.webcrypto; + if (webcrypto?.getRandomValues) { + const buf = new Uint8Array(length); + return webcrypto.getRandomValues(buf); + } else { + throw new Error('No secure random number generator available.'); + } } -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Twofish -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/** + * Create a secure random BigInt that is greater than or equal to min and less than max. + * @param {bigint} min - Lower bound, included + * @param {bigint} max - Upper bound, excluded + * @returns {bigint} Random BigInt. + * @async + */ +function getRandomBigInteger(min, max) { + if (max < min) { + throw new Error('Illegal parameter value: max <= min'); + } -function createTwofish() { - // - let keyBytes = null; - let dataBytes = null; - let dataOffset = -1; - // var dataLength = -1; - // var idx2 = -1; - // + const modulus = max - min; + const bytes = byteLength(modulus); - let tfsKey = []; - let tfsM = [ - [], - [], - [], - [] - ]; + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8)); + return mod$2(r, modulus) + min; +} - function tfsInit(key) { - keyBytes = key; - let i; - let a; - let b; - let c; - let d; - const meKey = []; - const moKey = []; - const inKey = []; - let kLen; - const sKey = []; - let f01; - let f5b; - let fef; +var random = /*#__PURE__*/Object.freeze({ + __proto__: null, + getRandomBigInteger: getRandomBigInteger, + getRandomBytes: getRandomBytes +}); - const q0 = [ - [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], - [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] - ]; - const q1 = [ - [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], - [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] - ]; - const q2 = [ - [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], - [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] - ]; - const q3 = [ - [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], - [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] - ]; - const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - const q = [ - [], - [] - ]; - const m = [ - [], - [], - [], - [] - ]; - - function ffm5b(x) { - return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +/** + * @fileoverview Algorithms for probabilistic random prime generation + * @module crypto/public_key/prime + */ +const _1n$c = BigInt(1); +/** + * Generate a probably prime random number + * @param bits - Bit length of the prime + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function randomProbablePrime(bits, e, k) { + const _30n = BigInt(30); + const min = _1n$c << BigInt(bits - 1); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 + * the next possible prime is mod 30: + * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 + */ + const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; + let n = getRandomBigInteger(min, min << _1n$c); + let i = bigIntToNumber(mod$2(n, _30n)); + do { + n += BigInt(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (bitLength(n) > bits) { + n = mod$2(n, min << _1n$c); + n += min; + i = bigIntToNumber(mod$2(n, _30n)); + } + } while (!isProbablePrime(n, e, k)); + return n; +} +/** + * Probabilistic primality testing + * @param n - Number to test + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function isProbablePrime(n, e, k) { + if (e && gcd(n - _1n$c, e) !== _1n$c) { + return false; } - - function ffmEf(x) { - return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + if (!divisionTest(n)) { + return false; } - - function mdsRem(p, q) { - let i; - let t; - let u; - for (i = 0; i < 8; i++) { - t = q >>> 24; - q = ((q << 8) & MAXINT) | p >>> 24; - p = (p << 8) & MAXINT; - u = t << 1; - if (t & 128) { - u ^= 333; + if (!fermat(n)) { + return false; + } + if (!millerRabin(n, k)) { + return false; + } + // TODO implement the Lucas test + // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + return true; +} +/** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n != 1. + * @param n - Number to test + * @param b - Optional Fermat test base + */ +function fermat(n, b = BigInt(2)) { + return modExp(b, n - _1n$c, n) === _1n$c; +} +function divisionTest(n) { + const _0n = BigInt(0); + return smallPrimes.every(m => mod$2(n, m) !== _0n); +} +// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c +const smallPrimes = [ + 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, + 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, + 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, + 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, + 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, + 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, + 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, + 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, + 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, + 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, + 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, + 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, + 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, + 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, + 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, + 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, + 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, + 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, + 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, + 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, + 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, + 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, + 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, + 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, + 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, + 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, + 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, + 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, + 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, + 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, + 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, + 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, + 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, + 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, + 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, + 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, + 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, + 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, + 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, + 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, + 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, + 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, + 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, + 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, + 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, + 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, + 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, + 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, + 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, + 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, + 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, + 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, + 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, + 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, + 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, + 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, + 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, + 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, + 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, + 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, + 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, + 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, + 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, + 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, + 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, + 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, + 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, + 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, + 4957, 4967, 4969, 4973, 4987, 4993, 4999 +].map(n => BigInt(n)); +// Miller-Rabin - Miller Rabin algorithm for primality test +// Copyright Fedor Indutny, 2014. +// +// This software is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin +// Sample syntax for Fixed-Base Miller-Rabin: +// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) +/** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n - Number to test + * @param k - Optional number of iterations of Miller-Rabin test + * @param rand - Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ +function millerRabin(n, k, rand) { + const len = bitLength(n); + if (!k) { + k = Math.max(1, (len / 48) | 0); + } + const n1 = n - _1n$c; // n - 1 + // Find d and s, (n - 1) = (2 ^ s) * d; + let s = 0; + while (!getBit(n1, s)) { + s++; + } + const d = n >> BigInt(s); + for (; k > 0; k--) { + const a = getRandomBigInteger(BigInt(2), n1); + let x = modExp(a, d, n); + if (x === _1n$c || x === n1) { + continue; } - q ^= t ^ (u << 16); - u ^= t >>> 1; - if (t & 1) { - u ^= 166; + let i; + for (i = 1; i < s; i++) { + x = mod$2(x * x, n); + if (x === _1n$c) { + return false; + } + if (x === n1) { + break; + } + } + if (i === s) { + return false; } - q ^= u << 24 | u << 8; - } - return q; - } - - function qp(n, x) { - const a = x >> 4; - const b = x & 15; - const c = q0[n][a ^ b]; - const d = q1[n][ror4[b] ^ ashx[a]]; - return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; } + return true; +} - function hFun(x, key) { - let a = getB(x, 0); - let b = getB(x, 1); - let c = getB(x, 2); - let d = getB(x, 3); - switch (kLen) { - case 4: - a = q[1][a] ^ getB(key[3], 0); - b = q[0][b] ^ getB(key[3], 1); - c = q[0][c] ^ getB(key[3], 2); - d = q[1][d] ^ getB(key[3], 3); - case 3: - a = q[1][a] ^ getB(key[2], 0); - b = q[1][b] ^ getB(key[2], 1); - c = q[0][c] ^ getB(key[2], 2); - d = q[0][d] ^ getB(key[2], 3); - case 2: - a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); - b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); - c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); - d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); - } - return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - keyBytes = keyBytes.slice(0, 32); - i = keyBytes.length; - while (i !== 16 && i !== 24 && i !== 32) { - keyBytes[i++] = 0; - } - for (i = 0; i < keyBytes.length; i += 4) { - inKey[i >> 2] = getW(keyBytes, i); - } - for (i = 0; i < 256; i++) { - q[0][i] = qp(0, i); - q[1][i] = qp(1, i); - } - for (i = 0; i < 256; i++) { - f01 = q[1][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - f01 = q[0][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } +/** + * ASN1 object identifiers for hashes + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} + */ +const hash_headers = []; +hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, + 0x10]; +hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; +hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; +hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, + 0x04, 0x20]; +hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x30]; +hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40]; +hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C]; - kLen = inKey.length / 2; - for (i = 0; i < kLen; i++) { - a = inKey[i + i]; - meKey[i] = a; - b = inKey[i + i + 1]; - moKey[i] = b; - sKey[kLen - i - 1] = mdsRem(a, b); - } - for (i = 0; i < 40; i += 2) { - a = 0x1010101 * i; - b = a + 0x1010101; - a = hFun(a, meKey); - b = rotw(hFun(b, moKey), 8); - tfsKey[i] = (a + b) & MAXINT; - tfsKey[i + 1] = rotw(a + 2 * b, 9); - } - for (i = 0; i < 256; i++) { - a = b = c = d = i; - switch (kLen) { - case 4: - a = q[1][a] ^ getB(sKey[3], 0); - b = q[0][b] ^ getB(sKey[3], 1); - c = q[0][c] ^ getB(sKey[3], 2); - d = q[1][d] ^ getB(sKey[3], 3); - case 3: - a = q[1][a] ^ getB(sKey[2], 0); - b = q[1][b] ^ getB(sKey[2], 1); - c = q[0][c] ^ getB(sKey[2], 2); - d = q[0][d] ^ getB(sKey[2], 3); - case 2: - tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; - tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; - tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; - tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; +/** + * Create padding with secure random data + * @private + * @param {Integer} length - Length of the padding in bytes + * @returns {Uint8Array} Random padding. + */ +function getPKCS1Padding(length) { + const result = new Uint8Array(length); + let count = 0; + while (count < length) { + const randomBytes = getRandomBytes(length - count); + for (let i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result[count++] = randomBytes[i]; } } } + return result; +} - function tfsG0(x) { - return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; - } - - function tfsG1(x) { - return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; - } - - function tfsFrnd(r, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); - blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); - blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; +/** + * Create a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} + * @param {Uint8Array} message - Message to be encoded + * @param {Integer} keyLength - The length in octets of the key modulus + * @returns {Uint8Array} EME-PKCS1 padded message. + */ +function emeEncode(message, keyLength) { + const mLength = message.length; + // length checking + if (mLength > keyLength - 11) { + throw new Error('Message too long'); } + // Generate an octet string PS of length k - mLen - 3 consisting of + // pseudo-randomly generated nonzero octets + const PS = getPKCS1Padding(keyLength - mLength - 3); + // Concatenate PS, the message M, and other padding to form an + // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. + const encoded = new Uint8Array(keyLength); + // 0x00 byte + encoded[1] = 2; + encoded.set(PS, 2); + // 0x00 bytes + encoded.set(message, keyLength - mLength); + return encoded; +} - function tfsIrnd(i, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; - blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; - blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); +/** + * Decode a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} + * @param {Uint8Array} encoded - Encoded message bytes + * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) + * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) + * @throws {Error} on decoding failure, unless `randomPayload` is provided + */ +function emeDecode(encoded, randomPayload) { + // encoded format: 0x00 0x02 0x00 + let offset = 2; + let separatorNotFound = 1; + for (let j = offset; j < encoded.length; j++) { + separatorNotFound &= encoded[j] !== 0; + offset += separatorNotFound; } - function tfsClose() { - tfsKey = []; - tfsM = [ - [], - [], - [], - [] - ]; - } + const psLen = offset - 2; + const payload = encoded.subarray(offset + 1); // discard the 0x00 separator + const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - function tfsEncrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; - for (let j = 0; j < 8; j++) { - tfsFrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); - dataOffset += 16; - return dataBytes; + if (randomPayload) { + return util.selectUint8Array(isValidPadding, payload, randomPayload); } - function tfsDecrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; - for (let j = 7; j >= 0; j--) { - tfsIrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); - dataOffset += 16; + if (isValidPadding) { + return payload; } - // added by Recurity Labs + throw new Error('Decryption error'); +} - function tfsFinal() { - return dataBytes; +/** + * Create a EMSA-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} + * @param {Integer} algo - Hash algorithm type used + * @param {Uint8Array} hashed - Message to be encoded + * @param {Integer} emLen - Intended length in octets of the encoded message + * @returns {Uint8Array} Encoded message. + */ +function emsaEncode(algo, hashed, emLen) { + let i; + if (hashed.length !== hash$1.getHashByteLength(algo)) { + throw new Error('Invalid hash length'); + } + // produce an ASN.1 DER value for the hash function used. + // Let T be the full hash prefix + const hashPrefix = new Uint8Array(hash_headers[algo].length); + for (i = 0; i < hash_headers[algo].length; i++) { + hashPrefix[i] = hash_headers[algo][i]; + } + // and let tLen be the length in octets prefix and hashed data + const tLen = hashPrefix.length + hashed.length; + if (emLen < tLen + 11) { + throw new Error('Intended encoded message length too short'); } + // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF + // The length of PS will be at least 8 octets + const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - return { - name: 'twofish', - blocksize: 128 / 8, - open: tfsInit, - close: tfsClose, - encrypt: tfsEncrypt, - decrypt: tfsDecrypt, - // added by Recurity Labs - finalize: tfsFinal - }; + // Concatenate PS, the hash prefix, hashed data, and other padding to form the + // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed + const EM = new Uint8Array(emLen); + EM[1] = 0x01; + EM.set(PS, 2); + EM.set(hashPrefix, emLen - tLen); + EM.set(hashed, emLen - hashed.length); + return EM; } -// added by Recurity Labs +var pkcs1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + emeDecode: emeDecode, + emeEncode: emeEncode, + emsaEncode: emsaEncode +}); -function TF(key) { - this.tf = createTwofish(); - this.tf.open(Array.from(key), 0); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - this.encrypt = function(block) { - return this.tf.encrypt(Array.from(block), 0); - }; -} -TF.keySize = TF.prototype.keySize = 32; -TF.blockSize = TF.prototype.blockSize = 16; +const webCrypto$5 = util.getWebCrypto(); +const nodeCrypto$3 = util.getNodeCrypto(); +const _1n$b = BigInt(1); -/* Modified by Recurity Labs GmbH - * - * Originally written by nklein software (nklein.com) +/** Create signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} hashed - Hashed message + * @returns {Promise} RSA Signature. + * @async */ +async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) { + if (hash$1.getHashByteLength(hashAlgo) >= n.length) { + // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error + // e.g. if a 512-bit RSA key is used with a SHA-512 digest. + // The size limit is actually slightly different but here we only care about throwing + // on common key sizes. + throw new Error('Digest size cannot exceed key modulus size'); + } -/* - * Javascript implementation based on Bruce Schneier's reference implementation. - * - * - * The constructor doesn't do much of anything. It's just here - * so we can start defining properties and methods and such. - */ -function Blowfish() {} + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeSign$1(hashAlgo, data, n, e, d, p, q, u); + } + } + return bnSign(hashAlgo, n, d, hashed); +} -/* - * Declare the block size so that protocols know what size - * Initialization Vector (IV) they will need. +/** + * Verify signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} s - Signature + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} hashed - Hashed message + * @returns {Boolean} + * @async */ -Blowfish.prototype.BLOCKSIZE = 8; +async function verify$6(hashAlgo, data, s, n, e, hashed) { + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeVerify$1(hashAlgo, data, s, n, e); + } + } + return bnVerify(hashAlgo, s, n, e, hashed); +} -/* - * These are the default SBOXES. +/** + * Encrypt message + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @returns {Promise} RSA Ciphertext. + * @async */ -Blowfish.prototype.SBOXES = [ - [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a - ], - [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 - ], - [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 - ], - [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ] -]; - -//* -//* This is the default PARRAY -//* -Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b -]; - -//* -//* This is the number of rounds the cipher will go -//* -Blowfish.prototype.NN = 16; - -//* -//* This function is needed to get rid of problems -//* with the high-bit getting set. If we don't do -//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not -//* equal to ( bb & 0x00FFFFFFFF ) even when they -//* agree bit-for-bit for the first 32 bits. -//* -Blowfish.prototype._clean = function(xx) { - if (xx < 0) { - const yy = xx & 0x7FFFFFFF; - xx = yy + 0x80000000; +async function encrypt$4(data, n, e) { + if (util.getNodeCrypto()) { + return nodeEncrypt(data, n, e); } - return xx; -}; - -//* -//* This is the mixing function that uses the sboxes -//* -Blowfish.prototype._F = function(xx) { - let yy; - - const dd = xx & 0x00FF; - xx >>>= 8; - const cc = xx & 0x00FF; - xx >>>= 8; - const bb = xx & 0x00FF; - xx >>>= 8; - const aa = xx & 0x00FF; + return bnEncrypt(data, n, e); +} - yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy ^= this.sboxes[2][cc]; - yy += this.sboxes[3][dd]; +/** + * Decrypt RSA message + * @param {Uint8Array} m - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} RSA Plaintext. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$4(data, n, e, d, p, q, u, randomPayload) { + // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, + // and we want to avoid checking the error type to decide if the random payload + // should indeed be returned. + if (util.getNodeCrypto() && !randomPayload) { + try { + return await nodeDecrypt(data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } + return bnDecrypt(data, n, e, d, p, q, u, randomPayload); +} - return yy; -}; +/** + * Generate a new random private key B bits long with public exponent E. + * + * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param {Integer} bits - RSA bit length + * @param {Integer} e - RSA public exponent + * @returns {{n, e, d, + * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = p ** -1 mod q + * @async + */ +async function generate$4(bits, e) { + e = BigInt(e); -//* -//* This method takes an array with two values, left and right -//* and does NN rounds of Blowfish on them. -//* -Blowfish.prototype._encryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; + // Native RSA keygen using Web Crypto + if (util.getWebCrypto()) { + const keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, // the specified keysize in bits + publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - let ii; + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); + // map JWK parameters to corresponding OpenPGP names + return jwkToPrivate(jwk, e); + } else if (util.getNodeCrypto()) { + const opts = { + modulusLength: bits, + publicExponent: bigIntToNumber(e), + publicKeyEncoding: { type: 'pkcs1', format: 'jwk' }, + privateKeyEncoding: { type: 'pkcs1', format: 'jwk' } + }; + const jwk = await new Promise((resolve, reject) => { + nodeCrypto$3.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => { + if (err) { + reject(err); + } else { + resolve(jwkPrivateKey); + } + }); + }); + return jwkToPrivate(jwk, e); + } - for (ii = 0; ii < this.NN; ++ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; + // RSA keygen fallback using 40 iterations of the Miller-Rabin test + // See https://stackoverflow.com/a/6330138 for justification + // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST + let p; + let q; + let n; + do { + q = randomProbablePrime(bits - (bits >> 1), e, 40); + p = randomProbablePrime(bits >> 1, e, 40); + n = p * q; + } while (bitLength(n) !== bits); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + const phi = (p - _1n$b) * (q - _1n$b); + + if (q < p) { + [p, q] = [q, p]; } - dataL ^= this.parray[this.NN + 0]; - dataR ^= this.parray[this.NN + 1]; + return { + n: bigIntToUint8Array(n), + e: bigIntToUint8Array(e), + d: bigIntToUint8Array(modInv(e, phi)), + p: bigIntToUint8Array(p), + q: bigIntToUint8Array(q), + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: bigIntToUint8Array(modInv(p, q)) + }; +} - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; +/** + * Validate RSA parameters + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA inverse of p w.r.t. q + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$9(n, e, d, p, q, u) { + n = uint8ArrayToBigInt(n); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); -//* -//* This method takes a vector of numbers and turns them -//* into long words so that they can be processed by the -//* real algorithm. -//* -//* Maybe I should make the real algorithm above take a vector -//* instead. That will involve more looping, but it won't require -//* the F() method to deconstruct the vector. -//* -Blowfish.prototype.encryptBlock = function(vector) { - let ii; - const vals = [0, 0]; - const off = this.BLOCKSIZE / 2; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); - vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); + // expect pq = n + if ((p * q) !== n) { + return false; } - this._encryptBlock(vals); + const _2n = BigInt(2); + // expect p*u = 1 mod q + u = uint8ArrayToBigInt(u); + if (mod$2(p * u, q) !== BigInt(1)) { + return false; + } - const ret = []; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); - ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); - // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); - // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + /** + * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) + * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] + * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] + * + * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) + */ + const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3)); + const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q + const rde = r * d * e; + + const areInverses = mod$2(rde, p - _1n$b) === r && mod$2(rde, q - _1n$b) === r; + if (!areInverses) { + return false; } - return ret; -}; + return true; +} -//* -//* This method takes an array with two values, left and right -//* and undoes NN rounds of Blowfish on them. -//* -Blowfish.prototype._decryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; +async function bnSign(hashAlgo, n, d, hashed) { + n = uint8ArrayToBigInt(n); + const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n))); + d = uint8ArrayToBigInt(d); + return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n)); +} - let ii; +async function webSign$1(hashName, data, n, e, d, p, q, u) { + /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. + * We swap them in privateToJWK, so it usually works out, but nevertheless, + * not all OpenPGP keys are compatible with this requirement. + * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still + * does if the underlying Web Crypto does so (though the tested implementations + * don't do so). + */ + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }; + const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); + return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); +} - for (ii = this.NN + 1; ii > 1; --ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; +async function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) { + const sign = nodeCrypto$3.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(data); + sign.end(); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + const jwk = await privateToJWK$1(n, e, d, p, q, u); + return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' })); +} + +async function bnVerify(hashAlgo, s, n, e, hashed) { + n = uint8ArrayToBigInt(n); + s = uint8ArrayToBigInt(s); + e = uint8ArrayToBigInt(e); + if (s >= n) { + throw new Error('Signature size cannot exceed modulus size'); } + const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n)); + const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n)); + return util.equalsUint8Array(EM1, EM2); +} - dataL ^= this.parray[1]; - dataR ^= this.parray[0]; +async function webVerify$1(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = await webCrypto$5.importKey('jwk', jwk, { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }, false, ['verify']); + return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); +} - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; +async function nodeVerify$1(hashAlgo, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1' }; -//* -//* This method takes a key array and initializes the -//* sboxes and parray for this encryption. -//* -Blowfish.prototype.init = function(key) { - let ii; - let jj = 0; + const verify = nodeCrypto$3.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(data); + verify.end(); - this.parray = []; - for (ii = 0; ii < this.NN + 2; ++ii) { - let data = 0x00000000; - for (let kk = 0; kk < 4; ++kk) { - data = (data << 8) | (key[jj] & 0x00FF); - if (++jj >= key.length) { - jj = 0; - } - } - this.parray[ii] = this.PARRAY[ii] ^ data; + try { + return verify.verify(key, s); + } catch (err) { + return false; } +} - this.sboxes = []; - for (ii = 0; ii < 4; ++ii) { - this.sboxes[ii] = []; - for (jj = 0; jj < 256; ++jj) { - this.sboxes[ii][jj] = this.SBOXES[ii][jj]; - } +async function nodeEncrypt(data, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; + + return new Uint8Array(nodeCrypto$3.publicEncrypt(key, data)); +} + +async function bnEncrypt(data, n, e) { + n = uint8ArrayToBigInt(n); + data = uint8ArrayToBigInt(emeEncode(data, byteLength(n))); + e = uint8ArrayToBigInt(e); + if (data >= n) { + throw new Error('Message size cannot exceed modulus size'); } + return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n)); +} - const vals = [0x00000000, 0x00000000]; +async function nodeDecrypt(data, n, e, d, p, q, u) { + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; - for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encryptBlock(vals); - this.parray[ii + 0] = vals[0]; - this.parray[ii + 1] = vals[1]; + try { + return new Uint8Array(nodeCrypto$3.privateDecrypt(key, data)); + } catch (err) { + throw new Error('Decryption error'); } +} - for (ii = 0; ii < 4; ++ii) { - for (jj = 0; jj < 256; jj += 2) { - this._encryptBlock(vals); - this.sboxes[ii][jj + 0] = vals[0]; - this.sboxes[ii][jj + 1] = vals[1]; - } +async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { + data = uint8ArrayToBigInt(data); + n = uint8ArrayToBigInt(n); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + u = uint8ArrayToBigInt(u); + if (data >= n) { + throw new Error('Data too large.'); } -}; + const dq = mod$2(d, q - _1n$b); // d mod (q-1) + const dp = mod$2(d, p - _1n$b); // d mod (p-1) -// added by Recurity Labs -function BF(key) { - this.bf = new Blowfish(); - this.bf.init(key); + const unblinder = getRandomBigInteger(BigInt(2), n); + const blinder = modExp(modInv(unblinder, n), e, n); + data = mod$2(data * blinder, n); - this.encrypt = function(block) { - return this.bf.encryptBlock(block); - }; -} + const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p + const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q + const h = mod$2(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q) -BF.keySize = BF.prototype.keySize = 16; -BF.blockSize = BF.prototype.blockSize = 8; + let result = h * p + mp; // result < n due to relations above -/** - * @fileoverview Symmetric cryptography functions - * @module crypto/cipher - * @private + result = mod$2(result * unblinder, n); + + return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload); +} + +/** Convert Openpgp private key params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + * @param {Uint8Array} d + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} u */ +async function privateToJWK$1(n, e, d, p, q, u) { + const pNum = uint8ArrayToBigInt(p); + const qNum = uint8ArrayToBigInt(q); + const dNum = uint8ArrayToBigInt(d); -/** - * AES-128 encryption and decryption (ID 7) - * @function - * @param {String} key - 128-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} + let dq = mod$2(dNum, qNum - _1n$b); // d mod (q-1) + let dp = mod$2(dNum, pNum - _1n$b); // d mod (p-1) + dp = bigIntToUint8Array(dp); + dq = bigIntToUint8Array(dq); + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + d: uint8ArrayToB64(d), + // switch p and q + p: uint8ArrayToB64(q), + q: uint8ArrayToB64(p), + // switch dp and dq + dp: uint8ArrayToB64(dq), + dq: uint8ArrayToB64(dp), + qi: uint8ArrayToB64(u), + ext: true + }; +} + +/** Convert Openpgp key public params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e */ -const aes128 = aes(128); -/** - * AES-128 Block Cipher (ID 8) - * @function - * @param {String} key - 192-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes192 = aes(192); -/** - * AES-128 Block Cipher (ID 9) - * @function - * @param {String} key - 256-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes256 = aes(256); -// Not in OpenPGP specifications -const des$1 = DES; -/** - * Triple DES Block Cipher (ID 2) - * @function - * @param {String} key - 192-bit key - * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67} - * @returns {Object} - */ -const tripledes = TripleDES; -/** - * CAST-128 Block Cipher (ID 3) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} - * @returns {Object} - */ -const cast5 = CAST5; -/** - * Twofish Block Cipher (ID 10) - * @function - * @param {String} key - 256-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH} - * @returns {Object} - */ -const twofish = TF; -/** - * Blowfish Block Cipher (ID 4) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH} - * @returns {Object} - */ -const blowfish = BF; -/** - * Not implemented - * @function - * @throws {Error} - */ -const idea = function() { - throw new Error('IDEA symmetric-key algorithm not implemented'); -}; +function publicToJWK(n, e) { + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + ext: true + }; +} -var cipher = /*#__PURE__*/Object.freeze({ +/** Convert JWK private key to OpenPGP private key params */ +function jwkToPrivate(jwk, e) { + return { + n: b64ToUint8Array(jwk.n), + e: bigIntToUint8Array(e), + d: b64ToUint8Array(jwk.d), + // switch p and q + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), + // Since p and q are switched in places, u is the inverse of jwk.q + u: b64ToUint8Array(jwk.qi) + }; +} + +var rsa = /*#__PURE__*/Object.freeze({ __proto__: null, - aes128: aes128, - aes192: aes192, - aes256: aes256, - des: des$1, - tripledes: tripledes, - cast5: cast5, - twofish: twofish, - blowfish: blowfish, - idea: idea + decrypt: decrypt$4, + encrypt: encrypt$4, + generate: generate$4, + sign: sign$6, + validateParams: validateParams$9, + verify: verify$6 }); -var sha1_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0, - w16 = 0, w17 = 0, w18 = 0, w19 = 0, - w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0, - w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0, - w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0, - w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0, - w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0, - w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - - // 0 - t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 1 - t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 2 - t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 3 - t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 4 - t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 5 - t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 6 - t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 7 - t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 8 - t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 9 - t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 10 - t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 11 - t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 12 - t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 13 - t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 14 - t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 15 - t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 16 - n = w13 ^ w8 ^ w2 ^ w0; - w16 = (n << 1) | (n >>> 31); - t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 17 - n = w14 ^ w9 ^ w3 ^ w1; - w17 = (n << 1) | (n >>> 31); - t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 18 - n = w15 ^ w10 ^ w4 ^ w2; - w18 = (n << 1) | (n >>> 31); - t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 19 - n = w16 ^ w11 ^ w5 ^ w3; - w19 = (n << 1) | (n >>> 31); - t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 20 - n = w17 ^ w12 ^ w6 ^ w4; - w20 = (n << 1) | (n >>> 31); - t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 21 - n = w18 ^ w13 ^ w7 ^ w5; - w21 = (n << 1) | (n >>> 31); - t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 22 - n = w19 ^ w14 ^ w8 ^ w6; - w22 = (n << 1) | (n >>> 31); - t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 23 - n = w20 ^ w15 ^ w9 ^ w7; - w23 = (n << 1) | (n >>> 31); - t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 24 - n = w21 ^ w16 ^ w10 ^ w8; - w24 = (n << 1) | (n >>> 31); - t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 25 - n = w22 ^ w17 ^ w11 ^ w9; - w25 = (n << 1) | (n >>> 31); - t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 26 - n = w23 ^ w18 ^ w12 ^ w10; - w26 = (n << 1) | (n >>> 31); - t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 27 - n = w24 ^ w19 ^ w13 ^ w11; - w27 = (n << 1) | (n >>> 31); - t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 28 - n = w25 ^ w20 ^ w14 ^ w12; - w28 = (n << 1) | (n >>> 31); - t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 29 - n = w26 ^ w21 ^ w15 ^ w13; - w29 = (n << 1) | (n >>> 31); - t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 30 - n = w27 ^ w22 ^ w16 ^ w14; - w30 = (n << 1) | (n >>> 31); - t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 31 - n = w28 ^ w23 ^ w17 ^ w15; - w31 = (n << 1) | (n >>> 31); - t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 32 - n = w29 ^ w24 ^ w18 ^ w16; - w32 = (n << 1) | (n >>> 31); - t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 33 - n = w30 ^ w25 ^ w19 ^ w17; - w33 = (n << 1) | (n >>> 31); - t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 34 - n = w31 ^ w26 ^ w20 ^ w18; - w34 = (n << 1) | (n >>> 31); - t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 35 - n = w32 ^ w27 ^ w21 ^ w19; - w35 = (n << 1) | (n >>> 31); - t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 36 - n = w33 ^ w28 ^ w22 ^ w20; - w36 = (n << 1) | (n >>> 31); - t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 37 - n = w34 ^ w29 ^ w23 ^ w21; - w37 = (n << 1) | (n >>> 31); - t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 38 - n = w35 ^ w30 ^ w24 ^ w22; - w38 = (n << 1) | (n >>> 31); - t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 39 - n = w36 ^ w31 ^ w25 ^ w23; - w39 = (n << 1) | (n >>> 31); - t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 40 - n = w37 ^ w32 ^ w26 ^ w24; - w40 = (n << 1) | (n >>> 31); - t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 41 - n = w38 ^ w33 ^ w27 ^ w25; - w41 = (n << 1) | (n >>> 31); - t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 42 - n = w39 ^ w34 ^ w28 ^ w26; - w42 = (n << 1) | (n >>> 31); - t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 43 - n = w40 ^ w35 ^ w29 ^ w27; - w43 = (n << 1) | (n >>> 31); - t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 44 - n = w41 ^ w36 ^ w30 ^ w28; - w44 = (n << 1) | (n >>> 31); - t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 45 - n = w42 ^ w37 ^ w31 ^ w29; - w45 = (n << 1) | (n >>> 31); - t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 46 - n = w43 ^ w38 ^ w32 ^ w30; - w46 = (n << 1) | (n >>> 31); - t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 47 - n = w44 ^ w39 ^ w33 ^ w31; - w47 = (n << 1) | (n >>> 31); - t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 48 - n = w45 ^ w40 ^ w34 ^ w32; - w48 = (n << 1) | (n >>> 31); - t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 49 - n = w46 ^ w41 ^ w35 ^ w33; - w49 = (n << 1) | (n >>> 31); - t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 50 - n = w47 ^ w42 ^ w36 ^ w34; - w50 = (n << 1) | (n >>> 31); - t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 51 - n = w48 ^ w43 ^ w37 ^ w35; - w51 = (n << 1) | (n >>> 31); - t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 52 - n = w49 ^ w44 ^ w38 ^ w36; - w52 = (n << 1) | (n >>> 31); - t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 53 - n = w50 ^ w45 ^ w39 ^ w37; - w53 = (n << 1) | (n >>> 31); - t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 54 - n = w51 ^ w46 ^ w40 ^ w38; - w54 = (n << 1) | (n >>> 31); - t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 55 - n = w52 ^ w47 ^ w41 ^ w39; - w55 = (n << 1) | (n >>> 31); - t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 56 - n = w53 ^ w48 ^ w42 ^ w40; - w56 = (n << 1) | (n >>> 31); - t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 57 - n = w54 ^ w49 ^ w43 ^ w41; - w57 = (n << 1) | (n >>> 31); - t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 58 - n = w55 ^ w50 ^ w44 ^ w42; - w58 = (n << 1) | (n >>> 31); - t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 59 - n = w56 ^ w51 ^ w45 ^ w43; - w59 = (n << 1) | (n >>> 31); - t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 60 - n = w57 ^ w52 ^ w46 ^ w44; - w60 = (n << 1) | (n >>> 31); - t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 61 - n = w58 ^ w53 ^ w47 ^ w45; - w61 = (n << 1) | (n >>> 31); - t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 62 - n = w59 ^ w54 ^ w48 ^ w46; - w62 = (n << 1) | (n >>> 31); - t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 63 - n = w60 ^ w55 ^ w49 ^ w47; - w63 = (n << 1) | (n >>> 31); - t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 64 - n = w61 ^ w56 ^ w50 ^ w48; - w64 = (n << 1) | (n >>> 31); - t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 65 - n = w62 ^ w57 ^ w51 ^ w49; - w65 = (n << 1) | (n >>> 31); - t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 66 - n = w63 ^ w58 ^ w52 ^ w50; - w66 = (n << 1) | (n >>> 31); - t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 67 - n = w64 ^ w59 ^ w53 ^ w51; - w67 = (n << 1) | (n >>> 31); - t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 68 - n = w65 ^ w60 ^ w54 ^ w52; - w68 = (n << 1) | (n >>> 31); - t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 69 - n = w66 ^ w61 ^ w55 ^ w53; - w69 = (n << 1) | (n >>> 31); - t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 70 - n = w67 ^ w62 ^ w56 ^ w54; - w70 = (n << 1) | (n >>> 31); - t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 71 - n = w68 ^ w63 ^ w57 ^ w55; - w71 = (n << 1) | (n >>> 31); - t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 72 - n = w69 ^ w64 ^ w58 ^ w56; - w72 = (n << 1) | (n >>> 31); - t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 73 - n = w70 ^ w65 ^ w59 ^ w57; - w73 = (n << 1) | (n >>> 31); - t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 74 - n = w71 ^ w66 ^ w60 ^ w58; - w74 = (n << 1) | (n >>> 31); - t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 75 - n = w72 ^ w67 ^ w61 ^ w59; - w75 = (n << 1) | (n >>> 31); - t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 76 - n = w73 ^ w68 ^ w62 ^ w60; - w76 = (n << 1) | (n >>> 31); - t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 77 - n = w74 ^ w69 ^ w63 ^ w61; - w77 = (n << 1) | (n >>> 31); - t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 78 - n = w75 ^ w70 ^ w64 ^ w62; - w78 = (n << 1) | (n >>> 31); - t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 79 - n = w76 ^ w71 ^ w65 ^ w63; - w79 = (n << 1) | (n >>> 31); - t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - } - - function reset () { - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if ( offset & 63 ) - return -1; - if ( ~output ) - if ( output & 31 ) - return -1; +const _1n$a = BigInt(1); - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; +/** + * ElGamal Encryption function + * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) + * @param {Uint8Array} data - To be padded and encrypted + * @param {Uint8Array} p + * @param {Uint8Array} g + * @param {Uint8Array} y + * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} + * @async + */ +async function encrypt$3(data, p, g, y) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } + const padded = emeEncode(data, byteLength(p)); + const m = uint8ArrayToBigInt(padded); - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0; + // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* + // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] + const k = getRandomBigInteger(_1n$a, p - _1n$a); + return { + c1: bigIntToUint8Array(modExp(g, k, p)), + c2: bigIntToUint8Array(mod$2(modExp(y, k, p) * m, p)) + }; +} - HEAP[offset|length] = 0x80; +/** + * ElGamal Encryption function + * @param {Uint8Array} c1 + * @param {Uint8Array} c2 + * @param {Uint8Array} p + * @param {Uint8Array} x + * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} Unpadded message. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$3(c1, c2, p, x, randomPayload) { + c1 = uint8ArrayToBigInt(c1); + c2 = uint8ArrayToBigInt(c2); + p = uint8ArrayToBigInt(p); + x = uint8ArrayToBigInt(x); - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - _core_heap(offset); + const padded = mod$2(modInv(modExp(c1, x, p), p) * c2, p); + return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload); +} - length = 0; +/** + * Validate ElGamal parameters + * @param {Uint8Array} p - ElGamal prime + * @param {Uint8Array} g - ElGamal group generator + * @param {Uint8Array} y - ElGamal public key + * @param {Uint8Array} x - ElGamal private exponent + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$8(p, g, y, x) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - HEAP[offset|0] = 0; - } + // Check that 1 < g < p + if (g <= _1n$a || g >= p) { + return false; + } - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; + // Expect p-1 to be large + const pSize = BigInt(bitLength(p)); + const _1023n = BigInt(1023); + if (pSize < _1023n) { + return false; + } - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; + /** + * g should have order p-1 + * Check that g ** (p-1) = 1 mod p + */ + if (modExp(g, p - _1n$a, p) !== _1n$a) { + return false; + } - TOTAL0 = 64; - TOTAL1 = 0; + /** + * Since p-1 is not prime, g might have a smaller order that divides p-1 + * We want to make sure that the order is large enough to hinder a small subgroup attack + * + * We just check g**i != 1 for all i up to a threshold + */ + let res = g; + let i = BigInt(1); + const _2n = BigInt(2); + const threshold = _2n << BigInt(17); // we want order > threshold + while (i < threshold) { + res = mod$2(res * g, p); + if (res === _1n$a) { + return false; } + i++; + } - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{r(p-1) + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const r = getRandomBigInteger(_2n << (pSize - _1n$a), _2n << pSize); // draw r of same size as p-1 + const rqx = (p - _1n$a) * r + x; + if (y !== modExp(g, rqx, p)) { + return false; + } - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); + return true; +} - if ( ~output ) - _state_to_heap(output); +var elgamal = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$3, + encrypt: encrypt$3, + validateParams: validateParams$8 +}); - return hashed|0; - } +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// See utils.ts for details. +const crypto$3 = + nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined; - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; +const nacl = {}; - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ - if ( offset & 63 ) - return -1; +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; - if ( ~output ) - if ( output & 31 ) - return -1; +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; +var _9 = new Uint8Array(32); _9[0] = 9; - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4; - count = (count-1)|0; +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} - count = (count-1)|0; - } +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} - if ( ~output ) - _state_to_heap(output); +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} - return 0; +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} - return { - // SHA1 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA1 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA1 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} -class Hash { - constructor() { - this.pos = 0; - this.len = 0; - } - reset() { - const { asm } = this.acquire_asm(); - this.result = null; - this.pos = 0; - this.len = 0; - asm.reset(); - return this; - } - process(data) { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - let hpos = this.pos; - let hlen = this.len; - let dpos = 0; - let dlen = data.length; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.process(hpos, hlen); - hpos += wlen; - hlen -= wlen; - if (!hlen) - hpos = 0; - } - this.pos = hpos; - this.len = hlen; - return this; - } - finish() { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - asm.finish(this.pos, this.len, 0); - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set(heap.subarray(0, this.HASH_SIZE)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return this; - } +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } -const _sha1_block_size = 64; -const _sha1_hash_size = 20; -const heap_pool$1 = []; -const asm_pool$1 = []; -class Sha1 extends Hash { - constructor() { - super(); - this.NAME = 'sha1'; - this.BLOCK_SIZE = _sha1_block_size; - this.HASH_SIZE = _sha1_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$1.pop() || _heap_init(); - this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$1.push(this.heap); - asm_pool$1.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha1().process(data).finish().result; - } -} -Sha1.NAME = 'sha1'; -Sha1.heap_pool = []; -Sha1.asm_pool = []; -Sha1.asm_function = sha1_asm; - -var sha256_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - f = H5; - g = H6; - h = H7; - - // 0 - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 1 - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 2 - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 3 - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 4 - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 5 - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 6 - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 7 - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 8 - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 9 - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 10 - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 11 - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 12 - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 13 - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 14 - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 15 - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 16 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 17 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 18 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 19 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 20 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 21 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 22 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 23 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 24 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 25 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 26 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 27 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 28 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 29 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 30 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 31 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 32 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 33 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 34 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 35 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 36 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 37 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 38 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 39 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 40 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 41 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 42 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 43 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 44 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 45 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 46 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 47 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 48 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 49 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 50 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 51 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 52 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 53 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 54 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 55 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 56 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 57 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 58 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 59 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 60 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 61 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 62 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 63 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; - } - - function reset () { - H0 = 0x6a09e667; - H1 = 0xbb67ae85; - H2 = 0x3c6ef372; - H3 = 0xa54ff53a; - H4 = 0x510e527f; - H5 = 0x9b05688c; - H6 = 0x1f83d9ab; - H7 = 0x5be0cd19; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - H5 = I5; - H6 = I6; - H7 = I7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - H5 = O5; - H6 = O6; - H7 = O7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - O5 = H5; - O6 = H6; - O7 = H7; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - I5 = H5; - I6 = H6; - I7 = H7; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - h5 = h5 ^ H5; - h6 = h6 ^ H6; - h7 = h7 ^ H7; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA256 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA256 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA256 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; - -const _sha256_block_size = 64; -const _sha256_hash_size = 32; -const heap_pool$2 = []; -const asm_pool$2 = []; -class Sha256 extends Hash { - constructor() { - super(); - this.NAME = 'sha256'; - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$2.pop() || _heap_init(); - this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$2.push(this.heap); - asm_pool$2.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha256().process(data).finish().result; - } -} -Sha256.NAME = 'sha256'; - -var minimalisticAssert = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var inherits_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; -} -}); - -var inherits = createCommonjsModule(function (module) { -try { - var util = util$1; - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = inherits_browser; -} -}); - -var inherits_1 = inherits; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -var toArray_1 = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -var htonl_1 = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -var toHex32_1 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -var zero2_1 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -var zero8_1 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -var join32_1 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -var split32_1 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -var rotr32_1 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -var rotl32_1 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -var sum32_1 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -var sum32_3_1 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -var sum32_4_1 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -var sum32_5_1 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -var sum64_1 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -var sum64_lo_1 = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -var sum64_5_lo_1 = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -var rotr64_hi_1 = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var rotr64_lo_1 = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var shr64_lo_1 = shr64_lo; - -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -var common = { - BlockHash: BlockHash_1 -}; - -var rotr32$1 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -var ft_1_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -var ch32_1 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -var maj32_1 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; - -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; - -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; - -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); -} -var g0_256_1 = g0_256; - -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); -} -var g1_256_1 = g1_256; - -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; - -var sum32$1 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$1 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; - -var BlockHash$1 = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$1); -var _256 = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - _256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, _256); -var _224 = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - -var rotr64_hi$1 = utils.rotr64_hi; -var rotr64_lo$1 = utils.rotr64_lo; -var shr64_hi$1 = utils.shr64_hi; -var shr64_lo$1 = utils.shr64_lo; -var sum64$1 = utils.sum64; -var sum64_hi$1 = utils.sum64_hi; -var sum64_lo$1 = utils.sum64_lo; -var sum64_4_hi$1 = utils.sum64_4_hi; -var sum64_4_lo$1 = utils.sum64_4_lo; -var sum64_5_hi$1 = utils.sum64_5_hi; -var sum64_5_lo$1 = utils.sum64_5_lo; - -var BlockHash$2 = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash$2); -var _512 = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - minimalisticAssert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); // 34 - var c2_hi = rotr64_hi$1(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); // 34 - var c2_lo = rotr64_lo$1(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); // 61 - var c2_hi = shr64_hi$1(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); // 61 - var c2_lo = shr64_lo$1(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - _512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, _512); -var _384 = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -var rotl32$1 = utils.rotl32; -var sum32$2 = utils.sum32; -var sum32_3$1 = utils.sum32_3; -var sum32_4$2 = utils.sum32_4; -var BlockHash$3 = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash$3.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash$3); -var ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32$2( - rotl32$1( - sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32$1(C, 10); - C = B; - B = T; - T = sum32$2( - rotl32$1( - sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$1(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -var ripemd = { - ripemd160: ripemd160 -}; - -/** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. - */ - -// MD5 Digest -async function md5(entree) { - const digest = md51(util.uint8ArrayToString(entree)); - return util.hexToUint8Array(hex(digest)); -} - -function md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - - a = ff(a, b, c, d, k[0], 7, -680876936); - d = ff(d, a, b, c, k[1], 12, -389564586); - c = ff(c, d, a, b, k[2], 17, 606105819); - b = ff(b, c, d, a, k[3], 22, -1044525330); - a = ff(a, b, c, d, k[4], 7, -176418897); - d = ff(d, a, b, c, k[5], 12, 1200080426); - c = ff(c, d, a, b, k[6], 17, -1473231341); - b = ff(b, c, d, a, k[7], 22, -45705983); - a = ff(a, b, c, d, k[8], 7, 1770035416); - d = ff(d, a, b, c, k[9], 12, -1958414417); - c = ff(c, d, a, b, k[10], 17, -42063); - b = ff(b, c, d, a, k[11], 22, -1990404162); - a = ff(a, b, c, d, k[12], 7, 1804603682); - d = ff(d, a, b, c, k[13], 12, -40341101); - c = ff(c, d, a, b, k[14], 17, -1502002290); - b = ff(b, c, d, a, k[15], 22, 1236535329); - - a = gg(a, b, c, d, k[1], 5, -165796510); - d = gg(d, a, b, c, k[6], 9, -1069501632); - c = gg(c, d, a, b, k[11], 14, 643717713); - b = gg(b, c, d, a, k[0], 20, -373897302); - a = gg(a, b, c, d, k[5], 5, -701558691); - d = gg(d, a, b, c, k[10], 9, 38016083); - c = gg(c, d, a, b, k[15], 14, -660478335); - b = gg(b, c, d, a, k[4], 20, -405537848); - a = gg(a, b, c, d, k[9], 5, 568446438); - d = gg(d, a, b, c, k[14], 9, -1019803690); - c = gg(c, d, a, b, k[3], 14, -187363961); - b = gg(b, c, d, a, k[8], 20, 1163531501); - a = gg(a, b, c, d, k[13], 5, -1444681467); - d = gg(d, a, b, c, k[2], 9, -51403784); - c = gg(c, d, a, b, k[7], 14, 1735328473); - b = gg(b, c, d, a, k[12], 20, -1926607734); - - a = hh(a, b, c, d, k[5], 4, -378558); - d = hh(d, a, b, c, k[8], 11, -2022574463); - c = hh(c, d, a, b, k[11], 16, 1839030562); - b = hh(b, c, d, a, k[14], 23, -35309556); - a = hh(a, b, c, d, k[1], 4, -1530992060); - d = hh(d, a, b, c, k[4], 11, 1272893353); - c = hh(c, d, a, b, k[7], 16, -155497632); - b = hh(b, c, d, a, k[10], 23, -1094730640); - a = hh(a, b, c, d, k[13], 4, 681279174); - d = hh(d, a, b, c, k[0], 11, -358537222); - c = hh(c, d, a, b, k[3], 16, -722521979); - b = hh(b, c, d, a, k[6], 23, 76029189); - a = hh(a, b, c, d, k[9], 4, -640364487); - d = hh(d, a, b, c, k[12], 11, -421815835); - c = hh(c, d, a, b, k[15], 16, 530742520); - b = hh(b, c, d, a, k[2], 23, -995338651); - - a = ii(a, b, c, d, k[0], 6, -198630844); - d = ii(d, a, b, c, k[7], 10, 1126891415); - c = ii(c, d, a, b, k[14], 15, -1416354905); - b = ii(b, c, d, a, k[5], 21, -57434055); - a = ii(a, b, c, d, k[12], 6, 1700485571); - d = ii(d, a, b, c, k[3], 10, -1894986606); - c = ii(c, d, a, b, k[10], 15, -1051523); - b = ii(b, c, d, a, k[1], 21, -2054922799); - a = ii(a, b, c, d, k[8], 6, 1873313359); - d = ii(d, a, b, c, k[15], 10, -30611744); - c = ii(c, d, a, b, k[6], 15, -1560198380); - b = ii(b, c, d, a, k[13], 21, 1309151649); - a = ii(a, b, c, d, k[4], 6, -145523070); - d = ii(d, a, b, c, k[11], 10, -1120210379); - c = ii(c, d, a, b, k[2], 15, 718787259); - b = ii(b, c, d, a, k[9], 21, -343485551); - - x[0] = add32(a, x[0]); - x[1] = add32(b, x[1]); - x[2] = add32(c, x[2]); - x[3] = add32(d, x[3]); -} - -function cmn(q, a, b, x, s, t) { - a = add32(add32(a, q), add32(x, t)); - return add32((a << s) | (a >>> (32 - s)), b); -} - -function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} - -function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); -} - -function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); -} - -function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -function md51(s) { - const n = s.length; - const state = [1732584193, -271733879, -1732584194, 271733878]; - let i; - for (i = 64; i <= s.length; i += 64) { - md5cycle(state, md5blk(s.substring(i - 64, i))); - } - s = s.substring(i - 64); - const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (i = 0; i < s.length; i++) { - tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); - } - tail[i >> 2] |= 0x80 << ((i % 4) << 3); - if (i > 55) { - md5cycle(state, tail); - for (i = 0; i < 16; i++) { - tail[i] = 0; - } - } - tail[14] = n * 8; - md5cycle(state, tail); - return state; -} - -/* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ -function md5blk(s) { /* I figured global was faster. */ - const md5blks = []; - let i; /* Andy King said do it this way. */ - for (i = 0; i < 64; i += 4) { - md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << - 24); - } - return md5blks; -} - -const hex_chr = '0123456789abcdef'.split(''); - -function rhex(n) { - let s = ''; - let j = 0; - for (; j < 4; j++) { - s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; - } - return s; -} - -function hex(x) { - for (let i = 0; i < x.length; i++) { - x[i] = rhex(x[i]); - } - return x.join(''); -} - -/* this function is much faster, -so if possible we use it. Some IEs -are the only ones I know of that -need the idiotic second function, -generated by an if clause. */ - -function add32(a, b) { - return (a + b) & 0xFFFFFFFF; -} - -/** - * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://github.com/indutny/hash.js|hash.js} - * @module crypto/hash - * @private - */ - -const webCrypto = util.getWebCrypto(); -const nodeCrypto = util.getNodeCrypto(); -const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes(); - -function nodeHash(type) { - if (!nodeCrypto || !nodeCryptoHashes.includes(type)) { - return; - } - return async function (data) { - const shasum = nodeCrypto.createHash(type); - return transform(data, value => { - shasum.update(value); - }, () => new Uint8Array(shasum.digest())); - }; -} - -function hashjsHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } - const hashInstance = hash(); - return transform(data, value => { - hashInstance.update(value); - }, () => new Uint8Array(hashInstance.digest())); - }; -} - -function asmcryptoHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (util.isStream(data)) { - const hashInstance = new hash(); - return transform(data, value => { - hashInstance.process(value); - }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } else { - return hash.bytes(data); - } - }; -} - -const hashFunctions = { - md5: nodeHash('md5') || md5, - sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'), - sha224: nodeHash('sha224') || hashjsHash(_224), - sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'), - sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'), - sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160) -}; - -var hash = { - - /** @see module:md5 */ - md5: hashFunctions.md5, - /** @see asmCrypto */ - sha1: hashFunctions.sha1, - /** @see hash.js */ - sha224: hashFunctions.sha224, - /** @see asmCrypto */ - sha256: hashFunctions.sha256, - /** @see hash.js */ - sha384: hashFunctions.sha384, - /** @see asmCrypto */ - sha512: hashFunctions.sha512, - /** @see hash.js */ - ripemd: hashFunctions.ripemd, - - /** - * Create a hash on the specified data using the specified algorithm - * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {Uint8Array} data - Data to be hashed - * @returns {Promise} Hash value. - */ - digest: function(algo, data) { - switch (algo) { - case enums.hash.md5: - return this.md5(data); - case enums.hash.sha1: - return this.sha1(data); - case enums.hash.ripemd: - return this.ripemd(data); - case enums.hash.sha256: - return this.sha256(data); - case enums.hash.sha384: - return this.sha384(data); - case enums.hash.sha512: - return this.sha512(data); - case enums.hash.sha224: - return this.sha224(data); - default: - throw new Error('Invalid hash function.'); - } - }, - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns {Integer} Size in bytes of the resulting hash. - */ - getHashByteLength: function(algo) { - switch (algo) { - case enums.hash.md5: - return 16; - case enums.hash.sha1: - case enums.hash.ripemd: - return 20; - case enums.hash.sha256: - return 32; - case enums.hash.sha384: - return 48; - case enums.hash.sha512: - return 64; - case enums.hash.sha224: - return 28; - default: - throw new Error('Invalid hash algorithm.'); - } - } -}; - -class AES_CFB { - static encrypt(data, key, iv) { - return new AES_CFB(key, iv).encrypt(data); - } - static decrypt(data, key, iv) { - return new AES_CFB(key, iv).decrypt(data); - } - constructor(key, iv, aes) { - this.aes = aes ? aes : new AES(key, iv, true, 'CFB'); - delete this.aes.padding; - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * Get implementation of the given cipher - * @param {enums.symmetric} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getCipher(algo) { - const algoName = enums.read(enums.symmetric, algo); - return cipher[algoName]; -} - -// Modified by ProtonTech AG - -const webCrypto$1 = util.getWebCrypto(); -const nodeCrypto$1 = util.getNodeCrypto(); - -const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : []; -const nodeAlgos = { - idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ - tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, - cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, - blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, - aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, - aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, - aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined - /* twofish is not implemented in OpenSSL */ -}; - -/** - * CFB encryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} plaintext - * @param {Uint8Array} iv - * @param {Object} config - full configuration, defaults to openpgp.config - * @returns MaybeStream - */ -async function encrypt(algo, key, plaintext, iv, config) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeEncrypt(algo, key, plaintext, iv); - } - if (util.isAES(algo)) { - return aesEncrypt(algo, key, plaintext, iv, config); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - const blockc = iv.slice(); - let pt = new Uint8Array(); - const process = chunk => { - if (chunk) { - pt = util.concatUint8Array([pt, chunk]); - } - const ciphertext = new Uint8Array(pt.length); - let i; - let j = 0; - while (chunk ? pt.length >= block_size : pt.length) { - const encblock = cipherfn.encrypt(blockc); - for (i = 0; i < block_size; i++) { - blockc[i] = pt[i] ^ encblock[i]; - ciphertext[j++] = blockc[i]; - } - pt = pt.subarray(block_size); - } - return ciphertext.subarray(0, j); - }; - return transform(plaintext, process, process); -} - -/** - * CFB decryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} ciphertext - * @param {Uint8Array} iv - * @returns MaybeStream - */ -async function decrypt(algo, key, ciphertext, iv) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeDecrypt(algo, key, ciphertext, iv); - } - if (util.isAES(algo)) { - return aesDecrypt(algo, key, ciphertext, iv); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - let blockp = iv; - let ct = new Uint8Array(); - const process = chunk => { - if (chunk) { - ct = util.concatUint8Array([ct, chunk]); - } - const plaintext = new Uint8Array(ct.length); - let i; - let j = 0; - while (chunk ? ct.length >= block_size : ct.length) { - const decblock = cipherfn.encrypt(blockp); - blockp = ct.subarray(0, block_size); - for (i = 0; i < block_size; i++) { - plaintext[j++] = blockp[i] ^ decblock[i]; - } - ct = ct.subarray(block_size); - } - return plaintext.subarray(0, j); - }; - return transform(ciphertext, process, process); -} - -function aesEncrypt(algo, key, pt, iv, config) { - if ( - util.getWebCrypto() && - key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support - !util.isStream(pt) && - pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2 - ) { // Web Crypto - return webEncrypt(algo, key, pt, iv); - } - // asm.js fallback - const cfb = new AES_CFB(key, iv); - return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish()); -} - -function aesDecrypt(algo, key, ct, iv) { - if (util.isStream(ct)) { - const cfb = new AES_CFB(key, iv); - return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish()); - } - return AES_CFB.decrypt(ct, key, iv); -} - -function xorMut(a, b) { - for (let i = 0; i < a.length; i++) { - a[i] = a[i] ^ b[i]; - } -} - -async function webEncrypt(algo, key, pt, iv) { - const ALGO = 'AES-CBC'; - const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']); - const { blockSize } = getCipher(algo); - const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]); - const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length); - xorMut(ct, pt); - return ct; -} - -function nodeEncrypt(algo, key, pt, iv) { - const algoName = enums.read(enums.symmetric, algo); - const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv); - return transform(pt, value => new Uint8Array(cipherObj.update(value))); -} - -function nodeDecrypt(algo, key, ct, iv) { - const algoName = enums.read(enums.symmetric, algo); - const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv); - return transform(ct, value => new Uint8Array(decipherObj.update(value))); -} - -var cfb = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt, - decrypt: decrypt -}); - -class AES_CTR { - static encrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - static decrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - constructor(key, nonce, aes) { - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - delete this.aes.padding; - this.AES_CTR_set_options(nonce); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - AES_CTR_set_options(nonce, counter, size) { - let { asm } = this.aes.acquire_asm(); - if (size !== undefined) { - if (size < 8 || size > 48) - throw new IllegalArgumentError('illegal counter size'); - let mask = Math.pow(2, size) - 1; - asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0); - } - else { - size = 48; - asm.set_mask(0, 0, 0xffff, 0xffffffff); - } - if (nonce !== undefined) { - let len = nonce.length; - if (!len || len > 16) - throw new IllegalArgumentError('illegal nonce size'); - let view = new DataView(new ArrayBuffer(16)); - new Uint8Array(view.buffer).set(nonce); - asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); - } - else { - throw new Error('nonce is required'); - } - if (counter !== undefined) { - if (counter < 0 || counter >= Math.pow(2, size)) - throw new IllegalArgumentError('illegal counter value'); - asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0); - } - } -} - -class AES_CBC { - static encrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).encrypt(data); - } - static decrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).decrypt(data); - } - constructor(key, iv, padding = true, aes) { - this.aes = aes ? aes : new AES(key, iv, padding, 'CBC'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * @fileoverview This module implements AES-CMAC on top of - * native AES-CBC using either the WebCrypto API or Node.js' crypto API. - * @module crypto/cmac - * @private - */ - -const webCrypto$2 = util.getWebCrypto(); -const nodeCrypto$2 = util.getNodeCrypto(); - - -/** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - -const blockLength = 16; - - -/** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param {Uint8Array} data - * @param {Uint8Array} padding - */ -function rightXORMut(data, padding) { - const offset = data.length - blockLength; - for (let i = 0; i < blockLength; i++) { - data[i + offset] ^= padding[i]; - } - return data; -} - -function pad(data, padding, padding2) { - // if |M| in {n, 2n, 3n, ...} - if (data.length && data.length % blockLength === 0) { - // then return M xor→ B, - return rightXORMut(data, padding); - } - // else return (M || 10^(n−1−(|M| mod n))) xor→ P - const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength))); - padded.set(data); - padded[data.length] = 0b10000000; - return rightXORMut(padded, padding2); -} - -const zeroBlock = new Uint8Array(blockLength); - -async function CMAC(key) { - const cbc = await CBC(key); - - // L ← E_K(0^n); B ← 2L; P ← 4L - const padding = util.double(await cbc(zeroBlock)); - const padding2 = util.double(padding); - - return async function(data) { - // return CBC_K(pad(M; B, P)) - return (await cbc(pad(data, padding, padding2))).subarray(-blockLength); - }; -} - -async function CBC(key) { - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); - return async function(pt) { - const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt); - return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt) { - const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); - const ct = en.update(pt); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt) { - return AES_CBC.encrypt(pt, key, false, zeroBlock); - }; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$3 = util.getWebCrypto(); -const nodeCrypto$3 = util.getNodeCrypto(); -const Buffer$1 = util.getNodeBuffer(); - - -const blockLength$1 = 16; -const ivLength = blockLength$1; -const tagLength = blockLength$1; - -const zero = new Uint8Array(blockLength$1); -const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1; -const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2; - -async function OMAC(key) { - const cmac = await CMAC(key); - return function(t, message) { - return cmac(util.concatUint8Array([t, message])); - }; -} - -async function CTR(key) { - if ( - util.getWebCrypto() && - key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - ) { - key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); - return async function(pt, iv) { - const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt); - return new Uint8Array(ct); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt, iv) { - const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); - const ct = Buffer$1.concat([en.update(pt), en.final()]); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt, iv) { - return AES_CTR.encrypt(pt, key, iv); - }; -} - - -/** - * Class to en/decrypt using EAX mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function EAX(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('EAX mode supports only AES cipher'); - } - - const [ - omac, - ctr - ] = await Promise.all([ - OMAC(key), - CTR(key) - ]); - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - const [ - omacNonce, - omacAdata - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata) - ]); - const ciphered = await ctr(plaintext, omacNonce); - const omacCiphered = await omac(two, ciphered); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - return util.concatUint8Array([ciphered, tag]); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to verify - * @returns {Promise} The plaintext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext'); - const ciphered = ciphertext.subarray(0, -tagLength); - const ctTag = ciphertext.subarray(-tagLength); - const [ - omacNonce, - omacAdata, - omacCiphered - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata), - omac(two, ciphered) - ]); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); - const plaintext = await ctr(ciphered, omacNonce); - return plaintext; - } - }; -} - - -/** - * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. - * @param {Uint8Array} iv - The initialization vector (16 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -EAX.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[8 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -EAX.blockLength = blockLength$1; -EAX.ivLength = ivLength; -EAX.tagLength = tagLength; - -// OpenPGP.js - An OpenPGP implementation in javascript - -const blockLength$2 = 16; -const ivLength$1 = 15; - -// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: -// While OCB [RFC7253] allows the authentication tag length to be of any -// number up to 128 bits long, this document requires a fixed -// authentication tag length of 128 bits (16 octets) for simplicity. -const tagLength$1 = 16; - - -function ntz(n) { - let ntz = 0; - for (let i = 1; (n & i) === 0; i <<= 1) { - ntz++; - } - return ntz; -} - -function xorMut$1(S, T) { - for (let i = 0; i < S.length; i++) { - S[i] ^= T[i]; - } - return S; -} - -function xor(S, T) { - return xorMut$1(S.slice(), T); -} - -const zeroBlock$1 = new Uint8Array(blockLength$2); -const one$1 = new Uint8Array([1]); - -/** - * Class to en/decrypt using OCB mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function OCB(cipher$1, key) { - - let maxNtz = 0; - let encipher; - let decipher; - let mask; - - constructKeyVariables(cipher$1, key); - - function constructKeyVariables(cipher$1, key) { - const cipherName = enums.read(enums.symmetric, cipher$1); - const aes = new cipher[cipherName](key); - encipher = aes.encrypt.bind(aes); - decipher = aes.decrypt.bind(aes); - - const mask_x = encipher(zeroBlock$1); - const mask_$ = util.double(mask_x); - mask = []; - mask[0] = util.double(mask_$); - - - mask.x = mask_x; - mask.$ = mask_$; - } - - function extendKeyVariables(text, adata) { - const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1; - for (let i = maxNtz + 1; i <= newMaxNtz; i++) { - mask[i] = util.double(mask[i - 1]); - } - maxNtz = newMaxNtz; - } - - function hash(adata) { - if (!adata.length) { - // Fast path - return zeroBlock$1; - } - - // - // Consider A as a sequence of 128-bit blocks - // - const m = adata.length / blockLength$2 | 0; - - const offset = new Uint8Array(blockLength$2); - const sum = new Uint8Array(blockLength$2); - for (let i = 0; i < m; i++) { - xorMut$1(offset, mask[ntz(i + 1)]); - xorMut$1(sum, encipher(xor(offset, adata))); - adata = adata.subarray(blockLength$2); - } - - // - // Process any final partial block; compute final hash value - // - if (adata.length) { - xorMut$1(offset, mask.x); - - const cipherInput = new Uint8Array(blockLength$2); - cipherInput.set(adata, 0); - cipherInput[adata.length] = 0b10000000; - xorMut$1(cipherInput, offset); - - xorMut$1(sum, encipher(cipherInput)); - } - - return sum; - } - - /** - * Encrypt/decrypt data. - * @param {encipher|decipher} fn - Encryption/decryption block cipher function - * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. - */ - function crypt(fn, text, nonce, adata) { - // - // Consider P as a sequence of 128-bit blocks - // - const m = text.length / blockLength$2 | 0; - - // - // Key-dependent variables - // - extendKeyVariables(text, adata); - - // - // Nonce-dependent and per-encryption variables - // - // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N - // Note: We assume here that tagLength mod 16 == 0. - const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]); - // bottom = str2num(Nonce[123..128]) - const bottom = paddedNonce[blockLength$2 - 1] & 0b111111; - // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) - paddedNonce[blockLength$2 - 1] &= 0b11000000; - const kTop = encipher(paddedNonce); - // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) - const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); - // Offset_0 = Stretch[1+bottom..128+bottom] - const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); - // Checksum_0 = zeros(128) - const checksum = new Uint8Array(blockLength$2); - - const ct = new Uint8Array(text.length + tagLength$1); - - // - // Process any whole blocks - // - let i; - let pos = 0; - for (i = 0; i < m; i++) { - // Offset_i = Offset_{i-1} xor L_{ntz(i)} - xorMut$1(offset, mask[ntz(i + 1)]); - // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) - // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) - ct.set(xorMut$1(fn(xor(offset, text)), offset), pos); - // Checksum_i = Checksum_{i-1} xor P_i - xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos)); - - text = text.subarray(blockLength$2); - pos += blockLength$2; - } - - // - // Process any final partial block and compute raw tag - // - if (text.length) { - // Offset_* = Offset_m xor L_* - xorMut$1(offset, mask.x); - // Pad = ENCIPHER(K, Offset_*) - const padding = encipher(offset); - // C_* = P_* xor Pad[1..bitlen(P_*)] - ct.set(xor(text, padding), pos); - - // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - const xorInput = new Uint8Array(blockLength$2); - xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); - xorInput[text.length] = 0b10000000; - xorMut$1(checksum, xorInput); - pos += text.length; - } - // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) - const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata)); - - // - // Assemble ciphertext - // - // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] - ct.set(tag, pos); - return ct; - } - - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - return crypt(encipher, plaintext, nonce, adata); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); - - const tag = ciphertext.subarray(-tagLength$1); - ciphertext = ciphertext.subarray(0, -tagLength$1); - - const crypted = crypt(decipher, ciphertext, nonce, adata); - // if (Tag[1..TAGLEN] == T) - if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { - return crypted.subarray(0, -tagLength$1); - } - throw new Error('Authentication tag mismatch'); - } - }; -} - - -/** - * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. - * @param {Uint8Array} iv - The initialization vector (15 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -OCB.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[7 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -OCB.blockLength = blockLength$2; -OCB.ivLength = ivLength$1; -OCB.tagLength = tagLength$1; - -const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 -class AES_GCM { - constructor(key, nonce, adata, tagSize = 16, aes) { - this.tagSize = tagSize; - this.gamma0 = 0; - this.counter = 1; - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - let { asm, heap } = this.aes.acquire_asm(); - // Init GCM - asm.gcm_init(); - // Tag size - if (this.tagSize < 4 || this.tagSize > 16) - throw new IllegalArgumentError('illegal tagSize value'); - // Nonce - const noncelen = nonce.length || 0; - const noncebuf = new Uint8Array(16); - if (noncelen !== 12) { - this._gcm_mac_process(nonce); - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = 0; - heap[4] = 0; - heap[5] = 0; - heap[6] = 0; - heap[7] = 0; - heap[8] = 0; - heap[9] = 0; - heap[10] = 0; - heap[11] = noncelen >>> 29; - heap[12] = (noncelen >>> 21) & 255; - heap[13] = (noncelen >>> 13) & 255; - heap[14] = (noncelen >>> 5) & 255; - heap[15] = (noncelen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_iv(0, 0, 0, 0); - noncebuf.set(heap.subarray(0, 16)); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; - } - const nonceview = new DataView(noncebuf.buffer); - this.gamma0 = nonceview.getUint32(12); - asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); - asm.set_mask(0, 0, 0, 0xffffffff); - // Associated data - if (adata !== undefined) { - if (adata.length > _AES_GCM_data_maxLength) - throw new IllegalArgumentError('illegal adata length'); - if (adata.length) { - this.adata = adata; - this._gcm_mac_process(adata); - } - else { - this.adata = undefined; - } - } - else { - this.adata = undefined; - } - // Counter - if (this.counter < 1 || this.counter > 0xffffffff) - throw new RangeError('counter must be a positive 32-bit integer'); - asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0); - } - static encrypt(cleartext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext); - } - static decrypt(ciphertext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext); - } - encrypt(data) { - return this.AES_GCM_encrypt(data); - } - decrypt(data) { - return this.AES_GCM_decrypt(data); - } - AES_GCM_Encrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len); - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Encrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let adata = this.adata; - let pos = this.aes.pos; - let len = this.aes.len; - const result = new Uint8Array(len + tagSize); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16); - if (len) - result.set(heap.subarray(pos, pos + len)); - let i = len; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - result.set(heap.subarray(0, tagSize), len); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_Decrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0; - let tlen = len + dlen - rlen; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > tlen) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - pos = 0; - len = 0; - } - if (dlen > 0) { - len += _heap_write(heap, 0, data, dpos, dlen); - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Decrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let tagSize = this.tagSize; - let adata = this.adata; - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rlen = len - tagSize; - if (len < tagSize) - throw new IllegalStateError('authentication tag not found'); - const result = new Uint8Array(rlen); - const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); - let i = rlen; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len - tagSize; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - let acheck = 0; - for (let i = 0; i < tagSize; ++i) - acheck |= atag[i] ^ heap[i]; - if (acheck) - throw new SecurityError('data integrity check failed'); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_decrypt(data) { - const result1 = this.AES_GCM_Decrypt_process(data); - const result2 = this.AES_GCM_Decrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - AES_GCM_encrypt(data) { - const result1 = this.AES_GCM_Encrypt_process(data); - const result2 = this.AES_GCM_Encrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - _gcm_mac_process(data) { - let { asm, heap } = this.aes.acquire_asm(); - let dpos = 0; - let dlen = data.length || 0; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, 0, data, dpos, dlen); - dpos += wlen; - dlen -= wlen; - while (wlen & 15) - heap[wlen++] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$4 = util.getWebCrypto(); -const nodeCrypto$4 = util.getNodeCrypto(); -const Buffer$2 = util.getNodeBuffer(); - -const blockLength$3 = 16; -const ivLength$2 = 12; // size of the IV in bytes -const tagLength$2 = 16; // size of the tag in bytes -const ALGO = 'AES-GCM'; - -/** - * Class to en/decrypt using GCM mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function GCM(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('GCM mode supports only AES cipher'); - } - - if (util.getNodeCrypto()) { // Node crypto library - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - en.setAAD(adata); - const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - de.setAAD(adata); - de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext - const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]); - return new Uint8Array(pt); - } - }; - } - - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); - - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.encrypt(pt, key, iv, adata); - } - const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt); - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.decrypt(ct, key, iv, adata); - } - const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct); - return new Uint8Array(pt); - } - }; - } - - return { - encrypt: async function(pt, iv, adata) { - return AES_GCM.encrypt(pt, key, iv, adata); - }, - - decrypt: async function(ct, iv, adata) { - return AES_GCM.decrypt(ct, key, iv, adata); - } - }; -} - - -/** - * Get GCM nonce. Note: this operation is not defined by the standard. - * A future version of the standard may define GCM mode differently, - * hopefully under a different ID (we use Private/Experimental algorithm - * ID 100) so that we can maintain backwards compatibility. - * @param {Uint8Array} iv - The initialization vector (12 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -GCM.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[4 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -GCM.blockLength = blockLength$3; -GCM.ivLength = ivLength$2; -GCM.tagLength = tagLength$2; - -/** - * @fileoverview Cipher modes - * @module crypto/mode - * @private - */ - -var mode = { - /** @see module:crypto/mode/cfb */ - cfb: cfb, - /** @see module:crypto/mode/gcm */ - gcm: GCM, - experimentalGCM: GCM, - /** @see module:crypto/mode/eax */ - eax: EAX, - /** @see module:crypto/mode/ocb */ - ocb: OCB -}; - -var naclFastLight = createCommonjsModule(function (module) { -/*jshint bitwise: false*/ - -(function(nacl) { - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d; - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d, h, r; - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - r = nacl.hash(sm.subarray(32, smlen)); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - h = nacl.hash(sm.subarray(0, smlen)); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i; - var t = new Uint8Array(32), h; - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - h = nacl.hash(m.subarray(0, n)); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - return n; -} - -var crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32; - -function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError('unexpected type, use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.box = {}; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof commonjsRequire !== 'undefined') { - // Node.js. - crypto = crypto$3; - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(module.exports ? module.exports : (self.nacl = self.nacl || {})); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const nodeCrypto$5 = util.getNodeCrypto(); - -/** - * Retrieve secure random byte array of the specified length - * @param {Integer} length - Length in bytes to generate - * @returns {Uint8Array} Random byte array. - */ -function getRandomBytes(length) { - const buf = new Uint8Array(length); - if (nodeCrypto$5) { - const bytes = nodeCrypto$5.randomBytes(buf.length); - buf.set(bytes); - } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - crypto.getRandomValues(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; -} - -/** - * Create a secure random BigInteger that is greater than or equal to min and less than max. - * @param {module:BigInteger} min - Lower bound, included - * @param {module:BigInteger} max - Upper bound, excluded - * @returns {Promise} Random BigInteger. - * @async - */ -async function getRandomBigInteger(min, max) { - const BigInteger = await util.getBigInteger(); - - if (max.lt(min)) { - throw new Error('Illegal parameter value: max <= min'); - } - - const modulus = max.sub(min); - const bytes = modulus.byteLength(); - - // Using a while loop is necessary to avoid bias introduced by the mod operation. - // However, we request 64 extra random bits so that the bias is negligible. - // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - const r = new BigInteger(await getRandomBytes(bytes + 8)); - return r.mod(modulus).add(min); -} - -var random = /*#__PURE__*/Object.freeze({ - __proto__: null, - getRandomBytes: getRandomBytes, - getRandomBigInteger: getRandomBigInteger -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Generate a probably prime random number - * @param {Integer} bits - Bit length of the prime - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns BigInteger - * @async - */ -async function randomProbablePrime(bits, e, k) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - const min = one.leftShift(new BigInteger(bits - 1)); - const thirty = new BigInteger(30); - /* - * We can avoid any multiples of 3 and 5 by looking at n mod 30 - * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 - * the next possible prime is mod 30: - * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 - */ - const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; - - const n = await getRandomBigInteger(min, min.leftShift(one)); - let i = n.mod(thirty).toNumber(); - - do { - n.iadd(new BigInteger(adds[i])); - i = (i + adds[i]) % adds.length; - // If reached the maximum, go back to the minimum. - if (n.bitLength() > bits) { - n.imod(min.leftShift(one)).iadd(min); - i = n.mod(thirty).toNumber(); - } - } while (!await isProbablePrime(n, e, k)); - return n; -} - -/** - * Probabilistic primality testing - * @param {BigInteger} n - Number to test - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns {boolean} - * @async - */ -async function isProbablePrime(n, e, k) { - if (e && !n.dec().gcd(e).isOne()) { - return false; - } - if (!await divisionTest(n)) { - return false; - } - if (!await fermat(n)) { - return false; - } - if (!await millerRabin(n, k)) { - return false; - } - // TODO implement the Lucas test - // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - return true; -} - -/** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n != 1. - * @param {BigInteger} n - Number to test - * @param {BigInteger} b - Optional Fermat test base - * @returns {boolean} - */ -async function fermat(n, b) { - const BigInteger = await util.getBigInteger(); - b = b || new BigInteger(2); - return b.modExp(n.dec(), n).isOne(); -} - -async function divisionTest(n) { - const BigInteger = await util.getBigInteger(); - return smallPrimes.every(m => { - return n.mod(new BigInteger(m)) !== 0; - }); -} - -// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c -const smallPrimes = [ - 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, - 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, - 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, - 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, - 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, - 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, - 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, - 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, - 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, - 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, - 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, - 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, - 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, - 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, - 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, - 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, - 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, - 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, - 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, - 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, - 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, - 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, - 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, - 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, - 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, - 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, - 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, - 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, - 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, - 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, - 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, - 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, - 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, - 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, - 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, - 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, - 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, - 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, - 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, - 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, - 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, - 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, - 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, - 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, - 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, - 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, - 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, - 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, - 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, - 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, - 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, - 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, - 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, - 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, - 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, - 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, - 4957, 4967, 4969, 4973, 4987, 4993, 4999 -]; - - -// Miller-Rabin - Miller Rabin algorithm for primality test -// Copyright Fedor Indutny, 2014. -// -// This software is licensed under the MIT License. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin - -// Sample syntax for Fixed-Base Miller-Rabin: -// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) - -/** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param {BigInteger} n - Number to test - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @param {Function} rand - Optional function to generate potential witnesses - * @returns {boolean} - * @async - */ -async function millerRabin(n, k, rand) { - const BigInteger = await util.getBigInteger(); - const len = n.bitLength(); - - if (!k) { - k = Math.max(1, (len / 48) | 0); - } - - const n1 = n.dec(); // n - 1 - - // Find d and s, (n - 1) = (2 ^ s) * d; - let s = 0; - while (!n1.getBit(s)) { s++; } - const d = n.rightShift(new BigInteger(s)); - - for (; k > 0; k--) { - const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1); - - let x = a.modExp(d, n); - if (x.isOne() || x.equal(n1)) { - continue; - } - - let i; - for (i = 1; i < s; i++) { - x = x.mul(x).mod(n); - - if (x.isOne()) { - return false; - } - if (x.equal(n1)) { - break; - } - } - - if (i === s) { - return false; - } - } - - return true; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ASN1 object identifiers for hashes - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} - */ -const hash_headers = []; -hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; -hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; -hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; -hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; -hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; -hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; -hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; - -/** - * Create padding with secure random data - * @private - * @param {Integer} length - Length of the padding in bytes - * @returns {Uint8Array} Random padding. - */ -function getPKCS1Padding(length) { - const result = new Uint8Array(length); - let count = 0; - while (count < length) { - const randomBytes = getRandomBytes(length - count); - for (let i = 0; i < randomBytes.length; i++) { - if (randomBytes[i] !== 0) { - result[count++] = randomBytes[i]; - } - } - } - return result; -} - -/** - * Create a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} - * @param {Uint8Array} message - Message to be encoded - * @param {Integer} keyLength - The length in octets of the key modulus - * @returns {Uint8Array} EME-PKCS1 padded message. - */ -function emeEncode(message, keyLength) { - const mLength = message.length; - // length checking - if (mLength > keyLength - 11) { - throw new Error('Message too long'); - } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - const PS = getPKCS1Padding(keyLength - mLength - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - const encoded = new Uint8Array(keyLength); - // 0x00 byte - encoded[1] = 2; - encoded.set(PS, 2); - // 0x00 bytes - encoded.set(message, keyLength - mLength); - return encoded; -} - -/** - * Decode a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} - * @param {Uint8Array} encoded - Encoded message bytes - * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) - * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) - * @throws {Error} on decoding failure, unless `randomPayload` is provided - */ -function emeDecode(encoded, randomPayload) { - // encoded format: 0x00 0x02 0x00 - let offset = 2; - let separatorNotFound = 1; - for (let j = offset; j < encoded.length; j++) { - separatorNotFound &= encoded[j] !== 0; - offset += separatorNotFound; - } - - const psLen = offset - 2; - const payload = encoded.subarray(offset + 1); // discard the 0x00 separator - const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - - if (randomPayload) { - return util.selectUint8Array(isValidPadding, payload, randomPayload); - } - - if (isValidPadding) { - return payload; - } - - throw new Error('Decryption error'); -} - -/** - * Create a EMSA-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} - * @param {Integer} algo - Hash algorithm type used - * @param {Uint8Array} hashed - Message to be encoded - * @param {Integer} emLen - Intended length in octets of the encoded message - * @returns {Uint8Array} Encoded message. - */ -async function emsaEncode(algo, hashed, emLen) { - let i; - if (hashed.length !== hash.getHashByteLength(algo)) { - throw new Error('Invalid hash length'); - } - // produce an ASN.1 DER value for the hash function used. - // Let T be the full hash prefix - const hashPrefix = new Uint8Array(hash_headers[algo].length); - for (i = 0; i < hash_headers[algo].length; i++) { - hashPrefix[i] = hash_headers[algo][i]; - } - // and let tLen be the length in octets prefix and hashed data - const tLen = hashPrefix.length + hashed.length; - if (emLen < tLen + 11) { - throw new Error('Intended encoded message length too short'); - } - // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF - // The length of PS will be at least 8 octets - const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - - // Concatenate PS, the hash prefix, hashed data, and other padding to form the - // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed - const EM = new Uint8Array(emLen); - EM[1] = 0x01; - EM.set(PS, 2); - EM.set(hashPrefix, emLen - tLen); - EM.set(hashed, emLen - hashed.length); - return EM; -} - -var pkcs1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - emeEncode: emeEncode, - emeDecode: emeDecode, - emsaEncode: emsaEncode -}); - -const webCrypto$5 = util.getWebCrypto(); -const nodeCrypto$6 = util.getNodeCrypto(); -const asn1 = nodeCrypto$6 ? asn1$2 : undefined; - -/* eslint-disable no-invalid-this */ -const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('version').int(), // 0 - this.key('modulus').int(), // n - this.key('publicExponent').int(), // e - this.key('privateExponent').int(), // d - this.key('prime1').int(), // p - this.key('prime2').int(), // q - this.key('exponent1').int(), // dp - this.key('exponent2').int(), // dq - this.key('coefficient').int() // u - ); -}) : undefined; - -const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('modulus').int(), // n - this.key('publicExponent').int() // e - ); -}) : undefined; -/* eslint-enable no-invalid-this */ - -/** Create signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} hashed - Hashed message - * @returns {Promise} RSA Signature. - * @async - */ -async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeSign(hashAlgo, data, n, e, d, p, q, u); - } - } - return bnSign(hashAlgo, n, d, hashed); -} - -/** - * Verify signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} s - Signature - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} hashed - Hashed message - * @returns {Boolean} - * @async - */ -async function verify(hashAlgo, data, s, n, e, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeVerify(hashAlgo, data, s, n, e); - } - } - return bnVerify(hashAlgo, s, n, e, hashed); -} - -/** - * Encrypt message - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @returns {Promise} RSA Ciphertext. - * @async - */ -async function encrypt$1(data, n, e) { - if (util.getNodeCrypto()) { - return nodeEncrypt$1(data, n, e); - } - return bnEncrypt(data, n, e); -} - -/** - * Decrypt RSA message - * @param {Uint8Array} m - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} RSA Plaintext. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$1(data, n, e, d, p, q, u, randomPayload) { - // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, - // and we want to avoid checking the error type to decide if the random payload - // should indeed be returned. - if (util.getNodeCrypto() && !randomPayload) { - try { - return await nodeDecrypt$1(data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } - return bnDecrypt(data, n, e, d, p, q, u, randomPayload); -} - -/** - * Generate a new random private key B bits long with public exponent E. - * - * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param {Integer} bits - RSA bit length - * @param {Integer} e - RSA public exponent - * @returns {{n, e, d, - * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = p ** -1 mod q - * @async - */ -async function generate(bits, e) { - const BigInteger = await util.getBigInteger(); - - e = new BigInteger(e); - - // Native RSA keygen using Web Crypto - if (util.getWebCrypto()) { - const keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, // the specified keysize in bits - publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); - // map JWK parameters to corresponding OpenPGP names - return { - n: b64ToUint8Array(jwk.n), - e: e.toUint8Array(), - d: b64ToUint8Array(jwk.d), - // switch p and q - p: b64ToUint8Array(jwk.q), - q: b64ToUint8Array(jwk.p), - // Since p and q are switched in places, u is the inverse of jwk.q - u: b64ToUint8Array(jwk.qi) - }; - } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) { - const opts = { - modulusLength: bits, - publicExponent: e.toNumber(), - publicKeyEncoding: { type: 'pkcs1', format: 'der' }, - privateKeyEncoding: { type: 'pkcs1', format: 'der' } - }; - const prv = await new Promise((resolve, reject) => { - nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => { - if (err) { - reject(err); - } else { - resolve(RSAPrivateKey.decode(der, 'der')); - } - }); - }); - /** - * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`. - * @link https://tools.ietf.org/html/rfc3447#section-3.2 - * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1 - */ - return { - n: prv.modulus.toArrayLike(Uint8Array), - e: prv.publicExponent.toArrayLike(Uint8Array), - d: prv.privateExponent.toArrayLike(Uint8Array), - // switch p and q - p: prv.prime2.toArrayLike(Uint8Array), - q: prv.prime1.toArrayLike(Uint8Array), - // Since p and q are switched in places, we can keep u as defined by DER - u: prv.coefficient.toArrayLike(Uint8Array) - }; - } - - // RSA keygen fallback using 40 iterations of the Miller-Rabin test - // See https://stackoverflow.com/a/6330138 for justification - // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST - let p; - let q; - let n; - do { - q = await randomProbablePrime(bits - (bits >> 1), e, 40); - p = await randomProbablePrime(bits >> 1, e, 40); - n = p.mul(q); - } while (n.bitLength() !== bits); - - const phi = p.dec().imul(q.dec()); - - if (q.lt(p)) { - [p, q] = [q, p]; - } - - return { - n: n.toUint8Array(), - e: e.toUint8Array(), - d: e.modInv(phi).toUint8Array(), - p: p.toUint8Array(), - q: q.toUint8Array(), - // dp: d.mod(p.subn(1)), - // dq: d.mod(q.subn(1)), - u: p.modInv(q).toUint8Array() - }; -} - -/** - * Validate RSA parameters - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA inverse of p w.r.t. q - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - p = new BigInteger(p); - q = new BigInteger(q); - - // expect pq = n - if (!p.mul(q).equal(n)) { - return false; - } - - const two = new BigInteger(2); - // expect p*u = 1 mod q - u = new BigInteger(u); - if (!p.mul(u).mod(q).isOne()) { - return false; - } - - e = new BigInteger(e); - d = new BigInteger(d); - /** - * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) - * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] - * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] - * - * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) - */ - const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3)); - const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q - const rde = r.mul(d).mul(e); - - const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r); - if (!areInverses) { - return false; - } - - return true; -} - -async function bnSign(hashAlgo, n, d, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); - d = new BigInteger(d); - if (m.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return m.modExp(d, n).toUint8Array('be', n.byteLength()); -} - -async function webSign(hashName, data, n, e, d, p, q, u) { - /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJWK, so it usually works out, but nevertheless, - * not all OpenPGP keys are compatible with this requirement. - * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still - * does if the underlying Web Crypto does so (though the tested implementations - * don't do so). - */ - const jwk = await privateToJWK(n, e, d, p, q, u); - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }; - const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); - return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); -} - -async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(data); - sign.end(); - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPrivateKey.encode(keyObject, 'der'); - return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' })); - } - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - return new Uint8Array(sign.sign(pem)); -} - -async function bnVerify(hashAlgo, s, n, e, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - s = new BigInteger(s); - e = new BigInteger(e); - if (s.gte(n)) { - throw new Error('Signature size cannot exceed modulus size'); - } - const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); - return util.equalsUint8Array(EM1, EM2); -} - -async function webVerify(hashName, data, s, n, e) { - const jwk = publicToJWK(n, e); - const key = await webCrypto$5.importKey('jwk', jwk, { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }, false, ['verify']); - return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); -} - -async function nodeVerify(hashAlgo, data, s, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(data); - verify.end(); - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1' }; - } else { - key = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - } - try { - return await verify.verify(key, s); - } catch (err) { - return false; - } -} - -async function nodeEncrypt$1(data, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data)); -} - -async function bnEncrypt(data, n, e) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - data = new BigInteger(emeEncode(data, n.byteLength())); - e = new BigInteger(e); - if (data.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return data.modExp(e, n).toUint8Array('be', n.byteLength()); -} - -async function nodeDecrypt$1(data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPrivateKey.encode(keyObject, 'der'); - key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - try { - return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data)); - } catch (err) { - throw new Error('Decryption error'); - } -} - -async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { - const BigInteger = await util.getBigInteger(); - data = new BigInteger(data); - n = new BigInteger(n); - e = new BigInteger(e); - d = new BigInteger(d); - p = new BigInteger(p); - q = new BigInteger(q); - u = new BigInteger(u); - if (data.gte(n)) { - throw new Error('Data too large.'); - } - const dq = d.mod(q.dec()); // d mod (q-1) - const dp = d.mod(p.dec()); // d mod (p-1) - - const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n); - const blinder = unblinder.modInv(n).modExp(e, n); - data = data.mul(blinder).mod(n); - - - const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p - const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q - const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q) - - let result = h.mul(p).add(mp); // result < n due to relations above - - result = result.mul(unblinder).mod(n); - - - return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload); -} - -/** Convert Openpgp private key params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - * @param {Uint8Array} d - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} u - */ -async function privateToJWK(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - const pNum = new BigInteger(p); - const qNum = new BigInteger(q); - const dNum = new BigInteger(d); - - let dq = dNum.mod(qNum.dec()); // d mod (q-1) - let dp = dNum.mod(pNum.dec()); // d mod (p-1) - dp = dp.toUint8Array(); - dq = dq.toUint8Array(); - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - d: uint8ArrayToB64(d, true), - // switch p and q - p: uint8ArrayToB64(q, true), - q: uint8ArrayToB64(p, true), - // switch dp and dq - dp: uint8ArrayToB64(dq, true), - dq: uint8ArrayToB64(dp, true), - qi: uint8ArrayToB64(u, true), - ext: true - }; -} - -/** Convert Openpgp key public params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - */ -function publicToJWK(n, e) { - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - ext: true - }; -} - -var rsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign, - verify: verify, - encrypt: encrypt$1, - decrypt: decrypt$1, - generate: generate, - validateParams: validateParams -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ElGamal Encryption function - * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) - * @param {Uint8Array} data - To be padded and encrypted - * @param {Uint8Array} p - * @param {Uint8Array} g - * @param {Uint8Array} y - * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} - * @async - */ -async function encrypt$2(data, p, g, y) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const padded = emeEncode(data, p.byteLength()); - const m = new BigInteger(padded); - - // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* - // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] - const k = await getRandomBigInteger(new BigInteger(1), p.dec()); - return { - c1: g.modExp(k, p).toUint8Array(), - c2: y.modExp(k, p).imul(m).imod(p).toUint8Array() - }; -} - -/** - * ElGamal Encryption function - * @param {Uint8Array} c1 - * @param {Uint8Array} c2 - * @param {Uint8Array} p - * @param {Uint8Array} x - * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} Unpadded message. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$2(c1, c2, p, x, randomPayload) { - const BigInteger = await util.getBigInteger(); - c1 = new BigInteger(c1); - c2 = new BigInteger(c2); - p = new BigInteger(p); - x = new BigInteger(x); - - const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p); - return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload); -} - -/** - * Validate ElGamal parameters - * @param {Uint8Array} p - ElGamal prime - * @param {Uint8Array} g - ElGamal group generator - * @param {Uint8Array} y - ElGamal public key - * @param {Uint8Array} x - ElGamal private exponent - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$1(p, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - // Expect p-1 to be large - const pSize = new BigInteger(p.bitLength()); - const n1023 = new BigInteger(1023); - if (pSize.lt(n1023)) { - return false; - } - - /** - * g should have order p-1 - * Check that g ** (p-1) = 1 mod p - */ - if (!g.modExp(p.dec(), p).isOne()) { - return false; - } - - /** - * Since p-1 is not prime, g might have a smaller order that divides p-1 - * We want to make sure that the order is large enough to hinder a small subgroup attack - * - * We just check g**i != 1 for all i up to a threshold - */ - let res = g; - const i = new BigInteger(1); - const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold - while (i.lt(threshold)) { - res = res.mul(g).imod(p); - if (res.isOne()) { - return false; - } - i.iinc(); - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{r(p-1) + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1 - const rqx = p.dec().imul(r).iadd(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var elgamal = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt$2, - decrypt: decrypt$2, - validateParams: validateParams$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class OID { - constructor(oid) { - if (oid instanceof OID) { - this.oid = oid.oid; - } else if (util.isArray(oid) || - util.isUint8Array(oid)) { - oid = new Uint8Array(oid); - if (oid[0] === 0x06) { // DER encoded oid byte array - if (oid[1] !== oid.length - 2) { - throw new Error('Length mismatch in DER encoded oid'); - } - oid = oid.subarray(2); - } - this.oid = oid; - } else { - this.oid = ''; - } - } - - /** - * Method to read an OID object - * @param {Uint8Array} input - Where to read the OID from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length >= 1) { - const length = input[0]; - if (input.length >= 1 + length) { - this.oid = input.subarray(1, 1 + length); - return 1 + this.oid.length; - } - } - throw new Error('Invalid oid'); - } - - /** - * Serialize an OID object - * @returns {Uint8Array} Array with the serialized value the OID. - */ - write() { - return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); - } - - /** - * Serialize an OID object as a hex string - * @returns {string} String with the hex value of the OID. - */ - toHex() { - return util.uint8ArrayToHex(this.oid); - } - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns {string} String with the canonical name of the curve. - */ - getName() { - const hex = this.toHex(); - if (enums.curve[hex]) { - return enums.write(enums.curve, hex); - } else { - throw new Error('Unknown curve object identifier.'); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -function keyFromPrivate(indutnyCurve, priv) { - const keyPair = indutnyCurve.keyPair({ priv: priv }); - return keyPair; -} - -function keyFromPublic(indutnyCurve, pub) { - const keyPair = indutnyCurve.keyPair({ pub: pub }); - if (keyPair.validate().result !== true) { - throw new Error('Invalid elliptic public key'); - } - return keyPair; -} - -async function getIndutnyCurve(name) { - if (!config.useIndutnyElliptic) { - throw new Error('This curve is only supported in the full build of OpenPGP.js'); - } - const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; }); - return new elliptic.ec(name); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -function readSimpleLength(bytes) { - let len = 0; - let offset; - const type = bytes[0]; - - - if (type < 192) { - [len] = bytes; - offset = 1; - } else if (type < 255) { - len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; - offset = 2; - } else if (type === 255) { - len = util.readNumber(bytes.subarray(1, 1 + 4)); - offset = 5; - } - - return { - len: len, - offset: offset - }; -} - -/** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * - * @param {Integer} length - The length to encode - * @returns {Uint8Array} String with openpgp length representation. - */ -function writeSimpleLength(length) { - if (length < 192) { - return new Uint8Array([length]); - } else if (length > 191 && length < 8384) { - /* - * let a = (total data packet length) - 192 let bc = two octet - * representation of a let d = b + 192 - */ - return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); -} - -function writePartialLength(power) { - if (power < 0 || power > 30) { - throw new Error('Partial Length power must be between 1 and 30'); - } - return new Uint8Array([224 + power]); -} - -function writeTag(tag_type) { - /* we're only generating v4 packet headers here */ - return new Uint8Array([0xC0 | tag_type]); -} - -/** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * - * @param {Integer} tag_type - Tag type - * @param {Integer} length - Length of the payload - * @returns {String} String of the header. - */ -function writeHeader(tag_type, length) { - /* we're only generating v4 packet headers here */ - return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); -} - -/** - * Whether the packet type supports partial lengths per RFC4880 - * @param {Integer} tag - Tag type - * @returns {Boolean} String of the header. - */ -function supportsStreaming(tag) { - return [ - enums.packet.literalData, - enums.packet.compressedData, - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ].includes(tag); -} - -/** - * Generic static Packet Parser function - * - * @param {Uint8Array | ReadableStream} input - Input stream as string - * @param {Function} callback - Function to call with the parsed packet - * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. - */ -async function readPackets(input, callback) { - const reader = getReader(input); - let writer; - let callbackReturned; - try { - const peekedBytes = await reader.peekBytes(2); - // some sanity checks - if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { - throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); - } - const headerByte = await reader.readByte(); - let tag = -1; - let format = -1; - let packetLength; - - format = 0; // 0 = old format; 1 = new format - if ((headerByte & 0x40) !== 0) { - format = 1; - } - - let packetLengthType; - if (format) { - // new format header - tag = headerByte & 0x3F; // bit 5-0 - } else { - // old format header - tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packetLengthType = headerByte & 0x03; // bit 1-0 - } - - const packetSupportsStreaming = supportsStreaming(tag); - let packet = null; - if (packetSupportsStreaming) { - if (util.isStream(input) === 'array') { - const arrayStream = new ArrayStream(); - writer = getWriter(arrayStream); - packet = arrayStream; - } else { - const transform = new TransformStream(); - writer = getWriter(transform.writable); - packet = transform.readable; - } - // eslint-disable-next-line callback-return - callbackReturned = callback({ tag, packet }); - } else { - packet = []; - } - - let wasPartialLength; - do { - if (!format) { - // 4.2.1. Old Format Packet Lengths - switch (packetLengthType) { - case 0: - // The packet has a one-octet length. The header is 2 octets - // long. - packetLength = await reader.readByte(); - break; - case 1: - // The packet has a two-octet length. The header is 3 octets - // long. - packetLength = (await reader.readByte() << 8) | await reader.readByte(); - break; - case 2: - // The packet has a four-octet length. The header is 5 - // octets long. - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - break; - default: - // 3 - The packet is of indeterminate length. The header is 1 - // octet long, and the implementation must determine how long - // the packet is. If the packet is in a file, this means that - // the packet extends until the end of the file. In general, - // an implementation SHOULD NOT use indeterminate-length - // packets except where the end of the data will be clear - // from the context, and even then it is better to use a - // definite length, or a new format header. The new format - // headers described below have a mechanism for precisely - // encoding data of indeterminate length. - packetLength = Infinity; - break; - } - } else { // 4.2.2. New Format Packet Lengths - // 4.2.2.1. One-Octet Lengths - const lengthByte = await reader.readByte(); - wasPartialLength = false; - if (lengthByte < 192) { - packetLength = lengthByte; - // 4.2.2.2. Two-Octet Lengths - } else if (lengthByte >= 192 && lengthByte < 224) { - packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; - // 4.2.2.4. Partial Body Lengths - } else if (lengthByte > 223 && lengthByte < 255) { - packetLength = 1 << (lengthByte & 0x1F); - wasPartialLength = true; - if (!packetSupportsStreaming) { - throw new TypeError('This packet type does not support partial lengths.'); - } - // 4.2.2.3. Five-Octet Lengths - } else { - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - } - } - if (packetLength > 0) { - let bytesRead = 0; - while (true) { - if (writer) await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (packetLength === Infinity) break; - throw new Error('Unexpected end of packet'); - } - const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); - if (writer) await writer.write(chunk); - else packet.push(chunk); - bytesRead += value.length; - if (bytesRead >= packetLength) { - reader.unshift(value.subarray(packetLength - bytesRead + value.length)); - break; - } - } - } - } while (wasPartialLength); - - // If this was not a packet that "supports streaming", we peek to check - // whether it is the last packet in the message. We peek 2 bytes instead - // of 1 because the beginning of this function also peeks 2 bytes, and we - // want to cut a `subarray` of the correct length into `web-stream-tools`' - // `externalBuffer` as a tiny optimization here. - // - // If it *was* a streaming packet (i.e. the data packets), we peek at the - // entire remainder of the stream, in order to forward errors in the - // remainder of the stream to the packet data. (Note that this means we - // read/peek at all signature packets before closing the literal data - // packet, for example.) This forwards MDC errors to the literal data - // stream, for example, so that they don't get lost / forgotten on - // decryptedMessage.packets.stream, which we never look at. - // - // An example of what we do when stream-parsing a message containing - // [ one-pass signature packet, literal data packet, signature packet ]: - // 1. Read the one-pass signature packet - // 2. Peek 2 bytes of the literal data packet - // 3. Parse the one-pass signature packet - // - // 4. Read the literal data packet, simultaneously stream-parsing it - // 5. Peek until the end of the message - // 6. Finish parsing the literal data packet - // - // 7. Read the signature packet again (we already peeked at it in step 5) - // 8. Peek at the end of the stream again (`peekBytes` returns undefined) - // 9. Parse the signature packet - // - // Note that this means that if there's an error in the very end of the - // stream, such as an MDC error, we throw in step 5 instead of in step 8 - // (or never), which is the point of this exercise. - const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); - if (writer) { - await writer.ready; - await writer.close(); - } else { - packet = util.concatUint8Array(packet); - // eslint-disable-next-line callback-return - await callback({ tag, packet }); - } - return !nextPacket || !nextPacket.length; - } catch (e) { - if (writer) { - await writer.abort(e); - return true; - } else { - throw e; - } - } finally { - if (writer) { - await callbackReturned; - } - reader.releaseLock(); - } -} - -class UnsupportedError extends Error { - constructor(...params) { - super(...params); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, UnsupportedError); - } - - this.name = 'UnsupportedError'; - } -} - -class UnparseablePacket { - constructor(tag, rawContent) { - this.tag = tag; - this.rawContent = rawContent; - } - - write() { - return this.rawContent; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$6 = util.getWebCrypto(); -const nodeCrypto$7 = util.getNodeCrypto(); - -const webCurves = { - 'p256': 'P-256', - 'p384': 'P-384', - 'p521': 'P-521' -}; -const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : []; -const nodeCurves = nodeCrypto$7 ? { - secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, - p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, - p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, - p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, - ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined, - curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined, - brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, - brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, - brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined -} : {}; - -const curves = { - p256: { - oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.p256, - web: webCurves.p256, - payloadSize: 32, - sharedSize: 256 - }, - p384: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.p384, - web: webCurves.p384, - payloadSize: 48, - sharedSize: 384 - }, - p521: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.p521, - web: webCurves.p521, - payloadSize: 66, - sharedSize: 528 - }, - secp256k1: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1, - payloadSize: 32 - }, - ed25519: { - oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], - keyType: enums.publicKey.eddsaLegacy, - hash: enums.hash.sha512, - node: false, // nodeCurves.ed25519 TODO - payloadSize: 32 - }, - curve25519: { - oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], - keyType: enums.publicKey.ecdh, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: false, // nodeCurves.curve25519 TODO - payloadSize: 32 - }, - brainpoolP256r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1, - payloadSize: 32 - }, - brainpoolP384r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1, - payloadSize: 48 - }, - brainpoolP512r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1, - payloadSize: 64 - } -}; - -class CurveWithOID { - constructor(oidOrName, params) { - try { - if (util.isArray(oidOrName) || - util.isUint8Array(oidOrName)) { - // by oid byte array - oidOrName = new OID(oidOrName); - } - if (oidOrName instanceof OID) { - // by curve OID - oidOrName = oidOrName.getName(); - } - // by curve name or oid string - this.name = enums.write(enums.curve, oidOrName); - } catch (err) { - throw new UnsupportedError('Unknown curve'); - } - params = params || curves[this.name]; - - this.keyType = params.keyType; - - this.oid = params.oid; - this.hash = params.hash; - this.cipher = params.cipher; - this.node = params.node && curves[this.name]; - this.web = params.web && curves[this.name]; - this.payloadSize = params.payloadSize; - if (this.web && util.getWebCrypto()) { - this.type = 'web'; - } else if (this.node && util.getNodeCrypto()) { - this.type = 'node'; - } else if (this.name === 'curve25519') { - this.type = 'curve25519'; - } else if (this.name === 'ed25519') { - this.type = 'ed25519'; - } - } - - async genKeyPair() { - let keyPair; - switch (this.type) { - case 'web': - try { - return await webGenKeyPair(this.name); - } catch (err) { - util.printDebugError('Browser did not support generating ec key ' + err.message); - break; - } - case 'node': - return nodeGenKeyPair(this.name); - case 'curve25519': { - const privateKey = getRandomBytes(32); - privateKey[0] = (privateKey[0] & 127) | 64; - privateKey[31] &= 248; - const secretKey = privateKey.slice().reverse(); - keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - case 'ed25519': { - const privateKey = getRandomBytes(32); - const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - } - const indutnyCurve = await getIndutnyCurve(this.name); - keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToString(getRandomBytes(32)) - }); - return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; - } -} - -async function generate$1(curve) { - const BigInteger = await util.getBigInteger(); - - curve = new CurveWithOID(curve); - const keyPair = await curve.genKeyPair(); - const Q = new BigInteger(keyPair.publicKey).toUint8Array(); - const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize); - return { - oid: curve.oid, - Q, - secret, - hash: curve.hash, - cipher: curve.cipher - }; -} - -/** - * Get preferred hash algo to use with the given curve - * @param {module:type/oid} oid - curve oid - * @returns {enums.hash} hash algorithm - */ -function getPreferredHashAlgo(oid) { - return curves[enums.write(enums.curve, oid.toHex())].hash; -} - -/** - * Validate ECDH and ECDSA parameters - * Not suitable for EdDSA (different secret key format) - * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves - * @param {module:type/oid} oid - EC object identifier - * @param {Uint8Array} Q - EC public point - * @param {Uint8Array} d - EC secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateStandardParams(algo, oid, Q, d) { - const supportedCurves = { - p256: true, - p384: true, - p521: true, - secp256k1: true, - curve25519: algo === enums.publicKey.ecdh, - brainpoolP256r1: true, - brainpoolP384r1: true, - brainpoolP512r1: true - }; - - // Check whether the given curve is supported - const curveName = oid.getName(); - if (!supportedCurves[curveName]) { - return false; - } - - if (curveName === 'curve25519') { - d = d.slice().reverse(); - // Re-derive public point Q' - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d); - - Q = new Uint8Array(Q); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - if (!util.equalsUint8Array(dG, Q)) { - return false; - } - - return true; - } - - const curve = await getIndutnyCurve(curveName); - try { - // Parse Q and check that it is on the curve but not at infinity - Q = keyFromPublic(curve, Q).getPublic(); - } catch (validationErrors) { - return false; - } - - /** - * Re-derive public point Q' = dG from private key - * Expect Q == Q' - */ - const dG = keyFromPrivate(curve, d).getPublic(); - if (!dG.eq(Q)) { - return false; - } - - return true; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -async function webGenKeyPair(name) { - // Note: keys generated with ECDSA and ECDH are structurally equivalent - const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - - const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey); - const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey); - - return { - publicKey: jwkToRawPublic(publicKey), - privateKey: b64ToUint8Array(privateKey.d) - }; -} - -async function nodeGenKeyPair(name) { - // Note: ECDSA and ECDH key generation is structurally equivalent - const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]); - await ecdh.generateKeys(); - return { - publicKey: new Uint8Array(ecdh.getPublicKey()), - privateKey: new Uint8Array(ecdh.getPrivateKey()) - }; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -/** - * @param {JsonWebKey} jwk - key for conversion - * - * @returns {Uint8Array} Raw public key. - */ -function jwkToRawPublic(jwk) { - const bufX = b64ToUint8Array(jwk.x); - const bufY = b64ToUint8Array(jwk.y); - const publicKey = new Uint8Array(bufX.length + bufY.length + 1); - publicKey[0] = 0x04; - publicKey.set(bufX, 1); - publicKey.set(bufY, bufX.length + 1); - return publicKey; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * - * @returns {JsonWebKey} Public key in jwk format. - */ -function rawPublicToJWK(payloadSize, name, publicKey) { - const len = payloadSize; - const bufX = publicKey.slice(1, len + 1); - const bufY = publicKey.slice(len + 1, len * 2 + 1); - // https://www.rfc-editor.org/rfc/rfc7518.txt - const jwk = { - kty: 'EC', - crv: name, - x: uint8ArrayToB64(bufX, true), - y: uint8ArrayToB64(bufY, true), - ext: true - }; - return jwk; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * @param {Uint8Array} privateKey - private key - * - * @returns {JsonWebKey} Private key in jwk format. - */ -function privateToJWK$1(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJWK(payloadSize, name, publicKey); - jwk.d = uint8ArrayToB64(privateKey, true); - return jwk; -} - -const webCrypto$7 = util.getWebCrypto(); -const nodeCrypto$8 = util.getNodeCrypto(); - -/** - * Sign a message using the provided key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - const keyPair = { publicKey, privateKey }; - switch (curve.type) { - case 'web': { - // If browser doesn't support a curve, we'll catch it - try { - // Need to await to make sure browser succeeds - return await webSign$1(curve, hashAlgo, message, keyPair); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunaley Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support signing: ' + err.message); - } - break; - } - case 'node': { - const signature = await nodeSign$1(curve, hashAlgo, message, keyPair); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - } - } - return ellipticSign(curve, hashed, privateKey); -} - -/** - * Verifies if a signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify - * @param {Uint8Array} message - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - switch (curve.type) { - case 'web': - try { - // Need to await to make sure browser succeeds - return await webVerify$1(curve, hashAlgo, signature, message, publicKey); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunately Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support verifying: ' + err.message); - } - break; - case 'node': - return nodeVerify$1(curve, hashAlgo, signature, message, publicKey); - } - } - const digest = (typeof hashAlgo === 'undefined') ? message : hashed; - return ellipticVerify(curve, signature, digest, publicKey); -} - -/** - * Validate ECDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDSA public point - * @param {Uint8Array} d - ECDSA secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$2(oid, Q, d) { - const curve = new CurveWithOID(oid); - // Reject curves x25519 and ed25519 - if (curve.keyType !== enums.publicKey.ecdsa) { - return false; - } - - // To speed up the validation, we try to use node- or webcrypto when available - // and sign + verify a random message - switch (curve.type) { - case 'web': - case 'node': { - const message = getRandomBytes(8); - const hashAlgo = enums.hash.sha256; - const hashed = await hash.digest(hashAlgo, message); - try { - const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed); - return await verify$1(oid, hashAlgo, signature, message, Q, hashed); - } catch (err) { - return false; - } - } - default: - return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); - } -} - - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -async function ellipticSign(curve, hashed, privateKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPrivate(indutnyCurve, privateKey); - const signature = key.sign(hashed); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; -} - -async function ellipticVerify(curve, signature, digest, publicKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPublic(indutnyCurve, publicKey); - return key.verify(digest, signature); -} - -async function webSign$1(curve, hashAlgo, message, keyPair) { - const len = curve.payloadSize; - const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['sign'] - ); - - const signature = new Uint8Array(await webCrypto$7.sign( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - message - )); - - return { - r: signature.slice(0, len), - s: signature.slice(len, len << 1) - }; -} - -async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['verify'] - ); - - const signature = util.concatUint8Array([r, s]).buffer; - - return webCrypto$7.verify( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - signature, - message - ); -} - -async function nodeSign$1(curve, hashAlgo, message, keyPair) { - const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(message); - sign.end(); - const key = ECPrivateKey.encode({ - version: 1, - parameters: curve.oid, - privateKey: Array.from(keyPair.privateKey), - publicKey: { unused: 0, data: Array.from(keyPair.publicKey) } - }, 'pem', { - label: 'EC PRIVATE KEY' - }); - - return ECDSASignature.decode(sign.sign(key), 'der'); -} - -async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(message); - verify.end(); - const key = SubjectPublicKeyInfo.encode({ - algorithm: { - algorithm: [1, 2, 840, 10045, 2, 1], - parameters: curve.oid - }, - subjectPublicKey: { unused: 0, data: Array.from(publicKey) } - }, 'pem', { - label: 'PUBLIC KEY' - }); - const signature = ECDSASignature.encode({ - r: new BN(r), s: new BN(s) - }, 'der'); - - try { - return verify.verify(key, signature); - } catch (err) { - return false; - } -} - -// Originally written by Owen Smith https://github.com/omsmith -// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ - -/* eslint-disable no-invalid-this */ - -const asn1$1 = nodeCrypto$8 ? asn1$2 : undefined; - -const ECDSASignature = nodeCrypto$8 ? - asn1$1.define('ECDSASignature', function() { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ); - }) : undefined; - -const ECPrivateKey = nodeCrypto$8 ? - asn1$1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().any(), - this.key('publicKey').explicit(1).optional().bitstr() - ); - }) : undefined; - -const AlgorithmIdentifier = nodeCrypto$8 ? - asn1$1.define('AlgorithmIdentifier', function() { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional().any() - ); - }) : undefined; - -const SubjectPublicKeyInfo = nodeCrypto$8 ? - asn1$1.define('SubjectPublicKeyInfo', function() { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ); - }) : undefined; - -var ecdsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$1, - verify: verify$1, - validateParams: validateParams$2 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Sign a message using the provided legacy EdDSA key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - // EdDSA signature params are returned in little-endian format - return { - r: signature.subarray(0, 32), - s: signature.subarray(32) - }; -} - -/** - * Verifies if a legacy EdDSA signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const signature = util.concatUint8Array([r, s]); - return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1)); -} -/** - * Validate legacy EdDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - EdDSA public point - * @param {Uint8Array} k - EdDSA secret seed - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$3(oid, Q, k) { - // Check whether the given curve is supported - if (oid.getName() !== 'ed25519') { - return false; - } - - /** - * Derive public point Q' = dG from private key - * and expect Q == Q' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - return util.equalsUint8Array(Q, dG); - -} - -var eddsa_legacy = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$2, - verify: verify$2, - validateParams: validateParams$3 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Generate (non-legacy) EdDSA key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} - */ -async function generate$2(algo) { - switch (algo) { - case enums.publicKey.ed25519: { - const seed = getRandomBytes(32); - const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed); - return { A, seed }; - } - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} - -/** - * Sign a message using the provided key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * RS: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - const secretKey = util.concatUint8Array([privateKey, publicKey]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - return { RS: signature }; - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - -} - -/** - * Verifies if a signature is valid for a message - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{ RS: Uint8Array }} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - return naclFastLight.sign.detached.verify(hashed, RS, publicKey); - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} -/** - * Validate (non-legacy) EdDSA parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - EdDSA public point - * @param {Uint8Array} seed - EdDSA secret seed - * @param {Uint8Array} oid - (legacy only) EdDSA OID - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$4(algo, A, seed) { - switch (algo) { - case enums.publicKey.ed25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed); - return util.equalsUint8Array(A, publicKey); - } - - case enums.publicKey.ed448: // unsupported - default: - return false; - } -} - -function getPreferredHashAlgo$1(algo) { - switch (algo) { - case enums.publicKey.ed25519: - return enums.hash.sha256; - default: - throw new Error('Unknown EdDSA algo'); - } -} - -var eddsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$2, - sign: sign$3, - verify: verify$3, - validateParams: validateParams$4, - getPreferredHashAlgo: getPreferredHashAlgo$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * AES key wrap - * @function - * @param {Uint8Array} key - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -function wrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const P = unpack(data); - let A = IV; - const R = P; - const n = P.length / 2; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 0; j <= 5; ++j) { - for (let i = 0; i < n; ++i) { - t[1] = n * j + (1 + i); - // B = A - B[0] = A[0]; - B[1] = A[1]; - // B = A || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES(K, B) - B = unpack(aes.encrypt(pack(B))); - // A = MSB(64, B) ^ t - A = B.subarray(0, 2); - A[0] ^= t[0]; - A[1] ^= t[1]; - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - return pack(A, R); -} - -/** - * AES key unwrap - * @function - * @param {String} key - * @param {String} data - * @returns {Uint8Array} - * @throws {Error} - */ -function unwrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const C = unpack(data); - let A = C.subarray(0, 2); - const R = C.subarray(2); - const n = C.length / 2 - 1; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 5; j >= 0; --j) { - for (let i = n - 1; i >= 0; --i) { - t[1] = n * j + (i + 1); - // B = A ^ t - B[0] = A[0] ^ t[0]; - B[1] = A[1] ^ t[1]; - // B = (A ^ t) || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES-1(B) - B = unpack(aes.decrypt(pack(B))); - // A = MSB(64, B) - A = B.subarray(0, 2); - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - if (A[0] === IV[0] && A[1] === IV[1]) { - return pack(R); - } - throw new Error('Key Data Integrity failed'); -} - -function createArrayBuffer(data) { - if (util.isString(data)) { - const { length } = data; - const buffer = new ArrayBuffer(length); - const view = new Uint8Array(buffer); - for (let j = 0; j < length; ++j) { - view[j] = data.charCodeAt(j); - } - return buffer; - } - return new Uint8Array(data).buffer; -} - -function unpack(data) { - const { length } = data; - const buffer = createArrayBuffer(data); - const view = new DataView(buffer); - const arr = new Uint32Array(length / 4); - for (let i = 0; i < length / 4; ++i) { - arr[i] = view.getUint32(4 * i); - } - return arr; -} - -function pack() { - let length = 0; - for (let k = 0; k < arguments.length; ++k) { - length += 4 * arguments[k].length; - } - const buffer = new ArrayBuffer(length); - const view = new DataView(buffer); - let offset = 0; - for (let i = 0; i < arguments.length; ++i) { - for (let j = 0; j < arguments[i].length; ++j) { - view.setUint32(offset + 4 * j, arguments[i][j]); - } - offset += 4 * arguments[i].length; - } - return new Uint8Array(buffer); -} - -var aesKW = /*#__PURE__*/Object.freeze({ - __proto__: null, - wrap: wrap, - unwrap: unwrap -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * @fileoverview Functions to add and remove PKCS5 padding - * @see PublicKeyEncryptedSessionKeyPacket - * @module crypto/pkcs5 - * @private - */ - -/** - * Add pkcs5 padding to a message - * @param {Uint8Array} message - message to pad - * @returns {Uint8Array} Padded message. - */ -function encode$1(message) { - const c = 8 - (message.length % 8); - const padded = new Uint8Array(message.length + c).fill(c); - padded.set(message); - return padded; -} - -/** - * Remove pkcs5 padding from a message - * @param {Uint8Array} message - message to remove padding from - * @returns {Uint8Array} Message without padding. - */ -function decode$1(message) { - const len = message.length; - if (len > 0) { - const c = message[len - 1]; - if (c >= 1) { - const provided = message.subarray(len - c); - const computed = new Uint8Array(c).fill(c); - if (util.equalsUint8Array(provided, computed)) { - return message.subarray(0, len - c); - } - } - } - throw new Error('Invalid padding'); -} - -var pkcs5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - encode: encode$1, - decode: decode$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$8 = util.getWebCrypto(); -const nodeCrypto$9 = util.getNodeCrypto(); - -/** - * Validate ECDH parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDH public point - * @param {Uint8Array} d - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$5(oid, Q, d) { - return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); -} - -// Build Param for ECDH algorithm (RFC 6637) -function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { - return util.concatUint8Array([ - oid.write(), - new Uint8Array([public_algo]), - kdfParams.write(), - util.stringToUint8Array('Anonymous Sender '), - fingerprint.subarray(0, 20) - ]); -} - -// Key Derivation Function (RFC 6637) -async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { - // Note: X is little endian for Curve25519, big-endian for all others. - // This is not ideal, but the RFC's are unclear - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - let i; - if (stripLeading) { - // Work around old go crypto bug - for (i = 0; i < X.length && X[i] === 0; i++); - X = X.subarray(i); - } - if (stripTrailing) { - // Work around old OpenPGP.js bug - for (i = X.length - 1; i >= 0 && X[i] === 0; i--); - X = X.subarray(0, i + 1); - } - const digest = await hash.digest(hashAlgo, util.concatUint8Array([ - new Uint8Array([0, 0, 0, 1]), - X, - param - ])); - return digest.subarray(0, length); -} - -/** - * Generate ECDHE ephemeral key and secret from public key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPublicEphemeralKey(curve, Q) { - switch (curve.type) { - case 'curve25519': { - const d = getRandomBytes(32); - const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d); - let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey); - publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); - return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPublicEphemeralKey(curve, Q); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePublicEphemeralKey(curve, Q); - } - return ellipticPublicEphemeralKey(curve, Q); -} - -/** - * Encrypt and wrap a session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} data - Unpadded session key data - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} - * @async - */ -async function encrypt$3(oid, kdfParams, data, Q, fingerprint) { - const m = encode$1(data); - - const curve = new CurveWithOID(oid); - const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); - const wrappedKey = wrap(Z, m); - return { publicKey, wrappedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPrivateEphemeralKey(curve, V, Q, d) { - if (d.length !== curve.payloadSize) { - const privateKey = new Uint8Array(curve.payloadSize); - privateKey.set(d, curve.payloadSize - d.length); - d = privateKey; - } - switch (curve.type) { - case 'curve25519': { - const secretKey = d.slice().reverse(); - const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1)); - return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPrivateEphemeralKey(curve, V, Q, d); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePrivateEphemeralKey(curve, V, d); - } - return ellipticPrivateEphemeralKey(curve, V, d); -} - -/** - * Decrypt and unwrap the value derived from session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} C - Encrypted and wrapped value derived from session key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Value derived from session key. - * @async - */ -async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) { - const curve = new CurveWithOID(oid); - const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - let err; - for (let i = 0; i < 3; i++) { - try { - // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); - return decode$1(unwrap(Z, C)); - } catch (e) { - err = e; - } - } - throw err; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d); - let privateKey = webCrypto$8.importKey( - 'jwk', - recipient, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); - let sender = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - [] - ); - [privateKey, sender] = await Promise.all([privateKey, sender]); - let S = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: sender - }, - privateKey, - curve.web.sharedSize - ); - let secret = webCrypto$8.exportKey( - 'jwk', - privateKey - ); - [S, secret] = await Promise.all([S, secret]); - const sharedKey = new Uint8Array(S); - const secretKey = b64ToUint8Array(secret.d); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); - let keyPair = webCrypto$8.generateKey( - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - let recipient = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - false, - [] - ); - [keyPair, recipient] = await Promise.all([keyPair, recipient]); - let s = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: recipient - }, - keyPair.privateKey, - curve.web.sharedSize - ); - let p = webCrypto$8.exportKey( - 'jwk', - keyPair.publicKey - ); - [s, p] = await Promise.all([s, p]); - const sharedKey = new Uint8Array(s); - const publicKey = new Uint8Array(jwkToRawPublic(p)); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPrivateEphemeralKey(curve, V, d) { - const indutnyCurve = await getIndutnyCurve(curve.name); - V = keyFromPublic(indutnyCurve, V); - d = keyFromPrivate(indutnyCurve, d); - const secretKey = new Uint8Array(d.getPrivate()); - const S = d.derive(V.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPublicEphemeralKey(curve, Q) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const v = await curve.genKeyPair(); - Q = keyFromPublic(indutnyCurve, Q); - const V = keyFromPrivate(indutnyCurve, v.privateKey); - const publicKey = v.publicKey; - const S = V.derive(Q.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePrivateEphemeralKey(curve, V, d) { - const recipient = nodeCrypto$9.createECDH(curve.node.node); - recipient.setPrivateKey(d); - const sharedKey = new Uint8Array(recipient.computeSecret(V)); - const secretKey = new Uint8Array(recipient.getPrivateKey()); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePublicEphemeralKey(curve, Q) { - const sender = nodeCrypto$9.createECDH(curve.node.node); - sender.generateKeys(); - const sharedKey = new Uint8Array(sender.computeSecret(Q)); - const publicKey = new Uint8Array(sender.getPublicKey()); - return { publicKey, sharedKey }; -} - -var ecdh = /*#__PURE__*/Object.freeze({ - __proto__: null, - validateParams: validateParams$5, - encrypt: encrypt$3, - decrypt: decrypt$3 -}); - -/** - * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. - * @module crypto/hkdf - * @private - */ - -const webCrypto$9 = util.getWebCrypto(); -const nodeCrypto$a = util.getNodeCrypto(); -const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle; - -async function HKDF(hashAlgo, inputKey, salt, info, outLen) { - const hash = enums.read(enums.webHash, hashAlgo); - if (!hash) throw new Error('Hash algo not supported with HKDF'); - - if (webCrypto$9 || nodeSubtleCrypto) { - const crypto = webCrypto$9 || nodeSubtleCrypto; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); - return new Uint8Array(bits); - } - - if (nodeCrypto$a) { - const hashAlgoName = enums.read(enums.hash, hashAlgo); - // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869 - - const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest(); - // Step 1: Extract - // PRK = HMAC-Hash(salt, IKM) - const pseudoRandomKey = computeHMAC(salt, inputKey); - - const hashLen = pseudoRandomKey.length; - - // Step 2: Expand - // HKDF-Expand(PRK, info, L) -> OKM - const n = Math.ceil(outLen / hashLen); - const outputKeyingMaterial = new Uint8Array(n * hashLen); - - // HMAC input buffer updated at each iteration - const roundInput = new Uint8Array(hashLen + info.length + 1); - // T_i and last byte are updated at each iteration, but `info` remains constant - roundInput.set(info, hashLen); - - for (let i = 0; i < n; i++) { - // T(0) = empty string (zero length) - // T(i) = HMAC-Hash(PRK, T(i-1) | info | i) - roundInput[roundInput.length - 1] = i + 1; - // t = T(i+1) - const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen)); - roundInput.set(t, 0); - - outputKeyingMaterial.set(t, i * hashLen); - } - - return outputKeyingMaterial.subarray(0, outLen); - } - - throw new Error('No HKDF implementation available'); -} - -/** - * @fileoverview Key encryption and decryption for RFC 6637 ECDH - * @module crypto/public_key/elliptic/ecdh - * @private - */ - -const HKDF_INFO = { - x25519: util.encodeUTF8('OpenPGP X25519') -}; - -/** - * Generate ECDH key for Montgomery curves - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} - */ -async function generate$3(algo) { - switch (algo) { - case enums.publicKey.x25519: { - // k stays in little-endian, unlike legacy ECDH over curve25519 - const k = getRandomBytes(32); - const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k); - return { A, k }; - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** -* Validate ECDH parameters -* @param {module:enums.publicKey} algo - Algorithm identifier -* @param {Uint8Array} A - ECDH public point -* @param {Uint8Array} k - ECDH secret scalar -* @returns {Promise} Whether params are valid. -* @async -*/ -async function validateParams$6(algo, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k); - return util.equalsUint8Array(A, publicKey); - } - - default: - return false; - } -} - -/** - * Wrap and encrypt a session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} data - session key data to be encrypted - * @param {Uint8Array} recipientA - Recipient public key (K_B) - * @returns {Promise<{ - * ephemeralPublicKey: Uint8Array, - * wrappedKey: Uint8Array - * }>} ephemeral public key (K_A) and encrypted key - * @async - */ -async function encrypt$4(algo, data, recipientA) { - switch (algo) { - case enums.publicKey.x25519: { - const ephemeralSecretKey = getRandomBytes(32); - const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA); - const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - recipientA, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - const wrappedKey = wrap(encryptionKey, data); - return { ephemeralPublicKey, wrappedKey }; - } - - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** - * Decrypt and unwrap the session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} ephemeralPublicKey - (K_A) - * @param {Uint8Array} wrappedKey, - * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF - * @param {Uint8Array} k - Recipient secret key (b) - * @returns {Promise} decrypted session key data - * @async - */ -async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - A, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - return unwrap(encryptionKey, wrappedKey); - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -var ecdh_x = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$3, - validateParams: validateParams$6, - encrypt: encrypt$4, - decrypt: decrypt$4 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -var elliptic = /*#__PURE__*/Object.freeze({ - __proto__: null, - CurveWithOID: CurveWithOID, - ecdh: ecdh, - ecdhX: ecdh_x, - ecdsa: ecdsa, - eddsaLegacy: eddsa_legacy, - eddsa: eddsa, - generate: generate$1, - getPreferredHashAlgo: getPreferredHashAlgo -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/* - TODO regarding the hash function, read: - https://tools.ietf.org/html/rfc4880#section-13.6 - https://tools.ietf.org/html/rfc4880#section-14 -*/ - -/** - * DSA Sign function - * @param {Integer} hashAlgo - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} x - * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} - * @async - */ -async function sign$4(hashAlgo, hashed, g, p, q, x) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - x = new BigInteger(x); - - let k; - let r; - let s; - let t; - g = g.mod(p); - x = x.mod(q); - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - while (true) { - // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - k = await getRandomBigInteger(one, q); // returns in [1, q-1] - r = g.modExp(k, p).imod(q); // (g**k mod p) mod q - if (r.isZero()) { - continue; - } - const xr = x.mul(r).imod(q); - t = h.add(xr).imod(q); // H(m) + x*r mod q - s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q - if (s.isZero()) { - continue; - } - break; - } - return { - r: r.toUint8Array('be', q.byteLength()), - s: s.toUint8Array('be', q.byteLength()) - }; -} - -/** - * DSA Verify function - * @param {Integer} hashAlgo - * @param {Uint8Array} r - * @param {Uint8Array} s - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} y - * @returns {boolean} - * @async - */ -async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) { - const BigInteger = await util.getBigInteger(); - const zero = new BigInteger(0); - r = new BigInteger(r); - s = new BigInteger(s); - - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - - if (r.lte(zero) || r.gte(q) || - s.lte(zero) || s.gte(q)) { - util.printDebug('invalid DSA Signature'); - return false; - } - const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q); - const w = s.modInv(q); // s**-1 mod q - if (w.isZero()) { - util.printDebug('invalid DSA Signature'); - return false; - } - - g = g.mod(p); - y = y.mod(p); - const u1 = h.mul(w).imod(q); // H(m) * w mod q - const u2 = r.mul(w).imod(q); // r * w mod q - const t1 = g.modExp(u1, p); // g**u1 mod p - const t2 = y.modExp(u2, p); // y**u2 mod p - const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q - return v.equal(r); -} - -/** - * Validate DSA parameters - * @param {Uint8Array} p - DSA prime - * @param {Uint8Array} q - DSA group order - * @param {Uint8Array} g - DSA sub-group generator - * @param {Uint8Array} y - DSA public key - * @param {Uint8Array} x - DSA private key - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$7(p, q, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - /** - * Check that subgroup order q divides p-1 - */ - if (!p.dec().mod(q).isZero()) { - return false; - } - - /** - * g has order q - * Check that g ** q = 1 mod p - */ - if (!g.modExp(q, p).isOne()) { - return false; - } - - /** - * Check q is large and probably prime (we mainly want to avoid small factors) - */ - const qSize = new BigInteger(q.bitLength()); - const n150 = new BigInteger(150); - if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) { - return false; - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{rq + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q - const rqx = q.mul(r).add(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var dsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$4, - verify: verify$4, - validateParams: validateParams$7 -}); - -/** - * @fileoverview Asymmetric cryptography functions - * @module crypto/public_key - * @private - */ - -var publicKey = { - /** @see module:crypto/public_key/rsa */ - rsa: rsa, - /** @see module:crypto/public_key/elgamal */ - elgamal: elgamal, - /** @see module:crypto/public_key/elliptic */ - elliptic: elliptic, - /** @see module:crypto/public_key/dsa */ - dsa: dsa, - /** @see tweetnacl */ - nacl: naclFastLight -}; - -/** - * @fileoverview Provides functions for asymmetric signing and signature verification - * @module crypto/signature - * @private - */ - -/** - * Parse signature in binary form to get the parameters. - * The returned values are only padded for EdDSA, since in the other cases their expected length - * depends on the key params, hence we delegate the padding to the signature verification function. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Uint8Array} signature - Data for which the signature was created - * @returns {Promise} True if signature is valid. - * @async - */ -function parseSignatureParams(algo, signature) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA signatures: - // - MPI of RSA signature value m**d mod n. - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const s = util.readMPI(signature.subarray(read)); - // The signature needs to be the same length as the public key modulo n. - // We pad s on signature verification, where we have access to n. - return { s }; - } - // Algorithm-Specific Fields for DSA or ECDSA signatures: - // - MPI of DSA or ECDSA value r. - // - MPI of DSA or ECDSA value s. - case enums.publicKey.dsa: - case enums.publicKey.ecdsa: - { - const r = util.readMPI(signature.subarray(read)); read += r.length + 2; - const s = util.readMPI(signature.subarray(read)); - return { r, s }; - } - // Algorithm-Specific Fields for legacy EdDSA signatures: - // - MPI of an EC point r. - // - EdDSA value s, in MPI, in the little endian representation - case enums.publicKey.eddsaLegacy: { - // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values: - // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 - let r = util.readMPI(signature.subarray(read)); read += r.length + 2; - r = util.leftPad(r, 32); - let s = util.readMPI(signature.subarray(read)); - s = util.leftPad(s, 32); - return { r, s }; - } - // Algorithm-Specific Fields for Ed25519 signatures: - // - 64 octets of the native signature - case enums.publicKey.ed25519: { - const RS = signature.subarray(read, read + 64); read += RS.length; - return { RS }; - } - default: - throw new UnsupportedError('Unknown signature algorithm.'); - } -} - -/** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} signature - Named algorithm-specific signature parameters - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Data for which the signature was created - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} True if signature is valid. - * @async - */ -async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto - return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); - } - case enums.publicKey.dsa: { - const { g, p, q, y } = publicParams; - const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers - return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicParams; - const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; - // padding needed for webcrypto - const r = util.leftPad(signature.r, curveSize); - const s = util.leftPad(signature.s, curveSize); - return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicParams; - // signature already padded on parsing - return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -/** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters - * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters - * @param {Uint8Array} data - Data to be signed - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} Signature Object containing named signature parameters. - * @async - */ -async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { - if (!publicKeyParams || !privateKeyParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); - return { s }; - } - case enums.publicKey.dsa: { - const { g, p, q } = publicKeyParams; - const { x } = privateKeyParams; - return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); - } - case enums.publicKey.elgamal: { - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicKeyParams; - const { d } = privateKeyParams; - return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -var signature = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseSignatureParams: parseSignatureParams, - verify: verify$5, - sign: sign$5 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class ECDHSymmetricKey { - constructor(data) { - if (data) { - this.data = data; - } - } - - /** - * Read an ECDHSymmetricKey from an Uint8Array: - * - 1 octect for the length `l` - * - `l` octects of encoded session key data - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - if (bytes.length >= 1) { - const length = bytes[0]; - if (bytes.length >= 1 + length) { - this.data = bytes.subarray(1, 1 + length); - return 1 + this.data.length; - } - } - throw new Error('Invalid symmetric key'); - } - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Implementation of type KDF parameters - * - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - * @module type/kdf_params - * @private - */ - -class KDFParams { - /** - * @param {enums.hash} hash - Hash algorithm - * @param {enums.symmetric} cipher - Symmetric algorithm - */ - constructor(data) { - if (data) { - const { hash, cipher } = data; - this.hash = hash; - this.cipher = cipher; - } else { - this.hash = null; - this.cipher = null; - } - } - - /** - * Read KDFParams from an Uint8Array - * @param {Uint8Array} input - Where to read the KDFParams from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { - throw new UnsupportedError('Cannot read KDFParams'); - } - this.hash = input[2]; - this.cipher = input[3]; - return 4; - } - - /** - * Write KDFParams to an Uint8Array - * @returns {Uint8Array} Array with the KDFParams value - */ - write() { - return new Uint8Array([3, 1, this.hash, this.cipher]); - } -} - -/** - * Encoded symmetric key for x25519 and x448 - * The payload format varies for v3 and v6 PKESK: - * the former includes an algorithm byte preceeding the encrypted session key. - * - * @module type/x25519x448_symkey - */ - -class ECDHXSymmetricKey { - static fromObject({ wrappedKey, algorithm }) { - const instance = new ECDHXSymmetricKey(); - instance.wrappedKey = wrappedKey; - instance.algorithm = algorithm; - return instance; - } - - /** - * - 1 octect for the length `l` - * - `l` octects of encoded session key data (with optional leading algorithm byte) - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - let read = 0; - let followLength = bytes[read++]; - this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even - followLength -= followLength % 2; - this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength; - } - - /** - * Write an MontgomerySymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([ - this.algorithm ? - new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : - new Uint8Array([this.wrappedKey.length]), - this.wrappedKey - ]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param {module:enums.publicKey} keyAlgo - Public key algorithm - * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Session key data to be encrypted - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Encrypted session key parameters. - * @async - */ -async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const { n, e } = publicParams; - const c = await publicKey.rsa.encrypt(data, n, e); - return { c }; - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - return publicKey.elgamal.encrypt(data, p, g, y); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicParams; - const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( - oid, kdfParams, data, Q, fingerprint); - return { V, C: new ECDHSymmetricKey(C) }; - } - case enums.publicKey.x25519: { - if (!util.isAES(symmetricAlgo)) { - // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 - throw new Error('X25519 keys can only encrypt AES session keys'); - } - const { A } = publicParams; - const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( - keyAlgo, data, A); - const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); - return { ephemeralPublicKey, C }; - } - default: - return []; - } -} - -/** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Object} publicKeyParams - Algorithm-specific public key parameters - * @param {Object} privateKeyParams - Algorithm-specific private key parameters - * @param {Object} sessionKeyParams - Encrypted session key parameters - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing - * (needed for constant-time processing in RSA and ElGamal) - * @returns {Promise} Decrypted data. - * @throws {Error} on sensitive decryption error, unless `randomPayload` is given - * @async - */ -async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: { - const { c } = sessionKeyParams; - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); - } - case enums.publicKey.elgamal: { - const { c1, c2 } = sessionKeyParams; - const p = publicKeyParams.p; - const x = privateKeyParams.x; - return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicKeyParams; - const { d } = privateKeyParams; - const { V, C } = sessionKeyParams; - return publicKey.elliptic.ecdh.decrypt( - oid, kdfParams, V, C.data, Q, d, fingerprint); - } - case enums.publicKey.x25519: { - const { A } = publicKeyParams; - const { k } = privateKeyParams; - const { ephemeralPublicKey, C } = sessionKeyParams; - if (!util.isAES(C.algorithm)) { - throw new Error('AES session key expected'); - } - return publicKey.elliptic.ecdhX.decrypt( - algo, ephemeralPublicKey, C.wrappedKey, A, k); - } - default: - throw new Error('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse public key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. - */ -function parsePublicKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; - const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; - return { read, publicParams: { n, e } }; - } - case enums.publicKey.dsa: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, q, g, y } }; - } - case enums.publicKey.elgamal: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, g, y } }; - } - case enums.publicKey.ecdsa: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.eddsaLegacy: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - Q = util.leftPad(Q, 33); - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.ecdh: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); - return { read: read, publicParams: { oid, Q, kdfParams } }; - } - case enums.publicKey.ed25519: - case enums.publicKey.x25519: { - const A = bytes.subarray(read, read + 32); read += A.length; - return { read, publicParams: { A } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse private key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @param {Object} publicParams - (ECC only) public params, needed to format some private params - * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. - */ -function parsePrivateKeyParams(algo, bytes, publicParams) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; - return { read, privateParams: { d, p, q, u } }; - } - case enums.publicKey.dsa: - case enums.publicKey.elgamal: { - const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; - return { read, privateParams: { x } }; - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const curve = new CurveWithOID(publicParams.oid); - let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - d = util.leftPad(d, curve.payloadSize); - return { read, privateParams: { d } }; - } - case enums.publicKey.eddsaLegacy: { - const curve = new CurveWithOID(publicParams.oid); - let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; - seed = util.leftPad(seed, curve.payloadSize); - return { read, privateParams: { seed } }; - } - case enums.publicKey.ed25519: { - const seed = bytes.subarray(read, read + 32); read += seed.length; - return { read, privateParams: { seed } }; - } - case enums.publicKey.x25519: { - const k = bytes.subarray(read, read + 32); read += k.length; - return { read, privateParams: { k } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** Returns the types comprising the encrypted session key of an algorithm - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {Object} The session key parameters referenced by name. - */ -function parseEncSessionKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA encrypted session keys: - // - MPI of RSA encrypted value m**e mod n. - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const c = util.readMPI(bytes.subarray(read)); - return { c }; - } - - // Algorithm-Specific Fields for Elgamal encrypted session keys: - // - MPI of Elgamal value g**k mod p - // - MPI of Elgamal value m * y**k mod p - case enums.publicKey.elgamal: { - const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; - const c2 = util.readMPI(bytes.subarray(read)); - return { c1, c2 }; - } - // Algorithm-Specific Fields for ECDH encrypted session keys: - // - MPI containing the ephemeral key used to establish the shared secret - // - ECDH Symmetric Key - case enums.publicKey.ecdh: { - const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; - const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); - return { V, C }; - } - // Algorithm-Specific Fields for X25519 encrypted session keys: - // - 32 octets representing an ephemeral X25519 public key. - // - A one-octet size of the following fields. - // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). - // - The encrypted session key. - case enums.publicKey.x25519: { - const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length; - const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); - return { ephemeralPublicKey, C }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Convert params to MPI and serializes them in the proper order - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} params - The key parameters indexed by name - * @returns {Uint8Array} The array containing the MPIs. - */ -function serializeParams(algo, params) { - // Some algorithms do not rely on MPIs to store the binary params - const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]); - const orderedParams = Object.keys(params).map(name => { - const param = params[name]; - if (!util.isUint8Array(param)) return param.write(); - return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); - }); - return util.concatUint8Array(orderedParams); -} - -/** - * Generate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Integer} bits - Bit length for RSA keys - * @param {module:type/oid} oid - Object identifier for ECC keys - * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. - * @async - */ -function generateParams(algo, bits, oid) { - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ - privateParams: { d, p, q, u }, - publicParams: { n, e } - })); - } - case enums.publicKey.ecdsa: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { d: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { seed: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.ecdh: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ - privateParams: { d: secret }, - publicParams: { - oid: new OID(oid), - Q, - kdfParams: new KDFParams({ hash, cipher }) - } - })); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ - privateParams: { seed }, - publicParams: { A } - })); - case enums.publicKey.x25519: - return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ - privateParams: { k }, - publicParams: { A } - })); - case enums.publicKey.dsa: - case enums.publicKey.elgamal: - throw new Error('Unsupported algorithm for key generation.'); - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Validate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Object} privateParams - Algorithm-specific private key parameters - * @returns {Promise} Whether the parameters are valid. - * @async - */ -async function validateParams$8(algo, publicParams, privateParams) { - if (!publicParams || !privateParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const { d, p, q, u } = privateParams; - return publicKey.rsa.validateParams(n, e, d, p, q, u); - } - case enums.publicKey.dsa: { - const { p, q, g, y } = publicParams; - const { x } = privateParams; - return publicKey.dsa.validateParams(p, q, g, y, x); - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - const { x } = privateParams; - return publicKey.elgamal.validateParams(p, g, y, x); - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; - const { oid, Q } = publicParams; - const { d } = privateParams; - return algoModule.validateParams(oid, Q, d); - } - case enums.publicKey.eddsaLegacy: { - const { Q, oid } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsa.validateParams(algo, A, seed); - } - case enums.publicKey.x25519: { - const { A } = publicParams; - const { k } = privateParams; - return publicKey.elliptic.ecdhX.validateParams(algo, A, k); - } - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - * @async - */ -async function getPrefixRandom(algo) { - const { blockSize } = getCipher(algo); - const prefixrandom = await getRandomBytes(blockSize); - const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - return util.concat([prefixrandom, repeat]); -} - -/** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Uint8Array} Random bytes as a string to be used as a key. - */ -function generateSessionKey(algo) { - const { keySize } = getCipher(algo); - return getRandomBytes(keySize); -} - -/** - * Get implementation of the given AEAD mode - * @param {enums.aead} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getAEADMode(algo) { - const algoName = enums.read(enums.aead, algo); - return mode[algoName]; -} - -/** - * Check whether the given curve OID is supported - * @param {module:type/oid} oid - EC object identifier - * @throws {UnsupportedError} if curve is not supported - */ -function checkSupportedCurve(oid) { - try { - oid.getName(); - } catch (e) { - throw new UnsupportedError('Unknown curve OID'); - } -} - -/** - * Get preferred hash algo for a given elliptic algo - * @param {module:enums.publicKey} algo - alrogithm identifier - * @param {module:type/oid} [oid] - curve OID if needed by algo - */ -function getPreferredCurveHashAlgo(algo, oid) { - switch (algo) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.getPreferredHashAlgo(oid); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); - default: - throw new Error('Unknown elliptic signing algo'); - } -} - -var crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - publicKeyEncrypt: publicKeyEncrypt, - publicKeyDecrypt: publicKeyDecrypt, - parsePublicKeyParams: parsePublicKeyParams, - parsePrivateKeyParams: parsePrivateKeyParams, - parseEncSessionKeyParams: parseEncSessionKeyParams, - serializeParams: serializeParams, - generateParams: generateParams, - validateParams: validateParams$8, - getPrefixRandom: getPrefixRandom, - generateSessionKey: generateSessionKey, - getAEADMode: getAEADMode, - getCipher: getCipher, - getPreferredCurveHashAlgo: getPreferredCurveHashAlgo -}); - -/** - * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash - * @module crypto - * @private - */ - -// TODO move cfb and gcm to cipher -const mod = { - /** @see module:crypto/cipher */ - cipher: cipher, - /** @see module:crypto/hash */ - hash: hash, - /** @see module:crypto/mode */ - mode: mode, - /** @see module:crypto/public_key */ - publicKey: publicKey, - /** @see module:crypto/signature */ - signature: signature, - /** @see module:crypto/random */ - random: random, - /** @see module:crypto/pkcs1 */ - pkcs1: pkcs1, - /** @see module:crypto/pkcs5 */ - pkcs5: pkcs5, - /** @see module:crypto/aes_kw */ - aesKW: aesKW -}; - -Object.assign(mod, crypto$1); - -var TYPED_OK = typeof Uint8Array !== "undefined" && - typeof Uint16Array !== "undefined" && - typeof Int32Array !== "undefined"; - - -// reduce buffer size, avoiding mem copy -function shrinkBuf(buf, size) { - if (buf.length === size) { - return buf; - } - if (buf.subarray) { - return buf.subarray(0, size); - } - buf.length = size; - return buf; -} - - -const fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - let i, l, len, pos, chunk; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - const result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -const fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// - -let Buf8 = TYPED_OK ? Uint8Array : Array; -let Buf16 = TYPED_OK ? Uint16Array : Array; -let Buf32 = TYPED_OK ? Int32Array : Array; -let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks; -let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -/* Allowed flush values; see deflate() and inflate() below for details */ -const Z_NO_FLUSH = 0; -const Z_PARTIAL_FLUSH = 1; -const Z_SYNC_FLUSH = 2; -const Z_FULL_FLUSH = 3; -const Z_FINISH = 4; -const Z_BLOCK = 5; -const Z_TREES = 6; - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -const Z_OK = 0; -const Z_STREAM_END = 1; -const Z_NEED_DICT = 2; -const Z_STREAM_ERROR = -2; -const Z_DATA_ERROR = -3; -//export const Z_MEM_ERROR = -4; -const Z_BUF_ERROR = -5; -const Z_DEFAULT_COMPRESSION = -1; - - -const Z_FILTERED = 1; -const Z_HUFFMAN_ONLY = 2; -const Z_RLE = 3; -const Z_FIXED = 4; -const Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -const Z_BINARY = 0; -const Z_TEXT = 1; -//export const Z_ASCII = 1; // = Z_TEXT (deprecated) -const Z_UNKNOWN = 2; - -/* The deflate compression method */ -const Z_DEFLATED = 8; -//export const Z_NULL = null // Use -1 or null inline, depending on var type - -/*============================================================================*/ - - -function zero$1(buf) { - let len = buf.length; while (--len >= 0) { - buf[len] = 0; - } -} - -// From zutil.h - -const STORED_BLOCK = 0; -const STATIC_TREES = 1; -const DYN_TREES = 2; -/* The three kinds of block type */ - -const MIN_MATCH = 3; -const MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -const LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -const LITERALS = 256; -/* number of literal bytes 0..255 */ - -const L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -const D_CODES = 30; -/* number of distance codes */ - -const BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -const HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -const MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -const Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -const MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -const END_BLOCK = 256; -/* end of block literal code */ - -const REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -const REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -const REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -const extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -const extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -const extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -const bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -const static_ltree = new Array((L_CODES + 2) * 2); -zero$1(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -const static_dtree = new Array(D_CODES * 2); -zero$1(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -const _dist_code = new Array(DIST_CODE_LEN); -zero$1(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero$1(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -const base_length = new Array(LENGTH_CODES); -zero$1(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -const base_dist = new Array(D_CODES); -zero$1(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -let static_l_desc; -let static_d_desc; -let static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = w & 0xff; - s.pending_buf[s.pending++] = w >>> 8 & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > Buf_size - length) { - s.bi_buf |= value << s.bi_valid & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> Buf_size - s.bi_valid; - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= value << s.bi_valid & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { - continue; - } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { - return; - } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { - bits--; - } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { - continue; - } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = code + bl_count[bits - 1] << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < 1 << extra_lbits[code]; n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < 1 << extra_dbits[code]; n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - let n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { - s.dyn_ltree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < D_CODES; n++) { - s.dyn_dtree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < BL_CODES; n++) { - s.bl_tree[n * 2]/*.Freq*/ = 0; - } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } - // while (len--) { - // put_byte(s, *buf++); - // } - arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - const _n2 = n * 2; - const _m2 = m * 2; - return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]; -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { - break; - } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) { - pqdownheap(s, tree, n); - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { - s.bl_tree[curlen * 2]/*.Freq*/++; - } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { - send_code(s, curlen, s.bl_tree); - } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - let max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - let rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - let black_mask = 0xf3ffc07f; - let n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -let static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) { - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = s.opt_len + 3 + 7 >>> 3; - static_lenb = s.static_len + 3 + 7 >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { - opt_lenb = static_lenb; - } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if (stored_len + 4 <= opt_lenb && buf !== -1) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif - - return s.last_lit === s.lit_bufsize - 1; - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function adler32(adler, buf, len, pos) { - let s1 = adler & 0xffff |0, - s2 = adler >>> 16 & 0xffff |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = s1 + buf[pos++] |0; - s2 = s2 + s1 |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return s1 | s2 << 16 |0; -} - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - let c; - const table = []; - - for (let n = 0; n < 256; n++) { - c = n; - for (let k = 0; k < 8; k++) { - c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -const crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - const t = crcTable, - end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return crc ^ -1; // >>> 0; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var msg = { - 2: "need dictionary", /* Z_NEED_DICT 2 */ - 1: "stream end", /* Z_STREAM_END 1 */ - 0: "", /* Z_OK 0 */ - "-1": "file error", /* Z_ERRNO (-1) */ - "-2": "stream error", /* Z_STREAM_ERROR (-2) */ - "-3": "data error", /* Z_DATA_ERROR (-3) */ - "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */ - "-5": "buffer error", /* Z_BUF_ERROR (-5) */ - "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */ -}; - -/*============================================================================*/ - - -const MAX_MEM_LEVEL = 9; - - -const LENGTH_CODES$1 = 29; -/* number of length codes, not counting the special END_BLOCK code */ -const LITERALS$1 = 256; -/* number of literal bytes 0..255 */ -const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; -/* number of Literal or Length codes, including the END_BLOCK code */ -const D_CODES$1 = 30; -/* number of distance codes */ -const BL_CODES$1 = 19; -/* number of codes used to transfer the bit lengths */ -const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; -/* maximum heap size */ -const MAX_BITS$1 = 15; -/* All codes must not exceed MAX_BITS bits */ - -const MIN_MATCH$1 = 3; -const MAX_MATCH$1 = 258; -const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); - -const PRESET_DICT = 0x20; - -const INIT_STATE = 42; -const EXTRA_STATE = 69; -const NAME_STATE = 73; -const COMMENT_STATE = 91; -const HCRC_STATE = 103; -const BUSY_STATE = 113; -const FINISH_STATE = 666; - -const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -const BS_BLOCK_DONE = 2; /* block flush performed */ -const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - const s = strm.state; - - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - let len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - const _win = s.window; // shortcut - - const wmask = s.w_mask; - const prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - const strend = s.strstart + MAX_MATCH$1; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH$1 - (strend - scan); - scan = strend - MAX_MATCH$1; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - const _w_size = s.w_size; - let p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH$1) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH$1) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // var curr = s.strstart + s.lookahead; - // var init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (; ;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH$1) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - - let max_insert; - - /* Process the input block. */ - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH$1 - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH$1 - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH$1; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH$1 - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - - const _win = s.window; - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH$1) { - fill_window(s); - if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH$1; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH$1 - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH$1) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -class Config { - constructor(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } -} -const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - s.ins_h = 0; -} - -class DeflateState { - constructor() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); - this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); - this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); - zero$2(this.dyn_ltree); - zero$2(this.dyn_dtree); - zero$2(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Buf16(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ - zero$2(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; - zero$2(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ - } -} - -function deflateResetKeep(strm) { - let s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - _tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - const ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - let wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); - s.window = new Buf8(s.w_size * 2); - s.head = new Buf16(s.hash_size); - s.prev = new Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - - -function deflate(strm, flush) { - let old_flush, s; - let beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } - //#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero$2(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - let status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - let dictLength = dictionary.length; - - let s; - let str, n; - let wrap; - let avail; - let next; - let input; - let tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new Buf8(s.w_size); - arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH$1) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH$1 - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH$1 - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - -// String encode/decode helpers - -try { - String.fromCharCode.apply(null, [ 0 ]); -} catch (__) { -} -try { - String.fromCharCode.apply(null, new Uint8Array(1)); -} catch (__) { -} - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -const _utf8len = new Buf8(256); -for (let q = 0; q < 256; q++) { - _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - -// convert string to array (typed, when possible) -function string2buf (str) { - let c, c2, m_pos, i, buf_len = 0; - const str_len = str.length; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - const buf = new Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | c >>> 6; - buf[i++] = 0x80 | c & 0x3f; - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | c >>> 12; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } else { - /* four bytes */ - buf[i++] = 0xf0 | c >>> 18; - buf[i++] = 0x80 | c >>> 12 & 0x3f; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } - } - - return buf; -} - - -// Convert binary string (typed, when possible) -function binstring2buf (str) { - const buf = new Buf8(str.length); - for (let i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class ZStream { - constructor() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } -} - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ - -class Deflate { - constructor(options) { - this.options = { - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - ...(options || {}) - }; - - const opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - let dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } - } - - /** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize } } = this; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = string2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -const BAD = 30; /* got a data error -- remain here until reset */ -const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let _out; /* local strm.output */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; - - - - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - const input = strm.input; - const last = _in + (strm.avail_in - 5); - _out = strm.next_out; - const output = strm.output; - const beg = _out - (start - strm.avail_out); - const end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - const dmax = state.dmax; - //#endif - const wsize = state.wsize; - const whave = state.whave; - const wnext = state.wnext; - const s_window = state.window; - hold = state.hold; - bits = state.bits; - const lcode = state.lencode; - const dcode = state.distcode; - const lmask = (1 << state.lenbits) - 1; - const dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & (1 << op) - 1; - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & (1 << op) - 1; - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dodist; - } else { - strm.msg = "invalid distance code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dolen; - } else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } else { - strm.msg = "invalid literal/length code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); - strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); - state.hold = hold; - state.bits = bits; - return; -} - -const MAXBITS = 15; -const ENOUGH_LENS = 852; -const ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -const CODES = 0; -const LENS = 1; -const DISTS = 2; - -const lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -const lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -const dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -const dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // var shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { - break; - } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { - break; - } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - const mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << len - drop; - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << len - 1; - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { - break; - } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { - break; - } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = root << 24 | curr << 16 | next - table_index |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = len - drop << 24 | 64 << 16 |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -} - -const CODES$1 = 0; -const LENS$1 = 1; -const DISTS$1 = 2; - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -const HEAD = 1; /* i: waiting for magic header */ -const FLAGS = 2; /* i: waiting for method and flags (gzip) */ -const TIME = 3; /* i: waiting for modification time (gzip) */ -const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -const EXLEN = 5; /* i: waiting for extra length (gzip) */ -const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -const NAME = 7; /* i: waiting for end of file name (gzip) */ -const COMMENT = 8; /* i: waiting for end of comment (gzip) */ -const HCRC = 9; /* i: waiting for header crc (gzip) */ -const DICTID = 10; /* i: waiting for dictionary check value */ -const DICT = 11; /* waiting for inflateSetDictionary() call */ -const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ -const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -const STORED = 14; /* i: waiting for stored size (length and complement) */ -const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -const COPY = 16; /* i/o: waiting for input or output to copy stored block */ -const TABLE = 17; /* i: waiting for dynamic block table lengths */ -const LENLENS = 18; /* i: waiting for code length code lengths */ -const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -const LEN_ = 20; /* i: same as LEN below, but only first time in */ -const LEN = 21; /* i: waiting for length/lit/eob code */ -const LENEXT = 22; /* i: waiting for length extra bits */ -const DIST = 23; /* i: waiting for distance code */ -const DISTEXT = 24; /* i: waiting for distance extra bits */ -const MATCH = 25; /* o: waiting for output space to copy string */ -const LIT = 26; /* o: waiting for output space to write literal */ -const CHECK = 27; /* i: waiting for 32-bit check value */ -const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -const DONE = 29; /* finished check, done -- remain here until reset */ -const BAD$1 = 30; /* got a data error -- remain here until reset */ -//const MEM = 31; /* got an inflate() memory error -- remain here until reset */ -const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -const ENOUGH_LENS$1 = 852; -const ENOUGH_DISTS$1 = 592; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -class InflateState { - constructor() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Buf16(320); /* temporary storage for code lengths */ - this.work = new Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ - } -} - -function inflateResetKeep(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); - state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - let wrap; - let state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - let ret; - let state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -let virgin = true; - -let lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - let sym; - - lenfix = new Buf32(512); - distfix = new Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - let dist; - const state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ - let opts; - - let n; // temporary var for NEED_BITS - - const order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD$1; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD$1; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE$1; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD$1; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE$1; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE$1; - /* falls through */ - case TYPE$1: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD$1; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD$1; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE$1; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD$1; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD$1) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD$1; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD$1; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE$1) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE$1; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD$1: - ret = Z_DATA_ERROR; - break inf_leave; - // case MEM: - // return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE$1 ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - const state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - let state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - const dictLength = dictionary.length; - - let state; - let dictid; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - updatewindow(strm, dictionary, dictLength, dictLength); - // if (ret) { - // state.mode = MEM; - // return Z_MEM_ERROR; - // } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class GZheader { - constructor() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; - } -} - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -class Inflate { - constructor(options) { - this.options = { - chunkSize: 16384, - windowBits: 0, - ...(options || {}) - }; - - const opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - let status = inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - inflateGetHeader(this.strm, this.header); - - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - opt.dictionary = new Uint8Array(opt.dictionary); - } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(msg[status]); - } - } - } - } - /** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize, dictionary } } = this; - let status, _mode; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - let allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = binstring2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = inflate(strm, Z_NO_FLUSH); /* no bad return value */ - - if (status === Z_NEED_DICT && dictionary) { - status = inflateSetDictionary(this.strm, dictionary); - } - - if (status === Z_BUF_ERROR && allowBufError === true) { - status = Z_OK; - allowBufError = false; - } - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - if (status === Z_STREAM_END) { - _mode = Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - - /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - - - /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -/* -node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - -Copyright (C) 2012 Eli Skeggs - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - -var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; - -// offset in bytes -var BitReader = function(stream) { - this.stream = stream; - this.bitOffset = 0; - this.curByte = 0; - this.hasByte = false; -}; - -BitReader.prototype._ensureByte = function() { - if (!this.hasByte) { - this.curByte = this.stream.readByte(); - this.hasByte = true; - } -}; - -// reads bits from the buffer -BitReader.prototype.read = function(bits) { - var result = 0; - while (bits > 0) { - this._ensureByte(); - var remaining = 8 - this.bitOffset; - // if we're in a byte - if (bits >= remaining) { - result <<= remaining; - result |= BITMASK[remaining] & this.curByte; - this.hasByte = false; - this.bitOffset = 0; - bits -= remaining; - } else { - result <<= bits; - var shift = remaining - bits; - result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; - this.bitOffset += bits; - bits = 0; - } - } - return result; -}; - -// seek to an arbitrary point in the buffer (expressed in bits) -BitReader.prototype.seek = function(pos) { - var n_bit = pos % 8; - var n_byte = (pos - n_bit) / 8; - this.bitOffset = n_bit; - this.stream.seek(n_byte); - this.hasByte = false; -}; - -// reads 6 bytes worth of data using the read method -BitReader.prototype.pi = function() { - var buf = new Uint8Array(6), i; - for (i = 0; i < buf.length; i++) { - buf[i] = this.read(8); - } - return bufToHex(buf); -}; - -function bufToHex(buf) { - return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); -} - -var bitreader = BitReader; - -/* very simple input/output stream interface */ -var Stream = function() { -}; - -// input streams ////////////// -/** Returns the next byte, or -1 for EOF. */ -Stream.prototype.readByte = function() { - throw new Error("abstract method readByte() not implemented"); -}; -/** Attempts to fill the buffer; returns number of bytes read, or - * -1 for EOF. */ -Stream.prototype.read = function(buffer, bufOffset, length) { - var bytesRead = 0; - while (bytesRead < length) { - var c = this.readByte(); - if (c < 0) { // EOF - return (bytesRead===0) ? -1 : bytesRead; - } - buffer[bufOffset++] = c; - bytesRead++; - } - return bytesRead; -}; -Stream.prototype.seek = function(new_pos) { - throw new Error("abstract method seek() not implemented"); -}; - -// output streams /////////// -Stream.prototype.writeByte = function(_byte) { - throw new Error("abstract method readByte() not implemented"); -}; -Stream.prototype.write = function(buffer, bufOffset, length) { - var i; - for (i=0; i>> 0; // return an unsigned value - }; - - /** - * Update the CRC with a single byte - * @param value The value to update the CRC with - */ - this.updateCRC = function(value) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - }; - - /** - * Update the CRC with a sequence of identical bytes - * @param value The value to update the CRC with - * @param count The number of bytes - */ - this.updateCRCRun = function(value, count) { - while (count-- > 0) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - } - }; - }; - return CRC32; -})(); - -/* -seek-bzip - a pure-javascript module for seeking within bzip2 data - -Copyright (C) 2013 C. Scott Ananian -Copyright (C) 2012 Eli Skeggs -Copyright (C) 2011 Kevin Kwok - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from node-bzip, copyright 2012 Eli Skeggs. -Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - - - - - -var MAX_HUFCODE_BITS = 20; -var MAX_SYMBOLS = 258; -var SYMBOL_RUNA = 0; -var SYMBOL_RUNB = 1; -var MIN_GROUPS = 2; -var MAX_GROUPS = 6; -var GROUP_SIZE = 50; - -var WHOLEPI = "314159265359"; -var SQRTPI = "177245385090"; - -var mtf = function(array, index) { - var src = array[index], i; - for (i = index; i > 0; i--) { - array[i] = array[i-1]; - } - array[0] = src; - return src; -}; - -var Err = { - OK: 0, - LAST_BLOCK: -1, - NOT_BZIP_DATA: -2, - UNEXPECTED_INPUT_EOF: -3, - UNEXPECTED_OUTPUT_EOF: -4, - DATA_ERROR: -5, - OUT_OF_MEMORY: -6, - OBSOLETE_INPUT: -7, - END_OF_BLOCK: -8 -}; -var ErrorMessages = {}; -ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; -ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; -ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; -ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; -ErrorMessages[Err.DATA_ERROR] = "Data error"; -ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; -ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - -var _throw = function(status, optDetail) { - var msg = ErrorMessages[status] || 'unknown error'; - if (optDetail) { msg += ': '+optDetail; } - var e = new TypeError(msg); - e.errorCode = status; - throw e; -}; - -var Bunzip = function(inputStream, outputStream) { - this.writePos = this.writeCurrent = this.writeCount = 0; - - this._start_bunzip(inputStream, outputStream); -}; -Bunzip.prototype._init_block = function() { - var moreBlocks = this._get_next_block(); - if ( !moreBlocks ) { - this.writeCount = -1; - return false; /* no more blocks */ - } - this.blockCRC = new crc32$1(); - return true; -}; -/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ -Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { - /* Ensure that file starts with "BZh['1'-'9']." */ - var buf = new Uint8Array(4); - if (inputStream.read(buf, 0, 4) !== 4 || - String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') - _throw(Err.NOT_BZIP_DATA, 'bad magic'); - - var level = buf[3] - 0x30; - if (level < 1 || level > 9) - _throw(Err.NOT_BZIP_DATA, 'level out of range'); - - this.reader = new bitreader(inputStream); - - /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of - uncompressed data. Allocate intermediate buffer for block. */ - this.dbufSize = 100000 * level; - this.nextoutput = 0; - this.outputStream = outputStream; - this.streamCRC = 0; -}; -Bunzip.prototype._get_next_block = function() { - var i, j, k; - var reader = this.reader; - // this is get_next_block() function from micro-bunzip: - /* Read in header signature and CRC, then validate signature. - (last block signature means CRC is for whole file, return now) */ - var h = reader.pi(); - if (h === SQRTPI) { // last block - return false; /* no more blocks */ - } - if (h !== WHOLEPI) - _throw(Err.NOT_BZIP_DATA); - this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) - this.streamCRC = (this.targetBlockCRC ^ - ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; - /* We can add support for blockRandomised if anybody complains. There was - some code for this in busybox 1.0.0-pre3, but nobody ever noticed that - it didn't actually work. */ - if (reader.read(1)) - _throw(Err.OBSOLETE_INPUT); - var origPointer = reader.read(24); - if (origPointer > this.dbufSize) - _throw(Err.DATA_ERROR, 'initial position out of bounds'); - /* mapping table: if some byte values are never used (encoding things - like ascii text), the compression code removes the gaps to have fewer - symbols to deal with, and writes a sparse bitfield indicating which - values were present. We make a translation table to convert the symbols - back to the corresponding bytes. */ - var t = reader.read(16); - var symToByte = new Uint8Array(256), symTotal = 0; - for (i = 0; i < 16; i++) { - if (t & (1 << (0xF - i))) { - var o = i * 16; - k = reader.read(16); - for (j = 0; j < 16; j++) - if (k & (1 << (0xF - j))) - symToByte[symTotal++] = o + j; - } - } - - /* How many different huffman coding groups does this block use? */ - var groupCount = reader.read(3); - if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) - _throw(Err.DATA_ERROR); - /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding - group. Read in the group selector list, which is stored as MTF encoded - bit runs. (MTF=Move To Front, as each value is used it's moved to the - start of the list.) */ - var nSelectors = reader.read(15); - if (nSelectors === 0) - _throw(Err.DATA_ERROR); - - var mtfSymbol = new Uint8Array(256); - for (i = 0; i < groupCount; i++) - mtfSymbol[i] = i; - - var selectors = new Uint8Array(nSelectors); // was 32768... - - for (i = 0; i < nSelectors; i++) { - /* Get next value */ - for (j = 0; reader.read(1); j++) - if (j >= groupCount) _throw(Err.DATA_ERROR); - /* Decode MTF to get the next selector */ - selectors[i] = mtf(mtfSymbol, j); - } - - /* Read the huffman coding tables for each group, which code for symTotal - literal symbols, plus two run symbols (RUNA, RUNB) */ - var symCount = symTotal + 2; - var groups = [], hufGroup; - for (j = 0; j < groupCount; j++) { - var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); - /* Read huffman code lengths for each symbol. They're stored in - a way similar to mtf; record a starting value for the first symbol, - and an offset from the previous value for everys symbol after that. */ - t = reader.read(5); // lengths - for (i = 0; i < symCount; i++) { - for (;;) { - if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); - /* If first bit is 0, stop. Else second bit indicates whether - to increment or decrement the value. */ - if(!reader.read(1)) - break; - if(!reader.read(1)) - t++; - else - t--; - } - length[i] = t; - } - - /* Find largest and smallest lengths in this group */ - var minLen, maxLen; - minLen = maxLen = length[0]; - for (i = 1; i < symCount; i++) { - if (length[i] > maxLen) - maxLen = length[i]; - else if (length[i] < minLen) - minLen = length[i]; - } - - /* Calculate permute[], base[], and limit[] tables from length[]. - * - * permute[] is the lookup table for converting huffman coded symbols - * into decoded symbols. base[] is the amount to subtract from the - * value of a huffman symbol of a given length when using permute[]. - * - * limit[] indicates the largest numerical value a symbol with a given - * number of bits can have. This is how the huffman codes can vary in - * length: each code with a value>limit[length] needs another bit. - */ - hufGroup = {}; - groups.push(hufGroup); - hufGroup.permute = new Uint16Array(MAX_SYMBOLS); - hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); - hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); - hufGroup.minLen = minLen; - hufGroup.maxLen = maxLen; - /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ - var pp = 0; - for (i = minLen; i <= maxLen; i++) { - temp[i] = hufGroup.limit[i] = 0; - for (t = 0; t < symCount; t++) - if (length[t] === i) - hufGroup.permute[pp++] = t; - } - /* Count symbols coded for at each bit length */ - for (i = 0; i < symCount; i++) - temp[length[i]]++; - /* Calculate limit[] (the largest symbol-coding value at each bit - * length, which is (previous limit<<1)+symbols at this level), and - * base[] (number of symbols to ignore at each bit length, which is - * limit minus the cumulative count of symbols coded for already). */ - pp = t = 0; - for (i = minLen; i < maxLen; i++) { - pp += temp[i]; - /* We read the largest possible symbol size and then unget bits - after determining how many we need, and those extra bits could - be set to anything. (They're noise from future symbols.) At - each level we're really only interested in the first few bits, - so here we set all the trailing to-be-ignored bits to 1 so they - don't affect the value>limit[length] comparison. */ - hufGroup.limit[i] = pp - 1; - pp <<= 1; - t += temp[i]; - hufGroup.base[i + 1] = pp - t; - } - hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ - hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; - hufGroup.base[minLen] = 0; - } - /* We've finished reading and digesting the block header. Now read this - block's huffman coded symbols from the file and undo the huffman coding - and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - - /* Initialize symbol occurrence counters and symbol Move To Front table */ - var byteCount = new Uint32Array(256); - for (i = 0; i < 256; i++) - mtfSymbol[i] = i; - /* Loop through compressed symbols. */ - var runPos = 0, dbufCount = 0, selector = 0, uc; - var dbuf = this.dbuf = new Uint32Array(this.dbufSize); - symCount = 0; - for (;;) { - /* Determine which huffman coding group to use. */ - if (!(symCount--)) { - symCount = GROUP_SIZE - 1; - if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } - hufGroup = groups[selectors[selector++]]; - } - /* Read next huffman-coded symbol. */ - i = hufGroup.minLen; - j = reader.read(i); - for (;;i++) { - if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } - if (j <= hufGroup.limit[i]) - break; - j = (j << 1) | reader.read(1); - } - /* Huffman decode value to get nextSym (with bounds checking) */ - j -= hufGroup.base[i]; - if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } - var nextSym = hufGroup.permute[j]; - /* We have now decoded the symbol, which indicates either a new literal - byte, or a repeated run of the most recent literal byte. First, - check if nextSym indicates a repeated run, and if so loop collecting - how many times to repeat the last literal. */ - if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { - /* If this is the start of a new run, zero out counter */ - if (!runPos){ - runPos = 1; - t = 0; - } - /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at - each bit position, add 1 or 2 instead. For example, - 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. - You can make any bit pattern that way using 1 less symbol than - the basic or 0/1 method (except all bits 0, which would use no - symbols, but a run of length 0 doesn't mean anything in this - context). Thus space is saved. */ - if (nextSym === SYMBOL_RUNA) - t += runPos; - else - t += 2 * runPos; - runPos <<= 1; - continue; - } - /* When we hit the first non-run symbol after a run, we now know - how many times to repeat the last literal, so append that many - copies to our buffer of decoded symbols (dbuf) now. (The last - literal used is the one at the head of the mtfSymbol array.) */ - if (runPos){ - runPos = 0; - if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } - uc = symToByte[mtfSymbol[0]]; - byteCount[uc] += t; - while (t--) - dbuf[dbufCount++] = uc; - } - /* Is this the terminating symbol? */ - if (nextSym > symTotal) - break; - /* At this point, nextSym indicates a new literal character. Subtract - one to get the position in the MTF array at which this literal is - currently to be found. (Note that the result can't be -1 or 0, - because 0 and 1 are RUNA and RUNB. But another instance of the - first symbol in the mtf array, position 0, would have been handled - as part of a run above. Therefore 1 unused mtf position minus - 2 non-literal nextSym values equals -1.) */ - if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } - i = nextSym - 1; - uc = mtf(mtfSymbol, i); - uc = symToByte[uc]; - /* We have our literal byte. Save it into dbuf. */ - byteCount[uc]++; - dbuf[dbufCount++] = uc; - } - /* At this point, we've read all the huffman-coded symbols (and repeated - runs) for this block from the input stream, and decoded them into the - intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. - Now undo the Burrows-Wheeler transform on dbuf. - See http://dogma.net/markn/articles/bwt/bwt.htm - */ - if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } - /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ - j = 0; - for (i = 0; i < 256; i++) { - k = j + byteCount[i]; - byteCount[i] = j; - j = k; - } - /* Figure out what order dbuf would be in if we sorted it. */ - for (i = 0; i < dbufCount; i++) { - uc = dbuf[i] & 0xff; - dbuf[byteCount[uc]] |= (i << 8); - byteCount[uc]++; - } - /* Decode first byte by hand to initialize "previous" byte. Note that it - doesn't get output, and if the first three characters are identical - it doesn't qualify as a run (hence writeRunCountdown=5). */ - var pos = 0, current = 0, run = 0; - if (dbufCount) { - pos = dbuf[origPointer]; - current = (pos & 0xff); - pos >>= 8; - run = -1; - } - this.writePos = pos; - this.writeCurrent = current; - this.writeCount = dbufCount; - this.writeRun = run; - - return true; /* more blocks to come */ -}; -/* Undo burrows-wheeler transform on intermediate buffer to produce output. - If start_bunzip was initialized with out_fd=-1, then up to len bytes of - data are written to outbuf. Return value is number of bytes written or - error (all errors are negative numbers). If out_fd!=-1, outbuf and len - are ignored, data is written to out_fd and return is RETVAL_OK or error. -*/ -Bunzip.prototype._read_bunzip = function(outputBuffer, len) { - var copies, previous, outbyte; - /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully - decoded, which results in this returning RETVAL_LAST_BLOCK, also - equal to -1... Confusing, I'm returning 0 here to indicate no - bytes written into the buffer */ - if (this.writeCount < 0) { return 0; } - var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; - var dbufCount = this.writeCount; this.outputsize; - var run = this.writeRun; - - while (dbufCount) { - dbufCount--; - previous = current; - pos = dbuf[pos]; - current = pos & 0xff; - pos >>= 8; - if (run++ === 3){ - copies = current; - outbyte = previous; - current = -1; - } else { - copies = 1; - outbyte = current; - } - this.blockCRC.updateCRCRun(outbyte, copies); - while (copies--) { - this.outputStream.writeByte(outbyte); - this.nextoutput++; - } - if (current != previous) - run = 0; - } - this.writeCount = dbufCount; - // check CRC - if (this.blockCRC.getCRC() !== this.targetBlockCRC) { - _throw(Err.DATA_ERROR, "Bad block CRC "+ - "(got "+this.blockCRC.getCRC().toString(16)+ - " expected "+this.targetBlockCRC.toString(16)+")"); - } - return this.nextoutput; -}; - -var coerceInputStream = function(input) { - if ('readByte' in input) { return input; } - var inputStream = new stream(); - inputStream.pos = 0; - inputStream.readByte = function() { return input[this.pos++]; }; - inputStream.seek = function(pos) { this.pos = pos; }; - inputStream.eof = function() { return this.pos >= input.length; }; - return inputStream; -}; -var coerceOutputStream = function(output) { - var outputStream = new stream(); - var resizeOk = true; - if (output) { - if (typeof(output)==='number') { - outputStream.buffer = new Uint8Array(output); - resizeOk = false; - } else if ('writeByte' in output) { - return output; - } else { - outputStream.buffer = output; - resizeOk = false; - } - } else { - outputStream.buffer = new Uint8Array(16384); - } - outputStream.pos = 0; - outputStream.writeByte = function(_byte) { - if (resizeOk && this.pos >= this.buffer.length) { - var newBuffer = new Uint8Array(this.buffer.length*2); - newBuffer.set(this.buffer); - this.buffer = newBuffer; - } - this.buffer[this.pos++] = _byte; - }; - outputStream.getBuffer = function() { - // trim buffer - if (this.pos !== this.buffer.length) { - if (!resizeOk) - throw new TypeError('outputsize does not match decoded input'); - var newBuffer = new Uint8Array(this.pos); - newBuffer.set(this.buffer.subarray(0, this.pos)); - this.buffer = newBuffer; - } - return this.buffer; - }; - outputStream._coerced = true; - return outputStream; -}; - -/* Static helper functions */ -// 'input' can be a stream or a buffer -// 'output' can be a stream or a buffer or a number (buffer size) -const decode$2 = function(input, output, multistream) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - - var bz = new Bunzip(inputStream, outputStream); - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - if (bz._init_block()) { - bz._read_bunzip(); - } else { - var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) - if (targetStreamCRC !== bz.streamCRC) { - _throw(Err.DATA_ERROR, "Bad stream CRC "+ - "(got "+bz.streamCRC.toString(16)+ - " expected "+targetStreamCRC.toString(16)+")"); - } - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - } else break; - } - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -const decodeBlock = function(input, pos, output) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - var bz = new Bunzip(inputStream, outputStream); - bz.reader.seek(pos); - /* Fill the decode buffer for the block */ - var moreBlocks = bz._get_next_block(); - if (moreBlocks) { - /* Init the CRC for writing */ - bz.blockCRC = new crc32$1(); - - /* Zero this so the current byte from before the seek is not written */ - bz.writeCopies = 0; - - /* Decompress the block and write to stdout */ - bz._read_bunzip(); - // XXX keep writing? - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -/* Reads bzip2 file from stream or buffer `input`, and invoke - * `callback(position, size)` once for each bzip2 block, - * where position gives the starting position (in *bits*) - * and size gives uncompressed size of the block (in *bytes*). */ -const table = function(input, callback, multistream) { - // make a stream from a buffer, if necessary - var inputStream = new stream(); - inputStream.delegate = coerceInputStream(input); - inputStream.pos = 0; - inputStream.readByte = function() { - this.pos++; - return this.delegate.readByte(); - }; - if (inputStream.delegate.eof) { - inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); - } - var outputStream = new stream(); - outputStream.pos = 0; - outputStream.writeByte = function() { this.pos++; }; - - var bz = new Bunzip(inputStream, outputStream); - var blockSize = bz.dbufSize; - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - - var position = inputStream.pos*8 + bz.reader.bitOffset; - if (bz.reader.hasByte) { position -= 8; } - - if (bz._init_block()) { - var start = outputStream.pos; - bz._read_bunzip(); - callback(position, outputStream.pos - start); - } else { - bz.reader.read(32); // (but we ignore the crc) - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - console.assert(bz.dbufSize === blockSize, - "shouldn't change block size within multistream file"); - } else break; - } - } -}; - -var lib = { - Bunzip, - Stream: stream, - Err, - decode: decode$2, - decodeBlock, - table -}; -var lib_4 = lib.decode; - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the Literal Data Packet (Tag 11) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - */ -class LiteralDataPacket { - static get tag() { - return enums.packet.literalData; - } - - /** - * @param {Date} date - The creation date of the literal package - */ - constructor(date = new Date()) { - this.format = enums.literal.utf8; // default format for literal data packets - this.date = util.normalizeDate(date); - this.text = null; // textual data representation - this.data = null; // literal data representation - this.filename = ''; - } - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param {String | ReadableStream} text - Any native javascript string - * @param {enums.literal} [format] - The format of the string of bytes - */ - setText(text, format = enums.literal.utf8) { - this.format = format; - this.text = text; - this.data = null; - } - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {String | ReadableStream} Literal data as text. - */ - getText(clone = false) { - if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read - this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); - } - return this.text; - } - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param {Uint8Array | ReadableStream} bytes - The string of bytes - * @param {enums.literal} format - The format of the string of bytes - */ - setBytes(bytes, format) { - this.format = format; - this.data = bytes; - this.text = null; - } - - - /** - * Get the byte sequence representing the literal packet data - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {Uint8Array | ReadableStream} A sequence of bytes. - */ - getBytes(clone = false) { - if (this.data === null) { - // encode UTF8 and normalize EOL to \r\n - this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); - } - if (clone) { - return passiveClone(this.data); - } - return this.data; - } - - - /** - * Sets the filename of the literal packet data - * @param {String} filename - Any native javascript string - */ - setFilename(filename) { - this.filename = filename; - } - - - /** - * Get the filename of the literal packet data - * @returns {String} Filename. - */ - getFilename() { - return this.filename; - } - - /** - * Parsing function for a literal data packet (tag 11). - * - * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet - * @returns {Promise} Object representation. - * @async - */ - async read(bytes) { - await parse(bytes, async reader => { - // - A one-octet field that describes how the data is formatted. - const format = await reader.readByte(); // enums.literal - - const filename_len = await reader.readByte(); - this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - - this.date = util.readDate(await reader.readBytes(4)); - - let data = reader.remainder(); - if (isArrayStream(data)) data = await readToEnd(data); - this.setBytes(data, format); - }); - } - - /** - * Creates a Uint8Array representation of the packet, excluding the data - * - * @returns {Uint8Array} Uint8Array representation of the packet. - */ - writeHeader() { - const filename = util.encodeUTF8(this.filename); - const filename_length = new Uint8Array([filename.length]); - - const format = new Uint8Array([this.format]); - const date = util.writeDate(this.date); - - return util.concatUint8Array([format, filename_length, filename, date]); - } - - /** - * Creates a Uint8Array representation of the packet - * - * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. - */ - write() { - const header = this.writeHeader(); - const data = this.getBytes(); - - return util.concat([header, data]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. -const verified = Symbol('verified'); - -// GPG puts the Issuer and Signature subpackets in the unhashed area. -// Tampering with those invalidates the signature, so we still trust them and parse them. -// All other unhashed subpackets are ignored. -const allowedUnhashedSubpackets = new Set([ - enums.signatureSubpacket.issuer, - enums.signatureSubpacket.issuerFingerprint, - enums.signatureSubpacket.embeddedSignature -]); - -/** - * Implementation of the Signature Packet (Tag 2) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - */ -class SignaturePacket { - static get tag() { - return enums.packet.signature; - } - - constructor() { - this.version = null; - /** @type {enums.signature} */ - this.signatureType = null; - /** @type {enums.hash} */ - this.hashAlgorithm = null; - /** @type {enums.publicKey} */ - this.publicKeyAlgorithm = null; - - this.signatureData = null; - this.unhashedSubpackets = []; - this.signedHashValue = null; - - this.created = null; - this.signatureExpirationTime = null; - this.signatureNeverExpires = true; - this.exportable = null; - this.trustLevel = null; - this.trustAmount = null; - this.regularExpression = null; - this.revocable = null; - this.keyExpirationTime = null; - this.keyNeverExpires = null; - this.preferredSymmetricAlgorithms = null; - this.revocationKeyClass = null; - this.revocationKeyAlgorithm = null; - this.revocationKeyFingerprint = null; - this.issuerKeyID = new KeyID(); - this.rawNotations = []; - this.notations = {}; - this.preferredHashAlgorithms = null; - this.preferredCompressionAlgorithms = null; - this.keyServerPreferences = null; - this.preferredKeyServer = null; - this.isPrimaryUserID = null; - this.policyURI = null; - this.keyFlags = null; - this.signersUserID = null; - this.reasonForRevocationFlag = null; - this.reasonForRevocationString = null; - this.features = null; - this.signatureTargetPublicKeyAlgorithm = null; - this.signatureTargetHashAlgorithm = null; - this.signatureTargetHash = null; - this.embeddedSignature = null; - this.issuerKeyVersion = null; - this.issuerFingerprint = null; - this.preferredAEADAlgorithms = null; - - this.revoked = null; - this[verified] = null; - } - - /** - * parsing function for a signature packet (tag 2). - * @param {String} bytes - Payload of a tag 2 packet - * @returns {SignaturePacket} Object representation. - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); - } - - this.signatureType = bytes[i++]; - this.publicKeyAlgorithm = bytes[i++]; - this.hashAlgorithm = bytes[i++]; - - // hashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), true); - if (!this.created) { - throw new Error('Missing signature creation time subpacket.'); - } - - // A V4 signature hashes the packet body - // starting from its first field, the version number, through the end - // of the hashed subpacket data. Thus, the fields hashed are the - // signature version, the signature type, the public-key algorithm, the - // hash algorithm, the hashed subpacket length, and the hashed - // subpacket body. - this.signatureData = bytes.subarray(0, i); - - // unhashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - - // Two-octet field holding left 16 bits of signed hash value. - this.signedHashValue = bytes.subarray(i, i + 2); - i += 2; - - this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length)); - } - - /** - * @returns {Uint8Array | ReadableStream} - */ - writeParams() { - if (this.params instanceof Promise) { - return fromAsync( - async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params) - ); - } - return mod.serializeParams(this.publicKeyAlgorithm, this.params); - } - - write() { - const arr = []; - arr.push(this.signatureData); - arr.push(this.writeUnhashedSubPackets()); - arr.push(this.signedHashValue); - arr.push(this.writeParams()); - return util.concat(arr); - } - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param {SecretKeyPacket} key - Private key used to sign the message. - * @param {Object} data - Contains packets to be signed. - * @param {Date} [date] - The signature creation time. - * @param {Boolean} [detached] - Whether to create a detached signature - * @throws {Error} if signing failed - * @async - */ - async sign(key, data, date = new Date(), detached = false) { - if (key.version === 5) { - this.version = 5; - } else { - this.version = 4; - } - const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; - - this.created = util.normalizeDate(date); - this.issuerKeyVersion = key.version; - this.issuerFingerprint = key.getFingerprintBytes(); - this.issuerKeyID = key.getKeyID(); - - // Add hashed subpackets - arr.push(this.writeHashedSubPackets()); - - // Remove unhashed subpackets, in case some allowed unhashed - // subpackets existed, in order not to duplicate them (in both - // the hashed and unhashed subpackets) when re-signing. - this.unhashedSubpackets = []; - - this.signatureData = util.concat(arr); - - const toHash = this.toHash(this.signatureType, data, detached); - const hash = await this.hash(this.signatureType, data, toHash, detached); - - this.signedHashValue = slice(clone(hash), 0, 2); - const signed = async () => mod.signature.sign( - this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) - ); - if (util.isStream(hash)) { - this.params = signed(); - } else { - this.params = await signed(); - - // Store the fact that this signature is valid, e.g. for when we call `await - // getLatestValidSignature(this.revocationSignatures, key, data)` later. - // Note that this only holds up if the key and data passed to verify are the - // same as the ones passed to sign. - this[verified] = true; - } - } - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeHashedSubPackets() { - const sub = enums.signatureSubpacket; - const arr = []; - let bytes; - if (this.created === null) { - throw new Error('Missing signature creation time'); - } - arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); - if (this.signatureExpirationTime !== null) { - arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); - } - if (this.exportable !== null) { - arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); - } - if (this.trustLevel !== null) { - bytes = new Uint8Array([this.trustLevel, this.trustAmount]); - arr.push(writeSubPacket(sub.trustSignature, true, bytes)); - } - if (this.regularExpression !== null) { - arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); - } - if (this.revocable !== null) { - arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); - } - if (this.keyExpirationTime !== null) { - arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); - } - if (this.preferredSymmetricAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); - arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); - } - if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); - bytes = util.concat([bytes, this.revocationKeyFingerprint]); - arr.push(writeSubPacket(sub.revocationKey, false, bytes)); - } - if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { - // If the version of [the] key is greater than 4, this subpacket - // MUST NOT be included in the signature. - arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write())); - } - this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { - bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; - const encodedName = util.encodeUTF8(name); - // 2 octets of name length - bytes.push(util.writeNumber(encodedName.length, 2)); - // 2 octets of value length - bytes.push(util.writeNumber(value.length, 2)); - bytes.push(encodedName); - bytes.push(value); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.notationData, critical, bytes)); - }); - if (this.preferredHashAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); - arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); - } - if (this.preferredCompressionAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); - arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); - } - if (this.keyServerPreferences !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); - arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); - } - if (this.preferredKeyServer !== null) { - arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); - } - if (this.isPrimaryUserID !== null) { - arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); - } - if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); - } - if (this.keyFlags !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); - arr.push(writeSubPacket(sub.keyFlags, true, bytes)); - } - if (this.signersUserID !== null) { - arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); - } - if (this.reasonForRevocationFlag !== null) { - bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); - arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); - } - if (this.features !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); - arr.push(writeSubPacket(sub.features, false, bytes)); - } - if (this.signatureTargetPublicKeyAlgorithm !== null) { - bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(util.stringToUint8Array(this.signatureTargetHash)); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); - } - if (this.embeddedSignature !== null) { - arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); - } - if (this.issuerFingerprint !== null) { - bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes)); - } - if (this.preferredAEADAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); - arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); - } - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - /** - * Creates an Uint8Array containing the unhashed subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeUnhashedSubPackets() { - const arr = []; - this.unhashedSubpackets.forEach(data => { - arr.push(writeSimpleLength(data.length)); - arr.push(data); - }); - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - // V4 signature sub packets - readSubPacket(bytes, hashed = true) { - let mypos = 0; - - // The leftmost bit denotes a "critical" packet - const critical = !!(bytes[mypos] & 0x80); - const type = bytes[mypos] & 0x7F; - - if (!hashed) { - this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length)); - if (!allowedUnhashedSubpackets.has(type)) { - return; - } - } - - mypos++; - - // subpacket type - switch (type) { - case enums.signatureSubpacket.signatureCreationTime: - // Signature Creation Time - this.created = util.readDate(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.signatureExpirationTime: { - // Signature Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.signatureNeverExpires = seconds === 0; - this.signatureExpirationTime = seconds; - - break; - } - case enums.signatureSubpacket.exportableCertification: - // Exportable Certification - this.exportable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.trustSignature: - // Trust Signature - this.trustLevel = bytes[mypos++]; - this.trustAmount = bytes[mypos++]; - break; - case enums.signatureSubpacket.regularExpression: - // Regular Expression - this.regularExpression = bytes[mypos]; - break; - case enums.signatureSubpacket.revocable: - // Revocable - this.revocable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.keyExpirationTime: { - // Key Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.keyExpirationTime = seconds; - this.keyNeverExpires = seconds === 0; - - break; - } - case enums.signatureSubpacket.preferredSymmetricAlgorithms: - // Preferred Symmetric Algorithms - this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.revocationKey: - // Revocation Key - // (1 octet of class, 1 octet of public-key algorithm ID, 20 - // octets of - // fingerprint) - this.revocationKeyClass = bytes[mypos++]; - this.revocationKeyAlgorithm = bytes[mypos++]; - this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); - break; - - case enums.signatureSubpacket.issuer: - // Issuer - this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); - break; - - case enums.signatureSubpacket.notationData: { - // Notation Data - const humanReadable = !!(bytes[mypos] & 0x80); - - // We extract key/value tuple from the byte stream. - mypos += 4; - const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - - const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); - const value = bytes.subarray(mypos + m, mypos + m + n); - - this.rawNotations.push({ name, humanReadable, value, critical }); - - if (humanReadable) { - this.notations[name] = util.decodeUTF8(value); - } - break; - } - case enums.signatureSubpacket.preferredHashAlgorithms: - // Preferred Hash Algorithms - this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredCompressionAlgorithms: - // Preferred Compression Algorithms - this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.keyServerPreferences: - // Key Server Preferences - this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredKeyServer: - // Preferred Key Server - this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.primaryUserID: - // Primary User ID - this.isPrimaryUserID = bytes[mypos++] !== 0; - break; - case enums.signatureSubpacket.policyURI: - // Policy URI - this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.keyFlags: - // Key Flags - this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signersUserID: - // Signer's User ID - this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.reasonForRevocation: - // Reason for Revocation - this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.features: - // Features - this.features = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signatureTarget: { - // Signature Target - // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) - this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; - this.signatureTargetHashAlgorithm = bytes[mypos++]; - - const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm); - - this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); - break; - } - case enums.signatureSubpacket.embeddedSignature: - // Embedded Signature - this.embeddedSignature = new SignaturePacket(); - this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.issuerFingerprint: - // Issuer Fingerprint - this.issuerKeyVersion = bytes[mypos++]; - this.issuerFingerprint = bytes.subarray(mypos, bytes.length); - if (this.issuerKeyVersion === 5) { - this.issuerKeyID.read(this.issuerFingerprint); - } else { - this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); - } - break; - case enums.signatureSubpacket.preferredAEADAlgorithms: - // Preferred AEAD Algorithms - this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - default: { - const err = new Error(`Unknown signature subpacket type ${type}`); - if (critical) { - throw err; - } else { - util.printDebug(err); - } - } - } - } - - readSubPackets(bytes, trusted = true, config) { - // Two-octet scalar octet count for following subpacket data. - const subpacketLength = util.readNumber(bytes.subarray(0, 2)); - - let i = 2; - - // subpacket data set (zero or more subpackets) - while (i < 2 + subpacketLength) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); - - i += len.len; - } - - return i; - } - - // Produces data to produce signature on - toSign(type, data) { - const t = enums.signature; - - switch (type) { - case t.binary: - if (data.text !== null) { - return util.encodeUTF8(data.getText(true)); - } - return data.getBytes(true); - - case t.text: { - const bytes = data.getBytes(true); - // normalize EOL to \r\n - return util.canonicalizeEOL(bytes); - } - case t.standalone: - return new Uint8Array(0); - - case t.certGeneric: - case t.certPersona: - case t.certCasual: - case t.certPositive: - case t.certRevocation: { - let packet; - let tag; - - if (data.userID) { - tag = 0xB4; - packet = data.userID; - } else if (data.userAttribute) { - tag = 0xD1; - packet = data.userAttribute; - } else { - throw new Error('Either a userID or userAttribute packet needs to be ' + - 'supplied for certification.'); - } - - const bytes = packet.write(); - - return util.concat([this.toSign(t.key, data), - new Uint8Array([tag]), - util.writeNumber(bytes.length, 4), - bytes]); - } - case t.subkeyBinding: - case t.subkeyRevocation: - case t.keyBinding: - return util.concat([this.toSign(t.key, data), this.toSign(t.key, { - key: data.bind - })]); - - case t.key: - if (data.key === undefined) { - throw new Error('Key packet is required for this signature.'); - } - return data.key.writeForHash(this.version); - - case t.keyRevocation: - return this.toSign(t.key, data); - case t.timestamp: - return new Uint8Array(0); - case t.thirdParty: - throw new Error('Not implemented'); - default: - throw new Error('Unknown signature type.'); - } - } - - calculateTrailer(data, detached) { - let length = 0; - return transform(clone(this.signatureData), value => { - length += value.length; - }, () => { - const arr = []; - if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { - if (detached) { - arr.push(new Uint8Array(6)); - } else { - arr.push(data.writeHeader()); - } - } - arr.push(new Uint8Array([this.version, 0xFF])); - if (this.version === 5) { - arr.push(new Uint8Array(4)); - } - arr.push(util.writeNumber(length, 4)); - // For v5, this should really be writeNumber(length, 8) rather than the - // hardcoded 4 zero bytes above - return util.concat(arr); - }); - } - - toHash(signatureType, data, detached = false) { - const bytes = this.toSign(signatureType, data); - - return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); - } - - async hash(signatureType, data, toHash, detached = false) { - if (!toHash) toHash = this.toHash(signatureType, data, detached); - return mod.hash.digest(this.hashAlgorithm, toHash); - } - - /** - * verifies the signature packet. Note: not all signature types are implemented - * @param {PublicSubkeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature - * @param {module:enums.signature} signatureType - Expected signature type - * @param {Uint8Array|Object} data - Data which on the signature applies - * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration - * @param {Boolean} [detached] - Whether to verify a detached signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if signature validation failed - * @async - */ - async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { - if (!this.issuerKeyID.equals(key.getKeyID())) { - throw new Error('Signature was not issued by the given public key'); - } - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); - } - - const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; - // Cryptographic validity is cached after one successful verification. - // However, for message signatures, we always re-verify, since the passed `data` can change - const skipVerify = this[verified] && !isMessageSignature; - if (!skipVerify) { - let toHash; - let hash; - if (this.hashed) { - hash = await this.hashed; - } else { - toHash = this.toHash(signatureType, data, detached); - hash = await this.hash(signatureType, data, toHash); - } - hash = await readToEnd(hash); - if (this.signedHashValue[0] !== hash[0] || - this.signedHashValue[1] !== hash[1]) { - throw new Error('Signed digest did not match'); - } - - this.params = await this.params; - - this[verified] = await mod.signature.verify( - this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, - toHash, hash - ); - - if (!this[verified]) { - throw new Error('Signature verification failed'); - } - } - - const normDate = util.normalizeDate(date); - if (normDate && this.created > normDate) { - throw new Error('Signature creation time is in the future'); - } - if (normDate && normDate >= this.getExpirationTime()) { - throw new Error('Signature is expired'); - } - if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { - throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && - [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { - throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - this.rawNotations.forEach(({ name, critical }) => { - if (critical && (config$1.knownNotations.indexOf(name) < 0)) { - throw new Error(`Unknown critical notation: ${name}`); - } - }); - if (this.revocationKeyClass !== null) { - throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); - } - } - - /** - * Verifies signature expiration date - * @param {Date} [date] - Use the given date for verification instead of the current time - * @returns {Boolean} True if expired. - */ - isExpired(date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - return !(this.created <= normDate && normDate < this.getExpirationTime()); - } - return false; - } - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns {Date | Infinity} Expiration time. - */ - getExpirationTime() { - return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); - } -} - -/** - * Creates a Uint8Array representation of a sub signature packet - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} - * @param {Integer} type - Subpacket signature type. - * @param {Boolean} critical - Whether the subpacket should be critical. - * @param {String} data - Data to be included - * @returns {Uint8Array} The signature subpacket. - * @private - */ -function writeSubPacket(type, critical, data) { - const arr = []; - arr.push(writeSimpleLength(data.length + 1)); - arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); - arr.push(data); - return util.concat(arr); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -const VERSION = 3; - -/** - * Implementation of the One-Pass Signature Packets (Tag 4) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ -class OnePassSignaturePacket { - static get tag() { - return enums.packet.onePassSignature; - } - - constructor() { - /** A one-octet version number. The current version is 3. */ - this.version = null; - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - * @type {enums.signature} - - */ - this.signatureType = null; - /** - * A one-octet number describing the hash algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} - * @type {enums.hash} - */ - this.hashAlgorithm = null; - /** - * A one-octet number describing the public-key algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} - * @type {enums.publicKey} - */ - this.publicKeyAlgorithm = null; - /** An eight-octet number holding the Key ID of the signing key. */ - this.issuerKeyID = null; - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - this.flags = null; - } - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param {Uint8Array} bytes - Payload of a tag 4 packet - * @returns {OnePassSignaturePacket} Object representation. - */ - read(bytes) { - let mypos = 0; - // A one-octet version number. The current version is 3. - this.version = bytes[mypos++]; - if (this.version !== VERSION) { - throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); - } - - // A one-octet signature type. Signature types are described in - // Section 5.2.1. - this.signatureType = bytes[mypos++]; - - // A one-octet number describing the hash algorithm used. - this.hashAlgorithm = bytes[mypos++]; - - // A one-octet number describing the public-key algorithm used. - this.publicKeyAlgorithm = bytes[mypos++]; - - // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyID = new KeyID(); - this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); - mypos += 8; - - // A one-octet number holding a flag showing whether the signature - // is nested. A zero value indicates that the next packet is - // another One-Pass Signature packet that describes another - // signature to be applied to the same message data. - this.flags = bytes[mypos++]; - return this; - } - - /** - * creates a string representation of a one-pass signature packet - * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. - */ - write() { - const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]); - - const end = new Uint8Array([this.flags]); - - return util.concatUint8Array([start, this.issuerKeyID.write(), end]); - } - - calculateTrailer(...args) { - return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); - } - - async verify() { - const correspondingSig = await this.correspondingSig; - if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { - throw new Error('Corresponding signature packet missing'); - } - if ( - correspondingSig.signatureType !== this.signatureType || - correspondingSig.hashAlgorithm !== this.hashAlgorithm || - correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyID.equals(this.issuerKeyID) - ) { - throw new Error('Corresponding signature packet does not match one-pass signature packet'); - } - correspondingSig.hashed = this.hashed; - return correspondingSig.verify.apply(correspondingSig, arguments); - } -} - -OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; -OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; -OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; - -/** - * Instantiate a new packet given its tag - * @function newPacketFromTag - * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @returns {Object} New packet object with type based on tag - * @throws {Error|UnsupportedError} for disallowed or unknown packets - */ -function newPacketFromTag(tag, allowedPackets) { - if (!allowedPackets[tag]) { - // distinguish between disallowed packets and unknown ones - let packetType; - try { - packetType = enums.read(enums.packet, tag); - } catch (e) { - throw new UnsupportedError(`Unknown packet type with tag: ${tag}`); - } - throw new Error(`Packet not allowed in this context: ${packetType}`); - } - return new allowedPackets[tag](); -} - -/** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - * @extends Array - */ -class PacketList extends Array { - /** - * Parses the given binary data and returns a list of packets. - * Equivalent to calling `read` on an empty PacketList instance. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @returns {PacketList} parsed list of packets - * @throws on parsing errors - * @async - */ - static async fromBinary(bytes, allowedPackets, config$1 = config) { - const packets = new PacketList(); - await packets.read(bytes, allowedPackets, config$1); - return packets; - } - - /** - * Reads a stream of binary data and interprets it as a list of packets. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @throws on parsing errors - * @async - */ - async read(bytes, allowedPackets, config$1 = config) { - if (config$1.additionalAllowedPackets.length) { - allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; - } - this.stream = transformPair(bytes, async (readable, writable) => { - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const done = await readPackets(readable, async parsed => { - try { - if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) { - // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: - // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 - // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 - return; - } - const packet = newPacketFromTag(parsed.tag, allowedPackets); - packet.packets = new PacketList(); - packet.fromStream = util.isStream(parsed.packet); - await packet.read(parsed.packet, config$1); - await writer.write(packet); - } catch (e) { - const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; - const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); - if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { - // The packets that support streaming are the ones that contain message data. - // Those are also the ones we want to be more strict about and throw on parse errors - // (since we likely cannot process the message without these packets anyway). - await writer.abort(e); - } else { - const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); - await writer.write(unparsedPacket); - } - util.printDebugError(e); - } - }); - if (done) { - await writer.ready; - await writer.close(); - return; - } - } - } catch (e) { - await writer.abort(e); - } - }); - - // Wait until first few packets have been read - const reader = getReader(this.stream); - while (true) { - const { done, value } = await reader.read(); - if (!done) { - this.push(value); - } else { - this.stream = null; - } - if (done || supportsStreaming(value.constructor.tag)) { - break; - } - } - reader.releaseLock(); - } - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. - */ - write() { - const arr = []; - - for (let i = 0; i < this.length; i++) { - const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; - const packetbytes = this[i].write(); - if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { - let buffer = []; - let bufferLength = 0; - const minLength = 512; - arr.push(writeTag(tag)); - arr.push(transform(packetbytes, value => { - buffer.push(value); - bufferLength += value.length; - if (bufferLength >= minLength) { - const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); - const chunkSize = 2 ** powerOf2; - const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); - buffer = [bufferConcat.subarray(1 + chunkSize)]; - bufferLength = buffer[0].length; - return bufferConcat.subarray(0, 1 + chunkSize); - } - }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); - } else { - if (util.isStream(packetbytes)) { - let length = 0; - arr.push(transform(clone(packetbytes), value => { - length += value.length; - }, () => writeHeader(tag, length))); - } else { - arr.push(writeHeader(tag, packetbytes.length)); - } - arr.push(packetbytes); - } - } - - return util.concat(arr); - } - - /** - * Creates a new PacketList with all packets matching the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {PacketList} - */ - filterByTag(...tags) { - const filtered = new PacketList(); - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(this[i].constructor.tag))) { - filtered.push(this[i]); - } - } - - return filtered; - } - - /** - * Traverses packet list and returns first packet with matching tag - * @param {module:enums.packet} tag - The packet tag - * @returns {Packet|undefined} - */ - findPacket(tag) { - return this.find(packet => packet.constructor.tag === tag); - } - - /** - * Find indices of packets with the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {Integer[]} packet indices - */ - indexOfTag(...tags) { - const tagIndex = []; - const that = this; - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(that[i].constructor.tag))) { - tagIndex.push(i); - } - } - return tagIndex; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Compressed Data packet can contain the following packet types -const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -/** - * Implementation of the Compressed Data Packet (Tag 8) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ -class CompressedDataPacket { - static get tag() { - return enums.packet.compressedData; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * List of packets - * @type {PacketList} - */ - this.packets = null; - /** - * Compression algorithm - * @type {enums.compression} - */ - this.algorithm = config$1.preferredCompressionAlgorithm; - - /** - * Compressed packet data - * @type {Uint8Array | ReadableStream} - */ - this.compressed = null; - - /** - * zip/zlib compression level, between 1 and 9 - */ - this.deflateLevel = config$1.deflateLevel; - } - - /** - * Parsing function for the packet. - * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async read(bytes, config$1 = config) { - await parse(bytes, async reader => { - - // One octet that gives the algorithm used to compress the packet. - this.algorithm = await reader.readByte(); - - // Compressed data, which makes up the remainder of the packet. - this.compressed = reader.remainder(); - - await this.decompress(config$1); - }); - } - - - /** - * Return the compressed packet. - * @returns {Uint8Array | ReadableStream} Binary compressed packet. - */ - write() { - if (this.compressed === null) { - this.compress(); - } - - return util.concat([new Uint8Array([this.algorithm]), this.compressed]); - } - - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async decompress(config$1 = config) { - const compressionName = enums.read(enums.compression, this.algorithm); - const decompressionFn = decompress_fns[compressionName]; - if (!decompressionFn) { - throw new Error(`${compressionName} decompression not supported`); - } - - this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1); - } - - /** - * Compress the packet data (member decompressedData) - */ - compress() { - const compressionName = enums.read(enums.compression, this.algorithm); - const compressionFn = compress_fns[compressionName]; - if (!compressionFn) { - throw new Error(`${compressionName} compression not supported`); - } - - this.compressed = compressionFn(this.packets.write(), this.deflateLevel); - } -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -const nodeZlib = util.getNodeZlib(); - -function uncompressed(data) { - return data; -} - -function node_zlib(func, create, options = {}) { - return function (data) { - if (!util.isStream(data) || isArrayStream(data)) { - return fromAsync(() => readToEnd(data).then(data => { - return new Promise((resolve, reject) => { - func(data, options, (err, result) => { - if (err) return reject(err); - resolve(result); - }); - }); - })); - } - return nodeToWeb(webToNode(data).pipe(create(options))); - }; -} - -function pako_zlib(constructor, options = {}) { - return function(data) { - const obj = new constructor(options); - return transform(data, value => { - if (value.length) { - obj.push(value, Z_SYNC_FLUSH); - return obj.result; - } - }, () => { - if (constructor === Deflate) { - obj.push([], Z_FINISH); - return obj.result; - } - }); - }; -} - -function bzip2(func) { - return function(data) { - return fromAsync(async () => func(await readToEnd(data))); - }; -} - -const compress_fns = nodeZlib ? { - zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed) -} : { - zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed) -}; - -const decompress_fns = nodeZlib ? { - uncompressed: uncompressed, - zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw), - zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -} : { - uncompressed: uncompressed, - zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), - zlib: /*#__PURE__*/ pako_zlib(Inflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -}; - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A SEIP packet can contain the following packet types -const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$1 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ -class SymEncryptedIntegrityProtectedDataPacket { - static get tag() { - return enums.packet.symEncryptedIntegrityProtectedData; - } - - constructor() { - this.version = VERSION$1; - this.encrypted = null; - this.packets = null; - } - - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - // - A one-octet version number. The only currently defined value is 1. - if (version !== VERSION$1) { - throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`); - } - - // - Encrypted data, the output of the selected symmetric-key cipher - // operating in Cipher Feedback mode with shift amount equal to the - // block size of the cipher (CFB-n where n is the block size). - this.encrypted = reader.remainder(); - }); - } - - write() { - return util.concat([new Uint8Array([VERSION$1]), this.encrypted]); - } - - /** - * Encrypt the payload in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on encryption failure - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - - let bytes = this.packets.write(); - if (isArrayStream(bytes)) bytes = await readToEnd(bytes); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - - const tohash = util.concat([prefix, bytes, mdc]); - const hash = await mod.hash.sha1(passiveClone(tohash)); - const plaintext = util.concat([tohash, hash]); - - this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); - return true; - } - - /** - * Decrypts the encrypted data contained in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on decryption failure - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - let encrypted = clone(this.encrypted); - if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); - - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - const realHash = slice(passiveClone(decrypted), -20); - const tohash = slice(decrypted, 0, -20); - const verifyHash = Promise.all([ - readToEnd(await mod.hash.sha1(passiveClone(tohash))), - readToEnd(realHash) - ]).then(([hash, mdc]) => { - if (!util.equalsUint8Array(hash, mdc)) { - throw new Error('Modification detected.'); - } - return new Uint8Array(); - }); - const bytes = slice(tohash, blockSize + 2); // Remove random prefix - let packetbytes = slice(bytes, 0, -2); // Remove MDC packet - packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); - if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { - packetbytes = await readToEnd(packetbytes); - } - this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1); - return true; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -// An AEAD-encrypted Data packet can contain the following packet types -const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$2 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ -class AEADEncryptedDataPacket { - static get tag() { - return enums.packet.aeadEncryptedData; - } - - constructor() { - this.version = VERSION$2; - /** @type {enums.symmetric} */ - this.cipherAlgorithm = null; - /** @type {enums.aead} */ - this.aeadAlgorithm = enums.aead.eax; - this.chunkSizeByte = null; - this.iv = null; - this.encrypted = null; - this.packets = null; - } - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param {Uint8Array | ReadableStream} bytes - * @throws {Error} on parsing failure - */ - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - if (version !== VERSION$2) { // The only currently defined value is 1. - throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); - } - this.cipherAlgorithm = await reader.readByte(); - this.aeadAlgorithm = await reader.readByte(); - this.chunkSizeByte = await reader.readByte(); - - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = await reader.readBytes(mode.ivLength); - this.encrypted = reader.remainder(); - }); - } - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns {Uint8Array | ReadableStream} The encrypted payload. - */ - write() { - return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); - } - - /** - * Decrypt the encrypted payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.packets = await PacketList.fromBinary( - await this.crypt('decrypt', key, clone(this.encrypted)), - allowedPackets$2, - config$1 - ); - } - - /** - * Encrypt the packet payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.cipherAlgorithm = sessionKeyAlgorithm; - - const { ivLength } = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV - this.chunkSizeByte = config$1.aeadChunkSizeByte; - const data = this.packets.write(); - this.encrypted = await this.crypt('encrypt', key, data); - } - - /** - * En/decrypt the payload. - * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt - * @param {Uint8Array} key - The session key used to en/decrypt the payload - * @param {Uint8Array | ReadableStream} data - The data to en/decrypt - * @returns {Promise>} - * @async - */ - async crypt(fn, key, data) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const modeInstance = await mode(this.cipherAlgorithm, key); - const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; - const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; - const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) - const adataBuffer = new ArrayBuffer(21); - const adataArray = new Uint8Array(adataBuffer, 0, 13); - const adataTagArray = new Uint8Array(adataBuffer); - const adataView = new DataView(adataBuffer); - const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0); - let chunkIndex = 0; - let latestPromise = Promise.resolve(); - let cryptedBytes = 0; - let queuedBytes = 0; - const iv = this.iv; - return transformPair(data, async (readable, writable) => { - if (util.isStream(readable) !== 'array') { - const buffer = new TransformStream({}, { - highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6), - size: array => array.length - }); - pipe(buffer.readable, writable); - writable = buffer.writable; - } - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); - const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); - chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); - let cryptedPromise; - let done; - if (!chunkIndex || chunk.length) { - reader.unshift(finalChunk); - cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray); - queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; - } else { - // After the last chunk, we either encrypt a final, empty - // data chunk to get the final authentication tag or - // validate that final authentication tag. - adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...) - cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray); - queuedBytes += tagLengthIfEncrypting; - done = true; - } - cryptedBytes += chunk.length - tagLengthIfDecrypting; - // eslint-disable-next-line no-loop-func - latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { - await writer.ready; - await writer.write(crypted); - queuedBytes -= crypted.length; - }).catch(err => writer.abort(err)); - if (done || queuedBytes > writer.desiredSize) { - await latestPromise; // Respect backpressure - } - if (!done) { - adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) - } else { - await writer.close(); - break; - } - } - } catch (e) { - await writer.abort(e); - } - }); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -const VERSION$3 = 3; - -/** - * Public-Key Encrypted Session Key Packets (Tag 1) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ -class PublicKeyEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.publicKeyEncryptedSessionKey; - } - - constructor() { - this.version = 3; - - this.publicKeyID = new KeyID(); - this.publicKeyAlgorithm = null; - - this.sessionKey = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = null; - - /** @type {Object} */ - this.encrypted = {}; - } - - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * - * @param {Uint8Array} bytes - Payload of a tag 1 packet - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - if (this.version !== VERSION$3) { - throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); - } - i += this.publicKeyID.read(bytes.subarray(i)); - this.publicKeyAlgorithm = bytes[i++]; - this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version); - if (this.publicKeyAlgorithm === enums.publicKey.x25519) { - this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); - } - } - - /** - * Create a binary representation of a tag 1 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const arr = [ - new Uint8Array([this.version]), - this.publicKeyID.write(), - new Uint8Array([this.publicKeyAlgorithm]), - mod.serializeParams(this.publicKeyAlgorithm, this.encrypted) - ]; - - return util.concatUint8Array(arr); - } - - /** - * Encrypt session key packet - * @param {PublicKeyPacket} key - Public key - * @throws {Error} if encryption failed - * @async - */ - async encrypt(key) { - const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); - const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey); - this.encrypted = await mod.publicKeyEncrypt( - algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes()); - } - - /** - * Decrypts the session key (only for public key encrypted session key packets (tag 1) - * @param {SecretKeyPacket} key - decrypted private key - * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. - * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } - * @throws {Error} if decryption failed, unless `randomSessionKey` is given - * @async - */ - async decrypt(key, randomSessionKey) { - // check that session key algo matches the secret key algo - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Decryption error'); - } - - const randomPayload = randomSessionKey ? - encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : - null; - const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload); - - const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); - - // v3 Montgomery curves have cleartext cipher algo - if (this.publicKeyAlgorithm !== enums.publicKey.x25519) { - this.sessionKeyAlgorithm = sessionKeyAlgorithm; - } - this.sessionKey = sessionKey; - } -} - - -function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // add checksum - return util.concatUint8Array([ - new Uint8Array([cipherAlgo]), - sessionKeyData, - util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) - ]); - } - case enums.publicKey.x25519: - return sessionKeyData; - default: - throw new Error('Unsupported public key algorithm'); - } -} - - -function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // verify checksum in constant time - const result = decryptedData.subarray(0, decryptedData.length - 2); - const checksum = decryptedData.subarray(decryptedData.length - 2); - const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); - const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; - const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; - if (randomSessionKey) { - // We must not leak info about the validity of the decrypted checksum or cipher algo. - // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. - const isValidPayload = isValidChecksum & - decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & - decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; - return { - sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), - sessionKeyAlgorithm: util.selectUint8( - isValidPayload, - decryptedSessionKey.sessionKeyAlgorithm, - randomSessionKey.sessionKeyAlgorithm - ) - }; - } else { - const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm); - if (isValidPayload) { - return decryptedSessionKey; - } else { - throw new Error('Decryption error'); - } - } - } - case enums.publicKey.x25519: - return { - sessionKey: decryptedData - }; - default: - throw new Error('Unsupported public key algorithm'); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -class S2K { - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * Hash function identifier, or 0 for gnu-dummy keys - * @type {module:enums.hash | 0} - */ - this.algorithm = enums.hash.sha256; - /** - * enums.s2k identifier or 'gnu-dummy' - * @type {String} - */ - this.type = 'iterated'; - /** @type {Integer} */ - this.c = config$1.s2kIterationCountByte; - /** Eight bytes of salt in a binary string. - * @type {Uint8Array} - */ - this.salt = null; - } - - getCount() { - // Exponent bias, defined in RFC4880 - const expbias = 6; - - return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); - } - - /** - * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param {Uint8Array} bytes - Payload of string-to-key specifier - * @returns {Integer} Actual length of the object. - */ - read(bytes) { - let i = 0; - try { - this.type = enums.read(enums.s2k, bytes[i++]); - } catch (err) { - throw new UnsupportedError('Unknown S2K type.'); - } - this.algorithm = bytes[i++]; - - switch (this.type) { - case 'simple': - break; - - case 'salted': - this.salt = bytes.subarray(i, i + 8); - i += 8; - break; - - case 'iterated': - this.salt = bytes.subarray(i, i + 8); - i += 8; - - // Octet 10: count, a one-octet, coded value - this.c = bytes[i++]; - break; - - case 'gnu': - if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { - i += 3; // GNU - const gnuExtType = 1000 + bytes[i++]; - if (gnuExtType === 1001) { - this.type = 'gnu-dummy'; - // GnuPG extension mode 1001 -- don't write secret key at all - } else { - throw new UnsupportedError('Unknown s2k gnu protection mode.'); - } - } else { - throw new UnsupportedError('Unknown s2k type.'); - } - break; - - default: - throw new UnsupportedError('Unknown s2k type.'); // unreachable - } - - return i; - } - - /** - * Serializes s2k information - * @returns {Uint8Array} Binary representation of s2k. - */ - write() { - if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); - } - const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; - - switch (this.type) { - case 'simple': - break; - case 'salted': - arr.push(this.salt); - break; - case 'iterated': - arr.push(this.salt); - arr.push(new Uint8Array([this.c])); - break; - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - - return util.concatUint8Array(arr); - } - - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param {String} passphrase - Passphrase containing user input - * @returns {Promise} Produced key with a length corresponding to. - * hashAlgorithm hash length - * @async - */ - async produceKey(passphrase, numBytes) { - passphrase = util.encodeUTF8(passphrase); - - const arr = []; - let rlength = 0; - - let prefixlen = 0; - while (rlength < numBytes) { - let toHash; - switch (this.type) { - case 'simple': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); - break; - case 'salted': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); - break; - case 'iterated': { - const data = util.concatUint8Array([this.salt, passphrase]); - let datalen = data.length; - const count = Math.max(this.getCount(), datalen); - toHash = new Uint8Array(prefixlen + count); - toHash.set(data, prefixlen); - for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { - toHash.copyWithin(pos, prefixlen, pos); - } - break; - } - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } - const result = await mod.hash.digest(this.algorithm, toHash); - arr.push(result); - rlength += result.length; - prefixlen++; - } - - return util.concatUint8Array(arr).subarray(0, numBytes); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Symmetric-Key Encrypted Session Key Packets (Tag 3) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: - * The Symmetric-Key Encrypted Session Key packet holds the - * symmetric-key encryption of a session key used to encrypt a message. - * Zero or more Public-Key Encrypted Session Key packets and/or - * Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data packet that holds an encrypted message. - * The message is encrypted with a session key, and the session key is - * itself encrypted and stored in the Encrypted Session Key packet or - * the Symmetric-Key Encrypted Session Key packet. - */ -class SymEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.symEncryptedSessionKey; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - this.version = config$1.aeadProtect ? 5 : 4; - this.sessionKey = null; - /** - * Algorithm to encrypt the session key with - * @type {enums.symmetric} - */ - this.sessionKeyEncryptionAlgorithm = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = enums.symmetric.aes256; - /** - * AEAD mode to encrypt the session key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); - this.encrypted = null; - this.s2k = null; - this.iv = null; - } - - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * - * @param {Uint8Array} bytes - Payload of a tag 3 packet - */ - read(bytes) { - let offset = 0; - - // A one-octet version number. The only currently defined version is 4. - this.version = bytes[offset++]; - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); - } - - // A one-octet number describing the symmetric algorithm used. - const algo = bytes[offset++]; - - if (this.version === 5) { - // A one-octet AEAD algorithm. - this.aeadAlgorithm = bytes[offset++]; - } - - // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new S2K(); - offset += this.s2k.read(bytes.subarray(offset, bytes.length)); - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - - // A starting initialization vector of size specified by the AEAD - // algorithm. - this.iv = bytes.subarray(offset, offset += mode.ivLength); - } - - // The encrypted session key itself, which is decrypted with the - // string-to-key object. This is optional in version 4. - if (this.version === 5 || offset < bytes.length) { - this.encrypted = bytes.subarray(offset, bytes.length); - this.sessionKeyEncryptionAlgorithm = algo; - } else { - this.sessionKeyAlgorithm = algo; - } - } - - /** - * Create a binary representation of a tag 3 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const algo = this.encrypted === null ? - this.sessionKeyAlgorithm : - this.sessionKeyEncryptionAlgorithm; - - let bytes; - - if (this.version === 5) { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]); - } else { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]); - - if (this.encrypted !== null) { - bytes = util.concatUint8Array([bytes, this.encrypted]); - } - } - - return bytes; - } - - /** - * Decrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(passphrase) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; - - const { blockSize, keySize } = mod.getCipher(algo); - const key = await this.s2k.produceKey(passphrase, keySize); - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, key); - this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); - } else if (this.encrypted !== null) { - const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); - - this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1, decrypted.length); - } else { - this.sessionKey = key; - } - } - - /** - * Encrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; - - this.sessionKeyEncryptionAlgorithm = algo; - - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - - const { blockSize, keySize } = mod.getCipher(algo); - const encryptionKey = await this.s2k.produceKey(passphrase, keySize); - - if (this.sessionKey === null) { - this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm); - } - - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV - const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, encryptionKey); - this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData); - } else { - const toEncrypt = util.concatUint8Array([ - new Uint8Array([this.sessionKeyAlgorithm]), - this.sessionKey - ]); - this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1); - } - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ -class PublicKeyPacket { - static get tag() { - return enums.packet.publicKey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - /** - * Packet version - * @type {Integer} - */ - this.version = config$1.v5Keys ? 5 : 4; - /** - * Key creation date. - * @type {Date} - */ - this.created = util.normalizeDate(date); - /** - * Public key algorithm. - * @type {enums.publicKey} - */ - this.algorithm = null; - /** - * Algorithm specific public params - * @type {Object} - */ - this.publicParams = null; - /** - * Time until expiration in days (V3 only) - * @type {Integer} - */ - this.expirationTimeV3 = 0; - /** - * Fingerprint bytes - * @type {Uint8Array} - */ - this.fingerprint = null; - /** - * KeyID - * @type {module:type/keyid~KeyID} - */ - this.keyID = null; - } - - /** - * Create a PublicKeyPacket from a SecretKeyPacket - * @param {SecretKeyPacket} secretKeyPacket - key packet to convert - * @returns {PublicKeyPacket} public key packet - * @static - */ - static fromSecretKeyPacket(secretKeyPacket) { - const keyPacket = new PublicKeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * @param {Uint8Array} bytes - Input array to read the packet from - * @returns {Object} This object with attributes set by the parser - * @async - */ - async read(bytes) { - let pos = 0; - // A one-octet version number (3, 4 or 5). - this.version = bytes[pos++]; - - if (this.version === 4 || this.version === 5) { - // - A four-octet number denoting the time that the key was created. - this.created = util.readDate(bytes.subarray(pos, pos + 4)); - pos += 4; - - // - A one-octet number denoting the public-key algorithm of this key. - this.algorithm = bytes[pos++]; - - if (this.version === 5) { - // - A four-octet scalar octet count for the following key material. - pos += 4; - } - - // - A series of values comprising the key material. - const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); - this.publicParams = publicParams; - pos += read; - - // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor - await this.computeFingerprintAndKeyID(); - return pos; - } - throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); - } - - /** - * Creates an OpenPGP public key packet for the given key. - * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. - */ - write() { - const arr = []; - // Version - arr.push(new Uint8Array([this.version])); - arr.push(util.writeDate(this.created)); - // A one-octet number denoting the public-key algorithm of this key - arr.push(new Uint8Array([this.algorithm])); - - const params = mod.serializeParams(this.algorithm, this.publicParams); - if (this.version === 5) { - // A four-octet scalar octet count for the following key material - arr.push(util.writeNumber(params.length, 4)); - } - // Algorithm-specific params - arr.push(params); - return util.concatUint8Array(arr); - } - - /** - * Write packet in order to be hashed; either for a signature or a fingerprint - * @param {Integer} version - target version of signature or key - */ - writeForHash(version) { - const bytes = this.writePublicKey(); - - if (version === 5) { - return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]); - } - return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); - } - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return null; - } - - /** - * Returns the creation time of the key - * @returns {Date} - */ - getCreationTime() { - return this.created; - } - - /** - * Return the key ID of the key - * @returns {module:type/keyid~KeyID} The 8-byte key ID - */ - getKeyID() { - return this.keyID; - } +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - /** - * Computes and set the key ID and fingerprint of the key - * @async - */ - async computeFingerprintAndKeyID() { - await this.computeFingerprint(); - this.keyID = new KeyID(); + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; - if (this.version === 5) { - this.keyID.read(this.fingerprint.subarray(0, 8)); - } else if (this.version === 4) { - this.keyID.read(this.fingerprint.subarray(12, 20)); - } else { - throw new Error('Unsupported key version'); - } - } + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - /** - * Computes and set the fingerprint of the key - */ - async computeFingerprint() { - const toHash = this.writeForHash(this.version); + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - if (this.version === 5) { - this.fingerprint = await mod.hash.sha256(toHash); - } else if (this.version === 4) { - this.fingerprint = await mod.hash.sha1(toHash); - } else { - throw new Error('Unsupported key version'); - } - } + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - /** - * Returns the fingerprint of the key, as an array of bytes - * @returns {Uint8Array} A Uint8Array containing the fingerprint - */ - getFingerprintBytes() { - return this.fingerprint; - } + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} - /** - * Calculates and returns the fingerprint of the key, as a string - * @returns {String} A string containing the fingerprint in lowercase hex - */ - getFingerprint() { - return util.uint8ArrayToHex(this.getFingerprintBytes()); - } +function S(o, a) { + M(o, a, a); +} - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns {Boolean} Whether the two keys have the same version and public key data. - */ - hasSameFingerprintAs(other) { - return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - /** - * Returns algorithm information - * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. - */ - getAlgorithmInfo() { - const result = {}; - result.algorithm = enums.read(enums.publicKey, this.algorithm); - // RSA, DSA or ElGamal public modulo - const modulo = this.publicParams.n || this.publicParams.p; - if (modulo) { - result.bits = util.uint8ArrayBitLength(modulo); - } else if (this.publicParams.oid) { - result.curve = this.publicParams.oid.getName(); - } - return result; +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; } -/** - * Alias of read() - * @see PublicKeyPacket#read - */ -PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; - -/** - * Alias of write() - * @see PublicKeyPacket#write - */ -PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A SE packet can contain the following packet types -const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -/** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ -class SymmetricallyEncryptedDataPacket { - static get tag() { - return enums.packet.symmetricallyEncryptedData; +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; } - - constructor() { - /** - * Encrypted secret-key data - */ - this.encrypted = null; - /** - * Decrypted packets contained within. - * @type {PacketList} - */ - this.packets = null; + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); } - - read(bytes) { - this.encrypted = bytes; + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} - write() { - return this.encrypted; - } +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error - if (!config$1.allowUnauthenticatedMessages) { - throw new Error('Message is not authenticated.'); +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - const encrypted = await readToEnd(clone(this.encrypted)); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, - encrypted.subarray(blockSize + 2), - encrypted.subarray(2, blockSize + 2) - ); - - this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1); - } + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const data = this.packets.write(); - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); - const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); - this.encrypted = util.concat([FRE, ciphertext]); - } -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -// GPG4Browsers - An OpenPGP implementation in javascript + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); -/** - * Implementation of the strange "Marker packet" (Tag 10) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * - * The body of this packet consists of: - * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). - * - * Such a packet MUST be ignored when received. It may be placed at the - * beginning of a message that uses features not available in PGP - * version 2.6 in order to cause that version to report that newer - * software is necessary to process the message. - */ -class MarkerPacket { - static get tag() { - return enums.packet.marker; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Parsing function for a marker data packet (tag 10). - * @param {Uint8Array} bytes - Payload of a tag 10 packet - * @returns {Boolean} whether the packet payload contains "PGP" - */ - read(bytes) { - if (bytes[0] === 0x50 && // P - bytes[1] === 0x47 && // G - bytes[2] === 0x50) { // P - return true; - } - return false; - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - write() { - return new Uint8Array([0x50, 0x47, 0x50]); - } -} + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); -// GPG4Browsers - An OpenPGP implementation in javascript + // add + h = bh3; + l = bl3; -/** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - * @extends PublicKeyPacket - */ -class PublicSubkeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.publicSubkey; - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - // eslint-disable-next-line no-useless-constructor - constructor(date, config) { - super(date, config); - } + h = th; + l = tl; - /** - * Create a PublicSubkeyPacket from a SecretSubkeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert - * @returns {SecretSubkeyPacket} public key packet - * @static - */ - static fromSecretSubkeyPacket(secretSubkeyPacket) { - const keyPacket = new PublicSubkeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -// GPG4Browsers - An OpenPGP implementation in javascript + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -/** - * Implementation of the User Attribute Packet (Tag 17) - * - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ -class UserAttributePacket { - static get tag() { - return enums.packet.userAttribute; - } + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - constructor() { - this.attributes = []; - } + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - /** - * parsing function for a user attribute packet (tag 17). - * @param {Uint8Array} input - Payload of a tag 17 packet - */ - read(bytes) { - let i = 0; - while (i < bytes.length) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); - i += len.len; - } - } + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - /** - * Creates a binary representation of the user attribute packet - * @returns {Uint8Array} String representation. - */ - write() { - const arr = []; - for (let i = 0; i < this.attributes.length; i++) { - arr.push(writeSimpleLength(this.attributes[i].length)); - arr.push(util.stringToUint8Array(this.attributes[i])); - } - return util.concatUint8Array(arr); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - /** - * Compare for equality - * @param {UserAttributePacket} usrAttr - * @returns {Boolean} True if equal. - */ - equals(usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { - return false; - } - return this.attributes.every(function(attr, index) { - return attr === usrAttr.attributes[index]; - }); - } -} + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; -// GPG4Browsers - An OpenPGP implementation in javascript + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -/** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - * @extends PublicKeyPacket - */ -class SecretKeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.secretKey; - } + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - /** - * Secret-key data - */ - this.keyMaterial = null; - /** - * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - this.isEncrypted = null; - /** - * S2K usage - * @type {enums.symmetric} - */ - this.s2kUsage = 0; - /** - * S2K object - * @type {type/s2k} - */ - this.s2k = null; - /** - * Symmetric algorithm to encrypt the key with - * @type {enums.symmetric} - */ - this.symmetric = null; - /** - * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aead = null; - /** - * Decrypted private parameters, referenced by name - * @type {Object} - */ - this.privateParams = null; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // 5.5.3. Secret-Key Packet Formats + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param {Uint8Array} bytes - Input string to read the packet from - * @async - */ - async read(bytes) { - // - A Public-Key or Public-Subkey packet, as described above. - let i = await this.readPublicKey(bytes); - const startOfSecretKeyData = i; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // - One octet indicating string-to-key usage conventions. Zero - // indicates that the secret-key data is not encrypted. 255 or 254 - // indicates that a string-to-key specifier is being given. Any - // other value is a symmetric-key encryption algorithm identifier. - this.s2kUsage = bytes[i++]; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // - Only for a version 5 packet, a one-octet scalar octet count of - // the next 4 optional fields. - if (this.version === 5) { - i++; + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } } - try { - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one-octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - this.symmetric = bytes[i++]; + // add + h = ah0; + l = al0; - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - this.aead = bytes[i++]; - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - this.s2k = new S2K(); - i += this.s2k.read(bytes.subarray(i, bytes.length)); + h = hh[0]; + l = hl[0]; - if (this.s2k.type === 'gnu-dummy') { - return; - } - } else if (this.s2kUsage) { - this.symmetric = this.s2kUsage; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage) { - this.iv = bytes.subarray( - i, - i + mod.getCipher(this.symmetric).blockSize - ); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - i += this.iv.length; - } - } catch (e) { - // if the s2k is unsupported, we still want to support encrypting and verifying with the given key - if (!this.s2kUsage) throw e; // always throw for decrypted keys - this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); - this.isEncrypted = true; - } + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - // - Only for a version 5 packet, a four-octet scalar octet count for - // the following key material. - if (this.version === 5) { - i += 4; - } + h = ah1; + l = al1; - // - Plain or encrypted multiprecision integers comprising the secret - // key data. These algorithm-specific fields are as described - // below. - this.keyMaterial = bytes.subarray(i); - this.isEncrypted = !!this.s2kUsage; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (!this.isEncrypted) { - const cleartext = this.keyMaterial.subarray(0, -2); - if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { - throw new Error('Key checksum mismatch'); - } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - if (err instanceof UnsupportedError) throw err; - // avoid throwing potentially sensitive errors - throw new Error('Error reading MPIs'); - } - } - } + h = hh[1]; + l = hl[1]; - /** - * Creates an OpenPGP key packet for the given key. - * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. - */ - write() { - const serializedPublicKey = this.writePublicKey(); - if (this.unparseableKeyMaterial) { - return util.concatUint8Array([ - serializedPublicKey, - this.unparseableKeyMaterial - ]); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const arr = [serializedPublicKey]; - arr.push(new Uint8Array([this.s2kUsage])); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - const optionalFieldsArr = []; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one- octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - optionalFieldsArr.push(this.symmetric); + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - optionalFieldsArr.push(this.aead); - } + h = ah2; + l = al2; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - optionalFieldsArr.push(...this.s2k.write()); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { - optionalFieldsArr.push(...this.iv); - } + h = hh[2]; + l = hl[2]; - if (this.version === 5) { - arr.push(new Uint8Array([optionalFieldsArr.length])); - } - arr.push(new Uint8Array(optionalFieldsArr)); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - if (!this.isDummy()) { - if (!this.s2kUsage) { - this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - if (this.version === 5) { - arr.push(util.writeNumber(this.keyMaterial.length, 4)); - } - arr.push(this.keyMaterial); + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - if (!this.s2kUsage) { - arr.push(util.writeChecksum(this.keyMaterial)); - } - } + h = ah3; + l = al3; - return util.concatUint8Array(arr); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - /** - * Check whether secret-key data is available in decrypted form. - * Returns false for gnu-dummy keys and null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return this.isEncrypted === false; - } + h = hh[3]; + l = hl[3]; - /** - * Check whether the key includes secret key material. - * Some secret keys do not include it, and can thus only be used - * for public-key operations (encryption and verification). - * Such keys are: - * - GNU-dummy keys, where the secret material has been stripped away - * - encrypted keys with unsupported S2K or cipher - */ - isMissingSecretKeyMaterial() { - return this.unparseableKeyMaterial !== undefined || this.isDummy(); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Check whether this is a gnu-dummy key - * @returns {Boolean} - */ - isDummy() { - return !!(this.s2k && this.s2k.type === 'gnu-dummy'); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - /** - * Remove private key material, converting the key to a dummy one. - * The resulting key cannot be used for signing/decrypting but can still verify signatures. - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - makeDummy(config$1 = config) { - if (this.isDummy()) { - return; - } - if (this.isDecrypted()) { - this.clearPrivateParams(); - } - delete this.unparseableKeyMaterial; - this.isEncrypted = null; - this.keyMaterial = null; - this.s2k = new S2K(config$1); - this.s2k.algorithm = 0; - this.s2k.c = 0; - this.s2k.type = 'gnu-dummy'; - this.s2kUsage = 254; - this.symmetric = enums.symmetric.aes256; - } + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param {String} passphrase - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - if (this.isDummy()) { - return; - } + h = ah4; + l = al4; - if (!this.isDecrypted()) { - throw new Error('Key packet is already encrypted'); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (!passphrase) { - throw new Error('A non-empty passphrase is required for key encryption.'); - } + h = hh[4]; + l = hl[4]; - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - const cleartext = mod.serializeParams(this.algorithm, this.privateParams); - this.symmetric = enums.symmetric.aes256; - const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const { blockSize } = mod.getCipher(this.symmetric); - this.iv = mod.random.getRandomBytes(blockSize); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - if (config$1.aeadProtect) { - this.s2kUsage = 253; - this.aead = enums.aead.eax; - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } else { - this.s2kUsage = 254; - this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ - cleartext, - await mod.hash.sha1(cleartext, config$1) - ]), this.iv, config$1); - } - } + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); - /** - * Decrypts the private key params which are needed to use the key. - * Successful decryption does not imply key integrity, call validate() to confirm that. - * {@link SecretKeyPacket.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param {String} passphrase - The passphrase for this private key as string - * @throws {Error} if the key is already decrypted, or if decryption was not successful - * @async - */ - async decrypt(passphrase) { - if (this.isDummy()) { - return false; - } + h = ah5; + l = al5; - if (this.unparseableKeyMaterial) { - throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this.isDecrypted()) { - throw new Error('Key packet is already decrypted.'); - } + h = hh[5]; + l = hl[5]; - let key; - if (this.s2kUsage === 254 || this.s2kUsage === 253) { - key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2kUsage === 255) { - throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); - } else { - throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - let cleartext; - if (this.s2kUsage === 253) { - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - try { - cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } catch (err) { - if (err.message === 'Authentication tag mismatch') { - throw new Error('Incorrect key passphrase: ' + err.message); - } - throw err; - } - } else { - const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; - cleartext = cleartextWithHash.subarray(0, -20); - const hash = await mod.hash.sha1(cleartext); + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { - throw new Error('Incorrect key passphrase'); - } - } + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - throw new Error('Error reading MPIs'); - } - this.isEncrypted = false; - this.keyMaterial = null; - this.s2kUsage = 0; - } + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; - /** - * Checks that the key parameters are consistent - * @throws {Error} if validation was not successful - * @async - */ - async validate() { - if (this.isDummy()) { - return; - } + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; - if (!this.isDecrypted()) { - throw new Error('Key is not decrypted'); - } + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); - let validParams; - try { - // this can throw if some parameters are undefined - validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); - } catch (_) { - validParams = false; - } - if (!validParams) { - throw new Error('Key is invalid'); - } - } + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - async generate(bits, curve) { - const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); - this.privateParams = privateParams; - this.publicParams = publicParams; - this.isEncrypted = false; + return 0; +} + +function add$1(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); } +} - /** - * Clear private key parameters - */ - clearPrivateParams() { - if (this.isMissingSecretKeyMaterial()) { - return; - } +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} - Object.keys(this.privateParams).forEach(name => { - const param = this.privateParams[name]; - param.fill(0); - delete this.privateParams[name]; - }); - this.privateParams = null; - this.isEncrypted = true; +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add$1(q, p); + add$1(p, p); + cswap(p, q, b); } } -async function produceEncryptionKey(s2k, passphrase, algorithm) { - const { keySize } = mod.getCipher(algorithm); - return s2k.produceKey(passphrase, keySize); +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); } -var emailAddresses = createCommonjsModule(function (module) { -// email-addresses.js - RFC 5322 email address parser -// v 3.1.0 -// -// http://tools.ietf.org/html/rfc5322 -// -// This library does not validate email addresses. -// emailAddresses attempts to parse addresses using the (fairly liberal) -// grammar specified in RFC 5322. -// -// email-addresses returns { -// ast: , -// addresses: [{ -// node: , -// name: , -// address: , -// local: , -// domain: -// }, ...] -// } -// -// emailAddresses.parseOneAddress and emailAddresses.parseAddressList -// work as you might expect. Try it out. -// -// Many thanks to Dominic Sayers and his documentation on the is_email function, -// http://code.google.com/p/isemail/ , which helped greatly in writing this parser. +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; -(function (global) { + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; -function parse5322(opts) { + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} - // tokenizing functions +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - function inStr() { return pos < len; } - function curTok() { return parseString[pos]; } - function getPos() { return pos; } - function setPos(i) { pos = i; } - function nextTok() { pos += 1; } - function initialize() { - pos = 0; - len = parseString.length; +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} - // parser helper functions +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} - function o(name, value) { - return { - name: name, - tokens: value || "", - semantic: value || "", - children: [] - }; - } +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - function wrap(name, ast) { - var n; - if (ast === null) { return null; } - n = o(name); - n.tokens = ast.tokens; - n.semantic = ast.semantic; - n.children.push(ast); - return n; - } + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - function add(parent, child) { - if (child !== null) { - parent.tokens += child.tokens; - parent.semantic += child.semantic; - } - parent.children.push(child); - return parent; - } + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - function compareToken(fxnCompare) { - var tok; - if (!inStr()) { return null; } - tok = curTok(); - if (fxnCompare(tok)) { - nextTok(); - return o('token', tok); - } - return null; - } + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - function literal(lit) { - return function literalFunc() { - return wrap('literal', compareToken(function (tok) { - return tok === lit; - })); - }; - } + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - function and() { - var args = arguments; - return function andFunc() { - var i, s, result, start; - start = getPos(); - s = o('and'); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result === null) { - setPos(start); - return null; - } - add(s, result); - } - return s; - }; + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; } + } - function or() { - var args = arguments; - return function orFunc() { - var i, result, start; - start = getPos(); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result !== null) { - return result; - } - setPos(start); - } - return null; - }; - } + modL(sm.subarray(32), x); + return smlen; +} - function opt(prod) { - return function optFunc() { - var result, start; - start = getPos(); - result = prod(); - if (result !== null) { - return result; - } - else { - setPos(start); - return o('opt'); - } - }; - } +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - function invis(prod) { - return function invisFunc() { - var result = prod(); - if (result !== null) { - result.semantic = ""; - } - return result; - }; - } + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - function colwsp(prod) { - return function collapseSemanticWhitespace() { - var result = prod(); - if (result !== null && result.semantic.length > 0) { - result.semantic = " "; - } - return result; - }; - } + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); - function star(prod, minimum) { - return function starFunc() { - var s, result, count, start, min; - start = getPos(); - s = o('star'); - count = 0; - min = minimum === undefined ? 0 : minimum; - while ((result = prod()) !== null) { - count = count + 1; - add(s, result); - } - if (count >= min) { - return s; - } - else { - setPos(start); - return null; - } - }; - } + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); - // One expects names to get normalized like this: - // " First Last " -> "First Last" - // "First Last" -> "First Last" - // "First Last" -> "First Last" - function collapseWhitespace(s) { - return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, ''); - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - // UTF-8 pseudo-production (RFC 6532) - // RFC 6532 extends RFC 5322 productions to include UTF-8 - // using the following productions: - // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // UTF8-2 = - // UTF8-3 = - // UTF8-4 = - // - // For reference, the extended RFC 5322 productions are: - // VCHAR =/ UTF8-non-ascii - // ctext =/ UTF8-non-ascii - // atext =/ UTF8-non-ascii - // qtext =/ UTF8-non-ascii - // dtext =/ UTF8-non-ascii - function isUTF8NonAscii(tok) { - // In JavaScript, we just deal directly with Unicode code points, - // so we aren't checking individual bytes for UTF-8 encoding. - // Just check that the character is non-ascii. - return tok.charCodeAt(0) >= 128; - } - - - // common productions (RFC 5234) - // http://tools.ietf.org/html/rfc5234 - // B.1. Core Rules - - // CR = %x0D - // ; carriage return - function cr() { return wrap('cr', literal('\r')()); } - - // CRLF = CR LF - // ; Internet standard newline - function crlf() { return wrap('crlf', and(cr, lf)()); } - - // DQUOTE = %x22 - // ; " (Double Quote) - function dquote() { return wrap('dquote', literal('"')()); } - - // HTAB = %x09 - // ; horizontal tab - function htab() { return wrap('htab', literal('\t')()); } - - // LF = %x0A - // ; linefeed - function lf() { return wrap('lf', literal('\n')()); } - - // SP = %x20 - function sp() { return wrap('sp', literal(' ')()); } - - // VCHAR = %x21-7E - // ; visible (printing) characters - function vchar() { - return wrap('vchar', compareToken(function vcharFunc(tok) { - var code = tok.charCodeAt(0); - var accept = (0x21 <= code && code <= 0x7E); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} - // WSP = SP / HTAB - // ; white space - function wsp() { return wrap('wsp', or(sp, htab)()); } - - - // email productions (RFC 5322) - // http://tools.ietf.org/html/rfc5322 - // 3.2.1. Quoted characters - - // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp - function quotedPair() { - var qp = wrap('quoted-pair', - or( - and(literal('\\'), or(vchar, wsp)), - obsQP - )()); - if (qp === null) { return null; } - // a quoted pair will be two characters, and the "\" character - // should be semantically "invisible" (RFC 5322 3.2.1) - qp.semantic = qp.semantic[1]; - return qp; - } - - // 3.2.2. Folding White Space and Comments - - // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS - function fws() { - return wrap('fws', or( - obsFws, - and( - opt(and( - star(wsp), - invis(crlf) - )), - star(wsp, 1) - ) - )()); - } - - // ctext = %d33-39 / ; Printable US-ASCII - // %d42-91 / ; characters not including - // %d93-126 / ; "(", ")", or "\" - // obs-ctext - function ctext() { - return wrap('ctext', or( - function ctextFunc1() { - return compareToken(function ctextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 39) || - (42 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsCtext - )()); - } - - // ccontent = ctext / quoted-pair / comment - function ccontent() { - return wrap('ccontent', or(ctext, quotedPair, comment)()); - } - - // comment = "(" *([FWS] ccontent) [FWS] ")" - function comment() { - return wrap('comment', and( - literal('('), - star(and(opt(fws), ccontent)), - opt(fws), - literal(')') - )()); - } - - // CFWS = (1*([FWS] comment) [FWS]) / FWS - function cfws() { - return wrap('cfws', or( - and( - star( - and(opt(fws), comment), - 1 - ), - opt(fws) - ), - fws - )()); - } - - // 3.2.3. Atom - - //atext = ALPHA / DIGIT / ; Printable US-ASCII - // "!" / "#" / ; characters not including - // "$" / "%" / ; specials. Used for atoms. - // "&" / "'" / - // "*" / "+" / - // "-" / "/" / - // "=" / "?" / - // "^" / "_" / - // "`" / "{" / - // "|" / "}" / - // "~" - function atext() { - return wrap('atext', compareToken(function atextFunc(tok) { - var accept = - ('a' <= tok && tok <= 'z') || - ('A' <= tok && tok <= 'Z') || - ('0' <= tok && tok <= '9') || - (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', - '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - // atom = [CFWS] 1*atext [CFWS] - function atom() { - return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))()); - } + if (n < 64) return -1; - // dot-atom-text = 1*atext *("." 1*atext) - function dotAtomText() { - var s, maybeText; - s = wrap('dot-atom-text', star(atext, 1)()); - if (s === null) { return s; } - maybeText = star(and(literal('.'), star(atext, 1)))(); - if (maybeText !== null) { - add(s, maybeText); - } - return s; - } - - // dot-atom = [CFWS] dot-atom-text [CFWS] - function dotAtom() { - return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))()); - } - - // 3.2.4. Quoted Strings - - // qtext = %d33 / ; Printable US-ASCII - // %d35-91 / ; characters not including - // %d93-126 / ; "\" or the quote character - // obs-qtext - function qtext() { - return wrap('qtext', or( - function qtextFunc1() { - return compareToken(function qtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 === code) || - (35 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsQtext - )()); - } + if (unpackneg(q, pk)) return -1; - // qcontent = qtext / quoted-pair - function qcontent() { - return wrap('qcontent', or(qtext, quotedPair)()); - } + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - // quoted-string = [CFWS] - // DQUOTE *([FWS] qcontent) [FWS] DQUOTE - // [CFWS] - function quotedString() { - return wrap('quoted-string', and( - invis(opt(cfws)), - invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), - invis(opt(cfws)) - )()); - } + scalarbase(q, sm.subarray(32)); + add$1(p, q); + pack(t, p); - // 3.2.5 Miscellaneous Tokens + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } - // word = atom / quoted-string - function word() { - return wrap('word', or(atom, quotedString)()); - } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} - // phrase = 1*word / obs-phrase - function phrase() { - return wrap('phrase', or(obsPhrase, star(word, 1))()); - } +var crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32; - // 3.4. Address Specification - // address = mailbox / group - function address() { - return wrap('address', or(mailbox, group)()); - } +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} - // mailbox = name-addr / addr-spec - function mailbox() { - return wrap('mailbox', or(nameAddr, addrSpec)()); - } +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} - // name-addr = [display-name] angle-addr - function nameAddr() { - return wrap('name-addr', and(opt(displayName), angleAddr)()); - } +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; - // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / - // obs-angle-addr - function angleAddr() { - return wrap('angle-addr', or( - and( - invis(opt(cfws)), - literal('<'), - addrSpec, - literal('>'), - invis(opt(cfws)) - ), - obsAngleAddr - )()); - } +nacl.box = {}; - // group = display-name ":" [group-list] ";" [CFWS] - function group() { - return wrap('group', and( - displayName, - literal(':'), - opt(groupList), - literal(';'), - invis(opt(cfws)) - )()); - } +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - // display-name = phrase - function displayName() { - return wrap('display-name', function phraseFixedSemantic() { - var result = phrase(); - if (result !== null) { - result.semantic = collapseWhitespace(result.semantic); - } - return result; - }()); - } - - // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list - function mailboxList() { - return wrap('mailbox-list', or( - and( - mailbox, - star(and(literal(','), mailbox)) - ), - obsMboxList - )()); - } - - // address-list = (address *("," address)) / obs-addr-list - function addressList() { - return wrap('address-list', or( - and( - address, - star(and(literal(','), address)) - ), - obsAddrList - )()); - } - - // group-list = mailbox-list / CFWS / obs-group-list - function groupList() { - return wrap('group-list', or( - mailboxList, - invis(cfws), - obsGroupList - )()); - } - - // 3.4.1 Addr-Spec Specification - - // local-part = dot-atom / quoted-string / obs-local-part - function localPart() { - // note: quoted-string, dotAtom are proper subsets of obs-local-part - // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree - return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)()); - } - - // dtext = %d33-90 / ; Printable US-ASCII - // %d94-126 / ; characters not including - // obs-dtext ; "[", "]", or "\" - function dtext() { - return wrap('dtext', or( - function dtextFunc1() { - return compareToken(function dtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 90) || - (94 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsDtext - )() - ); - } +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - function domainLiteral() { - return wrap('domain-literal', and( - invis(opt(cfws)), - literal('['), - star(and(opt(fws), dtext)), - opt(fws), - literal(']'), - invis(opt(cfws)) - )()); - } - - // domain = dot-atom / domain-literal / obs-domain - function domain() { - return wrap('domain', function domainCheckTLD() { - var result = or(obsDomain, dotAtom, domainLiteral)(); - if (opts.rejectTLD) { - if (result && result.semantic && result.semantic.indexOf('.') < 0) { - return null; - } - } - // strip all whitespace from domains - if (result) { - result.semantic = result.semantic.replace(/\s+/g, ''); - } - return result; - }()); - } - - // addr-spec = local-part "@" domain - function addrSpec() { - return wrap('addr-spec', and( - localPart, literal('@'), domain - )()); - } - - // 3.6.2 Originator Fields - // Below we only parse the field body, not the name of the field - // like "From:", "Sender:", or "Reply-To:". Other libraries that - // parse email headers can parse those and defer to these productions - // for the "RFC 5322" part. - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // from = "From:" (mailbox-list / address-list) CRLF - function fromSpec() { - return wrap('from', or( - mailboxList, - addressList - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // sender = "Sender:" (mailbox / address) CRLF - function senderSpec() { - return wrap('sender', or( - mailbox, - address - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // reply-to = "Reply-To:" address-list CRLF - function replyToSpec() { - return wrap('reply-to', addressList()); - } - - // 4.1. Miscellaneous Obsolete Tokens - - // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control - // %d11 / ; characters that do not - // %d12 / ; include the carriage - // %d14-31 / ; return, line feed, and - // %d127 ; white space characters - function obsNoWsCtl() { - return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) { - var code = tok.charCodeAt(0); - return ((1 <= code && code <= 8) || - (11 === code || 12 === code) || - (14 <= code && code <= 31) || - (127 === code)); - })); - } +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; - // obs-ctext = obs-NO-WS-CTL - function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); } - - // obs-qtext = obs-NO-WS-CTL - function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); } - - // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) - function obsQP() { - return opts.strict ? null : wrap('obs-qp', and( - literal('\\'), - or(literal('\0'), obsNoWsCtl, lf, cr) - )()); - } - - // obs-phrase = word *(word / "." / CFWS) - function obsPhrase() { - if (opts.strict ) return null; - return opts.atInDisplayName ? wrap('obs-phrase', and( - word, - star(or(word, literal('.'), literal('@'), colwsp(cfws))) - )()) : - wrap('obs-phrase', and( - word, - star(or(word, literal('.'), colwsp(cfws))) - )()); - } - - // 4.2. Obsolete Folding White Space - - // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908 - // obs-FWS = 1*([CRLF] WSP) - function obsFws() { - return opts.strict ? null : wrap('obs-FWS', star( - and(invis(opt(crlf)), wsp), - 1 - )()); - } - - // 4.4. Obsolete Addressing - - // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] - function obsAngleAddr() { - return opts.strict ? null : wrap('obs-angle-addr', and( - invis(opt(cfws)), - literal('<'), - obsRoute, - addrSpec, - literal('>'), - invis(opt(cfws)) - )()); - } - - // obs-route = obs-domain-list ":" - function obsRoute() { - return opts.strict ? null : wrap('obs-route', and( - obsDomainList, - literal(':') - )()); - } - - // obs-domain-list = *(CFWS / ",") "@" domain - // *("," [CFWS] ["@" domain]) - function obsDomainList() { - return opts.strict ? null : wrap('obs-domain-list', and( - star(or(invis(cfws), literal(','))), - literal('@'), - domain, - star(and( - literal(','), - invis(opt(cfws)), - opt(and(literal('@'), domain)) - )) - )()); - } - - // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) - function obsMboxList() { - return opts.strict ? null : wrap('obs-mbox-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - mailbox, - star(and( - literal(','), - opt(and( - mailbox, - invis(cfws) - )) - )) - )()); - } - - // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) - function obsAddrList() { - return opts.strict ? null : wrap('obs-addr-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - address, - star(and( - literal(','), - opt(and( - address, - invis(cfws) - )) - )) - )()); - } - - // obs-group-list = 1*([CFWS] ",") [CFWS] - function obsGroupList() { - return opts.strict ? null : wrap('obs-group-list', and( - star(and( - invis(opt(cfws)), - literal(',') - ), 1), - invis(opt(cfws)) - )()); - } - - // obs-local-part = word *("." word) - function obsLocalPart() { - return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))()); - } - - // obs-domain = atom *("." atom) - function obsDomain() { - return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))()); - } - - // obs-dtext = obs-NO-WS-CTL / quoted-pair - function obsDtext() { - return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)()); - } - - ///////////////////////////////////////////////////// - - // ast analysis - - function findNode(name, root) { - var i, stack, node; - if (root === null || root === undefined) { return null; } - stack = [root]; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - return node; - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return null; - } - - function findAllNodes(name, root) { - var i, stack, node, result; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - result.push(node); - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return result; - } +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; - function findAllNodesNoChildren(names, root) { - var i, stack, node, result, namesLookup; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - namesLookup = {}; - for (i = 0; i < names.length; i += 1) { - namesLookup[names[i]] = true; - } +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; - while (stack.length > 0) { - node = stack.pop(); - if (node.name in namesLookup) { - result.push(node); - // don't look at children (hence findAllNodesNoChildren) - } else { - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - } - return result; - } +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - function giveResult(ast) { - var addresses, groupsAndMailboxes, i, groupOrMailbox, result; - if (ast === null) { - return null; - } - addresses = []; - - // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'. - groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast); - for (i = 0; i < groupsAndMailboxes.length; i += 1) { - groupOrMailbox = groupsAndMailboxes[i]; - if (groupOrMailbox.name === 'group') { - addresses.push(giveResultGroup(groupOrMailbox)); - } else if (groupOrMailbox.name === 'mailbox') { - addresses.push(giveResultMailbox(groupOrMailbox)); - } - } +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - result = { - ast: ast, - addresses: addresses, - }; - if (opts.simple) { - result = simplifyResult(result); - } - if (opts.oneResult) { - return oneResult(result); - } - if (opts.simple) { - return result && result.addresses; - } else { - return result; - } - } +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; - function giveResultGroup(group) { - var i; - var groupName = findNode('display-name', group); - var groupResultMailboxes = []; - var mailboxes = findAllNodesNoChildren(['mailbox'], group); - for (i = 0; i < mailboxes.length; i += 1) { - groupResultMailboxes.push(giveResultMailbox(mailboxes[i])); - } - return { - node: group, - parts: { - name: groupName, - }, - type: group.name, // 'group' - name: grabSemantic(groupName), - addresses: groupResultMailboxes, - }; - } +nacl.setPRNG = function(fn) { + randombytes = fn; +}; - function giveResultMailbox(mailbox) { - var name = findNode('display-name', mailbox); - var aspec = findNode('addr-spec', mailbox); - var cfws = findAllNodes('cfws', mailbox); - var comments = findAllNodesNoChildren(['comment'], mailbox); +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + if (crypto$3 && crypto$3.getRandomValues) { + // Browsers and Node v16+ + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto$3.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } +})(); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - var local = findNode('local-part', aspec); - var domain = findNode('domain', aspec); - return { - node: mailbox, - parts: { - name: name, - address: aspec, - local: local, - domain: domain, - comments: cfws - }, - type: mailbox.name, // 'mailbox' - name: grabSemantic(name), - address: grabSemantic(aspec), - local: grabSemantic(local), - domain: grabSemantic(domain), - comments: concatComments(comments), - groupName: grabSemantic(mailbox.groupName), - }; - } - function grabSemantic(n) { - return n !== null && n !== undefined ? n.semantic : null; - } +const knownOIDs = { + '2a8648ce3d030107': enums.curve.nistP256, + '2b81040022': enums.curve.nistP384, + '2b81040023': enums.curve.nistP521, + '2b8104000a': enums.curve.secp256k1, + '2b06010401da470f01': enums.curve.ed25519Legacy, + '2b060104019755010501': enums.curve.curve25519Legacy, + '2b2403030208010107': enums.curve.brainpoolP256r1, + '2b240303020801010b': enums.curve.brainpoolP384r1, + '2b240303020801010d': enums.curve.brainpoolP512r1 +}; - function simplifyResult(result) { - var i; - if (result && result.addresses) { - for (i = 0; i < result.addresses.length; i += 1) { - delete result.addresses[i].node; - } +class OID { + constructor(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (util.isArray(oid) || + util.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { // DER encoded oid byte array + if (oid[1] !== oid.length - 2) { + throw new Error('Length mismatch in DER encoded oid'); } - return result; + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; } + } - function concatComments(comments) { - var result = ''; - if (comments) { - for (var i = 0; i < comments.length; i += 1) { - result += grabSemantic(comments[i]); - } - } - return result; + /** + * Method to read an OID object + * @param {Uint8Array} input - Where to read the OID from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } } + throw new Error('Invalid oid'); + } + + /** + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID. + */ + write() { + return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); + } + + /** + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID. + */ + toHex() { + return util.uint8ArrayToHex(this.oid); + } - function oneResult(result) { - if (!result) { return null; } - if (!opts.partial && result.addresses.length > 1) { return null; } - return result.addresses && result.addresses[0]; + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns {enums.curve} String with the canonical name of the curve + * @throws if unknown + */ + getName() { + const name = knownOIDs[this.toHex()]; + if (!name) { + throw new Error('Unknown curve object identifier.'); } - ///////////////////////////////////////////////////// + return name; + } +} - var parseString, pos, len, parsed, startProduction; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - opts = handleOpts(opts, {}); - if (opts === null) { return null; } - parseString = opts.input; +function readSimpleLength(bytes) { + let len = 0; + let offset; + const type = bytes[0]; - startProduction = { - 'address': address, - 'address-list': addressList, - 'angle-addr': angleAddr, - 'from': fromSpec, - 'group': group, - 'mailbox': mailbox, - 'mailbox-list': mailboxList, - 'reply-to': replyToSpec, - 'sender': senderSpec, - }[opts.startAt] || addressList; - if (!opts.strict) { - initialize(); - opts.strict = true; - parsed = startProduction(parseString); - if (opts.partial || !inStr()) { - return giveResult(parsed); - } - opts.strict = false; - } + if (type < 192) { + [len] = bytes; + offset = 1; + } else if (type < 255) { + len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; + offset = 2; + } else if (type === 255) { + len = util.readNumber(bytes.subarray(1, 1 + 4)); + offset = 5; + } - initialize(); - parsed = startProduction(parseString); - if (!opts.partial && inStr()) { return null; } - return giveResult(parsed); + return { + len: len, + offset: offset + }; } -function parseOneAddressSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'address-list', - })); +/** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * + * @param {Integer} length - The length to encode + * @returns {Uint8Array} String with openpgp length representation. + */ +function writeSimpleLength(length) { + if (length < 192) { + return new Uint8Array([length]); + } else if (length > 191 && length < 8384) { + /* + * let a = (total data packet length) - 192 let bc = two octet + * representation of a let d = b + 192 + */ + return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); + } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); } -function parseAddressListSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'address-list', - })); +function writePartialLength(power) { + if (power < 0 || power > 30) { + throw new Error('Partial Length power must be between 1 and 30'); + } + return new Uint8Array([224 + power]); } -function parseFromSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'from', - })); +function writeTag(tag_type) { + /* we're only generating v4 packet headers here */ + return new Uint8Array([0xC0 | tag_type]); } -function parseSenderSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'sender', - })); +/** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * + * @param {Integer} tag_type - Tag type + * @param {Integer} length - Length of the payload + * @returns {String} String of the header. + */ +function writeHeader(tag_type, length) { + /* we're only generating v4 packet headers here */ + return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); } -function parseReplyToSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'reply-to', - })); +/** + * Whether the packet type supports partial lengths per RFC4880 + * @param {Integer} tag - Tag type + * @returns {Boolean} String of the header. + */ +function supportsStreaming(tag) { + return [ + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ].includes(tag); } -function handleOpts(opts, defs) { - function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; +/** + * Generic static Packet Parser function + * + * @param {Uint8Array | ReadableStream} input - Input stream as string + * @param {Function} callback - Function to call with the parsed packet + * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. + */ +async function readPackets(input, callback) { + const reader = getReader(input); + let writer; + let callbackReturned; + try { + const peekedBytes = await reader.peekBytes(2); + // some sanity checks + if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { + throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); } + const headerByte = await reader.readByte(); + let tag = -1; + let format = -1; + let packetLength; - function isObject(o) { - return o === Object(o); + format = 0; // 0 = old format; 1 = new format + if ((headerByte & 0x40) !== 0) { + format = 1; } - function isNullUndef(o) { - return o === null || o === undefined; + let packetLengthType; + if (format) { + // new format header + tag = headerByte & 0x3F; // bit 5-0 + } else { + // old format header + tag = (headerByte & 0x3F) >> 2; // bit 5-2 + packetLengthType = headerByte & 0x03; // bit 1-0 } - var defaults, o; - - if (isString(opts)) { - opts = { input: opts }; - } else if (!isObject(opts)) { - return null; + const packetSupportsStreaming = supportsStreaming(tag); + let packet = null; + if (packetSupportsStreaming) { + if (util.isStream(input) === 'array') { + const arrayStream = new ArrayStream(); + writer = getWriter(arrayStream); + packet = arrayStream; + } else { + const transform = new TransformStream(); + writer = getWriter(transform.writable); + packet = transform.readable; + } + // eslint-disable-next-line callback-return + callbackReturned = callback({ tag, packet }); + } else { + packet = []; } - if (!isString(opts.input)) { return null; } - if (!defs) { return null; } - - defaults = { - oneResult: false, - partial: false, - rejectTLD: false, - rfc6532: false, - simple: false, - startAt: 'address-list', - strict: false, - atInDisplayName: false - }; - - for (o in defaults) { - if (isNullUndef(opts[o])) { - opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o]; + let wasPartialLength; + do { + if (!format) { + // 4.2.1. Old Format Packet Lengths + switch (packetLengthType) { + case 0: + // The packet has a one-octet length. The header is 2 octets + // long. + packetLength = await reader.readByte(); + break; + case 1: + // The packet has a two-octet length. The header is 3 octets + // long. + packetLength = (await reader.readByte() << 8) | await reader.readByte(); + break; + case 2: + // The packet has a four-octet length. The header is 5 + // octets long. + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + break; + default: + // 3 - The packet is of indeterminate length. The header is 1 + // octet long, and the implementation must determine how long + // the packet is. If the packet is in a file, this means that + // the packet extends until the end of the file. In general, + // an implementation SHOULD NOT use indeterminate-length + // packets except where the end of the data will be clear + // from the context, and even then it is better to use a + // definite length, or a new format header. The new format + // headers described below have a mechanism for precisely + // encoding data of indeterminate length. + packetLength = Infinity; + break; } - } - return opts; -} - -parse5322.parseOneAddress = parseOneAddressSimple; -parse5322.parseAddressList = parseAddressListSimple; -parse5322.parseFrom = parseFromSimple; -parse5322.parseSender = parseSenderSimple; -parse5322.parseReplyTo = parseReplyToSimple; - -{ - module.exports = parse5322; -} - -}()); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the User ID Packet (Tag 13) - * - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. - */ -class UserIDPacket { - static get tag() { - return enums.packet.userID; - } - - constructor() { - /** A string containing the user id. Usually in the form - * John Doe - * @type {String} - */ - this.userID = ''; - - this.name = ''; - this.email = ''; - this.comment = ''; - } + } else { // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + const lengthByte = await reader.readByte(); + wasPartialLength = false; + if (lengthByte < 192) { + packetLength = lengthByte; + // 4.2.2.2. Two-Octet Lengths + } else if (lengthByte >= 192 && lengthByte < 224) { + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + // 4.2.2.4. Partial Body Lengths + } else if (lengthByte > 223 && lengthByte < 255) { + packetLength = 1 << (lengthByte & 0x1F); + wasPartialLength = true; + if (!packetSupportsStreaming) { + throw new TypeError('This packet type does not support partial lengths.'); + } + // 4.2.2.3. Five-Octet Lengths + } else { + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + } + } + if (packetLength > 0) { + let bytesRead = 0; + while (true) { + if (writer) await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (packetLength === Infinity) break; + throw new Error('Unexpected end of packet'); + } + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); + if (writer) await writer.write(chunk); + else packet.push(chunk); + bytesRead += value.length; + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); + break; + } + } + } + } while (wasPartialLength); - /** - * Create UserIDPacket instance from object - * @param {Object} userID - Object specifying userID name, email and comment - * @returns {UserIDPacket} - * @static - */ - static fromObject(userID) { - if (util.isString(userID) || - (userID.name && !util.isString(userID.name)) || - (userID.email && !util.isEmailAddress(userID.email)) || - (userID.comment && !util.isString(userID.comment))) { - throw new Error('Invalid user ID format'); + // If this was not a packet that "supports streaming", we peek to check + // whether it is the last packet in the message. We peek 2 bytes instead + // of 1 because the beginning of this function also peeks 2 bytes, and we + // want to cut a `subarray` of the correct length into `web-stream-tools`' + // `externalBuffer` as a tiny optimization here. + // + // If it *was* a streaming packet (i.e. the data packets), we peek at the + // entire remainder of the stream, in order to forward errors in the + // remainder of the stream to the packet data. (Note that this means we + // read/peek at all signature packets before closing the literal data + // packet, for example.) This forwards MDC errors to the literal data + // stream, for example, so that they don't get lost / forgotten on + // decryptedMessage.packets.stream, which we never look at. + // + // An example of what we do when stream-parsing a message containing + // [ one-pass signature packet, literal data packet, signature packet ]: + // 1. Read the one-pass signature packet + // 2. Peek 2 bytes of the literal data packet + // 3. Parse the one-pass signature packet + // + // 4. Read the literal data packet, simultaneously stream-parsing it + // 5. Peek until the end of the message + // 6. Finish parsing the literal data packet + // + // 7. Read the signature packet again (we already peeked at it in step 5) + // 8. Peek at the end of the stream again (`peekBytes` returns undefined) + // 9. Parse the signature packet + // + // Note that this means that if there's an error in the very end of the + // stream, such as an MDC error, we throw in step 5 instead of in step 8 + // (or never), which is the point of this exercise. + const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); + if (writer) { + await writer.ready; + await writer.close(); + } else { + packet = util.concatUint8Array(packet); + // eslint-disable-next-line callback-return + await callback({ tag, packet }); } - const packet = new UserIDPacket(); - Object.assign(packet, userID); - const components = []; - if (packet.name) components.push(packet.name); - if (packet.comment) components.push(`(${packet.comment})`); - if (packet.email) components.push(`<${packet.email}>`); - packet.userID = components.join(' '); - return packet; - } - - /** - * Parsing function for a user id packet (tag 13). - * @param {Uint8Array} input - Payload of a tag 13 packet - */ - read(bytes, config$1 = config) { - const userID = util.decodeUTF8(bytes); - if (userID.length > config$1.maxUserIDLength) { - throw new Error('User ID string is too long'); + return !nextPacket || !nextPacket.length; + } catch (e) { + if (writer) { + await writer.abort(e); + return true; + } else { + throw e; } - try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); - this.comment = comments.replace(/^\(|\)$/g, ''); - this.name = name; - this.email = email; - } catch (e) {} - this.userID = userID; - } - - /** - * Creates a binary representation of the user id packet - * @returns {Uint8Array} Binary representation. - */ - write() { - return util.encodeUTF8(this.userID); - } - - equals(otherUserID) { - return otherUserID && otherUserID.userID === this.userID; + } finally { + if (writer) { + await callbackReturned; + } + reader.releaseLock(); } } -// GPG4Browsers - An OpenPGP implementation in javascript +class UnsupportedError extends Error { + constructor(...params) { + super(...params); -/** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - * @extends SecretKeyPacket - */ -class SecretSubkeyPacket extends SecretKeyPacket { - static get tag() { - return enums.packet.secretSubkey; - } + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); + } - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); + this.name = 'UnsupportedError'; } } -/** - * Implementation of the Trust Packet (Tag 12) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. - * - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. - */ -class TrustPacket { - static get tag() { - return enums.packet.trust; - } +// unknown packet types are handled differently depending on the packet criticality +class UnknownPacketError extends UnsupportedError { + constructor(...params) { + super(...params); - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - */ - read() { - throw new UnsupportedError('Trust packets are not supported'); - } + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); + } - write() { - throw new UnsupportedError('Trust packets are not supported'); + this.name = 'UnknownPacketError'; } } -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Signature can contain the following packets -const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - -/** - * Class that represents an OpenPGP signature. - */ -class Signature { - /** - * @param {PacketList} packetlist - The signature packets - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); +class UnparseablePacket { + constructor(tag, rawContent) { + this.tag = tag; + this.rawContent = rawContent; } - /** - * Returns binary encoded signature - * @returns {ReadableStream} Binary signature. - */ write() { - return this.packets.write(); - } - - /** - * Returns ASCII armored text of signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1); - } - - /** - * Returns an array of KeyIDs of all of the issuers who created this signature - * @returns {Array} The Key IDs of the signing keys - */ - getSigningKeyIDs() { - return this.packets.map(packet => packet.issuerKeyID); - } -} - -/** - * reads an (optionally armored) OpenPGP signature and returns a signature object - * @param {Object} options - * @param {String} [options.armoredSignature] - Armored signature to be parsed - * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New signature object. - * @async - * @static - */ -async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredSignature || binarySignature; - if (!input) { - throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); - } - if (armoredSignature && !util.isString(armoredSignature)) { - throw new Error('readSignature: options.armoredSignature must be a string'); - } - if (binarySignature && !util.isUint8Array(binarySignature)) { - throw new Error('readSignature: options.binarySignature must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (armoredSignature) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.signature) { - throw new Error('Armored text not of type signature'); - } - input = data; - } - const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1); - return new Signature(packetlist); -} - -/** - * @fileoverview Provides helpers methods for key module - * @module key/helper - * @private - */ - -async function generateSecretSubkey(options, config) { - const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); - secretSubkeyPacket.packets = null; - secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretSubkeyPacket.generate(options.rsaBits, options.curve); - await secretSubkeyPacket.computeFingerprintAndKeyID(); - return secretSubkeyPacket; -} - -async function generateSecretKey(options, config) { - const secretKeyPacket = new SecretKeyPacket(options.date, config); - secretKeyPacket.packets = null; - secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); - await secretKeyPacket.computeFingerprintAndKeyID(); - return secretKeyPacket; -} - -/** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param {Array} signatures - List of signatures - * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - full configuration - * @returns {Promise} The latest valid signature. - * @async - */ -async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { - let latestValid; - let exception; - for (let i = signatures.length - 1; i >= 0; i--) { - try { - if ( - (!latestValid || signatures[i].created >= latestValid.created) - ) { - await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); - latestValid = signatures[i]; - } - } catch (e) { - exception = e; - } - } - if (!latestValid) { - throw util.wrapError( - `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` - .replace('certGeneric ', 'self-') - .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), - exception); + return this.rawContent; } - return latestValid; } -function isDataExpired(keyPacket, signature, date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - const expirationTime = getKeyExpirationTime(keyPacket, signature); - return !(keyPacket.created <= normDate && normDate < expirationTime); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + +/** + * Generate (non-legacy) EdDSA key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} + */ +async function generate$3(algo) { + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']); + + const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey); + + return { + A: new Uint8Array(b64ToUint8Array(publicKey.x)), + seed: b64ToUint8Array(privateKey.d, true) + }; + } catch (err) { + if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux + throw err; + } + const seed = getRandomBytes(getPayloadSize$1(algo)); + const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed); + return { A, seed }; + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const seed = ed448.utils.randomPrivateKey(); + const A = ed448.getPublicKey(seed); + return { A, seed }; + } + default: + throw new Error('Unsupported EdDSA algorithm'); } - return false; } /** - * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} - * @param {SecretSubkeyPacket} subkey - Subkey key packet - * @param {SecretKeyPacket} primaryKey - Primary key packet - * @param {Object} options - * @param {Object} config - Full configuration + * Sign a message using the provided key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * RS: Uint8Array + * }>} Signature of the message + * @async */ -async function createBindingSignature(subkey, primaryKey, options, config) { - const dataToSign = {}; - dataToSign.key = primaryKey; - dataToSign.bind = subkey; - const signatureProperties = { signatureType: enums.signature.subkeyBinding }; - if (options.sign) { - signatureProperties.keyFlags = [enums.keyFlags.signData]; - signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, { - signatureType: enums.signature.keyBinding - }, options.date, undefined, undefined, undefined, config); - } else { - signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; +async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = privateKeyToJWK(algo, publicKey, privateKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']); + + const signature = new Uint8Array( + await webCrypto.sign('Ed25519', key, hashed) + ); + + return { RS: signature }; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + const secretKey = util.concatUint8Array([privateKey, publicKey]); + const signature = nacl.sign.detached(hashed, secretKey); + return { RS: signature }; + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const signature = ed448.sign(hashed, privateKey); + return { RS: signature }; + } + default: + throw new Error('Unsupported EdDSA algorithm'); } - const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); - return subkeySignaturePacket; + } /** - * Returns the preferred signature hash algorithm of a key - * @param {Key} [key] - The key to get preferences from - * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} config - full configuration - * @returns {Promise} + * Verifies if a signature is valid for a message + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{ RS: Uint8Array }} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} * @async */ -async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) { - let hashAlgo = config.preferredHashAlgorithm; - let prefAlgo = hashAlgo; - if (key) { - const primaryUser = await key.getPrimaryUser(date, userID, config); - if (primaryUser.selfCertification.preferredHashAlgorithms) { - [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; - } +async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); } - switch (keyPacket.algorithm) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: + switch (algo) { case enums.publicKey.ed25519: - prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid); + try { + const webCrypto = util.getWebCrypto(); + const jwk = publicKeyToJWK(algo, publicKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']); + const verified = await webCrypto.verify('Ed25519', key, RS, hashed); + return verified; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + return nacl.sign.detached.verify(hashed, RS, publicKey); + } + + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + return ed448.verify(RS, hashed, publicKey); + } + default: + throw new Error('Unsupported EdDSA algorithm'); } - return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; } - /** - * Returns the preferred symmetric/aead/compression algorithm for a set of keys - * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return - * @param {Array} [keys] - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Preferred algorithm + * Validate (non-legacy) EdDSA parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - EdDSA public point + * @param {Uint8Array} seed - EdDSA secret seed + * @param {Uint8Array} oid - (legacy only) EdDSA OID + * @returns {Promise} Whether params are valid. * @async */ -async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) { - const defaultAlgo = { // these are all must-implement in rfc4880bis - 'symmetric': enums.symmetric.aes128, - 'aead': enums.aead.eax, - 'compression': enums.compression.uncompressed - }[type]; - const preferredSenderAlgo = { - 'symmetric': config$1.preferredSymmetricAlgorithm, - 'aead': config$1.preferredAEADAlgorithm, - 'compression': config$1.preferredCompressionAlgorithm - }[type]; - const prefPropertyName = { - 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAEADAlgorithms', - 'compression': 'preferredCompressionAlgorithms' - }[type]; +async function validateParams$7(algo, A, seed) { + switch (algo) { + case enums.publicKey.ed25519: { + /** + * Derive public point A' from private key + * and expect A == A' + * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(seed); + return util.equalsUint8Array(A, publicKey); + } - // if preferredSenderAlgo appears in the prefs of all recipients, we pick it - // otherwise we use the default algo - // if no keys are available, preferredSenderAlgo is returned - const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; - return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; - })); - return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + + const publicKey = ed448.getPublicKey(seed); + return util.equalsUint8Array(A, publicKey); + } + default: + return false; + } } -/** - * Create signature packet - * @param {Object} dataToSign - Contains packets to be signed - * @param {PrivateKey} privateKey - key to get preferences from - * @param {SecretKeyPacket| - * SecretSubkeyPacket} signingKeyPacket secret key packet for signing - * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing - * @param {Date} [date] - Override the creationtime of the signature - * @param {Object} [userID] - User ID - * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [detached] - Whether to create a detached signature packet - * @param {Object} config - full configuration - * @returns {Promise} Signature packet. - */ -async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) { - if (signingKeyPacket.isDummy()) { - throw new Error('Cannot sign with a gnu-dummy key.'); +function getPayloadSize$1(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return 32; + + case enums.publicKey.ed448: + return 57; + + default: + throw new Error('Unsupported EdDSA algorithm'); } - if (!signingKeyPacket.isDecrypted()) { - throw new Error('Signing key is not decrypted.'); +} + +function getPreferredHashAlgo$2(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return enums.hash.sha256; + case enums.publicKey.ed448: + return enums.hash.sha512; + default: + throw new Error('Unknown EdDSA algo'); } - const signaturePacket = new SignaturePacket(); - Object.assign(signaturePacket, signatureProperties); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config); - signaturePacket.rawNotations = notations; - await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached); - return signaturePacket; } -/** - * Merges signatures from source[attr] to dest[attr] - * @param {Object} source - * @param {Object} dest - * @param {String} attr - * @param {Date} [date] - date to use for signature expiration check, instead of the current time - * @param {Function} [checkFn] - signature only merged if true - */ -async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { - source = source[attr]; - if (source) { - if (!dest[attr].length) { - dest[attr] = source; - } else { - await Promise.all(source.map(async function(sourceSig) { - if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && - !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); - })) { - dest[attr].push(sourceSig); - } - })); +const publicKeyToJWK = (algo, publicKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: uint8ArrayToB64(publicKey), + ext: true + }; + return jwk; } + default: + throw new Error('Unsupported EdDSA algorithm'); } -} +}; -/** - * Checks if a given certificate or binding signature is revoked - * @param {SecretKeyPacket| - * PublicKeyPacket} primaryKey The primary key packet - * @param {Object} dataToVerify - The data to check - * @param {Array} revocations - The revocation signatures to check - * @param {SignaturePacket} signature - The certificate or signature to check - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the signature revokes the data. - * @async - */ -async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { - key = key || primaryKey; - const revocationKeyIDs = []; - await Promise.all(revocations.map(async function(revocationSignature) { - try { - if ( - // Note: a third-party revocation signature could legitimately revoke a - // self-signature if the signature has an authorized revocation key. - // However, we don't support passing authorized revocation keys, nor - // verifying such revocation signatures. Instead, we indicate an error - // when parsing a key with an authorized revocation key, and ignore - // third-party revocation signatures here. (It could also be revoking a - // third-party key certification, which should only affect - // `verifyAllCertifications`.) - !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) - ) { - await revocationSignature.verify( - key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config - ); +const privateKeyToJWK = (algo, publicKey, privateKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = publicKeyToJWK(algo, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; + } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; + +var eddsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + generate: generate$3, + getPayloadSize: getPayloadSize$1, + getPreferredHashAlgo: getPreferredHashAlgo$2, + sign: sign$5, + validateParams: validateParams$7, + verify: verify$5 +}); - // TODO get an identifier of the revoked object instead - revocationKeyIDs.push(revocationSignature.issuerKeyID); - } - } catch (e) {} - })); - // TODO further verify that this is the signature that should be revoked - if (signature) { - signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : - signature.revoked || false; - return signature.revoked; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$4 = util.getWebCrypto(); +/** + * AES key wrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} dataToWrap + * @returns {Uint8Array} wrapped key + */ +async function wrap(algo, key, dataToWrap) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); } - return revocationKeyIDs.length > 0; + + try { + const wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']); + // Import data as HMAC key, as it has no key length requirements + const keyToWrap = await webCrypto$4.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + const wrapped = await webCrypto$4.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' }); + return new Uint8Array(wrapped); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + + return aeskw(key).encrypt(dataToWrap); } /** - * Returns key expiration time based on the given certification signature. - * The expiration time of the signature is ignored. - * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check - * @param {SignaturePacket} signature - signature to process - * @returns {Date|Infinity} expiration time or infinity if the key does not expire + * AES key unwrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} wrappedData + * @returns {Uint8Array} unwrapped data */ -function getKeyExpirationTime(keyPacket, signature) { - let expirationTime; - // check V4 expiration time - if (signature.keyNeverExpires === false) { - expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; +async function unwrap(algo, key, wrappedData) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } + + let wrappingKey; + try { + wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + return aeskw(key).decrypt(wrappedData); + } + + try { + const unwrapped = await webCrypto$4.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + return new Uint8Array(await webCrypto$4.exportKey('raw', unwrapped)); + } catch (err) { + if (err.name === 'OperationError') { + throw new Error('Key Data Integrity failed'); + } + throw err; } - return expirationTime ? new Date(expirationTime) : Infinity; } +var aesKW = /*#__PURE__*/Object.freeze({ + __proto__: null, + unwrap: unwrap, + wrap: wrap +}); + /** - * Returns whether aead is supported by all keys in the set - * @param {Array} keys - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} config - full configuration - * @returns {Promise} - * @async + * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. + * @module crypto/hkdf */ -async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) { - let supported = true; - // TODO replace when Promise.some or Promise.any are implemented - await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - if (!primaryUser.selfCertification.features || - !(primaryUser.selfCertification.features[0] & enums.features.aead)) { - supported = false; - } - })); - return supported; + + +const webCrypto$3 = util.getWebCrypto(); + +async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { + const hash = enums.read(enums.webHash, hashAlgo); + if (!hash) throw new Error('Hash algo not supported with HKDF'); + + const importedKey = await webCrypto$3.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto$3.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + return new Uint8Array(bits); } -function sanitizeKeyOptions(options, subkeyDefaults = {}) { - options.type = options.type || subkeyDefaults.type; - options.curve = options.curve || subkeyDefaults.curve; - options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; - options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; +/** + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @module crypto/public_key/elliptic/ecdh + */ - options.sign = options.sign || false; - switch (options.type) { - case 'ecc': - try { - options.curve = enums.write(enums.curve, options.curve); - } catch (e) { - throw new Error('Unknown curve'); - } - if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) { - options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; - } - if (options.sign) { - options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; - } else { - options.algorithm = enums.publicKey.ecdh; - } - break; - case 'rsa': - options.algorithm = enums.publicKey.rsaEncryptSign; - break; +const HKDF_INFO = { + x25519: util.encodeUTF8('OpenPGP X25519'), + x448: util.encodeUTF8('OpenPGP X448') +}; + +/** + * Generate ECDH key for Montgomery curves + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} + */ +async function generate$2(algo) { + switch (algo) { + case enums.publicKey.x25519: { + // k stays in little-endian, unlike legacy ECDH over curve25519 + const k = getRandomBytes(32); + const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k); + return { A, k }; + } + + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const k = x448.utils.randomPrivateKey(); + const A = x448.getPublicKey(k); + return { A, k }; + } default: - throw new Error(`Unsupported key type ${options.type}`); + throw new Error('Unsupported ECDH algorithm'); } - return options; } -function isValidSigningKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.rsaEncrypt && - keyAlgo !== enums.publicKey.elgamal && - keyAlgo !== enums.publicKey.ecdh && - keyAlgo !== enums.publicKey.x25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.signData) !== 0); -} - -function isValidEncryptionKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.dsa && - keyAlgo !== enums.publicKey.rsaSign && - keyAlgo !== enums.publicKey.ecdsa && - keyAlgo !== enums.publicKey.eddsaLegacy && - keyAlgo !== enums.publicKey.ed25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0); -} +/** +* Validate ECDH parameters +* @param {module:enums.publicKey} algo - Algorithm identifier +* @param {Uint8Array} A - ECDH public point +* @param {Uint8Array} k - ECDH secret scalar +* @returns {Promise} Whether params are valid. +* @async +*/ +async function validateParams$6(algo, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + /** + * Derive public point A' from private key + * and expect A == A' + */ + const { publicKey } = nacl.box.keyPair.fromSecretKey(k); + return util.equalsUint8Array(A, publicKey); + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + /** + * Derive public point A' from private key + * and expect A == A' + */ + const publicKey = x448.getPublicKey(k); + return util.equalsUint8Array(A, publicKey); + } -function isValidDecryptionKeyPacket(signature, config) { - if (config.allowInsecureDecryptionWithSigningKeys) { - // This is only relevant for RSA keys, all other signing algorithms cannot decrypt - return true; + default: + return false; } - - return !signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; } /** - * Check key against blacklisted algorithms and minimum strength requirements. - * @param {SecretKeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket - * @param {Config} config - * @throws {Error} if the key packet does not meet the requirements + * Wrap and encrypt a session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} data - session key data to be encrypted + * @param {Uint8Array} recipientA - Recipient public key (K_B) + * @returns {Promise<{ + * ephemeralPublicKey: Uint8Array, + * wrappedKey: Uint8Array + * }>} ephemeral public key (K_A) and encrypted key + * @async */ -function checkKeyRequirements(keyPacket, config) { - const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); - const algoInfo = keyPacket.getAlgorithmInfo(); - if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { - throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); - } - switch (keyAlgo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: - case enums.publicKey.rsaEncrypt: - if (algoInfo.bits < config.minRSABits) { - throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); - } - break; - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ecdh: - if (config.rejectCurves.has(algoInfo.curve)) { - throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); - } - break; +async function encrypt$2(algo, data, recipientA) { + const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + recipientA, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; + } + + default: + throw new Error('Unsupported ECDH algorithm'); } } /** - * @module key/User - * @private + * Decrypt and unwrap the session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} ephemeralPublicKey - (K_A) + * @param {Uint8Array} wrappedKey, + * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF + * @param {Uint8Array} k - Recipient secret key (b) + * @returns {Promise} decrypted session key data + * @async */ +async function decrypt$2(algo, ephemeralPublicKey, wrappedKey, A, k) { + const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + A, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); + } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} + +function getPayloadSize(algo) { + switch (algo) { + case enums.publicKey.x25519: + return 32; + + case enums.publicKey.x448: + return 56; + + default: + throw new Error('Unsupported ECDH algorithm'); + } +} /** - * Class that represents an user ID or attribute packet and the relevant signatures. - * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info - * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + * Generate shared secret and ephemeral public key for encryption + * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret + * @async */ -class User { - constructor(userPacket, mainKey) { - this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; - this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; - this.selfCertifications = []; - this.otherCertifications = []; - this.revocationSignatures = []; - this.mainKey = mainKey; +async function generateEphemeralEncryptionMaterial(algo, recipientA) { + switch (algo) { + case enums.publicKey.x25519: { + const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo)); + const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const ephemeralSecretKey = x448.utils.randomPrivateKey(); + const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + default: + throw new Error('Unsupported ECDH algorithm'); } +} - /** - * Transforms structured user data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.userID || this.userAttribute); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.selfCertifications); - packetlist.push(...this.otherCertifications); - return packetlist; +async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; + } + default: + throw new Error('Unsupported ECDH algorithm'); } +} - /** - * Shallow clone - * @returns {User} - */ - clone() { - const user = new User(this.userID || this.userAttribute, this.mainKey); - user.selfCertifications = [...this.selfCertifications]; - user.otherCertifications = [...this.otherCertifications]; - user.revocationSignatures = [...this.revocationSignatures]; - return user; +/** + * x25519 and x448 produce an all-zero value when given as input a point with small order. + * This does not lead to a security issue in the context of ECDH, but it is still unexpected, + * hence we throw. + * @param {Uint8Array} sharedSecret + */ +function assertNonZeroArray(sharedSecret) { + let acc = 0; + for (let i = 0; i < sharedSecret.length; i++) { + acc |= sharedSecret[i]; } - - /** - * Generate third-party certifications over this user and its primary key - * @param {Array} signingKeys - Decrypted private keys for signing - * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} New user with new certifications. - * @async - */ - async certify(signingKeys, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { - if (!privateKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - if (privateKey.hasSameFingerprintAs(primaryKey)) { - throw new Error("The user's own key can only be used for self-certifications"); - } - const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); - return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, { - // Most OpenPGP implementations use generic certification (0x10) - signatureType: enums.signature.certGeneric, - keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] - }, date, undefined, undefined, undefined, config); - })); - await user.update(this, date, config); - return user; + if (acc === 0) { + throw new Error('Unexpected low order point'); } +} - /** - * Checks if a given certificate of the user is revoked - * @param {SignaturePacket} certificate - The certificate to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked(primaryKey, enums.signature.certRevocation, { - key: primaryKey, - userID: this.userID, - userAttribute: this.userAttribute - }, this.revocationSignatures, certificate, keyPacket, date, config$1); +var ecdh_x = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$2, + encrypt: encrypt$2, + generate: generate$2, + generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial, + getPayloadSize: getPayloadSize, + recomputeSharedSecret: recomputeSharedSecret, + validateParams: validateParams$6 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$2 = util.getWebCrypto(); +const nodeCrypto$2 = util.getNodeCrypto(); + +const webCurves = { + [enums.curve.nistP256]: 'P-256', + [enums.curve.nistP384]: 'P-384', + [enums.curve.nistP521]: 'P-521' +}; +const knownCurves = nodeCrypto$2 ? nodeCrypto$2.getCurves() : []; +const nodeCurves = nodeCrypto$2 ? { + [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, + [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, + [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, + [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, + [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined, + [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined, + [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, + [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, + [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined +} : {}; + +const curves = { + [enums.curve.nistP256]: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.nistP256], + web: webCurves[enums.curve.nistP256], + payloadSize: 32, + sharedSize: 256, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP384]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.nistP384], + web: webCurves[enums.curve.nistP384], + payloadSize: 48, + sharedSize: 384, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP521]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.nistP521], + web: webCurves[enums.curve.nistP521], + payloadSize: 66, + sharedSize: 528, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.secp256k1]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.secp256k1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.ed25519Legacy]: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: enums.publicKey.eddsaLegacy, + hash: enums.hash.sha512, + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.curve25519Legacy]: { + oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: enums.publicKey.ecdh, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.brainpoolP256r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.brainpoolP256r1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP384r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.brainpoolP384r1], + payloadSize: 48, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP512r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.brainpoolP512r1], + payloadSize: 64, + wireFormatLeadingByte: 0x04 } +}; - /** - * Verifies the user certificate. - * @param {SignaturePacket} certificate - A certificate of this user - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate - * @throws if the user certificate is invalid. - * @async - */ - async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const { issuerKeyID } = certificate; - const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); - if (issuerKeys.length === 0) { - return null; +class CurveWithOID { + constructor(oidOrName) { + try { + this.name = oidOrName instanceof OID ? + oidOrName.getName() : + enums.write(enums.curve,oidOrName); + } catch (err) { + throw new UnsupportedError('Unknown curve'); } - await Promise.all(issuerKeys.map(async key => { - const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); - if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { - throw new Error('User certificate is revoked'); - } - try { - await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('User certificate is invalid', e); - } - })); - return true; - } + const params = curves[this.name]; - /** - * Verifies all user certificates - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllCertifications(verificationKeys, date = new Date(), config) { - const that = this; - const certifications = this.selfCertifications.concat(this.otherCertifications); - return Promise.all(certifications.map(async certification => ({ - keyID: certification.issuerKeyID, - valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) - }))); - } + this.keyType = params.keyType; - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} Status of user. - * @throws {Error} if there are no valid self signatures. - * @async - */ - async verify(date = new Date(), config) { - if (!this.selfCertifications.length) { - throw new Error('No self-certifications found'); + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node; + this.web = params.web; + this.payloadSize = params.payloadSize; + this.sharedSize = params.sharedSize; + this.wireFormatLeadingByte = params.wireFormatLeadingByte; + if (this.web && util.getWebCrypto()) { + this.type = 'web'; + } else if (this.node && util.getNodeCrypto()) { + this.type = 'node'; + } else if (this.name === enums.curve.curve25519Legacy) { + this.type = 'curve25519Legacy'; + } else if (this.name === enums.curve.ed25519Legacy) { + this.type = 'ed25519Legacy'; } - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // TODO replace when Promise.some or Promise.any are implemented - let exception; - for (let i = this.selfCertifications.length - 1; i >= 0; i--) { - try { - const selfCertification = this.selfCertifications[i]; - if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { - throw new Error('Self-certification is revoked'); - } + } + + async genKeyPair() { + switch (this.type) { + case 'web': try { - await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('Self-certification is invalid', e); + return await webGenKeyPair(this.name, this.wireFormatLeadingByte); + } catch (err) { + util.printDebugError('Browser did not support generating ec key ' + err.message); + return jsGenKeyPair(this.name); } - return true; - } catch (e) { - exception = e; + case 'node': + return nodeGenKeyPair(this.name); + case 'curve25519Legacy': { + // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3 + const { k, A } = await generate$2(enums.publicKey.x25519); + const privateKey = k.slice().reverse(); + privateKey[0] = (privateKey[0] & 127) | 64; + privateKey[31] &= 248; + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + case 'ed25519Legacy': { + const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519); + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; } + default: + return jsGenKeyPair(this.name); } - throw exception; - } - - /** - * Update user with new components from specified user - * @param {User} sourceUser - Source user to merge - * @param {Date} date - Date to verify the validity of signatures - * @param {Object} config - Full configuration - * @returns {Promise} - * @async - */ - async update(sourceUser, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // self signatures - await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { - try { - await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); - return true; - } catch (e) { - return false; - } - }); - // other signatures - await mergeSignatures(sourceUser, this, 'otherCertifications', date); - // revocation signatures - await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); - }); } +} - /** - * Revokes the user - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New user with revocation signature. - * @async - */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.certRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await user.update(this); - return user; - } +async function generate$1(curveName) { + const curve = new CurveWithOID(curveName); + const { oid, hash, cipher } = curve; + const keyPair = await curve.genKeyPair(); + return { + oid, + Q: keyPair.publicKey, + secret: util.leftPad(keyPair.privateKey, curve.payloadSize), + hash, + cipher + }; } /** - * @module key/Subkey - * @private + * Get preferred hash algo to use with the given curve + * @param {module:type/oid} oid - curve oid + * @returns {enums.hash} hash algorithm */ +function getPreferredHashAlgo$1(oid) { + return curves[oid.getName()].hash; +} /** - * Class that represents a subkey packet and the relevant signatures. - * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID - * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint - * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs - * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo - * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime - * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + * Validate ECDH and ECDSA parameters + * Not suitable for EdDSA (different secret key format) + * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves + * @param {module:type/oid} oid - EC object identifier + * @param {Uint8Array} Q - EC public point + * @param {Uint8Array} d - EC secret scalar + * @returns {Promise} Whether params are valid. + * @async */ -class Subkey { - /** - * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey - * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey - */ - constructor(subkeyPacket, mainKey) { - this.keyPacket = subkeyPacket; - this.bindingSignatures = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } - - /** - * Transforms structured subkey data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.bindingSignatures); - return packetlist; - } - - /** - * Shallow clone - * @return {Subkey} - */ - clone() { - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.bindingSignatures = [...this.bindingSignatures]; - subkey.revocationSignatures = [...this.revocationSignatures]; - return subkey; - } +async function validateStandardParams(algo, oid, Q, d) { + const supportedCurves = { + [enums.curve.nistP256]: true, + [enums.curve.nistP384]: true, + [enums.curve.nistP521]: true, + [enums.curve.secp256k1]: true, + [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh, + [enums.curve.brainpoolP256r1]: true, + [enums.curve.brainpoolP384r1]: true, + [enums.curve.brainpoolP512r1]: true + }; - /** - * Checks if a binding signature of a subkey is revoked - * @param {SignaturePacket} signature - The binding signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the binding signature is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked( - primaryKey, enums.signature.subkeyRevocation, { - key: primaryKey, - bind: this.keyPacket - }, this.revocationSignatures, signature, key, date, config$1 - ); + // Check whether the given curve is supported + const curveName = oid.getName(); + if (!supportedCurves[curveName]) { + return false; } - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} if the subkey is invalid. - * @async - */ - async verify(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - // check subkey binding signatures - const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - // check binding signature is not revoked - if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { - throw new Error('Subkey is revoked'); - } - // check for expiration time - if (isDataExpired(this.keyPacket, bindingSignature, date)) { - throw new Error('Subkey is expired'); - } - return bindingSignature; - } + if (curveName === enums.curve.curve25519Legacy) { + d = d.slice().reverse(); + // Re-derive public point Q' + const { publicKey } = nacl.box.keyPair.fromSecretKey(d); - /** - * Returns the expiration time of the subkey or Infinity if key does not expire. - * Returns null if the subkey is invalid. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async - */ - async getExpirationTime(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - let bindingSignature; - try { - bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - } catch (e) { - return null; + Q = new Uint8Array(Q); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + if (!util.equalsUint8Array(dG, Q)) { + return false; } - const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); - const sigExpiry = bindingSignature.getExpirationTime(); - return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; - } - /** - * Update subkey with new components from specified subkey - * @param {Subkey} subkey - Source subkey to merge - * @param {Date} [date] - Date to verify validity of signatures - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if update failed - * @async - */ - async update(subkey, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - if (!this.hasSameFingerprintAs(subkey)) { - throw new Error('Subkey update method: fingerprints of subkeys not equal'); - } - // key packet - if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && - subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { - this.keyPacket = subkey.keyPacket; - } - // update missing binding signatures - const that = this; - const dataToVerify = { key: primaryKey, bind: that.keyPacket }; - await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { - for (let i = 0; i < that.bindingSignatures.length; i++) { - if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { - if (srcBindSig.created > that.bindingSignatures[i].created) { - that.bindingSignatures[i] = srcBindSig; - } - return false; - } - } - try { - await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); - return true; - } catch (e) { - return false; - } - }); - // revocation signatures - await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); - }); + return true; } - /** - * Revokes the subkey - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New subkey with revocation signature. - * @async + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + /* + * Re-derive public point Q' = dG from private key + * Expect Q == Q' */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { key: primaryKey, bind: this.keyPacket }; - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.subkeyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await subkey.update(this); - return subkey; + const dG = nobleCurve.getPublicKey(d, false); + if (!util.equalsUint8Array(dG, Q)) { + return false; } - hasSameFingerprintAs(other) { - return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + return true; +} + +/** + * Check whether the public point has a valid encoding. + * NB: this function does not check e.g. whether the point belongs to the curve. + */ +function checkPublicPointEnconding(curve, V) { + const { payloadSize, wireFormatLeadingByte, name: curveName } = curve; + + const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2; + + if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) { + throw new Error('Invalid point encoding'); } } -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { - Subkey.prototype[name] = - function() { - return this.keyPacket[name](); - }; -}); +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// +async function jsGenKeyPair(name) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + const privateKey = nobleCurve.utils.randomPrivateKey(); + const publicKey = nobleCurve.getPublicKey(privateKey, false); + return { publicKey, privateKey }; +} -// GPG4Browsers - An OpenPGP implementation in javascript +async function webGenKeyPair(name, wireFormatLeadingByte) { + // Note: keys generated with ECDSA and ECDH are structurally equivalent + const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); -// A key revocation certificate can contain the following packets -const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); -const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); -const keyPacketTags = new Set([ - enums.packet.publicKey, enums.packet.privateKey, - enums.packet.publicSubkey, enums.packet.privateSubkey -]); + const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey); + + return { + publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte), + privateKey: b64ToUint8Array(privateKey.d) + }; +} + +async function nodeGenKeyPair(name) { + // Note: ECDSA and ECDH key generation is structurally equivalent + const ecdh = nodeCrypto$2.createECDH(nodeCurves[name]); + await ecdh.generateKeys(); + return { + publicKey: new Uint8Array(ecdh.getPublicKey()), + privateKey: new Uint8Array(ecdh.getPrivateKey()) + }; +} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// /** - * Abstract class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. - * @borrows PublicKeyPacket#getKeyID as Key#getKeyID - * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint - * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs - * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo - * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + * @param {JsonWebKey} jwk - key for conversion + * + * @returns {Uint8Array} Raw public key. */ -class Key { - /** - * Transforms packetlist to structured key data - * @param {PacketList} packetlist - The packets that form a key - * @param {Set} disallowedPackets - disallowed packet tags - */ - packetListToStructure(packetlist, disallowedPackets = new Set()) { - let user; - let primaryKeyID; - let subkey; - let ignoreUntil; +function jwkToRawPublic(jwk, wireFormatLeadingByte) { + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); + const publicKey = new Uint8Array(bufX.length + bufY.length + 1); + publicKey[0] = wireFormatLeadingByte; + publicKey.set(bufX, 1); + publicKey.set(bufY, bufX.length + 1); + return publicKey; +} - for (const packet of packetlist) { +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * + * @returns {JsonWebKey} Public key in jwk format. + */ +function rawPublicToJWK(payloadSize, name, publicKey) { + const len = payloadSize; + const bufX = publicKey.slice(1, len + 1); + const bufY = publicKey.slice(len + 1, len * 2 + 1); + // https://www.rfc-editor.org/rfc/rfc7518.txt + const jwk = { + kty: 'EC', + crv: name, + x: uint8ArrayToB64(bufX), + y: uint8ArrayToB64(bufY), + ext: true + }; + return jwk; +} - if (packet instanceof UnparseablePacket) { - const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); - if (isUnparseableKeyPacket && !ignoreUntil) { - // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must - // discard all non-key packets that follow, until another (sub)key packet is found. - if (mainKeyPacketTags.has(packet.tag)) { - ignoreUntil = mainKeyPacketTags; - } else { - ignoreUntil = keyPacketTags; - } - } - continue; - } +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * @param {Uint8Array} privateKey - private key + * + * @returns {JsonWebKey} Private key in jwk format. + */ +function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; +} - const tag = packet.constructor.tag; - if (ignoreUntil) { - if (!ignoreUntil.has(tag)) continue; - ignoreUntil = null; - } - if (disallowedPackets.has(tag)) { - throw new Error(`Unexpected packet type: ${tag}`); - } - switch (tag) { - case enums.packet.publicKey: - case enums.packet.secretKey: - if (this.keyPacket) { - throw new Error('Key block contains multiple keys'); - } - this.keyPacket = packet; - primaryKeyID = this.getKeyID(); - if (!primaryKeyID) { - throw new Error('Missing Key ID'); - } - break; - case enums.packet.userID: - case enums.packet.userAttribute: - user = new User(packet, this); - this.users.push(user); - break; - case enums.packet.publicSubkey: - case enums.packet.secretSubkey: - user = null; - subkey = new Subkey(packet, this); - this.subkeys.push(subkey); - break; - case enums.packet.signature: - switch (packet.signatureType) { - case enums.signature.certGeneric: - case enums.signature.certPersona: - case enums.signature.certCasual: - case enums.signature.certPositive: - if (!user) { - util.printDebug('Dropping certification signatures without preceding user packet'); - continue; - } - if (packet.issuerKeyID.equals(primaryKeyID)) { - user.selfCertifications.push(packet); - } else { - user.otherCertifications.push(packet); - } - break; - case enums.signature.certRevocation: - if (user) { - user.revocationSignatures.push(packet); - } else { - this.directSignatures.push(packet); - } - break; - case enums.signature.key: - this.directSignatures.push(packet); - break; - case enums.signature.subkeyBinding: - if (!subkey) { - util.printDebug('Dropping subkey binding signature without preceding subkey packet'); - continue; - } - subkey.bindingSignatures.push(packet); - break; - case enums.signature.keyRevocation: - this.revocationSignatures.push(packet); - break; - case enums.signature.subkeyRevocation: - if (!subkey) { - util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); - continue; - } - subkey.revocationSignatures.push(packet); - break; - } - break; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$1 = util.getWebCrypto(); +const nodeCrypto$1 = util.getNodeCrypto(); + +/** + * Sign a message using the provided key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (message && !util.isStream(message)) { + const keyPair = { publicKey, privateKey }; + switch (curve.type) { + case 'web': + // If browser doesn't support a curve, we'll catch it + try { + // Need to await to make sure browser succeeds + return await webSign(curve, hashAlgo, message, keyPair); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunaley Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support signing: ' + err.message); + } + break; + case 'node': + return nodeSign(curve, hashAlgo, message, privateKey); } } - /** - * Transforms structured key data to packetlist - * @returns {PacketList} The packets that form a key. - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.directSignatures); - this.users.map(user => packetlist.push(...user.toPacketList())); - this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); - return packetlist; - } + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + const signature = nobleCurve.sign(hashed, privateKey, { lowS: false }); + return { + r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize), + s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize) + }; +} - /** - * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. - * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. - * @returns {Promise} Clone of the key. - */ - clone(clonePrivateParams = false) { - const key = new this.constructor(this.toPacketList()); - if (clonePrivateParams) { - key.getKeys().forEach(k => { - // shallow clone the key packets - k.keyPacket = Object.create( - Object.getPrototypeOf(k.keyPacket), - Object.getOwnPropertyDescriptors(k.keyPacket) - ); - if (!k.keyPacket.isDecrypted()) return; - // deep clone the private params, which are cleared during encryption - const privateParams = {}; - Object.keys(k.keyPacket.privateParams).forEach(name => { - privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); - }); - k.keyPacket.privateParams = privateParams; - }); +/** + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} message - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + // See https://github.com/openpgpjs/openpgpjs/pull/948. + // NB: the impact was more likely limited to Brainpool curves, since thanks + // to WebCrypto availability, NIST curve should not have been affected. + // Similarly, secp256k1 should have been used rarely enough. + // However, we implement the fix for all curves, since it's only needed in case of + // verification failure, which is unexpected, hence a minor slowdown is acceptable. + const tryFallbackVerificationForOldBug = async () => ( + hashed[0] === 0 ? + jsVerify(curve, signature, hashed.subarray(1), publicKey) : + false + ); + + if (message && !util.isStream(message)) { + switch (curve.type) { + case 'web': + try { + // Need to await to make sure browser succeeds + const verified = await webVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunately Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support verifying: ' + err.message); + } + break; + case 'node': { + const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } } - return key; } - /** - * Returns an array containing all public or private subkeys matching keyID; - * If no keyID is given, returns all subkeys. - * @param {type/keyID} [keyID] - key ID to look for - * @returns {Array} array of subkeys - */ - getSubkeys(keyID = null) { - const subkeys = this.subkeys.filter(subkey => ( - !keyID || subkey.getKeyID().equals(keyID, true) - )); - return subkeys; + const verified = await jsVerify(curve, signature, hashed, publicKey); + return verified || tryFallbackVerificationForOldBug(); +} + +/** + * Validate ECDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDSA public point + * @param {Uint8Array} d - ECDSA secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$5(oid, Q, d) { + const curve = new CurveWithOID(oid); + // Reject curves x25519 and ed25519 + if (curve.keyType !== enums.publicKey.ecdsa) { + return false; } - /** - * Returns an array containing all public or private keys matching keyID. - * If no keyID is given, returns all keys, starting with the primary key. - * @param {type/keyid~KeyID} [keyID] - key ID to look for - * @returns {Array} array of keys - */ - getKeys(keyID = null) { - const keys = []; - if (!keyID || this.getKeyID().equals(keyID, true)) { - keys.push(this); + // To speed up the validation, we try to use node- or webcrypto when available + // and sign + verify a random message + switch (curve.type) { + case 'web': + case 'node': { + const message = getRandomBytes(8); + const hashAlgo = enums.hash.sha256; + const hashed = await hash$1.digest(hashAlgo, message); + try { + const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed); + // eslint-disable-next-line @typescript-eslint/return-await + return await verify$4(oid, hashAlgo, signature, message, Q, hashed); + } catch (err) { + return false; + } } - return keys.concat(this.getSubkeys(keyID)); + default: + return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); } +} - /** - * Returns key IDs of all keys - * @returns {Array} - */ - getKeyIDs() { - return this.getKeys().map(key => key.getKeyID()); - } - /** - * Returns userIDs - * @returns {Array} Array of userIDs. - */ - getUserIDs() { - return this.users.map(user => { - return user.userID ? user.userID.userID : null; - }).filter(userID => userID !== null); - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// - /** - * Returns binary encoded key - * @returns {Uint8Array} Binary key. - */ - write() { - return this.toPacketList().write(); - } +/** + * Fallback javascript implementation of ECDSA verification. + * To be used if no native implementation is available for the given curve/operation. + */ +async function jsVerify(curve, signature, hashed, publicKey) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false }); +} - /** - * Returns last created key or key by given keyID that is available for signing and verification - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} signing key - * @throws if no valid signing key was found - * @async - */ - async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature( - subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 - ); - if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) { - continue; - } - if (!bindingSignature.embeddedSignature) { - throw new Error('Missing embedded signature'); - } - // verify embedded signature - await getLatestValidSignature( - [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 - ); - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } catch (e) { - exception = e; - } - } - } +async function webSign(curve, hashAlgo, message, keyPair) { + const len = curve.payloadSize; + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['sign'] + ); + + const signature = new Uint8Array(await webCrypto$1.sign( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + message + )); + + return { + r: signature.slice(0, len), + s: signature.slice(len, len << 1) + }; +} + +async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['verify'] + ); + + const signature = util.concatUint8Array([r, s]).buffer; + + return webCrypto$1.verify( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + signature, + message + ); +} + +async function nodeSign(curve, hashAlgo, message, privateKey) { + // JWT encoding cannot be used for now, as Brainpool curves are not supported + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + privateKey: nodeBuffer.from(privateKey) + }); + + const sign = nodeCrypto$1.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(message); + sign.end(); + + const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' })); + const len = curve.payloadSize; + + return { + r: signature.subarray(0, len), + s: signature.subarray(len, len << 1) + }; +} - try { - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; - } - throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); +async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { publicKey: derPublicKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + publicKey: nodeBuffer.from(publicKey) + }); + + const verify = nodeCrypto$1.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(message); + verify.end(); + + const signature = util.concatUint8Array([r, s]); + + try { + return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature); + } catch (err) { + return false; } +} - /** - * Returns last created key or key by given keyID that is available for encryption or decryption - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} encryption key - * @throws if no valid encryption key was found - * @async - */ - async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - // V4: by convention subkeys are preferred for encryption service - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) { - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } - } catch (e) { - exception = e; - } - } - } +var ecdsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$4, + validateParams: validateParams$5, + verify: verify$4 +}); - try { - // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; - } - throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Sign a message using the provided legacy EdDSA key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); } + const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed); + // EdDSA signature params are returned in little-endian format + return { + r: signature.subarray(0, 32), + s: signature.subarray(32) + }; +} - /** - * Checks if a signature on a key is revoked - * @param {SignaturePacket} signature - The signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - return isDataRevoked( - this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 - ); +/** + * Verifies if a legacy EdDSA signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + const RS = util.concatUint8Array([r, s]); + return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed); +} +/** + * Validate legacy EdDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - EdDSA public point + * @param {Uint8Array} k - EdDSA secret seed + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$4(oid, Q, k) { + // Check whether the given curve is supported + if (oid.getName() !== enums.curve.ed25519Legacy) { + return false; } /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature. Throws if the primary key is invalid. - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} If key verification failed - * @async + * Derive public point Q' = dG from private key + * and expect Q == Q' */ - async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - // check for key revocation signatures - if (await this.isRevoked(null, null, date, config$1)) { - throw new Error('Primary key is revoked'); - } - // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); - // check for expiration time in binding signatures - if (isDataExpired(primaryKey, selfCertification, date)) { - throw new Error('Primary key is expired'); - } - // check for expiration time in direct signatures - const directSignature = await getLatestValidSignature( - this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 - ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key + const { publicKey } = nacl.sign.keyPair.fromSeed(k); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + return util.equalsUint8Array(Q, dG); - if (directSignature && isDataExpired(primaryKey, directSignature, date)) { - throw new Error('Primary key is expired'); - } - } +} - /** - * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. - * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. - * @param {Object} [userID] - User ID to consider instead of the primary user - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async - */ - async getExpirationTime(userID, config$1 = config) { - let primaryKeyExpiry; - try { - const { selfCertification } = await this.getPrimaryUser(null, userID, config$1); - const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); - const selfSigExpiry = selfCertification.getExpirationTime(); - const directSignature = await getLatestValidSignature( - this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 - ).catch(() => {}); - if (directSignature) { - const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); - // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, - // causing a discountinous validy period for the key - primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); - } else { - primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; - } - } catch (e) { - primaryKeyExpiry = null; - } +var eddsa_legacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$3, + validateParams: validateParams$4, + verify: verify$3 +}); - return util.normalizeDate(primaryKeyExpiry); - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * user: User, - * selfCertification: SignaturePacket - * }>} The primary user and the self signature - * @async - */ - async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const users = []; - let exception; - for (let i = 0; i < this.users.length; i++) { - try { - const user = this.users[i]; - if (!user.userID) { - continue; - } - if ( - (userID.name !== undefined && user.userID.name !== userID.name) || - (userID.email !== undefined && user.userID.email !== userID.email) || - (userID.comment !== undefined && user.userID.comment !== userID.comment) - ) { - throw new Error('Could not find user that matches that user ID'); - } - const dataToVerify = { userID: user.userID, key: primaryKey }; - const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); - users.push({ index: i, user, selfCertification }); - } catch (e) { - exception = e; +/** + * @fileoverview Functions to add and remove PKCS5 padding + * @see PublicKeyEncryptedSessionKeyPacket + * @module crypto/pkcs5 + * @private + */ + +/** + * Add pkcs5 padding to a message + * @param {Uint8Array} message - message to pad + * @returns {Uint8Array} Padded message. + */ +function encode(message) { + const c = 8 - (message.length % 8); + const padded = new Uint8Array(message.length + c).fill(c); + padded.set(message); + return padded; +} + +/** + * Remove pkcs5 padding from a message + * @param {Uint8Array} message - message to remove padding from + * @returns {Uint8Array} Message without padding. + */ +function decode$1(message) { + const len = message.length; + if (len > 0) { + const c = message[len - 1]; + if (c >= 1) { + const provided = message.subarray(len - c); + const computed = new Uint8Array(c).fill(c); + if (util.equalsUint8Array(provided, computed)) { + return message.subarray(0, len - c); } } - if (!users.length) { - throw exception || new Error('Could not find primary user'); - } - await Promise.all(users.map(async function (a) { - return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); - })); - // sort by primary user flag and signature creation time - const primaryUser = users.sort(function(a, b) { - const A = a.selfCertification; - const B = b.selfCertification; - return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; - }).pop(); - const { user, selfCertification: cert } = primaryUser; - if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { - throw new Error('Primary user is revoked'); - } - return primaryUser; } + throw new Error('Invalid padding'); +} - /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * - * If the source key is a private key and the destination key is public, - * a private key is returned. - * @param {Key} sourceKey - Source key to merge - * @param {Date} [date] - Date to verify validity of signatures and keys - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} updated key - * @async - */ - async update(sourceKey, date = new Date(), config$1 = config) { - if (!this.hasSameFingerprintAs(sourceKey)) { - throw new Error('Primary key fingerprints must be equal to update the key'); - } - if (!this.isPrivate() && sourceKey.isPrivate()) { - // check for equal subkey packets - const equal = (this.subkeys.length === sourceKey.subkeys.length) && - (this.subkeys.every(destSubkey => { - return sourceKey.subkeys.some(srcSubkey => { - return destSubkey.hasSameFingerprintAs(srcSubkey); - }); - })); - if (!equal) { - throw new Error('Cannot update public key with private key if subkeys mismatch'); - } +var pkcs5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: decode$1, + encode: encode +}); - return sourceKey.update(this, config$1); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto = util.getWebCrypto(); +const nodeCrypto = util.getNodeCrypto(); + +/** + * Validate ECDH parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDH public point + * @param {Uint8Array} d - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$3(oid, Q, d) { + return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); +} + +// Build Param for ECDH algorithm (RFC 6637) +function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { + return util.concatUint8Array([ + oid.write(), + new Uint8Array([public_algo]), + kdfParams.write(), + util.stringToUint8Array('Anonymous Sender '), + fingerprint + ]); +} + +// Key Derivation Function (RFC 6637) +async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { + // Note: X is little endian for Curve25519, big-endian for all others. + // This is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + let i; + if (stripLeading) { + // Work around old go crypto bug + for (i = 0; i < X.length && X[i] === 0; i++); + X = X.subarray(i); + } + if (stripTrailing) { + // Work around old OpenPGP.js bug + for (i = X.length - 1; i >= 0 && X[i] === 0; i--); + X = X.subarray(0, i + 1); + } + const digest = await hash$1.digest(hashAlgo, util.concatUint8Array([ + new Uint8Array([0, 0, 0, 1]), + X, + param + ])); + return digest.subarray(0, length); +} + +/** + * Generate ECDHE ephemeral key and secret from public key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPublicEphemeralKey(curve, Q) { + switch (curve.type) { + case 'curve25519Legacy': { + const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1)); + const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]); + return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } - // from here on, either: - // - destination key is private, source key is public - // - the keys are of the same type - // hence we don't need to convert the destination key type - const updatedKey = this.clone(); - // revocation signatures - await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { - return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); - }); - // direct signatures - await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); - // update users - await Promise.all(sourceKey.users.map(async srcUser => { - // multiple users with the same ID/attribute are not explicitly disallowed by the spec - // hence we support them, just in case - const usersToUpdate = updatedKey.users.filter(dstUser => ( - (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || - (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) - )); - if (usersToUpdate.length > 0) { - await Promise.all( - usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) - ); - } else { - const newUser = srcUser.clone(); - newUser.mainKey = updatedKey; - updatedKey.users.push(newUser); - } - })); - // update subkeys - await Promise.all(sourceKey.subkeys.map(async srcSubkey => { - // multiple subkeys with same fingerprint might be preset - const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( - dstSubkey.hasSameFingerprintAs(srcSubkey) - )); - if (subkeysToUpdate.length > 0) { - await Promise.all( - subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) - ); - } else { - const newSubkey = srcSubkey.clone(); - newSubkey.mainKey = updatedKey; - updatedKey.subkeys.push(newSubkey); + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPublicEphemeralKey(curve, Q); + } catch (err) { + util.printDebugError(err); + return jsPublicEphemeralKey(curve, Q); + } } - })); + break; + case 'node': + return nodePublicEphemeralKey(curve, Q); + default: + return jsPublicEphemeralKey(curve, Q); - return updatedKey; } +} - /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Armored revocation certificate. - * @async - */ - async getRevocationCertificate(date = new Date(), config$1 = config) { - const dataToVerify = { key: this.keyPacket }; - const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); - const packetlist = new PacketList(); - packetlist.push(revocationSignature); - return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); - } +/** + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} data - Unpadded session key data + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} + * @async + */ +async function encrypt$1(oid, kdfParams, data, Q, fingerprint) { + const m = encode(data); - /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param {String} revocationCertificate - armored revocation certificate - * @param {Date} [date] - Date to verify the certificate - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Revoked key. - * @async - */ - async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { - const input = await unarmor(revocationCertificate, config$1); - const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); - const revocationSignature = packetlist.findPacket(enums.packet.signature); - if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { - throw new Error('Could not find revocation signature packet'); - } - if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { - throw new Error('Revocation signature does not match key'); + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); + const wrappedKey = await wrap(kdfParams.cipher, Z, m); + return { publicKey, wrappedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; + } + switch (curve.type) { + case 'curve25519Legacy': { + const secretKey = d.slice().reverse(); + const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey); + return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPrivateEphemeralKey(curve, V, Q, d); + } catch (err) { + util.printDebugError(err); + return jsPrivateEphemeralKey(curve, V, d); + } + } + break; + case 'node': + return nodePrivateEphemeralKey(curve, V, d); + default: + return jsPrivateEphemeralKey(curve, V, d); + } +} + +/** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} C - Encrypted and wrapped value derived from session key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise} Value derived from session key. + * @async + */ +async function decrypt$1(oid, kdfParams, V, C, Q, d, fingerprint) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + checkPublicPointEnconding(curve, V); + const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + let err; + for (let i = 0; i < 3; i++) { try { - await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); + // Work around old go crypto bug and old OpenPGP.js bug, respectively. + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); + return decode$1(await unwrap(kdfParams.cipher, Z, C)); } catch (e) { - throw util.wrapError('Could not verify revocation signature', e); + err = e; } - const key = this.clone(); - key.revocationSignatures.push(revocationSignature); - return key; } + throw err; +} - /** - * Signs primary user of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signPrimaryUser(privateKeys, date, userID, config$1 = config) { - const { index, user } = await this.getPrimaryUser(date, userID, config$1); - const userSign = await user.certify(privateKeys, date, config$1); - const key = this.clone(); - key.users[index] = userSign; - return key; - } +async function jsPrivateEphemeralKey(curve, V, d) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V); + const sharedKey = sharedSecretWithParity.subarray(1); + return { secretKey: d, sharedKey }; +} - /** - * Signs all users of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for signing, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signAllUsers(privateKeys, date = new Date(), config$1 = config) { - const key = this.clone(); - key.users = await Promise.all(this.users.map(function(user) { - return user.certify(privateKeys, date, config$1); - })); - return key; - } +async function jsPublicEphemeralKey(curve, Q) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + const { publicKey: V, privateKey: v } = await curve.genKeyPair(); - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { - const primaryKey = this.keyPacket; - const { user } = await this.getPrimaryUser(date, userID, config$1); - const results = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - return results; - } + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q); + const sharedKey = sharedSecretWithParity.subarray(1); + return { publicKey: V, sharedKey }; +} - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of userID, signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { - const primaryKey = this.keyPacket; - const results = []; - await Promise.all(this.users.map(async user => { - const signatures = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; +/** + * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPrivateEphemeralKey(curve, V, Q, d) { + const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d); + let privateKey = webCrypto.importKey( + 'jwk', + recipient, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V); + let sender = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + [] + ); + [privateKey, sender] = await Promise.all([privateKey, sender]); + let S = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: sender + }, + privateKey, + curve.sharedSize + ); + let secret = webCrypto.exportKey( + 'jwk', + privateKey + ); + [S, secret] = await Promise.all([S, secret]); + const sharedKey = new Uint8Array(S); + const secretKey = b64ToUint8Array(secret.d); + return { secretKey, sharedKey }; +} - results.push(...signatures.map( - signature => ({ - userID: user.userID ? user.userID.userID : null, - userAttribute: user.userAttribute, - keyID: signature.keyID, - valid: signature.valid - })) - ); - })); - return results; - } +/** + * Generate ECDHE ephemeral key and secret from public key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPublicEphemeralKey(curve, Q) { + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q); + let keyPair = webCrypto.generateKey( + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + let recipient = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + false, + [] + ); + [keyPair, recipient] = await Promise.all([keyPair, recipient]); + let s = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: recipient + }, + keyPair.privateKey, + curve.sharedSize + ); + let p = webCrypto.exportKey( + 'jwk', + keyPair.publicKey + ); + [s, p] = await Promise.all([s, p]); + const sharedKey = new Uint8Array(s); + const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte)); + return { publicKey, sharedKey }; } -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { - Key.prototype[name] = - Subkey.prototype[name]; +/** + * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePrivateEphemeralKey(curve, V, d) { + const recipient = nodeCrypto.createECDH(curve.node); + recipient.setPrivateKey(d); + const sharedKey = new Uint8Array(recipient.computeSecret(V)); + const secretKey = new Uint8Array(recipient.getPrivateKey()); + return { secretKey, sharedKey }; +} + +/** + * Generate ECDHE ephemeral key and secret from public key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePublicEphemeralKey(curve, Q) { + const sender = nodeCrypto.createECDH(curve.node); + sender.generateKeys(); + const sharedKey = new Uint8Array(sender.computeSecret(Q)); + const publicKey = new Uint8Array(sender.getPublicKey()); + return { publicKey, sharedKey }; +} + +var ecdh = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$1, + encrypt: encrypt$1, + validateParams: validateParams$3 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +var elliptic = /*#__PURE__*/Object.freeze({ + __proto__: null, + CurveWithOID: CurveWithOID, + ecdh: ecdh, + ecdhX: ecdh_x, + ecdsa: ecdsa, + eddsa: eddsa, + eddsaLegacy: eddsa_legacy, + generate: generate$1, + getPreferredHashAlgo: getPreferredHashAlgo$1 }); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// // This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/** - * Class that represents an OpenPGP Public Key - */ -class PublicKey extends Key { - /** - * @param {PacketList} packetlist - The packets that form this key - */ - constructor(packetlist) { - super(); - this.keyPacket = null; - this.revocationSignatures = []; - this.directSignatures = []; - this.users = []; - this.subkeys = []; - if (packetlist) { - this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing public-key packet'); - } - } - } - /** - * Returns true if this is a private key - * @returns {false} - */ - isPrivate() { - return false; - } +/* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 +*/ - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - return this; - } +const _0n$7 = BigInt(0); +const _1n$9 = BigInt(1); - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); +/** + * DSA Sign function + * @param {Integer} hashAlgo + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} x + * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} + * @async + */ +async function sign$2(hashAlgo, hashed, g, p, q, x) { + const _0n = BigInt(0); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + x = uint8ArrayToBigInt(x); + + let k; + let r; + let s; + let t; + g = mod$2(g, p); + x = mod$2(x, q); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + while (true) { + // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + k = getRandomBigInteger(_1n$9, q); // returns in [1, q-1] + r = mod$2(modExp(g, k, p), q); // (g**k mod p) mod q + if (r === _0n) { + continue; + } + const xr = mod$2(x * r, q); + t = mod$2(h + xr, q); // H(m) + x*r mod q + s = mod$2(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q + if (s === _0n) { + continue; + } + break; } + return { + r: bigIntToUint8Array(r, 'be', byteLength(p)), + s: bigIntToUint8Array(s, 'be', byteLength(p)) + }; } /** - * Class that represents an OpenPGP Private key - */ -class PrivateKey extends PublicKey { - /** - * @param {PacketList} packetlist - The packets that form this key + * DSA Verify function + * @param {Integer} hashAlgo + * @param {Uint8Array} r + * @param {Uint8Array} s + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} y + * @returns {boolean} + * @async */ - constructor(packetlist) { - super(); - this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing private-key packet'); - } - } +async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) { + r = uint8ArrayToBigInt(r); + s = uint8ArrayToBigInt(s); - /** - * Returns true if this is a private key - * @returns {Boolean} - */ - isPrivate() { - return true; - } + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - const packetlist = new PacketList(); - const keyPackets = this.toPacketList(); - for (const keyPacket of keyPackets) { - switch (keyPacket.constructor.tag) { - case enums.packet.secretKey: { - const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); - packetlist.push(pubKeyPacket); - break; - } - case enums.packet.secretSubkey: { - const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); - packetlist.push(pubSubkeyPacket); - break; - } - default: - packetlist.push(keyPacket); - } - } - return new PublicKey(packetlist); + if (r <= _0n$7 || r >= q || + s <= _0n$7 || s >= q) { + util.printDebug('invalid DSA Signature'); + return false; } - - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + const w = modInv(s, q); // s**-1 mod q + if (w === _0n$7) { + util.printDebug('invalid DSA Signature'); + return false; } - /** - * Returns all keys that are available for decryption, matching the keyID when given - * This is useful to retrieve keys for session key decryption - * @param {module:type/keyid~KeyID} keyID, optional - * @param {Date} date, optional - * @param {String} userID, optional - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} Array of decryption keys. - * @async - */ - async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const keys = []; - for (let i = 0; i < this.subkeys.length; i++) { - if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { - try { - const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; - const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidDecryptionKeyPacket(bindingSignature, config$1)) { - keys.push(this.subkeys[i]); - } - } catch (e) {} - } - } - - // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && - isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) { - keys.push(this); - } + g = mod$2(g, p); + y = mod$2(y, p); + const u1 = mod$2(h * w, q); // H(m) * w mod q + const u2 = mod$2(r * w, q); // r * w mod q + const t1 = modExp(g, u1, p); // g**u1 mod p + const t2 = modExp(y, u2, p); // y**u2 mod p + const v = mod$2(mod$2(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q + return v === r; +} - return keys; +/** + * Validate DSA parameters + * @param {Uint8Array} p - DSA prime + * @param {Uint8Array} q - DSA group order + * @param {Uint8Array} g - DSA sub-group generator + * @param {Uint8Array} y - DSA public key + * @param {Uint8Array} x - DSA private key + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$2(p, q, g, y, x) { + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + // Check that 1 < g < p + if (g <= _1n$9 || g >= p) { + return false; } /** - * Returns true if the primary key or any subkey is decrypted. - * A dummy key is considered encrypted. + * Check that subgroup order q divides p-1 */ - isDecrypted() { - return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); + if (mod$2(p - _1n$9, q) !== _0n$7) { + return false; } /** - * Check whether the private and public primary key parameters correspond - * Together with verification of binding signatures, this guarantees key integrity - * In case of gnu-dummy primary key, it is enough to validate any signing subkeys - * otherwise all encryption subkeys are validated - * If only gnu-dummy keys are found, we cannot properly validate so we throw an error - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if validation was not successful and the key cannot be trusted - * @async + * g has order q + * Check that g ** q = 1 mod p */ - async validate(config$1 = config) { - if (!this.isPrivate()) { - throw new Error('Cannot validate a public key'); - } - - let signingKeyPacket; - if (!this.keyPacket.isDummy()) { - signingKeyPacket = this.keyPacket; - } else { - /** - * It is enough to validate any signing keys - * since its binding signatures are also checked - */ - const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); - // This could again be a dummy key - if (signingKey && !signingKey.keyPacket.isDummy()) { - signingKeyPacket = signingKey.keyPacket; - } - } - - if (signingKeyPacket) { - return signingKeyPacket.validate(); - } else { - const keys = this.getKeys(); - const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); - if (allDummies) { - throw new Error('Cannot validate an all-gnu-dummy key'); - } - - return Promise.all(keys.map(async key => key.keyPacket.validate())); - } + if (modExp(g, q, p) !== _1n$9) { + return false; } /** - * Clear private key parameters + * Check q is large and probably prime (we mainly want to avoid small factors) */ - clearPrivateParams() { - this.getKeys().forEach(({ keyPacket }) => { - if (keyPacket.isDecrypted()) { - keyPacket.clearPrivateParams(); - } - }); + const qSize = BigInt(bitLength(q)); + const _150n = BigInt(150); + if (qSize < _150n || !isProbablePrime(q, null, 32)) { + return false; } /** - * Revokes the key - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New key with revocation signature. - * @async + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{rq + x} to compare to y */ - async revoke( - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - if (!this.isPrivate()) { - throw new Error('Need private key for revoking'); - } - const dataToSign = { key: this.keyPacket }; - const key = this.clone(); - key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, undefined, config$1)); - return key; + x = uint8ArrayToBigInt(x); + const _2n = BigInt(2); + const r = getRandomBigInteger(_2n << (qSize - _1n$9), _2n << qSize); // draw r of same size as q + const rqx = q * r + x; + if (y !== modExp(g, rqx, p)) { + return false; } + return true; +} + +var dsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$2, + validateParams: validateParams$2, + verify: verify$2 +}); - /** - * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. - * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. - * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA - * @param {String} options.curve (optional) Elliptic curve for ECC keys - * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date (optional) Override the creation date of the key and the key signatures - * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false - * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} - * @async - */ - async addSubkey(options = {}) { - const config$1 = { ...config, ...options.config }; - if (options.passphrase) { - throw new Error('Subkey could not be encrypted here, please encrypt whole key'); +/** + * @fileoverview Asymmetric cryptography functions + * @module crypto/public_key + */ + + +var publicKey = { + /** @see module:crypto/public_key/rsa */ + rsa: rsa, + /** @see module:crypto/public_key/elgamal */ + elgamal: elgamal, + /** @see module:crypto/public_key/elliptic */ + elliptic: elliptic, + /** @see module:crypto/public_key/dsa */ + dsa: dsa +}; + +/** + * @fileoverview Provides functions for asymmetric signing and signature verification + * @module crypto/signature + */ + + +/** + * Parse signature in binary form to get the parameters. + * The returned values are only padded for EdDSA, since in the other cases their expected length + * depends on the key params, hence we delegate the padding to the signature verification function. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Uint8Array} signature - Data for which the signature was created + * @returns {Promise} True if signature is valid. + * @async + */ +function parseSignatureParams(algo, signature) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA signatures: + // - MPI of RSA signature value m**d mod n. + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + // The signature needs to be the same length as the public key modulo n. + // We pad s on signature verification, where we have access to n. + return { read, signatureParams: { s } }; } - if (options.rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); + // Algorithm-Specific Fields for DSA or ECDSA signatures: + // - MPI of DSA or ECDSA value r. + // - MPI of DSA or ECDSA value s. + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + { + // If the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; } - const secretKeyPacket = this.keyPacket; - if (secretKeyPacket.isDummy()) { - throw new Error('Cannot add subkey to gnu-dummy primary key'); + // Algorithm-Specific Fields for legacy EdDSA signatures: + // - MPI of an EC point r. + // - EdDSA value s, in MPI, in the little endian representation + case enums.publicKey.eddsaLegacy: { + // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature + // verification: if the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; } - if (!secretKeyPacket.isDecrypted()) { - throw new Error('Key is not decrypted'); + // Algorithm-Specific Fields for Ed25519 signatures: + // - 64 octets of the native signature + // Algorithm-Specific Fields for Ed448 signatures: + // - 114 octets of the native signature + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo); + const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length; + return { read, signatureParams: { RS } }; } - const defaultOptions = secretKeyPacket.getAlgorithmInfo(); - defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA - defaultOptions.rsaBits = defaultOptions.bits || 4096; - defaultOptions.curve = defaultOptions.curve || 'curve25519'; - options = sanitizeKeyOptions(options, defaultOptions); - const keyPacket = await generateSecretSubkey(options); - checkKeyRequirements(keyPacket, config$1); - const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); - const packetList = this.toPacketList(); - packetList.push(keyPacket, bindingSignature); - return new PrivateKey(packetList); + + default: + throw new UnsupportedError('Unknown signature algorithm.'); } } -// OpenPGP.js - An OpenPGP implementation in javascript - -// A Key can contain the following packets -const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ - PublicKeyPacket, - PublicSubkeyPacket, - SecretKeyPacket, - SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, - SignaturePacket -]); - /** - * Creates a PublicKey or PrivateKey depending on the packetlist in input - * @param {PacketList} - packets to parse - * @return {Key} parsed key - * @throws if no key packet was found + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} signature - Named algorithm-specific signature parameters + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Data for which the signature was created + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} True if signature is valid. + * @async */ -function createKey(packetlist) { - for (const packet of packetlist) { - switch (packet.constructor.tag) { - case enums.packet.secretKey: - return new PrivateKey(packetlist); - case enums.packet.publicKey: - return new PublicKey(packetlist); +async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto + return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); + } + case enums.publicKey.dsa: { + const { g, p, q, y } = publicParams; + const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers + return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); + } + case enums.publicKey.ecdsa: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // padding needed for webcrypto + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values: + // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed); } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); } - throw new Error('No key packet found'); } - /** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * By default, primary and subkeys will be of same type. - * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA - * @param {String} options.curve Elliptic curve for ECC keys - * @param {Integer} options.rsaBits Number of bits for RSA keys - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Creation date of the key and the key signatures - * @param {Object} config - Full configuration - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters + * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters + * @param {Uint8Array} data - Data to be signed + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} Signature Object containing named signature parameters. * @async - * @static - * @private */ -async function generate$4(options, config) { - options.sign = true; // primary key is always a signing key - options = sanitizeKeyOptions(options); - options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); - let promises = [generateSecretKey(options, config)]; - promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); - const packets = await Promise.all(promises); - - const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; +async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { + if (!publicKeyParams || !privateKeyParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); + return { s }; + } + case enums.publicKey.dsa: { + const { g, p, q } = publicKeyParams; + const { x } = privateKeyParams; + return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); + } + case enums.publicKey.elgamal: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + case enums.publicKey.ecdsa: { + const { oid, Q } = publicKeyParams; + const { d } = privateKeyParams; + return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); + } } -/** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param {PrivateKey} options.privateKey The private key to reformat - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Override the creation date of the key signatures - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * @param {Object} config - Full configuration - * - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ -async function reformat(options, config) { - options = sanitize(options); - const { privateKey } = options; +var signature = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseSignatureParams: parseSignatureParams, + sign: sign$1, + verify: verify$1 +}); - if (!privateKey.isPrivate()) { - throw new Error('Cannot reformat a public key'); - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (privateKey.keyPacket.isDummy()) { - throw new Error('Cannot reformat a gnu-dummy primary key'); - } - const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); - if (!isDecrypted) { - throw new Error('Key is not decrypted'); +class ECDHSymmetricKey { + constructor(data) { + if (data) { + this.data = data; + } } - const secretKeyPacket = privateKey.keyPacket; - - if (!options.subkeys) { - options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { - const secretSubkeyPacket = subkey.keyPacket; - const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; - const bindingSignature = await ( - getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) - ).catch(() => ({})); - return { - sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) - }; - })); + /** + * Read an ECDHSymmetricKey from an Uint8Array: + * - 1 octect for the length `l` + * - `l` octects of encoded session key data + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + if (bytes.length >= 1) { + const length = bytes[0]; + if (bytes.length >= 1 + length) { + this.data = bytes.subarray(1, 1 + length); + return 1 + this.data.length; + } + } + throw new Error('Invalid symmetric key'); } - const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); - if (options.subkeys.length !== secretSubkeyPackets.length) { - throw new Error('Number of subkey options does not match number of subkeys'); + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); } +} - options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); - - const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; - - function sanitize(options, subkeyDefaults = {}) { - options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return options; - } -} /** - * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection - * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. - * @param {SecretKeyPacket} secretKeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPackets - * @param {Object} options - * @param {Object} config - Full configuration - * @returns {PrivateKey} + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @module type/kdf_params + * @private */ -async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { - // set passphrase protection - if (options.passphrase) { - await secretKeyPacket.encrypt(options.passphrase, config); - } - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - await secretSubkeyPacket.encrypt(subkeyPassphrase, config); +class KDFParams { + /** + * @param {enums.hash} hash - Hash algorithm + * @param {enums.symmetric} cipher - Symmetric algorithm + */ + constructor(data) { + if (data) { + const { hash, cipher } = data; + this.hash = hash; + this.cipher = cipher; + } else { + this.hash = null; + this.cipher = null; } - })); - - const packetlist = new PacketList(); - packetlist.push(secretKeyPacket); + } - await Promise.all(options.userIDs.map(async function(userID, index) { - function createPreferredAlgos(algos, preferredAlgo) { - return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + /** + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input - Where to read the KDFParams from + * @returns {Number} Number of read bytes. + */ + read(input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new UnsupportedError('Cannot read KDFParams'); } + this.hash = input[2]; + this.cipher = input[3]; + return 4; + } - const userIDPacket = UserIDPacket.fromObject(userID); - const dataToSign = {}; - dataToSign.userID = userIDPacket; - dataToSign.key = secretKeyPacket; - - const signatureProperties = {}; - signatureProperties.signatureType = enums.signature.certGeneric; - signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; - signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([ - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) - enums.symmetric.aes256, - enums.symmetric.aes128, - enums.symmetric.aes192 - ], config.preferredSymmetricAlgorithm); - if (config.aeadProtect) { - signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([ - enums.aead.eax, - enums.aead.ocb - ], config.preferredAEADAlgorithm); - } - signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ - // prefer fast asm.js implementations (SHA-256) - enums.hash.sha256, - enums.hash.sha512 - ], config.preferredHashAlgorithm); - signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ - enums.compression.zlib, - enums.compression.zip, - enums.compression.uncompressed - ], config.preferredCompressionAlgorithm); - if (index === 0) { - signatureProperties.isPrimaryUserID = true; - } - // integrity protection always enabled - signatureProperties.features = [0]; - signatureProperties.features[0] |= enums.features.modificationDetection; - if (config.aeadProtect) { - signatureProperties.features[0] |= enums.features.aead; - } - if (config.v5Keys) { - signatureProperties.features[0] |= enums.features.v5Keys; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; - } + /** + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value + */ + write() { + return new Uint8Array([3, 1, this.hash, this.cipher]); + } +} - const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); +/** + * Encoded symmetric key for x25519 and x448 + * The payload format varies for v3 and v6 PKESK: + * the former includes an algorithm byte preceeding the encrypted session key. + * + * @module type/x25519x448_symkey + */ - return { userIDPacket, signaturePacket }; - })).then(list => { - list.forEach(({ userIDPacket, signaturePacket }) => { - packetlist.push(userIDPacket); - packetlist.push(signaturePacket); - }); - }); - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyOptions = options.subkeys[index]; - const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); - return { secretSubkeyPacket, subkeySignaturePacket }; - })).then(packets => { - packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { - packetlist.push(secretSubkeyPacket); - packetlist.push(subkeySignaturePacket); - }); - }); +class ECDHXSymmetricKey { + static fromObject({ wrappedKey, algorithm }) { + const instance = new ECDHXSymmetricKey(); + instance.wrappedKey = wrappedKey; + instance.algorithm = algorithm; + return instance; + } - // Add revocation signature packet for creating a revocation certificate. - // This packet should be removed before returning the key. - const dataToSign = { key: secretKeyPacket }; - packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.reasonForRevocation.noReason, - reasonForRevocationString: '' - }, options.date, undefined, undefined, undefined, config)); + /** + * - 1 octect for the length `l` + * - `l` octects of encoded session key data (with optional leading algorithm byte) + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. + */ + read(bytes) { + let read = 0; + let followLength = bytes[read++]; + this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even + followLength -= followLength % 2; + this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength; + } - if (options.passphrase) { - secretKeyPacket.clearPrivateParams(); + /** + * Write an MontgomerySymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data + */ + write() { + return util.concatUint8Array([ + this.algorithm ? + new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : + new Uint8Array([this.wrappedKey.length]), + this.wrappedKey + ]); } +} - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - secretSubkeyPacket.clearPrivateParams(); - } - })); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return new PrivateKey(packetlist); -} /** - * Reads an (optionally armored) OpenPGP key and returns a key object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} keyAlgo - Public key algorithm + * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only) + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Session key data to be encrypted + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @returns {Promise} Encrypted session key parameters. * @async - * @static */ -async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { - throw new Error('Armored text not of type key'); +async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const { n, e } = publicParams; + const c = await publicKey.rsa.encrypt(data, n, e); + return { c }; } - input = data; - } else { - input = binaryKey; + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + return publicKey.elgamal.encrypt(data, p, g, y); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicParams; + const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( + oid, kdfParams, data, Q, fingerprint); + return { V, C: new ECDHSymmetricKey(C) }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + if (symmetricAlgo && !util.isAES(symmetricAlgo)) { + // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 + throw new Error('X25519 and X448 keys can only encrypt AES session keys'); + } + const { A } = publicParams; + const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( + keyAlgo, data, A); + const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); + return { ephemeralPublicKey, C }; + } + default: + return []; } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return createKey(packetlist); } /** - * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Object} publicKeyParams - Algorithm-specific public key parameters + * @param {Object} privateKeyParams - Algorithm-specific private key parameters + * @param {Object} sessionKeyParams - Encrypted session key parameters + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing + * (needed for constant-time processing in RSA and ElGamal) + * @returns {Promise} Decrypted data. + * @throws {Error} on sensitive decryption error, unless `randomPayload` is given * @async - * @static */ -async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readPrivateKey: options.armoredKey must be a string'); +async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: { + const { c } = sessionKeyParams; + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); + } + case enums.publicKey.elgamal: { + const { c1, c2 } = sessionKeyParams; + const p = publicKeyParams.p; + const x = privateKeyParams.x; + return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicKeyParams; + const { d } = privateKeyParams; + const { V, C } = sessionKeyParams; + return publicKey.elliptic.ecdh.decrypt( + oid, kdfParams, V, C.data, Q, d, fingerprint); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicKeyParams; + const { k } = privateKeyParams; + const { ephemeralPublicKey, C } = sessionKeyParams; + if (C.algorithm !== null && !util.isAES(C.algorithm)) { + throw new Error('AES session key expected'); + } + return publicKey.elliptic.ecdhX.decrypt( + algo, ephemeralPublicKey, C.wrappedKey, A, k); + } + default: + throw new Error('Unknown public key encryption algorithm.'); } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); +} + +/** + * Parse public key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. + */ +function parsePublicKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; + const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; + return { read, publicParams: { n, e } }; + } + case enums.publicKey.dsa: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, q, g, y } }; + } + case enums.publicKey.elgamal: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, g, y } }; + } + case enums.publicKey.ecdsa: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.eddsaLegacy: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + if (oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + Q = util.leftPad(Q, 33); + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.ecdh: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); + return { read: read, publicParams: { oid, Q, kdfParams } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length; + return { read, publicParams: { A } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +} - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.privateKey)) { - throw new Error('Armored text not of type private key'); +/** + * Parse private key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @param {Object} publicParams - (ECC only) public params, needed to format some private params + * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. + */ +function parsePrivateKeyParams(algo, bytes, publicParams) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; + return { read, privateParams: { d, p, q, u } }; + } + case enums.publicKey.dsa: + case enums.publicKey.elgamal: { + const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; + return { read, privateParams: { x } }; + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + d = util.leftPad(d, payloadSize); + return { read, privateParams: { d } }; + } + case enums.publicKey.eddsaLegacy: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; + seed = util.leftPad(seed, payloadSize); + return { read, privateParams: { seed } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const payloadSize = getCurvePayloadSize(algo); + const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length; + return { read, privateParams: { seed } }; } - input = data; - } else { - input = binaryKey; + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const payloadSize = getCurvePayloadSize(algo); + const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length; + return { read, privateParams: { k } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return new PrivateKey(packetlist); } -/** - * Reads an (optionally armored) OpenPGP key block and returns a list of key objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static +/** Returns the types comprising the encrypted session key of an algorithm + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {Object} The session key parameters referenced by name. */ -async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +function parseEncSessionKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const c = util.readMPI(bytes.subarray(read)); + return { c }; + } - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { - throw new Error('Armored text not of type key'); + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case enums.publicKey.elgamal: { + const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; + const c2 = util.readMPI(bytes.subarray(read)); + return { c1, c2 }; } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = createKey(oneKeyList); - keys.push(newKey); + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case enums.publicKey.ecdh: { + const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; + const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); + return { V, C }; + } + // Algorithm-Specific Fields for X25519 or X448 encrypted session keys: + // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448). + // - A one-octet size of the following fields. + // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). + // - The encrypted session key. + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const pointSize = getCurvePayloadSize(algo); + const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length; + const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); + return { ephemeralPublicKey, C }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } - return keys; } /** - * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static + * Convert params to MPI and serializes them in the proper order + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} params - The key parameters indexed by name + * @returns {Uint8Array} The array containing the MPIs. */ -async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readPrivateKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); - } - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.privateKey) { - throw new Error('Armored text not of type private key'); - } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No secret key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = new PrivateKey(oneKeyList); - keys.push(newKey); - } - return keys; +function serializeParams(algo, params) { + // Some algorithms do not rely on MPIs to store the binary params + const algosWithNativeRepresentation = new Set([ + enums.publicKey.ed25519, + enums.publicKey.x25519, + enums.publicKey.ed448, + enums.publicKey.x448 + ]); + const orderedParams = Object.keys(params).map(name => { + const param = params[name]; + if (!util.isUint8Array(param)) return param.write(); + return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); + }); + return util.concatUint8Array(orderedParams); } -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Message can contain the following packets -const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - AEADEncryptedDataPacket, - SymEncryptedIntegrityProtectedDataPacket, - SymmetricallyEncryptedDataPacket, - PublicKeyEncryptedSessionKeyPacket, - SymEncryptedSessionKeyPacket, - OnePassSignaturePacket, - SignaturePacket -]); -// A SKESK packet can contain the following packets -const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); -// A detached signature can contain the following packets -const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - /** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + * Generate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Integer} bits - Bit length for RSA keys + * @param {module:type/oid} oid - Object identifier for ECC keys + * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. + * @async */ -class Message { - /** - * @param {PacketList} packetlist - The packets that form this message - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); - } - - /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns {Array} Array of keyID objects. - */ - getEncryptionKeyIDs() { - const keyIDs = []; - const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - pkESKeyPacketlist.forEach(function(packet) { - keyIDs.push(packet.publicKeyID); - }); - return keyIDs; - } - - /** - * Returns the key IDs of the keys that signed the message - * @returns {Array} Array of keyID objects. - */ - getSigningKeyIDs() { - const msg = this.unwrapCompressed(); - // search for one pass signatures - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); - if (onePassSigList.length > 0) { - return onePassSigList.map(packet => packet.issuerKeyID); - } - // if nothing found look for signature packets - const signatureList = msg.packets.filterByTag(enums.packet.signature); - return signatureList.map(packet => packet.issuerKeyID); - } - - /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Date} [date] - Use the given date for key verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with decrypted content. - * @async - */ - async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { - const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - - const symEncryptedPacketlist = this.packets.filterByTag( - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ); +function generateParams(algo, bits, oid) { + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ + privateParams: { d, p, q, u }, + publicParams: { n, e } + })); + case enums.publicKey.ecdsa: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { d: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { seed: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.ecdh: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ + privateParams: { d: secret }, + publicParams: { + oid: new OID(oid), + Q, + kdfParams: new KDFParams({ hash, cipher }) + } + })); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ + privateParams: { seed }, + publicParams: { A } + })); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ + privateParams: { k }, + publicParams: { A } + })); + case enums.publicKey.dsa: + case enums.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + default: + throw new Error('Unknown public key algorithm.'); + } +} - if (symEncryptedPacketlist.length === 0) { - throw new Error('No encrypted data found'); +/** + * Validate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Object} privateParams - Algorithm-specific private key parameters + * @returns {Promise} Whether the parameters are valid. + * @async + */ +async function validateParams$1(algo, publicParams, privateParams) { + if (!publicParams || !privateParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const { d, p, q, u } = privateParams; + return publicKey.rsa.validateParams(n, e, d, p, q, u); } - - const symEncryptedPacket = symEncryptedPacketlist[0]; - let exception = null; - const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { - if (!util.isUint8Array(data) || !util.isString(algorithmName)) { - throw new Error('Invalid session key for decryption.'); - } - - try { - const algo = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.decrypt(algo, data, config$1); - } catch (e) { - util.printDebugError(e); - exception = e; - } - })); - // We don't await stream.cancel here because it only returns when the other copy is canceled too. - cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. - symEncryptedPacket.encrypted = null; - await decryptedPromise; - - if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { - throw exception || new Error('Decryption failed.'); + case enums.publicKey.dsa: { + const { p, q, g, y } = publicParams; + const { x } = privateParams; + return publicKey.dsa.validateParams(p, q, g, y, x); } - - const resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - - return resultMsg; + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + const { x } = privateParams; + return publicKey.elgamal.validateParams(p, g, y, x); + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; + const { oid, Q } = publicParams; + const { d } = privateParams; + return algoModule.validateParams(oid, Q, d); + } + case enums.publicKey.eddsaLegacy: { + const { Q, oid } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsa.validateParams(algo, A, seed); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicParams; + const { k } = privateParams; + return publicKey.elliptic.ecdhX.validateParams(algo, A, k); + } + default: + throw new Error('Unknown public key algorithm.'); } +} - /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Date} [date] - Use the given date for key verification, instead of current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} array of object with potential sessionKey, algorithm pairs - * @async - */ - async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) { - let decryptedSessionKeyPackets = []; - - let exception; - if (passwords) { - const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); - if (skeskPackets.length === 0) { - throw new Error('No symmetrically encrypted session key packet found.'); - } - await Promise.all(passwords.map(async function(password, i) { - let packets; - if (i) { - packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); - } else { - packets = skeskPackets; - } - await Promise.all(packets.map(async function(skeskPacket) { - try { - await skeskPacket.decrypt(password); - decryptedSessionKeyPackets.push(skeskPacket); - } catch (err) { - util.printDebugError(err); - } - })); - })); - } else if (decryptionKeys) { - const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - if (pkeskPackets.length === 0) { - throw new Error('No public key encrypted session key packet found.'); - } - await Promise.all(pkeskPackets.map(async function(pkeskPacket) { - await Promise.all(decryptionKeys.map(async function(decryptionKey) { - let algos = [ - enums.symmetric.aes256, // Old OpenPGP.js default fallback - enums.symmetric.aes128, // RFC4880bis fallback - enums.symmetric.tripledes, // RFC4880 fallback - enums.symmetric.cast5 // Golang OpenPGP fallback - ]; - try { - const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere. - if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { - algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); - } - } catch (e) {} - - // do not check key expiration to allow decryption of old messages - const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); - await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { - if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) { - return; - } - if (!decryptionKeyPacket.isDecrypted()) { - throw new Error('Decryption key is not decrypted.'); - } - - // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. - const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal - ); - - if (doConstantTimeDecryption) { - // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, - // either with the successfully decrypted session key, or with a randomly generated one. - // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on - // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: - // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the - // randomly generated keys of the remaining key types. - // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly - // generated session keys. - // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. - - const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times - await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => { - const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); - pkeskPacketCopy.read(serialisedPKESK); - const randomSessionKey = { - sessionKeyAlgorithm, - sessionKey: mod.generateSessionKey(sessionKeyAlgorithm) - }; - try { - await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); - decryptedSessionKeyPackets.push(pkeskPacketCopy); - } catch (err) { - // `decrypt` can still throw some non-security-sensitive errors - util.printDebugError(err); - exception = err; - } - })); +/** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + * @async + */ +async function getPrefixRandom(algo) { + const { blockSize } = getCipherParams(algo); + const prefixrandom = await getRandomBytes(blockSize); + const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + return util.concat([prefixrandom, repeat]); +} - } else { - try { - await pkeskPacket.decrypt(decryptionKeyPacket); - if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) { - throw new Error('A non-preferred symmetric algorithm was used.'); - } - decryptedSessionKeyPackets.push(pkeskPacket); - } catch (err) { - util.printDebugError(err); - exception = err; - } - } - })); - })); - cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. - pkeskPacket.encrypted = null; - })); - } else { - throw new Error('No key or password specified.'); - } +/** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key. + */ +function generateSessionKey$1(algo) { + const { keySize } = getCipherParams(algo); + return getRandomBytes(keySize); +} - if (decryptedSessionKeyPackets.length > 0) { - // Return only unique session keys - if (decryptedSessionKeyPackets.length > 1) { - const seen = new Set(); - decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { - const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); - if (seen.has(k)) { - return false; - } - seen.add(k); - return true; - }); - } +/** + * Get implementation of the given AEAD mode + * @param {enums.aead} algo + * @returns {Object} + * @throws {Error} on invalid algo + */ +function getAEADMode(algo) { + const algoName = enums.read(enums.aead, algo); + return mode[algoName]; +} - return decryptedSessionKeyPackets.map(packet => ({ - data: packet.sessionKey, - algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm) - })); - } - throw exception || new Error('Session key decryption failed.'); +/** + * Check whether the given curve OID is supported + * @param {module:type/oid} oid - EC object identifier + * @throws {UnsupportedError} if curve is not supported + */ +function checkSupportedCurve(oid) { + try { + oid.getName(); + } catch (e) { + throw new UnsupportedError('Unknown curve OID'); } +} - /** - * Get literal data that is the body of the message - * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. - */ - getLiteralData() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getBytes()) || null; +/** + * Get encoded secret size for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getCurvePayloadSize(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: + case enums.publicKey.eddsaLegacy: + return new publicKey.elliptic.CurveWithOID(oid).payloadSize; + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPayloadSize(algo); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.getPayloadSize(algo); + default: + throw new Error('Unknown elliptic algo'); } +} - /** - * Get filename from literal data packet - * @returns {(String|null)} Filename of literal data packet as string. - */ - getFilename() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getFilename()) || null; +/** + * Get preferred signing hash algo for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getPreferredCurveHashAlgo(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.getPreferredHashAlgo(oid); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); + default: + throw new Error('Unknown elliptic signing algo'); } +} - /** - * Get literal data as text - * @returns {(String|null)} Literal body of the message interpreted as text. - */ - getText() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - if (literal) { - return literal.getText(); - } - return null; - } +var crypto$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + generateParams: generateParams, + generateSessionKey: generateSessionKey$1, + getAEADMode: getAEADMode, + getCipherParams: getCipherParams, + getCurvePayloadSize: getCurvePayloadSize, + getPreferredCurveHashAlgo: getPreferredCurveHashAlgo, + getPrefixRandom: getPrefixRandom, + parseEncSessionKeyParams: parseEncSessionKeyParams, + parsePrivateKeyParams: parsePrivateKeyParams, + parsePublicKeyParams: parsePublicKeyParams, + publicKeyDecrypt: publicKeyDecrypt, + publicKeyEncrypt: publicKeyEncrypt, + serializeParams: serializeParams, + validateParams: validateParams$1 +}); - /** - * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. - * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for - * @param {Date} [date] - Date to select algorithm preferences at - * @param {Array} [userIDs] - User IDs to select algorithm preferences for - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. - * @async - */ - static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { - const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1); - const algorithmName = enums.read(enums.symmetric, algo); - const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ? - enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) : - undefined; +/** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ - await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() - .catch(() => null) // ignore key strength requirements - .then(maybeKey => { - if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) { - throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); - } - }) - )); - const sessionKeyData = mod.generateSessionKey(algo); - return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName }; - } +// TODO move cfb and gcm to cipher +const mod$1 = { + /** @see module:crypto/cipher */ + cipher: cipher, + /** @see module:crypto/hash */ + hash: hash$1, + /** @see module:crypto/mode */ + mode: mode, + /** @see module:crypto/public_key */ + publicKey: publicKey, + /** @see module:crypto/signature */ + signature: signature, + /** @see module:crypto/random */ + random: random, + /** @see module:crypto/pkcs1 */ + pkcs1: pkcs1, + /** @see module:crypto/pkcs5 */ + pkcs5: pkcs5, + /** @see module:crypto/aes_kw */ + aesKW: aesKW +}; - /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - Password(s) for message encryption - * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] - * @param {Date} [date] - Override the creation date of the literal package - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async - */ - async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - if (sessionKey) { - if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { - throw new Error('Invalid session key for encryption.'); - } - } else if (encryptionKeys && encryptionKeys.length) { - sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); - } else if (passwords && passwords.length) { - sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); - } else { - throw new Error('No keys, passwords, or session key provided.'); - } +Object.assign(mod$1, crypto$2); - const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; +const ARGON2_TYPE = 0x02; // id +const ARGON2_VERSION = 0x13; +const ARGON2_SALT_SIZE = 16; - const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); +class Argon2OutOfMemoryError extends Error { + constructor(...params) { + super(...params); - let symEncryptedPacket; - if (aeadAlgorithmName) { - symEncryptedPacket = new AEADEncryptedDataPacket(); - symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName); - } else { - symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Argon2OutOfMemoryError); } - symEncryptedPacket.packets = this.packets; - - const algorithm = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); - msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new PacketList(); // remove packets after encryption - return msg; + this.name = 'Argon2OutOfMemoryError'; } +} - /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param {Uint8Array} sessionKey - session key for encryption - * @param {String} algorithmName - session key algorithm - * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - For message encryption - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [date] - Override the date - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async - */ - static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - const packetlist = new PacketList(); - const algorithm = enums.write(enums.symmetric, algorithmName); - const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); +// cache argon wasm module +let loadArgonWasmModule; +let argon2Promise; +// reload wasm module above this treshold, to deallocated used memory +const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; - if (encryptionKeys) { - const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { - const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = algorithm; - await pkESKeyPacket.encrypt(encryptionKey.keyPacket); - delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption - return pkESKeyPacket; - })); - packetlist.push(...results); - } - if (passwords) { - const testDecrypt = async function(keyPacket, password) { - try { - await keyPacket.decrypt(password); - return 1; - } catch (e) { - return 0; - } - }; +class Argon2S2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params; - const sum = (accumulator, currentValue) => accumulator + currentValue; + this.type = 'argon2'; + /** + * 16 bytes of salt + * @type {Uint8Array} + */ + this.salt = null; + /** + * number of passes + * @type {Integer} + */ + this.t = passes; + /** + * degree of parallelism (lanes) + * @type {Integer} + */ + this.p = parallelism; + /** + * exponent indicating memory size + * @type {Integer} + */ + this.encodedM = memoryExponent; + } - const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { - const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); - symEncryptedSessionKeyPacket.sessionKey = sessionKey; - symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; - if (aeadAlgorithm) { - symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; - } - await symEncryptedSessionKeyPacket.encrypt(password, config$1); + generateSalt() { + this.salt = mod$1.random.getRandomBytes(ARGON2_SALT_SIZE); + } - if (config$1.passwordCollisionCheck) { - const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); - if (results.reduce(sum) !== 1) { - return encryptPassword(sessionKey, algorithm, password); - } - } + /** + * Parsing function for argon2 string-to-key specifier. + * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; - delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption - return symEncryptedSessionKeyPacket; - }; + this.salt = bytes.subarray(i, i + 16); + i += 16; - const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd))); - packetlist.push(...results); - } + this.t = bytes[i++]; + this.p = bytes[i++]; + this.encodedM = bytes[i++]; // memory size exponent, one-octect - return new Message(packetlist); + return i; } /** - * Sign the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to add to the message - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with signed content. - * @async - */ - async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const packetlist = new PacketList(); + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + const arr = [ + new Uint8Array([enums.write(enums.s2k, this.type)]), + this.salt, + new Uint8Array([this.t, this.p, this.encodedM]) + ]; - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } + return util.concatUint8Array(arr); + } - let i; - let existingSigPacketlist; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to `keySize` + * @throws {Argon2OutOfMemoryError|Errors} + * @async + */ + async produceKey(passphrase, keySize) { + const decodedM = 2 << (this.encodedM - 1); - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signaturePacket.signatureType; - onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; - onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyID = signaturePacket.issuerKeyID; - if (!signingKeys.length && i === 0) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); - } - } + try { + // on first load, the argon2 lib is imported and the WASM module is initialized. + // the two steps need to be atomic to avoid race conditions causing multiple wasm modules + // being loaded when `argon2Promise` is not initialized. + loadArgonWasmModule = loadArgonWasmModule || (await Promise.resolve().then(function () { return index$1; })).default; + argon2Promise = argon2Promise || loadArgonWasmModule(); + + // important to keep local ref to argon2 in case the module is reloaded by another instance + const argon2 = await argon2Promise; + + const passwordBytes = util.encodeUTF8(passphrase); + const hash = argon2({ + version: ARGON2_VERSION, + type: ARGON2_TYPE, + password: passwordBytes, + salt: this.salt, + tagLength: keySize, + memorySize: decodedM, + parallelism: this.p, + passes: this.t + }); - await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) { - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); + // a lot of memory was used, reload to deallocate + if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); } - const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i]; - const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1); - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1); - onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyID = signingKey.getKeyID(); - if (i === signingKeys.length - 1) { - onePassSig.flags = 1; + return hash; + } catch (e) { + if (e.message && ( + e.message.includes('Unable to grow instance memory') || // Chrome + e.message.includes('failed to grow memory') || // Firefox + e.message.includes('WebAssembly.Memory.grow') || // Safari + e.message.includes('Out of memory') // Safari iOS + )) { + throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2'); + } else { + throw e; } - return onePassSig; - })).then(onePassSignatureList => { - onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig)); - }); + } + } +} - packetlist.push(literalDataPacket); - packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1))); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return new Message(packetlist); - } +class GenericS2K { /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param {module:enums.compression} algo - compression algorithm * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Message} New message with compressed content. */ - compress(algo, config$1 = config) { - if (algo === enums.compression.uncompressed) { - return this; - } + constructor(s2kType, config$1 = config) { + /** + * Hash function identifier, or 0 for gnu-dummy keys + * @type {module:enums.hash | 0} + */ + this.algorithm = enums.hash.sha256; + /** + * enums.s2k identifier or 'gnu-dummy' + * @type {String} + */ + this.type = enums.read(enums.s2k, s2kType); + /** @type {Integer} */ + this.c = config$1.s2kIterationCountByte; + /** Eight bytes of salt in a binary string. + * @type {Uint8Array} + */ + this.salt = null; + } - const compressed = new CompressedDataPacket(config$1); - compressed.algorithm = algo; - compressed.packets = this.packets; + generateSalt() { + switch (this.type) { + case 'salted': + case 'iterated': + this.salt = mod$1.random.getRandomBytes(8); + } + } - const packetList = new PacketList(); - packetList.push(compressed); + getCount() { + // Exponent bias, defined in RFC4880 + const expbias = 6; - return new Message(packetList); + return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); } /** - * Create a detached signature for the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New detached signature of message content. - * @async + * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param {Uint8Array} bytes - Payload of string-to-key specifier + * @returns {Integer} Actual length of the object. */ - async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } - return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - } + read(bytes) { + let i = 0; + this.algorithm = bytes[i++]; - /** - * Verify message signatures - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signatures. - * @async - */ - async verify(verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); - } - if (isArrayStream(msg.packets.stream)) { - msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); - } - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); - const signatureList = msg.packets.filterByTag(enums.packet.signature); - if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { - await Promise.all(onePassSigList.map(async onePassSig => { - onePassSig.correspondingSig = new Promise((resolve, reject) => { - onePassSig.correspondingSigResolve = resolve; - onePassSig.correspondingSigReject = reject; - }); - onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); - onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); - onePassSig.hashed.catch(() => {}); - })); - msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { - const reader = getReader(readable); - const writer = getWriter(writable); - try { - for (let i = 0; i < onePassSigList.length; i++) { - const { value: signature } = await reader.read(); - onePassSigList[i].correspondingSigResolve(signature); + switch (this.type) { + case 'simple': + break; + + case 'salted': + this.salt = bytes.subarray(i, i + 8); + i += 8; + break; + + case 'iterated': + this.salt = bytes.subarray(i, i + 8); + i += 8; + + // Octet 10: count, a one-octet, coded value + this.c = bytes[i++]; + break; + + case 'gnu': + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { + i += 3; // GNU + const gnuExtType = 1000 + bytes[i++]; + if (gnuExtType === 1001) { + this.type = 'gnu-dummy'; + // GnuPG extension mode 1001 -- don't write secret key at all + } else { + throw new UnsupportedError('Unknown s2k gnu protection mode.'); } - await reader.readToEnd(); - await writer.ready; - await writer.close(); - } catch (e) { - onePassSigList.forEach(onePassSig => { - onePassSig.correspondingSigReject(e); - }); - await writer.abort(e); + } else { + throw new UnsupportedError('Unknown s2k type.'); } - }); - return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + break; + + default: + throw new UnsupportedError('Unknown s2k type.'); // unreachable } - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); + + return i; } /** - * Verify detached message signature - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Signature} signature - * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. */ - verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); + write() { + if (this.type === 'gnu-dummy') { + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); } - const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; + + switch (this.type) { + case 'simple': + break; + case 'salted': + arr.push(this.salt); + break; + case 'iterated': + arr.push(this.salt); + arr.push(new Uint8Array([this.c])); + break; + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + + return util.concatUint8Array(arr); } /** - * Unwrap compressed message - * @returns {Message} Message Content of compressed message. + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to. + * hashAlgorithm hash length + * @async */ - unwrapCompressed() { - const compressed = this.packets.filterByTag(enums.packet.compressedData); - if (compressed.length) { - return new Message(compressed[0].packets); + async produceKey(passphrase, numBytes) { + passphrase = util.encodeUTF8(passphrase); + + const arr = []; + let rlength = 0; + + let prefixlen = 0; + while (rlength < numBytes) { + let toHash; + switch (this.type) { + case 'simple': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); + break; + case 'salted': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); + break; + case 'iterated': { + const data = util.concatUint8Array([this.salt, passphrase]); + let datalen = data.length; + const count = Math.max(this.getCount(), datalen); + toHash = new Uint8Array(prefixlen + count); + toHash.set(data, prefixlen); + for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { + toHash.copyWithin(pos, prefixlen, pos); + } + break; + } + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + const result = await mod$1.hash.digest(this.algorithm, toHash); + arr.push(result); + rlength += result.length; + prefixlen++; } - return this; - } - - /** - * Append signature to unencrypted message object - * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async appendSignature(detachedSignature, config$1 = config) { - await this.packets.read( - util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, - allowedDetachedSignaturePackets, - config$1 - ); - } - - /** - * Returns binary encoded message - * @returns {ReadableStream} Binary message. - */ - write() { - return this.packets.write(); - } - /** - * Returns ASCII armored text of message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.message, this.write(), null, null, null, config$1); + return util.concatUint8Array(arr).subarray(0, numBytes); } } +const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]); + /** - * Create signature packets for the message - * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign - * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to append - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Boolean} [detached] - Whether to create detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} List of signature packets. - * @async - * @private + * Instantiate a new S2K instance of the given type + * @param {module:enums.s2k} type + * @oaram {Object} [config] + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types */ -async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) { - const packetlist = new PacketList(); - - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; - - await Promise.all(signingKeys.map(async (primaryKey, i) => { - const userID = userIDs[i]; - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1); - return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1); - })).then(signatureList => { - packetlist.push(...signatureList); - }); - - if (signature) { - const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - packetlist.push(...existingSigPacketlist); +function newS2KFromType(type, config$1 = config) { + switch (type) { + case enums.s2k.argon2: + return new Argon2S2K(config$1); + case enums.s2k.iterated: + case enums.s2k.gnu: + case enums.s2k.salted: + case enums.s2k.simple: + return new GenericS2K(type, config$1); + default: + throw new UnsupportedError('Unsupported S2K type'); } - return packetlist; } /** - * Create object containing signer's keyID and validity of signature - * @param {SignaturePacket} signature - Signature packet - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Check signature validity with respect to the given date - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * keyID: module:type/keyid~KeyID, - * signature: Promise, - * verified: Promise - * }>} signer's keyID and validity of signature - * @async - * @private + * Instantiate a new S2K instance based on the config settings + * @oaram {Object} config + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types */ -async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - let primaryKey; - let unverifiedSigningKey; +function newS2KFromConfig(config) { + const { s2kType } = config; - for (const key of verificationKeys) { - const issuerKeys = key.getKeys(signature.issuerKeyID); - if (issuerKeys.length > 0) { - primaryKey = key; - unverifiedSigningKey = issuerKeys[0]; - break; - } + if (!allowedS2KTypesForEncryption.has(s2kType)) { + throw new Error('The provided `config.s2kType` value is not allowed'); } - const isOnePassSignature = signature instanceof OnePassSignaturePacket; - const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; - - const verifiedSig = { - keyID: signature.issuerKeyID, - verified: (async () => { - if (!unverifiedSigningKey) { - throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); - } - - await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); - const signaturePacket = await signaturePacketPromise; - if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { - throw new Error('Key is newer than the signature'); - } - // We pass the signature creation time to check whether the key was expired at the time of signing. - // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before - try { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); - } catch (e) { - // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, - // making the key invalid at the time of signing. - // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. - // Note: we do not support the edge case of a key that was reformatted and it has expired. - if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); - } else { - throw e; - } - } - return true; - })(), - signature: (async () => { - const signaturePacket = await signaturePacketPromise; - const packetlist = new PacketList(); - signaturePacket && packetlist.push(signaturePacket); - return new Signature(packetlist); - })() - }; - - // Mark potential promise rejections as "handled". This is needed because in - // some cases, we reject them before the user has a reasonable chance to - // handle them (e.g. `await readToEnd(result.data); await result.verified` and - // the data stream errors). - verifiedSig.signature.catch(() => {}); - verifiedSig.verified.catch(() => {}); - - return verifiedSig; + return newS2KFromType(s2kType, config); } +var require = createRequire('/'); +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +// Mediocre shim +var Worker; +try { + Worker = require('worker_threads').Worker; +} +catch (e) { +} + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, u32$1 = Uint32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +// see fleb note +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new u32$1(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return [b, r]; +}; +var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >>> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32$1 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, buf, st) { + // source length + var sl = dat.length; + if (!sl || (st && st.f && !st.l)) + return buf || new u8(0); + // have to estimate size + var noBuf = !buf || st; + // no state + var noSt = !st || st.i; + if (!st) + st = {}; + // Assumes roughly 33% compression ratio average + if (!buf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (noBuf) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >>> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17; + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + d[o + 2] |= v >>> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return [et, 0]; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return [v, 1]; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return [new u8(tr), mbt]; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return [cl.subarray(0, cli), s]; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >>> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; + var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; + var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; + var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + lcfreq[lclt[i] & 31]++; + for (var i = 0; i < lcdt.length; ++i) + lcfreq[lcdt[i] & 31]++; + var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); + if (flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + if (syms[i] > 255) { + var len = (syms[i] >>> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; + var dst = syms[i] & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new u32$1([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, lst) { + var s = dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var pos = 0; + if (!lvl || s < 8) { + for (var i = 0; i <= s; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[pos >> 3] = lst; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + } + else { + var opt = deo[lvl - 1]; + var n = opt >>> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = new u16(32768), head = new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new u32$1(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx bitpos + var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; + for (; i < s; ++i) { + // hash value + // deopt when i > s - 3 - at end, deopt acceptable + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && rem > 423) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = (i - dif + j + 32768) & 32767; + var pti = prev[ti]; + var cd = (ti - pti + 32768) & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += (imod - pimod + 32768) & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one Uint32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + // this is the easiest way to avoid needing to maintain state + if (!lst && pos & 7) + pos = wfblk(w, pos + 1, et); + } + return slc(o, 0, pre + shft(pos) + post); +}; +// Alder32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); + } + }; +}; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st); +}; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); +}; +// zlib footer: -4 to -0 is Adler32 /** - * Create list of objects containing signer's keyID and validity of signature - * @param {Array} signatureList - Array of signature packets - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} date - Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) - * @async - * @private + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (!cb && typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, !f), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.d = final; + this.p(chunk, final || false); + }; + return Deflate; +}()); +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + /** + * Creates an inflation stream + * @param cb The callback to call whenever data is inflated + */ + function Inflate(cb) { + this.s = {}; + this.p = new u8(0); + this.ondata = cb; + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + var l = this.p.length; + var n = new u8(l + c.length); + n.set(this.p), n.set(c, l), this.p = n; + }; + Inflate.prototype.c = function (final) { + this.d = this.s.i = final || false; + var bts = this.s.b; + var dt = inflt(this.p, this.o, this.s); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + this.c.p(c); + var raw = dopt(c, this.o, this.v && 2, f && 4, !f); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + return Zlib; +}()); +/** + * Streaming Zlib decompression */ -async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - return Promise.all(signatureList.filter(function(signature) { - return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); - }).map(async function(signature) { - return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); - })); +var Unzlib = /*#__PURE__*/ (function () { + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + function Unzlib(cb) { + this.v = 1; + Inflate.call(this, cb); + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 2 && !final) + return; + this.p = this.p.subarray(2), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; } +catch (e) { } + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** - * Reads an (optionally armored) OpenPGP message and returns a Message object - * @param {Object} options - * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed - * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New message object. - * @async - * @static + * Implementation of the Literal Data Packet (Tag 11) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. */ -async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredMessage || binaryMessage; - if (!input) { - throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); - } - if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { - throw new Error('readMessage: options.armoredMessage must be a string or stream'); +class LiteralDataPacket { + static get tag() { + return enums.packet.literalData; } - if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { - throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); + + /** + * @param {Date} date - The creation date of the literal package + */ + constructor(date = new Date()) { + this.format = enums.literal.utf8; // default format for literal data packets + this.date = util.normalizeDate(date); + this.text = null; // textual data representation + this.data = null; // literal data representation + this.filename = ''; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param {String | ReadableStream} text - Any native javascript string + * @param {enums.literal} [format] - The format of the string of bytes + */ + setText(text, format = enums.literal.utf8) { + this.format = format; + this.text = text; + this.data = null; } - if (armoredMessage) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.message) { - throw new Error('Armored text not of type message'); + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {String | ReadableStream} Literal data as text. + */ + getText(clone = false) { + if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read + this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); } - input = data; + return this.text; } - const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); - const message = new Message(packetlist); - message.fromStream = streamType; - return message; -} -/** - * Creates new message object from text or binary data. - * @param {Object} options - * @param {String | ReadableStream} [options.text] - The text message contents - * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents - * @param {String} [options.filename=""] - Name of the file (if any) - * @param {Date} [options.date=current date] - Date of the message, or modification date of the file - * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type - * @returns {Promise} New message object. - * @async - * @static - */ -async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { - let input = text !== undefined ? text : binary; - if (input === undefined) { - throw new Error('createMessage: must pass options object containing `text` or `binary`'); + /** + * Set the packet data to value represented by the provided string of bytes. + * @param {Uint8Array | ReadableStream} bytes - The string of bytes + * @param {enums.literal} format - The format of the string of bytes + */ + setBytes(bytes, format) { + this.format = format; + this.data = bytes; + this.text = null; } - if (text && !util.isString(text) && !util.isStream(text)) { - throw new Error('createMessage: options.text must be a string or stream'); + + + /** + * Get the byte sequence representing the literal packet data + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {Uint8Array | ReadableStream} A sequence of bytes. + */ + getBytes(clone = false) { + if (this.data === null) { + // encode UTF8 and normalize EOL to \r\n + this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); + } + if (clone) { + return passiveClone(this.data); + } + return this.data; } - if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { - throw new Error('createMessage: options.binary must be a Uint8Array or stream'); + + + /** + * Sets the filename of the literal packet data + * @param {String} filename - Any native javascript string + */ + setFilename(filename) { + this.filename = filename; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); + + /** + * Get the filename of the literal packet data + * @returns {String} Filename. + */ + getFilename() { + return this.filename; } - const literalDataPacket = new LiteralDataPacket(date); - if (text !== undefined) { - literalDataPacket.setText(input, enums.write(enums.literal, format)); - } else { - literalDataPacket.setBytes(input, enums.write(enums.literal, format)); + + /** + * Parsing function for a literal data packet (tag 11). + * + * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet + * @returns {Promise} Object representation. + * @async + */ + async read(bytes) { + await parse(bytes, async reader => { + // - A one-octet field that describes how the data is formatted. + const format = await reader.readByte(); // enums.literal + + const filename_len = await reader.readByte(); + this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); + + this.date = util.readDate(await reader.readBytes(4)); + + let data = reader.remainder(); + if (isArrayStream(data)) data = await readToEnd(data); + this.setBytes(data, format); + }); } - if (filename !== undefined) { - literalDataPacket.setFilename(filename); + + /** + * Creates a Uint8Array representation of the packet, excluding the data + * + * @returns {Uint8Array} Uint8Array representation of the packet. + */ + writeHeader() { + const filename = util.encodeUTF8(this.filename); + const filename_length = new Uint8Array([filename.length]); + + const format = new Uint8Array([this.format]); + const date = util.writeDate(this.date); + + return util.concatUint8Array([format, filename_length, filename, date]); + } + + /** + * Creates a Uint8Array representation of the packet + * + * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. + */ + write() { + const header = this.writeHeader(); + const data = this.getBytes(); + + return util.concat([header, data]); } - const literalDataPacketlist = new PacketList(); - literalDataPacketlist.push(literalDataPacket); - const message = new Message(literalDataPacketlist); - message.fromStream = streamType; - return message; } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// A Cleartext message can contain the following packets -const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. */ -class CleartextMessage { +class KeyID { + constructor() { + this.bytes = ''; + } + /** - * @param {String} text - The cleartext of the signed message - * @param {Signature} signature - The detached signature or an empty signature for unsigned messages - */ - constructor(text, signature) { - // remove trailing whitespace and normalize EOL to canonical form - this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); - if (signature && !(signature instanceof Signature)) { - throw new Error('Invalid signature input'); - } - this.signature = signature || new Signature(new PacketList()); + * Parsing method for a key id + * @param {Uint8Array} bytes - Input to read the key id from + */ + read(bytes) { + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); + return this.bytes.length; } /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns {Array} Array of keyID objects. + * Serializes the Key ID + * @returns {Uint8Array} Key ID as a Uint8Array. */ - getSigningKeyIDs() { - const keyIDs = []; - const signatureList = this.signature.packets; - signatureList.forEach(function(packet) { - keyIDs.push(packet.issuerKeyID); - }); - return keyIDs; + write() { + return util.stringToUint8Array(this.bytes); } /** - * Sign the cleartext message - * @param {Array} privateKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] - * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New cleartext message with signed content. - * @async + * Returns the Key ID represented as a hexadecimal string + * @returns {String} Key ID as a hexadecimal string. */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = new LiteralDataPacket(); - literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - return new CleartextMessage(this.text, newSignature); + toHex() { + return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); } /** - * Verify signatures of cleartext signed message - * @param {Array} keys - Array of keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async + * Checks equality of Key ID's + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard */ - verify(keys, date = new Date(), config$1 = config) { - const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - const literalDataPacket = new LiteralDataPacket(); - // we assume that cleartext signature is generated based on UTF8 cleartext - literalDataPacket.setText(this.text); - return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; } /** - * Get cleartext - * @returns {String} Cleartext of message. + * Checks to see if the Key ID is unset + * @returns {Boolean} True if the Key ID is null. */ - getText() { - // normalize end of line to \n - return this.text.replace(/\r\n/g, '\n'); + isNull() { + return this.bytes === ''; } /** - * Returns ASCII armored text of cleartext signed message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {String | ReadableStream} ASCII armor. + * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) + * @returns {Boolean} True if this is a wildcard Key ID. */ - armor(config$1 = config) { - let hashes = this.signature.packets.map(function(packet) { - return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); - }); - hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); - const body = { - hash: hashes.join(), - text: this.text, - data: this.signature.packets.write() - }; - return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1); + isWildcard() { + return /^0+$/.test(this.toHex()); } -} -/** - * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param {Object} options - * @param {String} options.cleartextMessage - Text to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New cleartext message object. - * @async - * @static - */ -async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!cleartextMessage) { - throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); + static mapToHex(keyID) { + return keyID.toHex(); } - if (!util.isString(cleartextMessage)) { - throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); + + static fromID(hex) { + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - const input = await unarmor(cleartextMessage); - if (input.type !== enums.armor.signed) { - throw new Error('No cleartext signed message.'); + static wildcard() { + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; } - const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1); - verifyHeaders$1(input.headers, packetlist); - const signature = new Signature(packetlist); - return new CleartextMessage(input.text, signature); } -/** - * Compare hash algorithm specified in the armor header with signatures - * @param {Array} headers - Armor headers - * @param {PacketList} packetlist - The packetlist with signature packets - * @private - */ -function verifyHeaders$1(headers, packetlist) { - const checkHashAlgos = function(hashAlgos) { - const check = packet => algo => packet.hashAlgorithm === algo; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - for (let i = 0; i < packetlist.length; i++) { - if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { - return false; - } - } - return true; - }; - let oneHeader = null; - let hashAlgos = []; - headers.forEach(function(header) { - oneHeader = header.match(/^Hash: (.+)$/); // get header value - if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace - oneHeader = oneHeader.split(','); - oneHeader = oneHeader.map(function(hash) { - hash = hash.toLowerCase(); - try { - return enums.write(enums.hash, hash); - } catch (e) { - throw new Error('Unknown hash algorithm in armor header: ' + hash); - } - }); - hashAlgos = hashAlgos.concat(oneHeader); - } else { - throw new Error('Only "Hash" header allowed in cleartext signed message'); - } - }); +// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. +const verified = Symbol('verified'); - if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { - throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { - throw new Error('Hash algorithm mismatch in armor header and signature'); - } -} +// A salt notation is used to randomize signatures. +// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks +// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170). +// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g. +// some chosen-prefix attacks. +// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt. +const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org'; + +// GPG puts the Issuer and Signature subpackets in the unhashed area. +// Tampering with those invalidates the signature, so we still trust them and parse them. +// All other unhashed subpackets are ignored. +const allowedUnhashedSubpackets = new Set([ + enums.signatureSubpacket.issuerKeyID, + enums.signatureSubpacket.issuerFingerprint, + enums.signatureSubpacket.embeddedSignature +]); /** - * Creates a new CleartextMessage object from text - * @param {Object} options - * @param {String} options.text - * @static - * @async + * Implementation of the Signature Packet (Tag 2) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. */ -async function createCleartextMessage({ text, ...rest }) { - if (!text) { - throw new Error('createCleartextMessage: must pass options object containing `text`'); +class SignaturePacket { + static get tag() { + return enums.packet.signature; } - if (!util.isString(text)) { - throw new Error('createCleartextMessage: options.text must be a string'); + + constructor() { + this.version = null; + /** @type {enums.signature} */ + this.signatureType = null; + /** @type {enums.hash} */ + this.hashAlgorithm = null; + /** @type {enums.publicKey} */ + this.publicKeyAlgorithm = null; + + this.signatureData = null; + this.unhashedSubpackets = []; + this.unknownSubpackets = []; + this.signedHashValue = null; + this.salt = null; + + this.created = null; + this.signatureExpirationTime = null; + this.signatureNeverExpires = true; + this.exportable = null; + this.trustLevel = null; + this.trustAmount = null; + this.regularExpression = null; + this.revocable = null; + this.keyExpirationTime = null; + this.keyNeverExpires = null; + this.preferredSymmetricAlgorithms = null; + this.revocationKeyClass = null; + this.revocationKeyAlgorithm = null; + this.revocationKeyFingerprint = null; + this.issuerKeyID = new KeyID(); + this.rawNotations = []; + this.notations = {}; + this.preferredHashAlgorithms = null; + this.preferredCompressionAlgorithms = null; + this.keyServerPreferences = null; + this.preferredKeyServer = null; + this.isPrimaryUserID = null; + this.policyURI = null; + this.keyFlags = null; + this.signersUserID = null; + this.reasonForRevocationFlag = null; + this.reasonForRevocationString = null; + this.features = null; + this.signatureTargetPublicKeyAlgorithm = null; + this.signatureTargetHashAlgorithm = null; + this.signatureTargetHash = null; + this.embeddedSignature = null; + this.issuerKeyVersion = null; + this.issuerFingerprint = null; + this.preferredAEADAlgorithms = null; + this.preferredCipherSuites = null; + + this.revoked = null; + this[verified] = null; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - return new CleartextMessage(text); -} + /** + * parsing function for a signature packet (tag 2). + * @param {String} bytes - Payload of a tag 2 packet + * @returns {SignaturePacket} Object representation. + */ + read(bytes, config$1 = config) { + let i = 0; + this.version = bytes[i++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } -// OpenPGP.js - An OpenPGP implementation in javascript + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); + } + + this.signatureType = bytes[i++]; + this.publicKeyAlgorithm = bytes[i++]; + this.hashAlgorithm = bytes[i++]; + + // hashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), true); + if (!this.created) { + throw new Error('Missing signature creation time subpacket.'); + } + + // A V4 signature hashes the packet body + // starting from its first field, the version number, through the end + // of the hashed subpacket data. Thus, the fields hashed are the + // signature version, the signature type, the public-key algorithm, the + // hash algorithm, the hashed subpacket length, and the hashed + // subpacket body. + this.signatureData = bytes.subarray(0, i); + + // unhashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), false); + // Two-octet field holding left 16 bits of signed hash value. + this.signedHashValue = bytes.subarray(i, i + 2); + i += 2; -////////////////////// -// // -// Key handling // -// // -////////////////////// + // Only for v6 signatures, a variable-length field containing: + if (this.version === 6) { + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[i++]; + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(i, i + saltLength); + i += saltLength; + } -/** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. - * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. - * @param {Object} options - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys - * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: - * curve25519 (default), p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 - * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` - * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static - */ -async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const signatureMaterial = bytes.subarray(i, bytes.length); + const { read, signatureParams } = mod$1.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial); + if (read < signatureMaterial.length) { + throw new Error('Error reading MPIs'); + } + this.params = signatureParams; + } - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key generation'); + /** + * @returns {Uint8Array | ReadableStream} + */ + writeParams() { + if (this.params instanceof Promise) { + return fromAsync( + async () => mod$1.serializeParams(this.publicKeyAlgorithm, await this.params) + ); + } + return mod$1.serializeParams(this.publicKeyAlgorithm, this.params); } - if (type === 'rsa' && rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + + write() { + const arr = []; + arr.push(this.signatureData); + arr.push(this.writeUnhashedSubPackets()); + arr.push(this.signedHashValue); + if (this.version === 6) { + arr.push(new Uint8Array([this.salt.length])); + arr.push(this.salt); + } + arr.push(this.writeParams()); + return util.concat(arr); } - const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; + /** + * Signs provided data. This needs to be done prior to serialization. + * @param {SecretKeyPacket} key - Private key used to sign the message. + * @param {Object} data - Contains packets to be signed. + * @param {Date} [date] - The signature creation time. + * @param {Boolean} [detached] - Whether to create a detached signature + * @throws {Error} if signing failed + * @async + */ + async sign(key, data, date = new Date(), detached = false, config) { + this.version = key.version; - try { - const { key, revocationCertificate } = await generate$4(options, config$1); - key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); + this.created = util.normalizeDate(date); + this.issuerKeyVersion = key.version; + this.issuerFingerprint = key.getFingerprintBytes(); + this.issuerKeyID = key.getKeyID(); - return { - privateKey: formatObject(key, format, config$1), - publicKey: formatObject(key.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error generating keypair', err); - } -} + const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; -/** - * Reformats signature packets for a key and rewraps key object. - * @param {Object} options - * @param {PrivateKey} options.privateKey - Private key to reformat - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended - * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static - */ -async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // add randomness to the signature + if (this.version === 6) { + const saltLength = saltLengthForHash(this.hashAlgorithm); + if (this.salt === null) { + this.salt = mod$1.random.getRandomBytes(saltLength); + } else if (saltLength !== this.salt.length) { + throw new Error('Provided salt does not have the required length'); + } + } else if (config.nonDeterministicSignaturesViaNotation) { + const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME)); + // since re-signing the same object is not supported, it's not expected to have multiple salt notations, + // but we guard against it as a sanity check + if (saltNotations.length === 0) { + const saltValue = mod$1.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm)); + this.rawNotations.push({ + name: SALT_NOTATION_NAME, + value: saltValue, + humanReadable: false, + critical: false + }); + } else { + throw new Error('Unexpected existing salt notation'); + } + } - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key reformat'); - } - const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; + // Add hashed subpackets + arr.push(this.writeHashedSubPackets()); - try { - const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); + // Remove unhashed subpackets, in case some allowed unhashed + // subpackets existed, in order not to duplicate them (in both + // the hashed and unhashed subpackets) when re-signing. + this.unhashedSubpackets = []; - return { - privateKey: formatObject(reformattedKey, format, config$1), - publicKey: formatObject(reformattedKey.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error reformatting keypair', err); + this.signatureData = util.concat(arr); + + const toHash = this.toHash(this.signatureType, data, detached); + const hash = await this.hash(this.signatureType, data, toHash, detached); + + this.signedHashValue = slice(clone(hash), 0, 2); + const signed = async () => mod$1.signature.sign( + this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) + ); + if (util.isStream(hash)) { + this.params = signed(); + } else { + this.params = await signed(); + + // Store the fact that this signature is valid, e.g. for when we call `await + // getLatestValidSignature(this.revocationSignatures, key, data)` later. + // Note that this only holds up if the key and data passed to verify are the + // same as the ones passed to sign. + this[verified] = true; + } } -} -/** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. - * @param {Object} options - * @param {Key} options.key - Public or private key to revoke - * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with - * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation - * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation - * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The revoked key in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or - * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise - * @async - * @static - */ -async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns {Uint8Array} Subpacket data. + */ + writeHashedSubPackets() { + const sub = enums.signatureSubpacket; + const arr = []; + let bytes; + if (this.created === null) { + throw new Error('Missing signature creation time'); + } + arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); + if (this.signatureExpirationTime !== null) { + arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); + } + if (this.exportable !== null) { + arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); + } + if (this.trustLevel !== null) { + bytes = new Uint8Array([this.trustLevel, this.trustAmount]); + arr.push(writeSubPacket(sub.trustSignature, true, bytes)); + } + if (this.regularExpression !== null) { + arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); + } + if (this.revocable !== null) { + arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); + } + if (this.keyExpirationTime !== null) { + arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); + } + if (this.preferredSymmetricAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); + arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); + } + if (this.revocationKeyClass !== null) { + bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); + bytes = util.concat([bytes, this.revocationKeyFingerprint]); + arr.push(writeSubPacket(sub.revocationKey, false, bytes)); + } + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) { + // If the version of [the] key is greater than 4, this subpacket + // MUST NOT be included in the signature. + arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write())); + } + this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { + bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; + const encodedName = util.encodeUTF8(name); + // 2 octets of name length + bytes.push(util.writeNumber(encodedName.length, 2)); + // 2 octets of value length + bytes.push(util.writeNumber(value.length, 2)); + bytes.push(encodedName); + bytes.push(value); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.notationData, critical, bytes)); + }); + if (this.preferredHashAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); + arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); + } + if (this.preferredCompressionAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); + arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); + } + if (this.keyServerPreferences !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); + arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); + } + if (this.preferredKeyServer !== null) { + arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); + } + if (this.isPrimaryUserID !== null) { + arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + } + if (this.policyURI !== null) { + arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); + } + if (this.keyFlags !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); + arr.push(writeSubPacket(sub.keyFlags, true, bytes)); + } + if (this.signersUserID !== null) { + arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); + } + if (this.reasonForRevocationFlag !== null) { + bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); + } + if (this.features !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); + arr.push(writeSubPacket(sub.features, false, bytes)); + } + if (this.signatureTargetPublicKeyAlgorithm !== null) { + bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; + bytes.push(util.stringToUint8Array(this.signatureTargetHash)); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); + } + if (this.embeddedSignature !== null) { + arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); + } + if (this.issuerFingerprint !== null) { + bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes)); + } + if (this.preferredAEADAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); + arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); + } + if (this.preferredCipherSuites !== null) { + bytes = new Uint8Array([].concat(...this.preferredCipherSuites)); + arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes)); + } - try { - const revokedKey = revocationCertificate ? - await key.applyRevocationCertificate(revocationCertificate, date, config$1) : - await key.revoke(reasonForRevocation, date, config$1); + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); - return revokedKey.isPrivate() ? { - privateKey: formatObject(revokedKey, format, config$1), - publicKey: formatObject(revokedKey.toPublic(), format, config$1) - } : { - privateKey: null, - publicKey: formatObject(revokedKey, format, config$1) - }; - } catch (err) { - throw util.wrapError('Error revoking key', err); + return util.concat([length, result]); } -} - -/** - * Unlock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to decrypt - * @param {String|Array} options.passphrase - The user's passphrase(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The unlocked key object. - * @async - */ -async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (!privateKey.isPrivate()) { - throw new Error('Cannot decrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); - const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; + /** + * Creates an Uint8Array containing the unhashed subpackets + * @returns {Uint8Array} Subpacket data. + */ + writeUnhashedSubPackets() { + const arr = this.unhashedSubpackets.map(({ type, critical, body }) => { + return writeSubPacket(type, critical, body); + }); - try { - await Promise.all(clonedPrivateKey.getKeys().map(key => ( - // try to decrypt each key with any of the given passphrases - util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) - ))); + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); - await clonedPrivateKey.validate(config$1); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error decrypting private key', err); + return util.concat([length, result]); } -} -/** - * Lock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to encrypt - * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The locked key object. - * @async - */ -async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // Signature subpackets + readSubPacket(bytes, hashed = true) { + let mypos = 0; - if (!privateKey.isPrivate()) { - throw new Error('Cannot encrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); + // The leftmost bit denotes a "critical" packet + const critical = !!(bytes[mypos] & 0x80); + const type = bytes[mypos] & 0x7F; - const keys = clonedPrivateKey.getKeys(); - const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); - if (passphrases.length !== keys.length) { - throw new Error('Invalid number of passphrases given for key encryption'); - } + mypos++; - try { - await Promise.all(keys.map(async (key, i) => { - const { keyPacket } = key; - await keyPacket.encrypt(passphrases[i], config$1); - keyPacket.clearPrivateParams(); - })); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error encrypting private key', err); - } -} + if (!hashed) { + this.unhashedSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + if (!allowedUnhashedSubpackets.has(type)) { + return; + } + } + // subpacket type + switch (type) { + case enums.signatureSubpacket.signatureCreationTime: + // Signature Creation Time + this.created = util.readDate(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.signatureExpirationTime: { + // Signature Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); -/////////////////////////////////////////// -// // -// Message encryption and decryption // -// // -/////////////////////////////////////////// + this.signatureNeverExpires = seconds === 0; + this.signatureExpirationTime = seconds; + break; + } + case enums.signatureSubpacket.exportableCertification: + // Exportable Certification + this.exportable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.trustSignature: + // Trust Signature + this.trustLevel = bytes[mypos++]; + this.trustAmount = bytes[mypos++]; + break; + case enums.signatureSubpacket.regularExpression: + // Regular Expression + this.regularExpression = bytes[mypos]; + break; + case enums.signatureSubpacket.revocable: + // Revocable + this.revocable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.keyExpirationTime: { + // Key Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); -/** - * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` - * must be specified. If signing keys are specified, those will be used to sign the message. - * @param {Object} options - * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message - * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed - * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message - * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Signature} [options.signature] - A detached signature to add to the encrypted message - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` - * @param {Date} [options.date=current date] - Override the creation date of the message signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords); - signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations); - if (rest.detached) { - throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); - } - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + this.keyExpirationTime = seconds; + this.keyNeverExpires = seconds === 0; - if (!signingKeys) { - signingKeys = []; - } - const streaming = message.fromStream; - try { - if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified - message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - message = message.compress( - await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1), - config$1 - ); - message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - if (format === 'object') return message; - // serialize data - const armor = format === 'armored'; - const data = armor ? message.armor(config$1) : message.write(); - return convertStream(data, streaming, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error encrypting message', err); - } -} + break; + } + case enums.signatureSubpacket.preferredSymmetricAlgorithms: + // Preferred Symmetric Algorithms + this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.revocationKey: + // Revocation Key + // (1 octet of class, 1 octet of public-key algorithm ID, 20 + // octets of + // fingerprint) + this.revocationKeyClass = bytes[mypos++]; + this.revocationKeyAlgorithm = bytes[mypos++]; + this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); + break; -/** - * Decrypts a message with the user's private key, a session key or a password. - * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). - * @param {Object} options - * @param {Message} options.message - The message object with the encrypted data - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key - * @param {String|String[]} [options.passwords] - Passwords to decrypt the message - * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } - * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: MaybeStream, (if format was 'utf8', the default) - * data: MaybeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static - */ -async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + case enums.signatureSubpacket.issuerKeyID: + // Issuer + if (this.version === 4) { + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + } else if (hashed) { + // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature, + // since the Issuer Fingerprint subpacket is to be used instead. + // The `issuerKeyID` value will be set when reading the issuerFingerprint packet. + // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it, + // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed) + // issuerFingerprint. + // If the packet is hashed, then we reject the signature, to avoid verifying data different from + // what was parsed. + throw new Error('Unexpected Issuer Key ID subpacket'); + } + break; - try { - const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); - if (!verificationKeys) { - verificationKeys = []; - } + case enums.signatureSubpacket.notationData: { + // Notation Data + const humanReadable = !!(bytes[mypos] & 0x80); - const result = {}; - result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); - result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); - result.filename = decrypted.getFilename(); - linkStreams(result, message); - if (expectSigned) { - if (verificationKeys.length === 0) { - throw new Error('Verification keys are required to verify message signatures'); + // We extract key/value tuple from the byte stream. + mypos += 4; + const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + + const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); + const value = bytes.subarray(mypos + m, mypos + m + n); + + this.rawNotations.push({ name, humanReadable, value, critical }); + + if (humanReadable) { + this.notations[name] = util.decodeUTF8(value); + } + break; } - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); + case enums.signatureSubpacket.preferredHashAlgorithms: + // Preferred Hash Algorithms + this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCompressionAlgorithms: + // Preferred Compression Algorithms + this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.keyServerPreferences: + // Key Server Preferences + this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredKeyServer: + // Preferred Key Server + this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.primaryUserID: + // Primary User ID + this.isPrimaryUserID = bytes[mypos++] !== 0; + break; + case enums.signatureSubpacket.policyURI: + // Policy URI + this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.keyFlags: + // Key Flags + this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signersUserID: + // Signer's User ID + this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.reasonForRevocation: + // Reason for Revocation + this.reasonForRevocationFlag = bytes[mypos++]; + this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.features: + // Features + this.features = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signatureTarget: { + // Signature Target + // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; + this.signatureTargetHashAlgorithm = bytes[mypos++]; + + const len = mod$1.getHashByteLength(this.signatureTargetHashAlgorithm); + + this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); + break; } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); + case enums.signatureSubpacket.embeddedSignature: + // Embedded Signature + this.embeddedSignature = new SignaturePacket(); + this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.issuerFingerprint: + // Issuer Fingerprint + this.issuerKeyVersion = bytes[mypos++]; + this.issuerFingerprint = bytes.subarray(mypos, bytes.length); + if (this.issuerKeyVersion >= 5) { + this.issuerKeyID.read(this.issuerFingerprint); + } else { + this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); + } + break; + case enums.signatureSubpacket.preferredAEADAlgorithms: + // Preferred AEAD Algorithms + this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCipherSuites: + // Preferred AEAD Cipher Suites + this.preferredCipherSuites = []; + for (let i = mypos; i < bytes.length; i += 2) { + this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]); + } + break; + default: + this.unknownSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + break; } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error decrypting message', err); } -} + readSubPackets(bytes, trusted = true, config) { + const subpacketLengthBytes = this.version === 6 ? 4 : 2; -////////////////////////////////////////// -// // -// Message signing and verification // -// // -////////////////////////////////////////// + // Two-octet scalar octet count for following subpacket data. + const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes)); + let i = subpacketLengthBytes; -/** - * Signs a message. - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed - * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [options.date=current date] - Override the creation date of the signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); checkOutputMessageFormat(format); - signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations); + // subpacket data set (zero or more subpackets) + while (i < 2 + subpacketLength) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); - if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); - if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); + i += len.len; + } - if (!signingKeys || signingKeys.length === 0) { - throw new Error('No signing keys provided'); + return i; } - try { - let signature; - if (detached) { - signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } else { - signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - if (format === 'object') return signature; + // Produces data to produce signature on + toSign(type, data) { + const t = enums.signature; - const armor = format === 'armored'; - signature = armor ? signature.armor(config$1) : signature.write(); - if (detached) { - signature = transformPair(message.packets.write(), async (readable, writable) => { - await Promise.all([ - pipe(signature, writable), - readToEnd(readable).catch(() => {}) - ]); - }); - } - return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error signing message', err); - } -} + switch (type) { + case t.binary: + if (data.text !== null) { + return util.encodeUTF8(data.getText(true)); + } + return data.getBytes(true); -/** - * Verifies signatures of cleartext signed message - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures - * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: MaybeStream, (if `message` was a CleartextMessage) - * data: MaybeStream, (if `message` was a Message) - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static - */ -async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + case t.text: { + const bytes = data.getBytes(true); + // normalize EOL to \r\n + return util.canonicalizeEOL(bytes); + } + case t.standalone: + return new Uint8Array(0); + + case t.certGeneric: + case t.certPersona: + case t.certCasual: + case t.certPositive: + case t.certRevocation: { + let packet; + let tag; + + if (data.userID) { + tag = 0xB4; + packet = data.userID; + } else if (data.userAttribute) { + tag = 0xD1; + packet = data.userAttribute; + } else { + throw new Error('Either a userID or userAttribute packet needs to be ' + + 'supplied for certification.'); + } + + const bytes = packet.write(); + + return util.concat([this.toSign(t.key, data), + new Uint8Array([tag]), + util.writeNumber(bytes.length, 4), + bytes]); + } + case t.subkeyBinding: + case t.subkeyRevocation: + case t.keyBinding: + return util.concat([this.toSign(t.key, data), this.toSign(t.key, { + key: data.bind + })]); - if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); - if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); + case t.key: + if (data.key === undefined) { + throw new Error('Key packet is required for this signature.'); + } + return data.key.writeForHash(this.version); - try { - const result = {}; - if (signature) { - result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); - } else { - result.signatures = await message.verify(verificationKeys, date, config$1); - } - result.data = format === 'binary' ? message.getLiteralData() : message.getText(); - if (message.fromStream && !signature) linkStreams(result, message); - if (expectSigned) { - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); - } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); + case t.keyRevocation: + return this.toSign(t.key, data); + case t.timestamp: + return new Uint8Array(0); + case t.thirdParty: + throw new Error('Not implemented'); + default: + throw new Error('Unknown signature type.'); } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error verifying signed message', err); } -} - - -/////////////////////////////////////////////// -// // -// Session key encryption and decryption // -// // -/////////////////////////////////////////////// - -/** - * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. - * @param {Object} options - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} - * @param {Date} [options.date=current date] - Date to select algorithm preferences at - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. - * @async - * @static - */ -async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - try { - const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error generating session key', err); + calculateTrailer(data, detached) { + let length = 0; + return transform(clone(this.signatureData), value => { + length += value.length; + }, () => { + const arr = []; + if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { + if (detached) { + arr.push(new Uint8Array(6)); + } else { + arr.push(data.writeHeader()); + } + } + arr.push(new Uint8Array([this.version, 0xFF])); + if (this.version === 5) { + arr.push(new Uint8Array(4)); + } + arr.push(util.writeNumber(length, 4)); + // For v5, this should really be writeNumber(length, 8) rather than the + // hardcoded 4 zero bytes above + return util.concat(arr); + }); } -} -/** - * Encrypt a symmetric session key with public keys, passwords, or both at once. - * At least one of `encryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) - * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key - * @param {String|String[]} [options.passwords] - Passwords for the message - * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [options.date=current date] - Override the date - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + toHash(signatureType, data, detached = false) { + const bytes = this.toSign(signatureType, data); - if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { - throw new Error('No encryption keys or passwords provided.'); + return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]); } - try { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - return formatObject(message, format, config$1); - } catch (err) { - throw util.wrapError('Error encrypting session key', err); + async hash(signatureType, data, toHash, detached = false) { + if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) { + // avoid hashing unexpected salt size + throw new Error('Signature salt does not have the expected length'); + } + + if (!toHash) toHash = this.toHash(signatureType, data, detached); + return mod$1.hash.digest(this.hashAlgorithm, toHash); } -} -/** - * Decrypt symmetric session keys using private keys or passwords (not both). - * One of `decryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Message} options.message - A message object containing the encrypted session key packets - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data - * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key - * @param {Date} [options.date] - Date to use for key verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: - * { data:Uint8Array, algorithm:String } - * @throws if no session key could be found or decrypted - * @async - * @static - */ -async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + /** + * verifies the signature packet. Note: not all signature types are implemented + * @param {PublicSubkeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature + * @param {module:enums.signature} signatureType - Expected signature type + * @param {Uint8Array|Object} data - Data which on the signature applies + * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration + * @param {Boolean} [detached] - Whether to verify a detached signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if signature validation failed + * @async + */ + async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { + if (!this.issuerKeyID.equals(key.getKeyID())) { + throw new Error('Signature was not issued by the given public key'); + } + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); + } - try { - const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error decrypting session keys', err); - } -} + const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; + // Cryptographic validity is cached after one successful verification. + // However, for message signatures, we always re-verify, since the passed `data` can change + const skipVerify = this[verified] && !isMessageSignature; + if (!skipVerify) { + let toHash; + let hash; + if (this.hashed) { + hash = await this.hashed; + } else { + toHash = this.toHash(signatureType, data, detached); + hash = await this.hash(signatureType, data, toHash); + } + hash = await readToEnd(hash); + if (this.signedHashValue[0] !== hash[0] || + this.signedHashValue[1] !== hash[1]) { + throw new Error('Signed digest did not match'); + } + this.params = await this.params; -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// + this[verified] = await mod$1.signature.verify( + this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, + toHash, hash + ); + if (!this[verified]) { + throw new Error('Signature verification failed'); + } + } -/** - * Input validation - * @private - */ -function checkString(data, name) { - if (!util.isString(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type String'); - } -} -function checkBinary(data, name) { - if (!util.isUint8Array(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array'); - } -} -function checkMessage(message) { - if (!(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message'); - } -} -function checkCleartextOrMessage(message) { - if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); - } -} -function checkOutputMessageFormat(format) { - if (format !== 'armored' && format !== 'binary' && format !== 'object') { - throw new Error(`Unsupported format ${format}`); - } -} -const defaultConfigPropsCount = Object.keys(config).length; -function checkConfig(config$1) { - const inputConfigProps = Object.keys(config$1); - if (inputConfigProps.length !== defaultConfigPropsCount) { - for (const inputProp of inputConfigProps) { - if (config[inputProp] === undefined) { - throw new Error(`Unknown config property: ${inputProp}`); + const normDate = util.normalizeDate(date); + if (normDate && this.created > normDate) { + throw new Error('Signature creation time is in the future'); + } + if (normDate && normDate >= this.getExpirationTime()) { + throw new Error('Signature is expired'); + } + if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { + throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && + [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { + throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + this.unknownSubpackets.forEach(({ type, critical }) => { + if (critical) { + throw new Error(`Unknown critical signature subpacket type ${type}`); + } + }); + this.rawNotations.forEach(({ name, critical }) => { + if (critical && (config$1.knownNotations.indexOf(name) < 0)) { + throw new Error(`Unknown critical notation: ${name}`); } + }); + if (this.revocationKeyClass !== null) { + throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); } } -} -/** - * Normalize parameter to an array if it is not undefined. - * @param {Object} param - the parameter to be normalized - * @returns {Array|undefined} The resulting array or undefined. - * @private - */ -function toArray$1(param) { - if (param && !util.isArray(param)) { - param = [param]; + /** + * Verifies signature expiration date + * @param {Date} [date] - Use the given date for verification instead of the current time + * @returns {Boolean} True if expired. + */ + isExpired(date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + return !(this.created <= normDate && normDate < this.getExpirationTime()); + } + return false; } - return param; -} -/** - * Convert data to or from Stream - * @param {Object} data - the data to convert - * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type - * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams - * @returns {Promise} The data in the respective format. - * @async - * @private - */ -async function convertStream(data, streaming, encoding = 'utf8') { - const streamType = util.isStream(data); - if (streamType === 'array') { - return readToEnd(data); - } - if (streaming === 'node') { - data = webToNode(data); - if (encoding !== 'binary') data.setEncoding(encoding); - return data; - } - if (streaming === 'web' && streamType === 'ponyfill') { - return toNativeReadable(data); + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns {Date | Infinity} Expiration time. + */ + getExpirationTime() { + return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); } - return data; } /** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param {Object} result - the data to convert - * @param {Message} message - message object - * @returns {Object} + * Creates a Uint8Array representation of a sub signature packet + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} + * @param {Integer} type - Subpacket signature type. + * @param {Boolean} critical - Whether the subpacket should be critical. + * @param {String} data - Data to be included + * @returns {Uint8Array} The signature subpacket. * @private */ -function linkStreams(result, message) { - result.data = transformPair(message.packets.stream, async (readable, writable) => { - await pipe(result.data, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - // Forward errors in the message stream to result.data. - await readToEnd(readable, _ => _); - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); +function writeSubPacket(type, critical, data) { + const arr = []; + arr.push(writeSimpleLength(data.length + 1)); + arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); + arr.push(data); + return util.concat(arr); } /** - * Convert the object to the given format - * @param {Key|Message} object - * @param {'armored'|'binary'|'object'} format - * @param {Object} config - Full configuration - * @returns {String|Uint8Array|Object} + * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh. + * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5} + * @param {enums.hash} hashAlgorithm - Hash algorithm. + * @returns {Integer} Salt length. + * @private */ -function formatObject(object, format, config) { - switch (format) { - case 'object': - return object; - case 'armored': - return object.armor(config); - case 'binary': - return object.write(); - default: - throw new Error(`Unsupported format ${format}`); +function saltLengthForHash(hashAlgorithm) { + switch (hashAlgorithm) { + case enums.hash.sha256: return 16; + case enums.hash.sha384: return 24; + case enums.hash.sha512: return 32; + case enums.hash.sha224: return 16; + case enums.hash.sha3_256: return 16; + case enums.hash.sha3_512: return 32; + default: throw new Error('Unsupported hash function'); } } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * web-streams-polyfill v3.0.3 + * Implementation of the One-Pass Signature Packets (Tag 4) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. */ -/// -const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? - Symbol : - description => `Symbol(${description})`; +class OnePassSignaturePacket { + static get tag() { + return enums.packet.onePassSignature; + } -/// -function noop() { - return undefined; -} -function getGlobals() { - if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else if (typeof global !== 'undefined') { - return global; - } - return undefined; -} -const globals = getGlobals(); + static fromSignaturePacket(signaturePacket, isLast) { + const onePassSig = new OnePassSignaturePacket(); + onePassSig.version = signaturePacket.version === 6 ? 6 : 3; + onePassSig.signatureType = signaturePacket.signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; + onePassSig.salt = signaturePacket.salt; // v6 only + onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only -function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -const rethrowAssertionErrorRejection = noop; + onePassSig.flags = isLast ? 1 : 0; + return onePassSig; + } -const originalPromise = Promise; -const originalPromiseThen = Promise.prototype.then; -const originalPromiseResolve = Promise.resolve.bind(originalPromise); -const originalPromiseReject = Promise.reject.bind(originalPromise); -function newPromise(executor) { - return new originalPromise(executor); -} -function promiseResolvedWith(value) { - return originalPromiseResolve(value); -} -function promiseRejectedWith(reason) { - return originalPromiseReject(reason); -} -function PerformPromiseThen(promise, onFulfilled, onRejected) { - // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an - // approximation. - return originalPromiseThen.call(promise, onFulfilled, onRejected); -} -function uponPromise(promise, onFulfilled, onRejected) { - PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); -} -function uponFulfillment(promise, onFulfilled) { - uponPromise(promise, onFulfilled); -} -function uponRejection(promise, onRejected) { - uponPromise(promise, undefined, onRejected); -} -function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { - return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); -} -function setPromiseIsHandledToTrue(promise) { - PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); -} -const queueMicrotask = (() => { - const globalQueueMicrotask = globals && globals.queueMicrotask; - if (typeof globalQueueMicrotask === 'function') { - return globalQueueMicrotask; - } - const resolvedPromise = promiseResolvedWith(undefined); - return (fn) => PerformPromiseThen(resolvedPromise, fn); -})(); -function reflectCall(F, V, args) { - if (typeof F !== 'function') { - throw new TypeError('Argument is not a function'); - } - return Function.prototype.apply.call(F, V, args); -} -function promiseCall(F, V, args) { - try { - return promiseResolvedWith(reflectCall(F, V, args)); - } - catch (value) { - return promiseRejectedWith(value); - } -} + constructor() { + /** A one-octet version number. The current versions are 3 and 6. */ + this.version = null; + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + * @type {enums.signature} -// Original from Chromium -// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js -const QUEUE_MAX_ARRAY_SIZE = 16384; -/** - * Simple queue structure. - * - * Avoids scalability issues with using a packed array directly by using - * multiple arrays in a linked list and keeping the array size bounded. - */ -class SimpleQueue { - constructor() { - this._cursor = 0; - this._size = 0; - // _front and _back are always defined. - this._front = { - _elements: [], - _next: undefined - }; - this._back = this._front; - // The cursor is used to avoid calling Array.shift(). - // It contains the index of the front element of the array inside the - // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). - this._cursor = 0; - // When there is only one node, size === elements.length - cursor. - this._size = 0; - } - get length() { - return this._size; - } - // For exception safety, this method is structured in order: - // 1. Read state - // 2. Calculate required state mutations - // 3. Perform state mutations - push(element) { - const oldBack = this._back; - let newBack = oldBack; - if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { - newBack = { - _elements: [], - _next: undefined - }; - } - // push() is the mutation most likely to throw an exception, so it - // goes first. - oldBack._elements.push(element); - if (newBack !== oldBack) { - this._back = newBack; - oldBack._next = newBack; - } - ++this._size; - } - // Like push(), shift() follows the read -> calculate -> mutate pattern for - // exception safety. - shift() { // must not be called on an empty queue - const oldFront = this._front; - let newFront = oldFront; - const oldCursor = this._cursor; - let newCursor = oldCursor + 1; - const elements = oldFront._elements; - const element = elements[oldCursor]; - if (newCursor === QUEUE_MAX_ARRAY_SIZE) { - newFront = oldFront._next; - newCursor = 0; - } - // No mutations before this point. - --this._size; - this._cursor = newCursor; - if (oldFront !== newFront) { - this._front = newFront; - } - // Permit shifted element to be garbage collected. - elements[oldCursor] = undefined; - return element; - } - // The tricky thing about forEach() is that it can be called - // re-entrantly. The queue may be mutated inside the callback. It is easy to - // see that push() within the callback has no negative effects since the end - // of the queue is checked for on every iteration. If shift() is called - // repeatedly within the callback then the next iteration may return an - // element that has been removed. In this case the callback will be called - // with undefined values until we either "catch up" with elements that still - // exist or reach the back of the queue. - forEach(callback) { - let i = this._cursor; - let node = this._front; - let elements = node._elements; - while (i !== elements.length || node._next !== undefined) { - if (i === elements.length) { - node = node._next; - elements = node._elements; - i = 0; - if (elements.length === 0) { - break; - } - } - callback(elements[i]); - ++i; - } - } - // Return the element that would be returned if shift() was called now, - // without modifying the queue. - peek() { // must not be called on an empty queue - const front = this._front; - const cursor = this._cursor; - return front._elements[cursor]; - } -} + */ + this.signatureType = null; + /** + * A one-octet number describing the hash algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} + * @type {enums.hash} + */ + this.hashAlgorithm = null; + /** + * A one-octet number describing the public-key algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} + * @type {enums.publicKey} + */ + this.publicKeyAlgorithm = null; + /** Only for v6, a variable-length field containing the salt. */ + this.salt = null; + /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */ + this.issuerKeyID = null; + /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */ + this.issuerFingerprint = null; + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + this.flags = null; + } -function ReadableStreamReaderGenericInitialize(reader, stream) { - reader._ownerReadableStream = stream; - stream._reader = reader; - if (stream._state === 'readable') { - defaultReaderClosedPromiseInitialize(reader); - } - else if (stream._state === 'closed') { - defaultReaderClosedPromiseInitializeAsResolved(reader); - } - else { - defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); - } -} -// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state -// check. -function ReadableStreamReaderGenericCancel(reader, reason) { - const stream = reader._ownerReadableStream; - return ReadableStreamCancel(stream, reason); -} -function ReadableStreamReaderGenericRelease(reader) { - if (reader._ownerReadableStream._state === 'readable') { - defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - else { - defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - reader._ownerReadableStream._reader = undefined; - reader._ownerReadableStream = undefined; -} -// Helper functions for the readers. -function readerLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released reader'); -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderClosedPromiseInitialize(reader) { - reader._closedPromise = newPromise((resolve, reject) => { - reader._closedPromise_resolve = resolve; - reader._closedPromise_reject = reject; - }); -} -function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseReject(reader, reason); -} -function defaultReaderClosedPromiseInitializeAsResolved(reader) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseResolve(reader); -} -function defaultReaderClosedPromiseReject(reader, reason) { - if (reader._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(reader._closedPromise); - reader._closedPromise_reject(reason); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -function defaultReaderClosedPromiseResetToRejected(reader, reason) { - defaultReaderClosedPromiseInitializeAsRejected(reader, reason); -} -function defaultReaderClosedPromiseResolve(reader) { - if (reader._closedPromise_resolve === undefined) { - return; + /** + * parsing function for a one-pass signature packet (tag 4). + * @param {Uint8Array} bytes - Payload of a tag 4 packet + * @returns {OnePassSignaturePacket} Object representation. + */ + read(bytes) { + let mypos = 0; + // A one-octet version number. The current versions are 3 or 6. + this.version = bytes[mypos++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); } - reader._closedPromise_resolve(undefined); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); -const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); -const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); -const PullSteps = SymbolPolyfill('[[PullSteps]]'); + // A one-octet signature type. Signature types are described in + // Section 5.2.1. + this.signatureType = bytes[mypos++]; -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill -const NumberIsFinite = Number.isFinite || function (x) { - return typeof x === 'number' && isFinite(x); -}; + // A one-octet number describing the hash algorithm used. + this.hashAlgorithm = bytes[mypos++]; -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill -const MathTrunc = Math.trunc || function (v) { - return v < 0 ? Math.ceil(v) : Math.floor(v); -}; + // A one-octet number describing the public-key algorithm used. + this.publicKeyAlgorithm = bytes[mypos++]; -// https://heycam.github.io/webidl/#idl-dictionaries -function isDictionary(x) { - return typeof x === 'object' || typeof x === 'function'; -} -function assertDictionary(obj, context) { - if (obj !== undefined && !isDictionary(obj)) { - throw new TypeError(`${context} is not an object.`); - } -} -// https://heycam.github.io/webidl/#idl-callback-functions -function assertFunction(x, context) { - if (typeof x !== 'function') { - throw new TypeError(`${context} is not a function.`); - } -} -// https://heycam.github.io/webidl/#idl-object -function isObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -function assertObject(x, context) { - if (!isObject(x)) { - throw new TypeError(`${context} is not an object.`); - } -} -function assertRequiredArgument(x, position, context) { - if (x === undefined) { - throw new TypeError(`Parameter ${position} is required in '${context}'.`); - } -} -function assertRequiredField(x, field, context) { - if (x === undefined) { - throw new TypeError(`${field} is required in '${context}'.`); - } -} -// https://heycam.github.io/webidl/#idl-unrestricted-double -function convertUnrestrictedDouble(value) { - return Number(value); -} -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} -function integerPart(x) { - return censorNegativeZero(MathTrunc(x)); -} -// https://heycam.github.io/webidl/#idl-unsigned-long-long -function convertUnsignedLongLongWithEnforceRange(value, context) { - const lowerBound = 0; - const upperBound = Number.MAX_SAFE_INTEGER; - let x = Number(value); - x = censorNegativeZero(x); - if (!NumberIsFinite(x)) { - throw new TypeError(`${context} is not a finite number`); - } - x = integerPart(x); - if (x < lowerBound || x > upperBound) { - throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + if (this.version === 6) { + // Only for v6 signatures, a variable-length field containing: + + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[mypos++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(mypos, mypos + saltLength); + mypos += saltLength; + + // Only for v6 packets, 32 octets of the fingerprint of the signing key. + this.issuerFingerprint = bytes.subarray(mypos, mypos + 32); + mypos += 32; + this.issuerKeyID = new KeyID(); + // For v6 the Key ID is the high-order 64 bits of the fingerprint. + this.issuerKeyID.read(this.issuerFingerprint); + } else { + // Only for v3 packets, an eight-octet number holding the Key ID of the signing key. + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); + mypos += 8; } - if (!NumberIsFinite(x) || x === 0) { - return 0; + + // A one-octet number holding a flag showing whether the signature + // is nested. A zero value indicates that the next packet is + // another One-Pass Signature packet that describes another + // signature to be applied to the same message data. + this.flags = bytes[mypos++]; + return this; + } + + /** + * creates a string representation of a one-pass signature packet + * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. + */ + write() { + const arr = [new Uint8Array([ + this.version, + this.signatureType, + this.hashAlgorithm, + this.publicKeyAlgorithm + ])]; + if (this.version === 6) { + arr.push( + new Uint8Array([this.salt.length]), + this.salt, + this.issuerFingerprint + ); + } else { + arr.push(this.issuerKeyID.write()); } - // TODO Use BigInt if supported? - // let xBigInt = BigInt(integerPart(x)); - // xBigInt = BigInt.asUintN(64, xBigInt); - // return Number(xBigInt); - return x; -} + arr.push(new Uint8Array([this.flags])); + return util.concatUint8Array(arr); + } -function assertReadableStream(x, context) { - if (!IsReadableStream(x)) { - throw new TypeError(`${context} is not a ReadableStream.`); - } -} + calculateTrailer(...args) { + return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); + } -// Abstract operations for the ReadableStream. -function AcquireReadableStreamDefaultReader(stream) { - return new ReadableStreamDefaultReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadRequest(stream, readRequest) { - stream._reader._readRequests.push(readRequest); -} -function ReadableStreamFulfillReadRequest(stream, chunk, done) { - const reader = stream._reader; - const readRequest = reader._readRequests.shift(); - if (done) { - readRequest._closeSteps(); + async verify() { + const correspondingSig = await this.correspondingSig; + if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { + throw new Error('Corresponding signature packet missing'); } - else { - readRequest._chunkSteps(chunk); + if ( + correspondingSig.signatureType !== this.signatureType || + correspondingSig.hashAlgorithm !== this.hashAlgorithm || + correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) || + (this.version === 3 && correspondingSig.version === 6) || + (this.version === 6 && correspondingSig.version !== 6) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt)) + ) { + throw new Error('Corresponding signature packet does not match one-pass signature packet'); } + correspondingSig.hashed = this.hashed; + return correspondingSig.verify.apply(correspondingSig, arguments); + } } -function ReadableStreamGetNumReadRequests(stream) { - return stream._reader._readRequests.length; -} -function ReadableStreamHasDefaultReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamDefaultReader(reader)) { - return false; + +OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; +OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; +OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; + +/** + * Instantiate a new packet given its tag + * @function newPacketFromTag + * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @returns {Object} New packet object with type based on tag + * @throws {Error|UnsupportedError} for disallowed or unknown packets + */ +function newPacketFromTag(tag, allowedPackets) { + if (!allowedPackets[tag]) { + // distinguish between disallowed packets and unknown ones + let packetType; + try { + packetType = enums.read(enums.packet, tag); + } catch (e) { + throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`); } - return true; + throw new Error(`Packet not allowed in this context: ${packetType}`); + } + return new allowedPackets[tag](); } + /** - * A default reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamDefaultReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, - * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } - /** - * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('read')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: () => resolvePromise({ value: undefined, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamDefaultReaderRead(this, readRequest); - return promise; + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + * @extends Array + */ +class PacketList extends Array { + /** + * Parses the given binary data and returns a list of packets. + * Equivalent to calling `read` on an empty PacketList instance. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @returns {PacketList} parsed list of packets + * @throws on parsing errors + * @async + */ + static async fromBinary(bytes, allowedPackets, config$1 = config) { + const packets = new PacketList(); + await packets.read(bytes, allowedPackets, config$1); + return packets; + } + + /** + * Reads a stream of binary data and interprets it as a list of packets. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @throws on parsing errors + * @async + */ + async read(bytes, allowedPackets, config$1 = config) { + if (config$1.additionalAllowedPackets.length) { + allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamDefaultReader(this)) { - throw defaultReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { + this.stream = transformPair(bytes, async (readable, writable) => { + const writer = getWriter(writable); + try { + while (true) { + await writer.ready; + const done = await readPackets(readable, async parsed => { + try { + if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) { + // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: + // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 + // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 + // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21 + return; + } + const packet = newPacketFromTag(parsed.tag, allowedPackets); + packet.packets = new PacketList(); + packet.fromStream = util.isStream(parsed.packet); + await packet.read(parsed.packet, config$1); + await writer.write(packet); + } catch (e) { + // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence, + // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored. + // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical. + if (e instanceof UnknownPacketError) { + if (parsed.tag <= 39) { + await writer.abort(e); + } else { + return; + } + } + + const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; + const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); + if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { + // The packets that support streaming are the ones that contain message data. + // Those are also the ones we want to be more strict about and throw on parse errors + // (since we likely cannot process the message without these packets anyway). + await writer.abort(e); + } else { + const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); + await writer.write(unparsedPacket); + } + util.printDebugError(e); + } + }); + if (done) { + await writer.ready; + await writer.close(); return; + } } - if (this._readRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamDefaultReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultReader', - configurable: true + } catch (e) { + await writer.abort(e); + } }); -} -// Abstract operations for the readers. -function IsReadableStreamDefaultReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { - return false; - } - return true; -} -function ReadableStreamDefaultReaderRead(reader, readRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'closed') { - readRequest._closeSteps(); - } - else if (stream._state === 'errored') { - readRequest._errorSteps(stream._storedError); - } - else { - stream._readableStreamController[PullSteps](readRequest); - } -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); -} -/// -let AsyncIteratorPrototype; -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - // We're running inside a ES2018+ environment, but we're compiling to an older syntax. - // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. - AsyncIteratorPrototype = { - // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) - // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator - [SymbolPolyfill.asyncIterator]() { - return this; - } - }; - Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); -} - -/// -class ReadableStreamAsyncIteratorImpl { - constructor(reader, preventCancel) { - this._ongoingPromise = undefined; - this._isFinished = false; - this._reader = reader; - this._preventCancel = preventCancel; - } - next() { - const nextSteps = () => this._nextSteps(); - this._ongoingPromise = this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : - nextSteps(); - return this._ongoingPromise; - } - return(value) { - const returnSteps = () => this._returnSteps(value); - return this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : - returnSteps(); - } - _nextSteps() { - if (this._isFinished) { - return Promise.resolve({ value: undefined, done: true }); - } - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('iterate')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => { - this._ongoingPromise = undefined; - // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. - // FIXME Is this a bug in the specification, or in the test? - queueMicrotask(() => resolvePromise({ value: chunk, done: false })); - }, - _closeSteps: () => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - resolvePromise({ value: undefined, done: true }); - }, - _errorSteps: reason => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - rejectPromise(reason); - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promise; - } - _returnSteps(value) { - if (this._isFinished) { - return Promise.resolve({ value, done: true }); - } - this._isFinished = true; - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('finish iterating')); - } - if (!this._preventCancel) { - const result = ReadableStreamReaderGenericCancel(reader, value); - ReadableStreamReaderGenericRelease(reader); - return transformPromiseWith(result, () => ({ value, done: true })); - } - ReadableStreamReaderGenericRelease(reader); - return promiseResolvedWith({ value, done: true }); + // Wait until first few packets have been read + const reader = getReader(this.stream); + while (true) { + const { done, value } = await reader.read(); + if (!done) { + this.push(value); + } else { + this.stream = null; + } + if (done || supportsStreaming(value.constructor.tag)) { + break; + } } -} -const ReadableStreamAsyncIteratorPrototype = { - next() { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); - } - return this._asyncIteratorImpl.next(); - }, - return(value) { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + reader.releaseLock(); + } + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. + */ + write() { + const arr = []; + + for (let i = 0; i < this.length; i++) { + const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; + const packetbytes = this[i].write(); + if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { + let buffer = []; + let bufferLength = 0; + const minLength = 512; + arr.push(writeTag(tag)); + arr.push(transform(packetbytes, value => { + buffer.push(value); + bufferLength += value.length; + if (bufferLength >= minLength) { + const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); + const chunkSize = 2 ** powerOf2; + const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); + buffer = [bufferConcat.subarray(1 + chunkSize)]; + bufferLength = buffer[0].length; + return bufferConcat.subarray(0, 1 + chunkSize); + } + }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); + } else { + if (util.isStream(packetbytes)) { + let length = 0; + arr.push(transform(clone(packetbytes), value => { + length += value.length; + }, () => writeHeader(tag, length))); + } else { + arr.push(writeHeader(tag, packetbytes.length)); } - return this._asyncIteratorImpl.return(value); - } -}; -if (AsyncIteratorPrototype !== undefined) { - Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); -} -// Abstract operations for the ReadableStream. -function AcquireReadableStreamAsyncIterator(stream, preventCancel) { - const reader = AcquireReadableStreamDefaultReader(stream); - const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); - iterator._asyncIteratorImpl = impl; - return iterator; -} -function IsReadableStreamAsyncIterator(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { - return false; + arr.push(packetbytes); + } } - return true; -} -// Helper functions for the ReadableStream. -function streamAsyncIteratorBrandCheckException(name) { - return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); -} -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill -const NumberIsNaN = Number.isNaN || function (x) { - // eslint-disable-next-line no-self-compare - return x !== x; -}; + return util.concat(arr); + } + + /** + * Creates a new PacketList with all packets matching the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {PacketList} + */ + filterByTag(...tags) { + const filtered = new PacketList(); + + const handle = tag => packetType => tag === packetType; -function IsFiniteNonNegativeNumber(v) { - if (!IsNonNegativeNumber(v)) { - return false; - } - if (v === Infinity) { - return false; - } - return true; -} -function IsNonNegativeNumber(v) { - if (typeof v !== 'number') { - return false; - } - if (NumberIsNaN(v)) { - return false; - } - if (v < 0) { - return false; + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(this[i].constructor.tag))) { + filtered.push(this[i]); + } } - return true; -} -function DequeueValue(container) { - const pair = container._queue.shift(); - container._queueTotalSize -= pair.size; - if (container._queueTotalSize < 0) { - container._queueTotalSize = 0; - } - return pair.value; -} -function EnqueueValueWithSize(container, value, size) { - size = Number(size); - if (!IsFiniteNonNegativeNumber(size)) { - throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); - } - container._queue.push({ value, size }); - container._queueTotalSize += size; -} -function PeekQueueValue(container) { - const pair = container._queue.peek(); - return pair.value; -} -function ResetQueue(container) { - container._queue = new SimpleQueue(); - container._queueTotalSize = 0; -} + return filtered; + } -function CreateArrayFromList(elements) { - // We use arrays to represent lists, so this is basically a no-op. - // Do a slice though just in case we happen to depend on the unique-ness. - return elements.slice(); -} -function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { - new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); -} -// Not implemented correctly -function TransferArrayBuffer(O) { - return O; -} -// Not implemented correctly -function IsDetachedBuffer(O) { - return false; -} + /** + * Traverses packet list and returns first packet with matching tag + * @param {module:enums.packet} tag - The packet tag + * @returns {Packet|undefined} + */ + findPacket(tag) { + return this.find(packet => packet.constructor.tag === tag); + } -/** - * A pull-into request in a {@link ReadableByteStreamController}. - * - * @public - */ -class ReadableStreamBYOBRequest { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. - */ - get view() { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('view'); - } - return this._view; - } - respond(bytesWritten) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respond'); - } - assertRequiredArgument(bytesWritten, 1, 'respond'); - bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - if (IsDetachedBuffer(this._view.buffer)) ; - ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); - } - respondWithNewView(view) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respondWithNewView'); - } - assertRequiredArgument(view, 1, 'respondWithNewView'); - if (!ArrayBuffer.isView(view)) { - throw new TypeError('You can only respond with array buffer views'); - } - if (view.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (view.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + /** + * Find indices of packets with the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {Integer[]} packet indices + */ + indexOfTag(...tags) { + const tagIndex = []; + const that = this; + + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(that[i].constructor.tag))) { + tagIndex.push(i); + } } + return tagIndex; + } } -Object.defineProperties(ReadableStreamBYOBRequest.prototype, { - respond: { enumerable: true }, - respondWithNewView: { enumerable: true }, - view: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBRequest', - configurable: true - }); -} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Compressed Data packet can contain the following packet types +const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + /** - * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * Implementation of the Compressed Data Packet (Tag 8) * - * @public + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. */ -class ReadableByteStreamController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the current BYOB pull request, or `null` if there isn't one. - */ - get byobRequest() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('byobRequest'); - } - if (this._byobRequest === null && this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); - const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); - SetUpReadableStreamBYOBRequest(byobRequest, this, view); - this._byobRequest = byobRequest; - } - return this._byobRequest; - } +class CompressedDataPacket { + static get tag() { + return enums.packet.compressedData; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + * List of packets + * @type {PacketList} */ - get desiredSize() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('desiredSize'); - } - return ReadableByteStreamControllerGetDesiredSize(this); - } + this.packets = null; /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. + * Compression algorithm + * @type {enums.compression} */ - close() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('close'); - } - if (this._closeRequested) { - throw new TypeError('The stream has already been closed; do not close it again!'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); - } - ReadableByteStreamControllerClose(this); - } - enqueue(chunk) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('enqueue'); - } - assertRequiredArgument(chunk, 1, 'enqueue'); - if (!ArrayBuffer.isView(chunk)) { - throw new TypeError('chunk must be an array buffer view'); - } - if (chunk.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (chunk.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._closeRequested) { - throw new TypeError('stream is closed or draining'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); - } - ReadableByteStreamControllerEnqueue(this, chunk); - } + this.algorithm = config$1.preferredCompressionAlgorithm; + /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + * Compressed packet data + * @type {Uint8Array | ReadableStream} */ - error(e = undefined) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('error'); - } - ReadableByteStreamControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - if (this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - firstDescriptor.bytesFilled = 0; - } - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableByteStreamControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableByteStream; - if (this._queueTotalSize > 0) { - const entry = this._queue.shift(); - this._queueTotalSize -= entry.byteLength; - ReadableByteStreamControllerHandleQueueDrain(this); - const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); - readRequest._chunkSteps(view); - return; - } - const autoAllocateChunkSize = this._autoAllocateChunkSize; - if (autoAllocateChunkSize !== undefined) { - let buffer; - try { - buffer = new ArrayBuffer(autoAllocateChunkSize); - } - catch (bufferE) { - readRequest._errorSteps(bufferE); - return; - } - const pullIntoDescriptor = { - buffer, - byteOffset: 0, - byteLength: autoAllocateChunkSize, - bytesFilled: 0, - elementSize: 1, - viewConstructor: Uint8Array, - readerType: 'default' - }; - this._pendingPullIntos.push(pullIntoDescriptor); - } - ReadableStreamAddReadRequest(stream, readRequest); - ReadableByteStreamControllerCallPullIfNeeded(this); - } -} -Object.defineProperties(ReadableByteStreamController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - byobRequest: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableByteStreamController', - configurable: true - }); -} -// Abstract operations for the ReadableByteStreamController. -function IsReadableByteStreamController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { - return false; - } - return true; -} -function IsReadableStreamBYOBRequest(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { - return false; - } - return true; -} -function ReadableByteStreamControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - // TODO: Test controller argument - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableByteStreamControllerError(controller, e); + this.compressed = null; + } + + /** + * Parsing function for the packet. + * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async read(bytes, config$1 = config) { + await parse(bytes, async reader => { + + // One octet that gives the algorithm used to compress the packet. + this.algorithm = await reader.readByte(); + + // Compressed data, which makes up the remainder of the packet. + this.compressed = reader.remainder(); + + await this.decompress(config$1); }); -} -function ReadableByteStreamControllerClearPendingPullIntos(controller) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - controller._pendingPullIntos = new SimpleQueue(); -} -function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { - let done = false; - if (stream._state === 'closed') { - done = true; - } - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - if (pullIntoDescriptor.readerType === 'default') { - ReadableStreamFulfillReadRequest(stream, filledView, done); - } - else { - ReadableStreamFulfillReadIntoRequest(stream, filledView, done); - } -} -function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { - const bytesFilled = pullIntoDescriptor.bytesFilled; - const elementSize = pullIntoDescriptor.elementSize; - return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); -} -function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { - controller._queue.push({ buffer, byteOffset, byteLength }); - controller._queueTotalSize += byteLength; -} -function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { - const elementSize = pullIntoDescriptor.elementSize; - const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; - const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); - const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; - const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; - let totalBytesToCopyRemaining = maxBytesToCopy; - let ready = false; - if (maxAlignedBytes > currentAlignedBytes) { - totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; - ready = true; - } - const queue = controller._queue; - while (totalBytesToCopyRemaining > 0) { - const headOfQueue = queue.peek(); - const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); - const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); - if (headOfQueue.byteLength === bytesToCopy) { - queue.shift(); - } - else { - headOfQueue.byteOffset += bytesToCopy; - headOfQueue.byteLength -= bytesToCopy; - } - controller._queueTotalSize -= bytesToCopy; - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); - totalBytesToCopyRemaining -= bytesToCopy; - } - return ready; -} -function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - pullIntoDescriptor.bytesFilled += size; -} -function ReadableByteStreamControllerHandleQueueDrain(controller) { - if (controller._queueTotalSize === 0 && controller._closeRequested) { - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(controller._controlledReadableByteStream); - } - else { - ReadableByteStreamControllerCallPullIfNeeded(controller); + } + + + /** + * Return the compressed packet. + * @returns {Uint8Array | ReadableStream} Binary compressed packet. + */ + write() { + if (this.compressed === null) { + this.compress(); } -} -function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { - if (controller._byobRequest === null) { - return; + + return util.concat([new Uint8Array([this.algorithm]), this.compressed]); + } + + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async decompress(config$1 = config) { + const compressionName = enums.read(enums.compression, this.algorithm); + const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async + if (!decompressionFn) { + throw new Error(`${compressionName} decompression not supported`); } - controller._byobRequest._associatedReadableByteStreamController = undefined; - controller._byobRequest._view = null; - controller._byobRequest = null; -} -function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { - while (controller._pendingPullIntos.length > 0) { - if (controller._queueTotalSize === 0) { - return; - } - const pullIntoDescriptor = controller._pendingPullIntos.peek(); - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - } + + this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets$5, config$1); + } + + /** + * Compress the packet data (member decompressedData) + */ + compress() { + const compressionName = enums.read(enums.compression, this.algorithm); + const compressionFn = compress_fns[compressionName]; + if (!compressionFn) { + throw new Error(`${compressionName} compression not supported`); } + + this.compressed = compressionFn(this.packets.write()); + } } -function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { - const stream = controller._controlledReadableByteStream; - let elementSize = 1; - if (view.constructor !== DataView) { - elementSize = view.constructor.BYTES_PER_ELEMENT; - } - const ctor = view.constructor; - const buffer = TransferArrayBuffer(view.buffer); - const pullIntoDescriptor = { - buffer, - byteOffset: view.byteOffset, - byteLength: view.byteLength, - bytesFilled: 0, - elementSize, - viewConstructor: ctor, - readerType: 'byob' - }; - if (controller._pendingPullIntos.length > 0) { - controller._pendingPullIntos.push(pullIntoDescriptor); - // No ReadableByteStreamControllerCallPullIfNeeded() call since: - // - No change happens on desiredSize - // - The source has already been notified of that there's at least 1 pending read(view) - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - return; - } - if (stream._state === 'closed') { - const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); - readIntoRequest._closeSteps(emptyView); - return; - } - if (controller._queueTotalSize > 0) { - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - ReadableByteStreamControllerHandleQueueDrain(controller); - readIntoRequest._chunkSteps(filledView); - return; - } - if (controller._closeRequested) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - readIntoRequest._errorSteps(e); - return; - } + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + +/** + * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise. + * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator + * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor + * @returns {ReadableStream} compressed or decompressed data + */ +function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) { + return data => { + if (!util.isStream(data) || isArrayStream(data)) { + return fromAsync(() => readToEnd(data).then(inputData => { + return new Promise((resolve, reject) => { + const zlibStream = new ZlibStreamedConstructor(); + zlibStream.ondata = processedData => { + resolve(processedData); + }; + try { + zlibStream.push(inputData, true); // only one chunk to push + } catch (err) { + reject(err); + } + }); + })); } - controller._pendingPullIntos.push(pullIntoDescriptor); - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { - firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); - const stream = controller._controlledReadableByteStream; - if (ReadableStreamHasBYOBReader(stream)) { - while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { - const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + + // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) + if (compressionStreamInstantiator) { + try { + const compressorOrDecompressor = compressionStreamInstantiator(); + return data.pipeThrough(compressorOrDecompressor); + } catch (err) { + // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate. + if (err.name !== 'TypeError') { + throw err; } + } } -} -function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { - if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { - throw new RangeError('bytesWritten out of range'); - } - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); - if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { - // TODO: Figure out whether we should detach the buffer or not here. - return; - } - ReadableByteStreamControllerShiftPendingPullInto(controller); - const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; - if (remainderSize > 0) { - const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); - ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); - } - pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); - pullIntoDescriptor.bytesFilled -= remainderSize; - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); -} -function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { - const firstDescriptor = controller._pendingPullIntos.peek(); - const state = controller._controlledReadableByteStream._state; - if (state === 'closed') { - if (bytesWritten !== 0) { - throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + + // JS fallback + const inputReader = data.getReader(); + const zlibStream = new ZlibStreamedConstructor(); + + return new ReadableStream({ + async start(controller) { + zlibStream.ondata = async (value, isLast) => { + controller.enqueue(value); + if (isLast) { + controller.close(); + } + }; + + while (true) { + const { done, value } = await inputReader.read(); + if (done) { + zlibStream.push(new Uint8Array(), true); + return; + } else if (value.length) { + zlibStream.push(value); + } } - ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); - } - else { - ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }); + }; } -function ReadableByteStreamControllerShiftPendingPullInto(controller) { - const descriptor = controller._pendingPullIntos.shift(); - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - return descriptor; + +function bzip2Decompress() { + return async function(data) { + const { decode: bunzipDecode } = await Promise.resolve().then(function () { return index; }); + return fromAsync(async () => bunzipDecode(await readToEnd(data))); + }; } -function ReadableByteStreamControllerShouldCallPull(controller) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return false; - } - if (controller._closeRequested) { - return false; - } - if (!controller._started) { - return false; + +/** + * Get Compression Stream API instatiators if the constructors are implemented. + * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported + * (supported formats cannot be determined in advance). + * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat + * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }} + */ +const getCompressionStreamInstantiators = compressionFormat => ({ + compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)), + decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat)) +}); + +const compress_fns = { + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib) +}; + +const decompress_fns = { + uncompressed: data => data, + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib), + bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import +}; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A SEIP packet can contain the following packet types +const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +/** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ +class SymEncryptedIntegrityProtectedDataPacket { + static get tag() { + return enums.packet.symEncryptedIntegrityProtectedData; + } + + static fromObject({ version, aeadAlgorithm }) { + if (version !== 1 && version !== 2) { + throw new Error('Unsupported SEIPD version'); } - if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; + + const seip = new SymEncryptedIntegrityProtectedDataPacket(); + seip.version = version; + if (version === 2) { + seip.aeadAlgorithm = aeadAlgorithm; } - if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { - return true; + + return seip; + } + + constructor() { + this.version = null; + + // The following 4 fields are for V2 only. + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = null; + this.chunkSizeByte = null; + this.salt = null; + + this.encrypted = null; + this.packets = null; + } + + async read(bytes) { + await parse(bytes, async reader => { + this.version = await reader.readByte(); + // - A one-octet version number with value 1 or 2. + if (this.version !== 1 && this.version !== 2) { + throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`); + } + + if (this.version === 2) { + // - A one-octet cipher algorithm. + this.cipherAlgorithm = await reader.readByte(); + // - A one-octet AEAD algorithm. + this.aeadAlgorithm = await reader.readByte(); + // - A one-octet chunk size. + this.chunkSizeByte = await reader.readByte(); + // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique. + this.salt = await reader.readBytes(32); + } + + // For V1: + // - Encrypted data, the output of the selected symmetric-key cipher + // operating in Cipher Feedback mode with shift amount equal to the + // block size of the cipher (CFB-n where n is the block size). + // For V2: + // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode. + // - A final, summary authentication tag for the AEAD mode. + this.encrypted = reader.remainder(); + }); + } + + write() { + if (this.version === 2) { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]); } - const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; + return util.concat([new Uint8Array([this.version]), this.encrypted]); + } + + /** + * Encrypt the payload in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on encryption failure + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + const { blockSize, keySize } = mod$1.getCipherParams(sessionKeyAlgorithm); + if (key.length !== keySize) { + throw new Error('Unexpected session key size'); } - return false; -} -function ReadableByteStreamControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; -} -// A client of ReadableByteStreamController may use these functions directly to bypass state check. -function ReadableByteStreamControllerClose(controller) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + + let bytes = this.packets.write(); + if (isArrayStream(bytes)) bytes = await readToEnd(bytes); + + if (this.version === 2) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + this.salt = mod$1.random.getRandomBytes(32); + this.chunkSizeByte = config$1.aeadChunkSizeByte; + this.encrypted = await runAEAD(this, 'encrypt', key, bytes); + } else { + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet + + const tohash = util.concat([prefix, bytes, mdc]); + const hash = await mod$1.hash.sha1(passiveClone(tohash)); + const plaintext = util.concat([tohash, hash]); + + this.encrypted = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); } - if (controller._queueTotalSize > 0) { - controller._closeRequested = true; - return; + return true; + } + + /** + * Decrypts the encrypted data contained in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on decryption failure + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + if (key.length !== mod$1.getCipherParams(sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); } - if (controller._pendingPullIntos.length > 0) { - const firstPendingPullInto = controller._pendingPullIntos.peek(); - if (firstPendingPullInto.bytesFilled > 0) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - throw e; - } + + let encrypted = clone(this.encrypted); + if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); + + let packetbytes; + if (this.version === 2) { + if (this.cipherAlgorithm !== sessionKeyAlgorithm) { + // sanity check + throw new Error('Unexpected session key algorithm'); + } + packetbytes = await runAEAD(this, 'decrypt', key, encrypted); + } else { + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); + + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + const realHash = slice(passiveClone(decrypted), -20); + const tohash = slice(decrypted, 0, -20); + const verifyHash = Promise.all([ + readToEnd(await mod$1.hash.sha1(passiveClone(tohash))), + readToEnd(realHash) + ]).then(([hash, mdc]) => { + if (!util.equalsUint8Array(hash, mdc)) { + throw new Error('Modification detected.'); + } + return new Uint8Array(); + }); + const bytes = slice(tohash, blockSize + 2); // Remove random prefix + packetbytes = slice(bytes, 0, -2); // Remove MDC packet + packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); + if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { + packetbytes = await readToEnd(packetbytes); + } } - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(stream); + + this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1); + return true; + } } -function ReadableByteStreamControllerEnqueue(controller, chunk) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + +/** + * En/decrypt the payload. + * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt + * @param {Uint8Array} key - The session key used to en/decrypt the payload + * @param {Uint8Array | ReadableStream} data - The data to en/decrypt + * @returns {Promise>} + * @async + */ +async function runAEAD(packet, fn, key, data) { + const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2; + const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import) + if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type'); + + const mode = mod$1.getAEADMode(packet.aeadAlgorithm); + const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; + const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; + const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) + const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0; + const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP); + const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP); + const adataTagArray = new Uint8Array(adataBuffer); + const adataView = new DataView(adataBuffer); + const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); + adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0); + let chunkIndex = 0; + let latestPromise = Promise.resolve(); + let cryptedBytes = 0; + let queuedBytes = 0; + let iv; + let ivView; + if (isSEIPDv2) { + const { keySize } = mod$1.getCipherParams(packet.cipherAlgorithm); + const { ivLength } = mode; + const info = new Uint8Array(adataBuffer, 0, 5); + const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength); + key = derived.subarray(0, keySize); + iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. + iv.fill(0, iv.length - 8); + ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + } else { // AEADEncryptedDataPacket + iv = packet.iv; + // ivView is unused in this case + } + const modeInstance = await mode(packet.cipherAlgorithm, key); + return transformPair(data, async (readable, writable) => { + if (util.isStream(readable) !== 'array') { + const buffer = new TransformStream({}, { + highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6), + size: array => array.length + }); + pipe(buffer.readable, writable); + writable = buffer.writable; } - const buffer = chunk.buffer; - const byteOffset = chunk.byteOffset; - const byteLength = chunk.byteLength; - const transferredBuffer = TransferArrayBuffer(buffer); - if (ReadableStreamHasDefaultReader(stream)) { - if (ReadableStreamGetNumReadRequests(stream) === 0) { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + const reader = getReader(readable); + const writer = getWriter(writable); + try { + while (true) { + let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); + const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); + chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); + let cryptedPromise; + let done; + let nonce; + if (isSEIPDv2) { // SEIPD V2 + nonce = iv; + } else { // AEADEncryptedDataPacket + nonce = iv.slice(); + for (let i = 0; i < 8; i++) { + nonce[iv.length - 8 + i] ^= chunkIndexArray[i]; + } } - else { - const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); - ReadableStreamFulfillReadRequest(stream, transferredView, false); + if (!chunkIndex || chunk.length) { + reader.unshift(finalChunk); + cryptedPromise = modeInstance[fn](chunk, nonce, adataArray); + cryptedPromise.catch(() => {}); + queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; + } else { + // After the last chunk, we either encrypt a final, empty + // data chunk to get the final authentication tag or + // validate that final authentication tag. + adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...) + cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray); + cryptedPromise.catch(() => {}); + queuedBytes += tagLengthIfEncrypting; + done = true; + } + cryptedBytes += chunk.length - tagLengthIfDecrypting; + // eslint-disable-next-line @typescript-eslint/no-loop-func + latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { + await writer.ready; + await writer.write(crypted); + queuedBytes -= crypted.length; + }).catch(err => writer.abort(err)); + if (done || queuedBytes > writer.desiredSize) { + await latestPromise; // Respect backpressure + } + if (!done) { + if (isSEIPDv2) { // SEIPD V2 + ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...) + } else { // AEADEncryptedDataPacket + adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) + } + } else { + await writer.close(); + break; } + } + } catch (e) { + await writer.ready.catch(() => {}); + await writer.abort(e); } - else if (ReadableStreamHasBYOBReader(stream)) { - // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); - } - else { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerError(controller, e) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return; - } - ReadableByteStreamControllerClearPendingPullIntos(controller); - ResetQueue(controller); - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableByteStreamControllerGetDesiredSize(controller) { - const state = controller._controlledReadableByteStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -function ReadableByteStreamControllerRespond(controller, bytesWritten) { - bytesWritten = Number(bytesWritten); - if (!IsFiniteNonNegativeNumber(bytesWritten)) { - throw new RangeError('bytesWritten must be a finite'); - } - ReadableByteStreamControllerRespondInternal(controller, bytesWritten); -} -function ReadableByteStreamControllerRespondWithNewView(controller, view) { - const firstDescriptor = controller._pendingPullIntos.peek(); - if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { - throw new RangeError('The region specified by view does not match byobRequest'); - } - if (firstDescriptor.byteLength !== view.byteLength) { - throw new RangeError('The buffer of view has different capacity than byobRequest'); - } - firstDescriptor.buffer = view.buffer; - ReadableByteStreamControllerRespondInternal(controller, view.byteLength); -} -function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { - controller._controlledReadableByteStream = stream; - controller._pullAgain = false; - controller._pulling = false; - controller._byobRequest = null; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._closeRequested = false; - controller._started = false; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - controller._autoAllocateChunkSize = autoAllocateChunkSize; - controller._pendingPullIntos = new SimpleQueue(); - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableByteStreamControllerCallPullIfNeeded(controller); - }, r => { - ReadableByteStreamControllerError(controller, r); - }); -} -function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { - const controller = Object.create(ReadableByteStreamController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingByteSource.start !== undefined) { - startAlgorithm = () => underlyingByteSource.start(controller); - } - if (underlyingByteSource.pull !== undefined) { - pullAlgorithm = () => underlyingByteSource.pull(controller); - } - if (underlyingByteSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingByteSource.cancel(reason); - } - const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; - if (autoAllocateChunkSize === 0) { - throw new TypeError('autoAllocateChunkSize must be greater than 0'); - } - SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); -} -function SetUpReadableStreamBYOBRequest(request, controller, view) { - request._associatedReadableByteStreamController = controller; - request._view = view; -} -// Helper functions for the ReadableStreamBYOBRequest. -function byobRequestBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); -} -// Helper functions for the ReadableByteStreamController. -function byteStreamControllerBrandCheckException(name) { - return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + }); } -// Abstract operations for the ReadableStream. -function AcquireReadableStreamBYOBReader(stream) { - return new ReadableStreamBYOBReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { - stream._reader._readIntoRequests.push(readIntoRequest); -} -function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { - const reader = stream._reader; - const readIntoRequest = reader._readIntoRequests.shift(); - if (done) { - readIntoRequest._closeSteps(chunk); - } - else { - readIntoRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadIntoRequests(stream) { - return stream._reader._readIntoRequests.length; -} -function ReadableStreamHasBYOBReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamBYOBReader(reader)) { - return false; - } - return true; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// An AEAD-encrypted Data packet can contain the following packet types +const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + +const VERSION$1 = 1; // A one-octet version number of the data packet. + +/** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ +class AEADEncryptedDataPacket { + static get tag() { + return enums.packet.aeadEncryptedData; + } + + constructor() { + this.version = VERSION$1; + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = enums.aead.eax; + this.chunkSizeByte = null; + this.iv = null; + this.encrypted = null; + this.packets = null; + } + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param {Uint8Array | ReadableStream} bytes + * @throws {Error} on parsing failure + */ + async read(bytes) { + await parse(bytes, async reader => { + const version = await reader.readByte(); + if (version !== VERSION$1) { // The only currently defined value is 1. + throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); + } + this.cipherAlgorithm = await reader.readByte(); + this.aeadAlgorithm = await reader.readByte(); + this.chunkSizeByte = await reader.readByte(); + + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = await reader.readBytes(mode.ivLength); + this.encrypted = reader.remainder(); + }); + } + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns {Uint8Array | ReadableStream} The encrypted payload. + */ + write() { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); + } + + /** + * Decrypt the encrypted payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.packets = await PacketList.fromBinary( + await runAEAD(this, 'decrypt', key, clone(this.encrypted)), + allowedPackets$3, + config$1 + ); + } + + /** + * Encrypt the packet payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + const { ivLength } = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(ivLength); // generate new random IV + this.chunkSizeByte = config$1.aeadChunkSizeByte; + const data = this.packets.write(); + this.encrypted = await runAEAD(this, 'encrypt', key, data); + } } + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * A BYOB reader vended by a {@link ReadableStream}. + * Public-Key Encrypted Session Key Packets (Tag 1) * - * @public - */ -class ReadableStreamBYOBReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - if (!IsReadableByteStreamController(stream._readableStreamController)) { - throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + - 'source'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readIntoRequests = new SimpleQueue(); - } + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ +class PublicKeyEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.publicKeyEncryptedSessionKey; + } + + constructor() { + this.version = null; + + // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()` + this.publicKeyID = new KeyID(); + + // For version 6: + this.publicKeyVersion = null; + this.publicKeyFingerprint = null; + + // For all versions: + this.publicKeyAlgorithm = null; + + this.sessionKey = null; /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the reader's lock is released before the stream finishes closing. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - get closed() { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('closed')); - } - return this._closedPromise; + this.sessionKeyAlgorithm = null; + + /** @type {Object} */ + this.encrypted = {}; + } + + static fromObject({ + version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm + }) { + const pkesk = new PublicKeyEncryptedSessionKeyPacket(); + + if (version !== 3 && version !== 6) { + throw new Error('Unsupported PKESK version'); } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); + + pkesk.version = version; + + if (version === 6) { + pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version; + pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes(); } - /** - * Attempts to reads bytes into view, and returns a promise resolved with the result. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read(view) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('read')); - } - if (!ArrayBuffer.isView(view)) { - return promiseRejectedWith(new TypeError('view must be an array buffer view')); - } - if (view.byteLength === 0) { - return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); - } - if (view.buffer.byteLength === 0) { - return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readIntoRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamBYOBReaderRead(this, view, readIntoRequest); - return promise; + + pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID(); + pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkesk.sessionKey = sessionKey; + pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm; + + return pkesk; + } + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * + * @param {Uint8Array} bytes - Payload of a tag 1 packet + */ + read(bytes) { + let offset = 0; + this.version = bytes[offset++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamBYOBReader(this)) { - throw byobReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readIntoRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + if (this.version === 6) { + // A one-octet size of the following two fields: + // - A one octet key version number. + // - The fingerprint of the public key or subkey to which the session key is encrypted. + // The size may also be zero. + const versionAndFingerprintLength = bytes[offset++]; + if (versionAndFingerprintLength) { + this.publicKeyVersion = bytes[offset++]; + const fingerprintLength = versionAndFingerprintLength - 1; + this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength; + if (this.publicKeyVersion >= 5) { + // For v5/6 the Key ID is the high-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint); + } else { + // For v4 The Key ID is the low-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8)); } - ReadableStreamReaderGenericRelease(this); + } else { + // The size may also be zero, and the key version and + // fingerprint omitted for an "anonymous recipient" + this.publicKeyID = KeyID.wildcard(); + } + } else { + offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8)); } -} -Object.defineProperties(ReadableStreamBYOBReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamBYOBReader(x) { - if (!typeIsObject(x)) { - return false; + this.publicKeyAlgorithm = bytes[offset++]; + this.encrypted = mod$1.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset)); + if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) { + if (this.version === 3) { + this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + } else if (this.encrypted.C.algorithm !== null) { + throw new Error('Unexpected cleartext symmetric algorithm'); + } } - if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { - return false; + } + + /** + * Create a binary representation of a tag 1 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const arr = [ + new Uint8Array([this.version]) + ]; + + if (this.version === 6) { + if (this.publicKeyFingerprint !== null) { + arr.push(new Uint8Array([ + this.publicKeyFingerprint.length + 1, + this.publicKeyVersion] + )); + arr.push(this.publicKeyFingerprint); + } else { + arr.push(new Uint8Array([0])); + } + } else { + arr.push(this.publicKeyID.write()); } - return true; -} -function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'errored') { - readIntoRequest._errorSteps(stream._storedError); + + arr.push( + new Uint8Array([this.publicKeyAlgorithm]), + mod$1.serializeParams(this.publicKeyAlgorithm, this.encrypted) + ); + + return util.concatUint8Array(arr); + } + + /** + * Encrypt session key packet + * @param {PublicKeyPacket} key - Public key + * @throws {Error} if encryption failed + * @async + */ + async encrypt(key) { + const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); + // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a + // v6 PKESK packet, as it is included in the v2 SEIPD packet. + const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey); + this.encrypted = await mod$1.publicKeyEncrypt( + algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint); + } + + /** + * Decrypts the session key (only for public key encrypted session key packets (tag 1) + * @param {SecretKeyPacket} key - decrypted private key + * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. + * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } + * @throws {Error} if decryption failed, unless `randomSessionKey` is given + * @async + */ + async decrypt(key, randomSessionKey) { + // check that session key algo matches the secret key algo + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Decryption error'); } - else { - ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + + const randomPayload = randomSessionKey ? + encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : + null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const decryptedData = await mod$1.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload); + + const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); + + if (this.version === 3) { + // v3 Montgomery curves have cleartext cipher algo + const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448; + this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm; + + if (sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } } -} -// Helper functions for the ReadableStreamBYOBReader. -function byobReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + this.sessionKey = sessionKey; + } } -function ExtractHighWaterMark(strategy, defaultHWM) { - const { highWaterMark } = strategy; - if (highWaterMark === undefined) { - return defaultHWM; - } - if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { - throw new RangeError('Invalid highWaterMark'); - } - return highWaterMark; + +function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + // add checksum + return util.concatUint8Array([ + new Uint8Array(version === 6 ? [] : [cipherAlgo]), + sessionKeyData, + util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) + ]); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return sessionKeyData; + default: + throw new Error('Unsupported public key algorithm'); + } } -function ExtractSizeAlgorithm(strategy) { - const { size } = strategy; - if (!size) { - return () => 1; + + +function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: { + // verify checksum in constant time + const result = decryptedData.subarray(0, decryptedData.length - 2); + const checksum = decryptedData.subarray(decryptedData.length - 2); + const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); + const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; + const decryptedSessionKey = version === 6 ? + { sessionKeyAlgorithm: null, sessionKey: result } : + { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; + if (randomSessionKey) { + // We must not leak info about the validity of the decrypted checksum or cipher algo. + // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. + const isValidPayload = isValidChecksum & + decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & + decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; + return { + sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), + sessionKeyAlgorithm: version === 6 ? null : util.selectUint8( + isValidPayload, + decryptedSessionKey.sessionKeyAlgorithm, + randomSessionKey.sessionKeyAlgorithm + ) + }; + } else { + const isValidPayload = isValidChecksum && ( + version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm)); + if (isValidPayload) { + return decryptedSessionKey; + } else { + throw new Error('Decryption error'); + } + } } - return size; -} - -function convertQueuingStrategy(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - const size = init === null || init === void 0 ? void 0 : init.size; - return { - highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), - size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) - }; -} -function convertQueuingStrategySize(fn, context) { - assertFunction(fn, context); - return chunk => convertUnrestrictedDouble(fn(chunk)); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return { + sessionKeyAlgorithm: null, + sessionKey: decryptedData + }; + default: + throw new Error('Unsupported public key algorithm'); + } } -function convertUnderlyingSink(original, context) { - assertDictionary(original, context); - const abort = original === null || original === void 0 ? void 0 : original.abort; - const close = original === null || original === void 0 ? void 0 : original.close; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - const write = original === null || original === void 0 ? void 0 : original.write; - return { - abort: abort === undefined ? - undefined : - convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), - close: close === undefined ? - undefined : - convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), - start: start === undefined ? - undefined : - convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), - write: write === undefined ? - undefined : - convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), - type - }; -} -function convertUnderlyingSinkAbortCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSinkCloseCallback(fn, original, context) { - assertFunction(fn, context); - return () => promiseCall(fn, original, []); -} -function convertUnderlyingSinkStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertUnderlyingSinkWriteCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function assertWritableStream(x, context) { - if (!IsWritableStream(x)) { - throw new TypeError(`${context} is not a WritableStream.`); - } -} /** - * A writable stream represents a destination for data, into which you can write. + * Symmetric-Key Encrypted Session Key Packets (Tag 3) * - * @public + * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: + * The Symmetric-Key Encrypted Session Key packet holds the + * symmetric-key encryption of a session key used to encrypt a message. + * Zero or more Public-Key Encrypted Session Key packets and/or + * Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data packet that holds an encrypted message. + * The message is encrypted with a session key, and the session key is + * itself encrypted and stored in the Encrypted Session Key packet or + * the Symmetric-Key Encrypted Session Key packet. */ -class WritableStream$1 { - constructor(rawUnderlyingSink = {}, rawStrategy = {}) { - if (rawUnderlyingSink === undefined) { - rawUnderlyingSink = null; - } - else { - assertObject(rawUnderlyingSink, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); - InitializeWritableStream(this); - const type = underlyingSink.type; - if (type !== undefined) { - throw new RangeError('Invalid type is specified'); - } - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); - } - /** - * Returns whether or not the writable stream is locked to a writer. - */ - get locked() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('locked'); - } - return IsWritableStreamLocked(this); - } +class SymEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.symEncryptedSessionKey; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + this.version = config$1.aeadProtect ? 6 : 4; + this.sessionKey = null; /** - * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be - * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort - * mechanism of the underlying sink. - * - * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled - * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel - * the stream) if the stream is currently locked. + * Algorithm to encrypt the session key with + * @type {enums.symmetric} */ - abort(reason = undefined) { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('abort')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); - } - return WritableStreamAbort(this, reason); - } + this.sessionKeyEncryptionAlgorithm = null; /** - * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its - * close behavior. During this time any further attempts to write will fail (without erroring the stream). - * - * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream - * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with - * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - close() { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('close')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); - } - if (WritableStreamCloseQueuedOrInFlight(this)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamClose(this); - } + this.sessionKeyAlgorithm = null; /** - * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream - * is locked, no other writer can be acquired until this one is released. - * - * This functionality is especially useful for creating abstractions that desire the ability to write to a stream - * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at - * the same time, which would cause the resulting written data to be unpredictable and probably useless. + * AEAD mode to encrypt the session key with (if AEAD protection is enabled) + * @type {enums.aead} */ - getWriter() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('getWriter'); - } - return AcquireWritableStreamDefaultWriter(this); - } -} -Object.defineProperties(WritableStream$1.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - getWriter: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStream', - configurable: true - }); -} -// Abstract operations for the WritableStream. -function AcquireWritableStreamDefaultWriter(stream) { - return new WritableStreamDefaultWriter(stream); -} -// Throws if and only if startAlgorithm throws. -function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(WritableStream$1.prototype); - InitializeWritableStream(stream); - const controller = Object.create(WritableStreamDefaultController.prototype); - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeWritableStream(stream) { - stream._state = 'writable'; - // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is - // 'erroring' or 'errored'. May be set to an undefined value. - stream._storedError = undefined; - stream._writer = undefined; - // Initialize to undefined first because the constructor of the controller checks this - // variable to validate the caller. - stream._writableStreamController = undefined; - // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data - // producer without waiting for the queued writes to finish. - stream._writeRequests = new SimpleQueue(); - // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents - // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. - stream._inFlightWriteRequest = undefined; - // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer - // has been detached. - stream._closeRequest = undefined; - // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it - // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. - stream._inFlightCloseRequest = undefined; - // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. - stream._pendingAbortRequest = undefined; - // The backpressure signal set by the controller. - stream._backpressure = false; -} -function IsWritableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { - return false; - } - return true; -} -function IsWritableStreamLocked(stream) { - if (stream._writer === undefined) { - return false; - } - return true; -} -function WritableStreamAbort(stream, reason) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseResolvedWith(undefined); - } - if (stream._pendingAbortRequest !== undefined) { - return stream._pendingAbortRequest._promise; - } - let wasAlreadyErroring = false; - if (state === 'erroring') { - wasAlreadyErroring = true; - // reason will not be used, so don't keep a reference to it. - reason = undefined; - } - const promise = newPromise((resolve, reject) => { - stream._pendingAbortRequest = { - _promise: undefined, - _resolve: resolve, - _reject: reject, - _reason: reason, - _wasAlreadyErroring: wasAlreadyErroring - }; - }); - stream._pendingAbortRequest._promise = promise; - if (!wasAlreadyErroring) { - WritableStreamStartErroring(stream, reason); - } - return promise; -} -function WritableStreamClose(stream) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); - } - const promise = newPromise((resolve, reject) => { - const closeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._closeRequest = closeRequest; - }); - const writer = stream._writer; - if (writer !== undefined && stream._backpressure && state === 'writable') { - defaultWriterReadyPromiseResolve(writer); - } - WritableStreamDefaultControllerClose(stream._writableStreamController); - return promise; -} -// WritableStream API exposed for controllers. -function WritableStreamAddWriteRequest(stream) { - const promise = newPromise((resolve, reject) => { - const writeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._writeRequests.push(writeRequest); - }); - return promise; -} -function WritableStreamDealWithRejection(stream, error) { - const state = stream._state; - if (state === 'writable') { - WritableStreamStartErroring(stream, error); - return; - } - WritableStreamFinishErroring(stream); -} -function WritableStreamStartErroring(stream, reason) { - const controller = stream._writableStreamController; - stream._state = 'erroring'; - stream._storedError = reason; - const writer = stream._writer; - if (writer !== undefined) { - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); - } - if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { - WritableStreamFinishErroring(stream); - } -} -function WritableStreamFinishErroring(stream) { - stream._state = 'errored'; - stream._writableStreamController[ErrorSteps](); - const storedError = stream._storedError; - stream._writeRequests.forEach(writeRequest => { - writeRequest._reject(storedError); - }); - stream._writeRequests = new SimpleQueue(); - if (stream._pendingAbortRequest === undefined) { - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const abortRequest = stream._pendingAbortRequest; - stream._pendingAbortRequest = undefined; - if (abortRequest._wasAlreadyErroring) { - abortRequest._reject(storedError); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; + this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); + this.encrypted = null; + this.s2k = null; + this.iv = null; + } + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * + * @param {Uint8Array} bytes - Payload of a tag 3 packet + */ + read(bytes) { + let offset = 0; + + // A one-octet version number with value 4, 5 or 6. + this.version = bytes[offset++]; + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); } - const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); - uponPromise(promise, () => { - abortRequest._resolve(); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }, (reason) => { - abortRequest._reject(reason); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }); -} -function WritableStreamFinishInFlightWrite(stream) { - stream._inFlightWriteRequest._resolve(undefined); - stream._inFlightWriteRequest = undefined; -} -function WritableStreamFinishInFlightWriteWithError(stream, error) { - stream._inFlightWriteRequest._reject(error); - stream._inFlightWriteRequest = undefined; - WritableStreamDealWithRejection(stream, error); -} -function WritableStreamFinishInFlightClose(stream) { - stream._inFlightCloseRequest._resolve(undefined); - stream._inFlightCloseRequest = undefined; - const state = stream._state; - if (state === 'erroring') { - // The error was too late to do anything, so it is ignored. - stream._storedError = undefined; - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._resolve(); - stream._pendingAbortRequest = undefined; - } + + if (this.version === 6) { + // A one-octet scalar octet count of the following 5 fields. + offset++; } - stream._state = 'closed'; - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseResolve(writer); + + // A one-octet number describing the symmetric algorithm used. + const algo = bytes[offset++]; + + if (this.version >= 5) { + // A one-octet AEAD algorithm. + this.aeadAlgorithm = bytes[offset++]; + + if (this.version === 6) { + // A one-octet scalar octet count of the following field. + offset++; + } } -} -function WritableStreamFinishInFlightCloseWithError(stream, error) { - stream._inFlightCloseRequest._reject(error); - stream._inFlightCloseRequest = undefined; - // Never execute sink abort() after sink close(). - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._reject(error); - stream._pendingAbortRequest = undefined; + + // A string-to-key (S2K) specifier, length as defined above. + const s2kType = bytes[offset++]; + this.s2k = newS2KFromType(s2kType); + offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + + // A starting initialization vector of size specified by the AEAD + // algorithm. + this.iv = bytes.subarray(offset, offset += mode.ivLength); } - WritableStreamDealWithRejection(stream, error); -} -// TODO(ricea): Fix alphabetical order. -function WritableStreamCloseQueuedOrInFlight(stream) { - if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; + + // The encrypted session key itself, which is decrypted with the + // string-to-key object. This is optional in version 4. + if (this.version >= 5 || offset < bytes.length) { + this.encrypted = bytes.subarray(offset, bytes.length); + this.sessionKeyEncryptionAlgorithm = algo; + } else { + this.sessionKeyAlgorithm = algo; } - return true; -} -function WritableStreamHasOperationMarkedInFlight(stream) { - if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; + } + + /** + * Create a binary representation of a tag 3 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const algo = this.encrypted === null ? + this.sessionKeyAlgorithm : + this.sessionKeyEncryptionAlgorithm; + + let bytes; + + const s2k = this.s2k.write(); + if (this.version === 6) { + const s2kLen = s2k.length; + const fieldsLen = 3 + s2kLen + this.iv.length; + bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]); + } else if (this.version === 5) { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]); + } else { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]); + + if (this.encrypted !== null) { + bytes = util.concatUint8Array([bytes, this.encrypted]); + } } - return true; -} -function WritableStreamMarkCloseRequestInFlight(stream) { - stream._inFlightCloseRequest = stream._closeRequest; - stream._closeRequest = undefined; -} -function WritableStreamMarkFirstWriteRequestInFlight(stream) { - stream._inFlightWriteRequest = stream._writeRequests.shift(); -} -function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { - if (stream._closeRequest !== undefined) { - stream._closeRequest._reject(stream._storedError); - stream._closeRequest = undefined; + + return bytes; + } + + /** + * Decrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(passphrase) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); + } else if (this.encrypted !== null) { + const decrypted = await mod$1.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + + this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); + this.sessionKey = decrypted.subarray(1, decrypted.length); + if (this.sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + } else { + // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo + this.sessionKey = key; } - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseReject(writer, stream._storedError); + } + + /** + * Encrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + this.sessionKeyEncryptionAlgorithm = algo; + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.sessionKey === null) { + this.sessionKey = mod$1.generateSessionKey(this.sessionKeyAlgorithm); } -} -function WritableStreamUpdateBackpressure(stream, backpressure) { - const writer = stream._writer; - if (writer !== undefined && backpressure !== stream._backpressure) { - if (backpressure) { - defaultWriterReadyPromiseReset(writer); - } - else { - defaultWriterReadyPromiseResolve(writer); - } + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(mode.ivLength); // generate new random IV + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); + } else { + const toEncrypt = util.concatUint8Array([ + new Uint8Array([this.sessionKeyAlgorithm]), + this.sessionKey + ]); + this.encrypted = await mod$1.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config$1); } - stream._backpressure = backpressure; + } } + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * A default writer vended by a {@link WritableStream}. + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. * - * @public - */ -class WritableStreamDefaultWriter { - constructor(stream) { - assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); - assertWritableStream(stream, 'First parameter'); - if (IsWritableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive writing by another writer'); - } - this._ownerWritableStream = stream; - stream._writer = this; - const state = stream._state; - if (state === 'writable') { - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { - defaultWriterReadyPromiseInitialize(this); - } - else { - defaultWriterReadyPromiseInitializeAsResolved(this); - } - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'erroring') { - defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'closed') { - defaultWriterReadyPromiseInitializeAsResolved(this); - defaultWriterClosedPromiseInitializeAsResolved(this); - } - else { - const storedError = stream._storedError; - defaultWriterReadyPromiseInitializeAsRejected(this, storedError); - defaultWriterClosedPromiseInitializeAsRejected(this, storedError); - } - } + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ +class PublicKeyPacket { + static get tag() { + return enums.packet.publicKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the writer’s lock is released before the stream finishes closing. + * Packet version + * @type {Integer} */ - get closed() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('closed')); - } - return this._closedPromise; - } + this.version = config$1.v6Keys ? 6 : 4; /** - * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. - * A producer can use this information to determine the right amount of data to write. - * - * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort - * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when - * the writer’s lock is released. + * Key creation date. + * @type {Date} */ - get desiredSize() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('desiredSize'); - } - if (this._ownerWritableStream === undefined) { - throw defaultWriterLockException('desiredSize'); - } - return WritableStreamDefaultWriterGetDesiredSize(this); - } + this.created = util.normalizeDate(date); /** - * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions - * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips - * back to zero or below, the getter will return a new promise that stays pending until the next transition. - * - * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become - * rejected. + * Public key algorithm. + * @type {enums.publicKey} */ - get ready() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('ready')); - } - return this._readyPromise; - } + this.algorithm = null; /** - * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + * Algorithm specific public params + * @type {Object} */ - abort(reason = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('abort')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('abort')); - } - return WritableStreamDefaultWriterAbort(this, reason); - } + this.publicParams = null; /** - * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + * Time until expiration in days (V3 only) + * @type {Integer} */ - close() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('close')); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return promiseRejectedWith(defaultWriterLockException('close')); - } - if (WritableStreamCloseQueuedOrInFlight(stream)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamDefaultWriterClose(this); - } + this.expirationTimeV3 = 0; /** - * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. - * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from - * now on; otherwise, the writer will appear closed. - * - * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the - * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). - * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents - * other producers from writing in an interleaved manner. + * Fingerprint bytes + * @type {Uint8Array} */ - releaseLock() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('releaseLock'); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return; - } - WritableStreamDefaultWriterRelease(this); - } - write(chunk = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('write')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - return WritableStreamDefaultWriterWrite(this, chunk); - } -} -Object.defineProperties(WritableStreamDefaultWriter.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - releaseLock: { enumerable: true }, - write: { enumerable: true }, - closed: { enumerable: true }, - desiredSize: { enumerable: true }, - ready: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultWriter', - configurable: true - }); -} -// Abstract operations for the WritableStreamDefaultWriter. -function IsWritableStreamDefaultWriter(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { - return false; - } - return true; -} -// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. -function WritableStreamDefaultWriterAbort(writer, reason) { - const stream = writer._ownerWritableStream; - return WritableStreamAbort(stream, reason); -} -function WritableStreamDefaultWriterClose(writer) { - const stream = writer._ownerWritableStream; - return WritableStreamClose(stream); -} -function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseResolvedWith(undefined); - } - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - return WritableStreamDefaultWriterClose(writer); -} -function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { - if (writer._closedPromiseState === 'pending') { - defaultWriterClosedPromiseReject(writer, error); - } - else { - defaultWriterClosedPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { - if (writer._readyPromiseState === 'pending') { - defaultWriterReadyPromiseReject(writer, error); - } - else { - defaultWriterReadyPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterGetDesiredSize(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (state === 'errored' || state === 'erroring') { - return null; + this.fingerprint = null; + /** + * KeyID + * @type {module:type/keyid~KeyID} + */ + this.keyID = null; + } + + /** + * Create a PublicKeyPacket from a SecretKeyPacket + * @param {SecretKeyPacket} secretKeyPacket - key packet to convert + * @returns {PublicKeyPacket} public key packet + * @static + */ + static fromSecretKeyPacket(secretKeyPacket) { + const keyPacket = new PublicKeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * @param {Uint8Array} bytes - Input array to read the packet from + * @returns {Object} This object with attributes set by the parser + * @async + */ + async read(bytes, config$1 = config) { + let pos = 0; + // A one-octet version number (4, 5 or 6). + this.version = bytes[pos++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); } - if (state === 'closed') { - return 0; + + if (this.version === 4 || this.version === 5 || this.version === 6) { + // - A four-octet number denoting the time that the key was created. + this.created = util.readDate(bytes.subarray(pos, pos + 4)); + pos += 4; + + // - A one-octet number denoting the public-key algorithm of this key. + this.algorithm = bytes[pos++]; + + if (this.version >= 5) { + // - A four-octet scalar octet count for the following key material. + pos += 4; + } + + // - A series of values comprising the key material. + const { read, publicParams } = mod$1.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if ( + this.version === 6 && + publicParams.oid && ( + publicParams.oid.getName() === enums.curve.curve25519Legacy || + publicParams.oid.getName() === enums.curve.ed25519Legacy + ) + ) { + throw new Error('Legacy curve25519 cannot be used with v6 keys'); + } + this.publicParams = publicParams; + pos += read; + + // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor + await this.computeFingerprintAndKeyID(); + return pos; } - return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); -} -function WritableStreamDefaultWriterRelease(writer) { - const stream = writer._ownerWritableStream; - const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); - // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not - // rejected until afterwards. This means that simply testing state will not work. - WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); - stream._writer = undefined; - writer._ownerWritableStream = undefined; -} -function WritableStreamDefaultWriterWrite(writer, chunk) { - const stream = writer._ownerWritableStream; - const controller = stream._writableStreamController; - const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); - if (stream !== writer._ownerWritableStream) { - return promiseRejectedWith(defaultWriterLockException('write to')); + throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); + } + + /** + * Creates an OpenPGP public key packet for the given key. + * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. + */ + write() { + const arr = []; + // Version + arr.push(new Uint8Array([this.version])); + arr.push(util.writeDate(this.created)); + // A one-octet number denoting the public-key algorithm of this key + arr.push(new Uint8Array([this.algorithm])); + + const params = mod$1.serializeParams(this.algorithm, this.publicParams); + if (this.version >= 5) { + // A four-octet scalar octet count for the following key material + arr.push(util.writeNumber(params.length, 4)); } - const state = stream._state; - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); + // Algorithm-specific params + arr.push(params); + return util.concatUint8Array(arr); + } + + /** + * Write packet in order to be hashed; either for a signature or a fingerprint + * @param {Integer} version - target version of signature or key + */ + writeForHash(version) { + const bytes = this.writePublicKey(); + + const versionOctet = 0x95 + version; + const lengthOctets = version >= 5 ? 4 : 2; + return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]); + } + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return null; + } + + /** + * Returns the creation time of the key + * @returns {Date} + */ + getCreationTime() { + return this.created; + } + + /** + * Return the key ID of the key + * @returns {module:type/keyid~KeyID} The 8-byte key ID + */ + getKeyID() { + return this.keyID; + } + + /** + * Computes and set the key ID and fingerprint of the key + * @async + */ + async computeFingerprintAndKeyID() { + await this.computeFingerprint(); + this.keyID = new KeyID(); + + if (this.version >= 5) { + this.keyID.read(this.fingerprint.subarray(0, 8)); + } else if (this.version === 4) { + this.keyID.read(this.fingerprint.subarray(12, 20)); + } else { + throw new Error('Unsupported key version'); } - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + + /** + * Computes and set the fingerprint of the key + */ + async computeFingerprint() { + const toHash = this.writeForHash(this.version); + + if (this.version >= 5) { + this.fingerprint = await mod$1.hash.sha256(toHash); + } else if (this.version === 4) { + this.fingerprint = await mod$1.hash.sha1(toHash); + } else { + throw new Error('Unsupported key version'); } - if (state === 'erroring') { - return promiseRejectedWith(stream._storedError); + } + + /** + * Returns the fingerprint of the key, as an array of bytes + * @returns {Uint8Array} A Uint8Array containing the fingerprint + */ + getFingerprintBytes() { + return this.fingerprint; + } + + /** + * Calculates and returns the fingerprint of the key, as a string + * @returns {String} A string containing the fingerprint in lowercase hex + */ + getFingerprint() { + return util.uint8ArrayToHex(this.getFingerprintBytes()); + } + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns {Boolean} Whether the two keys have the same version and public key data. + */ + hasSameFingerprintAs(other) { + return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); + } + + /** + * Returns algorithm information + * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. + */ + getAlgorithmInfo() { + const result = {}; + result.algorithm = enums.read(enums.publicKey, this.algorithm); + // RSA, DSA or ElGamal public modulo + const modulo = this.publicParams.n || this.publicParams.p; + if (modulo) { + result.bits = util.uint8ArrayBitLength(modulo); + } else if (this.publicParams.oid) { + result.curve = this.publicParams.oid.getName(); } - const promise = WritableStreamAddWriteRequest(stream); - WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); - return promise; + return result; + } } -const closeSentinel = {}; + +/** + * Alias of read() + * @see PublicKeyPacket#read + */ +PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; + +/** + * Alias of write() + * @see PublicKeyPacket#write + */ +PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A SE packet can contain the following packet types +const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + /** - * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) * - * @public + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). */ -class WritableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } +class SymmetricallyEncryptedDataPacket { + static get tag() { + return enums.packet.symmetricallyEncryptedData; + } + + constructor() { /** - * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. - * - * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying - * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the - * normal lifecycle of interactions with the underlying sink. + * Encrypted secret-key data */ - error(e = undefined) { - if (!IsWritableStreamDefaultController(this)) { - throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); - } - const state = this._controlledWritableStream._state; - if (state !== 'writable') { - // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so - // just treat it as a no-op. - return; - } - WritableStreamDefaultControllerError(this, e); - } - /** @internal */ - [AbortSteps](reason) { - const result = this._abortAlgorithm(reason); - WritableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [ErrorSteps]() { - ResetQueue(this); - } -} -Object.defineProperties(WritableStreamDefaultController.prototype, { - error: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultController', - configurable: true - }); -} -// Abstract operations implementing interface required by the WritableStream. -function IsWritableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { - return false; - } - return true; -} -function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledWritableStream = stream; - stream._writableStreamController = controller; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._writeAlgorithm = writeAlgorithm; - controller._closeAlgorithm = closeAlgorithm; - controller._abortAlgorithm = abortAlgorithm; - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - const startResult = startAlgorithm(); - const startPromise = promiseResolvedWith(startResult); - uponPromise(startPromise, () => { - controller._started = true; - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, r => { - controller._started = true; - WritableStreamDealWithRejection(stream, r); - }); -} -function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { - const controller = Object.create(WritableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let writeAlgorithm = () => promiseResolvedWith(undefined); - let closeAlgorithm = () => promiseResolvedWith(undefined); - let abortAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSink.start !== undefined) { - startAlgorithm = () => underlyingSink.start(controller); - } - if (underlyingSink.write !== undefined) { - writeAlgorithm = chunk => underlyingSink.write(chunk, controller); - } - if (underlyingSink.close !== undefined) { - closeAlgorithm = () => underlyingSink.close(); - } - if (underlyingSink.abort !== undefined) { - abortAlgorithm = reason => underlyingSink.abort(reason); - } - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); -} -// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. -function WritableStreamDefaultControllerClearAlgorithms(controller) { - controller._writeAlgorithm = undefined; - controller._closeAlgorithm = undefined; - controller._abortAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -function WritableStreamDefaultControllerClose(controller) { - EnqueueValueWithSize(controller, closeSentinel, 0); - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { - try { - return controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); - return 1; - } -} -function WritableStreamDefaultControllerGetDesiredSize(controller) { - return controller._strategyHWM - controller._queueTotalSize; -} -function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); - return; - } - const stream = controller._controlledWritableStream; - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -// Abstract operations for the WritableStreamDefaultController. -function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { - const stream = controller._controlledWritableStream; - if (!controller._started) { - return; - } - if (stream._inFlightWriteRequest !== undefined) { - return; - } - const state = stream._state; - if (state === 'erroring') { - WritableStreamFinishErroring(stream); - return; - } - if (controller._queue.length === 0) { - return; - } - const value = PeekQueueValue(controller); - if (value === closeSentinel) { - WritableStreamDefaultControllerProcessClose(controller); - } - else { - WritableStreamDefaultControllerProcessWrite(controller, value); - } -} -function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { - if (controller._controlledWritableStream._state === 'writable') { - WritableStreamDefaultControllerError(controller, error); - } -} -function WritableStreamDefaultControllerProcessClose(controller) { - const stream = controller._controlledWritableStream; - WritableStreamMarkCloseRequestInFlight(stream); - DequeueValue(controller); - const sinkClosePromise = controller._closeAlgorithm(); - WritableStreamDefaultControllerClearAlgorithms(controller); - uponPromise(sinkClosePromise, () => { - WritableStreamFinishInFlightClose(stream); - }, reason => { - WritableStreamFinishInFlightCloseWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerProcessWrite(controller, chunk) { - const stream = controller._controlledWritableStream; - WritableStreamMarkFirstWriteRequestInFlight(stream); - const sinkWritePromise = controller._writeAlgorithm(chunk); - uponPromise(sinkWritePromise, () => { - WritableStreamFinishInFlightWrite(stream); - const state = stream._state; - DequeueValue(controller); - if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, reason => { - if (stream._state === 'writable') { - WritableStreamDefaultControllerClearAlgorithms(controller); - } - WritableStreamFinishInFlightWriteWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerGetBackpressure(controller) { - const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); - return desiredSize <= 0; -} -// A client of WritableStreamDefaultController may use these functions directly to bypass state check. -function WritableStreamDefaultControllerError(controller, error) { - const stream = controller._controlledWritableStream; - WritableStreamDefaultControllerClearAlgorithms(controller); - WritableStreamStartErroring(stream, error); -} -// Helper functions for the WritableStream. -function streamBrandCheckException$2(name) { - return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); -} -// Helper functions for the WritableStreamDefaultWriter. -function defaultWriterBrandCheckException(name) { - return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); -} -function defaultWriterLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released writer'); -} -function defaultWriterClosedPromiseInitialize(writer) { - writer._closedPromise = newPromise((resolve, reject) => { - writer._closedPromise_resolve = resolve; - writer._closedPromise_reject = reject; - writer._closedPromiseState = 'pending'; - }); -} -function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseReject(writer, reason); -} -function defaultWriterClosedPromiseInitializeAsResolved(writer) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseResolve(writer); -} -function defaultWriterClosedPromiseReject(writer, reason) { - if (writer._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._closedPromise); - writer._closedPromise_reject(reason); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'rejected'; -} -function defaultWriterClosedPromiseResetToRejected(writer, reason) { - defaultWriterClosedPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterClosedPromiseResolve(writer) { - if (writer._closedPromise_resolve === undefined) { - return; - } - writer._closedPromise_resolve(undefined); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'resolved'; -} -function defaultWriterReadyPromiseInitialize(writer) { - writer._readyPromise = newPromise((resolve, reject) => { - writer._readyPromise_resolve = resolve; - writer._readyPromise_reject = reject; - }); - writer._readyPromiseState = 'pending'; -} -function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseReject(writer, reason); -} -function defaultWriterReadyPromiseInitializeAsResolved(writer) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseResolve(writer); -} -function defaultWriterReadyPromiseReject(writer, reason) { - if (writer._readyPromise_reject === undefined) { - return; + this.encrypted = null; + /** + * Decrypted packets contained within. + * @type {PacketList} + */ + this.packets = null; + } + + read(bytes) { + this.encrypted = bytes; + } + + write() { + return this.encrypted; + } + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error + if (!config$1.allowUnauthenticatedMessages) { + throw new Error('Message is not authenticated.'); } - setPromiseIsHandledToTrue(writer._readyPromise); - writer._readyPromise_reject(reason); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'rejected'; -} -function defaultWriterReadyPromiseReset(writer) { - defaultWriterReadyPromiseInitialize(writer); -} -function defaultWriterReadyPromiseResetToRejected(writer, reason) { - defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const encrypted = await readToEnd(clone(this.encrypted)); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, + encrypted.subarray(blockSize + 2), + encrypted.subarray(2, blockSize + 2) + ); + + this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1); + } + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + const data = this.packets.write(); + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const FRE = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); + const ciphertext = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); + this.encrypted = util.concat([FRE, ciphertext]); + } } -function defaultWriterReadyPromiseResolve(writer) { - if (writer._readyPromise_resolve === undefined) { - return; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the strange "Marker packet" (Tag 10) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * + * The body of this packet consists of: + * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + * + * Such a packet MUST be ignored when received. It may be placed at the + * beginning of a message that uses features not available in PGP + * version 2.6 in order to cause that version to report that newer + * software is necessary to process the message. + */ +class MarkerPacket { + static get tag() { + return enums.packet.marker; + } + + /** + * Parsing function for a marker data packet (tag 10). + * @param {Uint8Array} bytes - Payload of a tag 10 packet + * @returns {Boolean} whether the packet payload contains "PGP" + */ + read(bytes) { + if (bytes[0] === 0x50 && // P + bytes[1] === 0x47 && // G + bytes[2] === 0x50) { // P + return true; } - writer._readyPromise_resolve(undefined); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'fulfilled'; + return false; + } + + write() { + return new Uint8Array([0x50, 0x47, 0x50]); + } } -function isAbortSignal(value) { - if (typeof value !== 'object' || value === null) { - return false; - } - try { - return typeof value.aborted === 'boolean'; - } - catch (_a) { - // AbortSignal.prototype.aborted throws if its brand check fails - return false; - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + * @extends PublicKeyPacket + */ +class PublicSubkeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.publicSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(date, config) { + super(date, config); + } + + /** + * Create a PublicSubkeyPacket from a SecretSubkeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert + * @returns {SecretSubkeyPacket} public key packet + * @static + */ + static fromSecretSubkeyPacket(secretSubkeyPacket) { + const keyPacket = new PublicSubkeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } } -/// -const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + -/// -function isDOMExceptionConstructor(ctor) { - if (!(typeof ctor === 'function' || typeof ctor === 'object')) { - return false; +/** + * Implementation of the User Attribute Packet (Tag 17) + * + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ +class UserAttributePacket { + static get tag() { + return enums.packet.userAttribute; + } + + constructor() { + this.attributes = []; + } + + /** + * parsing function for a user attribute packet (tag 17). + * @param {Uint8Array} input - Payload of a tag 17 packet + */ + read(bytes) { + let i = 0; + while (i < bytes.length) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); + i += len.len; } - try { - new ctor(); - return true; + } + + /** + * Creates a binary representation of the user attribute packet + * @returns {Uint8Array} String representation. + */ + write() { + const arr = []; + for (let i = 0; i < this.attributes.length; i++) { + arr.push(writeSimpleLength(this.attributes[i].length)); + arr.push(util.stringToUint8Array(this.attributes[i])); } - catch (_a) { - return false; + return util.concatUint8Array(arr); + } + + /** + * Compare for equality + * @param {UserAttributePacket} usrAttr + * @returns {Boolean} True if equal. + */ + equals(usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { + return false; } -} -function createDOMExceptionPolyfill() { - // eslint-disable-next-line no-shadow - const ctor = function DOMException(message, name) { - this.message = message || ''; - this.name = name || 'Error'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - }; - ctor.prototype = Object.create(Error.prototype); - Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); - return ctor; -} -// eslint-disable-next-line no-redeclare -const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); - -function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { - const reader = AcquireReadableStreamDefaultReader(source); - const writer = AcquireWritableStreamDefaultWriter(dest); - source._disturbed = true; - let shuttingDown = false; - // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. - let currentWrite = promiseResolvedWith(undefined); - return newPromise((resolve, reject) => { - let abortAlgorithm; - if (signal !== undefined) { - abortAlgorithm = () => { - const error = new DOMException$1('Aborted', 'AbortError'); - const actions = []; - if (!preventAbort) { - actions.push(() => { - if (dest._state === 'writable') { - return WritableStreamAbort(dest, error); - } - return promiseResolvedWith(undefined); - }); - } - if (!preventCancel) { - actions.push(() => { - if (source._state === 'readable') { - return ReadableStreamCancel(source, error); - } - return promiseResolvedWith(undefined); - }); - } - shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); - }; - if (signal.aborted) { - abortAlgorithm(); - return; - } - signal.addEventListener('abort', abortAlgorithm); - } - // Using reader and writer, read all chunks from this and write them to dest - // - Backpressure must be enforced - // - Shutdown must stop all activity - function pipeLoop() { - return newPromise((resolveLoop, rejectLoop) => { - function next(done) { - if (done) { - resolveLoop(); - } - else { - // Use `PerformPromiseThen` instead of `uponPromise` to avoid - // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers - PerformPromiseThen(pipeStep(), next, rejectLoop); - } - } - next(false); - }); - } - function pipeStep() { - if (shuttingDown) { - return promiseResolvedWith(true); - } - return PerformPromiseThen(writer._readyPromise, () => { - return newPromise((resolveRead, rejectRead) => { - ReadableStreamDefaultReaderRead(reader, { - _chunkSteps: chunk => { - currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); - resolveRead(false); - }, - _closeSteps: () => resolveRead(true), - _errorSteps: rejectRead - }); - }); - }); - } - // Errors must be propagated forward - isOrBecomesErrored(source, reader._closedPromise, storedError => { - if (!preventAbort) { - shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Errors must be propagated backward - isOrBecomesErrored(dest, writer._closedPromise, storedError => { - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Closing must be propagated forward - isOrBecomesClosed(source, reader._closedPromise, () => { - if (!preventClose) { - shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); - } - else { - shutdown(); - } - }); - // Closing must be propagated backward - if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { - const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); - } - else { - shutdown(true, destClosed); - } - } - setPromiseIsHandledToTrue(pipeLoop()); - function waitForWritesToFinish() { - // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait - // for that too. - const oldCurrentWrite = currentWrite; - return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); - } - function isOrBecomesErrored(stream, promise, action) { - if (stream._state === 'errored') { - action(stream._storedError); - } - else { - uponRejection(promise, action); - } - } - function isOrBecomesClosed(stream, promise, action) { - if (stream._state === 'closed') { - action(); - } - else { - uponFulfillment(promise, action); - } - } - function shutdownWithAction(action, originalIsError, originalError) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), doTheRest); - } - else { - doTheRest(); - } - function doTheRest() { - uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); - } - } - function shutdown(isError, error) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); - } - else { - finalize(isError, error); - } - } - function finalize(isError, error) { - WritableStreamDefaultWriterRelease(writer); - ReadableStreamReaderGenericRelease(reader); - if (signal !== undefined) { - signal.removeEventListener('abort', abortAlgorithm); - } - if (isError) { - reject(error); - } - else { - resolve(undefined); - } - } + return this.attributes.every(function(attr, index) { + return attr === usrAttr.attributes[index]; }); + } } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. - * - * @public + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + * @extends PublicKeyPacket */ -class ReadableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } +class SecretKeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.secretKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + * Secret-key data */ - get desiredSize() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('desiredSize'); - } - return ReadableStreamDefaultControllerGetDesiredSize(this); - } + this.keyMaterial = null; /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. + * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. */ - close() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('close'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits close'); - } - ReadableStreamDefaultControllerClose(this); + this.isEncrypted = null; + /** + * S2K usage + * @type {enums.symmetric} + */ + this.s2kUsage = 0; + /** + * S2K object + * @type {type/s2k} + */ + this.s2k = null; + /** + * Symmetric algorithm to encrypt the key with + * @type {enums.symmetric} + */ + this.symmetric = null; + /** + * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) + * @type {enums.aead} + */ + this.aead = null; + /** + * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis + * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older). + * This value is only relevant to know how to decrypt the key: + * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism. + * @type {Boolean} + * @private + */ + this.isLegacyAEAD = null; + /** + * Decrypted private parameters, referenced by name + * @type {Object} + */ + this.privateParams = null; + /** + * `true` for keys whose integrity is already confirmed, based on + * the AEAD encryption mechanism + * @type {Boolean} + * @private + */ + this.usedModernAEAD = null; + } + + // 5.5.3. Secret-Key Packet Formats + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param {Uint8Array} bytes - Input string to read the packet from + * @async + */ + async read(bytes, config$1 = config) { + // - A Public-Key or Public-Subkey packet, as described above. + let i = await this.readPublicKey(bytes, config$1); + const startOfSecretKeyData = i; + + // - One octet indicating string-to-key usage conventions. Zero + // indicates that the secret-key data is not encrypted. 255 or 254 + // indicates that a string-to-key specifier is being given. Any + // other value is a symmetric-key encryption algorithm identifier. + this.s2kUsage = bytes[i++]; + + // - Only for a version 5 packet, a one-octet scalar octet count of + // the next 4 optional fields. + if (this.version === 5) { + i++; } - enqueue(chunk = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('enqueue'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits enqueue'); + + // - Only for a version 6 packet where the secret key material is + // encrypted (that is, where the previous octet is not zero), a one- + // octet scalar octet count of the cumulative length of all the + // following optional string-to-key parameter fields. + if (this.version === 6 && this.s2kUsage) { + i++; + } + + try { + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one-octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + this.symmetric = bytes[i++]; + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + this.aead = bytes[i++]; } - return ReadableStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('error'); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + i++; } - ReadableStreamDefaultControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableStream; - if (this._queue.length > 0) { - const chunk = DequeueValue(this); - if (this._closeRequested && this._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(this); - ReadableStreamClose(stream); - } - else { - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - readRequest._chunkSteps(chunk); + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + const s2kType = bytes[i++]; + this.s2k = newS2KFromType(s2kType); + i += this.s2k.read(bytes.subarray(i, bytes.length)); + + if (this.s2k.type === 'gnu-dummy') { + return; } - else { - ReadableStreamAddReadRequest(stream, readRequest); - ReadableStreamDefaultControllerCallPullIfNeeded(this); + } else if (this.s2kUsage) { + this.symmetric = this.s2kUsage; + } + + + if (this.s2kUsage) { + // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5). + // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format). + // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always + // fail if the key was parsed according to the wrong format, since the keys are processed differently. + // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag. + this.isLegacyAEAD = this.s2kUsage === 253 && ( + this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy)); + // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV) + // of the same length as the cipher's block size. + // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the + // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm. + // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero + if (this.s2kUsage !== 253 || this.isLegacyAEAD) { + this.iv = bytes.subarray( + i, + i + mod$1.getCipherParams(this.symmetric).blockSize + ); + this.usedModernAEAD = false; + } else { + // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted), + // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which + // is used as the nonce for the AEAD algorithm. + this.iv = bytes.subarray( + i, + i + mod$1.getAEADMode(this.aead).ivLength + ); + // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation. + this.usedModernAEAD = true; } + + i += this.iv.length; + } + } catch (e) { + // if the s2k is unsupported, we still want to support encrypting and verifying with the given key + if (!this.s2kUsage) throw e; // always throw for decrypted keys + this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); + this.isEncrypted = true; } -} -Object.defineProperties(ReadableStreamDefaultController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultController', - configurable: true - }); -} -// Abstract operations for the ReadableStreamDefaultController. -function IsReadableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { - return false; - } - return true; -} -function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; + + // - Only for a version 5 packet, a four-octet scalar octet count for + // the following key material. + if (this.version === 5) { + i += 4; } - controller._pulling = true; - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); + + // - Plain or encrypted multiprecision integers comprising the secret + // key data. These algorithm-specific fields are as described + // below. + this.keyMaterial = bytes.subarray(i); + this.isEncrypted = !!this.s2kUsage; + + if (!this.isEncrypted) { + let cleartext; + if (this.version === 6) { + cleartext = this.keyMaterial; + } else { + cleartext = this.keyMaterial.subarray(0, -2); + if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { + throw new Error('Key checksum mismatch'); } - }, e => { - ReadableStreamDefaultControllerError(controller, e); - }); -} -function ReadableStreamDefaultControllerShouldCallPull(controller) { - const stream = controller._controlledReadableStream; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return false; - } - if (!controller._started) { - return false; - } - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; - } - return false; -} -function ReadableStreamDefaultControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. -function ReadableStreamDefaultControllerClose(controller) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; - } - const stream = controller._controlledReadableStream; - controller._closeRequested = true; - if (controller._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamClose(stream); + } + try { + const { read, privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + if (read < cleartext.length) { + throw new Error('Error reading MPIs'); + } + this.privateParams = privateParams; + } catch (err) { + if (err instanceof UnsupportedError) throw err; + // avoid throwing potentially sensitive errors + throw new Error('Error reading MPIs'); + } } -} -function ReadableStreamDefaultControllerEnqueue(controller, chunk) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; + } + + /** + * Creates an OpenPGP key packet for the given key. + * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. + */ + write() { + const serializedPublicKey = this.writePublicKey(); + if (this.unparseableKeyMaterial) { + return util.concatUint8Array([ + serializedPublicKey, + this.unparseableKeyMaterial + ]); } - const stream = controller._controlledReadableStream; - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - ReadableStreamFulfillReadRequest(stream, chunk, false); + + const arr = [serializedPublicKey]; + arr.push(new Uint8Array([this.s2kUsage])); + + const optionalFieldsArr = []; + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one- octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + optionalFieldsArr.push(this.symmetric); + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + optionalFieldsArr.push(this.aead); + } + + const s2k = this.s2k.write(); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + optionalFieldsArr.push(s2k.length); + } + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + optionalFieldsArr.push(...s2k); } - else { - let chunkSize; - try { - chunkSize = controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - ReadableStreamDefaultControllerError(controller, chunkSizeE); - throw chunkSizeE; - } - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - ReadableStreamDefaultControllerError(controller, enqueueE); - throw enqueueE; - } + + // - [Optional] If secret data is encrypted (string-to-key usage octet + // not zero), an Initial Vector (IV) of the same length as the + // cipher's block size. + if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { + optionalFieldsArr.push(...this.iv); } - ReadableStreamDefaultControllerCallPullIfNeeded(controller); -} -function ReadableStreamDefaultControllerError(controller, e) { - const stream = controller._controlledReadableStream; - if (stream._state !== 'readable') { - return; + + if (this.version === 5 || (this.version === 6 && this.s2kUsage)) { + arr.push(new Uint8Array([optionalFieldsArr.length])); } - ResetQueue(controller); - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableStreamDefaultControllerGetDesiredSize(controller) { - const state = controller._controlledReadableStream._state; - if (state === 'errored') { - return null; + arr.push(new Uint8Array(optionalFieldsArr)); + + if (!this.isDummy()) { + if (!this.s2kUsage) { + this.keyMaterial = mod$1.serializeParams(this.algorithm, this.privateParams); + } + + if (this.version === 5) { + arr.push(util.writeNumber(this.keyMaterial.length, 4)); + } + arr.push(this.keyMaterial); + + if (!this.s2kUsage && this.version !== 6) { + arr.push(util.writeChecksum(this.keyMaterial)); + } } - if (state === 'closed') { - return 0; + + return util.concatUint8Array(arr); + } + + /** + * Check whether secret-key data is available in decrypted form. + * Returns false for gnu-dummy keys and null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return this.isEncrypted === false; + } + + /** + * Check whether the key includes secret key material. + * Some secret keys do not include it, and can thus only be used + * for public-key operations (encryption and verification). + * Such keys are: + * - GNU-dummy keys, where the secret material has been stripped away + * - encrypted keys with unsupported S2K or cipher + */ + isMissingSecretKeyMaterial() { + return this.unparseableKeyMaterial !== undefined || this.isDummy(); + } + + /** + * Check whether this is a gnu-dummy key + * @returns {Boolean} + */ + isDummy() { + return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + } + + /** + * Remove private key material, converting the key to a dummy one. + * The resulting key cannot be used for signing/decrypting but can still verify signatures. + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + makeDummy(config$1 = config) { + if (this.isDummy()) { + return; } - return controller._strategyHWM - controller._queueTotalSize; -} -// This is used in the implementation of TransformStream. -function ReadableStreamDefaultControllerHasBackpressure(controller) { - if (ReadableStreamDefaultControllerShouldCallPull(controller)) { - return false; + if (this.isDecrypted()) { + this.clearPrivateParams(); } - return true; -} -function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { - const state = controller._controlledReadableStream._state; - if (!controller._closeRequested && state === 'readable') { - return true; + delete this.unparseableKeyMaterial; + this.isEncrypted = null; + this.keyMaterial = null; + this.s2k = newS2KFromType(enums.s2k.gnu, config$1); + this.s2k.algorithm = 0; + this.s2k.c = 0; + this.s2k.type = 'gnu-dummy'; + this.s2kUsage = 254; + this.symmetric = enums.symmetric.aes256; + this.isLegacyAEAD = null; + this.usedModernAEAD = null; + } + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param {String} passphrase + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + if (this.isDummy()) { + return; } - return false; -} -function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledReadableStream = stream; - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._closeRequested = false; - controller._pullAgain = false; - controller._pulling = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - }, r => { - ReadableStreamDefaultControllerError(controller, r); - }); -} -function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { - const controller = Object.create(ReadableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSource.start !== undefined) { - startAlgorithm = () => underlyingSource.start(controller); - } - if (underlyingSource.pull !== undefined) { - pullAlgorithm = () => underlyingSource.pull(controller); - } - if (underlyingSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingSource.cancel(reason); - } - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); -} -// Helper functions for the ReadableStreamDefaultController. -function defaultControllerBrandCheckException$1(name) { - return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); -} - -function ReadableStreamTee(stream, cloneForBranch2) { - const reader = AcquireReadableStreamDefaultReader(stream); - let reading = false; - let canceled1 = false; - let canceled2 = false; - let reason1; - let reason2; - let branch1; - let branch2; - let resolveCancelPromise; - const cancelPromise = newPromise(resolve => { - resolveCancelPromise = resolve; - }); - function pullAlgorithm() { - if (reading) { - return promiseResolvedWith(undefined); - } - reading = true; - const readRequest = { - _chunkSteps: value => { - // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using - // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let - // successful synchronously-available reads get ahead of asynchronously-available errors. - queueMicrotask(() => { - reading = false; - const value1 = value; - const value2 = value; - // There is no way to access the cloning code right now in the reference implementation. - // If we add one then we'll need an implementation for serializable objects. - // if (!canceled2 && cloneForBranch2) { - // value2 = StructuredDeserialize(StructuredSerialize(value2)); - // } - if (!canceled1) { - ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1); - } - if (!canceled2) { - ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2); - } - }); - }, - _closeSteps: () => { - reading = false; - if (!canceled1) { - ReadableStreamDefaultControllerClose(branch1._readableStreamController); - } - if (!canceled2) { - ReadableStreamDefaultControllerClose(branch2._readableStreamController); - } - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }, - _errorSteps: () => { - reading = false; - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promiseResolvedWith(undefined); - } - function cancel1Algorithm(reason) { - canceled1 = true; - reason1 = reason; - if (canceled2) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function cancel2Algorithm(reason) { - canceled2 = true; - reason2 = reason; - if (canceled1) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function startAlgorithm() { - // do nothing - } - branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); - branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); - uponRejection(reader._closedPromise, (r) => { - ReadableStreamDefaultControllerError(branch1._readableStreamController, r); - ReadableStreamDefaultControllerError(branch2._readableStreamController, r); - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }); - return [branch1, branch2]; -} -function convertUnderlyingDefaultOrByteSource(source, context) { - assertDictionary(source, context); - const original = source; - const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; - const cancel = original === null || original === void 0 ? void 0 : original.cancel; - const pull = original === null || original === void 0 ? void 0 : original.pull; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - return { - autoAllocateChunkSize: autoAllocateChunkSize === undefined ? - undefined : - convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), - cancel: cancel === undefined ? - undefined : - convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), - pull: pull === undefined ? - undefined : - convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), - start: start === undefined ? - undefined : - convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), - type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) - }; -} -function convertUnderlyingSourceCancelCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSourcePullCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertUnderlyingSourceStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertReadableStreamType(type, context) { - type = `${type}`; - if (type !== 'bytes') { - throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + if (!this.isDecrypted()) { + throw new Error('Key packet is already encrypted'); } - return type; -} -function convertReaderOptions(options, context) { - assertDictionary(options, context); - const mode = options === null || options === void 0 ? void 0 : options.mode; - return { - mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) - }; -} -function convertReadableStreamReaderMode(mode, context) { - mode = `${mode}`; - if (mode !== 'byob') { - throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + if (!passphrase) { + throw new Error('A non-empty passphrase is required for key encryption.'); } - return mode; -} -function convertIteratorOptions(options, context) { - assertDictionary(options, context); - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - return { preventCancel: Boolean(preventCancel) }; -} + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + const cleartext = mod$1.serializeParams(this.algorithm, this.privateParams); + this.symmetric = enums.symmetric.aes256; -function convertPipeOptions(options, context) { - assertDictionary(options, context); - const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; - const signal = options === null || options === void 0 ? void 0 : options.signal; - if (signal !== undefined) { - assertAbortSignal(signal, `${context} has member 'signal' that`); - } - return { - preventAbort: Boolean(preventAbort), - preventCancel: Boolean(preventCancel), - preventClose: Boolean(preventClose), - signal - }; -} -function assertAbortSignal(signal, context) { - if (!isAbortSignal(signal)) { - throw new TypeError(`${context} is not an AbortSignal.`); - } -} + const { blockSize } = mod$1.getCipherParams(this.symmetric); -function convertReadableWritablePair(pair, context) { - assertDictionary(pair, context); - const readable = pair === null || pair === void 0 ? void 0 : pair.readable; - assertRequiredField(readable, 'readable', 'ReadableWritablePair'); - assertReadableStream(readable, `${context} has member 'readable' that`); - const writable = pair === null || pair === void 0 ? void 0 : pair.writable; - assertRequiredField(writable, 'writable', 'ReadableWritablePair'); - assertWritableStream(writable, `${context} has member 'writable' that`); - return { readable, writable }; -} + if (config$1.aeadProtect) { + this.s2kUsage = 253; + this.aead = config$1.preferredAEADAlgorithm; + const mode = mod$1.getAEADMode(this.aead); + this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead. + this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material -/** - * A readable stream represents a source of data, from which you can read. - * - * @public - */ -class ReadableStream$1 { - constructor(rawUnderlyingSource = {}, rawStrategy = {}) { - if (rawUnderlyingSource === undefined) { - rawUnderlyingSource = null; - } - else { - assertObject(rawUnderlyingSource, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); - InitializeReadableStream(this); - if (underlyingSource.type === 'bytes') { - if (strategy.size !== undefined) { - throw new RangeError('The strategy for a byte stream cannot have a size function'); - } - const highWaterMark = ExtractHighWaterMark(strategy, 0); - SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); - } - else { - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); - } - } - /** - * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. - */ - get locked() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('locked'); - } - return IsReadableStreamLocked(this); + const serializedPacketTag = writeTag(this.constructor.tag); + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + + const modeInstance = await mode(this.symmetric, key); + this.iv = this.isLegacyAEAD ? mod$1.random.getRandomBytes(blockSize) : mod$1.random.getRandomBytes(mode.ivLength); + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + + this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData); + } else { + this.s2kUsage = 254; + this.usedModernAEAD = false; + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric); + this.iv = mod$1.random.getRandomBytes(blockSize); + this.keyMaterial = await mod$1.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + cleartext, + await mod$1.hash.sha1(cleartext, config$1) + ]), this.iv, config$1); } - /** - * Cancels the stream, signaling a loss of interest in the stream by a consumer. - * - * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} - * method, which might or might not use it. - */ - cancel(reason = undefined) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('cancel')); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); - } - return ReadableStreamCancel(this, reason); + } + + /** + * Decrypts the private key params which are needed to use the key. + * Successful decryption does not imply key integrity, call validate() to confirm that. + * {@link SecretKeyPacket.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param {String} passphrase - The passphrase for this private key as string + * @throws {Error} if the key is already decrypted, or if decryption was not successful + * @async + */ + async decrypt(passphrase) { + if (this.isDummy()) { + return false; } - getReader(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('getReader'); - } - const options = convertReaderOptions(rawOptions, 'First parameter'); - if (options.mode === undefined) { - return AcquireReadableStreamDefaultReader(this); - } - return AcquireReadableStreamBYOBReader(this); + + if (this.unparseableKeyMaterial) { + throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); } - pipeThrough(rawTransform, rawOptions = {}) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('pipeThrough'); - } - assertRequiredArgument(rawTransform, 1, 'pipeThrough'); - const transform = convertReadableWritablePair(rawTransform, 'First parameter'); - const options = convertPipeOptions(rawOptions, 'Second parameter'); - if (IsReadableStreamLocked(this)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); - } - if (IsWritableStreamLocked(transform.writable)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); - } - const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - setPromiseIsHandledToTrue(promise); - return transform.readable; + + if (this.isDecrypted()) { + throw new Error('Key packet is already decrypted.'); } - pipeTo(destination, rawOptions = {}) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); - } - if (destination === undefined) { - return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); - } - if (!IsWritableStream(destination)) { - return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); - } - let options; - try { - options = convertPipeOptions(rawOptions, 'Second parameter'); - } - catch (e) { - return promiseRejectedWith(e); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); - } - if (IsWritableStreamLocked(destination)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); - } - return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + + let key; + const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only + if (this.s2kUsage === 254 || this.s2kUsage === 253) { + key = await produceEncryptionKey( + this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + } else if (this.s2kUsage === 255) { + throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); + } else { + throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); } - /** - * Tees this readable stream, returning a two-element array containing the two resulting branches as - * new {@link ReadableStream} instances. - * - * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. - * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be - * propagated to the stream's underlying source. - * - * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, - * this could allow interference between the two branches. - */ - tee() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('tee'); + + let cleartext; + if (this.s2kUsage === 253) { + const mode = mod$1.getAEADMode(this.aead); + const modeInstance = await mode(this.symmetric, key); + try { + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData); + } catch (err) { + if (err.message === 'Authentication tag mismatch') { + throw new Error('Incorrect key passphrase: ' + err.message); } - const branches = ReadableStreamTee(this); - return CreateArrayFromList(branches); + throw err; + } + } else { + const cleartextWithHash = await mod$1.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + + cleartext = cleartextWithHash.subarray(0, -20); + const hash = await mod$1.hash.sha1(cleartext); + + if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { + throw new Error('Incorrect key passphrase'); + } } - values(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('values'); - } - const options = convertIteratorOptions(rawOptions, 'First parameter'); - return AcquireReadableStreamAsyncIterator(this, options.preventCancel); - } -} -Object.defineProperties(ReadableStream$1.prototype, { - cancel: { enumerable: true }, - getReader: { enumerable: true }, - pipeThrough: { enumerable: true }, - pipeTo: { enumerable: true }, - tee: { enumerable: true }, - values: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStream', - configurable: true - }); -} -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, { - value: ReadableStream$1.prototype.values, - writable: true, - configurable: true - }); -} -// Abstract operations for the ReadableStream. -// Throws if and only if startAlgorithm throws. -function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(ReadableStream$1.prototype); - InitializeReadableStream(stream); - const controller = Object.create(ReadableStreamDefaultController.prototype); - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeReadableStream(stream) { - stream._state = 'readable'; - stream._reader = undefined; - stream._storedError = undefined; - stream._disturbed = false; -} -function IsReadableStream(x) { - if (!typeIsObject(x)) { - return false; + + try { + const { privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + this.privateParams = privateParams; + } catch (err) { + throw new Error('Error reading MPIs'); } - if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { - return false; + this.isEncrypted = false; + this.keyMaterial = null; + this.s2kUsage = 0; + this.aead = null; + this.symmetric = null; + this.isLegacyAEAD = null; + } + + /** + * Checks that the key parameters are consistent + * @throws {Error} if validation was not successful + * @async + */ + async validate() { + if (this.isDummy()) { + return; } - return true; -} -function IsReadableStreamLocked(stream) { - if (stream._reader === undefined) { - return false; + + if (!this.isDecrypted()) { + throw new Error('Key is not decrypted'); } - return true; -} -// ReadableStream API exposed for controllers. -function ReadableStreamCancel(stream, reason) { - stream._disturbed = true; - if (stream._state === 'closed') { - return promiseResolvedWith(undefined); + + if (this.usedModernAEAD) { + // key integrity confirmed by successful AEAD decryption + return; } - if (stream._state === 'errored') { - return promiseRejectedWith(stream._storedError); + + let validParams; + try { + // this can throw if some parameters are undefined + validParams = await mod$1.validateParams(this.algorithm, this.publicParams, this.privateParams); + } catch (_) { + validParams = false; } - ReadableStreamClose(stream); - const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); - return transformPromiseWith(sourceCancelPromise, noop); -} -function ReadableStreamClose(stream) { - stream._state = 'closed'; - const reader = stream._reader; - if (reader === undefined) { - return; + if (!validParams) { + throw new Error('Key is invalid'); } - defaultReaderClosedPromiseResolve(reader); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._closeSteps(); - }); - reader._readRequests = new SimpleQueue(); + } + + async generate(bits, curve) { + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if (this.version === 6 && ( + (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) || + this.algorithm === enums.publicKey.eddsaLegacy + )) { + throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`); + } + const { privateParams, publicParams } = await mod$1.generateParams(this.algorithm, bits, curve); + this.privateParams = privateParams; + this.publicParams = publicParams; + this.isEncrypted = false; + } + + /** + * Clear private key parameters + */ + clearPrivateParams() { + if (this.isMissingSecretKeyMaterial()) { + return; } + + Object.keys(this.privateParams).forEach(name => { + const param = this.privateParams[name]; + param.fill(0); + delete this.privateParams[name]; + }); + this.privateParams = null; + this.isEncrypted = true; + } } -function ReadableStreamError(stream, e) { - stream._state = 'errored'; - stream._storedError = e; - const reader = stream._reader; - if (reader === undefined) { - return; + +/** + * Derive encryption key + * @param {Number} keyVersion - key derivation differs for v5 keys + * @param {module:type/s2k} s2k + * @param {String} passphrase + * @param {module:enums.symmetric} cipherAlgo + * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5) + * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5) + * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only) + * @returns encryption key + */ +async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) { + if (s2k.type === 'argon2' && !aeadMode) { + throw new Error('Using Argon2 S2K without AEAD is not allowed'); + } + if (s2k.type === 'simple' && keyVersion === 6) { + throw new Error('Using Simple S2K with version 6 keys is not allowed'); + } + const { keySize } = mod$1.getCipherParams(cipherAlgo); + const derivedKey = await s2k.produceKey(passphrase, keySize); + if (!aeadMode || keyVersion === 5 || isLegacyAEAD) { + return derivedKey; + } + const info = util.concatUint8Array([ + serializedPacketTag, + new Uint8Array([keyVersion, cipherAlgo, aeadMode]) + ]); + return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize); +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the User ID Packet (Tag 13) + * + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ +class UserIDPacket { + static get tag() { + return enums.packet.userID; + } + + constructor() { + /** A string containing the user id. Usually in the form + * John Doe + * @type {String} + */ + this.userID = ''; + + this.name = ''; + this.email = ''; + this.comment = ''; + } + + /** + * Create UserIDPacket instance from object + * @param {Object} userID - Object specifying userID name, email and comment + * @returns {UserIDPacket} + * @static + */ + static fromObject(userID) { + if (util.isString(userID) || + (userID.name && !util.isString(userID.name)) || + (userID.email && !util.isEmailAddress(userID.email)) || + (userID.comment && !util.isString(userID.comment))) { + throw new Error('Invalid user ID format'); } - defaultReaderClosedPromiseReject(reader, e); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._errorSteps(e); - }); - reader._readRequests = new SimpleQueue(); + const packet = new UserIDPacket(); + Object.assign(packet, userID); + const components = []; + if (packet.name) components.push(packet.name); + if (packet.comment) components.push(`(${packet.comment})`); + if (packet.email) components.push(`<${packet.email}>`); + packet.userID = components.join(' '); + return packet; + } + + /** + * Parsing function for a user id packet (tag 13). + * @param {Uint8Array} input - Payload of a tag 13 packet + */ + read(bytes, config$1 = config) { + const userID = util.decodeUTF8(bytes); + if (userID.length > config$1.maxUserIDLength) { + throw new Error('User ID string is too long'); } - else { - reader._readIntoRequests.forEach(readIntoRequest => { - readIntoRequest._errorSteps(e); - }); - reader._readIntoRequests = new SimpleQueue(); + + /** + * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1, + * as well comments placed between the name (if present) and the bracketed email address: + * - name (comment) + * - email + * In the first case, the `email` is the only required part, and it must contain the `@` symbol. + * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, + * since they interfere with `comment` parsing. + */ + const re = /^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/; + const matches = re.exec(userID); + if (matches !== null) { + const { name, comment, email } = matches.groups; + this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace + this.name = name?.trim() || ''; + this.email = email.substring(1, email.length - 1); // remove brackets + } else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace + this.email = userID; } -} -// Helper functions for the ReadableStream. -function streamBrandCheckException$1(name) { - return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); -} -function convertQueuingStrategyInit(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); - return { - highWaterMark: convertUnrestrictedDouble(highWaterMark) - }; + this.userID = userID; + } + + /** + * Creates a binary representation of the user id packet + * @returns {Uint8Array} Binary representation. + */ + write() { + return util.encodeUTF8(this.userID); + } + + equals(otherUserID) { + return otherUserID && otherUserID.userID === this.userID; + } } -const byteLengthSizeFunction = function size(chunk) { - return chunk.byteLength; -}; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * A queuing strategy that counts the number of bytes in each chunk. - * - * @public + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + * @extends SecretKeyPacket */ -class ByteLengthQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('highWaterMark'); - } - return this._byteLengthQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by returning the value of its `byteLength` property. - */ - get size() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('size'); - } - return byteLengthSizeFunction; - } -} -Object.defineProperties(ByteLengthQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'ByteLengthQueuingStrategy', - configurable: true - }); -} -// Helper functions for the ByteLengthQueuingStrategy. -function byteLengthBrandCheckException(name) { - return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); -} -function IsByteLengthQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { - return false; - } - return true; +class SecretSubkeyPacket extends SecretKeyPacket { + static get tag() { + return enums.packet.secretSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); + } } -const countSizeFunction = function size() { - return 1; -}; /** - * A queuing strategy that counts the number of chunks. + * Implementation of the Trust Packet (Tag 12) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. * - * @public + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. */ -class CountQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'CountQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._countQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('highWaterMark'); - } - return this._countQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by always returning 1. - * This ensures that the total queue size is a count of the number of chunks in the queue. - */ - get size() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('size'); - } - return countSizeFunction; - } -} -Object.defineProperties(CountQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'CountQueuingStrategy', - configurable: true - }); -} -// Helper functions for the CountQueuingStrategy. -function countBrandCheckException(name) { - return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); -} -function IsCountQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { - return false; - } - return true; -} +class TrustPacket { + static get tag() { + return enums.packet.trust; + } -function convertTransformer(original, context) { - assertDictionary(original, context); - const flush = original === null || original === void 0 ? void 0 : original.flush; - const readableType = original === null || original === void 0 ? void 0 : original.readableType; - const start = original === null || original === void 0 ? void 0 : original.start; - const transform = original === null || original === void 0 ? void 0 : original.transform; - const writableType = original === null || original === void 0 ? void 0 : original.writableType; - return { - flush: flush === undefined ? - undefined : - convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), - readableType, - start: start === undefined ? - undefined : - convertTransformerStartCallback(start, original, `${context} has member 'start' that`), - transform: transform === undefined ? - undefined : - convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), - writableType - }; -} -function convertTransformerFlushCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertTransformerStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertTransformerTransformCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + */ + read() { + throw new UnsupportedError('Trust packets are not supported'); + } + + write() { + throw new UnsupportedError('Trust packets are not supported'); + } } -// Class TransformStream +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2022 Proton AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, - * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. - * In a manner specific to the transform stream in question, writes to the writable side result in new data being - * made available for reading from the readable side. + * Implementation of the Padding Packet * - * @public + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}: + * Padding Packet */ -class TransformStream$1 { - constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { - if (rawTransformer === undefined) { - rawTransformer = null; - } - const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); - const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); - const transformer = convertTransformer(rawTransformer, 'First parameter'); - if (transformer.readableType !== undefined) { - throw new RangeError('Invalid readableType specified'); - } - if (transformer.writableType !== undefined) { - throw new RangeError('Invalid writableType specified'); - } - const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); - const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); - const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); - const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); - let startPromise_resolve; - const startPromise = newPromise(resolve => { - startPromise_resolve = resolve; - }); - InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); - if (transformer.start !== undefined) { - startPromise_resolve(transformer.start(this._transformStreamController)); - } - else { - startPromise_resolve(undefined); - } - } - /** - * The readable side of the transform stream. - */ - get readable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('readable'); - } - return this._readable; - } - /** - * The writable side of the transform stream. - */ - get writable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('writable'); - } - return this._writable; - } -} -Object.defineProperties(TransformStream$1.prototype, { - readable: { enumerable: true }, - writable: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStream', - configurable: true - }); -} -function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { - function startAlgorithm() { - return startPromise; - } - function writeAlgorithm(chunk) { - return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); - } - function abortAlgorithm(reason) { - return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); - } - function closeAlgorithm() { - return TransformStreamDefaultSinkCloseAlgorithm(stream); - } - stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); - function pullAlgorithm() { - return TransformStreamDefaultSourcePullAlgorithm(stream); - } - function cancelAlgorithm(reason) { - TransformStreamErrorWritableAndUnblockWrite(stream, reason); - return promiseResolvedWith(undefined); - } - stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. - stream._backpressure = undefined; - stream._backpressureChangePromise = undefined; - stream._backpressureChangePromise_resolve = undefined; - TransformStreamSetBackpressure(stream, true); - stream._transformStreamController = undefined; -} -function IsTransformStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { - return false; - } - return true; -} -// This is a no-op if both sides are already errored. -function TransformStreamError(stream, e) { - ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); - TransformStreamErrorWritableAndUnblockWrite(stream, e); -} -function TransformStreamErrorWritableAndUnblockWrite(stream, e) { - TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); - WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); - if (stream._backpressure) { - // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() - // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time - // _backpressure is set. - TransformStreamSetBackpressure(stream, false); - } -} -function TransformStreamSetBackpressure(stream, backpressure) { - // Passes also when called during construction. - if (stream._backpressureChangePromise !== undefined) { - stream._backpressureChangePromise_resolve(); - } - stream._backpressureChangePromise = newPromise(resolve => { - stream._backpressureChangePromise_resolve = resolve; - }); - stream._backpressure = backpressure; +class PaddingPacket { + static get tag() { + return enums.packet.padding; + } + + constructor() { + this.padding = null; + } + + /** + * Read a padding packet + * @param {Uint8Array | ReadableStream} bytes + */ + read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars + // Padding packets are ignored, so this function is never called. + } + + /** + * Write the padding packet + * @returns {Uint8Array} The padding packet. + */ + write() { + return this.padding; + } + + /** + * Create random padding. + * @param {Number} length - The length of padding to be generated. + * @throws {Error} if padding generation was not successful + * @async + */ + async createPadding(length) { + this.padding = await mod$1.random.getRandomBytes(length); + } } -// Class TransformStreamDefaultController + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Signature can contain the following packets +const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + /** - * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. - * - * @public + * Class that represents an OpenPGP signature. */ -class TransformStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. - */ - get desiredSize() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('desiredSize'); - } - const readableController = this._controlledTransformStream._readable._readableStreamController; - return ReadableStreamDefaultControllerGetDesiredSize(readableController); - } - enqueue(chunk = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('enqueue'); - } - TransformStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors both the readable side and the writable side of the controlled transform stream, making all future - * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. - */ - error(reason = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('error'); - } - TransformStreamDefaultControllerError(this, reason); - } - /** - * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the - * transformer only needs to consume a portion of the chunks written to the writable side. - */ - terminate() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('terminate'); - } - TransformStreamDefaultControllerTerminate(this); - } -} -Object.defineProperties(TransformStreamDefaultController.prototype, { - enqueue: { enumerable: true }, - error: { enumerable: true }, - terminate: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStreamDefaultController', - configurable: true - }); -} -// Transform Stream Default Controller Abstract Operations -function IsTransformStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { - return false; - } - return true; -} -function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { - controller._controlledTransformStream = stream; - stream._transformStreamController = controller; - controller._transformAlgorithm = transformAlgorithm; - controller._flushAlgorithm = flushAlgorithm; -} -function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { - const controller = Object.create(TransformStreamDefaultController.prototype); - let transformAlgorithm = (chunk) => { - try { - TransformStreamDefaultControllerEnqueue(controller, chunk); - return promiseResolvedWith(undefined); - } - catch (transformResultE) { - return promiseRejectedWith(transformResultE); - } - }; - let flushAlgorithm = () => promiseResolvedWith(undefined); - if (transformer.transform !== undefined) { - transformAlgorithm = chunk => transformer.transform(chunk, controller); - } - if (transformer.flush !== undefined) { - flushAlgorithm = () => transformer.flush(controller); - } - SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); -} -function TransformStreamDefaultControllerClearAlgorithms(controller) { - controller._transformAlgorithm = undefined; - controller._flushAlgorithm = undefined; -} -function TransformStreamDefaultControllerEnqueue(controller, chunk) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { - throw new TypeError('Readable side is not in a state that permits enqueue'); - } - // We throttle transform invocations based on the backpressure of the ReadableStream, but we still - // accept TransformStreamDefaultControllerEnqueue() calls. - try { - ReadableStreamDefaultControllerEnqueue(readableController, chunk); - } - catch (e) { - // This happens when readableStrategy.size() throws. - TransformStreamErrorWritableAndUnblockWrite(stream, e); - throw stream._readable._storedError; - } - const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); - if (backpressure !== stream._backpressure) { - TransformStreamSetBackpressure(stream, true); - } -} -function TransformStreamDefaultControllerError(controller, e) { - TransformStreamError(controller._controlledTransformStream, e); -} -function TransformStreamDefaultControllerPerformTransform(controller, chunk) { - const transformPromise = controller._transformAlgorithm(chunk); - return transformPromiseWith(transformPromise, undefined, r => { - TransformStreamError(controller._controlledTransformStream, r); - throw r; - }); -} -function TransformStreamDefaultControllerTerminate(controller) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - ReadableStreamDefaultControllerClose(readableController); - const error = new TypeError('TransformStream terminated'); - TransformStreamErrorWritableAndUnblockWrite(stream, error); -} -// TransformStreamDefaultSink Algorithms -function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { - const controller = stream._transformStreamController; - if (stream._backpressure) { - const backpressureChangePromise = stream._backpressureChangePromise; - return transformPromiseWith(backpressureChangePromise, () => { - const writable = stream._writable; - const state = writable._state; - if (state === 'erroring') { - throw writable._storedError; - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - }); - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); -} -function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { - // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already - // errored. - TransformStreamError(stream, reason); - return promiseResolvedWith(undefined); -} -function TransformStreamDefaultSinkCloseAlgorithm(stream) { - // stream._readable cannot change after construction, so caching it across a call to user code is safe. - const readable = stream._readable; - const controller = stream._transformStreamController; - const flushPromise = controller._flushAlgorithm(); - TransformStreamDefaultControllerClearAlgorithms(controller); - // Return a promise that is fulfilled with undefined on success. - return transformPromiseWith(flushPromise, () => { - if (readable._state === 'errored') { - throw readable._storedError; - } - ReadableStreamDefaultControllerClose(readable._readableStreamController); - }, r => { - TransformStreamError(stream, r); - throw readable._storedError; - }); -} -// TransformStreamDefaultSource Algorithms -function TransformStreamDefaultSourcePullAlgorithm(stream) { - // Invariant. Enforced by the promises returned by start() and pull(). - TransformStreamSetBackpressure(stream, false); - // Prevent the next pull() call until there is backpressure. - return stream._backpressureChangePromise; -} -// Helper functions for the TransformStreamDefaultController. -function defaultControllerBrandCheckException(name) { - return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); -} -// Helper functions for the TransformStream. -function streamBrandCheckException(name) { - return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); -} +class Signature { + /** + * @param {PacketList} packetlist - The signature packets + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } -var ponyfill_es6 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, - CountQueuingStrategy: CountQueuingStrategy, - ReadableByteStreamController: ReadableByteStreamController, - ReadableStream: ReadableStream$1, - ReadableStreamBYOBReader: ReadableStreamBYOBReader, - ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, - ReadableStreamDefaultController: ReadableStreamDefaultController, - ReadableStreamDefaultReader: ReadableStreamDefaultReader, - TransformStream: TransformStream$1, - TransformStreamDefaultController: TransformStreamDefaultController, - WritableStream: WritableStream$1, - WritableStreamDefaultController: WritableStreamDefaultController, - WritableStreamDefaultWriter: WritableStreamDefaultWriter -}); + /** + * Returns binary encoded signature + * @returns {ReadableStream} Binary signature. + */ + write() { + return this.packets.write(); + } -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; + /** + * Returns ASCII armored text of signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1); + } -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + /** + * Returns an array of KeyIDs of all of the issuers who created this signature + * @returns {Array} The Key IDs of the signing keys + */ + getSigningKeyIDs() { + return this.packets.map(packet => packet.issuerKeyID); + } } -function assert$1(test) { - if (!test) { - throw new TypeError('Assertion failed'); +/** + * reads an (optionally armored) OpenPGP signature and returns a signature object + * @param {Object} options + * @param {String} [options.armoredSignature] - Armored signature to be parsed + * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New signature object. + * @async + * @static + */ +async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredSignature || binarySignature; + if (!input) { + throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); + } + if (armoredSignature && !util.isString(armoredSignature)) { + throw new Error('readSignature: options.armoredSignature must be a string'); + } + if (binarySignature && !util.isUint8Array(binarySignature)) { + throw new Error('readSignature: options.binarySignature must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (armoredSignature) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.signature) { + throw new Error('Armored text not of type signature'); } + input = data; + } + const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1); + return new Signature(packetlist); } -function noop$1() { - return; -} -function typeIsObject$1(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} +/** + * @fileoverview Provides helpers methods for key module + * @module key/helper + */ -function isStreamConstructor(ctor) { - if (typeof ctor !== 'function') { - return false; - } - var startCalled = false; - try { - new ctor({ - start: function () { - startCalled = true; - } - }); - } - catch (e) { - // ignore - } - return startCalled; -} -function isReadableStream(readable) { - if (!typeIsObject$1(readable)) { - return false; - } - if (typeof readable.getReader !== 'function') { - return false; - } - return true; -} -function isReadableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isReadableStream(new ctor())) { - return false; - } - return true; -} -function isWritableStream(writable) { - if (!typeIsObject$1(writable)) { - return false; - } - if (typeof writable.getWriter !== 'function') { - return false; - } - return true; -} -function isWritableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isWritableStream(new ctor())) { - return false; - } - return true; -} -function isTransformStream(transform) { - if (!typeIsObject$1(transform)) { - return false; - } - if (!isReadableStream(transform.readable)) { - return false; - } - if (!isWritableStream(transform.writable)) { - return false; - } - return true; -} -function isTransformStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isTransformStream(new ctor())) { - return false; - } - return true; + +async function generateSecretSubkey(options, config) { + const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); + secretSubkeyPacket.packets = null; + secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretSubkeyPacket.generate(options.rsaBits, options.curve); + await secretSubkeyPacket.computeFingerprintAndKeyID(); + return secretSubkeyPacket; } -function supportsByobReader(readable) { - try { - var reader = readable.getReader({ mode: 'byob' }); - reader.releaseLock(); - return true; - } - catch (_a) { - return false; - } + +async function generateSecretKey(options, config) { + const secretKeyPacket = new SecretKeyPacket(options.date, config); + secretKeyPacket.packets = null; + secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); + await secretKeyPacket.computeFingerprintAndKeyID(); + return secretKeyPacket; } -function supportsByteSource(ctor) { + +/** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param {Array} signatures - List of signatures + * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature + * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures, + * `enums.signatures.certGeneric` should be given regardless of the actual trust level) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - full configuration + * @returns {Promise} The latest valid signature. + * @async + */ +async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { + let latestValid; + let exception; + for (let i = signatures.length - 1; i >= 0; i--) { try { - new ctor({ type: 'bytes' }); - return true; - } - catch (_a) { - return false; + if ( + (!latestValid || signatures[i].created >= latestValid.created) + ) { + await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); + latestValid = signatures[i]; + } + } catch (e) { + exception = e; } + } + if (!latestValid) { + throw util.wrapError( + `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` + .replace('certGeneric ', 'self-') + .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), + exception); + } + return latestValid; } -function createReadableStreamWrapper(ctor) { - assert$1(isReadableStreamConstructor(ctor)); - var byteSourceSupported = supportsByteSource(ctor); - return function (readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - type = parseReadableType(type); - if (type === 'bytes' && !byteSourceSupported) { - type = undefined; - } - if (readable.constructor === ctor) { - if (type !== 'bytes' || supportsByobReader(readable)) { - return readable; - } - } - if (type === 'bytes') { - var source = createWrappingReadableSource(readable, { type: type }); - return new ctor(source); - } - else { - var source = createWrappingReadableSource(readable); - return new ctor(source); - } - }; -} -function createWrappingReadableSource(readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - assert$1(isReadableStream(readable)); - assert$1(readable.locked === false); - type = parseReadableType(type); - var source; - if (type === 'bytes') { - source = new WrappingReadableByteStreamSource(readable); - } - else { - source = new WrappingReadableStreamDefaultSource(readable); - } - return source; -} -function parseReadableType(type) { - var typeString = String(type); - if (typeString === 'bytes') { - return typeString; - } - else if (type === undefined) { - return type; - } - else { - throw new RangeError('Invalid type is specified'); - } -} -var AbstractWrappingReadableStreamSource = /** @class */ (function () { - function AbstractWrappingReadableStreamSource(underlyingStream) { - this._underlyingReader = undefined; - this._readerMode = undefined; - this._readableStreamController = undefined; - this._pendingRead = undefined; - this._underlyingStream = underlyingStream; - // always keep a reader attached to detect close/error - this._attachDefaultReader(); - } - AbstractWrappingReadableStreamSource.prototype.start = function (controller) { - this._readableStreamController = controller; - }; - AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) { - assert$1(this._underlyingReader !== undefined); - return this._underlyingReader.cancel(reason); - }; - AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () { - if (this._readerMode === "default" /* DEFAULT */) { - return; - } - this._detachReader(); - var reader = this._underlyingStream.getReader(); - this._readerMode = "default" /* DEFAULT */; - this._attachReader(reader); - }; - AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) { - var _this = this; - assert$1(this._underlyingReader === undefined); - this._underlyingReader = reader; - var closed = this._underlyingReader.closed; - if (!closed) { - return; - } - closed - .then(function () { return _this._finishPendingRead(); }) - .then(function () { - if (reader === _this._underlyingReader) { - _this._readableStreamController.close(); - } - }, function (reason) { - if (reader === _this._underlyingReader) { - _this._readableStreamController.error(reason); - } - }) - .catch(noop$1); - }; - AbstractWrappingReadableStreamSource.prototype._detachReader = function () { - if (this._underlyingReader === undefined) { - return; - } - this._underlyingReader.releaseLock(); - this._underlyingReader = undefined; - this._readerMode = undefined; - }; - AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () { - var _this = this; - this._attachDefaultReader(); - // TODO Backpressure? - var read = this._underlyingReader.read() - .then(function (result) { - var controller = _this._readableStreamController; - if (result.done) { - _this._tryClose(); - } - else { - controller.enqueue(result.value); - } - }); - this._setPendingRead(read); - return read; - }; - AbstractWrappingReadableStreamSource.prototype._tryClose = function () { - try { - this._readableStreamController.close(); - } - catch (_a) { - // already errored or closed - } - }; - AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) { - var _this = this; - var pendingRead; - var finishRead = function () { - if (_this._pendingRead === pendingRead) { - _this._pendingRead = undefined; - } - }; - this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead); - }; - AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () { - var _this = this; - if (!this._pendingRead) { - return undefined; - } - var afterRead = function () { return _this._finishPendingRead(); }; - return this._pendingRead.then(afterRead, afterRead); - }; - return AbstractWrappingReadableStreamSource; -}()); -var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) { - __extends(WrappingReadableStreamDefaultSource, _super); - function WrappingReadableStreamDefaultSource() { - return _super !== null && _super.apply(this, arguments) || this; - } - WrappingReadableStreamDefaultSource.prototype.pull = function () { - return this._pullWithDefaultReader(); - }; - return WrappingReadableStreamDefaultSource; -}(AbstractWrappingReadableStreamSource)); -function toUint8Array(view) { - return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); -} -function copyArrayBufferView(from, to) { - var fromArray = toUint8Array(from); - var toArray = toUint8Array(to); - toArray.set(fromArray, 0); -} -var WrappingReadableByteStreamSource = /** @class */ (function (_super) { - __extends(WrappingReadableByteStreamSource, _super); - function WrappingReadableByteStreamSource(underlyingStream) { - var _this = this; - var supportsByob = supportsByobReader(underlyingStream); - _this = _super.call(this, underlyingStream) || this; - _this._supportsByob = supportsByob; - return _this; - } - Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", { - get: function () { - return 'bytes'; - }, - enumerable: false, - configurable: true - }); - WrappingReadableByteStreamSource.prototype._attachByobReader = function () { - if (this._readerMode === "byob" /* BYOB */) { - return; - } - assert$1(this._supportsByob); - this._detachReader(); - var reader = this._underlyingStream.getReader({ mode: 'byob' }); - this._readerMode = "byob" /* BYOB */; - this._attachReader(reader); - }; - WrappingReadableByteStreamSource.prototype.pull = function () { - if (this._supportsByob) { - var byobRequest = this._readableStreamController.byobRequest; - if (byobRequest) { - return this._pullWithByobRequest(byobRequest); - } - } - return this._pullWithDefaultReader(); - }; - WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) { - var _this = this; - this._attachByobReader(); - // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly - // create a separate buffer to read into, then copy that to byobRequest.view - var buffer = new Uint8Array(byobRequest.view.byteLength); - // TODO Backpressure? - var read = this._underlyingReader.read(buffer) - .then(function (result) { - _this._readableStreamController; - if (result.done) { - _this._tryClose(); - byobRequest.respond(0); - } - else { - copyArrayBufferView(result.value, byobRequest.view); - byobRequest.respond(result.value.byteLength); - } - }); - this._setPendingRead(read); - return read; - }; - return WrappingReadableByteStreamSource; -}(AbstractWrappingReadableStreamSource)); - -function createWritableStreamWrapper(ctor) { - assert$1(isWritableStreamConstructor(ctor)); - return function (writable) { - if (writable.constructor === ctor) { - return writable; - } - var sink = createWrappingWritableSink(writable); - return new ctor(sink); - }; +function isDataExpired(keyPacket, signature, date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + const expirationTime = getKeyExpirationTime(keyPacket, signature); + return !(keyPacket.created <= normDate && normDate < expirationTime); + } + return false; } -function createWrappingWritableSink(writable) { - assert$1(isWritableStream(writable)); - assert$1(writable.locked === false); - var writer = writable.getWriter(); - return new WrappingWritableStreamSink(writer); -} -var WrappingWritableStreamSink = /** @class */ (function () { - function WrappingWritableStreamSink(underlyingWriter) { - var _this = this; - this._writableStreamController = undefined; - this._pendingWrite = undefined; - this._state = "writable" /* WRITABLE */; - this._storedError = undefined; - this._underlyingWriter = underlyingWriter; - this._errorPromise = new Promise(function (resolve, reject) { - _this._errorPromiseReject = reject; - }); - this._errorPromise.catch(noop$1); - } - WrappingWritableStreamSink.prototype.start = function (controller) { - var _this = this; - this._writableStreamController = controller; - this._underlyingWriter.closed - .then(function () { - _this._state = "closed" /* CLOSED */; - }) - .catch(function (reason) { return _this._finishErroring(reason); }); - }; - WrappingWritableStreamSink.prototype.write = function (chunk) { - var _this = this; - var writer = this._underlyingWriter; - // Detect past errors - if (writer.desiredSize === null) { - return writer.ready; - } - var writeRequest = writer.write(chunk); - // Detect future errors - writeRequest.catch(function (reason) { return _this._finishErroring(reason); }); - writer.ready.catch(function (reason) { return _this._startErroring(reason); }); - // Reject write when errored - var write = Promise.race([writeRequest, this._errorPromise]); - this._setPendingWrite(write); - return write; - }; - WrappingWritableStreamSink.prototype.close = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return this._underlyingWriter.close(); - } - return this._finishPendingWrite().then(function () { return _this.close(); }); - }; - WrappingWritableStreamSink.prototype.abort = function (reason) { - if (this._state === "errored" /* ERRORED */) { - return undefined; - } - var writer = this._underlyingWriter; - return writer.abort(reason); - }; - WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) { - var _this = this; - var pendingWrite; - var finishWrite = function () { - if (_this._pendingWrite === pendingWrite) { - _this._pendingWrite = undefined; - } - }; - this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite); - }; - WrappingWritableStreamSink.prototype._finishPendingWrite = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return Promise.resolve(); - } - var afterWrite = function () { return _this._finishPendingWrite(); }; - return this._pendingWrite.then(afterWrite, afterWrite); - }; - WrappingWritableStreamSink.prototype._startErroring = function (reason) { - var _this = this; - if (this._state === "writable" /* WRITABLE */) { - this._state = "erroring" /* ERRORING */; - this._storedError = reason; - var afterWrite = function () { return _this._finishErroring(reason); }; - if (this._pendingWrite === undefined) { - afterWrite(); - } - else { - this._finishPendingWrite().then(afterWrite, afterWrite); - } - this._writableStreamController.error(reason); - } - }; - WrappingWritableStreamSink.prototype._finishErroring = function (reason) { - if (this._state === "writable" /* WRITABLE */) { - this._startErroring(reason); - } - if (this._state === "erroring" /* ERRORING */) { - this._state = "errored" /* ERRORED */; - this._errorPromiseReject(this._storedError); - } - }; - return WrappingWritableStreamSink; -}()); -function createTransformStreamWrapper(ctor) { - assert$1(isTransformStreamConstructor(ctor)); - return function (transform) { - if (transform.constructor === ctor) { - return transform; - } - var transformer = createWrappingTransformer(transform); - return new ctor(transformer); - }; +/** + * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} + * @param {SecretSubkeyPacket} subkey - Subkey key packet + * @param {SecretKeyPacket} primaryKey - Primary key packet + * @param {Object} options + * @param {Object} config - Full configuration + */ +async function createBindingSignature(subkey, primaryKey, options, config) { + const dataToSign = {}; + dataToSign.key = primaryKey; + dataToSign.bind = subkey; + const signatureProperties = { signatureType: enums.signature.subkeyBinding }; + if (options.sign) { + signatureProperties.keyFlags = [enums.keyFlags.signData]; + signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, { + signatureType: enums.signature.keyBinding + }, options.date, undefined, undefined, undefined, config); + } else { + signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; + } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; + } + const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); + return subkeySignaturePacket; } -function createWrappingTransformer(transform) { - assert$1(isTransformStream(transform)); - var readable = transform.readable, writable = transform.writable; - assert$1(readable.locked === false); - assert$1(writable.locked === false); - var reader = readable.getReader(); - var writer; - try { - writer = writable.getWriter(); + +/** + * Returns the preferred signature hash algorithm for a set of keys. + * @param {Array} [targetKeys] - The keys to get preferences from + * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from + * @param {Object} config - full configuration + * @returns {Promise} + * @async + */ +async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) { + /** + * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the + * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys). + * if no keys are available, `preferredSenderAlgo` is returned. + * For ECC signing key, the curve preferred hash is taken into account as well (see logic below). + */ + const defaultAlgo = enums.hash.sha256; // MUST implement + const preferredSenderAlgo = config.preferredHashAlgorithm; + + const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => { + const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config); + const targetPrefs = selfCertification.preferredHashAlgorithms; + return targetPrefs; + })); + const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys + for (const supportedAlgos of supportedAlgosPerTarget) { + for (const hashAlgo of supportedAlgos) { + try { + // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on + const supportedAlgo = enums.write(enums.hash, hashAlgo); + supportedAlgosMap.set( + supportedAlgo, + supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1 + ); + } catch {} } - catch (e) { - reader.releaseLock(); // do not leak reader - throw e; + } + const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo; + const getStrongestSupportedHashAlgo = () => { + if (supportedAlgosMap.size === 0) { + return defaultAlgo; } - return new WrappingTransformStreamTransformer(reader, writer); -} -var WrappingTransformStreamTransformer = /** @class */ (function () { - function WrappingTransformStreamTransformer(reader, writer) { - var _this = this; - this._transformStreamController = undefined; - this._onRead = function (result) { - if (result.done) { - return; - } - _this._transformStreamController.enqueue(result.value); - return _this._reader.read().then(_this._onRead); - }; - this._onError = function (reason) { - _this._flushReject(reason); - _this._transformStreamController.error(reason); - _this._reader.cancel(reason).catch(noop$1); - _this._writer.abort(reason).catch(noop$1); - }; - this._onTerminate = function () { - _this._flushResolve(); - _this._transformStreamController.terminate(); - var error = new TypeError('TransformStream terminated'); - _this._writer.abort(error).catch(noop$1); - }; - this._reader = reader; - this._writer = writer; - this._flushPromise = new Promise(function (resolve, reject) { - _this._flushResolve = resolve; - _this._flushReject = reject; - }); + const sortedHashAlgos = Array.from(supportedAlgosMap.keys()) + .filter(hashAlgo => isSupportedHashAlgo(hashAlgo)) + .sort((algoA, algoB) => mod$1.hash.getHashByteLength(algoA) - mod$1.hash.getHashByteLength(algoB)); + const strongestHashAlgo = sortedHashAlgos[0]; + // defaultAlgo is always implicilty supported, and might be stronger than the rest + return mod$1.hash.getHashByteLength(strongestHashAlgo) >= mod$1.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo; + }; + + const eccAlgos = new Set([ + enums.publicKey.ecdsa, + enums.publicKey.eddsaLegacy, + enums.publicKey.ed25519, + enums.publicKey.ed448 + ]); + + if (eccAlgos.has(signingKeyPacket.algorithm)) { + // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see: + // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5 + // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough; + // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve + // preferred algo, even if not supported by all targets. + const preferredCurveAlgo = mod$1.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid); + + const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo); + const preferredSenderAlgoStrongerThanCurveAlgo = mod$1.hash.getHashByteLength(preferredSenderAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo); + + if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) { + return preferredSenderAlgo; + } else { + const strongestSupportedAlgo = getStrongestSupportedHashAlgo(); + return mod$1.hash.getHashByteLength(strongestSupportedAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo) ? + strongestSupportedAlgo : + preferredCurveAlgo; } - WrappingTransformStreamTransformer.prototype.start = function (controller) { - this._transformStreamController = controller; - this._reader.read() - .then(this._onRead) - .then(this._onTerminate, this._onError); - var readerClosed = this._reader.closed; - if (readerClosed) { - readerClosed - .then(this._onTerminate, this._onError); - } - }; - WrappingTransformStreamTransformer.prototype.transform = function (chunk) { - return this._writer.write(chunk); - }; - WrappingTransformStreamTransformer.prototype.flush = function () { - var _this = this; - return this._writer.close() - .then(function () { return _this._flushPromise; }); - }; - return WrappingTransformStreamTransformer; -}()); + } -var webStreamsAdapter = /*#__PURE__*/Object.freeze({ - __proto__: null, - createReadableStreamWrapper: createReadableStreamWrapper, - createTransformStreamWrapper: createTransformStreamWrapper, - createWrappingReadableSource: createWrappingReadableSource, - createWrappingTransformer: createWrappingTransformer, - createWrappingWritableSink: createWrappingWritableSink, - createWritableStreamWrapper: createWritableStreamWrapper -}); + // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this, + // since it was manually set by the sender. + return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo(); +} + +/** + * Returns the preferred compression algorithm for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Preferred compression algorithm + * @async + */ +async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const defaultAlgo = enums.compression.uncompressed; + const preferredSenderAlgo = config$1.preferredCompressionAlgorithm; -var bn = createCommonjsModule(function (module) { -(function (module, exports) { + // if preferredSenderAlgo appears in the prefs of all recipients, we pick it + // otherwise we use the default algo + // if no keys are available, preferredSenderAlgo is returned + const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { + const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1); + const recipientPrefs = selfCertification.preferredCompressionAlgorithms; + return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; + })); + return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; +} - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); +/** + * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred + * @async + */ +async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1))); + const withAEAD = keys.length ? + selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) : + config$1.aeadProtect; + + if (withAEAD) { + const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb }; + const desiredCipherSuites = [ + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm }, + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb }, + { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm } + ]; + for (const desiredCipherSuite of desiredCipherSuites) { + if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some( + cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo + ))) { + return desiredCipherSuite; + } + } + return defaultCipherSuite; } + const defaultSymAlgo = enums.symmetric.aes128; + const desiredSymAlgo = config$1.preferredSymmetricAlgorithm; + return { + symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ? + desiredSymAlgo : + defaultSymAlgo, + aeadAlgo: undefined + }; +} - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; +/** + * Create signature packet + * @param {Object} dataToSign - Contains packets to be signed + * @param {Array} recipientKeys - keys to get preferences from + * @param {SecretKeyPacket| + * SecretSubkeyPacket} signingKeyPacket secret key packet for signing + * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing + * @param {Date} [date] - Override the creationtime of the signature + * @param {Object} [userID] - User ID + * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [detached] - Whether to create a detached signature packet + * @param {Object} config - full configuration + * @returns {Promise} Signature packet. + */ +async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) { + if (signingKeyPacket.isDummy()) { + throw new Error('Cannot sign with a gnu-dummy key.'); } + if (!signingKeyPacket.isDecrypted()) { + throw new Error('Signing key is not decrypted.'); + } + const signaturePacket = new SignaturePacket(); + Object.assign(signaturePacket, signatureProperties); + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config); + signaturePacket.rawNotations = [...notations]; + await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config); + return signaturePacket; +} - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; +/** + * Merges signatures from source[attr] to dest[attr] + * @param {Object} source + * @param {Object} dest + * @param {String} attr + * @param {Date} [date] - date to use for signature expiration check, instead of the current time + * @param {Function} [checkFn] - signature only merged if true + */ +async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { + source = source[attr]; + if (source) { + if (!dest[attr].length) { + dest[attr] = source; + } else { + await Promise.all(source.map(async function(sourceSig) { + if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && + !dest[attr].some(function(destSig) { + return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); + })) { + dest[attr].push(sourceSig); + } + })); } + } +} - this.negative = 0; - this.words = null; - this.length = 0; +/** + * Checks if a given certificate or binding signature is revoked + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Object} dataToVerify - The data to check + * @param {Array} revocations - The revocation signatures to check + * @param {SignaturePacket} signature - The certificate or signature to check + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the signature revokes the data. + * @async + */ +async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { + key = key || primaryKey; + const revocationKeyIDs = []; + await Promise.all(revocations.map(async function(revocationSignature) { + try { + if ( + // Note: a third-party revocation signature could legitimately revoke a + // self-signature if the signature has an authorized revocation key. + // However, we don't support passing authorized revocation keys, nor + // verifying such revocation signatures. Instead, we indicate an error + // when parsing a key with an authorized revocation key, and ignore + // third-party revocation signatures here. (It could also be revoking a + // third-party key certification, which should only affect + // `verifyAllCertifications`.) + !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) + ) { + const isHardRevocation = ![ + enums.reasonForRevocation.keyRetired, + enums.reasonForRevocation.keySuperseded, + enums.reasonForRevocation.userIDInvalid + ].includes(revocationSignature.reasonForRevocationFlag); - // Reduction context - this.red = null; + await revocationSignature.verify( + key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config + ); - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; + // TODO get an identifier of the revoked object instead + revocationKeyIDs.push(revocationSignature.issuerKeyID); } + } catch (e) {} + })); + // TODO further verify that this is the signature that should be revoked + if (signature) { + signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : + signature.revoked || false; + return signature.revoked; + } + return revocationKeyIDs.length > 0; +} - this._init(number || 0, base || 10, endian || 'be'); - } +/** + * Returns key expiration time based on the given certification signature. + * The expiration time of the signature is ignored. + * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check + * @param {SignaturePacket} signature - signature to process + * @returns {Date|Infinity} expiration time or infinity if the key does not expire + */ +function getKeyExpirationTime(keyPacket, signature) { + let expirationTime; + // check V4 expiration time + if (signature.keyNeverExpires === false) { + expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; + return expirationTime ? new Date(expirationTime) : Infinity; +} + +function sanitizeKeyOptions(options, subkeyDefaults = {}) { + options.type = options.type || subkeyDefaults.type; + options.curve = options.curve || subkeyDefaults.curve; + options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; + options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; + + options.sign = options.sign || false; + + switch (options.type) { + case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve` + try { + options.curve = enums.write(enums.curve, options.curve); + } catch (e) { + throw new Error('Unknown curve'); + } + if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy || + options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now + options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; + } + if (options.sign) { + options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; + } else { + options.algorithm = enums.publicKey.ecdh; + } + break; + case 'curve25519': + options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519; + break; + case 'curve448': + options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448; + break; + case 'rsa': + options.algorithm = enums.publicKey.rsaEncryptSign; + break; + default: + throw new Error(`Unsupported key type ${options.type}`); } + return options; +} - BN.BN = BN; - BN.wordSize = 26; +function validateSigningKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + default: + return false; + } +} - var Buffer; - try { - Buffer = buffer.Buffer; - } catch (e) { +function validateEncryptionKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + default: + return false; } +} - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; +function validateDecryptionKeyPacket(keyPacket, signature, config) { + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) { + // This is only relevant for RSA keys, all other signing algorithms cannot decrypt + return true; + } - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; } + default: + return false; + } +} - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } +/** + * Check key against blacklisted algorithms and minimum strength requirements. + * @param {SecretKeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket + * @param {Config} config + * @throws {Error} if the key packet does not meet the requirements + */ +function checkKeyRequirements(keyPacket, config) { + const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); + const algoInfo = keyPacket.getAlgorithmInfo(); + if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { + throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); + } + switch (keyAlgo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.rsaEncrypt: + if (algoInfo.bits < config.minRSABits) { + throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); + } + break; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ecdh: + if (config.rejectCurves.has(algoInfo.curve)) { + throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); + } + break; + } +} - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); +/** + * @module key/User + */ - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } +/** + * Class that represents an user ID or attribute packet and the relevant signatures. + * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info + * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + */ +class User { + constructor(userPacket, mainKey) { + this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; + this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; + this.selfCertifications = []; + this.otherCertifications = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } - if (number[0] === '-') { - this.negative = 1; - } + /** + * Transforms structured user data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.userID || this.userAttribute); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.selfCertifications); + packetlist.push(...this.otherCertifications); + return packetlist; + } - this.strip(); + /** + * Shallow clone + * @returns {User} + */ + clone() { + const user = new User(this.userID || this.userAttribute, this.mainKey); + user.selfCertifications = [...this.selfCertifications]; + user.otherCertifications = [...this.otherCertifications]; + user.revocationSignatures = [...this.revocationSignatures]; + return user; + } - if (endian !== 'le') return; + /** + * Generate third-party certifications over this user and its primary key + * @param {Array} signingKeys - Decrypted private keys for signing + * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} New user with new certifications. + * @async + */ + async certify(signingKeys, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { + if (!privateKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + if (privateKey.hasSameFingerprintAs(primaryKey)) { + throw new Error("The user's own key can only be used for self-certifications"); + } + const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); + return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, { + // Most OpenPGP implementations use generic certification (0x10) + signatureType: enums.signature.certGeneric, + keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] + }, date, undefined, undefined, undefined, config); + })); + await user.update(this, date, config); + return user; + } - this._initArray(this.toArray(), base, endian); - }; + /** + * Checks if a given certificate of the user is revoked + * @param {SignaturePacket} certificate - The certificate to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked(primaryKey, enums.signature.certRevocation, { + key: primaryKey, + userID: this.userID, + userAttribute: this.userAttribute + }, this.revocationSignatures, certificate, keyPacket, date, config$1); + } - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; + /** + * Verifies the user certificate. + * @param {SignaturePacket} certificate - A certificate of this user + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate + * @throws if the user certificate is invalid. + * @async + */ + async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const { issuerKeyID } = certificate; + const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); + if (issuerKeys.length === 0) { + return null; } + await Promise.all(issuerKeys.map(async key => { + const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); + if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { + throw new Error('User certificate is revoked'); + } + try { + await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('User certificate is invalid', e); + } + })); + return true; + } - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } + /** + * Verifies all user certificates + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllCertifications(verificationKeys, date = new Date(), config) { + const that = this; + const certifications = this.selfCertifications.concat(this.otherCertifications); + return Promise.all(certifications.map(async certification => ({ + keyID: certification.issuerKeyID, + valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) + }))); + } - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} Status of user. + * @throws {Error} if there are no valid self signatures. + * @async + */ + async verify(date = new Date(), config) { + if (!this.selfCertifications.length) { + throw new Error('No self-certifications found'); } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // TODO replace when Promise.some or Promise.any are implemented + let exception; + for (let i = this.selfCertifications.length - 1; i >= 0; i--) { + try { + const selfCertification = this.selfCertifications[i]; + if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { + throw new Error('Self-certification is revoked'); } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + try { + await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('Self-certification is invalid', e); } + return true; + } catch (e) { + exception = e; } } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; + throw exception; } - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; + /** + * Update user with new components from specified user + * @param {User} sourceUser - Source user to merge + * @param {Date} date - Date to verify the validity of signatures + * @param {Object} config - Full configuration + * @returns {Promise} + * @async + */ + async update(sourceUser, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // self signatures + await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { + try { + await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); + return true; + } catch (e) { + return false; } - } - return r; + }); + // other signatures + await mergeSignatures(sourceUser, this, 'otherCertifications', date); + // revocation signatures + await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); + }); } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + /** + * Revokes the user + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New user with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.certRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await user.update(this); + return user; + } +} - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +/** + * @module key/Subkey + */ - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } +/** + * Class that represents a subkey packet and the relevant signatures. + * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID + * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint + * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs + * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo + * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime + * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + */ +class Subkey { + /** + * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey + * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey + */ + constructor(subkeyPacket, mainKey) { + this.keyPacket = subkeyPacket; + this.bindingSignatures = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + /** + * Transforms structured subkey data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.bindingSignatures); + return packetlist; + } - for (i = 0; i < mod; i++) { - pow *= base; - } + /** + * Shallow clone + * @return {Subkey} + */ + clone() { + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.bindingSignatures = [...this.bindingSignatures]; + subkey.revocationSignatures = [...this.revocationSignatures]; + return subkey; + } - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; + /** + * Checks if a binding signature of a subkey is revoked + * @param {SignaturePacket} signature - The binding signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the binding signature is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked( + primaryKey, enums.signature.subkeyRevocation, { + key: primaryKey, + bind: this.keyPacket + }, this.revocationSignatures, signature, key, date, config$1 + ); + } - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} if the subkey is invalid. + * @async + */ + async verify(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + // check subkey binding signatures + const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + // check binding signature is not revoked + if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { + throw new Error('Subkey is revoked'); } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; + // check for expiration time + if (isDataExpired(this.keyPacket, bindingSignature, date)) { + throw new Error('Subkey is expired'); } - return this; - }; + return bindingSignature; + } - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; + /** + * Returns the expiration time of the subkey or Infinity if key does not expire. + * Returns null if the subkey is invalid. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + let bindingSignature; + try { + bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + } catch (e) { + return null; } - return this._normSign(); - }; + const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); + const sigExpiry = bindingSignature.getExpirationTime(); + return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; + } - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; + /** + * Update subkey with new components from specified subkey + * @param {Subkey} subkey - Source subkey to merge + * @param {Date} [date] - Date to verify validity of signatures + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if update failed + * @async + */ + async update(subkey, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + if (!this.hasSameFingerprintAs(subkey)) { + throw new Error('Subkey update method: fingerprints of subkeys not equal'); } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; + // key packet + if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && + subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { + this.keyPacket = subkey.keyPacket; } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; + // update missing binding signatures + const that = this; + const dataToVerify = { key: primaryKey, bind: that.keyPacket }; + await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { + for (let i = 0; i < that.bindingSignatures.length; i++) { + if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { + if (srcBindSig.created > that.bindingSignatures[i].created) { + that.bindingSignatures[i] = srcBindSig; + } + return false; } } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; + try { + await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); + return true; + } catch (e) { + return false; } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; + }); + // revocation signatures + await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); + }); + } - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; + /** + * Revokes the subkey + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New subkey with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { key: primaryKey, bind: this.keyPacket }; + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.subkeyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await subkey.update(this); + return subkey; + } - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + hasSameFingerprintAs(other) { + return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + } +} - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { + Subkey.prototype[name] = + function() { + return this.keyPacket[name](); + }; +}); - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +// A key revocation certificate can contain the following packets +const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); +const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); +const keyPacketTags = new Set([ + enums.packet.publicKey, enums.packet.privateKey, + enums.packet.publicSubkey, enums.packet.privateSubkey +]); - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +/** + * Abstract class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + * @borrows PublicKeyPacket#getKeyID as Key#getKeyID + * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint + * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs + * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo + * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + */ +class Key { + /** + * Transforms packetlist to structured key data + * @param {PacketList} packetlist - The packets that form a key + * @param {Set} disallowedPackets - disallowed packet tags + */ + packetListToStructure(packetlist, disallowedPackets = new Set()) { + let user; + let primaryKeyID; + let subkey; + let ignoreUntil; - res[i] = b; - } + for (const packet of packetlist) { - for (; i < reqLength; i++) { - res[i] = 0; + if (packet instanceof UnparseablePacket) { + const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); + if (isUnparseableKeyPacket && !ignoreUntil) { + // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must + // discard all non-key packets that follow, until another (sub)key packet is found. + if (mainKeyPacketTags.has(packet.tag)) { + ignoreUntil = mainKeyPacketTags; + } else { + ignoreUntil = keyPacketTags; + } + } + continue; } - } - - return res; - }; - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; + const tag = packet.constructor.tag; + if (ignoreUntil) { + if (!ignoreUntil.has(tag)) continue; + ignoreUntil = null; } - if (t >= 0x8) { - r += 4; - t >>>= 4; + if (disallowedPackets.has(tag)) { + throw new Error(`Unexpected packet type: ${tag}`); } - if (t >= 0x02) { - r += 2; - t >>>= 2; + switch (tag) { + case enums.packet.publicKey: + case enums.packet.secretKey: + if (this.keyPacket) { + throw new Error('Key block contains multiple keys'); + } + this.keyPacket = packet; + primaryKeyID = this.getKeyID(); + if (!primaryKeyID) { + throw new Error('Missing Key ID'); + } + break; + case enums.packet.userID: + case enums.packet.userAttribute: + user = new User(packet, this); + this.users.push(user); + break; + case enums.packet.publicSubkey: + case enums.packet.secretSubkey: + user = null; + subkey = new Subkey(packet, this); + this.subkeys.push(subkey); + break; + case enums.packet.signature: + switch (packet.signatureType) { + case enums.signature.certGeneric: + case enums.signature.certPersona: + case enums.signature.certCasual: + case enums.signature.certPositive: + if (!user) { + util.printDebug('Dropping certification signatures without preceding user packet'); + continue; + } + if (packet.issuerKeyID.equals(primaryKeyID)) { + user.selfCertifications.push(packet); + } else { + user.otherCertifications.push(packet); + } + break; + case enums.signature.certRevocation: + if (user) { + user.revocationSignatures.push(packet); + } else { + this.directSignatures.push(packet); + } + break; + case enums.signature.key: + this.directSignatures.push(packet); + break; + case enums.signature.subkeyBinding: + if (!subkey) { + util.printDebug('Dropping subkey binding signature without preceding subkey packet'); + continue; + } + subkey.bindingSignatures.push(packet); + break; + case enums.signature.keyRevocation: + this.revocationSignatures.push(packet); + break; + case enums.signature.subkeyRevocation: + if (!subkey) { + util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); + continue; + } + subkey.revocationSignatures.push(packet); + break; + } + break; } - return r + t; - }; + } } - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + /** + * Transforms structured key data to packetlist + * @returns {PacketList} The packets that form a key. + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.directSignatures); + this.users.map(user => packetlist.push(...user.toPacketList())); + this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); + return packetlist; + } - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + /** + * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. + * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. + * @returns {Promise} Clone of the key. + */ + clone(clonePrivateParams = false) { + const key = new this.constructor(this.toPacketList()); + if (clonePrivateParams) { + key.getKeys().forEach(k => { + // shallow clone the key packets + k.keyPacket = Object.create( + Object.getPrototypeOf(k.keyPacket), + Object.getOwnPropertyDescriptors(k.keyPacket) + ); + if (!k.keyPacket.isDecrypted()) return; + // deep clone the private params, which are cleared during encryption + const privateParams = {}; + Object.keys(k.keyPacket.privateParams).forEach(name => { + privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); + }); + k.keyPacket.privateParams = privateParams; + }); } - if ((t & 0x1) === 0) { - r++; + return key; + } + + /** + * Returns an array containing all public or private subkeys matching keyID; + * If no keyID is given, returns all subkeys. + * @param {type/keyID} [keyID] - key ID to look for + * @returns {Array} array of subkeys + */ + getSubkeys(keyID = null) { + const subkeys = this.subkeys.filter(subkey => ( + !keyID || subkey.getKeyID().equals(keyID, true) + )); + return subkeys; + } + + /** + * Returns an array containing all public or private keys matching keyID. + * If no keyID is given, returns all keys, starting with the primary key. + * @param {type/keyid~KeyID} [keyID] - key ID to look for + * @returns {Array} array of keys + */ + getKeys(keyID = null) { + const keys = []; + if (!keyID || this.getKeyID().equals(keyID, true)) { + keys.push(this); } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + return keys.concat(this.getSubkeys(keyID)); + } - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + /** + * Returns key IDs of all keys + * @returns {Array} + */ + getKeyIDs() { + return this.getKeys().map(key => key.getKeyID()); + } - return w; + /** + * Returns userIDs + * @returns {Array} Array of userIDs. + */ + getUserIDs() { + return this.users.map(user => { + return user.userID ? user.userID.userID : null; + }).filter(userID => userID !== null); } - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + /** + * Returns binary encoded key + * @returns {Uint8Array} Binary key. + */ + write() { + return this.toPacketList().write(); + } - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; + /** + * Returns last created key or key by given keyID that is available for signing and verification + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} signing key + * @throws if no valid signing key was found + * @async + */ + async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature( + subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 + ); + if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + continue; + } + if (!bindingSignature.embeddedSignature) { + throw new Error('Missing embedded signature'); + } + // verify embedded signature + await getLatestValidSignature( + [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 + ); + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } catch (e) { + exception = e; + } + } } - return this.clone(); - }; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + try { + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateSigningKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); + } - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; + /** + * Returns last created key or key by given keyID that is available for encryption or decryption + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} encryption key + * @throws if no valid encryption key was found + * @async + */ + async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; + // V4: by convention subkeys are preferred for encryption service + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } + } catch (e) { + exception = e; + } + } } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + try { + // if no valid subkey for encryption, evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } + throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + } - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + /** + * Checks if a signature on a key is revoked + * @param {SignaturePacket} signature - The signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + return isDataRevoked( + this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 + ); + } - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature. Throws if the primary key is invalid. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} If key verification failed + * @async + */ + async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + // check for key revocation signatures + if (await this.isRevoked(null, null, date, config$1)) { + throw new Error('Primary key is revoked'); } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + // check for valid, unrevoked, unexpired self signature + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + // check for expiration time in binding signatures + if (isDataExpired(primaryKey, selfCertification, date)) { + throw new Error('Primary key is expired'); } + if (primaryKey.version !== 6) { + // check for expiration time in direct signatures (for V6 keys, the above already did so) + const directSignature = await getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + if (directSignature && isDataExpired(primaryKey, directSignature, date)) { + throw new Error('Primary key is expired'); + } + } + } - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; + /** + * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. + * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. + * @param {Object} [userID] - User ID to consider instead of the primary user + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(userID, config$1 = config) { + let primaryKeyExpiry; + try { + const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1); + const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); + const selfSigExpiry = selfCertification.getExpirationTime(); + const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature. + await getLatestValidSignature( + this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 + ).catch(() => {}); + if (directSignature) { + const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); + // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, + // causing a discountinous validy period for the key + primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); + } else { + primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; + } + } catch (e) { + primaryKeyExpiry = null; + } - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + return util.normalizeDate(primaryKeyExpiry); + } - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + /** + * For V4 keys, returns the self-signature of the primary user. + * For V5 keys, returns the latest valid direct-key self-signature. + * This self-signature is to be used to check the key expiration, + * algorithm preferences, and so on. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} The primary self-signature + * @async + */ + async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + if (primaryKey.version === 6) { + return getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ); } + const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + return selfCertification; + } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * user: User, + * selfCertification: SignaturePacket + * }>} The primary user and the self signature + * @async + */ + async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const users = []; + let exception; + for (let i = 0; i < this.users.length; i++) { + try { + const user = this.users[i]; + if (!user.userID) { + continue; + } + if ( + (userID.name !== undefined && user.userID.name !== userID.name) || + (userID.email !== undefined && user.userID.email !== userID.email) || + (userID.comment !== undefined && user.userID.comment !== userID.comment) + ) { + throw new Error('Could not find user that matches that user ID'); + } + const dataToVerify = { userID: user.userID, key: primaryKey }; + const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); + users.push({ index: i, user, selfCertification }); + } catch (e) { + exception = e; } } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; + if (!users.length) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('Could not find primary user'); } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + await Promise.all(users.map(async function (a) { + return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); + })); + // sort by primary user flag and signature creation time + const primaryUser = users.sort(function(a, b) { + const A = a.selfCertification; + const B = b.selfCertification; + return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; + }).pop(); + const { user, selfCertification: cert } = primaryUser; + if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { + throw new Error('Primary user is revoked'); } + return primaryUser; + } - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * + * If the source key is a private key and the destination key is public, + * a private key is returned. + * @param {Key} sourceKey - Source key to merge + * @param {Date} [date] - Date to verify validity of signatures and keys + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} updated key + * @async + */ + async update(sourceKey, date = new Date(), config$1 = config) { + if (!this.hasSameFingerprintAs(sourceKey)) { + throw new Error('Primary key fingerprints must be equal to update the key'); } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (!this.isPrivate() && sourceKey.isPrivate()) { + // check for equal subkey packets + const equal = (this.subkeys.length === sourceKey.subkeys.length) && + (this.subkeys.every(destSubkey => { + return sourceKey.subkeys.some(srcSubkey => { + return destSubkey.hasSameFingerprintAs(srcSubkey); + }); + })); + if (!equal) { + throw new Error('Cannot update public key with private key if subkeys mismatch'); } - } - - return this; - }; - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; + return sourceKey.update(this, config$1); } + // from here on, either: + // - destination key is private, source key is public + // - the keys are of the same type + // hence we don't need to convert the destination key type + const updatedKey = this.clone(); + // revocation signatures + await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { + return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); + }); + // direct signatures + await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); + // update users + await Promise.all(sourceKey.users.map(async srcUser => { + // multiple users with the same ID/attribute are not explicitly disallowed by the spec + // hence we support them, just in case + const usersToUpdate = updatedKey.users.filter(dstUser => ( + (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || + (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) + )); + if (usersToUpdate.length > 0) { + await Promise.all( + usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) + ); + } else { + const newUser = srcUser.clone(); + newUser.mainKey = updatedKey; + updatedKey.users.push(newUser); + } + })); + // update subkeys + await Promise.all(sourceKey.subkeys.map(async srcSubkey => { + // multiple subkeys with same fingerprint might be preset + const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( + dstSubkey.hasSameFingerprintAs(srcSubkey) + )); + if (subkeysToUpdate.length > 0) { + await Promise.all( + subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) + ); + } else { + const newSubkey = srcSubkey.clone(); + newSubkey.mainKey = updatedKey; + updatedKey.subkeys.push(newSubkey); + } + })); - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; + return updatedKey; + } - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Armored revocation certificate. + * @async + */ + async getRevocationCertificate(date = new Date(), config$1 = config) { + const dataToVerify = { key: this.keyPacket }; + const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); + const packetlist = new PacketList(); + packetlist.push(revocationSignature); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1); + } - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param {String} revocationCertificate - armored revocation certificate + * @param {Date} [date] - Date to verify the certificate + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Revoked key. + * @async + */ + async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { + const input = await unarmor(revocationCertificate); + const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); + const revocationSignature = packetlist.findPacket(enums.packet.signature); + if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { + throw new Error('Could not find revocation signature packet'); } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { + throw new Error('Revocation signature does not match key'); } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + try { + await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); + } catch (e) { + throw util.wrapError('Could not verify revocation signature', e); } + const key = this.clone(); + key.revocationSignatures.push(revocationSignature); + return key; + } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + /** + * Signs primary user of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signPrimaryUser(privateKeys, date, userID, config$1 = config) { + const { index, user } = await this.getPrimaryUser(date, userID, config$1); + const userSign = await user.certify(privateKeys, date, config$1); + const key = this.clone(); + key.users[index] = userSign; + return key; + } - this.length = Math.max(this.length, i); + /** + * Signs all users of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for signing, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signAllUsers(privateKeys, date = new Date(), config$1 = config) { + const key = this.clone(); + key.users = await Promise.all(this.users.map(function(user) { + return user.certify(privateKeys, date, config$1); + })); + return key; + } - if (a !== this) { - this.negative = 1; - } + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { + const primaryKey = this.keyPacket; + const { user } = await this.getPrimaryUser(date, userID, config$1); + const results = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + return results; + } + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of userID, signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { + const primaryKey = this.keyPacket; + const results = []; + await Promise.all(this.users.map(async user => { + const signatures = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + + results.push(...signatures.map( + signature => ({ + userID: user.userID ? user.userID.userID : null, + userAttribute: user.userAttribute, + keyID: signature.keyID, + valid: signature.valid + })) + ); + })); + return results; + } +} - return this.strip(); - }; +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { + Key.prototype[name] = + Subkey.prototype[name]; +}); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; +/** + * Class that represents an OpenPGP Public Key + */ +class PublicKey extends Key { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.keyPacket = null; + this.revocationSignatures = []; + this.directSignatures = []; + this.users = []; + this.subkeys = []; + if (packetlist) { + this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing public-key packet'); } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); } - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); + /** + * Returns true if this is a private key + * @returns {false} + */ + isPrivate() { + return false; } - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + return this; } - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } +} - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; +/** + * Class that represents an OpenPGP Private key + */ +class PrivateKey extends PublicKey { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing private-key packet'); } + } - return rb; - }; + /** + * Returns true if this is a private key + * @returns {Boolean} + */ + isPrivate() { + return true; + } - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + const packetlist = new PacketList(); + const keyPackets = this.toPacketList(); + for (const keyPacket of keyPackets) { + switch (keyPacket.constructor.tag) { + case enums.packet.secretKey: { + const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); + packetlist.push(pubKeyPacket); + break; + } + case enums.packet.secretSubkey: { + const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); + packetlist.push(pubSubkeyPacket); + break; + } + default: + packetlist.push(keyPacket); + } } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + return new PublicKey(packetlist); + } - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + /** + * Returns all keys that are available for decryption, matching the keyID when given + * This is useful to retrieve keys for session key decryption + * @param {module:type/keyid~KeyID} keyID, optional + * @param {Date} date, optional + * @param {String} userID, optional + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} Array of decryption keys. + * @throws {Error} if no decryption key is found + * @async + */ + async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const keys = []; + let exception = null; + for (let i = 0; i < this.subkeys.length; i++) { + if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { + if (this.subkeys[i].keyPacket.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + continue; + } - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; + try { + const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; + const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) { + keys.push(this.subkeys[i]); } + } catch (e) { + exception = e; } } } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - if (w < 0x4000000) { - carry = 0; + // evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) { + if (primaryKey.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); } else { - carry = w / 0x4000000 | 0; + keys.push(this); } } - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; + if (keys.length === 0) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('No decryption key packets found'); } - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; + return keys; + } - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + /** + * Returns true if the primary key or any subkey is decrypted. + * A dummy key is considered encrypted. + */ + isDecrypted() { + return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); + } - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; + /** + * Check whether the private and public primary key parameters correspond + * Together with verification of binding signatures, this guarantees key integrity + * In case of gnu-dummy primary key, it is enough to validate any signing subkeys + * otherwise all encryption subkeys are validated + * If only gnu-dummy keys are found, we cannot properly validate so we throw an error + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if validation was not successful and the key cannot be trusted + * @async + */ + async validate(config$1 = config) { + if (!this.isPrivate()) { + throw new Error('Cannot validate a public key'); } - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); + let signingKeyPacket; + if (!this.keyPacket.isDummy()) { + signingKeyPacket = this.keyPacket; + } else { + /** + * It is enough to validate any signing keys + * since its binding signatures are also checked + */ + const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); + // This could again be a dummy key + if (signingKey && !signingKey.keyPacket.isDummy()) { + signingKeyPacket = signingKey.keyPacket; } } - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); + if (signingKeyPacket) { + return signingKeyPacket.validate(); + } else { + const keys = this.getKeys(); + const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); + if (allDummies) { + throw new Error('Cannot validate an all-gnu-dummy key'); } - if (carry) { - this.words[i] = carry; - this.length++; - } + return Promise.all(keys.map(async key => key.keyPacket.validate())); } + } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; + /** + * Clear private key parameters + */ + clearPrivateParams() { + this.getKeys().forEach(({ keyPacket }) => { + if (keyPacket.isDecrypted()) { + keyPacket.clearPrivateParams(); } + }); + } - this.length += s; + /** + * Revokes the key + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New key with revocation signature. + * @async + */ + async revoke( + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + if (!this.isPrivate()) { + throw new Error('Need private key for revoking'); } + const dataToSign = { key: this.keyPacket }; + const key = this.clone(); + key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, undefined, config$1)); + return key; + } - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; + /** + * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. + * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519. + * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. + * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format). + * Note: Curve448 and Curve25519 are not widely supported yet. + * @param {String} options.curve (optional) Elliptic curve for ECC keys + * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date (optional) Override the creation date of the key and the key signatures + * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false + * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} + * @async + */ + async addSubkey(options = {}) { + const config$1 = { ...config, ...options.config }; + if (options.passphrase) { + throw new Error('Subkey could not be encrypted here, please encrypt whole key'); } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; + if (options.rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); } - - if (s === 0) ; else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; + const secretKeyPacket = this.keyPacket; + if (secretKeyPacket.isDummy()) { + throw new Error('Cannot add subkey to gnu-dummy primary key'); } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; + if (!secretKeyPacket.isDecrypted()) { + throw new Error('Key is not decrypted'); } + const defaultOptions = secretKeyPacket.getAlgorithmInfo(); + defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm); + defaultOptions.rsaBits = defaultOptions.bits || 4096; + defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy'; + options = sanitizeKeyOptions(options, defaultOptions); + // Every subkey for a v4 primary key MUST be a v4 subkey. + // Every subkey for a v6 primary key MUST be a v6 subkey. + // For v5 keys, since we dropped generation support, a v4 subkey is added. + // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user. + const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 }); + checkKeyRequirements(keyPacket, config$1); + const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); + const packetList = this.toPacketList(); + packetList.push(keyPacket, bindingSignature); + return new PrivateKey(packetList); + } +} - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } +function getDefaultSubkeyType(algoName) { + const algo = enums.write(enums.publicKey, algoName); + // NB: no encryption-only algos, since they cannot be in primary keys + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + return 'rsa'; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return 'ecc'; + case enums.publicKey.ed25519: + return 'curve25519'; + case enums.publicKey.ed448: + return 'curve448'; + default: + throw new Error('Unsupported algorithm'); + } +} - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return this.strip(); - }; - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; +// A Key can contain the following packets +const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +]); - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; +/** + * Creates a PublicKey or PrivateKey depending on the packetlist in input + * @param {PacketList} - packets to parse + * @return {Key} parsed key + * @throws if no key packet was found + */ +function createKey(packetlist) { + for (const packet of packetlist) { + switch (packet.constructor.tag) { + case enums.packet.secretKey: + return new PrivateKey(packetlist); + case enums.packet.publicKey: + return new PublicKey(packetlist); + } + } + throw new Error('No key packet found'); +} - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; +/** + * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format). + * @param {String} options.curve Elliptic curve for ECC keys + * @param {Integer} options.rsaBits Number of bits for RSA keys + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Creation date of the key and the key signatures + * @param {Object} config - Full configuration + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function generate(options, config) { + options.sign = true; // primary key is always a signing key + options = sanitizeKeyOptions(options); + options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); + let promises = [generateSecretKey(options, config)]; + promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); + const packets = await Promise.all(promises); - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; + const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; +} - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; +/** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param {PrivateKey} options.privateKey The private key to reformat + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Override the creation date of the key signatures + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * @param {Object} config - Full configuration + * + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function reformat(options, config) { + options = sanitize(options); + const { privateKey } = options; - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; + if (!privateKey.isPrivate()) { + throw new Error('Cannot reformat a public key'); + } - // Check bit and return - var w = this.words[s]; + if (privateKey.keyPacket.isDummy()) { + throw new Error('Cannot reformat a gnu-dummy primary key'); + } - return !!(w & q); - }; + const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); + if (!isDecrypted) { + throw new Error('Key is not decrypted'); + } - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + const secretKeyPacket = privateKey.keyPacket; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + if (!options.subkeys) { + options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { + const secretSubkeyPacket = subkey.keyPacket; + const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; + const bindingSignature = await ( + getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) + ).catch(() => ({})); + return { + sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) + }; + })); + } - if (this.length <= s) { - return this; - } + const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); + if (options.subkeys.length !== secretSubkeyPackets.length) { + throw new Error('Number of subkey options does not match number of subkeys'); + } - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); + options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; - return this.strip(); - }; + function sanitize(options, subkeyDefaults = {}) { + options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + return options; + } +} - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } +/** + * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection + * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. + * @param {SecretKeyPacket} secretKeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPackets + * @param {Object} options + * @param {Object} config - Full configuration + * @returns {PrivateKey} + */ +async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { + // set passphrase protection + if (options.passphrase) { + await secretKeyPacket.encrypt(options.passphrase, config); + } - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + await secretSubkeyPacket.encrypt(subkeyPassphrase, config); } + })); - // Add without checks - return this._iaddn(num); - }; + const packetlist = new PacketList(); + packetlist.push(secretKeyPacket); - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + function createPreferredAlgos(algos, preferredAlgo) { + return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + } - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } + function getKeySignatureProperties() { + const signatureProperties = {}; + signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; + const symmetricAlgorithms = createPreferredAlgos([ + // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + enums.symmetric.aes256, + enums.symmetric.aes128 + ], config.preferredSymmetricAlgorithm); + signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms; + if (config.aeadProtect) { + const aeadAlgorithms = createPreferredAlgos([ + enums.aead.gcm, + enums.aead.eax, + enums.aead.ocb + ], config.preferredAEADAlgorithm); + signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => { + return symmetricAlgorithms.map(symmetricAlgorithm => { + return [symmetricAlgorithm, aeadAlgorithm]; + }); + }); } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; + signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ + // prefer fast asm.js implementations (SHA-256) + enums.hash.sha256, + enums.hash.sha512, + enums.hash.sha3_256, + enums.hash.sha3_512 + ], config.preferredHashAlgorithm); + signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ + enums.compression.uncompressed, + enums.compression.zlib, + enums.compression.zip + ], config.preferredCompressionAlgorithm); + // integrity protection always enabled + signatureProperties.features = [0]; + signatureProperties.features[0] |= enums.features.modificationDetection; + if (config.aeadProtect) { + signatureProperties.features[0] |= enums.features.seipdv2; } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; } + return signatureProperties; + } - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + if (secretKeyPacket.version === 6) { // add direct key signature with key prefs + const dataToSign = { + key: secretKeyPacket + }; - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + const signatureProperties = getKeySignatureProperties(); + signatureProperties.signatureType = enums.signature.key; - this._expand(len); + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + packetlist.push(signaturePacket); + } - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; + await Promise.all(options.userIDs.map(async function(userID, index) { + const userIDPacket = UserIDPacket.fromObject(userID); + const dataToSign = { + userID: userIDPacket, + key: secretKeyPacket + }; + const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {}; + signatureProperties.signatureType = enums.signature.certPositive; + if (index === 0) { + signatureProperties.isPrimaryUserID = true; } - if (carry === 0) return this.strip(); + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; + return { userIDPacket, signaturePacket }; + })).then(list => { + list.forEach(({ userIDPacket, signaturePacket }) => { + packetlist.push(userIDPacket); + packetlist.push(signaturePacket); + }); + }); - return this.strip(); - }; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyOptions = options.subkeys[index]; + const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); + return { secretSubkeyPacket, subkeySignaturePacket }; + })).then(packets => { + packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { + packetlist.push(secretSubkeyPacket); + packetlist.push(subkeySignaturePacket); + }); + }); - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; + // Add revocation signature packet for creating a revocation certificate. + // This packet should be removed before returning the key. + const dataToSign = { key: secretKeyPacket }; + packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.reasonForRevocation.noReason, + reasonForRevocationString: '' + }, options.date, undefined, undefined, undefined, config)); - var a = this.clone(); - var b = num; + if (options.passphrase) { + secretKeyPacket.clearPrivateParams(); + } - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + secretSubkeyPacket.clearPrivateParams(); } + })); - // Initialize quotient - var m = a.length - b.length; - var q; + return new PrivateKey(packetlist); +} - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } +/** + * Reads an (optionally armored) OpenPGP key and returns a key object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { + throw new Error('Armored text not of type key'); } + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]); + return createKey(firstKeyPacketList); +} - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); +/** + * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readPrivateKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.privateKey)) { + throw new Error('Armored text not of type private key'); } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; } + const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + return new PrivateKey(firstPrivateKeyList); + } + throw new Error('No secret key packet found'); +} - return { - div: q || null, - mod: a - }; - }; +/** + * Reads an (optionally armored) OpenPGP key block and returns a list of key objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { + throw new Error('Armored text not of type key'); + } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + for (let i = 0; i < keyIndex.length; i++) { + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = createKey(oneKeyList); + keys.push(newKey); + } + return keys; +} - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; +/** + * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readPrivateKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); + } + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.privateKey) { + throw new Error('Armored text not of type private key'); } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = new PrivateKey(oneKeyList); + keys.push(newKey); + } + if (keys.length === 0) { + throw new Error('No secret key packet found'); + } + return keys; +} - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - return { - div: div, - mod: mod - }; - } +// A Message can contain the following packets +const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + AEADEncryptedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket +]); +// A SKESK packet can contain the following packets +const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); +// A detached signature can contain the following packets +const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); +/** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ +class Message { + /** + * @param {PacketList} packetlist - The packets that form this message + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } - if (mode !== 'mod') { - div = res.div.neg(); - } + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns {Array} Array of keyID objects. + */ + getEncryptionKeyIDs() { + const keyIDs = []; + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + pkESKeyPacketlist.forEach(function(packet) { + keyIDs.push(packet.publicKeyID); + }); + return keyIDs; + } - return { - div: div, - mod: res.mod - }; + /** + * Returns the key IDs of the keys that signed the message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const msg = this.unwrapCompressed(); + // search for one pass signatures + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); + if (onePassSigList.length > 0) { + return onePassSigList.map(packet => packet.issuerKeyID); } + // if nothing found look for signature packets + const signatureList = msg.packets.filterByTag(enums.packet.signature); + return signatureList.map(packet => packet.issuerKeyID); + } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Date} [date] - Use the given date for key verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with decrypted content. + * @async + */ + async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { + const symEncryptedPacketlist = this.packets.filterByTag( + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ); - return { - div: res.div, - mod: mod - }; + if (symEncryptedPacketlist.length === 0) { + throw new Error('No encrypted data found'); } - // Both numbers are positive at this point + const symEncryptedPacket = symEncryptedPacketlist[0]; + const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm; - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } + const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1); - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; + let exception = null; + const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { + if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) { + throw new Error('Invalid session key for decryption.'); } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; + try { + const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.decrypt(algo, data, config$1); + } catch (e) { + util.printDebugError(e); + exception = e; } + })); + // We don't await stream.cancel here because it only returns when the other copy is canceled too. + cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. + symEncryptedPacket.encrypted = null; + await decryptedPromise; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; + if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { + throw exception || new Error('Decryption failed.'); } - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } + const resultMsg = new Message(symEncryptedPacket.packets); + symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - return this.strip(); - }; + return resultMsg; + } - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable) + * @param {Date} [date] - Use the given date for key verification, instead of current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * @async + */ + async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) { + let decryptedSessionKeyPackets = []; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + let exception; + if (passwords) { + const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); + if (skeskPackets.length === 0) { + throw new Error('No symmetrically encrypted session key packet found.'); + } + await Promise.all(passwords.map(async function(password, i) { + let packets; + if (i) { + packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); + } else { + packets = skeskPackets; + } + await Promise.all(packets.map(async function(skeskPacket) { + try { + await skeskPacket.decrypt(password); + decryptedSessionKeyPackets.push(skeskPacket); + } catch (err) { + util.printDebugError(err); + if (err instanceof Argon2OutOfMemoryError) { + exception = err; + } + } + })); + })); + } else if (decryptionKeys) { + const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + if (pkeskPackets.length === 0) { + throw new Error('No public key encrypted session key packet found.'); + } + await Promise.all(pkeskPackets.map(async function(pkeskPacket) { + await Promise.all(decryptionKeys.map(async function(decryptionKey) { + let decryptionKeyPackets; + try { + // do not check key expiration to allow decryption of old messages + decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); + } catch (err) { + exception = err; + return; + } - var x = this; - var y = p.clone(); + let algos = [ + enums.symmetric.aes256, // Old OpenPGP.js default fallback + enums.symmetric.aes128, // RFC4880bis fallback + enums.symmetric.tripledes, // RFC4880 fallback + enums.symmetric.cast5 // Golang OpenPGP fallback + ]; + try { + const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere. + if (selfCertification.preferredSymmetricAlgorithms) { + algos = algos.concat(selfCertification.preferredSymmetricAlgorithms); + } + } catch (e) {} - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } + await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { + if (!decryptionKeyPacket.isDecrypted()) { + throw new Error('Decryption key is not decrypted.'); + } - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); + // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. + const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal + ); - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + if (doConstantTimeDecryption) { + // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, + // either with the successfully decrypted session key, or with a randomly generated one. + // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on + // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: + // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the + // randomly generated keys of the remaining key types. + // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly + // generated session keys. + // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. - var g = 0; + const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times + await Promise.all(( + expectedSymmetricAlgorithm ? + [expectedSymmetricAlgorithm] : + Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms) + ).map(async sessionKeyAlgorithm => { + const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); + pkeskPacketCopy.read(serialisedPKESK); + const randomSessionKey = { + sessionKeyAlgorithm, + sessionKey: mod$1.generateSessionKey(sessionKeyAlgorithm) + }; + try { + await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); + decryptedSessionKeyPackets.push(pkeskPacketCopy); + } catch (err) { + // `decrypt` can still throw some non-security-sensitive errors + util.printDebugError(err); + exception = err; + } + })); - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + } else { + try { + await pkeskPacket.decrypt(decryptionKeyPacket); + const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm; + if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) { + throw new Error('A non-preferred symmetric algorithm was used.'); + } + decryptedSessionKeyPackets.push(pkeskPacket); + } catch (err) { + util.printDebugError(err); + exception = err; + } + } + })); + })); + cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. + pkeskPacket.encrypted = null; + })); + } else { + throw new Error('No key or password specified.'); } - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); + if (decryptedSessionKeyPackets.length > 0) { + // Return only unique session keys + if (decryptedSessionKeyPackets.length > 1) { + const seen = new Set(); + decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { + const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); + if (seen.has(k)) { + return false; } - - C.iushrn(1); - D.iushrn(1); - } + seen.add(k); + return true; + }); } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } + return decryptedSessionKeyPackets.map(packet => ({ + data: packet.sessionKey, + algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm) + })); } + throw exception || new Error('Session key decryption failed.'); + } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); + /** + * Get literal data that is the body of the message + * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + */ + getLiteralData() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getBytes()) || null; + } - var a = this; - var b = p.clone(); + /** + * Get filename from literal data packet + * @returns {(String|null)} Filename of literal data packet as string. + */ + getFilename() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getFilename()) || null; + } - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + /** + * Get literal data as text + * @returns {(String|null)} Literal body of the message interpreted as text. + */ + getText() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + if (literal) { + return literal.getText(); } + return null; + } - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } + /** + * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. + * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for + * @param {Date} [date] - Date to select algorithm preferences at + * @param {Array} [userIDs] - User IDs to select algorithm preferences for + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. + * @async + */ + static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { + const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1); + const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo); + const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined; - x1.iushrn(1); + await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() + .catch(() => null) // ignore key strength requirements + .then(maybeKey => { + if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) && + !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted + throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } + }) + )); - x2.iushrn(1); - } - } + const sessionKeyData = mod$1.generateSessionKey(symmetricAlgo); + return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName }; + } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - Password(s) for message encryption + * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] + * @param {Date} [date] - Override the creation date of the literal package + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + if (sessionKey) { + if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { + throw new Error('Invalid session key for encryption.'); } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; + } else if (encryptionKeys && encryptionKeys.length) { + sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); + } else if (passwords && passwords.length) { + sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); + throw new Error('No keys, passwords, or session key provided.'); } - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; - a.isub(b); - } while (true); + const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); - return b.iushln(shift); - }; + const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({ + version: aeadAlgorithmName ? 2 : 1, + aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null + }); + symEncryptedPacket.packets = this.packets; - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + const algorithm = enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + msg.packets.push(symEncryptedPacket); + symEncryptedPacket.packets = new PacketList(); // remove packets after encryption + return msg; + } - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param {Uint8Array} sessionKey - session key for encryption + * @param {String} algorithmName - session key algorithm + * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - For message encryption + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [date] - Override the date + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + const packetlist = new PacketList(); + const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName); + const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; + if (encryptionKeys) { + const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { + const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } + const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({ + version: aeadAlgorithm ? 6 : 3, + encryptionKeyPacket: encryptionKey.keyPacket, + anonymousRecipient: wildcard, + sessionKey, + sessionKeyAlgorithm: symmetricAlgorithm + }); - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + await pkESKeyPacket.encrypt(encryptionKey.keyPacket); + delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption + return pkESKeyPacket; + })); + packetlist.push(...results); } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + if (passwords) { + const testDecrypt = async function(keyPacket, password) { + try { + await keyPacket.decrypt(password); + return 1; + } catch (e) { + return 0; + } + }; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + const sum = (accumulator, currentValue) => accumulator + currentValue; - this.strip(); + const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { + const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); + symEncryptedSessionKeyPacket.sessionKey = sessionKey; + symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; + if (aeadAlgorithm) { + symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; + } + await symEncryptedSessionKeyPacket.encrypt(password, config$1); - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + if (config$1.passwordCollisionCheck) { + const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); + if (results.reduce(sum) !== 1) { + return encryptPassword(sessionKey, algorithm, password); + } + } - assert(num <= 0x3ffffff, 'Number is too big'); + delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption + return symEncryptedSessionKeyPacket; + }; - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd))); + packetlist.push(...results); } - if (this.negative !== 0) return -res | 0; - return res; - }; - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; + return new Message(packetlist); + } - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; + /** + * Sign the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to add to the message + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with signed content. + * @async + */ + async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const packetlist = new PacketList(); - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; + const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well + const onePassSignaturePackets = signaturePackets.map( + (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0)) + .reverse(); // innermost OPS refers to the first signature packet - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; + packetlist.push(...onePassSignaturePackets); + packetlist.push(literalDataPacket); + packetlist.push(...signaturePackets); - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; + return new Message(packetlist); + } - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param {module:enums.compression} algo - compression algorithm + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Message} New message with compressed content. + */ + compress(algo, config$1 = config) { + if (algo === enums.compression.uncompressed) { + return this; + } - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + const compressed = new CompressedDataPacket(config$1); + compressed.algorithm = algo; + compressed.packets = this.packets; - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + const packetList = new PacketList(); + packetList.push(compressed); - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + return new Message(packetList); + } - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New detached signature of message content. + * @async + */ + async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); + } + return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config$1)); + } - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; + /** + * Verify message signatures + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signatures. + * @async + */ + async verify(verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + if (isArrayStream(msg.packets.stream)) { + msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + } + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); + const signatureList = msg.packets.filterByTag(enums.packet.signature); + if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { + await Promise.all(onePassSigList.map(async onePassSig => { + onePassSig.correspondingSig = new Promise((resolve, reject) => { + onePassSig.correspondingSigResolve = resolve; + onePassSig.correspondingSigReject = reject; + }); + onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); + onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); + onePassSig.hashed.catch(() => {}); + })); + msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { + const reader = getReader(readable); + const writer = getWriter(writable); + try { + for (let i = 0; i < onePassSigList.length; i++) { + const { value: signature } = await reader.read(); + onePassSigList[i].correspondingSigResolve(signature); + } + await reader.readToEnd(); + await writer.ready; + await writer.close(); + } catch (e) { + onePassSigList.forEach(onePassSig => { + onePassSig.correspondingSigReject(e); + }); + await writer.abort(e); + } + }); + return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + } + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); + } - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + /** + * Verify detached message signature + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Signature} signature + * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); + } - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; + /** + * Unwrap compressed message + * @returns {Message} Message Content of compressed message. + */ + unwrapCompressed() { + const compressed = this.packets.filterByTag(enums.packet.compressedData); + if (compressed.length) { + return new Message(compressed[0].packets); + } return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + } - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + /** + * Append signature to unencrypted message object + * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async appendSignature(detachedSignature, config$1 = config) { + await this.packets.read( + util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, + allowedDetachedSignaturePackets, + config$1 + ); + } - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + /** + * Returns binary encoded message + * @returns {ReadableStream} Binary message. + */ + write() { + return this.packets.write(); + } - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + /** + * Returns ASCII armored text of message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + const trailingPacket = this.packets[this.packets.length - 1]; + // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer. + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ? + trailingPacket.version !== 2 : + this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1); + } +} - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; +/** + * Create signature packets for the message + * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign + * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing + * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to append + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creationtime of the signature + * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures + * @param {Boolean} [detached] - Whether to create detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} List of signature packets. + * @async + * @private + */ +async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) { + const packetlist = new PacketList(); - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + // If data packet was created from Uint8Array, use binary, otherwise use text + const signatureType = literalDataPacket.text === null ? + enums.signature.binary : enums.signature.text; - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; + await Promise.all(signingKeys.map(async (primaryKey, i) => { + const signingUserID = signingUserIDs[i]; + if (!primaryKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1); + return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1); + })).then(signatureList => { + packetlist.push(...signatureList); + }); - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; + if (signature) { + const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + packetlist.push(...existingSigPacketlist); + } + return packetlist; +} - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; +/** + * Create object containing signer's keyID and validity of signature + * @param {SignaturePacket} signature - Signature packet + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Check signature validity with respect to the given date + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * keyID: module:type/keyid~KeyID, + * signature: Promise, + * verified: Promise + * }>} signer's keyID and validity of signature + * @async + * @private + */ +async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + let primaryKey; + let unverifiedSigningKey; - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + for (const key of verificationKeys) { + const issuerKeys = key.getKeys(signature.issuerKeyID); + if (issuerKeys.length > 0) { + primaryKey = key; + unverifiedSigningKey = issuerKeys[0]; + break; + } + } - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; + const isOnePassSignature = signature instanceof OnePassSignaturePacket; + const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + const verifiedSig = { + keyID: signature.issuerKeyID, + verified: (async () => { + if (!unverifiedSigningKey) { + throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + } - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); + await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); + const signaturePacket = await signaturePacketPromise; + if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { + throw new Error('Key is newer than the signature'); + } + // We pass the signature creation time to check whether the key was expired at the time of signing. + // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before + try { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); + } catch (e) { + // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, + // making the key invalid at the time of signing. + // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. + // Note: we do not support the edge case of a key that was reformatted and it has expired. + if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + } else { + throw e; + } + } + return true; + })(), + signature: (async () => { + const signaturePacket = await signaturePacketPromise; + const packetlist = new PacketList(); + signaturePacket && packetlist.push(signaturePacket); + return new Signature(packetlist); + })() }; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + // Mark potential promise rejections as "handled". This is needed because in + // some cases, we reject them before the user has a reasonable chance to + // handle them (e.g. `await readToEnd(result.data); await result.verified` and + // the data stream errors). + verifiedSig.signature.catch(() => {}); + verifiedSig.verified.catch(() => {}); - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + return verifiedSig; +} - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); +/** + * Create list of objects containing signer's keyID and validity of signature + * @param {Array} signatureList - Array of signature packets + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} date - Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) + * @async + * @private + */ +async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + return Promise.all(signatureList.filter(function(signature) { + return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); + }).map(async function(signature) { + return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); + })); +} - this.tmp = this._tmp(); +/** + * Reads an (optionally armored) OpenPGP message and returns a Message object + * @param {Object} options + * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed + * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New message object. + * @async + * @static + */ +async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredMessage || binaryMessage; + if (!input) { + throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { + throw new Error('readMessage: options.armoredMessage must be a string or stream'); } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; + if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { + throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } + const streamType = util.isStream(input); + if (armoredMessage) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.message) { + throw new Error('Armored text not of type message'); } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + input = data; } - inherits(P224, MPrime); + const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); + const message = new Message(packetlist); + message.fromStream = streamType; + return message; +} - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +/** + * Creates new message object from text or binary data. + * @param {Object} options + * @param {String | ReadableStream} [options.text] - The text message contents + * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents + * @param {String} [options.filename=""] - Name of the file (if any) + * @param {Date} [options.date=current date] - Date of the message, or modification date of the file + * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type + * @returns {Promise} New message object. + * @async + * @static + */ +async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { + const input = text !== undefined ? text : binary; + if (input === undefined) { + throw new Error('createMessage: must pass options object containing `text` or `binary`'); } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + if (text && !util.isString(text) && !util.isStream(text)) { + throw new Error('createMessage: options.text must be a string or stream'); } - inherits(P25519, MPrime); + if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { + throw new Error('createMessage: options.binary must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; + const streamType = util.isStream(input); + const literalDataPacket = new LiteralDataPacket(date); + if (text !== undefined) { + literalDataPacket.setText(input, enums.write(enums.literal, format)); + } else { + literalDataPacket.setBytes(input, enums.write(enums.literal, format)); + } + if (filename !== undefined) { + literalDataPacket.setFilename(filename); + } + const literalDataPacketlist = new PacketList(); + literalDataPacketlist.push(literalDataPacket); + const message = new Message(literalDataPacketlist); + message.fromStream = streamType; + return message; +} - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - return prime; - }; +// A Cleartext message can contain the following packets +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; +/** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ +class CleartextMessage { + /** + * @param {String} text - The cleartext of the signed message + * @param {Signature} signature - The detached signature or an empty signature for unsigned messages + */ + constructor(text, signature) { + // remove trailing whitespace and normalize EOL to canonical form + this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); + if (signature && !(signature instanceof Signature)) { + throw new Error('Invalid signature input'); } + this.signature = signature || new Signature(new PacketList()); } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const keyIDs = []; + const signatureList = this.signature.packets; + signatureList.forEach(function(packet) { + keyIDs.push(packet.issuerKeyID); + }); + return keyIDs; + } - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; + /** + * Sign the cleartext message + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] + * @param {Date} [date] - The creation time of the signature that should be created + * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New cleartext message with signed content. + * @async + */ + async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const literalDataPacket = new LiteralDataPacket(); + literalDataPacket.setText(this.text); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1)); + return new CleartextMessage(this.text, newSignature); + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; + /** + * Verify signatures of cleartext signed message + * @param {Array} keys - Array of keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verify(keys, date = new Date(), config$1 = config) { + const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + const literalDataPacket = new LiteralDataPacket(); + // we assume that cleartext signature is generated based on UTF8 cleartext + literalDataPacket.setText(this.text); + return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + } - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } + /** + * Get cleartext + * @returns {String} Cleartext of message. + */ + getText() { + // normalize end of line to \n + return this.text.replace(/\r\n/g, '\n'); + } - return this.m.sub(a)._forceRed(this); - }; + /** + * Returns ASCII armored text of cleartext signed message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {String | ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // emit header and checksum if one of the signatures has a version not 6 + const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6); + const hash = emitHeaderAndChecksum ? + Array.from(new Set(this.signature.packets.map( + packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase() + ))).join() : + null; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + const body = { + hash, + text: this.text, + data: this.signature.packets.write() + }; - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1); + } +} - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); +/** + * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param {Object} options + * @param {String} options.cleartextMessage - Text to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New cleartext message object. + * @async + * @static + */ +async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!cleartextMessage) { + throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); + } + if (!util.isString(cleartextMessage)) { + throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + const input = await unarmor(cleartextMessage); + if (input.type !== enums.armor.signed) { + throw new Error('No cleartext signed message.'); + } + const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1); + verifyHeaders(input.headers, packetlist); + const signature = new Signature(packetlist); + return new CleartextMessage(input.text, signature); +} - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); +/** + * Compare hash algorithm specified in the armor header with signatures + * @param {Array} headers - Armor headers + * @param {PacketList} packetlist - The packetlist with signature packets + * @private + */ +function verifyHeaders(headers, packetlist) { + const checkHashAlgos = function(hashAlgos) { + const check = packet => algo => packet.hashAlgorithm === algo; - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + for (let i = 0; i < packetlist.length; i++) { + if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { + return false; + } } - return res._forceRed(this); + return true; }; - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + const hashAlgos = []; + headers.forEach(header => { + const hashHeader = header.match(/^Hash: (.+)$/); // get header value + if (hashHeader) { + const parsedHashIDs = hashHeader[1] + .replace(/\s/g, '') // remove whitespace + .split(',') + .map(hashName => { + try { + return enums.write(enums.hash, hashName.toLowerCase()); + } catch (e) { + throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase()); + } + }); + hashAlgos.push(...parsedHashIDs); + } else { + throw new Error('Only "Hash" header allowed in cleartext signed message'); } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + }); - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { + throw new Error('Hash algorithm mismatch in armor header and signature'); + } +} - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; +/** + * Creates a new CleartextMessage object from text + * @param {Object} options + * @param {String} options.text + * @static + * @async + */ +async function createCleartextMessage({ text, ...rest }) { + if (!text) { + throw new Error('createCleartextMessage: must pass options object containing `text`'); + } + if (!util.isString(text)) { + throw new Error('createCleartextMessage: options.text must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + return new CleartextMessage(text); +} - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } +////////////////////// +// // +// Key handling // +// // +////////////////////// - return r; - }; - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. + * @param {Object} options + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys). + * Note: Curve448 and Curve25519 (new format) are not widely supported yet. + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys + * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys: + * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 + * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` + * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + if (!type && !curve) { + type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them) + curve = 'curve25519Legacy'; // unused with type != 'ecc' + } else { + type = type || 'ecc'; + curve = curve || 'curve25519Legacy'; + } + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); + if (userIDs.length === 0 && !config$1.v6Keys) { + throw new Error('UserIDs are required for V4 keys'); + } + if (type === 'rsa' && rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + } - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } + const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } + try { + const { key, revocationCertificate } = await generate(options, config$1); + key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } + return { + privateKey: formatObject(key, format, config$1), + publicKey: formatObject(key.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error generating keypair', err); + } +} - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } +/** + * Reformats signature packets for a key and rewraps key object. + * @param {Object} options + * @param {PrivateKey} options.privateKey - Private key to reformat + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended + * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) { + throw new Error('UserIDs are required for V4 keys'); + } + const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } + try { + const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); - return res; - }; + return { + privateKey: formatObject(reformattedKey, format, config$1), + publicKey: formatObject(reformattedKey.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error reformatting keypair', err); + } +} - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); +/** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. + * @param {Object} options + * @param {Key} options.key - Public or private key to revoke + * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with + * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation + * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation + * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The revoked key in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or + * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise + * @async + * @static + */ +async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - return r === num ? r.clone() : r; - }; + try { + const revokedKey = revocationCertificate ? + await key.applyRevocationCertificate(revocationCertificate, date, config$1) : + await key.revoke(reasonForRevocation, date, config$1); - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; + return revokedKey.isPrivate() ? { + privateKey: formatObject(revokedKey, format, config$1), + publicKey: formatObject(revokedKey.toPublic(), format, config$1) + } : { + privateKey: null, + publicKey: formatObject(revokedKey, format, config$1) + }; + } catch (err) { + throw util.wrapError('Error revoking key', err); + } +} - // - // Montgomery method engine - // +/** + * Unlock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to decrypt + * @param {String|Array} options.passphrase - The user's passphrase(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The unlocked key object. + * @async + */ +async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - BN.mont = function mont (num) { - return new Mont(num); - }; + if (!privateKey.isPrivate()) { + throw new Error('Cannot decrypt a public key'); + } + const clonedPrivateKey = privateKey.clone(true); + const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; - function Mont (m) { - Red.call(this, m); + try { + await Promise.all(clonedPrivateKey.getKeys().map(key => ( + // try to decrypt each key with any of the given passphrases + util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) + ))); - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + await clonedPrivateKey.validate(config$1); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error decrypting private key', err); + } +} - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); +/** + * Lock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to encrypt + * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The locked key object. + * @async + */ +async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); + if (!privateKey.isPrivate()) { + throw new Error('Cannot encrypt a public key'); } - inherits(Mont, Red); + const clonedPrivateKey = privateKey.clone(true); - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + const keys = clonedPrivateKey.getKeys(); + const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); + if (passphrases.length !== keys.length) { + throw new Error('Invalid number of passphrases given for key encryption'); + } - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + try { + await Promise.all(keys.map(async (key, i) => { + const { keyPacket } = key; + await keyPacket.encrypt(passphrases[i], config$1); + keyPacket.clearPrivateParams(); + })); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error encrypting private key', err); + } +} - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; +/////////////////////////////////////////// +// // +// Message encryption and decryption // +// // +/////////////////////////////////////////// - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - return res._forceRed(this); - }; +/** + * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` + * must be specified. If signing keys are specified, those will be used to sign the message. + * @param {Object} options + * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message + * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed + * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message + * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Signature} [options.signature] - A detached signature to add to the encrypted message + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` + * @param {Date} [options.date=current date] - Override the creation date of the message signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords); + signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations); + if (rest.detached) { + throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); + } + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + if (!signingKeys) { + signingKeys = []; + } - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + try { + if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified + message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1); } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(module, commonjsGlobal); -}); - -var bn$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': bn, - __moduleExports: bn -}); + message = message.compress( + await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), + config$1 + ); + message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + if (format === 'object') return message; + // serialize data + const armor = format === 'armored'; + const data = armor ? message.armor(config$1) : message.write(); + return await convertStream(data); + } catch (err) { + throw util.wrapError('Error encrypting message', err); + } +} /** - * @fileoverview - * BigInteger implementation of basic operations - * Wrapper of bn.js library (wwww.github.com/indutny/bn.js) - * @module biginteger/bn - * @private + * Decrypts a message with the user's private key, a session key or a password. + * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). + * @param {Object} options + * @param {Message} options.message - The message object with the encrypted data + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key + * @param {String|String[]} [options.passwords] - Passwords to decrypt the message + * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } + * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing decrypted and verified message in the form: + * + * { + * data: MaybeStream, (if format was 'utf8', the default) + * data: MaybeStream, (if format was 'binary') + * filename: String, + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static */ +async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); -/** - * @private - */ -class BigInteger$1 { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); + try { + const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); + if (!verificationKeys) { + verificationKeys = []; } - this.value = new bn(n); + const result = {}; + result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); + result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); + result.filename = decrypted.getFilename(); + linkStreams(result, message); + if (expectSigned) { + if (verificationKeys.length === 0) { + throw new Error('Verification keys are required to verify message signatures'); + } + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error decrypting message', err); } +} - clone() { - const clone = new BigInteger$1(null); - this.value.copy(clone.value); - return clone; - } - /** - * BigInteger increment in place - */ - iinc() { - this.value.iadd(new bn(1)); - return this; - } +////////////////////////////////////////// +// // +// Message signing and verification // +// // +////////////////////////////////////////// - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - /** - * BigInteger decrement in place - */ - idec() { - this.value.isub(new bn(1)); - return this; - } +/** + * Signs a message. + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed + * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext + * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [options.date=current date] - Override the creation date of the signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); checkOutputMessageFormat(format); + signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations); - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); + if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value.iadd(x.value); - return this; + if (!signingKeys || signingKeys.length === 0) { + throw new Error('No signing keys provided'); } - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + try { + let signature; + if (detached) { + signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } else { + signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } + if (format === 'object') return signature; - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value.isub(x.value); - return this; + const armor = format === 'armored'; + signature = armor ? signature.armor(config$1) : signature.write(); + if (detached) { + signature = transformPair(message.packets.write(), async (readable, writable) => { + await Promise.all([ + pipe(signature, writable), + readToEnd(readable).catch(() => {}) + ]); + }); + } + return await convertStream(signature); + } catch (err) { + throw util.wrapError('Error signing message', err); } +} - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } +/** + * Verifies signatures of cleartext signed message + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures + * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing verified message in the form: + * + * { + * data: MaybeStream, (if `message` was a CleartextMessage) + * data: MaybeStream, (if `message` was a Message) + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static + */ +async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value.imul(x.value); - return this; - } + if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); + if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); + try { + const result = {}; + if (signature) { + result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); + } else { + result.signatures = await message.verify(verificationKeys, date, config$1); + } + result.data = format === 'binary' ? message.getLiteralData() : message.getText(); + if (message.fromStream && !signature) linkStreams(result, message); + if (expectSigned) { + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error verifying signed message', err); } +} - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value = this.value.umod(m.value); - return this; - } - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } +/////////////////////////////////////////////// +// // +// Session key encryption and decryption // +// // +/////////////////////////////////////////////// - /** - * Compute modular exponentiation - * Much faster than this.exp(e).mod(n) - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - // We use either Montgomery or normal reduction context - // Montgomery requires coprime n and R (montogmery multiplier) - // bn.js picks R as power of 2, so n must be odd - const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value); - const x = this.clone(); - x.value = x.value.toRed(nred).redPow(e.value).fromRed(); - return x; - } +/** + * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. + * @param {Object} options + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} + * @param {Date} [options.date=current date] - Date to select algorithm preferences at + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. + * @async + * @static + */ +async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - // invm returns a wrong result if the inverse does not exist - if (!this.gcd(n).isOne()) { - throw new Error('Inverse does not exist'); - } - return new BigInteger$1(this.value.invm(n.value)); + try { + const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error generating session key', err); } +} - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} n - Operand - * @returns {BigInteger} gcd - */ - gcd(n) { - return new BigInteger$1(this.value.gcd(n.value)); - } +/** + * Encrypt a symmetric session key with public keys, passwords, or both at once. + * At least one of `encryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) + * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key + * @param {String|String[]} [options.passwords] - Passwords for the message + * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [options.date=current date] - Override the date + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value.ishln(x.value.toNumber()); - return this; + if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { + throw new Error('No encryption keys or passwords provided.'); } - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); + try { + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + return formatObject(message, format, config$1); + } catch (err) { + throw util.wrapError('Error encrypting session key', err); } +} - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value.ishrn(x.value.toNumber()); - return this; - } +/** + * Decrypt symmetric session keys using private keys or passwords (not both). + * One of `decryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Message} options.message - A message object containing the encrypted session key packets + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data + * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key + * @param {Date} [options.date] - Date to use for key verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: + * { data:Uint8Array, algorithm:String } + * @throws if no session key could be found or decrypted + * @async + * @static + */ +async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); + try { + const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error decrypting session keys', err); } +} - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value.eq(x.value); - } - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value.lt(x.value); - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value.lte(x.value); - } - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value.gt(x.value); +/** + * Input validation + * @private + */ +function checkString(data, name) { + if (!util.isString(data)) { + throw new Error('Parameter [' + (name) + '] must be of type String'); } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value.gte(x.value); +} +function checkBinary(data, name) { + if (!util.isUint8Array(data)) { + throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array'); } - - isZero() { - return this.value.isZero(); +} +function checkMessage(message) { + if (!(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message'); } - - isOne() { - return this.value.eq(new bn(1)); +} +function checkCleartextOrMessage(message) { + if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); } - - isNegative() { - return this.value.isNeg(); +} +function checkOutputMessageFormat(format) { + if (format !== 'armored' && format !== 'binary' && format !== 'object') { + throw new Error(`Unsupported format ${format}`); } - - isEven() { - return this.value.isEven(); +} +const defaultConfigPropsCount = Object.keys(config).length; +function checkConfig(config$1) { + const inputConfigProps = Object.keys(config$1); + if (inputConfigProps.length !== defaultConfigPropsCount) { + for (const inputProp of inputConfigProps) { + if (config[inputProp] === undefined) { + throw new Error(`Unknown config property: ${inputProp}`); + } + } } +} - abs() { - const res = this.clone(); - res.value = res.value.abs(); - return res; +/** + * Normalize parameter to an array if it is not undefined. + * @param {Object} param - the parameter to be normalized + * @returns {Array|undefined} The resulting array or undefined. + * @private + */ +function toArray(param) { + if (param && !util.isArray(param)) { + param = [param]; } + return param; +} - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); +/** + * Convert data to or from Stream + * @param {Object} data - the data to convert + * @returns {Promise} The data in the respective format. + * @async + * @private + */ +async function convertStream(data) { + const streamType = util.isStream(data); + if (streamType === 'array') { + return readToEnd(data); } + return data; +} - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - return this.value.toNumber(); - } +/** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param {Object} result - the data to convert + * @param {Message} message - message object + * @returns {Object} + * @private + */ +function linkStreams(result, message) { + result.data = transformPair(message.packets.stream, async (readable, writable) => { + await pipe(result.data, writable, { + preventClose: true + }); + const writer = getWriter(writable); + try { + // Forward errors in the message stream to result.data. + await readToEnd(readable, _ => _); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + }); +} - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - return this.value.testn(i) ? 1 : 0; +/** + * Convert the object to the given format + * @param {Key|Message} object + * @param {'armored'|'binary'|'object'} format + * @param {Object} config - Full configuration + * @returns {String|Uint8Array|Object} + */ +function formatObject(object, format, config) { + switch (format) { + case 'object': + return object; + case 'armored': + return object.armor(config); + case 'binary': + return object.write(); + default: + throw new Error(`Unsupported format ${format}`); } +} - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - return this.value.bitLength(); - } +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +// copied from utils +function isBytes$1(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes$1(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 +// See utils.ts for details. +// @ts-ignore +const crypto$1 = nc && typeof nc === 'object' && 'webcrypto' in nc + ? nc.webcrypto + : nc && typeof nc === 'object' && 'randomBytes' in nc + ? nc + : undefined; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$1(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes$1(data); + bytes(data); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$1(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto$1 && typeof crypto$1.randomBytes === 'function') { + return crypto$1.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - return this.value.byteLength(); - } +/** + * Polyfill for Safari 14 + */ +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +/** + * Choice: a ? b : c + */ +const Chi = (a, b, c) => (a & b) ^ (~a & c); +/** + * Majority function, true if any two inputs is true + */ +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - return this.value.toArrayLike(Uint8Array, endian, length); - } +// HMAC (RFC 2104) +class HMAC extends Hash { + constructor(hash$1, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash$1.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + * @example + * import { hmac } from '@noble/hashes/hmac'; + * import { sha256 } from '@noble/hashes/sha2'; + * const mac1 = hmac(sha256, 'key', 'message'); + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n$6 = /* @__PURE__ */ BigInt(0); +const _1n$8 = /* @__PURE__ */ BigInt(1); +const _2n$5 = /* @__PURE__ */ BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Is positive bigint +const isPosBig = (n) => typeof n === 'bigint' && _0n$6 <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +/** + * Asserts min <= n < max. NOTE: It's < max and not <= max. + * @example + * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) + */ +function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n$6; n >>= _1n$8, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n$8; +} +/** + * Sets single bit at position. + */ +function bitSet(n, pos, value) { + return n | ((value ? _1n$8 : _0n$6) << BigInt(pos)); +} +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n$5 << BigInt(n - 1)) - _1n$8; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +/** + * throws not implemented error + */ +const notImplemented = () => { + throw new Error('not implemented'); +}; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +function memoized(fn) { + const map = new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; } -var bn_interface = /*#__PURE__*/Object.freeze({ +var ut = /*#__PURE__*/Object.freeze({ __proto__: null, - 'default': BigInteger$1 + aInRange: aInRange, + abool: abool, + abytes: abytes, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + inRange: inRange, + isBytes: isBytes, + memoized: memoized, + notImplemented: notImplemented, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject }); -var utils_1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +// prettier-ignore +const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$4 = BigInt(2), _3n$2 = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n$1 = BigInt(8); +// prettier-ignore +BigInt(9); BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n$5 ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n$5 || power < _0n$5) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n$7) + return _0n$5; + let res = _1n$7; + while (power > _0n$5) { + if (power & _1n$7) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n$7; + } return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$5) { + res *= res; + res %= modulo; } - } - return res; + return res; } -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n$5 || modulo <= _0n$5) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n$5, u = _1n$7; + while (a !== _0n$5) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + // prettier-ignore + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$7) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n$7) / _2n$4; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n$7, S = 0; Q % _2n$4 === _0n$5; Q /= _2n$4, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n$4; Z < P && pow(Z, legendreC, P) !== P - _1n$7; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n$7) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n$7) / _2n$4; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n$7 << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n$2) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n$7) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n$1 === _5n) { + const c1 = (P - _5n) / _8n$1; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$4); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$4), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n$5) + throw new Error('Expected power > 0'); + if (power === _0n$5) + return f.ONE; + if (power === _1n$7) + return num; + let p = f.ONE; + let d = num; + while (power > _0n$5) { + if (power & _1n$7) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$7; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * NOTE: operations don't check 'isValid' for all elements for performance reasons, + * it is caller responsibility to check this. + * This is low-level code, please make sure you know what you doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$5) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$5, + ONE: _1n$7, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$5 <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n$5, + isOdd: (num) => (num & _1n$7) === _1n$7, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n$7) + _1n$7; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const _0n$4 = BigInt(0); +const _1n$6 = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$4) { + if (n & _1n$6) + p = p.add(d); + d = d.double(); + n >>= _1n$6; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$6; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c Curve Point constructor + * @param field field over CURVE.N - important that it's not over CURVE.P + * @param points array of L curve points + * @param scalars array of L scalars (aka private keys / bigints) + */ +function pippenger(c, field, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.ZERO; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); } -utils.zero2 = zero2; -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html + */ +const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 128) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 127; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n$3) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected assertion'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 128)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + abytes(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + return tlv.encode(0x30, seq); + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$3 = BigInt(0), _1n$5 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return inRange(num, _1n$5, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (isBytes(key)) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, N); // disabled by default, enabled for BLS + aInRange('private key', num, _1n$5, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // Memoized toAffine / validity check. They are heavy. Points are immutable. + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p) => { + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n$1); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + aInRange('scalar', sc, _0n$3, CURVE.n); + const I = Point.ZERO; + if (sc === _0n$3) + return I; + if (sc === _1n$5) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$3 || k2 > _0n$3) { + if (k1 & _1n$5) + k1p = k1p.add(d); + if (k2 & _1n$5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$5; + k2 >>= _1n$5; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange('scalar', scalar, _1n$5, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n$3 || a === _1n$5 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$5) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$5) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; } -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; -}); - -var utils_1$1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - - - - -utils.assert = minimalisticAssert; -utils.toArray = utils_1.toArray; -utils.zero2 = utils_1.zero2; -utils.toHex = utils_1.toHex; -utils.encode = utils_1.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; +function validateOpts$2(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +function weierstrass(curveDef) { + const CURVE = validateOpts$2(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n$5, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n$5) === _1n$5; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$5; + return number > HALF; } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + // slice bytes num + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange('r', this.r, _1n$5, CURVE_ORDER); // r in [1..N] + aInRange('s', this.s, _1n$5, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$3, ORDER_MASK); + // works with order, can have different size than numToField! + return numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n$3) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n$3) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$5); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; } -utils.getJSF = getJSF; -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), + randomBytes, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp$7 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A$4 = Fp$7.create(BigInt('-3')); +const CURVE_B$4 = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +const p256 = createCurve({ + a: CURVE_A$4, // Equation params: a, b + b: CURVE_B$4, + Fp: Fp$7, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp$6 = Field(P$1); +const CURVE_A$3 = Fp$6.create(BigInt('-3')); +// prettier-ignore +const CURVE_B$3 = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +const p384 = createCurve({ + a: CURVE_A$3, // Equation params: a, b + b: CURVE_B$3, + Fp: Fp$6, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp$5 = Field(P); +const CURVE = { + a: Fp$5.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp: Fp$5, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp: Fp$5, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n$2 = /* @__PURE__ */ BigInt(0); +const _1n$4 = /* @__PURE__ */ BigInt(1); +const _2n$3 = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n$2; + for (let j = 0; j < 7; j++) { + R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n$3) + t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts$1(curve) { + const opts = validateBasic(curve); + validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +function twistedEdwards(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n$1 }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + aInRange('coordinate ' + title, n, _0n$1, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n$1, y: _1n$3 }; + if (zz !== _1n$3) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n$3, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n$2 * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n$1) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n$2 * T2); + const D = modP(T1 * _2n$2 * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n$1) + return I; + if (this.equals(I) || n === _1n$3) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n$3) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('pointHex.y', y, _0n$1, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n$3); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n$3) === _1n$3; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n$1 && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n$1, _1n$3, _1n$3, _0n$1); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l + const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; } -utils.cachedProperty = cachedProperty; -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n = BigInt(0); +const _1n$2 = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n$2; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n$2; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n$2; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; } -utils.parseBytes = parseBytes; -function intFromLE(bytes) { - return new bn(bytes, 'hex', 'le'); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n$1, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n$1, P) * b2) % P; + const b223 = (pow2(b222, _1n$1, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; } -utils.intFromLE = intFromLE; +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp$4 = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp: Fp$4, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes$1(utf8ToBytes$1('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +/* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +(Fp$4.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +BigInt(156326); +// 1-d +BigInt('39082'); +// 1-2d +BigInt('78163'); +// √(-d) +BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp$3.eql(Fp$3.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp$3 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$3, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +BigInt(0); +secp256k1.ProjectivePoint; + +// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4 +// eslint-disable-next-line new-cap +const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377')); +const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9')); +const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'); +// prettier-ignore +const brainpoolP256r1 = createCurve({ + a: CURVE_A$2, // Equation params: a, b + b: CURVE_B$2, + Fp: Fp$2, + // Curve order (q), total count of valid points in the field + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + // Base (generator) point (x, y) + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), + lowS: false +}, sha256); + +// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6 +// eslint-disable-next-line new-cap +const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53')); +const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826')); +const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'); +// prettier-ignore +const brainpoolP384r1 = createCurve({ + a: CURVE_A$1, // Equation params: a, b + b: CURVE_B$1, + Fp: Fp$1, + // Curve order (q), total count of valid points in the field + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + // Base (generator) point (x, y) + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), + lowS: false +}, sha384); + +// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7 +// eslint-disable-next-line new-cap +const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3')); +const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca')); +const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'); +// prettier-ignore +const brainpoolP512r1 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, + // Curve order (q), total count of valid points in the field + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + // Base (generator) point (x, y) + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), + lowS: false +}, sha512); + +/** + * This file is needed to dynamic import the noble-curves. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleCurves = new Map(Object.entries({ + nistP256: p256, + nistP384: p384, + nistP521: p521, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, + secp256k1, + x448, + ed448 +})); + +var noble_curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleCurves: nobleCurves }); -var r$1; - -var brorand = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -var Rand_1 = Rand; +//Paul Tero, July 2001 +//http://www.tero.co.uk/des/ +// +//Optimised for performance with large blocks by Michael Hayworth, November 2001 +//http://www.netdealing.com +// +// Modified by Recurity Labs GmbH -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; +//THIS SOFTWARE IS PROVIDED "AS IS" AND +//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +//SUCH DAMAGE. -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); +//des +//this takes the key, the message, and whether to encrypt or decrypt - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; +function des(keys, message, encrypt, mode, iv, padding) { + //declaring this locally speeds things up a bit + const spfunction1 = [ + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, + 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, + 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, + 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ]; + const spfunction2 = [ + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, + -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, + -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, + -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, + 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, + -0x7fef7fe0, 0x108000 + ]; + const spfunction3 = [ + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, + 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, + 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, + 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ]; + const spfunction4 = [ + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, + 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, + 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ]; + const spfunction5 = [ + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, + 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, + 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, + 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, + 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, + 0x40080000, 0x2080100, 0x40000100 + ]; + const spfunction6 = [ + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, + 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, + 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, + 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ]; + const spfunction7 = [ + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, + 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, + 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, + 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ]; + const spfunction8 = [ + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, + 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, + 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, + 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ]; -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; + //create the 16 or 48 subkeys we will need + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let endloop; + let loopinc; + let len = message.length; - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; + //set up the loops for single and triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des + if (iterations === 3) { + looping = encrypt ? [0, 32, 2] : [30, -2, -2]; + } else { + looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto$2 = crypto$3; - if (typeof crypto$2.randomBytes !== 'function') - throw new Error('Not supported'); - Rand.prototype._rand = function _rand(n) { - return crypto$2.randomBytes(n); - }; - } catch (e) { + //pad the message depending on the padding parameter + //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt + if (encrypt) { + message = desAddPadding(message); + len = message.length; } -} -brorand.Rand = Rand_1; -var getNAF = utils_1$1.getNAF; -var getJSF = utils_1$1.getJSF; -var assert$2 = utils_1$1.assert; + //store the result here + let result = new Uint8Array(len); + let k = 0; -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); + //loop through each 64 bit chunk of the message + while (m < len) { + left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); + //first each 64 but chunk of the message must be permuted according to IP + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + //do this either 1 or 3 times for each chunk of the message + for (j = 0; j < iterations; j += 3) { + endloop = looping[j + 1]; + loopinc = looping[j + 2]; + //now go through and perform the encryption or decryption + for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency + right1 = right ^ keys[i]; + right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + //the result is attained by passing these bytes through the S selection functions + temp = left; + left = right; + right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> + 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & + 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); + } + temp = left; + left = right; + right = temp; //unreverse left and right + } //for either 1 or 3 iterations - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + //move then each one bit to the right + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -var base = BaseCurve; + //now perform IP-1, which is IP in the opposite direction + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; + result[k++] = (left >>> 24); + result[k++] = ((left >>> 16) & 0xff); + result[k++] = ((left >>> 8) & 0xff); + result[k++] = (left & 0xff); + result[k++] = (right >>> 24); + result[k++] = ((right >>> 16) & 0xff); + result[k++] = ((right >>> 8) & 0xff); + result[k++] = (right & 0xff); + } //for every 8 characters, or 64 bits in the message -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; + //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt + if (!encrypt) { + result = desRemovePadding(result); + } -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$2(p.precomputed); - var doubles = p._getDoubles(); + return result; +} //end of des - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } +//desCreateKeys +//this takes as input a 64 bit key (even though only 56 bits are used) +//as an array of 2 integers, and returns 16 48 bit keys - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; +function desCreateKeys(key) { + //declaring this locally speeds things up a bit + const pc2bytes0 = [ + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ]; + const pc2bytes1 = [ + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ]; + const pc2bytes2 = [ + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ]; + const pc2bytes3 = [ + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ]; + const pc2bytes4 = [ + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ]; + const pc2bytes5 = [ + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ]; + const pc2bytes6 = [ + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ]; + const pc2bytes7 = [ + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ]; + const pc2bytes8 = [ + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ]; + const pc2bytes9 = [ + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ]; + const pc2bytes10 = [ + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ]; + const pc2bytes11 = [ + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ]; + const pc2bytes12 = [ + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ]; + const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; + //how many iterations (1 for des, 3 for triple des) + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + //stores the return keys + const keys = new Array(32 * iterations); + //now define the left shifts which need to be done + const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + //other variables + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - // Get NAF form - var naf = getNAF(k, w); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 2) ^ right) & 0x33333333; + right ^= temp; + left ^= (temp << 2); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); + //the right side needs to be shifted and to get the last four bits of the left side + temp = (left << 8) | ((right >>> 20) & 0x000000f0); + //left needs to be put upside down + left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); + right = temp; - if (i < 0) - break; - var z = naf[i]; - assert$2(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; + //now go through and perform these shifts on the left and right keys + for (let i = 0; i < shifts.length; i++) { + //shift the keys either one or two bits to the left + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; + //now apply PC-2, in such a way that E is easier when encrypting or decrypting + //this conversion will look like PC-2 except only the last 6 bits of each byte are used + //rather than 48 consecutive bits and the order of lines will be according to + //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 + lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( + left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & + 0xf]; + righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | + pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]; + temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; + keys[n++] = lefttemp ^ temp; + keys[n++] = righttemp ^ (temp << 16); } + } //for each iterations + //return the keys we've created + return keys; +} //end of desCreateKeys - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; +function desAddPadding(message, padding) { + const padLength = 8 - (message.length % 8); - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } + let pad; + if ((padLength < 8)) { //pad the message out with null bytes + pad = 0; + } else if (padLength === 8) { + return message; + } else { + throw new Error('des: invalid padding'); } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { + paddedMessage[i] = message[i]; + } + for (let j = 0; j < padLength; j++) { + paddedMessage[message.length + j] = pad; + } - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; + return paddedMessage; +} - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); +function desRemovePadding(message, padding) { + let padLength = null; + let pad; + { // null padding + pad = 0; + } - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); + if (!padLength) { + padLength = 1; + while (message[message.length - padLength] === pad) { + padLength++; } + padLength--; } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; + return message.subarray(0, message.length - padLength); } -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert$2(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$2(bytes[bytes.length - 1] % 2 === 1); +// added by Recurity Labs - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); +function TripleDES(key) { + this.key = []; - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + for (let i = 0; i < 3; i++) { + this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - var precomputed = { - doubles: null, - naf: null, - beta: null + this.encrypt = function(block) { + return des( + desCreateKeys(this.key[2]), + des( + desCreateKeys(this.key[1]), + des( + desCreateKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true); }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; +} - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; +TripleDES.keySize = TripleDES.prototype.keySize = 24; +TripleDES.blockSize = TripleDES.prototype.blockSize = 8; -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; +// Copyright 2010 pjacobs@xeekr.com . All rights reserved. -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; +// Modified by Recurity Labs GmbH -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; +// fixed/modified by Herbert Hanewinkel, www.haneWIN.de +// check www.haneWIN.de for the latest version -var assert$3 = utils_1$1.assert; +// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. +// CAST-128 is a common OpenPGP cipher. -function ShortCurve(conf) { - base.call(this, 'short', conf); - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); +// CAST5 constructor - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; +function OpenPGPSymEncCAST5() { + this.BlockSize = 8; + this.KeySize = 16; - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, base); -var short_1 = ShortCurve; + this.setKey = function(key) { + this.masking = new Array(16); + this.rotate = new Array(16); -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + this.reset(); - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; + if (key.length === this.KeySize) { + this.keySchedule(key); } else { - lambda = lambdas[1]; - assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + throw new Error('CAST-128: keys must be 16 bytes'); } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis + return true; }; -}; -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + this.reset = function() { + for (let i = 0; i < 16; i++) { + this.masking[i] = 0; + this.rotate[i] = 0; } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; + }; -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + this.getBlockSize = function() { + return this.BlockSize; + }; - var x = point.x; - var y = point.y; + this.encrypt = function(src) { + const dst = new Array(src.length); - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; -function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >>> 16) & 255; + dst[i + 6] = (l >>> 8) & 255; + dst[i + 7] = l & 255; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + return dst; + }; - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + this.decrypt = function(src) { + const dst = new Array(src.length); - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >> 16) & 255; + dst[i + 6] = (l >> 8) & 255; + dst[i + 7] = l & 255; } - }; - return res; -}; -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + return dst; + }; + const scheduleA = new Array(4); -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; + scheduleA[0] = new Array(4); + scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; + scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; + scheduleA[1] = new Array(4); + scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + O = P - if (p.inf) - return this; + scheduleA[2] = new Array(4); + scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; + scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); + scheduleA[3] = new Array(4); + scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + const scheduleB = new Array(4); - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; + scheduleB[0] = new Array(4); + scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; + scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; + scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; + scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; + scheduleB[1] = new Array(4); + scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; + scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; + scheduleB[1][2] = [7, 6, 8, 9, 3]; + scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - var a = this.curve.a; + scheduleB[2] = new Array(4); + scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; + scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; + scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; + scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; + scheduleB[3] = new Array(4); + scheduleB[3][0] = [8, 9, 7, 6, 3]; + scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; + scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; + scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; + // changed 'in' to 'inn' (in javascript 'in' is a reserved word) + this.keySchedule = function(inn) { + const t = new Array(8); + const k = new Array(32); -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; + let j; -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; + for (let i = 0; i < 4; i++) { + j = i * 4; + t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + } -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; + const x = [6, 7, 4, 5]; + let ki = 0; + let w; -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { + for (j = 0; j < 4; j++) { + const a = scheduleA[round][j]; + w = t[a[1]]; -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; + w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; + w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; + w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; + w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; + w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; + t[a[0]] = w; + } -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + for (j = 0; j < 4; j++) { + const b = scheduleB[round][j]; + w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) + w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; + w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; + w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; + w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; + k[ki] = w; + ki++; + } } - }; - } - return res; -}; + } -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + for (let i = 0; i < 16; i++) { + this.masking[i] = k[i]; + this.rotate[i] = k[16 + i] & 0x1f; + } + }; - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; + // These are the three 'f' functions. See RFC 2144, section 2.2. -function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); + function f1(d, m, r) { + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - // P + O = P - if (p.isInfinity()) - return this; + function f2(d, m, r) { + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; + } - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); + function f3(d, m, r) { + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + const sBox = new Array(8); + sBox[0] = [ + 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, + 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, + 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, + 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, + 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, + 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, + 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, + 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, + 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, + 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, + 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, + 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, + 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, + 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, + 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, + 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, + 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, + 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, + 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, + 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, + 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, + 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, + 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, + 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, + 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, + 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, + 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, + 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, + 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, + 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, + 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ]; + + sBox[1] = [ + 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, + 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, + 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, + 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, + 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, + 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, + 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, + 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, + 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, + 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, + 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, + 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, + 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, + 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, + 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, + 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, + 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, + 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, + 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, + 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, + 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, + 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, + 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, + 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, + 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, + 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, + 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, + 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, + 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, + 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, + 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ]; - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); + sBox[2] = [ + 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, + 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, + 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, + 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, + 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, + 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, + 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, + 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, + 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, + 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, + 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, + 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, + 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, + 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, + 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, + 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, + 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, + 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, + 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, + 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, + 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, + 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, + 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, + 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, + 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, + 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, + 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, + 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, + 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, + 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, + 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ]; - return this.curve.jpoint(nx, ny, nz); -}; + sBox[3] = [ + 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, + 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, + 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, + 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, + 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, + 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, + 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, + 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, + 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, + 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, + 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, + 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, + 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, + 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, + 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, + 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, + 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, + 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, + 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, + 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, + 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, + 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, + 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, + 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, + 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, + 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, + 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, + 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, + 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, + 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, + 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ]; -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + sBox[4] = [ + 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, + 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, + 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, + 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, + 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, + 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, + 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, + 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, + 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, + 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, + 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, + 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, + 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, + 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, + 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, + 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, + 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, + 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, + 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, + 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, + 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, + 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, + 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, + 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, + 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, + 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, + 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, + 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, + 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, + 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, + 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ]; - // P + O = P - if (p.isInfinity()) - return this; + sBox[5] = [ + 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, + 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, + 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, + 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, + 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, + 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, + 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, + 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, + 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, + 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, + 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, + 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, + 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, + 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, + 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, + 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, + 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, + 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, + 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, + 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, + 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, + 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, + 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, + 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, + 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, + 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, + 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, + 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, + 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, + 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, + 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ]; - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } + sBox[6] = [ + 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, + 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, + 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, + 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, + 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, + 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, + 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, + 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, + 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, + 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, + 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, + 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, + 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, + 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, + 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, + 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, + 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, + 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, + 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, + 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, + 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, + 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, + 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, + 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, + 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, + 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, + 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, + 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, + 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, + 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, + 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ]; - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + sBox[7] = [ + 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, + 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, + 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, + 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, + 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, + 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, + 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, + 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, + 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, + 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, + 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, + 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, + 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, + 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, + 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, + 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, + 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, + 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, + 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, + 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, + 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, + 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, + 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, + 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, + 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, + 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, + 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, + 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, + 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, + 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, + 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ]; +} - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); +function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); + this.cast5.setKey(key); - return this.curve.jpoint(nx, ny, nz); -}; + this.encrypt = function(block) { + return this.cast5.encrypt(block); + }; +} -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); +CAST5.blockSize = CAST5.prototype.blockSize = 8; +CAST5.keySize = CAST5.prototype.keySize = 16; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } +/* eslint-disable no-mixed-operators, no-fallthrough */ - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); +/* Modified by Recurity Labs GmbH + * + * Cipher.js + * A block-cipher algorithm implementation on JavaScript + * See Cipher.readme.txt for further information. + * + * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] + * This script file is distributed under the LGPL + * + * ACKNOWLEDGMENT + * + * The main subroutines are written by Michiel van Everdingen. + * + * Michiel van Everdingen + * http://home.versatel.nl/MAvanEverdingen/index.html + * + * All rights for these routines are reserved to Michiel van Everdingen. + * + */ - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//Math +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); +const MAXINT = 0xFFFFFFFF; - jx = nx; - jz = nz; - jyd = dny; - } +function rotw(w, n) { + return (w << n | w >>> (32 - n)) & MAXINT; +} - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; +function getW(a, i) { + return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +} -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; +function setW(a, i, w) { + a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +} - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; +function getB(x, n) { + return (x >>> (n * 8)) & 0xFF; +} -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Twofish +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; +function createTwofish() { + // + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; + // var dataLength = -1; + // var idx2 = -1; + // -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + let tfsKey = []; + let tfsM = [ + [], + [], + [], + [] + ]; - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + function tfsInit(key) { + keyBytes = key; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + const q0 = [ + [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], + [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] + ]; + const q1 = [ + [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], + [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] + ]; + const q2 = [ + [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], + [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] + ]; + const q3 = [ + [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], + [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] + ]; + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ + [], + [] + ]; + const m = [ + [], + [], + [], + [] + ]; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + function ffm5b(x) { + return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + } - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); + function ffmEf(x) { + return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + } - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); + function mdsRem(p, q) { + let i; + let t; + let u; + for (i = 0; i < 8; i++) { + t = q >>> 24; + q = ((q << 8) & MAXINT) | p >>> 24; + p = (p << 8) & MAXINT; + u = t << 1; + if (t & 128) { + u ^= 333; + } + q ^= t ^ (u << 16); + u ^= t >>> 1; + if (t & 1) { + u ^= 166; + } + q ^= u << 24 | u << 8; + } + return q; + } - return this.curve.jpoint(nx, ny, nz); -}; + function qp(n, x) { + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; + return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; + } -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; + function hFun(x, key) { + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); + switch (kLen) { + case 4: + a = q[1][a] ^ getB(key[3], 0); + b = q[0][b] ^ getB(key[3], 1); + c = q[0][c] ^ getB(key[3], 2); + d = q[1][d] ^ getB(key[3], 3); + case 3: + a = q[1][a] ^ getB(key[2], 0); + b = q[1][b] ^ getB(key[2], 1); + c = q[0][c] ^ getB(key[2], 2); + d = q[0][d] ^ getB(key[2], 3); + case 2: + a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); + b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); + c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); + d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); + } + return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; + } -JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); + keyBytes = keyBytes.slice(0, 32); + i = keyBytes.length; + while (i !== 16 && i !== 24 && i !== 32) { + keyBytes[i++] = 0; + } - return this.curve._wnafMul(this, k); -}; + for (i = 0; i < keyBytes.length; i += 4) { + inKey[i >> 2] = getW(keyBytes, i); + } + for (i = 0; i < 256; i++) { + q[0][i] = qp(0, i); + q[1][i] = qp(1, i); + } + for (i = 0; i < 256; i++) { + f01 = q[1][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + f01 = q[0][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + kLen = inKey.length / 2; + for (i = 0; i < kLen; i++) { + a = inKey[i + i]; + meKey[i] = a; + b = inKey[i + i + 1]; + moKey[i] = b; + sKey[kLen - i - 1] = mdsRem(a, b); + } + for (i = 0; i < 40; i += 2) { + a = 0x1010101 * i; + b = a + 0x1010101; + a = hFun(a, meKey); + b = rotw(hFun(b, moKey), 8); + tfsKey[i] = (a + b) & MAXINT; + tfsKey[i + 1] = rotw(a + 2 * b, 9); + } + for (i = 0; i < 256; i++) { + a = b = c = d = i; + switch (kLen) { + case 4: + a = q[1][a] ^ getB(sKey[3], 0); + b = q[0][b] ^ getB(sKey[3], 1); + c = q[0][c] ^ getB(sKey[3], 2); + d = q[1][d] ^ getB(sKey[3], 3); + case 3: + a = q[1][a] ^ getB(sKey[2], 0); + b = q[1][b] ^ getB(sKey[2], 1); + c = q[0][c] ^ getB(sKey[2], 2); + d = q[0][d] ^ getB(sKey[2], 3); + case 2: + tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; + tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; + tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; + tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + } + } + } - if (this === p) - return true; + function tfsG0(x) { + return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; + } - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; + function tfsG1(x) { + return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; + } - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; + function tfsFrnd(r, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); + blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); + blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + } -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; + function tfsIrnd(i, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; + blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; + blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + } - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; + function tfsClose() { + tfsKey = []; + tfsM = [ + [], + [], + [], + [] + ]; + } - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; + function tfsEncrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { + tfsFrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); + dataOffset += 16; + return dataBytes; } -}; -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + function tfsDecrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { + tfsIrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); + dataOffset += 16; + } -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; + // added by Recurity Labs -function MontCurve(conf) { - base.call(this, 'mont', conf); + function tfsFinal() { + return dataBytes; + } - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - // Note: this implementation is according to the original paper - // by P. Montgomery, NOT the one by D. J. Bernstein. - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + return { + name: 'twofish', + blocksize: 128 / 8, + open: tfsInit, + close: tfsClose, + encrypt: tfsEncrypt, + decrypt: tfsDecrypt, + // added by Recurity Labs + finalize: tfsFinal + }; } -inherits(MontCurve, base); -var mont = MontCurve; -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); +// added by Recurity Labs - return y.redSqr().cmp(rhs) === 0; -}; +function TF(key) { + this.tf = createTwofish(); + this.tf.open(Array.from(key), 0); -function Point$1(curve, x, z) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } + this.encrypt = function(block) { + return this.tf.encrypt(Array.from(block), 0); + }; } -inherits(Point$1, base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - var bytes = utils_1$1.toArray(bytes, enc); - - // TODO Curve448 - // Montgomery curve points must be represented in the compressed format - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (bytes.length === 33 && bytes[0] === 0x40) - bytes = bytes.slice(1, 33).reverse(); // point must be little-endian - if (bytes.length !== 32) - throw new Error('Unknown point compression format'); - return this.point(bytes, 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); -}; - -Point$1.prototype.precompute = function precompute() { - // No-op -}; - -Point$1.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - - // Note: the output should always be little-endian - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (compact) { - return [ 0x40 ].concat(this.getX().toArray('le', len)); - } else { - return this.getX().toArray('be', len); - } -}; - -Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); -}; - -Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; -Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; +TF.keySize = TF.prototype.keySize = 32; +TF.blockSize = TF.prototype.blockSize = 16; -Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; +/* Modified by Recurity Labs GmbH + * + * Originally written by nklein software (nklein.com) + */ -Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; +/* + * Javascript implementation based on Bruce Schneier's reference implementation. + * + * + * The constructor doesn't do much of anything. It's just here + * so we can start defining properties and methods and such. + */ +function Blowfish() {} -Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; +/* + * Declare the block size so that protocols know what size + * Initialization Vector (IV) they will need. + */ +Blowfish.prototype.BLOCKSIZE = 8; -Point$1.prototype.mul = function mul(k) { - k = new bn(k, 16); +/* + * These are the default SBOXES. + */ +Blowfish.prototype.SBOXES = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] +]; - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q +//* +//* This is the default PARRAY +//* +Blowfish.prototype.PARRAY = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b +]; - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); +//* +//* This is the number of rounds the cipher will go +//* +Blowfish.prototype.NN = 16; - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } +//* +//* This function is needed to get rid of problems +//* with the high-bit getting set. If we don't do +//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not +//* equal to ( bb & 0x00FFFFFFFF ) even when they +//* agree bit-for-bit for the first 32 bits. +//* +Blowfish.prototype._clean = function(xx) { + if (xx < 0) { + const yy = xx & 0x7FFFFFFF; + xx = yy + 0x80000000; } - return b; -}; - -Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); + return xx; }; -var assert$4 = utils_1$1.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - base.call(this, 'edwards', conf); - - this.a = new bn(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); +//* +//* This is the mixing function that uses the sboxes +//* +Blowfish.prototype._F = function(xx) { + let yy; - assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, base); -var edwards = EdwardsCurve; + const dd = xx & 0x00FF; + xx >>>= 8; + const cc = xx & 0x00FF; + xx >>>= 8; + const bb = xx & 0x00FF; + xx >>>= 8; + const aa = xx & 0x00FF; -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; + yy = this.sboxes[0][aa] + this.sboxes[1][bb]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); + return yy; }; -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; +//* +//* This method takes an array with two values, left and right +//* and does NN rounds of Blowfish on them. +//* +Blowfish.prototype._encryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); + let ii; - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + for (ii = 0; ii < this.NN; ++ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; - return this.point(x, y); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new bn(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); +//* +//* This method takes a vector of numbers and turns them +//* into long words so that they can be processed by the +//* real algorithm. +//* +//* Maybe I should make the real algorithm above take a vector +//* instead. That will involve more looping, but it won't require +//* the F() method to deconstruct the vector. +//* +Blowfish.prototype.encryptBlock = function(vector) { + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); + vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); } - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + this._encryptBlock(vals); - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + const ret = []; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); + ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); + // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); + // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + } - return this.point(x, y); + return ret; }; -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; +//* +//* This method takes an array with two values, left and right +//* and undoes NN rounds of Blowfish on them. +//* +Blowfish.prototype._decryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; -function Point$2(curve, x, y, z, t) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point$2, base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$2.fromJSON(this, obj); -}; + let ii; -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point$2(this, x, y, z, t); -}; + for (ii = this.NN + 1; ii > 1; --ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; -Point$2.fromJSON = function fromJSON(curve, obj) { - return new Point$2(curve, obj[0], obj[1], obj[2]); -}; + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } -Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; -Point$2.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; -Point$2.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; +//* +//* This method takes a key array and initializes the +//* sboxes and parray for this encryption. +//* +Blowfish.prototype.init = function(key) { + let ii; + let jj = 0; -Point$2.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); + this.parray = []; + for (ii = 0; ii < this.NN + 2; ++ii) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { + data = (data << 8) | (key[jj] & 0x00FF); + if (++jj >= key.length) { + jj = 0; + } } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point$2.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); + this.parray[ii] = this.PARRAY[ii] ^ data; } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; + this.sboxes = []; + for (ii = 0; ii < 4; ++ii) { + this.sboxes[ii] = []; + for (jj = 0; jj < 256; ++jj) { + this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + } + } -Point$2.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; + const vals = [0x00000000, 0x00000000]; -Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; + for (ii = 0; ii < this.NN + 2; ii += 2) { + this._encryptBlock(vals); + this.parray[ii + 0] = vals[0]; + this.parray[ii + 1] = vals[1]; + } -Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + for (ii = 0; ii < 4; ++ii) { + for (jj = 0; jj < 256; jj += 2) { + this._encryptBlock(vals); + this.sboxes[ii][jj + 0] = vals[0]; + this.sboxes[ii][jj + 1] = vals[1]; + } + } }; -Point$2.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; +// added by Recurity Labs +function BF(key) { + this.bf = new Blowfish(); + this.bf.init(key); -Point$2.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; + this.encrypt = function(block) { + return this.bf.encryptBlock(block); + }; +} -Point$2.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; +BF.keySize = BF.prototype.keySize = 16; +BF.blockSize = BF.prototype.blockSize = 8; -Point$2.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; +/** + * This file is needed to dynamic import the legacy ciphers. + * Separate dynamic imports are not convenient as they result in multiple chunks. + */ -Point$2.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; -Point$2.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; +const legacyCiphers = new Map([ + [enums.symmetric.tripledes, TripleDES], + [enums.symmetric.cast5, CAST5], + [enums.symmetric.blowfish, BF], + [enums.symmetric.twofish, TF] +]); - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; +var legacy_ciphers = /*#__PURE__*/Object.freeze({ + __proto__: null, + legacyCiphers: legacyCiphers +}); - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends HashMD { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + R_BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); -// Compatibility with BaseCurve -Point$2.prototype.toP = Point$2.prototype.normalize; -Point$2.prototype.mixedAdd = Point$2.prototype.add; +/** + * This file is needed to dynamic import the noble-hashes. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ -var curve_1 = createCommonjsModule(function (module, exports) { -var curve = exports; +const nobleHashes = new Map(Object.entries({ + sha1, + sha224, + sha256, + sha384, + sha512, + sha3_256, + sha3_512, + ripemd160 +})); -curve.base = base; -curve.short = short_1; -curve.mont = mont; -curve.edwards = edwards; +var noble_hashes = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleHashes: nobleHashes }); -var rotl32$2 = utils.rotl32; -var sum32$3 = utils.sum32; -var sum32_5$2 = utils.sum32_5; -var ft_1$1 = common$1.ft_1; -var BlockHash$4 = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; +// Adapted from the reference implementation in RFC7693 +// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); +// Uint64 values are represented using two Uint32s, stored as little endian +// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays +// need to be manually handled - BlockHash$4.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); +// 64-bit unsigned addition (little endian, in place) +// Sets a[i,i+1] += b[j,j+1] +// `a` and `b` must be Uint32Array(2) +function ADD64 (a, i, b, j) { + a[i] += b[j]; + a[i+1] += b[j+1] + (a[i] < b[j]); // add carry } -utils.inherits(SHA1, BlockHash$4); -var _1 = SHA1; +// Increment 64-bit little-endian unsigned value by `c` (in place) +// `a` must be Uint32Array(2) +function INC64 (a, c) { + a[0] += c; + a[1] += (a[0] < c); +} -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; +// G Mixing function +// The ROTRs are inlined for speed +function G$1 (v, m, a, b, c, d, ix, iy) { + ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1] + ADD64(v, a, m, ix); // v[a, a+1] += x ... x0 -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + ADD64(v, c, v, d); - for(; i < W.length; i++) - W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor0 >>> 24) ^ (xor1 << 8); + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; + ADD64(v, a, v, b); + ADD64(v, a, m, iy); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$2(b, 30); - b = a; - a = t; - } + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = (xor0 >>> 16) ^ (xor1 << 16); + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); - this.h[0] = sum32$3(this.h[0], a); - this.h[1] = sum32$3(this.h[1], b); - this.h[2] = sum32$3(this.h[2], c); - this.h[3] = sum32$3(this.h[3], d); - this.h[4] = sum32$3(this.h[4], e); -}; + ADD64(v, c, v, d); -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor1 >>> 31) ^ (xor0 << 1); + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); +} -var sha1 = _1; -var sha224 = _224; -var sha256 = _256; -var sha384 = _384; -var sha512 = _512; - -var sha = { - sha1: sha1, - sha224: sha224, - sha256: sha256, - sha384: sha384, - sha512: sha512 -}; +// Initialization Vector +const BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]); -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -var hmac = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; +// These are offsets into a Uint64 buffer. +// Multiply them all by 2 to make them offsets into a Uint32 buffer +const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +].map(x => x * 2)); + +// Compression function. 'last' flag indicates last block. +// Note: we're representing 16 uint64s as 32 uint32s +function compress(S, last) { + const v = new Uint32Array(32); + const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32); + + // init work variables + for (let i = 0; i < 16; i++) { + v[i] = S.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + + // low 64 bits of offset + v[24] ^= S.t0[0]; + v[25] ^= S.t0[1]; + // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1 + + // if last block + const f0 = last ? 0xFFFFFFFF : 0; + v[28] ^= f0; + v[29] ^= f0; + + // twelve rounds of mixing + for (let i = 0; i < 12; i++) { + // ROUND(r) + const i16 = i << 4; + G$1(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1]); + G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]); + G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]); + G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]); + G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]); + G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]); + G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]); + G$1(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15]); + } + + for (let i = 0; i < 16; i++) { + S.h[i] ^= v[i] ^ v[i + 16]; + } +} + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +class Blake2b { + constructor(outlen, key, salt, personal) { + const params = new Uint8Array(64); + // 0: outlen, keylen, fanout, depth + // 4: leaf length, sequential mode + // 8: node offset + // 12: node offset + // 16: node depth, inner length, rfu + // 20: rfu + // 24: rfu + // 28: rfu + // 32: salt + // 36: salt + // 40: salt + // 44: salt + // 48: personal + // 52: personal + // 56: personal + // 60: personal + + // init internal state + this.S = { + b: new Uint8Array(BLOCKBYTES), + h: new Uint32Array(OUTBYTES_MAX / 4), + t0: new Uint32Array(2), // input counter `t`, lower 64-bits only + c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES` + outlen // output length in bytes + }; -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; + // init parameter block + params[0] = outlen; + if (key) params[1] = key.length; + params[2] = 1; // fanout + params[3] = 1; // depth + if (salt) params.set(salt, 32); + if (personal) params.set(personal, 48); + const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT); -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; + // initialize hash state + for (let i = 0; i < 16; i++) { + this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i]; + } -var hash_1 = createCommonjsModule(function (module, exports) { -var hash = exports; - -hash.utils = utils; -hash.common = common; -hash.sha = sha; -hash.ripemd = ripemd; -hash.hmac = hmac; - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; -}); + // key the hash, if applicable + if (key) { + const block = new Uint8Array(BLOCKBYTES); + block.set(key); + this.update(block); + } + } -var secp256k1 = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] + // Updates a BLAKE2b streaming hash + // Requires Uint8Array (byte array) + update(input) { + if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer') + // for (let i = 0; i < input.length; i++) { + // if (this.S.c === BLOCKBYTES) { // buffer full + // INC64(this.S.t0, this.S.c) // add counters + // compress(this.S, false) + // this.S.c = 0 // empty buffer + // } + // this.S.b[this.S.c++] = input[i] + // } + let i = 0; + while(i < input.length) { + if (this.S.c === BLOCKBYTES) { // buffer full + INC64(this.S.t0, this.S.c); // add counters + compress(this.S, false); + this.S.c = 0; // empty buffer + } + let left = BLOCKBYTES - this.S.c; + this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds + const fill = Math.min(left, input.length - i); + this.S.c += fill; + i += fill; + } + return this } -}; -var curves_1 = createCommonjsModule(function (module, exports) { + /** + * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one + * @param {Uint8Array} [prealloc] - optional preallocated buffer + * @returns {ArrayBuffer} message digest + */ + digest(prealloc) { + INC64(this.S.t0, this.S.c); // mark last block offset + + // final block, padded + this.S.b.fill(0, this.S.c); + this.S.c = BLOCKBYTES; + compress(this.S, true); + + const out = prealloc || new Uint8Array(this.S.outlen); + for (let i = 0; i < this.S.outlen; i++) { + // must be loaded individually since default Uint32 endianness is platform dependant + out[i] = this.S.h[i >> 2] >> (8 * (i & 3)); + } + this.S.h = null; // prevent calling `update` after `digest` + return out.buffer; + } +} -var curves = exports; +function createHash(outlen, key, salt, personal) { + if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`) + return new Blake2b(outlen, key, salt, personal) +} +const OUTBYTES_MAX = 64; +const BLOCKBYTES = 128; +const TYPE = 2; // Argon2id +const VERSION = 0x13; +const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1; +const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const SALTBYTES_MIN = 8; +const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const passwordBYTES_MIN = 8; +const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional) +const SECRETBYTES_MAX = 32; // key (optional) -var assert = utils_1$1.assert; +const ARGON2_BLOCK_SIZE = 1024; +const ARGON2_PREHASH_DIGEST_LENGTH = 64; -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve_1.short(options); - else if (options.type === 'edwards') - this.curve = new curve_1.edwards(options); - else if (options.type === 'mont') - this.curve = new curve_1.mont(options); - else throw new Error('Unknown curve type.'); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; +const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); +// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3]) +function LE32(buf, n, i) { + buf[i+0] = n; + buf[i+1] = n >> 8; + buf[i+2] = n >> 16; + buf[i+3] = n >> 24; + return buf; } -curves.PresetCurve = PresetCurve; -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); +/** + * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7]) + * @param {Uint8Array} buf + * @param {Number} n + * @param {Number} i + */ +function LE64(buf, n, i) { + if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported"); + // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations + // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps) + // so we manually extract each byte + let remainder = n; + for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER + buf[offset] = remainder; // implicit & 0xff + remainder = (remainder - buf[offset]) / 256; + } + return buf; } -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash_1.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); +/** + * Variable-Length Hash Function H' + * @param {Number} outlen - T + * @param {Uint8Array} X - value to hash + * @param {Uint8Array} res - output buffer, of length `outlength` or larger + */ +function H_(outlen, X, res) { + const V = new Uint8Array(64); // no need to keep around all V_i -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash_1.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); + const V1_in = new Uint8Array(4 + X.length); + LE32(V1_in, outlen, 0); + V1_in.set(X, 4); + if (outlen <= 64) { + // H'^T(A) = H^T(LE32(T)||A) + createHash(outlen).update(V1_in).digest(res); + return res + } -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash_1.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); + const r = Math.ceil(outlen / 32) - 2; -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash_1.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); + // Let V_i be a 64-byte block and W_i be its first 32 bytes. + // V_1 = H^(64)(LE32(T)||A) + // V_2 = H^(64)(V_1) + // ... + // V_r = H^(64)(V_{r-1}) + // V_{r+1} = H^(T-32*r)(V_{r}) + // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1} + for (let i = 0; i < r; i++) { + createHash(64).update(i === 0 ? V1_in : V).digest(V); + // store W_i in result buffer already + res.set(V.subarray(0, 32), i*32); + } + // V_{r+1} + const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest()); + res.set(V_r1, r*32); -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash_1.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); + return res; +} -// https://tools.ietf.org/html/rfc7748#section-4.1 -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '9' - ] -}); +// compute buf = xs ^ ys +function XOR(wasmContext, buf, xs, ys) { + wasmContext.fn.XOR( + buf.byteOffset, + xs.byteOffset, + ys.byteOffset, + ); + return buf +} -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); +/** + * @param {Uint8Array} X (read-only) + * @param {Uint8Array} Y (read-only) + * @param {Uint8Array} R - output buffer + * @returns + */ +function G(wasmContext, X, Y, R) { + wasmContext.fn.G( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} -// https://tools.ietf.org/html/rfc5639#section-3.4 -defineCurve('brainpoolP256r1', { - type: 'short', - prime: null, - p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377', - a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9', - b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6', - n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7', - hash: hash_1.sha256, // or 384, or 512 - gRed: false, - g: [ - '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262', - '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997' - ] -}); +function G2(wasmContext, X, Y, R) { + wasmContext.fn.G2( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values. +function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) { + // For each segment, we do the following. First, we compute the value Z as: + // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) ) + wasmContext.refs.prngTmp.fill(0); + const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8); + LE64(Z, pass, 0); + LE64(Z, lane, 8); + LE64(Z, slice, 16); + LE64(Z, m_, 24); + LE64(Z, totalPasses, 32); + LE64(Z, TYPE, 40); + + // Then we compute q/(128*SL) 1024-byte values + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ), + // ..., + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )), + for(let i = 1; i <= segmentLength; i++) { + // tmp.set(Z); // no need to re-copy + LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed + const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR ); + + // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2 + // NB: the first generated pair must be used for the first block of the segment, and so on. + // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset. + for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) { + yield g2.subarray(k, k+8); + } + } + return []; +} + +function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) { + const assertLength = (name, value, min, max) => { + if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); } + }; -// https://tools.ietf.org/html/rfc5639#section-3.6 -defineCurve('brainpoolP384r1', { - type: 'short', - prime: null, - p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' + - 'ACD3A729 901D1A71 87470013 3107EC53', - a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' + - '8AA5814A 503AD4EB 04A8C7DD 22CE2826', - b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' + - '7CB43902 95DBC994 3AB78696 FA504C11', - n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' + - 'CF3AB6AF 6B7FC310 3B883202 E9046565', - hash: hash_1.sha384, // or 512 - gRed: false, - g: [ - '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' + - 'E8E826E03436D646AAEF87B2E247D4AF1E', - '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' + - '280E4646217791811142820341263C5315' - ] -}); + if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version'); + assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX); + assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX); + assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX); + assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX); + // optional fields + ad && assertLength('associated data', ad, 0, ADBYTES_MAX); + secret && assertLength('secret', secret, 0, SECRETBYTES_MAX); -// https://tools.ietf.org/html/rfc5639#section-3.7 -defineCurve('brainpoolP512r1', { - type: 'short', - prime: null, - p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' + - '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3', - a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' + - '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA', - b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' + - '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723', - n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' + - '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069', - hash: hash_1.sha512, - gRed: false, - g: [ - '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' + - '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', - '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' + - '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892' - ] -}); + return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes }; +} -// https://en.bitcoin.it/wiki/Secp256k1 -var pre; -try { - pre = secp256k1; -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash_1.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], +const KB = 1024; +const WASM_PAGE_SIZE = 64 * KB; - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); -}); +function argon2id(params, { memory, instance: wasmInstance }) { + if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + const ctx = validateParams({ type: TYPE, version: VERSION, ...params }); - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports; + const wasmRefs = {}; + const wasmFn = {}; + wasmFn.G = wasmG; + wasmFn.G2 = wasmG2; + wasmFn.XOR = wasmXOR; - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p. + const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes)); + const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references + if (memory.buffer.byteLength < requiredMemory) { + const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE); + // If enough memory is available, the `memory.buffer` is internally detached and the reference updated. + // Otherwise, the operation fails, and the original memory can still be used. + memory.grow(missing); + } - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils_1.toArray(options.pers, options.persEnc || 'hex'); - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -var hmacDrbg = HmacDRBG; + let offset = 0; + // Init wasm memory needed in other functions + wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length; + wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length; + wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length; + wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length; + // Init wasm memory needed locally + const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT; + const wasmContext = { fn: wasmFn, refs: wasmRefs }; + const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length; + const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE); + const allocatedMemory = new Uint8Array(memory.buffer, 0, offset); + + // 1. Establish H_0 + const H0 = getH0(ctx); + + // 2. Allocate the memory as m' 1024-byte blocks + // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns. + const q = m_ / ctx.lanes; + const B = new Array(ctx.lanes).fill(null).map(() => new Array(q)); + const initBlock = (i, j) => { + B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE); + return B[i][j]; + }; -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + for (let i = 0; i < ctx.lanes; i++) { + // const LEi = LE0; // since p = 1 for us + const tmp = new Uint8Array(H0.length + 8); + // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0)); + // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + LE32(tmp, 1, H0.length); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1)); + } + + // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2 + // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes + // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc. + const SL = 4; // vertical slices + const segmentLength = q / SL; + for (let pass = 0; pass < ctx.passes; pass++) { + // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel + for (let sl = 0; sl < SL; sl++) { + const isDataIndependent = pass === 0 && sl <= 1; + for (let i = 0; i < ctx.lanes; i++) { // lane + // On the first slice of the first pass, blocks 0 and 1 are already filled + let segmentOffset = sl === 0 && pass === 0 ? 2 : 0; + // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory) + const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null; + for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) { + const j = sl * segmentLength + segmentOffset; + const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q] + + // we can assume the PRNG is never done + const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength); + const l = lz[0]; const z = lz[1]; + // for (let i = 0; i < p; i++ ) + // B[i][j] = G(B[i][j-1], B[l][z]) + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + if (pass === 0) initBlock(i, j); + G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]); + + // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one + if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]); + } + } + } + } + + // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column: + // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1] + const C = B[0][q-1]; + for(let i = 1; i < ctx.lanes; i++) { + XOR(wasmContext, C, C, B[i][q-1]); + } + + const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength)); + // clear memory since the module might be cached + allocatedMemory.fill(0); // clear sensitive contents + memory.grow(0); // allow deallocation + // 8. The output tag is computed as H'^T(C). + return tag; + +} + +function getH0(ctx) { + const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH); + const ZERO32 = new Uint8Array(4); + const params = new Uint8Array(24); + LE32(params, ctx.lanes, 0); + LE32(params, ctx.tagLength, 4); + LE32(params, ctx.memorySize, 8); + LE32(params, ctx.passes, 12); + LE32(params, ctx.version, 16); + LE32(params, ctx.type, 20); + + const toHash = [params]; + if (ctx.password) { + toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0)); + toHash.push(ctx.password); + } else { + toHash.push(ZERO32); // context.password.length + } - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; + if (ctx.salt) { + toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0)); + toHash.push(ctx.salt); + } else { + toHash.push(ZERO32); // context.salt.length } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; + if (ctx.secret) { + toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0)); + toHash.push(ctx.secret); + // todo clear secret? + } else { + toHash.push(ZERO32); // context.secret.length + } -HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); -}; + if (ctx.ad) { + toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0)); + toHash.push(ctx.ad); + } else { + toHash.push(ZERO32); // context.ad.length + } + H.update(concatArrays(toHash)); -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; + const outputBuffer = H.digest(); + return new Uint8Array(outputBuffer); +} - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; +function concatArrays(arrays) { + if (arrays.length === 1) return arrays[0]; + + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!(arrays[i] instanceof Uint8Array)) { + throw new Error('concatArrays: Data must be in the form of a Uint8Array'); + } -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; + totalLength += arrays[i].length; } - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach((element) => { + result.set(element, pos); + pos += element.length; + }); + + return result; +} - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); +let isSIMDSupported; +async function wasmLoader(memory, getSIMD, getNonSIMD) { + const importObject = { env: { memory } }; + if (isSIMDSupported === undefined) { + try { + const loaded = await getSIMD(importObject); + isSIMDSupported = true; + return loaded; + } catch(e) { + isSIMDSupported = false; + } + } - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; + const loader = isSIMDSupported ? getSIMD : getNonSIMD; + return loader(importObject); +} -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); +async function setupWasm(getSIMD, getNonSIMD) { + const memory = new WebAssembly.Memory({ + // in pages of 64KiB each + // these values need to be compatible with those declared when building in `build-wasm` + initial: 1040, // 65MB + maximum: 65536, // 4GB + }); + const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD); - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } + /** + * Argon2id hash function + * @callback computeHash + * @param {Object} params + * @param {Uint8Array} params.password - password + * @param {Uint8Array} params.salt - salt + * @param {Integer} params.parallelism + * @param {Integer} params.passes + * @param {Integer} params.memorySize - in kibibytes + * @param {Integer} params.tagLength - output tag length + * @param {Uint8Array} [params.ad] - associated data (optional) + * @param {Uint8Array} [params.secret] - secret data (optional) + * @return {Uint8Array} argon2id hash + */ + const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory }); - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } + return computeHash; +} - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); +function _loadWasmModule (sync, filepath, src, imports) { + function _instantiateOrCompile(source, imports, stream) { + var instantiateFunc = WebAssembly.instantiate; + var compileFunc = WebAssembly.compile; + + if (imports) { + return instantiateFunc(source, imports) + } else { + return compileFunc(source) + } } - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils_1.encode(res, enc); -}; + +var buf = null; + + +buf = Buffer.from(src, 'base64'); -var assert$5 = utils_1$1.assert; -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); + { + return _instantiateOrCompile(buf, imports) + } } -var key = KeyPair; -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; +function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QA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QAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)} - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; +function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwA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gAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)} -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; +const loadWasm = async () => setupWasm( + (instanceObject) => wasmSIMD(instanceObject), + (instanceObject) => wasmNonSIMD(instanceObject), +); - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; +var index$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: loadWasm +}); -// TODO: should not validate for X25519 -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); +/* +node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; +Copyright (C) 2012 Eli Skeggs - return { result: true, reason: null }; -}; +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. -KeyPair.prototype.getPublic = function getPublic(enc, compact) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. - if (!enc) - return this.pub; +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html - return this.pub.encode(enc, compact); -}; +Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; +Based on micro-bunzip by Rob Landley (rob@landley.net). -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new bn(key, enc || 16); - - // For Curve25519/Curve448 we have a specific procedure. - // TODO Curve448 - if (this.ec.curve.type === 'mont') { - var one = this.ec.curve.one; - var mask = one.ushln(255 - 3).sub(one).ushln(3); - this.priv = this.priv.or(one.ushln(255 - 1)); - this.priv = this.priv.and(mask); - } else - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; +var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); +// offset in bytes +var BitReader$1 = function(stream) { + this.stream = stream; + this.bitOffset = 0; + this.curByte = 0; + this.hasByte = false; }; -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); +BitReader$1.prototype._ensureByte = function() { + if (!this.hasByte) { + this.curByte = this.stream.readByte(); + this.hasByte = true; + } }; -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); +// reads bits from the buffer +BitReader$1.prototype.read = function(bits) { + var result = 0; + while (bits > 0) { + this._ensureByte(); + var remaining = 8 - this.bitOffset; + // if we're in a byte + if (bits >= remaining) { + result <<= remaining; + result |= BITMASK[remaining] & this.curByte; + this.hasByte = false; + this.bitOffset = 0; + bits -= remaining; + } else { + result <<= bits; + var shift = remaining - bits; + result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; + this.bitOffset += bits; + bits = 0; + } + } + return result; }; -KeyPair.prototype.inspect = function inspect() { - return ''; +// seek to an arbitrary point in the buffer (expressed in bits) +BitReader$1.prototype.seek = function(pos) { + var n_bit = pos % 8; + var n_byte = (pos - n_bit) / 8; + this.bitOffset = n_bit; + this.stream.seek(n_byte); + this.hasByte = false; }; -var assert$6 = utils_1$1.assert; - -function Signature$1(options, enc) { - if (options instanceof Signature$1) - return options; - - if (this._importDER(options, enc)) - return; +// reads 6 bytes worth of data using the read method +BitReader$1.prototype.pi = function() { + var buf = new Uint8Array(6), i; + for (i = 0; i < buf.length; i++) { + buf[i] = this.read(8); + } + return bufToHex(buf); +}; - assert$6(options.r && options.s, 'Signature without r or s'); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; +function bufToHex(buf) { + return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); } -var signature$1 = Signature$1; -function Position() { - this.place = 0; -} +var bitreader = BitReader$1; -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} +/* very simple input/output stream interface */ -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} +var Stream$1 = function() { +}; -Signature$1.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); +// input streams ////////////// +/** Returns the next byte, or -1 for EOF. */ +Stream$1.prototype.readByte = function() { + throw new Error("abstract method readByte() not implemented"); +}; +/** Attempts to fill the buffer; returns number of bytes read, or + * -1 for EOF. */ +Stream$1.prototype.read = function(buffer, bufOffset, length) { + var bytesRead = 0; + while (bytesRead < length) { + var c = this.readByte(); + if (c < 0) { // EOF + return (bytesRead===0) ? -1 : bytesRead; + } + buffer[bufOffset++] = c; + bytesRead++; } - - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - - return true; + return bytesRead; +}; +Stream$1.prototype.seek = function(new_pos) { + throw new Error("abstract method seek() not implemented"); }; -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; +// output streams /////////// +Stream$1.prototype.writeByte = function(_byte) { + throw new Error("abstract method readByte() not implemented"); +}; +Stream$1.prototype.write = function(buffer, bufOffset, length) { + var i; + for (i=0; i>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature$1.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); + return length; +}; +Stream$1.prototype.flush = function() { }; -var assert$7 = utils_1$1.assert; +var stream = Stream$1; +/* CRC32, used in Bzip2 implementation. + * This is a port of CRC32.java from the jbzip2 implementation at + * https://code.google.com/p/jbzip2 + * which is: + * Copyright (c) 2011 Matthew Francis + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * This JavaScript implementation is: + * Copyright (c) 2013 C. Scott Ananian + * with the same licensing terms as Matthew Francis' original implementation. + */ +var crc32 = (function() { + /** + * A static CRC lookup table + */ + var crc32Lookup = new Uint32Array([ + 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, + 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, + 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, + 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, + 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, + 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, + 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, + 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, + 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, + 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, + 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, + 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, + 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, + 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, + 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, + 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, + 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 + ]); -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); + var CRC32 = function() { + /** + * The current CRC + */ + var crc = 0xffffffff; - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options); + /** + * @return The current CRC + */ + this.getCRC = function() { + return (~crc) >>> 0; // return an unsigned value + }; - options = curves_1[options]; - } + /** + * Update the CRC with a single byte + * @param value The value to update the CRC with + */ + this.updateCRC = function(value) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + }; - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves_1.PresetCurve) - options = { curve: options }; + /** + * Update the CRC with a sequence of identical bytes + * @param value The value to update the CRC with + * @param count The number of bytes + */ + this.updateCRCRun = function(value, count) { + while (count-- > 0) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + } + }; + }; + return CRC32; +})(); - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; +/* +seek-bzip - a pure-javascript module for seeking within bzip2 data - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); +Copyright (C) 2013 C. Scott Ananian +Copyright (C) 2012 Eli Skeggs +Copyright (C) 2011 Kevin Kwok - // Hash function for DRBG - this.hash = options.hash || options.curve.hash; -} -var ec = EC; +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. -EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); -}; +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); -}; +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); -}; +Adapted from node-bzip, copyright 2012 Eli Skeggs. +Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); +Based on micro-bunzip by Rob Landley (rob@landley.net). - // Key generation for curve25519 is simpler - if (this.curve.type === 'mont') { - var priv = new bn(drbg.generate(32)); - return this.keyFromPrivate(priv); - } +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; +var BitReader = bitreader; +var Stream = stream; +var CRC32 = crc32; - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; +var MAX_HUFCODE_BITS = 20; +var MAX_SYMBOLS = 258; +var SYMBOL_RUNA = 0; +var SYMBOL_RUNB = 1; +var MIN_GROUPS = 2; +var MAX_GROUPS = 6; +var GROUP_SIZE = 50; -EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) { - bitSize = bitSize || msg.byteLength() * 8; - var delta = bitSize - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; +var WHOLEPI = "314159265359"; +var SQRTPI = "177245385090"; -EC.prototype.truncateMsg = function truncateMSG(msg) { - // Bit size is only determined correctly for Uint8Arrays and hex strings - var bitSize; - if (msg instanceof Uint8Array) { - bitSize = msg.byteLength * 8; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else if (typeof msg === 'string') { - bitSize = msg.length * 4; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else { - msg = this._truncateToN(new bn(msg, 16)); +var mtf = function(array, index) { + var src = array[index], i; + for (i = index; i > 0; i--) { + array[i] = array[i-1]; } - return msg; + array[0] = src; + return src; }; -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this.truncateMsg(msg); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); +var Err = { + OK: 0, + LAST_BLOCK: -1, + NOT_BZIP_DATA: -2, + UNEXPECTED_INPUT_EOF: -3, + UNEXPECTED_OUTPUT_EOF: -4, + DATA_ERROR: -5, + OUT_OF_MEMORY: -6, + OBSOLETE_INPUT: -7, + END_OF_BLOCK: -8 +}; +var ErrorMessages = {}; +ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; +ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; +ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; +ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; +ErrorMessages[Err.DATA_ERROR] = "Data error"; +ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; +ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; +var _throw = function(status, optDetail) { + var msg = ErrorMessages[status] || 'unknown error'; + if (optDetail) { msg += ': '+optDetail; } + var e = new TypeError(msg); + e.errorCode = status; + throw e; +}; - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; +var Bunzip = function(inputStream, outputStream) { + this.writePos = this.writeCurrent = this.writeCount = 0; - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + this._start_bunzip(inputStream, outputStream); +}; +Bunzip.prototype._init_block = function() { + var moreBlocks = this._get_next_block(); + if ( !moreBlocks ) { + this.writeCount = -1; + return false; /* no more blocks */ + } + this.blockCRC = new CRC32(); + return true; +}; +/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ +Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { + /* Ensure that file starts with "BZh['1'-'9']." */ + var buf = new Uint8Array(4); + if (inputStream.read(buf, 0, 4) !== 4 || + String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') + _throw(Err.NOT_BZIP_DATA, 'bad magic'); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + var level = buf[3] - 0x30; + if (level < 1 || level > 9) + _throw(Err.NOT_BZIP_DATA, 'level out of range'); - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + this.reader = new BitReader(inputStream); - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; + /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of + uncompressed data. Allocate intermediate buffer for block. */ + this.dbufSize = 100000 * level; + this.nextoutput = 0; + this.outputStream = outputStream; + this.streamCRC = 0; +}; +Bunzip.prototype._get_next_block = function() { + var i, j, k; + var reader = this.reader; + // this is get_next_block() function from micro-bunzip: + /* Read in header signature and CRC, then validate signature. + (last block signature means CRC is for whole file, return now) */ + var h = reader.pi(); + if (h === SQRTPI) { // last block + return false; /* no more blocks */ + } + if (h !== WHOLEPI) + _throw(Err.NOT_BZIP_DATA); + this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) + this.streamCRC = (this.targetBlockCRC ^ + ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; + /* We can add support for blockRandomised if anybody complains. There was + some code for this in busybox 1.0.0-pre3, but nobody ever noticed that + it didn't actually work. */ + if (reader.read(1)) + _throw(Err.OBSOLETE_INPUT); + var origPointer = reader.read(24); + if (origPointer > this.dbufSize) + _throw(Err.DATA_ERROR, 'initial position out of bounds'); + /* mapping table: if some byte values are never used (encoding things + like ascii text), the compression code removes the gaps to have fewer + symbols to deal with, and writes a sparse bitfield indicating which + values were present. We make a translation table to convert the symbols + back to the corresponding bytes. */ + var t = reader.read(16); + var symToByte = new Uint8Array(256), symTotal = 0; + for (i = 0; i < 16; i++) { + if (t & (1 << (0xF - i))) { + var o = i * 16; + k = reader.read(16); + for (j = 0; j < 16; j++) + if (k & (1 << (0xF - j))) + symToByte[symTotal++] = o + j; } - - return new signature$1({ r: r, s: s, recoveryParam: recoveryParam }); } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - key = this.keyFromPublic(key, enc); - signature = new signature$1(signature, 'hex'); - // Fallback to the old code - var ret = this._verify(this.truncateMsg(msg), signature, key) || - this._verify(this._truncateToN(new bn(msg, 16)), signature, key); - return ret; -}; -EC.prototype._verify = function _verify(msg, signature, key) { - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; + /* How many different huffman coding groups does this block use? */ + var groupCount = reader.read(3); + if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) + _throw(Err.DATA_ERROR); + /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding + group. Read in the group selector list, which is stored as MTF encoded + bit runs. (MTF=Move To Front, as each value is used it's moved to the + start of the list.) */ + var nSelectors = reader.read(15); + if (nSelectors === 0) + _throw(Err.DATA_ERROR); - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); + var mtfSymbol = new Uint8Array(256); + for (i = 0; i < groupCount; i++) + mtfSymbol[i] = i; - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + var selectors = new Uint8Array(nSelectors); // was 32768... - return p.getX().umod(this.n).cmp(r) === 0; + for (i = 0; i < nSelectors; i++) { + /* Get next value */ + for (j = 0; reader.read(1); j++) + if (j >= groupCount) _throw(Err.DATA_ERROR); + /* Decode MTF to get the next selector */ + selectors[i] = mtf(mtfSymbol, j); } - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; + /* Read the huffman coding tables for each group, which code for symTotal + literal symbols, plus two run symbols (RUNA, RUNB) */ + var symCount = symTotal + 2; + var groups = [], hufGroup; + for (j = 0; j < groupCount; j++) { + var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); + /* Read huffman code lengths for each symbol. They're stored in + a way similar to mtf; record a starting value for the first symbol, + and an offset from the previous value for everys symbol after that. */ + t = reader.read(5); // lengths + for (i = 0; i < symCount; i++) { + for (;;) { + if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); + /* If first bit is 0, stop. Else second bit indicates whether + to increment or decrement the value. */ + if(!reader.read(1)) + break; + if(!reader.read(1)) + t++; + else + t--; + } + length[i] = t; + } -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$7((3 & j) === j, 'The recovery param is more than two bits'); - signature = new signature$1(signature, enc); - - var n = this.n; - var e = new bn(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; + /* Find largest and smallest lengths in this group */ + var minLen, maxLen; + minLen = maxLen = length[0]; + for (i = 1; i < symCount; i++) { + if (length[i] > maxLen) + maxLen = length[i]; + else if (length[i] < minLen) + minLen = length[i]; + } -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new signature$1(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; + /* Calculate permute[], base[], and limit[] tables from length[]. + * + * permute[] is the lookup table for converting huffman coded symbols + * into decoded symbols. base[] is the amount to subtract from the + * value of a huffman symbol of a given length when using permute[]. + * + * limit[] indicates the largest numerical value a symbol with a given + * number of bits can have. This is how the huffman codes can vary in + * length: each code with a value>limit[length] needs another bit. + */ + hufGroup = {}; + groups.push(hufGroup); + hufGroup.permute = new Uint16Array(MAX_SYMBOLS); + hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); + hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); + hufGroup.minLen = minLen; + hufGroup.maxLen = maxLen; + /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ + var pp = 0; + for (i = minLen; i <= maxLen; i++) { + temp[i] = hufGroup.limit[i] = 0; + for (t = 0; t < symCount; t++) + if (length[t] === i) + hufGroup.permute[pp++] = t; + } + /* Count symbols coded for at each bit length */ + for (i = 0; i < symCount; i++) + temp[length[i]]++; + /* Calculate limit[] (the largest symbol-coding value at each bit + * length, which is (previous limit<<1)+symbols at this level), and + * base[] (number of symbols to ignore at each bit length, which is + * limit minus the cumulative count of symbols coded for already). */ + pp = t = 0; + for (i = minLen; i < maxLen; i++) { + pp += temp[i]; + /* We read the largest possible symbol size and then unget bits + after determining how many we need, and those extra bits could + be set to anything. (They're noise from future symbols.) At + each level we're really only interested in the first few bits, + so here we set all the trailing to-be-ignored bits to 1 so they + don't affect the value>limit[length] comparison. */ + hufGroup.limit[i] = pp - 1; + pp <<= 1; + t += temp[i]; + hufGroup.base[i + 1] = pp - t; + } + hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ + hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; + hufGroup.base[minLen] = 0; + } + /* We've finished reading and digesting the block header. Now read this + block's huffman coded symbols from the file and undo the huffman coding + and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { + /* Initialize symbol occurrence counters and symbol Move To Front table */ + var byteCount = new Uint32Array(256); + for (i = 0; i < 256; i++) + mtfSymbol[i] = i; + /* Loop through compressed symbols. */ + var runPos = 0, dbufCount = 0, selector = 0, uc; + var dbuf = this.dbuf = new Uint32Array(this.dbufSize); + symCount = 0; + for (;;) { + /* Determine which huffman coding group to use. */ + if (!(symCount--)) { + symCount = GROUP_SIZE - 1; + if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } + hufGroup = groups[selectors[selector++]]; + } + /* Read next huffman-coded symbol. */ + i = hufGroup.minLen; + j = reader.read(i); + for (;;i++) { + if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } + if (j <= hufGroup.limit[i]) + break; + j = (j << 1) | reader.read(1); + } + /* Huffman decode value to get nextSym (with bounds checking) */ + j -= hufGroup.base[i]; + if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } + var nextSym = hufGroup.permute[j]; + /* We have now decoded the symbol, which indicates either a new literal + byte, or a repeated run of the most recent literal byte. First, + check if nextSym indicates a repeated run, and if so loop collecting + how many times to repeat the last literal. */ + if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { + /* If this is the start of a new run, zero out counter */ + if (!runPos){ + runPos = 1; + t = 0; + } + /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at + each bit position, add 1 or 2 instead. For example, + 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. + You can make any bit pattern that way using 1 less symbol than + the basic or 0/1 method (except all bits 0, which would use no + symbols, but a run of length 0 doesn't mean anything in this + context). Thus space is saved. */ + if (nextSym === SYMBOL_RUNA) + t += runPos; + else + t += 2 * runPos; + runPos <<= 1; continue; } - - if (Qprime.eq(Q)) - return i; + /* When we hit the first non-run symbol after a run, we now know + how many times to repeat the last literal, so append that many + copies to our buffer of decoded symbols (dbuf) now. (The last + literal used is the one at the head of the mtfSymbol array.) */ + if (runPos){ + runPos = 0; + if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } + uc = symToByte[mtfSymbol[0]]; + byteCount[uc] += t; + while (t--) + dbuf[dbufCount++] = uc; + } + /* Is this the terminating symbol? */ + if (nextSym > symTotal) + break; + /* At this point, nextSym indicates a new literal character. Subtract + one to get the position in the MTF array at which this literal is + currently to be found. (Note that the result can't be -1 or 0, + because 0 and 1 are RUNA and RUNB. But another instance of the + first symbol in the mtf array, position 0, would have been handled + as part of a run above. Therefore 1 unused mtf position minus + 2 non-literal nextSym values equals -1.) */ + if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } + i = nextSym - 1; + uc = mtf(mtfSymbol, i); + uc = symToByte[uc]; + /* We have our literal byte. Save it into dbuf. */ + byteCount[uc]++; + dbuf[dbufCount++] = uc; } - throw new Error('Unable to find valid recovery factor'); -}; - -var assert$8 = utils_1$1.assert; -var parseBytes = utils_1$1.parseBytes; -var cachedProperty = utils_1$1.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair$1(eddsa, params) { - this.eddsa = eddsa; - if (params.hasOwnProperty('secret')) - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else { - this._pubBytes = parseBytes(params.pub); - if (this._pubBytes && this._pubBytes.length === 33 && - this._pubBytes[0] === 0x40) - this._pubBytes = this._pubBytes.slice(1, 33); - if (this._pubBytes && this._pubBytes.length !== 32) - throw new Error('Unknown point compression format'); - } -} - -KeyPair$1.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$1) - return pub; - return new KeyPair$1(eddsa, { pub: pub }); -}; - -KeyPair$1.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$1) - return secret; - return new KeyPair$1(eddsa, { secret: secret }); -}; - -KeyPair$1.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair$1, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair$1, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair$1, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair$1, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair$1.prototype.sign = function sign(message) { - assert$8(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair$1.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair$1.prototype.getSecret = function getSecret(enc) { - assert$8(this._secret, 'KeyPair is public only'); - return utils_1$1.encode(this.secret(), enc); -}; - -KeyPair$1.prototype.getPublic = function getPublic(enc, compact) { - return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); -}; - -var key$1 = KeyPair$1; - -var assert$9 = utils_1$1.assert; -var cachedProperty$1 = utils_1$1.cachedProperty; -var parseBytes$1 = utils_1$1.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature$2(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; + /* At this point, we've read all the huffman-coded symbols (and repeated + runs) for this block from the input stream, and decoded them into the + intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. + Now undo the Burrows-Wheeler transform on dbuf. + See http://dogma.net/markn/articles/bwt/bwt.htm + */ + if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } + /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ + j = 0; + for (i = 0; i < 256; i++) { + k = j + byteCount[i]; + byteCount[i] = j; + j = k; } + /* Figure out what order dbuf would be in if we sorted it. */ + for (i = 0; i < dbufCount; i++) { + uc = dbuf[i] & 0xff; + dbuf[byteCount[uc]] |= (i << 8); + byteCount[uc]++; + } + /* Decode first byte by hand to initialize "previous" byte. Note that it + doesn't get output, and if the first three characters are identical + it doesn't qualify as a run (hence writeRunCountdown=5). */ + var pos = 0, current = 0, run = 0; + if (dbufCount) { + pos = dbuf[origPointer]; + current = (pos & 0xff); + pos >>= 8; + run = -1; + } + this.writePos = pos; + this.writeCurrent = current; + this.writeCount = dbufCount; + this.writeRun = run; - assert$9(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof bn) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty$1(Signature$2, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty$1(Signature$2, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature$2.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature$2.prototype.toHex = function toHex() { - return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -var signature$2 = Signature$2; - -var assert$a = utils_1$1.assert; -var parseBytes$2 = utils_1$1.parseBytes; - - - -function EDDSA(curve) { - assert$a(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = curves_1[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash_1.sha512; -} - -var eddsa$1 = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes$2(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); + return true; /* more blocks to come */ }; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message +/* Undo burrows-wheeler transform on intermediate buffer to produce output. + If start_bunzip was initialized with out_fd=-1, then up to len bytes of + data are written to outbuf. Return value is number of bytes written or + error (all errors are negative numbers). If out_fd!=-1, outbuf and len + are ignored, data is written to out_fd and return is RETVAL_OK or error. */ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes$2(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n); -}; +Bunzip.prototype._read_bunzip = function(outputBuffer, len) { + var copies, previous, outbyte; + /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully + decoded, which results in this returning RETVAL_LAST_BLOCK, also + equal to -1... Confusing, I'm returning 0 here to indicate no + bytes written into the buffer */ + if (this.writeCount < 0) { return 0; } + var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; + var dbufCount = this.writeCount; this.outputsize; + var run = this.writeRun; -EDDSA.prototype.keyPair = function keyPair(options) { - return new key$1(this, options); + while (dbufCount) { + dbufCount--; + previous = current; + pos = dbuf[pos]; + current = pos & 0xff; + pos >>= 8; + if (run++ === 3){ + copies = current; + outbyte = previous; + current = -1; + } else { + copies = 1; + outbyte = current; + } + this.blockCRC.updateCRCRun(outbyte, copies); + while (copies--) { + this.outputStream.writeByte(outbyte); + this.nextoutput++; + } + if (current != previous) + run = 0; + } + this.writeCount = dbufCount; + // check CRC + if (this.blockCRC.getCRC() !== this.targetBlockCRC) { + _throw(Err.DATA_ERROR, "Bad block CRC "+ + "(got "+this.blockCRC.getCRC().toString(16)+ + " expected "+this.targetBlockCRC.toString(16)+")"); + } + return this.nextoutput; }; -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return key$1.fromPublic(this, pub); +var coerceInputStream = function(input) { + if ('readByte' in input) { return input; } + var inputStream = new Stream(); + inputStream.pos = 0; + inputStream.readByte = function() { return input[this.pos++]; }; + inputStream.seek = function(pos) { this.pos = pos; }; + inputStream.eof = function() { return this.pos >= input.length; }; + return inputStream; }; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return key$1.fromSecret(this, secret); +var coerceOutputStream = function(output) { + var outputStream = new Stream(); + var resizeOk = true; + if (output) { + if (typeof(output)==='number') { + outputStream.buffer = new Uint8Array(output); + resizeOk = false; + } else if ('writeByte' in output) { + return output; + } else { + outputStream.buffer = output; + resizeOk = false; + } + } else { + outputStream.buffer = new Uint8Array(16384); + } + outputStream.pos = 0; + outputStream.writeByte = function(_byte) { + if (resizeOk && this.pos >= this.buffer.length) { + var newBuffer = new Uint8Array(this.buffer.length*2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + this.buffer[this.pos++] = _byte; + }; + outputStream.getBuffer = function() { + // trim buffer + if (this.pos !== this.buffer.length) { + if (!resizeOk) + throw new TypeError('outputsize does not match decoded input'); + var newBuffer = new Uint8Array(this.pos); + newBuffer.set(this.buffer.subarray(0, this.pos)); + this.buffer = newBuffer; + } + return this.buffer; + }; + outputStream._coerced = true; + return outputStream; }; -EDDSA.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.curve.n.toArray() - }); +/* Static helper functions */ +// 'input' can be a stream or a buffer +// 'output' can be a stream or a buffer or a number (buffer size) +const decode = function(input, output, multistream) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); - return this.keyFromSecret(drbg.generate(32)); + var bz = new Bunzip(inputStream, outputStream); + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + if (bz._init_block()) { + bz._read_bunzip(); + } else { + var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) + if (targetStreamCRC !== bz.streamCRC) { + _throw(Err.DATA_ERROR, "Bad stream CRC "+ + "(got "+bz.streamCRC.toString(16)+ + " expected "+targetStreamCRC.toString(16)+")"); + } + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + } else break; + } + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; +const decodeBlock = function(input, pos, output) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + var bz = new Bunzip(inputStream, outputStream); + bz.reader.seek(pos); + /* Fill the decode buffer for the block */ + var moreBlocks = bz._get_next_block(); + if (moreBlocks) { + /* Init the CRC for writing */ + bz.blockCRC = new CRC32(); -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof signature$2) - return sig; - return new signature$2(this, sig); -}; + /* Zero this so the current byte from before the seek is not written */ + bz.writeCopies = 0; -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; + /* Decompress the block and write to stdout */ + bz._read_bunzip(); + // XXX keep writing? + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; +/* Reads bzip2 file from stream or buffer `input`, and invoke + * `callback(position, size)` once for each bzip2 block, + * where position gives the starting position (in *bits*) + * and size gives uncompressed size of the block (in *bytes*). */ +const table = function(input, callback, multistream) { + // make a stream from a buffer, if necessary + var inputStream = new Stream(); + inputStream.delegate = coerceInputStream(input); + inputStream.pos = 0; + inputStream.readByte = function() { + this.pos++; + return this.delegate.readByte(); + }; + if (inputStream.delegate.eof) { + inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); + } + var outputStream = new Stream(); + outputStream.pos = 0; + outputStream.writeByte = function() { this.pos++; }; -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils_1$1.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils_1$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; + var bz = new Bunzip(inputStream, outputStream); + var blockSize = bz.dbufSize; + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; + var position = inputStream.pos*8 + bz.reader.bitOffset; + if (bz.reader.hasByte) { position -= 8; } -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils_1$1.intFromLE(bytes); + if (bz._init_block()) { + var start = outputStream.pos; + bz._read_bunzip(); + callback(position, outputStream.pos - start); + } else { + bz.reader.read(32); // (but we ignore the crc) + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + console.assert(bz.dbufSize === blockSize, + "shouldn't change block size within multistream file"); + } else break; + } + } }; -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; +var lib = { + Bunzip, + Stream, + Err, + decode, + decodeBlock, + table }; -var elliptic_1 = createCommonjsModule(function (module, exports) { - -var elliptic = exports; - -elliptic.utils = utils_1$1; -elliptic.rand = brorand; -elliptic.curve = curve_1; -elliptic.curves = curves_1; - -// Protocols -elliptic.ec = ec; -elliptic.eddsa = eddsa$1; -}); - -var elliptic$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': elliptic_1, - __moduleExports: elliptic_1 -}); +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null +}, [lib]); -export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt$5 as decrypt, decryptKey, decryptSessionKeys, encrypt$5 as encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey$1 as generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign$6 as sign, unarmor, verify$6 as verify }; +export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PaddingPacket, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt, decryptKey, decryptSessionKeys, encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign, unarmor, verify }; diff --git a/app/node_modules/openpgp/dist/openpgp.js b/app/node_modules/openpgp/dist/openpgp.js index bde39ddc1..ff7db97e0 100644 --- a/app/node_modules/openpgp/dist/openpgp.js +++ b/app/node_modules/openpgp/dist/openpgp.js @@ -1,9 +1,24 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ var openpgp = (function (exports) { 'use strict'; const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); + } + const doneWritingPromise = Symbol('doneWritingPromise'); const doneWritingResolve = Symbol('doneWritingResolve'); const doneWritingReject = Symbol('doneWritingReject'); @@ -13,6 +28,9 @@ var openpgp = (function (exports) { class ArrayStream extends Array { constructor() { super(); + // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work + Object.setPrototypeOf(this, ArrayStream.prototype); + this[doneWritingPromise] = new Promise((resolve, reject) => { this[doneWritingResolve] = resolve; this[doneWritingReject] = reject; @@ -113,15 +131,14 @@ var openpgp = (function (exports) { */ Writer.prototype.releaseLock = function() {}; - const isNode = typeof globalThis.process === 'object' && + /* eslint-disable no-prototype-builtins */ + typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; - const NodeReadableStream = isNode && void('stream').Readable; - /** * Check whether data is a Stream, and if so of which type * @param {Any} input data to check - * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false} + * @returns {'web'|'node'|'array'|'web-like'|false} */ function isStream(input) { if (isArrayStream(input)) { @@ -130,11 +147,11 @@ var openpgp = (function (exports) { if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { return 'web'; } - if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) { - return 'ponyfill'; - } - if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) { - return 'node'; + // try and detect a node native stream without having to import its class + if (input && + !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) && + typeof input._read === 'function' && typeof input._readableState === 'object') { + throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`'); } if (input && input.getReader) { return 'web-like'; @@ -178,99 +195,12 @@ var openpgp = (function (exports) { return result; } - const NodeBuffer = isNode && void('buffer').Buffer; - const NodeReadableStream$1 = isNode && void('stream').Readable; - + const doneReadingSet = new WeakSet(); /** - * Web / node stream conversion functions - * From https://github.com/gwicke/node-web-streams + * The external buffer is used to store values that have been peeked or unshifted from the original stream. + * Because of how streams are implemented, such values cannot be "put back" in the original stream, + * but they need to be returned first when reading from the input again. */ - - let nodeToWeb; - let webToNode; - - if (NodeReadableStream$1) { - - /** - * Convert a Node Readable Stream to a Web ReadableStream - * @param {Readable} nodeStream - * @returns {ReadableStream} - */ - nodeToWeb = function(nodeStream) { - let canceled = false; - return new ReadableStream({ - start(controller) { - nodeStream.pause(); - nodeStream.on('data', chunk => { - if (canceled) { - return; - } - if (NodeBuffer.isBuffer(chunk)) { - chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - controller.enqueue(chunk); - nodeStream.pause(); - }); - nodeStream.on('end', () => { - if (canceled) { - return; - } - controller.close(); - }); - nodeStream.on('error', e => controller.error(e)); - }, - pull() { - nodeStream.resume(); - }, - cancel(reason) { - canceled = true; - nodeStream.destroy(reason); - } - }); - }; - - - class NodeReadable extends NodeReadableStream$1 { - constructor(webStream, options) { - super(options); - this._reader = getReader(webStream); - } - - async _read(size) { - try { - while (true) { - const { done, value } = await this._reader.read(); - if (done) { - this.push(null); - break; - } - if (!this.push(value)) { - break; - } - } - } catch (e) { - this.destroy(e); - } - } - - async _destroy(error, callback) { - this._reader.cancel(error).then(callback, callback); - } - } - - /** - * Convert a Web ReadableStream to a Node Readable Stream - * @param {ReadableStream} webStream - * @param {Object} options - * @returns {Readable} - */ - webToNode = function(webStream, options) { - return new NodeReadable(webStream, options); - }; - - } - - const doneReadingSet = new WeakSet(); const externalBuffer = Symbol('externalBuffer'); /** @@ -289,13 +219,10 @@ var openpgp = (function (exports) { const reader = input.getReader(); this._read = reader.read.bind(reader); this._releaseLock = () => {}; - this._cancel = async () => {}; + this._cancel = () => {}; return; } let streamType = isStream(input); - if (streamType === 'node') { - input = nodeToWeb(input); - } if (streamType) { const reader = input.getReader(); this._read = reader.read.bind(reader); @@ -402,6 +329,7 @@ var openpgp = (function (exports) { Reader.prototype.readBytes = async function(length) { const buffer = []; let bufferLength = 0; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) { @@ -461,6 +389,7 @@ var openpgp = (function (exports) { */ Reader.prototype.readToEnd = async function(join=concat) { const result = []; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) break; @@ -469,32 +398,6 @@ var openpgp = (function (exports) { return join(result); }; - let { ReadableStream, WritableStream, TransformStream } = globalThis; - - let toPonyfillReadable, toNativeReadable; - - async function loadStreamsPonyfill() { - if (TransformStream) { - return; - } - - const [ponyfill, adapter] = await Promise.all([ - Promise.resolve().then(function () { return ponyfill_es6; }), - Promise.resolve().then(function () { return webStreamsAdapter; }) - ]); - - ({ ReadableStream, WritableStream, TransformStream } = ponyfill); - - const { createReadableStreamWrapper } = adapter; - - if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) { - toPonyfillReadable = createReadableStreamWrapper(ReadableStream); - toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream); - } - } - - const NodeBuffer$1 = isNode && void('buffer').Buffer; - /** * Convert data to Stream * @param {ReadableStream|Uint8array|String} input data to convert @@ -502,12 +405,6 @@ var openpgp = (function (exports) { */ function toStream(input) { let streamType = isStream(input); - if (streamType === 'node') { - return nodeToWeb(input); - } - if (streamType === 'web' && toPonyfillReadable) { - return toPonyfillReadable(input); - } if (streamType) { return input; } @@ -520,7 +417,7 @@ var openpgp = (function (exports) { } /** - * Convert data to ArrayStream + * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream. * @param {Object} input data to convert * @returns {ArrayStream} Converted data */ @@ -553,9 +450,6 @@ var openpgp = (function (exports) { if (typeof list[0] === 'string') { return list.join(''); } - if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) { - return NodeBuffer$1.concat(list); - } return concatUint8Array(list); } @@ -596,24 +490,6 @@ var openpgp = (function (exports) { return result; } - /** - * Get a Reader - * @param {ReadableStream|Uint8array|String} input - * @returns {Reader} - */ - function getReader(input) { - return new Reader(input); - } - - /** - * Get a Writer - * @param {WritableStream} input - * @returns {Writer} - */ - function getWriter(input) { - return new Writer(input); - } - /** * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. * @param {ReadableStream|Uint8array|String} input @@ -650,6 +526,7 @@ var openpgp = (function (exports) { const reader = getReader(input); const writer = getWriter(target); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -901,6 +778,7 @@ var openpgp = (function (exports) { const reader = getReader(readable); const writer = getWriter(writable); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -984,9 +862,8 @@ var openpgp = (function (exports) { if (returnValue.length >= -end) { lastBytes = slice(returnValue, end); return slice(returnValue, begin, end); - } else { - lastBytes = returnValue; } + lastBytes = returnValue; }); } console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); @@ -995,9 +872,8 @@ var openpgp = (function (exports) { if (input[externalBuffer]) { input = concat(input[externalBuffer].concat([input])); } - if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) { - if (end === Infinity) end = input.length; - return input.subarray(begin, end); + if (isUint8Array(input)) { + return input.subarray(begin, end === Infinity ? input.length : end); } return input.slice(begin, end); } @@ -1029,7 +905,10 @@ var openpgp = (function (exports) { async function cancel(input, reason) { if (isStream(input)) { if (input.cancel) { - return input.cancel(reason); + const cancelled = await input.cancel(reason); + // the stream is not always cancelled at this point, so we wait some more + await new Promise(setTimeout); + return cancelled; } if (input.destroy) { input.destroy(reason); @@ -1058,636 +937,152 @@ var openpgp = (function (exports) { return arrayStream; } - /* eslint-disable new-cap */ + /** + * Get a Reader + * @param {ReadableStream|Uint8array|String} input + * @returns {Reader} + */ + function getReader(input) { + return new Reader(input); + } /** - * @fileoverview - * BigInteger implementation of basic operations - * that wraps the native BigInt library. - * Operations are not constant time, - * but we try and limit timing leakage where we can - * @module biginteger/native - * @private + * Get a Writer + * @param {WritableStream} input + * @returns {Writer} */ + function getWriter(input) { + return new Writer(input); + } /** - * @private + * @module enums */ - class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on null or undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - if (n instanceof Uint8Array) { - const bytes = n; - const hex = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - const hexByte = bytes[i].toString(16); - hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte; - } - this.value = BigInt('0x0' + hex.join('')); - } else { - this.value = BigInt(n); - } - } + const byValue = Symbol('byValue'); - clone() { - return new BigInteger(this.value); - } + var enums = { - /** - * BigInteger increment in place + /** Maps curve names under various standards to one + * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} + * @enum {String} + * @readonly */ - iinc() { - this.value++; - return this; - } + curve: { + /** NIST P-256 Curve */ + 'nistP256': 'nistP256', + /** @deprecated use `nistP256` instead */ + 'p256': 'nistP256', - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } + /** NIST P-384 Curve */ + 'nistP384': 'nistP384', + /** @deprecated use `nistP384` instead */ + 'p384': 'nistP384', - /** - * BigInteger decrement in place - */ - idec() { - this.value--; - return this; - } + /** NIST P-521 Curve */ + 'nistP521': 'nistP521', + /** @deprecated use `nistP521` instead */ + 'p521': 'nistP521', - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + /** SECG SECP256k1 Curve */ + 'secp256k1': 'secp256k1', - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value += x.value; - return this; - } + /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ + 'ed25519Legacy': 'ed25519Legacy', + /** @deprecated use `ed25519Legacy` instead */ + 'ed25519': 'ed25519Legacy', - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ + 'curve25519Legacy': 'curve25519Legacy', + /** @deprecated use `curve25519Legacy` instead */ + 'curve25519': 'curve25519Legacy', - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value -= x.value; - return this; - } + /** BrainpoolP256r1 Curve */ + 'brainpoolP256r1': 'brainpoolP256r1', - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } + /** BrainpoolP384r1 Curve */ + 'brainpoolP384r1': 'brainpoolP384r1', - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value *= x.value; - return this; - } + /** BrainpoolP512r1 Curve */ + 'brainpoolP512r1': 'brainpoolP512r1' + }, - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. + /** A string to key specifier type + * @enum {Integer} + * @readonly */ - mul(x) { - return this.clone().imul(x); - } + s2k: { + simple: 0, + salted: 1, + iterated: 3, + argon2: 4, + gnu: 101 + }, - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} + * @enum {Integer} + * @readonly */ - imod(m) { - this.value %= m.value; - if (this.isNegative()) { - this.iadd(m); - } - return this; - } + publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ + rsaEncryptSign: 1, + /** RSA (Encrypt only) [HAC] */ + rsaEncrypt: 2, + /** RSA (Sign only) [HAC] */ + rsaSign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ + elgamal: 16, + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsaLegacy: 22, + /** Reserved for AEDH */ + aedh: 23, + /** Reserved for AEDSA */ + aedsa: 24, + /** X25519 (Encrypt only) */ + x25519: 25, + /** X448 (Encrypt only) */ + x448: 26, + /** Ed25519 (Sign only) */ + ed25519: 27, + /** Ed448 (Sign only) */ + ed448: 28 + }, - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + * @enum {Integer} + * @readonly */ - mod(m) { - return this.clone().imod(m); - } + symmetric: { + /** Not implemented! */ + idea: 1, + tripledes: 2, + cast5: 3, + blowfish: 4, + aes128: 7, + aes192: 8, + aes256: 9, + twofish: 10 + }, - /** - * Compute modular exponentiation using square and multiply - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + * @enum {Integer} + * @readonly */ - modExp(e, n) { - if (n.isZero()) throw Error('Modulo cannot be zero'); - if (n.isOne()) return new BigInteger(0); - if (e.isNegative()) throw Error('Unsopported negative exponent'); - - let exp = e.value; - let x = this.value; - - x %= n.value; - let r = BigInt(1); - while (exp > BigInt(0)) { - const lsb = exp & BigInt(1); - exp >>= BigInt(1); // e / 2 - // Always compute multiplication step, to reduce timing leakage - const rx = (r * x) % n.value; - // Update r only if lsb is 1 (odd exponent) - r = lsb ? rx : r; - x = (x * x) % n.value; // Square - } - return new BigInteger(r); - } - - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - const { gcd, x } = this._egcd(n); - if (!gcd.isOne()) { - throw new Error('Inverse does not exist'); - } - return x.add(n).mod(n); - } - - /** - * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) - * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b) - * @param {BigInteger} b - Second operand - * @returns {{ gcd, x, y: BigInteger }} - */ - _egcd(b) { - let x = BigInt(0); - let y = BigInt(1); - let xPrev = BigInt(1); - let yPrev = BigInt(0); - - let a = this.value; - b = b.value; - - while (b !== BigInt(0)) { - const q = a / b; - let tmp = x; - x = xPrev - q * x; - xPrev = tmp; - - tmp = y; - y = yPrev - q * y; - yPrev = tmp; - - tmp = b; - b = a % b; - a = tmp; - } - - return { - x: new BigInteger(xPrev), - y: new BigInteger(yPrev), - gcd: new BigInteger(a) - }; - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} b - Operand - * @returns {BigInteger} gcd - */ - gcd(b) { - let a = this.value; - b = b.value; - while (b !== BigInt(0)) { - const tmp = b; - b = a % b; - a = tmp; - } - return new BigInteger(a); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value <<= x.value; - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value >>= x.value; - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value === x.value; - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value < x.value; - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value <= x.value; - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value > x.value; - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value >= x.value; - } - - isZero() { - return this.value === BigInt(0); - } - - isOne() { - return this.value === BigInt(1); - } - - isNegative() { - return this.value < BigInt(0); - } - - isEven() { - return !(this.value & BigInt(1)); - } - - abs() { - const res = this.clone(); - if (this.isNegative()) { - res.value = -res.value; - } - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - const number = Number(this.value); - if (number > Number.MAX_SAFE_INTEGER) { - // We throw and error to conform with the bn.js implementation - throw new Error('Number can only safely store up to 53 bits'); - } - return number; - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - const bit = (this.value >> BigInt(i)) & BigInt(1); - return (bit === BigInt(0)) ? 0 : 1; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - const zero = new BigInteger(0); - const one = new BigInteger(1); - const negOne = new BigInteger(-1); - - // -1n >> -1n is -1n - // 1n >> 1n is 0n - const target = this.isNegative() ? negOne : zero; - let bitlen = 1; - const tmp = this.clone(); - while (!tmp.irightShift(one).equal(target)) { - bitlen++; - } - return bitlen; - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - const zero = new BigInteger(0); - const negOne = new BigInteger(-1); - - const target = this.isNegative() ? negOne : zero; - const eight = new BigInteger(8); - let len = 1; - const tmp = this.clone(); - while (!tmp.irightShift(eight).equal(target)) { - len++; - } - return len; - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) - // this is faster than shift+mod iterations - let hex = this.value.toString(16); - if (hex.length % 2 === 1) { - hex = '0' + hex; - } - - const rawLength = hex.length / 2; - const bytes = new Uint8Array(length || rawLength); - // parse hex - const offset = length ? (length - rawLength) : 0; - let i = 0; - while (i < rawLength) { - bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); - i++; - } - - if (endian !== 'be') { - bytes.reverse(); - } - - return bytes; - } - } - - const detectBigInt = () => typeof BigInt !== 'undefined'; - - async function getBigInteger() { - if (detectBigInt()) { - return BigInteger; - } else { - const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; }); - return BigInteger; - } - } - - /** - * @module enums - */ - - const byValue = Symbol('byValue'); - - var enums = { - - /** Maps curve names under various standards to one - * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} - * @enum {String} - * @readonly - */ - curve: { - /** NIST P-256 Curve */ - 'p256': 'p256', - 'P-256': 'p256', - 'secp256r1': 'p256', - 'prime256v1': 'p256', - '1.2.840.10045.3.1.7': 'p256', - '2a8648ce3d030107': 'p256', - '2A8648CE3D030107': 'p256', - - /** NIST P-384 Curve */ - 'p384': 'p384', - 'P-384': 'p384', - 'secp384r1': 'p384', - '1.3.132.0.34': 'p384', - '2b81040022': 'p384', - '2B81040022': 'p384', - - /** NIST P-521 Curve */ - 'p521': 'p521', - 'P-521': 'p521', - 'secp521r1': 'p521', - '1.3.132.0.35': 'p521', - '2b81040023': 'p521', - '2B81040023': 'p521', - - /** SECG SECP256k1 Curve */ - 'secp256k1': 'secp256k1', - '1.3.132.0.10': 'secp256k1', - '2b8104000a': 'secp256k1', - '2B8104000A': 'secp256k1', - - /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ - 'ed25519Legacy': 'ed25519', - 'ED25519': 'ed25519', - /** @deprecated use `ed25519Legacy` instead */ - 'ed25519': 'ed25519', - 'Ed25519': 'ed25519', - '1.3.6.1.4.1.11591.15.1': 'ed25519', - '2b06010401da470f01': 'ed25519', - '2B06010401DA470F01': 'ed25519', - - /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ - 'curve25519Legacy': 'curve25519', - 'X25519': 'curve25519', - 'cv25519': 'curve25519', - /** @deprecated use `curve25519Legacy` instead */ - 'curve25519': 'curve25519', - 'Curve25519': 'curve25519', - '1.3.6.1.4.1.3029.1.5.1': 'curve25519', - '2b060104019755010501': 'curve25519', - '2B060104019755010501': 'curve25519', - - /** BrainpoolP256r1 Curve */ - 'brainpoolP256r1': 'brainpoolP256r1', - '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1', - '2b2403030208010107': 'brainpoolP256r1', - '2B2403030208010107': 'brainpoolP256r1', - - /** BrainpoolP384r1 Curve */ - 'brainpoolP384r1': 'brainpoolP384r1', - '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1', - '2b240303020801010b': 'brainpoolP384r1', - '2B240303020801010B': 'brainpoolP384r1', - - /** BrainpoolP512r1 Curve */ - 'brainpoolP512r1': 'brainpoolP512r1', - '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1', - '2b240303020801010d': 'brainpoolP512r1', - '2B240303020801010D': 'brainpoolP512r1' - }, - - /** A string to key specifier type - * @enum {Integer} - * @readonly - */ - s2k: { - simple: 0, - salted: 1, - iterated: 3, - gnu: 101 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} - * @enum {Integer} - * @readonly - */ - publicKey: { - /** RSA (Encrypt or Sign) [HAC] */ - rsaEncryptSign: 1, - /** RSA (Encrypt only) [HAC] */ - rsaEncrypt: 2, - /** RSA (Sign only) [HAC] */ - rsaSign: 3, - /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ - elgamal: 16, - /** DSA (Sign only) [FIPS186] [HAC] */ - dsa: 17, - /** ECDH (Encrypt only) [RFC6637] */ - ecdh: 18, - /** ECDSA (Sign only) [RFC6637] */ - ecdsa: 19, - /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) - * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ - eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility - /** @deprecated use `eddsaLegacy` instead */ - ed25519Legacy: 22, - /** @deprecated use `eddsaLegacy` instead */ - eddsa: 22, - /** Reserved for AEDH */ - aedh: 23, - /** Reserved for AEDSA */ - aedsa: 24, - /** X25519 (Encrypt only) */ - x25519: 25, - /** X448 (Encrypt only) */ - x448: 26, - /** Ed25519 (Sign only) */ - ed25519: 27, - /** Ed448 (Sign only) */ - ed448: 28 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - * @enum {Integer} - * @readonly - */ - symmetric: { - plaintext: 0, - /** Not implemented! */ - idea: 1, - tripledes: 2, - cast5: 3, - blowfish: 4, - aes128: 7, - aes192: 8, - aes256: 9, - twofish: 10 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - * @enum {Integer} - * @readonly - */ - compression: { - uncompressed: 0, - /** RFC1951 */ - zip: 1, - /** RFC1950 */ - zlib: 2, - bzip2: 3 - }, + compression: { + uncompressed: 0, + /** RFC1951 */ + zip: 1, + /** RFC1950 */ + zlib: 2, + bzip2: 3 + }, /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} * @enum {Integer} @@ -1700,7 +1095,9 @@ var openpgp = (function (exports) { sha256: 8, sha384: 9, sha512: 10, - sha224: 11 + sha224: 11, + sha3_256: 12, + sha3_512: 14 }, /** A list of hash names as accepted by webCrypto functions. @@ -1721,6 +1118,7 @@ var openpgp = (function (exports) { aead: { eax: 1, ocb: 2, + gcm: 3, experimentalGCM: 100 // Private algorithm }, @@ -1746,7 +1144,8 @@ var openpgp = (function (exports) { userAttribute: 17, symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + padding: 21 }, /** Data types in the literal packet @@ -1902,7 +1301,7 @@ var openpgp = (function (exports) { placeholderBackwardsCompatibility: 10, preferredSymmetricAlgorithms: 11, revocationKey: 12, - issuer: 16, + issuerKeyID: 16, notationData: 20, preferredHashAlgorithms: 21, preferredCompressionAlgorithms: 22, @@ -1917,7 +1316,8 @@ var openpgp = (function (exports) { signatureTarget: 31, embeddedSignature: 32, issuerFingerprint: 33, - preferredAEADAlgorithms: 34 + preferredAEADAlgorithms: 34, + preferredCipherSuites: 39 }, /** Key flags @@ -1986,7 +1386,8 @@ var openpgp = (function (exports) { aead: 2, /** 0x04 - Version 5 Public-Key Packet format and corresponding new * fingerprint format */ - v5Keys: 4 + v5Keys: 4, + seipdv2: 8 }, /** @@ -2032,9 +1433,328 @@ var openpgp = (function (exports) { }; // GPG4Browsers - An OpenPGP implementation in javascript - - const debugMode = (() => { - try { + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + var config = { + /** + * @memberof module:config + * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} + */ + preferredHashAlgorithm: enums.hash.sha512, + /** + * @memberof module:config + * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} + */ + preferredSymmetricAlgorithm: enums.symmetric.aes256, + /** + * @memberof module:config + * @property {Integer} compression Default compression algorithm {@link module:enums.compression} + */ + preferredCompressionAlgorithm: enums.compression.uncompressed, + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * This option is applicable to: + * - key generation (encryption key preferences), + * - password-based message encryption, and + * - private key encryption. + * In the case of message encryption using public keys, the encryption key preferences are respected instead. + * Note: not all OpenPGP implementations are compatible with this option. + * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10} + * @memberof module:config + * @property {Boolean} aeadProtect + */ + aeadProtect: false, + /** + * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`) + * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`, + * this option must be set, otherwise key parsing and/or key decryption will fail. + * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys + * will be processed incorrectly. + */ + parseAEADEncryptedV4KeysAsLegacy: false, + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aeadProtect is set to true. + * @memberof module:config + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} + */ + preferredAEADAlgorithm: enums.aead.gcm, + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aeadProtect is set to true. + * Must be an integer value from 0 to 56. + * @memberof module:config + * @property {Integer} aeadChunkSizeByte + */ + aeadChunkSizeByte: 12, + /** + * Use v6 keys. + * Note: not all OpenPGP implementations are compatible with this option. + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + * @memberof module:config + * @property {Boolean} v6Keys + */ + v6Keys: false, + /** + * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet). + * These are non-standard entities, which in the crypto-refresh have been superseded + * by v6 keys and v6 signatures, respectively. + * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries, + * hence parsing them might be necessary in some cases. + */ + enableParsingV5Entities: false, + /** + * S2K (String to Key) type, used for key derivation in the context of secret key encryption + * and password-encrypted data. Weaker s2k options are not allowed. + * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it + * (pending standardisation). + * @memberof module:config + * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k} + */ + s2kType: enums.s2k.iterated, + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}: + * Iteration Count Byte for Iterated and Salted S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`. + * Note: this is the exponent value, not the final number of iterations (refer to specs for more details). + * @memberof module:config + * @property {Integer} s2kIterationCountByte + */ + s2kIterationCountByte: 224, + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}: + * Argon2 parameters for S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`. + * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"), + * to ensure compatibility with memory-constrained environments. + * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4. + * @memberof module:config + * @property {Object} params + * @property {Integer} params.passes - number of iterations t + * @property {Integer} params.parallelism - degree of parallelism p + * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes. + */ + s2kArgon2Params: { + passes: 3, + parallelism: 4, // lanes + memoryExponent: 16 // 64 MiB of RAM + }, + /** + * Allow decryption of messages without integrity protection. + * This is an **insecure** setting: + * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. + * - it enables downgrade attacks against integrity-protected messages. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedMessages + */ + allowUnauthenticatedMessages: false, + /** + * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to + * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible + * and deferring checking their integrity until the decrypted stream has been read in full. + * + * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity: + * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL + * (see https://efail.de/). + * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data. + * + * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedStream + */ + allowUnauthenticatedStream: false, + /** + * Minimum RSA key size allowed for key generation and message signing, verification and encryption. + * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. + * @memberof module:config + * @property {Number} minRSABits + */ + minRSABits: 2047, + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + * @memberof module:config + * @property {Boolean} passwordCollisionCheck + */ + passwordCollisionCheck: false, + /** + * Allow decryption using RSA keys without `encrypt` flag. + * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug + * where key flags were ignored when selecting a key for encryption. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureDecryptionWithSigningKeys: false, + /** + * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. + * Instead, a verification key will also be consider valid as long as it is valid at the current time. + * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, + * and have self-signature's creation date that does not match the primary key creation date. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureVerificationWithReformattedKeys: false, + /** + * Allow using keys that do not have any key flags set. + * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages + * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29). + * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation. + * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm. + */ + allowMissingKeyFlags: false, + /** + * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). + * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: + * - new/incoming messages are automatically decrypted (without user interaction); + * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). + * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. + * @memberof module:config + * @property {Boolean} constantTimePKCS1Decryption + */ + constantTimePKCS1Decryption: false, + /** + * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. + * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. + * However, the more algorithms are added, the slower the decryption procedure becomes. + * @memberof module:config + * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} + */ + constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), + /** + * @memberof module:config + * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error + */ + ignoreUnsupportedPackets: true, + /** + * @memberof module:config + * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error + */ + ignoreMalformedPackets: false, + /** + * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only + * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable + * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). + * @memberof module:config + * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] + */ + additionalAllowedPackets: [], + /** + * @memberof module:config + * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages + */ + showVersion: false, + /** + * @memberof module:config + * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages + */ + showComment: false, + /** + * @memberof module:config + * @property {String} versionString A version string to be included in armored messages + */ + versionString: 'OpenPGP.js 6.0.0', + /** + * @memberof module:config + * @property {String} commentString A comment string to be included in armored messages + */ + commentString: 'https://openpgpjs.org', + + /** + * Max userID string length (used for parsing) + * @memberof module:config + * @property {Integer} maxUserIDLength + */ + maxUserIDLength: 1024 * 5, + /** + * Contains notatations that are considered "known". Known notations do not trigger + * validation error when the notation is marked as critical. + * @memberof module:config + * @property {Array} knownNotations + */ + knownNotations: [], + /** + * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design). + * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur + * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of + * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks. + * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases. + */ + nonDeterministicSignaturesViaNotation: true, + /** + * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API. + * When false, certain standard curves will not be supported (depending on the platform). + * @memberof module:config + * @property {Boolean} useEllipticFallback + */ + useEllipticFallback: true, + /** + * Reject insecure hash algorithms + * @memberof module:config + * @property {Set} rejectHashAlgorithms {@link module:enums.hash} + */ + rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), + /** + * Reject insecure message hash algorithms + * @memberof module:config + * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} + */ + rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), + /** + * Reject insecure public key algorithms for key generation and message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} + */ + rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), + /** + * Reject non-standard curves for key generation, message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectCurves {@link module:enums.curve} + */ + rejectCurves: new Set([enums.curve.secp256k1]) + }; + + /** + * @fileoverview This object contains global configuration values. + * @see module:config/config + * @module config + */ + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + const createRequire = () => () => {}; // Must be stripped in browser built + + const debugMode = (() => { + try { return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env } catch (e) {} return false; @@ -2045,6 +1765,8 @@ var openpgp = (function (exports) { return typeof data === 'string' || data instanceof String; }, + nodeRequire: createRequire(), + isArray: function(data) { return data instanceof Array; }, @@ -2053,6 +1775,35 @@ var openpgp = (function (exports) { isStream: isStream, + /** + * Load noble-curves lib on demand and return the requested curve function + * @param {enums.publicKey} publicKeyAlgo + * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA) + * @returns curve implementation + * @throws on unrecognized curve, or curve not implemented by noble-curve + */ + getNobleCurve: async (publicKeyAlgo, curveName) => { + if (!config.useEllipticFallback) { + throw new Error('This curve is only supported in the full build of OpenPGP.js'); + } + + const { nobleCurves } = await Promise.resolve().then(function () { return noble_curves; }); + switch (publicKeyAlgo) { + case enums.publicKey.ecdh: + case enums.publicKey.ecdsa: { + const curve = nobleCurves.get(curveName); + if (!curve) throw new Error('Unsupported curve'); + return curve; + } + case enums.publicKey.x448: + return nobleCurves.get('x448'); + case enums.publicKey.ed448: + return nobleCurves.get('ed448'); + default: + throw new Error('Unsupported curve'); + } + }, + readNumber: function (bytes) { let n = 0; for (let i = 0; i < bytes.length; i++) { @@ -2094,7 +1845,26 @@ var openpgp = (function (exports) { readMPI: function (bytes) { const bits = (bytes[0] << 8) | bytes[1]; const bytelen = (bits + 7) >>> 3; - return bytes.subarray(2, 2 + bytelen); + // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures, + // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed + // has not been authenticated (yet). + // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues. + // Also, AEAD is also not affected. + return util.readExactSubarray(bytes, 2, 2 + bytelen); + }, + + /** + * Read exactly `end - start` bytes from input. + * This is a stricter version of `.subarray`. + * @param {Uint8Array} input - Input data to parse + * @returns {Uint8Array} subarray of size always equal to `end - start` + * @throws if the input array is too short. + */ + readExactSubarray: function (input, start, end) { + if (input.length < (end - start)) { + throw new Error('Input array too short'); + } + return input.subarray(start, end); }, /** @@ -2104,6 +1874,9 @@ var openpgp = (function (exports) { * @returns {Uint8Array} Padded bytes. */ leftPad(bytes, length) { + if (bytes.length > length) { + throw new Error('Input array too long'); + } const padded = new Uint8Array(length); const offset = length - bytes.length; padded.set(bytes, offset); @@ -2159,18 +1932,10 @@ var openpgp = (function (exports) { * @returns {String} Hexadecimal representation of the array. */ uint8ArrayToHex: function (bytes) { - const r = []; - const e = bytes.length; - let c = 0; - let h; - while (c < e) { - h = bytes[c++].toString(16); - while (h.length < 2) { - h = '0' + h; - } - r.push('' + h); - } - return r.join(''); + const hexAlphabet = '0123456789abcdef'; + let s = ''; + bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; }); + return s; }, /** @@ -2381,32 +2146,30 @@ var openpgp = (function (exports) { }, /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available */ getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; }, - /** - * Get BigInteger class - * It wraps the native BigInt type if it's available - * Otherwise it relies on bn.js - * @returns {BigInteger} - * @async - */ - getBigInteger, - /** * Get native Node.js crypto api. * @returns {Object} The crypto module or 'undefined'. */ getNodeCrypto: function() { - return void('crypto'); + return this.nodeRequire('crypto'); }, getNodeZlib: function() { - return void('zlib'); + return this.nodeRequire('zlib'); }, /** @@ -2415,7 +2178,7 @@ var openpgp = (function (exports) { * @returns {Function} The Buffer constructor or 'undefined'. */ getNodeBuffer: function() { - return ({}).Buffer; + return (this.nodeRequire('buffer') || {}).Buffer; }, getHardwareConcurrency: function() { @@ -2423,15 +2186,24 @@ var openpgp = (function (exports) { return navigator.hardwareConcurrency || 1; } - const os = void('os'); // Assume we're on Node.js. + const os = this.nodeRequire('os'); // Assume we're on Node.js. return os.cpus().length; }, - isEmailAddress: function(data) { + /** + * Test email format to ensure basic compliance: + * - must include a single @ + * - no control or space unicode chars allowed + * - no backslash and square brackets (as the latter can mess with the userID parsing) + * - cannot end with a punctuation char + * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation, + * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)). + */ + isEmailAddress: function(data) { if (!util.isString(data)) { return false; } - const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/; + const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u; return re.test(data); }, @@ -2634,14 +2406,15 @@ var openpgp = (function (exports) { * provided with the application or distribution. */ - const Buffer = util.getNodeBuffer(); + + const Buffer$2 = util.getNodeBuffer(); let encodeChunk; let decodeChunk; - if (Buffer) { - encodeChunk = buf => Buffer.from(buf).toString('base64'); + if (Buffer$2) { + encodeChunk = buf => Buffer$2.from(buf).toString('base64'); decodeChunk = str => { - const b = Buffer.from(str, 'base64'); + const b = Buffer$2.from(str, 'base64'); return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); }; } else { @@ -2655,7 +2428,7 @@ var openpgp = (function (exports) { * @returns {String | ReadableStream} Radix-64 version of input string. * @static */ - function encode(data) { + function encode$1(data) { let buf = new Uint8Array(); return transform(data, value => { buf = util.concatUint8Array([buf, value]); @@ -2679,7 +2452,7 @@ var openpgp = (function (exports) { * @returns {Uint8Array | ReadableStream} Binary array version of input string. * @static */ - function decode(data) { + function decode$2(data) { let buf = ''; return transform(data, value => { buf += value; @@ -2715,7 +2488,7 @@ var openpgp = (function (exports) { * @returns {Uint8Array} An array of 8-bit integers. */ function b64ToUint8Array(base64) { - return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); + return decode$2(base64.replace(/-/g, '+').replace(/_/g, '/')); } /** @@ -2725,254 +2498,30 @@ var openpgp = (function (exports) { * @returns {String} Base-64 encoded string. */ function uint8ArrayToB64(bytes, url) { - let encoded = encode(bytes).replace(/[\r\n]/g, ''); - if (url) { + let encoded = encode$1(bytes).replace(/[\r\n]/g, ''); + { encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); } return encoded; } // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - var config = { - /** - * @memberof module:config - * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} - */ - preferredHashAlgorithm: enums.hash.sha256, - /** - * @memberof module:config - * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} - */ - preferredSymmetricAlgorithm: enums.symmetric.aes256, - /** - * @memberof module:config - * @property {Integer} compression Default compression algorithm {@link module:enums.compression} - */ - preferredCompressionAlgorithm: enums.compression.uncompressed, - /** - * @memberof module:config - * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9 - */ - deflateLevel: 6, - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} - * @memberof module:config - * @property {Boolean} aeadProtect - */ - aeadProtect: false, - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. - * @memberof module:config - * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} - */ - preferredAEADAlgorithm: enums.aead.eax, - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. - * Must be an integer value from 0 to 56. - * @memberof module:config - * @property {Integer} aeadChunkSizeByte - */ - aeadChunkSizeByte: 12, - /** - * Use V5 keys. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @memberof module:config - * @property {Boolean} v5Keys - */ - v5Keys: false, - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - * @memberof module:config - * @property {Integer} s2kIterationCountByte - */ - s2kIterationCountByte: 224, - /** - * Allow decryption of messages without integrity protection. - * This is an **insecure** setting: - * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. - * - it enables downgrade attacks against integrity-protected messages. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedMessages - */ - allowUnauthenticatedMessages: false, - /** - * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to - * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible - * and deferring checking their integrity until the decrypted stream has been read in full. - * - * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedStream - */ - allowUnauthenticatedStream: false, - /** - * @memberof module:config - * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum - */ - checksumRequired: false, - /** - * Minimum RSA key size allowed for key generation and message signing, verification and encryption. - * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. - * @memberof module:config - * @property {Number} minRSABits - */ - minRSABits: 2047, - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - * @memberof module:config - * @property {Boolean} passwordCollisionCheck - */ - passwordCollisionCheck: false, - /** - * @memberof module:config - * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored - */ - revocationsExpire: false, - /** - * Allow decryption using RSA keys without `encrypt` flag. - * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug - * where key flags were ignored when selecting a key for encryption. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureDecryptionWithSigningKeys: false, - /** - * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. - * Instead, a verification key will also be consider valid as long as it is valid at the current time. - * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, - * and have self-signature's creation date that does not match the primary key creation date. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureVerificationWithReformattedKeys: false, - - /** - * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). - * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: - * - new/incoming messages are automatically decrypted (without user interaction); - * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). - * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. - * @memberof module:config - * @property {Boolean} constantTimePKCS1Decryption - */ - constantTimePKCS1Decryption: false, - /** - * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. - * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. - * However, the more algorithms are added, the slower the decryption procedure becomes. - * @memberof module:config - * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} - */ - constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), - - /** - * @memberof module:config - * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available - */ - minBytesForWebCrypto: 1000, - /** - * @memberof module:config - * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error - */ - ignoreUnsupportedPackets: true, - /** - * @memberof module:config - * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error - */ - ignoreMalformedPackets: false, - /** - * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only - * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable - * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). - * @memberof module:config - * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] - */ - additionalAllowedPackets: [], - /** - * @memberof module:config - * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages - */ - showVersion: false, - /** - * @memberof module:config - * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages - */ - showComment: false, - /** - * @memberof module:config - * @property {String} versionString A version string to be included in armored messages - */ - versionString: 'OpenPGP.js 5.11.2', - /** - * @memberof module:config - * @property {String} commentString A comment string to be included in armored messages - */ - commentString: 'https://openpgpjs.org', - - /** - * Max userID string length (used for parsing) - * @memberof module:config - * @property {Integer} maxUserIDLength - */ - maxUserIDLength: 1024 * 5, - /** - * Contains notatations that are considered "known". Known notations do not trigger - * validation error when the notation is marked as critical. - * @memberof module:config - * @property {Array} knownNotations - */ - knownNotations: [], - /** - * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. - * When false, certain standard curves will not be supported (depending on the platform). - * Note: the indutny/elliptic curve library is not designed to be constant time. - * @memberof module:config - * @property {Boolean} useIndutnyElliptic - */ - useIndutnyElliptic: true, - /** - * Reject insecure hash algorithms - * @memberof module:config - * @property {Set} rejectHashAlgorithms {@link module:enums.hash} - */ - rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), - /** - * Reject insecure message hash algorithms - * @memberof module:config - * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} - */ - rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), - /** - * Reject insecure public key algorithms for key generation and message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} - */ - rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), - /** - * Reject non-standard curves for key generation, message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectCurves {@link module:enums.curve} - */ - rejectCurves: new Set([enums.curve.secp256k1]) - }; - - /** - * @fileoverview This object contains global configuration values. - * @see module:config/config - * @module config - */ - - // GPG4Browsers - An OpenPGP implementation in javascript /** * Finds out which Ascii Armoring type is used. Throws error if unknown type. @@ -3000,33 +2549,33 @@ var openpgp = (function (exports) { // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipartSection; - } else + } // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipartLast; - } else + } // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; - } else + } // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; - } else + } // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.publicKey; - } else + } // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.privateKey; - } else + } // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE @@ -3060,7 +2609,6 @@ var openpgp = (function (exports) { return result; } - /** * Calculates a checksum over the given data and returns it base64 encoded * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for @@ -3069,7 +2617,7 @@ var openpgp = (function (exports) { */ function getCheckSum(data) { const crc = createcrc24(data); - return encode(crc); + return encode$1(crc); } // https://create.stephan-brumme.com/crc32/#slicing-by-8-overview @@ -3102,7 +2650,7 @@ var openpgp = (function (exports) { } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness - const isLittleEndian = (function() { + const isLittleEndian$1 = (function() { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */); // Int16Array uses the platform's endianness. @@ -3118,7 +2666,7 @@ var openpgp = (function (exports) { function createcrc24(input) { let crc = 0xCE04B7; return transform(input, value => { - const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0; + const len32 = isLittleEndian$1 ? Math.floor(value.length / 4) : 0; const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32); for (let i = 0; i < len32; i++) { crc ^= arr32[i]; @@ -3142,7 +2690,7 @@ var openpgp = (function (exports) { * @private * @param {Array} headers - Armor headers */ - function verifyHeaders(headers) { + function verifyHeaders$1(headers) { for (let i = 0; i < headers.length; i++) { if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); @@ -3154,24 +2702,21 @@ var openpgp = (function (exports) { } /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param {String} text - OpenPGP armored message part - * @returns {Object} An object with attribute "body" containing the body. - * and an attribute "checksum" containing the checksum. + * Remove the (optional) checksum from an armored message. + * @param {String} text - OpenPGP armored message + * @returns {String} The body of the armored message. * @private */ - function splitChecksum(text) { + function removeChecksum(text) { let body = text; - let checksum = ''; const lastEquals = text.lastIndexOf('='); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); - checksum = text.slice(lastEquals + 1).substr(0, 4); } - return { body: body, checksum: checksum }; + return body; } /** @@ -3183,7 +2728,7 @@ var openpgp = (function (exports) { * @async * @static */ - function unarmor(input, config$1 = config) { + function unarmor(input) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { @@ -3196,8 +2741,7 @@ var openpgp = (function (exports) { let headersDone; let text = []; let textDone; - let checksum; - let data = decode(transformPair(input, async (readable, writable) => { + const data = decode$2(transformPair(input, async (readable, writable) => { const reader = getReader(readable); try { while (true) { @@ -3218,21 +2762,21 @@ var openpgp = (function (exports) { if (!reEmptyLine.test(line)) { lastHeaders.push(line); } else { - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); headersDone = true; - if (textDone || type !== 2) { + if (textDone || type !== enums.armor.signed) { resolve({ text, data, headers, type }); break; } } - } else if (!textDone && type === 2) { + } else if (!textDone && type === enums.armor.signed) { if (!reSplit.test(line)) { // Reverse dash-escaping for msg text.push(line.replace(/^- /, '')); } else { text = text.join('\r\n'); textDone = true; - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); lastHeaders = []; headersDone = false; } @@ -3262,9 +2806,8 @@ var openpgp = (function (exports) { if (parts.length === 1) { throw new Error('Misformed armored text'); } - const split = splitChecksum(parts[0].slice(0, -1)); - checksum = split.checksum; - await writer.write(split.body); + const body = removeChecksum(parts[0].slice(0, -1)); + await writer.write(body); break; } } @@ -3274,24 +2817,6 @@ var openpgp = (function (exports) { await writer.abort(e); } })); - data = transformPair(data, async (readable, writable) => { - const checksumVerified = readToEnd(getCheckSum(passiveClone(readable))); - checksumVerified.catch(() => {}); - await pipe(readable, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - const checksumVerifiedString = (await checksumVerified).replace('\n', ''); - if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) { - throw new Error('Ascii armor integrity check failed'); - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); } catch (e) { reject(e); } @@ -3311,10 +2836,13 @@ var openpgp = (function (exports) { * @param {Integer} [partIndex] * @param {Integer} [partTotal] * @param {String} [customComment] - Additional comment to add to the armored string + * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum + * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks) + * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {String | ReadableStream} Armored text. * @static */ - function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) { + function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) { let text; let hash; if (messageType === enums.armor.signed) { @@ -3322,59 +2850,62 @@ var openpgp = (function (exports) { hash = body.hash; body = body.data; } - const bodyClone = passiveClone(body); + // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug + // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071) + const maybeBodyClone = emitChecksum && passiveClone(body); + const result = []; switch (messageType) { case enums.armor.multipartSection: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); break; case enums.armor.multipartLast: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); break; case enums.armor.signed: result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); - result.push('Hash: ' + hash + '\n\n'); + result.push(hash ? `Hash: ${hash}\n\n` : '\n'); result.push(text.replace(/^-/mg, '- -')); result.push('\n-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; case enums.armor.message: result.push('-----BEGIN PGP MESSAGE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE-----\n'); break; case enums.armor.publicKey: result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); break; case enums.armor.privateKey: result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); break; case enums.armor.signature: result.push('-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; } @@ -3382,40690 +2913,25657 @@ var openpgp = (function (exports) { return util.concat(result); } - // GPG4Browsers - An OpenPGP implementation in javascript + async function getLegacyCipher(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + throw new Error('Not a legacy cipher'); + case enums.symmetric.cast5: + case enums.symmetric.blowfish: + case enums.symmetric.twofish: + case enums.symmetric.tripledes: { + const { legacyCiphers } = await Promise.resolve().then(function () { return legacy_ciphers; }); + const cipher = legacyCiphers.get(algo); + if (!cipher) { + throw new Error('Unsupported cipher algorithm'); + } + return cipher; + } + default: + throw new Error('Unsupported cipher algorithm'); + } + } /** - * Implementation of type key id - * - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. + * Get block size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ - class KeyID { - constructor() { - this.bytes = ''; - } - - /** - * Parsing method for a key id - * @param {Uint8Array} bytes - Input to read the key id from - */ - read(bytes) { - this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); - return this.bytes.length; - } - - /** - * Serializes the Key ID - * @returns {Uint8Array} Key ID as a Uint8Array. - */ - write() { - return util.stringToUint8Array(this.bytes); - } - - /** - * Returns the Key ID represented as a hexadecimal string - * @returns {String} Key ID as a hexadecimal string. - */ - toHex() { - return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); - } - - /** - * Checks equality of Key ID's - * @param {KeyID} keyID - * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard - */ - equals(keyID, matchWildcard = false) { - return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; - } - - /** - * Checks to see if the Key ID is unset - * @returns {Boolean} True if the Key ID is null. - */ - isNull() { - return this.bytes === ''; - } - - /** - * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) - * @returns {Boolean} True if this is a wildcard Key ID. - */ - isWildcard() { - return /^0+$/.test(this.toHex()); - } - - static mapToHex(keyID) { - return keyID.toHex(); - } - - static fromID(hex) { - const keyID = new KeyID(); - keyID.read(util.hexToUint8Array(hex)); - return keyID; + function getCipherBlockSize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 16; + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + case enums.symmetric.tripledes: + return 8; + default: + throw new Error('Unsupported cipher'); } + } - static wildcard() { - const keyID = new KeyID(); - keyID.read(new Uint8Array(8)); - return keyID; + /** + * Get key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ + function getCipherKeySize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + return 16; + case enums.symmetric.aes192: + case enums.symmetric.tripledes: + return 24; + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 32; + default: + throw new Error('Unsupported cipher'); } } /** - * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. - * @author Artem S Vybornov - * @license MIT + * Get block and key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ - var AES_asm = function () { - - /** - * Galois Field stuff init flag - */ - var ginit_done = false; + function getCipherParams(algo) { + return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) }; + } - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; + var cipher = /*#__PURE__*/Object.freeze({ + __proto__: null, + getCipherParams: getCipherParams, + getLegacyCipher: getLegacyCipher + }); - /** - * Init Galois Field tables - */ - function ginit() { - gexp3 = [], - glog3 = []; + /** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ - var a = 1, c, d; - for (c = 0; c < 255; c++) { - gexp3[c] = a; - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if (d === 0x80) a ^= 0x1b; - a ^= gexp3[c]; + // MD5 Digest + async function md5(entree) { + const digest = md51(util.uint8ArrayToString(entree)); + return util.hexToUint8Array(hex(digest)); + } - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; + function md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; - ginit_done = true; - } + a = ff(a, b, c, d, k[0], 7, -680876936); + d = ff(d, a, b, c, k[1], 12, -389564586); + c = ff(c, d, a, b, k[2], 17, 606105819); + b = ff(b, c, d, a, k[3], 22, -1044525330); + a = ff(a, b, c, d, k[4], 7, -176418897); + d = ff(d, a, b, c, k[5], 12, 1200080426); + c = ff(c, d, a, b, k[6], 17, -1473231341); + b = ff(b, c, d, a, k[7], 22, -45705983); + a = ff(a, b, c, d, k[8], 7, 1770035416); + d = ff(d, a, b, c, k[9], 12, -1958414417); + c = ff(c, d, a, b, k[10], 17, -42063); + b = ff(b, c, d, a, k[11], 22, -1990404162); + a = ff(a, b, c, d, k[12], 7, 1804603682); + d = ff(d, a, b, c, k[13], 12, -40341101); + c = ff(c, d, a, b, k[14], 17, -1502002290); + b = ff(b, c, d, a, k[15], 22, 1236535329); - /** - * Galois Field multiplication - * @param {number} a - * @param {number} b - * @return {number} - */ - function gmul(a, b) { - var c = gexp3[(glog3[a] + glog3[b]) % 255]; - if (a === 0 || b === 0) c = 0; - return c; - } + a = gg(a, b, c, d, k[1], 5, -165796510); + d = gg(d, a, b, c, k[6], 9, -1069501632); + c = gg(c, d, a, b, k[11], 14, 643717713); + b = gg(b, c, d, a, k[0], 20, -373897302); + a = gg(a, b, c, d, k[5], 5, -701558691); + d = gg(d, a, b, c, k[10], 9, 38016083); + c = gg(c, d, a, b, k[15], 14, -660478335); + b = gg(b, c, d, a, k[4], 20, -405537848); + a = gg(a, b, c, d, k[9], 5, 568446438); + d = gg(d, a, b, c, k[14], 9, -1019803690); + c = gg(c, d, a, b, k[3], 14, -187363961); + b = gg(b, c, d, a, k[8], 20, 1163531501); + a = gg(a, b, c, d, k[13], 5, -1444681467); + d = gg(d, a, b, c, k[2], 9, -51403784); + c = gg(c, d, a, b, k[7], 14, 1735328473); + b = gg(b, c, d, a, k[12], 20, -1926607734); - /** - * Galois Field reciprocal - * @param {number} a - * @return {number} - */ - function ginv(a) { - var i = gexp3[255 - glog3[a]]; - if (a === 0) i = 0; - return i; - } + a = hh(a, b, c, d, k[5], 4, -378558); + d = hh(d, a, b, c, k[8], 11, -2022574463); + c = hh(c, d, a, b, k[11], 16, 1839030562); + b = hh(b, c, d, a, k[14], 23, -35309556); + a = hh(a, b, c, d, k[1], 4, -1530992060); + d = hh(d, a, b, c, k[4], 11, 1272893353); + c = hh(c, d, a, b, k[7], 16, -155497632); + b = hh(b, c, d, a, k[10], 23, -1094730640); + a = hh(a, b, c, d, k[13], 4, 681279174); + d = hh(d, a, b, c, k[0], 11, -358537222); + c = hh(c, d, a, b, k[3], 16, -722521979); + b = hh(b, c, d, a, k[6], 23, 76029189); + a = hh(a, b, c, d, k[9], 4, -640364487); + d = hh(d, a, b, c, k[12], 11, -421815835); + c = hh(c, d, a, b, k[15], 16, 530742520); + b = hh(b, c, d, a, k[2], 23, -995338651); - /** - * AES stuff init flag - */ - var aes_init_done = false; + a = ii(a, b, c, d, k[0], 6, -198630844); + d = ii(d, a, b, c, k[7], 10, 1126891415); + c = ii(c, d, a, b, k[14], 15, -1416354905); + b = ii(b, c, d, a, k[5], 21, -57434055); + a = ii(a, b, c, d, k[12], 6, 1700485571); + d = ii(d, a, b, c, k[3], 10, -1894986606); + c = ii(c, d, a, b, k[10], 15, -1051523); + b = ii(b, c, d, a, k[1], 21, -2054922799); + a = ii(a, b, c, d, k[8], 6, 1873313359); + d = ii(d, a, b, c, k[15], 10, -30611744); + c = ii(c, d, a, b, k[6], 15, -1560198380); + b = ii(b, c, d, a, k[13], 21, 1309151649); + a = ii(a, b, c, d, k[4], 6, -145523070); + d = ii(d, a, b, c, k[11], 10, -1120210379); + c = ii(c, d, a, b, k[2], 15, 718787259); + b = ii(b, c, d, a, k[9], 21, -343485551); - /** - * Encryption, Decryption, S-Box and KeyTransform tables - * - * @type {number[]} - */ - var aes_sbox; + x[0] = add32(a, x[0]); + x[1] = add32(b, x[1]); + x[2] = add32(c, x[2]); + x[3] = add32(d, x[3]); + } - /** - * @type {number[]} - */ - var aes_sinv; + function cmn(q, a, b, x, s, t) { + a = add32(add32(a, q), add32(x, t)); + return add32((a << s) | (a >>> (32 - s)), b); + } - /** - * @type {number[][]} - */ - var aes_enc; + function ff(a, b, c, d, x, s, t) { + return cmn((b & c) | ((~b) & d), a, b, x, s, t); + } - /** - * @type {number[][]} - */ - var aes_dec; + function gg(a, b, c, d, x, s, t) { + return cmn((b & d) | (c & (~d)), a, b, x, s, t); + } - /** - * Init AES tables - */ - function aes_init() { - if (!ginit_done) ginit(); + function hh(a, b, c, d, x, s, t) { + return cmn(b ^ c ^ d, a, b, x, s, t); + } - // Calculates AES S-Box value - function _s(a) { - var c, s, x; - s = x = ginv(a); - for (c = 0; c < 4; c++) { - s = ((s << 1) | (s >>> 7)) & 255; - x ^= s; - } - x ^= 99; - return x; - } - - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [[], [], [], []], - aes_dec = [[], [], [], []]; - - for (var i = 0; i < 256; i++) { - var s = _s(i); - - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; - - // Ecryption and Decryption tables - aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s); - aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i); - // Rotate tables - for (var t = 1; t < 4; t++) { - aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24); - aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24); - } - } + function ii(a, b, c, d, x, s, t) { + return cmn(c ^ (b | (~d)), a, b, x, s, t); + } - aes_init_done = true; + function md51(s) { + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; + for (i = 64; i <= s.length; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); } - - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-     * 0x0000   encryption key schedule
-     * 0x0400   decryption key schedule
-     * 0x0800   sbox
-     * 0x0c00   inv sbox
-     * 0x1000   encryption tables
-     * 0x2000   decryption tables
-     * 0x3000   reserved (future GCM multiplication lookup table)
-     * 0x4000   data
-     * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param foreign - ignored - * @param buffer - heap buffer to link with - */ - var wrapper = function (foreign, buffer) { - // Init AES stuff for the first time - if (!aes_init_done) aes_init(); - - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set(aes_sbox, 0x0800 >> 2); - heap.set(aes_sinv, 0x0c00 >> 2); - for (var i = 0; i < 4; i++) { - heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2); - heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2); + s = s.substring(i - 64); + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < s.length; i++) { + tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + } + tail[i >> 2] |= 0x80 << ((i % 4) << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i++) { + tail[i] = 0; } + } + tail[14] = n * 8; + md5cycle(state, tail); + return state; + } - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {number} k0 - key vector components - * @param {number} k1 - key vector components - * @param {number} k2 - key vector components - * @param {number} k3 - key vector components - * @param {number} k4 - key vector components - * @param {number} k5 - key vector components - * @param {number} k6 - key vector components - * @param {number} k7 - key vector components - */ - function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { - var ekeys = heap.subarray(0x000, 60), - dkeys = heap.subarray(0x100, 0x100 + 60); - - // Encryption key schedule - ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); - for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { - var k = ekeys[i - 1]; - if ((i % ks === 0) || (ks === 8 && i % ks === 4)) { - k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; - } - if (i % ks === 0) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0); - } - ekeys[i] = ekeys[i - ks] ^ k; - } - - // Decryption key schedule - for (var j = 0; j < i; j += 4) { - for (var jj = 0; jj < 4; jj++) { - var k = ekeys[i - (4 + j) + (4 - jj) % 4]; - if (j < 4 || j >= i - 4) { - dkeys[j + jj] = k; - } else { - dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] - ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] - ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] - ^ aes_dec[3][aes_sbox[k & 255]]; - } - } - } - - // Set rounds number - asm.set_rounds(ks + 5); - } - - // create library object with necessary properties - var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array}; - - var asm = function (stdlib, foreign, buffer) { - "use asm"; - - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); - - /** - * AES core - * @param {number} k - precomputed key schedule offset - * @param {number} s - precomputed sbox table offset - * @param {number} t - precomputed round table offset - * @param {number} r - number of inner rounds to perform - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _core(k, s, t, r, x0, x1, x2, x3) { - k = k | 0; - s = s | 0; - t = t | 0; - r = r | 0; - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k | 0) >> 2], - x1 = x1 ^ HEAP[(k | 4) >> 2], - x2 = x2 ^ HEAP[(k | 8) >> 2], - x3 = x3 ^ HEAP[(k | 12) >> 2]; - - // round 1..r - for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) { - y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } - - // final round - S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - } - - /** - * ECB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } - - /** - * ECB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - } - - - /** - * CBC mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } - - /** - * CBC mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * CFB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } - - - /** - * CFB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * OFB mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ofb(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * CTR mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ctr(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); - - N3 = (~M3 & N3) | M3 & (N3 + 1); - N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0)); - N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0)); - N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0)); - - S0 = S0 ^ x0; - S1 = S1 ^ x1; - S2 = S2 ^ x2; - S3 = S3 ^ x3; - } - - /** - * GCM mode MAC calculation - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _gcm_mac(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0 | 0, - y1 = H1 | 0, - y2 = H2 | 0, - y3 = H3 | 0; - - for (; (i | 0) < 128; i = (i + 1) | 0) { - if (y0 >>> 31) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } - - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); - - c = x3 & 1; - - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); - - if (c) x0 = x0 ^ 0xe1000000; - } - - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } - - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {number} r - number if inner AES rounds - */ - function set_rounds(r) { - r = r | 0; - R = r; - } - - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {number} s0 - state vector - * @param {number} s1 - state vector - * @param {number} s2 - state vector - * @param {number} s3 - state vector - */ - function set_state(s0, s1, s2, s3) { - s0 = s0 | 0; - s1 = s1 | 0; - s2 = s2 | 0; - s3 = s3 | 0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } - - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {number} i0 - iv vector - * @param {number} i1 - iv vector - * @param {number} i2 - iv vector - * @param {number} i3 - iv vector - */ - function set_iv(i0, i1, i2, i3) { - i0 = i0 | 0; - i1 = i1 | 0; - i2 = i2 | 0; - i3 = i3 | 0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } - - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} n0 - nonce vector - * @param {number} n1 - nonce vector - * @param {number} n2 - nonce vector - * @param {number} n3 - nonce vector - */ - function set_nonce(n0, n1, n2, n3) { - n0 = n0 | 0; - n1 = n1 | 0; - n2 = n2 | 0; - n3 = n3 | 0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } - - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} m0 - counter mask vector - * @param {number} m1 - counter mask vector - * @param {number} m2 - counter mask vector - * @param {number} m3 - counter mask vector - */ - function set_mask(m0, m1, m2, m3) { - m0 = m0 | 0; - m1 = m1 | 0; - m2 = m2 | 0; - m3 = m3 | 0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } - - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} c0 - counter vector - * @param {number} c1 - counter vector - * @param {number} c2 - counter vector - * @param {number} c3 - counter vector - */ - function set_counter(c0, c1, c2, c3) { - c0 = c0 | 0; - c1 = c1 | 0; - c2 = c2 | 0; - c3 = c3 | 0; - - N3 = (~M3 & N3) | M3 & c3, - N2 = (~M2 & N2) | M2 & c2, - N1 = (~M1 & N1) | M1 & c1, - N0 = (~M0 & N0) | M0 & c0; - } - - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_state(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - return 16; - } - - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_iv(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = I0 >>> 24, - DATA[pos | 1] = I0 >>> 16 & 255, - DATA[pos | 2] = I0 >>> 8 & 255, - DATA[pos | 3] = I0 & 255, - DATA[pos | 4] = I1 >>> 24, - DATA[pos | 5] = I1 >>> 16 & 255, - DATA[pos | 6] = I1 >>> 8 & 255, - DATA[pos | 7] = I1 & 255, - DATA[pos | 8] = I2 >>> 24, - DATA[pos | 9] = I2 >>> 16 & 255, - DATA[pos | 10] = I2 >>> 8 & 255, - DATA[pos | 11] = I2 & 255, - DATA[pos | 12] = I3 >>> 24, - DATA[pos | 13] = I3 >>> 16 & 255, - DATA[pos | 14] = I3 >>> 8 & 255, - DATA[pos | 15] = I3 & 255; - - return 16; - } - - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init() { - _ecb_enc(0, 0, 0, 0); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } - - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function cipher(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; - - var ret = 0; + /* there needs to be support for Unicode here, + * unless we pretend that we can redefine the MD-5 + * algorithm for multi-byte characters (perhaps + * by adding every four 16-bit characters and + * shortening the sum to 32 bits). Otherwise + * I suggest performing MD-5 as if every character + * was two bytes--e.g., 0040 0025 = @%--but then + * how will an ordinary MD-5 sum be matched? + * There is no way to standardize text to something + * like UTF-8 before transformation; speed cost is + * utterly prohibitive. The JavaScript standard + * itself needs to look at this: it should start + * providing access to strings as preformed UTF-8 + * 8-bit unsigned value arrays. + */ + function md5blk(s) { /* I figured global was faster. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << + 24); + } + return md5blks; + } - if (pos & 15) return -1; + const hex_chr = '0123456789abcdef'.split(''); - while ((len | 0) >= 16) { - _cipher_modes[mode & 7]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); + function rhex(n) { + let s = ''; + let j = 0; + for (; j < 4; j++) { + s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; + } + return s; + } - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } + function hex(x) { + for (let i = 0; i < x.length; i++) { + x[i] = rhex(x[i]); + } + return x.join(''); + } - return ret | 0; - } + /* this function is much faster, + so if possible we use it. Some IEs + are the only ones I know of that + need the idiotic second function, + generated by an if clause. */ - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function mac(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; + function add32(a, b) { + return (a + b) & 0xFFFFFFFF; + } - var ret = 0; + /** + * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. + * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} + * @see {@link https://github.com/indutny/hash.js|hash.js} + * @module crypto/hash + */ - if (pos & 15) return -1; - while ((len | 0) >= 16) { - _mac_modes[mode & 1]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); + const webCrypto$a = util.getWebCrypto(); + const nodeCrypto$9 = util.getNodeCrypto(); + const nodeCryptoHashes = nodeCrypto$9 && nodeCrypto$9.getHashes(); - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } + function nodeHash(type) { + if (!nodeCrypto$9 || !nodeCryptoHashes.includes(type)) { + return; + } + return async function (data) { + const shasum = nodeCrypto$9.createHash(type); + return transform(data, value => { + shasum.update(value); + }, () => new Uint8Array(shasum.digest())); + }; + } - return ret | 0; - } + function nobleHash(nobleHashName, webCryptoHashName) { + const getNobleHash = async () => { + const { nobleHashes } = await Promise.resolve().then(function () { return noble_hashes; }); + const hash = nobleHashes.get(nobleHashName); + if (!hash) throw new Error('Unsupported hash'); + return hash; + }; - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; + return async function(data) { + if (isArrayStream(data)) { + data = await readToEnd(data); + } + if (util.isStream(data)) { + const hash = await getNobleHash(); - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [_cbc_enc, _gcm_mac]; + const hashInstance = hash.create(); + return transform(data, value => { + hashInstance.update(value); + }, () => hashInstance.digest()); + } else if (webCrypto$a && webCryptoHashName) { + return new Uint8Array(await webCrypto$a.digest(webCryptoHashName, data)); + } else { + const hash = await getNobleHash(); - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter: set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac, - }; - }(stdlib, foreign, buffer); + return hash(data); + } + }; + } - asm.set_key = set_key; + var hash$1 = { - return asm; - }; + /** @see module:md5 */ + md5: nodeHash('md5') || md5, + sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'), + sha224: nodeHash('sha224') || nobleHash('sha224'), + sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'), + sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'), + sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'), + ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'), + sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'), + sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'), /** - * AES enciphering mode constants - * @enum {number} - * @const + * Create a hash on the specified data using the specified algorithm + * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param {Uint8Array} data - Data to be hashed + * @returns {Promise} Hash value. */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7, + digest: function(algo, data) { + switch (algo) { + case enums.hash.md5: + return this.md5(data); + case enums.hash.sha1: + return this.sha1(data); + case enums.hash.ripemd: + return this.ripemd(data); + case enums.hash.sha256: + return this.sha256(data); + case enums.hash.sha384: + return this.sha384(data); + case enums.hash.sha512: + return this.sha512(data); + case enums.hash.sha224: + return this.sha224(data); + case enums.hash.sha3_256: + return this.sha3_256(data); + case enums.hash.sha3_512: + return this.sha3_512(data); + default: + throw new Error('Unsupported hash function'); + } }, - /** - * AES deciphering mode constants - * @enum {number} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7, - }, - - /** - * AES MAC mode constants - * @enum {number} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1, - }; - /** - * Heap data offset - * @type {number} - * @const + * Returns the hash size in bytes of the specified hash algorithm type + * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns {Integer} Size in bytes of the resulting hash. */ - wrapper.HEAP_DATA = 0x4000; - - return wrapper; - }(); - - function is_bytes(a) { - return a instanceof Uint8Array; - } - function _heap_init(heap, heapSize) { - const size = heap ? heap.byteLength : heapSize || 65536; - if (size & 0xfff || size <= 0) - throw new Error('heap size must be a positive integer and a multiple of 4096'); - heap = heap || new Uint8Array(new ArrayBuffer(size)); - return heap; - } - function _heap_write(heap, hpos, data, dpos, dlen) { - const hlen = heap.length - hpos; - const wlen = hlen < dlen ? hlen : dlen; - heap.set(data.subarray(dpos, dpos + wlen), hpos); - return wlen; - } - function joinBytes(...arg) { - const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0); - const ret = new Uint8Array(totalLenght); - let cursor = 0; - for (let i = 0; i < arg.length; i++) { - ret.set(arg[i], cursor); - cursor += arg[i].length; - } - return ret; - } - - class IllegalStateError extends Error { - constructor(...args) { - super(...args); + getHashByteLength: function(algo) { + switch (algo) { + case enums.hash.md5: + return 16; + case enums.hash.sha1: + case enums.hash.ripemd: + return 20; + case enums.hash.sha256: + return 32; + case enums.hash.sha384: + return 48; + case enums.hash.sha512: + return 64; + case enums.hash.sha224: + return 28; + case enums.hash.sha3_256: + return 32; + case enums.hash.sha3_512: + return 64; + default: + throw new Error('Invalid hash algorithm.'); } + } + }; + + function isBytes$2(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } - class IllegalArgumentError extends Error { - constructor(...args) { - super(...args); - } + function bytes$1(b, ...lengths) { + if (!isBytes$2(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); + } + function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); } - class SecurityError extends Error { - constructor(...args) { - super(...args); + function output$1(out, instance) { + bytes$1(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } - const heap_pool = []; - const asm_pool = []; - class AES { - constructor(key, iv, padding = true, mode, heap, asm) { - this.pos = 0; - this.len = 0; - this.mode = mode; - // The AES object state - this.pos = 0; - this.len = 0; - this.key = key; - this.iv = iv; - this.padding = padding; - // The AES "worker" - this.acquire_asm(heap, asm); - } - acquire_asm(heap, asm) { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA); - this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer); - this.reset(this.key, this.iv); - } - return { heap: this.heap, asm: this.asm }; + /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ + // Cast array to different type + const u8$1 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); + const u32$2 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + // Cast array to view + const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + // big-endian hardware is rare. Just in case someone still decides to run ciphers: + // early-throw an error because we don't support BE yet. + const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; + if (!isLE$1) + throw new Error('Non little-endian hardware is not supported'); + /** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ + function utf8ToBytes$2(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 + } + /** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ + function toBytes$1(data) { + if (typeof data === 'string') + data = utf8ToBytes$2(data); + else if (isBytes$2(data)) + data = copyBytes(data); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; + } + /** + * Copies several Uint8Arrays into one. + */ + function concatBytes$2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes$1(a); + sum += a.length; } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool.push(this.heap); - asm_pool.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - reset(key, iv) { - const { asm } = this.acquire_asm(); - // Key - const keylen = key.length; - if (keylen !== 16 && keylen !== 24 && keylen !== 32) - throw new IllegalArgumentError('illegal key size'); - const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); - asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0); - // IV - if (iv !== undefined) { - if (iv.length !== 16) - throw new IllegalArgumentError('illegal iv size'); - let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); - asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); - } - else { - asm.set_iv(0, 0, 0, 0); - } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; } - AES_Encrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - let result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; + return res; + } + // Compares 2 u8a-s in kinda constant time + function equalBytes$1(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; + } + /** + * @__NO_SIDE_EFFECTS__ + */ + const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; + }; + // Polyfill for Safari 14 + function setBigUint64$1(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = 0; + const l = 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); + } + // Is byte array aligned to 4 byte offset (u32)? + function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; + } + // copy bytes to new u8a (aligned). Because Buffer.slice is broken. + function copyBytes(bytes) { + return Uint8Array.from(bytes); + } + function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } + } + + // GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. + // Implemented in terms of GHash with conversion function for keys + // GCM GHASH from NIST SP800-38d, SIV from RFC 8452. + // https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf + // GHASH modulo: x^128 + x^7 + x^2 + x + 1 + // POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 + const BLOCK_SIZE$1 = 16; + // TODO: rewrite + // temporary padding buffer + const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); + const ZEROS32 = u32$2(ZEROS16); + const POLY$1 = 0xe1; // v = 2*v % POLY + // v = 2*v % POLY + // NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x + // We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) + const mul2$1 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly + }; + }; + const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; + /** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ + function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; + } + const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; + }; + class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE$1; + this.outputLen = BLOCK_SIZE$1; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes$1(key); + bytes$1(key, 16); + const kView = createView$1(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); } } - this.pos = pos; - this.len = len; - return result; - } - AES_Encrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let plen = 16 - (len % 16); - let rlen = len; - if (this.hasOwnProperty('padding')) { - if (this.padding) { - for (let p = 0; p < plen; ++p) { - heap[pos + len + p] = plen; + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; } - len += plen; - rlen = len; - } - else if (len % 16) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); } } - else { - len += plen; + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + const left = data.length % BLOCK_SIZE$1; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + clean(ZEROS32); // clean tmp buffer } - const result = new Uint8Array(rlen); - if (len) - asm.cipher(amode, hpos + pos, len); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - AES_Decrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let plen = 0; - let wlen = 0; - if (this.padding) { - plen = len + dlen - rlen || 16; - rlen -= plen; + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE$1); + this.digestInto(res); + this.destroy(); + return res; + } + } + class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes$1(key); + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const left = data.length % BLOCK_SIZE$1; + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + clean(ZEROS32); } - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; + return this; + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } + } + function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes$1(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; + } + const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); + wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + + // prettier-ignore + /* + AES (Advanced Encryption Standard) aka Rijndael block cipher. + + Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: + 1. **S-box**, table substitution + 2. **Shift rows**, cyclic shift left of all rows of data array + 3. **Mix columns**, multiplying every column by fixed polynomial + 4. **Add round key**, round_key xor i-th column of array + + Resources: + - FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf + - Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf + */ + const BLOCK_SIZE = 16; + const BLOCK_SIZE32 = 4; + const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); + const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 + // TODO: remove multiplication, binary ops only + function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); + } + function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; + } + // AES S-box is generated using finite field inversion, + // an affine transform, and xor of a constant 0x63. + const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; + })(); + // Inverted S-box + const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); + // Rotate u32 by 8 + const rotr32_8 = (n) => (n << 24) | (n >>> 8); + const rotl32_8 = (n) => (n << 8) | (n >>> 24); + // The byte swap operation for uint32 (LE<->BE) + const byteSwap$1 = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); + // T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: + // - LE instead of BE + // - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; + // so index is u16, instead of u8. This speeds up things, unexpectedly + function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; + } + const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); + const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); + const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; + })(); + function expandKeyLE(key) { + bytes$1(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const toClean = []; + if (!isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = u32$2(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; + } + function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; + } + // Apply tables + function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); + } + function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); + } + function encrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + // Can't be merged with encrypt: arg positions for apply0123 / applySbox are different + function decrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + function getDst(len, dst) { + if (dst === undefined) + return new Uint8Array(len); + bytes$1(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + if (!isAligned32(dst)) + throw new Error('unaligned dst'); + return dst; + } + // TODO: investigate merging with ctr32 + function ctrCounter(xk, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32$2(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; + } + // AES CTR with overflowing 32 bit counter + // It's possible to do 32le significantly simpler (and probably faster) by using u32. + // But, we need both, and perf bottleneck is in ghash anyway. + function ctr32(xk, isLE, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32$2(ctr); + const view = createView$1(ctr); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; + } + /** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ + const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + bytes$1(key); + bytes$1(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + bytes$1(buf); + if (dst !== undefined) { + bytes$1(dst); + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; + }); + function validateBlockDecrypt(data) { + bytes$1(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } + } + function validateBlockEncrypt(plaintext, pcks5, dst) { + bytes$1(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (!isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32$2(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32$2(out); + return { b, o, out }; + } + function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error('aes/pcks5: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error('aes/pcks5: wrong padding'); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error('aes/pcks5: wrong padding'); + return out; + } + function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32$2(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; + } + /** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ + const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + bytes$1(key); + bytes$1(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); } - else { - pos = 0; - len = 0; + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + const out = getDst(ciphertext.length, dst); + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32$2(ciphertext); + const o = u32$2(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$6(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); } + clean(...toClean); + return validatePCKS(out, pcks5); + }, + }; + }); + /** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ + const cfb$1 = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + bytes$1(key); + bytes$1(iv, 16); + function processCfb(src, isEncrypt, dst) { + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$6(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + const buf = u8$1(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; + }); + // TODO: merge with chacha, however gcm has bitLen while chacha has byteLen + function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD == null ? 0 : AAD.length; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView$1(num); + if (AAD) + setBigUint64$1(view, 0, BigInt(aadLength * 8), isLE); + setBigUint64$1(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + const res = h.digest(); + clean(num); + return res; + } + /** + * GCM: Galois/Counter Mode. + * Modern, parallel version of CTR, with MAC. + * Be careful: MACs can be forged. + * Unsafe to use random nonces under the same key, due to collision chance. + * As for nonce size, prefer 12-byte, instead of 8-byte. + */ + const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + bytes$1(key); + bytes$1(nonce); + if (AAD !== undefined) + bytes$1(AAD); + // NIST 800-38d doesn't enforce minimum nonce length. + // We enforce 8 bytes for compat with openssl. + // 12 bytes are recommended. More than 12 bytes would be converted into 12. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); } - this.pos = pos; - this.len = len; - return result; - } - AES_Decrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let rlen = len; - if (len > 0) { - if (len % 16) { - if (this.hasOwnProperty('padding')) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - else { - len += 16 - (len % 16); + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView$1(nonceLen); + setBigUint64$1(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + bytes$1(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + if (!equalBytes$1(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; + }); + function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); + } + function encryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = encrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; + } + function decryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = decrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; + } + /** + * AES-W (base for AESKW/AESKWP). + * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf), + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/). + */ + const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints. + // If you need it larger, open an issue. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i + (a0 = s0), (a1 = s1 ^ byteSwap$1(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3); } } - asm.cipher(amode, hpos + pos, len); - if (this.hasOwnProperty('padding') && this.padding) { - let pad = heap[pos + rlen - 1]; - if (pad < 1 || pad > 16 || pad > rlen) - throw new SecurityError('bad padding'); - let pcheck = 0; - for (let i = pad; i > 1; i--) - pcheck |= pad ^ heap[pos + rlen - i]; - if (pcheck) - throw new SecurityError('bad padding'); - rlen -= pad; - } + (o32[0] = a0), (o32[1] = a1); // out = A || out } - const result = new Uint8Array(rlen); - if (rlen > 0) { - result.set(heap.subarray(pos, pos + rlen)); + xk.fill(0); + }, + decrypt(kek, out) { + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap$1(ctr); + const { s0, s1, s2, s3 } = decrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); } - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - } + xk.fill(0); + }, + }; + const AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 + /** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * For padded version, use aeskwp. + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf). + */ + const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + bytes$1(plaintext); + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes$2(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes$1(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, + })); + // Private, unsafe low-level methods. Can change at any time. + const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt: encrypt$6, + decrypt: decrypt$6, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, + }; - class AES_ECB { - static encrypt(data, key, padding = false) { - return new AES_ECB(key, padding).encrypt(data); - } - static decrypt(data, key, padding = false) { - return new AES_ECB(key, padding).decrypt(data); - } - constructor(key, padding = false, aes) { - this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); + // Modified by ProtonTech AG + + + const webCrypto$9 = util.getWebCrypto(); + const nodeCrypto$8 = util.getNodeCrypto(); + + const knownAlgos = nodeCrypto$8 ? nodeCrypto$8.getCiphers() : []; + const nodeAlgos = { + idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ + tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, + cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, + blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, + aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, + aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, + aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined + /* twofish is not implemented in OpenSSL */ + }; + + /** + * CFB encryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} plaintext + * @param {Uint8Array} iv + * @param {Object} config - full configuration, defaults to openpgp.config + * @returns MaybeStream + */ + async function encrypt$5(algo, key, plaintext, iv, config) { + const algoName = enums.read(enums.symmetric, algo); + if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. + return nodeEncrypt$1(algo, key, plaintext, iv); + } + if (util.isAES(algo)) { + return aesEncrypt(algo, key, plaintext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; + + const blockc = iv.slice(); + let pt = new Uint8Array(); + const process = chunk => { + if (chunk) { + pt = util.concatUint8Array([pt, chunk]); } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); + const ciphertext = new Uint8Array(pt.length); + let i; + let j = 0; + while (chunk ? pt.length >= block_size : pt.length) { + const encblock = cipherfn.encrypt(blockc); + for (i = 0; i < block_size; i++) { + blockc[i] = pt[i] ^ encblock[i]; + ciphertext[j++] = blockc[i]; + } + pt = pt.subarray(block_size); } + return ciphertext.subarray(0, j); + }; + return transform(plaintext, process, process); } /** - * Javascript AES implementation. - * This is used as fallback if the native Crypto APIs are not available. + * CFB decryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} ciphertext + * @param {Uint8Array} iv + * @returns MaybeStream */ - function aes(length) { - const C = function(key) { - const aesECB = new AES_ECB(key); + async function decrypt$5(algo, key, ciphertext, iv) { + const algoName = enums.read(enums.symmetric, algo); + if (nodeCrypto$8 && nodeAlgos[algoName]) { // Node crypto library. + return nodeDecrypt$1(algo, key, ciphertext, iv); + } + if (util.isAES(algo)) { + return aesDecrypt(algo, key, ciphertext, iv); + } - this.encrypt = function(block) { - return aesECB.encrypt(block); - }; + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; - this.decrypt = function(block) { - return aesECB.decrypt(block); - }; + let blockp = iv; + let ct = new Uint8Array(); + const process = chunk => { + if (chunk) { + ct = util.concatUint8Array([ct, chunk]); + } + const plaintext = new Uint8Array(ct.length); + let i; + let j = 0; + while (chunk ? ct.length >= block_size : ct.length) { + const decblock = cipherfn.encrypt(blockp); + blockp = ct.subarray(0, block_size); + for (i = 0; i < block_size; i++) { + plaintext[j++] = blockp[i] ^ decblock[i]; + } + ct = ct.subarray(block_size); + } + return plaintext.subarray(0, j); }; + return transform(ciphertext, process, process); + } - C.blockSize = C.prototype.blockSize = 16; - C.keySize = C.prototype.keySize = length / 8; + class WebCryptoEncryptor { + constructor(algo, key, iv) { + const { blockSize } = getCipherParams(algo); + this.key = key; + this.prevBlock = iv; + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + this.zeroBlock = new Uint8Array(this.blockSize); + } - return C; - } + static async isSupported(algo) { + const { keySize } = getCipherParams(algo); + return webCrypto$9.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt']) + .then(() => true, () => false); + } - //Paul Tero, July 2001 - //http://www.tero.co.uk/des/ - // - //Optimised for performance with large blocks by Michael Hayworth, November 2001 - //http://www.netdealing.com - // - // Modified by Recurity Labs GmbH + async _runCBC(plaintext, nonZeroIV) { + const mode = 'AES-CBC'; + this.keyRef = this.keyRef || await webCrypto$9.importKey('raw', this.key, mode, false, ['encrypt']); + const ciphertext = await webCrypto$9.encrypt( + { name: mode, iv: nonZeroIV || this.zeroBlock }, + this.keyRef, + plaintext + ); + return new Uint8Array(ciphertext).subarray(0, plaintext.length); + } + + async encryptChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const plaintext = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + const toEncrypt = util.concatUint8Array([ + this.prevBlock, + plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock + ]); - //THIS SOFTWARE IS PROVIDED "AS IS" AND - //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - //ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - //OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - //OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - //SUCH DAMAGE. + const encryptedBlocks = await this._runCBC(toEncrypt); + xorMut$1(encryptedBlocks, plaintext); + this.prevBlock = encryptedBlocks.slice(-this.blockSize); - //des - //this takes the key, the message, and whether to encrypt or decrypt + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - function des(keys, message, encrypt, mode, iv, padding) { - //declaring this locally speeds things up a bit - const spfunction1 = [ - 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, - 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, - 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, - 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, - 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 - ]; - const spfunction2 = [ - -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, - -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, - -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, - -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, - -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, - 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000 - ]; - const spfunction3 = [ - 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, - 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, - 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, - 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, - 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 - ]; - const spfunction4 = [ - 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, - 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, - 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, - 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 - ]; - const spfunction5 = [ - 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, - 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, - 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, - 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, - 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, - 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100 - ]; - const spfunction6 = [ - 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, - 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, - 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, - 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, - 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 - ]; - const spfunction7 = [ - 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, - 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, - 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, - 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, - 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 - ]; - const spfunction8 = [ - 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, - 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, - 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, - 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, - 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 - ]; + return encryptedBlocks; + } - //create the 16 or 48 subkeys we will need - let m = 0; - let i; - let j; - let temp; - let right1; - let right2; - let left; - let right; - let looping; - let cbcleft; - let cbcleft2; - let cbcright; - let cbcright2; - let endloop; - let loopinc; - let len = message.length; + this.i += added.length; + let encryptedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + const curBlock = this.nextBlock; + encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + this.prevBlock = encryptedBlock.slice(); + this.i = 0; - //set up the loops for single and triple des - const iterations = keys.length === 32 ? 3 : 9; //single or triple des - if (iterations === 3) { - looping = encrypt ? [0, 32, 2] : [30, -2, -2]; - } else { - looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + encryptedBlock = new Uint8Array(); + } + + return encryptedBlock; } - //pad the message depending on the padding parameter - //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt - if (encrypt) { - message = desAddPadding(message, padding); - len = message.length; + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + this.nextBlock = this.nextBlock.subarray(0, this.i); + const curBlock = this.nextBlock; + const encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + result = encryptedBlock.subarray(0, curBlock.length); + } + + this.clearSensitiveData(); + return result; } - //store the result here - let result = new Uint8Array(len); - let k = 0; + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.keyRef = null; + this.key = null; + } - if (mode === 1) { //CBC mode - cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - m = 0; + async encrypt(plaintext) { + // plaintext is internally padded to block length before encryption + const encryptedWithPadding = await this._runCBC( + util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), + this.iv + ); + // drop encrypted padding + const ct = encryptedWithPadding.subarray(0, plaintext.length); + xorMut$1(ct, plaintext); + this.clearSensitiveData(); + return ct; } + } - //loop through each 64 bit chunk of the message - while (m < len) { - left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + class NobleStreamProcessor { + constructor(forEncryption, algo, key, iv) { + this.forEncryption = forEncryption; + const { blockSize } = getCipherParams(algo); + this.key = unsafe.expandKeyLE(key); - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - left ^= cbcleft; - right ^= cbcright; - } else { - cbcleft2 = cbcleft; - cbcright2 = cbcright; - cbcleft = left; - cbcright = right; - } + if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers + this.prevBlock = getUint32Array(iv); + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + } + + _runCFB(src) { + const src32 = getUint32Array(src); + const dst = new Uint8Array(src.length); + const dst32 = getUint32Array(dst); + for (let i = 0; i + 4 <= dst32.length; i += 4) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4); } + return dst; + } - //first each 64 but chunk of the message must be permuted according to IP - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); + async processChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const toProcess = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); - //do this either 1 or 3 times for each chunk of the message - for (j = 0; j < iterations; j += 3) { - endloop = looping[j + 1]; - loopinc = looping[j + 2]; - //now go through and perform the encryption or decryption - for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency - right1 = right ^ keys[i]; - right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - //the result is attained by passing these bytes through the S selection functions - temp = left; - left = right; - right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> - 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & - 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); - } - temp = left; - left = right; - right = temp; //unreverse left and right - } //for either 1 or 3 iterations + const processedBlocks = this._runCFB(toProcess); - //move then each one bit to the right - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - //now perform IP-1, which is IP in the opposite direction - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); + return processedBlocks; + } - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - cbcleft = left; - cbcright = right; - } else { - left ^= cbcleft2; - right ^= cbcright2; - } + this.i += added.length; + + let processedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + processedBlock = this._runCFB(this.nextBlock); + this.i = 0; + + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + processedBlock = new Uint8Array(); } - result[k++] = (left >>> 24); - result[k++] = ((left >>> 16) & 0xff); - result[k++] = ((left >>> 8) & 0xff); - result[k++] = (left & 0xff); - result[k++] = (right >>> 24); - result[k++] = ((right >>> 16) & 0xff); - result[k++] = ((right >>> 8) & 0xff); - result[k++] = (right & 0xff); - } //for every 8 characters, or 64 bits in the message + return processedBlock; + } - //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt - if (!encrypt) { - result = desRemovePadding(result, padding); + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + const processedBlock = this._runCFB(this.nextBlock); + + result = processedBlock.subarray(0, this.i); + } + + this.clearSensitiveData(); + return result; } - return result; - } //end of des + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.key.fill(0); + } + } - //desCreateKeys - //this takes as input a 64 bit key (even though only 56 bits are used) - //as an array of 2 integers, and returns 16 48 bit keys + async function aesEncrypt(algo, key, pt, iv) { + if (webCrypto$9 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys + const cfb = new WebCryptoEncryptor(algo, key, iv); + return util.isStream(pt) ? transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt); + } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream + const cfb = new NobleStreamProcessor(true, algo, key, iv); + return transform(pt, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).encrypt(pt); + } - function desCreateKeys(key) { - //declaring this locally speeds things up a bit - const pc2bytes0 = [ - 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 - ]; - const pc2bytes1 = [ - 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 - ]; - const pc2bytes2 = [ - 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808 - ]; - const pc2bytes3 = [ - 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 - ]; - const pc2bytes4 = [ - 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010 - ]; - const pc2bytes5 = [ - 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420 - ]; - const pc2bytes6 = [ - 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 - ]; - const pc2bytes7 = [ - 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 - ]; - const pc2bytes8 = [ - 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002 - ]; - const pc2bytes9 = [ - 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 - ]; - const pc2bytes10 = [ - 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020 - ]; - const pc2bytes11 = [ - 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 - ]; - const pc2bytes12 = [ - 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 - ]; - const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; + async function aesDecrypt(algo, key, ct, iv) { + if (util.isStream(ct)) { + const cfb = new NobleStreamProcessor(false, algo, key, iv); + return transform(ct, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).decrypt(ct); + } - //how many iterations (1 for des, 3 for triple des) - const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - //stores the return keys - const keys = new Array(32 * iterations); - //now define the left shifts which need to be done - const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - //other variables - let lefttemp; - let righttemp; - let m = 0; - let n = 0; - let temp; + function xorMut$1(a, b) { + const aLength = Math.min(a.length, b.length); + for (let i = 0; i < aLength; i++) { + a[i] = a[i] ^ b[i]; + } + } - for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations - let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 2) ^ right) & 0x33333333; - right ^= temp; - left ^= (temp << 2); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); + function nodeEncrypt$1(algo, key, pt, iv) { + const algoName = enums.read(enums.symmetric, algo); + const cipherObj = new nodeCrypto$8.createCipheriv(nodeAlgos[algoName], key, iv); + return transform(pt, value => new Uint8Array(cipherObj.update(value))); + } - //the right side needs to be shifted and to get the last four bits of the left side - temp = (left << 8) | ((right >>> 20) & 0x000000f0); - //left needs to be put upside down - left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); - right = temp; + function nodeDecrypt$1(algo, key, ct, iv) { + const algoName = enums.read(enums.symmetric, algo); + const decipherObj = new nodeCrypto$8.createDecipheriv(nodeAlgos[algoName], key, iv); + return transform(ct, value => new Uint8Array(decipherObj.update(value))); + } - //now go through and perform these shifts on the left and right keys - for (let i = 0; i < shifts.length; i++) { - //shift the keys either one or two bits to the left - if (shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; + var cfb = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$5, + encrypt: encrypt$5 + }); - //now apply PC-2, in such a way that E is easier when encrypting or decrypting - //this conversion will look like PC-2 except only the last 6 bits of each byte are used - //rather than 48 consecutive bits and the order of lines will be according to - //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 - lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( - left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & - 0xf]; - righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | - pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]; - temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; - keys[n++] = lefttemp ^ temp; - keys[n++] = righttemp ^ (temp << 16); - } - } //for each iterations - //return the keys we've created - return keys; - } //end of desCreateKeys + /** + * @fileoverview This module implements AES-CMAC on top of + * native AES-CBC using either the WebCrypto API or Node.js' crypto API. + * @module crypto/cmac + */ - function desAddPadding(message, padding) { - const padLength = 8 - (message.length % 8); + const webCrypto$8 = util.getWebCrypto(); + const nodeCrypto$7 = util.getNodeCrypto(); - let pad; - if (padding === 2 && (padLength < 8)) { //pad the message with spaces - pad = ' '.charCodeAt(0); - } else if (padding === 1) { //PKCS7 padding - pad = padLength; - } else if (!padding && (padLength < 8)) { //pad the message out with null bytes - pad = 0; - } else if (padLength === 8) { - return message; - } else { - throw new Error('des: invalid padding'); - } - const paddedMessage = new Uint8Array(message.length + padLength); - for (let i = 0; i < message.length; i++) { - paddedMessage[i] = message[i]; - } - for (let j = 0; j < padLength; j++) { - paddedMessage[message.length + j] = pad; - } + /** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ - return paddedMessage; - } + const blockLength$3 = 16; - function desRemovePadding(message, padding) { - let padLength = null; - let pad; - if (padding === 2) { // space padded - pad = ' '.charCodeAt(0); - } else if (padding === 1) { // PKCS7 - padLength = message[message.length - 1]; - } else if (!padding) { // null padding - pad = 0; - } else { - throw new Error('des: invalid padding'); - } - if (!padLength) { - padLength = 1; - while (message[message.length - padLength] === pad) { - padLength++; - } - padLength--; + /** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param {Uint8Array} data + * @param {Uint8Array} padding + */ + function rightXORMut(data, padding) { + const offset = data.length - blockLength$3; + for (let i = 0; i < blockLength$3; i++) { + data[i + offset] ^= padding[i]; } + return data; + } - return message.subarray(0, message.length - padLength); + function pad(data, padding, padding2) { + // if |M| in {n, 2n, 3n, ...} + if (data.length && data.length % blockLength$3 === 0) { + // then return M xor→ B, + return rightXORMut(data, padding); + } + // else return (M || 10^(n−1−(|M| mod n))) xor→ P + const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3))); + padded.set(data); + padded[data.length] = 0b10000000; + return rightXORMut(padded, padding2); } - // added by Recurity Labs + const zeroBlock$1 = new Uint8Array(blockLength$3); - function TripleDES(key) { - this.key = []; + async function CMAC(key) { + const cbc = await CBC(key); - for (let i = 0; i < 3; i++) { - this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); - } + // L ← E_K(0^n); B ← 2L; P ← 4L + const padding = util.double(await cbc(zeroBlock$1)); + const padding2 = util.double(padding); - this.encrypt = function(block) { - return des( - desCreateKeys(this.key[2]), - des( - desCreateKeys(this.key[1]), - des( - desCreateKeys(this.key[0]), - block, true, 0, null, null - ), - false, 0, null, null - ), true, 0, null, null - ); + return async function(data) { + // return CBC_K(pad(M; B, P)) + return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3); }; } - TripleDES.keySize = TripleDES.prototype.keySize = 24; - TripleDES.blockSize = TripleDES.prototype.blockSize = 8; - - // This is "original" DES - - function DES(key) { - this.key = key; + async function CBC(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt) { + const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1); + const ct = en.update(pt); + return new Uint8Array(ct); + }; + } - this.encrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, true, 0, null, padding); - }; + if (util.getWebCrypto()) { + try { + key = await webCrypto$8.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); + return async function(pt) { + const ct = await webCrypto$8.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt); + return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - this.decrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, false, 0, null, padding); + return async function(pt) { + return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt); }; } - // Use of this source code is governed by a BSD-style - // license that can be found in the LICENSE file. - - // Copyright 2010 pjacobs@xeekr.com . All rights reserved. - - // Modified by Recurity Labs GmbH + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2018 ProtonTech AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // fixed/modified by Herbert Hanewinkel, www.haneWIN.de - // check www.haneWIN.de for the latest version - // cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. - // CAST-128 is a common OpenPGP cipher. + const webCrypto$7 = util.getWebCrypto(); + const nodeCrypto$6 = util.getNodeCrypto(); + const Buffer$1 = util.getNodeBuffer(); - // CAST5 constructor + const blockLength$2 = 16; + const ivLength$2 = blockLength$2; + const tagLength$2 = blockLength$2; - function OpenPGPSymEncCAST5() { - this.BlockSize = 8; - this.KeySize = 16; + const zero = new Uint8Array(blockLength$2); + const one$1 = new Uint8Array(blockLength$2); one$1[blockLength$2 - 1] = 1; + const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2; - this.setKey = function(key) { - this.masking = new Array(16); - this.rotate = new Array(16); + async function OMAC(key) { + const cmac = await CMAC(key); + return function(t, message) { + return cmac(util.concatUint8Array([t, message])); + }; + } - this.reset(); + async function CTR(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt, iv) { + const en = new nodeCrypto$6.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); + const ct = Buffer$1.concat([en.update(pt), en.final()]); + return new Uint8Array(ct); + }; + } - if (key.length === this.KeySize) { - this.keySchedule(key); - } else { - throw new Error('CAST-128: keys must be 16 bytes'); + if (util.getWebCrypto()) { + try { + const keyRef = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); + return async function(pt, iv) { + const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt); + return new Uint8Array(ct); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); } - return true; + } + + return async function(pt, iv) { + return ctr(key, iv).encrypt(pt); }; + } - this.reset = function() { - for (let i = 0; i < 16; i++) { - this.masking[i] = 0; - this.rotate[i] = 0; + + /** + * Class to en/decrypt using EAX mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ + async function EAX(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('EAX mode supports only AES cipher'); + } + + const [ + omac, + ctr + ] = await Promise.all([ + OMAC(key), + CTR(key) + ]); + + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + const [ + omacNonce, + omacAdata + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata) + ]); + const ciphered = await ctr(plaintext, omacNonce); + const omacCiphered = await omac(two, ciphered); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + return util.concatUint8Array([ciphered, tag]); + }, + + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to verify + * @returns {Promise} The plaintext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$2) throw new Error('Invalid EAX ciphertext'); + const ciphered = ciphertext.subarray(0, -tagLength$2); + const ctTag = ciphertext.subarray(-tagLength$2); + const [ + omacNonce, + omacAdata, + omacCiphered + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata), + omac(two, ciphered) + ]); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); + const plaintext = await ctr(ciphered, omacNonce); + return plaintext; } }; + } - this.getBlockSize = function() { - return this.BlockSize; - }; - this.encrypt = function(src) { - const dst = new Array(src.length); + /** + * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. + * @param {Uint8Array} iv - The initialization vector (16 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ + EAX.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[8 + i] ^= chunkIndex[i]; + } + return nonce; + }; - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; + EAX.blockLength = blockLength$2; + EAX.ivLength = ivLength$2; + EAX.tagLength = tagLength$2; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2018 ProtonTech AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; + const blockLength$1 = 16; + const ivLength$1 = 15; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: + // While OCB [RFC7253] allows the authentication tag length to be of any + // number up to 128 bits long, this document requires a fixed + // authentication tag length of 128 bits (16 octets) for simplicity. + const tagLength$1 = 16; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >>> 16) & 255; - dst[i + 6] = (l >>> 8) & 255; - dst[i + 7] = l & 255; - } - return dst; - }; + function ntz(n) { + let ntz = 0; + for (let i = 1; (n & i) === 0; i <<= 1) { + ntz++; + } + return ntz; + } - this.decrypt = function(src) { - const dst = new Array(src.length); + function xorMut(S, T) { + for (let i = 0; i < S.length; i++) { + S[i] ^= T[i]; + } + return S; + } - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; + function xor(S, T) { + return xorMut(S.slice(), T); + } - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; + const zeroBlock = new Uint8Array(blockLength$1); + const one = new Uint8Array([1]); - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; + /** + * Class to en/decrypt using OCB mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ + async function OCB(cipher, key) { + const { keySize } = getCipherParams(cipher); + // sanity checks + if (!util.isAES(cipher) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; + let maxNtz = 0; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; + // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls, + // hence its execution cannot be broken up. + // As a result, WebCrypto cannot currently be used for `encipher`. + const aes = cbc(key, zeroBlock, { disablePadding: true }); + const encipher = block => aes.encrypt(block); + const decipher = block => aes.decrypt(block); + let mask; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >> 16) & 255; - dst[i + 6] = (l >> 8) & 255; - dst[i + 7] = l & 255; - } + constructKeyVariables(); - return dst; - }; - const scheduleA = new Array(4); + function constructKeyVariables() { + const mask_x = encipher(zeroBlock); + const mask_$ = util.double(mask_x); + mask = []; + mask[0] = util.double(mask_$); - scheduleA[0] = new Array(4); - scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; - scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - scheduleA[1] = new Array(4); - scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + mask.x = mask_x; + mask.$ = mask_$; + } - scheduleA[2] = new Array(4); - scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; - scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + function extendKeyVariables(text, adata) { + const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1; + for (let i = maxNtz + 1; i <= newMaxNtz; i++) { + mask[i] = util.double(mask[i - 1]); + } + maxNtz = newMaxNtz; + } + function hash(adata) { + if (!adata.length) { + // Fast path + return zeroBlock; + } - scheduleA[3] = new Array(4); - scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + // + // Consider A as a sequence of 128-bit blocks + // + const m = adata.length / blockLength$1 | 0; - const scheduleB = new Array(4); + const offset = new Uint8Array(blockLength$1); + const sum = new Uint8Array(blockLength$1); + for (let i = 0; i < m; i++) { + xorMut(offset, mask[ntz(i + 1)]); + xorMut(sum, encipher(xor(offset, adata))); + adata = adata.subarray(blockLength$1); + } - scheduleB[0] = new Array(4); - scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; - scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; - scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; - scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; + // + // Process any final partial block; compute final hash value + // + if (adata.length) { + xorMut(offset, mask.x); - scheduleB[1] = new Array(4); - scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; - scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; - scheduleB[1][2] = [7, 6, 8, 9, 3]; - scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; + const cipherInput = new Uint8Array(blockLength$1); + cipherInput.set(adata, 0); + cipherInput[adata.length] = 0b10000000; + xorMut(cipherInput, offset); + xorMut(sum, encipher(cipherInput)); + } - scheduleB[2] = new Array(4); - scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; - scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; - scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; - scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; + return sum; + } + + /** + * Encrypt/decrypt data. + * @param {encipher|decipher} fn - Encryption/decryption block cipher function + * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. + */ + function crypt(fn, text, nonce, adata) { + // + // Consider P as a sequence of 128-bit blocks + // + const m = text.length / blockLength$1 | 0; + // + // Key-dependent variables + // + extendKeyVariables(text, adata); - scheduleB[3] = new Array(4); - scheduleB[3][0] = [8, 9, 7, 6, 3]; - scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; - scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; - scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; + // + // Nonce-dependent and per-encryption variables + // + // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + // Note: We assume here that tagLength mod 16 == 0. + const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]); + // bottom = str2num(Nonce[123..128]) + const bottom = paddedNonce[blockLength$1 - 1] & 0b111111; + // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + paddedNonce[blockLength$1 - 1] &= 0b11000000; + const kTop = encipher(paddedNonce); + // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); + // Offset_0 = Stretch[1+bottom..128+bottom] + const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); + // Checksum_0 = zeros(128) + const checksum = new Uint8Array(blockLength$1); - // changed 'in' to 'inn' (in javascript 'in' is a reserved word) - this.keySchedule = function(inn) { - const t = new Array(8); - const k = new Array(32); + const ct = new Uint8Array(text.length + tagLength$1); - let j; + // + // Process any whole blocks + // + let i; + let pos = 0; + for (i = 0; i < m; i++) { + // Offset_i = Offset_{i-1} xor L_{ntz(i)} + xorMut(offset, mask[ntz(i + 1)]); + // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + ct.set(xorMut(fn(xor(offset, text)), offset), pos); + // Checksum_i = Checksum_{i-1} xor P_i + xorMut(checksum, fn === encipher ? text : ct.subarray(pos)); - for (let i = 0; i < 4; i++) { - j = i * 4; - t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + text = text.subarray(blockLength$1); + pos += blockLength$1; } - const x = [6, 7, 4, 5]; - let ki = 0; - let w; + // + // Process any final partial block and compute raw tag + // + if (text.length) { + // Offset_* = Offset_m xor L_* + xorMut(offset, mask.x); + // Pad = ENCIPHER(K, Offset_*) + const padding = encipher(offset); + // C_* = P_* xor Pad[1..bitlen(P_*)] + ct.set(xor(text, padding), pos); - for (let half = 0; half < 2; half++) { - for (let round = 0; round < 4; round++) { - for (j = 0; j < 4; j++) { - const a = scheduleA[round][j]; - w = t[a[1]]; + // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) + const xorInput = new Uint8Array(blockLength$1); + xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); + xorInput[text.length] = 0b10000000; + xorMut(checksum, xorInput); + pos += text.length; + } + // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata)); - w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; - w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; - w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; - w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; - w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; - t[a[0]] = w; - } + // + // Assemble ciphertext + // + // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] + ct.set(tag, pos); + return ct; + } - for (j = 0; j < 4; j++) { - const b = scheduleB[round][j]; - w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; - w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; - w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; - w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; - k[ki] = w; - ki++; - } - } - } + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + return crypt(encipher, plaintext, nonce, adata); + }, - for (let i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); + + const tag = ciphertext.subarray(-tagLength$1); + ciphertext = ciphertext.subarray(0, -tagLength$1); + + const crypted = crypt(decipher, ciphertext, nonce, adata); + // if (Tag[1..TAGLEN] == T) + if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { + return crypted.subarray(0, -tagLength$1); + } + throw new Error('Authentication tag mismatch'); } }; + } - // These are the three 'f' functions. See RFC 2144, section 2.2. - function f1(d, m, r) { - const t = m + d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; + /** + * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. + * @param {Uint8Array} iv - The initialization vector (15 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ + OCB.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[7 + i] ^= chunkIndex[i]; } + return nonce; + }; - function f2(d, m, r) { - const t = m ^ d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; - } + OCB.blockLength = blockLength$1; + OCB.ivLength = ivLength$1; + OCB.tagLength = tagLength$1; - function f3(d, m, r) { - const t = m - d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2016 Tankred Hase + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + const webCrypto$6 = util.getWebCrypto(); + const nodeCrypto$5 = util.getNodeCrypto(); + const Buffer = util.getNodeBuffer(); + + const blockLength = 16; + const ivLength = 12; // size of the IV in bytes + const tagLength = 16; // size of the tag in bytes + const ALGO = 'AES-GCM'; + + /** + * Class to en/decrypt using GCM mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ + async function GCM(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('GCM mode supports only AES cipher'); } - const sBox = new Array(8); - sBox[0] = [ - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf - ]; + if (util.getNodeCrypto()) { // Node crypto library + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + const en = new nodeCrypto$5.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + en.setAAD(adata); + const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext + return new Uint8Array(ct); + }, - sBox[1] = [ - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + const de = new nodeCrypto$5.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + de.setAAD(adata); + de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext + const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]); + return new Uint8Array(pt); + } + }; + } - sBox[2] = [ - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 - ]; + if (util.getWebCrypto()) { + try { + const _key = await webCrypto$6.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); + // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages + const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) || + navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/); + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && !pt.length) { + return gcm(key, iv, adata).encrypt(pt); + } + const ct = await webCrypto$6.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt); + return new Uint8Array(ct); + }, - sBox[3] = [ - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) { + return gcm(key, iv, adata).decrypt(ct); + } + try { + const pt = await webCrypto$6.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct); + return new Uint8Array(pt); + } catch (e) { + if (e.name === 'OperationError') { + throw new Error('Authentication tag mismatch'); + } + } + } + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - sBox[4] = [ - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 - ]; + return { + encrypt: async function(pt, iv, adata) { + return gcm(key, iv, adata).encrypt(pt); + }, - sBox[5] = [ - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f - ]; + decrypt: async function(ct, iv, adata) { + return gcm(key, iv, adata).decrypt(ct); + } + }; + } - sBox[6] = [ - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 - ]; - - sBox[7] = [ - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e - ]; - } - - function CAST5(key) { - this.cast5 = new OpenPGPSymEncCAST5(); - this.cast5.setKey(key); - - this.encrypt = function(block) { - return this.cast5.encrypt(block); - }; - } - CAST5.blockSize = CAST5.prototype.blockSize = 8; - CAST5.keySize = CAST5.prototype.keySize = 16; - - /* eslint-disable no-mixed-operators, no-fallthrough */ + /** + * Get GCM nonce. Note: this operation is not defined by the standard. + * A future version of the standard may define GCM mode differently, + * hopefully under a different ID (we use Private/Experimental algorithm + * ID 100) so that we can maintain backwards compatibility. + * @param {Uint8Array} iv - The initialization vector (12 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ + GCM.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[4 + i] ^= chunkIndex[i]; + } + return nonce; + }; + GCM.blockLength = blockLength; + GCM.ivLength = ivLength; + GCM.tagLength = tagLength; - /* Modified by Recurity Labs GmbH - * - * Cipher.js - * A block-cipher algorithm implementation on JavaScript - * See Cipher.readme.txt for further information. - * - * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] - * This script file is distributed under the LGPL - * - * ACKNOWLEDGMENT - * - * The main subroutines are written by Michiel van Everdingen. - * - * Michiel van Everdingen - * http://home.versatel.nl/MAvanEverdingen/index.html - * - * All rights for these routines are reserved to Michiel van Everdingen. - * + /** + * @fileoverview Cipher modes + * @module crypto/mode */ - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //Math - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - const MAXINT = 0xFFFFFFFF; + var mode = { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: GCM, + experimentalGCM: GCM, + /** @see module:crypto/mode/eax */ + eax: EAX, + /** @see module:crypto/mode/ocb */ + ocb: OCB + }; - function rotw(w, n) { - return (w << n | w >>> (32 - n)) & MAXINT; + // Operations are not constant time, but we try and limit timing leakage where we can + const _0n$8 = BigInt(0); + const _1n$d = BigInt(1); + function uint8ArrayToBigInt(bytes) { + const hexAlphabet = '0123456789ABCDEF'; + let s = ''; + bytes.forEach(v => { + s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; + }); + return BigInt('0x0' + s); + } + function mod$2(a, m) { + const reduced = a % m; + return reduced < _0n$8 ? reduced + m : reduced; + } + /** + * Compute modular exponentiation using square and multiply + * @param {BigInt} a - Base + * @param {BigInt} e - Exponent + * @param {BigInt} n - Modulo + * @returns {BigInt} b ** e mod n. + */ + function modExp(b, e, n) { + if (n === _0n$8) + throw Error('Modulo cannot be zero'); + if (n === _1n$d) + return BigInt(0); + if (e < _0n$8) + throw Error('Unsopported negative exponent'); + let exp = e; + let x = b; + x %= n; + let r = BigInt(1); + while (exp > _0n$8) { + const lsb = exp & _1n$d; + exp >>= _1n$d; // e / 2 + // Always compute multiplication step, to reduce timing leakage + const rx = (r * x) % n; + // Update r only if lsb is 1 (odd exponent) + r = lsb ? rx : r; + x = (x * x) % n; // Square + } + return r; } - - function getW(a, i) { - return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; + function abs(x) { + return x >= _0n$8 ? x : -x; } - - function setW(a, i, w) { - a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); + /** + * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) + * Given a and b, compute (x, y) such that ax + by = gdc(a, b). + * Negative numbers are also supported. + * @param {BigInt} a - First operand + * @param {BigInt} b - Second operand + * @returns {{ gcd, x, y: bigint }} + */ + function _egcd(aInput, bInput) { + let x = BigInt(0); + let y = BigInt(1); + let xPrev = BigInt(1); + let yPrev = BigInt(0); + // Deal with negative numbers: run algo over absolute values, + // and "move" the sign to the returned x and/or y. + // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers + let a = abs(aInput); + let b = abs(bInput); + const aNegated = aInput < _0n$8; + const bNegated = bInput < _0n$8; + while (b !== _0n$8) { + const q = a / b; + let tmp = x; + x = xPrev - q * x; + xPrev = tmp; + tmp = y; + y = yPrev - q * y; + yPrev = tmp; + tmp = b; + b = a % b; + a = tmp; + } + return { + x: aNegated ? -xPrev : xPrev, + y: bNegated ? -yPrev : yPrev, + gcd: a + }; + } + /** + * Compute the inverse of `a` modulo `n` + * Note: `a` and and `n` must be relatively prime + * @param {BigInt} a + * @param {BigInt} n - Modulo + * @returns {BigInt} x such that a*x = 1 mod n + * @throws {Error} if the inverse does not exist + */ + function modInv(a, n) { + const { gcd, x } = _egcd(a, n); + if (gcd !== _1n$d) { + throw new Error('Inverse does not exist'); + } + return mod$2(x + n, n); + } + /** + * Compute greatest common divisor between this and n + * @param {BigInt} aInput - Operand + * @param {BigInt} bInput - Operand + * @returns {BigInt} gcd + */ + function gcd(aInput, bInput) { + let a = aInput; + let b = bInput; + while (b !== _0n$8) { + const tmp = b; + b = a % b; + a = tmp; + } + return a; + } + /** + * Get this value as an exact Number (max 53 bits) + * Fails if this value is too large + * @returns {Number} + */ + function bigIntToNumber(x) { + const number = Number(x); + if (number > Number.MAX_SAFE_INTEGER) { + // We throw and error to conform with the bn.js implementation + throw new Error('Number can only safely store up to 53 bits'); + } + return number; + } + /** + * Get value of i-th bit + * @param {BigInt} x + * @param {Number} i - Bit index + * @returns {Number} Bit value. + */ + function getBit(x, i) { + const bit = (x >> BigInt(i)) & _1n$d; + return bit === _0n$8 ? 0 : 1; + } + /** + * Compute bit length + */ + function bitLength(x) { + // -1n >> -1n is -1n + // 1n >> 1n is 0n + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + let bitlen = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _1n$d) !== target) { + bitlen++; + } + return bitlen; + } + /** + * Compute byte length + */ + function byteLength(x) { + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + const _8n = BigInt(8); + let len = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _8n) !== target) { + len++; + } + return len; + } + /** + * Get Uint8Array representation of this number + * @param {String} endian - Endianess of output array (defaults to 'be') + * @param {Number} length - Of output array + * @returns {Uint8Array} + */ + function bigIntToUint8Array(x, endian = 'be', length) { + // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) + // this is faster than shift+mod iterations + let hex = x.toString(16); + if (hex.length % 2 === 1) { + hex = '0' + hex; + } + const rawLength = hex.length / 2; + const bytes = new Uint8Array(length || rawLength); + // parse hex + const offset = length ? length - rawLength : 0; + let i = 0; + while (i < rawLength) { + bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + i++; + } + if (endian !== 'be') { + bytes.reverse(); + } + return bytes; } - function getB(x, n) { - return (x >>> (n * 8)) & 0xFF; + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + const nodeCrypto$4 = util.getNodeCrypto(); + + /** + * Retrieve secure random byte array of the specified length + * @param {Integer} length - Length in bytes to generate + * @returns {Uint8Array} Random byte array. + */ + function getRandomBytes(length) { + const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$4?.webcrypto; + if (webcrypto?.getRandomValues) { + const buf = new Uint8Array(length); + return webcrypto.getRandomValues(buf); + } else { + throw new Error('No secure random number generator available.'); + } } - // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Twofish - // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** + * Create a secure random BigInt that is greater than or equal to min and less than max. + * @param {bigint} min - Lower bound, included + * @param {bigint} max - Upper bound, excluded + * @returns {bigint} Random BigInt. + * @async + */ + function getRandomBigInteger(min, max) { + if (max < min) { + throw new Error('Illegal parameter value: max <= min'); + } - function createTwofish() { - // - let keyBytes = null; - let dataBytes = null; - let dataOffset = -1; - // var dataLength = -1; - // var idx2 = -1; - // + const modulus = max - min; + const bytes = byteLength(modulus); - let tfsKey = []; - let tfsM = [ - [], - [], - [], - [] - ]; + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8)); + return mod$2(r, modulus) + min; + } - function tfsInit(key) { - keyBytes = key; - let i; - let a; - let b; - let c; - let d; - const meKey = []; - const moKey = []; - const inKey = []; - let kLen; - const sKey = []; - let f01; - let f5b; - let fef; + var random = /*#__PURE__*/Object.freeze({ + __proto__: null, + getRandomBigInteger: getRandomBigInteger, + getRandomBytes: getRandomBytes + }); - const q0 = [ - [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], - [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] - ]; - const q1 = [ - [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], - [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] - ]; - const q2 = [ - [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], - [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] - ]; - const q3 = [ - [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], - [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] - ]; - const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - const q = [ - [], - [] - ]; - const m = [ - [], - [], - [], - [] - ]; - - function ffm5b(x) { - return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2018 Proton Technologies AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** + * @fileoverview Algorithms for probabilistic random prime generation + * @module crypto/public_key/prime + */ + const _1n$c = BigInt(1); + /** + * Generate a probably prime random number + * @param bits - Bit length of the prime + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ + function randomProbablePrime(bits, e, k) { + const _30n = BigInt(30); + const min = _1n$c << BigInt(bits - 1); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 + * the next possible prime is mod 30: + * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 + */ + const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; + let n = getRandomBigInteger(min, min << _1n$c); + let i = bigIntToNumber(mod$2(n, _30n)); + do { + n += BigInt(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (bitLength(n) > bits) { + n = mod$2(n, min << _1n$c); + n += min; + i = bigIntToNumber(mod$2(n, _30n)); + } + } while (!isProbablePrime(n, e, k)); + return n; + } + /** + * Probabilistic primality testing + * @param n - Number to test + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ + function isProbablePrime(n, e, k) { + if (e && gcd(n - _1n$c, e) !== _1n$c) { + return false; } - - function ffmEf(x) { - return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + if (!divisionTest(n)) { + return false; } - - function mdsRem(p, q) { - let i; - let t; - let u; - for (i = 0; i < 8; i++) { - t = q >>> 24; - q = ((q << 8) & MAXINT) | p >>> 24; - p = (p << 8) & MAXINT; - u = t << 1; - if (t & 128) { - u ^= 333; + if (!fermat(n)) { + return false; + } + if (!millerRabin(n, k)) { + return false; + } + // TODO implement the Lucas test + // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + return true; + } + /** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n != 1. + * @param n - Number to test + * @param b - Optional Fermat test base + */ + function fermat(n, b = BigInt(2)) { + return modExp(b, n - _1n$c, n) === _1n$c; + } + function divisionTest(n) { + const _0n = BigInt(0); + return smallPrimes.every(m => mod$2(n, m) !== _0n); + } + // https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c + const smallPrimes = [ + 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, + 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, + 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, + 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, + 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, + 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, + 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, + 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, + 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, + 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, + 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, + 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, + 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, + 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, + 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, + 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, + 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, + 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, + 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, + 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, + 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, + 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, + 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, + 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, + 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, + 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, + 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, + 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, + 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, + 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, + 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, + 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, + 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, + 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, + 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, + 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, + 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, + 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, + 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, + 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, + 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, + 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, + 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, + 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, + 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, + 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, + 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, + 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, + 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, + 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, + 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, + 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, + 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, + 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, + 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, + 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, + 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, + 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, + 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, + 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, + 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, + 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, + 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, + 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, + 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, + 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, + 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, + 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, + 4957, 4967, 4969, 4973, 4987, 4993, 4999 + ].map(n => BigInt(n)); + // Miller-Rabin - Miller Rabin algorithm for primality test + // Copyright Fedor Indutny, 2014. + // + // This software is licensed under the MIT License. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + // Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin + // Sample syntax for Fixed-Base Miller-Rabin: + // millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) + /** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n - Number to test + * @param k - Optional number of iterations of Miller-Rabin test + * @param rand - Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ + function millerRabin(n, k, rand) { + const len = bitLength(n); + if (!k) { + k = Math.max(1, (len / 48) | 0); + } + const n1 = n - _1n$c; // n - 1 + // Find d and s, (n - 1) = (2 ^ s) * d; + let s = 0; + while (!getBit(n1, s)) { + s++; + } + const d = n >> BigInt(s); + for (; k > 0; k--) { + const a = getRandomBigInteger(BigInt(2), n1); + let x = modExp(a, d, n); + if (x === _1n$c || x === n1) { + continue; } - q ^= t ^ (u << 16); - u ^= t >>> 1; - if (t & 1) { - u ^= 166; + let i; + for (i = 1; i < s; i++) { + x = mod$2(x * x, n); + if (x === _1n$c) { + return false; + } + if (x === n1) { + break; + } + } + if (i === s) { + return false; } - q ^= u << 24 | u << 8; - } - return q; - } - - function qp(n, x) { - const a = x >> 4; - const b = x & 15; - const c = q0[n][a ^ b]; - const d = q1[n][ror4[b] ^ ashx[a]]; - return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; } + return true; + } - function hFun(x, key) { - let a = getB(x, 0); - let b = getB(x, 1); - let c = getB(x, 2); - let d = getB(x, 3); - switch (kLen) { - case 4: - a = q[1][a] ^ getB(key[3], 0); - b = q[0][b] ^ getB(key[3], 1); - c = q[0][c] ^ getB(key[3], 2); - d = q[1][d] ^ getB(key[3], 3); - case 3: - a = q[1][a] ^ getB(key[2], 0); - b = q[1][b] ^ getB(key[2], 1); - c = q[0][c] ^ getB(key[2], 2); - d = q[0][d] ^ getB(key[2], 3); - case 2: - a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); - b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); - c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); - d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); - } - return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - keyBytes = keyBytes.slice(0, 32); - i = keyBytes.length; - while (i !== 16 && i !== 24 && i !== 32) { - keyBytes[i++] = 0; - } - for (i = 0; i < keyBytes.length; i += 4) { - inKey[i >> 2] = getW(keyBytes, i); - } - for (i = 0; i < 256; i++) { - q[0][i] = qp(0, i); - q[1][i] = qp(1, i); - } - for (i = 0; i < 256; i++) { - f01 = q[1][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - f01 = q[0][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } + /** + * ASN1 object identifiers for hashes + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} + */ + const hash_headers = []; + hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, + 0x10]; + hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; + hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; + hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, + 0x04, 0x20]; + hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x30]; + hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40]; + hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C]; - kLen = inKey.length / 2; - for (i = 0; i < kLen; i++) { - a = inKey[i + i]; - meKey[i] = a; - b = inKey[i + i + 1]; - moKey[i] = b; - sKey[kLen - i - 1] = mdsRem(a, b); - } - for (i = 0; i < 40; i += 2) { - a = 0x1010101 * i; - b = a + 0x1010101; - a = hFun(a, meKey); - b = rotw(hFun(b, moKey), 8); - tfsKey[i] = (a + b) & MAXINT; - tfsKey[i + 1] = rotw(a + 2 * b, 9); - } - for (i = 0; i < 256; i++) { - a = b = c = d = i; - switch (kLen) { - case 4: - a = q[1][a] ^ getB(sKey[3], 0); - b = q[0][b] ^ getB(sKey[3], 1); - c = q[0][c] ^ getB(sKey[3], 2); - d = q[1][d] ^ getB(sKey[3], 3); - case 3: - a = q[1][a] ^ getB(sKey[2], 0); - b = q[1][b] ^ getB(sKey[2], 1); - c = q[0][c] ^ getB(sKey[2], 2); - d = q[0][d] ^ getB(sKey[2], 3); - case 2: - tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; - tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; - tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; - tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + /** + * Create padding with secure random data + * @private + * @param {Integer} length - Length of the padding in bytes + * @returns {Uint8Array} Random padding. + */ + function getPKCS1Padding(length) { + const result = new Uint8Array(length); + let count = 0; + while (count < length) { + const randomBytes = getRandomBytes(length - count); + for (let i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result[count++] = randomBytes[i]; } } } + return result; + } - function tfsG0(x) { - return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; - } - - function tfsG1(x) { - return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; - } - - function tfsFrnd(r, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); - blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); - blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + /** + * Create a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} + * @param {Uint8Array} message - Message to be encoded + * @param {Integer} keyLength - The length in octets of the key modulus + * @returns {Uint8Array} EME-PKCS1 padded message. + */ + function emeEncode(message, keyLength) { + const mLength = message.length; + // length checking + if (mLength > keyLength - 11) { + throw new Error('Message too long'); } + // Generate an octet string PS of length k - mLen - 3 consisting of + // pseudo-randomly generated nonzero octets + const PS = getPKCS1Padding(keyLength - mLength - 3); + // Concatenate PS, the message M, and other padding to form an + // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. + const encoded = new Uint8Array(keyLength); + // 0x00 byte + encoded[1] = 2; + encoded.set(PS, 2); + // 0x00 bytes + encoded.set(message, keyLength - mLength); + return encoded; + } - function tfsIrnd(i, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; - blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; - blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} + * @param {Uint8Array} encoded - Encoded message bytes + * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) + * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) + * @throws {Error} on decoding failure, unless `randomPayload` is provided + */ + function emeDecode(encoded, randomPayload) { + // encoded format: 0x00 0x02 0x00 + let offset = 2; + let separatorNotFound = 1; + for (let j = offset; j < encoded.length; j++) { + separatorNotFound &= encoded[j] !== 0; + offset += separatorNotFound; } - function tfsClose() { - tfsKey = []; - tfsM = [ - [], - [], - [], - [] - ]; - } + const psLen = offset - 2; + const payload = encoded.subarray(offset + 1); // discard the 0x00 separator + const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - function tfsEncrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; - for (let j = 0; j < 8; j++) { - tfsFrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); - dataOffset += 16; - return dataBytes; + if (randomPayload) { + return util.selectUint8Array(isValidPadding, payload, randomPayload); } - function tfsDecrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; - for (let j = 7; j >= 0; j--) { - tfsIrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); - dataOffset += 16; + if (isValidPadding) { + return payload; } - // added by Recurity Labs + throw new Error('Decryption error'); + } - function tfsFinal() { - return dataBytes; + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} + * @param {Integer} algo - Hash algorithm type used + * @param {Uint8Array} hashed - Message to be encoded + * @param {Integer} emLen - Intended length in octets of the encoded message + * @returns {Uint8Array} Encoded message. + */ + function emsaEncode(algo, hashed, emLen) { + let i; + if (hashed.length !== hash$1.getHashByteLength(algo)) { + throw new Error('Invalid hash length'); + } + // produce an ASN.1 DER value for the hash function used. + // Let T be the full hash prefix + const hashPrefix = new Uint8Array(hash_headers[algo].length); + for (i = 0; i < hash_headers[algo].length; i++) { + hashPrefix[i] = hash_headers[algo][i]; + } + // and let tLen be the length in octets prefix and hashed data + const tLen = hashPrefix.length + hashed.length; + if (emLen < tLen + 11) { + throw new Error('Intended encoded message length too short'); } + // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF + // The length of PS will be at least 8 octets + const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - return { - name: 'twofish', - blocksize: 128 / 8, - open: tfsInit, - close: tfsClose, - encrypt: tfsEncrypt, - decrypt: tfsDecrypt, - // added by Recurity Labs - finalize: tfsFinal - }; + // Concatenate PS, the hash prefix, hashed data, and other padding to form the + // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed + const EM = new Uint8Array(emLen); + EM[1] = 0x01; + EM.set(PS, 2); + EM.set(hashPrefix, emLen - tLen); + EM.set(hashed, emLen - hashed.length); + return EM; } - // added by Recurity Labs + var pkcs1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + emeDecode: emeDecode, + emeEncode: emeEncode, + emsaEncode: emsaEncode + }); - function TF(key) { - this.tf = createTwofish(); - this.tf.open(Array.from(key), 0); + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - this.encrypt = function(block) { - return this.tf.encrypt(Array.from(block), 0); - }; - } - TF.keySize = TF.prototype.keySize = 32; - TF.blockSize = TF.prototype.blockSize = 16; + const webCrypto$5 = util.getWebCrypto(); + const nodeCrypto$3 = util.getNodeCrypto(); + const _1n$b = BigInt(1); - /* Modified by Recurity Labs GmbH - * - * Originally written by nklein software (nklein.com) + /** Create signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} hashed - Hashed message + * @returns {Promise} RSA Signature. + * @async */ + async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) { + if (hash$1.getHashByteLength(hashAlgo) >= n.length) { + // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error + // e.g. if a 512-bit RSA key is used with a SHA-512 digest. + // The size limit is actually slightly different but here we only care about throwing + // on common key sizes. + throw new Error('Digest size cannot exceed key modulus size'); + } - /* - * Javascript implementation based on Bruce Schneier's reference implementation. - * - * - * The constructor doesn't do much of anything. It's just here - * so we can start defining properties and methods and such. - */ - function Blowfish() {} + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeSign$1(hashAlgo, data, n, e, d, p, q, u); + } + } + return bnSign(hashAlgo, n, d, hashed); + } - /* - * Declare the block size so that protocols know what size - * Initialization Vector (IV) they will need. + /** + * Verify signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} s - Signature + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} hashed - Hashed message + * @returns {Boolean} + * @async */ - Blowfish.prototype.BLOCKSIZE = 8; + async function verify$6(hashAlgo, data, s, n, e, hashed) { + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeVerify$1(hashAlgo, data, s, n, e); + } + } + return bnVerify(hashAlgo, s, n, e, hashed); + } - /* - * These are the default SBOXES. + /** + * Encrypt message + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @returns {Promise} RSA Ciphertext. + * @async */ - Blowfish.prototype.SBOXES = [ - [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a - ], - [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 - ], - [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 - ], - [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ] - ]; - - //* - //* This is the default PARRAY - //* - Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b - ]; - - //* - //* This is the number of rounds the cipher will go - //* - Blowfish.prototype.NN = 16; - - //* - //* This function is needed to get rid of problems - //* with the high-bit getting set. If we don't do - //* this, then sometimes ( aa & 0x00FFFFFFFF ) is not - //* equal to ( bb & 0x00FFFFFFFF ) even when they - //* agree bit-for-bit for the first 32 bits. - //* - Blowfish.prototype._clean = function(xx) { - if (xx < 0) { - const yy = xx & 0x7FFFFFFF; - xx = yy + 0x80000000; + async function encrypt$4(data, n, e) { + if (util.getNodeCrypto()) { + return nodeEncrypt(data, n, e); } - return xx; - }; - - //* - //* This is the mixing function that uses the sboxes - //* - Blowfish.prototype._F = function(xx) { - let yy; + return bnEncrypt(data, n, e); + } - const dd = xx & 0x00FF; - xx >>>= 8; - const cc = xx & 0x00FF; - xx >>>= 8; - const bb = xx & 0x00FF; - xx >>>= 8; - const aa = xx & 0x00FF; + /** + * Decrypt RSA message + * @param {Uint8Array} m - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} RSA Plaintext. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ + async function decrypt$4(data, n, e, d, p, q, u, randomPayload) { + // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, + // and we want to avoid checking the error type to decide if the random payload + // should indeed be returned. + if (util.getNodeCrypto() && !randomPayload) { + try { + return await nodeDecrypt(data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } + return bnDecrypt(data, n, e, d, p, q, u, randomPayload); + } - yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy ^= this.sboxes[2][cc]; - yy += this.sboxes[3][dd]; + /** + * Generate a new random private key B bits long with public exponent E. + * + * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param {Integer} bits - RSA bit length + * @param {Integer} e - RSA public exponent + * @returns {{n, e, d, + * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = p ** -1 mod q + * @async + */ + async function generate$4(bits, e) { + e = BigInt(e); - return yy; - }; + // Native RSA keygen using Web Crypto + if (util.getWebCrypto()) { + const keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, // the specified keysize in bits + publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - //* - //* This method takes an array with two values, left and right - //* and does NN rounds of Blowfish on them. - //* - Blowfish.prototype._encryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); + // map JWK parameters to corresponding OpenPGP names + return jwkToPrivate(jwk, e); + } else if (util.getNodeCrypto()) { + const opts = { + modulusLength: bits, + publicExponent: bigIntToNumber(e), + publicKeyEncoding: { type: 'pkcs1', format: 'jwk' }, + privateKeyEncoding: { type: 'pkcs1', format: 'jwk' } + }; + const jwk = await new Promise((resolve, reject) => { + nodeCrypto$3.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => { + if (err) { + reject(err); + } else { + resolve(jwkPrivateKey); + } + }); + }); + return jwkToPrivate(jwk, e); + } - let ii; + // RSA keygen fallback using 40 iterations of the Miller-Rabin test + // See https://stackoverflow.com/a/6330138 for justification + // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST + let p; + let q; + let n; + do { + q = randomProbablePrime(bits - (bits >> 1), e, 40); + p = randomProbablePrime(bits >> 1, e, 40); + n = p * q; + } while (bitLength(n) !== bits); - for (ii = 0; ii < this.NN; ++ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; + const phi = (p - _1n$b) * (q - _1n$b); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + if (q < p) { + [p, q] = [q, p]; } - dataL ^= this.parray[this.NN + 0]; - dataR ^= this.parray[this.NN + 1]; + return { + n: bigIntToUint8Array(n), + e: bigIntToUint8Array(e), + d: bigIntToUint8Array(modInv(e, phi)), + p: bigIntToUint8Array(p), + q: bigIntToUint8Array(q), + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: bigIntToUint8Array(modInv(p, q)) + }; + } - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); - }; + /** + * Validate RSA parameters + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA inverse of p w.r.t. q + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$9(n, e, d, p, q, u) { + n = uint8ArrayToBigInt(n); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); - //* - //* This method takes a vector of numbers and turns them - //* into long words so that they can be processed by the - //* real algorithm. - //* - //* Maybe I should make the real algorithm above take a vector - //* instead. That will involve more looping, but it won't require - //* the F() method to deconstruct the vector. - //* - Blowfish.prototype.encryptBlock = function(vector) { - let ii; - const vals = [0, 0]; - const off = this.BLOCKSIZE / 2; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); - vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); + // expect pq = n + if ((p * q) !== n) { + return false; } - this._encryptBlock(vals); + const _2n = BigInt(2); + // expect p*u = 1 mod q + u = uint8ArrayToBigInt(u); + if (mod$2(p * u, q) !== BigInt(1)) { + return false; + } - const ret = []; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); - ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); - // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); - // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + /** + * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) + * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] + * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] + * + * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) + */ + const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3)); + const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q + const rde = r * d * e; + + const areInverses = mod$2(rde, p - _1n$b) === r && mod$2(rde, q - _1n$b) === r; + if (!areInverses) { + return false; } - return ret; - }; + return true; + } - //* - //* This method takes an array with two values, left and right - //* and undoes NN rounds of Blowfish on them. - //* - Blowfish.prototype._decryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; + async function bnSign(hashAlgo, n, d, hashed) { + n = uint8ArrayToBigInt(n); + const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n))); + d = uint8ArrayToBigInt(d); + return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n)); + } - let ii; + async function webSign$1(hashName, data, n, e, d, p, q, u) { + /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. + * We swap them in privateToJWK, so it usually works out, but nevertheless, + * not all OpenPGP keys are compatible with this requirement. + * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still + * does if the underlying Web Crypto does so (though the tested implementations + * don't do so). + */ + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }; + const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); + return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); + } - for (ii = this.NN + 1; ii > 1; --ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; + async function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) { + const sign = nodeCrypto$3.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(data); + sign.end(); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + const jwk = await privateToJWK$1(n, e, d, p, q, u); + return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' })); + } + + async function bnVerify(hashAlgo, s, n, e, hashed) { + n = uint8ArrayToBigInt(n); + s = uint8ArrayToBigInt(s); + e = uint8ArrayToBigInt(e); + if (s >= n) { + throw new Error('Signature size cannot exceed modulus size'); } + const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n)); + const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n)); + return util.equalsUint8Array(EM1, EM2); + } - dataL ^= this.parray[1]; - dataR ^= this.parray[0]; + async function webVerify$1(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = await webCrypto$5.importKey('jwk', jwk, { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }, false, ['verify']); + return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); + } - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); - }; + async function nodeVerify$1(hashAlgo, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1' }; - //* - //* This method takes a key array and initializes the - //* sboxes and parray for this encryption. - //* - Blowfish.prototype.init = function(key) { - let ii; - let jj = 0; + const verify = nodeCrypto$3.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(data); + verify.end(); - this.parray = []; - for (ii = 0; ii < this.NN + 2; ++ii) { - let data = 0x00000000; - for (let kk = 0; kk < 4; ++kk) { - data = (data << 8) | (key[jj] & 0x00FF); - if (++jj >= key.length) { - jj = 0; - } - } - this.parray[ii] = this.PARRAY[ii] ^ data; + try { + return verify.verify(key, s); + } catch (err) { + return false; } + } - this.sboxes = []; - for (ii = 0; ii < 4; ++ii) { - this.sboxes[ii] = []; - for (jj = 0; jj < 256; ++jj) { - this.sboxes[ii][jj] = this.SBOXES[ii][jj]; - } + async function nodeEncrypt(data, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; + + return new Uint8Array(nodeCrypto$3.publicEncrypt(key, data)); + } + + async function bnEncrypt(data, n, e) { + n = uint8ArrayToBigInt(n); + data = uint8ArrayToBigInt(emeEncode(data, byteLength(n))); + e = uint8ArrayToBigInt(e); + if (data >= n) { + throw new Error('Message size cannot exceed modulus size'); } + return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n)); + } - const vals = [0x00000000, 0x00000000]; + async function nodeDecrypt(data, n, e, d, p, q, u) { + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; - for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encryptBlock(vals); - this.parray[ii + 0] = vals[0]; - this.parray[ii + 1] = vals[1]; + try { + return new Uint8Array(nodeCrypto$3.privateDecrypt(key, data)); + } catch (err) { + throw new Error('Decryption error'); } + } - for (ii = 0; ii < 4; ++ii) { - for (jj = 0; jj < 256; jj += 2) { - this._encryptBlock(vals); - this.sboxes[ii][jj + 0] = vals[0]; - this.sboxes[ii][jj + 1] = vals[1]; - } + async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { + data = uint8ArrayToBigInt(data); + n = uint8ArrayToBigInt(n); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + u = uint8ArrayToBigInt(u); + if (data >= n) { + throw new Error('Data too large.'); } - }; + const dq = mod$2(d, q - _1n$b); // d mod (q-1) + const dp = mod$2(d, p - _1n$b); // d mod (p-1) - // added by Recurity Labs - function BF(key) { - this.bf = new Blowfish(); - this.bf.init(key); + const unblinder = getRandomBigInteger(BigInt(2), n); + const blinder = modExp(modInv(unblinder, n), e, n); + data = mod$2(data * blinder, n); - this.encrypt = function(block) { - return this.bf.encryptBlock(block); - }; - } + const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p + const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q + const h = mod$2(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q) - BF.keySize = BF.prototype.keySize = 16; - BF.blockSize = BF.prototype.blockSize = 8; + let result = h * p + mp; // result < n due to relations above - /** - * @fileoverview Symmetric cryptography functions - * @module crypto/cipher - * @private + result = mod$2(result * unblinder, n); + + return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload); + } + + /** Convert Openpgp private key params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + * @param {Uint8Array} d + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} u */ + async function privateToJWK$1(n, e, d, p, q, u) { + const pNum = uint8ArrayToBigInt(p); + const qNum = uint8ArrayToBigInt(q); + const dNum = uint8ArrayToBigInt(d); - /** - * AES-128 encryption and decryption (ID 7) - * @function - * @param {String} key - 128-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} + let dq = mod$2(dNum, qNum - _1n$b); // d mod (q-1) + let dp = mod$2(dNum, pNum - _1n$b); // d mod (p-1) + dp = bigIntToUint8Array(dp); + dq = bigIntToUint8Array(dq); + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + d: uint8ArrayToB64(d), + // switch p and q + p: uint8ArrayToB64(q), + q: uint8ArrayToB64(p), + // switch dp and dq + dp: uint8ArrayToB64(dq), + dq: uint8ArrayToB64(dp), + qi: uint8ArrayToB64(u), + ext: true + }; + } + + /** Convert Openpgp key public params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e */ - const aes128 = aes(128); - /** - * AES-128 Block Cipher (ID 8) - * @function - * @param {String} key - 192-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ - const aes192 = aes(192); - /** - * AES-128 Block Cipher (ID 9) - * @function - * @param {String} key - 256-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ - const aes256 = aes(256); - // Not in OpenPGP specifications - const des$1 = DES; - /** - * Triple DES Block Cipher (ID 2) - * @function - * @param {String} key - 192-bit key - * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67} - * @returns {Object} - */ - const tripledes = TripleDES; - /** - * CAST-128 Block Cipher (ID 3) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} - * @returns {Object} - */ - const cast5 = CAST5; - /** - * Twofish Block Cipher (ID 10) - * @function - * @param {String} key - 256-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH} - * @returns {Object} - */ - const twofish = TF; - /** - * Blowfish Block Cipher (ID 4) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH} - * @returns {Object} - */ - const blowfish = BF; - /** - * Not implemented - * @function - * @throws {Error} - */ - const idea = function() { - throw new Error('IDEA symmetric-key algorithm not implemented'); - }; + function publicToJWK(n, e) { + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + ext: true + }; + } - var cipher = /*#__PURE__*/Object.freeze({ + /** Convert JWK private key to OpenPGP private key params */ + function jwkToPrivate(jwk, e) { + return { + n: b64ToUint8Array(jwk.n), + e: bigIntToUint8Array(e), + d: b64ToUint8Array(jwk.d), + // switch p and q + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), + // Since p and q are switched in places, u is the inverse of jwk.q + u: b64ToUint8Array(jwk.qi) + }; + } + + var rsa = /*#__PURE__*/Object.freeze({ __proto__: null, - aes128: aes128, - aes192: aes192, - aes256: aes256, - des: des$1, - tripledes: tripledes, - cast5: cast5, - twofish: twofish, - blowfish: blowfish, - idea: idea + decrypt: decrypt$4, + encrypt: encrypt$4, + generate: generate$4, + sign: sign$6, + validateParams: validateParams$9, + verify: verify$6 }); - var sha1_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0, - w16 = 0, w17 = 0, w18 = 0, w19 = 0, - w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0, - w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0, - w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0, - w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0, - w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0, - w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - - // 0 - t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 1 - t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 2 - t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 3 - t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 4 - t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 5 - t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 6 - t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 7 - t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 8 - t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 9 - t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 10 - t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 11 - t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 12 - t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 13 - t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 14 - t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 15 - t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 16 - n = w13 ^ w8 ^ w2 ^ w0; - w16 = (n << 1) | (n >>> 31); - t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 17 - n = w14 ^ w9 ^ w3 ^ w1; - w17 = (n << 1) | (n >>> 31); - t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 18 - n = w15 ^ w10 ^ w4 ^ w2; - w18 = (n << 1) | (n >>> 31); - t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 19 - n = w16 ^ w11 ^ w5 ^ w3; - w19 = (n << 1) | (n >>> 31); - t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 20 - n = w17 ^ w12 ^ w6 ^ w4; - w20 = (n << 1) | (n >>> 31); - t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 21 - n = w18 ^ w13 ^ w7 ^ w5; - w21 = (n << 1) | (n >>> 31); - t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 22 - n = w19 ^ w14 ^ w8 ^ w6; - w22 = (n << 1) | (n >>> 31); - t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 23 - n = w20 ^ w15 ^ w9 ^ w7; - w23 = (n << 1) | (n >>> 31); - t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 24 - n = w21 ^ w16 ^ w10 ^ w8; - w24 = (n << 1) | (n >>> 31); - t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 25 - n = w22 ^ w17 ^ w11 ^ w9; - w25 = (n << 1) | (n >>> 31); - t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 26 - n = w23 ^ w18 ^ w12 ^ w10; - w26 = (n << 1) | (n >>> 31); - t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 27 - n = w24 ^ w19 ^ w13 ^ w11; - w27 = (n << 1) | (n >>> 31); - t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 28 - n = w25 ^ w20 ^ w14 ^ w12; - w28 = (n << 1) | (n >>> 31); - t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 29 - n = w26 ^ w21 ^ w15 ^ w13; - w29 = (n << 1) | (n >>> 31); - t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 30 - n = w27 ^ w22 ^ w16 ^ w14; - w30 = (n << 1) | (n >>> 31); - t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 31 - n = w28 ^ w23 ^ w17 ^ w15; - w31 = (n << 1) | (n >>> 31); - t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 32 - n = w29 ^ w24 ^ w18 ^ w16; - w32 = (n << 1) | (n >>> 31); - t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 33 - n = w30 ^ w25 ^ w19 ^ w17; - w33 = (n << 1) | (n >>> 31); - t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 34 - n = w31 ^ w26 ^ w20 ^ w18; - w34 = (n << 1) | (n >>> 31); - t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 35 - n = w32 ^ w27 ^ w21 ^ w19; - w35 = (n << 1) | (n >>> 31); - t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 36 - n = w33 ^ w28 ^ w22 ^ w20; - w36 = (n << 1) | (n >>> 31); - t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 37 - n = w34 ^ w29 ^ w23 ^ w21; - w37 = (n << 1) | (n >>> 31); - t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 38 - n = w35 ^ w30 ^ w24 ^ w22; - w38 = (n << 1) | (n >>> 31); - t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 39 - n = w36 ^ w31 ^ w25 ^ w23; - w39 = (n << 1) | (n >>> 31); - t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 40 - n = w37 ^ w32 ^ w26 ^ w24; - w40 = (n << 1) | (n >>> 31); - t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 41 - n = w38 ^ w33 ^ w27 ^ w25; - w41 = (n << 1) | (n >>> 31); - t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 42 - n = w39 ^ w34 ^ w28 ^ w26; - w42 = (n << 1) | (n >>> 31); - t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 43 - n = w40 ^ w35 ^ w29 ^ w27; - w43 = (n << 1) | (n >>> 31); - t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 44 - n = w41 ^ w36 ^ w30 ^ w28; - w44 = (n << 1) | (n >>> 31); - t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 45 - n = w42 ^ w37 ^ w31 ^ w29; - w45 = (n << 1) | (n >>> 31); - t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 46 - n = w43 ^ w38 ^ w32 ^ w30; - w46 = (n << 1) | (n >>> 31); - t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 47 - n = w44 ^ w39 ^ w33 ^ w31; - w47 = (n << 1) | (n >>> 31); - t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 48 - n = w45 ^ w40 ^ w34 ^ w32; - w48 = (n << 1) | (n >>> 31); - t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 49 - n = w46 ^ w41 ^ w35 ^ w33; - w49 = (n << 1) | (n >>> 31); - t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 50 - n = w47 ^ w42 ^ w36 ^ w34; - w50 = (n << 1) | (n >>> 31); - t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 51 - n = w48 ^ w43 ^ w37 ^ w35; - w51 = (n << 1) | (n >>> 31); - t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 52 - n = w49 ^ w44 ^ w38 ^ w36; - w52 = (n << 1) | (n >>> 31); - t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 53 - n = w50 ^ w45 ^ w39 ^ w37; - w53 = (n << 1) | (n >>> 31); - t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 54 - n = w51 ^ w46 ^ w40 ^ w38; - w54 = (n << 1) | (n >>> 31); - t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 55 - n = w52 ^ w47 ^ w41 ^ w39; - w55 = (n << 1) | (n >>> 31); - t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 56 - n = w53 ^ w48 ^ w42 ^ w40; - w56 = (n << 1) | (n >>> 31); - t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 57 - n = w54 ^ w49 ^ w43 ^ w41; - w57 = (n << 1) | (n >>> 31); - t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 58 - n = w55 ^ w50 ^ w44 ^ w42; - w58 = (n << 1) | (n >>> 31); - t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 59 - n = w56 ^ w51 ^ w45 ^ w43; - w59 = (n << 1) | (n >>> 31); - t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 60 - n = w57 ^ w52 ^ w46 ^ w44; - w60 = (n << 1) | (n >>> 31); - t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 61 - n = w58 ^ w53 ^ w47 ^ w45; - w61 = (n << 1) | (n >>> 31); - t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 62 - n = w59 ^ w54 ^ w48 ^ w46; - w62 = (n << 1) | (n >>> 31); - t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 63 - n = w60 ^ w55 ^ w49 ^ w47; - w63 = (n << 1) | (n >>> 31); - t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 64 - n = w61 ^ w56 ^ w50 ^ w48; - w64 = (n << 1) | (n >>> 31); - t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 65 - n = w62 ^ w57 ^ w51 ^ w49; - w65 = (n << 1) | (n >>> 31); - t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 66 - n = w63 ^ w58 ^ w52 ^ w50; - w66 = (n << 1) | (n >>> 31); - t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 67 - n = w64 ^ w59 ^ w53 ^ w51; - w67 = (n << 1) | (n >>> 31); - t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 68 - n = w65 ^ w60 ^ w54 ^ w52; - w68 = (n << 1) | (n >>> 31); - t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 69 - n = w66 ^ w61 ^ w55 ^ w53; - w69 = (n << 1) | (n >>> 31); - t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 70 - n = w67 ^ w62 ^ w56 ^ w54; - w70 = (n << 1) | (n >>> 31); - t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 71 - n = w68 ^ w63 ^ w57 ^ w55; - w71 = (n << 1) | (n >>> 31); - t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 72 - n = w69 ^ w64 ^ w58 ^ w56; - w72 = (n << 1) | (n >>> 31); - t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 73 - n = w70 ^ w65 ^ w59 ^ w57; - w73 = (n << 1) | (n >>> 31); - t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 74 - n = w71 ^ w66 ^ w60 ^ w58; - w74 = (n << 1) | (n >>> 31); - t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 75 - n = w72 ^ w67 ^ w61 ^ w59; - w75 = (n << 1) | (n >>> 31); - t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 76 - n = w73 ^ w68 ^ w62 ^ w60; - w76 = (n << 1) | (n >>> 31); - t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 77 - n = w74 ^ w69 ^ w63 ^ w61; - w77 = (n << 1) | (n >>> 31); - t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 78 - n = w75 ^ w70 ^ w64 ^ w62; - w78 = (n << 1) | (n >>> 31); - t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 79 - n = w76 ^ w71 ^ w65 ^ w63; - w79 = (n << 1) | (n >>> 31); - t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - } - - function reset () { - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if ( offset & 63 ) - return -1; - if ( ~output ) - if ( output & 31 ) - return -1; + const _1n$a = BigInt(1); - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; + /** + * ElGamal Encryption function + * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) + * @param {Uint8Array} data - To be padded and encrypted + * @param {Uint8Array} p + * @param {Uint8Array} g + * @param {Uint8Array} y + * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} + * @async + */ + async function encrypt$3(data, p, g, y) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } + const padded = emeEncode(data, byteLength(p)); + const m = uint8ArrayToBigInt(padded); - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0; + // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* + // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] + const k = getRandomBigInteger(_1n$a, p - _1n$a); + return { + c1: bigIntToUint8Array(modExp(g, k, p)), + c2: bigIntToUint8Array(mod$2(modExp(y, k, p) * m, p)) + }; + } - HEAP[offset|length] = 0x80; + /** + * ElGamal Encryption function + * @param {Uint8Array} c1 + * @param {Uint8Array} c2 + * @param {Uint8Array} p + * @param {Uint8Array} x + * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} Unpadded message. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ + async function decrypt$3(c1, c2, p, x, randomPayload) { + c1 = uint8ArrayToBigInt(c1); + c2 = uint8ArrayToBigInt(c2); + p = uint8ArrayToBigInt(p); + x = uint8ArrayToBigInt(x); - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - _core_heap(offset); + const padded = mod$2(modInv(modExp(c1, x, p), p) * c2, p); + return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload); + } - length = 0; + /** + * Validate ElGamal parameters + * @param {Uint8Array} p - ElGamal prime + * @param {Uint8Array} g - ElGamal group generator + * @param {Uint8Array} y - ElGamal public key + * @param {Uint8Array} x - ElGamal private exponent + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$8(p, g, y, x) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - HEAP[offset|0] = 0; - } + // Check that 1 < g < p + if (g <= _1n$a || g >= p) { + return false; + } - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; + // Expect p-1 to be large + const pSize = BigInt(bitLength(p)); + const _1023n = BigInt(1023); + if (pSize < _1023n) { + return false; + } - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; + /** + * g should have order p-1 + * Check that g ** (p-1) = 1 mod p + */ + if (modExp(g, p - _1n$a, p) !== _1n$a) { + return false; + } - TOTAL0 = 64; - TOTAL1 = 0; + /** + * Since p-1 is not prime, g might have a smaller order that divides p-1 + * We want to make sure that the order is large enough to hinder a small subgroup attack + * + * We just check g**i != 1 for all i up to a threshold + */ + let res = g; + let i = BigInt(1); + const _2n = BigInt(2); + const threshold = _2n << BigInt(17); // we want order > threshold + while (i < threshold) { + res = mod$2(res * g, p); + if (res === _1n$a) { + return false; } + i++; + } - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{r(p-1) + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const r = getRandomBigInteger(_2n << (pSize - _1n$a), _2n << pSize); // draw r of same size as p-1 + const rqx = (p - _1n$a) * r + x; + if (y !== modExp(g, rqx, p)) { + return false; + } - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); + return true; + } - if ( ~output ) - _state_to_heap(output); + var elgamal = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$3, + encrypt: encrypt$3, + validateParams: validateParams$8 + }); - return hashed|0; - } + // declare const globalThis: Record | undefined; + const crypto$3 = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; + const nacl = {}; - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; + // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. + // Public domain. + // + // Implementation derived from TweetNaCl version 20140427. + // See for details: http://tweetnacl.cr.yp.to/ - if ( offset & 63 ) - return -1; + var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; + }; - if ( ~output ) - if ( output & 31 ) - return -1; + // Pluggable, initialized in high-level API below. + var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; + var _9 = new Uint8Array(32); _9[0] = 9; - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4; - count = (count-1)|0; + var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; + } - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; + } - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; + function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); + } - count = (count-1)|0; - } + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; + } - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; + function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); + } - if ( ~output ) - _state_to_heap(output); + function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } + } - return 0; + function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } + } - return { - // SHA1 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA1 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA1 - pbkdf2_generate_block: pbkdf2_generate_block - } - }; + function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); + } - class Hash { - constructor() { - this.pos = 0; - this.len = 0; - } - reset() { - const { asm } = this.acquire_asm(); - this.result = null; - this.pos = 0; - this.len = 0; - asm.reset(); - return this; - } - process(data) { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - let hpos = this.pos; - let hlen = this.len; - let dpos = 0; - let dlen = data.length; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.process(hpos, hlen); - hpos += wlen; - hlen -= wlen; - if (!hlen) - hpos = 0; - } - this.pos = hpos; - this.len = hlen; - return this; - } - finish() { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - asm.finish(this.pos, this.len, 0); - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set(heap.subarray(0, this.HASH_SIZE)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return this; - } + function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } - const _sha1_block_size = 64; - const _sha1_hash_size = 20; - const heap_pool$1 = []; - const asm_pool$1 = []; - class Sha1 extends Hash { - constructor() { - super(); - this.NAME = 'sha1'; - this.BLOCK_SIZE = _sha1_block_size; - this.HASH_SIZE = _sha1_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$1.pop() || _heap_init(); - this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$1.push(this.heap); - asm_pool$1.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha1().process(data).finish().result; - } - } - Sha1.NAME = 'sha1'; - Sha1.heap_pool = []; - Sha1.asm_pool = []; - Sha1.asm_function = sha1_asm; - - var sha256_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - f = H5; - g = H6; - h = H7; - - // 0 - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 1 - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 2 - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 3 - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 4 - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 5 - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 6 - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 7 - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 8 - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 9 - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 10 - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 11 - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 12 - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 13 - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 14 - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 15 - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 16 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 17 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 18 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 19 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 20 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 21 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 22 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 23 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 24 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 25 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 26 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 27 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 28 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 29 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 30 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 31 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 32 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 33 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 34 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 35 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 36 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 37 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 38 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 39 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 40 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 41 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 42 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 43 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 44 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 45 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 46 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 47 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 48 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 49 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 50 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 51 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 52 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 53 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 54 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 55 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 56 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 57 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 58 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 59 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 60 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 61 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 62 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 63 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } + function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; + } - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; - } - - function reset () { - H0 = 0x6a09e667; - H1 = 0xbb67ae85; - H2 = 0x3c6ef372; - H3 = 0xa54ff53a; - H4 = 0x510e527f; - H5 = 0x9b05688c; - H6 = 0x1f83d9ab; - H7 = 0x5be0cd19; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } + function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; + } - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; + function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; + } - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - H5 = I5; - H6 = I6; - H7 = I7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - H5 = O5; - H6 = O6; - H7 = O7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - O5 = H5; - O6 = H6; - O7 = H7; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - I5 = H5; - I6 = H6; - I7 = H7; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - h5 = h5 ^ H5; - h6 = h6 ^ H6; - h7 = h7 ^ H7; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA256 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA256 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA256 - pbkdf2_generate_block: pbkdf2_generate_block - } - }; - - const _sha256_block_size = 64; - const _sha256_hash_size = 32; - const heap_pool$2 = []; - const asm_pool$2 = []; - class Sha256 extends Hash { - constructor() { - super(); - this.NAME = 'sha256'; - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$2.pop() || _heap_init(); - this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$2.push(this.heap); - asm_pool$2.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha256().process(data).finish().result; - } - } - Sha256.NAME = 'sha256'; - - var minimalisticAssert = assert; - - function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); - } - - var inherits_browser = createCommonjsModule(function (module) { - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - }); - - var inherits_1 = inherits_browser; - - function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; - } - var toArray_1 = toArray; - - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - var toHex_1 = toHex; - - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - var htonl_1 = htonl; - - function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; - } - var toHex32_1 = toHex32; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - var zero2_1 = zero2; - - function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; - } - var zero8_1 = zero8; - - function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; - } - var join32_1 = join32; - - function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; - } - var split32_1 = split32; - - function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); - } - var rotr32_1 = rotr32; - - function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); - } - var rotl32_1 = rotl32; - - function sum32(a, b) { - return (a + b) >>> 0; - } - var sum32_1 = sum32; - - function sum32_3(a, b, c) { - return (a + b + c) >>> 0; - } - var sum32_3_1 = sum32_3; - - function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - var sum32_4_1 = sum32_4; - - function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - var sum32_5_1 = sum32_5; - - function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; - } - var sum64_1 = sum64; - - function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - var sum64_hi_1 = sum64_hi; - - function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - var sum64_lo_1 = sum64_lo; - - function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; - } - var sum64_4_hi_1 = sum64_4_hi; - - function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - var sum64_4_lo_1 = sum64_4_lo; - - function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; - } - var sum64_5_hi_1 = sum64_5_hi; - - function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; - } - var sum64_5_lo_1 = sum64_5_lo; - - function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - var rotr64_hi_1 = rotr64_hi; - - function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - var rotr64_lo_1 = rotr64_lo; - - function shr64_hi(ah, al, num) { - return ah >>> num; - } - var shr64_hi_1 = shr64_hi; - - function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - var shr64_lo_1 = shr64_lo; - - var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 - }; - - function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; - } - var BlockHash_1 = BlockHash; - - BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; - }; - - BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - - return this._digest(enc); - }; - - BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; - }; - - var common = { - BlockHash: BlockHash_1 - }; - - var rotr32$1 = utils.rotr32; - - function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); - } - var ft_1_1 = ft_1; - - function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); - } - var ch32_1 = ch32; - - function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - var maj32_1 = maj32; - - function p32(x, y, z) { - return x ^ y ^ z; - } - var p32_1 = p32; - - function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); - } - var s0_256_1 = s0_256; - - function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); - } - var s1_256_1 = s1_256; - - function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); - } - var g0_256_1 = g0_256; - - function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); - } - var g1_256_1 = g1_256; - - var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 - }; - - var sum32$1 = utils.sum32; - var sum32_4$1 = utils.sum32_4; - var sum32_5$1 = utils.sum32_5; - var ch32$1 = common$1.ch32; - var maj32$1 = common$1.maj32; - var s0_256$1 = common$1.s0_256; - var s1_256$1 = common$1.s1_256; - var g0_256$1 = common$1.g0_256; - var g1_256$1 = common$1.g1_256; - - var BlockHash$1 = common.BlockHash; - - var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 - ]; - - function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils.inherits(SHA256, BlockHash$1); - var _256 = SHA256; - - SHA256.blockSize = 512; - SHA256.outSize = 256; - SHA256.hmacStrength = 192; - SHA256.padLength = 64; - - SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; - - SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); - }; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - _256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils.inherits(SHA224, _256); - var _224 = SHA224; - - SHA224.blockSize = 512; - SHA224.outSize = 224; - SHA224.hmacStrength = 192; - SHA224.padLength = 64; - - SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); - }; - - var rotr64_hi$1 = utils.rotr64_hi; - var rotr64_lo$1 = utils.rotr64_lo; - var shr64_hi$1 = utils.shr64_hi; - var shr64_lo$1 = utils.shr64_lo; - var sum64$1 = utils.sum64; - var sum64_hi$1 = utils.sum64_hi; - var sum64_lo$1 = utils.sum64_lo; - var sum64_4_hi$1 = utils.sum64_4_hi; - var sum64_4_lo$1 = utils.sum64_4_lo; - var sum64_5_hi$1 = utils.sum64_5_hi; - var sum64_5_lo$1 = utils.sum64_5_lo; - - var BlockHash$2 = common.BlockHash; - - var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 - ]; - - function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); - } - utils.inherits(SHA512, BlockHash$2); - var _512 = SHA512; - - SHA512.blockSize = 1024; - SHA512.outSize = 512; - SHA512.hmacStrength = 192; - SHA512.padLength = 128; - - SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } - }; - - SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - minimalisticAssert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); - }; - - SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); - }; - - function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; - } - - function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; - } - - function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; - } - - function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; - } - - function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); // 34 - var c2_hi = rotr64_hi$1(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } - - function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); // 34 - var c2_lo = rotr64_lo$1(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } - - function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } - - function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } - - function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } - - function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } - - function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); // 61 - var c2_hi = shr64_hi$1(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } - - function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); // 61 - var c2_lo = shr64_lo$1(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } - - function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - _512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; - } - utils.inherits(SHA384, _512); - var _384 = SHA384; - - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; - - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); - }; - - var rotl32$1 = utils.rotl32; - var sum32$2 = utils.sum32; - var sum32_3$1 = utils.sum32_3; - var sum32_4$2 = utils.sum32_4; - var BlockHash$3 = common.BlockHash; - - function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash$3.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils.inherits(RIPEMD160, BlockHash$3); - var ripemd160 = RIPEMD160; - - RIPEMD160.blockSize = 512; - RIPEMD160.outSize = 160; - RIPEMD160.hmacStrength = 192; - RIPEMD160.padLength = 64; - - RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32$2( - rotl32$1( - sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32$1(C, 10); - C = B; - B = T; - T = sum32$2( - rotl32$1( - sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$1(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; - }; - - RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); - }; - - function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); - } - - function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; - } - - function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; - } - - var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 - ]; - - var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 - ]; - - var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 - ]; - - var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 - ]; - - var ripemd = { - ripemd160: ripemd160 - }; - - /** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. - */ - - // MD5 Digest - async function md5(entree) { - const digest = md51(util.uint8ArrayToString(entree)); - return util.hexToUint8Array(hex(digest)); - } - - function md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - - a = ff(a, b, c, d, k[0], 7, -680876936); - d = ff(d, a, b, c, k[1], 12, -389564586); - c = ff(c, d, a, b, k[2], 17, 606105819); - b = ff(b, c, d, a, k[3], 22, -1044525330); - a = ff(a, b, c, d, k[4], 7, -176418897); - d = ff(d, a, b, c, k[5], 12, 1200080426); - c = ff(c, d, a, b, k[6], 17, -1473231341); - b = ff(b, c, d, a, k[7], 22, -45705983); - a = ff(a, b, c, d, k[8], 7, 1770035416); - d = ff(d, a, b, c, k[9], 12, -1958414417); - c = ff(c, d, a, b, k[10], 17, -42063); - b = ff(b, c, d, a, k[11], 22, -1990404162); - a = ff(a, b, c, d, k[12], 7, 1804603682); - d = ff(d, a, b, c, k[13], 12, -40341101); - c = ff(c, d, a, b, k[14], 17, -1502002290); - b = ff(b, c, d, a, k[15], 22, 1236535329); - - a = gg(a, b, c, d, k[1], 5, -165796510); - d = gg(d, a, b, c, k[6], 9, -1069501632); - c = gg(c, d, a, b, k[11], 14, 643717713); - b = gg(b, c, d, a, k[0], 20, -373897302); - a = gg(a, b, c, d, k[5], 5, -701558691); - d = gg(d, a, b, c, k[10], 9, 38016083); - c = gg(c, d, a, b, k[15], 14, -660478335); - b = gg(b, c, d, a, k[4], 20, -405537848); - a = gg(a, b, c, d, k[9], 5, 568446438); - d = gg(d, a, b, c, k[14], 9, -1019803690); - c = gg(c, d, a, b, k[3], 14, -187363961); - b = gg(b, c, d, a, k[8], 20, 1163531501); - a = gg(a, b, c, d, k[13], 5, -1444681467); - d = gg(d, a, b, c, k[2], 9, -51403784); - c = gg(c, d, a, b, k[7], 14, 1735328473); - b = gg(b, c, d, a, k[12], 20, -1926607734); - - a = hh(a, b, c, d, k[5], 4, -378558); - d = hh(d, a, b, c, k[8], 11, -2022574463); - c = hh(c, d, a, b, k[11], 16, 1839030562); - b = hh(b, c, d, a, k[14], 23, -35309556); - a = hh(a, b, c, d, k[1], 4, -1530992060); - d = hh(d, a, b, c, k[4], 11, 1272893353); - c = hh(c, d, a, b, k[7], 16, -155497632); - b = hh(b, c, d, a, k[10], 23, -1094730640); - a = hh(a, b, c, d, k[13], 4, 681279174); - d = hh(d, a, b, c, k[0], 11, -358537222); - c = hh(c, d, a, b, k[3], 16, -722521979); - b = hh(b, c, d, a, k[6], 23, 76029189); - a = hh(a, b, c, d, k[9], 4, -640364487); - d = hh(d, a, b, c, k[12], 11, -421815835); - c = hh(c, d, a, b, k[15], 16, 530742520); - b = hh(b, c, d, a, k[2], 23, -995338651); - - a = ii(a, b, c, d, k[0], 6, -198630844); - d = ii(d, a, b, c, k[7], 10, 1126891415); - c = ii(c, d, a, b, k[14], 15, -1416354905); - b = ii(b, c, d, a, k[5], 21, -57434055); - a = ii(a, b, c, d, k[12], 6, 1700485571); - d = ii(d, a, b, c, k[3], 10, -1894986606); - c = ii(c, d, a, b, k[10], 15, -1051523); - b = ii(b, c, d, a, k[1], 21, -2054922799); - a = ii(a, b, c, d, k[8], 6, 1873313359); - d = ii(d, a, b, c, k[15], 10, -30611744); - c = ii(c, d, a, b, k[6], 15, -1560198380); - b = ii(b, c, d, a, k[13], 21, 1309151649); - a = ii(a, b, c, d, k[4], 6, -145523070); - d = ii(d, a, b, c, k[11], 10, -1120210379); - c = ii(c, d, a, b, k[2], 15, 718787259); - b = ii(b, c, d, a, k[9], 21, -343485551); - - x[0] = add32(a, x[0]); - x[1] = add32(b, x[1]); - x[2] = add32(c, x[2]); - x[3] = add32(d, x[3]); - } - - function cmn(q, a, b, x, s, t) { - a = add32(add32(a, q), add32(x, t)); - return add32((a << s) | (a >>> (32 - s)), b); - } - - function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); - } - - function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); - } - - function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); - } - - function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); - } - - function md51(s) { - const n = s.length; - const state = [1732584193, -271733879, -1732584194, 271733878]; - let i; - for (i = 64; i <= s.length; i += 64) { - md5cycle(state, md5blk(s.substring(i - 64, i))); - } - s = s.substring(i - 64); - const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (i = 0; i < s.length; i++) { - tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); - } - tail[i >> 2] |= 0x80 << ((i % 4) << 3); - if (i > 55) { - md5cycle(state, tail); - for (i = 0; i < 16; i++) { - tail[i] = 0; - } - } - tail[14] = n * 8; - md5cycle(state, tail); - return state; - } - - /* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ - function md5blk(s) { /* I figured global was faster. */ - const md5blks = []; - let i; /* Andy King said do it this way. */ - for (i = 0; i < 64; i += 4) { - md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << - 24); - } - return md5blks; - } - - const hex_chr = '0123456789abcdef'.split(''); - - function rhex(n) { - let s = ''; - let j = 0; - for (; j < 4; j++) { - s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; - } - return s; - } - - function hex(x) { - for (let i = 0; i < x.length; i++) { - x[i] = rhex(x[i]); - } - return x.join(''); - } - - /* this function is much faster, - so if possible we use it. Some IEs - are the only ones I know of that - need the idiotic second function, - generated by an if clause. */ - - function add32(a, b) { - return (a + b) & 0xFFFFFFFF; - } - - /** - * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://github.com/indutny/hash.js|hash.js} - * @module crypto/hash - * @private - */ - - const webCrypto = util.getWebCrypto(); - const nodeCrypto = util.getNodeCrypto(); - const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes(); - - function nodeHash(type) { - if (!nodeCrypto || !nodeCryptoHashes.includes(type)) { - return; - } - return async function (data) { - const shasum = nodeCrypto.createHash(type); - return transform(data, value => { - shasum.update(value); - }, () => new Uint8Array(shasum.digest())); - }; - } - - function hashjsHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } - const hashInstance = hash(); - return transform(data, value => { - hashInstance.update(value); - }, () => new Uint8Array(hashInstance.digest())); - }; - } - - function asmcryptoHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (util.isStream(data)) { - const hashInstance = new hash(); - return transform(data, value => { - hashInstance.process(value); - }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } else { - return hash.bytes(data); - } - }; - } - - const hashFunctions = { - md5: nodeHash('md5') || md5, - sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'), - sha224: nodeHash('sha224') || hashjsHash(_224), - sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'), - sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'), - sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160) - }; - - var hash = { - - /** @see module:md5 */ - md5: hashFunctions.md5, - /** @see asmCrypto */ - sha1: hashFunctions.sha1, - /** @see hash.js */ - sha224: hashFunctions.sha224, - /** @see asmCrypto */ - sha256: hashFunctions.sha256, - /** @see hash.js */ - sha384: hashFunctions.sha384, - /** @see asmCrypto */ - sha512: hashFunctions.sha512, - /** @see hash.js */ - ripemd: hashFunctions.ripemd, - - /** - * Create a hash on the specified data using the specified algorithm - * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {Uint8Array} data - Data to be hashed - * @returns {Promise} Hash value. - */ - digest: function(algo, data) { - switch (algo) { - case enums.hash.md5: - return this.md5(data); - case enums.hash.sha1: - return this.sha1(data); - case enums.hash.ripemd: - return this.ripemd(data); - case enums.hash.sha256: - return this.sha256(data); - case enums.hash.sha384: - return this.sha384(data); - case enums.hash.sha512: - return this.sha512(data); - case enums.hash.sha224: - return this.sha224(data); - default: - throw new Error('Invalid hash function.'); - } - }, - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns {Integer} Size in bytes of the resulting hash. - */ - getHashByteLength: function(algo) { - switch (algo) { - case enums.hash.md5: - return 16; - case enums.hash.sha1: - case enums.hash.ripemd: - return 20; - case enums.hash.sha256: - return 32; - case enums.hash.sha384: - return 48; - case enums.hash.sha512: - return 64; - case enums.hash.sha224: - return 28; - default: - throw new Error('Invalid hash algorithm.'); - } - } - }; - - class AES_CFB { - static encrypt(data, key, iv) { - return new AES_CFB(key, iv).encrypt(data); - } - static decrypt(data, key, iv) { - return new AES_CFB(key, iv).decrypt(data); - } - constructor(key, iv, aes) { - this.aes = aes ? aes : new AES(key, iv, true, 'CFB'); - delete this.aes.padding; - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } - } - - /** - * Get implementation of the given cipher - * @param {enums.symmetric} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ - function getCipher(algo) { - const algoName = enums.read(enums.symmetric, algo); - return cipher[algoName]; - } - - // Modified by ProtonTech AG - - const webCrypto$1 = util.getWebCrypto(); - const nodeCrypto$1 = util.getNodeCrypto(); - - const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : []; - const nodeAlgos = { - idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ - tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, - cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, - blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, - aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, - aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, - aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined - /* twofish is not implemented in OpenSSL */ - }; - - /** - * CFB encryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} plaintext - * @param {Uint8Array} iv - * @param {Object} config - full configuration, defaults to openpgp.config - * @returns MaybeStream - */ - async function encrypt(algo, key, plaintext, iv, config) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeEncrypt(algo, key, plaintext, iv); - } - if (util.isAES(algo)) { - return aesEncrypt(algo, key, plaintext, iv, config); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - const blockc = iv.slice(); - let pt = new Uint8Array(); - const process = chunk => { - if (chunk) { - pt = util.concatUint8Array([pt, chunk]); - } - const ciphertext = new Uint8Array(pt.length); - let i; - let j = 0; - while (chunk ? pt.length >= block_size : pt.length) { - const encblock = cipherfn.encrypt(blockc); - for (i = 0; i < block_size; i++) { - blockc[i] = pt[i] ^ encblock[i]; - ciphertext[j++] = blockc[i]; - } - pt = pt.subarray(block_size); - } - return ciphertext.subarray(0, j); - }; - return transform(plaintext, process, process); - } - - /** - * CFB decryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} ciphertext - * @param {Uint8Array} iv - * @returns MaybeStream - */ - async function decrypt(algo, key, ciphertext, iv) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeDecrypt(algo, key, ciphertext, iv); - } - if (util.isAES(algo)) { - return aesDecrypt(algo, key, ciphertext, iv); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - let blockp = iv; - let ct = new Uint8Array(); - const process = chunk => { - if (chunk) { - ct = util.concatUint8Array([ct, chunk]); - } - const plaintext = new Uint8Array(ct.length); - let i; - let j = 0; - while (chunk ? ct.length >= block_size : ct.length) { - const decblock = cipherfn.encrypt(blockp); - blockp = ct.subarray(0, block_size); - for (i = 0; i < block_size; i++) { - plaintext[j++] = blockp[i] ^ decblock[i]; - } - ct = ct.subarray(block_size); - } - return plaintext.subarray(0, j); - }; - return transform(ciphertext, process, process); - } - - function aesEncrypt(algo, key, pt, iv, config) { - if ( - util.getWebCrypto() && - key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support - !util.isStream(pt) && - pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2 - ) { // Web Crypto - return webEncrypt(algo, key, pt, iv); - } - // asm.js fallback - const cfb = new AES_CFB(key, iv); - return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish()); - } - - function aesDecrypt(algo, key, ct, iv) { - if (util.isStream(ct)) { - const cfb = new AES_CFB(key, iv); - return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish()); - } - return AES_CFB.decrypt(ct, key, iv); - } - - function xorMut(a, b) { - for (let i = 0; i < a.length; i++) { - a[i] = a[i] ^ b[i]; - } - } - - async function webEncrypt(algo, key, pt, iv) { - const ALGO = 'AES-CBC'; - const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']); - const { blockSize } = getCipher(algo); - const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]); - const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length); - xorMut(ct, pt); - return ct; - } - - function nodeEncrypt(algo, key, pt, iv) { - const algoName = enums.read(enums.symmetric, algo); - const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv); - return transform(pt, value => new Uint8Array(cipherObj.update(value))); - } - - function nodeDecrypt(algo, key, ct, iv) { - const algoName = enums.read(enums.symmetric, algo); - const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv); - return transform(ct, value => new Uint8Array(decipherObj.update(value))); - } - - var cfb = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt, - decrypt: decrypt - }); - - class AES_CTR { - static encrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - static decrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - constructor(key, nonce, aes) { - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - delete this.aes.padding; - this.AES_CTR_set_options(nonce); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - AES_CTR_set_options(nonce, counter, size) { - let { asm } = this.aes.acquire_asm(); - if (size !== undefined) { - if (size < 8 || size > 48) - throw new IllegalArgumentError('illegal counter size'); - let mask = Math.pow(2, size) - 1; - asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0); - } - else { - size = 48; - asm.set_mask(0, 0, 0xffff, 0xffffffff); - } - if (nonce !== undefined) { - let len = nonce.length; - if (!len || len > 16) - throw new IllegalArgumentError('illegal nonce size'); - let view = new DataView(new ArrayBuffer(16)); - new Uint8Array(view.buffer).set(nonce); - asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); - } - else { - throw new Error('nonce is required'); - } - if (counter !== undefined) { - if (counter < 0 || counter >= Math.pow(2, size)) - throw new IllegalArgumentError('illegal counter value'); - asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0); - } - } - } - - class AES_CBC { - static encrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).encrypt(data); - } - static decrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).decrypt(data); - } - constructor(key, iv, padding = true, aes) { - this.aes = aes ? aes : new AES(key, iv, padding, 'CBC'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } - } - - /** - * @fileoverview This module implements AES-CMAC on top of - * native AES-CBC using either the WebCrypto API or Node.js' crypto API. - * @module crypto/cmac - * @private - */ - - const webCrypto$2 = util.getWebCrypto(); - const nodeCrypto$2 = util.getNodeCrypto(); - - - /** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - - const blockLength = 16; - - - /** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param {Uint8Array} data - * @param {Uint8Array} padding - */ - function rightXORMut(data, padding) { - const offset = data.length - blockLength; - for (let i = 0; i < blockLength; i++) { - data[i + offset] ^= padding[i]; - } - return data; - } - - function pad(data, padding, padding2) { - // if |M| in {n, 2n, 3n, ...} - if (data.length && data.length % blockLength === 0) { - // then return M xor→ B, - return rightXORMut(data, padding); - } - // else return (M || 10^(n−1−(|M| mod n))) xor→ P - const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength))); - padded.set(data); - padded[data.length] = 0b10000000; - return rightXORMut(padded, padding2); - } - - const zeroBlock = new Uint8Array(blockLength); - - async function CMAC(key) { - const cbc = await CBC(key); - - // L ← E_K(0^n); B ← 2L; P ← 4L - const padding = util.double(await cbc(zeroBlock)); - const padding2 = util.double(padding); - - return async function(data) { - // return CBC_K(pad(M; B, P)) - return (await cbc(pad(data, padding, padding2))).subarray(-blockLength); - }; - } - - async function CBC(key) { - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); - return async function(pt) { - const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt); - return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt) { - const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); - const ct = en.update(pt); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt) { - return AES_CBC.encrypt(pt, key, false, zeroBlock); - }; - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - const webCrypto$3 = util.getWebCrypto(); - const nodeCrypto$3 = util.getNodeCrypto(); - const Buffer$1 = util.getNodeBuffer(); - - - const blockLength$1 = 16; - const ivLength = blockLength$1; - const tagLength = blockLength$1; - - const zero = new Uint8Array(blockLength$1); - const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1; - const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2; - - async function OMAC(key) { - const cmac = await CMAC(key); - return function(t, message) { - return cmac(util.concatUint8Array([t, message])); - }; - } - - async function CTR(key) { - if ( - util.getWebCrypto() && - key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - ) { - key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); - return async function(pt, iv) { - const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt); - return new Uint8Array(ct); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt, iv) { - const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); - const ct = Buffer$1.concat([en.update(pt), en.final()]); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt, iv) { - return AES_CTR.encrypt(pt, key, iv); - }; - } - - - /** - * Class to en/decrypt using EAX mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ - async function EAX(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('EAX mode supports only AES cipher'); - } - - const [ - omac, - ctr - ] = await Promise.all([ - OMAC(key), - CTR(key) - ]); - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - const [ - omacNonce, - omacAdata - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata) - ]); - const ciphered = await ctr(plaintext, omacNonce); - const omacCiphered = await omac(two, ciphered); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - return util.concatUint8Array([ciphered, tag]); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to verify - * @returns {Promise} The plaintext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext'); - const ciphered = ciphertext.subarray(0, -tagLength); - const ctTag = ciphertext.subarray(-tagLength); - const [ - omacNonce, - omacAdata, - omacCiphered - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata), - omac(two, ciphered) - ]); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); - const plaintext = await ctr(ciphered, omacNonce); - return plaintext; - } - }; - } - - - /** - * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. - * @param {Uint8Array} iv - The initialization vector (16 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ - EAX.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[8 + i] ^= chunkIndex[i]; - } - return nonce; - }; - - EAX.blockLength = blockLength$1; - EAX.ivLength = ivLength; - EAX.tagLength = tagLength; - - // OpenPGP.js - An OpenPGP implementation in javascript - - const blockLength$2 = 16; - const ivLength$1 = 15; - - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: - // While OCB [RFC7253] allows the authentication tag length to be of any - // number up to 128 bits long, this document requires a fixed - // authentication tag length of 128 bits (16 octets) for simplicity. - const tagLength$1 = 16; - - - function ntz(n) { - let ntz = 0; - for (let i = 1; (n & i) === 0; i <<= 1) { - ntz++; - } - return ntz; - } - - function xorMut$1(S, T) { - for (let i = 0; i < S.length; i++) { - S[i] ^= T[i]; - } - return S; - } - - function xor(S, T) { - return xorMut$1(S.slice(), T); - } - - const zeroBlock$1 = new Uint8Array(blockLength$2); - const one$1 = new Uint8Array([1]); - - /** - * Class to en/decrypt using OCB mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ - async function OCB(cipher$1, key) { - - let maxNtz = 0; - let encipher; - let decipher; - let mask; - - constructKeyVariables(cipher$1, key); - - function constructKeyVariables(cipher$1, key) { - const cipherName = enums.read(enums.symmetric, cipher$1); - const aes = new cipher[cipherName](key); - encipher = aes.encrypt.bind(aes); - decipher = aes.decrypt.bind(aes); - - const mask_x = encipher(zeroBlock$1); - const mask_$ = util.double(mask_x); - mask = []; - mask[0] = util.double(mask_$); - - - mask.x = mask_x; - mask.$ = mask_$; - } - - function extendKeyVariables(text, adata) { - const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1; - for (let i = maxNtz + 1; i <= newMaxNtz; i++) { - mask[i] = util.double(mask[i - 1]); - } - maxNtz = newMaxNtz; - } - - function hash(adata) { - if (!adata.length) { - // Fast path - return zeroBlock$1; - } - - // - // Consider A as a sequence of 128-bit blocks - // - const m = adata.length / blockLength$2 | 0; - - const offset = new Uint8Array(blockLength$2); - const sum = new Uint8Array(blockLength$2); - for (let i = 0; i < m; i++) { - xorMut$1(offset, mask[ntz(i + 1)]); - xorMut$1(sum, encipher(xor(offset, adata))); - adata = adata.subarray(blockLength$2); - } - - // - // Process any final partial block; compute final hash value - // - if (adata.length) { - xorMut$1(offset, mask.x); - - const cipherInput = new Uint8Array(blockLength$2); - cipherInput.set(adata, 0); - cipherInput[adata.length] = 0b10000000; - xorMut$1(cipherInput, offset); - - xorMut$1(sum, encipher(cipherInput)); - } - - return sum; - } - - /** - * Encrypt/decrypt data. - * @param {encipher|decipher} fn - Encryption/decryption block cipher function - * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. - */ - function crypt(fn, text, nonce, adata) { - // - // Consider P as a sequence of 128-bit blocks - // - const m = text.length / blockLength$2 | 0; - - // - // Key-dependent variables - // - extendKeyVariables(text, adata); - - // - // Nonce-dependent and per-encryption variables - // - // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N - // Note: We assume here that tagLength mod 16 == 0. - const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]); - // bottom = str2num(Nonce[123..128]) - const bottom = paddedNonce[blockLength$2 - 1] & 0b111111; - // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) - paddedNonce[blockLength$2 - 1] &= 0b11000000; - const kTop = encipher(paddedNonce); - // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) - const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); - // Offset_0 = Stretch[1+bottom..128+bottom] - const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); - // Checksum_0 = zeros(128) - const checksum = new Uint8Array(blockLength$2); - - const ct = new Uint8Array(text.length + tagLength$1); - - // - // Process any whole blocks - // - let i; - let pos = 0; - for (i = 0; i < m; i++) { - // Offset_i = Offset_{i-1} xor L_{ntz(i)} - xorMut$1(offset, mask[ntz(i + 1)]); - // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) - // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) - ct.set(xorMut$1(fn(xor(offset, text)), offset), pos); - // Checksum_i = Checksum_{i-1} xor P_i - xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos)); - - text = text.subarray(blockLength$2); - pos += blockLength$2; - } - - // - // Process any final partial block and compute raw tag - // - if (text.length) { - // Offset_* = Offset_m xor L_* - xorMut$1(offset, mask.x); - // Pad = ENCIPHER(K, Offset_*) - const padding = encipher(offset); - // C_* = P_* xor Pad[1..bitlen(P_*)] - ct.set(xor(text, padding), pos); - - // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - const xorInput = new Uint8Array(blockLength$2); - xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); - xorInput[text.length] = 0b10000000; - xorMut$1(checksum, xorInput); - pos += text.length; - } - // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) - const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata)); - - // - // Assemble ciphertext - // - // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] - ct.set(tag, pos); - return ct; - } - - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - return crypt(encipher, plaintext, nonce, adata); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); - - const tag = ciphertext.subarray(-tagLength$1); - ciphertext = ciphertext.subarray(0, -tagLength$1); - - const crypted = crypt(decipher, ciphertext, nonce, adata); - // if (Tag[1..TAGLEN] == T) - if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { - return crypted.subarray(0, -tagLength$1); - } - throw new Error('Authentication tag mismatch'); - } - }; - } - - - /** - * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. - * @param {Uint8Array} iv - The initialization vector (15 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ - OCB.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[7 + i] ^= chunkIndex[i]; - } - return nonce; - }; - - OCB.blockLength = blockLength$2; - OCB.ivLength = ivLength$1; - OCB.tagLength = tagLength$1; - - const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 - class AES_GCM { - constructor(key, nonce, adata, tagSize = 16, aes) { - this.tagSize = tagSize; - this.gamma0 = 0; - this.counter = 1; - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - let { asm, heap } = this.aes.acquire_asm(); - // Init GCM - asm.gcm_init(); - // Tag size - if (this.tagSize < 4 || this.tagSize > 16) - throw new IllegalArgumentError('illegal tagSize value'); - // Nonce - const noncelen = nonce.length || 0; - const noncebuf = new Uint8Array(16); - if (noncelen !== 12) { - this._gcm_mac_process(nonce); - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = 0; - heap[4] = 0; - heap[5] = 0; - heap[6] = 0; - heap[7] = 0; - heap[8] = 0; - heap[9] = 0; - heap[10] = 0; - heap[11] = noncelen >>> 29; - heap[12] = (noncelen >>> 21) & 255; - heap[13] = (noncelen >>> 13) & 255; - heap[14] = (noncelen >>> 5) & 255; - heap[15] = (noncelen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_iv(0, 0, 0, 0); - noncebuf.set(heap.subarray(0, 16)); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; - } - const nonceview = new DataView(noncebuf.buffer); - this.gamma0 = nonceview.getUint32(12); - asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); - asm.set_mask(0, 0, 0, 0xffffffff); - // Associated data - if (adata !== undefined) { - if (adata.length > _AES_GCM_data_maxLength) - throw new IllegalArgumentError('illegal adata length'); - if (adata.length) { - this.adata = adata; - this._gcm_mac_process(adata); - } - else { - this.adata = undefined; - } - } - else { - this.adata = undefined; - } - // Counter - if (this.counter < 1 || this.counter > 0xffffffff) - throw new RangeError('counter must be a positive 32-bit integer'); - asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0); - } - static encrypt(cleartext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext); - } - static decrypt(ciphertext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext); - } - encrypt(data) { - return this.AES_GCM_encrypt(data); - } - decrypt(data) { - return this.AES_GCM_decrypt(data); - } - AES_GCM_Encrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len); - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Encrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let adata = this.adata; - let pos = this.aes.pos; - let len = this.aes.len; - const result = new Uint8Array(len + tagSize); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16); - if (len) - result.set(heap.subarray(pos, pos + len)); - let i = len; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - result.set(heap.subarray(0, tagSize), len); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_Decrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0; - let tlen = len + dlen - rlen; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > tlen) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - pos = 0; - len = 0; - } - if (dlen > 0) { - len += _heap_write(heap, 0, data, dpos, dlen); - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Decrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let tagSize = this.tagSize; - let adata = this.adata; - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rlen = len - tagSize; - if (len < tagSize) - throw new IllegalStateError('authentication tag not found'); - const result = new Uint8Array(rlen); - const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); - let i = rlen; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len - tagSize; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - let acheck = 0; - for (let i = 0; i < tagSize; ++i) - acheck |= atag[i] ^ heap[i]; - if (acheck) - throw new SecurityError('data integrity check failed'); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_decrypt(data) { - const result1 = this.AES_GCM_Decrypt_process(data); - const result2 = this.AES_GCM_Decrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - AES_GCM_encrypt(data) { - const result1 = this.AES_GCM_Encrypt_process(data); - const result2 = this.AES_GCM_Encrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - _gcm_mac_process(data) { - let { asm, heap } = this.aes.acquire_asm(); - let dpos = 0; - let dlen = data.length || 0; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, 0, data, dpos, dlen); - dpos += wlen; - dlen -= wlen; - while (wlen & 15) - heap[wlen++] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen); - } - } - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - const webCrypto$4 = util.getWebCrypto(); - const nodeCrypto$4 = util.getNodeCrypto(); - const Buffer$2 = util.getNodeBuffer(); - - const blockLength$3 = 16; - const ivLength$2 = 12; // size of the IV in bytes - const tagLength$2 = 16; // size of the tag in bytes - const ALGO = 'AES-GCM'; - - /** - * Class to en/decrypt using GCM mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ - async function GCM(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('GCM mode supports only AES cipher'); - } - - if (util.getNodeCrypto()) { // Node crypto library - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - en.setAAD(adata); - const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - de.setAAD(adata); - de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext - const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]); - return new Uint8Array(pt); - } - }; - } - - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); - - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.encrypt(pt, key, iv, adata); - } - const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt); - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.decrypt(ct, key, iv, adata); - } - const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct); - return new Uint8Array(pt); - } - }; - } - - return { - encrypt: async function(pt, iv, adata) { - return AES_GCM.encrypt(pt, key, iv, adata); - }, - - decrypt: async function(ct, iv, adata) { - return AES_GCM.decrypt(ct, key, iv, adata); - } - }; - } - - - /** - * Get GCM nonce. Note: this operation is not defined by the standard. - * A future version of the standard may define GCM mode differently, - * hopefully under a different ID (we use Private/Experimental algorithm - * ID 100) so that we can maintain backwards compatibility. - * @param {Uint8Array} iv - The initialization vector (12 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ - GCM.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[4 + i] ^= chunkIndex[i]; - } - return nonce; - }; - - GCM.blockLength = blockLength$3; - GCM.ivLength = ivLength$2; - GCM.tagLength = tagLength$2; - - /** - * @fileoverview Cipher modes - * @module crypto/mode - * @private - */ - - var mode = { - /** @see module:crypto/mode/cfb */ - cfb: cfb, - /** @see module:crypto/mode/gcm */ - gcm: GCM, - experimentalGCM: GCM, - /** @see module:crypto/mode/eax */ - eax: EAX, - /** @see module:crypto/mode/ocb */ - ocb: OCB - }; - - var naclFastLight = createCommonjsModule(function (module) { - /*jshint bitwise: false*/ - - (function(nacl) { - - // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. - // Public domain. - // - // Implementation derived from TweetNaCl version 20140427. - // See for details: http://tweetnacl.cr.yp.to/ - - var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; - }; - - // Pluggable, initialized in high-level API below. - var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - - var _9 = new Uint8Array(32); _9[0] = 9; - - var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - - function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; - } - - function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); - } - - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; - } - - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); - } - - function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } - } - - function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - - function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; - } - - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; - } - - function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; - } - - function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; - } - - function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; - } - - function S(o, a) { - M(o, a, a); - } - - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; - } - - function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; - } - - function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); - } - - function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); - } - - function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - - function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } - } - - function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } - } - - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - - function crypto_sign_keypair(pk, sk, seeded) { - var d; - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; - } - - var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } - } - - function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); - } - - // Note: difference from C - smlen returned, not passed as argument. - function crypto_sign(sm, m, n, sk) { - var d, h, r; - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - r = nacl.hash(sm.subarray(32, smlen)); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - h = nacl.hash(sm.subarray(0, smlen)); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; - } - - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; - } - - function crypto_sign_open(m, sm, n, pk) { - var i; - var t = new Uint8Array(32), h; - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - h = nacl.hash(m.subarray(0, n)); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - return n; - } - - var crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32; - - function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError('unexpected type, use Uint8Array'); - } - } - - function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; - } - - nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; - }; - - nacl.box = {}; - - nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; - }; - - nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; - }; - - nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; - }; - - nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; - }; - - nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); - }; - - nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; - }; - - nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; - }; - - nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; - }; - - nacl.setPRNG = function(fn) { - randombytes = fn; - }; - - (function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof commonjsRequire !== 'undefined') { - // Node.js. - crypto = void('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } - })(); - - })(module.exports ? module.exports : (self.nacl = self.nacl || {})); - }); - - // GPG4Browsers - An OpenPGP implementation in javascript - - const nodeCrypto$5 = util.getNodeCrypto(); - - /** - * Retrieve secure random byte array of the specified length - * @param {Integer} length - Length in bytes to generate - * @returns {Uint8Array} Random byte array. - */ - function getRandomBytes(length) { - const buf = new Uint8Array(length); - if (nodeCrypto$5) { - const bytes = nodeCrypto$5.randomBytes(buf.length); - buf.set(bytes); - } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - crypto.getRandomValues(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; - } - - /** - * Create a secure random BigInteger that is greater than or equal to min and less than max. - * @param {module:BigInteger} min - Lower bound, included - * @param {module:BigInteger} max - Upper bound, excluded - * @returns {Promise} Random BigInteger. - * @async - */ - async function getRandomBigInteger(min, max) { - const BigInteger = await util.getBigInteger(); - - if (max.lt(min)) { - throw new Error('Illegal parameter value: max <= min'); - } - - const modulus = max.sub(min); - const bytes = modulus.byteLength(); - - // Using a while loop is necessary to avoid bias introduced by the mod operation. - // However, we request 64 extra random bits so that the bias is negligible. - // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - const r = new BigInteger(await getRandomBytes(bytes + 8)); - return r.mod(modulus).add(min); - } - - var random = /*#__PURE__*/Object.freeze({ - __proto__: null, - getRandomBytes: getRandomBytes, - getRandomBigInteger: getRandomBigInteger - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - /** - * Generate a probably prime random number - * @param {Integer} bits - Bit length of the prime - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns BigInteger - * @async - */ - async function randomProbablePrime(bits, e, k) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - const min = one.leftShift(new BigInteger(bits - 1)); - const thirty = new BigInteger(30); - /* - * We can avoid any multiples of 3 and 5 by looking at n mod 30 - * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 - * the next possible prime is mod 30: - * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 - */ - const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; - - const n = await getRandomBigInteger(min, min.leftShift(one)); - let i = n.mod(thirty).toNumber(); - - do { - n.iadd(new BigInteger(adds[i])); - i = (i + adds[i]) % adds.length; - // If reached the maximum, go back to the minimum. - if (n.bitLength() > bits) { - n.imod(min.leftShift(one)).iadd(min); - i = n.mod(thirty).toNumber(); - } - } while (!await isProbablePrime(n, e, k)); - return n; - } - - /** - * Probabilistic primality testing - * @param {BigInteger} n - Number to test - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns {boolean} - * @async - */ - async function isProbablePrime(n, e, k) { - if (e && !n.dec().gcd(e).isOne()) { - return false; - } - if (!await divisionTest(n)) { - return false; - } - if (!await fermat(n)) { - return false; - } - if (!await millerRabin(n, k)) { - return false; - } - // TODO implement the Lucas test - // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - return true; - } - - /** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n != 1. - * @param {BigInteger} n - Number to test - * @param {BigInteger} b - Optional Fermat test base - * @returns {boolean} - */ - async function fermat(n, b) { - const BigInteger = await util.getBigInteger(); - b = b || new BigInteger(2); - return b.modExp(n.dec(), n).isOne(); - } - - async function divisionTest(n) { - const BigInteger = await util.getBigInteger(); - return smallPrimes.every(m => { - return n.mod(new BigInteger(m)) !== 0; - }); - } - - // https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c - const smallPrimes = [ - 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, - 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, - 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, - 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, - 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, - 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, - 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, - 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, - 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, - 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, - 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, - 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, - 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, - 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, - 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, - 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, - 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, - 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, - 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, - 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, - 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, - 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, - 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, - 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, - 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, - 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, - 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, - 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, - 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, - 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, - 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, - 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, - 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, - 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, - 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, - 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, - 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, - 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, - 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, - 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, - 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, - 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, - 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, - 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, - 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, - 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, - 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, - 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, - 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, - 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, - 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, - 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, - 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, - 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, - 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, - 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, - 4957, 4967, 4969, 4973, 4987, 4993, 4999 - ]; - - - // Miller-Rabin - Miller Rabin algorithm for primality test - // Copyright Fedor Indutny, 2014. - // - // This software is licensed under the MIT License. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin - - // Sample syntax for Fixed-Base Miller-Rabin: - // millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) - - /** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param {BigInteger} n - Number to test - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @param {Function} rand - Optional function to generate potential witnesses - * @returns {boolean} - * @async - */ - async function millerRabin(n, k, rand) { - const BigInteger = await util.getBigInteger(); - const len = n.bitLength(); - - if (!k) { - k = Math.max(1, (len / 48) | 0); - } - - const n1 = n.dec(); // n - 1 - - // Find d and s, (n - 1) = (2 ^ s) * d; - let s = 0; - while (!n1.getBit(s)) { s++; } - const d = n.rightShift(new BigInteger(s)); - - for (; k > 0; k--) { - const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1); - - let x = a.modExp(d, n); - if (x.isOne() || x.equal(n1)) { - continue; - } - - let i; - for (i = 1; i < s; i++) { - x = x.mul(x).mod(n); - - if (x.isOne()) { - return false; - } - if (x.equal(n1)) { - break; - } - } - - if (i === s) { - return false; - } - } - - return true; - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - /** - * ASN1 object identifiers for hashes - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} - */ - const hash_headers = []; - hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; - hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; - hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; - hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; - hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; - hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; - hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; - - /** - * Create padding with secure random data - * @private - * @param {Integer} length - Length of the padding in bytes - * @returns {Uint8Array} Random padding. - */ - function getPKCS1Padding(length) { - const result = new Uint8Array(length); - let count = 0; - while (count < length) { - const randomBytes = getRandomBytes(length - count); - for (let i = 0; i < randomBytes.length; i++) { - if (randomBytes[i] !== 0) { - result[count++] = randomBytes[i]; - } - } - } - return result; - } - - /** - * Create a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} - * @param {Uint8Array} message - Message to be encoded - * @param {Integer} keyLength - The length in octets of the key modulus - * @returns {Uint8Array} EME-PKCS1 padded message. - */ - function emeEncode(message, keyLength) { - const mLength = message.length; - // length checking - if (mLength > keyLength - 11) { - throw new Error('Message too long'); - } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - const PS = getPKCS1Padding(keyLength - mLength - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - const encoded = new Uint8Array(keyLength); - // 0x00 byte - encoded[1] = 2; - encoded.set(PS, 2); - // 0x00 bytes - encoded.set(message, keyLength - mLength); - return encoded; - } - - /** - * Decode a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} - * @param {Uint8Array} encoded - Encoded message bytes - * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) - * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) - * @throws {Error} on decoding failure, unless `randomPayload` is provided - */ - function emeDecode(encoded, randomPayload) { - // encoded format: 0x00 0x02 0x00 - let offset = 2; - let separatorNotFound = 1; - for (let j = offset; j < encoded.length; j++) { - separatorNotFound &= encoded[j] !== 0; - offset += separatorNotFound; - } - - const psLen = offset - 2; - const payload = encoded.subarray(offset + 1); // discard the 0x00 separator - const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - - if (randomPayload) { - return util.selectUint8Array(isValidPadding, payload, randomPayload); - } - - if (isValidPadding) { - return payload; - } - - throw new Error('Decryption error'); - } - - /** - * Create a EMSA-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} - * @param {Integer} algo - Hash algorithm type used - * @param {Uint8Array} hashed - Message to be encoded - * @param {Integer} emLen - Intended length in octets of the encoded message - * @returns {Uint8Array} Encoded message. - */ - async function emsaEncode(algo, hashed, emLen) { - let i; - if (hashed.length !== hash.getHashByteLength(algo)) { - throw new Error('Invalid hash length'); - } - // produce an ASN.1 DER value for the hash function used. - // Let T be the full hash prefix - const hashPrefix = new Uint8Array(hash_headers[algo].length); - for (i = 0; i < hash_headers[algo].length; i++) { - hashPrefix[i] = hash_headers[algo][i]; - } - // and let tLen be the length in octets prefix and hashed data - const tLen = hashPrefix.length + hashed.length; - if (emLen < tLen + 11) { - throw new Error('Intended encoded message length too short'); - } - // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF - // The length of PS will be at least 8 octets - const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - - // Concatenate PS, the hash prefix, hashed data, and other padding to form the - // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed - const EM = new Uint8Array(emLen); - EM[1] = 0x01; - EM.set(PS, 2); - EM.set(hashPrefix, emLen - tLen); - EM.set(hashed, emLen - hashed.length); - return EM; - } - - var pkcs1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - emeEncode: emeEncode, - emeDecode: emeDecode, - emsaEncode: emsaEncode - }); - - // GPG4Browsers - An OpenPGP implementation in javascript - - const webCrypto$5 = util.getWebCrypto(); - const nodeCrypto$6 = util.getNodeCrypto(); - const asn1 = nodeCrypto$6 ? void('asn1.js') : undefined; - - /* eslint-disable no-invalid-this */ - const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('version').int(), // 0 - this.key('modulus').int(), // n - this.key('publicExponent').int(), // e - this.key('privateExponent').int(), // d - this.key('prime1').int(), // p - this.key('prime2').int(), // q - this.key('exponent1').int(), // dp - this.key('exponent2').int(), // dq - this.key('coefficient').int() // u - ); - }) : undefined; - - const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('modulus').int(), // n - this.key('publicExponent').int() // e - ); - }) : undefined; - /* eslint-enable no-invalid-this */ - - /** Create signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} hashed - Hashed message - * @returns {Promise} RSA Signature. - * @async - */ - async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeSign(hashAlgo, data, n, e, d, p, q, u); - } - } - return bnSign(hashAlgo, n, d, hashed); - } - - /** - * Verify signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} s - Signature - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} hashed - Hashed message - * @returns {Boolean} - * @async - */ - async function verify(hashAlgo, data, s, n, e, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeVerify(hashAlgo, data, s, n, e); - } - } - return bnVerify(hashAlgo, s, n, e, hashed); - } - - /** - * Encrypt message - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @returns {Promise} RSA Ciphertext. - * @async - */ - async function encrypt$1(data, n, e) { - if (util.getNodeCrypto()) { - return nodeEncrypt$1(data, n, e); - } - return bnEncrypt(data, n, e); - } - - /** - * Decrypt RSA message - * @param {Uint8Array} m - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} RSA Plaintext. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ - async function decrypt$1(data, n, e, d, p, q, u, randomPayload) { - // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, - // and we want to avoid checking the error type to decide if the random payload - // should indeed be returned. - if (util.getNodeCrypto() && !randomPayload) { - try { - return await nodeDecrypt$1(data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } - return bnDecrypt(data, n, e, d, p, q, u, randomPayload); - } - - /** - * Generate a new random private key B bits long with public exponent E. - * - * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param {Integer} bits - RSA bit length - * @param {Integer} e - RSA public exponent - * @returns {{n, e, d, - * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = p ** -1 mod q - * @async - */ - async function generate(bits, e) { - const BigInteger = await util.getBigInteger(); - - e = new BigInteger(e); - - // Native RSA keygen using Web Crypto - if (util.getWebCrypto()) { - const keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, // the specified keysize in bits - publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); - // map JWK parameters to corresponding OpenPGP names - return { - n: b64ToUint8Array(jwk.n), - e: e.toUint8Array(), - d: b64ToUint8Array(jwk.d), - // switch p and q - p: b64ToUint8Array(jwk.q), - q: b64ToUint8Array(jwk.p), - // Since p and q are switched in places, u is the inverse of jwk.q - u: b64ToUint8Array(jwk.qi) - }; - } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) { - const opts = { - modulusLength: bits, - publicExponent: e.toNumber(), - publicKeyEncoding: { type: 'pkcs1', format: 'der' }, - privateKeyEncoding: { type: 'pkcs1', format: 'der' } - }; - const prv = await new Promise((resolve, reject) => { - nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => { - if (err) { - reject(err); - } else { - resolve(RSAPrivateKey.decode(der, 'der')); - } - }); - }); - /** - * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`. - * @link https://tools.ietf.org/html/rfc3447#section-3.2 - * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1 - */ - return { - n: prv.modulus.toArrayLike(Uint8Array), - e: prv.publicExponent.toArrayLike(Uint8Array), - d: prv.privateExponent.toArrayLike(Uint8Array), - // switch p and q - p: prv.prime2.toArrayLike(Uint8Array), - q: prv.prime1.toArrayLike(Uint8Array), - // Since p and q are switched in places, we can keep u as defined by DER - u: prv.coefficient.toArrayLike(Uint8Array) - }; - } - - // RSA keygen fallback using 40 iterations of the Miller-Rabin test - // See https://stackoverflow.com/a/6330138 for justification - // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST - let p; - let q; - let n; - do { - q = await randomProbablePrime(bits - (bits >> 1), e, 40); - p = await randomProbablePrime(bits >> 1, e, 40); - n = p.mul(q); - } while (n.bitLength() !== bits); - - const phi = p.dec().imul(q.dec()); - - if (q.lt(p)) { - [p, q] = [q, p]; - } - - return { - n: n.toUint8Array(), - e: e.toUint8Array(), - d: e.modInv(phi).toUint8Array(), - p: p.toUint8Array(), - q: q.toUint8Array(), - // dp: d.mod(p.subn(1)), - // dq: d.mod(q.subn(1)), - u: p.modInv(q).toUint8Array() - }; - } - - /** - * Validate RSA parameters - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA inverse of p w.r.t. q - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - p = new BigInteger(p); - q = new BigInteger(q); - - // expect pq = n - if (!p.mul(q).equal(n)) { - return false; - } - - const two = new BigInteger(2); - // expect p*u = 1 mod q - u = new BigInteger(u); - if (!p.mul(u).mod(q).isOne()) { - return false; - } - - e = new BigInteger(e); - d = new BigInteger(d); - /** - * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) - * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] - * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] - * - * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) - */ - const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3)); - const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q - const rde = r.mul(d).mul(e); - - const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r); - if (!areInverses) { - return false; - } - - return true; - } - - async function bnSign(hashAlgo, n, d, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); - d = new BigInteger(d); - if (m.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return m.modExp(d, n).toUint8Array('be', n.byteLength()); - } - - async function webSign(hashName, data, n, e, d, p, q, u) { - /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJWK, so it usually works out, but nevertheless, - * not all OpenPGP keys are compatible with this requirement. - * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still - * does if the underlying Web Crypto does so (though the tested implementations - * don't do so). - */ - const jwk = await privateToJWK(n, e, d, p, q, u); - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }; - const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); - return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); - } - - async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(data); - sign.end(); - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPrivateKey.encode(keyObject, 'der'); - return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' })); - } - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - return new Uint8Array(sign.sign(pem)); - } - - async function bnVerify(hashAlgo, s, n, e, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - s = new BigInteger(s); - e = new BigInteger(e); - if (s.gte(n)) { - throw new Error('Signature size cannot exceed modulus size'); - } - const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); - return util.equalsUint8Array(EM1, EM2); - } - - async function webVerify(hashName, data, s, n, e) { - const jwk = publicToJWK(n, e); - const key = await webCrypto$5.importKey('jwk', jwk, { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }, false, ['verify']); - return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); - } - - async function nodeVerify(hashAlgo, data, s, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(data); - verify.end(); - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1' }; - } else { - key = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - } - try { - return await verify.verify(key, s); - } catch (err) { - return false; - } - } - - async function nodeEncrypt$1(data, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data)); - } - - async function bnEncrypt(data, n, e) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - data = new BigInteger(emeEncode(data, n.byteLength())); - e = new BigInteger(e); - if (data.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return data.modExp(e, n).toUint8Array('be', n.byteLength()); - } - - async function nodeDecrypt$1(data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPrivateKey.encode(keyObject, 'der'); - key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - try { - return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data)); - } catch (err) { - throw new Error('Decryption error'); - } - } - - async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { - const BigInteger = await util.getBigInteger(); - data = new BigInteger(data); - n = new BigInteger(n); - e = new BigInteger(e); - d = new BigInteger(d); - p = new BigInteger(p); - q = new BigInteger(q); - u = new BigInteger(u); - if (data.gte(n)) { - throw new Error('Data too large.'); - } - const dq = d.mod(q.dec()); // d mod (q-1) - const dp = d.mod(p.dec()); // d mod (p-1) - - const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n); - const blinder = unblinder.modInv(n).modExp(e, n); - data = data.mul(blinder).mod(n); - - - const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p - const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q - const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q) - - let result = h.mul(p).add(mp); // result < n due to relations above - - result = result.mul(unblinder).mod(n); - - - return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload); - } - - /** Convert Openpgp private key params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - * @param {Uint8Array} d - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} u - */ - async function privateToJWK(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - const pNum = new BigInteger(p); - const qNum = new BigInteger(q); - const dNum = new BigInteger(d); - - let dq = dNum.mod(qNum.dec()); // d mod (q-1) - let dp = dNum.mod(pNum.dec()); // d mod (p-1) - dp = dp.toUint8Array(); - dq = dq.toUint8Array(); - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - d: uint8ArrayToB64(d, true), - // switch p and q - p: uint8ArrayToB64(q, true), - q: uint8ArrayToB64(p, true), - // switch dp and dq - dp: uint8ArrayToB64(dq, true), - dq: uint8ArrayToB64(dp, true), - qi: uint8ArrayToB64(u, true), - ext: true - }; - } - - /** Convert Openpgp key public params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - */ - function publicToJWK(n, e) { - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - ext: true - }; - } - - var rsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign, - verify: verify, - encrypt: encrypt$1, - decrypt: decrypt$1, - generate: generate, - validateParams: validateParams - }); - - // GPG4Browsers - An OpenPGP implementation in javascript - - /** - * ElGamal Encryption function - * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) - * @param {Uint8Array} data - To be padded and encrypted - * @param {Uint8Array} p - * @param {Uint8Array} g - * @param {Uint8Array} y - * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} - * @async - */ - async function encrypt$2(data, p, g, y) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const padded = emeEncode(data, p.byteLength()); - const m = new BigInteger(padded); - - // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* - // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] - const k = await getRandomBigInteger(new BigInteger(1), p.dec()); - return { - c1: g.modExp(k, p).toUint8Array(), - c2: y.modExp(k, p).imul(m).imod(p).toUint8Array() - }; - } - - /** - * ElGamal Encryption function - * @param {Uint8Array} c1 - * @param {Uint8Array} c2 - * @param {Uint8Array} p - * @param {Uint8Array} x - * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} Unpadded message. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ - async function decrypt$2(c1, c2, p, x, randomPayload) { - const BigInteger = await util.getBigInteger(); - c1 = new BigInteger(c1); - c2 = new BigInteger(c2); - p = new BigInteger(p); - x = new BigInteger(x); - - const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p); - return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload); - } - - /** - * Validate ElGamal parameters - * @param {Uint8Array} p - ElGamal prime - * @param {Uint8Array} g - ElGamal group generator - * @param {Uint8Array} y - ElGamal public key - * @param {Uint8Array} x - ElGamal private exponent - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$1(p, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - // Expect p-1 to be large - const pSize = new BigInteger(p.bitLength()); - const n1023 = new BigInteger(1023); - if (pSize.lt(n1023)) { - return false; - } - - /** - * g should have order p-1 - * Check that g ** (p-1) = 1 mod p - */ - if (!g.modExp(p.dec(), p).isOne()) { - return false; - } - - /** - * Since p-1 is not prime, g might have a smaller order that divides p-1 - * We want to make sure that the order is large enough to hinder a small subgroup attack - * - * We just check g**i != 1 for all i up to a threshold - */ - let res = g; - const i = new BigInteger(1); - const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold - while (i.lt(threshold)) { - res = res.mul(g).imod(p); - if (res.isOne()) { - return false; - } - i.iinc(); - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{r(p-1) + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1 - const rqx = p.dec().imul(r).iadd(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; - } - - var elgamal = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt$2, - decrypt: decrypt$2, - validateParams: validateParams$1 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - class OID { - constructor(oid) { - if (oid instanceof OID) { - this.oid = oid.oid; - } else if (util.isArray(oid) || - util.isUint8Array(oid)) { - oid = new Uint8Array(oid); - if (oid[0] === 0x06) { // DER encoded oid byte array - if (oid[1] !== oid.length - 2) { - throw new Error('Length mismatch in DER encoded oid'); - } - oid = oid.subarray(2); - } - this.oid = oid; - } else { - this.oid = ''; - } - } - - /** - * Method to read an OID object - * @param {Uint8Array} input - Where to read the OID from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length >= 1) { - const length = input[0]; - if (input.length >= 1 + length) { - this.oid = input.subarray(1, 1 + length); - return 1 + this.oid.length; - } - } - throw new Error('Invalid oid'); - } - - /** - * Serialize an OID object - * @returns {Uint8Array} Array with the serialized value the OID. - */ - write() { - return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); - } - - /** - * Serialize an OID object as a hex string - * @returns {string} String with the hex value of the OID. - */ - toHex() { - return util.uint8ArrayToHex(this.oid); - } - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns {string} String with the canonical name of the curve. - */ - getName() { - const hex = this.toHex(); - if (enums.curve[hex]) { - return enums.write(enums.curve, hex); - } else { - throw new Error('Unknown curve object identifier.'); - } - } - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - function keyFromPrivate(indutnyCurve, priv) { - const keyPair = indutnyCurve.keyPair({ priv: priv }); - return keyPair; - } - - function keyFromPublic(indutnyCurve, pub) { - const keyPair = indutnyCurve.keyPair({ pub: pub }); - if (keyPair.validate().result !== true) { - throw new Error('Invalid elliptic public key'); - } - return keyPair; - } - - async function getIndutnyCurve(name) { - if (!config.useIndutnyElliptic) { - throw new Error('This curve is only supported in the full build of OpenPGP.js'); - } - const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; }); - return new elliptic.ec(name); - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - function readSimpleLength(bytes) { - let len = 0; - let offset; - const type = bytes[0]; - - - if (type < 192) { - [len] = bytes; - offset = 1; - } else if (type < 255) { - len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; - offset = 2; - } else if (type === 255) { - len = util.readNumber(bytes.subarray(1, 1 + 4)); - offset = 5; - } - - return { - len: len, - offset: offset - }; - } - - /** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * - * @param {Integer} length - The length to encode - * @returns {Uint8Array} String with openpgp length representation. - */ - function writeSimpleLength(length) { - if (length < 192) { - return new Uint8Array([length]); - } else if (length > 191 && length < 8384) { - /* - * let a = (total data packet length) - 192 let bc = two octet - * representation of a let d = b + 192 - */ - return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); - } - - function writePartialLength(power) { - if (power < 0 || power > 30) { - throw new Error('Partial Length power must be between 1 and 30'); - } - return new Uint8Array([224 + power]); - } - - function writeTag(tag_type) { - /* we're only generating v4 packet headers here */ - return new Uint8Array([0xC0 | tag_type]); - } - - /** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * - * @param {Integer} tag_type - Tag type - * @param {Integer} length - Length of the payload - * @returns {String} String of the header. - */ - function writeHeader(tag_type, length) { - /* we're only generating v4 packet headers here */ - return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); - } - - /** - * Whether the packet type supports partial lengths per RFC4880 - * @param {Integer} tag - Tag type - * @returns {Boolean} String of the header. - */ - function supportsStreaming(tag) { - return [ - enums.packet.literalData, - enums.packet.compressedData, - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ].includes(tag); - } - - /** - * Generic static Packet Parser function - * - * @param {Uint8Array | ReadableStream} input - Input stream as string - * @param {Function} callback - Function to call with the parsed packet - * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. - */ - async function readPackets(input, callback) { - const reader = getReader(input); - let writer; - let callbackReturned; - try { - const peekedBytes = await reader.peekBytes(2); - // some sanity checks - if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { - throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); - } - const headerByte = await reader.readByte(); - let tag = -1; - let format = -1; - let packetLength; - - format = 0; // 0 = old format; 1 = new format - if ((headerByte & 0x40) !== 0) { - format = 1; - } - - let packetLengthType; - if (format) { - // new format header - tag = headerByte & 0x3F; // bit 5-0 - } else { - // old format header - tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packetLengthType = headerByte & 0x03; // bit 1-0 - } - - const packetSupportsStreaming = supportsStreaming(tag); - let packet = null; - if (packetSupportsStreaming) { - if (util.isStream(input) === 'array') { - const arrayStream = new ArrayStream(); - writer = getWriter(arrayStream); - packet = arrayStream; - } else { - const transform = new TransformStream(); - writer = getWriter(transform.writable); - packet = transform.readable; - } - // eslint-disable-next-line callback-return - callbackReturned = callback({ tag, packet }); - } else { - packet = []; - } - - let wasPartialLength; - do { - if (!format) { - // 4.2.1. Old Format Packet Lengths - switch (packetLengthType) { - case 0: - // The packet has a one-octet length. The header is 2 octets - // long. - packetLength = await reader.readByte(); - break; - case 1: - // The packet has a two-octet length. The header is 3 octets - // long. - packetLength = (await reader.readByte() << 8) | await reader.readByte(); - break; - case 2: - // The packet has a four-octet length. The header is 5 - // octets long. - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - break; - default: - // 3 - The packet is of indeterminate length. The header is 1 - // octet long, and the implementation must determine how long - // the packet is. If the packet is in a file, this means that - // the packet extends until the end of the file. In general, - // an implementation SHOULD NOT use indeterminate-length - // packets except where the end of the data will be clear - // from the context, and even then it is better to use a - // definite length, or a new format header. The new format - // headers described below have a mechanism for precisely - // encoding data of indeterminate length. - packetLength = Infinity; - break; - } - } else { // 4.2.2. New Format Packet Lengths - // 4.2.2.1. One-Octet Lengths - const lengthByte = await reader.readByte(); - wasPartialLength = false; - if (lengthByte < 192) { - packetLength = lengthByte; - // 4.2.2.2. Two-Octet Lengths - } else if (lengthByte >= 192 && lengthByte < 224) { - packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; - // 4.2.2.4. Partial Body Lengths - } else if (lengthByte > 223 && lengthByte < 255) { - packetLength = 1 << (lengthByte & 0x1F); - wasPartialLength = true; - if (!packetSupportsStreaming) { - throw new TypeError('This packet type does not support partial lengths.'); - } - // 4.2.2.3. Five-Octet Lengths - } else { - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - } - } - if (packetLength > 0) { - let bytesRead = 0; - while (true) { - if (writer) await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (packetLength === Infinity) break; - throw new Error('Unexpected end of packet'); - } - const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); - if (writer) await writer.write(chunk); - else packet.push(chunk); - bytesRead += value.length; - if (bytesRead >= packetLength) { - reader.unshift(value.subarray(packetLength - bytesRead + value.length)); - break; - } - } - } - } while (wasPartialLength); - - // If this was not a packet that "supports streaming", we peek to check - // whether it is the last packet in the message. We peek 2 bytes instead - // of 1 because the beginning of this function also peeks 2 bytes, and we - // want to cut a `subarray` of the correct length into `web-stream-tools`' - // `externalBuffer` as a tiny optimization here. - // - // If it *was* a streaming packet (i.e. the data packets), we peek at the - // entire remainder of the stream, in order to forward errors in the - // remainder of the stream to the packet data. (Note that this means we - // read/peek at all signature packets before closing the literal data - // packet, for example.) This forwards MDC errors to the literal data - // stream, for example, so that they don't get lost / forgotten on - // decryptedMessage.packets.stream, which we never look at. - // - // An example of what we do when stream-parsing a message containing - // [ one-pass signature packet, literal data packet, signature packet ]: - // 1. Read the one-pass signature packet - // 2. Peek 2 bytes of the literal data packet - // 3. Parse the one-pass signature packet - // - // 4. Read the literal data packet, simultaneously stream-parsing it - // 5. Peek until the end of the message - // 6. Finish parsing the literal data packet - // - // 7. Read the signature packet again (we already peeked at it in step 5) - // 8. Peek at the end of the stream again (`peekBytes` returns undefined) - // 9. Parse the signature packet - // - // Note that this means that if there's an error in the very end of the - // stream, such as an MDC error, we throw in step 5 instead of in step 8 - // (or never), which is the point of this exercise. - const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); - if (writer) { - await writer.ready; - await writer.close(); - } else { - packet = util.concatUint8Array(packet); - // eslint-disable-next-line callback-return - await callback({ tag, packet }); - } - return !nextPacket || !nextPacket.length; - } catch (e) { - if (writer) { - await writer.abort(e); - return true; - } else { - throw e; - } - } finally { - if (writer) { - await callbackReturned; - } - reader.releaseLock(); - } - } - - class UnsupportedError extends Error { - constructor(...params) { - super(...params); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, UnsupportedError); - } - - this.name = 'UnsupportedError'; - } - } - - class UnparseablePacket { - constructor(tag, rawContent) { - this.tag = tag; - this.rawContent = rawContent; - } - - write() { - return this.rawContent; - } - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - const webCrypto$6 = util.getWebCrypto(); - const nodeCrypto$7 = util.getNodeCrypto(); - - const webCurves = { - 'p256': 'P-256', - 'p384': 'P-384', - 'p521': 'P-521' - }; - const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : []; - const nodeCurves = nodeCrypto$7 ? { - secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, - p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, - p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, - p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, - ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined, - curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined, - brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, - brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, - brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined - } : {}; - - const curves = { - p256: { - oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.p256, - web: webCurves.p256, - payloadSize: 32, - sharedSize: 256 - }, - p384: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.p384, - web: webCurves.p384, - payloadSize: 48, - sharedSize: 384 - }, - p521: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.p521, - web: webCurves.p521, - payloadSize: 66, - sharedSize: 528 - }, - secp256k1: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1, - payloadSize: 32 - }, - ed25519: { - oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], - keyType: enums.publicKey.eddsaLegacy, - hash: enums.hash.sha512, - node: false, // nodeCurves.ed25519 TODO - payloadSize: 32 - }, - curve25519: { - oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], - keyType: enums.publicKey.ecdh, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: false, // nodeCurves.curve25519 TODO - payloadSize: 32 - }, - brainpoolP256r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1, - payloadSize: 32 - }, - brainpoolP384r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1, - payloadSize: 48 - }, - brainpoolP512r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1, - payloadSize: 64 - } - }; - - class CurveWithOID { - constructor(oidOrName, params) { - try { - if (util.isArray(oidOrName) || - util.isUint8Array(oidOrName)) { - // by oid byte array - oidOrName = new OID(oidOrName); - } - if (oidOrName instanceof OID) { - // by curve OID - oidOrName = oidOrName.getName(); - } - // by curve name or oid string - this.name = enums.write(enums.curve, oidOrName); - } catch (err) { - throw new UnsupportedError('Unknown curve'); - } - params = params || curves[this.name]; - - this.keyType = params.keyType; - - this.oid = params.oid; - this.hash = params.hash; - this.cipher = params.cipher; - this.node = params.node && curves[this.name]; - this.web = params.web && curves[this.name]; - this.payloadSize = params.payloadSize; - if (this.web && util.getWebCrypto()) { - this.type = 'web'; - } else if (this.node && util.getNodeCrypto()) { - this.type = 'node'; - } else if (this.name === 'curve25519') { - this.type = 'curve25519'; - } else if (this.name === 'ed25519') { - this.type = 'ed25519'; - } - } - - async genKeyPair() { - let keyPair; - switch (this.type) { - case 'web': - try { - return await webGenKeyPair(this.name); - } catch (err) { - util.printDebugError('Browser did not support generating ec key ' + err.message); - break; - } - case 'node': - return nodeGenKeyPair(this.name); - case 'curve25519': { - const privateKey = getRandomBytes(32); - privateKey[0] = (privateKey[0] & 127) | 64; - privateKey[31] &= 248; - const secretKey = privateKey.slice().reverse(); - keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - case 'ed25519': { - const privateKey = getRandomBytes(32); - const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - } - const indutnyCurve = await getIndutnyCurve(this.name); - keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToString(getRandomBytes(32)) - }); - return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; - } - } - - async function generate$1(curve) { - const BigInteger = await util.getBigInteger(); - - curve = new CurveWithOID(curve); - const keyPair = await curve.genKeyPair(); - const Q = new BigInteger(keyPair.publicKey).toUint8Array(); - const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize); - return { - oid: curve.oid, - Q, - secret, - hash: curve.hash, - cipher: curve.cipher - }; - } - - /** - * Get preferred hash algo to use with the given curve - * @param {module:type/oid} oid - curve oid - * @returns {enums.hash} hash algorithm - */ - function getPreferredHashAlgo(oid) { - return curves[enums.write(enums.curve, oid.toHex())].hash; - } - - /** - * Validate ECDH and ECDSA parameters - * Not suitable for EdDSA (different secret key format) - * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves - * @param {module:type/oid} oid - EC object identifier - * @param {Uint8Array} Q - EC public point - * @param {Uint8Array} d - EC secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateStandardParams(algo, oid, Q, d) { - const supportedCurves = { - p256: true, - p384: true, - p521: true, - secp256k1: true, - curve25519: algo === enums.publicKey.ecdh, - brainpoolP256r1: true, - brainpoolP384r1: true, - brainpoolP512r1: true - }; - - // Check whether the given curve is supported - const curveName = oid.getName(); - if (!supportedCurves[curveName]) { - return false; - } - - if (curveName === 'curve25519') { - d = d.slice().reverse(); - // Re-derive public point Q' - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d); - - Q = new Uint8Array(Q); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - if (!util.equalsUint8Array(dG, Q)) { - return false; - } - - return true; - } - - const curve = await getIndutnyCurve(curveName); - try { - // Parse Q and check that it is on the curve but not at infinity - Q = keyFromPublic(curve, Q).getPublic(); - } catch (validationErrors) { - return false; - } - - /** - * Re-derive public point Q' = dG from private key - * Expect Q == Q' - */ - const dG = keyFromPrivate(curve, d).getPublic(); - if (!dG.eq(Q)) { - return false; - } - - return true; - } - - ////////////////////////// - // // - // Helper functions // - // // - ////////////////////////// - - - async function webGenKeyPair(name) { - // Note: keys generated with ECDSA and ECDH are structurally equivalent - const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - - const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey); - const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey); - - return { - publicKey: jwkToRawPublic(publicKey), - privateKey: b64ToUint8Array(privateKey.d) - }; - } - - async function nodeGenKeyPair(name) { - // Note: ECDSA and ECDH key generation is structurally equivalent - const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]); - await ecdh.generateKeys(); - return { - publicKey: new Uint8Array(ecdh.getPublicKey()), - privateKey: new Uint8Array(ecdh.getPrivateKey()) - }; - } - - ////////////////////////// - // // - // Helper functions // - // // - ////////////////////////// - - /** - * @param {JsonWebKey} jwk - key for conversion - * - * @returns {Uint8Array} Raw public key. - */ - function jwkToRawPublic(jwk) { - const bufX = b64ToUint8Array(jwk.x); - const bufY = b64ToUint8Array(jwk.y); - const publicKey = new Uint8Array(bufX.length + bufY.length + 1); - publicKey[0] = 0x04; - publicKey.set(bufX, 1); - publicKey.set(bufY, bufX.length + 1); - return publicKey; - } - - /** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * - * @returns {JsonWebKey} Public key in jwk format. - */ - function rawPublicToJWK(payloadSize, name, publicKey) { - const len = payloadSize; - const bufX = publicKey.slice(1, len + 1); - const bufY = publicKey.slice(len + 1, len * 2 + 1); - // https://www.rfc-editor.org/rfc/rfc7518.txt - const jwk = { - kty: 'EC', - crv: name, - x: uint8ArrayToB64(bufX, true), - y: uint8ArrayToB64(bufY, true), - ext: true - }; - return jwk; - } - - /** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * @param {Uint8Array} privateKey - private key - * - * @returns {JsonWebKey} Private key in jwk format. - */ - function privateToJWK$1(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJWK(payloadSize, name, publicKey); - jwk.d = uint8ArrayToB64(privateKey, true); - return jwk; - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - const webCrypto$7 = util.getWebCrypto(); - const nodeCrypto$8 = util.getNodeCrypto(); - - /** - * Sign a message using the provided key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ - async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - const keyPair = { publicKey, privateKey }; - switch (curve.type) { - case 'web': { - // If browser doesn't support a curve, we'll catch it - try { - // Need to await to make sure browser succeeds - return await webSign$1(curve, hashAlgo, message, keyPair); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunaley Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support signing: ' + err.message); - } - break; - } - case 'node': { - const signature = await nodeSign$1(curve, hashAlgo, message, keyPair); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - } - } - return ellipticSign(curve, hashed, privateKey); - } - - /** - * Verifies if a signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify - * @param {Uint8Array} message - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ - async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - switch (curve.type) { - case 'web': - try { - // Need to await to make sure browser succeeds - return await webVerify$1(curve, hashAlgo, signature, message, publicKey); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunately Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support verifying: ' + err.message); - } - break; - case 'node': - return nodeVerify$1(curve, hashAlgo, signature, message, publicKey); - } - } - const digest = (typeof hashAlgo === 'undefined') ? message : hashed; - return ellipticVerify(curve, signature, digest, publicKey); - } - - /** - * Validate ECDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDSA public point - * @param {Uint8Array} d - ECDSA secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$2(oid, Q, d) { - const curve = new CurveWithOID(oid); - // Reject curves x25519 and ed25519 - if (curve.keyType !== enums.publicKey.ecdsa) { - return false; - } - - // To speed up the validation, we try to use node- or webcrypto when available - // and sign + verify a random message - switch (curve.type) { - case 'web': - case 'node': { - const message = getRandomBytes(8); - const hashAlgo = enums.hash.sha256; - const hashed = await hash.digest(hashAlgo, message); - try { - const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed); - return await verify$1(oid, hashAlgo, signature, message, Q, hashed); - } catch (err) { - return false; - } - } - default: - return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); - } - } - - - ////////////////////////// - // // - // Helper functions // - // // - ////////////////////////// - - async function ellipticSign(curve, hashed, privateKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPrivate(indutnyCurve, privateKey); - const signature = key.sign(hashed); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - - async function ellipticVerify(curve, signature, digest, publicKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPublic(indutnyCurve, publicKey); - return key.verify(digest, signature); - } - - async function webSign$1(curve, hashAlgo, message, keyPair) { - const len = curve.payloadSize; - const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['sign'] - ); - - const signature = new Uint8Array(await webCrypto$7.sign( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - message - )); - - return { - r: signature.slice(0, len), - s: signature.slice(len, len << 1) - }; - } - - async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['verify'] - ); - - const signature = util.concatUint8Array([r, s]).buffer; - - return webCrypto$7.verify( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - signature, - message - ); - } - - async function nodeSign$1(curve, hashAlgo, message, keyPair) { - const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(message); - sign.end(); - const key = ECPrivateKey.encode({ - version: 1, - parameters: curve.oid, - privateKey: Array.from(keyPair.privateKey), - publicKey: { unused: 0, data: Array.from(keyPair.publicKey) } - }, 'pem', { - label: 'EC PRIVATE KEY' - }); - - return ECDSASignature.decode(sign.sign(key), 'der'); - } - - async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(message); - verify.end(); - const key = SubjectPublicKeyInfo.encode({ - algorithm: { - algorithm: [1, 2, 840, 10045, 2, 1], - parameters: curve.oid - }, - subjectPublicKey: { unused: 0, data: Array.from(publicKey) } - }, 'pem', { - label: 'PUBLIC KEY' - }); - const signature = ECDSASignature.encode({ - r: new BN(r), s: new BN(s) - }, 'der'); - - try { - return verify.verify(key, signature); - } catch (err) { - return false; - } - } - - // Originally written by Owen Smith https://github.com/omsmith - // Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ - - /* eslint-disable no-invalid-this */ - - const asn1$1 = nodeCrypto$8 ? void('asn1.js') : undefined; - - const ECDSASignature = nodeCrypto$8 ? - asn1$1.define('ECDSASignature', function() { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ); - }) : undefined; - - const ECPrivateKey = nodeCrypto$8 ? - asn1$1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().any(), - this.key('publicKey').explicit(1).optional().bitstr() - ); - }) : undefined; - - const AlgorithmIdentifier = nodeCrypto$8 ? - asn1$1.define('AlgorithmIdentifier', function() { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional().any() - ); - }) : undefined; - - const SubjectPublicKeyInfo = nodeCrypto$8 ? - asn1$1.define('SubjectPublicKeyInfo', function() { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ); - }) : undefined; - - var ecdsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$1, - verify: verify$1, - validateParams: validateParams$2 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - - /** - * Sign a message using the provided legacy EdDSA key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ - async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - // EdDSA signature params are returned in little-endian format - return { - r: signature.subarray(0, 32), - s: signature.subarray(32) - }; - } - - /** - * Verifies if a legacy EdDSA signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ - async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const signature = util.concatUint8Array([r, s]); - return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1)); - } - /** - * Validate legacy EdDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - EdDSA public point - * @param {Uint8Array} k - EdDSA secret seed - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$3(oid, Q, k) { - // Check whether the given curve is supported - if (oid.getName() !== 'ed25519') { - return false; - } - - /** - * Derive public point Q' = dG from private key - * and expect Q == Q' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - return util.equalsUint8Array(Q, dG); - - } - - var eddsa_legacy = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$2, - verify: verify$2, - validateParams: validateParams$3 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - - /** - * Generate (non-legacy) EdDSA key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} - */ - async function generate$2(algo) { - switch (algo) { - case enums.publicKey.ed25519: { - const seed = getRandomBytes(32); - const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed); - return { A, seed }; - } - default: - throw new Error('Unsupported EdDSA algorithm'); - } - } - - /** - * Sign a message using the provided key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * RS: Uint8Array - * }>} Signature of the message - * @async - */ - async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - const secretKey = util.concatUint8Array([privateKey, publicKey]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - return { RS: signature }; - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - - } - - /** - * Verifies if a signature is valid for a message - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{ RS: Uint8Array }} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ - async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - return naclFastLight.sign.detached.verify(hashed, RS, publicKey); - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - } - /** - * Validate (non-legacy) EdDSA parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - EdDSA public point - * @param {Uint8Array} seed - EdDSA secret seed - * @param {Uint8Array} oid - (legacy only) EdDSA OID - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$4(algo, A, seed) { - switch (algo) { - case enums.publicKey.ed25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed); - return util.equalsUint8Array(A, publicKey); - } - - case enums.publicKey.ed448: // unsupported - default: - return false; - } - } - - function getPreferredHashAlgo$1(algo) { - switch (algo) { - case enums.publicKey.ed25519: - return enums.hash.sha256; - default: - throw new Error('Unknown EdDSA algo'); - } - } - - var eddsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$2, - sign: sign$3, - verify: verify$3, - validateParams: validateParams$4, - getPreferredHashAlgo: getPreferredHashAlgo$1 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - /** - * AES key wrap - * @function - * @param {Uint8Array} key - * @param {Uint8Array} data - * @returns {Uint8Array} - */ - function wrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const P = unpack(data); - let A = IV; - const R = P; - const n = P.length / 2; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 0; j <= 5; ++j) { - for (let i = 0; i < n; ++i) { - t[1] = n * j + (1 + i); - // B = A - B[0] = A[0]; - B[1] = A[1]; - // B = A || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES(K, B) - B = unpack(aes.encrypt(pack(B))); - // A = MSB(64, B) ^ t - A = B.subarray(0, 2); - A[0] ^= t[0]; - A[1] ^= t[1]; - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - return pack(A, R); - } - - /** - * AES key unwrap - * @function - * @param {String} key - * @param {String} data - * @returns {Uint8Array} - * @throws {Error} - */ - function unwrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const C = unpack(data); - let A = C.subarray(0, 2); - const R = C.subarray(2); - const n = C.length / 2 - 1; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 5; j >= 0; --j) { - for (let i = n - 1; i >= 0; --i) { - t[1] = n * j + (i + 1); - // B = A ^ t - B[0] = A[0] ^ t[0]; - B[1] = A[1] ^ t[1]; - // B = (A ^ t) || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES-1(B) - B = unpack(aes.decrypt(pack(B))); - // A = MSB(64, B) - A = B.subarray(0, 2); - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - if (A[0] === IV[0] && A[1] === IV[1]) { - return pack(R); - } - throw new Error('Key Data Integrity failed'); - } - - function createArrayBuffer(data) { - if (util.isString(data)) { - const { length } = data; - const buffer = new ArrayBuffer(length); - const view = new Uint8Array(buffer); - for (let j = 0; j < length; ++j) { - view[j] = data.charCodeAt(j); - } - return buffer; - } - return new Uint8Array(data).buffer; - } - - function unpack(data) { - const { length } = data; - const buffer = createArrayBuffer(data); - const view = new DataView(buffer); - const arr = new Uint32Array(length / 4); - for (let i = 0; i < length / 4; ++i) { - arr[i] = view.getUint32(4 * i); - } - return arr; - } - - function pack() { - let length = 0; - for (let k = 0; k < arguments.length; ++k) { - length += 4 * arguments[k].length; - } - const buffer = new ArrayBuffer(length); - const view = new DataView(buffer); - let offset = 0; - for (let i = 0; i < arguments.length; ++i) { - for (let j = 0; j < arguments[i].length; ++j) { - view.setUint32(offset + 4 * j, arguments[i][j]); - } - offset += 4 * arguments[i].length; - } - return new Uint8Array(buffer); - } - - var aesKW = /*#__PURE__*/Object.freeze({ - __proto__: null, - wrap: wrap, - unwrap: unwrap - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - /** - * @fileoverview Functions to add and remove PKCS5 padding - * @see PublicKeyEncryptedSessionKeyPacket - * @module crypto/pkcs5 - * @private - */ - - /** - * Add pkcs5 padding to a message - * @param {Uint8Array} message - message to pad - * @returns {Uint8Array} Padded message. - */ - function encode$1(message) { - const c = 8 - (message.length % 8); - const padded = new Uint8Array(message.length + c).fill(c); - padded.set(message); - return padded; - } - - /** - * Remove pkcs5 padding from a message - * @param {Uint8Array} message - message to remove padding from - * @returns {Uint8Array} Message without padding. - */ - function decode$1(message) { - const len = message.length; - if (len > 0) { - const c = message[len - 1]; - if (c >= 1) { - const provided = message.subarray(len - c); - const computed = new Uint8Array(c).fill(c); - if (util.equalsUint8Array(provided, computed)) { - return message.subarray(0, len - c); - } - } - } - throw new Error('Invalid padding'); - } - - var pkcs5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - encode: encode$1, - decode: decode$1 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - const webCrypto$8 = util.getWebCrypto(); - const nodeCrypto$9 = util.getNodeCrypto(); - - /** - * Validate ECDH parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDH public point - * @param {Uint8Array} d - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$5(oid, Q, d) { - return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); - } - - // Build Param for ECDH algorithm (RFC 6637) - function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { - return util.concatUint8Array([ - oid.write(), - new Uint8Array([public_algo]), - kdfParams.write(), - util.stringToUint8Array('Anonymous Sender '), - fingerprint.subarray(0, 20) - ]); - } - - // Key Derivation Function (RFC 6637) - async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { - // Note: X is little endian for Curve25519, big-endian for all others. - // This is not ideal, but the RFC's are unclear - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - let i; - if (stripLeading) { - // Work around old go crypto bug - for (i = 0; i < X.length && X[i] === 0; i++); - X = X.subarray(i); - } - if (stripTrailing) { - // Work around old OpenPGP.js bug - for (i = X.length - 1; i >= 0 && X[i] === 0; i--); - X = X.subarray(0, i + 1); - } - const digest = await hash.digest(hashAlgo, util.concatUint8Array([ - new Uint8Array([0, 0, 0, 1]), - X, - param - ])); - return digest.subarray(0, length); - } - - /** - * Generate ECDHE ephemeral key and secret from public key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function genPublicEphemeralKey(curve, Q) { - switch (curve.type) { - case 'curve25519': { - const d = getRandomBytes(32); - const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d); - let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey); - publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); - return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPublicEphemeralKey(curve, Q); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePublicEphemeralKey(curve, Q); - } - return ellipticPublicEphemeralKey(curve, Q); - } - - /** - * Encrypt and wrap a session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} data - Unpadded session key data - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} - * @async - */ - async function encrypt$3(oid, kdfParams, data, Q, fingerprint) { - const m = encode$1(data); - - const curve = new CurveWithOID(oid); - const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); - const wrappedKey = wrap(Z, m); - return { publicKey, wrappedKey }; - } - - /** - * Generate ECDHE secret from private key and public part of ephemeral key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function genPrivateEphemeralKey(curve, V, Q, d) { - if (d.length !== curve.payloadSize) { - const privateKey = new Uint8Array(curve.payloadSize); - privateKey.set(d, curve.payloadSize - d.length); - d = privateKey; - } - switch (curve.type) { - case 'curve25519': { - const secretKey = d.slice().reverse(); - const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1)); - return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPrivateEphemeralKey(curve, V, Q, d); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePrivateEphemeralKey(curve, V, d); - } - return ellipticPrivateEphemeralKey(curve, V, d); - } - - /** - * Decrypt and unwrap the value derived from session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} C - Encrypted and wrapped value derived from session key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Value derived from session key. - * @async - */ - async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) { - const curve = new CurveWithOID(oid); - const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - let err; - for (let i = 0; i < 3; i++) { - try { - // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); - return decode$1(unwrap(Z, C)); - } catch (e) { - err = e; - } - } - throw err; - } - - /** - * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d); - let privateKey = webCrypto$8.importKey( - 'jwk', - recipient, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); - let sender = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - [] - ); - [privateKey, sender] = await Promise.all([privateKey, sender]); - let S = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: sender - }, - privateKey, - curve.web.sharedSize - ); - let secret = webCrypto$8.exportKey( - 'jwk', - privateKey - ); - [S, secret] = await Promise.all([S, secret]); - const sharedKey = new Uint8Array(S); - const secretKey = b64ToUint8Array(secret.d); - return { secretKey, sharedKey }; - } - - /** - * Generate ECDHE ephemeral key and secret from public key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); - let keyPair = webCrypto$8.generateKey( - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - let recipient = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - false, - [] - ); - [keyPair, recipient] = await Promise.all([keyPair, recipient]); - let s = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: recipient - }, - keyPair.privateKey, - curve.web.sharedSize - ); - let p = webCrypto$8.exportKey( - 'jwk', - keyPair.publicKey - ); - [s, p] = await Promise.all([s, p]); - const sharedKey = new Uint8Array(s); - const publicKey = new Uint8Array(jwkToRawPublic(p)); - return { publicKey, sharedKey }; - } - - /** - * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function ellipticPrivateEphemeralKey(curve, V, d) { - const indutnyCurve = await getIndutnyCurve(curve.name); - V = keyFromPublic(indutnyCurve, V); - d = keyFromPrivate(indutnyCurve, d); - const secretKey = new Uint8Array(d.getPrivate()); - const S = d.derive(V.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { secretKey, sharedKey }; - } - - /** - * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function ellipticPublicEphemeralKey(curve, Q) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const v = await curve.genKeyPair(); - Q = keyFromPublic(indutnyCurve, Q); - const V = keyFromPrivate(indutnyCurve, v.privateKey); - const publicKey = v.publicKey; - const S = V.derive(Q.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { publicKey, sharedKey }; - } - - /** - * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function nodePrivateEphemeralKey(curve, V, d) { - const recipient = nodeCrypto$9.createECDH(curve.node.node); - recipient.setPrivateKey(d); - const sharedKey = new Uint8Array(recipient.computeSecret(V)); - const secretKey = new Uint8Array(recipient.getPrivateKey()); - return { secretKey, sharedKey }; - } - - /** - * Generate ECDHE ephemeral key and secret from public key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ - async function nodePublicEphemeralKey(curve, Q) { - const sender = nodeCrypto$9.createECDH(curve.node.node); - sender.generateKeys(); - const sharedKey = new Uint8Array(sender.computeSecret(Q)); - const publicKey = new Uint8Array(sender.getPublicKey()); - return { publicKey, sharedKey }; - } - - var ecdh = /*#__PURE__*/Object.freeze({ - __proto__: null, - validateParams: validateParams$5, - encrypt: encrypt$3, - decrypt: decrypt$3 - }); - - /** - * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. - * @module crypto/hkdf - * @private - */ - - const webCrypto$9 = util.getWebCrypto(); - const nodeCrypto$a = util.getNodeCrypto(); - const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle; - - async function HKDF(hashAlgo, inputKey, salt, info, outLen) { - const hash = enums.read(enums.webHash, hashAlgo); - if (!hash) throw new Error('Hash algo not supported with HKDF'); - - if (webCrypto$9 || nodeSubtleCrypto) { - const crypto = webCrypto$9 || nodeSubtleCrypto; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); - return new Uint8Array(bits); - } - - if (nodeCrypto$a) { - const hashAlgoName = enums.read(enums.hash, hashAlgo); - // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869 - - const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest(); - // Step 1: Extract - // PRK = HMAC-Hash(salt, IKM) - const pseudoRandomKey = computeHMAC(salt, inputKey); - - const hashLen = pseudoRandomKey.length; - - // Step 2: Expand - // HKDF-Expand(PRK, info, L) -> OKM - const n = Math.ceil(outLen / hashLen); - const outputKeyingMaterial = new Uint8Array(n * hashLen); - - // HMAC input buffer updated at each iteration - const roundInput = new Uint8Array(hashLen + info.length + 1); - // T_i and last byte are updated at each iteration, but `info` remains constant - roundInput.set(info, hashLen); - - for (let i = 0; i < n; i++) { - // T(0) = empty string (zero length) - // T(i) = HMAC-Hash(PRK, T(i-1) | info | i) - roundInput[roundInput.length - 1] = i + 1; - // t = T(i+1) - const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen)); - roundInput.set(t, 0); - - outputKeyingMaterial.set(t, i * hashLen); - } - - return outputKeyingMaterial.subarray(0, outLen); - } - - throw new Error('No HKDF implementation available'); - } - - /** - * @fileoverview Key encryption and decryption for RFC 6637 ECDH - * @module crypto/public_key/elliptic/ecdh - * @private - */ - - const HKDF_INFO = { - x25519: util.encodeUTF8('OpenPGP X25519') - }; - - /** - * Generate ECDH key for Montgomery curves - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} - */ - async function generate$3(algo) { - switch (algo) { - case enums.publicKey.x25519: { - // k stays in little-endian, unlike legacy ECDH over curve25519 - const k = getRandomBytes(32); - const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k); - return { A, k }; - } - default: - throw new Error('Unsupported ECDH algorithm'); - } - } - - /** - * Validate ECDH parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - ECDH public point - * @param {Uint8Array} k - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$6(algo, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k); - return util.equalsUint8Array(A, publicKey); - } - - default: - return false; - } - } - - /** - * Wrap and encrypt a session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} data - session key data to be encrypted - * @param {Uint8Array} recipientA - Recipient public key (K_B) - * @returns {Promise<{ - * ephemeralPublicKey: Uint8Array, - * wrappedKey: Uint8Array - * }>} ephemeral public key (K_A) and encrypted key - * @async - */ - async function encrypt$4(algo, data, recipientA) { - switch (algo) { - case enums.publicKey.x25519: { - const ephemeralSecretKey = getRandomBytes(32); - const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA); - const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - recipientA, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - const wrappedKey = wrap(encryptionKey, data); - return { ephemeralPublicKey, wrappedKey }; - } - - default: - throw new Error('Unsupported ECDH algorithm'); - } - } - - /** - * Decrypt and unwrap the session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} ephemeralPublicKey - (K_A) - * @param {Uint8Array} wrappedKey, - * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF - * @param {Uint8Array} k - Recipient secret key (b) - * @returns {Promise} decrypted session key data - * @async - */ - async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - A, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - return unwrap(encryptionKey, wrappedKey); - } - default: - throw new Error('Unsupported ECDH algorithm'); - } - } - - var ecdh_x = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$3, - validateParams: validateParams$6, - encrypt: encrypt$4, - decrypt: decrypt$4 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - var elliptic = /*#__PURE__*/Object.freeze({ - __proto__: null, - CurveWithOID: CurveWithOID, - ecdh: ecdh, - ecdhX: ecdh_x, - ecdsa: ecdsa, - eddsaLegacy: eddsa_legacy, - eddsa: eddsa, - generate: generate$1, - getPreferredHashAlgo: getPreferredHashAlgo - }); - - // GPG4Browsers - An OpenPGP implementation in javascript - - /* - TODO regarding the hash function, read: - https://tools.ietf.org/html/rfc4880#section-13.6 - https://tools.ietf.org/html/rfc4880#section-14 - */ - - /** - * DSA Sign function - * @param {Integer} hashAlgo - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} x - * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} - * @async - */ - async function sign$4(hashAlgo, hashed, g, p, q, x) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - x = new BigInteger(x); - - let k; - let r; - let s; - let t; - g = g.mod(p); - x = x.mod(q); - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - while (true) { - // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - k = await getRandomBigInteger(one, q); // returns in [1, q-1] - r = g.modExp(k, p).imod(q); // (g**k mod p) mod q - if (r.isZero()) { - continue; - } - const xr = x.mul(r).imod(q); - t = h.add(xr).imod(q); // H(m) + x*r mod q - s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q - if (s.isZero()) { - continue; - } - break; - } - return { - r: r.toUint8Array('be', q.byteLength()), - s: s.toUint8Array('be', q.byteLength()) - }; - } - - /** - * DSA Verify function - * @param {Integer} hashAlgo - * @param {Uint8Array} r - * @param {Uint8Array} s - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} y - * @returns {boolean} - * @async - */ - async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) { - const BigInteger = await util.getBigInteger(); - const zero = new BigInteger(0); - r = new BigInteger(r); - s = new BigInteger(s); - - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - - if (r.lte(zero) || r.gte(q) || - s.lte(zero) || s.gte(q)) { - util.printDebug('invalid DSA Signature'); - return false; - } - const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q); - const w = s.modInv(q); // s**-1 mod q - if (w.isZero()) { - util.printDebug('invalid DSA Signature'); - return false; - } - - g = g.mod(p); - y = y.mod(p); - const u1 = h.mul(w).imod(q); // H(m) * w mod q - const u2 = r.mul(w).imod(q); // r * w mod q - const t1 = g.modExp(u1, p); // g**u1 mod p - const t2 = y.modExp(u2, p); // y**u2 mod p - const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q - return v.equal(r); - } - - /** - * Validate DSA parameters - * @param {Uint8Array} p - DSA prime - * @param {Uint8Array} q - DSA group order - * @param {Uint8Array} g - DSA sub-group generator - * @param {Uint8Array} y - DSA public key - * @param {Uint8Array} x - DSA private key - * @returns {Promise} Whether params are valid. - * @async - */ - async function validateParams$7(p, q, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - /** - * Check that subgroup order q divides p-1 - */ - if (!p.dec().mod(q).isZero()) { - return false; - } - - /** - * g has order q - * Check that g ** q = 1 mod p - */ - if (!g.modExp(q, p).isOne()) { - return false; - } - - /** - * Check q is large and probably prime (we mainly want to avoid small factors) - */ - const qSize = new BigInteger(q.bitLength()); - const n150 = new BigInteger(150); - if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) { - return false; - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{rq + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q - const rqx = q.mul(r).add(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; - } - - var dsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$4, - verify: verify$4, - validateParams: validateParams$7 - }); - - /** - * @fileoverview Asymmetric cryptography functions - * @module crypto/public_key - * @private - */ - - var publicKey = { - /** @see module:crypto/public_key/rsa */ - rsa: rsa, - /** @see module:crypto/public_key/elgamal */ - elgamal: elgamal, - /** @see module:crypto/public_key/elliptic */ - elliptic: elliptic, - /** @see module:crypto/public_key/dsa */ - dsa: dsa, - /** @see tweetnacl */ - nacl: naclFastLight - }; - - /** - * @fileoverview Provides functions for asymmetric signing and signature verification - * @module crypto/signature - * @private - */ - - /** - * Parse signature in binary form to get the parameters. - * The returned values are only padded for EdDSA, since in the other cases their expected length - * depends on the key params, hence we delegate the padding to the signature verification function. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Uint8Array} signature - Data for which the signature was created - * @returns {Promise} True if signature is valid. - * @async - */ - function parseSignatureParams(algo, signature) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA signatures: - // - MPI of RSA signature value m**d mod n. - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const s = util.readMPI(signature.subarray(read)); - // The signature needs to be the same length as the public key modulo n. - // We pad s on signature verification, where we have access to n. - return { s }; - } - // Algorithm-Specific Fields for DSA or ECDSA signatures: - // - MPI of DSA or ECDSA value r. - // - MPI of DSA or ECDSA value s. - case enums.publicKey.dsa: - case enums.publicKey.ecdsa: - { - const r = util.readMPI(signature.subarray(read)); read += r.length + 2; - const s = util.readMPI(signature.subarray(read)); - return { r, s }; - } - // Algorithm-Specific Fields for legacy EdDSA signatures: - // - MPI of an EC point r. - // - EdDSA value s, in MPI, in the little endian representation - case enums.publicKey.eddsaLegacy: { - // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values: - // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 - let r = util.readMPI(signature.subarray(read)); read += r.length + 2; - r = util.leftPad(r, 32); - let s = util.readMPI(signature.subarray(read)); - s = util.leftPad(s, 32); - return { r, s }; - } - // Algorithm-Specific Fields for Ed25519 signatures: - // - 64 octets of the native signature - case enums.publicKey.ed25519: { - const RS = signature.subarray(read, read + 64); read += RS.length; - return { RS }; - } - default: - throw new UnsupportedError('Unknown signature algorithm.'); - } - } - - /** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} signature - Named algorithm-specific signature parameters - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Data for which the signature was created - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} True if signature is valid. - * @async - */ - async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto - return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); - } - case enums.publicKey.dsa: { - const { g, p, q, y } = publicParams; - const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers - return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicParams; - const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; - // padding needed for webcrypto - const r = util.leftPad(signature.r, curveSize); - const s = util.leftPad(signature.s, curveSize); - return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicParams; - // signature already padded on parsing - return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } - } - - /** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters - * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters - * @param {Uint8Array} data - Data to be signed - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} Signature Object containing named signature parameters. - * @async - */ - async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { - if (!publicKeyParams || !privateKeyParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); - return { s }; - } - case enums.publicKey.dsa: { - const { g, p, q } = publicKeyParams; - const { x } = privateKeyParams; - return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); - } - case enums.publicKey.elgamal: { - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicKeyParams; - const { d } = privateKeyParams; - return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } - } - - var signature = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseSignatureParams: parseSignatureParams, - verify: verify$5, - sign: sign$5 - }); - - // OpenPGP.js - An OpenPGP implementation in javascript - - class ECDHSymmetricKey { - constructor(data) { - if (data) { - this.data = data; - } - } - - /** - * Read an ECDHSymmetricKey from an Uint8Array: - * - 1 octect for the length `l` - * - `l` octects of encoded session key data - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - if (bytes.length >= 1) { - const length = bytes[0]; - if (bytes.length >= 1 + length) { - this.data = bytes.subarray(1, 1 + length); - return 1 + this.data.length; - } - } - throw new Error('Invalid symmetric key'); - } - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); - } - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - /** - * Implementation of type KDF parameters - * - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - * @module type/kdf_params - * @private - */ - - class KDFParams { - /** - * @param {enums.hash} hash - Hash algorithm - * @param {enums.symmetric} cipher - Symmetric algorithm - */ - constructor(data) { - if (data) { - const { hash, cipher } = data; - this.hash = hash; - this.cipher = cipher; - } else { - this.hash = null; - this.cipher = null; - } - } - - /** - * Read KDFParams from an Uint8Array - * @param {Uint8Array} input - Where to read the KDFParams from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { - throw new UnsupportedError('Cannot read KDFParams'); - } - this.hash = input[2]; - this.cipher = input[3]; - return 4; - } - - /** - * Write KDFParams to an Uint8Array - * @returns {Uint8Array} Array with the KDFParams value - */ - write() { - return new Uint8Array([3, 1, this.hash, this.cipher]); - } - } - - /** - * Encoded symmetric key for x25519 and x448 - * The payload format varies for v3 and v6 PKESK: - * the former includes an algorithm byte preceeding the encrypted session key. - * - * @module type/x25519x448_symkey - */ - - class ECDHXSymmetricKey { - static fromObject({ wrappedKey, algorithm }) { - const instance = new ECDHXSymmetricKey(); - instance.wrappedKey = wrappedKey; - instance.algorithm = algorithm; - return instance; - } - - /** - * - 1 octect for the length `l` - * - `l` octects of encoded session key data (with optional leading algorithm byte) - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - let read = 0; - let followLength = bytes[read++]; - this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even - followLength -= followLength % 2; - this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength; - } - - /** - * Write an MontgomerySymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([ - this.algorithm ? - new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : - new Uint8Array([this.wrappedKey.length]), - this.wrappedKey - ]); - } - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - /** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param {module:enums.publicKey} keyAlgo - Public key algorithm - * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Session key data to be encrypted - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Encrypted session key parameters. - * @async - */ - async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const { n, e } = publicParams; - const c = await publicKey.rsa.encrypt(data, n, e); - return { c }; - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - return publicKey.elgamal.encrypt(data, p, g, y); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicParams; - const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( - oid, kdfParams, data, Q, fingerprint); - return { V, C: new ECDHSymmetricKey(C) }; - } - case enums.publicKey.x25519: { - if (!util.isAES(symmetricAlgo)) { - // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 - throw new Error('X25519 keys can only encrypt AES session keys'); - } - const { A } = publicParams; - const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( - keyAlgo, data, A); - const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); - return { ephemeralPublicKey, C }; - } - default: - return []; - } - } - - /** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Object} publicKeyParams - Algorithm-specific public key parameters - * @param {Object} privateKeyParams - Algorithm-specific private key parameters - * @param {Object} sessionKeyParams - Encrypted session key parameters - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing - * (needed for constant-time processing in RSA and ElGamal) - * @returns {Promise} Decrypted data. - * @throws {Error} on sensitive decryption error, unless `randomPayload` is given - * @async - */ - async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: { - const { c } = sessionKeyParams; - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); - } - case enums.publicKey.elgamal: { - const { c1, c2 } = sessionKeyParams; - const p = publicKeyParams.p; - const x = privateKeyParams.x; - return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicKeyParams; - const { d } = privateKeyParams; - const { V, C } = sessionKeyParams; - return publicKey.elliptic.ecdh.decrypt( - oid, kdfParams, V, C.data, Q, d, fingerprint); - } - case enums.publicKey.x25519: { - const { A } = publicKeyParams; - const { k } = privateKeyParams; - const { ephemeralPublicKey, C } = sessionKeyParams; - if (!util.isAES(C.algorithm)) { - throw new Error('AES session key expected'); - } - return publicKey.elliptic.ecdhX.decrypt( - algo, ephemeralPublicKey, C.wrappedKey, A, k); - } - default: - throw new Error('Unknown public key encryption algorithm.'); - } - } - - /** - * Parse public key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. - */ - function parsePublicKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; - const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; - return { read, publicParams: { n, e } }; - } - case enums.publicKey.dsa: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, q, g, y } }; - } - case enums.publicKey.elgamal: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, g, y } }; - } - case enums.publicKey.ecdsa: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.eddsaLegacy: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - Q = util.leftPad(Q, 33); - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.ecdh: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); - return { read: read, publicParams: { oid, Q, kdfParams } }; - } - case enums.publicKey.ed25519: - case enums.publicKey.x25519: { - const A = bytes.subarray(read, read + 32); read += A.length; - return { read, publicParams: { A } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } - } - - /** - * Parse private key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @param {Object} publicParams - (ECC only) public params, needed to format some private params - * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. - */ - function parsePrivateKeyParams(algo, bytes, publicParams) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; - return { read, privateParams: { d, p, q, u } }; - } - case enums.publicKey.dsa: - case enums.publicKey.elgamal: { - const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; - return { read, privateParams: { x } }; - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const curve = new CurveWithOID(publicParams.oid); - let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - d = util.leftPad(d, curve.payloadSize); - return { read, privateParams: { d } }; - } - case enums.publicKey.eddsaLegacy: { - const curve = new CurveWithOID(publicParams.oid); - let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; - seed = util.leftPad(seed, curve.payloadSize); - return { read, privateParams: { seed } }; - } - case enums.publicKey.ed25519: { - const seed = bytes.subarray(read, read + 32); read += seed.length; - return { read, privateParams: { seed } }; - } - case enums.publicKey.x25519: { - const k = bytes.subarray(read, read + 32); read += k.length; - return { read, privateParams: { k } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } - } - - /** Returns the types comprising the encrypted session key of an algorithm - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {Object} The session key parameters referenced by name. - */ - function parseEncSessionKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA encrypted session keys: - // - MPI of RSA encrypted value m**e mod n. - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const c = util.readMPI(bytes.subarray(read)); - return { c }; - } - - // Algorithm-Specific Fields for Elgamal encrypted session keys: - // - MPI of Elgamal value g**k mod p - // - MPI of Elgamal value m * y**k mod p - case enums.publicKey.elgamal: { - const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; - const c2 = util.readMPI(bytes.subarray(read)); - return { c1, c2 }; - } - // Algorithm-Specific Fields for ECDH encrypted session keys: - // - MPI containing the ephemeral key used to establish the shared secret - // - ECDH Symmetric Key - case enums.publicKey.ecdh: { - const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; - const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); - return { V, C }; - } - // Algorithm-Specific Fields for X25519 encrypted session keys: - // - 32 octets representing an ephemeral X25519 public key. - // - A one-octet size of the following fields. - // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). - // - The encrypted session key. - case enums.publicKey.x25519: { - const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length; - const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); - return { ephemeralPublicKey, C }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } - } - - /** - * Convert params to MPI and serializes them in the proper order - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} params - The key parameters indexed by name - * @returns {Uint8Array} The array containing the MPIs. - */ - function serializeParams(algo, params) { - // Some algorithms do not rely on MPIs to store the binary params - const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]); - const orderedParams = Object.keys(params).map(name => { - const param = params[name]; - if (!util.isUint8Array(param)) return param.write(); - return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); - }); - return util.concatUint8Array(orderedParams); - } - - /** - * Generate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Integer} bits - Bit length for RSA keys - * @param {module:type/oid} oid - Object identifier for ECC keys - * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. - * @async - */ - function generateParams(algo, bits, oid) { - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ - privateParams: { d, p, q, u }, - publicParams: { n, e } - })); - } - case enums.publicKey.ecdsa: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { d: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { seed: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.ecdh: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ - privateParams: { d: secret }, - publicParams: { - oid: new OID(oid), - Q, - kdfParams: new KDFParams({ hash, cipher }) - } - })); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ - privateParams: { seed }, - publicParams: { A } - })); - case enums.publicKey.x25519: - return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ - privateParams: { k }, - publicParams: { A } - })); - case enums.publicKey.dsa: - case enums.publicKey.elgamal: - throw new Error('Unsupported algorithm for key generation.'); - default: - throw new Error('Unknown public key algorithm.'); - } - } - - /** - * Validate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Object} privateParams - Algorithm-specific private key parameters - * @returns {Promise} Whether the parameters are valid. - * @async - */ - async function validateParams$8(algo, publicParams, privateParams) { - if (!publicParams || !privateParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const { d, p, q, u } = privateParams; - return publicKey.rsa.validateParams(n, e, d, p, q, u); - } - case enums.publicKey.dsa: { - const { p, q, g, y } = publicParams; - const { x } = privateParams; - return publicKey.dsa.validateParams(p, q, g, y, x); - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - const { x } = privateParams; - return publicKey.elgamal.validateParams(p, g, y, x); - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; - const { oid, Q } = publicParams; - const { d } = privateParams; - return algoModule.validateParams(oid, Q, d); - } - case enums.publicKey.eddsaLegacy: { - const { Q, oid } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsa.validateParams(algo, A, seed); - } - case enums.publicKey.x25519: { - const { A } = publicParams; - const { k } = privateParams; - return publicKey.elliptic.ecdhX.validateParams(algo, A, k); - } - default: - throw new Error('Unknown public key algorithm.'); - } - } - - /** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - * @async - */ - async function getPrefixRandom(algo) { - const { blockSize } = getCipher(algo); - const prefixrandom = await getRandomBytes(blockSize); - const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - return util.concat([prefixrandom, repeat]); - } - - /** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Uint8Array} Random bytes as a string to be used as a key. - */ - function generateSessionKey(algo) { - const { keySize } = getCipher(algo); - return getRandomBytes(keySize); - } - - /** - * Get implementation of the given AEAD mode - * @param {enums.aead} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ - function getAEADMode(algo) { - const algoName = enums.read(enums.aead, algo); - return mode[algoName]; - } - - /** - * Check whether the given curve OID is supported - * @param {module:type/oid} oid - EC object identifier - * @throws {UnsupportedError} if curve is not supported - */ - function checkSupportedCurve(oid) { - try { - oid.getName(); - } catch (e) { - throw new UnsupportedError('Unknown curve OID'); - } - } - - /** - * Get preferred hash algo for a given elliptic algo - * @param {module:enums.publicKey} algo - alrogithm identifier - * @param {module:type/oid} [oid] - curve OID if needed by algo - */ - function getPreferredCurveHashAlgo(algo, oid) { - switch (algo) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.getPreferredHashAlgo(oid); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); - default: - throw new Error('Unknown elliptic signing algo'); - } - } - - var crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - publicKeyEncrypt: publicKeyEncrypt, - publicKeyDecrypt: publicKeyDecrypt, - parsePublicKeyParams: parsePublicKeyParams, - parsePrivateKeyParams: parsePrivateKeyParams, - parseEncSessionKeyParams: parseEncSessionKeyParams, - serializeParams: serializeParams, - generateParams: generateParams, - validateParams: validateParams$8, - getPrefixRandom: getPrefixRandom, - generateSessionKey: generateSessionKey, - getAEADMode: getAEADMode, - getCipher: getCipher, - getPreferredCurveHashAlgo: getPreferredCurveHashAlgo - }); - - /** - * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash - * @module crypto - * @private - */ - - // TODO move cfb and gcm to cipher - const mod = { - /** @see module:crypto/cipher */ - cipher: cipher, - /** @see module:crypto/hash */ - hash: hash, - /** @see module:crypto/mode */ - mode: mode, - /** @see module:crypto/public_key */ - publicKey: publicKey, - /** @see module:crypto/signature */ - signature: signature, - /** @see module:crypto/random */ - random: random, - /** @see module:crypto/pkcs1 */ - pkcs1: pkcs1, - /** @see module:crypto/pkcs5 */ - pkcs5: pkcs5, - /** @see module:crypto/aes_kw */ - aesKW: aesKW - }; - - Object.assign(mod, crypto$1); - - var TYPED_OK = typeof Uint8Array !== "undefined" && - typeof Uint16Array !== "undefined" && - typeof Int32Array !== "undefined"; - - - // reduce buffer size, avoiding mem copy - function shrinkBuf(buf, size) { - if (buf.length === size) { - return buf; - } - if (buf.subarray) { - return buf.subarray(0, size); - } - buf.length = size; - return buf; - } - - - const fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - let i, l, len, pos, chunk; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - const result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } - }; - - const fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } - }; - - - // Enable/Disable typed arrays use, for testing - // - - let Buf8 = TYPED_OK ? Uint8Array : Array; - let Buf16 = TYPED_OK ? Uint16Array : Array; - let Buf32 = TYPED_OK ? Int32Array : Array; - let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks; - let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet; - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - /* Allowed flush values; see deflate() and inflate() below for details */ - const Z_NO_FLUSH = 0; - const Z_PARTIAL_FLUSH = 1; - const Z_SYNC_FLUSH = 2; - const Z_FULL_FLUSH = 3; - const Z_FINISH = 4; - const Z_BLOCK = 5; - const Z_TREES = 6; - - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - const Z_OK = 0; - const Z_STREAM_END = 1; - const Z_NEED_DICT = 2; - const Z_STREAM_ERROR = -2; - const Z_DATA_ERROR = -3; - //export const Z_MEM_ERROR = -4; - const Z_BUF_ERROR = -5; - const Z_DEFAULT_COMPRESSION = -1; - - - const Z_FILTERED = 1; - const Z_HUFFMAN_ONLY = 2; - const Z_RLE = 3; - const Z_FIXED = 4; - const Z_DEFAULT_STRATEGY = 0; - - /* Possible values of the data_type field (though see inflate()) */ - const Z_BINARY = 0; - const Z_TEXT = 1; - //export const Z_ASCII = 1; // = Z_TEXT (deprecated) - const Z_UNKNOWN = 2; - - /* The deflate compression method */ - const Z_DEFLATED = 8; - //export const Z_NULL = null // Use -1 or null inline, depending on var type - - /*============================================================================*/ - - - function zero$1(buf) { - let len = buf.length; while (--len >= 0) { - buf[len] = 0; - } - } - - // From zutil.h - - const STORED_BLOCK = 0; - const STATIC_TREES = 1; - const DYN_TREES = 2; - /* The three kinds of block type */ - - const MIN_MATCH = 3; - const MAX_MATCH = 258; - /* The minimum and maximum match lengths */ - - // From deflate.h - /* =========================================================================== - * Internal compression state. - */ - - const LENGTH_CODES = 29; - /* number of length codes, not counting the special END_BLOCK code */ - - const LITERALS = 256; - /* number of literal bytes 0..255 */ - - const L_CODES = LITERALS + 1 + LENGTH_CODES; - /* number of Literal or Length codes, including the END_BLOCK code */ - - const D_CODES = 30; - /* number of distance codes */ - - const BL_CODES = 19; - /* number of codes used to transfer the bit lengths */ - - const HEAP_SIZE = 2 * L_CODES + 1; - /* maximum heap size */ - - const MAX_BITS = 15; - /* All codes must not exceed MAX_BITS bits */ - - const Buf_size = 16; - /* size of bit buffer in bi_buf */ - - - /* =========================================================================== - * Constants - */ - - const MAX_BL_BITS = 7; - /* Bit length codes must not exceed MAX_BL_BITS bits */ - - const END_BLOCK = 256; - /* end of block literal code */ - - const REP_3_6 = 16; - /* repeat previous bit length 3-6 times (2 bits of repeat count) */ - - const REPZ_3_10 = 17; - /* repeat a zero length 3-10 times (3 bits of repeat count) */ - - const REPZ_11_138 = 18; - /* repeat a zero length 11-138 times (7 bits of repeat count) */ - - /* eslint-disable comma-spacing,array-bracket-spacing */ - const extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - - const extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - - const extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - - const bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; - /* eslint-enable comma-spacing,array-bracket-spacing */ - - /* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - - /* =========================================================================== - * Local data. These are initialized only once. - */ - - // We pre-fill arrays with 0 to avoid uninitialized gaps - - const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - - // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 - const static_ltree = new Array((L_CODES + 2) * 2); - zero$1(static_ltree); - /* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - - const static_dtree = new Array(D_CODES * 2); - zero$1(static_dtree); - /* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - - const _dist_code = new Array(DIST_CODE_LEN); - zero$1(_dist_code); - /* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - - const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); - zero$1(_length_code); - /* length code for each normalized match length (0 == MIN_MATCH) */ - - const base_length = new Array(LENGTH_CODES); - zero$1(base_length); - /* First normalized length for each code (0 = MIN_MATCH) */ - - const base_dist = new Array(D_CODES); - zero$1(base_dist); - /* First normalized distance for each code (0 = distance of 1) */ - - - function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; - } - - - let static_l_desc; - let static_d_desc; - let static_bl_desc; - - - function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ - } - - - - function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; - } - - - /* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ - function put_short(s, w) { - // put_byte(s, (uch)((w) & 0xff)); - // put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = w & 0xff; - s.pending_buf[s.pending++] = w >>> 8 & 0xff; - } - - - /* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ - function send_bits(s, value, length) { - if (s.bi_valid > Buf_size - length) { - s.bi_buf |= value << s.bi_valid & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> Buf_size - s.bi_valid; - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= value << s.bi_valid & 0xffff; - s.bi_valid += length; - } - } - - - function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); - } - - - /* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ - function bi_reverse(code, len) { - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; - } - - - /* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ - function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } - } - - - /* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ - function gen_bitlen(s, desc) - // deflate_state *s; - // tree_desc *desc; /* the tree descriptor */ - { - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { - continue; - } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { - return; - } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { - bits--; - } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { - continue; - } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } - } - - - /* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ - function gen_codes(tree, max_code, bl_count) - // ct_data *tree; /* the tree to decorate */ - // int max_code; /* largest code with non zero frequency */ - // ushf *bl_count; /* number of codes at each bit length */ - { - const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = code + bl_count[bits - 1] << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < 1 << extra_lbits[code]; n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < 1 << extra_dbits[code]; n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; - } - - - /* =========================================================================== - * Initialize a new block. - */ - function init_block(s) { - let n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { - s.dyn_ltree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < D_CODES; n++) { - s.dyn_dtree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < BL_CODES; n++) { - s.bl_tree[n * 2]/*.Freq*/ = 0; - } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; - } - - - /* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ - function bi_windup(s) { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; - } - - /* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ - function copy_block(s, buf, len, header) - //DeflateState *s; - //charf *buf; /* the input data */ - //unsigned len; /* its length */ - //int header; /* true if block header must be written */ - { - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } - // while (len--) { - // put_byte(s, *buf++); - // } - arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; - } - - /* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ - function smaller(tree, n, m, depth) { - const _n2 = n * 2; - const _m2 = m * 2; - return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]; - } - - /* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ - function pqdownheap(s, tree, k) - // deflate_state *s; - // ct_data *tree; /* the tree to restore */ - // int k; /* node to move down */ - { - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { - break; - } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; - } - - - // inlined manually - // var SMALLEST = 1; - - /* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ - function compress_block(s, ltree, dtree) - // deflate_state *s; - // const ct_data *ltree; /* literal tree */ - // const ct_data *dtree; /* distance tree */ - { - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); - } - - - /* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ - function build_tree(s, desc) - // deflate_state *s; - // tree_desc *desc; /* the tree descriptor */ - { - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) { - pqdownheap(s, tree, n); - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); - } - - - /* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ - function scan_tree(s, tree, max_code) - // deflate_state *s; - // ct_data *tree; /* the tree to be scanned */ - // int max_code; /* and its largest code of non zero frequency */ - { - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { - s.bl_tree[curlen * 2]/*.Freq*/++; - } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } - } - - - /* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ - function send_tree(s, tree, max_code) - // deflate_state *s; - // ct_data *tree; /* the tree to be scanned */ - // int max_code; /* and its largest code of non zero frequency */ - { - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { - send_code(s, curlen, s.bl_tree); - } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } - } - - - /* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ - function build_bl_tree(s) { - let max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; - } - - - /* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ - function send_all_trees(s, lcodes, dcodes, blcodes) - // deflate_state *s; - // int lcodes, dcodes, blcodes; /* number of codes for each tree */ - { - let rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); - } - - - /* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ - function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - let black_mask = 0xf3ffc07f; - let n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; - } - - - let static_init_done = false; - - /* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ - function _tr_init(s) { - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); - } - - - /* =========================================================================== - * Send a stored block - */ - function _tr_stored_block(s, buf, stored_len, last) - //DeflateState *s; - //charf *buf; /* input block */ - //ulg stored_len; /* length of input block */ - //int last; /* one if this is the last block for a file */ - { - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ - } - - - /* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ - function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); - } - - - /* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ - function _tr_flush_block(s, buf, stored_len, last) - //DeflateState *s; - //charf *buf; /* input block, or NULL if too old */ - //ulg stored_len; /* length of input block */ - //int last; /* one if this is the last block for a file */ - { - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = s.opt_len + 3 + 7 >>> 3; - static_lenb = s.static_len + 3 + 7 >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { - opt_lenb = static_lenb; - } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if (stored_len + 4 <= opt_lenb && buf !== -1) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); - } - - /* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ - function _tr_tally(s, dist, lc) - // deflate_state *s; - // unsigned dist; /* distance of matched string */ - // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ - { - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif - - return s.last_lit === s.lit_bufsize - 1; - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ - } - - // Note: adler32 takes 12% for level 0 and 2% for level 6. - // It isn't worth it to make additional optimizations as in original. - // Small size is preferable. - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - function adler32(adler, buf, len, pos) { - let s1 = adler & 0xffff |0, - s2 = adler >>> 16 & 0xffff |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = s1 + buf[pos++] |0; - s2 = s2 + s1 |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return s1 | s2 << 16 |0; - } - - // Note: we can't get significant speed boost here. - // So write code to minimize size - no pregenerated tables - // and array tools dependencies. - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - // Use ordinary array, since untyped makes no boost here - function makeTable() { - let c; - const table = []; - - for (let n = 0; n < 256; n++) { - c = n; - for (let k = 0; k < 8; k++) { - c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; - } - table[n] = c; - } - - return table; - } - - // Create table on load. Just 255 signed longs. Not a problem. - const crcTable = makeTable(); - - - function crc32(crc, buf, len, pos) { - const t = crcTable, - end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return crc ^ -1; // >>> 0; - } - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - var msg = { - 2: "need dictionary", /* Z_NEED_DICT 2 */ - 1: "stream end", /* Z_STREAM_END 1 */ - 0: "", /* Z_OK 0 */ - "-1": "file error", /* Z_ERRNO (-1) */ - "-2": "stream error", /* Z_STREAM_ERROR (-2) */ - "-3": "data error", /* Z_DATA_ERROR (-3) */ - "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */ - "-5": "buffer error", /* Z_BUF_ERROR (-5) */ - "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */ - }; - - /*============================================================================*/ - - - const MAX_MEM_LEVEL = 9; - - - const LENGTH_CODES$1 = 29; - /* number of length codes, not counting the special END_BLOCK code */ - const LITERALS$1 = 256; - /* number of literal bytes 0..255 */ - const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; - /* number of Literal or Length codes, including the END_BLOCK code */ - const D_CODES$1 = 30; - /* number of distance codes */ - const BL_CODES$1 = 19; - /* number of codes used to transfer the bit lengths */ - const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; - /* maximum heap size */ - const MAX_BITS$1 = 15; - /* All codes must not exceed MAX_BITS bits */ - - const MIN_MATCH$1 = 3; - const MAX_MATCH$1 = 258; - const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); - - const PRESET_DICT = 0x20; - - const INIT_STATE = 42; - const EXTRA_STATE = 69; - const NAME_STATE = 73; - const COMMENT_STATE = 91; - const HCRC_STATE = 103; - const BUSY_STATE = 113; - const FINISH_STATE = 666; - - const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ - const BS_BLOCK_DONE = 2; /* block flush performed */ - const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ - const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - - const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - - function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; - } - - function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); - } - - function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - - /* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ - function flush_pending(strm) { - const s = strm.state; - - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } - } - - - function flush_block_only(s, last) { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); - } - - - function put_byte(s, b) { - s.pending_buf[s.pending++] = b; - } - - - /* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ - function putShortMSB(s, b) { - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; - } - - - /* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ - function read_buf(strm, buf, start, size) { - let len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; - } - - - /* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ - function longest_match(s, cur_match) { - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - const _win = s.window; // shortcut - - const wmask = s.w_mask; - const prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - const strend = s.strstart + MAX_MATCH$1; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH$1 - (strend - scan); - scan = strend - MAX_MATCH$1; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; - } - - - /* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ - function fill_window(s) { - const _w_size = s.w_size; - let p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH$1) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH$1) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // var curr = s.strstart + s.lookahead; - // var init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); - } - - /* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ - function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (; ;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; - } - - /* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ - function deflate_fast(s, flush) { - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH$1) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; - } - - /* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ - function deflate_slow(s, flush) { - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - - let max_insert; - - /* Process the input block. */ - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH$1 - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH$1 - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH$1; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH$1 - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; - } - - - /* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ - function deflate_rle(s, flush) { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - - const _win = s.window; - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH$1) { - fill_window(s); - if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH$1; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH$1 - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH$1) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; - } - - /* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ - function deflate_huff(s, flush) { - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; - } - - /* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ - class Config { - constructor(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } - } - const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ - ]; - - - /* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ - function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - s.ins_h = 0; - } - - class DeflateState { - constructor() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); - this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); - this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); - zero$2(this.dyn_ltree); - zero$2(this.dyn_dtree); - zero$2(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Buf16(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ - zero$2(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; - zero$2(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ - } - } - - function deflateResetKeep(strm) { - let s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - _tr_init(s); - return Z_OK; - } - - - function deflateReset(strm) { - const ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; - } - - - function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; - } - - - function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - let wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); - s.window = new Buf8(s.w_size * 2); - s.head = new Buf16(s.hash_size); - s.prev = new Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); - } - - - function deflate(strm, flush) { - let old_flush, s; - let beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } - //#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero$2(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; - } - - function deflateEnd(strm) { - let status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; - } - - - /* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ - function deflateSetDictionary(strm, dictionary) { - let dictLength = dictionary.length; - - let s; - let str, n; - let wrap; - let avail; - let next; - let input; - let tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new Buf8(s.w_size); - arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH$1) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH$1 - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH$1 - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; - } - - /* Not implemented - exports.deflateBound = deflateBound; - exports.deflateCopy = deflateCopy; - exports.deflateParams = deflateParams; - exports.deflatePending = deflatePending; - exports.deflatePrime = deflatePrime; - exports.deflateTune = deflateTune; - */ - - // String encode/decode helpers - - try { - String.fromCharCode.apply(null, [ 0 ]); - } catch (__) { - } - try { - String.fromCharCode.apply(null, new Uint8Array(1)); - } catch (__) { - } - - - // Table with utf8 lengths (calculated by first byte of sequence) - // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, - // because max possible codepoint is 0x10ffff - const _utf8len = new Buf8(256); - for (let q = 0; q < 256; q++) { - _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; - } - _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - - // convert string to array (typed, when possible) - function string2buf (str) { - let c, c2, m_pos, i, buf_len = 0; - const str_len = str.length; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - const buf = new Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | c >>> 6; - buf[i++] = 0x80 | c & 0x3f; - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | c >>> 12; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } else { - /* four bytes */ - buf[i++] = 0xf0 | c >>> 18; - buf[i++] = 0x80 | c >>> 12 & 0x3f; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } - } - - return buf; - } - - - // Convert binary string (typed, when possible) - function binstring2buf (str) { - const buf = new Buf8(str.length); - for (let i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; - } - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - class ZStream { - constructor() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } - } - - /* ===========================================================================*/ - - - /** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - - /* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - - /** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - - /** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - - /** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - - /** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ - - class Deflate { - constructor(options) { - this.options = { - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - ...(options || {}) - }; - - const opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - let dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } - } - - /** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize } } = this; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = string2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; - } - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - // See state defs from inflate.js - const BAD = 30; /* got a data error -- remain here until reset */ - const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - - /* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ - function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let _out; /* local strm.output */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; - - - - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - const input = strm.input; - const last = _in + (strm.avail_in - 5); - _out = strm.next_out; - const output = strm.output; - const beg = _out - (start - strm.avail_out); - const end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - const dmax = state.dmax; - //#endif - const wsize = state.wsize; - const whave = state.whave; - const wnext = state.wnext; - const s_window = state.window; - hold = state.hold; - bits = state.bits; - const lcode = state.lencode; - const dcode = state.distcode; - const lmask = (1 << state.lenbits) - 1; - const dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & (1 << op) - 1; - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & (1 << op) - 1; - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dodist; - } else { - strm.msg = "invalid distance code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dolen; - } else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } else { - strm.msg = "invalid literal/length code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); - strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); - state.hold = hold; - state.bits = bits; - return; - } - - const MAXBITS = 15; - const ENOUGH_LENS = 852; - const ENOUGH_DISTS = 592; - //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - - const CODES = 0; - const LENS = 1; - const DISTS = 2; - - const lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 - ]; - - const lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 - ]; - - const dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 - ]; - - const dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 - ]; - - function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // var shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { - break; - } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { - break; - } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - const mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << len - drop; - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << len - 1; - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { - break; - } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { - break; - } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = root << 24 | curr << 16 | next - table_index |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = len - drop << 24 | 64 << 16 |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; - } - - const CODES$1 = 0; - const LENS$1 = 1; - const DISTS$1 = 2; - - /* STATES ====================================================================*/ - /* ===========================================================================*/ - - - const HEAD = 1; /* i: waiting for magic header */ - const FLAGS = 2; /* i: waiting for method and flags (gzip) */ - const TIME = 3; /* i: waiting for modification time (gzip) */ - const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ - const EXLEN = 5; /* i: waiting for extra length (gzip) */ - const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ - const NAME = 7; /* i: waiting for end of file name (gzip) */ - const COMMENT = 8; /* i: waiting for end of comment (gzip) */ - const HCRC = 9; /* i: waiting for header crc (gzip) */ - const DICTID = 10; /* i: waiting for dictionary check value */ - const DICT = 11; /* waiting for inflateSetDictionary() call */ - const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ - const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ - const STORED = 14; /* i: waiting for stored size (length and complement) */ - const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ - const COPY = 16; /* i/o: waiting for input or output to copy stored block */ - const TABLE = 17; /* i: waiting for dynamic block table lengths */ - const LENLENS = 18; /* i: waiting for code length code lengths */ - const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ - const LEN_ = 20; /* i: same as LEN below, but only first time in */ - const LEN = 21; /* i: waiting for length/lit/eob code */ - const LENEXT = 22; /* i: waiting for length extra bits */ - const DIST = 23; /* i: waiting for distance code */ - const DISTEXT = 24; /* i: waiting for distance extra bits */ - const MATCH = 25; /* o: waiting for output space to copy string */ - const LIT = 26; /* o: waiting for output space to write literal */ - const CHECK = 27; /* i: waiting for 32-bit check value */ - const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ - const DONE = 29; /* finished check, done -- remain here until reset */ - const BAD$1 = 30; /* got a data error -- remain here until reset */ - //const MEM = 31; /* got an inflate() memory error -- remain here until reset */ - const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - - /* ===========================================================================*/ - - - - const ENOUGH_LENS$1 = 852; - const ENOUGH_DISTS$1 = 592; - - - function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); - } - - - class InflateState { - constructor() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Buf16(320); /* temporary storage for code lengths */ - this.work = new Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ - } - } - - function inflateResetKeep(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); - state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; - } - - function inflateReset(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - - } - - function inflateReset2(strm, windowBits) { - let wrap; - let state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); - } - - function inflateInit2(strm, windowBits) { - let ret; - let state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; - } - - - /* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ - let virgin = true; - - let lenfix, distfix; // We have no pointers in JS, so keep tables separate - - function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - let sym; - - lenfix = new Buf32(512); - distfix = new Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; - } - - - /* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ - function updatewindow(strm, src, end, copy) { - let dist; - const state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; - } - - function inflate(strm, flush) { - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ - let opts; - - let n; // temporary var for NEED_BITS - - const order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD$1; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD$1; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE$1; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD$1; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE$1; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE$1; - /* falls through */ - case TYPE$1: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD$1; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD$1; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE$1; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - //#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD$1; - break; - } - //#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD$1) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD$1; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD$1; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE$1) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE$1; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } - //#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // Trace((stderr, "inflate.c too far\n")); - // copy -= state.whave; - // if (copy > state.length) { copy = state.length; } - // if (copy > left) { copy = left; } - // left -= copy; - // state.length -= copy; - // do { - // output[put++] = 0; - // } while (--copy); - // if (state.length === 0) { state.mode = LEN; } - // break; - //#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD$1: - ret = Z_DATA_ERROR; - break inf_leave; - // case MEM: - // return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE$1 ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; - } - - function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - const state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; - } - - function inflateGetHeader(strm, head) { - let state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; - } - - function inflateSetDictionary(strm, dictionary) { - const dictLength = dictionary.length; - - let state; - let dictid; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - updatewindow(strm, dictionary, dictLength, dictLength); - // if (ret) { - // state.mode = MEM; - // return Z_MEM_ERROR; - // } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; - } - - /* Not implemented - exports.inflateCopy = inflateCopy; - exports.inflateGetDictionary = inflateGetDictionary; - exports.inflateMark = inflateMark; - exports.inflatePrime = inflatePrime; - exports.inflateSync = inflateSync; - exports.inflateSyncPoint = inflateSyncPoint; - exports.inflateUndermine = inflateUndermine; - */ - - // (C) 1995-2013 Jean-loup Gailly and Mark Adler - // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin - // - // This software is provided 'as-is', without any express or implied - // warranty. In no event will the authors be held liable for any damages - // arising from the use of this software. - // - // Permission is granted to anyone to use this software for any purpose, - // including commercial applications, and to alter it and redistribute it - // freely, subject to the following restrictions: - // - // 1. The origin of this software must not be misrepresented; you must not - // claim that you wrote the original software. If you use this software - // in a product, an acknowledgment in the product documentation would be - // appreciated but is not required. - // 2. Altered source versions must be plainly marked as such, and must not be - // misrepresented as being the original software. - // 3. This notice may not be removed or altered from any source distribution. - - class GZheader { - constructor() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; - } - } - - /** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - - /* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - - /** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - - /** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - - /** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - - /** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ - class Inflate { - constructor(options) { - this.options = { - chunkSize: 16384, - windowBits: 0, - ...(options || {}) - }; - - const opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - let status = inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - inflateGetHeader(this.strm, this.header); - - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - opt.dictionary = new Uint8Array(opt.dictionary); - } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(msg[status]); - } - } - } - } - /** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize, dictionary } } = this; - let status, _mode; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - let allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = binstring2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = inflate(strm, Z_NO_FLUSH); /* no bad return value */ - - if (status === Z_NEED_DICT && dictionary) { - status = inflateSetDictionary(this.strm, dictionary); - } - - if (status === Z_BUF_ERROR && allowBufError === true) { - status = Z_OK; - allowBufError = false; - } - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - if (status === Z_STREAM_END) { - _mode = Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - - /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - - - /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; - } - - /* - node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - - Copyright (C) 2012 Eli Skeggs - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, see - http://www.gnu.org/licenses/lgpl-2.1.html - - Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). - - Based on micro-bunzip by Rob Landley (rob@landley.net). - - Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), - which also acknowledges contributions by Mike Burrows, David Wheeler, - Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, - Robert Sedgewick, and Jon L. Bentley. - */ - - var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; - - // offset in bytes - var BitReader = function(stream) { - this.stream = stream; - this.bitOffset = 0; - this.curByte = 0; - this.hasByte = false; - }; - - BitReader.prototype._ensureByte = function() { - if (!this.hasByte) { - this.curByte = this.stream.readByte(); - this.hasByte = true; - } - }; - - // reads bits from the buffer - BitReader.prototype.read = function(bits) { - var result = 0; - while (bits > 0) { - this._ensureByte(); - var remaining = 8 - this.bitOffset; - // if we're in a byte - if (bits >= remaining) { - result <<= remaining; - result |= BITMASK[remaining] & this.curByte; - this.hasByte = false; - this.bitOffset = 0; - bits -= remaining; - } else { - result <<= bits; - var shift = remaining - bits; - result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; - this.bitOffset += bits; - bits = 0; - } - } - return result; - }; - - // seek to an arbitrary point in the buffer (expressed in bits) - BitReader.prototype.seek = function(pos) { - var n_bit = pos % 8; - var n_byte = (pos - n_bit) / 8; - this.bitOffset = n_bit; - this.stream.seek(n_byte); - this.hasByte = false; - }; - - // reads 6 bytes worth of data using the read method - BitReader.prototype.pi = function() { - var buf = new Uint8Array(6), i; - for (i = 0; i < buf.length; i++) { - buf[i] = this.read(8); - } - return bufToHex(buf); - }; - - function bufToHex(buf) { - return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); - } - - var bitreader = BitReader; - - /* very simple input/output stream interface */ - var Stream = function() { - }; - - // input streams ////////////// - /** Returns the next byte, or -1 for EOF. */ - Stream.prototype.readByte = function() { - throw new Error("abstract method readByte() not implemented"); - }; - /** Attempts to fill the buffer; returns number of bytes read, or - * -1 for EOF. */ - Stream.prototype.read = function(buffer, bufOffset, length) { - var bytesRead = 0; - while (bytesRead < length) { - var c = this.readByte(); - if (c < 0) { // EOF - return (bytesRead===0) ? -1 : bytesRead; - } - buffer[bufOffset++] = c; - bytesRead++; - } - return bytesRead; - }; - Stream.prototype.seek = function(new_pos) { - throw new Error("abstract method seek() not implemented"); - }; - - // output streams /////////// - Stream.prototype.writeByte = function(_byte) { - throw new Error("abstract method readByte() not implemented"); - }; - Stream.prototype.write = function(buffer, bufOffset, length) { - var i; - for (i=0; i>> 0; // return an unsigned value - }; - - /** - * Update the CRC with a single byte - * @param value The value to update the CRC with - */ - this.updateCRC = function(value) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - }; - - /** - * Update the CRC with a sequence of identical bytes - * @param value The value to update the CRC with - * @param count The number of bytes - */ - this.updateCRCRun = function(value, count) { - while (count-- > 0) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - } - }; - }; - return CRC32; - })(); - - /* - seek-bzip - a pure-javascript module for seeking within bzip2 data - - Copyright (C) 2013 C. Scott Ananian - Copyright (C) 2012 Eli Skeggs - Copyright (C) 2011 Kevin Kwok - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, see - http://www.gnu.org/licenses/lgpl-2.1.html - - Adapted from node-bzip, copyright 2012 Eli Skeggs. - Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - - Based on micro-bunzip by Rob Landley (rob@landley.net). - - Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), - which also acknowledges contributions by Mike Burrows, David Wheeler, - Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, - Robert Sedgewick, and Jon L. Bentley. - */ - - - - - - var MAX_HUFCODE_BITS = 20; - var MAX_SYMBOLS = 258; - var SYMBOL_RUNA = 0; - var SYMBOL_RUNB = 1; - var MIN_GROUPS = 2; - var MAX_GROUPS = 6; - var GROUP_SIZE = 50; - - var WHOLEPI = "314159265359"; - var SQRTPI = "177245385090"; - - var mtf = function(array, index) { - var src = array[index], i; - for (i = index; i > 0; i--) { - array[i] = array[i-1]; - } - array[0] = src; - return src; - }; - - var Err = { - OK: 0, - LAST_BLOCK: -1, - NOT_BZIP_DATA: -2, - UNEXPECTED_INPUT_EOF: -3, - UNEXPECTED_OUTPUT_EOF: -4, - DATA_ERROR: -5, - OUT_OF_MEMORY: -6, - OBSOLETE_INPUT: -7, - END_OF_BLOCK: -8 - }; - var ErrorMessages = {}; - ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; - ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; - ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; - ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; - ErrorMessages[Err.DATA_ERROR] = "Data error"; - ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; - ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - - var _throw = function(status, optDetail) { - var msg = ErrorMessages[status] || 'unknown error'; - if (optDetail) { msg += ': '+optDetail; } - var e = new TypeError(msg); - e.errorCode = status; - throw e; - }; - - var Bunzip = function(inputStream, outputStream) { - this.writePos = this.writeCurrent = this.writeCount = 0; - - this._start_bunzip(inputStream, outputStream); - }; - Bunzip.prototype._init_block = function() { - var moreBlocks = this._get_next_block(); - if ( !moreBlocks ) { - this.writeCount = -1; - return false; /* no more blocks */ - } - this.blockCRC = new crc32$1(); - return true; - }; - /* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ - Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { - /* Ensure that file starts with "BZh['1'-'9']." */ - var buf = new Uint8Array(4); - if (inputStream.read(buf, 0, 4) !== 4 || - String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') - _throw(Err.NOT_BZIP_DATA, 'bad magic'); - - var level = buf[3] - 0x30; - if (level < 1 || level > 9) - _throw(Err.NOT_BZIP_DATA, 'level out of range'); - - this.reader = new bitreader(inputStream); - - /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of - uncompressed data. Allocate intermediate buffer for block. */ - this.dbufSize = 100000 * level; - this.nextoutput = 0; - this.outputStream = outputStream; - this.streamCRC = 0; - }; - Bunzip.prototype._get_next_block = function() { - var i, j, k; - var reader = this.reader; - // this is get_next_block() function from micro-bunzip: - /* Read in header signature and CRC, then validate signature. - (last block signature means CRC is for whole file, return now) */ - var h = reader.pi(); - if (h === SQRTPI) { // last block - return false; /* no more blocks */ - } - if (h !== WHOLEPI) - _throw(Err.NOT_BZIP_DATA); - this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) - this.streamCRC = (this.targetBlockCRC ^ - ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; - /* We can add support for blockRandomised if anybody complains. There was - some code for this in busybox 1.0.0-pre3, but nobody ever noticed that - it didn't actually work. */ - if (reader.read(1)) - _throw(Err.OBSOLETE_INPUT); - var origPointer = reader.read(24); - if (origPointer > this.dbufSize) - _throw(Err.DATA_ERROR, 'initial position out of bounds'); - /* mapping table: if some byte values are never used (encoding things - like ascii text), the compression code removes the gaps to have fewer - symbols to deal with, and writes a sparse bitfield indicating which - values were present. We make a translation table to convert the symbols - back to the corresponding bytes. */ - var t = reader.read(16); - var symToByte = new Uint8Array(256), symTotal = 0; - for (i = 0; i < 16; i++) { - if (t & (1 << (0xF - i))) { - var o = i * 16; - k = reader.read(16); - for (j = 0; j < 16; j++) - if (k & (1 << (0xF - j))) - symToByte[symTotal++] = o + j; - } - } - - /* How many different huffman coding groups does this block use? */ - var groupCount = reader.read(3); - if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) - _throw(Err.DATA_ERROR); - /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding - group. Read in the group selector list, which is stored as MTF encoded - bit runs. (MTF=Move To Front, as each value is used it's moved to the - start of the list.) */ - var nSelectors = reader.read(15); - if (nSelectors === 0) - _throw(Err.DATA_ERROR); - - var mtfSymbol = new Uint8Array(256); - for (i = 0; i < groupCount; i++) - mtfSymbol[i] = i; - - var selectors = new Uint8Array(nSelectors); // was 32768... - - for (i = 0; i < nSelectors; i++) { - /* Get next value */ - for (j = 0; reader.read(1); j++) - if (j >= groupCount) _throw(Err.DATA_ERROR); - /* Decode MTF to get the next selector */ - selectors[i] = mtf(mtfSymbol, j); - } - - /* Read the huffman coding tables for each group, which code for symTotal - literal symbols, plus two run symbols (RUNA, RUNB) */ - var symCount = symTotal + 2; - var groups = [], hufGroup; - for (j = 0; j < groupCount; j++) { - var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); - /* Read huffman code lengths for each symbol. They're stored in - a way similar to mtf; record a starting value for the first symbol, - and an offset from the previous value for everys symbol after that. */ - t = reader.read(5); // lengths - for (i = 0; i < symCount; i++) { - for (;;) { - if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); - /* If first bit is 0, stop. Else second bit indicates whether - to increment or decrement the value. */ - if(!reader.read(1)) - break; - if(!reader.read(1)) - t++; - else - t--; - } - length[i] = t; - } - - /* Find largest and smallest lengths in this group */ - var minLen, maxLen; - minLen = maxLen = length[0]; - for (i = 1; i < symCount; i++) { - if (length[i] > maxLen) - maxLen = length[i]; - else if (length[i] < minLen) - minLen = length[i]; - } - - /* Calculate permute[], base[], and limit[] tables from length[]. - * - * permute[] is the lookup table for converting huffman coded symbols - * into decoded symbols. base[] is the amount to subtract from the - * value of a huffman symbol of a given length when using permute[]. - * - * limit[] indicates the largest numerical value a symbol with a given - * number of bits can have. This is how the huffman codes can vary in - * length: each code with a value>limit[length] needs another bit. - */ - hufGroup = {}; - groups.push(hufGroup); - hufGroup.permute = new Uint16Array(MAX_SYMBOLS); - hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); - hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); - hufGroup.minLen = minLen; - hufGroup.maxLen = maxLen; - /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ - var pp = 0; - for (i = minLen; i <= maxLen; i++) { - temp[i] = hufGroup.limit[i] = 0; - for (t = 0; t < symCount; t++) - if (length[t] === i) - hufGroup.permute[pp++] = t; - } - /* Count symbols coded for at each bit length */ - for (i = 0; i < symCount; i++) - temp[length[i]]++; - /* Calculate limit[] (the largest symbol-coding value at each bit - * length, which is (previous limit<<1)+symbols at this level), and - * base[] (number of symbols to ignore at each bit length, which is - * limit minus the cumulative count of symbols coded for already). */ - pp = t = 0; - for (i = minLen; i < maxLen; i++) { - pp += temp[i]; - /* We read the largest possible symbol size and then unget bits - after determining how many we need, and those extra bits could - be set to anything. (They're noise from future symbols.) At - each level we're really only interested in the first few bits, - so here we set all the trailing to-be-ignored bits to 1 so they - don't affect the value>limit[length] comparison. */ - hufGroup.limit[i] = pp - 1; - pp <<= 1; - t += temp[i]; - hufGroup.base[i + 1] = pp - t; - } - hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ - hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; - hufGroup.base[minLen] = 0; - } - /* We've finished reading and digesting the block header. Now read this - block's huffman coded symbols from the file and undo the huffman coding - and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - - /* Initialize symbol occurrence counters and symbol Move To Front table */ - var byteCount = new Uint32Array(256); - for (i = 0; i < 256; i++) - mtfSymbol[i] = i; - /* Loop through compressed symbols. */ - var runPos = 0, dbufCount = 0, selector = 0, uc; - var dbuf = this.dbuf = new Uint32Array(this.dbufSize); - symCount = 0; - for (;;) { - /* Determine which huffman coding group to use. */ - if (!(symCount--)) { - symCount = GROUP_SIZE - 1; - if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } - hufGroup = groups[selectors[selector++]]; - } - /* Read next huffman-coded symbol. */ - i = hufGroup.minLen; - j = reader.read(i); - for (;;i++) { - if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } - if (j <= hufGroup.limit[i]) - break; - j = (j << 1) | reader.read(1); - } - /* Huffman decode value to get nextSym (with bounds checking) */ - j -= hufGroup.base[i]; - if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } - var nextSym = hufGroup.permute[j]; - /* We have now decoded the symbol, which indicates either a new literal - byte, or a repeated run of the most recent literal byte. First, - check if nextSym indicates a repeated run, and if so loop collecting - how many times to repeat the last literal. */ - if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { - /* If this is the start of a new run, zero out counter */ - if (!runPos){ - runPos = 1; - t = 0; - } - /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at - each bit position, add 1 or 2 instead. For example, - 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. - You can make any bit pattern that way using 1 less symbol than - the basic or 0/1 method (except all bits 0, which would use no - symbols, but a run of length 0 doesn't mean anything in this - context). Thus space is saved. */ - if (nextSym === SYMBOL_RUNA) - t += runPos; - else - t += 2 * runPos; - runPos <<= 1; - continue; - } - /* When we hit the first non-run symbol after a run, we now know - how many times to repeat the last literal, so append that many - copies to our buffer of decoded symbols (dbuf) now. (The last - literal used is the one at the head of the mtfSymbol array.) */ - if (runPos){ - runPos = 0; - if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } - uc = symToByte[mtfSymbol[0]]; - byteCount[uc] += t; - while (t--) - dbuf[dbufCount++] = uc; - } - /* Is this the terminating symbol? */ - if (nextSym > symTotal) - break; - /* At this point, nextSym indicates a new literal character. Subtract - one to get the position in the MTF array at which this literal is - currently to be found. (Note that the result can't be -1 or 0, - because 0 and 1 are RUNA and RUNB. But another instance of the - first symbol in the mtf array, position 0, would have been handled - as part of a run above. Therefore 1 unused mtf position minus - 2 non-literal nextSym values equals -1.) */ - if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } - i = nextSym - 1; - uc = mtf(mtfSymbol, i); - uc = symToByte[uc]; - /* We have our literal byte. Save it into dbuf. */ - byteCount[uc]++; - dbuf[dbufCount++] = uc; - } - /* At this point, we've read all the huffman-coded symbols (and repeated - runs) for this block from the input stream, and decoded them into the - intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. - Now undo the Burrows-Wheeler transform on dbuf. - See http://dogma.net/markn/articles/bwt/bwt.htm - */ - if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } - /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ - j = 0; - for (i = 0; i < 256; i++) { - k = j + byteCount[i]; - byteCount[i] = j; - j = k; - } - /* Figure out what order dbuf would be in if we sorted it. */ - for (i = 0; i < dbufCount; i++) { - uc = dbuf[i] & 0xff; - dbuf[byteCount[uc]] |= (i << 8); - byteCount[uc]++; - } - /* Decode first byte by hand to initialize "previous" byte. Note that it - doesn't get output, and if the first three characters are identical - it doesn't qualify as a run (hence writeRunCountdown=5). */ - var pos = 0, current = 0, run = 0; - if (dbufCount) { - pos = dbuf[origPointer]; - current = (pos & 0xff); - pos >>= 8; - run = -1; - } - this.writePos = pos; - this.writeCurrent = current; - this.writeCount = dbufCount; - this.writeRun = run; - - return true; /* more blocks to come */ - }; - /* Undo burrows-wheeler transform on intermediate buffer to produce output. - If start_bunzip was initialized with out_fd=-1, then up to len bytes of - data are written to outbuf. Return value is number of bytes written or - error (all errors are negative numbers). If out_fd!=-1, outbuf and len - are ignored, data is written to out_fd and return is RETVAL_OK or error. - */ - Bunzip.prototype._read_bunzip = function(outputBuffer, len) { - var copies, previous, outbyte; - /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully - decoded, which results in this returning RETVAL_LAST_BLOCK, also - equal to -1... Confusing, I'm returning 0 here to indicate no - bytes written into the buffer */ - if (this.writeCount < 0) { return 0; } - var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; - var dbufCount = this.writeCount; this.outputsize; - var run = this.writeRun; - - while (dbufCount) { - dbufCount--; - previous = current; - pos = dbuf[pos]; - current = pos & 0xff; - pos >>= 8; - if (run++ === 3){ - copies = current; - outbyte = previous; - current = -1; - } else { - copies = 1; - outbyte = current; - } - this.blockCRC.updateCRCRun(outbyte, copies); - while (copies--) { - this.outputStream.writeByte(outbyte); - this.nextoutput++; - } - if (current != previous) - run = 0; - } - this.writeCount = dbufCount; - // check CRC - if (this.blockCRC.getCRC() !== this.targetBlockCRC) { - _throw(Err.DATA_ERROR, "Bad block CRC "+ - "(got "+this.blockCRC.getCRC().toString(16)+ - " expected "+this.targetBlockCRC.toString(16)+")"); - } - return this.nextoutput; - }; - - var coerceInputStream = function(input) { - if ('readByte' in input) { return input; } - var inputStream = new stream(); - inputStream.pos = 0; - inputStream.readByte = function() { return input[this.pos++]; }; - inputStream.seek = function(pos) { this.pos = pos; }; - inputStream.eof = function() { return this.pos >= input.length; }; - return inputStream; - }; - var coerceOutputStream = function(output) { - var outputStream = new stream(); - var resizeOk = true; - if (output) { - if (typeof(output)==='number') { - outputStream.buffer = new Uint8Array(output); - resizeOk = false; - } else if ('writeByte' in output) { - return output; - } else { - outputStream.buffer = output; - resizeOk = false; - } - } else { - outputStream.buffer = new Uint8Array(16384); - } - outputStream.pos = 0; - outputStream.writeByte = function(_byte) { - if (resizeOk && this.pos >= this.buffer.length) { - var newBuffer = new Uint8Array(this.buffer.length*2); - newBuffer.set(this.buffer); - this.buffer = newBuffer; - } - this.buffer[this.pos++] = _byte; - }; - outputStream.getBuffer = function() { - // trim buffer - if (this.pos !== this.buffer.length) { - if (!resizeOk) - throw new TypeError('outputsize does not match decoded input'); - var newBuffer = new Uint8Array(this.pos); - newBuffer.set(this.buffer.subarray(0, this.pos)); - this.buffer = newBuffer; - } - return this.buffer; - }; - outputStream._coerced = true; - return outputStream; - }; - - /* Static helper functions */ - // 'input' can be a stream or a buffer - // 'output' can be a stream or a buffer or a number (buffer size) - const decode$2 = function(input, output, multistream) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - - var bz = new Bunzip(inputStream, outputStream); - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - if (bz._init_block()) { - bz._read_bunzip(); - } else { - var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) - if (targetStreamCRC !== bz.streamCRC) { - _throw(Err.DATA_ERROR, "Bad stream CRC "+ - "(got "+bz.streamCRC.toString(16)+ - " expected "+targetStreamCRC.toString(16)+")"); - } - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - } else break; - } - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); - }; - const decodeBlock = function(input, pos, output) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - var bz = new Bunzip(inputStream, outputStream); - bz.reader.seek(pos); - /* Fill the decode buffer for the block */ - var moreBlocks = bz._get_next_block(); - if (moreBlocks) { - /* Init the CRC for writing */ - bz.blockCRC = new crc32$1(); - - /* Zero this so the current byte from before the seek is not written */ - bz.writeCopies = 0; - - /* Decompress the block and write to stdout */ - bz._read_bunzip(); - // XXX keep writing? - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); - }; - /* Reads bzip2 file from stream or buffer `input`, and invoke - * `callback(position, size)` once for each bzip2 block, - * where position gives the starting position (in *bits*) - * and size gives uncompressed size of the block (in *bytes*). */ - const table = function(input, callback, multistream) { - // make a stream from a buffer, if necessary - var inputStream = new stream(); - inputStream.delegate = coerceInputStream(input); - inputStream.pos = 0; - inputStream.readByte = function() { - this.pos++; - return this.delegate.readByte(); - }; - if (inputStream.delegate.eof) { - inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); - } - var outputStream = new stream(); - outputStream.pos = 0; - outputStream.writeByte = function() { this.pos++; }; - - var bz = new Bunzip(inputStream, outputStream); - var blockSize = bz.dbufSize; - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - - var position = inputStream.pos*8 + bz.reader.bitOffset; - if (bz.reader.hasByte) { position -= 8; } - - if (bz._init_block()) { - var start = outputStream.pos; - bz._read_bunzip(); - callback(position, outputStream.pos - start); - } else { - bz.reader.read(32); // (but we ignore the crc) - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - console.assert(bz.dbufSize === blockSize, - "shouldn't change block size within multistream file"); - } else break; - } - } - }; - - var lib = { - Bunzip, - Stream: stream, - Err, - decode: decode$2, - decodeBlock, - table - }; - var lib_4 = lib.decode; - - // GPG4Browsers - An OpenPGP implementation in javascript - - /** - * Implementation of the Literal Data Packet (Tag 11) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - */ - class LiteralDataPacket { - static get tag() { - return enums.packet.literalData; - } - - /** - * @param {Date} date - The creation date of the literal package - */ - constructor(date = new Date()) { - this.format = enums.literal.utf8; // default format for literal data packets - this.date = util.normalizeDate(date); - this.text = null; // textual data representation - this.data = null; // literal data representation - this.filename = ''; - } - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param {String | ReadableStream} text - Any native javascript string - * @param {enums.literal} [format] - The format of the string of bytes - */ - setText(text, format = enums.literal.utf8) { - this.format = format; - this.text = text; - this.data = null; - } - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {String | ReadableStream} Literal data as text. - */ - getText(clone = false) { - if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read - this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); - } - return this.text; - } - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param {Uint8Array | ReadableStream} bytes - The string of bytes - * @param {enums.literal} format - The format of the string of bytes - */ - setBytes(bytes, format) { - this.format = format; - this.data = bytes; - this.text = null; - } - - - /** - * Get the byte sequence representing the literal packet data - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {Uint8Array | ReadableStream} A sequence of bytes. - */ - getBytes(clone = false) { - if (this.data === null) { - // encode UTF8 and normalize EOL to \r\n - this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); - } - if (clone) { - return passiveClone(this.data); - } - return this.data; - } - - - /** - * Sets the filename of the literal packet data - * @param {String} filename - Any native javascript string - */ - setFilename(filename) { - this.filename = filename; - } - - - /** - * Get the filename of the literal packet data - * @returns {String} Filename. - */ - getFilename() { - return this.filename; - } - - /** - * Parsing function for a literal data packet (tag 11). - * - * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet - * @returns {Promise} Object representation. - * @async - */ - async read(bytes) { - await parse(bytes, async reader => { - // - A one-octet field that describes how the data is formatted. - const format = await reader.readByte(); // enums.literal - - const filename_len = await reader.readByte(); - this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - - this.date = util.readDate(await reader.readBytes(4)); - - let data = reader.remainder(); - if (isArrayStream(data)) data = await readToEnd(data); - this.setBytes(data, format); - }); - } - - /** - * Creates a Uint8Array representation of the packet, excluding the data - * - * @returns {Uint8Array} Uint8Array representation of the packet. - */ - writeHeader() { - const filename = util.encodeUTF8(this.filename); - const filename_length = new Uint8Array([filename.length]); - - const format = new Uint8Array([this.format]); - const date = util.writeDate(this.date); - - return util.concatUint8Array([format, filename_length, filename, date]); - } - - /** - * Creates a Uint8Array representation of the packet - * - * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. - */ - write() { - const header = this.writeHeader(); - const data = this.getBytes(); - - return util.concat([header, data]); - } - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - // Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. - const verified = Symbol('verified'); - - // GPG puts the Issuer and Signature subpackets in the unhashed area. - // Tampering with those invalidates the signature, so we still trust them and parse them. - // All other unhashed subpackets are ignored. - const allowedUnhashedSubpackets = new Set([ - enums.signatureSubpacket.issuer, - enums.signatureSubpacket.issuerFingerprint, - enums.signatureSubpacket.embeddedSignature - ]); - - /** - * Implementation of the Signature Packet (Tag 2) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - */ - class SignaturePacket { - static get tag() { - return enums.packet.signature; - } - - constructor() { - this.version = null; - /** @type {enums.signature} */ - this.signatureType = null; - /** @type {enums.hash} */ - this.hashAlgorithm = null; - /** @type {enums.publicKey} */ - this.publicKeyAlgorithm = null; - - this.signatureData = null; - this.unhashedSubpackets = []; - this.signedHashValue = null; - - this.created = null; - this.signatureExpirationTime = null; - this.signatureNeverExpires = true; - this.exportable = null; - this.trustLevel = null; - this.trustAmount = null; - this.regularExpression = null; - this.revocable = null; - this.keyExpirationTime = null; - this.keyNeverExpires = null; - this.preferredSymmetricAlgorithms = null; - this.revocationKeyClass = null; - this.revocationKeyAlgorithm = null; - this.revocationKeyFingerprint = null; - this.issuerKeyID = new KeyID(); - this.rawNotations = []; - this.notations = {}; - this.preferredHashAlgorithms = null; - this.preferredCompressionAlgorithms = null; - this.keyServerPreferences = null; - this.preferredKeyServer = null; - this.isPrimaryUserID = null; - this.policyURI = null; - this.keyFlags = null; - this.signersUserID = null; - this.reasonForRevocationFlag = null; - this.reasonForRevocationString = null; - this.features = null; - this.signatureTargetPublicKeyAlgorithm = null; - this.signatureTargetHashAlgorithm = null; - this.signatureTargetHash = null; - this.embeddedSignature = null; - this.issuerKeyVersion = null; - this.issuerFingerprint = null; - this.preferredAEADAlgorithms = null; - - this.revoked = null; - this[verified] = null; - } - - /** - * parsing function for a signature packet (tag 2). - * @param {String} bytes - Payload of a tag 2 packet - * @returns {SignaturePacket} Object representation. - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); - } - - this.signatureType = bytes[i++]; - this.publicKeyAlgorithm = bytes[i++]; - this.hashAlgorithm = bytes[i++]; - - // hashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), true); - if (!this.created) { - throw new Error('Missing signature creation time subpacket.'); - } - - // A V4 signature hashes the packet body - // starting from its first field, the version number, through the end - // of the hashed subpacket data. Thus, the fields hashed are the - // signature version, the signature type, the public-key algorithm, the - // hash algorithm, the hashed subpacket length, and the hashed - // subpacket body. - this.signatureData = bytes.subarray(0, i); - - // unhashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - - // Two-octet field holding left 16 bits of signed hash value. - this.signedHashValue = bytes.subarray(i, i + 2); - i += 2; - - this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length)); - } - - /** - * @returns {Uint8Array | ReadableStream} - */ - writeParams() { - if (this.params instanceof Promise) { - return fromAsync( - async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params) - ); - } - return mod.serializeParams(this.publicKeyAlgorithm, this.params); - } - - write() { - const arr = []; - arr.push(this.signatureData); - arr.push(this.writeUnhashedSubPackets()); - arr.push(this.signedHashValue); - arr.push(this.writeParams()); - return util.concat(arr); - } - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param {SecretKeyPacket} key - Private key used to sign the message. - * @param {Object} data - Contains packets to be signed. - * @param {Date} [date] - The signature creation time. - * @param {Boolean} [detached] - Whether to create a detached signature - * @throws {Error} if signing failed - * @async - */ - async sign(key, data, date = new Date(), detached = false) { - if (key.version === 5) { - this.version = 5; - } else { - this.version = 4; - } - const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; - - this.created = util.normalizeDate(date); - this.issuerKeyVersion = key.version; - this.issuerFingerprint = key.getFingerprintBytes(); - this.issuerKeyID = key.getKeyID(); - - // Add hashed subpackets - arr.push(this.writeHashedSubPackets()); - - // Remove unhashed subpackets, in case some allowed unhashed - // subpackets existed, in order not to duplicate them (in both - // the hashed and unhashed subpackets) when re-signing. - this.unhashedSubpackets = []; - - this.signatureData = util.concat(arr); - - const toHash = this.toHash(this.signatureType, data, detached); - const hash = await this.hash(this.signatureType, data, toHash, detached); - - this.signedHashValue = slice(clone(hash), 0, 2); - const signed = async () => mod.signature.sign( - this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) - ); - if (util.isStream(hash)) { - this.params = signed(); - } else { - this.params = await signed(); - - // Store the fact that this signature is valid, e.g. for when we call `await - // getLatestValidSignature(this.revocationSignatures, key, data)` later. - // Note that this only holds up if the key and data passed to verify are the - // same as the ones passed to sign. - this[verified] = true; - } - } - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeHashedSubPackets() { - const sub = enums.signatureSubpacket; - const arr = []; - let bytes; - if (this.created === null) { - throw new Error('Missing signature creation time'); - } - arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); - if (this.signatureExpirationTime !== null) { - arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); - } - if (this.exportable !== null) { - arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); - } - if (this.trustLevel !== null) { - bytes = new Uint8Array([this.trustLevel, this.trustAmount]); - arr.push(writeSubPacket(sub.trustSignature, true, bytes)); - } - if (this.regularExpression !== null) { - arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); - } - if (this.revocable !== null) { - arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); - } - if (this.keyExpirationTime !== null) { - arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); - } - if (this.preferredSymmetricAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); - arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); - } - if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); - bytes = util.concat([bytes, this.revocationKeyFingerprint]); - arr.push(writeSubPacket(sub.revocationKey, false, bytes)); - } - if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { - // If the version of [the] key is greater than 4, this subpacket - // MUST NOT be included in the signature. - arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write())); - } - this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { - bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; - const encodedName = util.encodeUTF8(name); - // 2 octets of name length - bytes.push(util.writeNumber(encodedName.length, 2)); - // 2 octets of value length - bytes.push(util.writeNumber(value.length, 2)); - bytes.push(encodedName); - bytes.push(value); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.notationData, critical, bytes)); - }); - if (this.preferredHashAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); - arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); - } - if (this.preferredCompressionAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); - arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); - } - if (this.keyServerPreferences !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); - arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); - } - if (this.preferredKeyServer !== null) { - arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); - } - if (this.isPrimaryUserID !== null) { - arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); - } - if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); - } - if (this.keyFlags !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); - arr.push(writeSubPacket(sub.keyFlags, true, bytes)); - } - if (this.signersUserID !== null) { - arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); - } - if (this.reasonForRevocationFlag !== null) { - bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); - arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); - } - if (this.features !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); - arr.push(writeSubPacket(sub.features, false, bytes)); - } - if (this.signatureTargetPublicKeyAlgorithm !== null) { - bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(util.stringToUint8Array(this.signatureTargetHash)); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); - } - if (this.embeddedSignature !== null) { - arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); - } - if (this.issuerFingerprint !== null) { - bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes)); - } - if (this.preferredAEADAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); - arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); - } - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - /** - * Creates an Uint8Array containing the unhashed subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeUnhashedSubPackets() { - const arr = []; - this.unhashedSubpackets.forEach(data => { - arr.push(writeSimpleLength(data.length)); - arr.push(data); - }); - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - // V4 signature sub packets - readSubPacket(bytes, hashed = true) { - let mypos = 0; - - // The leftmost bit denotes a "critical" packet - const critical = !!(bytes[mypos] & 0x80); - const type = bytes[mypos] & 0x7F; - - if (!hashed) { - this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length)); - if (!allowedUnhashedSubpackets.has(type)) { - return; - } - } - - mypos++; - - // subpacket type - switch (type) { - case enums.signatureSubpacket.signatureCreationTime: - // Signature Creation Time - this.created = util.readDate(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.signatureExpirationTime: { - // Signature Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.signatureNeverExpires = seconds === 0; - this.signatureExpirationTime = seconds; - - break; - } - case enums.signatureSubpacket.exportableCertification: - // Exportable Certification - this.exportable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.trustSignature: - // Trust Signature - this.trustLevel = bytes[mypos++]; - this.trustAmount = bytes[mypos++]; - break; - case enums.signatureSubpacket.regularExpression: - // Regular Expression - this.regularExpression = bytes[mypos]; - break; - case enums.signatureSubpacket.revocable: - // Revocable - this.revocable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.keyExpirationTime: { - // Key Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.keyExpirationTime = seconds; - this.keyNeverExpires = seconds === 0; - - break; - } - case enums.signatureSubpacket.preferredSymmetricAlgorithms: - // Preferred Symmetric Algorithms - this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.revocationKey: - // Revocation Key - // (1 octet of class, 1 octet of public-key algorithm ID, 20 - // octets of - // fingerprint) - this.revocationKeyClass = bytes[mypos++]; - this.revocationKeyAlgorithm = bytes[mypos++]; - this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); - break; - - case enums.signatureSubpacket.issuer: - // Issuer - this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); - break; - - case enums.signatureSubpacket.notationData: { - // Notation Data - const humanReadable = !!(bytes[mypos] & 0x80); - - // We extract key/value tuple from the byte stream. - mypos += 4; - const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - - const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); - const value = bytes.subarray(mypos + m, mypos + m + n); - - this.rawNotations.push({ name, humanReadable, value, critical }); - - if (humanReadable) { - this.notations[name] = util.decodeUTF8(value); - } - break; - } - case enums.signatureSubpacket.preferredHashAlgorithms: - // Preferred Hash Algorithms - this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredCompressionAlgorithms: - // Preferred Compression Algorithms - this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.keyServerPreferences: - // Key Server Preferences - this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredKeyServer: - // Preferred Key Server - this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.primaryUserID: - // Primary User ID - this.isPrimaryUserID = bytes[mypos++] !== 0; - break; - case enums.signatureSubpacket.policyURI: - // Policy URI - this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.keyFlags: - // Key Flags - this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signersUserID: - // Signer's User ID - this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.reasonForRevocation: - // Reason for Revocation - this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.features: - // Features - this.features = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signatureTarget: { - // Signature Target - // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) - this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; - this.signatureTargetHashAlgorithm = bytes[mypos++]; - - const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm); - - this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); - break; - } - case enums.signatureSubpacket.embeddedSignature: - // Embedded Signature - this.embeddedSignature = new SignaturePacket(); - this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.issuerFingerprint: - // Issuer Fingerprint - this.issuerKeyVersion = bytes[mypos++]; - this.issuerFingerprint = bytes.subarray(mypos, bytes.length); - if (this.issuerKeyVersion === 5) { - this.issuerKeyID.read(this.issuerFingerprint); - } else { - this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); - } - break; - case enums.signatureSubpacket.preferredAEADAlgorithms: - // Preferred AEAD Algorithms - this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - default: { - const err = new Error(`Unknown signature subpacket type ${type}`); - if (critical) { - throw err; - } else { - util.printDebug(err); - } - } - } - } - - readSubPackets(bytes, trusted = true, config) { - // Two-octet scalar octet count for following subpacket data. - const subpacketLength = util.readNumber(bytes.subarray(0, 2)); - - let i = 2; - - // subpacket data set (zero or more subpackets) - while (i < 2 + subpacketLength) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); - - i += len.len; - } - - return i; - } - - // Produces data to produce signature on - toSign(type, data) { - const t = enums.signature; - - switch (type) { - case t.binary: - if (data.text !== null) { - return util.encodeUTF8(data.getText(true)); - } - return data.getBytes(true); - - case t.text: { - const bytes = data.getBytes(true); - // normalize EOL to \r\n - return util.canonicalizeEOL(bytes); - } - case t.standalone: - return new Uint8Array(0); - - case t.certGeneric: - case t.certPersona: - case t.certCasual: - case t.certPositive: - case t.certRevocation: { - let packet; - let tag; - - if (data.userID) { - tag = 0xB4; - packet = data.userID; - } else if (data.userAttribute) { - tag = 0xD1; - packet = data.userAttribute; - } else { - throw new Error('Either a userID or userAttribute packet needs to be ' + - 'supplied for certification.'); - } - - const bytes = packet.write(); - - return util.concat([this.toSign(t.key, data), - new Uint8Array([tag]), - util.writeNumber(bytes.length, 4), - bytes]); - } - case t.subkeyBinding: - case t.subkeyRevocation: - case t.keyBinding: - return util.concat([this.toSign(t.key, data), this.toSign(t.key, { - key: data.bind - })]); - - case t.key: - if (data.key === undefined) { - throw new Error('Key packet is required for this signature.'); - } - return data.key.writeForHash(this.version); - - case t.keyRevocation: - return this.toSign(t.key, data); - case t.timestamp: - return new Uint8Array(0); - case t.thirdParty: - throw new Error('Not implemented'); - default: - throw new Error('Unknown signature type.'); - } - } - - calculateTrailer(data, detached) { - let length = 0; - return transform(clone(this.signatureData), value => { - length += value.length; - }, () => { - const arr = []; - if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { - if (detached) { - arr.push(new Uint8Array(6)); - } else { - arr.push(data.writeHeader()); - } - } - arr.push(new Uint8Array([this.version, 0xFF])); - if (this.version === 5) { - arr.push(new Uint8Array(4)); - } - arr.push(util.writeNumber(length, 4)); - // For v5, this should really be writeNumber(length, 8) rather than the - // hardcoded 4 zero bytes above - return util.concat(arr); - }); - } - - toHash(signatureType, data, detached = false) { - const bytes = this.toSign(signatureType, data); - - return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); - } - - async hash(signatureType, data, toHash, detached = false) { - if (!toHash) toHash = this.toHash(signatureType, data, detached); - return mod.hash.digest(this.hashAlgorithm, toHash); - } - - /** - * verifies the signature packet. Note: not all signature types are implemented - * @param {PublicSubkeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature - * @param {module:enums.signature} signatureType - Expected signature type - * @param {Uint8Array|Object} data - Data which on the signature applies - * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration - * @param {Boolean} [detached] - Whether to verify a detached signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if signature validation failed - * @async - */ - async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { - if (!this.issuerKeyID.equals(key.getKeyID())) { - throw new Error('Signature was not issued by the given public key'); - } - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); - } - - const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; - // Cryptographic validity is cached after one successful verification. - // However, for message signatures, we always re-verify, since the passed `data` can change - const skipVerify = this[verified] && !isMessageSignature; - if (!skipVerify) { - let toHash; - let hash; - if (this.hashed) { - hash = await this.hashed; - } else { - toHash = this.toHash(signatureType, data, detached); - hash = await this.hash(signatureType, data, toHash); - } - hash = await readToEnd(hash); - if (this.signedHashValue[0] !== hash[0] || - this.signedHashValue[1] !== hash[1]) { - throw new Error('Signed digest did not match'); - } - - this.params = await this.params; - - this[verified] = await mod.signature.verify( - this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, - toHash, hash - ); - - if (!this[verified]) { - throw new Error('Signature verification failed'); - } - } - - const normDate = util.normalizeDate(date); - if (normDate && this.created > normDate) { - throw new Error('Signature creation time is in the future'); - } - if (normDate && normDate >= this.getExpirationTime()) { - throw new Error('Signature is expired'); - } - if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { - throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && - [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { - throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - this.rawNotations.forEach(({ name, critical }) => { - if (critical && (config$1.knownNotations.indexOf(name) < 0)) { - throw new Error(`Unknown critical notation: ${name}`); - } - }); - if (this.revocationKeyClass !== null) { - throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); - } - } - - /** - * Verifies signature expiration date - * @param {Date} [date] - Use the given date for verification instead of the current time - * @returns {Boolean} True if expired. - */ - isExpired(date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - return !(this.created <= normDate && normDate < this.getExpirationTime()); - } - return false; - } - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns {Date | Infinity} Expiration time. - */ - getExpirationTime() { - return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); - } - } - - /** - * Creates a Uint8Array representation of a sub signature packet - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} - * @param {Integer} type - Subpacket signature type. - * @param {Boolean} critical - Whether the subpacket should be critical. - * @param {String} data - Data to be included - * @returns {Uint8Array} The signature subpacket. - * @private - */ - function writeSubPacket(type, critical, data) { - const arr = []; - arr.push(writeSimpleLength(data.length + 1)); - arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); - arr.push(data); - return util.concat(arr); - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - const VERSION = 3; - - /** - * Implementation of the One-Pass Signature Packets (Tag 4) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ - class OnePassSignaturePacket { - static get tag() { - return enums.packet.onePassSignature; - } - - constructor() { - /** A one-octet version number. The current version is 3. */ - this.version = null; - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - * @type {enums.signature} - - */ - this.signatureType = null; - /** - * A one-octet number describing the hash algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} - * @type {enums.hash} - */ - this.hashAlgorithm = null; - /** - * A one-octet number describing the public-key algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} - * @type {enums.publicKey} - */ - this.publicKeyAlgorithm = null; - /** An eight-octet number holding the Key ID of the signing key. */ - this.issuerKeyID = null; - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - this.flags = null; - } - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param {Uint8Array} bytes - Payload of a tag 4 packet - * @returns {OnePassSignaturePacket} Object representation. - */ - read(bytes) { - let mypos = 0; - // A one-octet version number. The current version is 3. - this.version = bytes[mypos++]; - if (this.version !== VERSION) { - throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); - } - - // A one-octet signature type. Signature types are described in - // Section 5.2.1. - this.signatureType = bytes[mypos++]; - - // A one-octet number describing the hash algorithm used. - this.hashAlgorithm = bytes[mypos++]; - - // A one-octet number describing the public-key algorithm used. - this.publicKeyAlgorithm = bytes[mypos++]; - - // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyID = new KeyID(); - this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); - mypos += 8; - - // A one-octet number holding a flag showing whether the signature - // is nested. A zero value indicates that the next packet is - // another One-Pass Signature packet that describes another - // signature to be applied to the same message data. - this.flags = bytes[mypos++]; - return this; - } - - /** - * creates a string representation of a one-pass signature packet - * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. - */ - write() { - const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]); - - const end = new Uint8Array([this.flags]); - - return util.concatUint8Array([start, this.issuerKeyID.write(), end]); - } - - calculateTrailer(...args) { - return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); - } - - async verify() { - const correspondingSig = await this.correspondingSig; - if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { - throw new Error('Corresponding signature packet missing'); - } - if ( - correspondingSig.signatureType !== this.signatureType || - correspondingSig.hashAlgorithm !== this.hashAlgorithm || - correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyID.equals(this.issuerKeyID) - ) { - throw new Error('Corresponding signature packet does not match one-pass signature packet'); - } - correspondingSig.hashed = this.hashed; - return correspondingSig.verify.apply(correspondingSig, arguments); - } - } - - OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; - OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; - OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; - - /** - * Instantiate a new packet given its tag - * @function newPacketFromTag - * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @returns {Object} New packet object with type based on tag - * @throws {Error|UnsupportedError} for disallowed or unknown packets - */ - function newPacketFromTag(tag, allowedPackets) { - if (!allowedPackets[tag]) { - // distinguish between disallowed packets and unknown ones - let packetType; - try { - packetType = enums.read(enums.packet, tag); - } catch (e) { - throw new UnsupportedError(`Unknown packet type with tag: ${tag}`); - } - throw new Error(`Packet not allowed in this context: ${packetType}`); - } - return new allowedPackets[tag](); - } - - /** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - * @extends Array - */ - class PacketList extends Array { - /** - * Parses the given binary data and returns a list of packets. - * Equivalent to calling `read` on an empty PacketList instance. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @returns {PacketList} parsed list of packets - * @throws on parsing errors - * @async - */ - static async fromBinary(bytes, allowedPackets, config$1 = config) { - const packets = new PacketList(); - await packets.read(bytes, allowedPackets, config$1); - return packets; - } - - /** - * Reads a stream of binary data and interprets it as a list of packets. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @throws on parsing errors - * @async - */ - async read(bytes, allowedPackets, config$1 = config) { - if (config$1.additionalAllowedPackets.length) { - allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; - } - this.stream = transformPair(bytes, async (readable, writable) => { - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const done = await readPackets(readable, async parsed => { - try { - if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) { - // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: - // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 - // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 - return; - } - const packet = newPacketFromTag(parsed.tag, allowedPackets); - packet.packets = new PacketList(); - packet.fromStream = util.isStream(parsed.packet); - await packet.read(parsed.packet, config$1); - await writer.write(packet); - } catch (e) { - const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; - const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); - if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { - // The packets that support streaming are the ones that contain message data. - // Those are also the ones we want to be more strict about and throw on parse errors - // (since we likely cannot process the message without these packets anyway). - await writer.abort(e); - } else { - const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); - await writer.write(unparsedPacket); - } - util.printDebugError(e); - } - }); - if (done) { - await writer.ready; - await writer.close(); - return; - } - } - } catch (e) { - await writer.abort(e); - } - }); - - // Wait until first few packets have been read - const reader = getReader(this.stream); - while (true) { - const { done, value } = await reader.read(); - if (!done) { - this.push(value); - } else { - this.stream = null; - } - if (done || supportsStreaming(value.constructor.tag)) { - break; - } - } - reader.releaseLock(); - } - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. - */ - write() { - const arr = []; - - for (let i = 0; i < this.length; i++) { - const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; - const packetbytes = this[i].write(); - if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { - let buffer = []; - let bufferLength = 0; - const minLength = 512; - arr.push(writeTag(tag)); - arr.push(transform(packetbytes, value => { - buffer.push(value); - bufferLength += value.length; - if (bufferLength >= minLength) { - const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); - const chunkSize = 2 ** powerOf2; - const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); - buffer = [bufferConcat.subarray(1 + chunkSize)]; - bufferLength = buffer[0].length; - return bufferConcat.subarray(0, 1 + chunkSize); - } - }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); - } else { - if (util.isStream(packetbytes)) { - let length = 0; - arr.push(transform(clone(packetbytes), value => { - length += value.length; - }, () => writeHeader(tag, length))); - } else { - arr.push(writeHeader(tag, packetbytes.length)); - } - arr.push(packetbytes); - } - } - - return util.concat(arr); - } - - /** - * Creates a new PacketList with all packets matching the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {PacketList} - */ - filterByTag(...tags) { - const filtered = new PacketList(); - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(this[i].constructor.tag))) { - filtered.push(this[i]); - } - } - - return filtered; - } - - /** - * Traverses packet list and returns first packet with matching tag - * @param {module:enums.packet} tag - The packet tag - * @returns {Packet|undefined} - */ - findPacket(tag) { - return this.find(packet => packet.constructor.tag === tag); - } - - /** - * Find indices of packets with the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {Integer[]} packet indices - */ - indexOfTag(...tags) { - const tagIndex = []; - const that = this; - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(that[i].constructor.tag))) { - tagIndex.push(i); - } - } - return tagIndex; - } - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - // A Compressed Data packet can contain the following packet types - const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - OnePassSignaturePacket, - SignaturePacket - ]); - - /** - * Implementation of the Compressed Data Packet (Tag 8) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ - class CompressedDataPacket { - static get tag() { - return enums.packet.compressedData; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * List of packets - * @type {PacketList} - */ - this.packets = null; - /** - * Compression algorithm - * @type {enums.compression} - */ - this.algorithm = config$1.preferredCompressionAlgorithm; - - /** - * Compressed packet data - * @type {Uint8Array | ReadableStream} - */ - this.compressed = null; - - /** - * zip/zlib compression level, between 1 and 9 - */ - this.deflateLevel = config$1.deflateLevel; - } - - /** - * Parsing function for the packet. - * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async read(bytes, config$1 = config) { - await parse(bytes, async reader => { - - // One octet that gives the algorithm used to compress the packet. - this.algorithm = await reader.readByte(); - - // Compressed data, which makes up the remainder of the packet. - this.compressed = reader.remainder(); - - await this.decompress(config$1); - }); - } - - - /** - * Return the compressed packet. - * @returns {Uint8Array | ReadableStream} Binary compressed packet. - */ - write() { - if (this.compressed === null) { - this.compress(); - } - - return util.concat([new Uint8Array([this.algorithm]), this.compressed]); - } - - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async decompress(config$1 = config) { - const compressionName = enums.read(enums.compression, this.algorithm); - const decompressionFn = decompress_fns[compressionName]; - if (!decompressionFn) { - throw new Error(`${compressionName} decompression not supported`); - } - - this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1); - } - - /** - * Compress the packet data (member decompressedData) - */ - compress() { - const compressionName = enums.read(enums.compression, this.algorithm); - const compressionFn = compress_fns[compressionName]; - if (!compressionFn) { - throw new Error(`${compressionName} compression not supported`); - } - - this.compressed = compressionFn(this.packets.write(), this.deflateLevel); - } - } - - ////////////////////////// - // // - // Helper functions // - // // - ////////////////////////// - - - const nodeZlib = util.getNodeZlib(); - - function uncompressed(data) { - return data; - } - - function node_zlib(func, create, options = {}) { - return function (data) { - if (!util.isStream(data) || isArrayStream(data)) { - return fromAsync(() => readToEnd(data).then(data => { - return new Promise((resolve, reject) => { - func(data, options, (err, result) => { - if (err) return reject(err); - resolve(result); - }); - }); - })); - } - return nodeToWeb(webToNode(data).pipe(create(options))); - }; - } - - function pako_zlib(constructor, options = {}) { - return function(data) { - const obj = new constructor(options); - return transform(data, value => { - if (value.length) { - obj.push(value, Z_SYNC_FLUSH); - return obj.result; - } - }, () => { - if (constructor === Deflate) { - obj.push([], Z_FINISH); - return obj.result; - } - }); - }; - } - - function bzip2(func) { - return function(data) { - return fromAsync(async () => func(await readToEnd(data))); - }; - } - - const compress_fns = nodeZlib ? { - zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed) - } : { - zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed) - }; - - const decompress_fns = nodeZlib ? { - uncompressed: uncompressed, - zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw), - zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) - } : { - uncompressed: uncompressed, - zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), - zlib: /*#__PURE__*/ pako_zlib(Inflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) - }; - - // GPG4Browsers - An OpenPGP implementation in javascript - - // A SEIP packet can contain the following packet types - const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - ]); - - const VERSION$1 = 1; // A one-octet version number of the data packet. - - /** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ - class SymEncryptedIntegrityProtectedDataPacket { - static get tag() { - return enums.packet.symEncryptedIntegrityProtectedData; - } - - constructor() { - this.version = VERSION$1; - this.encrypted = null; - this.packets = null; - } - - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - // - A one-octet version number. The only currently defined value is 1. - if (version !== VERSION$1) { - throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`); - } - - // - Encrypted data, the output of the selected symmetric-key cipher - // operating in Cipher Feedback mode with shift amount equal to the - // block size of the cipher (CFB-n where n is the block size). - this.encrypted = reader.remainder(); - }); - } - - write() { - return util.concat([new Uint8Array([VERSION$1]), this.encrypted]); - } - - /** - * Encrypt the payload in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on encryption failure - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - - let bytes = this.packets.write(); - if (isArrayStream(bytes)) bytes = await readToEnd(bytes); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - - const tohash = util.concat([prefix, bytes, mdc]); - const hash = await mod.hash.sha1(passiveClone(tohash)); - const plaintext = util.concat([tohash, hash]); - - this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); - return true; - } - - /** - * Decrypts the encrypted data contained in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on decryption failure - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - let encrypted = clone(this.encrypted); - if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); - - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - const realHash = slice(passiveClone(decrypted), -20); - const tohash = slice(decrypted, 0, -20); - const verifyHash = Promise.all([ - readToEnd(await mod.hash.sha1(passiveClone(tohash))), - readToEnd(realHash) - ]).then(([hash, mdc]) => { - if (!util.equalsUint8Array(hash, mdc)) { - throw new Error('Modification detected.'); - } - return new Uint8Array(); - }); - const bytes = slice(tohash, blockSize + 2); // Remove random prefix - let packetbytes = slice(bytes, 0, -2); // Remove MDC packet - packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); - if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { - packetbytes = await readToEnd(packetbytes); - } - this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1); - return true; - } - } - - // OpenPGP.js - An OpenPGP implementation in javascript - - // An AEAD-encrypted Data packet can contain the following packet types - const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - ]); - - const VERSION$2 = 1; // A one-octet version number of the data packet. - - /** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ - class AEADEncryptedDataPacket { - static get tag() { - return enums.packet.aeadEncryptedData; - } - - constructor() { - this.version = VERSION$2; - /** @type {enums.symmetric} */ - this.cipherAlgorithm = null; - /** @type {enums.aead} */ - this.aeadAlgorithm = enums.aead.eax; - this.chunkSizeByte = null; - this.iv = null; - this.encrypted = null; - this.packets = null; - } - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param {Uint8Array | ReadableStream} bytes - * @throws {Error} on parsing failure - */ - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - if (version !== VERSION$2) { // The only currently defined value is 1. - throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); - } - this.cipherAlgorithm = await reader.readByte(); - this.aeadAlgorithm = await reader.readByte(); - this.chunkSizeByte = await reader.readByte(); - - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = await reader.readBytes(mode.ivLength); - this.encrypted = reader.remainder(); - }); - } - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns {Uint8Array | ReadableStream} The encrypted payload. - */ - write() { - return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); - } - - /** - * Decrypt the encrypted payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.packets = await PacketList.fromBinary( - await this.crypt('decrypt', key, clone(this.encrypted)), - allowedPackets$2, - config$1 - ); - } - - /** - * Encrypt the packet payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.cipherAlgorithm = sessionKeyAlgorithm; - - const { ivLength } = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV - this.chunkSizeByte = config$1.aeadChunkSizeByte; - const data = this.packets.write(); - this.encrypted = await this.crypt('encrypt', key, data); - } - - /** - * En/decrypt the payload. - * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt - * @param {Uint8Array} key - The session key used to en/decrypt the payload - * @param {Uint8Array | ReadableStream} data - The data to en/decrypt - * @returns {Promise>} - * @async - */ - async crypt(fn, key, data) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const modeInstance = await mode(this.cipherAlgorithm, key); - const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; - const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; - const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) - const adataBuffer = new ArrayBuffer(21); - const adataArray = new Uint8Array(adataBuffer, 0, 13); - const adataTagArray = new Uint8Array(adataBuffer); - const adataView = new DataView(adataBuffer); - const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0); - let chunkIndex = 0; - let latestPromise = Promise.resolve(); - let cryptedBytes = 0; - let queuedBytes = 0; - const iv = this.iv; - return transformPair(data, async (readable, writable) => { - if (util.isStream(readable) !== 'array') { - const buffer = new TransformStream({}, { - highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6), - size: array => array.length - }); - pipe(buffer.readable, writable); - writable = buffer.writable; - } - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); - const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); - chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); - let cryptedPromise; - let done; - if (!chunkIndex || chunk.length) { - reader.unshift(finalChunk); - cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray); - queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; - } else { - // After the last chunk, we either encrypt a final, empty - // data chunk to get the final authentication tag or - // validate that final authentication tag. - adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...) - cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray); - queuedBytes += tagLengthIfEncrypting; - done = true; - } - cryptedBytes += chunk.length - tagLengthIfDecrypting; - // eslint-disable-next-line no-loop-func - latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { - await writer.ready; - await writer.write(crypted); - queuedBytes -= crypted.length; - }).catch(err => writer.abort(err)); - if (done || queuedBytes > writer.desiredSize) { - await latestPromise; // Respect backpressure - } - if (!done) { - adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) - } else { - await writer.close(); - break; - } - } - } catch (e) { - await writer.abort(e); - } - }); - } - } - - // GPG4Browsers - An OpenPGP implementation in javascript + function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - const VERSION$3 = 3; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; - /** - * Public-Key Encrypted Session Key Packets (Tag 1) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ - class PublicKeyEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.publicKeyEncryptedSessionKey; - } + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - constructor() { - this.version = 3; + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - this.publicKeyID = new KeyID(); - this.publicKeyAlgorithm = null; + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - this.sessionKey = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = null; + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; + } - /** @type {Object} */ - this.encrypted = {}; - } + function S(o, a) { + M(o, a, a); + } - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * - * @param {Uint8Array} bytes - Payload of a tag 1 packet - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - if (this.version !== VERSION$3) { - throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); - } - i += this.publicKeyID.read(bytes.subarray(i)); - this.publicKeyAlgorithm = bytes[i++]; - this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version); - if (this.publicKeyAlgorithm === enums.publicKey.x25519) { - this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); - } + function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; + } - /** - * Create a binary representation of a tag 1 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const arr = [ - new Uint8Array([this.version]), - this.publicKeyID.write(), - new Uint8Array([this.publicKeyAlgorithm]), - mod.serializeParams(this.publicKeyAlgorithm, this.encrypted) - ]; - - return util.concatUint8Array(arr); + function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; + } - /** - * Encrypt session key packet - * @param {PublicKeyPacket} key - Public key - * @throws {Error} if encryption failed - * @async - */ - async encrypt(key) { - const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); - const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey); - this.encrypted = await mod.publicKeyEncrypt( - algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes()); + function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; } - - /** - * Decrypts the session key (only for public key encrypted session key packets (tag 1) - * @param {SecretKeyPacket} key - decrypted private key - * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. - * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } - * @throws {Error} if decryption failed, unless `randomSessionKey` is given - * @async - */ - async decrypt(key, randomSessionKey) { - // check that session key algo matches the secret key algo - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Decryption error'); - } - - const randomPayload = randomSessionKey ? - encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : - null; - const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload); - - const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); - - // v3 Montgomery curves have cleartext cipher algo - if (this.publicKeyAlgorithm !== enums.publicKey.x25519) { - this.sessionKeyAlgorithm = sessionKeyAlgorithm; - } - this.sessionKey = sessionKey; + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; } + function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); + } - function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // add checksum - return util.concatUint8Array([ - new Uint8Array([cipherAlgo]), - sessionKeyData, - util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) - ]); - } - case enums.publicKey.x25519: - return sessionKeyData; - default: - throw new Error('Unsupported public key algorithm'); - } + function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); } + var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + ]; - function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // verify checksum in constant time - const result = decryptedData.subarray(0, decryptedData.length - 2); - const checksum = decryptedData.subarray(decryptedData.length - 2); - const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); - const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; - const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; - if (randomSessionKey) { - // We must not leak info about the validity of the decrypted checksum or cipher algo. - // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. - const isValidPayload = isValidChecksum & - decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & - decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; - return { - sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), - sessionKeyAlgorithm: util.selectUint8( - isValidPayload, - decryptedSessionKey.sessionKeyAlgorithm, - randomSessionKey.sessionKeyAlgorithm - ) - }; - } else { - const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm); - if (isValidPayload) { - return decryptedSessionKey; - } else { - throw new Error('Decryption error'); - } - } + function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } - case enums.publicKey.x25519: - return { - sessionKey: decryptedData - }; - default: - throw new Error('Unsupported public key algorithm'); - } - } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; - // GPG4Browsers - An OpenPGP implementation in javascript + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; - class S2K { - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * Hash function identifier, or 0 for gnu-dummy keys - * @type {module:enums.hash | 0} - */ - this.algorithm = enums.hash.sha256; - /** - * enums.s2k identifier or 'gnu-dummy' - * @type {String} - */ - this.type = 'iterated'; - /** @type {Integer} */ - this.c = config$1.s2kIterationCountByte; - /** Eight bytes of salt in a binary string. - * @type {Uint8Array} - */ - this.salt = null; - } + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - getCount() { - // Exponent bias, defined in RFC4880 - const expbias = 6; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); - } + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - /** - * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param {Uint8Array} bytes - Payload of string-to-key specifier - * @returns {Integer} Actual length of the object. - */ - read(bytes) { - let i = 0; - try { - this.type = enums.read(enums.s2k, bytes[i++]); - } catch (err) { - throw new UnsupportedError('Unknown S2K type.'); - } - this.algorithm = bytes[i++]; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - switch (this.type) { - case 'simple': - break; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - case 'salted': - this.salt = bytes.subarray(i, i + 8); - i += 8; - break; + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); - case 'iterated': - this.salt = bytes.subarray(i, i + 8); - i += 8; + // add + h = bh3; + l = bl3; - // Octet 10: count, a one-octet, coded value - this.c = bytes[i++]; - break; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - case 'gnu': - if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { - i += 3; // GNU - const gnuExtType = 1000 + bytes[i++]; - if (gnuExtType === 1001) { - this.type = 'gnu-dummy'; - // GnuPG extension mode 1001 -- don't write secret key at all - } else { - throw new UnsupportedError('Unknown s2k gnu protection mode.'); - } - } else { - throw new UnsupportedError('Unknown s2k type.'); - } - break; + h = th; + l = tl; - default: - throw new UnsupportedError('Unknown s2k type.'); // unreachable - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return i; - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - /** - * Serializes s2k information - * @returns {Uint8Array} Binary representation of s2k. - */ - write() { - if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); - } - const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - switch (this.type) { - case 'simple': - break; - case 'salted': - arr.push(this.salt); - break; - case 'iterated': - arr.push(this.salt); - arr.push(new Uint8Array([this.c])); - break; - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - return util.concatUint8Array(arr); - } + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param {String} passphrase - Passphrase containing user input - * @returns {Promise} Produced key with a length corresponding to. - * hashAlgorithm hash length - * @async - */ - async produceKey(passphrase, numBytes) { - passphrase = util.encodeUTF8(passphrase); + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - const arr = []; - let rlength = 0; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - let prefixlen = 0; - while (rlength < numBytes) { - let toHash; - switch (this.type) { - case 'simple': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); - break; - case 'salted': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); - break; - case 'iterated': { - const data = util.concatUint8Array([this.salt, passphrase]); - let datalen = data.length; - const count = Math.max(this.getCount(), datalen); - toHash = new Uint8Array(prefixlen + count); - toHash.set(data, prefixlen); - for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { - toHash.copyWithin(pos, prefixlen, pos); - } - break; + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); } - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); } - const result = await mod.hash.digest(this.algorithm, toHash); - arr.push(result); - rlength += result.length; - prefixlen++; } - return util.concatUint8Array(arr).subarray(0, numBytes); - } - } + // add + h = ah0; + l = al0; - // GPG4Browsers - An OpenPGP implementation in javascript + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - /** - * Symmetric-Key Encrypted Session Key Packets (Tag 3) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: - * The Symmetric-Key Encrypted Session Key packet holds the - * symmetric-key encryption of a session key used to encrypt a message. - * Zero or more Public-Key Encrypted Session Key packets and/or - * Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data packet that holds an encrypted message. - * The message is encrypted with a session key, and the session key is - * itself encrypted and stored in the Encrypted Session Key packet or - * the Symmetric-Key Encrypted Session Key packet. - */ - class SymEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.symEncryptedSessionKey; - } + h = hh[0]; + l = hl[0]; - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - this.version = config$1.aeadProtect ? 5 : 4; - this.sessionKey = null; - /** - * Algorithm to encrypt the session key with - * @type {enums.symmetric} - */ - this.sessionKeyEncryptionAlgorithm = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = enums.symmetric.aes256; - /** - * AEAD mode to encrypt the session key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); - this.encrypted = null; - this.s2k = null; - this.iv = null; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * - * @param {Uint8Array} bytes - Payload of a tag 3 packet - */ - read(bytes) { - let offset = 0; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // A one-octet version number. The only currently defined version is 4. - this.version = bytes[offset++]; - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); - } + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - // A one-octet number describing the symmetric algorithm used. - const algo = bytes[offset++]; + h = ah1; + l = al1; - if (this.version === 5) { - // A one-octet AEAD algorithm. - this.aeadAlgorithm = bytes[offset++]; - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new S2K(); - offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + h = hh[1]; + l = hl[1]; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // A starting initialization vector of size specified by the AEAD - // algorithm. - this.iv = bytes.subarray(offset, offset += mode.ivLength); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // The encrypted session key itself, which is decrypted with the - // string-to-key object. This is optional in version 4. - if (this.version === 5 || offset < bytes.length) { - this.encrypted = bytes.subarray(offset, bytes.length); - this.sessionKeyEncryptionAlgorithm = algo; - } else { - this.sessionKeyAlgorithm = algo; - } - } + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - /** - * Create a binary representation of a tag 3 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const algo = this.encrypted === null ? - this.sessionKeyAlgorithm : - this.sessionKeyEncryptionAlgorithm; + h = ah2; + l = al2; - let bytes; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this.version === 5) { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]); - } else { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]); + h = hh[2]; + l = hl[2]; - if (this.encrypted !== null) { - bytes = util.concatUint8Array([bytes, this.encrypted]); - } - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return bytes; - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - /** - * Decrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(passphrase) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - const { blockSize, keySize } = mod.getCipher(algo); - const key = await this.s2k.produceKey(passphrase, keySize); + h = ah3; + l = al3; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, key); - this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); - } else if (this.encrypted !== null) { - const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1, decrypted.length); - } else { - this.sessionKey = key; - } - } + h = hh[3]; + l = hl[3]; - /** - * Encrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this.sessionKeyEncryptionAlgorithm = algo; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - const { blockSize, keySize } = mod.getCipher(algo); - const encryptionKey = await this.s2k.produceKey(passphrase, keySize); + h = ah4; + l = al4; - if (this.sessionKey === null) { - this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV - const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, encryptionKey); - this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData); - } else { - const toEncrypt = util.concatUint8Array([ - new Uint8Array([this.sessionKeyAlgorithm]), - this.sessionKey - ]); - this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1); - } + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; } + + return n; } - // GPG4Browsers - An OpenPGP implementation in javascript + function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; - /** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ - class PublicKeyPacket { - static get tag() { - return enums.packet.publicKey; - } + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - /** - * Packet version - * @type {Integer} - */ - this.version = config$1.v5Keys ? 5 : 4; - /** - * Key creation date. - * @type {Date} - */ - this.created = util.normalizeDate(date); - /** - * Public key algorithm. - * @type {enums.publicKey} - */ - this.algorithm = null; - /** - * Algorithm specific public params - * @type {Object} - */ - this.publicParams = null; - /** - * Time until expiration in days (V3 only) - * @type {Integer} - */ - this.expirationTimeV3 = 0; - /** - * Fingerprint bytes - * @type {Uint8Array} - */ - this.fingerprint = null; - /** - * KeyID - * @type {module:type/keyid~KeyID} - */ - this.keyID = null; - } + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; + } + + function add$1(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - /** - * Create a PublicKeyPacket from a SecretKeyPacket - * @param {SecretKeyPacket} secretKeyPacket - key packet to convert - * @returns {PublicKeyPacket} public key packet - * @static - */ - static fromSecretKeyPacket(secretKeyPacket) { - const keyPacket = new PublicKeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); + } + + function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); } + } - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * @param {Uint8Array} bytes - Input array to read the packet from - * @returns {Object} This object with attributes set by the parser - * @async - */ - async read(bytes) { - let pos = 0; - // A one-octet version number (3, 4 or 5). - this.version = bytes[pos++]; + function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } - if (this.version === 4 || this.version === 5) { - // - A four-octet number denoting the time that the key was created. - this.created = util.readDate(bytes.subarray(pos, pos + 4)); - pos += 4; + function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add$1(q, p); + add$1(p, p); + cswap(p, q, b); + } + } - // - A one-octet number denoting the public-key algorithm of this key. - this.algorithm = bytes[pos++]; + function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); + } - if (this.version === 5) { - // - A four-octet scalar octet count for the following key material. - pos += 4; - } + function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - // - A series of values comprising the key material. - const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); - this.publicParams = publicParams; - pos += read; + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor - await this.computeFingerprintAndKeyID(); - return pos; - } - throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); - } + scalarbase(p, d); + pack(pk, p); - /** - * Creates an OpenPGP public key packet for the given key. - * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. - */ - write() { - const arr = []; - // Version - arr.push(new Uint8Array([this.version])); - arr.push(util.writeDate(this.created)); - // A one-octet number denoting the public-key algorithm of this key - arr.push(new Uint8Array([this.algorithm])); + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; + } - const params = mod.serializeParams(this.algorithm, this.publicParams); - if (this.version === 5) { - // A four-octet scalar octet count for the following key material - arr.push(util.writeNumber(params.length, 4)); + var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + + function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; } - // Algorithm-specific params - arr.push(params); - return util.concatUint8Array(arr); + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; } + } - /** - * Write packet in order to be hashed; either for a signature or a fingerprint - * @param {Integer} version - target version of signature or key - */ - writeForHash(version) { - const bytes = this.writePublicKey(); + function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); + } - if (version === 5) { - return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]); - } - return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); - } + // Note: difference from C - smlen returned, not passed as argument. + function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return null; - } + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - /** - * Returns the creation time of the key - * @returns {Date} - */ - getCreationTime() { - return this.created; - } + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - /** - * Return the key ID of the key - * @returns {module:type/keyid~KeyID} The 8-byte key ID - */ - getKeyID() { - return this.keyID; - } + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - /** - * Computes and set the key ID and fingerprint of the key - * @async - */ - async computeFingerprintAndKeyID() { - await this.computeFingerprint(); - this.keyID = new KeyID(); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - if (this.version === 5) { - this.keyID.read(this.fingerprint.subarray(0, 8)); - } else if (this.version === 4) { - this.keyID.read(this.fingerprint.subarray(12, 20)); - } else { - throw new Error('Unsupported key version'); + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; } } - /** - * Computes and set the fingerprint of the key - */ - async computeFingerprint() { - const toHash = this.writeForHash(this.version); + modL(sm.subarray(32), x); + return smlen; + } - if (this.version === 5) { - this.fingerprint = await mod.hash.sha256(toHash); - } else if (this.version === 4) { - this.fingerprint = await mod.hash.sha1(toHash); - } else { - throw new Error('Unsupported key version'); - } - } + function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - /** - * Returns the fingerprint of the key, as an array of bytes - * @returns {Uint8Array} A Uint8Array containing the fingerprint - */ - getFingerprintBytes() { - return this.fingerprint; - } + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - /** - * Calculates and returns the fingerprint of the key, as a string - * @returns {String} A string containing the fingerprint in lowercase hex - */ - getFingerprint() { - return util.uint8ArrayToHex(this.getFingerprintBytes()); - } + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns {Boolean} Whether the two keys have the same version and public key data. - */ - hasSameFingerprintAs(other) { - return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - /** - * Returns algorithm information - * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. - */ - getAlgorithmInfo() { - const result = {}; - result.algorithm = enums.read(enums.publicKey, this.algorithm); - // RSA, DSA or ElGamal public modulo - const modulo = this.publicParams.n || this.publicParams.p; - if (modulo) { - result.bits = util.uint8ArrayBitLength(modulo); - } else if (this.publicParams.oid) { - result.curve = this.publicParams.oid.getName(); - } - return result; - } + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; } - /** - * Alias of read() - * @see PublicKeyPacket#read - */ - PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; + function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - /** - * Alias of write() - * @see PublicKeyPacket#write - */ - PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + if (n < 64) return -1; - // GPG4Browsers - An OpenPGP implementation in javascript + if (unpackneg(q, pk)) return -1; - // A SE packet can contain the following packet types - const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket - ]); + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - /** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ - class SymmetricallyEncryptedDataPacket { - static get tag() { - return enums.packet.symmetricallyEncryptedData; - } + scalarbase(q, sm.subarray(32)); + add$1(p, q); + pack(t, p); - constructor() { - /** - * Encrypted secret-key data - */ - this.encrypted = null; - /** - * Decrypted packets contained within. - * @type {PacketList} - */ - this.packets = null; + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; } - read(bytes) { - this.encrypted = bytes; - } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; + } - write() { - return this.encrypted; + var crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32; + + function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); } + } - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config + function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; + } - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error - if (!config$1.allowUnauthenticatedMessages) { - throw new Error('Message is not authenticated.'); - } + nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; + }; - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - const encrypted = await readToEnd(clone(this.encrypted)); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, - encrypted.subarray(blockSize + 2), - encrypted.subarray(2, blockSize + 2) - ); + nacl.box = {}; - this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1); - } + nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; + }; - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const data = this.packets.write(); - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); + nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; + }; - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); - const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); - this.encrypted = util.concat([FRE, ciphertext]); - } - } + nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; + }; - // GPG4Browsers - An OpenPGP implementation in javascript + nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; + }; - /** - * Implementation of the strange "Marker packet" (Tag 10) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * - * The body of this packet consists of: - * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). - * - * Such a packet MUST be ignored when received. It may be placed at the - * beginning of a message that uses features not available in PGP - * version 2.6 in order to cause that version to report that newer - * software is necessary to process the message. - */ - class MarkerPacket { - static get tag() { - return enums.packet.marker; + nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); + }; + + nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; + }; + + nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; + }; + + nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; + }; + + nacl.setPRNG = function(fn) { + randombytes = fn; + }; + + (function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + if (crypto$3 && crypto$3.getRandomValues) { + // Browsers and Node v16+ + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto$3.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); } + })(); - /** - * Parsing function for a marker data packet (tag 10). - * @param {Uint8Array} bytes - Payload of a tag 10 packet - * @returns {Boolean} whether the packet payload contains "PGP" - */ - read(bytes) { - if (bytes[0] === 0x50 && // P - bytes[1] === 0x47 && // G - bytes[2] === 0x50) { // P - return true; - } - return false; - } + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - write() { - return new Uint8Array([0x50, 0x47, 0x50]); - } - } - // GPG4Browsers - An OpenPGP implementation in javascript + const knownOIDs = { + '2a8648ce3d030107': enums.curve.nistP256, + '2b81040022': enums.curve.nistP384, + '2b81040023': enums.curve.nistP521, + '2b8104000a': enums.curve.secp256k1, + '2b06010401da470f01': enums.curve.ed25519Legacy, + '2b060104019755010501': enums.curve.curve25519Legacy, + '2b2403030208010107': enums.curve.brainpoolP256r1, + '2b240303020801010b': enums.curve.brainpoolP384r1, + '2b240303020801010d': enums.curve.brainpoolP512r1 + }; - /** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - * @extends PublicKeyPacket - */ - class PublicSubkeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.publicSubkey; + class OID { + constructor(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (util.isArray(oid) || + util.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { // DER encoded oid byte array + if (oid[1] !== oid.length - 2) { + throw new Error('Length mismatch in DER encoded oid'); + } + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; + } } /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config + * Method to read an OID object + * @param {Uint8Array} input - Where to read the OID from + * @returns {Number} Number of read bytes. */ - // eslint-disable-next-line no-useless-constructor - constructor(date, config) { - super(date, config); + read(input) { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } + } + throw new Error('Invalid oid'); } /** - * Create a PublicSubkeyPacket from a SecretSubkeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert - * @returns {SecretSubkeyPacket} public key packet - * @static + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID. */ - static fromSecretSubkeyPacket(secretSubkeyPacket) { - const keyPacket = new PublicSubkeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } - } - - // GPG4Browsers - An OpenPGP implementation in javascript - - /** - * Implementation of the User Attribute Packet (Tag 17) - * - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ - class UserAttributePacket { - static get tag() { - return enums.packet.userAttribute; - } - - constructor() { - this.attributes = []; + write() { + return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); } /** - * parsing function for a user attribute packet (tag 17). - * @param {Uint8Array} input - Payload of a tag 17 packet + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID. */ - read(bytes) { - let i = 0; - while (i < bytes.length) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); - i += len.len; - } + toHex() { + return util.uint8ArrayToHex(this.oid); } /** - * Creates a binary representation of the user attribute packet - * @returns {Uint8Array} String representation. + * If a known curve object identifier, return the canonical name of the curve + * @returns {enums.curve} String with the canonical name of the curve + * @throws if unknown */ - write() { - const arr = []; - for (let i = 0; i < this.attributes.length; i++) { - arr.push(writeSimpleLength(this.attributes[i].length)); - arr.push(util.stringToUint8Array(this.attributes[i])); + getName() { + const name = knownOIDs[this.toHex()]; + if (!name) { + throw new Error('Unknown curve object identifier.'); } - return util.concatUint8Array(arr); - } - /** - * Compare for equality - * @param {UserAttributePacket} usrAttr - * @returns {Boolean} True if equal. - */ - equals(usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { - return false; - } - return this.attributes.every(function(attr, index) { - return attr === usrAttr.attributes[index]; - }); + return name; } } // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - * @extends PublicKeyPacket - */ - class SecretKeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.secretKey; - } - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - /** - * Secret-key data - */ - this.keyMaterial = null; - /** - * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - this.isEncrypted = null; - /** - * S2K usage - * @type {enums.symmetric} - */ - this.s2kUsage = 0; - /** - * S2K object - * @type {type/s2k} - */ - this.s2k = null; - /** - * Symmetric algorithm to encrypt the key with - * @type {enums.symmetric} - */ - this.symmetric = null; - /** - * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aead = null; - /** - * Decrypted private parameters, referenced by name - * @type {Object} - */ - this.privateParams = null; - } + function readSimpleLength(bytes) { + let len = 0; + let offset; + const type = bytes[0]; - // 5.5.3. Secret-Key Packet Formats - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param {Uint8Array} bytes - Input string to read the packet from - * @async - */ - async read(bytes) { - // - A Public-Key or Public-Subkey packet, as described above. - let i = await this.readPublicKey(bytes); - const startOfSecretKeyData = i; + if (type < 192) { + [len] = bytes; + offset = 1; + } else if (type < 255) { + len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; + offset = 2; + } else if (type === 255) { + len = util.readNumber(bytes.subarray(1, 1 + 4)); + offset = 5; + } - // - One octet indicating string-to-key usage conventions. Zero - // indicates that the secret-key data is not encrypted. 255 or 254 - // indicates that a string-to-key specifier is being given. Any - // other value is a symmetric-key encryption algorithm identifier. - this.s2kUsage = bytes[i++]; + return { + len: len, + offset: offset + }; + } - // - Only for a version 5 packet, a one-octet scalar octet count of - // the next 4 optional fields. - if (this.version === 5) { - i++; - } + /** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * + * @param {Integer} length - The length to encode + * @returns {Uint8Array} String with openpgp length representation. + */ + function writeSimpleLength(length) { + if (length < 192) { + return new Uint8Array([length]); + } else if (length > 191 && length < 8384) { + /* + * let a = (total data packet length) - 192 let bc = two octet + * representation of a let d = b + 192 + */ + return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); + } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); + } - try { - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one-octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - this.symmetric = bytes[i++]; + function writePartialLength(power) { + if (power < 0 || power > 30) { + throw new Error('Partial Length power must be between 1 and 30'); + } + return new Uint8Array([224 + power]); + } - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - this.aead = bytes[i++]; - } + function writeTag(tag_type) { + /* we're only generating v4 packet headers here */ + return new Uint8Array([0xC0 | tag_type]); + } - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - this.s2k = new S2K(); - i += this.s2k.read(bytes.subarray(i, bytes.length)); + /** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * + * @param {Integer} tag_type - Tag type + * @param {Integer} length - Length of the payload + * @returns {String} String of the header. + */ + function writeHeader(tag_type, length) { + /* we're only generating v4 packet headers here */ + return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); + } - if (this.s2k.type === 'gnu-dummy') { - return; - } - } else if (this.s2kUsage) { - this.symmetric = this.s2kUsage; - } + /** + * Whether the packet type supports partial lengths per RFC4880 + * @param {Integer} tag - Tag type + * @returns {Boolean} String of the header. + */ + function supportsStreaming(tag) { + return [ + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ].includes(tag); + } - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage) { - this.iv = bytes.subarray( - i, - i + mod.getCipher(this.symmetric).blockSize - ); + /** + * Generic static Packet Parser function + * + * @param {Uint8Array | ReadableStream} input - Input stream as string + * @param {Function} callback - Function to call with the parsed packet + * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. + */ + async function readPackets(input, callback) { + const reader = getReader(input); + let writer; + let callbackReturned; + try { + const peekedBytes = await reader.peekBytes(2); + // some sanity checks + if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { + throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); + } + const headerByte = await reader.readByte(); + let tag = -1; + let format = -1; + let packetLength; - i += this.iv.length; - } - } catch (e) { - // if the s2k is unsupported, we still want to support encrypting and verifying with the given key - if (!this.s2kUsage) throw e; // always throw for decrypted keys - this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); - this.isEncrypted = true; + format = 0; // 0 = old format; 1 = new format + if ((headerByte & 0x40) !== 0) { + format = 1; } - // - Only for a version 5 packet, a four-octet scalar octet count for - // the following key material. - if (this.version === 5) { - i += 4; + let packetLengthType; + if (format) { + // new format header + tag = headerByte & 0x3F; // bit 5-0 + } else { + // old format header + tag = (headerByte & 0x3F) >> 2; // bit 5-2 + packetLengthType = headerByte & 0x03; // bit 1-0 } - // - Plain or encrypted multiprecision integers comprising the secret - // key data. These algorithm-specific fields are as described - // below. - this.keyMaterial = bytes.subarray(i); - this.isEncrypted = !!this.s2kUsage; + const packetSupportsStreaming = supportsStreaming(tag); + let packet = null; + if (packetSupportsStreaming) { + if (util.isStream(input) === 'array') { + const arrayStream = new ArrayStream(); + writer = getWriter(arrayStream); + packet = arrayStream; + } else { + const transform = new TransformStream(); + writer = getWriter(transform.writable); + packet = transform.readable; + } + // eslint-disable-next-line callback-return + callbackReturned = callback({ tag, packet }); + } else { + packet = []; + } - if (!this.isEncrypted) { - const cleartext = this.keyMaterial.subarray(0, -2); - if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { - throw new Error('Key checksum mismatch'); + let wasPartialLength; + do { + if (!format) { + // 4.2.1. Old Format Packet Lengths + switch (packetLengthType) { + case 0: + // The packet has a one-octet length. The header is 2 octets + // long. + packetLength = await reader.readByte(); + break; + case 1: + // The packet has a two-octet length. The header is 3 octets + // long. + packetLength = (await reader.readByte() << 8) | await reader.readByte(); + break; + case 2: + // The packet has a four-octet length. The header is 5 + // octets long. + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + break; + default: + // 3 - The packet is of indeterminate length. The header is 1 + // octet long, and the implementation must determine how long + // the packet is. If the packet is in a file, this means that + // the packet extends until the end of the file. In general, + // an implementation SHOULD NOT use indeterminate-length + // packets except where the end of the data will be clear + // from the context, and even then it is better to use a + // definite length, or a new format header. The new format + // headers described below have a mechanism for precisely + // encoding data of indeterminate length. + packetLength = Infinity; + break; + } + } else { // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + const lengthByte = await reader.readByte(); + wasPartialLength = false; + if (lengthByte < 192) { + packetLength = lengthByte; + // 4.2.2.2. Two-Octet Lengths + } else if (lengthByte >= 192 && lengthByte < 224) { + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + // 4.2.2.4. Partial Body Lengths + } else if (lengthByte > 223 && lengthByte < 255) { + packetLength = 1 << (lengthByte & 0x1F); + wasPartialLength = true; + if (!packetSupportsStreaming) { + throw new TypeError('This packet type does not support partial lengths.'); + } + // 4.2.2.3. Five-Octet Lengths + } else { + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + } } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - if (err instanceof UnsupportedError) throw err; - // avoid throwing potentially sensitive errors - throw new Error('Error reading MPIs'); + if (packetLength > 0) { + let bytesRead = 0; + while (true) { + if (writer) await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (packetLength === Infinity) break; + throw new Error('Unexpected end of packet'); + } + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); + if (writer) await writer.write(chunk); + else packet.push(chunk); + bytesRead += value.length; + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); + break; + } + } } + } while (wasPartialLength); + + // If this was not a packet that "supports streaming", we peek to check + // whether it is the last packet in the message. We peek 2 bytes instead + // of 1 because the beginning of this function also peeks 2 bytes, and we + // want to cut a `subarray` of the correct length into `web-stream-tools`' + // `externalBuffer` as a tiny optimization here. + // + // If it *was* a streaming packet (i.e. the data packets), we peek at the + // entire remainder of the stream, in order to forward errors in the + // remainder of the stream to the packet data. (Note that this means we + // read/peek at all signature packets before closing the literal data + // packet, for example.) This forwards MDC errors to the literal data + // stream, for example, so that they don't get lost / forgotten on + // decryptedMessage.packets.stream, which we never look at. + // + // An example of what we do when stream-parsing a message containing + // [ one-pass signature packet, literal data packet, signature packet ]: + // 1. Read the one-pass signature packet + // 2. Peek 2 bytes of the literal data packet + // 3. Parse the one-pass signature packet + // + // 4. Read the literal data packet, simultaneously stream-parsing it + // 5. Peek until the end of the message + // 6. Finish parsing the literal data packet + // + // 7. Read the signature packet again (we already peeked at it in step 5) + // 8. Peek at the end of the stream again (`peekBytes` returns undefined) + // 9. Parse the signature packet + // + // Note that this means that if there's an error in the very end of the + // stream, such as an MDC error, we throw in step 5 instead of in step 8 + // (or never), which is the point of this exercise. + const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); + if (writer) { + await writer.ready; + await writer.close(); + } else { + packet = util.concatUint8Array(packet); + // eslint-disable-next-line callback-return + await callback({ tag, packet }); } - } - - /** - * Creates an OpenPGP key packet for the given key. - * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. - */ - write() { - const serializedPublicKey = this.writePublicKey(); - if (this.unparseableKeyMaterial) { - return util.concatUint8Array([ - serializedPublicKey, - this.unparseableKeyMaterial - ]); + return !nextPacket || !nextPacket.length; + } catch (e) { + if (writer) { + await writer.abort(e); + return true; + } else { + throw e; } - - const arr = [serializedPublicKey]; - arr.push(new Uint8Array([this.s2kUsage])); - - const optionalFieldsArr = []; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one- octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - optionalFieldsArr.push(this.symmetric); - - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - optionalFieldsArr.push(this.aead); - } - - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - optionalFieldsArr.push(...this.s2k.write()); + } finally { + if (writer) { + await callbackReturned; } + reader.releaseLock(); + } + } - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { - optionalFieldsArr.push(...this.iv); - } + class UnsupportedError extends Error { + constructor(...params) { + super(...params); - if (this.version === 5) { - arr.push(new Uint8Array([optionalFieldsArr.length])); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - arr.push(new Uint8Array(optionalFieldsArr)); - if (!this.isDummy()) { - if (!this.s2kUsage) { - this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams); - } + this.name = 'UnsupportedError'; + } + } - if (this.version === 5) { - arr.push(util.writeNumber(this.keyMaterial.length, 4)); - } - arr.push(this.keyMaterial); + // unknown packet types are handled differently depending on the packet criticality + class UnknownPacketError extends UnsupportedError { + constructor(...params) { + super(...params); - if (!this.s2kUsage) { - arr.push(util.writeChecksum(this.keyMaterial)); - } + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - return util.concatUint8Array(arr); - } - - /** - * Check whether secret-key data is available in decrypted form. - * Returns false for gnu-dummy keys and null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return this.isEncrypted === false; + this.name = 'UnknownPacketError'; } + } - /** - * Check whether the key includes secret key material. - * Some secret keys do not include it, and can thus only be used - * for public-key operations (encryption and verification). - * Such keys are: - * - GNU-dummy keys, where the secret material has been stripped away - * - encrypted keys with unsupported S2K or cipher - */ - isMissingSecretKeyMaterial() { - return this.unparseableKeyMaterial !== undefined || this.isDummy(); + class UnparseablePacket { + constructor(tag, rawContent) { + this.tag = tag; + this.rawContent = rawContent; } - /** - * Check whether this is a gnu-dummy key - * @returns {Boolean} - */ - isDummy() { - return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + write() { + return this.rawContent; } + } - /** - * Remove private key material, converting the key to a dummy one. - * The resulting key cannot be used for signing/decrypting but can still verify signatures. - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - makeDummy(config$1 = config) { - if (this.isDummy()) { - return; - } - if (this.isDecrypted()) { - this.clearPrivateParams(); - } - delete this.unparseableKeyMaterial; - this.isEncrypted = null; - this.keyMaterial = null; - this.s2k = new S2K(config$1); - this.s2k.algorithm = 0; - this.s2k.c = 0; - this.s2k.type = 'gnu-dummy'; - this.s2kUsage = 254; - this.symmetric = enums.symmetric.aes256; - } + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2018 Proton Technologies AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param {String} passphrase - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - if (this.isDummy()) { - return; - } - if (!this.isDecrypted()) { - throw new Error('Key packet is already encrypted'); - } - if (!passphrase) { - throw new Error('A non-empty passphrase is required for key encryption.'); - } + /** + * Generate (non-legacy) EdDSA key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} + */ + async function generate$3(algo) { + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']); - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - const cleartext = mod.serializeParams(this.algorithm, this.privateParams); - this.symmetric = enums.symmetric.aes256; - const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); + const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey); - const { blockSize } = mod.getCipher(this.symmetric); - this.iv = mod.random.getRandomBytes(blockSize); + return { + A: new Uint8Array(b64ToUint8Array(publicKey.x)), + seed: b64ToUint8Array(privateKey.d, true) + }; + } catch (err) { + if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux + throw err; + } + const seed = getRandomBytes(getPayloadSize$1(algo)); + const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed); + return { A, seed }; + } - if (config$1.aeadProtect) { - this.s2kUsage = 253; - this.aead = enums.aead.eax; - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } else { - this.s2kUsage = 254; - this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ - cleartext, - await mod.hash.sha1(cleartext, config$1) - ]), this.iv, config$1); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const seed = ed448.utils.randomPrivateKey(); + const A = ed448.getPublicKey(seed); + return { A, seed }; } + default: + throw new Error('Unsupported EdDSA algorithm'); } + } - /** - * Decrypts the private key params which are needed to use the key. - * Successful decryption does not imply key integrity, call validate() to confirm that. - * {@link SecretKeyPacket.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param {String} passphrase - The passphrase for this private key as string - * @throws {Error} if the key is already decrypted, or if decryption was not successful - * @async - */ - async decrypt(passphrase) { - if (this.isDummy()) { - return false; - } + /** + * Sign a message using the provided key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * RS: Uint8Array + * }>} Signature of the message + * @async + */ + async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = privateKeyToJWK(algo, publicKey, privateKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']); - if (this.unparseableKeyMaterial) { - throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); - } + const signature = new Uint8Array( + await webCrypto.sign('Ed25519', key, hashed) + ); - if (this.isDecrypted()) { - throw new Error('Key packet is already decrypted.'); - } + return { RS: signature }; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + const secretKey = util.concatUint8Array([privateKey, publicKey]); + const signature = nacl.sign.detached(hashed, secretKey); + return { RS: signature }; + } - let key; - if (this.s2kUsage === 254 || this.s2kUsage === 253) { - key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2kUsage === 255) { - throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); - } else { - throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const signature = ed448.sign(hashed, privateKey); + return { RS: signature }; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } - let cleartext; - if (this.s2kUsage === 253) { - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); + } + + /** + * Verifies if a signature is valid for a message + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{ RS: Uint8Array }} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ + async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: try { - cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); + const webCrypto = util.getWebCrypto(); + const jwk = publicKeyToJWK(algo, publicKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']); + const verified = await webCrypto.verify('Ed25519', key, RS, hashed); + return verified; } catch (err) { - if (err.message === 'Authentication tag mismatch') { - throw new Error('Incorrect key passphrase: ' + err.message); + if (err.name !== 'NotSupportedError') { + throw err; } - throw err; - } - } else { - const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); - - cleartext = cleartextWithHash.subarray(0, -20); - const hash = await mod.hash.sha1(cleartext); - - if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { - throw new Error('Incorrect key passphrase'); + return nacl.sign.detached.verify(hashed, RS, publicKey); } - } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - throw new Error('Error reading MPIs'); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + return ed448.verify(RS, hashed, publicKey); } - this.isEncrypted = false; - this.keyMaterial = null; - this.s2kUsage = 0; + default: + throw new Error('Unsupported EdDSA algorithm'); } - - /** - * Checks that the key parameters are consistent - * @throws {Error} if validation was not successful - * @async - */ - async validate() { - if (this.isDummy()) { - return; + } + /** + * Validate (non-legacy) EdDSA parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - EdDSA public point + * @param {Uint8Array} seed - EdDSA secret seed + * @param {Uint8Array} oid - (legacy only) EdDSA OID + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$7(algo, A, seed) { + switch (algo) { + case enums.publicKey.ed25519: { + /** + * Derive public point A' from private key + * and expect A == A' + * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(seed); + return util.equalsUint8Array(A, publicKey); } - if (!this.isDecrypted()) { - throw new Error('Key is not decrypted'); - } + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); - let validParams; - try { - // this can throw if some parameters are undefined - validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); - } catch (_) { - validParams = false; - } - if (!validParams) { - throw new Error('Key is invalid'); + const publicKey = ed448.getPublicKey(seed); + return util.equalsUint8Array(A, publicKey); } + default: + return false; } + } - async generate(bits, curve) { - const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); - this.privateParams = privateParams; - this.publicParams = publicParams; - this.isEncrypted = false; - } + function getPayloadSize$1(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return 32; - /** - * Clear private key parameters - */ - clearPrivateParams() { - if (this.isMissingSecretKeyMaterial()) { - return; - } + case enums.publicKey.ed448: + return 57; - Object.keys(this.privateParams).forEach(name => { - const param = this.privateParams[name]; - param.fill(0); - delete this.privateParams[name]; - }); - this.privateParams = null; - this.isEncrypted = true; + default: + throw new Error('Unsupported EdDSA algorithm'); } } - async function produceEncryptionKey(s2k, passphrase, algorithm) { - const { keySize } = mod.getCipher(algorithm); - return s2k.produceKey(passphrase, keySize); + function getPreferredHashAlgo$2(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return enums.hash.sha256; + case enums.publicKey.ed448: + return enums.hash.sha512; + default: + throw new Error('Unknown EdDSA algo'); + } } - var emailAddresses = createCommonjsModule(function (module) { - // email-addresses.js - RFC 5322 email address parser - // v 3.1.0 - // - // http://tools.ietf.org/html/rfc5322 - // - // This library does not validate email addresses. - // emailAddresses attempts to parse addresses using the (fairly liberal) - // grammar specified in RFC 5322. - // - // email-addresses returns { - // ast: , - // addresses: [{ - // node: , - // name: , - // address: , - // local: , - // domain: - // }, ...] - // } - // - // emailAddresses.parseOneAddress and emailAddresses.parseAddressList - // work as you might expect. Try it out. - // - // Many thanks to Dominic Sayers and his documentation on the is_email function, - // http://code.google.com/p/isemail/ , which helped greatly in writing this parser. - - (function (global) { - - function parse5322(opts) { - - // tokenizing functions - - function inStr() { return pos < len; } - function curTok() { return parseString[pos]; } - function getPos() { return pos; } - function setPos(i) { pos = i; } - function nextTok() { pos += 1; } - function initialize() { - pos = 0; - len = parseString.length; - } - - // parser helper functions - - function o(name, value) { - return { - name: name, - tokens: value || "", - semantic: value || "", - children: [] - }; - } - - function wrap(name, ast) { - var n; - if (ast === null) { return null; } - n = o(name); - n.tokens = ast.tokens; - n.semantic = ast.semantic; - n.children.push(ast); - return n; - } - - function add(parent, child) { - if (child !== null) { - parent.tokens += child.tokens; - parent.semantic += child.semantic; - } - parent.children.push(child); - return parent; + const publicKeyToJWK = (algo, publicKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: uint8ArrayToB64(publicKey), + ext: true + }; + return jwk; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } + }; - function compareToken(fxnCompare) { - var tok; - if (!inStr()) { return null; } - tok = curTok(); - if (fxnCompare(tok)) { - nextTok(); - return o('token', tok); - } - return null; + const privateKeyToJWK = (algo, publicKey, privateKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = publicKeyToJWK(algo, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } + }; - function literal(lit) { - return function literalFunc() { - return wrap('literal', compareToken(function (tok) { - return tok === lit; - })); - }; - } + var eddsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + generate: generate$3, + getPayloadSize: getPayloadSize$1, + getPreferredHashAlgo: getPreferredHashAlgo$2, + sign: sign$5, + validateParams: validateParams$7, + verify: verify$5 + }); - function and() { - var args = arguments; - return function andFunc() { - var i, s, result, start; - start = getPos(); - s = o('and'); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result === null) { - setPos(start); - return null; - } - add(s, result); - } - return s; - }; - } + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function or() { - var args = arguments; - return function orFunc() { - var i, result, start; - start = getPos(); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result !== null) { - return result; - } - setPos(start); - } - return null; - }; - } - function opt(prod) { - return function optFunc() { - var result, start; - start = getPos(); - result = prod(); - if (result !== null) { - return result; - } - else { - setPos(start); - return o('opt'); - } - }; - } + const webCrypto$4 = util.getWebCrypto(); + /** + * AES key wrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} dataToWrap + * @returns {Uint8Array} wrapped key + */ + async function wrap(algo, key, dataToWrap) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - function invis(prod) { - return function invisFunc() { - var result = prod(); - if (result !== null) { - result.semantic = ""; - } - return result; - }; + try { + const wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']); + // Import data as HMAC key, as it has no key length requirements + const keyToWrap = await webCrypto$4.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + const wrapped = await webCrypto$4.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' }); + return new Uint8Array(wrapped); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + } - function colwsp(prod) { - return function collapseSemanticWhitespace() { - var result = prod(); - if (result !== null && result.semantic.length > 0) { - result.semantic = " "; - } - return result; - }; - } + return aeskw(key).encrypt(dataToWrap); + } - function star(prod, minimum) { - return function starFunc() { - var s, result, count, start, min; - start = getPos(); - s = o('star'); - count = 0; - min = minimum === undefined ? 0 : minimum; - while ((result = prod()) !== null) { - count = count + 1; - add(s, result); - } - if (count >= min) { - return s; - } - else { - setPos(start); - return null; - } - }; - } + /** + * AES key unwrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} wrappedData + * @returns {Uint8Array} unwrapped data + */ + async function unwrap(algo, key, wrappedData) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - // One expects names to get normalized like this: - // " First Last " -> "First Last" - // "First Last" -> "First Last" - // "First Last" -> "First Last" - function collapseWhitespace(s) { - return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, ''); + let wrappingKey; + try { + wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + return aeskw(key).decrypt(wrappedData); + } - // UTF-8 pseudo-production (RFC 6532) - // RFC 6532 extends RFC 5322 productions to include UTF-8 - // using the following productions: - // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // UTF8-2 = - // UTF8-3 = - // UTF8-4 = - // - // For reference, the extended RFC 5322 productions are: - // VCHAR =/ UTF8-non-ascii - // ctext =/ UTF8-non-ascii - // atext =/ UTF8-non-ascii - // qtext =/ UTF8-non-ascii - // dtext =/ UTF8-non-ascii - function isUTF8NonAscii(tok) { - // In JavaScript, we just deal directly with Unicode code points, - // so we aren't checking individual bytes for UTF-8 encoding. - // Just check that the character is non-ascii. - return tok.charCodeAt(0) >= 128; - } - - - // common productions (RFC 5234) - // http://tools.ietf.org/html/rfc5234 - // B.1. Core Rules - - // CR = %x0D - // ; carriage return - function cr() { return wrap('cr', literal('\r')()); } - - // CRLF = CR LF - // ; Internet standard newline - function crlf() { return wrap('crlf', and(cr, lf)()); } - - // DQUOTE = %x22 - // ; " (Double Quote) - function dquote() { return wrap('dquote', literal('"')()); } - - // HTAB = %x09 - // ; horizontal tab - function htab() { return wrap('htab', literal('\t')()); } - - // LF = %x0A - // ; linefeed - function lf() { return wrap('lf', literal('\n')()); } - - // SP = %x20 - function sp() { return wrap('sp', literal(' ')()); } - - // VCHAR = %x21-7E - // ; visible (printing) characters - function vchar() { - return wrap('vchar', compareToken(function vcharFunc(tok) { - var code = tok.charCodeAt(0); - var accept = (0x21 <= code && code <= 0x7E); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); + try { + const unwrapped = await webCrypto$4.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + return new Uint8Array(await webCrypto$4.exportKey('raw', unwrapped)); + } catch (err) { + if (err.name === 'OperationError') { + throw new Error('Key Data Integrity failed'); } + throw err; + } + } - // WSP = SP / HTAB - // ; white space - function wsp() { return wrap('wsp', or(sp, htab)()); } - - - // email productions (RFC 5322) - // http://tools.ietf.org/html/rfc5322 - // 3.2.1. Quoted characters - - // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp - function quotedPair() { - var qp = wrap('quoted-pair', - or( - and(literal('\\'), or(vchar, wsp)), - obsQP - )()); - if (qp === null) { return null; } - // a quoted pair will be two characters, and the "\" character - // should be semantically "invisible" (RFC 5322 3.2.1) - qp.semantic = qp.semantic[1]; - return qp; - } - - // 3.2.2. Folding White Space and Comments - - // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS - function fws() { - return wrap('fws', or( - obsFws, - and( - opt(and( - star(wsp), - invis(crlf) - )), - star(wsp, 1) - ) - )()); - } - - // ctext = %d33-39 / ; Printable US-ASCII - // %d42-91 / ; characters not including - // %d93-126 / ; "(", ")", or "\" - // obs-ctext - function ctext() { - return wrap('ctext', or( - function ctextFunc1() { - return compareToken(function ctextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 39) || - (42 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsCtext - )()); - } - - // ccontent = ctext / quoted-pair / comment - function ccontent() { - return wrap('ccontent', or(ctext, quotedPair, comment)()); - } - - // comment = "(" *([FWS] ccontent) [FWS] ")" - function comment() { - return wrap('comment', and( - literal('('), - star(and(opt(fws), ccontent)), - opt(fws), - literal(')') - )()); - } - - // CFWS = (1*([FWS] comment) [FWS]) / FWS - function cfws() { - return wrap('cfws', or( - and( - star( - and(opt(fws), comment), - 1 - ), - opt(fws) - ), - fws - )()); - } - - // 3.2.3. Atom - - //atext = ALPHA / DIGIT / ; Printable US-ASCII - // "!" / "#" / ; characters not including - // "$" / "%" / ; specials. Used for atoms. - // "&" / "'" / - // "*" / "+" / - // "-" / "/" / - // "=" / "?" / - // "^" / "_" / - // "`" / "{" / - // "|" / "}" / - // "~" - function atext() { - return wrap('atext', compareToken(function atextFunc(tok) { - var accept = - ('a' <= tok && tok <= 'z') || - ('A' <= tok && tok <= 'Z') || - ('0' <= tok && tok <= '9') || - (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', - '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } + var aesKW = /*#__PURE__*/Object.freeze({ + __proto__: null, + unwrap: unwrap, + wrap: wrap + }); - // atom = [CFWS] 1*atext [CFWS] - function atom() { - return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))()); - } + /** + * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. + * @module crypto/hkdf + */ - // dot-atom-text = 1*atext *("." 1*atext) - function dotAtomText() { - var s, maybeText; - s = wrap('dot-atom-text', star(atext, 1)()); - if (s === null) { return s; } - maybeText = star(and(literal('.'), star(atext, 1)))(); - if (maybeText !== null) { - add(s, maybeText); - } - return s; - } - - // dot-atom = [CFWS] dot-atom-text [CFWS] - function dotAtom() { - return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))()); - } - - // 3.2.4. Quoted Strings - - // qtext = %d33 / ; Printable US-ASCII - // %d35-91 / ; characters not including - // %d93-126 / ; "\" or the quote character - // obs-qtext - function qtext() { - return wrap('qtext', or( - function qtextFunc1() { - return compareToken(function qtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 === code) || - (35 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsQtext - )()); - } - // qcontent = qtext / quoted-pair - function qcontent() { - return wrap('qcontent', or(qtext, quotedPair)()); - } + const webCrypto$3 = util.getWebCrypto(); - // quoted-string = [CFWS] - // DQUOTE *([FWS] qcontent) [FWS] DQUOTE - // [CFWS] - function quotedString() { - return wrap('quoted-string', and( - invis(opt(cfws)), - invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), - invis(opt(cfws)) - )()); - } + async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { + const hash = enums.read(enums.webHash, hashAlgo); + if (!hash) throw new Error('Hash algo not supported with HKDF'); - // 3.2.5 Miscellaneous Tokens + const importedKey = await webCrypto$3.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto$3.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + return new Uint8Array(bits); + } - // word = atom / quoted-string - function word() { - return wrap('word', or(atom, quotedString)()); - } + /** + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @module crypto/public_key/elliptic/ecdh + */ - // phrase = 1*word / obs-phrase - function phrase() { - return wrap('phrase', or(obsPhrase, star(word, 1))()); - } - // 3.4. Address Specification - // address = mailbox / group - function address() { - return wrap('address', or(mailbox, group)()); - } + const HKDF_INFO = { + x25519: util.encodeUTF8('OpenPGP X25519'), + x448: util.encodeUTF8('OpenPGP X448') + }; - // mailbox = name-addr / addr-spec - function mailbox() { - return wrap('mailbox', or(nameAddr, addrSpec)()); + /** + * Generate ECDH key for Montgomery curves + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} + */ + async function generate$2(algo) { + switch (algo) { + case enums.publicKey.x25519: { + // k stays in little-endian, unlike legacy ECDH over curve25519 + const k = getRandomBytes(32); + const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k); + return { A, k }; } - // name-addr = [display-name] angle-addr - function nameAddr() { - return wrap('name-addr', and(opt(displayName), angleAddr)()); + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const k = x448.utils.randomPrivateKey(); + const A = x448.getPublicKey(k); + return { A, k }; } + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / - // obs-angle-addr - function angleAddr() { - return wrap('angle-addr', or( - and( - invis(opt(cfws)), - literal('<'), - addrSpec, - literal('>'), - invis(opt(cfws)) - ), - obsAngleAddr - )()); + /** + * Validate ECDH parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - ECDH public point + * @param {Uint8Array} k - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$6(algo, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + /** + * Derive public point A' from private key + * and expect A == A' + */ + const { publicKey } = nacl.box.keyPair.fromSecretKey(k); + return util.equalsUint8Array(A, publicKey); } - - // group = display-name ":" [group-list] ";" [CFWS] - function group() { - return wrap('group', and( - displayName, - literal(':'), - opt(groupList), - literal(';'), - invis(opt(cfws)) - )()); + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + /** + * Derive public point A' from private key + * and expect A == A' + */ + const publicKey = x448.getPublicKey(k); + return util.equalsUint8Array(A, publicKey); } - // display-name = phrase - function displayName() { - return wrap('display-name', function phraseFixedSemantic() { - var result = phrase(); - if (result !== null) { - result.semantic = collapseWhitespace(result.semantic); - } - return result; - }()); - } - - // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list - function mailboxList() { - return wrap('mailbox-list', or( - and( - mailbox, - star(and(literal(','), mailbox)) - ), - obsMboxList - )()); - } - - // address-list = (address *("," address)) / obs-addr-list - function addressList() { - return wrap('address-list', or( - and( - address, - star(and(literal(','), address)) - ), - obsAddrList - )()); - } - - // group-list = mailbox-list / CFWS / obs-group-list - function groupList() { - return wrap('group-list', or( - mailboxList, - invis(cfws), - obsGroupList - )()); - } - - // 3.4.1 Addr-Spec Specification - - // local-part = dot-atom / quoted-string / obs-local-part - function localPart() { - // note: quoted-string, dotAtom are proper subsets of obs-local-part - // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree - return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)()); - } - - // dtext = %d33-90 / ; Printable US-ASCII - // %d94-126 / ; characters not including - // obs-dtext ; "[", "]", or "\" - function dtext() { - return wrap('dtext', or( - function dtextFunc1() { - return compareToken(function dtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 90) || - (94 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsDtext - )() - ); - } + default: + return false; + } + } - // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - function domainLiteral() { - return wrap('domain-literal', and( - invis(opt(cfws)), - literal('['), - star(and(opt(fws), dtext)), - opt(fws), - literal(']'), - invis(opt(cfws)) - )()); - } - - // domain = dot-atom / domain-literal / obs-domain - function domain() { - return wrap('domain', function domainCheckTLD() { - var result = or(obsDomain, dotAtom, domainLiteral)(); - if (opts.rejectTLD) { - if (result && result.semantic && result.semantic.indexOf('.') < 0) { - return null; - } - } - // strip all whitespace from domains - if (result) { - result.semantic = result.semantic.replace(/\s+/g, ''); - } - return result; - }()); - } - - // addr-spec = local-part "@" domain - function addrSpec() { - return wrap('addr-spec', and( - localPart, literal('@'), domain - )()); - } - - // 3.6.2 Originator Fields - // Below we only parse the field body, not the name of the field - // like "From:", "Sender:", or "Reply-To:". Other libraries that - // parse email headers can parse those and defer to these productions - // for the "RFC 5322" part. - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // from = "From:" (mailbox-list / address-list) CRLF - function fromSpec() { - return wrap('from', or( - mailboxList, - addressList - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // sender = "Sender:" (mailbox / address) CRLF - function senderSpec() { - return wrap('sender', or( - mailbox, - address - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // reply-to = "Reply-To:" address-list CRLF - function replyToSpec() { - return wrap('reply-to', addressList()); - } - - // 4.1. Miscellaneous Obsolete Tokens - - // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control - // %d11 / ; characters that do not - // %d12 / ; include the carriage - // %d14-31 / ; return, line feed, and - // %d127 ; white space characters - function obsNoWsCtl() { - return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) { - var code = tok.charCodeAt(0); - return ((1 <= code && code <= 8) || - (11 === code || 12 === code) || - (14 <= code && code <= 31) || - (127 === code)); - })); + /** + * Wrap and encrypt a session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} data - session key data to be encrypted + * @param {Uint8Array} recipientA - Recipient public key (K_B) + * @returns {Promise<{ + * ephemeralPublicKey: Uint8Array, + * wrappedKey: Uint8Array + * }>} ephemeral public key (K_A) and encrypted key + * @async + */ + async function encrypt$2(algo, data, recipientA) { + const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + recipientA, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; } - - // obs-ctext = obs-NO-WS-CTL - function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); } - - // obs-qtext = obs-NO-WS-CTL - function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); } - - // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) - function obsQP() { - return opts.strict ? null : wrap('obs-qp', and( - literal('\\'), - or(literal('\0'), obsNoWsCtl, lf, cr) - )()); - } - - // obs-phrase = word *(word / "." / CFWS) - function obsPhrase() { - if (opts.strict ) return null; - return opts.atInDisplayName ? wrap('obs-phrase', and( - word, - star(or(word, literal('.'), literal('@'), colwsp(cfws))) - )()) : - wrap('obs-phrase', and( - word, - star(or(word, literal('.'), colwsp(cfws))) - )()); - } - - // 4.2. Obsolete Folding White Space - - // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908 - // obs-FWS = 1*([CRLF] WSP) - function obsFws() { - return opts.strict ? null : wrap('obs-FWS', star( - and(invis(opt(crlf)), wsp), - 1 - )()); - } - - // 4.4. Obsolete Addressing - - // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] - function obsAngleAddr() { - return opts.strict ? null : wrap('obs-angle-addr', and( - invis(opt(cfws)), - literal('<'), - obsRoute, - addrSpec, - literal('>'), - invis(opt(cfws)) - )()); - } - - // obs-route = obs-domain-list ":" - function obsRoute() { - return opts.strict ? null : wrap('obs-route', and( - obsDomainList, - literal(':') - )()); - } - - // obs-domain-list = *(CFWS / ",") "@" domain - // *("," [CFWS] ["@" domain]) - function obsDomainList() { - return opts.strict ? null : wrap('obs-domain-list', and( - star(or(invis(cfws), literal(','))), - literal('@'), - domain, - star(and( - literal(','), - invis(opt(cfws)), - opt(and(literal('@'), domain)) - )) - )()); - } - - // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) - function obsMboxList() { - return opts.strict ? null : wrap('obs-mbox-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - mailbox, - star(and( - literal(','), - opt(and( - mailbox, - invis(cfws) - )) - )) - )()); - } - - // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) - function obsAddrList() { - return opts.strict ? null : wrap('obs-addr-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - address, - star(and( - literal(','), - opt(and( - address, - invis(cfws) - )) - )) - )()); - } - - // obs-group-list = 1*([CFWS] ",") [CFWS] - function obsGroupList() { - return opts.strict ? null : wrap('obs-group-list', and( - star(and( - invis(opt(cfws)), - literal(',') - ), 1), - invis(opt(cfws)) - )()); - } - - // obs-local-part = word *("." word) - function obsLocalPart() { - return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))()); - } - - // obs-domain = atom *("." atom) - function obsDomain() { - return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))()); - } - - // obs-dtext = obs-NO-WS-CTL / quoted-pair - function obsDtext() { - return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)()); - } - - ///////////////////////////////////////////////////// - - // ast analysis - - function findNode(name, root) { - var i, stack, node; - if (root === null || root === undefined) { return null; } - stack = [root]; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - return node; - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return null; - } - - function findAllNodes(name, root) { - var i, stack, node, result; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - result.push(node); - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return result; + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; } - function findAllNodesNoChildren(names, root) { - var i, stack, node, result, namesLookup; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - namesLookup = {}; - for (i = 0; i < names.length; i += 1) { - namesLookup[names[i]] = true; - } + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - while (stack.length > 0) { - node = stack.pop(); - if (node.name in namesLookup) { - result.push(node); - // don't look at children (hence findAllNodesNoChildren) - } else { - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - } - return result; + /** + * Decrypt and unwrap the session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} ephemeralPublicKey - (K_A) + * @param {Uint8Array} wrappedKey, + * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF + * @param {Uint8Array} k - Recipient secret key (b) + * @returns {Promise} decrypted session key data + * @async + */ + async function decrypt$2(algo, ephemeralPublicKey, wrappedKey, A, k) { + const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + A, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); } - - function giveResult(ast) { - var addresses, groupsAndMailboxes, i, groupOrMailbox, result; - if (ast === null) { - return null; - } - addresses = []; - - // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'. - groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast); - for (i = 0; i < groupsAndMailboxes.length; i += 1) { - groupOrMailbox = groupsAndMailboxes[i]; - if (groupOrMailbox.name === 'group') { - addresses.push(giveResultGroup(groupOrMailbox)); - } else if (groupOrMailbox.name === 'mailbox') { - addresses.push(giveResultMailbox(groupOrMailbox)); - } - } - - result = { - ast: ast, - addresses: addresses, - }; - if (opts.simple) { - result = simplifyResult(result); - } - if (opts.oneResult) { - return oneResult(result); - } - if (opts.simple) { - return result && result.addresses; - } else { - return result; - } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); } + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - function giveResultGroup(group) { - var i; - var groupName = findNode('display-name', group); - var groupResultMailboxes = []; - var mailboxes = findAllNodesNoChildren(['mailbox'], group); - for (i = 0; i < mailboxes.length; i += 1) { - groupResultMailboxes.push(giveResultMailbox(mailboxes[i])); - } - return { - node: group, - parts: { - name: groupName, - }, - type: group.name, // 'group' - name: grabSemantic(groupName), - addresses: groupResultMailboxes, - }; - } + function getPayloadSize(algo) { + switch (algo) { + case enums.publicKey.x25519: + return 32; - function giveResultMailbox(mailbox) { - var name = findNode('display-name', mailbox); - var aspec = findNode('addr-spec', mailbox); - var cfws = findAllNodes('cfws', mailbox); - var comments = findAllNodesNoChildren(['comment'], mailbox); + case enums.publicKey.x448: + return 56; + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - var local = findNode('local-part', aspec); - var domain = findNode('domain', aspec); - return { - node: mailbox, - parts: { - name: name, - address: aspec, - local: local, - domain: domain, - comments: cfws - }, - type: mailbox.name, // 'mailbox' - name: grabSemantic(name), - address: grabSemantic(aspec), - local: grabSemantic(local), - domain: grabSemantic(domain), - comments: concatComments(comments), - groupName: grabSemantic(mailbox.groupName), - }; + /** + * Generate shared secret and ephemeral public key for encryption + * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret + * @async + */ + async function generateEphemeralEncryptionMaterial(algo, recipientA) { + switch (algo) { + case enums.publicKey.x25519: { + const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo)); + const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const ephemeralSecretKey = x448.utils.randomPrivateKey(); + const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; } + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - function grabSemantic(n) { - return n !== null && n !== undefined ? n.semantic : null; + async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; } - - function simplifyResult(result) { - var i; - if (result && result.addresses) { - for (i = 0; i < result.addresses.length; i += 1) { - delete result.addresses[i].node; - } - } - return result; + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; } + default: + throw new Error('Unsupported ECDH algorithm'); + } + } - function concatComments(comments) { - var result = ''; - if (comments) { - for (var i = 0; i < comments.length; i += 1) { - result += grabSemantic(comments[i]); - } - } - return result; - } + /** + * x25519 and x448 produce an all-zero value when given as input a point with small order. + * This does not lead to a security issue in the context of ECDH, but it is still unexpected, + * hence we throw. + * @param {Uint8Array} sharedSecret + */ + function assertNonZeroArray(sharedSecret) { + let acc = 0; + for (let i = 0; i < sharedSecret.length; i++) { + acc |= sharedSecret[i]; + } + if (acc === 0) { + throw new Error('Unexpected low order point'); + } + } - function oneResult(result) { - if (!result) { return null; } - if (!opts.partial && result.addresses.length > 1) { return null; } - return result.addresses && result.addresses[0]; - } + var ecdh_x = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$2, + encrypt: encrypt$2, + generate: generate$2, + generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial, + getPayloadSize: getPayloadSize, + recomputeSharedSecret: recomputeSharedSecret, + validateParams: validateParams$6 + }); - ///////////////////////////////////////////////////// + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - var parseString, pos, len, parsed, startProduction; - opts = handleOpts(opts, {}); - if (opts === null) { return null; } + const webCrypto$2 = util.getWebCrypto(); + const nodeCrypto$2 = util.getNodeCrypto(); - parseString = opts.input; + const webCurves = { + [enums.curve.nistP256]: 'P-256', + [enums.curve.nistP384]: 'P-384', + [enums.curve.nistP521]: 'P-521' + }; + const knownCurves = nodeCrypto$2 ? nodeCrypto$2.getCurves() : []; + const nodeCurves = nodeCrypto$2 ? { + [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, + [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, + [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, + [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, + [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined, + [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined, + [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, + [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, + [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined + } : {}; - startProduction = { - 'address': address, - 'address-list': addressList, - 'angle-addr': angleAddr, - 'from': fromSpec, - 'group': group, - 'mailbox': mailbox, - 'mailbox-list': mailboxList, - 'reply-to': replyToSpec, - 'sender': senderSpec, - }[opts.startAt] || addressList; + const curves = { + [enums.curve.nistP256]: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.nistP256], + web: webCurves[enums.curve.nistP256], + payloadSize: 32, + sharedSize: 256, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP384]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.nistP384], + web: webCurves[enums.curve.nistP384], + payloadSize: 48, + sharedSize: 384, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP521]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.nistP521], + web: webCurves[enums.curve.nistP521], + payloadSize: 66, + sharedSize: 528, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.secp256k1]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.secp256k1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.ed25519Legacy]: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: enums.publicKey.eddsaLegacy, + hash: enums.hash.sha512, + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.curve25519Legacy]: { + oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: enums.publicKey.ecdh, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.brainpoolP256r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.brainpoolP256r1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP384r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.brainpoolP384r1], + payloadSize: 48, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP512r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.brainpoolP512r1], + payloadSize: 64, + wireFormatLeadingByte: 0x04 + } + }; - if (!opts.strict) { - initialize(); - opts.strict = true; - parsed = startProduction(parseString); - if (opts.partial || !inStr()) { - return giveResult(parsed); - } - opts.strict = false; + class CurveWithOID { + constructor(oidOrName) { + try { + this.name = oidOrName instanceof OID ? + oidOrName.getName() : + enums.write(enums.curve,oidOrName); + } catch (err) { + throw new UnsupportedError('Unknown curve'); } + const params = curves[this.name]; - initialize(); - parsed = startProduction(parseString); - if (!opts.partial && inStr()) { return null; } - return giveResult(parsed); - } - - function parseOneAddressSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'address-list', - })); - } + this.keyType = params.keyType; - function parseAddressListSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'address-list', - })); - } + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node; + this.web = params.web; + this.payloadSize = params.payloadSize; + this.sharedSize = params.sharedSize; + this.wireFormatLeadingByte = params.wireFormatLeadingByte; + if (this.web && util.getWebCrypto()) { + this.type = 'web'; + } else if (this.node && util.getNodeCrypto()) { + this.type = 'node'; + } else if (this.name === enums.curve.curve25519Legacy) { + this.type = 'curve25519Legacy'; + } else if (this.name === enums.curve.ed25519Legacy) { + this.type = 'ed25519Legacy'; + } + } - function parseFromSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'from', - })); + async genKeyPair() { + switch (this.type) { + case 'web': + try { + return await webGenKeyPair(this.name, this.wireFormatLeadingByte); + } catch (err) { + util.printDebugError('Browser did not support generating ec key ' + err.message); + return jsGenKeyPair(this.name); + } + case 'node': + return nodeGenKeyPair(this.name); + case 'curve25519Legacy': { + // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3 + const { k, A } = await generate$2(enums.publicKey.x25519); + const privateKey = k.slice().reverse(); + privateKey[0] = (privateKey[0] & 127) | 64; + privateKey[31] &= 248; + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + case 'ed25519Legacy': { + const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519); + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + default: + return jsGenKeyPair(this.name); + } + } } - function parseSenderSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'sender', - })); + async function generate$1(curveName) { + const curve = new CurveWithOID(curveName); + const { oid, hash, cipher } = curve; + const keyPair = await curve.genKeyPair(); + return { + oid, + Q: keyPair.publicKey, + secret: util.leftPad(keyPair.privateKey, curve.payloadSize), + hash, + cipher + }; } - function parseReplyToSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'reply-to', - })); + /** + * Get preferred hash algo to use with the given curve + * @param {module:type/oid} oid - curve oid + * @returns {enums.hash} hash algorithm + */ + function getPreferredHashAlgo$1(oid) { + return curves[oid.getName()].hash; } - function handleOpts(opts, defs) { - function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; - } - - function isObject(o) { - return o === Object(o); - } + /** + * Validate ECDH and ECDSA parameters + * Not suitable for EdDSA (different secret key format) + * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves + * @param {module:type/oid} oid - EC object identifier + * @param {Uint8Array} Q - EC public point + * @param {Uint8Array} d - EC secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateStandardParams(algo, oid, Q, d) { + const supportedCurves = { + [enums.curve.nistP256]: true, + [enums.curve.nistP384]: true, + [enums.curve.nistP521]: true, + [enums.curve.secp256k1]: true, + [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh, + [enums.curve.brainpoolP256r1]: true, + [enums.curve.brainpoolP384r1]: true, + [enums.curve.brainpoolP512r1]: true + }; - function isNullUndef(o) { - return o === null || o === undefined; - } + // Check whether the given curve is supported + const curveName = oid.getName(); + if (!supportedCurves[curveName]) { + return false; + } - var defaults, o; + if (curveName === enums.curve.curve25519Legacy) { + d = d.slice().reverse(); + // Re-derive public point Q' + const { publicKey } = nacl.box.keyPair.fromSecretKey(d); - if (isString(opts)) { - opts = { input: opts }; - } else if (!isObject(opts)) { - return null; + Q = new Uint8Array(Q); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + if (!util.equalsUint8Array(dG, Q)) { + return false; } - if (!isString(opts.input)) { return null; } - if (!defs) { return null; } - - defaults = { - oneResult: false, - partial: false, - rejectTLD: false, - rfc6532: false, - simple: false, - startAt: 'address-list', - strict: false, - atInDisplayName: false - }; - - for (o in defaults) { - if (isNullUndef(opts[o])) { - opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o]; - } - } - return opts; - } + return true; + } - parse5322.parseOneAddress = parseOneAddressSimple; - parse5322.parseAddressList = parseAddressListSimple; - parse5322.parseFrom = parseFromSimple; - parse5322.parseSender = parseSenderSimple; - parse5322.parseReplyTo = parseReplyToSimple; + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + /* + * Re-derive public point Q' = dG from private key + * Expect Q == Q' + */ + const dG = nobleCurve.getPublicKey(d, false); + if (!util.equalsUint8Array(dG, Q)) { + return false; + } - { - module.exports = parse5322; + return true; } - }()); - }); - - // GPG4Browsers - An OpenPGP implementation in javascript - /** - * Implementation of the User ID Packet (Tag 13) - * - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. + * Check whether the public point has a valid encoding. + * NB: this function does not check e.g. whether the point belongs to the curve. */ - class UserIDPacket { - static get tag() { - return enums.packet.userID; - } + function checkPublicPointEnconding(curve, V) { + const { payloadSize, wireFormatLeadingByte, name: curveName } = curve; - constructor() { - /** A string containing the user id. Usually in the form - * John Doe - * @type {String} - */ - this.userID = ''; + const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2; - this.name = ''; - this.email = ''; - this.comment = ''; + if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) { + throw new Error('Invalid point encoding'); } + } - /** - * Create UserIDPacket instance from object - * @param {Object} userID - Object specifying userID name, email and comment - * @returns {UserIDPacket} - * @static - */ - static fromObject(userID) { - if (util.isString(userID) || - (userID.name && !util.isString(userID.name)) || - (userID.email && !util.isEmailAddress(userID.email)) || - (userID.comment && !util.isString(userID.comment))) { - throw new Error('Invalid user ID format'); - } - const packet = new UserIDPacket(); - Object.assign(packet, userID); - const components = []; - if (packet.name) components.push(packet.name); - if (packet.comment) components.push(`(${packet.comment})`); - if (packet.email) components.push(`<${packet.email}>`); - packet.userID = components.join(' '); - return packet; - } + ////////////////////////// + // // + // Helper functions // + // // + ////////////////////////// + async function jsGenKeyPair(name) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + const privateKey = nobleCurve.utils.randomPrivateKey(); + const publicKey = nobleCurve.getPublicKey(privateKey, false); + return { publicKey, privateKey }; + } - /** - * Parsing function for a user id packet (tag 13). - * @param {Uint8Array} input - Payload of a tag 13 packet - */ - read(bytes, config$1 = config) { - const userID = util.decodeUTF8(bytes); - if (userID.length > config$1.maxUserIDLength) { - throw new Error('User ID string is too long'); - } - try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); - this.comment = comments.replace(/^\(|\)$/g, ''); - this.name = name; - this.email = email; - } catch (e) {} - this.userID = userID; - } + async function webGenKeyPair(name, wireFormatLeadingByte) { + // Note: keys generated with ECDSA and ECDH are structurally equivalent + const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - /** - * Creates a binary representation of the user id packet - * @returns {Uint8Array} Binary representation. - */ - write() { - return util.encodeUTF8(this.userID); - } + const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey); - equals(otherUserID) { - return otherUserID && otherUserID.userID === this.userID; - } + return { + publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte), + privateKey: b64ToUint8Array(privateKey.d) + }; } - // GPG4Browsers - An OpenPGP implementation in javascript + async function nodeGenKeyPair(name) { + // Note: ECDSA and ECDH key generation is structurally equivalent + const ecdh = nodeCrypto$2.createECDH(nodeCurves[name]); + await ecdh.generateKeys(); + return { + publicKey: new Uint8Array(ecdh.getPublicKey()), + privateKey: new Uint8Array(ecdh.getPrivateKey()) + }; + } + + ////////////////////////// + // // + // Helper functions // + // // + ////////////////////////// /** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - * @extends SecretKeyPacket + * @param {JsonWebKey} jwk - key for conversion + * + * @returns {Uint8Array} Raw public key. */ - class SecretSubkeyPacket extends SecretKeyPacket { - static get tag() { - return enums.packet.secretSubkey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - } + function jwkToRawPublic(jwk, wireFormatLeadingByte) { + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); + const publicKey = new Uint8Array(bufX.length + bufY.length + 1); + publicKey[0] = wireFormatLeadingByte; + publicKey.set(bufX, 1); + publicKey.set(bufY, bufX.length + 1); + return publicKey; } /** - * Implementation of the Trust Packet (Tag 12) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key * - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. + * @returns {JsonWebKey} Public key in jwk format. */ - class TrustPacket { - static get tag() { - return enums.packet.trust; - } - - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - */ - read() { - throw new UnsupportedError('Trust packets are not supported'); - } + function rawPublicToJWK(payloadSize, name, publicKey) { + const len = payloadSize; + const bufX = publicKey.slice(1, len + 1); + const bufY = publicKey.slice(len + 1, len * 2 + 1); + // https://www.rfc-editor.org/rfc/rfc7518.txt + const jwk = { + kty: 'EC', + crv: name, + x: uint8ArrayToB64(bufX), + y: uint8ArrayToB64(bufY), + ext: true + }; + return jwk; + } - write() { - throw new UnsupportedError('Trust packets are not supported'); - } + /** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * @param {Uint8Array} privateKey - private key + * + * @returns {JsonWebKey} Private key in jwk format. + */ + function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } - // GPG4Browsers - An OpenPGP implementation in javascript + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // A Signature can contain the following packets - const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + + const webCrypto$1 = util.getWebCrypto(); + const nodeCrypto$1 = util.getNodeCrypto(); /** - * Class that represents an OpenPGP signature. + * Sign a message using the provided key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async */ - class Signature { - /** - * @param {PacketList} packetlist - The signature packets - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); - } - - /** - * Returns binary encoded signature - * @returns {ReadableStream} Binary signature. - */ - write() { - return this.packets.write(); - } - - /** - * Returns ASCII armored text of signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1); + async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (message && !util.isStream(message)) { + const keyPair = { publicKey, privateKey }; + switch (curve.type) { + case 'web': + // If browser doesn't support a curve, we'll catch it + try { + // Need to await to make sure browser succeeds + return await webSign(curve, hashAlgo, message, keyPair); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunaley Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support signing: ' + err.message); + } + break; + case 'node': + return nodeSign(curve, hashAlgo, message, privateKey); + } } - /** - * Returns an array of KeyIDs of all of the issuers who created this signature - * @returns {Array} The Key IDs of the signing keys - */ - getSigningKeyIDs() { - return this.packets.map(packet => packet.issuerKeyID); - } + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + const signature = nobleCurve.sign(hashed, privateKey, { lowS: false }); + return { + r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize), + s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize) + }; } /** - * reads an (optionally armored) OpenPGP signature and returns a signature object - * @param {Object} options - * @param {String} [options.armoredSignature] - Armored signature to be parsed - * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New signature object. + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} message - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} * @async - * @static */ - async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredSignature || binarySignature; - if (!input) { - throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); - } - if (armoredSignature && !util.isString(armoredSignature)) { - throw new Error('readSignature: options.armoredSignature must be a string'); - } - if (binarySignature && !util.isUint8Array(binarySignature)) { - throw new Error('readSignature: options.binarySignature must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + // See https://github.com/openpgpjs/openpgpjs/pull/948. + // NB: the impact was more likely limited to Brainpool curves, since thanks + // to WebCrypto availability, NIST curve should not have been affected. + // Similarly, secp256k1 should have been used rarely enough. + // However, we implement the fix for all curves, since it's only needed in case of + // verification failure, which is unexpected, hence a minor slowdown is acceptable. + const tryFallbackVerificationForOldBug = async () => ( + hashed[0] === 0 ? + jsVerify(curve, signature, hashed.subarray(1), publicKey) : + false + ); - if (armoredSignature) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.signature) { - throw new Error('Armored text not of type signature'); + if (message && !util.isStream(message)) { + switch (curve.type) { + case 'web': + try { + // Need to await to make sure browser succeeds + const verified = await webVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunately Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support verifying: ' + err.message); + } + break; + case 'node': { + const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } } - input = data; } - const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1); - return new Signature(packetlist); - } - - /** - * @fileoverview Provides helpers methods for key module - * @module key/helper - * @private - */ - - async function generateSecretSubkey(options, config) { - const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); - secretSubkeyPacket.packets = null; - secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretSubkeyPacket.generate(options.rsaBits, options.curve); - await secretSubkeyPacket.computeFingerprintAndKeyID(); - return secretSubkeyPacket; - } - async function generateSecretKey(options, config) { - const secretKeyPacket = new SecretKeyPacket(options.date, config); - secretKeyPacket.packets = null; - secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); - await secretKeyPacket.computeFingerprintAndKeyID(); - return secretKeyPacket; + const verified = await jsVerify(curve, signature, hashed, publicKey); + return verified || tryFallbackVerificationForOldBug(); } /** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param {Array} signatures - List of signatures - * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - full configuration - * @returns {Promise} The latest valid signature. + * Validate ECDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDSA public point + * @param {Uint8Array} d - ECDSA secret scalar + * @returns {Promise} Whether params are valid. * @async */ - async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { - let latestValid; - let exception; - for (let i = signatures.length - 1; i >= 0; i--) { - try { - if ( - (!latestValid || signatures[i].created >= latestValid.created) - ) { - await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); - latestValid = signatures[i]; + async function validateParams$5(oid, Q, d) { + const curve = new CurveWithOID(oid); + // Reject curves x25519 and ed25519 + if (curve.keyType !== enums.publicKey.ecdsa) { + return false; + } + + // To speed up the validation, we try to use node- or webcrypto when available + // and sign + verify a random message + switch (curve.type) { + case 'web': + case 'node': { + const message = getRandomBytes(8); + const hashAlgo = enums.hash.sha256; + const hashed = await hash$1.digest(hashAlgo, message); + try { + const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed); + // eslint-disable-next-line @typescript-eslint/return-await + return await verify$4(oid, hashAlgo, signature, message, Q, hashed); + } catch (err) { + return false; } - } catch (e) { - exception = e; } + default: + return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); } - if (!latestValid) { - throw util.wrapError( - `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` - .replace('certGeneric ', 'self-') - .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), - exception); - } - return latestValid; } - function isDataExpired(keyPacket, signature, date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - const expirationTime = getKeyExpirationTime(keyPacket, signature); - return !(keyPacket.created <= normDate && normDate < expirationTime); - } - return false; - } + + ////////////////////////// + // // + // Helper functions // + // // + ////////////////////////// /** - * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} - * @param {SecretSubkeyPacket} subkey - Subkey key packet - * @param {SecretKeyPacket} primaryKey - Primary key packet - * @param {Object} options - * @param {Object} config - Full configuration + * Fallback javascript implementation of ECDSA verification. + * To be used if no native implementation is available for the given curve/operation. */ - async function createBindingSignature(subkey, primaryKey, options, config) { - const dataToSign = {}; - dataToSign.key = primaryKey; - dataToSign.bind = subkey; - const signatureProperties = { signatureType: enums.signature.subkeyBinding }; - if (options.sign) { - signatureProperties.keyFlags = [enums.keyFlags.signData]; - signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, { - signatureType: enums.signature.keyBinding - }, options.date, undefined, undefined, undefined, config); - } else { - signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; - } - const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); - return subkeySignaturePacket; + async function jsVerify(curve, signature, hashed, publicKey) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false }); } - /** - * Returns the preferred signature hash algorithm of a key - * @param {Key} [key] - The key to get preferences from - * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} config - full configuration - * @returns {Promise} - * @async - */ - async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) { - let hashAlgo = config.preferredHashAlgorithm; - let prefAlgo = hashAlgo; - if (key) { - const primaryUser = await key.getPrimaryUser(date, userID, config); - if (primaryUser.selfCertification.preferredHashAlgorithms) { - [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; - } - } - switch (keyPacket.algorithm) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ed25519: - prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid); + async function webSign(curve, hashAlgo, message, keyPair) { + const len = curve.payloadSize; + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['sign'] + ); + + const signature = new Uint8Array(await webCrypto$1.sign( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + message + )); + + return { + r: signature.slice(0, len), + s: signature.slice(len, len << 1) + }; + } + + async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['verify'] + ); + + const signature = util.concatUint8Array([r, s]).buffer; + + return webCrypto$1.verify( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + signature, + message + ); + } + + async function nodeSign(curve, hashAlgo, message, privateKey) { + // JWT encoding cannot be used for now, as Brainpool curves are not supported + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + privateKey: nodeBuffer.from(privateKey) + }); + + const sign = nodeCrypto$1.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(message); + sign.end(); + + const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' })); + const len = curve.payloadSize; + + return { + r: signature.subarray(0, len), + s: signature.subarray(len, len << 1) + }; + } + + async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { publicKey: derPublicKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + publicKey: nodeBuffer.from(publicKey) + }); + + const verify = nodeCrypto$1.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(message); + verify.end(); + + const signature = util.concatUint8Array([r, s]); + + try { + return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature); + } catch (err) { + return false; } - return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; } - /** - * Returns the preferred symmetric/aead/compression algorithm for a set of keys - * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return - * @param {Array} [keys] - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Preferred algorithm - * @async - */ - async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) { - const defaultAlgo = { // these are all must-implement in rfc4880bis - 'symmetric': enums.symmetric.aes128, - 'aead': enums.aead.eax, - 'compression': enums.compression.uncompressed - }[type]; - const preferredSenderAlgo = { - 'symmetric': config$1.preferredSymmetricAlgorithm, - 'aead': config$1.preferredAEADAlgorithm, - 'compression': config$1.preferredCompressionAlgorithm - }[type]; - const prefPropertyName = { - 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAEADAlgorithms', - 'compression': 'preferredCompressionAlgorithms' - }[type]; + var ecdsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$4, + validateParams: validateParams$5, + verify: verify$4 + }); + + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2018 Proton Technologies AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // if preferredSenderAlgo appears in the prefs of all recipients, we pick it - // otherwise we use the default algo - // if no keys are available, preferredSenderAlgo is returned - const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; - return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; - })); - return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; - } /** - * Create signature packet - * @param {Object} dataToSign - Contains packets to be signed - * @param {PrivateKey} privateKey - key to get preferences from - * @param {SecretKeyPacket| - * SecretSubkeyPacket} signingKeyPacket secret key packet for signing - * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing - * @param {Date} [date] - Override the creationtime of the signature - * @param {Object} [userID] - User ID - * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [detached] - Whether to create a detached signature packet - * @param {Object} config - full configuration - * @returns {Promise} Signature packet. + * Sign a message using the provided legacy EdDSA key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async */ - async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) { - if (signingKeyPacket.isDummy()) { - throw new Error('Cannot sign with a gnu-dummy key.'); - } - if (!signingKeyPacket.isDecrypted()) { - throw new Error('Signing key is not decrypted.'); + async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); } - const signaturePacket = new SignaturePacket(); - Object.assign(signaturePacket, signatureProperties); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config); - signaturePacket.rawNotations = notations; - await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached); - return signaturePacket; + const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed); + // EdDSA signature params are returned in little-endian format + return { + r: signature.subarray(0, 32), + s: signature.subarray(32) + }; } /** - * Merges signatures from source[attr] to dest[attr] - * @param {Object} source - * @param {Object} dest - * @param {String} attr - * @param {Date} [date] - date to use for signature expiration check, instead of the current time - * @param {Function} [checkFn] - signature only merged if true + * Verifies if a legacy EdDSA signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async */ - async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { - source = source[attr]; - if (source) { - if (!dest[attr].length) { - dest[attr] = source; - } else { - await Promise.all(source.map(async function(sourceSig) { - if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && - !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); - })) { - dest[attr].push(sourceSig); - } - })); - } + async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); } + const RS = util.concatUint8Array([r, s]); + return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed); } - /** - * Checks if a given certificate or binding signature is revoked - * @param {SecretKeyPacket| - * PublicKeyPacket} primaryKey The primary key packet - * @param {Object} dataToVerify - The data to check - * @param {Array} revocations - The revocation signatures to check - * @param {SignaturePacket} signature - The certificate or signature to check - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the signature revokes the data. + * Validate legacy EdDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - EdDSA public point + * @param {Uint8Array} k - EdDSA secret seed + * @returns {Promise} Whether params are valid. * @async */ - async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { - key = key || primaryKey; - const revocationKeyIDs = []; - await Promise.all(revocations.map(async function(revocationSignature) { - try { - if ( - // Note: a third-party revocation signature could legitimately revoke a - // self-signature if the signature has an authorized revocation key. - // However, we don't support passing authorized revocation keys, nor - // verifying such revocation signatures. Instead, we indicate an error - // when parsing a key with an authorized revocation key, and ignore - // third-party revocation signatures here. (It could also be revoking a - // third-party key certification, which should only affect - // `verifyAllCertifications`.) - !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) - ) { - await revocationSignature.verify( - key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config - ); - - // TODO get an identifier of the revoked object instead - revocationKeyIDs.push(revocationSignature.issuerKeyID); - } - } catch (e) {} - })); - // TODO further verify that this is the signature that should be revoked - if (signature) { - signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : - signature.revoked || false; - return signature.revoked; + async function validateParams$4(oid, Q, k) { + // Check whether the given curve is supported + if (oid.getName() !== enums.curve.ed25519Legacy) { + return false; } - return revocationKeyIDs.length > 0; + + /** + * Derive public point Q' = dG from private key + * and expect Q == Q' + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(k); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + return util.equalsUint8Array(Q, dG); + } + var eddsa_legacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$3, + validateParams: validateParams$4, + verify: verify$3 + }); + + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * Returns key expiration time based on the given certification signature. - * The expiration time of the signature is ignored. - * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check - * @param {SignaturePacket} signature - signature to process - * @returns {Date|Infinity} expiration time or infinity if the key does not expire + * @fileoverview Functions to add and remove PKCS5 padding + * @see PublicKeyEncryptedSessionKeyPacket + * @module crypto/pkcs5 + * @private */ - function getKeyExpirationTime(keyPacket, signature) { - let expirationTime; - // check V4 expiration time - if (signature.keyNeverExpires === false) { - expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; - } - return expirationTime ? new Date(expirationTime) : Infinity; + + /** + * Add pkcs5 padding to a message + * @param {Uint8Array} message - message to pad + * @returns {Uint8Array} Padded message. + */ + function encode(message) { + const c = 8 - (message.length % 8); + const padded = new Uint8Array(message.length + c).fill(c); + padded.set(message); + return padded; } /** - * Returns whether aead is supported by all keys in the set - * @param {Array} keys - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} config - full configuration - * @returns {Promise} - * @async + * Remove pkcs5 padding from a message + * @param {Uint8Array} message - message to remove padding from + * @returns {Uint8Array} Message without padding. */ - async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) { - let supported = true; - // TODO replace when Promise.some or Promise.any are implemented - await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - if (!primaryUser.selfCertification.features || - !(primaryUser.selfCertification.features[0] & enums.features.aead)) { - supported = false; + function decode$1(message) { + const len = message.length; + if (len > 0) { + const c = message[len - 1]; + if (c >= 1) { + const provided = message.subarray(len - c); + const computed = new Uint8Array(c).fill(c); + if (util.equalsUint8Array(provided, computed)) { + return message.subarray(0, len - c); + } } - })); - return supported; + } + throw new Error('Invalid padding'); } - function sanitizeKeyOptions(options, subkeyDefaults = {}) { - options.type = options.type || subkeyDefaults.type; - options.curve = options.curve || subkeyDefaults.curve; - options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; - options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; - - options.sign = options.sign || false; + var pkcs5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: decode$1, + encode: encode + }); - switch (options.type) { - case 'ecc': - try { - options.curve = enums.write(enums.curve, options.curve); - } catch (e) { - throw new Error('Unknown curve'); - } - if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) { - options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; - } - if (options.sign) { - options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; - } else { - options.algorithm = enums.publicKey.ecdh; - } - break; - case 'rsa': - options.algorithm = enums.publicKey.rsaEncryptSign; - break; - default: - throw new Error(`Unsupported key type ${options.type}`); - } - return options; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + const webCrypto = util.getWebCrypto(); + const nodeCrypto = util.getNodeCrypto(); + + /** + * Validate ECDH parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDH public point + * @param {Uint8Array} d - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$3(oid, Q, d) { + return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); } - function isValidSigningKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.rsaEncrypt && - keyAlgo !== enums.publicKey.elgamal && - keyAlgo !== enums.publicKey.ecdh && - keyAlgo !== enums.publicKey.x25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.signData) !== 0); - } - - function isValidEncryptionKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.dsa && - keyAlgo !== enums.publicKey.rsaSign && - keyAlgo !== enums.publicKey.ecdsa && - keyAlgo !== enums.publicKey.eddsaLegacy && - keyAlgo !== enums.publicKey.ed25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0); + // Build Param for ECDH algorithm (RFC 6637) + function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { + return util.concatUint8Array([ + oid.write(), + new Uint8Array([public_algo]), + kdfParams.write(), + util.stringToUint8Array('Anonymous Sender '), + fingerprint + ]); } - function isValidDecryptionKeyPacket(signature, config) { - if (config.allowInsecureDecryptionWithSigningKeys) { - // This is only relevant for RSA keys, all other signing algorithms cannot decrypt - return true; + // Key Derivation Function (RFC 6637) + async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { + // Note: X is little endian for Curve25519, big-endian for all others. + // This is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + let i; + if (stripLeading) { + // Work around old go crypto bug + for (i = 0; i < X.length && X[i] === 0; i++); + X = X.subarray(i); } - - return !signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + if (stripTrailing) { + // Work around old OpenPGP.js bug + for (i = X.length - 1; i >= 0 && X[i] === 0; i--); + X = X.subarray(0, i + 1); + } + const digest = await hash$1.digest(hashAlgo, util.concatUint8Array([ + new Uint8Array([0, 0, 0, 1]), + X, + param + ])); + return digest.subarray(0, length); } /** - * Check key against blacklisted algorithms and minimum strength requirements. - * @param {SecretKeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket - * @param {Config} config - * @throws {Error} if the key packet does not meet the requirements + * Generate ECDHE ephemeral key and secret from public key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async */ - function checkKeyRequirements(keyPacket, config) { - const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); - const algoInfo = keyPacket.getAlgorithmInfo(); - if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { - throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); - } - switch (keyAlgo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: - case enums.publicKey.rsaEncrypt: - if (algoInfo.bits < config.minRSABits) { - throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); - } - break; - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ecdh: - if (config.rejectCurves.has(algoInfo.curve)) { - throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); + async function genPublicEphemeralKey(curve, Q) { + switch (curve.type) { + case 'curve25519Legacy': { + const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1)); + const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]); + return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPublicEphemeralKey(curve, Q); + } catch (err) { + util.printDebugError(err); + return jsPublicEphemeralKey(curve, Q); + } } break; + case 'node': + return nodePublicEphemeralKey(curve, Q); + default: + return jsPublicEphemeralKey(curve, Q); + } } /** - * @module key/User - * @private - */ - - /** - * Class that represents an user ID or attribute packet and the relevant signatures. - * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info - * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} data - Unpadded session key data + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} + * @async */ - class User { - constructor(userPacket, mainKey) { - this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; - this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; - this.selfCertifications = []; - this.otherCertifications = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } - - /** - * Transforms structured user data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.userID || this.userAttribute); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.selfCertifications); - packetlist.push(...this.otherCertifications); - return packetlist; - } + async function encrypt$1(oid, kdfParams, data, Q, fingerprint) { + const m = encode(data); - /** - * Shallow clone - * @returns {User} - */ - clone() { - const user = new User(this.userID || this.userAttribute, this.mainKey); - user.selfCertifications = [...this.selfCertifications]; - user.otherCertifications = [...this.otherCertifications]; - user.revocationSignatures = [...this.revocationSignatures]; - return user; - } - - /** - * Generate third-party certifications over this user and its primary key - * @param {Array} signingKeys - Decrypted private keys for signing - * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} New user with new certifications. - * @async - */ - async certify(signingKeys, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { - if (!privateKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - if (privateKey.hasSameFingerprintAs(primaryKey)) { - throw new Error("The user's own key can only be used for self-certifications"); - } - const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); - return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, { - // Most OpenPGP implementations use generic certification (0x10) - signatureType: enums.signature.certGeneric, - keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] - }, date, undefined, undefined, undefined, config); - })); - await user.update(this, date, config); - return user; - } - - /** - * Checks if a given certificate of the user is revoked - * @param {SignaturePacket} certificate - The certificate to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked(primaryKey, enums.signature.certRevocation, { - key: primaryKey, - userID: this.userID, - userAttribute: this.userAttribute - }, this.revocationSignatures, certificate, keyPacket, date, config$1); - } - - /** - * Verifies the user certificate. - * @param {SignaturePacket} certificate - A certificate of this user - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate - * @throws if the user certificate is invalid. - * @async - */ - async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const { issuerKeyID } = certificate; - const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); - if (issuerKeys.length === 0) { - return null; - } - await Promise.all(issuerKeys.map(async key => { - const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); - if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { - throw new Error('User certificate is revoked'); - } - try { - await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('User certificate is invalid', e); - } - })); - return true; - } + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); + const wrappedKey = await wrap(kdfParams.cipher, Z, m); + return { publicKey, wrappedKey }; + } - /** - * Verifies all user certificates - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllCertifications(verificationKeys, date = new Date(), config) { - const that = this; - const certifications = this.selfCertifications.concat(this.otherCertifications); - return Promise.all(certifications.map(async certification => ({ - keyID: certification.issuerKeyID, - valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) - }))); + /** + * Generate ECDHE secret from private key and public part of ephemeral key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ + async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; } - - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} Status of user. - * @throws {Error} if there are no valid self signatures. - * @async - */ - async verify(date = new Date(), config) { - if (!this.selfCertifications.length) { - throw new Error('No self-certifications found'); + switch (curve.type) { + case 'curve25519Legacy': { + const secretKey = d.slice().reverse(); + const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey); + return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // TODO replace when Promise.some or Promise.any are implemented - let exception; - for (let i = this.selfCertifications.length - 1; i >= 0; i--) { - try { - const selfCertification = this.selfCertifications[i]; - if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { - throw new Error('Self-certification is revoked'); - } + case 'web': + if (curve.web && util.getWebCrypto()) { try { - await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('Self-certification is invalid', e); + return await webPrivateEphemeralKey(curve, V, Q, d); + } catch (err) { + util.printDebugError(err); + return jsPrivateEphemeralKey(curve, V, d); } - return true; - } catch (e) { - exception = e; } - } - throw exception; + break; + case 'node': + return nodePrivateEphemeralKey(curve, V, d); + default: + return jsPrivateEphemeralKey(curve, V, d); } + } - /** - * Update user with new components from specified user - * @param {User} sourceUser - Source user to merge - * @param {Date} date - Date to verify the validity of signatures - * @param {Object} config - Full configuration - * @returns {Promise} - * @async - */ - async update(sourceUser, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // self signatures - await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { - try { - await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); - return true; - } catch (e) { - return false; - } - }); - // other signatures - await mergeSignatures(sourceUser, this, 'otherCertifications', date); - // revocation signatures - await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); - }); + /** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} C - Encrypted and wrapped value derived from session key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise} Value derived from session key. + * @async + */ + async function decrypt$1(oid, kdfParams, V, C, Q, d, fingerprint) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + checkPublicPointEnconding(curve, V); + const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + let err; + for (let i = 0; i < 3; i++) { + try { + // Work around old go crypto bug and old OpenPGP.js bug, respectively. + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); + return decode$1(await unwrap(kdfParams.cipher, Z, C)); + } catch (e) { + err = e; + } } + throw err; + } - /** - * Revokes the user - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New user with revocation signature. - * @async - */ - async revoke( - primaryKey, + async function jsPrivateEphemeralKey(curve, V, d) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V); + const sharedKey = sharedSecretWithParity.subarray(1); + return { secretKey: d, sharedKey }; + } + + async function jsPublicEphemeralKey(curve, Q) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + const { publicKey: V, privateKey: v } = await curve.genKeyPair(); + + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q); + const sharedKey = sharedSecretWithParity.subarray(1); + return { publicKey: V, sharedKey }; + } + + /** + * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ + async function webPrivateEphemeralKey(curve, V, Q, d) { + const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d); + let privateKey = webCrypto.importKey( + 'jwk', + recipient, { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.certRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await user.update(this); - return user; - } + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V); + let sender = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + [] + ); + [privateKey, sender] = await Promise.all([privateKey, sender]); + let S = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: sender + }, + privateKey, + curve.sharedSize + ); + let secret = webCrypto.exportKey( + 'jwk', + privateKey + ); + [S, secret] = await Promise.all([S, secret]); + const sharedKey = new Uint8Array(S); + const secretKey = b64ToUint8Array(secret.d); + return { secretKey, sharedKey }; + } + + /** + * Generate ECDHE ephemeral key and secret from public key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ + async function webPublicEphemeralKey(curve, Q) { + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q); + let keyPair = webCrypto.generateKey( + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + let recipient = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + false, + [] + ); + [keyPair, recipient] = await Promise.all([keyPair, recipient]); + let s = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: recipient + }, + keyPair.privateKey, + curve.sharedSize + ); + let p = webCrypto.exportKey( + 'jwk', + keyPair.publicKey + ); + [s, p] = await Promise.all([s, p]); + const sharedKey = new Uint8Array(s); + const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte)); + return { publicKey, sharedKey }; + } + + /** + * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ + async function nodePrivateEphemeralKey(curve, V, d) { + const recipient = nodeCrypto.createECDH(curve.node); + recipient.setPrivateKey(d); + const sharedKey = new Uint8Array(recipient.computeSecret(V)); + const secretKey = new Uint8Array(recipient.getPrivateKey()); + return { secretKey, sharedKey }; + } + + /** + * Generate ECDHE ephemeral key and secret from public key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ + async function nodePublicEphemeralKey(curve, Q) { + const sender = nodeCrypto.createECDH(curve.node); + sender.generateKeys(); + const sharedKey = new Uint8Array(sender.computeSecret(Q)); + const publicKey = new Uint8Array(sender.getPublicKey()); + return { publicKey, sharedKey }; } + var ecdh = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$1, + encrypt: encrypt$1, + validateParams: validateParams$3 + }); + + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + var elliptic = /*#__PURE__*/Object.freeze({ + __proto__: null, + CurveWithOID: CurveWithOID, + ecdh: ecdh, + ecdhX: ecdh_x, + ecdsa: ecdsa, + eddsa: eddsa, + eddsaLegacy: eddsa_legacy, + generate: generate$1, + getPreferredHashAlgo: getPreferredHashAlgo$1 + }); + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 + */ + + const _0n$7 = BigInt(0); + const _1n$9 = BigInt(1); + /** - * @module key/Subkey - * @private + * DSA Sign function + * @param {Integer} hashAlgo + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} x + * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} + * @async */ + async function sign$2(hashAlgo, hashed, g, p, q, x) { + const _0n = BigInt(0); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + x = uint8ArrayToBigInt(x); + + let k; + let r; + let s; + let t; + g = mod$2(g, p); + x = mod$2(x, q); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + while (true) { + // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + k = getRandomBigInteger(_1n$9, q); // returns in [1, q-1] + r = mod$2(modExp(g, k, p), q); // (g**k mod p) mod q + if (r === _0n) { + continue; + } + const xr = mod$2(x * r, q); + t = mod$2(h + xr, q); // H(m) + x*r mod q + s = mod$2(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q + if (s === _0n) { + continue; + } + break; + } + return { + r: bigIntToUint8Array(r, 'be', byteLength(p)), + s: bigIntToUint8Array(s, 'be', byteLength(p)) + }; + } /** - * Class that represents a subkey packet and the relevant signatures. - * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID - * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint - * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs - * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo - * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime - * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + * DSA Verify function + * @param {Integer} hashAlgo + * @param {Uint8Array} r + * @param {Uint8Array} s + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} y + * @returns {boolean} + * @async */ - class Subkey { - /** - * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey - * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey - */ - constructor(subkeyPacket, mainKey) { - this.keyPacket = subkeyPacket; - this.bindingSignatures = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } + async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) { + r = uint8ArrayToBigInt(r); + s = uint8ArrayToBigInt(s); - /** - * Transforms structured subkey data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.bindingSignatures); - return packetlist; - } + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - /** - * Shallow clone - * @return {Subkey} - */ - clone() { - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.bindingSignatures = [...this.bindingSignatures]; - subkey.revocationSignatures = [...this.revocationSignatures]; - return subkey; + if (r <= _0n$7 || r >= q || + s <= _0n$7 || s >= q) { + util.printDebug('invalid DSA Signature'); + return false; } - - /** - * Checks if a binding signature of a subkey is revoked - * @param {SignaturePacket} signature - The binding signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the binding signature is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked( - primaryKey, enums.signature.subkeyRevocation, { - key: primaryKey, - bind: this.keyPacket - }, this.revocationSignatures, signature, key, date, config$1 - ); + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + const w = modInv(s, q); // s**-1 mod q + if (w === _0n$7) { + util.printDebug('invalid DSA Signature'); + return false; } - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} if the subkey is invalid. - * @async - */ - async verify(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - // check subkey binding signatures - const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - // check binding signature is not revoked - if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { - throw new Error('Subkey is revoked'); - } - // check for expiration time - if (isDataExpired(this.keyPacket, bindingSignature, date)) { - throw new Error('Subkey is expired'); - } - return bindingSignature; + g = mod$2(g, p); + y = mod$2(y, p); + const u1 = mod$2(h * w, q); // H(m) * w mod q + const u2 = mod$2(r * w, q); // r * w mod q + const t1 = modExp(g, u1, p); // g**u1 mod p + const t2 = modExp(y, u2, p); // y**u2 mod p + const v = mod$2(mod$2(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q + return v === r; + } + + /** + * Validate DSA parameters + * @param {Uint8Array} p - DSA prime + * @param {Uint8Array} q - DSA group order + * @param {Uint8Array} g - DSA sub-group generator + * @param {Uint8Array} y - DSA public key + * @param {Uint8Array} x - DSA private key + * @returns {Promise} Whether params are valid. + * @async + */ + async function validateParams$2(p, q, g, y, x) { + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + // Check that 1 < g < p + if (g <= _1n$9 || g >= p) { + return false; } /** - * Returns the expiration time of the subkey or Infinity if key does not expire. - * Returns null if the subkey is invalid. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async + * Check that subgroup order q divides p-1 */ - async getExpirationTime(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - let bindingSignature; - try { - bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - } catch (e) { - return null; - } - const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); - const sigExpiry = bindingSignature.getExpirationTime(); - return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; + if (mod$2(p - _1n$9, q) !== _0n$7) { + return false; } /** - * Update subkey with new components from specified subkey - * @param {Subkey} subkey - Source subkey to merge - * @param {Date} [date] - Date to verify validity of signatures - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if update failed - * @async - */ - async update(subkey, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - if (!this.hasSameFingerprintAs(subkey)) { - throw new Error('Subkey update method: fingerprints of subkeys not equal'); - } - // key packet - if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && - subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { - this.keyPacket = subkey.keyPacket; - } - // update missing binding signatures - const that = this; - const dataToVerify = { key: primaryKey, bind: that.keyPacket }; - await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { - for (let i = 0; i < that.bindingSignatures.length; i++) { - if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { - if (srcBindSig.created > that.bindingSignatures[i].created) { - that.bindingSignatures[i] = srcBindSig; - } - return false; - } - } - try { - await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); - return true; - } catch (e) { - return false; - } - }); - // revocation signatures - await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); - }); + * g has order q + * Check that g ** q = 1 mod p + */ + if (modExp(g, q, p) !== _1n$9) { + return false; } /** - * Revokes the subkey - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New subkey with revocation signature. - * @async + * Check q is large and probably prime (we mainly want to avoid small factors) */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { key: primaryKey, bind: this.keyPacket }; - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.subkeyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await subkey.update(this); - return subkey; + const qSize = BigInt(bitLength(q)); + const _150n = BigInt(150); + if (qSize < _150n || !isProbablePrime(q, null, 32)) { + return false; } - hasSameFingerprintAs(other) { - return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{rq + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const _2n = BigInt(2); + const r = getRandomBigInteger(_2n << (qSize - _1n$9), _2n << qSize); // draw r of same size as q + const rqx = q * r + x; + if (y !== modExp(g, rqx, p)) { + return false; } + + return true; } - ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { - Subkey.prototype[name] = - function() { - return this.keyPacket[name](); - }; + var dsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$2, + validateParams: validateParams$2, + verify: verify$2 }); - // GPG4Browsers - An OpenPGP implementation in javascript - - // A key revocation certificate can contain the following packets - const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); - const keyPacketTags = new Set([ - enums.packet.publicKey, enums.packet.privateKey, - enums.packet.publicSubkey, enums.packet.privateSubkey - ]); - /** - * Abstract class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. - * @borrows PublicKeyPacket#getKeyID as Key#getKeyID - * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint - * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs - * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo - * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + * @fileoverview Asymmetric cryptography functions + * @module crypto/public_key */ - class Key { - /** - * Transforms packetlist to structured key data - * @param {PacketList} packetlist - The packets that form a key - * @param {Set} disallowedPackets - disallowed packet tags - */ - packetListToStructure(packetlist, disallowedPackets = new Set()) { - let user; - let primaryKeyID; - let subkey; - let ignoreUntil; - for (const packet of packetlist) { - if (packet instanceof UnparseablePacket) { - const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); - if (isUnparseableKeyPacket && !ignoreUntil) { - // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must - // discard all non-key packets that follow, until another (sub)key packet is found. - if (mainKeyPacketTags.has(packet.tag)) { - ignoreUntil = mainKeyPacketTags; - } else { - ignoreUntil = keyPacketTags; - } - } - continue; - } + var publicKey = { + /** @see module:crypto/public_key/rsa */ + rsa: rsa, + /** @see module:crypto/public_key/elgamal */ + elgamal: elgamal, + /** @see module:crypto/public_key/elliptic */ + elliptic: elliptic, + /** @see module:crypto/public_key/dsa */ + dsa: dsa + }; - const tag = packet.constructor.tag; - if (ignoreUntil) { - if (!ignoreUntil.has(tag)) continue; - ignoreUntil = null; - } - if (disallowedPackets.has(tag)) { - throw new Error(`Unexpected packet type: ${tag}`); - } - switch (tag) { - case enums.packet.publicKey: - case enums.packet.secretKey: - if (this.keyPacket) { - throw new Error('Key block contains multiple keys'); - } - this.keyPacket = packet; - primaryKeyID = this.getKeyID(); - if (!primaryKeyID) { - throw new Error('Missing Key ID'); - } - break; - case enums.packet.userID: - case enums.packet.userAttribute: - user = new User(packet, this); - this.users.push(user); - break; - case enums.packet.publicSubkey: - case enums.packet.secretSubkey: - user = null; - subkey = new Subkey(packet, this); - this.subkeys.push(subkey); - break; - case enums.packet.signature: - switch (packet.signatureType) { - case enums.signature.certGeneric: - case enums.signature.certPersona: - case enums.signature.certCasual: - case enums.signature.certPositive: - if (!user) { - util.printDebug('Dropping certification signatures without preceding user packet'); - continue; - } - if (packet.issuerKeyID.equals(primaryKeyID)) { - user.selfCertifications.push(packet); - } else { - user.otherCertifications.push(packet); - } - break; - case enums.signature.certRevocation: - if (user) { - user.revocationSignatures.push(packet); - } else { - this.directSignatures.push(packet); - } - break; - case enums.signature.key: - this.directSignatures.push(packet); - break; - case enums.signature.subkeyBinding: - if (!subkey) { - util.printDebug('Dropping subkey binding signature without preceding subkey packet'); - continue; - } - subkey.bindingSignatures.push(packet); - break; - case enums.signature.keyRevocation: - this.revocationSignatures.push(packet); - break; - case enums.signature.subkeyRevocation: - if (!subkey) { - util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); - continue; - } - subkey.revocationSignatures.push(packet); - break; - } - break; - } - } - } + /** + * @fileoverview Provides functions for asymmetric signing and signature verification + * @module crypto/signature + */ - /** - * Transforms structured key data to packetlist - * @returns {PacketList} The packets that form a key. - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.directSignatures); - this.users.map(user => packetlist.push(...user.toPacketList())); - this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); - return packetlist; - } - /** - * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. - * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. - * @returns {Promise} Clone of the key. - */ - clone(clonePrivateParams = false) { - const key = new this.constructor(this.toPacketList()); - if (clonePrivateParams) { - key.getKeys().forEach(k => { - // shallow clone the key packets - k.keyPacket = Object.create( - Object.getPrototypeOf(k.keyPacket), - Object.getOwnPropertyDescriptors(k.keyPacket) - ); - if (!k.keyPacket.isDecrypted()) return; - // deep clone the private params, which are cleared during encryption - const privateParams = {}; - Object.keys(k.keyPacket.privateParams).forEach(name => { - privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); - }); - k.keyPacket.privateParams = privateParams; - }); + /** + * Parse signature in binary form to get the parameters. + * The returned values are only padded for EdDSA, since in the other cases their expected length + * depends on the key params, hence we delegate the padding to the signature verification function. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Uint8Array} signature - Data for which the signature was created + * @returns {Promise} True if signature is valid. + * @async + */ + function parseSignatureParams(algo, signature) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA signatures: + // - MPI of RSA signature value m**d mod n. + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + // The signature needs to be the same length as the public key modulo n. + // We pad s on signature verification, where we have access to n. + return { read, signatureParams: { s } }; + } + // Algorithm-Specific Fields for DSA or ECDSA signatures: + // - MPI of DSA or ECDSA value r. + // - MPI of DSA or ECDSA value s. + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + { + // If the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for legacy EdDSA signatures: + // - MPI of an EC point r. + // - EdDSA value s, in MPI, in the little endian representation + case enums.publicKey.eddsaLegacy: { + // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature + // verification: if the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for Ed25519 signatures: + // - 64 octets of the native signature + // Algorithm-Specific Fields for Ed448 signatures: + // - 114 octets of the native signature + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo); + const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length; + return { read, signatureParams: { RS } }; } - return key; - } - /** - * Returns an array containing all public or private subkeys matching keyID; - * If no keyID is given, returns all subkeys. - * @param {type/keyID} [keyID] - key ID to look for - * @returns {Array} array of subkeys - */ - getSubkeys(keyID = null) { - const subkeys = this.subkeys.filter(subkey => ( - !keyID || subkey.getKeyID().equals(keyID, true) - )); - return subkeys; + default: + throw new UnsupportedError('Unknown signature algorithm.'); } + } - /** - * Returns an array containing all public or private keys matching keyID. - * If no keyID is given, returns all keys, starting with the primary key. - * @param {type/keyid~KeyID} [keyID] - key ID to look for - * @returns {Array} array of keys - */ - getKeys(keyID = null) { - const keys = []; - if (!keyID || this.getKeyID().equals(keyID, true)) { - keys.push(this); + /** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} signature - Named algorithm-specific signature parameters + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Data for which the signature was created + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} True if signature is valid. + * @async + */ + async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto + return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); } - return keys.concat(this.getSubkeys(keyID)); + case enums.publicKey.dsa: { + const { g, p, q, y } = publicParams; + const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers + return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); + } + case enums.publicKey.ecdsa: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // padding needed for webcrypto + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values: + // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); } + } - /** - * Returns key IDs of all keys - * @returns {Array} - */ - getKeyIDs() { - return this.getKeys().map(key => key.getKeyID()); + /** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters + * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters + * @param {Uint8Array} data - Data to be signed + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} Signature Object containing named signature parameters. + * @async + */ + async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { + if (!publicKeyParams || !privateKeyParams) { + throw new Error('Missing key parameters'); } - - /** - * Returns userIDs - * @returns {Array} Array of userIDs. - */ - getUserIDs() { - return this.users.map(user => { - return user.userID ? user.userID.userID : null; - }).filter(userID => userID !== null); + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); + return { s }; + } + case enums.publicKey.dsa: { + const { g, p, q } = publicKeyParams; + const { x } = privateKeyParams; + return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); + } + case enums.publicKey.elgamal: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + case enums.publicKey.ecdsa: { + const { oid, Q } = publicKeyParams; + const { d } = privateKeyParams; + return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); } + } - /** - * Returns binary encoded key - * @returns {Uint8Array} Binary key. - */ - write() { - return this.toPacketList().write(); - } + var signature = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseSignatureParams: parseSignatureParams, + sign: sign$1, + verify: verify$1 + }); - /** - * Returns last created key or key by given keyID that is available for signing and verification - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} signing key - * @throws if no valid signing key was found - * @async - */ - async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature( - subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 - ); - if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) { - continue; - } - if (!bindingSignature.embeddedSignature) { - throw new Error('Missing embedded signature'); - } - // verify embedded signature - await getLatestValidSignature( - [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 - ); - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } catch (e) { - exception = e; - } - } - } + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - try { - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; + + class ECDHSymmetricKey { + constructor(data) { + if (data) { + this.data = data; } - throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); } /** - * Returns last created key or key by given keyID that is available for encryption or decryption - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} encryption key - * @throws if no valid encryption key was found - * @async + * Read an ECDHSymmetricKey from an Uint8Array: + * - 1 octect for the length `l` + * - `l` octects of encoded session key data + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. */ - async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - // V4: by convention subkeys are preferred for encryption service - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) { - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } - } catch (e) { - exception = e; - } - } - } - - try { - // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { - checkKeyRequirements(primaryKey, config$1); - return this; + read(bytes) { + if (bytes.length >= 1) { + const length = bytes[0]; + if (bytes.length >= 1 + length) { + this.data = bytes.subarray(1, 1 + length); + return 1 + this.data.length; } - } catch (e) { - exception = e; } - throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + throw new Error('Invalid symmetric key'); } /** - * Checks if a signature on a key is revoked - * @param {SignaturePacket} signature - The signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the certificate is revoked. - * @async + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - return isDataRevoked( - this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 - ); + write() { + return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); } + } - /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature. Throws if the primary key is invalid. - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} If key verification failed - * @async - */ - async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - // check for key revocation signatures - if (await this.isRevoked(null, null, date, config$1)) { - throw new Error('Primary key is revoked'); - } - // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); - // check for expiration time in binding signatures - if (isDataExpired(primaryKey, selfCertification, date)) { - throw new Error('Primary key is expired'); - } - // check for expiration time in direct signatures - const directSignature = await getLatestValidSignature( - this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 - ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (directSignature && isDataExpired(primaryKey, directSignature, date)) { - throw new Error('Primary key is expired'); - } - } + /** + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @module type/kdf_params + * @private + */ + + class KDFParams { /** - * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. - * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. - * @param {Object} [userID] - User ID to consider instead of the primary user - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async + * @param {enums.hash} hash - Hash algorithm + * @param {enums.symmetric} cipher - Symmetric algorithm */ - async getExpirationTime(userID, config$1 = config) { - let primaryKeyExpiry; - try { - const { selfCertification } = await this.getPrimaryUser(null, userID, config$1); - const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); - const selfSigExpiry = selfCertification.getExpirationTime(); - const directSignature = await getLatestValidSignature( - this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 - ).catch(() => {}); - if (directSignature) { - const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); - // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, - // causing a discountinous validy period for the key - primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); - } else { - primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; - } - } catch (e) { - primaryKeyExpiry = null; + constructor(data) { + if (data) { + const { hash, cipher } = data; + this.hash = hash; + this.cipher = cipher; + } else { + this.hash = null; + this.cipher = null; } - - return util.normalizeDate(primaryKeyExpiry); } - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * user: User, - * selfCertification: SignaturePacket - * }>} The primary user and the self signature - * @async + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input - Where to read the KDFParams from + * @returns {Number} Number of read bytes. */ - async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const users = []; - let exception; - for (let i = 0; i < this.users.length; i++) { - try { - const user = this.users[i]; - if (!user.userID) { - continue; - } - if ( - (userID.name !== undefined && user.userID.name !== userID.name) || - (userID.email !== undefined && user.userID.email !== userID.email) || - (userID.comment !== undefined && user.userID.comment !== userID.comment) - ) { - throw new Error('Could not find user that matches that user ID'); - } - const dataToVerify = { userID: user.userID, key: primaryKey }; - const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); - users.push({ index: i, user, selfCertification }); - } catch (e) { - exception = e; - } - } - if (!users.length) { - throw exception || new Error('Could not find primary user'); - } - await Promise.all(users.map(async function (a) { - return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); - })); - // sort by primary user flag and signature creation time - const primaryUser = users.sort(function(a, b) { - const A = a.selfCertification; - const B = b.selfCertification; - return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; - }).pop(); - const { user, selfCertification: cert } = primaryUser; - if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { - throw new Error('Primary user is revoked'); + read(input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new UnsupportedError('Cannot read KDFParams'); } - return primaryUser; + this.hash = input[2]; + this.cipher = input[3]; + return 4; } /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * - * If the source key is a private key and the destination key is public, - * a private key is returned. - * @param {Key} sourceKey - Source key to merge - * @param {Date} [date] - Date to verify validity of signatures and keys - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} updated key - * @async + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value */ - async update(sourceKey, date = new Date(), config$1 = config) { - if (!this.hasSameFingerprintAs(sourceKey)) { - throw new Error('Primary key fingerprints must be equal to update the key'); - } - if (!this.isPrivate() && sourceKey.isPrivate()) { - // check for equal subkey packets - const equal = (this.subkeys.length === sourceKey.subkeys.length) && - (this.subkeys.every(destSubkey => { - return sourceKey.subkeys.some(srcSubkey => { - return destSubkey.hasSameFingerprintAs(srcSubkey); - }); - })); - if (!equal) { - throw new Error('Cannot update public key with private key if subkeys mismatch'); - } + write() { + return new Uint8Array([3, 1, this.hash, this.cipher]); + } + } - return sourceKey.update(this, config$1); - } - // from here on, either: - // - destination key is private, source key is public - // - the keys are of the same type - // hence we don't need to convert the destination key type - const updatedKey = this.clone(); - // revocation signatures - await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { - return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); - }); - // direct signatures - await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); - // update users - await Promise.all(sourceKey.users.map(async srcUser => { - // multiple users with the same ID/attribute are not explicitly disallowed by the spec - // hence we support them, just in case - const usersToUpdate = updatedKey.users.filter(dstUser => ( - (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || - (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) - )); - if (usersToUpdate.length > 0) { - await Promise.all( - usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) - ); - } else { - const newUser = srcUser.clone(); - newUser.mainKey = updatedKey; - updatedKey.users.push(newUser); - } - })); - // update subkeys - await Promise.all(sourceKey.subkeys.map(async srcSubkey => { - // multiple subkeys with same fingerprint might be preset - const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( - dstSubkey.hasSameFingerprintAs(srcSubkey) - )); - if (subkeysToUpdate.length > 0) { - await Promise.all( - subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) - ); - } else { - const newSubkey = srcSubkey.clone(); - newSubkey.mainKey = updatedKey; - updatedKey.subkeys.push(newSubkey); - } - })); + /** + * Encoded symmetric key for x25519 and x448 + * The payload format varies for v3 and v6 PKESK: + * the former includes an algorithm byte preceeding the encrypted session key. + * + * @module type/x25519x448_symkey + */ - return updatedKey; + + class ECDHXSymmetricKey { + static fromObject({ wrappedKey, algorithm }) { + const instance = new ECDHXSymmetricKey(); + instance.wrappedKey = wrappedKey; + instance.algorithm = algorithm; + return instance; } /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Armored revocation certificate. - * @async + * - 1 octect for the length `l` + * - `l` octects of encoded session key data (with optional leading algorithm byte) + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. */ - async getRevocationCertificate(date = new Date(), config$1 = config) { - const dataToVerify = { key: this.keyPacket }; - const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); - const packetlist = new PacketList(); - packetlist.push(revocationSignature); - return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); + read(bytes) { + let read = 0; + let followLength = bytes[read++]; + this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even + followLength -= followLength % 2; + this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength; } /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param {String} revocationCertificate - armored revocation certificate - * @param {Date} [date] - Date to verify the certificate - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Revoked key. - * @async + * Write an MontgomerySymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data */ - async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { - const input = await unarmor(revocationCertificate, config$1); - const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); - const revocationSignature = packetlist.findPacket(enums.packet.signature); - if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { - throw new Error('Could not find revocation signature packet'); + write() { + return util.concatUint8Array([ + this.algorithm ? + new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : + new Uint8Array([this.wrappedKey.length]), + this.wrappedKey + ]); + } + } + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} keyAlgo - Public key algorithm + * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only) + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Session key data to be encrypted + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @returns {Promise} Encrypted session key parameters. + * @async + */ + async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const { n, e } = publicParams; + const c = await publicKey.rsa.encrypt(data, n, e); + return { c }; } - if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { - throw new Error('Revocation signature does not match key'); + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + return publicKey.elgamal.encrypt(data, p, g, y); } - try { - await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); - } catch (e) { - throw util.wrapError('Could not verify revocation signature', e); + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicParams; + const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( + oid, kdfParams, data, Q, fingerprint); + return { V, C: new ECDHSymmetricKey(C) }; } - const key = this.clone(); - key.revocationSignatures.push(revocationSignature); - return key; + case enums.publicKey.x25519: + case enums.publicKey.x448: { + if (symmetricAlgo && !util.isAES(symmetricAlgo)) { + // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 + throw new Error('X25519 and X448 keys can only encrypt AES session keys'); + } + const { A } = publicParams; + const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( + keyAlgo, data, A); + const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); + return { ephemeralPublicKey, C }; + } + default: + return []; } + } - /** - * Signs primary user of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signPrimaryUser(privateKeys, date, userID, config$1 = config) { - const { index, user } = await this.getPrimaryUser(date, userID, config$1); - const userSign = await user.certify(privateKeys, date, config$1); - const key = this.clone(); - key.users[index] = userSign; - return key; + /** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Object} publicKeyParams - Algorithm-specific public key parameters + * @param {Object} privateKeyParams - Algorithm-specific private key parameters + * @param {Object} sessionKeyParams - Encrypted session key parameters + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing + * (needed for constant-time processing in RSA and ElGamal) + * @returns {Promise} Decrypted data. + * @throws {Error} on sensitive decryption error, unless `randomPayload` is given + * @async + */ + async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: { + const { c } = sessionKeyParams; + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); + } + case enums.publicKey.elgamal: { + const { c1, c2 } = sessionKeyParams; + const p = publicKeyParams.p; + const x = privateKeyParams.x; + return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicKeyParams; + const { d } = privateKeyParams; + const { V, C } = sessionKeyParams; + return publicKey.elliptic.ecdh.decrypt( + oid, kdfParams, V, C.data, Q, d, fingerprint); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicKeyParams; + const { k } = privateKeyParams; + const { ephemeralPublicKey, C } = sessionKeyParams; + if (C.algorithm !== null && !util.isAES(C.algorithm)) { + throw new Error('AES session key expected'); + } + return publicKey.elliptic.ecdhX.decrypt( + algo, ephemeralPublicKey, C.wrappedKey, A, k); + } + default: + throw new Error('Unknown public key encryption algorithm.'); + } + } + + /** + * Parse public key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. + */ + function parsePublicKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; + const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; + return { read, publicParams: { n, e } }; + } + case enums.publicKey.dsa: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, q, g, y } }; + } + case enums.publicKey.elgamal: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, g, y } }; + } + case enums.publicKey.ecdsa: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.eddsaLegacy: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + if (oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + Q = util.leftPad(Q, 33); + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.ecdh: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); + return { read: read, publicParams: { oid, Q, kdfParams } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length; + return { read, publicParams: { A } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); + } + } + + /** + * Parse private key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @param {Object} publicParams - (ECC only) public params, needed to format some private params + * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. + */ + function parsePrivateKeyParams(algo, bytes, publicParams) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; + return { read, privateParams: { d, p, q, u } }; + } + case enums.publicKey.dsa: + case enums.publicKey.elgamal: { + const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; + return { read, privateParams: { x } }; + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + d = util.leftPad(d, payloadSize); + return { read, privateParams: { d } }; + } + case enums.publicKey.eddsaLegacy: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; + seed = util.leftPad(seed, payloadSize); + return { read, privateParams: { seed } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const payloadSize = getCurvePayloadSize(algo); + const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length; + return { read, privateParams: { seed } }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const payloadSize = getCurvePayloadSize(algo); + const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length; + return { read, privateParams: { k } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } + } - /** - * Signs all users of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for signing, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signAllUsers(privateKeys, date = new Date(), config$1 = config) { - const key = this.clone(); - key.users = await Promise.all(this.users.map(function(user) { - return user.certify(privateKeys, date, config$1); - })); - return key; - } + /** Returns the types comprising the encrypted session key of an algorithm + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {Object} The session key parameters referenced by name. + */ + function parseEncSessionKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const c = util.readMPI(bytes.subarray(read)); + return { c }; + } - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { - const primaryKey = this.keyPacket; - const { user } = await this.getPrimaryUser(date, userID, config$1); - const results = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - return results; + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case enums.publicKey.elgamal: { + const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; + const c2 = util.readMPI(bytes.subarray(read)); + return { c1, c2 }; + } + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case enums.publicKey.ecdh: { + const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; + const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); + return { V, C }; + } + // Algorithm-Specific Fields for X25519 or X448 encrypted session keys: + // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448). + // - A one-octet size of the following fields. + // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). + // - The encrypted session key. + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const pointSize = getCurvePayloadSize(algo); + const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length; + const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); + return { ephemeralPublicKey, C }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } + } - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of userID, signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { - const primaryKey = this.keyPacket; - const results = []; - await Promise.all(this.users.map(async user => { - const signatures = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + /** + * Convert params to MPI and serializes them in the proper order + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} params - The key parameters indexed by name + * @returns {Uint8Array} The array containing the MPIs. + */ + function serializeParams(algo, params) { + // Some algorithms do not rely on MPIs to store the binary params + const algosWithNativeRepresentation = new Set([ + enums.publicKey.ed25519, + enums.publicKey.x25519, + enums.publicKey.ed448, + enums.publicKey.x448 + ]); + const orderedParams = Object.keys(params).map(name => { + const param = params[name]; + if (!util.isUint8Array(param)) return param.write(); + return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); + }); + return util.concatUint8Array(orderedParams); + } - results.push(...signatures.map( - signature => ({ - userID: user.userID ? user.userID.userID : null, - userAttribute: user.userAttribute, - keyID: signature.keyID, - valid: signature.valid - })) - ); - })); - return results; + /** + * Generate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Integer} bits - Bit length for RSA keys + * @param {module:type/oid} oid - Object identifier for ECC keys + * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. + * @async + */ + function generateParams(algo, bits, oid) { + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ + privateParams: { d, p, q, u }, + publicParams: { n, e } + })); + case enums.publicKey.ecdsa: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { d: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { seed: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.ecdh: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ + privateParams: { d: secret }, + publicParams: { + oid: new OID(oid), + Q, + kdfParams: new KDFParams({ hash, cipher }) + } + })); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ + privateParams: { seed }, + publicParams: { A } + })); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ + privateParams: { k }, + publicParams: { A } + })); + case enums.publicKey.dsa: + case enums.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + default: + throw new Error('Unknown public key algorithm.'); } } - ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { - Key.prototype[name] = - Subkey.prototype[name]; - }); - - // This library is free software; you can redistribute it and/or - /** - * Class that represents an OpenPGP Public Key + * Validate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Object} privateParams - Algorithm-specific private key parameters + * @returns {Promise} Whether the parameters are valid. + * @async */ - class PublicKey extends Key { - /** - * @param {PacketList} packetlist - The packets that form this key - */ - constructor(packetlist) { - super(); - this.keyPacket = null; - this.revocationSignatures = []; - this.directSignatures = []; - this.users = []; - this.subkeys = []; - if (packetlist) { - this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing public-key packet'); - } + async function validateParams$1(algo, publicParams, privateParams) { + if (!publicParams || !privateParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const { d, p, q, u } = privateParams; + return publicKey.rsa.validateParams(n, e, d, p, q, u); + } + case enums.publicKey.dsa: { + const { p, q, g, y } = publicParams; + const { x } = privateParams; + return publicKey.dsa.validateParams(p, q, g, y, x); + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + const { x } = privateParams; + return publicKey.elgamal.validateParams(p, g, y, x); + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; + const { oid, Q } = publicParams; + const { d } = privateParams; + return algoModule.validateParams(oid, Q, d); + } + case enums.publicKey.eddsaLegacy: { + const { Q, oid } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsa.validateParams(algo, A, seed); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicParams; + const { k } = privateParams; + return publicKey.elliptic.ecdhX.validateParams(algo, A, k); } - } - - /** - * Returns true if this is a private key - * @returns {false} - */ - isPrivate() { - return false; - } - - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - return this; - } - - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + default: + throw new Error('Unknown public key algorithm.'); } } /** - * Class that represents an OpenPGP Private key + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + * @async */ - class PrivateKey extends PublicKey { - /** - * @param {PacketList} packetlist - The packets that form this key + async function getPrefixRandom(algo) { + const { blockSize } = getCipherParams(algo); + const prefixrandom = await getRandomBytes(blockSize); + const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + return util.concat([prefixrandom, repeat]); + } + + /** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key. */ - constructor(packetlist) { - super(); - this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing private-key packet'); - } - } + function generateSessionKey$1(algo) { + const { keySize } = getCipherParams(algo); + return getRandomBytes(keySize); + } - /** - * Returns true if this is a private key - * @returns {Boolean} - */ - isPrivate() { - return true; - } + /** + * Get implementation of the given AEAD mode + * @param {enums.aead} algo + * @returns {Object} + * @throws {Error} on invalid algo + */ + function getAEADMode(algo) { + const algoName = enums.read(enums.aead, algo); + return mode[algoName]; + } - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - const packetlist = new PacketList(); - const keyPackets = this.toPacketList(); - for (const keyPacket of keyPackets) { - switch (keyPacket.constructor.tag) { - case enums.packet.secretKey: { - const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); - packetlist.push(pubKeyPacket); - break; - } - case enums.packet.secretSubkey: { - const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); - packetlist.push(pubSubkeyPacket); - break; - } - default: - packetlist.push(keyPacket); - } - } - return new PublicKey(packetlist); + /** + * Check whether the given curve OID is supported + * @param {module:type/oid} oid - EC object identifier + * @throws {UnsupportedError} if curve is not supported + */ + function checkSupportedCurve(oid) { + try { + oid.getName(); + } catch (e) { + throw new UnsupportedError('Unknown curve OID'); } + } - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + /** + * Get encoded secret size for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ + function getCurvePayloadSize(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: + case enums.publicKey.eddsaLegacy: + return new publicKey.elliptic.CurveWithOID(oid).payloadSize; + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPayloadSize(algo); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.getPayloadSize(algo); + default: + throw new Error('Unknown elliptic algo'); } + } - /** - * Returns all keys that are available for decryption, matching the keyID when given - * This is useful to retrieve keys for session key decryption - * @param {module:type/keyid~KeyID} keyID, optional - * @param {Date} date, optional - * @param {String} userID, optional - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} Array of decryption keys. - * @async - */ - async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const keys = []; - for (let i = 0; i < this.subkeys.length; i++) { - if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { - try { - const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; - const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidDecryptionKeyPacket(bindingSignature, config$1)) { - keys.push(this.subkeys[i]); - } - } catch (e) {} - } - } - - // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && - isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) { - keys.push(this); - } - - return keys; + /** + * Get preferred signing hash algo for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ + function getPreferredCurveHashAlgo(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.getPreferredHashAlgo(oid); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); + default: + throw new Error('Unknown elliptic signing algo'); } + } - /** - * Returns true if the primary key or any subkey is decrypted. - * A dummy key is considered encrypted. - */ - isDecrypted() { - return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); - } + var crypto$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + generateParams: generateParams, + generateSessionKey: generateSessionKey$1, + getAEADMode: getAEADMode, + getCipherParams: getCipherParams, + getCurvePayloadSize: getCurvePayloadSize, + getPreferredCurveHashAlgo: getPreferredCurveHashAlgo, + getPrefixRandom: getPrefixRandom, + parseEncSessionKeyParams: parseEncSessionKeyParams, + parsePrivateKeyParams: parsePrivateKeyParams, + parsePublicKeyParams: parsePublicKeyParams, + publicKeyDecrypt: publicKeyDecrypt, + publicKeyEncrypt: publicKeyEncrypt, + serializeParams: serializeParams, + validateParams: validateParams$1 + }); - /** - * Check whether the private and public primary key parameters correspond - * Together with verification of binding signatures, this guarantees key integrity - * In case of gnu-dummy primary key, it is enough to validate any signing subkeys - * otherwise all encryption subkeys are validated - * If only gnu-dummy keys are found, we cannot properly validate so we throw an error - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if validation was not successful and the key cannot be trusted - * @async - */ - async validate(config$1 = config) { - if (!this.isPrivate()) { - throw new Error('Cannot validate a public key'); - } + /** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ - let signingKeyPacket; - if (!this.keyPacket.isDummy()) { - signingKeyPacket = this.keyPacket; - } else { - /** - * It is enough to validate any signing keys - * since its binding signatures are also checked - */ - const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); - // This could again be a dummy key - if (signingKey && !signingKey.keyPacket.isDummy()) { - signingKeyPacket = signingKey.keyPacket; - } - } - if (signingKeyPacket) { - return signingKeyPacket.validate(); - } else { - const keys = this.getKeys(); - const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); - if (allDummies) { - throw new Error('Cannot validate an all-gnu-dummy key'); - } + // TODO move cfb and gcm to cipher + const mod$1 = { + /** @see module:crypto/cipher */ + cipher: cipher, + /** @see module:crypto/hash */ + hash: hash$1, + /** @see module:crypto/mode */ + mode: mode, + /** @see module:crypto/public_key */ + publicKey: publicKey, + /** @see module:crypto/signature */ + signature: signature, + /** @see module:crypto/random */ + random: random, + /** @see module:crypto/pkcs1 */ + pkcs1: pkcs1, + /** @see module:crypto/pkcs5 */ + pkcs5: pkcs5, + /** @see module:crypto/aes_kw */ + aesKW: aesKW + }; - return Promise.all(keys.map(async key => key.keyPacket.validate())); + Object.assign(mod$1, crypto$2); + + const ARGON2_TYPE = 0x02; // id + const ARGON2_VERSION = 0x13; + const ARGON2_SALT_SIZE = 16; + + class Argon2OutOfMemoryError extends Error { + constructor(...params) { + super(...params); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Argon2OutOfMemoryError); } - } - /** - * Clear private key parameters - */ - clearPrivateParams() { - this.getKeys().forEach(({ keyPacket }) => { - if (keyPacket.isDecrypted()) { - keyPacket.clearPrivateParams(); - } - }); + this.name = 'Argon2OutOfMemoryError'; } + } + + // cache argon wasm module + let loadArgonWasmModule; + let argon2Promise; + // reload wasm module above this treshold, to deallocated used memory + const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; + class Argon2S2K { /** - * Revokes the key - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New key with revocation signature. - * @async - */ - async revoke( - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - if (!this.isPrivate()) { - throw new Error('Need private key for revoking'); - } - const dataToSign = { key: this.keyPacket }; - const key = this.clone(); - key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, undefined, config$1)); - return key; + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params; + + this.type = 'argon2'; + /** + * 16 bytes of salt + * @type {Uint8Array} + */ + this.salt = null; + /** + * number of passes + * @type {Integer} + */ + this.t = passes; + /** + * degree of parallelism (lanes) + * @type {Integer} + */ + this.p = parallelism; + /** + * exponent indicating memory size + * @type {Integer} + */ + this.encodedM = memoryExponent; } + generateSalt() { + this.salt = mod$1.random.getRandomBytes(ARGON2_SALT_SIZE); + } /** - * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. - * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. - * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA - * @param {String} options.curve (optional) Elliptic curve for ECC keys - * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date (optional) Override the creation date of the key and the key signatures - * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false - * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} - * @async - */ - async addSubkey(options = {}) { - const config$1 = { ...config, ...options.config }; - if (options.passphrase) { - throw new Error('Subkey could not be encrypted here, please encrypt whole key'); - } - if (options.rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); - } - const secretKeyPacket = this.keyPacket; - if (secretKeyPacket.isDummy()) { - throw new Error('Cannot add subkey to gnu-dummy primary key'); - } - if (!secretKeyPacket.isDecrypted()) { - throw new Error('Key is not decrypted'); - } - const defaultOptions = secretKeyPacket.getAlgorithmInfo(); - defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA - defaultOptions.rsaBits = defaultOptions.bits || 4096; - defaultOptions.curve = defaultOptions.curve || 'curve25519'; - options = sanitizeKeyOptions(options, defaultOptions); - const keyPacket = await generateSecretSubkey(options); - checkKeyRequirements(keyPacket, config$1); - const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); - const packetList = this.toPacketList(); - packetList.push(keyPacket, bindingSignature); - return new PrivateKey(packetList); - } - } + * Parsing function for argon2 string-to-key specifier. + * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; - // OpenPGP.js - An OpenPGP implementation in javascript + this.salt = bytes.subarray(i, i + 16); + i += 16; - // A Key can contain the following packets - const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ - PublicKeyPacket, - PublicSubkeyPacket, - SecretKeyPacket, - SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, - SignaturePacket - ]); + this.t = bytes[i++]; + this.p = bytes[i++]; + this.encodedM = bytes[i++]; // memory size exponent, one-octect - /** - * Creates a PublicKey or PrivateKey depending on the packetlist in input - * @param {PacketList} - packets to parse - * @return {Key} parsed key - * @throws if no key packet was found - */ - function createKey(packetlist) { - for (const packet of packetlist) { - switch (packet.constructor.tag) { - case enums.packet.secretKey: - return new PrivateKey(packetlist); - case enums.packet.publicKey: - return new PublicKey(packetlist); - } + return i; } - throw new Error('No key packet found'); - } + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + const arr = [ + new Uint8Array([enums.write(enums.s2k, this.type)]), + this.salt, + new Uint8Array([this.t, this.p, this.encodedM]) + ]; - /** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * By default, primary and subkeys will be of same type. - * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA - * @param {String} options.curve Elliptic curve for ECC keys - * @param {Integer} options.rsaBits Number of bits for RSA keys - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Creation date of the key and the key signatures - * @param {Object} config - Full configuration - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ - async function generate$4(options, config) { - options.sign = true; // primary key is always a signing key - options = sanitizeKeyOptions(options); - options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); - let promises = [generateSecretKey(options, config)]; - promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); - const packets = await Promise.all(promises); + return util.concatUint8Array(arr); + } - const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; - } + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to `keySize` + * @throws {Argon2OutOfMemoryError|Errors} + * @async + */ + async produceKey(passphrase, keySize) { + const decodedM = 2 << (this.encodedM - 1); - /** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param {PrivateKey} options.privateKey The private key to reformat - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Override the creation date of the key signatures - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * @param {Object} config - Full configuration - * - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ - async function reformat(options, config) { - options = sanitize(options); - const { privateKey } = options; + try { + // on first load, the argon2 lib is imported and the WASM module is initialized. + // the two steps need to be atomic to avoid race conditions causing multiple wasm modules + // being loaded when `argon2Promise` is not initialized. + loadArgonWasmModule = loadArgonWasmModule || (await Promise.resolve().then(function () { return index$1; })).default; + argon2Promise = argon2Promise || loadArgonWasmModule(); + + // important to keep local ref to argon2 in case the module is reloaded by another instance + const argon2 = await argon2Promise; + + const passwordBytes = util.encodeUTF8(passphrase); + const hash = argon2({ + version: ARGON2_VERSION, + type: ARGON2_TYPE, + password: passwordBytes, + salt: this.salt, + tagLength: keySize, + memorySize: decodedM, + parallelism: this.p, + passes: this.t + }); - if (!privateKey.isPrivate()) { - throw new Error('Cannot reformat a public key'); + // a lot of memory was used, reload to deallocate + if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); + } + return hash; + } catch (e) { + if (e.message && ( + e.message.includes('Unable to grow instance memory') || // Chrome + e.message.includes('failed to grow memory') || // Firefox + e.message.includes('WebAssembly.Memory.grow') || // Safari + e.message.includes('Out of memory') // Safari iOS + )) { + throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2'); + } else { + throw e; + } + } } + } - if (privateKey.keyPacket.isDummy()) { - throw new Error('Cannot reformat a gnu-dummy primary key'); + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + class GenericS2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(s2kType, config$1 = config) { + /** + * Hash function identifier, or 0 for gnu-dummy keys + * @type {module:enums.hash | 0} + */ + this.algorithm = enums.hash.sha256; + /** + * enums.s2k identifier or 'gnu-dummy' + * @type {String} + */ + this.type = enums.read(enums.s2k, s2kType); + /** @type {Integer} */ + this.c = config$1.s2kIterationCountByte; + /** Eight bytes of salt in a binary string. + * @type {Uint8Array} + */ + this.salt = null; } - const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); - if (!isDecrypted) { - throw new Error('Key is not decrypted'); + generateSalt() { + switch (this.type) { + case 'salted': + case 'iterated': + this.salt = mod$1.random.getRandomBytes(8); + } } - const secretKeyPacket = privateKey.keyPacket; + getCount() { + // Exponent bias, defined in RFC4880 + const expbias = 6; - if (!options.subkeys) { - options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { - const secretSubkeyPacket = subkey.keyPacket; - const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; - const bindingSignature = await ( - getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) - ).catch(() => ({})); - return { - sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) - }; - })); + return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); } - const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); - if (options.subkeys.length !== secretSubkeyPackets.length) { - throw new Error('Number of subkey options does not match number of subkeys'); - } + /** + * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param {Uint8Array} bytes - Payload of string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; + this.algorithm = bytes[i++]; - options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); + switch (this.type) { + case 'simple': + break; - const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; + case 'salted': + this.salt = bytes.subarray(i, i + 8); + i += 8; + break; - function sanitize(options, subkeyDefaults = {}) { - options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; + case 'iterated': + this.salt = bytes.subarray(i, i + 8); + i += 8; - return options; - } - } + // Octet 10: count, a one-octet, coded value + this.c = bytes[i++]; + break; - /** - * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection - * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. - * @param {SecretKeyPacket} secretKeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPackets - * @param {Object} options - * @param {Object} config - Full configuration - * @returns {PrivateKey} - */ - async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { - // set passphrase protection - if (options.passphrase) { - await secretKeyPacket.encrypt(options.passphrase, config); - } + case 'gnu': + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { + i += 3; // GNU + const gnuExtType = 1000 + bytes[i++]; + if (gnuExtType === 1001) { + this.type = 'gnu-dummy'; + // GnuPG extension mode 1001 -- don't write secret key at all + } else { + throw new UnsupportedError('Unknown s2k gnu protection mode.'); + } + } else { + throw new UnsupportedError('Unknown s2k type.'); + } + break; - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - await secretSubkeyPacket.encrypt(subkeyPassphrase, config); + default: + throw new UnsupportedError('Unknown s2k type.'); // unreachable } - })); - const packetlist = new PacketList(); - packetlist.push(secretKeyPacket); + return i; + } - await Promise.all(options.userIDs.map(async function(userID, index) { - function createPreferredAlgos(algos, preferredAlgo) { - return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + if (this.type === 'gnu-dummy') { + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); } + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; - const userIDPacket = UserIDPacket.fromObject(userID); - const dataToSign = {}; - dataToSign.userID = userIDPacket; - dataToSign.key = secretKeyPacket; - - const signatureProperties = {}; - signatureProperties.signatureType = enums.signature.certGeneric; - signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; - signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([ - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) - enums.symmetric.aes256, - enums.symmetric.aes128, - enums.symmetric.aes192 - ], config.preferredSymmetricAlgorithm); - if (config.aeadProtect) { - signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([ - enums.aead.eax, - enums.aead.ocb - ], config.preferredAEADAlgorithm); - } - signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ - // prefer fast asm.js implementations (SHA-256) - enums.hash.sha256, - enums.hash.sha512 - ], config.preferredHashAlgorithm); - signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ - enums.compression.zlib, - enums.compression.zip, - enums.compression.uncompressed - ], config.preferredCompressionAlgorithm); - if (index === 0) { - signatureProperties.isPrimaryUserID = true; - } - // integrity protection always enabled - signatureProperties.features = [0]; - signatureProperties.features[0] |= enums.features.modificationDetection; - if (config.aeadProtect) { - signatureProperties.features[0] |= enums.features.aead; - } - if (config.v5Keys) { - signatureProperties.features[0] |= enums.features.v5Keys; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; + switch (this.type) { + case 'simple': + break; + case 'salted': + arr.push(this.salt); + break; + case 'iterated': + arr.push(this.salt); + arr.push(new Uint8Array([this.c])); + break; + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); } - const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + return util.concatUint8Array(arr); + } - return { userIDPacket, signaturePacket }; - })).then(list => { - list.forEach(({ userIDPacket, signaturePacket }) => { - packetlist.push(userIDPacket); - packetlist.push(signaturePacket); - }); - }); + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to. + * hashAlgorithm hash length + * @async + */ + async produceKey(passphrase, numBytes) { + passphrase = util.encodeUTF8(passphrase); - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyOptions = options.subkeys[index]; - const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); - return { secretSubkeyPacket, subkeySignaturePacket }; - })).then(packets => { - packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { - packetlist.push(secretSubkeyPacket); - packetlist.push(subkeySignaturePacket); - }); - }); + const arr = []; + let rlength = 0; - // Add revocation signature packet for creating a revocation certificate. - // This packet should be removed before returning the key. - const dataToSign = { key: secretKeyPacket }; - packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.reasonForRevocation.noReason, - reasonForRevocationString: '' - }, options.date, undefined, undefined, undefined, config)); + let prefixlen = 0; + while (rlength < numBytes) { + let toHash; + switch (this.type) { + case 'simple': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); + break; + case 'salted': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); + break; + case 'iterated': { + const data = util.concatUint8Array([this.salt, passphrase]); + let datalen = data.length; + const count = Math.max(this.getCount(), datalen); + toHash = new Uint8Array(prefixlen + count); + toHash.set(data, prefixlen); + for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { + toHash.copyWithin(pos, prefixlen, pos); + } + break; + } + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + const result = await mod$1.hash.digest(this.algorithm, toHash); + arr.push(result); + rlength += result.length; + prefixlen++; + } - if (options.passphrase) { - secretKeyPacket.clearPrivateParams(); + return util.concatUint8Array(arr).subarray(0, numBytes); } + } - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - secretSubkeyPacket.clearPrivateParams(); + const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]); + + /** + * Instantiate a new S2K instance of the given type + * @param {module:enums.s2k} type + * @oaram {Object} [config] + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ + function newS2KFromType(type, config$1 = config) { + switch (type) { + case enums.s2k.argon2: + return new Argon2S2K(config$1); + case enums.s2k.iterated: + case enums.s2k.gnu: + case enums.s2k.salted: + case enums.s2k.simple: + return new GenericS2K(type, config$1); + default: + throw new UnsupportedError('Unsupported S2K type'); + } + } + + /** + * Instantiate a new S2K instance based on the config settings + * @oaram {Object} config + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ + function newS2KFromConfig(config) { + const { s2kType } = config; + + if (!allowedS2KTypesForEncryption.has(s2kType)) { + throw new Error('The provided `config.s2kType` value is not allowed'); + } + + return newS2KFromType(s2kType, config); + } + + // DEFLATE is a complex format; to read this code, you should probably check the RFC first: + // https://tools.ietf.org/html/rfc1951 + // You may also wish to take a look at the guide I made about this program: + // https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad + // Some of the following code is similar to that of UZIP.js: + // https://github.com/photopea/UZIP.js + // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. + // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint + // is better for memory in most engines (I *think*). + + // aliases for shorter compressed code (most minifers don't do this) + var u8 = Uint8Array, u16 = Uint16Array, u32$1 = Uint32Array; + // fixed length extra bits + var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); + // fixed distance extra bits + // see fleb note + var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); + // code length index map + var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); + // get base, reverse index map from extra bits + var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new u32$1(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return [b, r]; + }; + var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; + // we can ignore the fact that the other numbers are wrong; they never happen anyway + fl[28] = 258, revfl[258] = 28; + var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; + // map of value to reverse (assuming 16 bits) + var rev = new u16(32768); + for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; + } + // create huffman tree from u8 "map": index -> code length for code index + // mb (max bits) must be at most 15 + // TODO: optimize/split up? + var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >>> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); + } + } + } + return co; + }); + // fixed length tree + var flt = new u8(288); + for (var i = 0; i < 144; ++i) + flt[i] = 8; + for (var i = 144; i < 256; ++i) + flt[i] = 9; + for (var i = 256; i < 280; ++i) + flt[i] = 7; + for (var i = 280; i < 288; ++i) + flt[i] = 8; + // fixed distance tree + var fdt = new u8(32); + for (var i = 0; i < 32; ++i) + fdt[i] = 5; + // fixed length map + var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); + // fixed distance map + var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); + // find max of array + var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; + }; + // read d, starting at bit p and mask with m + var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; + }; + // read d, starting at bit p continuing for at least 16 bits + var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); + }; + // get end of byte + var shft = function (p) { return ((p + 7) / 8) | 0; }; + // typed array slice - allows garbage collector to free original reference, + // while being more compatible than .slice + var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32$1 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; + }; + // error codes + var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method + ]; + var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; + }; + // expands raw DEFLATE data + var inflt = function (dat, buf, st) { + // source length + var sl = dat.length; + if (!sl || (st && st.f && !st.l)) + return buf || new u8(0); + // have to estimate size + var noBuf = !buf || st; + // no state + var noSt = !st || st.i; + if (!st) + st = {}; + // Assumes roughly 33% compression ratio average + if (!buf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (noBuf) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >>> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17; + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); + }; + // starting at p, write the minimum number of bits that can hold v to d + var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + }; + // starting at p, write the minimum number of bits (>8) that can hold v to d + var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + d[o + 2] |= v >>> 16; + }; + // creates code lengths from a frequency table + var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return [et, 0]; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return [v, 1]; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return [new u8(tr), mbt]; + }; + // get the max length and assign length codes + var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); + }; + // length codes generation + var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return [cl.subarray(0, cli), s]; + }; + // calculate the length of output from tree, code lengths + var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; + }; + // writes a fixed block + // returns the new bit pos + var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >>> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; + }; + // writes a block + var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; + var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; + var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; + var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + lcfreq[lclt[i] & 31]++; + for (var i = 0; i < lcdt.length; ++i) + lcfreq[lcdt[i] & 31]++; + var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); + if (flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + if (syms[i] > 255) { + var len = (syms[i] >>> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; + var dst = syms[i] & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; + }; + // deflate options (nice << 13) | chain + var deo = /*#__PURE__*/ new u32$1([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); + // empty + var et = /*#__PURE__*/ new u8(0); + // compresses data into a raw DEFLATE buffer + var dflt = function (dat, lvl, plvl, pre, post, lst) { + var s = dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var pos = 0; + if (!lvl || s < 8) { + for (var i = 0; i <= s; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[pos >> 3] = lst; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } } - })); - - return new PrivateKey(packetlist); - } - + else { + var opt = deo[lvl - 1]; + var n = opt >>> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = new u16(32768), head = new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new u32$1(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx bitpos + var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; + for (; i < s; ++i) { + // hash value + // deopt when i > s - 3 - at end, deopt acceptable + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && rem > 423) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = (i - dif + j + 32768) & 32767; + var pti = prev[ti]; + var cd = (ti - pti + 32768) & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += (imod - pimod + 32768) & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one Uint32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + // this is the easiest way to avoid needing to maintain state + if (!lst && pos & 7) + pos = wfblk(w, pos + 1, et); + } + return slc(o, 0, pre + shft(pos) + post); + }; + // Alder32 + var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); + } + }; + }; + // deflate with opts + var dopt = function (dat, opt, pre, post, st) { + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st); + }; + // write bytes + var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; + }; + // zlib header + var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); + }; + // zlib footer: -4 to -0 is Adler32 /** - * Reads an (optionally armored) OpenPGP key and returns a key object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static + * Streaming DEFLATE compression */ - async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { - throw new Error('Armored text not of type key'); + var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (!cb && typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return createKey(packetlist); - } - + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, !f), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.d = final; + this.p(chunk, final || false); + }; + return Deflate; + }()); /** - * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static + * Streaming DEFLATE decompression */ - async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readPrivateKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.privateKey)) { - throw new Error('Armored text not of type private key'); - } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return new PrivateKey(packetlist); - } - + var Inflate = /*#__PURE__*/ (function () { + /** + * Creates an inflation stream + * @param cb The callback to call whenever data is inflated + */ + function Inflate(cb) { + this.s = {}; + this.p = new u8(0); + this.ondata = cb; + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + var l = this.p.length; + var n = new u8(l + c.length); + n.set(this.p), n.set(c, l), this.p = n; + }; + Inflate.prototype.c = function (final) { + this.d = this.s.i = final || false; + var bts = this.s.b; + var dt = inflt(this.p, this.o, this.s); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; + }()); /** - * Reads an (optionally armored) OpenPGP key block and returns a list of key objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static + * Streaming Zlib compression */ - async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { - throw new Error('Armored text not of type key'); + var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = createKey(oneKeyList); - keys.push(newKey); - } - return keys; - } - + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + this.c.p(c); + var raw = dopt(c, this.o, this.v && 2, f && 4, !f); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + return Zlib; + }()); /** - * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static + * Streaming Zlib decompression */ - async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readPrivateKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); - } - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.privateKey) { - throw new Error('Armored text not of type private key'); + var Unzlib = /*#__PURE__*/ (function () { + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + function Unzlib(cb) { + this.v = 1; + Inflate.call(this, cb); } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No secret key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = new PrivateKey(oneKeyList); - keys.push(newKey); - } - return keys; + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 2 && !final) + return; + this.p = this.p.subarray(2), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; + }()); + // text decoder + var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); + // text decoder stream + var tds = 0; + try { + td.decode(et, { stream: true }); + tds = 1; } + catch (e) { } // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // A Message can contain the following packets - const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - AEADEncryptedDataPacket, - SymEncryptedIntegrityProtectedDataPacket, - SymmetricallyEncryptedDataPacket, - PublicKeyEncryptedSessionKeyPacket, - SymEncryptedSessionKeyPacket, - OnePassSignaturePacket, - SignaturePacket - ]); - // A SKESK packet can contain the following packets - const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); - // A detached signature can contain the following packets - const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + * Implementation of the Literal Data Packet (Tag 11) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. */ - class Message { - /** - * @param {PacketList} packetlist - The packets that form this message - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); + class LiteralDataPacket { + static get tag() { + return enums.packet.literalData; } /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns {Array} Array of keyID objects. + * @param {Date} date - The creation date of the literal package */ - getEncryptionKeyIDs() { - const keyIDs = []; - const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - pkESKeyPacketlist.forEach(function(packet) { - keyIDs.push(packet.publicKeyID); - }); - return keyIDs; + constructor(date = new Date()) { + this.format = enums.literal.utf8; // default format for literal data packets + this.date = util.normalizeDate(date); + this.text = null; // textual data representation + this.data = null; // literal data representation + this.filename = ''; + } + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param {String | ReadableStream} text - Any native javascript string + * @param {enums.literal} [format] - The format of the string of bytes + */ + setText(text, format = enums.literal.utf8) { + this.format = format; + this.text = text; + this.data = null; } /** - * Returns the key IDs of the keys that signed the message - * @returns {Array} Array of keyID objects. + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {String | ReadableStream} Literal data as text. */ - getSigningKeyIDs() { - const msg = this.unwrapCompressed(); - // search for one pass signatures - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); - if (onePassSigList.length > 0) { - return onePassSigList.map(packet => packet.issuerKeyID); + getText(clone = false) { + if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read + this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); } - // if nothing found look for signature packets - const signatureList = msg.packets.filterByTag(enums.packet.signature); - return signatureList.map(packet => packet.issuerKeyID); + return this.text; } /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Date} [date] - Use the given date for key verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with decrypted content. - * @async + * Set the packet data to value represented by the provided string of bytes. + * @param {Uint8Array | ReadableStream} bytes - The string of bytes + * @param {enums.literal} format - The format of the string of bytes */ - async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { - const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1); + setBytes(bytes, format) { + this.format = format; + this.data = bytes; + this.text = null; + } - const symEncryptedPacketlist = this.packets.filterByTag( - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ); - if (symEncryptedPacketlist.length === 0) { - throw new Error('No encrypted data found'); + /** + * Get the byte sequence representing the literal packet data + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {Uint8Array | ReadableStream} A sequence of bytes. + */ + getBytes(clone = false) { + if (this.data === null) { + // encode UTF8 and normalize EOL to \r\n + this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); } + if (clone) { + return passiveClone(this.data); + } + return this.data; + } - const symEncryptedPacket = symEncryptedPacketlist[0]; - let exception = null; - const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { - if (!util.isUint8Array(data) || !util.isString(algorithmName)) { - throw new Error('Invalid session key for decryption.'); - } - - try { - const algo = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.decrypt(algo, data, config$1); - } catch (e) { - util.printDebugError(e); - exception = e; - } - })); - // We don't await stream.cancel here because it only returns when the other copy is canceled too. - cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. - symEncryptedPacket.encrypted = null; - await decryptedPromise; - if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { - throw exception || new Error('Decryption failed.'); - } + /** + * Sets the filename of the literal packet data + * @param {String} filename - Any native javascript string + */ + setFilename(filename) { + this.filename = filename; + } - const resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - return resultMsg; + /** + * Get the filename of the literal packet data + * @returns {String} Filename. + */ + getFilename() { + return this.filename; } /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Date} [date] - Use the given date for key verification, instead of current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * Parsing function for a literal data packet (tag 11). + * + * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet + * @returns {Promise} Object representation. * @async */ - async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) { - let decryptedSessionKeyPackets = []; + async read(bytes) { + await parse(bytes, async reader => { + // - A one-octet field that describes how the data is formatted. + const format = await reader.readByte(); // enums.literal - let exception; - if (passwords) { - const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); - if (skeskPackets.length === 0) { - throw new Error('No symmetrically encrypted session key packet found.'); - } - await Promise.all(passwords.map(async function(password, i) { - let packets; - if (i) { - packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); - } else { - packets = skeskPackets; - } - await Promise.all(packets.map(async function(skeskPacket) { - try { - await skeskPacket.decrypt(password); - decryptedSessionKeyPackets.push(skeskPacket); - } catch (err) { - util.printDebugError(err); - } - })); - })); - } else if (decryptionKeys) { - const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - if (pkeskPackets.length === 0) { - throw new Error('No public key encrypted session key packet found.'); - } - await Promise.all(pkeskPackets.map(async function(pkeskPacket) { - await Promise.all(decryptionKeys.map(async function(decryptionKey) { - let algos = [ - enums.symmetric.aes256, // Old OpenPGP.js default fallback - enums.symmetric.aes128, // RFC4880bis fallback - enums.symmetric.tripledes, // RFC4880 fallback - enums.symmetric.cast5 // Golang OpenPGP fallback - ]; - try { - const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere. - if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { - algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); - } - } catch (e) {} + const filename_len = await reader.readByte(); + this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - // do not check key expiration to allow decryption of old messages - const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); - await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { - if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) { - return; - } - if (!decryptionKeyPacket.isDecrypted()) { - throw new Error('Decryption key is not decrypted.'); - } + this.date = util.readDate(await reader.readBytes(4)); - // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. - const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal - ); + let data = reader.remainder(); + if (isArrayStream(data)) data = await readToEnd(data); + this.setBytes(data, format); + }); + } - if (doConstantTimeDecryption) { - // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, - // either with the successfully decrypted session key, or with a randomly generated one. - // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on - // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: - // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the - // randomly generated keys of the remaining key types. - // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly - // generated session keys. - // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. + /** + * Creates a Uint8Array representation of the packet, excluding the data + * + * @returns {Uint8Array} Uint8Array representation of the packet. + */ + writeHeader() { + const filename = util.encodeUTF8(this.filename); + const filename_length = new Uint8Array([filename.length]); - const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times - await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => { - const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); - pkeskPacketCopy.read(serialisedPKESK); - const randomSessionKey = { - sessionKeyAlgorithm, - sessionKey: mod.generateSessionKey(sessionKeyAlgorithm) - }; - try { - await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); - decryptedSessionKeyPackets.push(pkeskPacketCopy); - } catch (err) { - // `decrypt` can still throw some non-security-sensitive errors - util.printDebugError(err); - exception = err; - } - })); + const format = new Uint8Array([this.format]); + const date = util.writeDate(this.date); - } else { - try { - await pkeskPacket.decrypt(decryptionKeyPacket); - if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) { - throw new Error('A non-preferred symmetric algorithm was used.'); - } - decryptedSessionKeyPackets.push(pkeskPacket); - } catch (err) { - util.printDebugError(err); - exception = err; - } - } - })); - })); - cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. - pkeskPacket.encrypted = null; - })); - } else { - throw new Error('No key or password specified.'); - } + return util.concatUint8Array([format, filename_length, filename, date]); + } - if (decryptedSessionKeyPackets.length > 0) { - // Return only unique session keys - if (decryptedSessionKeyPackets.length > 1) { - const seen = new Set(); - decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { - const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); - if (seen.has(k)) { - return false; - } - seen.add(k); - return true; - }); - } + /** + * Creates a Uint8Array representation of the packet + * + * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. + */ + write() { + const header = this.writeHeader(); + const data = this.getBytes(); - return decryptedSessionKeyPackets.map(packet => ({ - data: packet.sessionKey, - algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm) - })); - } - throw exception || new Error('Session key decryption failed.'); + return util.concat([header, data]); + } + } + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ + class KeyID { + constructor() { + this.bytes = ''; } /** - * Get literal data that is the body of the message - * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + * Parsing method for a key id + * @param {Uint8Array} bytes - Input to read the key id from */ - getLiteralData() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getBytes()) || null; + read(bytes) { + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); + return this.bytes.length; } /** - * Get filename from literal data packet - * @returns {(String|null)} Filename of literal data packet as string. + * Serializes the Key ID + * @returns {Uint8Array} Key ID as a Uint8Array. */ - getFilename() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getFilename()) || null; + write() { + return util.stringToUint8Array(this.bytes); } /** - * Get literal data as text - * @returns {(String|null)} Literal body of the message interpreted as text. + * Returns the Key ID represented as a hexadecimal string + * @returns {String} Key ID as a hexadecimal string. */ - getText() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - if (literal) { - return literal.getText(); - } - return null; + toHex() { + return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); } /** - * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. - * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for - * @param {Date} [date] - Date to select algorithm preferences at - * @param {Array} [userIDs] - User IDs to select algorithm preferences for - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. - * @async + * Checks equality of Key ID's + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard */ - static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { - const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1); - const algorithmName = enums.read(enums.symmetric, algo); - const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ? - enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) : - undefined; - - await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() - .catch(() => null) // ignore key strength requirements - .then(maybeKey => { - if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) { - throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); - } - }) - )); + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; + } - const sessionKeyData = mod.generateSessionKey(algo); - return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName }; + /** + * Checks to see if the Key ID is unset + * @returns {Boolean} True if the Key ID is null. + */ + isNull() { + return this.bytes === ''; } /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - Password(s) for message encryption - * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] - * @param {Date} [date] - Override the creation date of the literal package - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async + * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) + * @returns {Boolean} True if this is a wildcard Key ID. */ - async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - if (sessionKey) { - if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { - throw new Error('Invalid session key for encryption.'); - } - } else if (encryptionKeys && encryptionKeys.length) { - sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); - } else if (passwords && passwords.length) { - sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); - } else { - throw new Error('No keys, passwords, or session key provided.'); - } + isWildcard() { + return /^0+$/.test(this.toHex()); + } - const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; + static mapToHex(keyID) { + return keyID.toHex(); + } - const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); + static fromID(hex) { + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; + } - let symEncryptedPacket; - if (aeadAlgorithmName) { - symEncryptedPacket = new AEADEncryptedDataPacket(); - symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName); - } else { - symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); - } - symEncryptedPacket.packets = this.packets; + static wildcard() { + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; + } + } - const algorithm = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new PacketList(); // remove packets after encryption - return msg; - } - /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param {Uint8Array} sessionKey - session key for encryption - * @param {String} algorithmName - session key algorithm - * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - For message encryption - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [date] - Override the date - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async - */ - static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - const packetlist = new PacketList(); - const algorithm = enums.write(enums.symmetric, algorithmName); - const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); + // Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. + const verified = Symbol('verified'); - if (encryptionKeys) { - const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { - const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = algorithm; - await pkESKeyPacket.encrypt(encryptionKey.keyPacket); - delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption - return pkESKeyPacket; - })); - packetlist.push(...results); - } - if (passwords) { - const testDecrypt = async function(keyPacket, password) { - try { - await keyPacket.decrypt(password); - return 1; - } catch (e) { - return 0; - } - }; + // A salt notation is used to randomize signatures. + // This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks + // leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170). + // For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g. + // some chosen-prefix attacks. + // v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt. + const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org'; - const sum = (accumulator, currentValue) => accumulator + currentValue; + // GPG puts the Issuer and Signature subpackets in the unhashed area. + // Tampering with those invalidates the signature, so we still trust them and parse them. + // All other unhashed subpackets are ignored. + const allowedUnhashedSubpackets = new Set([ + enums.signatureSubpacket.issuerKeyID, + enums.signatureSubpacket.issuerFingerprint, + enums.signatureSubpacket.embeddedSignature + ]); - const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { - const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); - symEncryptedSessionKeyPacket.sessionKey = sessionKey; - symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; - if (aeadAlgorithm) { - symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; - } - await symEncryptedSessionKeyPacket.encrypt(password, config$1); + /** + * Implementation of the Signature Packet (Tag 2) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + */ + class SignaturePacket { + static get tag() { + return enums.packet.signature; + } - if (config$1.passwordCollisionCheck) { - const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); - if (results.reduce(sum) !== 1) { - return encryptPassword(sessionKey, algorithm, password); - } - } + constructor() { + this.version = null; + /** @type {enums.signature} */ + this.signatureType = null; + /** @type {enums.hash} */ + this.hashAlgorithm = null; + /** @type {enums.publicKey} */ + this.publicKeyAlgorithm = null; - delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption - return symEncryptedSessionKeyPacket; - }; + this.signatureData = null; + this.unhashedSubpackets = []; + this.unknownSubpackets = []; + this.signedHashValue = null; + this.salt = null; - const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd))); - packetlist.push(...results); - } + this.created = null; + this.signatureExpirationTime = null; + this.signatureNeverExpires = true; + this.exportable = null; + this.trustLevel = null; + this.trustAmount = null; + this.regularExpression = null; + this.revocable = null; + this.keyExpirationTime = null; + this.keyNeverExpires = null; + this.preferredSymmetricAlgorithms = null; + this.revocationKeyClass = null; + this.revocationKeyAlgorithm = null; + this.revocationKeyFingerprint = null; + this.issuerKeyID = new KeyID(); + this.rawNotations = []; + this.notations = {}; + this.preferredHashAlgorithms = null; + this.preferredCompressionAlgorithms = null; + this.keyServerPreferences = null; + this.preferredKeyServer = null; + this.isPrimaryUserID = null; + this.policyURI = null; + this.keyFlags = null; + this.signersUserID = null; + this.reasonForRevocationFlag = null; + this.reasonForRevocationString = null; + this.features = null; + this.signatureTargetPublicKeyAlgorithm = null; + this.signatureTargetHashAlgorithm = null; + this.signatureTargetHash = null; + this.embeddedSignature = null; + this.issuerKeyVersion = null; + this.issuerFingerprint = null; + this.preferredAEADAlgorithms = null; + this.preferredCipherSuites = null; - return new Message(packetlist); + this.revoked = null; + this[verified] = null; } /** - * Sign the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to add to the message - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with signed content. - * @async + * parsing function for a signature packet (tag 2). + * @param {String} bytes - Payload of a tag 2 packet + * @returns {SignaturePacket} Object representation. */ - async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const packetlist = new PacketList(); + read(bytes, config$1 = config) { + let i = 0; + this.version = bytes[i++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); } - let i; - let existingSigPacketlist; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; + this.signatureType = bytes[i++]; + this.publicKeyAlgorithm = bytes[i++]; + this.hashAlgorithm = bytes[i++]; - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signaturePacket.signatureType; - onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; - onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyID = signaturePacket.issuerKeyID; - if (!signingKeys.length && i === 0) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); - } + // hashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), true); + if (!this.created) { + throw new Error('Missing signature creation time subpacket.'); } - await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) { - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i]; - const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1); - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1); - onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyID = signingKey.getKeyID(); - if (i === signingKeys.length - 1) { - onePassSig.flags = 1; - } - return onePassSig; - })).then(onePassSignatureList => { - onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig)); - }); + // A V4 signature hashes the packet body + // starting from its first field, the version number, through the end + // of the hashed subpacket data. Thus, the fields hashed are the + // signature version, the signature type, the public-key algorithm, the + // hash algorithm, the hashed subpacket length, and the hashed + // subpacket body. + this.signatureData = bytes.subarray(0, i); - packetlist.push(literalDataPacket); - packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1))); + // unhashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - return new Message(packetlist); + // Two-octet field holding left 16 bits of signed hash value. + this.signedHashValue = bytes.subarray(i, i + 2); + i += 2; + + // Only for v6 signatures, a variable-length field containing: + if (this.version === 6) { + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[i++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(i, i + saltLength); + i += saltLength; + } + + const signatureMaterial = bytes.subarray(i, bytes.length); + const { read, signatureParams } = mod$1.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial); + if (read < signatureMaterial.length) { + throw new Error('Error reading MPIs'); + } + this.params = signatureParams; } /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param {module:enums.compression} algo - compression algorithm - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Message} New message with compressed content. + * @returns {Uint8Array | ReadableStream} */ - compress(algo, config$1 = config) { - if (algo === enums.compression.uncompressed) { - return this; + writeParams() { + if (this.params instanceof Promise) { + return fromAsync( + async () => mod$1.serializeParams(this.publicKeyAlgorithm, await this.params) + ); } + return mod$1.serializeParams(this.publicKeyAlgorithm, this.params); + } - const compressed = new CompressedDataPacket(config$1); - compressed.algorithm = algo; - compressed.packets = this.packets; - - const packetList = new PacketList(); - packetList.push(compressed); - - return new Message(packetList); + write() { + const arr = []; + arr.push(this.signatureData); + arr.push(this.writeUnhashedSubPackets()); + arr.push(this.signedHashValue); + if (this.version === 6) { + arr.push(new Uint8Array([this.salt.length])); + arr.push(this.salt); + } + arr.push(this.writeParams()); + return util.concat(arr); } /** - * Create a detached signature for the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New detached signature of message content. + * Signs provided data. This needs to be done prior to serialization. + * @param {SecretKeyPacket} key - Private key used to sign the message. + * @param {Object} data - Contains packets to be signed. + * @param {Date} [date] - The signature creation time. + * @param {Boolean} [detached] - Whether to create a detached signature + * @throws {Error} if signing failed * @async */ - async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); + async sign(key, data, date = new Date(), detached = false, config) { + this.version = key.version; + + this.created = util.normalizeDate(date); + this.issuerKeyVersion = key.version; + this.issuerFingerprint = key.getFingerprintBytes(); + this.issuerKeyID = key.getKeyID(); + + const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; + + // add randomness to the signature + if (this.version === 6) { + const saltLength = saltLengthForHash(this.hashAlgorithm); + if (this.salt === null) { + this.salt = mod$1.random.getRandomBytes(saltLength); + } else if (saltLength !== this.salt.length) { + throw new Error('Provided salt does not have the required length'); + } + } else if (config.nonDeterministicSignaturesViaNotation) { + const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME)); + // since re-signing the same object is not supported, it's not expected to have multiple salt notations, + // but we guard against it as a sanity check + if (saltNotations.length === 0) { + const saltValue = mod$1.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm)); + this.rawNotations.push({ + name: SALT_NOTATION_NAME, + value: saltValue, + humanReadable: false, + critical: false + }); + } else { + throw new Error('Unexpected existing salt notation'); + } + } + + // Add hashed subpackets + arr.push(this.writeHashedSubPackets()); + + // Remove unhashed subpackets, in case some allowed unhashed + // subpackets existed, in order not to duplicate them (in both + // the hashed and unhashed subpackets) when re-signing. + this.unhashedSubpackets = []; + + this.signatureData = util.concat(arr); + + const toHash = this.toHash(this.signatureType, data, detached); + const hash = await this.hash(this.signatureType, data, toHash, detached); + + this.signedHashValue = slice(clone(hash), 0, 2); + const signed = async () => mod$1.signature.sign( + this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) + ); + if (util.isStream(hash)) { + this.params = signed(); + } else { + this.params = await signed(); + + // Store the fact that this signature is valid, e.g. for when we call `await + // getLatestValidSignature(this.revocationSignatures, key, data)` later. + // Note that this only holds up if the key and data passed to verify are the + // same as the ones passed to sign. + this[verified] = true; } - return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); } /** - * Verify message signatures - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signatures. - * @async + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns {Uint8Array} Subpacket data. */ - async verify(verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); + writeHashedSubPackets() { + const sub = enums.signatureSubpacket; + const arr = []; + let bytes; + if (this.created === null) { + throw new Error('Missing signature creation time'); + } + arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); + if (this.signatureExpirationTime !== null) { + arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); + } + if (this.exportable !== null) { + arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); + } + if (this.trustLevel !== null) { + bytes = new Uint8Array([this.trustLevel, this.trustAmount]); + arr.push(writeSubPacket(sub.trustSignature, true, bytes)); + } + if (this.regularExpression !== null) { + arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); + } + if (this.revocable !== null) { + arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); + } + if (this.keyExpirationTime !== null) { + arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); + } + if (this.preferredSymmetricAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); + arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); + } + if (this.revocationKeyClass !== null) { + bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); + bytes = util.concat([bytes, this.revocationKeyFingerprint]); + arr.push(writeSubPacket(sub.revocationKey, false, bytes)); + } + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) { + // If the version of [the] key is greater than 4, this subpacket + // MUST NOT be included in the signature. + arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write())); + } + this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { + bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; + const encodedName = util.encodeUTF8(name); + // 2 octets of name length + bytes.push(util.writeNumber(encodedName.length, 2)); + // 2 octets of value length + bytes.push(util.writeNumber(value.length, 2)); + bytes.push(encodedName); + bytes.push(value); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.notationData, critical, bytes)); + }); + if (this.preferredHashAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); + arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); + } + if (this.preferredCompressionAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); + arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); + } + if (this.keyServerPreferences !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); + arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); + } + if (this.preferredKeyServer !== null) { + arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); + } + if (this.isPrimaryUserID !== null) { + arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + } + if (this.policyURI !== null) { + arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); + } + if (this.keyFlags !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); + arr.push(writeSubPacket(sub.keyFlags, true, bytes)); + } + if (this.signersUserID !== null) { + arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); + } + if (this.reasonForRevocationFlag !== null) { + bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); } - if (isArrayStream(msg.packets.stream)) { - msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + if (this.features !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); + arr.push(writeSubPacket(sub.features, false, bytes)); } - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); - const signatureList = msg.packets.filterByTag(enums.packet.signature); - if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { - await Promise.all(onePassSigList.map(async onePassSig => { - onePassSig.correspondingSig = new Promise((resolve, reject) => { - onePassSig.correspondingSigResolve = resolve; - onePassSig.correspondingSigReject = reject; - }); - onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); - onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); - onePassSig.hashed.catch(() => {}); - })); - msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { - const reader = getReader(readable); - const writer = getWriter(writable); - try { - for (let i = 0; i < onePassSigList.length; i++) { - const { value: signature } = await reader.read(); - onePassSigList[i].correspondingSigResolve(signature); - } - await reader.readToEnd(); - await writer.ready; - await writer.close(); - } catch (e) { - onePassSigList.forEach(onePassSig => { - onePassSig.correspondingSigReject(e); - }); - await writer.abort(e); - } - }); - return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + if (this.signatureTargetPublicKeyAlgorithm !== null) { + bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; + bytes.push(util.stringToUint8Array(this.signatureTargetHash)); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); } - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); - } - - /** - * Verify detached message signature - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Signature} signature - * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); + if (this.embeddedSignature !== null) { + arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); } - const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); - } - - /** - * Unwrap compressed message - * @returns {Message} Message Content of compressed message. - */ - unwrapCompressed() { - const compressed = this.packets.filterByTag(enums.packet.compressedData); - if (compressed.length) { - return new Message(compressed[0].packets); + if (this.issuerFingerprint !== null) { + bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes)); + } + if (this.preferredAEADAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); + arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); + } + if (this.preferredCipherSuites !== null) { + bytes = new Uint8Array([].concat(...this.preferredCipherSuites)); + arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes)); } - return this; - } - /** - * Append signature to unencrypted message object - * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async appendSignature(detachedSignature, config$1 = config) { - await this.packets.read( - util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, - allowedDetachedSignaturePackets, - config$1 - ); - } + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); - /** - * Returns binary encoded message - * @returns {ReadableStream} Binary message. - */ - write() { - return this.packets.write(); + return util.concat([length, result]); } /** - * Returns ASCII armored text of message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. + * Creates an Uint8Array containing the unhashed subpackets + * @returns {Uint8Array} Subpacket data. */ - armor(config$1 = config) { - return armor(enums.armor.message, this.write(), null, null, null, config$1); + writeUnhashedSubPackets() { + const arr = this.unhashedSubpackets.map(({ type, critical, body }) => { + return writeSubPacket(type, critical, body); + }); + + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); + + return util.concat([length, result]); } - } - /** - * Create signature packets for the message - * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign - * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to append - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Boolean} [detached] - Whether to create detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} List of signature packets. - * @async - * @private - */ - async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) { - const packetlist = new PacketList(); + // Signature subpackets + readSubPacket(bytes, hashed = true) { + let mypos = 0; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; + // The leftmost bit denotes a "critical" packet + const critical = !!(bytes[mypos] & 0x80); + const type = bytes[mypos] & 0x7F; - await Promise.all(signingKeys.map(async (primaryKey, i) => { - const userID = userIDs[i]; - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); + mypos++; + + if (!hashed) { + this.unhashedSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + if (!allowedUnhashedSubpackets.has(type)) { + return; + } } - const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1); - return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1); - })).then(signatureList => { - packetlist.push(...signatureList); - }); - if (signature) { - const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - packetlist.push(...existingSigPacketlist); - } - return packetlist; - } + // subpacket type + switch (type) { + case enums.signatureSubpacket.signatureCreationTime: + // Signature Creation Time + this.created = util.readDate(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.signatureExpirationTime: { + // Signature Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - /** - * Create object containing signer's keyID and validity of signature - * @param {SignaturePacket} signature - Signature packet - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Check signature validity with respect to the given date - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * keyID: module:type/keyid~KeyID, - * signature: Promise, - * verified: Promise - * }>} signer's keyID and validity of signature - * @async - * @private - */ - async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - let primaryKey; - let unverifiedSigningKey; + this.signatureNeverExpires = seconds === 0; + this.signatureExpirationTime = seconds; - for (const key of verificationKeys) { - const issuerKeys = key.getKeys(signature.issuerKeyID); - if (issuerKeys.length > 0) { - primaryKey = key; - unverifiedSigningKey = issuerKeys[0]; - break; - } - } + break; + } + case enums.signatureSubpacket.exportableCertification: + // Exportable Certification + this.exportable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.trustSignature: + // Trust Signature + this.trustLevel = bytes[mypos++]; + this.trustAmount = bytes[mypos++]; + break; + case enums.signatureSubpacket.regularExpression: + // Regular Expression + this.regularExpression = bytes[mypos]; + break; + case enums.signatureSubpacket.revocable: + // Revocable + this.revocable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.keyExpirationTime: { + // Key Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); + + this.keyExpirationTime = seconds; + this.keyNeverExpires = seconds === 0; + + break; + } + case enums.signatureSubpacket.preferredSymmetricAlgorithms: + // Preferred Symmetric Algorithms + this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.revocationKey: + // Revocation Key + // (1 octet of class, 1 octet of public-key algorithm ID, 20 + // octets of + // fingerprint) + this.revocationKeyClass = bytes[mypos++]; + this.revocationKeyAlgorithm = bytes[mypos++]; + this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); + break; + + case enums.signatureSubpacket.issuerKeyID: + // Issuer + if (this.version === 4) { + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + } else if (hashed) { + // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature, + // since the Issuer Fingerprint subpacket is to be used instead. + // The `issuerKeyID` value will be set when reading the issuerFingerprint packet. + // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it, + // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed) + // issuerFingerprint. + // If the packet is hashed, then we reject the signature, to avoid verifying data different from + // what was parsed. + throw new Error('Unexpected Issuer Key ID subpacket'); + } + break; + + case enums.signatureSubpacket.notationData: { + // Notation Data + const humanReadable = !!(bytes[mypos] & 0x80); + + // We extract key/value tuple from the byte stream. + mypos += 4; + const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; - const isOnePassSignature = signature instanceof OnePassSignaturePacket; - const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; + const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); + const value = bytes.subarray(mypos + m, mypos + m + n); - const verifiedSig = { - keyID: signature.issuerKeyID, - verified: (async () => { - if (!unverifiedSigningKey) { - throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + this.rawNotations.push({ name, humanReadable, value, critical }); + + if (humanReadable) { + this.notations[name] = util.decodeUTF8(value); + } + break; } + case enums.signatureSubpacket.preferredHashAlgorithms: + // Preferred Hash Algorithms + this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCompressionAlgorithms: + // Preferred Compression Algorithms + this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.keyServerPreferences: + // Key Server Preferences + this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredKeyServer: + // Preferred Key Server + this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.primaryUserID: + // Primary User ID + this.isPrimaryUserID = bytes[mypos++] !== 0; + break; + case enums.signatureSubpacket.policyURI: + // Policy URI + this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.keyFlags: + // Key Flags + this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signersUserID: + // Signer's User ID + this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.reasonForRevocation: + // Reason for Revocation + this.reasonForRevocationFlag = bytes[mypos++]; + this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.features: + // Features + this.features = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signatureTarget: { + // Signature Target + // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; + this.signatureTargetHashAlgorithm = bytes[mypos++]; - await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); - const signaturePacket = await signaturePacketPromise; - if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { - throw new Error('Key is newer than the signature'); + const len = mod$1.getHashByteLength(this.signatureTargetHashAlgorithm); + + this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); + break; } - // We pass the signature creation time to check whether the key was expired at the time of signing. - // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before - try { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); - } catch (e) { - // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, - // making the key invalid at the time of signing. - // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. - // Note: we do not support the edge case of a key that was reformatted and it has expired. - if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + case enums.signatureSubpacket.embeddedSignature: + // Embedded Signature + this.embeddedSignature = new SignaturePacket(); + this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.issuerFingerprint: + // Issuer Fingerprint + this.issuerKeyVersion = bytes[mypos++]; + this.issuerFingerprint = bytes.subarray(mypos, bytes.length); + if (this.issuerKeyVersion >= 5) { + this.issuerKeyID.read(this.issuerFingerprint); } else { - throw e; + this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); } - } - return true; - })(), - signature: (async () => { - const signaturePacket = await signaturePacketPromise; - const packetlist = new PacketList(); - signaturePacket && packetlist.push(signaturePacket); - return new Signature(packetlist); - })() - }; + break; + case enums.signatureSubpacket.preferredAEADAlgorithms: + // Preferred AEAD Algorithms + this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCipherSuites: + // Preferred AEAD Cipher Suites + this.preferredCipherSuites = []; + for (let i = mypos; i < bytes.length; i += 2) { + this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]); + } + break; + default: + this.unknownSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + break; + } + } - // Mark potential promise rejections as "handled". This is needed because in - // some cases, we reject them before the user has a reasonable chance to - // handle them (e.g. `await readToEnd(result.data); await result.verified` and - // the data stream errors). - verifiedSig.signature.catch(() => {}); - verifiedSig.verified.catch(() => {}); + readSubPackets(bytes, trusted = true, config) { + const subpacketLengthBytes = this.version === 6 ? 4 : 2; - return verifiedSig; - } + // Two-octet scalar octet count for following subpacket data. + const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes)); - /** - * Create list of objects containing signer's keyID and validity of signature - * @param {Array} signatureList - Array of signature packets - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} date - Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) - * @async - * @private - */ - async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - return Promise.all(signatureList.filter(function(signature) { - return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); - }).map(async function(signature) { - return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); - })); - } + let i = subpacketLengthBytes; - /** - * Reads an (optionally armored) OpenPGP message and returns a Message object - * @param {Object} options - * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed - * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New message object. - * @async - * @static - */ - async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredMessage || binaryMessage; - if (!input) { - throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); - } - if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { - throw new Error('readMessage: options.armoredMessage must be a string or stream'); - } - if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { - throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // subpacket data set (zero or more subpackets) + while (i < 2 + subpacketLength) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - if (armoredMessage) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.message) { - throw new Error('Armored text not of type message'); + this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); + + i += len.len; } - input = data; - } - const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); - const message = new Message(packetlist); - message.fromStream = streamType; - return message; - } - /** - * Creates new message object from text or binary data. - * @param {Object} options - * @param {String | ReadableStream} [options.text] - The text message contents - * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents - * @param {String} [options.filename=""] - Name of the file (if any) - * @param {Date} [options.date=current date] - Date of the message, or modification date of the file - * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type - * @returns {Promise} New message object. - * @async - * @static - */ - async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { - let input = text !== undefined ? text : binary; - if (input === undefined) { - throw new Error('createMessage: must pass options object containing `text` or `binary`'); - } - if (text && !util.isString(text) && !util.isStream(text)) { - throw new Error('createMessage: options.text must be a string or stream'); - } - if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { - throw new Error('createMessage: options.binary must be a Uint8Array or stream'); + return i; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - const literalDataPacket = new LiteralDataPacket(date); - if (text !== undefined) { - literalDataPacket.setText(input, enums.write(enums.literal, format)); - } else { - literalDataPacket.setBytes(input, enums.write(enums.literal, format)); - } - if (filename !== undefined) { - literalDataPacket.setFilename(filename); - } - const literalDataPacketlist = new PacketList(); - literalDataPacketlist.push(literalDataPacket); - const message = new Message(literalDataPacketlist); - message.fromStream = streamType; - return message; - } + // Produces data to produce signature on + toSign(type, data) { + const t = enums.signature; + + switch (type) { + case t.binary: + if (data.text !== null) { + return util.encodeUTF8(data.getText(true)); + } + return data.getBytes(true); + + case t.text: { + const bytes = data.getBytes(true); + // normalize EOL to \r\n + return util.canonicalizeEOL(bytes); + } + case t.standalone: + return new Uint8Array(0); + + case t.certGeneric: + case t.certPersona: + case t.certCasual: + case t.certPositive: + case t.certRevocation: { + let packet; + let tag; - // GPG4Browsers - An OpenPGP implementation in javascript + if (data.userID) { + tag = 0xB4; + packet = data.userID; + } else if (data.userAttribute) { + tag = 0xD1; + packet = data.userAttribute; + } else { + throw new Error('Either a userID or userAttribute packet needs to be ' + + 'supplied for certification.'); + } - // A Cleartext message can contain the following packets - const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + const bytes = packet.write(); - /** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} - */ - class CleartextMessage { - /** - * @param {String} text - The cleartext of the signed message - * @param {Signature} signature - The detached signature or an empty signature for unsigned messages - */ - constructor(text, signature) { - // remove trailing whitespace and normalize EOL to canonical form - this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); - if (signature && !(signature instanceof Signature)) { - throw new Error('Invalid signature input'); + return util.concat([this.toSign(t.key, data), + new Uint8Array([tag]), + util.writeNumber(bytes.length, 4), + bytes]); + } + case t.subkeyBinding: + case t.subkeyRevocation: + case t.keyBinding: + return util.concat([this.toSign(t.key, data), this.toSign(t.key, { + key: data.bind + })]); + + case t.key: + if (data.key === undefined) { + throw new Error('Key packet is required for this signature.'); + } + return data.key.writeForHash(this.version); + + case t.keyRevocation: + return this.toSign(t.key, data); + case t.timestamp: + return new Uint8Array(0); + case t.thirdParty: + throw new Error('Not implemented'); + default: + throw new Error('Unknown signature type.'); } - this.signature = signature || new Signature(new PacketList()); } - /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns {Array} Array of keyID objects. - */ - getSigningKeyIDs() { - const keyIDs = []; - const signatureList = this.signature.packets; - signatureList.forEach(function(packet) { - keyIDs.push(packet.issuerKeyID); + calculateTrailer(data, detached) { + let length = 0; + return transform(clone(this.signatureData), value => { + length += value.length; + }, () => { + const arr = []; + if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { + if (detached) { + arr.push(new Uint8Array(6)); + } else { + arr.push(data.writeHeader()); + } + } + arr.push(new Uint8Array([this.version, 0xFF])); + if (this.version === 5) { + arr.push(new Uint8Array(4)); + } + arr.push(util.writeNumber(length, 4)); + // For v5, this should really be writeNumber(length, 8) rather than the + // hardcoded 4 zero bytes above + return util.concat(arr); }); - return keyIDs; } - /** - * Sign the cleartext message - * @param {Array} privateKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] - * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New cleartext message with signed content. - * @async - */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = new LiteralDataPacket(); - literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - return new CleartextMessage(this.text, newSignature); - } + toHash(signatureType, data, detached = false) { + const bytes = this.toSign(signatureType, data); - /** - * Verify signatures of cleartext signed message - * @param {Array} keys - Array of keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verify(keys, date = new Date(), config$1 = config) { - const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - const literalDataPacket = new LiteralDataPacket(); - // we assume that cleartext signature is generated based on UTF8 cleartext - literalDataPacket.setText(this.text); - return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]); } - /** - * Get cleartext - * @returns {String} Cleartext of message. - */ - getText() { - // normalize end of line to \n - return this.text.replace(/\r\n/g, '\n'); + async hash(signatureType, data, toHash, detached = false) { + if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) { + // avoid hashing unexpected salt size + throw new Error('Signature salt does not have the expected length'); + } + + if (!toHash) toHash = this.toHash(signatureType, data, detached); + return mod$1.hash.digest(this.hashAlgorithm, toHash); } /** - * Returns ASCII armored text of cleartext signed message + * verifies the signature packet. Note: not all signature types are implemented + * @param {PublicSubkeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature + * @param {module:enums.signature} signatureType - Expected signature type + * @param {Uint8Array|Object} data - Data which on the signature applies + * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration + * @param {Boolean} [detached] - Whether to verify a detached signature * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {String | ReadableStream} ASCII armor. + * @throws {Error} if signature validation failed + * @async */ - armor(config$1 = config) { - let hashes = this.signature.packets.map(function(packet) { - return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); - }); - hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); - const body = { - hash: hashes.join(), - text: this.text, - data: this.signature.packets.write() - }; - return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1); - } - } + async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { + if (!this.issuerKeyID.equals(key.getKeyID())) { + throw new Error('Signature was not issued by the given public key'); + } + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); + } - /** - * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param {Object} options - * @param {String} options.cleartextMessage - Text to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New cleartext message object. - * @async - * @static - */ - async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!cleartextMessage) { - throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); - } - if (!util.isString(cleartextMessage)) { - throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; + // Cryptographic validity is cached after one successful verification. + // However, for message signatures, we always re-verify, since the passed `data` can change + const skipVerify = this[verified] && !isMessageSignature; + if (!skipVerify) { + let toHash; + let hash; + if (this.hashed) { + hash = await this.hashed; + } else { + toHash = this.toHash(signatureType, data, detached); + hash = await this.hash(signatureType, data, toHash); + } + hash = await readToEnd(hash); + if (this.signedHashValue[0] !== hash[0] || + this.signedHashValue[1] !== hash[1]) { + throw new Error('Signed digest did not match'); + } - const input = await unarmor(cleartextMessage); - if (input.type !== enums.armor.signed) { - throw new Error('No cleartext signed message.'); - } - const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1); - verifyHeaders$1(input.headers, packetlist); - const signature = new Signature(packetlist); - return new CleartextMessage(input.text, signature); - } + this.params = await this.params; - /** - * Compare hash algorithm specified in the armor header with signatures - * @param {Array} headers - Armor headers - * @param {PacketList} packetlist - The packetlist with signature packets - * @private - */ - function verifyHeaders$1(headers, packetlist) { - const checkHashAlgos = function(hashAlgos) { - const check = packet => algo => packet.hashAlgorithm === algo; + this[verified] = await mod$1.signature.verify( + this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, + toHash, hash + ); - for (let i = 0; i < packetlist.length; i++) { - if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { - return false; + if (!this[verified]) { + throw new Error('Signature verification failed'); } } - return true; - }; - let oneHeader = null; - let hashAlgos = []; - headers.forEach(function(header) { - oneHeader = header.match(/^Hash: (.+)$/); // get header value - if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace - oneHeader = oneHeader.split(','); - oneHeader = oneHeader.map(function(hash) { - hash = hash.toLowerCase(); - try { - return enums.write(enums.hash, hash); - } catch (e) { - throw new Error('Unknown hash algorithm in armor header: ' + hash); - } - }); - hashAlgos = hashAlgos.concat(oneHeader); - } else { - throw new Error('Only "Hash" header allowed in cleartext signed message'); + const normDate = util.normalizeDate(date); + if (normDate && this.created > normDate) { + throw new Error('Signature creation time is in the future'); + } + if (normDate && normDate >= this.getExpirationTime()) { + throw new Error('Signature is expired'); + } + if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { + throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && + [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { + throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + this.unknownSubpackets.forEach(({ type, critical }) => { + if (critical) { + throw new Error(`Unknown critical signature subpacket type ${type}`); + } + }); + this.rawNotations.forEach(({ name, critical }) => { + if (critical && (config$1.knownNotations.indexOf(name) < 0)) { + throw new Error(`Unknown critical notation: ${name}`); + } + }); + if (this.revocationKeyClass !== null) { + throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); + } + } + + /** + * Verifies signature expiration date + * @param {Date} [date] - Use the given date for verification instead of the current time + * @returns {Boolean} True if expired. + */ + isExpired(date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + return !(this.created <= normDate && normDate < this.getExpirationTime()); } - }); + return false; + } - if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { - throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { - throw new Error('Hash algorithm mismatch in armor header and signature'); + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns {Date | Infinity} Expiration time. + */ + getExpirationTime() { + return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); } } /** - * Creates a new CleartextMessage object from text - * @param {Object} options - * @param {String} options.text - * @static - * @async + * Creates a Uint8Array representation of a sub signature packet + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} + * @param {Integer} type - Subpacket signature type. + * @param {Boolean} critical - Whether the subpacket should be critical. + * @param {String} data - Data to be included + * @returns {Uint8Array} The signature subpacket. + * @private */ - async function createCleartextMessage({ text, ...rest }) { - if (!text) { - throw new Error('createCleartextMessage: must pass options object containing `text`'); - } - if (!util.isString(text)) { - throw new Error('createCleartextMessage: options.text must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - return new CleartextMessage(text); + function writeSubPacket(type, critical, data) { + const arr = []; + arr.push(writeSimpleLength(data.length + 1)); + arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); + arr.push(data); + return util.concat(arr); } - // OpenPGP.js - An OpenPGP implementation in javascript - + /** + * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh. + * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5} + * @param {enums.hash} hashAlgorithm - Hash algorithm. + * @returns {Integer} Salt length. + * @private + */ + function saltLengthForHash(hashAlgorithm) { + switch (hashAlgorithm) { + case enums.hash.sha256: return 16; + case enums.hash.sha384: return 24; + case enums.hash.sha512: return 32; + case enums.hash.sha224: return 16; + case enums.hash.sha3_256: return 16; + case enums.hash.sha3_512: return 32; + default: throw new Error('Unsupported hash function'); + } + } - ////////////////////// - // // - // Key handling // - // // - ////////////////////// + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. - * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. - * @param {Object} options - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys - * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: - * curve25519 (default), p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 - * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` - * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static + * Implementation of the One-Pass Signature Packets (Tag 4) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. */ - async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key generation'); - } - if (type === 'rsa' && rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + class OnePassSignaturePacket { + static get tag() { + return enums.packet.onePassSignature; } - const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - - try { - const { key, revocationCertificate } = await generate$4(options, config$1); - key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); + static fromSignaturePacket(signaturePacket, isLast) { + const onePassSig = new OnePassSignaturePacket(); + onePassSig.version = signaturePacket.version === 6 ? 6 : 3; + onePassSig.signatureType = signaturePacket.signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; + onePassSig.salt = signaturePacket.salt; // v6 only + onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only - return { - privateKey: formatObject(key, format, config$1), - publicKey: formatObject(key.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error generating keypair', err); + onePassSig.flags = isLast ? 1 : 0; + return onePassSig; } - } - /** - * Reformats signature packets for a key and rewraps key object. - * @param {Object} options - * @param {PrivateKey} options.privateKey - Private key to reformat - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended - * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static - */ - async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + constructor() { + /** A one-octet version number. The current versions are 3 and 6. */ + this.version = null; + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + * @type {enums.signature} - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key reformat'); + */ + this.signatureType = null; + /** + * A one-octet number describing the hash algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} + * @type {enums.hash} + */ + this.hashAlgorithm = null; + /** + * A one-octet number describing the public-key algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} + * @type {enums.publicKey} + */ + this.publicKeyAlgorithm = null; + /** Only for v6, a variable-length field containing the salt. */ + this.salt = null; + /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */ + this.issuerKeyID = null; + /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */ + this.issuerFingerprint = null; + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + this.flags = null; } - const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - try { - const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); + /** + * parsing function for a one-pass signature packet (tag 4). + * @param {Uint8Array} bytes - Payload of a tag 4 packet + * @returns {OnePassSignaturePacket} Object representation. + */ + read(bytes) { + let mypos = 0; + // A one-octet version number. The current versions are 3 or 6. + this.version = bytes[mypos++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); + } - return { - privateKey: formatObject(reformattedKey, format, config$1), - publicKey: formatObject(reformattedKey.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error reformatting keypair', err); - } - } + // A one-octet signature type. Signature types are described in + // Section 5.2.1. + this.signatureType = bytes[mypos++]; - /** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. - * @param {Object} options - * @param {Key} options.key - Public or private key to revoke - * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with - * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation - * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation - * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The revoked key in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or - * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise - * @async - * @static - */ - async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // A one-octet number describing the hash algorithm used. + this.hashAlgorithm = bytes[mypos++]; - try { - const revokedKey = revocationCertificate ? - await key.applyRevocationCertificate(revocationCertificate, date, config$1) : - await key.revoke(reasonForRevocation, date, config$1); + // A one-octet number describing the public-key algorithm used. + this.publicKeyAlgorithm = bytes[mypos++]; - return revokedKey.isPrivate() ? { - privateKey: formatObject(revokedKey, format, config$1), - publicKey: formatObject(revokedKey.toPublic(), format, config$1) - } : { - privateKey: null, - publicKey: formatObject(revokedKey, format, config$1) - }; - } catch (err) { - throw util.wrapError('Error revoking key', err); - } - } + if (this.version === 6) { + // Only for v6 signatures, a variable-length field containing: - /** - * Unlock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to decrypt - * @param {String|Array} options.passphrase - The user's passphrase(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The unlocked key object. - * @async - */ - async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[mypos++]; - if (!privateKey.isPrivate()) { - throw new Error('Cannot decrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); - const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(mypos, mypos + saltLength); + mypos += saltLength; - try { - await Promise.all(clonedPrivateKey.getKeys().map(key => ( - // try to decrypt each key with any of the given passphrases - util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) - ))); + // Only for v6 packets, 32 octets of the fingerprint of the signing key. + this.issuerFingerprint = bytes.subarray(mypos, mypos + 32); + mypos += 32; + this.issuerKeyID = new KeyID(); + // For v6 the Key ID is the high-order 64 bits of the fingerprint. + this.issuerKeyID.read(this.issuerFingerprint); + } else { + // Only for v3 packets, an eight-octet number holding the Key ID of the signing key. + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); + mypos += 8; + } - await clonedPrivateKey.validate(config$1); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error decrypting private key', err); + // A one-octet number holding a flag showing whether the signature + // is nested. A zero value indicates that the next packet is + // another One-Pass Signature packet that describes another + // signature to be applied to the same message data. + this.flags = bytes[mypos++]; + return this; } - } - - /** - * Lock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to encrypt - * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The locked key object. - * @async - */ - async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (!privateKey.isPrivate()) { - throw new Error('Cannot encrypt a public key'); + /** + * creates a string representation of a one-pass signature packet + * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. + */ + write() { + const arr = [new Uint8Array([ + this.version, + this.signatureType, + this.hashAlgorithm, + this.publicKeyAlgorithm + ])]; + if (this.version === 6) { + arr.push( + new Uint8Array([this.salt.length]), + this.salt, + this.issuerFingerprint + ); + } else { + arr.push(this.issuerKeyID.write()); + } + arr.push(new Uint8Array([this.flags])); + return util.concatUint8Array(arr); } - const clonedPrivateKey = privateKey.clone(true); - const keys = clonedPrivateKey.getKeys(); - const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); - if (passphrases.length !== keys.length) { - throw new Error('Invalid number of passphrases given for key encryption'); + calculateTrailer(...args) { + return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); } - try { - await Promise.all(keys.map(async (key, i) => { - const { keyPacket } = key; - await keyPacket.encrypt(passphrases[i], config$1); - keyPacket.clearPrivateParams(); - })); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error encrypting private key', err); + async verify() { + const correspondingSig = await this.correspondingSig; + if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { + throw new Error('Corresponding signature packet missing'); + } + if ( + correspondingSig.signatureType !== this.signatureType || + correspondingSig.hashAlgorithm !== this.hashAlgorithm || + correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) || + (this.version === 3 && correspondingSig.version === 6) || + (this.version === 6 && correspondingSig.version !== 6) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt)) + ) { + throw new Error('Corresponding signature packet does not match one-pass signature packet'); + } + correspondingSig.hashed = this.hashed; + return correspondingSig.verify.apply(correspondingSig, arguments); } } - - /////////////////////////////////////////// - // // - // Message encryption and decryption // - // // - /////////////////////////////////////////// - + OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; + OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; + OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; /** - * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` - * must be specified. If signing keys are specified, those will be used to sign the message. - * @param {Object} options - * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message - * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed - * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message - * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Signature} [options.signature] - A detached signature to add to the encrypted message - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` - * @param {Date} [options.date=current date] - Override the creation date of the message signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static + * Instantiate a new packet given its tag + * @function newPacketFromTag + * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @returns {Object} New packet object with type based on tag + * @throws {Error|UnsupportedError} for disallowed or unknown packets */ - async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords); - signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations); - if (rest.detached) { - throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); - } - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (!signingKeys) { - signingKeys = []; - } - const streaming = message.fromStream; - try { - if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified - message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); + function newPacketFromTag(tag, allowedPackets) { + if (!allowedPackets[tag]) { + // distinguish between disallowed packets and unknown ones + let packetType; + try { + packetType = enums.read(enums.packet, tag); + } catch (e) { + throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`); } - message = message.compress( - await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1), - config$1 - ); - message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - if (format === 'object') return message; - // serialize data - const armor = format === 'armored'; - const data = armor ? message.armor(config$1) : message.write(); - return convertStream(data, streaming, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error encrypting message', err); + throw new Error(`Packet not allowed in this context: ${packetType}`); } + return new allowedPackets[tag](); } /** - * Decrypts a message with the user's private key, a session key or a password. - * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). - * @param {Object} options - * @param {Message} options.message - The message object with the encrypted data - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key - * @param {String|String[]} [options.passwords] - Passwords to decrypt the message - * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } - * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: MaybeStream, (if format was 'utf8', the default) - * data: MaybeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + * @extends Array */ - async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + class PacketList extends Array { + /** + * Parses the given binary data and returns a list of packets. + * Equivalent to calling `read` on an empty PacketList instance. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @returns {PacketList} parsed list of packets + * @throws on parsing errors + * @async + */ + static async fromBinary(bytes, allowedPackets, config$1 = config) { + const packets = new PacketList(); + await packets.read(bytes, allowedPackets, config$1); + return packets; + } - try { - const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); - if (!verificationKeys) { - verificationKeys = []; + /** + * Reads a stream of binary data and interprets it as a list of packets. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @throws on parsing errors + * @async + */ + async read(bytes, allowedPackets, config$1 = config) { + if (config$1.additionalAllowedPackets.length) { + allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; } + this.stream = transformPair(bytes, async (readable, writable) => { + const writer = getWriter(writable); + try { + while (true) { + await writer.ready; + const done = await readPackets(readable, async parsed => { + try { + if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) { + // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: + // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 + // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 + // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21 + return; + } + const packet = newPacketFromTag(parsed.tag, allowedPackets); + packet.packets = new PacketList(); + packet.fromStream = util.isStream(parsed.packet); + await packet.read(parsed.packet, config$1); + await writer.write(packet); + } catch (e) { + // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence, + // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored. + // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical. + if (e instanceof UnknownPacketError) { + if (parsed.tag <= 39) { + await writer.abort(e); + } else { + return; + } + } - const result = {}; - result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); - result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); - result.filename = decrypted.getFilename(); - linkStreams(result, message); - if (expectSigned) { - if (verificationKeys.length === 0) { - throw new Error('Verification keys are required to verify message signatures'); + const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; + const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); + if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { + // The packets that support streaming are the ones that contain message data. + // Those are also the ones we want to be more strict about and throw on parse errors + // (since we likely cannot process the message without these packets anyway). + await writer.abort(e); + } else { + const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); + await writer.write(unparsedPacket); + } + util.printDebugError(e); + } + }); + if (done) { + await writer.ready; + await writer.close(); + return; + } + } + } catch (e) { + await writer.abort(e); + } + }); + + // Wait until first few packets have been read + const reader = getReader(this.stream); + while (true) { + const { done, value } = await reader.read(); + if (!done) { + this.push(value); + } else { + this.stream = null; } - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); + if (done || supportsStreaming(value.constructor.tag)) { + break; } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error decrypting message', err); + reader.releaseLock(); } - } + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. + */ + write() { + const arr = []; - ////////////////////////////////////////// - // // - // Message signing and verification // - // // - ////////////////////////////////////////// + for (let i = 0; i < this.length; i++) { + const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; + const packetbytes = this[i].write(); + if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { + let buffer = []; + let bufferLength = 0; + const minLength = 512; + arr.push(writeTag(tag)); + arr.push(transform(packetbytes, value => { + buffer.push(value); + bufferLength += value.length; + if (bufferLength >= minLength) { + const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); + const chunkSize = 2 ** powerOf2; + const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); + buffer = [bufferConcat.subarray(1 + chunkSize)]; + bufferLength = buffer[0].length; + return bufferConcat.subarray(0, 1 + chunkSize); + } + }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); + } else { + if (util.isStream(packetbytes)) { + let length = 0; + arr.push(transform(clone(packetbytes), value => { + length += value.length; + }, () => writeHeader(tag, length))); + } else { + arr.push(writeHeader(tag, packetbytes.length)); + } + arr.push(packetbytes); + } + } + return util.concat(arr); + } - /** - * Signs a message. - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed - * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [options.date=current date] - Override the creation date of the signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ - async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); checkOutputMessageFormat(format); - signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations); + /** + * Creates a new PacketList with all packets matching the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {PacketList} + */ + filterByTag(...tags) { + const filtered = new PacketList(); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const handle = tag => packetType => tag === packetType; - if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); - if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(this[i].constructor.tag))) { + filtered.push(this[i]); + } + } - if (!signingKeys || signingKeys.length === 0) { - throw new Error('No signing keys provided'); + return filtered; } - try { - let signature; - if (detached) { - signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } else { - signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - if (format === 'object') return signature; + /** + * Traverses packet list and returns first packet with matching tag + * @param {module:enums.packet} tag - The packet tag + * @returns {Packet|undefined} + */ + findPacket(tag) { + return this.find(packet => packet.constructor.tag === tag); + } - const armor = format === 'armored'; - signature = armor ? signature.armor(config$1) : signature.write(); - if (detached) { - signature = transformPair(message.packets.write(), async (readable, writable) => { - await Promise.all([ - pipe(signature, writable), - readToEnd(readable).catch(() => {}) - ]); - }); + /** + * Find indices of packets with the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {Integer[]} packet indices + */ + indexOfTag(...tags) { + const tagIndex = []; + const that = this; + + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(that[i].constructor.tag))) { + tagIndex.push(i); + } } - return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error signing message', err); + return tagIndex; } } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + // A Compressed Data packet can contain the following packet types + const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket + ]); + /** - * Verifies signatures of cleartext signed message - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures - * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: MaybeStream, (if `message` was a CleartextMessage) - * data: MaybeStream, (if `message` was a Message) - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } + * Implementation of the Compressed Data Packet (Tag 8) * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. */ - async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + class CompressedDataPacket { + static get tag() { + return enums.packet.compressedData; + } - if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); - if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + /** + * List of packets + * @type {PacketList} + */ + this.packets = null; + /** + * Compression algorithm + * @type {enums.compression} + */ + this.algorithm = config$1.preferredCompressionAlgorithm; - try { - const result = {}; - if (signature) { - result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); - } else { - result.signatures = await message.verify(verificationKeys, date, config$1); - } - result.data = format === 'binary' ? message.getLiteralData() : message.getText(); - if (message.fromStream && !signature) linkStreams(result, message); - if (expectSigned) { - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); - } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); + /** + * Compressed packet data + * @type {Uint8Array | ReadableStream} + */ + this.compressed = null; + } + + /** + * Parsing function for the packet. + * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async read(bytes, config$1 = config) { + await parse(bytes, async reader => { + + // One octet that gives the algorithm used to compress the packet. + this.algorithm = await reader.readByte(); + + // Compressed data, which makes up the remainder of the packet. + this.compressed = reader.remainder(); + + await this.decompress(config$1); + }); + } + + + /** + * Return the compressed packet. + * @returns {Uint8Array | ReadableStream} Binary compressed packet. + */ + write() { + if (this.compressed === null) { + this.compress(); } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error verifying signed message', err); + + return util.concat([new Uint8Array([this.algorithm]), this.compressed]); } - } - /////////////////////////////////////////////// - // // - // Session key encryption and decryption // - // // - /////////////////////////////////////////////// + /** + * Decompression method for decompressing the compressed data + * read by read_packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async decompress(config$1 = config) { + const compressionName = enums.read(enums.compression, this.algorithm); + const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async + if (!decompressionFn) { + throw new Error(`${compressionName} decompression not supported`); + } - /** - * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. - * @param {Object} options - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} - * @param {Date} [options.date=current date] - Date to select algorithm preferences at - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. - * @async - * @static - */ - async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets$5, config$1); + } - try { - const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error generating session key', err); + /** + * Compress the packet data (member decompressedData) + */ + compress() { + const compressionName = enums.read(enums.compression, this.algorithm); + const compressionFn = compress_fns[compressionName]; + if (!compressionFn) { + throw new Error(`${compressionName} compression not supported`); + } + + this.compressed = compressionFn(this.packets.write()); } } + ////////////////////////// + // // + // Helper functions // + // // + ////////////////////////// + /** - * Encrypt a symmetric session key with public keys, passwords, or both at once. - * At least one of `encryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) - * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key - * @param {String|String[]} [options.passwords] - Passwords for the message - * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [options.date=current date] - Override the date - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static + * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise. + * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator + * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor + * @returns {ReadableStream} compressed or decompressed data */ - async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) { + return data => { + if (!util.isStream(data) || isArrayStream(data)) { + return fromAsync(() => readToEnd(data).then(inputData => { + return new Promise((resolve, reject) => { + const zlibStream = new ZlibStreamedConstructor(); + zlibStream.ondata = processedData => { + resolve(processedData); + }; + try { + zlibStream.push(inputData, true); // only one chunk to push + } catch (err) { + reject(err); + } + }); + })); + } - if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { - throw new Error('No encryption keys or passwords provided.'); - } + // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) + if (compressionStreamInstantiator) { + try { + const compressorOrDecompressor = compressionStreamInstantiator(); + return data.pipeThrough(compressorOrDecompressor); + } catch (err) { + // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate. + if (err.name !== 'TypeError') { + throw err; + } + } + } - try { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - return formatObject(message, format, config$1); - } catch (err) { - throw util.wrapError('Error encrypting session key', err); - } + // JS fallback + const inputReader = data.getReader(); + const zlibStream = new ZlibStreamedConstructor(); + + return new ReadableStream({ + async start(controller) { + zlibStream.ondata = async (value, isLast) => { + controller.enqueue(value); + if (isLast) { + controller.close(); + } + }; + + while (true) { + const { done, value } = await inputReader.read(); + if (done) { + zlibStream.push(new Uint8Array(), true); + return; + } else if (value.length) { + zlibStream.push(value); + } + } + } + }); + }; + } + + function bzip2Decompress() { + return async function(data) { + const { decode: bunzipDecode } = await Promise.resolve().then(function () { return index; }); + return fromAsync(async () => bunzipDecode(await readToEnd(data))); + }; } /** - * Decrypt symmetric session keys using private keys or passwords (not both). - * One of `decryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Message} options.message - A message object containing the encrypted session key packets - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data - * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key - * @param {Date} [options.date] - Date to use for key verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: - * { data:Uint8Array, algorithm:String } - * @throws if no session key could be found or decrypted - * @async - * @static + * Get Compression Stream API instatiators if the constructors are implemented. + * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported + * (supported formats cannot be determined in advance). + * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat + * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }} */ - async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const getCompressionStreamInstantiators = compressionFormat => ({ + compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)), + decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat)) + }); - try { - const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error decrypting session keys', err); - } - } + const compress_fns = { + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib) + }; + const decompress_fns = { + uncompressed: data => data, + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib), + bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import + }; - ////////////////////////// - // // - // Helper functions // - // // - ////////////////////////// + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + // A SEIP packet can contain the following packet types + const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + ]); + /** - * Input validation - * @private + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. */ - function checkString(data, name) { - if (!util.isString(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type String'); + class SymEncryptedIntegrityProtectedDataPacket { + static get tag() { + return enums.packet.symEncryptedIntegrityProtectedData; } - } - function checkBinary(data, name) { - if (!util.isUint8Array(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array'); + + static fromObject({ version, aeadAlgorithm }) { + if (version !== 1 && version !== 2) { + throw new Error('Unsupported SEIPD version'); + } + + const seip = new SymEncryptedIntegrityProtectedDataPacket(); + seip.version = version; + if (version === 2) { + seip.aeadAlgorithm = aeadAlgorithm; + } + + return seip; } - } - function checkMessage(message) { - if (!(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message'); + + constructor() { + this.version = null; + + // The following 4 fields are for V2 only. + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = null; + this.chunkSizeByte = null; + this.salt = null; + + this.encrypted = null; + this.packets = null; } - } - function checkCleartextOrMessage(message) { - if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); + + async read(bytes) { + await parse(bytes, async reader => { + this.version = await reader.readByte(); + // - A one-octet version number with value 1 or 2. + if (this.version !== 1 && this.version !== 2) { + throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`); + } + + if (this.version === 2) { + // - A one-octet cipher algorithm. + this.cipherAlgorithm = await reader.readByte(); + // - A one-octet AEAD algorithm. + this.aeadAlgorithm = await reader.readByte(); + // - A one-octet chunk size. + this.chunkSizeByte = await reader.readByte(); + // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique. + this.salt = await reader.readBytes(32); + } + + // For V1: + // - Encrypted data, the output of the selected symmetric-key cipher + // operating in Cipher Feedback mode with shift amount equal to the + // block size of the cipher (CFB-n where n is the block size). + // For V2: + // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode. + // - A final, summary authentication tag for the AEAD mode. + this.encrypted = reader.remainder(); + }); } - } - function checkOutputMessageFormat(format) { - if (format !== 'armored' && format !== 'binary' && format !== 'object') { - throw new Error(`Unsupported format ${format}`); + + write() { + if (this.version === 2) { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]); + } + return util.concat([new Uint8Array([this.version]), this.encrypted]); + } + + /** + * Encrypt the payload in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on encryption failure + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + const { blockSize, keySize } = mod$1.getCipherParams(sessionKeyAlgorithm); + if (key.length !== keySize) { + throw new Error('Unexpected session key size'); + } + + let bytes = this.packets.write(); + if (isArrayStream(bytes)) bytes = await readToEnd(bytes); + + if (this.version === 2) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + this.salt = mod$1.random.getRandomBytes(32); + this.chunkSizeByte = config$1.aeadChunkSizeByte; + this.encrypted = await runAEAD(this, 'encrypt', key, bytes); + } else { + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet + + const tohash = util.concat([prefix, bytes, mdc]); + const hash = await mod$1.hash.sha1(passiveClone(tohash)); + const plaintext = util.concat([tohash, hash]); + + this.encrypted = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); + } + return true; } - } - const defaultConfigPropsCount = Object.keys(config).length; - function checkConfig(config$1) { - const inputConfigProps = Object.keys(config$1); - if (inputConfigProps.length !== defaultConfigPropsCount) { - for (const inputProp of inputConfigProps) { - if (config[inputProp] === undefined) { - throw new Error(`Unknown config property: ${inputProp}`); + + /** + * Decrypts the encrypted data contained in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on decryption failure + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + if (key.length !== mod$1.getCipherParams(sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + + let encrypted = clone(this.encrypted); + if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); + + let packetbytes; + if (this.version === 2) { + if (this.cipherAlgorithm !== sessionKeyAlgorithm) { + // sanity check + throw new Error('Unexpected session key algorithm'); + } + packetbytes = await runAEAD(this, 'decrypt', key, encrypted); + } else { + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); + + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + const realHash = slice(passiveClone(decrypted), -20); + const tohash = slice(decrypted, 0, -20); + const verifyHash = Promise.all([ + readToEnd(await mod$1.hash.sha1(passiveClone(tohash))), + readToEnd(realHash) + ]).then(([hash, mdc]) => { + if (!util.equalsUint8Array(hash, mdc)) { + throw new Error('Modification detected.'); + } + return new Uint8Array(); + }); + const bytes = slice(tohash, blockSize + 2); // Remove random prefix + packetbytes = slice(bytes, 0, -2); // Remove MDC packet + packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); + if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { + packetbytes = await readToEnd(packetbytes); } } - } - } - /** - * Normalize parameter to an array if it is not undefined. - * @param {Object} param - the parameter to be normalized - * @returns {Array|undefined} The resulting array or undefined. - * @private - */ - function toArray$1(param) { - if (param && !util.isArray(param)) { - param = [param]; + this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1); + return true; } - return param; } /** - * Convert data to or from Stream - * @param {Object} data - the data to convert - * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type - * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams - * @returns {Promise} The data in the respective format. + * En/decrypt the payload. + * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt + * @param {Uint8Array} key - The session key used to en/decrypt the payload + * @param {Uint8Array | ReadableStream} data - The data to en/decrypt + * @returns {Promise>} * @async - * @private - */ - async function convertStream(data, streaming, encoding = 'utf8') { - const streamType = util.isStream(data); - if (streamType === 'array') { - return readToEnd(data); - } - if (streaming === 'node') { - data = webToNode(data); - if (encoding !== 'binary') data.setEncoding(encoding); - return data; - } - if (streaming === 'web' && streamType === 'ponyfill') { - return toNativeReadable(data); - } - return data; - } - - /** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param {Object} result - the data to convert - * @param {Message} message - message object - * @returns {Object} - * @private */ - function linkStreams(result, message) { - result.data = transformPair(message.packets.stream, async (readable, writable) => { - await pipe(result.data, writable, { - preventClose: true - }); + async function runAEAD(packet, fn, key, data) { + const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2; + const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import) + if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type'); + + const mode = mod$1.getAEADMode(packet.aeadAlgorithm); + const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; + const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; + const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) + const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0; + const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP); + const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP); + const adataTagArray = new Uint8Array(adataBuffer); + const adataView = new DataView(adataBuffer); + const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); + adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0); + let chunkIndex = 0; + let latestPromise = Promise.resolve(); + let cryptedBytes = 0; + let queuedBytes = 0; + let iv; + let ivView; + if (isSEIPDv2) { + const { keySize } = mod$1.getCipherParams(packet.cipherAlgorithm); + const { ivLength } = mode; + const info = new Uint8Array(adataBuffer, 0, 5); + const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength); + key = derived.subarray(0, keySize); + iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. + iv.fill(0, iv.length - 8); + ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + } else { // AEADEncryptedDataPacket + iv = packet.iv; + // ivView is unused in this case + } + const modeInstance = await mode(packet.cipherAlgorithm, key); + return transformPair(data, async (readable, writable) => { + if (util.isStream(readable) !== 'array') { + const buffer = new TransformStream({}, { + highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6), + size: array => array.length + }); + pipe(buffer.readable, writable); + writable = buffer.writable; + } + const reader = getReader(readable); const writer = getWriter(writable); try { - // Forward errors in the message stream to result.data. - await readToEnd(readable, _ => _); - await writer.close(); + while (true) { + let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); + const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); + chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); + let cryptedPromise; + let done; + let nonce; + if (isSEIPDv2) { // SEIPD V2 + nonce = iv; + } else { // AEADEncryptedDataPacket + nonce = iv.slice(); + for (let i = 0; i < 8; i++) { + nonce[iv.length - 8 + i] ^= chunkIndexArray[i]; + } + } + if (!chunkIndex || chunk.length) { + reader.unshift(finalChunk); + cryptedPromise = modeInstance[fn](chunk, nonce, adataArray); + cryptedPromise.catch(() => {}); + queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; + } else { + // After the last chunk, we either encrypt a final, empty + // data chunk to get the final authentication tag or + // validate that final authentication tag. + adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...) + cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray); + cryptedPromise.catch(() => {}); + queuedBytes += tagLengthIfEncrypting; + done = true; + } + cryptedBytes += chunk.length - tagLengthIfDecrypting; + // eslint-disable-next-line @typescript-eslint/no-loop-func + latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { + await writer.ready; + await writer.write(crypted); + queuedBytes -= crypted.length; + }).catch(err => writer.abort(err)); + if (done || queuedBytes > writer.desiredSize) { + await latestPromise; // Respect backpressure + } + if (!done) { + if (isSEIPDv2) { // SEIPD V2 + ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...) + } else { // AEADEncryptedDataPacket + adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) + } + } else { + await writer.close(); + break; + } + } } catch (e) { + await writer.ready.catch(() => {}); await writer.abort(e); } }); } - /** - * Convert the object to the given format - * @param {Key|Message} object - * @param {'armored'|'binary'|'object'} format - * @param {Object} config - Full configuration - * @returns {String|Uint8Array|Object} - */ - function formatObject(object, format, config) { - switch (format) { - case 'object': - return object; - case 'armored': - return object.armor(config); - case 'binary': - return object.write(); - default: - throw new Error(`Unsupported format ${format}`); - } - } - - /** - * web-streams-polyfill v3.0.3 - */ - /// - const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? - Symbol : - description => `Symbol(${description})`; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2016 Tankred Hase + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /// - function noop() { - return undefined; - } - function getGlobals() { - if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else if (typeof global !== 'undefined') { - return global; - } - return undefined; - } - const globals = getGlobals(); - function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; - } - const rethrowAssertionErrorRejection = noop; + // An AEAD-encrypted Data packet can contain the following packet types + const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + ]); - const originalPromise = Promise; - const originalPromiseThen = Promise.prototype.then; - const originalPromiseResolve = Promise.resolve.bind(originalPromise); - const originalPromiseReject = Promise.reject.bind(originalPromise); - function newPromise(executor) { - return new originalPromise(executor); - } - function promiseResolvedWith(value) { - return originalPromiseResolve(value); - } - function promiseRejectedWith(reason) { - return originalPromiseReject(reason); - } - function PerformPromiseThen(promise, onFulfilled, onRejected) { - // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an - // approximation. - return originalPromiseThen.call(promise, onFulfilled, onRejected); - } - function uponPromise(promise, onFulfilled, onRejected) { - PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); - } - function uponFulfillment(promise, onFulfilled) { - uponPromise(promise, onFulfilled); - } - function uponRejection(promise, onRejected) { - uponPromise(promise, undefined, onRejected); - } - function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { - return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); - } - function setPromiseIsHandledToTrue(promise) { - PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); - } - const queueMicrotask = (() => { - const globalQueueMicrotask = globals && globals.queueMicrotask; - if (typeof globalQueueMicrotask === 'function') { - return globalQueueMicrotask; - } - const resolvedPromise = promiseResolvedWith(undefined); - return (fn) => PerformPromiseThen(resolvedPromise, fn); - })(); - function reflectCall(F, V, args) { - if (typeof F !== 'function') { - throw new TypeError('Argument is not a function'); - } - return Function.prototype.apply.call(F, V, args); - } - function promiseCall(F, V, args) { - try { - return promiseResolvedWith(reflectCall(F, V, args)); - } - catch (value) { - return promiseRejectedWith(value); - } - } + const VERSION$1 = 1; // A one-octet version number of the data packet. - // Original from Chromium - // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js - const QUEUE_MAX_ARRAY_SIZE = 16384; /** - * Simple queue structure. + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet * - * Avoids scalability issues with using a packed array directly by using - * multiple arrays in a linked list and keeping the array size bounded. + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet */ - class SimpleQueue { - constructor() { - this._cursor = 0; - this._size = 0; - // _front and _back are always defined. - this._front = { - _elements: [], - _next: undefined - }; - this._back = this._front; - // The cursor is used to avoid calling Array.shift(). - // It contains the index of the front element of the array inside the - // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). - this._cursor = 0; - // When there is only one node, size === elements.length - cursor. - this._size = 0; - } - get length() { - return this._size; - } - // For exception safety, this method is structured in order: - // 1. Read state - // 2. Calculate required state mutations - // 3. Perform state mutations - push(element) { - const oldBack = this._back; - let newBack = oldBack; - if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { - newBack = { - _elements: [], - _next: undefined - }; - } - // push() is the mutation most likely to throw an exception, so it - // goes first. - oldBack._elements.push(element); - if (newBack !== oldBack) { - this._back = newBack; - oldBack._next = newBack; - } - ++this._size; - } - // Like push(), shift() follows the read -> calculate -> mutate pattern for - // exception safety. - shift() { // must not be called on an empty queue - const oldFront = this._front; - let newFront = oldFront; - const oldCursor = this._cursor; - let newCursor = oldCursor + 1; - const elements = oldFront._elements; - const element = elements[oldCursor]; - if (newCursor === QUEUE_MAX_ARRAY_SIZE) { - newFront = oldFront._next; - newCursor = 0; - } - // No mutations before this point. - --this._size; - this._cursor = newCursor; - if (oldFront !== newFront) { - this._front = newFront; - } - // Permit shifted element to be garbage collected. - elements[oldCursor] = undefined; - return element; - } - // The tricky thing about forEach() is that it can be called - // re-entrantly. The queue may be mutated inside the callback. It is easy to - // see that push() within the callback has no negative effects since the end - // of the queue is checked for on every iteration. If shift() is called - // repeatedly within the callback then the next iteration may return an - // element that has been removed. In this case the callback will be called - // with undefined values until we either "catch up" with elements that still - // exist or reach the back of the queue. - forEach(callback) { - let i = this._cursor; - let node = this._front; - let elements = node._elements; - while (i !== elements.length || node._next !== undefined) { - if (i === elements.length) { - node = node._next; - elements = node._elements; - i = 0; - if (elements.length === 0) { - break; - } - } - callback(elements[i]); - ++i; - } - } - // Return the element that would be returned if shift() was called now, - // without modifying the queue. - peek() { // must not be called on an empty queue - const front = this._front; - const cursor = this._cursor; - return front._elements[cursor]; - } - } + class AEADEncryptedDataPacket { + static get tag() { + return enums.packet.aeadEncryptedData; + } - function ReadableStreamReaderGenericInitialize(reader, stream) { - reader._ownerReadableStream = stream; - stream._reader = reader; - if (stream._state === 'readable') { - defaultReaderClosedPromiseInitialize(reader); - } - else if (stream._state === 'closed') { - defaultReaderClosedPromiseInitializeAsResolved(reader); - } - else { - defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); - } - } - // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state - // check. - function ReadableStreamReaderGenericCancel(reader, reason) { - const stream = reader._ownerReadableStream; - return ReadableStreamCancel(stream, reason); - } - function ReadableStreamReaderGenericRelease(reader) { - if (reader._ownerReadableStream._state === 'readable') { - defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - else { - defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - reader._ownerReadableStream._reader = undefined; - reader._ownerReadableStream = undefined; - } - // Helper functions for the readers. - function readerLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released reader'); - } - // Helper functions for the ReadableStreamDefaultReader. - function defaultReaderClosedPromiseInitialize(reader) { - reader._closedPromise = newPromise((resolve, reject) => { - reader._closedPromise_resolve = resolve; - reader._closedPromise_reject = reject; - }); - } - function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseReject(reader, reason); - } - function defaultReaderClosedPromiseInitializeAsResolved(reader) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseResolve(reader); - } - function defaultReaderClosedPromiseReject(reader, reason) { - if (reader._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(reader._closedPromise); - reader._closedPromise_reject(reason); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; - } - function defaultReaderClosedPromiseResetToRejected(reader, reason) { - defaultReaderClosedPromiseInitializeAsRejected(reader, reason); - } - function defaultReaderClosedPromiseResolve(reader) { - if (reader._closedPromise_resolve === undefined) { - return; - } - reader._closedPromise_resolve(undefined); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; - } + constructor() { + this.version = VERSION$1; + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = enums.aead.eax; + this.chunkSizeByte = null; + this.iv = null; + this.encrypted = null; + this.packets = null; + } - const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); - const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); - const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); - const PullSteps = SymbolPolyfill('[[PullSteps]]'); + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param {Uint8Array | ReadableStream} bytes + * @throws {Error} on parsing failure + */ + async read(bytes) { + await parse(bytes, async reader => { + const version = await reader.readByte(); + if (version !== VERSION$1) { // The only currently defined value is 1. + throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); + } + this.cipherAlgorithm = await reader.readByte(); + this.aeadAlgorithm = await reader.readByte(); + this.chunkSizeByte = await reader.readByte(); - /// - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill - const NumberIsFinite = Number.isFinite || function (x) { - return typeof x === 'number' && isFinite(x); - }; + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = await reader.readBytes(mode.ivLength); + this.encrypted = reader.remainder(); + }); + } - /// - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill - const MathTrunc = Math.trunc || function (v) { - return v < 0 ? Math.ceil(v) : Math.floor(v); - }; + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns {Uint8Array | ReadableStream} The encrypted payload. + */ + write() { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); + } - // https://heycam.github.io/webidl/#idl-dictionaries - function isDictionary(x) { - return typeof x === 'object' || typeof x === 'function'; - } - function assertDictionary(obj, context) { - if (obj !== undefined && !isDictionary(obj)) { - throw new TypeError(`${context} is not an object.`); - } - } - // https://heycam.github.io/webidl/#idl-callback-functions - function assertFunction(x, context) { - if (typeof x !== 'function') { - throw new TypeError(`${context} is not a function.`); - } - } - // https://heycam.github.io/webidl/#idl-object - function isObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; - } - function assertObject(x, context) { - if (!isObject(x)) { - throw new TypeError(`${context} is not an object.`); - } - } - function assertRequiredArgument(x, position, context) { - if (x === undefined) { - throw new TypeError(`Parameter ${position} is required in '${context}'.`); - } - } - function assertRequiredField(x, field, context) { - if (x === undefined) { - throw new TypeError(`${field} is required in '${context}'.`); - } - } - // https://heycam.github.io/webidl/#idl-unrestricted-double - function convertUnrestrictedDouble(value) { - return Number(value); - } - function censorNegativeZero(x) { - return x === 0 ? 0 : x; - } - function integerPart(x) { - return censorNegativeZero(MathTrunc(x)); - } - // https://heycam.github.io/webidl/#idl-unsigned-long-long - function convertUnsignedLongLongWithEnforceRange(value, context) { - const lowerBound = 0; - const upperBound = Number.MAX_SAFE_INTEGER; - let x = Number(value); - x = censorNegativeZero(x); - if (!NumberIsFinite(x)) { - throw new TypeError(`${context} is not a finite number`); - } - x = integerPart(x); - if (x < lowerBound || x > upperBound) { - throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); - } - if (!NumberIsFinite(x) || x === 0) { - return 0; - } - // TODO Use BigInt if supported? - // let xBigInt = BigInt(integerPart(x)); - // xBigInt = BigInt.asUintN(64, xBigInt); - // return Number(xBigInt); - return x; - } + /** + * Decrypt the encrypted payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.packets = await PacketList.fromBinary( + await runAEAD(this, 'decrypt', key, clone(this.encrypted)), + allowedPackets$3, + config$1 + ); + } + + /** + * Encrypt the packet payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.cipherAlgorithm = sessionKeyAlgorithm; - function assertReadableStream(x, context) { - if (!IsReadableStream(x)) { - throw new TypeError(`${context} is not a ReadableStream.`); - } + const { ivLength } = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(ivLength); // generate new random IV + this.chunkSizeByte = config$1.aeadChunkSizeByte; + const data = this.packets.write(); + this.encrypted = await runAEAD(this, 'encrypt', key, data); + } } - // Abstract operations for the ReadableStream. - function AcquireReadableStreamDefaultReader(stream) { - return new ReadableStreamDefaultReader(stream); - } - // ReadableStream API exposed for controllers. - function ReadableStreamAddReadRequest(stream, readRequest) { - stream._reader._readRequests.push(readRequest); - } - function ReadableStreamFulfillReadRequest(stream, chunk, done) { - const reader = stream._reader; - const readRequest = reader._readRequests.shift(); - if (done) { - readRequest._closeSteps(); - } - else { - readRequest._chunkSteps(chunk); - } - } - function ReadableStreamGetNumReadRequests(stream) { - return stream._reader._readRequests.length; - } - function ReadableStreamHasDefaultReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamDefaultReader(reader)) { - return false; - } - return true; - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * A default reader vended by a {@link ReadableStream}. + * Public-Key Encrypted Session Key Packets (Tag 1) * - * @public - */ - class ReadableStreamDefaultReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readRequests = new SimpleQueue(); - } + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + class PublicKeyEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.publicKeyEncryptedSessionKey; + } + + constructor() { + this.version = null; + + // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()` + this.publicKeyID = new KeyID(); + + // For version 6: + this.publicKeyVersion = null; + this.publicKeyFingerprint = null; + + // For all versions: + this.publicKeyAlgorithm = null; + + this.sessionKey = null; /** - * Returns a promise that will be fulfilled when the stream becomes closed, - * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - get closed() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('closed')); - } - return this._closedPromise; + this.sessionKeyAlgorithm = null; + + /** @type {Object} */ + this.encrypted = {}; + } + + static fromObject({ + version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm + }) { + const pkesk = new PublicKeyEncryptedSessionKeyPacket(); + + if (version !== 3 && version !== 6) { + throw new Error('Unsupported PKESK version'); } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); + + pkesk.version = version; + + if (version === 6) { + pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version; + pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes(); } - /** - * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('read')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: () => resolvePromise({ value: undefined, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamDefaultReaderRead(this, readRequest); - return promise; + + pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID(); + pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkesk.sessionKey = sessionKey; + pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm; + + return pkesk; + } + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * + * @param {Uint8Array} bytes - Payload of a tag 1 packet + */ + read(bytes) { + let offset = 0; + this.version = bytes[offset++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamDefaultReader(this)) { - throw defaultReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + if (this.version === 6) { + // A one-octet size of the following two fields: + // - A one octet key version number. + // - The fingerprint of the public key or subkey to which the session key is encrypted. + // The size may also be zero. + const versionAndFingerprintLength = bytes[offset++]; + if (versionAndFingerprintLength) { + this.publicKeyVersion = bytes[offset++]; + const fingerprintLength = versionAndFingerprintLength - 1; + this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength; + if (this.publicKeyVersion >= 5) { + // For v5/6 the Key ID is the high-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint); + } else { + // For v4 The Key ID is the low-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8)); } - ReadableStreamReaderGenericRelease(this); - } - } - Object.defineProperties(ReadableStreamDefaultReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultReader', - configurable: true - }); - } - // Abstract operations for the readers. - function IsReadableStreamDefaultReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { - return false; - } - return true; - } - function ReadableStreamDefaultReaderRead(reader, readRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'closed') { - readRequest._closeSteps(); - } - else if (stream._state === 'errored') { - readRequest._errorSteps(stream._storedError); + } else { + // The size may also be zero, and the key version and + // fingerprint omitted for an "anonymous recipient" + this.publicKeyID = KeyID.wildcard(); + } + } else { + offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8)); } - else { - stream._readableStreamController[PullSteps](readRequest); + this.publicKeyAlgorithm = bytes[offset++]; + this.encrypted = mod$1.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset)); + if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) { + if (this.version === 3) { + this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + } else if (this.encrypted.C.algorithm !== null) { + throw new Error('Unexpected cleartext symmetric algorithm'); + } } - } - // Helper functions for the ReadableStreamDefaultReader. - function defaultReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); - } + } - /// - let AsyncIteratorPrototype; - if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - // We're running inside a ES2018+ environment, but we're compiling to an older syntax. - // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. - AsyncIteratorPrototype = { - // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) - // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator - [SymbolPolyfill.asyncIterator]() { - return this; - } - }; - Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); - } - - /// - class ReadableStreamAsyncIteratorImpl { - constructor(reader, preventCancel) { - this._ongoingPromise = undefined; - this._isFinished = false; - this._reader = reader; - this._preventCancel = preventCancel; - } - next() { - const nextSteps = () => this._nextSteps(); - this._ongoingPromise = this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : - nextSteps(); - return this._ongoingPromise; - } - return(value) { - const returnSteps = () => this._returnSteps(value); - return this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : - returnSteps(); - } - _nextSteps() { - if (this._isFinished) { - return Promise.resolve({ value: undefined, done: true }); - } - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('iterate')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => { - this._ongoingPromise = undefined; - // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. - // FIXME Is this a bug in the specification, or in the test? - queueMicrotask(() => resolvePromise({ value: chunk, done: false })); - }, - _closeSteps: () => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - resolvePromise({ value: undefined, done: true }); - }, - _errorSteps: reason => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - rejectPromise(reason); - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promise; - } - _returnSteps(value) { - if (this._isFinished) { - return Promise.resolve({ value, done: true }); - } - this._isFinished = true; - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('finish iterating')); - } - if (!this._preventCancel) { - const result = ReadableStreamReaderGenericCancel(reader, value); - ReadableStreamReaderGenericRelease(reader); - return transformPromiseWith(result, () => ({ value, done: true })); - } - ReadableStreamReaderGenericRelease(reader); - return promiseResolvedWith({ value, done: true }); - } - } - const ReadableStreamAsyncIteratorPrototype = { - next() { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); - } - return this._asyncIteratorImpl.next(); - }, - return(value) { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); - } - return this._asyncIteratorImpl.return(value); + /** + * Create a binary representation of a tag 1 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const arr = [ + new Uint8Array([this.version]) + ]; + + if (this.version === 6) { + if (this.publicKeyFingerprint !== null) { + arr.push(new Uint8Array([ + this.publicKeyFingerprint.length + 1, + this.publicKeyVersion] + )); + arr.push(this.publicKeyFingerprint); + } else { + arr.push(new Uint8Array([0])); + } + } else { + arr.push(this.publicKeyID.write()); } - }; - if (AsyncIteratorPrototype !== undefined) { - Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); - } - // Abstract operations for the ReadableStream. - function AcquireReadableStreamAsyncIterator(stream, preventCancel) { - const reader = AcquireReadableStreamDefaultReader(stream); - const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); - iterator._asyncIteratorImpl = impl; - return iterator; - } - function IsReadableStreamAsyncIterator(x) { - if (!typeIsObject(x)) { - return false; + + arr.push( + new Uint8Array([this.publicKeyAlgorithm]), + mod$1.serializeParams(this.publicKeyAlgorithm, this.encrypted) + ); + + return util.concatUint8Array(arr); + } + + /** + * Encrypt session key packet + * @param {PublicKeyPacket} key - Public key + * @throws {Error} if encryption failed + * @async + */ + async encrypt(key) { + const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); + // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a + // v6 PKESK packet, as it is included in the v2 SEIPD packet. + const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey); + this.encrypted = await mod$1.publicKeyEncrypt( + algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint); + } + + /** + * Decrypts the session key (only for public key encrypted session key packets (tag 1) + * @param {SecretKeyPacket} key - decrypted private key + * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. + * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } + * @throws {Error} if decryption failed, unless `randomSessionKey` is given + * @async + */ + async decrypt(key, randomSessionKey) { + // check that session key algo matches the secret key algo + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Decryption error'); } - if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { - return false; + + const randomPayload = randomSessionKey ? + encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : + null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const decryptedData = await mod$1.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload); + + const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); + + if (this.version === 3) { + // v3 Montgomery curves have cleartext cipher algo + const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448; + this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm; + + if (sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } } - return true; - } - // Helper functions for the ReadableStream. - function streamAsyncIteratorBrandCheckException(name) { - return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + this.sessionKey = sessionKey; + } } - /// - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill - const NumberIsNaN = Number.isNaN || function (x) { - // eslint-disable-next-line no-self-compare - return x !== x; - }; - function IsFiniteNonNegativeNumber(v) { - if (!IsNonNegativeNumber(v)) { - return false; - } - if (v === Infinity) { - return false; - } - return true; + function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + // add checksum + return util.concatUint8Array([ + new Uint8Array(version === 6 ? [] : [cipherAlgo]), + sessionKeyData, + util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) + ]); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return sessionKeyData; + default: + throw new Error('Unsupported public key algorithm'); + } } - function IsNonNegativeNumber(v) { - if (typeof v !== 'number') { - return false; - } - if (NumberIsNaN(v)) { - return false; - } - if (v < 0) { - return false; + + + function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: { + // verify checksum in constant time + const result = decryptedData.subarray(0, decryptedData.length - 2); + const checksum = decryptedData.subarray(decryptedData.length - 2); + const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); + const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; + const decryptedSessionKey = version === 6 ? + { sessionKeyAlgorithm: null, sessionKey: result } : + { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; + if (randomSessionKey) { + // We must not leak info about the validity of the decrypted checksum or cipher algo. + // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. + const isValidPayload = isValidChecksum & + decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & + decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; + return { + sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), + sessionKeyAlgorithm: version === 6 ? null : util.selectUint8( + isValidPayload, + decryptedSessionKey.sessionKeyAlgorithm, + randomSessionKey.sessionKeyAlgorithm + ) + }; + } else { + const isValidPayload = isValidChecksum && ( + version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm)); + if (isValidPayload) { + return decryptedSessionKey; + } else { + throw new Error('Decryption error'); + } + } } - return true; + case enums.publicKey.x25519: + case enums.publicKey.x448: + return { + sessionKeyAlgorithm: null, + sessionKey: decryptedData + }; + default: + throw new Error('Unsupported public key algorithm'); + } } - function DequeueValue(container) { - const pair = container._queue.shift(); - container._queueTotalSize -= pair.size; - if (container._queueTotalSize < 0) { - container._queueTotalSize = 0; - } - return pair.value; - } - function EnqueueValueWithSize(container, value, size) { - size = Number(size); - if (!IsFiniteNonNegativeNumber(size)) { - throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); - } - container._queue.push({ value, size }); - container._queueTotalSize += size; - } - function PeekQueueValue(container) { - const pair = container._queue.peek(); - return pair.value; - } - function ResetQueue(container) { - container._queue = new SimpleQueue(); - container._queueTotalSize = 0; - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function CreateArrayFromList(elements) { - // We use arrays to represent lists, so this is basically a no-op. - // Do a slice though just in case we happen to depend on the unique-ness. - return elements.slice(); - } - function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { - new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); - } - // Not implemented correctly - function TransferArrayBuffer(O) { - return O; - } - // Not implemented correctly - function IsDetachedBuffer(O) { - return false; - } /** - * A pull-into request in a {@link ReadableByteStreamController}. - * - * @public - */ - class ReadableStreamBYOBRequest { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. - */ - get view() { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('view'); - } - return this._view; - } - respond(bytesWritten) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respond'); - } - assertRequiredArgument(bytesWritten, 1, 'respond'); - bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - if (IsDetachedBuffer(this._view.buffer)) ; - ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); - } - respondWithNewView(view) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respondWithNewView'); - } - assertRequiredArgument(view, 1, 'respondWithNewView'); - if (!ArrayBuffer.isView(view)) { - throw new TypeError('You can only respond with array buffer views'); - } - if (view.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (view.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); - } - } - Object.defineProperties(ReadableStreamBYOBRequest.prototype, { - respond: { enumerable: true }, - respondWithNewView: { enumerable: true }, - view: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBRequest', - configurable: true - }); - } - /** - * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * Symmetric-Key Encrypted Session Key Packets (Tag 3) * - * @public + * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: + * The Symmetric-Key Encrypted Session Key packet holds the + * symmetric-key encryption of a session key used to encrypt a message. + * Zero or more Public-Key Encrypted Session Key packets and/or + * Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data packet that holds an encrypted message. + * The message is encrypted with a session key, and the session key is + * itself encrypted and stored in the Encrypted Session Key packet or + * the Symmetric-Key Encrypted Session Key packet. */ - class ReadableByteStreamController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the current BYOB pull request, or `null` if there isn't one. - */ - get byobRequest() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('byobRequest'); - } - if (this._byobRequest === null && this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); - const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); - SetUpReadableStreamBYOBRequest(byobRequest, this, view); - this._byobRequest = byobRequest; - } - return this._byobRequest; - } + class SymEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.symEncryptedSessionKey; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + this.version = config$1.aeadProtect ? 6 : 4; + this.sessionKey = null; /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + * Algorithm to encrypt the session key with + * @type {enums.symmetric} */ - get desiredSize() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('desiredSize'); - } - return ReadableByteStreamControllerGetDesiredSize(this); - } + this.sessionKeyEncryptionAlgorithm = null; /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - close() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('close'); - } - if (this._closeRequested) { - throw new TypeError('The stream has already been closed; do not close it again!'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); - } - ReadableByteStreamControllerClose(this); - } - enqueue(chunk) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('enqueue'); - } - assertRequiredArgument(chunk, 1, 'enqueue'); - if (!ArrayBuffer.isView(chunk)) { - throw new TypeError('chunk must be an array buffer view'); - } - if (chunk.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (chunk.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._closeRequested) { - throw new TypeError('stream is closed or draining'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); - } - ReadableByteStreamControllerEnqueue(this, chunk); - } + this.sessionKeyAlgorithm = null; /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + * AEAD mode to encrypt the session key with (if AEAD protection is enabled) + * @type {enums.aead} */ - error(e = undefined) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('error'); - } - ReadableByteStreamControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - if (this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - firstDescriptor.bytesFilled = 0; - } - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableByteStreamControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableByteStream; - if (this._queueTotalSize > 0) { - const entry = this._queue.shift(); - this._queueTotalSize -= entry.byteLength; - ReadableByteStreamControllerHandleQueueDrain(this); - const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); - readRequest._chunkSteps(view); - return; - } - const autoAllocateChunkSize = this._autoAllocateChunkSize; - if (autoAllocateChunkSize !== undefined) { - let buffer; - try { - buffer = new ArrayBuffer(autoAllocateChunkSize); - } - catch (bufferE) { - readRequest._errorSteps(bufferE); - return; - } - const pullIntoDescriptor = { - buffer, - byteOffset: 0, - byteLength: autoAllocateChunkSize, - bytesFilled: 0, - elementSize: 1, - viewConstructor: Uint8Array, - readerType: 'default' - }; - this._pendingPullIntos.push(pullIntoDescriptor); - } - ReadableStreamAddReadRequest(stream, readRequest); - ReadableByteStreamControllerCallPullIfNeeded(this); - } - } - Object.defineProperties(ReadableByteStreamController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - byobRequest: { enumerable: true }, - desiredSize: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableByteStreamController', - configurable: true - }); - } - // Abstract operations for the ReadableByteStreamController. - function IsReadableByteStreamController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { - return false; - } - return true; - } - function IsReadableStreamBYOBRequest(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { - return false; - } - return true; - } - function ReadableByteStreamControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - // TODO: Test controller argument - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableByteStreamControllerError(controller, e); - }); - } - function ReadableByteStreamControllerClearPendingPullIntos(controller) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - controller._pendingPullIntos = new SimpleQueue(); - } - function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { - let done = false; - if (stream._state === 'closed') { - done = true; - } - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - if (pullIntoDescriptor.readerType === 'default') { - ReadableStreamFulfillReadRequest(stream, filledView, done); - } - else { - ReadableStreamFulfillReadIntoRequest(stream, filledView, done); - } - } - function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { - const bytesFilled = pullIntoDescriptor.bytesFilled; - const elementSize = pullIntoDescriptor.elementSize; - return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); - } - function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { - controller._queue.push({ buffer, byteOffset, byteLength }); - controller._queueTotalSize += byteLength; - } - function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { - const elementSize = pullIntoDescriptor.elementSize; - const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; - const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); - const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; - const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; - let totalBytesToCopyRemaining = maxBytesToCopy; - let ready = false; - if (maxAlignedBytes > currentAlignedBytes) { - totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; - ready = true; - } - const queue = controller._queue; - while (totalBytesToCopyRemaining > 0) { - const headOfQueue = queue.peek(); - const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); - const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); - if (headOfQueue.byteLength === bytesToCopy) { - queue.shift(); - } - else { - headOfQueue.byteOffset += bytesToCopy; - headOfQueue.byteLength -= bytesToCopy; - } - controller._queueTotalSize -= bytesToCopy; - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); - totalBytesToCopyRemaining -= bytesToCopy; - } - return ready; - } - function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - pullIntoDescriptor.bytesFilled += size; - } - function ReadableByteStreamControllerHandleQueueDrain(controller) { - if (controller._queueTotalSize === 0 && controller._closeRequested) { - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(controller._controlledReadableByteStream); - } - else { - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - } - function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { - if (controller._byobRequest === null) { - return; - } - controller._byobRequest._associatedReadableByteStreamController = undefined; - controller._byobRequest._view = null; - controller._byobRequest = null; - } - function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { - while (controller._pendingPullIntos.length > 0) { - if (controller._queueTotalSize === 0) { - return; - } - const pullIntoDescriptor = controller._pendingPullIntos.peek(); - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - } - } - } - function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { - const stream = controller._controlledReadableByteStream; - let elementSize = 1; - if (view.constructor !== DataView) { - elementSize = view.constructor.BYTES_PER_ELEMENT; - } - const ctor = view.constructor; - const buffer = TransferArrayBuffer(view.buffer); - const pullIntoDescriptor = { - buffer, - byteOffset: view.byteOffset, - byteLength: view.byteLength, - bytesFilled: 0, - elementSize, - viewConstructor: ctor, - readerType: 'byob' - }; - if (controller._pendingPullIntos.length > 0) { - controller._pendingPullIntos.push(pullIntoDescriptor); - // No ReadableByteStreamControllerCallPullIfNeeded() call since: - // - No change happens on desiredSize - // - The source has already been notified of that there's at least 1 pending read(view) - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - return; - } - if (stream._state === 'closed') { - const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); - readIntoRequest._closeSteps(emptyView); - return; - } - if (controller._queueTotalSize > 0) { - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - ReadableByteStreamControllerHandleQueueDrain(controller); - readIntoRequest._chunkSteps(filledView); - return; - } - if (controller._closeRequested) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - readIntoRequest._errorSteps(e); - return; - } - } - controller._pendingPullIntos.push(pullIntoDescriptor); - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { - firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); - const stream = controller._controlledReadableByteStream; - if (ReadableStreamHasBYOBReader(stream)) { - while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { - const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); - } - } - } - function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { - if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { - throw new RangeError('bytesWritten out of range'); - } - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); - if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { - // TODO: Figure out whether we should detach the buffer or not here. - return; - } - ReadableByteStreamControllerShiftPendingPullInto(controller); - const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; - if (remainderSize > 0) { - const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); - ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); - } - pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); - pullIntoDescriptor.bytesFilled -= remainderSize; - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); - } - function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { - const firstDescriptor = controller._pendingPullIntos.peek(); - const state = controller._controlledReadableByteStream._state; - if (state === 'closed') { - if (bytesWritten !== 0) { - throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); - } - ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); - } - else { - ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - function ReadableByteStreamControllerShiftPendingPullInto(controller) { - const descriptor = controller._pendingPullIntos.shift(); - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - return descriptor; - } - function ReadableByteStreamControllerShouldCallPull(controller) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return false; - } - if (controller._closeRequested) { - return false; - } - if (!controller._started) { - return false; - } - if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; + this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); + this.encrypted = null; + this.s2k = null; + this.iv = null; + } + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * + * @param {Uint8Array} bytes - Payload of a tag 3 packet + */ + read(bytes) { + let offset = 0; + + // A one-octet version number with value 4, 5 or 6. + this.version = bytes[offset++]; + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); } - return false; - } - function ReadableByteStreamControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - } - // A client of ReadableByteStreamController may use these functions directly to bypass state check. - function ReadableByteStreamControllerClose(controller) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + + if (this.version === 6) { + // A one-octet scalar octet count of the following 5 fields. + offset++; } - if (controller._queueTotalSize > 0) { - controller._closeRequested = true; - return; + + // A one-octet number describing the symmetric algorithm used. + const algo = bytes[offset++]; + + if (this.version >= 5) { + // A one-octet AEAD algorithm. + this.aeadAlgorithm = bytes[offset++]; + + if (this.version === 6) { + // A one-octet scalar octet count of the following field. + offset++; + } } - if (controller._pendingPullIntos.length > 0) { - const firstPendingPullInto = controller._pendingPullIntos.peek(); - if (firstPendingPullInto.bytesFilled > 0) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - throw e; - } + + // A string-to-key (S2K) specifier, length as defined above. + const s2kType = bytes[offset++]; + this.s2k = newS2KFromType(s2kType); + offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + + // A starting initialization vector of size specified by the AEAD + // algorithm. + this.iv = bytes.subarray(offset, offset += mode.ivLength); } - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(stream); - } - function ReadableByteStreamControllerEnqueue(controller, chunk) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + + // The encrypted session key itself, which is decrypted with the + // string-to-key object. This is optional in version 4. + if (this.version >= 5 || offset < bytes.length) { + this.encrypted = bytes.subarray(offset, bytes.length); + this.sessionKeyEncryptionAlgorithm = algo; + } else { + this.sessionKeyAlgorithm = algo; } - const buffer = chunk.buffer; - const byteOffset = chunk.byteOffset; - const byteLength = chunk.byteLength; - const transferredBuffer = TransferArrayBuffer(buffer); - if (ReadableStreamHasDefaultReader(stream)) { - if (ReadableStreamGetNumReadRequests(stream) === 0) { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - else { - const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); - ReadableStreamFulfillReadRequest(stream, transferredView, false); - } + } + + /** + * Create a binary representation of a tag 3 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const algo = this.encrypted === null ? + this.sessionKeyAlgorithm : + this.sessionKeyEncryptionAlgorithm; + + let bytes; + + const s2k = this.s2k.write(); + if (this.version === 6) { + const s2kLen = s2k.length; + const fieldsLen = 3 + s2kLen + this.iv.length; + bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]); + } else if (this.version === 5) { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]); + } else { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]); + + if (this.encrypted !== null) { + bytes = util.concatUint8Array([bytes, this.encrypted]); + } } - else if (ReadableStreamHasBYOBReader(stream)) { - // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + + return bytes; + } + + /** + * Decrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(passphrase) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); + } else if (this.encrypted !== null) { + const decrypted = await mod$1.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + + this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); + this.sessionKey = decrypted.subarray(1, decrypted.length); + if (this.sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + } else { + // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo + this.sessionKey = key; } - else { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + + /** + * Encrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + this.sessionKeyEncryptionAlgorithm = algo; + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.sessionKey === null) { + this.sessionKey = mod$1.generateSessionKey(this.sessionKeyAlgorithm); } - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - function ReadableByteStreamControllerError(controller, e) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return; + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(mode.ivLength); // generate new random IV + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); + } else { + const toEncrypt = util.concatUint8Array([ + new Uint8Array([this.sessionKeyAlgorithm]), + this.sessionKey + ]); + this.encrypted = await mod$1.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config$1); } - ReadableByteStreamControllerClearPendingPullIntos(controller); - ResetQueue(controller); - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); - } - function ReadableByteStreamControllerGetDesiredSize(controller) { - const state = controller._controlledReadableByteStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; - } - function ReadableByteStreamControllerRespond(controller, bytesWritten) { - bytesWritten = Number(bytesWritten); - if (!IsFiniteNonNegativeNumber(bytesWritten)) { - throw new RangeError('bytesWritten must be a finite'); - } - ReadableByteStreamControllerRespondInternal(controller, bytesWritten); - } - function ReadableByteStreamControllerRespondWithNewView(controller, view) { - const firstDescriptor = controller._pendingPullIntos.peek(); - if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { - throw new RangeError('The region specified by view does not match byobRequest'); - } - if (firstDescriptor.byteLength !== view.byteLength) { - throw new RangeError('The buffer of view has different capacity than byobRequest'); - } - firstDescriptor.buffer = view.buffer; - ReadableByteStreamControllerRespondInternal(controller, view.byteLength); - } - function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { - controller._controlledReadableByteStream = stream; - controller._pullAgain = false; - controller._pulling = false; - controller._byobRequest = null; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._closeRequested = false; - controller._started = false; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - controller._autoAllocateChunkSize = autoAllocateChunkSize; - controller._pendingPullIntos = new SimpleQueue(); - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableByteStreamControllerCallPullIfNeeded(controller); - }, r => { - ReadableByteStreamControllerError(controller, r); - }); + } } - function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { - const controller = Object.create(ReadableByteStreamController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingByteSource.start !== undefined) { - startAlgorithm = () => underlyingByteSource.start(controller); - } - if (underlyingByteSource.pull !== undefined) { - pullAlgorithm = () => underlyingByteSource.pull(controller); - } - if (underlyingByteSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ + class PublicKeyPacket { + static get tag() { + return enums.packet.publicKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + /** + * Packet version + * @type {Integer} + */ + this.version = config$1.v6Keys ? 6 : 4; + /** + * Key creation date. + * @type {Date} + */ + this.created = util.normalizeDate(date); + /** + * Public key algorithm. + * @type {enums.publicKey} + */ + this.algorithm = null; + /** + * Algorithm specific public params + * @type {Object} + */ + this.publicParams = null; + /** + * Time until expiration in days (V3 only) + * @type {Integer} + */ + this.expirationTimeV3 = 0; + /** + * Fingerprint bytes + * @type {Uint8Array} + */ + this.fingerprint = null; + /** + * KeyID + * @type {module:type/keyid~KeyID} + */ + this.keyID = null; + } + + /** + * Create a PublicKeyPacket from a SecretKeyPacket + * @param {SecretKeyPacket} secretKeyPacket - key packet to convert + * @returns {PublicKeyPacket} public key packet + * @static + */ + static fromSecretKeyPacket(secretKeyPacket) { + const keyPacket = new PublicKeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * @param {Uint8Array} bytes - Input array to read the packet from + * @returns {Object} This object with attributes set by the parser + * @async + */ + async read(bytes, config$1 = config) { + let pos = 0; + // A one-octet version number (4, 5 or 6). + this.version = bytes[pos++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); } - const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; - if (autoAllocateChunkSize === 0) { - throw new TypeError('autoAllocateChunkSize must be greater than 0'); + + if (this.version === 4 || this.version === 5 || this.version === 6) { + // - A four-octet number denoting the time that the key was created. + this.created = util.readDate(bytes.subarray(pos, pos + 4)); + pos += 4; + + // - A one-octet number denoting the public-key algorithm of this key. + this.algorithm = bytes[pos++]; + + if (this.version >= 5) { + // - A four-octet scalar octet count for the following key material. + pos += 4; + } + + // - A series of values comprising the key material. + const { read, publicParams } = mod$1.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if ( + this.version === 6 && + publicParams.oid && ( + publicParams.oid.getName() === enums.curve.curve25519Legacy || + publicParams.oid.getName() === enums.curve.ed25519Legacy + ) + ) { + throw new Error('Legacy curve25519 cannot be used with v6 keys'); + } + this.publicParams = publicParams; + pos += read; + + // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor + await this.computeFingerprintAndKeyID(); + return pos; } - SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); - } - function SetUpReadableStreamBYOBRequest(request, controller, view) { - request._associatedReadableByteStreamController = controller; - request._view = view; - } - // Helper functions for the ReadableStreamBYOBRequest. - function byobRequestBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); - } - // Helper functions for the ReadableByteStreamController. - function byteStreamControllerBrandCheckException(name) { - return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); - } + throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); + } - // Abstract operations for the ReadableStream. - function AcquireReadableStreamBYOBReader(stream) { - return new ReadableStreamBYOBReader(stream); - } - // ReadableStream API exposed for controllers. - function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { - stream._reader._readIntoRequests.push(readIntoRequest); - } - function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { - const reader = stream._reader; - const readIntoRequest = reader._readIntoRequests.shift(); - if (done) { - readIntoRequest._closeSteps(chunk); + /** + * Creates an OpenPGP public key packet for the given key. + * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. + */ + write() { + const arr = []; + // Version + arr.push(new Uint8Array([this.version])); + arr.push(util.writeDate(this.created)); + // A one-octet number denoting the public-key algorithm of this key + arr.push(new Uint8Array([this.algorithm])); + + const params = mod$1.serializeParams(this.algorithm, this.publicParams); + if (this.version >= 5) { + // A four-octet scalar octet count for the following key material + arr.push(util.writeNumber(params.length, 4)); } - else { - readIntoRequest._chunkSteps(chunk); + // Algorithm-specific params + arr.push(params); + return util.concatUint8Array(arr); + } + + /** + * Write packet in order to be hashed; either for a signature or a fingerprint + * @param {Integer} version - target version of signature or key + */ + writeForHash(version) { + const bytes = this.writePublicKey(); + + const versionOctet = 0x95 + version; + const lengthOctets = version >= 5 ? 4 : 2; + return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]); + } + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return null; + } + + /** + * Returns the creation time of the key + * @returns {Date} + */ + getCreationTime() { + return this.created; + } + + /** + * Return the key ID of the key + * @returns {module:type/keyid~KeyID} The 8-byte key ID + */ + getKeyID() { + return this.keyID; + } + + /** + * Computes and set the key ID and fingerprint of the key + * @async + */ + async computeFingerprintAndKeyID() { + await this.computeFingerprint(); + this.keyID = new KeyID(); + + if (this.version >= 5) { + this.keyID.read(this.fingerprint.subarray(0, 8)); + } else if (this.version === 4) { + this.keyID.read(this.fingerprint.subarray(12, 20)); + } else { + throw new Error('Unsupported key version'); } - } - function ReadableStreamGetNumReadIntoRequests(stream) { - return stream._reader._readIntoRequests.length; - } - function ReadableStreamHasBYOBReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; + } + + /** + * Computes and set the fingerprint of the key + */ + async computeFingerprint() { + const toHash = this.writeForHash(this.version); + + if (this.version >= 5) { + this.fingerprint = await mod$1.hash.sha256(toHash); + } else if (this.version === 4) { + this.fingerprint = await mod$1.hash.sha1(toHash); + } else { + throw new Error('Unsupported key version'); } - if (!IsReadableStreamBYOBReader(reader)) { - return false; + } + + /** + * Returns the fingerprint of the key, as an array of bytes + * @returns {Uint8Array} A Uint8Array containing the fingerprint + */ + getFingerprintBytes() { + return this.fingerprint; + } + + /** + * Calculates and returns the fingerprint of the key, as a string + * @returns {String} A string containing the fingerprint in lowercase hex + */ + getFingerprint() { + return util.uint8ArrayToHex(this.getFingerprintBytes()); + } + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns {Boolean} Whether the two keys have the same version and public key data. + */ + hasSameFingerprintAs(other) { + return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); + } + + /** + * Returns algorithm information + * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. + */ + getAlgorithmInfo() { + const result = {}; + result.algorithm = enums.read(enums.publicKey, this.algorithm); + // RSA, DSA or ElGamal public modulo + const modulo = this.publicParams.n || this.publicParams.p; + if (modulo) { + result.bits = util.uint8ArrayBitLength(modulo); + } else if (this.publicParams.oid) { + result.curve = this.publicParams.oid.getName(); } - return true; + return result; + } } + + /** + * Alias of read() + * @see PublicKeyPacket#read + */ + PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; + + /** + * Alias of write() + * @see PublicKeyPacket#write + */ + PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + // A SE packet can contain the following packet types + const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket + ]); + /** - * A BYOB reader vended by a {@link ReadableStream}. + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) * - * @public - */ - class ReadableStreamBYOBReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - if (!IsReadableByteStreamController(stream._readableStreamController)) { - throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + - 'source'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readIntoRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ + class SymmetricallyEncryptedDataPacket { + static get tag() { + return enums.packet.symmetricallyEncryptedData; + } + + constructor() { /** - * Attempts to reads bytes into view, and returns a promise resolved with the result. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + * Encrypted secret-key data */ - read(view) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('read')); - } - if (!ArrayBuffer.isView(view)) { - return promiseRejectedWith(new TypeError('view must be an array buffer view')); - } - if (view.byteLength === 0) { - return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); - } - if (view.buffer.byteLength === 0) { - return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readIntoRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamBYOBReaderRead(this, view, readIntoRequest); - return promise; - } + this.encrypted = null; /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. + * Decrypted packets contained within. + * @type {PacketList} */ - releaseLock() { - if (!IsReadableStreamBYOBReader(this)) { - throw byobReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readIntoRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } - } - Object.defineProperties(ReadableStreamBYOBReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBReader', - configurable: true - }); - } - // Abstract operations for the readers. - function IsReadableStreamBYOBReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { - return false; + this.packets = null; + } + + read(bytes) { + this.encrypted = bytes; + } + + write() { + return this.encrypted; + } + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error + if (!config$1.allowUnauthenticatedMessages) { + throw new Error('Message is not authenticated.'); } - return true; + + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const encrypted = await readToEnd(clone(this.encrypted)); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, + encrypted.subarray(blockSize + 2), + encrypted.subarray(2, blockSize + 2) + ); + + this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1); + } + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + const data = this.packets.write(); + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const FRE = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); + const ciphertext = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); + this.encrypted = util.concat([FRE, ciphertext]); + } } - function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'errored') { - readIntoRequest._errorSteps(stream._storedError); - } - else { - ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of the strange "Marker packet" (Tag 10) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * + * The body of this packet consists of: + * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + * + * Such a packet MUST be ignored when received. It may be placed at the + * beginning of a message that uses features not available in PGP + * version 2.6 in order to cause that version to report that newer + * software is necessary to process the message. + */ + class MarkerPacket { + static get tag() { + return enums.packet.marker; + } + + /** + * Parsing function for a marker data packet (tag 10). + * @param {Uint8Array} bytes - Payload of a tag 10 packet + * @returns {Boolean} whether the packet payload contains "PGP" + */ + read(bytes) { + if (bytes[0] === 0x50 && // P + bytes[1] === 0x47 && // G + bytes[2] === 0x50) { // P + return true; } + return false; + } + + write() { + return new Uint8Array([0x50, 0x47, 0x50]); + } } - // Helper functions for the ReadableStreamBYOBReader. - function byobReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + * @extends PublicKeyPacket + */ + class PublicSubkeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.publicSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(date, config) { + super(date, config); + } + + /** + * Create a PublicSubkeyPacket from a SecretSubkeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert + * @returns {SecretSubkeyPacket} public key packet + * @static + */ + static fromSecretSubkeyPacket(secretSubkeyPacket) { + const keyPacket = new PublicSubkeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } } - function ExtractHighWaterMark(strategy, defaultHWM) { - const { highWaterMark } = strategy; - if (highWaterMark === undefined) { - return defaultHWM; - } - if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { - throw new RangeError('Invalid highWaterMark'); + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of the User Attribute Packet (Tag 17) + * + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ + class UserAttributePacket { + static get tag() { + return enums.packet.userAttribute; + } + + constructor() { + this.attributes = []; + } + + /** + * parsing function for a user attribute packet (tag 17). + * @param {Uint8Array} input - Payload of a tag 17 packet + */ + read(bytes) { + let i = 0; + while (i < bytes.length) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); + i += len.len; } - return highWaterMark; - } - function ExtractSizeAlgorithm(strategy) { - const { size } = strategy; - if (!size) { - return () => 1; + } + + /** + * Creates a binary representation of the user attribute packet + * @returns {Uint8Array} String representation. + */ + write() { + const arr = []; + for (let i = 0; i < this.attributes.length; i++) { + arr.push(writeSimpleLength(this.attributes[i].length)); + arr.push(util.stringToUint8Array(this.attributes[i])); } - return size; - } + return util.concatUint8Array(arr); + } - function convertQueuingStrategy(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - const size = init === null || init === void 0 ? void 0 : init.size; - return { - highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), - size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) - }; - } - function convertQueuingStrategySize(fn, context) { - assertFunction(fn, context); - return chunk => convertUnrestrictedDouble(fn(chunk)); + /** + * Compare for equality + * @param {UserAttributePacket} usrAttr + * @returns {Boolean} True if equal. + */ + equals(usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { + return false; + } + return this.attributes.every(function(attr, index) { + return attr === usrAttr.attributes[index]; + }); + } } - function convertUnderlyingSink(original, context) { - assertDictionary(original, context); - const abort = original === null || original === void 0 ? void 0 : original.abort; - const close = original === null || original === void 0 ? void 0 : original.close; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - const write = original === null || original === void 0 ? void 0 : original.write; - return { - abort: abort === undefined ? - undefined : - convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), - close: close === undefined ? - undefined : - convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), - start: start === undefined ? - undefined : - convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), - write: write === undefined ? - undefined : - convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), - type - }; - } - function convertUnderlyingSinkAbortCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); - } - function convertUnderlyingSinkCloseCallback(fn, original, context) { - assertFunction(fn, context); - return () => promiseCall(fn, original, []); - } - function convertUnderlyingSinkStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); - } - function convertUnderlyingSinkWriteCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function assertWritableStream(x, context) { - if (!IsWritableStream(x)) { - throw new TypeError(`${context} is not a WritableStream.`); - } - } /** - * A writable stream represents a destination for data, into which you can write. - * - * @public + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + * @extends PublicKeyPacket */ - class WritableStream$1 { - constructor(rawUnderlyingSink = {}, rawStrategy = {}) { - if (rawUnderlyingSink === undefined) { - rawUnderlyingSink = null; - } - else { - assertObject(rawUnderlyingSink, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); - InitializeWritableStream(this); - const type = underlyingSink.type; - if (type !== undefined) { - throw new RangeError('Invalid type is specified'); - } - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); - } + class SecretKeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.secretKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); /** - * Returns whether or not the writable stream is locked to a writer. + * Secret-key data */ - get locked() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('locked'); - } - return IsWritableStreamLocked(this); - } + this.keyMaterial = null; /** - * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be - * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort - * mechanism of the underlying sink. - * - * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled - * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel - * the stream) if the stream is currently locked. + * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. */ - abort(reason = undefined) { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('abort')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); - } - return WritableStreamAbort(this, reason); - } + this.isEncrypted = null; /** - * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its - * close behavior. During this time any further attempts to write will fail (without erroring the stream). - * - * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream - * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with - * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + * S2K usage + * @type {enums.symmetric} */ - close() { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('close')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); - } - if (WritableStreamCloseQueuedOrInFlight(this)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamClose(this); - } + this.s2kUsage = 0; /** - * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream - * is locked, no other writer can be acquired until this one is released. - * - * This functionality is especially useful for creating abstractions that desire the ability to write to a stream - * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at - * the same time, which would cause the resulting written data to be unpredictable and probably useless. + * S2K object + * @type {type/s2k} */ - getWriter() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('getWriter'); - } - return AcquireWritableStreamDefaultWriter(this); - } - } - Object.defineProperties(WritableStream$1.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - getWriter: { enumerable: true }, - locked: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStream', - configurable: true - }); - } - // Abstract operations for the WritableStream. - function AcquireWritableStreamDefaultWriter(stream) { - return new WritableStreamDefaultWriter(stream); - } - // Throws if and only if startAlgorithm throws. - function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(WritableStream$1.prototype); - InitializeWritableStream(stream); - const controller = Object.create(WritableStreamDefaultController.prototype); - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - return stream; - } - function InitializeWritableStream(stream) { - stream._state = 'writable'; - // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is - // 'erroring' or 'errored'. May be set to an undefined value. - stream._storedError = undefined; - stream._writer = undefined; - // Initialize to undefined first because the constructor of the controller checks this - // variable to validate the caller. - stream._writableStreamController = undefined; - // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data - // producer without waiting for the queued writes to finish. - stream._writeRequests = new SimpleQueue(); - // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents - // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. - stream._inFlightWriteRequest = undefined; - // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer - // has been detached. - stream._closeRequest = undefined; - // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it - // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. - stream._inFlightCloseRequest = undefined; - // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. - stream._pendingAbortRequest = undefined; - // The backpressure signal set by the controller. - stream._backpressure = false; - } - function IsWritableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { - return false; - } - return true; - } - function IsWritableStreamLocked(stream) { - if (stream._writer === undefined) { - return false; - } - return true; - } - function WritableStreamAbort(stream, reason) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseResolvedWith(undefined); - } - if (stream._pendingAbortRequest !== undefined) { - return stream._pendingAbortRequest._promise; - } - let wasAlreadyErroring = false; - if (state === 'erroring') { - wasAlreadyErroring = true; - // reason will not be used, so don't keep a reference to it. - reason = undefined; - } - const promise = newPromise((resolve, reject) => { - stream._pendingAbortRequest = { - _promise: undefined, - _resolve: resolve, - _reject: reject, - _reason: reason, - _wasAlreadyErroring: wasAlreadyErroring - }; - }); - stream._pendingAbortRequest._promise = promise; - if (!wasAlreadyErroring) { - WritableStreamStartErroring(stream, reason); - } - return promise; - } - function WritableStreamClose(stream) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); - } - const promise = newPromise((resolve, reject) => { - const closeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._closeRequest = closeRequest; - }); - const writer = stream._writer; - if (writer !== undefined && stream._backpressure && state === 'writable') { - defaultWriterReadyPromiseResolve(writer); - } - WritableStreamDefaultControllerClose(stream._writableStreamController); - return promise; - } - // WritableStream API exposed for controllers. - function WritableStreamAddWriteRequest(stream) { - const promise = newPromise((resolve, reject) => { - const writeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._writeRequests.push(writeRequest); - }); - return promise; - } - function WritableStreamDealWithRejection(stream, error) { - const state = stream._state; - if (state === 'writable') { - WritableStreamStartErroring(stream, error); - return; - } - WritableStreamFinishErroring(stream); - } - function WritableStreamStartErroring(stream, reason) { - const controller = stream._writableStreamController; - stream._state = 'erroring'; - stream._storedError = reason; - const writer = stream._writer; - if (writer !== undefined) { - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); - } - if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { - WritableStreamFinishErroring(stream); - } - } - function WritableStreamFinishErroring(stream) { - stream._state = 'errored'; - stream._writableStreamController[ErrorSteps](); - const storedError = stream._storedError; - stream._writeRequests.forEach(writeRequest => { - writeRequest._reject(storedError); - }); - stream._writeRequests = new SimpleQueue(); - if (stream._pendingAbortRequest === undefined) { - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const abortRequest = stream._pendingAbortRequest; - stream._pendingAbortRequest = undefined; - if (abortRequest._wasAlreadyErroring) { - abortRequest._reject(storedError); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); - uponPromise(promise, () => { - abortRequest._resolve(); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }, (reason) => { - abortRequest._reject(reason); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }); - } - function WritableStreamFinishInFlightWrite(stream) { - stream._inFlightWriteRequest._resolve(undefined); - stream._inFlightWriteRequest = undefined; - } - function WritableStreamFinishInFlightWriteWithError(stream, error) { - stream._inFlightWriteRequest._reject(error); - stream._inFlightWriteRequest = undefined; - WritableStreamDealWithRejection(stream, error); - } - function WritableStreamFinishInFlightClose(stream) { - stream._inFlightCloseRequest._resolve(undefined); - stream._inFlightCloseRequest = undefined; - const state = stream._state; - if (state === 'erroring') { - // The error was too late to do anything, so it is ignored. - stream._storedError = undefined; - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._resolve(); - stream._pendingAbortRequest = undefined; - } - } - stream._state = 'closed'; - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseResolve(writer); - } - } - function WritableStreamFinishInFlightCloseWithError(stream, error) { - stream._inFlightCloseRequest._reject(error); - stream._inFlightCloseRequest = undefined; - // Never execute sink abort() after sink close(). - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._reject(error); - stream._pendingAbortRequest = undefined; - } - WritableStreamDealWithRejection(stream, error); - } - // TODO(ricea): Fix alphabetical order. - function WritableStreamCloseQueuedOrInFlight(stream) { - if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; - } - function WritableStreamHasOperationMarkedInFlight(stream) { - if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; - } - function WritableStreamMarkCloseRequestInFlight(stream) { - stream._inFlightCloseRequest = stream._closeRequest; - stream._closeRequest = undefined; - } - function WritableStreamMarkFirstWriteRequestInFlight(stream) { - stream._inFlightWriteRequest = stream._writeRequests.shift(); - } - function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { - if (stream._closeRequest !== undefined) { - stream._closeRequest._reject(stream._storedError); - stream._closeRequest = undefined; - } - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseReject(writer, stream._storedError); - } - } - function WritableStreamUpdateBackpressure(stream, backpressure) { - const writer = stream._writer; - if (writer !== undefined && backpressure !== stream._backpressure) { - if (backpressure) { - defaultWriterReadyPromiseReset(writer); - } - else { - defaultWriterReadyPromiseResolve(writer); - } - } - stream._backpressure = backpressure; - } - /** - * A default writer vended by a {@link WritableStream}. - * - * @public - */ - class WritableStreamDefaultWriter { - constructor(stream) { - assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); - assertWritableStream(stream, 'First parameter'); - if (IsWritableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive writing by another writer'); - } - this._ownerWritableStream = stream; - stream._writer = this; - const state = stream._state; - if (state === 'writable') { - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { - defaultWriterReadyPromiseInitialize(this); - } - else { - defaultWriterReadyPromiseInitializeAsResolved(this); - } - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'erroring') { - defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'closed') { - defaultWriterReadyPromiseInitializeAsResolved(this); - defaultWriterClosedPromiseInitializeAsResolved(this); - } - else { - const storedError = stream._storedError; - defaultWriterReadyPromiseInitializeAsRejected(this, storedError); - defaultWriterClosedPromiseInitializeAsRejected(this, storedError); - } - } + this.s2k = null; /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the writer’s lock is released before the stream finishes closing. + * Symmetric algorithm to encrypt the key with + * @type {enums.symmetric} */ - get closed() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('closed')); - } - return this._closedPromise; - } + this.symmetric = null; /** - * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. - * A producer can use this information to determine the right amount of data to write. - * - * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort - * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when - * the writer’s lock is released. + * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) + * @type {enums.aead} */ - get desiredSize() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('desiredSize'); - } - if (this._ownerWritableStream === undefined) { - throw defaultWriterLockException('desiredSize'); - } - return WritableStreamDefaultWriterGetDesiredSize(this); - } + this.aead = null; /** - * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions - * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips - * back to zero or below, the getter will return a new promise that stays pending until the next transition. - * - * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become - * rejected. + * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis + * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older). + * This value is only relevant to know how to decrypt the key: + * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism. + * @type {Boolean} + * @private */ - get ready() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('ready')); - } - return this._readyPromise; - } + this.isLegacyAEAD = null; /** - * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + * Decrypted private parameters, referenced by name + * @type {Object} */ - abort(reason = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('abort')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('abort')); - } - return WritableStreamDefaultWriterAbort(this, reason); - } + this.privateParams = null; /** - * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + * `true` for keys whose integrity is already confirmed, based on + * the AEAD encryption mechanism + * @type {Boolean} + * @private */ - close() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('close')); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return promiseRejectedWith(defaultWriterLockException('close')); - } - if (WritableStreamCloseQueuedOrInFlight(stream)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamDefaultWriterClose(this); + this.usedModernAEAD = null; + } + + // 5.5.3. Secret-Key Packet Formats + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param {Uint8Array} bytes - Input string to read the packet from + * @async + */ + async read(bytes, config$1 = config) { + // - A Public-Key or Public-Subkey packet, as described above. + let i = await this.readPublicKey(bytes, config$1); + const startOfSecretKeyData = i; + + // - One octet indicating string-to-key usage conventions. Zero + // indicates that the secret-key data is not encrypted. 255 or 254 + // indicates that a string-to-key specifier is being given. Any + // other value is a symmetric-key encryption algorithm identifier. + this.s2kUsage = bytes[i++]; + + // - Only for a version 5 packet, a one-octet scalar octet count of + // the next 4 optional fields. + if (this.version === 5) { + i++; } - /** - * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. - * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from - * now on; otherwise, the writer will appear closed. - * - * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the - * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). - * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents - * other producers from writing in an interleaved manner. - */ - releaseLock() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('releaseLock'); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return; - } - WritableStreamDefaultWriterRelease(this); + + // - Only for a version 6 packet where the secret key material is + // encrypted (that is, where the previous octet is not zero), a one- + // octet scalar octet count of the cumulative length of all the + // following optional string-to-key parameter fields. + if (this.version === 6 && this.s2kUsage) { + i++; } - write(chunk = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('write')); + + try { + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one-octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + this.symmetric = bytes[i++]; + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + this.aead = bytes[i++]; } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('write to')); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + i++; } - return WritableStreamDefaultWriterWrite(this, chunk); - } - } - Object.defineProperties(WritableStreamDefaultWriter.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - releaseLock: { enumerable: true }, - write: { enumerable: true }, - closed: { enumerable: true }, - desiredSize: { enumerable: true }, - ready: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultWriter', - configurable: true - }); - } - // Abstract operations for the WritableStreamDefaultWriter. - function IsWritableStreamDefaultWriter(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { - return false; - } - return true; - } - // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. - function WritableStreamDefaultWriterAbort(writer, reason) { - const stream = writer._ownerWritableStream; - return WritableStreamAbort(stream, reason); - } - function WritableStreamDefaultWriterClose(writer) { - const stream = writer._ownerWritableStream; - return WritableStreamClose(stream); - } - function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseResolvedWith(undefined); - } - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - return WritableStreamDefaultWriterClose(writer); - } - function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { - if (writer._closedPromiseState === 'pending') { - defaultWriterClosedPromiseReject(writer, error); - } - else { - defaultWriterClosedPromiseResetToRejected(writer, error); - } - } - function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { - if (writer._readyPromiseState === 'pending') { - defaultWriterReadyPromiseReject(writer, error); - } - else { - defaultWriterReadyPromiseResetToRejected(writer, error); - } - } - function WritableStreamDefaultWriterGetDesiredSize(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (state === 'errored' || state === 'erroring') { - return null; - } - if (state === 'closed') { - return 0; - } - return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); - } - function WritableStreamDefaultWriterRelease(writer) { - const stream = writer._ownerWritableStream; - const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); - // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not - // rejected until afterwards. This means that simply testing state will not work. - WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); - stream._writer = undefined; - writer._ownerWritableStream = undefined; - } - function WritableStreamDefaultWriterWrite(writer, chunk) { - const stream = writer._ownerWritableStream; - const controller = stream._writableStreamController; - const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); - if (stream !== writer._ownerWritableStream) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - const state = stream._state; - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); - } - if (state === 'erroring') { - return promiseRejectedWith(stream._storedError); - } - const promise = WritableStreamAddWriteRequest(stream); - WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); - return promise; - } - const closeSentinel = {}; - /** - * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. - * - * @public - */ - class WritableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. - * - * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying - * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the - * normal lifecycle of interactions with the underlying sink. - */ - error(e = undefined) { - if (!IsWritableStreamDefaultController(this)) { - throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + const s2kType = bytes[i++]; + this.s2k = newS2KFromType(s2kType); + i += this.s2k.read(bytes.subarray(i, bytes.length)); + + if (this.s2k.type === 'gnu-dummy') { + return; } - const state = this._controlledWritableStream._state; - if (state !== 'writable') { - // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so - // just treat it as a no-op. - return; + } else if (this.s2kUsage) { + this.symmetric = this.s2kUsage; + } + + + if (this.s2kUsage) { + // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5). + // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format). + // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always + // fail if the key was parsed according to the wrong format, since the keys are processed differently. + // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag. + this.isLegacyAEAD = this.s2kUsage === 253 && ( + this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy)); + // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV) + // of the same length as the cipher's block size. + // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the + // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm. + // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero + if (this.s2kUsage !== 253 || this.isLegacyAEAD) { + this.iv = bytes.subarray( + i, + i + mod$1.getCipherParams(this.symmetric).blockSize + ); + this.usedModernAEAD = false; + } else { + // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted), + // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which + // is used as the nonce for the AEAD algorithm. + this.iv = bytes.subarray( + i, + i + mod$1.getAEADMode(this.aead).ivLength + ); + // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation. + this.usedModernAEAD = true; } - WritableStreamDefaultControllerError(this, e); - } - /** @internal */ - [AbortSteps](reason) { - const result = this._abortAlgorithm(reason); - WritableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [ErrorSteps]() { - ResetQueue(this); - } - } - Object.defineProperties(WritableStreamDefaultController.prototype, { - error: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultController', - configurable: true - }); - } - // Abstract operations implementing interface required by the WritableStream. - function IsWritableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { - return false; - } - return true; - } - function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledWritableStream = stream; - stream._writableStreamController = controller; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._writeAlgorithm = writeAlgorithm; - controller._closeAlgorithm = closeAlgorithm; - controller._abortAlgorithm = abortAlgorithm; - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - const startResult = startAlgorithm(); - const startPromise = promiseResolvedWith(startResult); - uponPromise(startPromise, () => { - controller._started = true; - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, r => { - controller._started = true; - WritableStreamDealWithRejection(stream, r); - }); - } - function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { - const controller = Object.create(WritableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let writeAlgorithm = () => promiseResolvedWith(undefined); - let closeAlgorithm = () => promiseResolvedWith(undefined); - let abortAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSink.start !== undefined) { - startAlgorithm = () => underlyingSink.start(controller); - } - if (underlyingSink.write !== undefined) { - writeAlgorithm = chunk => underlyingSink.write(chunk, controller); - } - if (underlyingSink.close !== undefined) { - closeAlgorithm = () => underlyingSink.close(); - } - if (underlyingSink.abort !== undefined) { - abortAlgorithm = reason => underlyingSink.abort(reason); - } - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - } - // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. - function WritableStreamDefaultControllerClearAlgorithms(controller) { - controller._writeAlgorithm = undefined; - controller._closeAlgorithm = undefined; - controller._abortAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; - } - function WritableStreamDefaultControllerClose(controller) { - EnqueueValueWithSize(controller, closeSentinel, 0); - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - } - function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { - try { - return controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); - return 1; - } - } - function WritableStreamDefaultControllerGetDesiredSize(controller) { - return controller._strategyHWM - controller._queueTotalSize; - } - function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); - return; - } - const stream = controller._controlledWritableStream; - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - } - // Abstract operations for the WritableStreamDefaultController. - function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { - const stream = controller._controlledWritableStream; - if (!controller._started) { - return; - } - if (stream._inFlightWriteRequest !== undefined) { - return; - } - const state = stream._state; - if (state === 'erroring') { - WritableStreamFinishErroring(stream); - return; - } - if (controller._queue.length === 0) { - return; - } - const value = PeekQueueValue(controller); - if (value === closeSentinel) { - WritableStreamDefaultControllerProcessClose(controller); - } - else { - WritableStreamDefaultControllerProcessWrite(controller, value); + + i += this.iv.length; + } + } catch (e) { + // if the s2k is unsupported, we still want to support encrypting and verifying with the given key + if (!this.s2kUsage) throw e; // always throw for decrypted keys + this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); + this.isEncrypted = true; } - } - function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { - if (controller._controlledWritableStream._state === 'writable') { - WritableStreamDefaultControllerError(controller, error); + + // - Only for a version 5 packet, a four-octet scalar octet count for + // the following key material. + if (this.version === 5) { + i += 4; } - } - function WritableStreamDefaultControllerProcessClose(controller) { - const stream = controller._controlledWritableStream; - WritableStreamMarkCloseRequestInFlight(stream); - DequeueValue(controller); - const sinkClosePromise = controller._closeAlgorithm(); - WritableStreamDefaultControllerClearAlgorithms(controller); - uponPromise(sinkClosePromise, () => { - WritableStreamFinishInFlightClose(stream); - }, reason => { - WritableStreamFinishInFlightCloseWithError(stream, reason); - }); - } - function WritableStreamDefaultControllerProcessWrite(controller, chunk) { - const stream = controller._controlledWritableStream; - WritableStreamMarkFirstWriteRequestInFlight(stream); - const sinkWritePromise = controller._writeAlgorithm(chunk); - uponPromise(sinkWritePromise, () => { - WritableStreamFinishInFlightWrite(stream); - const state = stream._state; - DequeueValue(controller); - if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); + + // - Plain or encrypted multiprecision integers comprising the secret + // key data. These algorithm-specific fields are as described + // below. + this.keyMaterial = bytes.subarray(i); + this.isEncrypted = !!this.s2kUsage; + + if (!this.isEncrypted) { + let cleartext; + if (this.version === 6) { + cleartext = this.keyMaterial; + } else { + cleartext = this.keyMaterial.subarray(0, -2); + if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { + throw new Error('Key checksum mismatch'); } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, reason => { - if (stream._state === 'writable') { - WritableStreamDefaultControllerClearAlgorithms(controller); + } + try { + const { read, privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + if (read < cleartext.length) { + throw new Error('Error reading MPIs'); } - WritableStreamFinishInFlightWriteWithError(stream, reason); - }); - } - function WritableStreamDefaultControllerGetBackpressure(controller) { - const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); - return desiredSize <= 0; - } - // A client of WritableStreamDefaultController may use these functions directly to bypass state check. - function WritableStreamDefaultControllerError(controller, error) { - const stream = controller._controlledWritableStream; - WritableStreamDefaultControllerClearAlgorithms(controller); - WritableStreamStartErroring(stream, error); - } - // Helper functions for the WritableStream. - function streamBrandCheckException$2(name) { - return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); - } - // Helper functions for the WritableStreamDefaultWriter. - function defaultWriterBrandCheckException(name) { - return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); - } - function defaultWriterLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released writer'); - } - function defaultWriterClosedPromiseInitialize(writer) { - writer._closedPromise = newPromise((resolve, reject) => { - writer._closedPromise_resolve = resolve; - writer._closedPromise_reject = reject; - writer._closedPromiseState = 'pending'; - }); - } - function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseReject(writer, reason); - } - function defaultWriterClosedPromiseInitializeAsResolved(writer) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseResolve(writer); - } - function defaultWriterClosedPromiseReject(writer, reason) { - if (writer._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._closedPromise); - writer._closedPromise_reject(reason); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'rejected'; - } - function defaultWriterClosedPromiseResetToRejected(writer, reason) { - defaultWriterClosedPromiseInitializeAsRejected(writer, reason); - } - function defaultWriterClosedPromiseResolve(writer) { - if (writer._closedPromise_resolve === undefined) { - return; + this.privateParams = privateParams; + } catch (err) { + if (err instanceof UnsupportedError) throw err; + // avoid throwing potentially sensitive errors + throw new Error('Error reading MPIs'); + } } - writer._closedPromise_resolve(undefined); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'resolved'; - } - function defaultWriterReadyPromiseInitialize(writer) { - writer._readyPromise = newPromise((resolve, reject) => { - writer._readyPromise_resolve = resolve; - writer._readyPromise_reject = reject; - }); - writer._readyPromiseState = 'pending'; - } - function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseReject(writer, reason); - } - function defaultWriterReadyPromiseInitializeAsResolved(writer) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseResolve(writer); - } - function defaultWriterReadyPromiseReject(writer, reason) { - if (writer._readyPromise_reject === undefined) { - return; + } + + /** + * Creates an OpenPGP key packet for the given key. + * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. + */ + write() { + const serializedPublicKey = this.writePublicKey(); + if (this.unparseableKeyMaterial) { + return util.concatUint8Array([ + serializedPublicKey, + this.unparseableKeyMaterial + ]); } - setPromiseIsHandledToTrue(writer._readyPromise); - writer._readyPromise_reject(reason); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'rejected'; - } - function defaultWriterReadyPromiseReset(writer) { - defaultWriterReadyPromiseInitialize(writer); - } - function defaultWriterReadyPromiseResetToRejected(writer, reason) { - defaultWriterReadyPromiseInitializeAsRejected(writer, reason); - } - function defaultWriterReadyPromiseResolve(writer) { - if (writer._readyPromise_resolve === undefined) { - return; + + const arr = [serializedPublicKey]; + arr.push(new Uint8Array([this.s2kUsage])); + + const optionalFieldsArr = []; + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one- octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + optionalFieldsArr.push(this.symmetric); + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + optionalFieldsArr.push(this.aead); + } + + const s2k = this.s2k.write(); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + optionalFieldsArr.push(s2k.length); + } + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + optionalFieldsArr.push(...s2k); } - writer._readyPromise_resolve(undefined); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'fulfilled'; - } - function isAbortSignal(value) { - if (typeof value !== 'object' || value === null) { - return false; + // - [Optional] If secret data is encrypted (string-to-key usage octet + // not zero), an Initial Vector (IV) of the same length as the + // cipher's block size. + if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { + optionalFieldsArr.push(...this.iv); } - try { - return typeof value.aborted === 'boolean'; + + if (this.version === 5 || (this.version === 6 && this.s2kUsage)) { + arr.push(new Uint8Array([optionalFieldsArr.length])); } - catch (_a) { - // AbortSignal.prototype.aborted throws if its brand check fails - return false; + arr.push(new Uint8Array(optionalFieldsArr)); + + if (!this.isDummy()) { + if (!this.s2kUsage) { + this.keyMaterial = mod$1.serializeParams(this.algorithm, this.privateParams); + } + + if (this.version === 5) { + arr.push(util.writeNumber(this.keyMaterial.length, 4)); + } + arr.push(this.keyMaterial); + + if (!this.s2kUsage && this.version !== 6) { + arr.push(util.writeChecksum(this.keyMaterial)); + } } - } - /// - const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + return util.concatUint8Array(arr); + } - /// - function isDOMExceptionConstructor(ctor) { - if (!(typeof ctor === 'function' || typeof ctor === 'object')) { - return false; - } - try { - new ctor(); - return true; + /** + * Check whether secret-key data is available in decrypted form. + * Returns false for gnu-dummy keys and null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return this.isEncrypted === false; + } + + /** + * Check whether the key includes secret key material. + * Some secret keys do not include it, and can thus only be used + * for public-key operations (encryption and verification). + * Such keys are: + * - GNU-dummy keys, where the secret material has been stripped away + * - encrypted keys with unsupported S2K or cipher + */ + isMissingSecretKeyMaterial() { + return this.unparseableKeyMaterial !== undefined || this.isDummy(); + } + + /** + * Check whether this is a gnu-dummy key + * @returns {Boolean} + */ + isDummy() { + return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + } + + /** + * Remove private key material, converting the key to a dummy one. + * The resulting key cannot be used for signing/decrypting but can still verify signatures. + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + makeDummy(config$1 = config) { + if (this.isDummy()) { + return; } - catch (_a) { - return false; + if (this.isDecrypted()) { + this.clearPrivateParams(); } - } - function createDOMExceptionPolyfill() { - // eslint-disable-next-line no-shadow - const ctor = function DOMException(message, name) { - this.message = message || ''; - this.name = name || 'Error'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - }; - ctor.prototype = Object.create(Error.prototype); - Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); - return ctor; - } - // eslint-disable-next-line no-redeclare - const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); - - function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { - const reader = AcquireReadableStreamDefaultReader(source); - const writer = AcquireWritableStreamDefaultWriter(dest); - source._disturbed = true; - let shuttingDown = false; - // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. - let currentWrite = promiseResolvedWith(undefined); - return newPromise((resolve, reject) => { - let abortAlgorithm; - if (signal !== undefined) { - abortAlgorithm = () => { - const error = new DOMException$1('Aborted', 'AbortError'); - const actions = []; - if (!preventAbort) { - actions.push(() => { - if (dest._state === 'writable') { - return WritableStreamAbort(dest, error); - } - return promiseResolvedWith(undefined); - }); - } - if (!preventCancel) { - actions.push(() => { - if (source._state === 'readable') { - return ReadableStreamCancel(source, error); - } - return promiseResolvedWith(undefined); - }); - } - shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); - }; - if (signal.aborted) { - abortAlgorithm(); - return; - } - signal.addEventListener('abort', abortAlgorithm); - } - // Using reader and writer, read all chunks from this and write them to dest - // - Backpressure must be enforced - // - Shutdown must stop all activity - function pipeLoop() { - return newPromise((resolveLoop, rejectLoop) => { - function next(done) { - if (done) { - resolveLoop(); - } - else { - // Use `PerformPromiseThen` instead of `uponPromise` to avoid - // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers - PerformPromiseThen(pipeStep(), next, rejectLoop); - } - } - next(false); - }); - } - function pipeStep() { - if (shuttingDown) { - return promiseResolvedWith(true); - } - return PerformPromiseThen(writer._readyPromise, () => { - return newPromise((resolveRead, rejectRead) => { - ReadableStreamDefaultReaderRead(reader, { - _chunkSteps: chunk => { - currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); - resolveRead(false); - }, - _closeSteps: () => resolveRead(true), - _errorSteps: rejectRead - }); - }); - }); - } - // Errors must be propagated forward - isOrBecomesErrored(source, reader._closedPromise, storedError => { - if (!preventAbort) { - shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Errors must be propagated backward - isOrBecomesErrored(dest, writer._closedPromise, storedError => { - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Closing must be propagated forward - isOrBecomesClosed(source, reader._closedPromise, () => { - if (!preventClose) { - shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); - } - else { - shutdown(); - } - }); - // Closing must be propagated backward - if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { - const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); - } - else { - shutdown(true, destClosed); - } - } - setPromiseIsHandledToTrue(pipeLoop()); - function waitForWritesToFinish() { - // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait - // for that too. - const oldCurrentWrite = currentWrite; - return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); - } - function isOrBecomesErrored(stream, promise, action) { - if (stream._state === 'errored') { - action(stream._storedError); - } - else { - uponRejection(promise, action); - } - } - function isOrBecomesClosed(stream, promise, action) { - if (stream._state === 'closed') { - action(); - } - else { - uponFulfillment(promise, action); - } - } - function shutdownWithAction(action, originalIsError, originalError) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), doTheRest); - } - else { - doTheRest(); - } - function doTheRest() { - uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); - } - } - function shutdown(isError, error) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); - } - else { - finalize(isError, error); - } - } - function finalize(isError, error) { - WritableStreamDefaultWriterRelease(writer); - ReadableStreamReaderGenericRelease(reader); - if (signal !== undefined) { - signal.removeEventListener('abort', abortAlgorithm); - } - if (isError) { - reject(error); - } - else { - resolve(undefined); - } - } - }); - } + delete this.unparseableKeyMaterial; + this.isEncrypted = null; + this.keyMaterial = null; + this.s2k = newS2KFromType(enums.s2k.gnu, config$1); + this.s2k.algorithm = 0; + this.s2k.c = 0; + this.s2k.type = 'gnu-dummy'; + this.s2kUsage = 254; + this.symmetric = enums.symmetric.aes256; + this.isLegacyAEAD = null; + this.usedModernAEAD = null; + } - /** - * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. - * - * @public - */ - class ReadableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('desiredSize'); - } - return ReadableStreamDefaultControllerGetDesiredSize(this); + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param {String} passphrase + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + if (this.isDummy()) { + return; } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('close'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits close'); - } - ReadableStreamDefaultControllerClose(this); + + if (!this.isDecrypted()) { + throw new Error('Key packet is already encrypted'); } - enqueue(chunk = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('enqueue'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits enqueue'); - } - return ReadableStreamDefaultControllerEnqueue(this, chunk); + + if (!passphrase) { + throw new Error('A non-empty passphrase is required for key encryption.'); } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('error'); - } - ReadableStreamDefaultControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableStream; - if (this._queue.length > 0) { - const chunk = DequeueValue(this); - if (this._closeRequested && this._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(this); - ReadableStreamClose(stream); - } - else { - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - readRequest._chunkSteps(chunk); - } - else { - ReadableStreamAddReadRequest(stream, readRequest); - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + const cleartext = mod$1.serializeParams(this.algorithm, this.privateParams); + this.symmetric = enums.symmetric.aes256; + + const { blockSize } = mod$1.getCipherParams(this.symmetric); + + if (config$1.aeadProtect) { + this.s2kUsage = 253; + this.aead = config$1.preferredAEADAlgorithm; + const mode = mod$1.getAEADMode(this.aead); + this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead. + this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material + + const serializedPacketTag = writeTag(this.constructor.tag); + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + + const modeInstance = await mode(this.symmetric, key); + this.iv = this.isLegacyAEAD ? mod$1.random.getRandomBytes(blockSize) : mod$1.random.getRandomBytes(mode.ivLength); + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + + this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData); + } else { + this.s2kUsage = 254; + this.usedModernAEAD = false; + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric); + this.iv = mod$1.random.getRandomBytes(blockSize); + this.keyMaterial = await mod$1.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + cleartext, + await mod$1.hash.sha1(cleartext, config$1) + ]), this.iv, config$1); } - } - Object.defineProperties(ReadableStreamDefaultController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - desiredSize: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultController', - configurable: true - }); - } - // Abstract operations for the ReadableStreamDefaultController. - function IsReadableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; + } + + /** + * Decrypts the private key params which are needed to use the key. + * Successful decryption does not imply key integrity, call validate() to confirm that. + * {@link SecretKeyPacket.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param {String} passphrase - The passphrase for this private key as string + * @throws {Error} if the key is already decrypted, or if decryption was not successful + * @async + */ + async decrypt(passphrase) { + if (this.isDummy()) { + return false; } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { - return false; + + if (this.unparseableKeyMaterial) { + throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); } - return true; - } - function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); - if (!shouldPull) { - return; + + if (this.isDecrypted()) { + throw new Error('Key packet is already decrypted.'); } - if (controller._pulling) { - controller._pullAgain = true; - return; + + let key; + const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only + if (this.s2kUsage === 254 || this.s2kUsage === 253) { + key = await produceEncryptionKey( + this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + } else if (this.s2kUsage === 255) { + throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); + } else { + throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); } - controller._pulling = true; - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); + + let cleartext; + if (this.s2kUsage === 253) { + const mode = mod$1.getAEADMode(this.aead); + const modeInstance = await mode(this.symmetric, key); + try { + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData); + } catch (err) { + if (err.message === 'Authentication tag mismatch') { + throw new Error('Incorrect key passphrase: ' + err.message); } - }, e => { - ReadableStreamDefaultControllerError(controller, e); - }); - } - function ReadableStreamDefaultControllerShouldCallPull(controller) { - const stream = controller._controlledReadableStream; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return false; - } - if (!controller._started) { - return false; + throw err; + } + } else { + const cleartextWithHash = await mod$1.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + + cleartext = cleartextWithHash.subarray(0, -20); + const hash = await mod$1.hash.sha1(cleartext); + + if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { + throw new Error('Incorrect key passphrase'); + } } - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; + + try { + const { privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + this.privateParams = privateParams; + } catch (err) { + throw new Error('Error reading MPIs'); } - const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; + this.isEncrypted = false; + this.keyMaterial = null; + this.s2kUsage = 0; + this.aead = null; + this.symmetric = null; + this.isLegacyAEAD = null; + } + + /** + * Checks that the key parameters are consistent + * @throws {Error} if validation was not successful + * @async + */ + async validate() { + if (this.isDummy()) { + return; } - return false; - } - function ReadableStreamDefaultControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; - } - // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. - function ReadableStreamDefaultControllerClose(controller) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; + + if (!this.isDecrypted()) { + throw new Error('Key is not decrypted'); } - const stream = controller._controlledReadableStream; - controller._closeRequested = true; - if (controller._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamClose(stream); + + if (this.usedModernAEAD) { + // key integrity confirmed by successful AEAD decryption + return; } - } - function ReadableStreamDefaultControllerEnqueue(controller, chunk) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; + + let validParams; + try { + // this can throw if some parameters are undefined + validParams = await mod$1.validateParams(this.algorithm, this.publicParams, this.privateParams); + } catch (_) { + validParams = false; } - const stream = controller._controlledReadableStream; - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - ReadableStreamFulfillReadRequest(stream, chunk, false); + if (!validParams) { + throw new Error('Key is invalid'); } - else { - let chunkSize; - try { - chunkSize = controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - ReadableStreamDefaultControllerError(controller, chunkSizeE); - throw chunkSizeE; - } - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - ReadableStreamDefaultControllerError(controller, enqueueE); - throw enqueueE; - } + } + + async generate(bits, curve) { + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if (this.version === 6 && ( + (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) || + this.algorithm === enums.publicKey.eddsaLegacy + )) { + throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`); + } + const { privateParams, publicParams } = await mod$1.generateParams(this.algorithm, bits, curve); + this.privateParams = privateParams; + this.publicParams = publicParams; + this.isEncrypted = false; + } + + /** + * Clear private key parameters + */ + clearPrivateParams() { + if (this.isMissingSecretKeyMaterial()) { + return; } - ReadableStreamDefaultControllerCallPullIfNeeded(controller); + + Object.keys(this.privateParams).forEach(name => { + const param = this.privateParams[name]; + param.fill(0); + delete this.privateParams[name]; + }); + this.privateParams = null; + this.isEncrypted = true; + } } - function ReadableStreamDefaultControllerError(controller, e) { - const stream = controller._controlledReadableStream; - if (stream._state !== 'readable') { - return; - } - ResetQueue(controller); - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); + + /** + * Derive encryption key + * @param {Number} keyVersion - key derivation differs for v5 keys + * @param {module:type/s2k} s2k + * @param {String} passphrase + * @param {module:enums.symmetric} cipherAlgo + * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5) + * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5) + * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only) + * @returns encryption key + */ + async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) { + if (s2k.type === 'argon2' && !aeadMode) { + throw new Error('Using Argon2 S2K without AEAD is not allowed'); + } + if (s2k.type === 'simple' && keyVersion === 6) { + throw new Error('Using Simple S2K with version 6 keys is not allowed'); + } + const { keySize } = mod$1.getCipherParams(cipherAlgo); + const derivedKey = await s2k.produceKey(passphrase, keySize); + if (!aeadMode || keyVersion === 5 || isLegacyAEAD) { + return derivedKey; + } + const info = util.concatUint8Array([ + serializedPacketTag, + new Uint8Array([keyVersion, cipherAlgo, aeadMode]) + ]); + return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize); } - function ReadableStreamDefaultControllerGetDesiredSize(controller) { - const state = controller._controlledReadableStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of the User ID Packet (Tag 13) + * + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ + class UserIDPacket { + static get tag() { + return enums.packet.userID; + } + + constructor() { + /** A string containing the user id. Usually in the form + * John Doe + * @type {String} + */ + this.userID = ''; + + this.name = ''; + this.email = ''; + this.comment = ''; + } + + /** + * Create UserIDPacket instance from object + * @param {Object} userID - Object specifying userID name, email and comment + * @returns {UserIDPacket} + * @static + */ + static fromObject(userID) { + if (util.isString(userID) || + (userID.name && !util.isString(userID.name)) || + (userID.email && !util.isEmailAddress(userID.email)) || + (userID.comment && !util.isString(userID.comment))) { + throw new Error('Invalid user ID format'); } - return controller._strategyHWM - controller._queueTotalSize; - } - // This is used in the implementation of TransformStream. - function ReadableStreamDefaultControllerHasBackpressure(controller) { - if (ReadableStreamDefaultControllerShouldCallPull(controller)) { - return false; + const packet = new UserIDPacket(); + Object.assign(packet, userID); + const components = []; + if (packet.name) components.push(packet.name); + if (packet.comment) components.push(`(${packet.comment})`); + if (packet.email) components.push(`<${packet.email}>`); + packet.userID = components.join(' '); + return packet; + } + + /** + * Parsing function for a user id packet (tag 13). + * @param {Uint8Array} input - Payload of a tag 13 packet + */ + read(bytes, config$1 = config) { + const userID = util.decodeUTF8(bytes); + if (userID.length > config$1.maxUserIDLength) { + throw new Error('User ID string is too long'); } - return true; - } - function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { - const state = controller._controlledReadableStream._state; - if (!controller._closeRequested && state === 'readable') { - return true; + + /** + * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1, + * as well comments placed between the name (if present) and the bracketed email address: + * - name (comment) + * - email + * In the first case, the `email` is the only required part, and it must contain the `@` symbol. + * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, + * since they interfere with `comment` parsing. + */ + const re = /^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/; + const matches = re.exec(userID); + if (matches !== null) { + const { name, comment, email } = matches.groups; + this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace + this.name = name?.trim() || ''; + this.email = email.substring(1, email.length - 1); // remove brackets + } else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace + this.email = userID; } - return false; - } - function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledReadableStream = stream; - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._closeRequested = false; - controller._pullAgain = false; - controller._pulling = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - }, r => { - ReadableStreamDefaultControllerError(controller, r); - }); - } - function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { - const controller = Object.create(ReadableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSource.start !== undefined) { - startAlgorithm = () => underlyingSource.start(controller); - } - if (underlyingSource.pull !== undefined) { - pullAlgorithm = () => underlyingSource.pull(controller); - } - if (underlyingSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingSource.cancel(reason); - } - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - } - // Helper functions for the ReadableStreamDefaultController. - function defaultControllerBrandCheckException$1(name) { - return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); - } - - function ReadableStreamTee(stream, cloneForBranch2) { - const reader = AcquireReadableStreamDefaultReader(stream); - let reading = false; - let canceled1 = false; - let canceled2 = false; - let reason1; - let reason2; - let branch1; - let branch2; - let resolveCancelPromise; - const cancelPromise = newPromise(resolve => { - resolveCancelPromise = resolve; - }); - function pullAlgorithm() { - if (reading) { - return promiseResolvedWith(undefined); - } - reading = true; - const readRequest = { - _chunkSteps: value => { - // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using - // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let - // successful synchronously-available reads get ahead of asynchronously-available errors. - queueMicrotask(() => { - reading = false; - const value1 = value; - const value2 = value; - // There is no way to access the cloning code right now in the reference implementation. - // If we add one then we'll need an implementation for serializable objects. - // if (!canceled2 && cloneForBranch2) { - // value2 = StructuredDeserialize(StructuredSerialize(value2)); - // } - if (!canceled1) { - ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1); - } - if (!canceled2) { - ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2); - } - }); - }, - _closeSteps: () => { - reading = false; - if (!canceled1) { - ReadableStreamDefaultControllerClose(branch1._readableStreamController); - } - if (!canceled2) { - ReadableStreamDefaultControllerClose(branch2._readableStreamController); - } - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }, - _errorSteps: () => { - reading = false; - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promiseResolvedWith(undefined); - } - function cancel1Algorithm(reason) { - canceled1 = true; - reason1 = reason; - if (canceled2) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function cancel2Algorithm(reason) { - canceled2 = true; - reason2 = reason; - if (canceled1) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function startAlgorithm() { - // do nothing - } - branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); - branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); - uponRejection(reader._closedPromise, (r) => { - ReadableStreamDefaultControllerError(branch1._readableStreamController, r); - ReadableStreamDefaultControllerError(branch2._readableStreamController, r); - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }); - return [branch1, branch2]; - } - function convertUnderlyingDefaultOrByteSource(source, context) { - assertDictionary(source, context); - const original = source; - const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; - const cancel = original === null || original === void 0 ? void 0 : original.cancel; - const pull = original === null || original === void 0 ? void 0 : original.pull; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - return { - autoAllocateChunkSize: autoAllocateChunkSize === undefined ? - undefined : - convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), - cancel: cancel === undefined ? - undefined : - convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), - pull: pull === undefined ? - undefined : - convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), - start: start === undefined ? - undefined : - convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), - type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) - }; - } - function convertUnderlyingSourceCancelCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); + this.userID = userID; + } + + /** + * Creates a binary representation of the user id packet + * @returns {Uint8Array} Binary representation. + */ + write() { + return util.encodeUTF8(this.userID); + } + + equals(otherUserID) { + return otherUserID && otherUserID.userID === this.userID; + } } - function convertUnderlyingSourcePullCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); + + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + * @extends SecretKeyPacket + */ + class SecretSubkeyPacket extends SecretKeyPacket { + static get tag() { + return enums.packet.secretSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); + } } - function convertUnderlyingSourceStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); + + /** + * Implementation of the Trust Packet (Tag 12) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ + class TrustPacket { + static get tag() { + return enums.packet.trust; + } + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + */ + read() { + throw new UnsupportedError('Trust packets are not supported'); + } + + write() { + throw new UnsupportedError('Trust packets are not supported'); + } } - function convertReadableStreamType(type, context) { - type = `${type}`; - if (type !== 'bytes') { - throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); - } - return type; + + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2022 Proton AG + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + + /** + * Implementation of the Padding Packet + * + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}: + * Padding Packet + */ + class PaddingPacket { + static get tag() { + return enums.packet.padding; + } + + constructor() { + this.padding = null; + } + + /** + * Read a padding packet + * @param {Uint8Array | ReadableStream} bytes + */ + read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars + // Padding packets are ignored, so this function is never called. + } + + /** + * Write the padding packet + * @returns {Uint8Array} The padding packet. + */ + write() { + return this.padding; + } + + /** + * Create random padding. + * @param {Number} length - The length of padding to be generated. + * @throws {Error} if padding generation was not successful + * @async + */ + async createPadding(length) { + this.padding = await mod$1.random.getRandomBytes(length); + } } - function convertReaderOptions(options, context) { - assertDictionary(options, context); - const mode = options === null || options === void 0 ? void 0 : options.mode; - return { - mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) - }; - } - function convertReadableStreamReaderMode(mode, context) { - mode = `${mode}`; - if (mode !== 'byob') { - throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); - } - return mode; - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function convertIteratorOptions(options, context) { - assertDictionary(options, context); - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - return { preventCancel: Boolean(preventCancel) }; - } - function convertPipeOptions(options, context) { - assertDictionary(options, context); - const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; - const signal = options === null || options === void 0 ? void 0 : options.signal; - if (signal !== undefined) { - assertAbortSignal(signal, `${context} has member 'signal' that`); - } - return { - preventAbort: Boolean(preventAbort), - preventCancel: Boolean(preventCancel), - preventClose: Boolean(preventClose), - signal - }; - } - function assertAbortSignal(signal, context) { - if (!isAbortSignal(signal)) { - throw new TypeError(`${context} is not an AbortSignal.`); - } - } + // A Signature can contain the following packets + const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + + /** + * Class that represents an OpenPGP signature. + */ + class Signature { + /** + * @param {PacketList} packetlist - The signature packets + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } + + /** + * Returns binary encoded signature + * @returns {ReadableStream} Binary signature. + */ + write() { + return this.packets.write(); + } + + /** + * Returns ASCII armored text of signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1); + } - function convertReadableWritablePair(pair, context) { - assertDictionary(pair, context); - const readable = pair === null || pair === void 0 ? void 0 : pair.readable; - assertRequiredField(readable, 'readable', 'ReadableWritablePair'); - assertReadableStream(readable, `${context} has member 'readable' that`); - const writable = pair === null || pair === void 0 ? void 0 : pair.writable; - assertRequiredField(writable, 'writable', 'ReadableWritablePair'); - assertWritableStream(writable, `${context} has member 'writable' that`); - return { readable, writable }; + /** + * Returns an array of KeyIDs of all of the issuers who created this signature + * @returns {Array} The Key IDs of the signing keys + */ + getSigningKeyIDs() { + return this.packets.map(packet => packet.issuerKeyID); + } } /** - * A readable stream represents a source of data, from which you can read. - * - * @public + * reads an (optionally armored) OpenPGP signature and returns a signature object + * @param {Object} options + * @param {String} [options.armoredSignature] - Armored signature to be parsed + * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New signature object. + * @async + * @static */ - class ReadableStream$1 { - constructor(rawUnderlyingSource = {}, rawStrategy = {}) { - if (rawUnderlyingSource === undefined) { - rawUnderlyingSource = null; - } - else { - assertObject(rawUnderlyingSource, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); - InitializeReadableStream(this); - if (underlyingSource.type === 'bytes') { - if (strategy.size !== undefined) { - throw new RangeError('The strategy for a byte stream cannot have a size function'); - } - const highWaterMark = ExtractHighWaterMark(strategy, 0); - SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); - } - else { - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); - } - } - /** - * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. - */ - get locked() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('locked'); - } - return IsReadableStreamLocked(this); - } - /** - * Cancels the stream, signaling a loss of interest in the stream by a consumer. - * - * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} - * method, which might or might not use it. - */ - cancel(reason = undefined) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('cancel')); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); - } - return ReadableStreamCancel(this, reason); - } - getReader(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('getReader'); - } - const options = convertReaderOptions(rawOptions, 'First parameter'); - if (options.mode === undefined) { - return AcquireReadableStreamDefaultReader(this); - } - return AcquireReadableStreamBYOBReader(this); - } - pipeThrough(rawTransform, rawOptions = {}) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('pipeThrough'); - } - assertRequiredArgument(rawTransform, 1, 'pipeThrough'); - const transform = convertReadableWritablePair(rawTransform, 'First parameter'); - const options = convertPipeOptions(rawOptions, 'Second parameter'); - if (IsReadableStreamLocked(this)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); - } - if (IsWritableStreamLocked(transform.writable)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); - } - const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - setPromiseIsHandledToTrue(promise); - return transform.readable; - } - pipeTo(destination, rawOptions = {}) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); - } - if (destination === undefined) { - return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); - } - if (!IsWritableStream(destination)) { - return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); - } - let options; - try { - options = convertPipeOptions(rawOptions, 'Second parameter'); - } - catch (e) { - return promiseRejectedWith(e); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); - } - if (IsWritableStreamLocked(destination)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); - } - return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - } - /** - * Tees this readable stream, returning a two-element array containing the two resulting branches as - * new {@link ReadableStream} instances. - * - * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. - * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be - * propagated to the stream's underlying source. - * - * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, - * this could allow interference between the two branches. - */ - tee() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('tee'); - } - const branches = ReadableStreamTee(this); - return CreateArrayFromList(branches); - } - values(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('values'); - } - const options = convertIteratorOptions(rawOptions, 'First parameter'); - return AcquireReadableStreamAsyncIterator(this, options.preventCancel); - } - } - Object.defineProperties(ReadableStream$1.prototype, { - cancel: { enumerable: true }, - getReader: { enumerable: true }, - pipeThrough: { enumerable: true }, - pipeTo: { enumerable: true }, - tee: { enumerable: true }, - values: { enumerable: true }, - locked: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStream', - configurable: true - }); - } - if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, { - value: ReadableStream$1.prototype.values, - writable: true, - configurable: true - }); - } - // Abstract operations for the ReadableStream. - // Throws if and only if startAlgorithm throws. - function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(ReadableStream$1.prototype); - InitializeReadableStream(stream); - const controller = Object.create(ReadableStreamDefaultController.prototype); - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - return stream; - } - function InitializeReadableStream(stream) { - stream._state = 'readable'; - stream._reader = undefined; - stream._storedError = undefined; - stream._disturbed = false; - } - function IsReadableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { - return false; - } - return true; - } - function IsReadableStreamLocked(stream) { - if (stream._reader === undefined) { - return false; - } - return true; - } - // ReadableStream API exposed for controllers. - function ReadableStreamCancel(stream, reason) { - stream._disturbed = true; - if (stream._state === 'closed') { - return promiseResolvedWith(undefined); - } - if (stream._state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - ReadableStreamClose(stream); - const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); - return transformPromiseWith(sourceCancelPromise, noop); - } - function ReadableStreamClose(stream) { - stream._state = 'closed'; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseResolve(reader); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._closeSteps(); - }); - reader._readRequests = new SimpleQueue(); - } - } - function ReadableStreamError(stream, e) { - stream._state = 'errored'; - stream._storedError = e; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseReject(reader, e); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._errorSteps(e); - }); - reader._readRequests = new SimpleQueue(); - } - else { - reader._readIntoRequests.forEach(readIntoRequest => { - readIntoRequest._errorSteps(e); - }); - reader._readIntoRequests = new SimpleQueue(); + async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredSignature || binarySignature; + if (!input) { + throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); + } + if (armoredSignature && !util.isString(armoredSignature)) { + throw new Error('readSignature: options.armoredSignature must be a string'); + } + if (binarySignature && !util.isUint8Array(binarySignature)) { + throw new Error('readSignature: options.binarySignature must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (armoredSignature) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.signature) { + throw new Error('Armored text not of type signature'); } + input = data; + } + const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1); + return new Signature(packetlist); } - // Helper functions for the ReadableStream. - function streamBrandCheckException$1(name) { - return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + + /** + * @fileoverview Provides helpers methods for key module + * @module key/helper + */ + + + async function generateSecretSubkey(options, config) { + const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); + secretSubkeyPacket.packets = null; + secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretSubkeyPacket.generate(options.rsaBits, options.curve); + await secretSubkeyPacket.computeFingerprintAndKeyID(); + return secretSubkeyPacket; } - function convertQueuingStrategyInit(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); - return { - highWaterMark: convertUnrestrictedDouble(highWaterMark) - }; + async function generateSecretKey(options, config) { + const secretKeyPacket = new SecretKeyPacket(options.date, config); + secretKeyPacket.packets = null; + secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); + await secretKeyPacket.computeFingerprintAndKeyID(); + return secretKeyPacket; } - const byteLengthSizeFunction = function size(chunk) { - return chunk.byteLength; - }; /** - * A queuing strategy that counts the number of bytes in each chunk. - * - * @public + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param {Array} signatures - List of signatures + * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature + * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures, + * `enums.signatures.certGeneric` should be given regardless of the actual trust level) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - full configuration + * @returns {Promise} The latest valid signature. + * @async */ - class ByteLengthQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('highWaterMark'); - } - return this._byteLengthQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by returning the value of its `byteLength` property. - */ - get size() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('size'); - } - return byteLengthSizeFunction; + async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { + let latestValid; + let exception; + for (let i = signatures.length - 1; i >= 0; i--) { + try { + if ( + (!latestValid || signatures[i].created >= latestValid.created) + ) { + await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); + latestValid = signatures[i]; + } + } catch (e) { + exception = e; } + } + if (!latestValid) { + throw util.wrapError( + `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` + .replace('certGeneric ', 'self-') + .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), + exception); + } + return latestValid; } - Object.defineProperties(ByteLengthQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'ByteLengthQueuingStrategy', - configurable: true - }); - } - // Helper functions for the ByteLengthQueuingStrategy. - function byteLengthBrandCheckException(name) { - return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + + function isDataExpired(keyPacket, signature, date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + const expirationTime = getKeyExpirationTime(keyPacket, signature); + return !(keyPacket.created <= normDate && normDate < expirationTime); + } + return false; } - function IsByteLengthQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { - return false; - } - return true; + + /** + * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} + * @param {SecretSubkeyPacket} subkey - Subkey key packet + * @param {SecretKeyPacket} primaryKey - Primary key packet + * @param {Object} options + * @param {Object} config - Full configuration + */ + async function createBindingSignature(subkey, primaryKey, options, config) { + const dataToSign = {}; + dataToSign.key = primaryKey; + dataToSign.bind = subkey; + const signatureProperties = { signatureType: enums.signature.subkeyBinding }; + if (options.sign) { + signatureProperties.keyFlags = [enums.keyFlags.signData]; + signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, { + signatureType: enums.signature.keyBinding + }, options.date, undefined, undefined, undefined, config); + } else { + signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; + } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; + } + const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); + return subkeySignaturePacket; } - const countSizeFunction = function size() { - return 1; - }; /** - * A queuing strategy that counts the number of chunks. - * - * @public + * Returns the preferred signature hash algorithm for a set of keys. + * @param {Array} [targetKeys] - The keys to get preferences from + * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from + * @param {Object} config - full configuration + * @returns {Promise} + * @async */ - class CountQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'CountQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._countQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('highWaterMark'); - } - return this._countQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by always returning 1. - * This ensures that the total queue size is a count of the number of chunks in the queue. - */ - get size() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('size'); - } - return countSizeFunction; + async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) { + /** + * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the + * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys). + * if no keys are available, `preferredSenderAlgo` is returned. + * For ECC signing key, the curve preferred hash is taken into account as well (see logic below). + */ + const defaultAlgo = enums.hash.sha256; // MUST implement + const preferredSenderAlgo = config.preferredHashAlgorithm; + + const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => { + const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config); + const targetPrefs = selfCertification.preferredHashAlgorithms; + return targetPrefs; + })); + const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys + for (const supportedAlgos of supportedAlgosPerTarget) { + for (const hashAlgo of supportedAlgos) { + try { + // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on + const supportedAlgo = enums.write(enums.hash, hashAlgo); + supportedAlgosMap.set( + supportedAlgo, + supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1 + ); + } catch {} } - } - Object.defineProperties(CountQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'CountQueuingStrategy', - configurable: true - }); - } - // Helper functions for the CountQueuingStrategy. - function countBrandCheckException(name) { - return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); - } - function IsCountQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; + } + const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo; + const getStrongestSupportedHashAlgo = () => { + if (supportedAlgosMap.size === 0) { + return defaultAlgo; } - if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { - return false; + const sortedHashAlgos = Array.from(supportedAlgosMap.keys()) + .filter(hashAlgo => isSupportedHashAlgo(hashAlgo)) + .sort((algoA, algoB) => mod$1.hash.getHashByteLength(algoA) - mod$1.hash.getHashByteLength(algoB)); + const strongestHashAlgo = sortedHashAlgos[0]; + // defaultAlgo is always implicilty supported, and might be stronger than the rest + return mod$1.hash.getHashByteLength(strongestHashAlgo) >= mod$1.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo; + }; + + const eccAlgos = new Set([ + enums.publicKey.ecdsa, + enums.publicKey.eddsaLegacy, + enums.publicKey.ed25519, + enums.publicKey.ed448 + ]); + + if (eccAlgos.has(signingKeyPacket.algorithm)) { + // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see: + // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5 + // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough; + // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve + // preferred algo, even if not supported by all targets. + const preferredCurveAlgo = mod$1.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid); + + const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo); + const preferredSenderAlgoStrongerThanCurveAlgo = mod$1.hash.getHashByteLength(preferredSenderAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo); + + if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) { + return preferredSenderAlgo; + } else { + const strongestSupportedAlgo = getStrongestSupportedHashAlgo(); + return mod$1.hash.getHashByteLength(strongestSupportedAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo) ? + strongestSupportedAlgo : + preferredCurveAlgo; } - return true; - } + } - function convertTransformer(original, context) { - assertDictionary(original, context); - const flush = original === null || original === void 0 ? void 0 : original.flush; - const readableType = original === null || original === void 0 ? void 0 : original.readableType; - const start = original === null || original === void 0 ? void 0 : original.start; - const transform = original === null || original === void 0 ? void 0 : original.transform; - const writableType = original === null || original === void 0 ? void 0 : original.writableType; - return { - flush: flush === undefined ? - undefined : - convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), - readableType, - start: start === undefined ? - undefined : - convertTransformerStartCallback(start, original, `${context} has member 'start' that`), - transform: transform === undefined ? - undefined : - convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), - writableType - }; - } - function convertTransformerFlushCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); - } - function convertTransformerStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); - } - function convertTransformerTransformCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this, + // since it was manually set by the sender. + return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo(); } - // Class TransformStream /** - * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, - * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. - * In a manner specific to the transform stream in question, writes to the writable side result in new data being - * made available for reading from the readable side. - * - * @public + * Returns the preferred compression algorithm for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Preferred compression algorithm + * @async */ - class TransformStream$1 { - constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { - if (rawTransformer === undefined) { - rawTransformer = null; - } - const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); - const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); - const transformer = convertTransformer(rawTransformer, 'First parameter'); - if (transformer.readableType !== undefined) { - throw new RangeError('Invalid readableType specified'); - } - if (transformer.writableType !== undefined) { - throw new RangeError('Invalid writableType specified'); - } - const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); - const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); - const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); - const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); - let startPromise_resolve; - const startPromise = newPromise(resolve => { - startPromise_resolve = resolve; - }); - InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); - if (transformer.start !== undefined) { - startPromise_resolve(transformer.start(this._transformStreamController)); - } - else { - startPromise_resolve(undefined); - } - } - /** - * The readable side of the transform stream. - */ - get readable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('readable'); - } - return this._readable; - } - /** - * The writable side of the transform stream. - */ - get writable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('writable'); - } - return this._writable; - } - } - Object.defineProperties(TransformStream$1.prototype, { - readable: { enumerable: true }, - writable: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStream', - configurable: true - }); - } - function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { - function startAlgorithm() { - return startPromise; - } - function writeAlgorithm(chunk) { - return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); - } - function abortAlgorithm(reason) { - return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); - } - function closeAlgorithm() { - return TransformStreamDefaultSinkCloseAlgorithm(stream); - } - stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); - function pullAlgorithm() { - return TransformStreamDefaultSourcePullAlgorithm(stream); - } - function cancelAlgorithm(reason) { - TransformStreamErrorWritableAndUnblockWrite(stream, reason); - return promiseResolvedWith(undefined); - } - stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. - stream._backpressure = undefined; - stream._backpressureChangePromise = undefined; - stream._backpressureChangePromise_resolve = undefined; - TransformStreamSetBackpressure(stream, true); - stream._transformStreamController = undefined; - } - function IsTransformStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { - return false; - } - return true; - } - // This is a no-op if both sides are already errored. - function TransformStreamError(stream, e) { - ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); - TransformStreamErrorWritableAndUnblockWrite(stream, e); - } - function TransformStreamErrorWritableAndUnblockWrite(stream, e) { - TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); - WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); - if (stream._backpressure) { - // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() - // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time - // _backpressure is set. - TransformStreamSetBackpressure(stream, false); - } - } - function TransformStreamSetBackpressure(stream, backpressure) { - // Passes also when called during construction. - if (stream._backpressureChangePromise !== undefined) { - stream._backpressureChangePromise_resolve(); - } - stream._backpressureChangePromise = newPromise(resolve => { - stream._backpressureChangePromise_resolve = resolve; - }); - stream._backpressure = backpressure; + async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const defaultAlgo = enums.compression.uncompressed; + const preferredSenderAlgo = config$1.preferredCompressionAlgorithm; + + // if preferredSenderAlgo appears in the prefs of all recipients, we pick it + // otherwise we use the default algo + // if no keys are available, preferredSenderAlgo is returned + const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { + const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1); + const recipientPrefs = selfCertification.preferredCompressionAlgorithms; + return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; + })); + return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; } - // Class TransformStreamDefaultController + /** - * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. - * - * @public + * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred + * @async */ - class TransformStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. - */ - get desiredSize() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('desiredSize'); - } - const readableController = this._controlledTransformStream._readable._readableStreamController; - return ReadableStreamDefaultControllerGetDesiredSize(readableController); - } - enqueue(chunk = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('enqueue'); - } - TransformStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors both the readable side and the writable side of the controlled transform stream, making all future - * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. - */ - error(reason = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('error'); - } - TransformStreamDefaultControllerError(this, reason); - } - /** - * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the - * transformer only needs to consume a portion of the chunks written to the writable side. - */ - terminate() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('terminate'); - } - TransformStreamDefaultControllerTerminate(this); - } - } - Object.defineProperties(TransformStreamDefaultController.prototype, { - enqueue: { enumerable: true }, - error: { enumerable: true }, - terminate: { enumerable: true }, - desiredSize: { enumerable: true } - }); - if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStreamDefaultController', - configurable: true - }); - } - // Transform Stream Default Controller Abstract Operations - function IsTransformStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { - return false; + async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1))); + const withAEAD = keys.length ? + selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) : + config$1.aeadProtect; + + if (withAEAD) { + const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb }; + const desiredCipherSuites = [ + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm }, + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb }, + { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm } + ]; + for (const desiredCipherSuite of desiredCipherSuites) { + if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some( + cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo + ))) { + return desiredCipherSuite; + } } - return true; + return defaultCipherSuite; + } + const defaultSymAlgo = enums.symmetric.aes128; + const desiredSymAlgo = config$1.preferredSymmetricAlgorithm; + return { + symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ? + desiredSymAlgo : + defaultSymAlgo, + aeadAlgo: undefined + }; } - function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { - controller._controlledTransformStream = stream; - stream._transformStreamController = controller; - controller._transformAlgorithm = transformAlgorithm; - controller._flushAlgorithm = flushAlgorithm; + + /** + * Create signature packet + * @param {Object} dataToSign - Contains packets to be signed + * @param {Array} recipientKeys - keys to get preferences from + * @param {SecretKeyPacket| + * SecretSubkeyPacket} signingKeyPacket secret key packet for signing + * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing + * @param {Date} [date] - Override the creationtime of the signature + * @param {Object} [userID] - User ID + * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [detached] - Whether to create a detached signature packet + * @param {Object} config - full configuration + * @returns {Promise} Signature packet. + */ + async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) { + if (signingKeyPacket.isDummy()) { + throw new Error('Cannot sign with a gnu-dummy key.'); + } + if (!signingKeyPacket.isDecrypted()) { + throw new Error('Signing key is not decrypted.'); + } + const signaturePacket = new SignaturePacket(); + Object.assign(signaturePacket, signatureProperties); + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config); + signaturePacket.rawNotations = [...notations]; + await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config); + return signaturePacket; } - function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { - const controller = Object.create(TransformStreamDefaultController.prototype); - let transformAlgorithm = (chunk) => { - try { - TransformStreamDefaultControllerEnqueue(controller, chunk); - return promiseResolvedWith(undefined); - } - catch (transformResultE) { - return promiseRejectedWith(transformResultE); + + /** + * Merges signatures from source[attr] to dest[attr] + * @param {Object} source + * @param {Object} dest + * @param {String} attr + * @param {Date} [date] - date to use for signature expiration check, instead of the current time + * @param {Function} [checkFn] - signature only merged if true + */ + async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { + source = source[attr]; + if (source) { + if (!dest[attr].length) { + dest[attr] = source; + } else { + await Promise.all(source.map(async function(sourceSig) { + if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && + !dest[attr].some(function(destSig) { + return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); + })) { + dest[attr].push(sourceSig); } - }; - let flushAlgorithm = () => promiseResolvedWith(undefined); - if (transformer.transform !== undefined) { - transformAlgorithm = chunk => transformer.transform(chunk, controller); - } - if (transformer.flush !== undefined) { - flushAlgorithm = () => transformer.flush(controller); + })); } - SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); - } - function TransformStreamDefaultControllerClearAlgorithms(controller) { - controller._transformAlgorithm = undefined; - controller._flushAlgorithm = undefined; + } } - function TransformStreamDefaultControllerEnqueue(controller, chunk) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { - throw new TypeError('Readable side is not in a state that permits enqueue'); - } - // We throttle transform invocations based on the backpressure of the ReadableStream, but we still - // accept TransformStreamDefaultControllerEnqueue() calls. + + /** + * Checks if a given certificate or binding signature is revoked + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Object} dataToVerify - The data to check + * @param {Array} revocations - The revocation signatures to check + * @param {SignaturePacket} signature - The certificate or signature to check + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the signature revokes the data. + * @async + */ + async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { + key = key || primaryKey; + const revocationKeyIDs = []; + await Promise.all(revocations.map(async function(revocationSignature) { try { - ReadableStreamDefaultControllerEnqueue(readableController, chunk); - } - catch (e) { - // This happens when readableStrategy.size() throws. - TransformStreamErrorWritableAndUnblockWrite(stream, e); - throw stream._readable._storedError; - } - const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); - if (backpressure !== stream._backpressure) { - TransformStreamSetBackpressure(stream, true); - } - } - function TransformStreamDefaultControllerError(controller, e) { - TransformStreamError(controller._controlledTransformStream, e); - } - function TransformStreamDefaultControllerPerformTransform(controller, chunk) { - const transformPromise = controller._transformAlgorithm(chunk); - return transformPromiseWith(transformPromise, undefined, r => { - TransformStreamError(controller._controlledTransformStream, r); - throw r; - }); - } - function TransformStreamDefaultControllerTerminate(controller) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - ReadableStreamDefaultControllerClose(readableController); - const error = new TypeError('TransformStream terminated'); - TransformStreamErrorWritableAndUnblockWrite(stream, error); - } - // TransformStreamDefaultSink Algorithms - function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { - const controller = stream._transformStreamController; - if (stream._backpressure) { - const backpressureChangePromise = stream._backpressureChangePromise; - return transformPromiseWith(backpressureChangePromise, () => { - const writable = stream._writable; - const state = writable._state; - if (state === 'erroring') { - throw writable._storedError; - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - }); - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - } - function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { - // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already - // errored. - TransformStreamError(stream, reason); - return promiseResolvedWith(undefined); - } - function TransformStreamDefaultSinkCloseAlgorithm(stream) { - // stream._readable cannot change after construction, so caching it across a call to user code is safe. - const readable = stream._readable; - const controller = stream._transformStreamController; - const flushPromise = controller._flushAlgorithm(); - TransformStreamDefaultControllerClearAlgorithms(controller); - // Return a promise that is fulfilled with undefined on success. - return transformPromiseWith(flushPromise, () => { - if (readable._state === 'errored') { - throw readable._storedError; - } - ReadableStreamDefaultControllerClose(readable._readableStreamController); - }, r => { - TransformStreamError(stream, r); - throw readable._storedError; - }); - } - // TransformStreamDefaultSource Algorithms - function TransformStreamDefaultSourcePullAlgorithm(stream) { - // Invariant. Enforced by the promises returned by start() and pull(). - TransformStreamSetBackpressure(stream, false); - // Prevent the next pull() call until there is backpressure. - return stream._backpressureChangePromise; - } - // Helper functions for the TransformStreamDefaultController. - function defaultControllerBrandCheckException(name) { - return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + if ( + // Note: a third-party revocation signature could legitimately revoke a + // self-signature if the signature has an authorized revocation key. + // However, we don't support passing authorized revocation keys, nor + // verifying such revocation signatures. Instead, we indicate an error + // when parsing a key with an authorized revocation key, and ignore + // third-party revocation signatures here. (It could also be revoking a + // third-party key certification, which should only affect + // `verifyAllCertifications`.) + !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) + ) { + const isHardRevocation = ![ + enums.reasonForRevocation.keyRetired, + enums.reasonForRevocation.keySuperseded, + enums.reasonForRevocation.userIDInvalid + ].includes(revocationSignature.reasonForRevocationFlag); + + await revocationSignature.verify( + key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config + ); + + // TODO get an identifier of the revoked object instead + revocationKeyIDs.push(revocationSignature.issuerKeyID); + } + } catch (e) {} + })); + // TODO further verify that this is the signature that should be revoked + if (signature) { + signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : + signature.revoked || false; + return signature.revoked; + } + return revocationKeyIDs.length > 0; } - // Helper functions for the TransformStream. - function streamBrandCheckException(name) { - return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + + /** + * Returns key expiration time based on the given certification signature. + * The expiration time of the signature is ignored. + * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check + * @param {SignaturePacket} signature - signature to process + * @returns {Date|Infinity} expiration time or infinity if the key does not expire + */ + function getKeyExpirationTime(keyPacket, signature) { + let expirationTime; + // check V4 expiration time + if (signature.keyNeverExpires === false) { + expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; + } + return expirationTime ? new Date(expirationTime) : Infinity; } - var ponyfill_es6 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, - CountQueuingStrategy: CountQueuingStrategy, - ReadableByteStreamController: ReadableByteStreamController, - ReadableStream: ReadableStream$1, - ReadableStreamBYOBReader: ReadableStreamBYOBReader, - ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, - ReadableStreamDefaultController: ReadableStreamDefaultController, - ReadableStreamDefaultReader: ReadableStreamDefaultReader, - TransformStream: TransformStream$1, - TransformStreamDefaultController: TransformStreamDefaultController, - WritableStream: WritableStream$1, - WritableStreamDefaultController: WritableStreamDefaultController, - WritableStreamDefaultWriter: WritableStreamDefaultWriter - }); + function sanitizeKeyOptions(options, subkeyDefaults = {}) { + options.type = options.type || subkeyDefaults.type; + options.curve = options.curve || subkeyDefaults.curve; + options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; + options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; + options.sign = options.sign || false; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + switch (options.type) { + case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve` + try { + options.curve = enums.write(enums.curve, options.curve); + } catch (e) { + throw new Error('Unknown curve'); + } + if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy || + options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now + options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; + } + if (options.sign) { + options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; + } else { + options.algorithm = enums.publicKey.ecdh; + } + break; + case 'curve25519': + options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519; + break; + case 'curve448': + options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448; + break; + case 'rsa': + options.algorithm = enums.publicKey.rsaEncryptSign; + break; + default: + throw new Error(`Unsupported key type ${options.type}`); + } + return options; } - function assert$1(test) { - if (!test) { - throw new TypeError('Assertion failed'); - } + function validateSigningKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + default: + return false; + } } - function noop$1() { - return; - } - function typeIsObject$1(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; + function validateEncryptionKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + default: + return false; + } } - function isStreamConstructor(ctor) { - if (typeof ctor !== 'function') { - return false; - } - var startCalled = false; - try { - new ctor({ - start: function () { - startCalled = true; - } - }); - } - catch (e) { - // ignore - } - return startCalled; - } - function isReadableStream(readable) { - if (!typeIsObject$1(readable)) { - return false; - } - if (typeof readable.getReader !== 'function') { - return false; - } - return true; - } - function isReadableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isReadableStream(new ctor())) { - return false; - } - return true; - } - function isWritableStream(writable) { - if (!typeIsObject$1(writable)) { - return false; - } - if (typeof writable.getWriter !== 'function') { - return false; - } - return true; - } - function isWritableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isWritableStream(new ctor())) { - return false; - } - return true; - } - function isTransformStream(transform) { - if (!typeIsObject$1(transform)) { - return false; - } - if (!isReadableStream(transform.readable)) { - return false; - } - if (!isWritableStream(transform.writable)) { - return false; - } - return true; - } - function isTransformStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isTransformStream(new ctor())) { - return false; - } - return true; - } - function supportsByobReader(readable) { - try { - var reader = readable.getReader({ mode: 'byob' }); - reader.releaseLock(); + function validateDecryptionKeyPacket(keyPacket, signature, config) { + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) { + // This is only relevant for RSA keys, all other signing algorithms cannot decrypt return true; + } + + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; } - catch (_a) { - return false; - } + default: + return false; + } } - function supportsByteSource(ctor) { - try { - new ctor({ type: 'bytes' }); - return true; - } - catch (_a) { - return false; - } + + /** + * Check key against blacklisted algorithms and minimum strength requirements. + * @param {SecretKeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket + * @param {Config} config + * @throws {Error} if the key packet does not meet the requirements + */ + function checkKeyRequirements(keyPacket, config) { + const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); + const algoInfo = keyPacket.getAlgorithmInfo(); + if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { + throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); + } + switch (keyAlgo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.rsaEncrypt: + if (algoInfo.bits < config.minRSABits) { + throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); + } + break; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ecdh: + if (config.rejectCurves.has(algoInfo.curve)) { + throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); + } + break; + } } - function createReadableStreamWrapper(ctor) { - assert$1(isReadableStreamConstructor(ctor)); - var byteSourceSupported = supportsByteSource(ctor); - return function (readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - type = parseReadableType(type); - if (type === 'bytes' && !byteSourceSupported) { - type = undefined; - } - if (readable.constructor === ctor) { - if (type !== 'bytes' || supportsByobReader(readable)) { - return readable; - } - } - if (type === 'bytes') { - var source = createWrappingReadableSource(readable, { type: type }); - return new ctor(source); - } - else { - var source = createWrappingReadableSource(readable); - return new ctor(source); - } + /** + * @module key/User + */ + + + /** + * Class that represents an user ID or attribute packet and the relevant signatures. + * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info + * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + */ + class User { + constructor(userPacket, mainKey) { + this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; + this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; + this.selfCertifications = []; + this.otherCertifications = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } + + /** + * Transforms structured user data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.userID || this.userAttribute); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.selfCertifications); + packetlist.push(...this.otherCertifications); + return packetlist; + } + + /** + * Shallow clone + * @returns {User} + */ + clone() { + const user = new User(this.userID || this.userAttribute, this.mainKey); + user.selfCertifications = [...this.selfCertifications]; + user.otherCertifications = [...this.otherCertifications]; + user.revocationSignatures = [...this.revocationSignatures]; + return user; + } + + /** + * Generate third-party certifications over this user and its primary key + * @param {Array} signingKeys - Decrypted private keys for signing + * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} New user with new certifications. + * @async + */ + async certify(signingKeys, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { + if (!privateKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + if (privateKey.hasSameFingerprintAs(primaryKey)) { + throw new Error("The user's own key can only be used for self-certifications"); + } + const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); + return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, { + // Most OpenPGP implementations use generic certification (0x10) + signatureType: enums.signature.certGeneric, + keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] + }, date, undefined, undefined, undefined, config); + })); + await user.update(this, date, config); + return user; + } + + /** + * Checks if a given certificate of the user is revoked + * @param {SignaturePacket} certificate - The certificate to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked(primaryKey, enums.signature.certRevocation, { + key: primaryKey, + userID: this.userID, + userAttribute: this.userAttribute + }, this.revocationSignatures, certificate, keyPacket, date, config$1); + } + + /** + * Verifies the user certificate. + * @param {SignaturePacket} certificate - A certificate of this user + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate + * @throws if the user certificate is invalid. + * @async + */ + async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey }; - } - function createWrappingReadableSource(readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - assert$1(isReadableStream(readable)); - assert$1(readable.locked === false); - type = parseReadableType(type); - var source; - if (type === 'bytes') { - source = new WrappingReadableByteStreamSource(readable); - } - else { - source = new WrappingReadableStreamDefaultSource(readable); - } - return source; - } - function parseReadableType(type) { - var typeString = String(type); - if (typeString === 'bytes') { - return typeString; - } - else if (type === undefined) { - return type; - } - else { - throw new RangeError('Invalid type is specified'); + const { issuerKeyID } = certificate; + const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); + if (issuerKeys.length === 0) { + return null; } - } - var AbstractWrappingReadableStreamSource = /** @class */ (function () { - function AbstractWrappingReadableStreamSource(underlyingStream) { - this._underlyingReader = undefined; - this._readerMode = undefined; - this._readableStreamController = undefined; - this._pendingRead = undefined; - this._underlyingStream = underlyingStream; - // always keep a reader attached to detect close/error - this._attachDefaultReader(); + await Promise.all(issuerKeys.map(async key => { + const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); + if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { + throw new Error('User certificate is revoked'); + } + try { + await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('User certificate is invalid', e); + } + })); + return true; + } + + /** + * Verifies all user certificates + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllCertifications(verificationKeys, date = new Date(), config) { + const that = this; + const certifications = this.selfCertifications.concat(this.otherCertifications); + return Promise.all(certifications.map(async certification => ({ + keyID: certification.issuerKeyID, + valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) + }))); + } + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} Status of user. + * @throws {Error} if there are no valid self signatures. + * @async + */ + async verify(date = new Date(), config) { + if (!this.selfCertifications.length) { + throw new Error('No self-certifications found'); } - AbstractWrappingReadableStreamSource.prototype.start = function (controller) { - this._readableStreamController = controller; - }; - AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) { - assert$1(this._underlyingReader !== undefined); - return this._underlyingReader.cancel(reason); - }; - AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () { - if (this._readerMode === "default" /* DEFAULT */) { - return; - } - this._detachReader(); - var reader = this._underlyingStream.getReader(); - this._readerMode = "default" /* DEFAULT */; - this._attachReader(reader); - }; - AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) { - var _this = this; - assert$1(this._underlyingReader === undefined); - this._underlyingReader = reader; - var closed = this._underlyingReader.closed; - if (!closed) { - return; - } - closed - .then(function () { return _this._finishPendingRead(); }) - .then(function () { - if (reader === _this._underlyingReader) { - _this._readableStreamController.close(); - } - }, function (reason) { - if (reader === _this._underlyingReader) { - _this._readableStreamController.error(reason); - } - }) - .catch(noop$1); + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey }; - AbstractWrappingReadableStreamSource.prototype._detachReader = function () { - if (this._underlyingReader === undefined) { - return; + // TODO replace when Promise.some or Promise.any are implemented + let exception; + for (let i = this.selfCertifications.length - 1; i >= 0; i--) { + try { + const selfCertification = this.selfCertifications[i]; + if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { + throw new Error('Self-certification is revoked'); } - this._underlyingReader.releaseLock(); - this._underlyingReader = undefined; - this._readerMode = undefined; - }; - AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () { - var _this = this; - this._attachDefaultReader(); - // TODO Backpressure? - var read = this._underlyingReader.read() - .then(function (result) { - var controller = _this._readableStreamController; - if (result.done) { - _this._tryClose(); - } - else { - controller.enqueue(result.value); - } - }); - this._setPendingRead(read); - return read; - }; - AbstractWrappingReadableStreamSource.prototype._tryClose = function () { try { - this._readableStreamController.close(); - } - catch (_a) { - // already errored or closed - } - }; - AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) { - var _this = this; - var pendingRead; - var finishRead = function () { - if (_this._pendingRead === pendingRead) { - _this._pendingRead = undefined; - } - }; - this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead); - }; - AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () { - var _this = this; - if (!this._pendingRead) { - return undefined; + await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('Self-certification is invalid', e); } - var afterRead = function () { return _this._finishPendingRead(); }; - return this._pendingRead.then(afterRead, afterRead); - }; - return AbstractWrappingReadableStreamSource; - }()); - var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) { - __extends(WrappingReadableStreamDefaultSource, _super); - function WrappingReadableStreamDefaultSource() { - return _super !== null && _super.apply(this, arguments) || this; + return true; + } catch (e) { + exception = e; + } } - WrappingReadableStreamDefaultSource.prototype.pull = function () { - return this._pullWithDefaultReader(); + throw exception; + } + + /** + * Update user with new components from specified user + * @param {User} sourceUser - Source user to merge + * @param {Date} date - Date to verify the validity of signatures + * @param {Object} config - Full configuration + * @returns {Promise} + * @async + */ + async update(sourceUser, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey }; - return WrappingReadableStreamDefaultSource; - }(AbstractWrappingReadableStreamSource)); - function toUint8Array(view) { - return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); - } - function copyArrayBufferView(from, to) { - var fromArray = toUint8Array(from); - var toArray = toUint8Array(to); - toArray.set(fromArray, 0); - } - var WrappingReadableByteStreamSource = /** @class */ (function (_super) { - __extends(WrappingReadableByteStreamSource, _super); - function WrappingReadableByteStreamSource(underlyingStream) { - var _this = this; - var supportsByob = supportsByobReader(underlyingStream); - _this = _super.call(this, underlyingStream) || this; - _this._supportsByob = supportsByob; - return _this; - } - Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", { - get: function () { - return 'bytes'; - }, - enumerable: false, - configurable: true + // self signatures + await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { + try { + await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); + return true; + } catch (e) { + return false; + } }); - WrappingReadableByteStreamSource.prototype._attachByobReader = function () { - if (this._readerMode === "byob" /* BYOB */) { - return; - } - assert$1(this._supportsByob); - this._detachReader(); - var reader = this._underlyingStream.getReader({ mode: 'byob' }); - this._readerMode = "byob" /* BYOB */; - this._attachReader(reader); - }; - WrappingReadableByteStreamSource.prototype.pull = function () { - if (this._supportsByob) { - var byobRequest = this._readableStreamController.byobRequest; - if (byobRequest) { - return this._pullWithByobRequest(byobRequest); - } - } - return this._pullWithDefaultReader(); - }; - WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) { - var _this = this; - this._attachByobReader(); - // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly - // create a separate buffer to read into, then copy that to byobRequest.view - var buffer = new Uint8Array(byobRequest.view.byteLength); - // TODO Backpressure? - var read = this._underlyingReader.read(buffer) - .then(function (result) { - _this._readableStreamController; - if (result.done) { - _this._tryClose(); - byobRequest.respond(0); - } - else { - copyArrayBufferView(result.value, byobRequest.view); - byobRequest.respond(result.value.byteLength); - } - }); - this._setPendingRead(read); - return read; - }; - return WrappingReadableByteStreamSource; - }(AbstractWrappingReadableStreamSource)); - - function createWritableStreamWrapper(ctor) { - assert$1(isWritableStreamConstructor(ctor)); - return function (writable) { - if (writable.constructor === ctor) { - return writable; - } - var sink = createWrappingWritableSink(writable); - return new ctor(sink); - }; - } - function createWrappingWritableSink(writable) { - assert$1(isWritableStream(writable)); - assert$1(writable.locked === false); - var writer = writable.getWriter(); - return new WrappingWritableStreamSink(writer); - } - var WrappingWritableStreamSink = /** @class */ (function () { - function WrappingWritableStreamSink(underlyingWriter) { - var _this = this; - this._writableStreamController = undefined; - this._pendingWrite = undefined; - this._state = "writable" /* WRITABLE */; - this._storedError = undefined; - this._underlyingWriter = underlyingWriter; - this._errorPromise = new Promise(function (resolve, reject) { - _this._errorPromiseReject = reject; - }); - this._errorPromise.catch(noop$1); - } - WrappingWritableStreamSink.prototype.start = function (controller) { - var _this = this; - this._writableStreamController = controller; - this._underlyingWriter.closed - .then(function () { - _this._state = "closed" /* CLOSED */; - }) - .catch(function (reason) { return _this._finishErroring(reason); }); - }; - WrappingWritableStreamSink.prototype.write = function (chunk) { - var _this = this; - var writer = this._underlyingWriter; - // Detect past errors - if (writer.desiredSize === null) { - return writer.ready; - } - var writeRequest = writer.write(chunk); - // Detect future errors - writeRequest.catch(function (reason) { return _this._finishErroring(reason); }); - writer.ready.catch(function (reason) { return _this._startErroring(reason); }); - // Reject write when errored - var write = Promise.race([writeRequest, this._errorPromise]); - this._setPendingWrite(write); - return write; - }; - WrappingWritableStreamSink.prototype.close = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return this._underlyingWriter.close(); - } - return this._finishPendingWrite().then(function () { return _this.close(); }); - }; - WrappingWritableStreamSink.prototype.abort = function (reason) { - if (this._state === "errored" /* ERRORED */) { - return undefined; - } - var writer = this._underlyingWriter; - return writer.abort(reason); - }; - WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) { - var _this = this; - var pendingWrite; - var finishWrite = function () { - if (_this._pendingWrite === pendingWrite) { - _this._pendingWrite = undefined; - } - }; - this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite); - }; - WrappingWritableStreamSink.prototype._finishPendingWrite = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return Promise.resolve(); - } - var afterWrite = function () { return _this._finishPendingWrite(); }; - return this._pendingWrite.then(afterWrite, afterWrite); - }; - WrappingWritableStreamSink.prototype._startErroring = function (reason) { - var _this = this; - if (this._state === "writable" /* WRITABLE */) { - this._state = "erroring" /* ERRORING */; - this._storedError = reason; - var afterWrite = function () { return _this._finishErroring(reason); }; - if (this._pendingWrite === undefined) { - afterWrite(); - } - else { - this._finishPendingWrite().then(afterWrite, afterWrite); - } - this._writableStreamController.error(reason); - } - }; - WrappingWritableStreamSink.prototype._finishErroring = function (reason) { - if (this._state === "writable" /* WRITABLE */) { - this._startErroring(reason); - } - if (this._state === "erroring" /* ERRORING */) { - this._state = "errored" /* ERRORED */; - this._errorPromiseReject(this._storedError); - } - }; - return WrappingWritableStreamSink; - }()); + // other signatures + await mergeSignatures(sourceUser, this, 'otherCertifications', date); + // revocation signatures + await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); + }); + } - function createTransformStreamWrapper(ctor) { - assert$1(isTransformStreamConstructor(ctor)); - return function (transform) { - if (transform.constructor === ctor) { - return transform; - } - var transformer = createWrappingTransformer(transform); - return new ctor(transformer); + /** + * Revokes the user + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New user with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.certRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await user.update(this); + return user; + } } - function createWrappingTransformer(transform) { - assert$1(isTransformStream(transform)); - var readable = transform.readable, writable = transform.writable; - assert$1(readable.locked === false); - assert$1(writable.locked === false); - var reader = readable.getReader(); - var writer; - try { - writer = writable.getWriter(); - } - catch (e) { - reader.releaseLock(); // do not leak reader - throw e; - } - return new WrappingTransformStreamTransformer(reader, writer); - } - var WrappingTransformStreamTransformer = /** @class */ (function () { - function WrappingTransformStreamTransformer(reader, writer) { - var _this = this; - this._transformStreamController = undefined; - this._onRead = function (result) { - if (result.done) { - return; - } - _this._transformStreamController.enqueue(result.value); - return _this._reader.read().then(_this._onRead); - }; - this._onError = function (reason) { - _this._flushReject(reason); - _this._transformStreamController.error(reason); - _this._reader.cancel(reason).catch(noop$1); - _this._writer.abort(reason).catch(noop$1); - }; - this._onTerminate = function () { - _this._flushResolve(); - _this._transformStreamController.terminate(); - var error = new TypeError('TransformStream terminated'); - _this._writer.abort(error).catch(noop$1); - }; - this._reader = reader; - this._writer = writer; - this._flushPromise = new Promise(function (resolve, reject) { - _this._flushResolve = resolve; - _this._flushReject = reject; - }); - } - WrappingTransformStreamTransformer.prototype.start = function (controller) { - this._transformStreamController = controller; - this._reader.read() - .then(this._onRead) - .then(this._onTerminate, this._onError); - var readerClosed = this._reader.closed; - if (readerClosed) { - readerClosed - .then(this._onTerminate, this._onError); - } - }; - WrappingTransformStreamTransformer.prototype.transform = function (chunk) { - return this._writer.write(chunk); - }; - WrappingTransformStreamTransformer.prototype.flush = function () { - var _this = this; - return this._writer.close() - .then(function () { return _this._flushPromise; }); - }; - return WrappingTransformStreamTransformer; - }()); - var webStreamsAdapter = /*#__PURE__*/Object.freeze({ - __proto__: null, - createReadableStreamWrapper: createReadableStreamWrapper, - createTransformStreamWrapper: createTransformStreamWrapper, - createWrappingReadableSource: createWrappingReadableSource, - createWrappingTransformer: createWrappingTransformer, - createWrappingWritableSink: createWrappingWritableSink, - createWritableStreamWrapper: createWritableStreamWrapper - }); + /** + * @module key/Subkey + */ - var bn = createCommonjsModule(function (module) { - (function (module, exports) { - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); + /** + * Class that represents a subkey packet and the relevant signatures. + * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID + * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint + * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs + * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo + * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime + * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + */ + class Subkey { + /** + * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey + * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey + */ + constructor(subkeyPacket, mainKey) { + this.keyPacket = subkeyPacket; + this.bindingSignatures = []; + this.revocationSignatures = []; + this.mainKey = mainKey; } - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; + /** + * Transforms structured subkey data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.bindingSignatures); + return packetlist; } - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; + /** + * Shallow clone + * @return {Subkey} + */ + clone() { + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.bindingSignatures = [...this.bindingSignatures]; + subkey.revocationSignatures = [...this.revocationSignatures]; + return subkey; } - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = void('buffer').Buffer; - } catch (e) { + /** + * Checks if a binding signature of a subkey is revoked + * @param {SignaturePacket} signature - The binding signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the binding signature is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked( + primaryKey, enums.signature.subkeyRevocation, { + key: primaryKey, + bind: this.keyPacket + }, this.revocationSignatures, signature, key, date, config$1 + ); } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} if the subkey is invalid. + * @async + */ + async verify(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + // check subkey binding signatures + const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + // check binding signature is not revoked + if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { + throw new Error('Subkey is revoked'); } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } + // check for expiration time + if (isDataExpired(this.keyPacket, bindingSignature, date)) { + throw new Error('Subkey is expired'); } - return r; + return bindingSignature; } - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } + /** + * Returns the expiration time of the subkey or Infinity if key does not expire. + * Returns null if the subkey is invalid. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + let bindingSignature; + try { + bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + } catch (e) { + return null; } - return r; + const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); + const sigExpiry = bindingSignature.getExpirationTime(); + return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; + /** + * Update subkey with new components from specified subkey + * @param {Subkey} subkey - Source subkey to merge + * @param {Date} [date] - Date to verify validity of signatures + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if update failed + * @async + */ + async update(subkey, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + if (!this.hasSameFingerprintAs(subkey)) { + throw new Error('Subkey update method: fingerprints of subkeys not equal'); } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } + // key packet + if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && + subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { + this.keyPacket = subkey.keyPacket; } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; + // update missing binding signatures + const that = this; + const dataToVerify = { key: primaryKey, bind: that.keyPacket }; + await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { + for (let i = 0; i < that.bindingSignatures.length; i++) { + if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { + if (srcBindSig.created > that.bindingSignatures[i].created) { + that.bindingSignatures[i] = srcBindSig; + } + return false; + } } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); + try { + await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); + return true; + } catch (e) { + return false; } - } - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + }); + // revocation signatures + await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); + }); + } - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + /** + * Revokes the subkey + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New subkey with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { key: primaryKey, bind: this.keyPacket }; + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.subkeyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await subkey.update(this); + return subkey; + } - /* + hasSameFingerprintAs(other) { + return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + } + } - var zeros = []; - var groupSizes = []; - var groupBases = []; + ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { + Subkey.prototype[name] = + function() { + return this.keyPacket[name](); + }; + }); - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; + // A key revocation certificate can contain the following packets + const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); + const keyPacketTags = new Set([ + enums.packet.publicKey, enums.packet.privateKey, + enums.packet.publicSubkey, enums.packet.privateSubkey + ]); - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; + /** + * Abstract class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + * @borrows PublicKeyPacket#getKeyID as Key#getKeyID + * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint + * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs + * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo + * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + */ + class Key { + /** + * Transforms packetlist to structured key data + * @param {PacketList} packetlist - The packets that form a key + * @param {Set} disallowedPackets - disallowed packet tags + */ + packetListToStructure(packetlist, disallowedPackets = new Set()) { + let user; + let primaryKeyID; + let subkey; + let ignoreUntil; - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; + for (const packet of packetlist) { - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; + if (packet instanceof UnparseablePacket) { + const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); + if (isUnparseableKeyPacket && !ignoreUntil) { + // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must + // discard all non-key packets that follow, until another (sub)key packet is found. + if (mainKeyPacketTags.has(packet.tag)) { + ignoreUntil = mainKeyPacketTags; + } else { + ignoreUntil = keyPacketTags; + } } + continue; } - if (this.isZero()) { - out = '0' + out; + + const tag = packet.constructor.tag; + if (ignoreUntil) { + if (!ignoreUntil.has(tag)) continue; + ignoreUntil = null; } - while (out.length % padding !== 0) { - out = '0' + out; + if (disallowedPackets.has(tag)) { + throw new Error(`Unexpected packet type: ${tag}`); } - if (this.negative !== 0) { - out = '-' + out; + switch (tag) { + case enums.packet.publicKey: + case enums.packet.secretKey: + if (this.keyPacket) { + throw new Error('Key block contains multiple keys'); + } + this.keyPacket = packet; + primaryKeyID = this.getKeyID(); + if (!primaryKeyID) { + throw new Error('Missing Key ID'); + } + break; + case enums.packet.userID: + case enums.packet.userAttribute: + user = new User(packet, this); + this.users.push(user); + break; + case enums.packet.publicSubkey: + case enums.packet.secretSubkey: + user = null; + subkey = new Subkey(packet, this); + this.subkeys.push(subkey); + break; + case enums.packet.signature: + switch (packet.signatureType) { + case enums.signature.certGeneric: + case enums.signature.certPersona: + case enums.signature.certCasual: + case enums.signature.certPositive: + if (!user) { + util.printDebug('Dropping certification signatures without preceding user packet'); + continue; + } + if (packet.issuerKeyID.equals(primaryKeyID)) { + user.selfCertifications.push(packet); + } else { + user.otherCertifications.push(packet); + } + break; + case enums.signature.certRevocation: + if (user) { + user.revocationSignatures.push(packet); + } else { + this.directSignatures.push(packet); + } + break; + case enums.signature.key: + this.directSignatures.push(packet); + break; + case enums.signature.subkeyBinding: + if (!subkey) { + util.printDebug('Dropping subkey binding signature without preceding subkey packet'); + continue; + } + subkey.bindingSignatures.push(packet); + break; + case enums.signature.keyRevocation: + this.revocationSignatures.push(packet); + break; + case enums.signature.subkeyRevocation: + if (!subkey) { + util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); + continue; + } + subkey.revocationSignatures.push(packet); + break; + } + break; } - return out; } + } - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + /** + * Transforms structured key data to packetlist + * @returns {PacketList} The packets that form a key. + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.directSignatures); + this.users.map(user => packetlist.push(...user.toPacketList())); + this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); + return packetlist; + } - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + /** + * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. + * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. + * @returns {Promise} Clone of the key. + */ + clone(clonePrivateParams = false) { + const key = new this.constructor(this.toPacketList()); + if (clonePrivateParams) { + key.getKeys().forEach(k => { + // shallow clone the key packets + k.keyPacket = Object.create( + Object.getPrototypeOf(k.keyPacket), + Object.getOwnPropertyDescriptors(k.keyPacket) + ); + if (!k.keyPacket.isDecrypted()) return; + // deep clone the private params, which are cleared during encryption + const privateParams = {}; + Object.keys(k.keyPacket.privateParams).forEach(name => { + privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); + }); + k.keyPacket.privateParams = privateParams; + }); + } + return key; + } - res[i] = b; - } + /** + * Returns an array containing all public or private subkeys matching keyID; + * If no keyID is given, returns all subkeys. + * @param {type/keyID} [keyID] - key ID to look for + * @returns {Array} array of subkeys + */ + getSubkeys(keyID = null) { + const subkeys = this.subkeys.filter(subkey => ( + !keyID || subkey.getKeyID().equals(keyID, true) + )); + return subkeys; + } - for (; i < reqLength; i++) { - res[i] = 0; - } + /** + * Returns an array containing all public or private keys matching keyID. + * If no keyID is given, returns all keys, starting with the primary key. + * @param {type/keyid~KeyID} [keyID] - key ID to look for + * @returns {Array} array of keys + */ + getKeys(keyID = null) { + const keys = []; + if (!keyID || this.getKeyID().equals(keyID, true)) { + keys.push(this); } + return keys.concat(this.getSubkeys(keyID)); + } - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; + /** + * Returns key IDs of all keys + * @returns {Array} + */ + getKeyIDs() { + return this.getKeys().map(key => key.getKeyID()); } - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + /** + * Returns userIDs + * @returns {Array} Array of userIDs. + */ + getUserIDs() { + return this.users.map(user => { + return user.userID ? user.userID.userID : null; + }).filter(userID => userID !== null); + } - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + /** + * Returns binary encoded key + * @returns {Uint8Array} Binary key. + */ + write() { + return this.toPacketList().write(); + } + + /** + * Returns last created key or key by given keyID that is available for signing and verification + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} signing key + * @throws if no valid signing key was found + * @async + */ + async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - if ((t & 0x1) === 0) { - r++; + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature( + subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 + ); + if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + continue; + } + if (!bindingSignature.embeddedSignature) { + throw new Error('Missing embedded signature'); + } + // verify embedded signature + await getLatestValidSignature( + [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 + ); + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } catch (e) { + exception = e; + } + } } - return r; - }; - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + try { + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateSigningKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } - - return w; + throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); } - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + /** + * Returns last created key or key by given keyID that is available for encryption or decryption + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} encryption key + * @throws if no valid encryption key was found + * @async + */ + async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + // V4: by convention subkeys are preferred for encryption service + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } + } catch (e) { + exception = e; + } + } } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; + try { + // if no valid subkey for encryption, evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } + throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + } - return this; - }; + /** + * Checks if a signature on a key is revoked + * @param {SignaturePacket} signature - The signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + return isDataRevoked( + this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 + ); + } - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature. Throws if the primary key is invalid. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} If key verification failed + * @async + */ + async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + // check for key revocation signatures + if (await this.isRevoked(null, null, date, config$1)) { + throw new Error('Primary key is revoked'); } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + // check for valid, unrevoked, unexpired self signature + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + // check for expiration time in binding signatures + if (isDataExpired(primaryKey, selfCertification, date)) { + throw new Error('Primary key is expired'); } + if (primaryKey.version !== 6) { + // check for expiration time in direct signatures (for V6 keys, the above already did so) + const directSignature = await getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; + if (directSignature && isDataExpired(primaryKey, directSignature, date)) { + throw new Error('Primary key is expired'); + } } + } - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + /** + * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. + * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. + * @param {Object} [userID] - User ID to consider instead of the primary user + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(userID, config$1 = config) { + let primaryKeyExpiry; + try { + const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1); + const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); + const selfSigExpiry = selfCertification.getExpirationTime(); + const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature. + await getLatestValidSignature( + this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 + ).catch(() => {}); + if (directSignature) { + const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); + // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, + // causing a discountinous validy period for the key + primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); + } else { + primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; + } + } catch (e) { + primaryKeyExpiry = null; } - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + return util.normalizeDate(primaryKeyExpiry); + } - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + /** + * For V4 keys, returns the self-signature of the primary user. + * For V5 keys, returns the latest valid direct-key self-signature. + * This self-signature is to be used to check the key expiration, + * algorithm preferences, and so on. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} The primary self-signature + * @async + */ + async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + if (primaryKey.version === 6) { + return getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ); } + const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + return selfCertification; + } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * user: User, + * selfCertification: SignaturePacket + * }>} The primary user and the self signature + * @async + */ + async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const users = []; + let exception; + for (let i = 0; i < this.users.length; i++) { + try { + const user = this.users[i]; + if (!user.userID) { + continue; + } + if ( + (userID.name !== undefined && user.userID.name !== userID.name) || + (userID.email !== undefined && user.userID.email !== userID.email) || + (userID.comment !== undefined && user.userID.comment !== userID.comment) + ) { + throw new Error('Could not find user that matches that user ID'); + } + const dataToVerify = { userID: user.userID, key: primaryKey }; + const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); + users.push({ index: i, user, selfCertification }); + } catch (e) { + exception = e; } } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; + if (!users.length) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('Could not find primary user'); } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + await Promise.all(users.map(async function (a) { + return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); + })); + // sort by primary user flag and signature creation time + const primaryUser = users.sort(function(a, b) { + const A = a.selfCertification; + const B = b.selfCertification; + return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; + }).pop(); + const { user, selfCertification: cert } = primaryUser; + if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { + throw new Error('Primary user is revoked'); } + return primaryUser; + } - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * + * If the source key is a private key and the destination key is public, + * a private key is returned. + * @param {Key} sourceKey - Source key to merge + * @param {Date} [date] - Date to verify validity of signatures and keys + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} updated key + * @async + */ + async update(sourceKey, date = new Date(), config$1 = config) { + if (!this.hasSameFingerprintAs(sourceKey)) { + throw new Error('Primary key fingerprints must be equal to update the key'); } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (!this.isPrivate() && sourceKey.isPrivate()) { + // check for equal subkey packets + const equal = (this.subkeys.length === sourceKey.subkeys.length) && + (this.subkeys.every(destSubkey => { + return sourceKey.subkeys.some(srcSubkey => { + return destSubkey.hasSameFingerprintAs(srcSubkey); + }); + })); + if (!equal) { + throw new Error('Cannot update public key with private key if subkeys mismatch'); } - } - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; + return sourceKey.update(this, config$1); } + // from here on, either: + // - destination key is private, source key is public + // - the keys are of the same type + // hence we don't need to convert the destination key type + const updatedKey = this.clone(); + // revocation signatures + await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { + return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); + }); + // direct signatures + await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); + // update users + await Promise.all(sourceKey.users.map(async srcUser => { + // multiple users with the same ID/attribute are not explicitly disallowed by the spec + // hence we support them, just in case + const usersToUpdate = updatedKey.users.filter(dstUser => ( + (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || + (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) + )); + if (usersToUpdate.length > 0) { + await Promise.all( + usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) + ); + } else { + const newUser = srcUser.clone(); + newUser.mainKey = updatedKey; + updatedKey.users.push(newUser); + } + })); + // update subkeys + await Promise.all(sourceKey.subkeys.map(async srcSubkey => { + // multiple subkeys with same fingerprint might be preset + const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( + dstSubkey.hasSameFingerprintAs(srcSubkey) + )); + if (subkeysToUpdate.length > 0) { + await Promise.all( + subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) + ); + } else { + const newSubkey = srcSubkey.clone(); + newSubkey.mainKey = updatedKey; + updatedKey.subkeys.push(newSubkey); + } + })); - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; + return updatedKey; + } - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Armored revocation certificate. + * @async + */ + async getRevocationCertificate(date = new Date(), config$1 = config) { + const dataToVerify = { key: this.keyPacket }; + const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); + const packetlist = new PacketList(); + packetlist.push(revocationSignature); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1); + } - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param {String} revocationCertificate - armored revocation certificate + * @param {Date} [date] - Date to verify the certificate + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Revoked key. + * @async + */ + async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { + const input = await unarmor(revocationCertificate); + const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); + const revocationSignature = packetlist.findPacket(enums.packet.signature); + if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { + throw new Error('Could not find revocation signature packet'); } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { + throw new Error('Revocation signature does not match key'); } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + try { + await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); + } catch (e) { + throw util.wrapError('Could not verify revocation signature', e); } + const key = this.clone(); + key.revocationSignatures.push(revocationSignature); + return key; + } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + /** + * Signs primary user of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signPrimaryUser(privateKeys, date, userID, config$1 = config) { + const { index, user } = await this.getPrimaryUser(date, userID, config$1); + const userSign = await user.certify(privateKeys, date, config$1); + const key = this.clone(); + key.users[index] = userSign; + return key; + } + + /** + * Signs all users of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for signing, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signAllUsers(privateKeys, date = new Date(), config$1 = config) { + const key = this.clone(); + key.users = await Promise.all(this.users.map(function(user) { + return user.certify(privateKeys, date, config$1); + })); + return key; + } + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { + const primaryKey = this.keyPacket; + const { user } = await this.getPrimaryUser(date, userID, config$1); + const results = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + return results; + } - this.length = Math.max(this.length, i); + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of userID, signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { + const primaryKey = this.keyPacket; + const results = []; + await Promise.all(this.users.map(async user => { + const signatures = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - if (a !== this) { - this.negative = 1; - } + results.push(...signatures.map( + signature => ({ + userID: user.userID ? user.userID.userID : null, + userAttribute: user.userAttribute, + keyID: signature.keyID, + valid: signature.valid + })) + ); + })); + return results; + } + } - return this.strip(); - }; + ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { + Key.prototype[name] = + Subkey.prototype[name]; + }); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + /** + * Class that represents an OpenPGP Public Key + */ + class PublicKey extends Key { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.keyPacket = null; + this.revocationSignatures = []; + this.directSignatures = []; + this.users = []; + this.subkeys = []; + if (packetlist) { + this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing public-key packet'); } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; } - - return out.strip(); } - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); + /** + * Returns true if this is a private key + * @returns {false} + */ + isPrivate() { + return false; } - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + return this; } - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } + } - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; + /** + * Class that represents an OpenPGP Private key + */ + class PrivateKey extends PublicKey { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing private-key packet'); } + } - return rb; - }; + /** + * Returns true if this is a private key + * @returns {Boolean} + */ + isPrivate() { + return true; + } - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + const packetlist = new PacketList(); + const keyPackets = this.toPacketList(); + for (const keyPacket of keyPackets) { + switch (keyPacket.constructor.tag) { + case enums.packet.secretKey: { + const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); + packetlist.push(pubKeyPacket); + break; + } + case enums.packet.secretSubkey: { + const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); + packetlist.push(pubSubkeyPacket); + break; + } + default: + packetlist.push(keyPacket); + } } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + return new PublicKey(packetlist); + } - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + /** + * Returns all keys that are available for decryption, matching the keyID when given + * This is useful to retrieve keys for session key decryption + * @param {module:type/keyid~KeyID} keyID, optional + * @param {Date} date, optional + * @param {String} userID, optional + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} Array of decryption keys. + * @throws {Error} if no decryption key is found + * @async + */ + async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const keys = []; + let exception = null; + for (let i = 0; i < this.subkeys.length; i++) { + if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { + if (this.subkeys[i].keyPacket.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + continue; + } - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; + try { + const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; + const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) { + keys.push(this.subkeys[i]); } + } catch (e) { + exception = e; } } } - }; - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; + // evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) { + if (primaryKey.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + } else { + keys.push(this); + } } - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; + if (keys.length === 0) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('No decryption key packets found'); + } - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + return keys; + } - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + /** + * Returns true if the primary key or any subkey is decrypted. + * A dummy key is considered encrypted. + */ + isDecrypted() { + return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); + } - t = iws[i]; + /** + * Check whether the private and public primary key parameters correspond + * Together with verification of binding signatures, this guarantees key integrity + * In case of gnu-dummy primary key, it is enough to validate any signing subkeys + * otherwise all encryption subkeys are validated + * If only gnu-dummy keys are found, we cannot properly validate so we throw an error + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if validation was not successful and the key cannot be trusted + * @async + */ + async validate(config$1 = config) { + if (!this.isPrivate()) { + throw new Error('Cannot validate a public key'); + } - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; + let signingKeyPacket; + if (!this.keyPacket.isDummy()) { + signingKeyPacket = this.keyPacket; + } else { + /** + * It is enough to validate any signing keys + * since its binding signatures are also checked + */ + const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); + // This could again be a dummy key + if (signingKey && !signingKey.keyPacket.isDummy()) { + signingKeyPacket = signingKey.keyPacket; + } } - }; - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; + if (signingKeyPacket) { + return signingKeyPacket.validate(); + } else { + const keys = this.getKeys(); + const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); + if (allDummies) { + throw new Error('Cannot validate an all-gnu-dummy key'); + } - ws[i] = w & 0x3ffffff; + return Promise.all(keys.map(async key => key.keyPacket.validate())); + } + } - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; + /** + * Clear private key parameters + */ + clearPrivateParams() { + this.getKeys().forEach(({ keyPacket }) => { + if (keyPacket.isDecrypted()) { + keyPacket.clearPrivateParams(); } - } + }); + } - return ws; - }; + /** + * Revokes the key + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New key with revocation signature. + * @async + */ + async revoke( + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + if (!this.isPrivate()) { + throw new Error('Need private key for revoking'); + } + const dataToSign = { key: this.keyPacket }; + const key = this.clone(); + key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, undefined, config$1)); + return key; + } - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + /** + * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. + * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519. + * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. + * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format). + * Note: Curve448 and Curve25519 are not widely supported yet. + * @param {String} options.curve (optional) Elliptic curve for ECC keys + * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date (optional) Override the creation date of the key and the key signatures + * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false + * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} + * @async + */ + async addSubkey(options = {}) { + const config$1 = { ...config, ...options.config }; + if (options.passphrase) { + throw new Error('Subkey could not be encrypted here, please encrypt whole key'); } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; + if (options.rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; + const secretKeyPacket = this.keyPacket; + if (secretKeyPacket.isDummy()) { + throw new Error('Cannot add subkey to gnu-dummy primary key'); } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; + if (!secretKeyPacket.isDecrypted()) { + throw new Error('Key is not decrypted'); } + const defaultOptions = secretKeyPacket.getAlgorithmInfo(); + defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm); + defaultOptions.rsaBits = defaultOptions.bits || 4096; + defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy'; + options = sanitizeKeyOptions(options, defaultOptions); + // Every subkey for a v4 primary key MUST be a v4 subkey. + // Every subkey for a v6 primary key MUST be a v6 subkey. + // For v5 keys, since we dropped generation support, a v4 subkey is added. + // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user. + const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 }); + checkKeyRequirements(keyPacket, config$1); + const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); + const packetList = this.toPacketList(); + packetList.push(keyPacket, bindingSignature); + return new PrivateKey(packetList); + } + } - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; + function getDefaultSubkeyType(algoName) { + const algo = enums.write(enums.publicKey, algoName); + // NB: no encryption-only algos, since they cannot be in primary keys + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + return 'rsa'; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return 'ecc'; + case enums.publicKey.ed25519: + return 'curve25519'; + case enums.publicKey.ed448: + return 'curve448'; + default: + throw new Error('Unsupported algorithm'); + } + } - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2015-2016 Decentral + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } + // A Key can contain the following packets + const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket + ]); - if (carry !== 0) { - this.words[i] = carry; - this.length++; + /** + * Creates a PublicKey or PrivateKey depending on the packetlist in input + * @param {PacketList} - packets to parse + * @return {Key} parsed key + * @throws if no key packet was found + */ + function createKey(packetlist) { + for (const packet of packetlist) { + switch (packet.constructor.tag) { + case enums.packet.secretKey: + return new PrivateKey(packetlist); + case enums.packet.publicKey: + return new PublicKey(packetlist); } + } + throw new Error('No key packet found'); + } - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; + /** + * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format). + * @param {String} options.curve Elliptic curve for ECC keys + * @param {Integer} options.rsaBits Number of bits for RSA keys + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Creation date of the key and the key signatures + * @param {Object} config - Full configuration + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ + async function generate(options, config) { + options.sign = true; // primary key is always a signing key + options = sanitizeKeyOptions(options); + options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); + let promises = [generateSecretKey(options, config)]; + promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); + const packets = await Promise.all(promises); - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; + const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; + } - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + /** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param {PrivateKey} options.privateKey The private key to reformat + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Override the creation date of the key signatures + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * @param {Object} config - Full configuration + * + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ + async function reformat(options, config) { + options = sanitize(options); + const { privateKey } = options; - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } + if (!privateKey.isPrivate()) { + throw new Error('Cannot reformat a public key'); + } - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; + if (privateKey.keyPacket.isDummy()) { + throw new Error('Cannot reformat a gnu-dummy primary key'); + } - res = res.mul(q); - } - } + const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); + if (!isDecrypted) { + throw new Error('Key is not decrypted'); + } - return res; - }; + const secretKeyPacket = privateKey.keyPacket; - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } + if (!options.subkeys) { + options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { + const secretSubkeyPacket = subkey.keyPacket; + const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; + const bindingSignature = await ( + getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) + ).catch(() => ({})); + return { + sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) + }; + })); + } - if (carry) { - this.words[i] = carry; - this.length++; - } - } + const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); + if (options.subkeys.length !== secretSubkeyPackets.length) { + throw new Error('Number of subkey options does not match number of subkeys'); + } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } + options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); - for (i = 0; i < s; i++) { - this.words[i] = 0; - } + const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; - this.length += s; - } + function sanitize(options, subkeyDefaults = {}) { + options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; - return this.strip(); - }; + return options; + } + } - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; + /** + * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection + * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. + * @param {SecretKeyPacket} secretKeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPackets + * @param {Object} options + * @param {Object} config - Full configuration + * @returns {PrivateKey} + */ + async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { + // set passphrase protection + if (options.passphrase) { + await secretKeyPacket.encrypt(options.passphrase, config); + } - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + await secretSubkeyPacket.encrypt(subkeyPassphrase, config); } + })); - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } + const packetlist = new PacketList(); + packetlist.push(secretKeyPacket); - if (s === 0) ; else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } + function createPreferredAlgos(algos, preferredAlgo) { + return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + } - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; + function getKeySignatureProperties() { + const signatureProperties = {}; + signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; + const symmetricAlgorithms = createPreferredAlgos([ + // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + enums.symmetric.aes256, + enums.symmetric.aes128 + ], config.preferredSymmetricAlgorithm); + signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms; + if (config.aeadProtect) { + const aeadAlgorithms = createPreferredAlgos([ + enums.aead.gcm, + enums.aead.eax, + enums.aead.ocb + ], config.preferredAEADAlgorithm); + signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => { + return symmetricAlgorithms.map(symmetricAlgorithm => { + return [symmetricAlgorithm, aeadAlgorithm]; + }); + }); } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; + signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ + // prefer fast asm.js implementations (SHA-256) + enums.hash.sha256, + enums.hash.sha512, + enums.hash.sha3_256, + enums.hash.sha3_512 + ], config.preferredHashAlgorithm); + signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ + enums.compression.uncompressed, + enums.compression.zlib, + enums.compression.zip + ], config.preferredCompressionAlgorithm); + // integrity protection always enabled + signatureProperties.features = [0]; + signatureProperties.features[0] |= enums.features.modificationDetection; + if (config.aeadProtect) { + signatureProperties.features[0] |= enums.features.seipdv2; } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; } + return signatureProperties; + } - return this.strip(); - }; + if (secretKeyPacket.version === 6) { // add direct key signature with key prefs + const dataToSign = { + key: secretKeyPacket + }; - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; + const signatureProperties = getKeySignatureProperties(); + signatureProperties.signatureType = enums.signature.key; - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + packetlist.push(signaturePacket); + } - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; + await Promise.all(options.userIDs.map(async function(userID, index) { + const userIDPacket = UserIDPacket.fromObject(userID); + const dataToSign = { + userID: userIDPacket, + key: secretKeyPacket + }; + const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {}; + signatureProperties.signatureType = enums.signature.certPositive; + if (index === 0) { + signatureProperties.isPrimaryUserID = true; + } - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; + return { userIDPacket, signaturePacket }; + })).then(list => { + list.forEach(({ userIDPacket, signaturePacket }) => { + packetlist.push(userIDPacket); + packetlist.push(signaturePacket); + }); + }); - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyOptions = options.subkeys[index]; + const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); + return { secretSubkeyPacket, subkeySignaturePacket }; + })).then(packets => { + packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { + packetlist.push(secretSubkeyPacket); + packetlist.push(subkeySignaturePacket); + }); + }); - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; + // Add revocation signature packet for creating a revocation certificate. + // This packet should be removed before returning the key. + const dataToSign = { key: secretKeyPacket }; + packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.reasonForRevocation.noReason, + reasonForRevocationString: '' + }, options.date, undefined, undefined, undefined, config)); - // Check bit and return - var w = this.words[s]; + if (options.passphrase) { + secretKeyPacket.clearPrivateParams(); + } - return !!(w & q); - }; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + secretSubkeyPacket.clearPrivateParams(); + } + })); - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + return new PrivateKey(packetlist); + } - assert(this.negative === 0, 'imaskn works only with positive numbers'); + /** + * Reads an (optionally armored) OpenPGP key and returns a key object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ + async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (this.length <= s) { - return this; + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { + throw new Error('Armored text not of type key'); } + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]); + return createKey(firstKeyPacketList); + } - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); + /** + * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ + async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readPrivateKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.privateKey)) { + throw new Error('Armored text not of type private key'); } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; } + const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + return new PrivateKey(firstPrivateKeyList); + } + throw new Error('No secret key packet found'); + } - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + /** + * Reads an (optionally armored) OpenPGP key block and returns a list of key objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ + async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { + throw new Error('Armored text not of type key'); } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + for (let i = 0; i < keyIndex.length; i++) { + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = createKey(oneKeyList); + keys.push(newKey); + } + return keys; + } - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; + /** + * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ + async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readPrivateKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); + } + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.privateKey) { + throw new Error('Armored text not of type private key'); } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; } + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = new PrivateKey(oneKeyList); + keys.push(newKey); + } + if (keys.length === 0) { + throw new Error('No secret key packet found'); + } + return keys; + } - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return this; - }; - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + // A Message can contain the following packets + const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + AEADEncryptedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket + ]); + // A SKESK packet can contain the following packets + const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); + // A detached signature can contain the following packets + const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + /** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + class Message { + /** + * @param {PacketList} packetlist - The packets that form this message + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } - this._expand(len); + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns {Array} Array of keyID objects. + */ + getEncryptionKeyIDs() { + const keyIDs = []; + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + pkESKeyPacketlist.forEach(function(packet) { + keyIDs.push(packet.publicKeyID); + }); + return keyIDs; + } - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; + /** + * Returns the key IDs of the keys that signed the message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const msg = this.unwrapCompressed(); + // search for one pass signatures + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); + if (onePassSigList.length > 0) { + return onePassSigList.map(packet => packet.issuerKeyID); } + // if nothing found look for signature packets + const signatureList = msg.packets.filterByTag(enums.packet.signature); + return signatureList.map(packet => packet.issuerKeyID); + } - if (carry === 0) return this.strip(); + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Date} [date] - Use the given date for key verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with decrypted content. + * @async + */ + async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { + const symEncryptedPacketlist = this.packets.filterByTag( + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ); - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; + if (symEncryptedPacketlist.length === 0) { + throw new Error('No encrypted data found'); } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } + const symEncryptedPacket = symEncryptedPacketlist[0]; + const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm; - // Initialize quotient - var m = a.length - b.length; - var q; + const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1); - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; + let exception = null; + const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { + if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) { + throw new Error('Invalid session key for decryption.'); } - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; + try { + const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.decrypt(algo, data, config$1); + } catch (e) { + util.printDebugError(e); + exception = e; } + })); + // We don't await stream.cancel here because it only returns when the other copy is canceled too. + cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. + symEncryptedPacket.encrypted = null; + await decryptedPromise; + + if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { + throw exception || new Error('Decryption failed.'); } - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + const resultMsg = new Message(symEncryptedPacket.packets); + symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + return resultMsg; + } - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable) + * @param {Date} [date] - Use the given date for key verification, instead of current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * @async + */ + async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) { + let decryptedSessionKeyPackets = []; + + let exception; + if (passwords) { + const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); + if (skeskPackets.length === 0) { + throw new Error('No symmetrically encrypted session key packet found.'); } - if (q) { - q.words[j] = qj; + await Promise.all(passwords.map(async function(password, i) { + let packets; + if (i) { + packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); + } else { + packets = skeskPackets; + } + await Promise.all(packets.map(async function(skeskPacket) { + try { + await skeskPacket.decrypt(password); + decryptedSessionKeyPackets.push(skeskPacket); + } catch (err) { + util.printDebugError(err); + if (err instanceof Argon2OutOfMemoryError) { + exception = err; + } + } + })); + })); + } else if (decryptionKeys) { + const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + if (pkeskPackets.length === 0) { + throw new Error('No public key encrypted session key packet found.'); } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; + await Promise.all(pkeskPackets.map(async function(pkeskPacket) { + await Promise.all(decryptionKeys.map(async function(decryptionKey) { + let decryptionKeyPackets; + try { + // do not check key expiration to allow decryption of old messages + decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); + } catch (err) { + exception = err; + return; + } - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); + let algos = [ + enums.symmetric.aes256, // Old OpenPGP.js default fallback + enums.symmetric.aes128, // RFC4880bis fallback + enums.symmetric.tripledes, // RFC4880 fallback + enums.symmetric.cast5 // Golang OpenPGP fallback + ]; + try { + const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere. + if (selfCertification.preferredSymmetricAlgorithms) { + algos = algos.concat(selfCertification.preferredSymmetricAlgorithms); + } + } catch (e) {} - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } + await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { + if (!decryptionKeyPacket.isDecrypted()) { + throw new Error('Decryption key is not decrypted.'); + } - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); + // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. + const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal + ); - if (mode !== 'mod') { - div = res.div.neg(); - } + if (doConstantTimeDecryption) { + // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, + // either with the successfully decrypted session key, or with a randomly generated one. + // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on + // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: + // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the + // randomly generated keys of the remaining key types. + // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly + // generated session keys. + // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times + await Promise.all(( + expectedSymmetricAlgorithm ? + [expectedSymmetricAlgorithm] : + Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms) + ).map(async sessionKeyAlgorithm => { + const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); + pkeskPacketCopy.read(serialisedPKESK); + const randomSessionKey = { + sessionKeyAlgorithm, + sessionKey: mod$1.generateSessionKey(sessionKeyAlgorithm) + }; + try { + await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); + decryptedSessionKeyPackets.push(pkeskPacketCopy); + } catch (err) { + // `decrypt` can still throw some non-security-sensitive errors + util.printDebugError(err); + exception = err; + } + })); - return { - div: div, - mod: mod - }; + } else { + try { + await pkeskPacket.decrypt(decryptionKeyPacket); + const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm; + if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) { + throw new Error('A non-preferred symmetric algorithm was used.'); + } + decryptedSessionKeyPackets.push(pkeskPacket); + } catch (err) { + util.printDebugError(err); + exception = err; + } + } + })); + })); + cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. + pkeskPacket.encrypted = null; + })); + } else { + throw new Error('No key or password specified.'); } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); + if (decryptedSessionKeyPackets.length > 0) { + // Return only unique session keys + if (decryptedSessionKeyPackets.length > 1) { + const seen = new Set(); + decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { + const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); + if (seen.has(k)) { + return false; + } + seen.add(k); + return true; + }); } - return { - div: div, - mod: res.mod - }; + return decryptedSessionKeyPackets.map(packet => ({ + data: packet.sessionKey, + algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm) + })); } + throw exception || new Error('Session key decryption failed.'); + } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + /** + * Get literal data that is the body of the message + * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + */ + getLiteralData() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getBytes()) || null; + } - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + /** + * Get filename from literal data packet + * @returns {(String|null)} Filename of literal data packet as string. + */ + getFilename() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getFilename()) || null; + } - return { - div: res.div, - mod: mod - }; + /** + * Get literal data as text + * @returns {(String|null)} Literal body of the message interpreted as text. + */ + getText() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + if (literal) { + return literal.getText(); } + return null; + } - // Both numbers are positive at this point + /** + * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. + * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for + * @param {Date} [date] - Date to select algorithm preferences at + * @param {Array} [userIDs] - User IDs to select algorithm preferences for + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. + * @async + */ + static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { + const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1); + const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo); + const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined; - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } + await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() + .catch(() => null) // ignore key strength requirements + .then(maybeKey => { + if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) && + !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted + throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); + } + }) + )); - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } + const sessionKeyData = mod$1.generateSessionKey(symmetricAlgo); + return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName }; + } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - Password(s) for message encryption + * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] + * @param {Date} [date] - Override the creation date of the literal package + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + if (sessionKey) { + if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { + throw new Error('Invalid session key for encryption.'); } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; + } else if (encryptionKeys && encryptionKeys.length) { + sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); + } else if (passwords && passwords.length) { + sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); + } else { + throw new Error('No keys, passwords, or session key provided.'); } - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({ + version: aeadAlgorithmName ? 2 : 1, + aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null + }); + symEncryptedPacket.packets = this.packets; - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; + const algorithm = enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; + msg.packets.push(symEncryptedPacket); + symEncryptedPacket.packets = new PacketList(); // remove packets after encryption + return msg; + } - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param {Uint8Array} sessionKey - session key for encryption + * @param {String} algorithmName - session key algorithm + * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - For message encryption + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [date] - Override the date + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + const packetlist = new PacketList(); + const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName); + const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); - return acc; - }; + if (encryptionKeys) { + const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { + const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); + const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({ + version: aeadAlgorithm ? 6 : 3, + encryptionKeyPacket: encryptionKey.keyPacket, + anonymousRecipient: wildcard, + sessionKey, + sessionKeyAlgorithm: symmetricAlgorithm + }); - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; + await pkESKeyPacket.encrypt(encryptionKey.keyPacket); + delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption + return pkESKeyPacket; + })); + packetlist.push(...results); } + if (passwords) { + const testDecrypt = async function(keyPacket, password) { + try { + await keyPacket.decrypt(password); + return 1; + } catch (e) { + return 0; + } + }; - return this.strip(); - }; + const sum = (accumulator, currentValue) => accumulator + currentValue; - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { + const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); + symEncryptedSessionKeyPacket.sessionKey = sessionKey; + symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; + if (aeadAlgorithm) { + symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; + } + await symEncryptedSessionKeyPacket.encrypt(password, config$1); - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + if (config$1.passwordCollisionCheck) { + const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); + if (results.reduce(sum) !== 1) { + return encryptPassword(sessionKey, algorithm, password); + } + } - var x = this; - var y = p.clone(); + delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption + return symEncryptedSessionKeyPacket; + }; - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd))); + packetlist.push(...results); } - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + return new Message(packetlist); + } - var g = 0; + /** + * Sign the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to add to the message + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with signed content. + * @async + */ + async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const packetlist = new PacketList(); - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); } - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } + const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well + const onePassSignaturePackets = signaturePackets.map( + (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0)) + .reverse(); // innermost OPS refers to the first signature packet - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } + packetlist.push(...onePassSignaturePackets); + packetlist.push(literalDataPacket); + packetlist.push(...signaturePackets); - C.iushrn(1); - D.iushrn(1); - } - } + return new Message(packetlist); + } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param {module:enums.compression} algo - compression algorithm + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Message} New message with compressed content. + */ + compress(algo, config$1 = config) { + if (algo === enums.compression.uncompressed) { + return this; } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; + const compressed = new CompressedDataPacket(config$1); + compressed.algorithm = algo; + compressed.packets = this.packets; - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); + const packetList = new PacketList(); + packetList.push(compressed); - var a = this; - var b = p.clone(); + return new Message(packetList); + } - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New detached signature of message content. + * @async + */ + async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); } + return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config$1)); + } - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); + /** + * Verify message signatures + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signatures. + * @async + */ + async verify(verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + if (isArrayStream(msg.packets.stream)) { + msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + } + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); + const signatureList = msg.packets.filterByTag(enums.packet.signature); + if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { + await Promise.all(onePassSigList.map(async onePassSig => { + onePassSig.correspondingSig = new Promise((resolve, reject) => { + onePassSig.correspondingSigResolve = resolve; + onePassSig.correspondingSigReject = reject; + }); + onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); + onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); + onePassSig.hashed.catch(() => {}); + })); + msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { + const reader = getReader(readable); + const writer = getWriter(writable); + try { + for (let i = 0; i < onePassSigList.length; i++) { + const { value: signature } = await reader.read(); + onePassSigList[i].correspondingSigResolve(signature); } - - x2.iushrn(1); + await reader.readToEnd(); + await writer.ready; + await writer.close(); + } catch (e) { + onePassSigList.forEach(onePassSig => { + onePassSig.correspondingSigReject(e); + }); + await writer.abort(e); } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); + }); + return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); } + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); + } - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; + /** + * Verify detached message signature + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Signature} signature + * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); } + const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); + } - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + /** + * Unwrap compressed message + * @returns {Message} Message Content of compressed message. + */ + unwrapCompressed() { + const compressed = this.packets.filterByTag(enums.packet.compressedData); + if (compressed.length) { + return new Message(compressed[0].packets); } return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; + } - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + /** + * Append signature to unencrypted message object + * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async appendSignature(detachedSignature, config$1 = config) { + await this.packets.read( + util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, + allowedDetachedSignaturePackets, + config$1 + ); + } - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + /** + * Returns binary encoded message + * @returns {ReadableStream} Binary message. + */ + write() { + return this.packets.write(); + } - this.strip(); + /** + * Returns ASCII armored text of message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + const trailingPacket = this.packets[this.packets.length - 1]; + // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer. + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ? + trailingPacket.version !== 2 : + this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1); + } + } - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + /** + * Create signature packets for the message + * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign + * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing + * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to append + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creationtime of the signature + * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures + * @param {Boolean} [detached] - Whether to create detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} List of signature packets. + * @async + * @private + */ + async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) { + const packetlist = new PacketList(); - assert(num <= 0x3ffffff, 'Number is too big'); + // If data packet was created from Uint8Array, use binary, otherwise use text + const signatureType = literalDataPacket.text === null ? + enums.signature.binary : enums.signature.text; - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + await Promise.all(signingKeys.map(async (primaryKey, i) => { + const signingUserID = signingUserIDs[i]; + if (!primaryKey.isPrivate()) { + throw new Error('Need private key for signing'); } - if (this.negative !== 0) return -res | 0; - return res; - }; + const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1); + return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1); + })).then(signatureList => { + packetlist.push(...signatureList); + }); - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; + if (signature) { + const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + packetlist.push(...existingSigPacketlist); + } + return packetlist; + } - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; + /** + * Create object containing signer's keyID and validity of signature + * @param {SignaturePacket} signature - Signature packet + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Check signature validity with respect to the given date + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * keyID: module:type/keyid~KeyID, + * signature: Promise, + * verified: Promise + * }>} signer's keyID and validity of signature + * @async + * @private + */ + async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + let primaryKey; + let unverifiedSigningKey; - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } + for (const key of verificationKeys) { + const issuerKeys = key.getKeys(signature.issuerKeyID); + if (issuerKeys.length > 0) { + primaryKey = key; + unverifiedSigningKey = issuerKeys[0]; break; } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + } - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; + const isOnePassSignature = signature instanceof OnePassSignaturePacket; + const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + const verifiedSig = { + keyID: signature.issuerKeyID, + verified: (async () => { + if (!unverifiedSigningKey) { + throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + } - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); + await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); + const signaturePacket = await signaturePacketPromise; + if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { + throw new Error('Key is newer than the signature'); + } + // We pass the signature creation time to check whether the key was expired at the time of signing. + // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before + try { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); + } catch (e) { + // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, + // making the key invalid at the time of signing. + // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. + // Note: we do not support the edge case of a key that was reformatted and it has expired. + if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + } else { + throw e; + } + } + return true; + })(), + signature: (async () => { + const signaturePacket = await signaturePacketPromise; + const packetlist = new PacketList(); + signaturePacket && packetlist.push(signaturePacket); + return new Signature(packetlist); + })() }; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + // Mark potential promise rejections as "handled". This is needed because in + // some cases, we reject them before the user has a reasonable chance to + // handle them (e.g. `await readToEnd(result.data); await result.verified` and + // the data stream errors). + verifiedSig.signature.catch(() => {}); + verifiedSig.verified.catch(() => {}); - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + return verifiedSig; + } - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); + /** + * Create list of objects containing signer's keyID and validity of signature + * @param {Array} signatureList - Array of signature packets + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} date - Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) + * @async + * @private + */ + async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + return Promise.all(signatureList.filter(function(signature) { + return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); + }).map(async function(signature) { + return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); + })); + } - this.tmp = this._tmp(); + /** + * Reads an (optionally armored) OpenPGP message and returns a Message object + * @param {Object} options + * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed + * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New message object. + * @async + * @static + */ + async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredMessage || binaryMessage; + if (!input) { + throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { + throw new Error('readMessage: options.armoredMessage must be a string or stream'); } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; + if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { + throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } + const streamType = util.isStream(input); + if (armoredMessage) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.message) { + throw new Error('Armored text not of type message'); } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + input = data; } - inherits(P224, MPrime); + const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); + const message = new Message(packetlist); + message.fromStream = streamType; + return message; + } - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + /** + * Creates new message object from text or binary data. + * @param {Object} options + * @param {String | ReadableStream} [options.text] - The text message contents + * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents + * @param {String} [options.filename=""] - Name of the file (if any) + * @param {Date} [options.date=current date] - Date of the message, or modification date of the file + * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type + * @returns {Promise} New message object. + * @async + * @static + */ + async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { + const input = text !== undefined ? text : binary; + if (input === undefined) { + throw new Error('createMessage: must pass options object containing `text` or `binary`'); } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + if (text && !util.isString(text) && !util.isStream(text)) { + throw new Error('createMessage: options.text must be a string or stream'); + } + if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { + throw new Error('createMessage: options.binary must be a Uint8Array or stream'); } - inherits(P25519, MPrime); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; + const streamType = util.isStream(input); + const literalDataPacket = new LiteralDataPacket(date); + if (text !== undefined) { + literalDataPacket.setText(input, enums.write(enums.literal, format)); + } else { + literalDataPacket.setBytes(input, enums.write(enums.literal, format)); + } + if (filename !== undefined) { + literalDataPacket.setFilename(filename); + } + const literalDataPacketlist = new PacketList(); + literalDataPacketlist.push(literalDataPacket); + const message = new Message(literalDataPacketlist); + message.fromStream = streamType; + return message; + } - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; + // GPG4Browsers - An OpenPGP implementation in javascript + // Copyright (C) 2011 Recurity Labs GmbH + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - return prime; - }; + // A Cleartext message can contain the following packets + const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; + /** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ + class CleartextMessage { + /** + * @param {String} text - The cleartext of the signed message + * @param {Signature} signature - The detached signature or an empty signature for unsigned messages + */ + constructor(text, signature) { + // remove trailing whitespace and normalize EOL to canonical form + this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); + if (signature && !(signature instanceof Signature)) { + throw new Error('Invalid signature input'); } + this.signature = signature || new Signature(new PacketList()); } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const keyIDs = []; + const signatureList = this.signature.packets; + signatureList.forEach(function(packet) { + keyIDs.push(packet.issuerKeyID); + }); + return keyIDs; + } - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; + /** + * Sign the cleartext message + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] + * @param {Date} [date] - The creation time of the signature that should be created + * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New cleartext message with signed content. + * @async + */ + async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const literalDataPacket = new LiteralDataPacket(); + literalDataPacket.setText(this.text); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1)); + return new CleartextMessage(this.text, newSignature); + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; + /** + * Verify signatures of cleartext signed message + * @param {Array} keys - Array of keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verify(keys, date = new Date(), config$1 = config) { + const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + const literalDataPacket = new LiteralDataPacket(); + // we assume that cleartext signature is generated based on UTF8 cleartext + literalDataPacket.setText(this.text); + return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + } - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } + /** + * Get cleartext + * @returns {String} Cleartext of message. + */ + getText() { + // normalize end of line to \n + return this.text.replace(/\r\n/g, '\n'); + } - return this.m.sub(a)._forceRed(this); - }; + /** + * Returns ASCII armored text of cleartext signed message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {String | ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // emit header and checksum if one of the signatures has a version not 6 + const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6); + const hash = emitHeaderAndChecksum ? + Array.from(new Set(this.signature.packets.map( + packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase() + ))).join() : + null; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + const body = { + hash, + text: this.text, + data: this.signature.packets.write() + }; - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1); + } + } - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + /** + * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param {Object} options + * @param {String} options.cleartextMessage - Text to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New cleartext message object. + * @async + * @static + */ + async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!cleartextMessage) { + throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); + } + if (!util.isString(cleartextMessage)) { + throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + const input = await unarmor(cleartextMessage); + if (input.type !== enums.armor.signed) { + throw new Error('No cleartext signed message.'); + } + const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1); + verifyHeaders(input.headers, packetlist); + const signature = new Signature(packetlist); + return new CleartextMessage(input.text, signature); + } - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + /** + * Compare hash algorithm specified in the armor header with signatures + * @param {Array} headers - Armor headers + * @param {PacketList} packetlist - The packetlist with signature packets + * @private + */ + function verifyHeaders(headers, packetlist) { + const checkHashAlgos = function(hashAlgos) { + const check = packet => algo => packet.hashAlgorithm === algo; - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + for (let i = 0; i < packetlist.length; i++) { + if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { + return false; + } } - return res._forceRed(this); + return true; }; - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + const hashAlgos = []; + headers.forEach(header => { + const hashHeader = header.match(/^Hash: (.+)$/); // get header value + if (hashHeader) { + const parsedHashIDs = hashHeader[1] + .replace(/\s/g, '') // remove whitespace + .split(',') + .map(hashName => { + try { + return enums.write(enums.hash, hashName.toLowerCase()); + } catch (e) { + throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase()); + } + }); + hashAlgos.push(...parsedHashIDs); + } else { + throw new Error('Only "Hash" header allowed in cleartext signed message'); } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + }); - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { + throw new Error('Hash algorithm mismatch in armor header and signature'); + } + } - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; + /** + * Creates a new CleartextMessage object from text + * @param {Object} options + * @param {String} options.text + * @static + * @async + */ + async function createCleartextMessage({ text, ...rest }) { + if (!text) { + throw new Error('createCleartextMessage: must pass options object containing `text`'); + } + if (!util.isString(text)) { + throw new Error('createCleartextMessage: options.text must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + return new CleartextMessage(text); + } - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + // OpenPGP.js - An OpenPGP implementation in javascript + // Copyright (C) 2016 Tankred Hase + // + // This library is free software; you can redistribute it and/or + // modify it under the terms of the GNU Lesser General Public + // License as published by the Free Software Foundation; either + // version 3.0 of the License, or (at your option) any later version. + // + // This library is distributed in the hope that it will be useful, + // but WITHOUT ANY WARRANTY; without even the implied warranty of + // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + // Lesser General Public License for more details. + // + // You should have received a copy of the GNU Lesser General Public + // License along with this library; if not, write to the Free Software + // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } + ////////////////////// + // // + // Key handling // + // // + ////////////////////// - return r; - }; - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; + /** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. + * @param {Object} options + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys). + * Note: Curve448 and Curve25519 (new format) are not widely supported yet. + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys + * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys: + * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 + * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` + * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ + async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + if (!type && !curve) { + type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them) + curve = 'curve25519Legacy'; // unused with type != 'ecc' + } else { + type = type || 'ecc'; + curve = curve || 'curve25519Legacy'; + } + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); + if (userIDs.length === 0 && !config$1.v6Keys) { + throw new Error('UserIDs are required for V4 keys'); + } + if (type === 'rsa' && rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + } - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } + const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } + try { + const { key, revocationCertificate } = await generate(options, config$1); + key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } + return { + privateKey: formatObject(key, format, config$1), + publicKey: formatObject(key.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error generating keypair', err); + } + } - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } + /** + * Reformats signature packets for a key and rewraps key object. + * @param {Object} options + * @param {PrivateKey} options.privateKey - Private key to reformat + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended + * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ + async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) { + throw new Error('UserIDs are required for V4 keys'); + } + const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } + try { + const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); - return res; - }; + return { + privateKey: formatObject(reformattedKey, format, config$1), + publicKey: formatObject(reformattedKey.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error reformatting keypair', err); + } + } - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); + /** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. + * @param {Object} options + * @param {Key} options.key - Public or private key to revoke + * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with + * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation + * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation + * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The revoked key in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or + * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise + * @async + * @static + */ + async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - return r === num ? r.clone() : r; - }; + try { + const revokedKey = revocationCertificate ? + await key.applyRevocationCertificate(revocationCertificate, date, config$1) : + await key.revoke(reasonForRevocation, date, config$1); - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; + return revokedKey.isPrivate() ? { + privateKey: formatObject(revokedKey, format, config$1), + publicKey: formatObject(revokedKey.toPublic(), format, config$1) + } : { + privateKey: null, + publicKey: formatObject(revokedKey, format, config$1) + }; + } catch (err) { + throw util.wrapError('Error revoking key', err); + } + } - // - // Montgomery method engine - // + /** + * Unlock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to decrypt + * @param {String|Array} options.passphrase - The user's passphrase(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The unlocked key object. + * @async + */ + async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - BN.mont = function mont (num) { - return new Mont(num); - }; + if (!privateKey.isPrivate()) { + throw new Error('Cannot decrypt a public key'); + } + const clonedPrivateKey = privateKey.clone(true); + const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; - function Mont (m) { - Red.call(this, m); + try { + await Promise.all(clonedPrivateKey.getKeys().map(key => ( + // try to decrypt each key with any of the given passphrases + util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) + ))); - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + await clonedPrivateKey.validate(config$1); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error decrypting private key', err); + } + } - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + /** + * Lock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to encrypt + * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The locked key object. + * @async + */ + async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); + if (!privateKey.isPrivate()) { + throw new Error('Cannot encrypt a public key'); } - inherits(Mont, Red); + const clonedPrivateKey = privateKey.clone(true); - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + const keys = clonedPrivateKey.getKeys(); + const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); + if (passphrases.length !== keys.length) { + throw new Error('Invalid number of passphrases given for key encryption'); + } - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + try { + await Promise.all(keys.map(async (key, i) => { + const { keyPacket } = key; + await keyPacket.encrypt(passphrases[i], config$1); + keyPacket.clearPrivateParams(); + })); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error encrypting private key', err); + } + } - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + /////////////////////////////////////////// + // // + // Message encryption and decryption // + // // + /////////////////////////////////////////// - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - return res._forceRed(this); - }; + /** + * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` + * must be specified. If signing keys are specified, those will be used to sign the message. + * @param {Object} options + * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message + * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed + * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message + * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Signature} [options.signature] - A detached signature to add to the encrypted message + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` + * @param {Date} [options.date=current date] - Override the creation date of the message signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ + async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords); + signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations); + if (rest.detached) { + throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); + } + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + if (!signingKeys) { + signingKeys = []; + } - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + try { + if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified + message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1); } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; - })(module, commonjsGlobal); - }); - - var bn$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': bn, - __moduleExports: bn - }); + message = message.compress( + await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), + config$1 + ); + message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + if (format === 'object') return message; + // serialize data + const armor = format === 'armored'; + const data = armor ? message.armor(config$1) : message.write(); + return await convertStream(data); + } catch (err) { + throw util.wrapError('Error encrypting message', err); + } + } /** - * @fileoverview - * BigInteger implementation of basic operations - * Wrapper of bn.js library (wwww.github.com/indutny/bn.js) - * @module biginteger/bn - * @private + * Decrypts a message with the user's private key, a session key or a password. + * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). + * @param {Object} options + * @param {Message} options.message - The message object with the encrypted data + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key + * @param {String|String[]} [options.passwords] - Passwords to decrypt the message + * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } + * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing decrypted and verified message in the form: + * + * { + * data: MaybeStream, (if format was 'utf8', the default) + * data: MaybeStream, (if format was 'binary') + * filename: String, + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static */ + async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * @private - */ - class BigInteger$1 { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); + try { + const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); + if (!verificationKeys) { + verificationKeys = []; } - this.value = new bn(n); + const result = {}; + result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); + result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); + result.filename = decrypted.getFilename(); + linkStreams(result, message); + if (expectSigned) { + if (verificationKeys.length === 0) { + throw new Error('Verification keys are required to verify message signatures'); + } + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error decrypting message', err); } + } - clone() { - const clone = new BigInteger$1(null); - this.value.copy(clone.value); - return clone; - } - /** - * BigInteger increment in place - */ - iinc() { - this.value.iadd(new bn(1)); - return this; - } + ////////////////////////////////////////// + // // + // Message signing and verification // + // // + ////////////////////////////////////////// - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - /** - * BigInteger decrement in place - */ - idec() { - this.value.isub(new bn(1)); - return this; - } + /** + * Signs a message. + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed + * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext + * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [options.date=current date] - Override the creation date of the signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ + async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); checkOutputMessageFormat(format); + signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations); - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); + if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value.iadd(x.value); - return this; + if (!signingKeys || signingKeys.length === 0) { + throw new Error('No signing keys provided'); } - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + try { + let signature; + if (detached) { + signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } else { + signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } + if (format === 'object') return signature; - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value.isub(x.value); - return this; + const armor = format === 'armored'; + signature = armor ? signature.armor(config$1) : signature.write(); + if (detached) { + signature = transformPair(message.packets.write(), async (readable, writable) => { + await Promise.all([ + pipe(signature, writable), + readToEnd(readable).catch(() => {}) + ]); + }); + } + return await convertStream(signature); + } catch (err) { + throw util.wrapError('Error signing message', err); } + } - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } + /** + * Verifies signatures of cleartext signed message + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures + * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing verified message in the form: + * + * { + * data: MaybeStream, (if `message` was a CleartextMessage) + * data: MaybeStream, (if `message` was a Message) + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static + */ + async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value.imul(x.value); - return this; - } + if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); + if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); + try { + const result = {}; + if (signature) { + result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); + } else { + result.signatures = await message.verify(verificationKeys, date, config$1); + } + result.data = format === 'binary' ? message.getLiteralData() : message.getText(); + if (message.fromStream && !signature) linkStreams(result, message); + if (expectSigned) { + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error verifying signed message', err); } + } - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value = this.value.umod(m.value); - return this; - } - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } + /////////////////////////////////////////////// + // // + // Session key encryption and decryption // + // // + /////////////////////////////////////////////// - /** - * Compute modular exponentiation - * Much faster than this.exp(e).mod(n) - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - // We use either Montgomery or normal reduction context - // Montgomery requires coprime n and R (montogmery multiplier) - // bn.js picks R as power of 2, so n must be odd - const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value); - const x = this.clone(); - x.value = x.value.toRed(nred).redPow(e.value).fromRed(); - return x; - } + /** + * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. + * @param {Object} options + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} + * @param {Date} [options.date=current date] - Date to select algorithm preferences at + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. + * @async + * @static + */ + async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - // invm returns a wrong result if the inverse does not exist - if (!this.gcd(n).isOne()) { - throw new Error('Inverse does not exist'); - } - return new BigInteger$1(this.value.invm(n.value)); + try { + const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error generating session key', err); } + } - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} n - Operand - * @returns {BigInteger} gcd - */ - gcd(n) { - return new BigInteger$1(this.value.gcd(n.value)); - } + /** + * Encrypt a symmetric session key with public keys, passwords, or both at once. + * At least one of `encryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) + * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key + * @param {String|String[]} [options.passwords] - Passwords for the message + * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [options.date=current date] - Override the date + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ + async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value.ishln(x.value.toNumber()); - return this; + if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { + throw new Error('No encryption keys or passwords provided.'); } - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); + try { + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + return formatObject(message, format, config$1); + } catch (err) { + throw util.wrapError('Error encrypting session key', err); } + } - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value.ishrn(x.value.toNumber()); - return this; - } + /** + * Decrypt symmetric session keys using private keys or passwords (not both). + * One of `decryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Message} options.message - A message object containing the encrypted session key packets + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data + * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key + * @param {Date} [options.date] - Date to use for key verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: + * { data:Uint8Array, algorithm:String } + * @throws if no session key could be found or decrypted + * @async + * @static + */ + async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); + try { + const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error decrypting session keys', err); } + } - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value.eq(x.value); - } - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value.lt(x.value); - } + ////////////////////////// + // // + // Helper functions // + // // + ////////////////////////// - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value.lte(x.value); - } - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value.gt(x.value); + /** + * Input validation + * @private + */ + function checkString(data, name) { + if (!util.isString(data)) { + throw new Error('Parameter [' + (name) + '] must be of type String'); } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value.gte(x.value); + } + function checkBinary(data, name) { + if (!util.isUint8Array(data)) { + throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array'); } - - isZero() { - return this.value.isZero(); + } + function checkMessage(message) { + if (!(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message'); } - - isOne() { - return this.value.eq(new bn(1)); + } + function checkCleartextOrMessage(message) { + if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); } - - isNegative() { - return this.value.isNeg(); + } + function checkOutputMessageFormat(format) { + if (format !== 'armored' && format !== 'binary' && format !== 'object') { + throw new Error(`Unsupported format ${format}`); } - - isEven() { - return this.value.isEven(); + } + const defaultConfigPropsCount = Object.keys(config).length; + function checkConfig(config$1) { + const inputConfigProps = Object.keys(config$1); + if (inputConfigProps.length !== defaultConfigPropsCount) { + for (const inputProp of inputConfigProps) { + if (config[inputProp] === undefined) { + throw new Error(`Unknown config property: ${inputProp}`); + } + } } + } - abs() { - const res = this.clone(); - res.value = res.value.abs(); - return res; + /** + * Normalize parameter to an array if it is not undefined. + * @param {Object} param - the parameter to be normalized + * @returns {Array|undefined} The resulting array or undefined. + * @private + */ + function toArray(param) { + if (param && !util.isArray(param)) { + param = [param]; } + return param; + } - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); + /** + * Convert data to or from Stream + * @param {Object} data - the data to convert + * @returns {Promise} The data in the respective format. + * @async + * @private + */ + async function convertStream(data) { + const streamType = util.isStream(data); + if (streamType === 'array') { + return readToEnd(data); } + return data; + } - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - return this.value.toNumber(); - } + /** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param {Object} result - the data to convert + * @param {Message} message - message object + * @returns {Object} + * @private + */ + function linkStreams(result, message) { + result.data = transformPair(message.packets.stream, async (readable, writable) => { + await pipe(result.data, writable, { + preventClose: true + }); + const writer = getWriter(writable); + try { + // Forward errors in the message stream to result.data. + await readToEnd(readable, _ => _); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + }); + } - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - return this.value.testn(i) ? 1 : 0; + /** + * Convert the object to the given format + * @param {Key|Message} object + * @param {'armored'|'binary'|'object'} format + * @param {Object} config - Full configuration + * @returns {String|Uint8Array|Object} + */ + function formatObject(object, format, config) { + switch (format) { + case 'object': + return object; + case 'armored': + return object.armor(config); + case 'binary': + return object.write(); + default: + throw new Error(`Unsupported format ${format}`); } + } - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - return this.value.bitLength(); - } + function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); + } + // copied from utils + function isBytes$1(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); + } + function bytes(b, ...lengths) { + if (!isBytes$1(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); + } + function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); + } + function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); + } + function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } + } + + const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; + + /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. + // node.js versions earlier than v19 don't declare it in global scope. + // For node.js, package.json#exports field mapping rewrites import + // from `crypto` to `cryptoNode`, which imports native module. + // Makes the utils un-importable in browsers without a bundler. + // Once node.js 18 is deprecated (2025-04-30), we can just drop the import. + const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + // Cast array to view + const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + // The rotate right (circular right shift) operation for uint32 + const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); + // The rotate left (circular left shift) operation for uint32 + const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); + const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; + // The byte swap operation for uint32 + const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); + // In place byte swap for Uint32Array + function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + } + /** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ + function utf8ToBytes$1(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 + } + /** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ + function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes$1(data); + bytes(data); + return data; + } + /** + * Copies several Uint8Arrays into one. + */ + function concatBytes$1(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; + } + // For runtime check if class implements interface + class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } + } + function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; + } + function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; + } + /** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ + function randomBytes(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto$1 && typeof crypto$1.randomBytes === 'function') { + return crypto$1.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); + } - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - return this.value.byteLength(); - } + /** + * Polyfill for Safari 14 + */ + function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); + } + /** + * Choice: a ? b : c + */ + const Chi = (a, b, c) => (a & b) ^ (~a & c); + /** + * Majority function, true if any two inputs is true + */ + const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); + /** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ + class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + } + + // SHA2-256 need to try 2^128 hashes to execute birthday attack. + // BTC network is doing 2^67 hashes/sec as per early 2023. + // Round constants: + // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) + // prettier-ignore + const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]); + // Initial state: + // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 + // prettier-ignore + const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]); + // Temporary buffer, not used to store anything between runs + // Named this way because it matches specification. + const SHA256_W = /* @__PURE__ */ new Uint32Array(64); + class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + } + // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf + class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } + } + /** + * SHA2-256 hash function + * @param message - data that would be hashed + */ + const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + /** + * SHA2-224 hash function + */ + const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - return this.value.toArrayLike(Uint8Array, endian, length); - } + // HMAC (RFC 2104) + class HMAC extends Hash { + constructor(hash$1, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash$1.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + } + /** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + * @example + * import { hmac } from '@noble/hashes/hmac'; + * import { sha256 } from '@noble/hashes/sha2'; + * const mac1 = hmac(sha256, 'key', 'message'); + */ + const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); + hmac.create = (hash, key) => new HMAC(hash, key); + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // 100 lines of code in the file are duplicated from noble-hashes (utils). + // This is OK: `abstract` directory does not use noble-hashes. + // User may opt-in into using different hashing library. This way, noble-hashes + // won't be included into their bundle. + const _0n$6 = /* @__PURE__ */ BigInt(0); + const _1n$8 = /* @__PURE__ */ BigInt(1); + const _2n$5 = /* @__PURE__ */ BigInt(2); + function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); + } + function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); + } + function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); + } + // Array where index 0xf0 (240) is mapped to string 'f0' + const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); + /** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ + function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; + } + function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + } + function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); + } + // We use optimized technique to convert hex string to byte array + const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; + function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; + } + /** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ + function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; + } + // BE: Big Endian, LE: Little Endian + function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); + } + function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); + } + function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); + } + function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); + } + // Unpadded, rarely used + function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); + } + /** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ + function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; + } + /** + * Copies several Uint8Arrays into one. + */ + function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; + } + // Compares 2 u8a-s in kinda constant time + function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; + } + /** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ + function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 + } + // Is positive bigint + const isPosBig = (n) => typeof n === 'bigint' && _0n$6 <= n; + function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; + } + /** + * Asserts min <= n < max. NOTE: It's < max and not <= max. + * @example + * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) + */ + function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`); + } + // Bit operations + /** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ + function bitLen(n) { + let len; + for (len = 0; n > _0n$6; n >>= _1n$8, len += 1) + ; + return len; + } + /** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ + function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n$8; + } + /** + * Sets single bit at position. + */ + function bitSet(n, pos, value) { + return n | ((value ? _1n$8 : _0n$6) << BigInt(pos)); + } + /** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ + const bitMask = (n) => (_2n$5 << BigInt(n - 1)) - _1n$8; + // DRBG + const u8n = (data) => new Uint8Array(data); // creates Uint8Array + const u8fr = (arr) => Uint8Array.from(arr); // another shortcut + /** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ + function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; + } + // Validating curves and fields + const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), + }; + // type Record = { [P in K]: T; } + function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; + } + // validate type tests + // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; + // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! + // // Should fail type-check + // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); + // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); + // const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); + // const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); + /** + * throws not implemented error + */ + const notImplemented = () => { + throw new Error('not implemented'); + }; + /** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ + function memoized(fn) { + const map = new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; } - var bn_interface = /*#__PURE__*/Object.freeze({ + var ut = /*#__PURE__*/Object.freeze({ __proto__: null, - 'default': BigInteger$1 + aInRange: aInRange, + abool: abool, + abytes: abytes, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + inRange: inRange, + isBytes: isBytes, + memoized: memoized, + notImplemented: notImplemented, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject }); - var utils_1 = createCommonjsModule(function (module, exports) { - - var utils = exports; - - function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // Utilities for modular arithmetics and finite fields + // prettier-ignore + const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$4 = BigInt(2), _3n$2 = BigInt(3); + // prettier-ignore + const _4n = BigInt(4), _5n = BigInt(5), _8n$1 = BigInt(8); + // prettier-ignore + BigInt(9); BigInt(16); + // Calculates a modulo b + function mod(a, b) { + const result = a % b; + return result >= _0n$5 ? result : b + result; + } + /** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ + // TODO: use field version && remove + function pow(num, power, modulo) { + if (modulo <= _0n$5 || power < _0n$5) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n$7) + return _0n$5; + let res = _1n$7; + while (power > _0n$5) { + if (power & _1n$7) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n$7; + } return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); + } + // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) + function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$5) { + res *= res; + res %= modulo; } - } - return res; + return res; } - utils.toArray = toArray; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; + // Inverses number over modulo + function invert(number, modulo) { + if (number === _0n$5 || modulo <= _0n$5) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n$5, u = _1n$7; + while (a !== _0n$5) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + // prettier-ignore + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$7) + throw new Error('invert: does not exist'); + return mod(x, modulo); + } + /** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ + function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n$7) / _2n$4; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n$7, S = 0; Q % _2n$4 === _0n$5; Q /= _2n$4, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n$4; Z < P && pow(Z, legendreC, P) !== P - _1n$7; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n$7) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n$7) / _2n$4; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n$7 << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; + } + function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n$2) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n$7) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n$1 === _5n) { + const c1 = (P - _5n) / _8n$1; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$4); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$4), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); + } + // prettier-ignore + const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' + ]; + function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); + } + // Generic field functions + /** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ + function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n$5) + throw new Error('Expected power > 0'); + if (power === _0n$5) + return f.ONE; + if (power === _1n$7) + return num; + let p = f.ONE; + let d = num; + while (power > _0n$5) { + if (power & _1n$7) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$7; + } + return p; + } + /** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ + function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; + } + // CURVE.n lengths + function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; + } + /** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * NOTE: operations don't check 'isValid' for all elements for performance reasons, + * it is caller responsibility to check this. + * This is low-level code, please make sure you know what you doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ + function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$5) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$5, + ONE: _1n$7, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$5 <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n$5, + isOdd: (num) => (num & _1n$7) === _1n$7, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); + } + /** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ + function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); + } + /** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ + function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); + } + /** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ + function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n$7) + _1n$7; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); + } + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // Abelian group utilities + const _0n$4 = BigInt(0); + const _1n$6 = BigInt(1); + // Since points in different groups cannot be equal (different object constructor), + // we can have single place to store precomputes + const pointPrecomputes = new WeakMap(); + const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) + // Elliptic curve multiplication of Point by scalar. Fragile. + // Scalars should always be less than curve order: this should be checked inside of a curve itself. + // Creates precomputation tables for fast multiplication: + // - private scalar is split by fixed size windows of W bits + // - every window point is collected from window's table & added to accumulator + // - since windows are different, same point inside tables won't be accessed more than once per calc + // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) + // - +1 window is neccessary for wNAF + // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication + // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow + // windows to be in different memory locations + function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$4) { + if (n & _1n$6) + p = p.add(d); + d = d.double(); + n >>= _1n$6; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$6; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; + } + /** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c Curve Point constructor + * @param field field over CURVE.N - important that it's not over CURVE.P + * @param points array of L curve points + * @param scalars array of L scalars (aka private keys / bigints) + */ + function pippenger(c, field, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.ZERO; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; + } + function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); } - utils.zero2 = zero2; - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // Short Weierstrass curve. The formula is: y² = x³ + ax + b + function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); + } + function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); + } + const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; + /** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html + */ + const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 128) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 127; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n$3) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected assertion'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 128)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + abytes(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + return tlv.encode(0x30, seq); + }, + }; + // Be friendly to bad ECMAScript parsers by not using bigint literals + // prettier-ignore + const _0n$3 = BigInt(0), _1n$5 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); + function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return inRange(num, _1n$5, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (isBytes(key)) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, N); // disabled by default, enabled for BLS + aInRange('private key', num, _1n$5, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // Memoized toAffine / validity check. They are heavy. Points are immutable. + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p) => { + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n$1); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + aInRange('scalar', sc, _0n$3, CURVE.n); + const I = Point.ZERO; + if (sc === _0n$3) + return I; + if (sc === _1n$5) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$3 || k2 > _0n$3) { + if (k1 & _1n$5) + k1p = k1p.add(d); + if (k2 & _1n$5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$5; + k2 >>= _1n$5; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange('scalar', scalar, _1n$5, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n$3 || a === _1n$5 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$5) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$5) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; } - utils.toHex = toHex; - - utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; - }; - }); - - var utils_1$1 = createCommonjsModule(function (module, exports) { - - var utils = exports; - - - - - utils.assert = minimalisticAssert; - utils.toArray = utils_1.toArray; - utils.zero2 = utils_1.zero2; - utils.toHex = utils_1.toHex; - utils.encode = utils_1.encode; - - // Represent num in a w-NAF form - function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; + function validateOpts$2(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); + } + /** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ + function weierstrass(curveDef) { + const CURVE = validateOpts$2(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n$5, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n$5) === _1n$5; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$5; + return number > HALF; } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; - } - utils.getNAF = getNAF; - - // Represent k1, k2 in a Joint Sparse Form - function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + // slice bytes num + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange('r', this.r, _1n$5, CURVE_ORDER); // r in [1..N] + aInRange('s', this.s, _1n$5, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$3, ORDER_MASK); + // works with order, can have different size than numToField! + return numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n$3) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n$3) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$5); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; } - utils.getJSF = getJSF; - function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // connects noble-curves to noble-hashes + function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), + randomBytes, + }; + } + function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); + } + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // NIST secp256r1 aka p256 + // https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 + const Fp$7 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); + const CURVE_A$4 = Fp$7.create(BigInt('-3')); + const CURVE_B$4 = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); + // prettier-ignore + const p256 = createCurve({ + a: CURVE_A$4, // Equation params: a, b + b: CURVE_B$4, + Fp: Fp$7, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, + }, sha256); + + const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); + const _32n = /* @__PURE__ */ BigInt(32); + // We are not using BigUint64Array, because they are extremely slow as per 2022 + function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; + } + function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; + } + const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); + // for Shift in [0, 32) + const shrSH = (h, _l, s) => h >>> s; + const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + // Right rotate for Shift in [1, 32) + const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); + const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + // Right rotate for Shift in (32, 64), NOTE: 32 is special case. + const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); + const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); + // Right rotate for shift===32 (just swaps l&h) + const rotr32H = (_h, l) => l; + const rotr32L = (h, _l) => h; + // Left rotate for Shift in [1, 32) + const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); + const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); + // Left rotate for Shift in (32, 64), NOTE: 32 is special case. + const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); + const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); + // JS uses 32-bit signed integers for bitwise operations which means we cannot + // simple take carry out of low bit sum by shift, we need to use division. + function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; + } + // Addition with more than 2 elements + const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); + const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; + const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); + const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; + const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); + const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + // prettier-ignore + const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, + }; + + // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): + // prettier-ignore + const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' + ].map(n => BigInt(n))))(); + // Temporary buffer, not used to store anything between runs + const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); + const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); + class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + } + class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } + } + const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); + const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // NIST secp384r1 aka p384 + // https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 + // Field over which we'll do calculations. + // prettier-ignore + const P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); + const Fp$6 = Field(P$1); + const CURVE_A$3 = Fp$6.create(BigInt('-3')); + // prettier-ignore + const CURVE_B$3 = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); + // prettier-ignore + const p384 = createCurve({ + a: CURVE_A$3, // Equation params: a, b + b: CURVE_B$3, + Fp: Fp$6, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, + }, sha384); + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // NIST secp521r1 aka p521 + // Note that it's 521, which differs from 512 of its hash function. + // https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 + // Field over which we'll do calculations. + // prettier-ignore + const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + const Fp$5 = Field(P); + const CURVE = { + a: Fp$5.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp: Fp$5, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), + }; + // prettier-ignore + const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp: Fp$5, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b + }, sha512); + + // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. + // It's called a sponge function. + // Various per round constants calculations + const SHA3_PI = []; + const SHA3_ROTL = []; + const _SHA3_IOTA = []; + const _0n$2 = /* @__PURE__ */ BigInt(0); + const _1n$4 = /* @__PURE__ */ BigInt(1); + const _2n$3 = /* @__PURE__ */ BigInt(2); + const _7n = /* @__PURE__ */ BigInt(7); + const _256n = /* @__PURE__ */ BigInt(256); + const _0x71n = /* @__PURE__ */ BigInt(0x71); + for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n$2; + for (let j = 0; j < 7; j++) { + R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n$3) + t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4); + } + _SHA3_IOTA.push(t); + } + const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + // Left rotation (without 0, 32, 64) + const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); + const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + // Same as keccakf1600, but allows to skip some rounds + function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); + } + class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } + } + const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + /** + * SHA3-256 hash function + * @param message - that would be hashed + */ + const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); + const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); + const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); + const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² + // Be friendly to bad ECMAScript parsers by not using bigint literals + // prettier-ignore + const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8); + // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: + const VERIFY_DEFAULT = { zip215: true }; + function validateOpts$1(curve) { + const opts = validateBasic(curve); + validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); + } + /** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ + function twistedEdwards(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n$1 }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + aInRange('coordinate ' + title, n, _0n$1, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n$1, y: _1n$3 }; + if (zz !== _1n$3) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n$3, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n$2 * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n$1) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n$2 * T2); + const D = modP(T1 * _2n$2 * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n$1) + return I; + if (this.equals(I) || n === _1n$3) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n$3) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('pointHex.y', y, _0n$1, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n$3); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n$3) === _1n$3; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n$1 && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n$1, _1n$3, _1n$3, _0n$1); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l + const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; } - utils.cachedProperty = cachedProperty; - function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + const _0n = BigInt(0); + const _1n$2 = BigInt(1); + function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); + } + // NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) + // Uses only one coordinate instead of two + function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n$2; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n$2; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n$2; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; } - utils.parseBytes = parseBytes; - function intFromLE(bytes) { - return new bn(bytes, 'hex', 'le'); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + /** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ + const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); + const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); + const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); + // prettier-ignore + const _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11); + // prettier-ignore + const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); + // powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. + // Used for efficient square root calculation. + // ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] + function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n$1, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n$1, P) * b2) % P; + const b223 = (pow2(b222, _1n$1, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; + } + function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; } - utils.intFromLE = intFromLE; + // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. + // Uses algo from RFC8032 5.1.3. + function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; + } + const Fp$4 = Field(ed448P, 456, true); + const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp: Fp$4, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes$1(utf8ToBytes$1('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, + }; + const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); + // NOTE: there is no ed448ctx, since ed448 supports ctx by default + /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); + const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, + }))(); + // TODO: add edwardsToMontgomeryPriv, similar to ed25519 version + // Hash To Curve Elligator2 Map + (Fp$4.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic + BigInt(156326); + // 1-d + BigInt('39082'); + // 1-2d + BigInt('78163'); + // √(-d) + BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); + // 1 / √(-d) + BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); + BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); + const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); + const _1n = BigInt(1); + const _2n = BigInt(2); + const divNearest = (a, b) => (a + b / _2n) / b; + /** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ + function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp$3.eql(Fp$3.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; + } + const Fp$3 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + /** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ + const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$3, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, sha256); + // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki + BigInt(0); + secp256k1.ProjectivePoint; + + // brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4 + // eslint-disable-next-line new-cap + const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377')); + const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9')); + const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'); + // prettier-ignore + const brainpoolP256r1 = createCurve({ + a: CURVE_A$2, // Equation params: a, b + b: CURVE_B$2, + Fp: Fp$2, + // Curve order (q), total count of valid points in the field + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + // Base (generator) point (x, y) + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), + lowS: false + }, sha256); + + // brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6 + // eslint-disable-next-line new-cap + const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53')); + const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826')); + const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'); + // prettier-ignore + const brainpoolP384r1 = createCurve({ + a: CURVE_A$1, // Equation params: a, b + b: CURVE_B$1, + Fp: Fp$1, + // Curve order (q), total count of valid points in the field + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + // Base (generator) point (x, y) + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), + lowS: false + }, sha384); + + // brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7 + // eslint-disable-next-line new-cap + const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3')); + const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca')); + const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'); + // prettier-ignore + const brainpoolP512r1 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, + // Curve order (q), total count of valid points in the field + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + // Base (generator) point (x, y) + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), + lowS: false + }, sha512); + + /** + * This file is needed to dynamic import the noble-curves. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + + const nobleCurves = new Map(Object.entries({ + nistP256: p256, + nistP384: p384, + nistP521: p521, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, + secp256k1, + x448, + ed448 + })); + + var noble_curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleCurves: nobleCurves }); - var r$1; - - var brorand = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); - }; - - function Rand(rand) { - this.rand = rand; - } - var Rand_1 = Rand; + //Paul Tero, July 2001 + //http://www.tero.co.uk/des/ + // + //Optimised for performance with large blocks by Michael Hayworth, November 2001 + //http://www.netdealing.com + // + // Modified by Recurity Labs GmbH - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + //THIS SOFTWARE IS PROVIDED "AS IS" AND + //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + //ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + //OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + //OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + //SUCH DAMAGE. - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + //des + //this takes the key, the message, and whether to encrypt or decrypt - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; - }; + function des(keys, message, encrypt, mode, iv, padding) { + //declaring this locally speeds things up a bit + const spfunction1 = [ + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, + 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, + 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, + 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ]; + const spfunction2 = [ + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, + -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, + -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, + -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, + 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, + -0x7fef7fe0, 0x108000 + ]; + const spfunction3 = [ + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, + 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, + 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, + 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ]; + const spfunction4 = [ + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, + 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, + 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ]; + const spfunction5 = [ + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, + 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, + 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, + 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, + 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, + 0x40080000, 0x2080100, 0x40000100 + ]; + const spfunction6 = [ + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, + 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, + 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, + 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ]; + const spfunction7 = [ + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, + 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, + 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, + 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ]; + const spfunction8 = [ + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, + 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, + 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, + 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ]; - if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; + //create the 16 or 48 subkeys we will need + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let endloop; + let loopinc; + let len = message.length; - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; + //set up the loops for single and triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des + if (iterations === 3) { + looping = encrypt ? [0, 32, 2] : [30, -2, -2]; + } else { + looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; } - } else { - // Node.js or Web worker with no crypto support - try { - var crypto$2 = void('crypto'); - if (typeof crypto$2.randomBytes !== 'function') - throw new Error('Not supported'); - Rand.prototype._rand = function _rand(n) { - return crypto$2.randomBytes(n); - }; - } catch (e) { + //pad the message depending on the padding parameter + //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt + if (encrypt) { + message = desAddPadding(message); + len = message.length; } - } - brorand.Rand = Rand_1; - var getNAF = utils_1$1.getNAF; - var getJSF = utils_1$1.getJSF; - var assert$2 = utils_1$1.assert; + //store the result here + let result = new Uint8Array(len); + let k = 0; - function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); + //loop through each 64 bit chunk of the message + while (m < len) { + left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); + //first each 64 but chunk of the message must be permuted according to IP + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + //do this either 1 or 3 times for each chunk of the message + for (j = 0; j < iterations; j += 3) { + endloop = looping[j + 1]; + loopinc = looping[j + 2]; + //now go through and perform the encryption or decryption + for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency + right1 = right ^ keys[i]; + right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + //the result is attained by passing these bytes through the S selection functions + temp = left; + left = right; + right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> + 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & + 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); + } + temp = left; + left = right; + right = temp; //unreverse left and right + } //for either 1 or 3 iterations - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + //move then each one bit to the right + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } - } - var base = BaseCurve; + //now perform IP-1, which is IP in the opposite direction + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); - BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); - }; + result[k++] = (left >>> 24); + result[k++] = ((left >>> 16) & 0xff); + result[k++] = ((left >>> 8) & 0xff); + result[k++] = (left & 0xff); + result[k++] = (right >>> 24); + result[k++] = ((right >>> 16) & 0xff); + result[k++] = ((right >>> 8) & 0xff); + result[k++] = (right & 0xff); + } //for every 8 characters, or 64 bits in the message - BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); - }; + //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt + if (!encrypt) { + result = desRemovePadding(result); + } - BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$2(p.precomputed); - var doubles = p._getDoubles(); + return result; + } //end of des - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } + //desCreateKeys + //this takes as input a 64 bit key (even though only 56 bits are used) + //as an array of 2 integers, and returns 16 48 bit keys - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); - }; + function desCreateKeys(key) { + //declaring this locally speeds things up a bit + const pc2bytes0 = [ + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ]; + const pc2bytes1 = [ + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ]; + const pc2bytes2 = [ + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ]; + const pc2bytes3 = [ + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ]; + const pc2bytes4 = [ + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ]; + const pc2bytes5 = [ + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ]; + const pc2bytes6 = [ + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ]; + const pc2bytes7 = [ + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ]; + const pc2bytes8 = [ + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ]; + const pc2bytes9 = [ + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ]; + const pc2bytes10 = [ + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ]; + const pc2bytes11 = [ + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ]; + const pc2bytes12 = [ + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ]; + const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; - BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; + //how many iterations (1 for des, 3 for triple des) + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + //stores the return keys + const keys = new Array(32 * iterations); + //now define the left shifts which need to be done + const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + //other variables + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - // Get NAF form - var naf = getNAF(k, w); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 2) ^ right) & 0x33333333; + right ^= temp; + left ^= (temp << 2); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); + //the right side needs to be shifted and to get the last four bits of the left side + temp = (left << 8) | ((right >>> 20) & 0x000000f0); + //left needs to be put upside down + left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); + right = temp; - if (i < 0) - break; - var z = naf[i]; - assert$2(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; - }; + //now go through and perform these shifts on the left and right keys + for (let i = 0; i < shifts.length; i++) { + //shift the keys either one or two bits to the left + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; - BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; + //now apply PC-2, in such a way that E is easier when encrypting or decrypting + //this conversion will look like PC-2 except only the last 6 bits of each byte are used + //rather than 48 consecutive bits and the order of lines will be according to + //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 + lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( + left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & + 0xf]; + righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | + pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]; + temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; + keys[n++] = lefttemp ^ temp; + keys[n++] = righttemp ^ (temp << 16); } + } //for each iterations + //return the keys we've created + return keys; + } //end of desCreateKeys - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; + function desAddPadding(message, padding) { + const padLength = 8 - (message.length % 8); - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } + let pad; + if ((padLength < 8)) { //pad the message out with null bytes + pad = 0; + } else if (padLength === 8) { + return message; + } else { + throw new Error('des: invalid padding'); } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { + paddedMessage[i] = message[i]; + } + for (let j = 0; j < padLength; j++) { + paddedMessage[message.length + j] = pad; + } - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; + return paddedMessage; + } - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); + function desRemovePadding(message, padding) { + let padLength = null; + let pad; + { // null padding + pad = 0; + } - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); + if (!padLength) { + padLength = 1; + while (message[message.length - padLength] === pad) { + padLength++; } + padLength--; } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); - }; - function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; + return message.subarray(0, message.length - padLength); } - BaseCurve.BasePoint = BasePoint; - - BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); - }; - - BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); - }; - BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert$2(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$2(bytes[bytes.length - 1] % 2 === 1); + // added by Recurity Labs - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); + function TripleDES(key) { + this.key = []; - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + for (let i = 0; i < 3; i++) { + this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); } - throw new Error('Unknown point format'); - }; - - BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); - }; - - BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; - }; - - BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); - }; - - BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - var precomputed = { - doubles: null, - naf: null, - beta: null + this.encrypt = function(block) { + return des( + desCreateKeys(this.key[2]), + des( + desCreateKeys(this.key[1]), + des( + desCreateKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true); }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; - }; - - BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); - }; - - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + } - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; - }; + TripleDES.keySize = TripleDES.prototype.keySize = 24; + TripleDES.blockSize = TripleDES.prototype.blockSize = 8; - BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; - }; + // Copyright 2010 pjacobs@xeekr.com . All rights reserved. - BasePoint.prototype._getBeta = function _getBeta() { - return null; - }; + // Modified by Recurity Labs GmbH - BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; - }; + // fixed/modified by Herbert Hanewinkel, www.haneWIN.de + // check www.haneWIN.de for the latest version - var assert$3 = utils_1$1.assert; + // cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. + // CAST-128 is a common OpenPGP cipher. - function ShortCurve(conf) { - base.call(this, 'short', conf); - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); + // CAST5 constructor - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + function OpenPGPSymEncCAST5() { + this.BlockSize = 8; + this.KeySize = 16; - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); - } - inherits_browser(ShortCurve, base); - var short_1 = ShortCurve; + this.setKey = function(key) { + this.masking = new Array(16); + this.rotate = new Array(16); - ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + this.reset(); - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; + if (key.length === this.KeySize) { + this.keySchedule(key); } else { - lambda = lambdas[1]; - assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + throw new Error('CAST-128: keys must be 16 bytes'); } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis + return true; }; - }; - - ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; - }; - - ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + this.reset = function() { + for (let i = 0; i < 16; i++) { + this.masking[i] = 0; + this.rotate[i] = 0; } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; - }; - - ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; - }; - - ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); - }; + }; - ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + this.getBlockSize = function() { + return this.BlockSize; + }; - var x = point.x; - var y = point.y; + this.encrypt = function(src) { + const dst = new Array(src.length); - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; - }; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; - ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; - }; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; - function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >>> 16) & 255; + dst[i + 6] = (l >>> 8) & 255; + dst[i + 7] = l & 255; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } - } - inherits_browser(Point, base.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); - }; - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); - }; - - Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + return dst; + }; - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + this.decrypt = function(src) { + const dst = new Array(src.length); - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; - }; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; - Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; - }; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; - Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >> 16) & 255; + dst[i + 6] = (l >> 8) & 255; + dst[i + 7] = l & 255; } - }; - return res; - }; - Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + return dst; + }; + const scheduleA = new Array(4); - Point.prototype.isInfinity = function isInfinity() { - return this.inf; - }; + scheduleA[0] = new Array(4); + scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; + scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; + scheduleA[1] = new Array(4); + scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + O = P - if (p.inf) - return this; + scheduleA[2] = new Array(4); + scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; + scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); + scheduleA[3] = new Array(4); + scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + const scheduleB = new Array(4); - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); - }; + scheduleB[0] = new Array(4); + scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; + scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; + scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; + scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; - Point.prototype.dbl = function dbl() { - if (this.inf) - return this; + scheduleB[1] = new Array(4); + scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; + scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; + scheduleB[1][2] = [7, 6, 8, 9, 3]; + scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - var a = this.curve.a; + scheduleB[2] = new Array(4); + scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; + scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; + scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; + scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); - }; + scheduleB[3] = new Array(4); + scheduleB[3][0] = [8, 9, 7, 6, 3]; + scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; + scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; + scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; - Point.prototype.getX = function getX() { - return this.x.fromRed(); - }; + // changed 'in' to 'inn' (in javascript 'in' is a reserved word) + this.keySchedule = function(inn) { + const t = new Array(8); + const k = new Array(32); - Point.prototype.getY = function getY() { - return this.y.fromRed(); - }; + let j; - Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); - }; + for (let i = 0; i < 4; i++) { + j = i * 4; + t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + } - Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); - }; + const x = [6, 7, 4, 5]; + let ki = 0; + let w; - Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); - }; + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { + for (j = 0; j < 4; j++) { + const a = scheduleA[round][j]; + w = t[a[1]]; - Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); - }; + w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; + w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; + w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; + w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; + w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; + t[a[0]] = w; + } - Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + for (j = 0; j < 4; j++) { + const b = scheduleB[round][j]; + w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) + w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; + w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; + w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; + w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; + k[ki] = w; + ki++; + } } - }; - } - return res; - }; + } - Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + for (let i = 0; i < 16; i++) { + this.masking[i] = k[i]; + this.rotate[i] = k[16 + i] & 0x1f; + } + }; - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; + // These are the three 'f' functions. See RFC 2144, section 2.2. - function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); + function f1(d, m, r) { + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; - } - inherits_browser(JPoint, base.BasePoint); - - ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); - }; - - JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); - }; - - JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }; - - JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - // P + O = P - if (p.isInfinity()) - return this; + function f2(d, m, r) { + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; + } - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); + function f3(d, m, r) { + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + const sBox = new Array(8); + sBox[0] = [ + 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, + 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, + 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, + 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, + 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, + 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, + 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, + 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, + 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, + 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, + 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, + 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, + 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, + 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, + 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, + 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, + 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, + 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, + 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, + 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, + 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, + 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, + 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, + 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, + 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, + 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, + 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, + 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, + 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, + 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, + 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ]; + + sBox[1] = [ + 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, + 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, + 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, + 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, + 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, + 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, + 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, + 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, + 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, + 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, + 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, + 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, + 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, + 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, + 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, + 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, + 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, + 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, + 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, + 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, + 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, + 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, + 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, + 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, + 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, + 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, + 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, + 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, + 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, + 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, + 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ]; - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); + sBox[2] = [ + 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, + 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, + 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, + 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, + 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, + 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, + 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, + 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, + 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, + 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, + 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, + 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, + 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, + 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, + 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, + 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, + 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, + 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, + 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, + 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, + 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, + 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, + 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, + 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, + 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, + 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, + 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, + 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, + 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, + 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, + 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ]; - return this.curve.jpoint(nx, ny, nz); - }; + sBox[3] = [ + 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, + 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, + 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, + 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, + 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, + 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, + 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, + 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, + 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, + 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, + 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, + 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, + 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, + 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, + 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, + 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, + 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, + 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, + 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, + 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, + 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, + 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, + 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, + 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, + 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, + 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, + 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, + 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, + 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, + 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, + 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ]; - JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + sBox[4] = [ + 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, + 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, + 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, + 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, + 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, + 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, + 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, + 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, + 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, + 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, + 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, + 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, + 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, + 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, + 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, + 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, + 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, + 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, + 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, + 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, + 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, + 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, + 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, + 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, + 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, + 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, + 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, + 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, + 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, + 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, + 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ]; - // P + O = P - if (p.isInfinity()) - return this; + sBox[5] = [ + 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, + 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, + 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, + 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, + 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, + 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, + 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, + 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, + 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, + 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, + 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, + 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, + 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, + 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, + 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, + 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, + 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, + 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, + 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, + 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, + 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, + 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, + 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, + 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, + 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, + 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, + 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, + 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, + 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, + 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, + 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ]; - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } + sBox[6] = [ + 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, + 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, + 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, + 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, + 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, + 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, + 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, + 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, + 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, + 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, + 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, + 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, + 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, + 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, + 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, + 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, + 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, + 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, + 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, + 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, + 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, + 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, + 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, + 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, + 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, + 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, + 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, + 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, + 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, + 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, + 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ]; - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + sBox[7] = [ + 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, + 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, + 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, + 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, + 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, + 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, + 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, + 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, + 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, + 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, + 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, + 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, + 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, + 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, + 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, + 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, + 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, + 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, + 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, + 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, + 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, + 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, + 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, + 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, + 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, + 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, + 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, + 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, + 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, + 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, + 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ]; + } - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); + function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); + this.cast5.setKey(key); - return this.curve.jpoint(nx, ny, nz); - }; + this.encrypt = function(block) { + return this.cast5.encrypt(block); + }; + } - JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); + CAST5.blockSize = CAST5.prototype.blockSize = 8; + CAST5.keySize = CAST5.prototype.keySize = 16; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } + /* eslint-disable no-mixed-operators, no-fallthrough */ - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + /* Modified by Recurity Labs GmbH + * + * Cipher.js + * A block-cipher algorithm implementation on JavaScript + * See Cipher.readme.txt for further information. + * + * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] + * This script file is distributed under the LGPL + * + * ACKNOWLEDGMENT + * + * The main subroutines are written by Michiel van Everdingen. + * + * Michiel van Everdingen + * http://home.versatel.nl/MAvanEverdingen/index.html + * + * All rights for these routines are reserved to Michiel van Everdingen. + * + */ - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //Math + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); + const MAXINT = 0xFFFFFFFF; - jx = nx; - jz = nz; - jyd = dny; - } + function rotw(w, n) { + return (w << n | w >>> (32 - n)) & MAXINT; + } - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); - }; + function getW(a, i) { + return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; + } - JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; + function setW(a, i, w) { + a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); + } - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); - }; + function getB(x, n) { + return (x >>> (n * 8)) & 0xFF; + } - JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); - }; + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Twofish + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); - }; + function createTwofish() { + // + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; + // var dataLength = -1; + // var idx2 = -1; + // - JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + let tfsKey = []; + let tfsM = [ + [], + [], + [], + [] + ]; - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + function tfsInit(key) { + keyBytes = key; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + const q0 = [ + [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], + [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] + ]; + const q1 = [ + [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], + [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] + ]; + const q2 = [ + [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], + [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] + ]; + const q3 = [ + [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], + [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] + ]; + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ + [], + [] + ]; + const m = [ + [], + [], + [], + [] + ]; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + function ffm5b(x) { + return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + } - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); + function ffmEf(x) { + return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + } - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); + function mdsRem(p, q) { + let i; + let t; + let u; + for (i = 0; i < 8; i++) { + t = q >>> 24; + q = ((q << 8) & MAXINT) | p >>> 24; + p = (p << 8) & MAXINT; + u = t << 1; + if (t & 128) { + u ^= 333; + } + q ^= t ^ (u << 16); + u ^= t >>> 1; + if (t & 1) { + u ^= 166; + } + q ^= u << 24 | u << 8; + } + return q; + } - return this.curve.jpoint(nx, ny, nz); - }; + function qp(n, x) { + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; + return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; + } - JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); - }; + function hFun(x, key) { + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); + switch (kLen) { + case 4: + a = q[1][a] ^ getB(key[3], 0); + b = q[0][b] ^ getB(key[3], 1); + c = q[0][c] ^ getB(key[3], 2); + d = q[1][d] ^ getB(key[3], 3); + case 3: + a = q[1][a] ^ getB(key[2], 0); + b = q[1][b] ^ getB(key[2], 1); + c = q[0][c] ^ getB(key[2], 2); + d = q[0][d] ^ getB(key[2], 3); + case 2: + a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); + b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); + c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); + d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); + } + return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; + } - JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); + keyBytes = keyBytes.slice(0, 32); + i = keyBytes.length; + while (i !== 16 && i !== 24 && i !== 32) { + keyBytes[i++] = 0; + } - return this.curve._wnafMul(this, k); - }; + for (i = 0; i < keyBytes.length; i += 4) { + inKey[i >> 2] = getW(keyBytes, i); + } + for (i = 0; i < 256; i++) { + q[0][i] = qp(0, i); + q[1][i] = qp(1, i); + } + for (i = 0; i < 256; i++) { + f01 = q[1][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + f01 = q[0][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } - JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + kLen = inKey.length / 2; + for (i = 0; i < kLen; i++) { + a = inKey[i + i]; + meKey[i] = a; + b = inKey[i + i + 1]; + moKey[i] = b; + sKey[kLen - i - 1] = mdsRem(a, b); + } + for (i = 0; i < 40; i += 2) { + a = 0x1010101 * i; + b = a + 0x1010101; + a = hFun(a, meKey); + b = rotw(hFun(b, moKey), 8); + tfsKey[i] = (a + b) & MAXINT; + tfsKey[i + 1] = rotw(a + 2 * b, 9); + } + for (i = 0; i < 256; i++) { + a = b = c = d = i; + switch (kLen) { + case 4: + a = q[1][a] ^ getB(sKey[3], 0); + b = q[0][b] ^ getB(sKey[3], 1); + c = q[0][c] ^ getB(sKey[3], 2); + d = q[1][d] ^ getB(sKey[3], 3); + case 3: + a = q[1][a] ^ getB(sKey[2], 0); + b = q[1][b] ^ getB(sKey[2], 1); + c = q[0][c] ^ getB(sKey[2], 2); + d = q[0][d] ^ getB(sKey[2], 3); + case 2: + tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; + tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; + tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; + tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + } + } + } - if (this === p) - return true; + function tfsG0(x) { + return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; + } - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; + function tfsG1(x) { + return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; + } - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; - }; + function tfsFrnd(r, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); + blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); + blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + } - JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; + function tfsIrnd(i, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; + blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; + blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + } - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; + function tfsClose() { + tfsKey = []; + tfsM = [ + [], + [], + [], + [] + ]; + } - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; + function tfsEncrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { + tfsFrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); + dataOffset += 16; + return dataBytes; } - }; - JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + function tfsDecrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { + tfsIrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); + dataOffset += 16; + } - JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + // added by Recurity Labs - function MontCurve(conf) { - base.call(this, 'mont', conf); + function tfsFinal() { + return dataBytes; + } - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - // Note: this implementation is according to the original paper - // by P. Montgomery, NOT the one by D. J. Bernstein. - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + return { + name: 'twofish', + blocksize: 128 / 8, + open: tfsInit, + close: tfsClose, + encrypt: tfsEncrypt, + decrypt: tfsDecrypt, + // added by Recurity Labs + finalize: tfsFinal + }; } - inherits_browser(MontCurve, base); - var mont = MontCurve; - MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); + // added by Recurity Labs - return y.redSqr().cmp(rhs) === 0; - }; + function TF(key) { + this.tf = createTwofish(); + this.tf.open(Array.from(key), 0); - function Point$1(curve, x, z) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } + this.encrypt = function(block) { + return this.tf.encrypt(Array.from(block), 0); + }; } - inherits_browser(Point$1, base.BasePoint); - - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - var bytes = utils_1$1.toArray(bytes, enc); - - // TODO Curve448 - // Montgomery curve points must be represented in the compressed format - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (bytes.length === 33 && bytes[0] === 0x40) - bytes = bytes.slice(1, 33).reverse(); // point must be little-endian - if (bytes.length !== 32) - throw new Error('Unknown point compression format'); - return this.point(bytes, 1); - }; - - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; - - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; - - Point$1.prototype.precompute = function precompute() { - // No-op - }; - - Point$1.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - - // Note: the output should always be little-endian - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (compact) { - return [ 0x40 ].concat(this.getX().toArray('le', len)); - } else { - return this.getX().toArray('be', len); - } - }; - - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; - - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + TF.keySize = TF.prototype.keySize = 32; + TF.blockSize = TF.prototype.blockSize = 16; - Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); - }; + /* Modified by Recurity Labs GmbH + * + * Originally written by nklein software (nklein.com) + */ - Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; + /* + * Javascript implementation based on Bruce Schneier's reference implementation. + * + * + * The constructor doesn't do much of anything. It's just here + * so we can start defining properties and methods and such. + */ + function Blowfish() {} - Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); - }; + /* + * Declare the block size so that protocols know what size + * Initialization Vector (IV) they will need. + */ + Blowfish.prototype.BLOCKSIZE = 8; - Point$1.prototype.mul = function mul(k) { - k = new bn(k, 16); + /* + * These are the default SBOXES. + */ + Blowfish.prototype.SBOXES = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] + ]; - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q + //* + //* This is the default PARRAY + //* + Blowfish.prototype.PARRAY = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b + ]; - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); + //* + //* This is the number of rounds the cipher will go + //* + Blowfish.prototype.NN = 16; - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } + //* + //* This function is needed to get rid of problems + //* with the high-bit getting set. If we don't do + //* this, then sometimes ( aa & 0x00FFFFFFFF ) is not + //* equal to ( bb & 0x00FFFFFFFF ) even when they + //* agree bit-for-bit for the first 32 bits. + //* + Blowfish.prototype._clean = function(xx) { + if (xx < 0) { + const yy = xx & 0x7FFFFFFF; + xx = yy + 0x80000000; } - return b; - }; - - Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; - - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; - }; - - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); + return xx; }; - var assert$4 = utils_1$1.assert; - - function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - base.call(this, 'edwards', conf); - - this.a = new bn(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); + //* + //* This is the mixing function that uses the sboxes + //* + Blowfish.prototype._F = function(xx) { + let yy; - assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits_browser(EdwardsCurve, base); - var edwards = EdwardsCurve; + const dd = xx & 0x00FF; + xx >>>= 8; + const cc = xx & 0x00FF; + xx >>>= 8; + const bb = xx & 0x00FF; + xx >>>= 8; + const aa = xx & 0x00FF; - EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); - }; + yy = this.sboxes[0][aa] + this.sboxes[1][bb]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; - EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); + return yy; }; - // Just for compatibility with Short curve - EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); - }; + //* + //* This method takes an array with two values, left and right + //* and does NN rounds of Blowfish on them. + //* + Blowfish.prototype._encryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; - EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); + let ii; - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + for (ii = 0; ii < this.NN; ++ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; - return this.point(x, y); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; - EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new bn(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); + //* + //* This method takes a vector of numbers and turns them + //* into long words so that they can be processed by the + //* real algorithm. + //* + //* Maybe I should make the real algorithm above take a vector + //* instead. That will involve more looping, but it won't require + //* the F() method to deconstruct the vector. + //* + Blowfish.prototype.encryptBlock = function(vector) { + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); + vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); } - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + this._encryptBlock(vals); - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + const ret = []; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); + ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); + // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); + // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + } - return this.point(x, y); + return ret; }; - EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; - }; + //* + //* This method takes an array with two values, left and right + //* and undoes NN rounds of Blowfish on them. + //* + Blowfish.prototype._decryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; - function Point$2(curve, x, y, z, t) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } - } - inherits_browser(Point$2, base.BasePoint); - - EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$2.fromJSON(this, obj); - }; + let ii; - EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point$2(this, x, y, z, t); - }; + for (ii = this.NN + 1; ii > 1; --ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; - Point$2.fromJSON = function fromJSON(curve, obj) { - return new Point$2(curve, obj[0], obj[1], obj[2]); - }; + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } - Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; - Point$2.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; - Point$2.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); - }; + //* + //* This method takes a key array and initializes the + //* sboxes and parray for this encryption. + //* + Blowfish.prototype.init = function(key) { + let ii; + let jj = 0; - Point$2.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); + this.parray = []; + for (ii = 0; ii < this.NN + 2; ++ii) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { + data = (data << 8) | (key[jj] & 0x00FF); + if (++jj >= key.length) { + jj = 0; + } } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); - }; - - Point$2.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); - }; - - Point$2.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); - }; - - Point$2.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); + this.parray[ii] = this.PARRAY[ii] ^ data; } - return this.curve.point(nx, ny, nz); - }; - - Point$2.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); - }; + this.sboxes = []; + for (ii = 0; ii < 4; ++ii) { + this.sboxes[ii] = []; + for (jj = 0; jj < 256; ++jj) { + this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + } + } - Point$2.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); - }; + const vals = [0x00000000, 0x00000000]; - Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); - }; + for (ii = 0; ii < this.NN + 2; ii += 2) { + this._encryptBlock(vals); + this.parray[ii + 0] = vals[0]; + this.parray[ii + 1] = vals[1]; + } - Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + for (ii = 0; ii < 4; ++ii) { + for (jj = 0; jj < 256; jj += 2) { + this._encryptBlock(vals); + this.sboxes[ii][jj + 0] = vals[0]; + this.sboxes[ii][jj + 1] = vals[1]; + } + } }; - Point$2.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; - }; + // added by Recurity Labs + function BF(key) { + this.bf = new Blowfish(); + this.bf.init(key); - Point$2.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); - }; + this.encrypt = function(block) { + return this.bf.encryptBlock(block); + }; + } - Point$2.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); - }; + BF.keySize = BF.prototype.keySize = 16; + BF.blockSize = BF.prototype.blockSize = 8; - Point$2.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); - }; + /** + * This file is needed to dynamic import the legacy ciphers. + * Separate dynamic imports are not convenient as they result in multiple chunks. + */ - Point$2.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; - }; - Point$2.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; + const legacyCiphers = new Map([ + [enums.symmetric.tripledes, TripleDES], + [enums.symmetric.cast5, CAST5], + [enums.symmetric.blowfish, BF], + [enums.symmetric.twofish, TF] + ]); - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; + var legacy_ciphers = /*#__PURE__*/Object.freeze({ + __proto__: null, + legacyCiphers: legacyCiphers + }); - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + // SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. + // Initial state + const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, + ]); + // Temporary buffer, not used to store anything between runs + // Named this way because it matches specification. + const SHA1_W = /* @__PURE__ */ new Uint32Array(80); + class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } + } + /** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ + const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + + // https://homes.esat.kuleuven.be/~bosselae/ripemd160.html + // https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf + const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); + const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); + const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); + let idxL = [Id]; + let idxR = [Pi]; + for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); + const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], + ].map((i) => new Uint8Array(i)); + const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); + const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); + const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, + ]); + const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, + ]); + // It's called f() in spec. + function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); + } + // Temporary buffer, not used to store anything between runs + const R_BUF = /* @__PURE__ */ new Uint32Array(16); + class RIPEMD160 extends HashMD { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + R_BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } + } + /** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ + const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); - // Compatibility with BaseCurve - Point$2.prototype.toP = Point$2.prototype.normalize; - Point$2.prototype.mixedAdd = Point$2.prototype.add; + /** + * This file is needed to dynamic import the noble-hashes. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ - var curve_1 = createCommonjsModule(function (module, exports) { - var curve = exports; + const nobleHashes = new Map(Object.entries({ + sha1, + sha224, + sha256, + sha384, + sha512, + sha3_256, + sha3_512, + ripemd160 + })); - curve.base = base; - curve.short = short_1; - curve.mont = mont; - curve.edwards = edwards; + var noble_hashes = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleHashes: nobleHashes }); - var rotl32$2 = utils.rotl32; - var sum32$3 = utils.sum32; - var sum32_5$2 = utils.sum32_5; - var ft_1$1 = common$1.ft_1; - var BlockHash$4 = common.BlockHash; - - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; + // Adapted from the reference implementation in RFC7693 + // Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); + // Uint64 values are represented using two Uint32s, stored as little endian + // NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays + // need to be manually handled - BlockHash$4.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); + // 64-bit unsigned addition (little endian, in place) + // Sets a[i,i+1] += b[j,j+1] + // `a` and `b` must be Uint32Array(2) + function ADD64 (a, i, b, j) { + a[i] += b[j]; + a[i+1] += b[j+1] + (a[i] < b[j]); // add carry } - utils.inherits(SHA1, BlockHash$4); - var _1 = SHA1; + // Increment 64-bit little-endian unsigned value by `c` (in place) + // `a` must be Uint32Array(2) + function INC64 (a, c) { + a[0] += c; + a[1] += (a[0] < c); + } - SHA1.blockSize = 512; - SHA1.outSize = 160; - SHA1.hmacStrength = 80; - SHA1.padLength = 64; + // G Mixing function + // The ROTRs are inlined for speed + function G$1 (v, m, a, b, c, d, ix, iy) { + ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1] + ADD64(v, a, m, ix); // v[a, a+1] += x ... x0 - SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + ADD64(v, c, v, d); - for(; i < W.length; i++) - W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor0 >>> 24) ^ (xor1 << 8); + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; + ADD64(v, a, v, b); + ADD64(v, a, m, iy); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$2(b, 30); - b = a; - a = t; - } + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = (xor0 >>> 16) ^ (xor1 << 16); + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); - this.h[0] = sum32$3(this.h[0], a); - this.h[1] = sum32$3(this.h[1], b); - this.h[2] = sum32$3(this.h[2], c); - this.h[3] = sum32$3(this.h[3], d); - this.h[4] = sum32$3(this.h[4], e); - }; + ADD64(v, c, v, d); - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); - }; + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor1 >>> 31) ^ (xor0 << 1); + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); + } - var sha1 = _1; - var sha224 = _224; - var sha256 = _256; - var sha384 = _384; - var sha512 = _512; - - var sha = { - sha1: sha1, - sha224: sha224, - sha256: sha256, - sha384: sha384, - sha512: sha512 - }; + // Initialization Vector + const BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 + ]); - function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); - } - var hmac = Hmac; - - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); - }; + // These are offsets into a Uint64 buffer. + // Multiply them all by 2 to make them offsets into a Uint32 buffer + const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 + ].map(x => x * 2)); + + // Compression function. 'last' flag indicates last block. + // Note: we're representing 16 uint64s as 32 uint32s + function compress(S, last) { + const v = new Uint32Array(32); + const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32); + + // init work variables + for (let i = 0; i < 16; i++) { + v[i] = S.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + + // low 64 bits of offset + v[24] ^= S.t0[0]; + v[25] ^= S.t0[1]; + // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1 + + // if last block + const f0 = last ? 0xFFFFFFFF : 0; + v[28] ^= f0; + v[29] ^= f0; + + // twelve rounds of mixing + for (let i = 0; i < 12; i++) { + // ROUND(r) + const i16 = i << 4; + G$1(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1]); + G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]); + G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]); + G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]); + G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]); + G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]); + G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]); + G$1(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15]); + } + + for (let i = 0; i < 16; i++) { + S.h[i] ^= v[i] ^ v[i + 16]; + } + } + + // Creates a BLAKE2b hashing context + // Requires an output length between 1 and 64 bytes + // Takes an optional Uint8Array key + class Blake2b { + constructor(outlen, key, salt, personal) { + const params = new Uint8Array(64); + // 0: outlen, keylen, fanout, depth + // 4: leaf length, sequential mode + // 8: node offset + // 12: node offset + // 16: node depth, inner length, rfu + // 20: rfu + // 24: rfu + // 28: rfu + // 32: salt + // 36: salt + // 40: salt + // 44: salt + // 48: personal + // 52: personal + // 56: personal + // 60: personal + + // init internal state + this.S = { + b: new Uint8Array(BLOCKBYTES), + h: new Uint32Array(OUTBYTES_MAX / 4), + t0: new Uint32Array(2), // input counter `t`, lower 64-bits only + c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES` + outlen // output length in bytes + }; - Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; - }; + // init parameter block + params[0] = outlen; + if (key) params[1] = key.length; + params[2] = 1; // fanout + params[3] = 1; // depth + if (salt) params.set(salt, 32); + if (personal) params.set(personal, 48); + const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT); - Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); - }; + // initialize hash state + for (let i = 0; i < 16; i++) { + this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i]; + } - var hash_1 = createCommonjsModule(function (module, exports) { - var hash = exports; - - hash.utils = utils; - hash.common = common; - hash.sha = sha; - hash.ripemd = ripemd; - hash.hmac = hmac; - - // Proxy hash functions to the main object - hash.sha1 = hash.sha.sha1; - hash.sha256 = hash.sha.sha256; - hash.sha224 = hash.sha.sha224; - hash.sha384 = hash.sha.sha384; - hash.sha512 = hash.sha.sha512; - hash.ripemd160 = hash.ripemd.ripemd160; - }); + // key the hash, if applicable + if (key) { + const block = new Uint8Array(BLOCKBYTES); + block.set(key); + this.update(block); + } + } - var secp256k1 = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] + // Updates a BLAKE2b streaming hash + // Requires Uint8Array (byte array) + update(input) { + if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer') + // for (let i = 0; i < input.length; i++) { + // if (this.S.c === BLOCKBYTES) { // buffer full + // INC64(this.S.t0, this.S.c) // add counters + // compress(this.S, false) + // this.S.c = 0 // empty buffer + // } + // this.S.b[this.S.c++] = input[i] + // } + let i = 0; + while(i < input.length) { + if (this.S.c === BLOCKBYTES) { // buffer full + INC64(this.S.t0, this.S.c); // add counters + compress(this.S, false); + this.S.c = 0; // empty buffer + } + let left = BLOCKBYTES - this.S.c; + this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds + const fill = Math.min(left, input.length - i); + this.S.c += fill; + i += fill; + } + return this } - }; - var curves_1 = createCommonjsModule(function (module, exports) { + /** + * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one + * @param {Uint8Array} [prealloc] - optional preallocated buffer + * @returns {ArrayBuffer} message digest + */ + digest(prealloc) { + INC64(this.S.t0, this.S.c); // mark last block offset + + // final block, padded + this.S.b.fill(0, this.S.c); + this.S.c = BLOCKBYTES; + compress(this.S, true); + + const out = prealloc || new Uint8Array(this.S.outlen); + for (let i = 0; i < this.S.outlen; i++) { + // must be loaded individually since default Uint32 endianness is platform dependant + out[i] = this.S.h[i >> 2] >> (8 * (i & 3)); + } + this.S.h = null; // prevent calling `update` after `digest` + return out.buffer; + } + } - var curves = exports; + function createHash(outlen, key, salt, personal) { + if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`) + return new Blake2b(outlen, key, salt, personal) + } + const OUTBYTES_MAX = 64; + const BLOCKBYTES = 128; + const TYPE = 2; // Argon2id + const VERSION = 0x13; + const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; + const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1; + const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; + const SALTBYTES_MIN = 8; + const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; + const passwordBYTES_MIN = 8; + const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; + const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional) + const SECRETBYTES_MAX = 32; // key (optional) - var assert = utils_1$1.assert; + const ARGON2_BLOCK_SIZE = 1024; + const ARGON2_PREHASH_DIGEST_LENGTH = 64; - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve_1.short(options); - else if (options.type === 'edwards') - this.curve = new curve_1.edwards(options); - else if (options.type === 'mont') - this.curve = new curve_1.mont(options); - else throw new Error('Unknown curve type.'); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; + const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); + // store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3]) + function LE32(buf, n, i) { + buf[i+0] = n; + buf[i+1] = n >> 8; + buf[i+2] = n >> 16; + buf[i+3] = n >> 24; + return buf; } - curves.PresetCurve = PresetCurve; - function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); + /** + * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7]) + * @param {Uint8Array} buf + * @param {Number} n + * @param {Number} i + */ + function LE64(buf, n, i) { + if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported"); + // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations + // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps) + // so we manually extract each byte + let remainder = n; + for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER + buf[offset] = remainder; // implicit & 0xff + remainder = (remainder - buf[offset]) / 256; + } + return buf; } - defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash_1.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] - }); + /** + * Variable-Length Hash Function H' + * @param {Number} outlen - T + * @param {Uint8Array} X - value to hash + * @param {Uint8Array} res - output buffer, of length `outlength` or larger + */ + function H_(outlen, X, res) { + const V = new Uint8Array(64); // no need to keep around all V_i - defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash_1.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] - }); + const V1_in = new Uint8Array(4 + X.length); + LE32(V1_in, outlen, 0); + V1_in.set(X, 4); + if (outlen <= 64) { + // H'^T(A) = H^T(LE32(T)||A) + createHash(outlen).update(V1_in).digest(res); + return res + } - defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash_1.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] - }); + const r = Math.ceil(outlen / 32) - 2; - defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash_1.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] - }); + // Let V_i be a 64-byte block and W_i be its first 32 bytes. + // V_1 = H^(64)(LE32(T)||A) + // V_2 = H^(64)(V_1) + // ... + // V_r = H^(64)(V_{r-1}) + // V_{r+1} = H^(T-32*r)(V_{r}) + // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1} + for (let i = 0; i < r; i++) { + createHash(64).update(i === 0 ? V1_in : V).digest(V); + // store W_i in result buffer already + res.set(V.subarray(0, 32), i*32); + } + // V_{r+1} + const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest()); + res.set(V_r1, r*32); - defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash_1.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] - }); + return res; + } - // https://tools.ietf.org/html/rfc7748#section-4.1 - defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '9' - ] - }); + // compute buf = xs ^ ys + function XOR(wasmContext, buf, xs, ys) { + wasmContext.fn.XOR( + buf.byteOffset, + xs.byteOffset, + ys.byteOffset, + ); + return buf + } - defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] - }); + /** + * @param {Uint8Array} X (read-only) + * @param {Uint8Array} Y (read-only) + * @param {Uint8Array} R - output buffer + * @returns + */ + function G(wasmContext, X, Y, R) { + wasmContext.fn.G( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; + } - // https://tools.ietf.org/html/rfc5639#section-3.4 - defineCurve('brainpoolP256r1', { - type: 'short', - prime: null, - p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377', - a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9', - b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6', - n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7', - hash: hash_1.sha256, // or 384, or 512 - gRed: false, - g: [ - '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262', - '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997' - ] - }); + function G2(wasmContext, X, Y, R) { + wasmContext.fn.G2( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; + } + + // Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values. + function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) { + // For each segment, we do the following. First, we compute the value Z as: + // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) ) + wasmContext.refs.prngTmp.fill(0); + const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8); + LE64(Z, pass, 0); + LE64(Z, lane, 8); + LE64(Z, slice, 16); + LE64(Z, m_, 24); + LE64(Z, totalPasses, 32); + LE64(Z, TYPE, 40); + + // Then we compute q/(128*SL) 1024-byte values + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ), + // ..., + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )), + for(let i = 1; i <= segmentLength; i++) { + // tmp.set(Z); // no need to re-copy + LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed + const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR ); + + // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2 + // NB: the first generated pair must be used for the first block of the segment, and so on. + // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset. + for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) { + yield g2.subarray(k, k+8); + } + } + return []; + } + + function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) { + const assertLength = (name, value, min, max) => { + if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); } + }; - // https://tools.ietf.org/html/rfc5639#section-3.6 - defineCurve('brainpoolP384r1', { - type: 'short', - prime: null, - p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' + - 'ACD3A729 901D1A71 87470013 3107EC53', - a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' + - '8AA5814A 503AD4EB 04A8C7DD 22CE2826', - b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' + - '7CB43902 95DBC994 3AB78696 FA504C11', - n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' + - 'CF3AB6AF 6B7FC310 3B883202 E9046565', - hash: hash_1.sha384, // or 512 - gRed: false, - g: [ - '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' + - 'E8E826E03436D646AAEF87B2E247D4AF1E', - '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' + - '280E4646217791811142820341263C5315' - ] - }); + if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version'); + assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX); + assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX); + assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX); + assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX); + // optional fields + ad && assertLength('associated data', ad, 0, ADBYTES_MAX); + secret && assertLength('secret', secret, 0, SECRETBYTES_MAX); - // https://tools.ietf.org/html/rfc5639#section-3.7 - defineCurve('brainpoolP512r1', { - type: 'short', - prime: null, - p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' + - '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3', - a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' + - '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA', - b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' + - '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723', - n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' + - '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069', - hash: hash_1.sha512, - gRed: false, - g: [ - '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' + - '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', - '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' + - '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892' - ] - }); + return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes }; + } - // https://en.bitcoin.it/wiki/Secp256k1 - var pre; - try { - pre = secp256k1; - } catch (e) { - pre = undefined; - } - - defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash_1.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], + const KB = 1024; + const WASM_PAGE_SIZE = 64 * KB; - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] - }); - }); + function argon2id(params, { memory, instance: wasmInstance }) { + if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system - function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + const ctx = validateParams({ type: TYPE, version: VERSION, ...params }); - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports; + const wasmRefs = {}; + const wasmFn = {}; + wasmFn.G = wasmG; + wasmFn.G2 = wasmG2; + wasmFn.XOR = wasmXOR; - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p. + const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes)); + const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references + if (memory.buffer.byteLength < requiredMemory) { + const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE); + // If enough memory is available, the `memory.buffer` is internally detached and the reference updated. + // Otherwise, the operation fails, and the original memory can still be used. + memory.grow(missing); + } - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils_1.toArray(options.pers, options.persEnc || 'hex'); - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG; + let offset = 0; + // Init wasm memory needed in other functions + wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length; + wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length; + wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length; + wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length; + // Init wasm memory needed locally + const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT; + const wasmContext = { fn: wasmFn, refs: wasmRefs }; + const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length; + const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE); + const allocatedMemory = new Uint8Array(memory.buffer, 0, offset); + + // 1. Establish H_0 + const H0 = getH0(ctx); + + // 2. Allocate the memory as m' 1024-byte blocks + // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns. + const q = m_ / ctx.lanes; + const B = new Array(ctx.lanes).fill(null).map(() => new Array(q)); + const initBlock = (i, j) => { + B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE); + return B[i][j]; + }; - HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + for (let i = 0; i < ctx.lanes; i++) { + // const LEi = LE0; // since p = 1 for us + const tmp = new Uint8Array(H0.length + 8); + // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0)); + // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + LE32(tmp, 1, H0.length); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1)); + } + + // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2 + // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes + // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc. + const SL = 4; // vertical slices + const segmentLength = q / SL; + for (let pass = 0; pass < ctx.passes; pass++) { + // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel + for (let sl = 0; sl < SL; sl++) { + const isDataIndependent = pass === 0 && sl <= 1; + for (let i = 0; i < ctx.lanes; i++) { // lane + // On the first slice of the first pass, blocks 0 and 1 are already filled + let segmentOffset = sl === 0 && pass === 0 ? 2 : 0; + // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory) + const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null; + for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) { + const j = sl * segmentLength + segmentOffset; + const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q] + + // we can assume the PRNG is never done + const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength); + const l = lz[0]; const z = lz[1]; + // for (let i = 0; i < p; i++ ) + // B[i][j] = G(B[i][j-1], B[l][z]) + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + if (pass === 0) initBlock(i, j); + G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]); + + // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one + if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]); + } + } + } + } + + // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column: + // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1] + const C = B[0][q-1]; + for(let i = 1; i < ctx.lanes; i++) { + XOR(wasmContext, C, C, B[i][q-1]); + } + + const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength)); + // clear memory since the module might be cached + allocatedMemory.fill(0); // clear sensitive contents + memory.grow(0); // allow deallocation + // 8. The output tag is computed as H'^T(C). + return tag; + + } + + function getH0(ctx) { + const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH); + const ZERO32 = new Uint8Array(4); + const params = new Uint8Array(24); + LE32(params, ctx.lanes, 0); + LE32(params, ctx.tagLength, 4); + LE32(params, ctx.memorySize, 8); + LE32(params, ctx.passes, 12); + LE32(params, ctx.version, 16); + LE32(params, ctx.type, 20); + + const toHash = [params]; + if (ctx.password) { + toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0)); + toHash.push(ctx.password); + } else { + toHash.push(ZERO32); // context.password.length + } - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; + if (ctx.salt) { + toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0)); + toHash.push(ctx.salt); + } else { + toHash.push(ZERO32); // context.salt.length } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 - }; + if (ctx.secret) { + toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0)); + toHash.push(ctx.secret); + // todo clear secret? + } else { + toHash.push(ZERO32); // context.secret.length + } - HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); - }; + if (ctx.ad) { + toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0)); + toHash.push(ctx.ad); + } else { + toHash.push(ZERO32); // context.ad.length + } + H.update(concatArrays(toHash)); - HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; + const outputBuffer = H.digest(); + return new Uint8Array(outputBuffer); + } - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); - }; + function concatArrays(arrays) { + if (arrays.length === 1) return arrays[0]; + + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!(arrays[i] instanceof Uint8Array)) { + throw new Error('concatArrays: Data must be in the form of a Uint8Array'); + } - HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; + totalLength += arrays[i].length; } - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach((element) => { + result.set(element, pos); + pos += element.length; + }); + + return result; + } + + let isSIMDSupported; + async function wasmLoader(memory, getSIMD, getNonSIMD) { + const importObject = { env: { memory } }; + if (isSIMDSupported === undefined) { + try { + const loaded = await getSIMD(importObject); + isSIMDSupported = true; + return loaded; + } catch(e) { + isSIMDSupported = false; + } + } - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + const loader = isSIMDSupported ? getSIMD : getNonSIMD; + return loader(importObject); + } - this._update(entropy.concat(add || [])); - this._reseed = 1; - }; + async function setupWasm(getSIMD, getNonSIMD) { + const memory = new WebAssembly.Memory({ + // in pages of 64KiB each + // these values need to be compatible with those declared when building in `build-wasm` + initial: 1040, // 65MB + maximum: 65536, // 4GB + }); + const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD); - HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); + /** + * Argon2id hash function + * @callback computeHash + * @param {Object} params + * @param {Uint8Array} params.password - password + * @param {Uint8Array} params.salt - salt + * @param {Integer} params.parallelism + * @param {Integer} params.passes + * @param {Integer} params.memorySize - in kibibytes + * @param {Integer} params.tagLength - output tag length + * @param {Uint8Array} [params.ad] - associated data (optional) + * @param {Uint8Array} [params.secret] - secret data (optional) + * @return {Uint8Array} argon2id hash + */ + const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory }); - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } + return computeHash; + } - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } + function _loadWasmModule (sync, filepath, src, imports) { + function _instantiateOrCompile(source, imports, stream) { + var instantiateFunc = WebAssembly.instantiate; + var compileFunc = WebAssembly.compile; - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); + if (imports) { + return instantiateFunc(source, imports) + } else { + return compileFunc(source) + } } - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils_1.encode(res, enc); - }; + + var buf = null; - var assert$5 = utils_1$1.assert; - function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; + var raw = globalThis.atob(src); + var rawLength = raw.length; + buf = new Uint8Array(new ArrayBuffer(rawLength)); + for(var i = 0; i < rawLength; i++) { + buf[i] = raw.charCodeAt(i); + } + - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); + + { + return _instantiateOrCompile(buf, imports) + } } - var key = KeyPair; - KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; + function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEUCIG/c4BIAkgCf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAX9USIFQSj9ywEgBUEY/c0B/VAiCCAE/c4BIAggCP0NAAECAwgJCgsAAQID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IAf9USIFQQH9ywEgBUE//c0B/VAiBSAJIAr9USIEQQH9ywEgBEE//c0B/VAiBCAE/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/QsEgAIgACAEIAUgBf0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eH/0LBIADIBBBAWoiEEEIRw0AC0EAIRADQCACIBBBBHQiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACACIABBEHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBIHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBMHIiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)} - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); - }; + function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)} - KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; + const loadWasm = async () => setupWasm( + (instanceObject) => wasmSIMD(instanceObject), + (instanceObject) => wasmNonSIMD(instanceObject), + ); - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); - }; + var index$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: loadWasm + }); - // TODO: should not validate for X25519 - KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); + /* + node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; + Copyright (C) 2012 Eli Skeggs - return { result: true, reason: null }; - }; + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - KeyPair.prototype.getPublic = function getPublic(enc, compact) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - if (!enc) - return this.pub; + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see + http://www.gnu.org/licenses/lgpl-2.1.html - return this.pub.encode(enc, compact); - }; + Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). - KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; + Based on micro-bunzip by Rob Landley (rob@landley.net). - KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new bn(key, enc || 16); - - // For Curve25519/Curve448 we have a specific procedure. - // TODO Curve448 - if (this.ec.curve.type === 'mont') { - var one = this.ec.curve.one; - var mask = one.ushln(255 - 3).sub(one).ushln(3); - this.priv = this.priv.or(one.ushln(255 - 1)); - this.priv = this.priv.and(mask); - } else - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); - }; + Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), + which also acknowledges contributions by Mike Burrows, David Wheeler, + Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, + Robert Sedgewick, and Jon L. Bentley. + */ - KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); - }; + var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; - // ECDH - KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); + // offset in bytes + var BitReader$1 = function(stream) { + this.stream = stream; + this.bitOffset = 0; + this.curByte = 0; + this.hasByte = false; }; - // ECDSA - KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); + BitReader$1.prototype._ensureByte = function() { + if (!this.hasByte) { + this.curByte = this.stream.readByte(); + this.hasByte = true; + } }; - KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); + // reads bits from the buffer + BitReader$1.prototype.read = function(bits) { + var result = 0; + while (bits > 0) { + this._ensureByte(); + var remaining = 8 - this.bitOffset; + // if we're in a byte + if (bits >= remaining) { + result <<= remaining; + result |= BITMASK[remaining] & this.curByte; + this.hasByte = false; + this.bitOffset = 0; + bits -= remaining; + } else { + result <<= bits; + var shift = remaining - bits; + result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; + this.bitOffset += bits; + bits = 0; + } + } + return result; }; - KeyPair.prototype.inspect = function inspect() { - return ''; + // seek to an arbitrary point in the buffer (expressed in bits) + BitReader$1.prototype.seek = function(pos) { + var n_bit = pos % 8; + var n_byte = (pos - n_bit) / 8; + this.bitOffset = n_bit; + this.stream.seek(n_byte); + this.hasByte = false; }; - var assert$6 = utils_1$1.assert; - - function Signature$1(options, enc) { - if (options instanceof Signature$1) - return options; - - if (this._importDER(options, enc)) - return; + // reads 6 bytes worth of data using the read method + BitReader$1.prototype.pi = function() { + var buf = new Uint8Array(6), i; + for (i = 0; i < buf.length; i++) { + buf[i] = this.read(8); + } + return bufToHex(buf); + }; - assert$6(options.r && options.s, 'Signature without r or s'); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; + function bufToHex(buf) { + return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); } - var signature$1 = Signature$1; - function Position() { - this.place = 0; - } + var bitreader = BitReader$1; - function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; - } + /* very simple input/output stream interface */ - function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); - } + var Stream$1 = function() { + }; - Signature$1.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); + // input streams ////////////// + /** Returns the next byte, or -1 for EOF. */ + Stream$1.prototype.readByte = function() { + throw new Error("abstract method readByte() not implemented"); + }; + /** Attempts to fill the buffer; returns number of bytes read, or + * -1 for EOF. */ + Stream$1.prototype.read = function(buffer, bufOffset, length) { + var bytesRead = 0; + while (bytesRead < length) { + var c = this.readByte(); + if (c < 0) { // EOF + return (bytesRead===0) ? -1 : bytesRead; + } + buffer[bufOffset++] = c; + bytesRead++; } - - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - - return true; + return bytesRead; + }; + Stream$1.prototype.seek = function(new_pos) { + throw new Error("abstract method seek() not implemented"); }; - function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; + // output streams /////////// + Stream$1.prototype.writeByte = function(_byte) { + throw new Error("abstract method readByte() not implemented"); + }; + Stream$1.prototype.write = function(buffer, bufOffset, length) { + var i; + for (i=0; i>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); - } - - Signature$1.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); + return length; + }; + Stream$1.prototype.flush = function() { }; - var assert$7 = utils_1$1.assert; + var stream = Stream$1; + /* CRC32, used in Bzip2 implementation. + * This is a port of CRC32.java from the jbzip2 implementation at + * https://code.google.com/p/jbzip2 + * which is: + * Copyright (c) 2011 Matthew Francis + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * This JavaScript implementation is: + * Copyright (c) 2013 C. Scott Ananian + * with the same licensing terms as Matthew Francis' original implementation. + */ + var crc32 = (function() { + /** + * A static CRC lookup table + */ + var crc32Lookup = new Uint32Array([ + 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, + 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, + 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, + 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, + 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, + 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, + 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, + 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, + 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, + 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, + 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, + 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, + 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, + 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, + 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, + 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, + 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 + ]); - function EC(options) { - if (!(this instanceof EC)) - return new EC(options); + var CRC32 = function() { + /** + * The current CRC + */ + var crc = 0xffffffff; - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options); + /** + * @return The current CRC + */ + this.getCRC = function() { + return (~crc) >>> 0; // return an unsigned value + }; - options = curves_1[options]; - } + /** + * Update the CRC with a single byte + * @param value The value to update the CRC with + */ + this.updateCRC = function(value) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + }; - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves_1.PresetCurve) - options = { curve: options }; + /** + * Update the CRC with a sequence of identical bytes + * @param value The value to update the CRC with + * @param count The number of bytes + */ + this.updateCRCRun = function(value, count) { + while (count-- > 0) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + } + }; + }; + return CRC32; + })(); - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; + /* + seek-bzip - a pure-javascript module for seeking within bzip2 data - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); + Copyright (C) 2013 C. Scott Ananian + Copyright (C) 2012 Eli Skeggs + Copyright (C) 2011 Kevin Kwok - // Hash function for DRBG - this.hash = options.hash || options.curve.hash; - } - var ec = EC; + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); - }; + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); - }; + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see + http://www.gnu.org/licenses/lgpl-2.1.html - EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); - }; + Adapted from node-bzip, copyright 2012 Eli Skeggs. + Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); + Based on micro-bunzip by Rob Landley (rob@landley.net). - // Key generation for curve25519 is simpler - if (this.curve.type === 'mont') { - var priv = new bn(drbg.generate(32)); - return this.keyFromPrivate(priv); - } + Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), + which also acknowledges contributions by Mike Burrows, David Wheeler, + Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, + Robert Sedgewick, and Jon L. Bentley. + */ - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; + var BitReader = bitreader; + var Stream = stream; + var CRC32 = crc32; - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); - }; + var MAX_HUFCODE_BITS = 20; + var MAX_SYMBOLS = 258; + var SYMBOL_RUNA = 0; + var SYMBOL_RUNB = 1; + var MIN_GROUPS = 2; + var MAX_GROUPS = 6; + var GROUP_SIZE = 50; - EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) { - bitSize = bitSize || msg.byteLength() * 8; - var delta = bitSize - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; - }; + var WHOLEPI = "314159265359"; + var SQRTPI = "177245385090"; - EC.prototype.truncateMsg = function truncateMSG(msg) { - // Bit size is only determined correctly for Uint8Arrays and hex strings - var bitSize; - if (msg instanceof Uint8Array) { - bitSize = msg.byteLength * 8; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else if (typeof msg === 'string') { - bitSize = msg.length * 4; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else { - msg = this._truncateToN(new bn(msg, 16)); + var mtf = function(array, index) { + var src = array[index], i; + for (i = index; i > 0; i--) { + array[i] = array[i-1]; } - return msg; + array[0] = src; + return src; }; - EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this.truncateMsg(msg); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); + var Err = { + OK: 0, + LAST_BLOCK: -1, + NOT_BZIP_DATA: -2, + UNEXPECTED_INPUT_EOF: -3, + UNEXPECTED_OUTPUT_EOF: -4, + DATA_ERROR: -5, + OUT_OF_MEMORY: -6, + OBSOLETE_INPUT: -7, + END_OF_BLOCK: -8 + }; + var ErrorMessages = {}; + ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; + ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; + ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; + ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; + ErrorMessages[Err.DATA_ERROR] = "Data error"; + ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; + ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; + var _throw = function(status, optDetail) { + var msg = ErrorMessages[status] || 'unknown error'; + if (optDetail) { msg += ': '+optDetail; } + var e = new TypeError(msg); + e.errorCode = status; + throw e; + }; - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; + var Bunzip = function(inputStream, outputStream) { + this.writePos = this.writeCurrent = this.writeCount = 0; - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + this._start_bunzip(inputStream, outputStream); + }; + Bunzip.prototype._init_block = function() { + var moreBlocks = this._get_next_block(); + if ( !moreBlocks ) { + this.writeCount = -1; + return false; /* no more blocks */ + } + this.blockCRC = new CRC32(); + return true; + }; + /* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ + Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { + /* Ensure that file starts with "BZh['1'-'9']." */ + var buf = new Uint8Array(4); + if (inputStream.read(buf, 0, 4) !== 4 || + String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') + _throw(Err.NOT_BZIP_DATA, 'bad magic'); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + var level = buf[3] - 0x30; + if (level < 1 || level > 9) + _throw(Err.NOT_BZIP_DATA, 'level out of range'); - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + this.reader = new BitReader(inputStream); - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; + /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of + uncompressed data. Allocate intermediate buffer for block. */ + this.dbufSize = 100000 * level; + this.nextoutput = 0; + this.outputStream = outputStream; + this.streamCRC = 0; + }; + Bunzip.prototype._get_next_block = function() { + var i, j, k; + var reader = this.reader; + // this is get_next_block() function from micro-bunzip: + /* Read in header signature and CRC, then validate signature. + (last block signature means CRC is for whole file, return now) */ + var h = reader.pi(); + if (h === SQRTPI) { // last block + return false; /* no more blocks */ + } + if (h !== WHOLEPI) + _throw(Err.NOT_BZIP_DATA); + this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) + this.streamCRC = (this.targetBlockCRC ^ + ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; + /* We can add support for blockRandomised if anybody complains. There was + some code for this in busybox 1.0.0-pre3, but nobody ever noticed that + it didn't actually work. */ + if (reader.read(1)) + _throw(Err.OBSOLETE_INPUT); + var origPointer = reader.read(24); + if (origPointer > this.dbufSize) + _throw(Err.DATA_ERROR, 'initial position out of bounds'); + /* mapping table: if some byte values are never used (encoding things + like ascii text), the compression code removes the gaps to have fewer + symbols to deal with, and writes a sparse bitfield indicating which + values were present. We make a translation table to convert the symbols + back to the corresponding bytes. */ + var t = reader.read(16); + var symToByte = new Uint8Array(256), symTotal = 0; + for (i = 0; i < 16; i++) { + if (t & (1 << (0xF - i))) { + var o = i * 16; + k = reader.read(16); + for (j = 0; j < 16; j++) + if (k & (1 << (0xF - j))) + symToByte[symTotal++] = o + j; } - - return new signature$1({ r: r, s: s, recoveryParam: recoveryParam }); } - }; - - EC.prototype.verify = function verify(msg, signature, key, enc) { - key = this.keyFromPublic(key, enc); - signature = new signature$1(signature, 'hex'); - // Fallback to the old code - var ret = this._verify(this.truncateMsg(msg), signature, key) || - this._verify(this._truncateToN(new bn(msg, 16)), signature, key); - return ret; - }; - EC.prototype._verify = function _verify(msg, signature, key) { - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; + /* How many different huffman coding groups does this block use? */ + var groupCount = reader.read(3); + if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) + _throw(Err.DATA_ERROR); + /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding + group. Read in the group selector list, which is stored as MTF encoded + bit runs. (MTF=Move To Front, as each value is used it's moved to the + start of the list.) */ + var nSelectors = reader.read(15); + if (nSelectors === 0) + _throw(Err.DATA_ERROR); - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); + var mtfSymbol = new Uint8Array(256); + for (i = 0; i < groupCount; i++) + mtfSymbol[i] = i; - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + var selectors = new Uint8Array(nSelectors); // was 32768... - return p.getX().umod(this.n).cmp(r) === 0; + for (i = 0; i < nSelectors; i++) { + /* Get next value */ + for (j = 0; reader.read(1); j++) + if (j >= groupCount) _throw(Err.DATA_ERROR); + /* Decode MTF to get the next selector */ + selectors[i] = mtf(mtfSymbol, j); } - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); - }; + /* Read the huffman coding tables for each group, which code for symTotal + literal symbols, plus two run symbols (RUNA, RUNB) */ + var symCount = symTotal + 2; + var groups = [], hufGroup; + for (j = 0; j < groupCount; j++) { + var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); + /* Read huffman code lengths for each symbol. They're stored in + a way similar to mtf; record a starting value for the first symbol, + and an offset from the previous value for everys symbol after that. */ + t = reader.read(5); // lengths + for (i = 0; i < symCount; i++) { + for (;;) { + if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); + /* If first bit is 0, stop. Else second bit indicates whether + to increment or decrement the value. */ + if(!reader.read(1)) + break; + if(!reader.read(1)) + t++; + else + t--; + } + length[i] = t; + } - EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$7((3 & j) === j, 'The recovery param is more than two bits'); - signature = new signature$1(signature, enc); - - var n = this.n; - var e = new bn(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); - }; + /* Find largest and smallest lengths in this group */ + var minLen, maxLen; + minLen = maxLen = length[0]; + for (i = 1; i < symCount; i++) { + if (length[i] > maxLen) + maxLen = length[i]; + else if (length[i] < minLen) + minLen = length[i]; + } - EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new signature$1(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; + /* Calculate permute[], base[], and limit[] tables from length[]. + * + * permute[] is the lookup table for converting huffman coded symbols + * into decoded symbols. base[] is the amount to subtract from the + * value of a huffman symbol of a given length when using permute[]. + * + * limit[] indicates the largest numerical value a symbol with a given + * number of bits can have. This is how the huffman codes can vary in + * length: each code with a value>limit[length] needs another bit. + */ + hufGroup = {}; + groups.push(hufGroup); + hufGroup.permute = new Uint16Array(MAX_SYMBOLS); + hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); + hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); + hufGroup.minLen = minLen; + hufGroup.maxLen = maxLen; + /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ + var pp = 0; + for (i = minLen; i <= maxLen; i++) { + temp[i] = hufGroup.limit[i] = 0; + for (t = 0; t < symCount; t++) + if (length[t] === i) + hufGroup.permute[pp++] = t; + } + /* Count symbols coded for at each bit length */ + for (i = 0; i < symCount; i++) + temp[length[i]]++; + /* Calculate limit[] (the largest symbol-coding value at each bit + * length, which is (previous limit<<1)+symbols at this level), and + * base[] (number of symbols to ignore at each bit length, which is + * limit minus the cumulative count of symbols coded for already). */ + pp = t = 0; + for (i = minLen; i < maxLen; i++) { + pp += temp[i]; + /* We read the largest possible symbol size and then unget bits + after determining how many we need, and those extra bits could + be set to anything. (They're noise from future symbols.) At + each level we're really only interested in the first few bits, + so here we set all the trailing to-be-ignored bits to 1 so they + don't affect the value>limit[length] comparison. */ + hufGroup.limit[i] = pp - 1; + pp <<= 1; + t += temp[i]; + hufGroup.base[i + 1] = pp - t; + } + hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ + hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; + hufGroup.base[minLen] = 0; + } + /* We've finished reading and digesting the block header. Now read this + block's huffman coded symbols from the file and undo the huffman coding + and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { + /* Initialize symbol occurrence counters and symbol Move To Front table */ + var byteCount = new Uint32Array(256); + for (i = 0; i < 256; i++) + mtfSymbol[i] = i; + /* Loop through compressed symbols. */ + var runPos = 0, dbufCount = 0, selector = 0, uc; + var dbuf = this.dbuf = new Uint32Array(this.dbufSize); + symCount = 0; + for (;;) { + /* Determine which huffman coding group to use. */ + if (!(symCount--)) { + symCount = GROUP_SIZE - 1; + if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } + hufGroup = groups[selectors[selector++]]; + } + /* Read next huffman-coded symbol. */ + i = hufGroup.minLen; + j = reader.read(i); + for (;;i++) { + if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } + if (j <= hufGroup.limit[i]) + break; + j = (j << 1) | reader.read(1); + } + /* Huffman decode value to get nextSym (with bounds checking) */ + j -= hufGroup.base[i]; + if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } + var nextSym = hufGroup.permute[j]; + /* We have now decoded the symbol, which indicates either a new literal + byte, or a repeated run of the most recent literal byte. First, + check if nextSym indicates a repeated run, and if so loop collecting + how many times to repeat the last literal. */ + if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { + /* If this is the start of a new run, zero out counter */ + if (!runPos){ + runPos = 1; + t = 0; + } + /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at + each bit position, add 1 or 2 instead. For example, + 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. + You can make any bit pattern that way using 1 less symbol than + the basic or 0/1 method (except all bits 0, which would use no + symbols, but a run of length 0 doesn't mean anything in this + context). Thus space is saved. */ + if (nextSym === SYMBOL_RUNA) + t += runPos; + else + t += 2 * runPos; + runPos <<= 1; continue; } - - if (Qprime.eq(Q)) - return i; + /* When we hit the first non-run symbol after a run, we now know + how many times to repeat the last literal, so append that many + copies to our buffer of decoded symbols (dbuf) now. (The last + literal used is the one at the head of the mtfSymbol array.) */ + if (runPos){ + runPos = 0; + if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } + uc = symToByte[mtfSymbol[0]]; + byteCount[uc] += t; + while (t--) + dbuf[dbufCount++] = uc; + } + /* Is this the terminating symbol? */ + if (nextSym > symTotal) + break; + /* At this point, nextSym indicates a new literal character. Subtract + one to get the position in the MTF array at which this literal is + currently to be found. (Note that the result can't be -1 or 0, + because 0 and 1 are RUNA and RUNB. But another instance of the + first symbol in the mtf array, position 0, would have been handled + as part of a run above. Therefore 1 unused mtf position minus + 2 non-literal nextSym values equals -1.) */ + if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } + i = nextSym - 1; + uc = mtf(mtfSymbol, i); + uc = symToByte[uc]; + /* We have our literal byte. Save it into dbuf. */ + byteCount[uc]++; + dbuf[dbufCount++] = uc; } - throw new Error('Unable to find valid recovery factor'); - }; - - var assert$8 = utils_1$1.assert; - var parseBytes = utils_1$1.parseBytes; - var cachedProperty = utils_1$1.cachedProperty; - - /** - * @param {EDDSA} eddsa - instance - * @param {Object} params - public/private key parameters - * - * @param {Array} [params.secret] - secret seed bytes - * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) - * @param {Array} [params.pub] - public key point encoded as bytes - * - */ - function KeyPair$1(eddsa, params) { - this.eddsa = eddsa; - if (params.hasOwnProperty('secret')) - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else { - this._pubBytes = parseBytes(params.pub); - if (this._pubBytes && this._pubBytes.length === 33 && - this._pubBytes[0] === 0x40) - this._pubBytes = this._pubBytes.slice(1, 33); - if (this._pubBytes && this._pubBytes.length !== 32) - throw new Error('Unknown point compression format'); - } - } - - KeyPair$1.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$1) - return pub; - return new KeyPair$1(eddsa, { pub: pub }); - }; - - KeyPair$1.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$1) - return secret; - return new KeyPair$1(eddsa, { secret: secret }); - }; - - KeyPair$1.prototype.secret = function secret() { - return this._secret; - }; - - cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); - - cachedProperty(KeyPair$1, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); - - cachedProperty(KeyPair$1, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; - }); - - cachedProperty(KeyPair$1, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); - - cachedProperty(KeyPair$1, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); - - cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); - - KeyPair$1.prototype.sign = function sign(message) { - assert$8(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); - }; - - KeyPair$1.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; - - KeyPair$1.prototype.getSecret = function getSecret(enc) { - assert$8(this._secret, 'KeyPair is public only'); - return utils_1$1.encode(this.secret(), enc); - }; - - KeyPair$1.prototype.getPublic = function getPublic(enc, compact) { - return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); - }; - - var key$1 = KeyPair$1; - - var assert$9 = utils_1$1.assert; - var cachedProperty$1 = utils_1$1.cachedProperty; - var parseBytes$1 = utils_1$1.parseBytes; - - /** - * @param {EDDSA} eddsa - eddsa instance - * @param {Array|Object} sig - - * @param {Array|Point} [sig.R] - R point as Point or bytes - * @param {Array|bn} [sig.S] - S scalar as bn or bytes - * @param {Array} [sig.Rencoded] - R point encoded - * @param {Array} [sig.Sencoded] - S scalar encoded - */ - function Signature$2(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; + /* At this point, we've read all the huffman-coded symbols (and repeated + runs) for this block from the input stream, and decoded them into the + intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. + Now undo the Burrows-Wheeler transform on dbuf. + See http://dogma.net/markn/articles/bwt/bwt.htm + */ + if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } + /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ + j = 0; + for (i = 0; i < 256; i++) { + k = j + byteCount[i]; + byteCount[i] = j; + j = k; } + /* Figure out what order dbuf would be in if we sorted it. */ + for (i = 0; i < dbufCount; i++) { + uc = dbuf[i] & 0xff; + dbuf[byteCount[uc]] |= (i << 8); + byteCount[uc]++; + } + /* Decode first byte by hand to initialize "previous" byte. Note that it + doesn't get output, and if the first three characters are identical + it doesn't qualify as a run (hence writeRunCountdown=5). */ + var pos = 0, current = 0, run = 0; + if (dbufCount) { + pos = dbuf[origPointer]; + current = (pos & 0xff); + pos >>= 8; + run = -1; + } + this.writePos = pos; + this.writeCurrent = current; + this.writeCount = dbufCount; + this.writeRun = run; - assert$9(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof bn) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; - } - - cachedProperty$1(Signature$2, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); - - cachedProperty$1(Signature$2, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); - - cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); - - cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); - - Signature$2.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; - - Signature$2.prototype.toHex = function toHex() { - return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase(); - }; - - var signature$2 = Signature$2; - - var assert$a = utils_1$1.assert; - var parseBytes$2 = utils_1$1.parseBytes; - - - - function EDDSA(curve) { - assert$a(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = curves_1[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash_1.sha512; - } - - var eddsa$1 = EDDSA; - - /** - * @param {Array|String} message - message bytes - * @param {Array|String|KeyPair} secret - secret bytes or a keypair - * @returns {Signature} - signature - */ - EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes$2(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); + return true; /* more blocks to come */ }; - - /** - * @param {Array} message - message bytes - * @param {Array|String|Signature} sig - sig bytes - * @param {Array|String|Point|KeyPair} pub - public key - * @returns {Boolean} - true if public key matches sig of message + /* Undo burrows-wheeler transform on intermediate buffer to produce output. + If start_bunzip was initialized with out_fd=-1, then up to len bytes of + data are written to outbuf. Return value is number of bytes written or + error (all errors are negative numbers). If out_fd!=-1, outbuf and len + are ignored, data is written to out_fd and return is RETVAL_OK or error. */ - EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes$2(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); - }; - - EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n); - }; + Bunzip.prototype._read_bunzip = function(outputBuffer, len) { + var copies, previous, outbyte; + /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully + decoded, which results in this returning RETVAL_LAST_BLOCK, also + equal to -1... Confusing, I'm returning 0 here to indicate no + bytes written into the buffer */ + if (this.writeCount < 0) { return 0; } + var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; + var dbufCount = this.writeCount; this.outputsize; + var run = this.writeRun; - EDDSA.prototype.keyPair = function keyPair(options) { - return new key$1(this, options); + while (dbufCount) { + dbufCount--; + previous = current; + pos = dbuf[pos]; + current = pos & 0xff; + pos >>= 8; + if (run++ === 3){ + copies = current; + outbyte = previous; + current = -1; + } else { + copies = 1; + outbyte = current; + } + this.blockCRC.updateCRCRun(outbyte, copies); + while (copies--) { + this.outputStream.writeByte(outbyte); + this.nextoutput++; + } + if (current != previous) + run = 0; + } + this.writeCount = dbufCount; + // check CRC + if (this.blockCRC.getCRC() !== this.targetBlockCRC) { + _throw(Err.DATA_ERROR, "Bad block CRC "+ + "(got "+this.blockCRC.getCRC().toString(16)+ + " expected "+this.targetBlockCRC.toString(16)+")"); + } + return this.nextoutput; }; - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return key$1.fromPublic(this, pub); + var coerceInputStream = function(input) { + if ('readByte' in input) { return input; } + var inputStream = new Stream(); + inputStream.pos = 0; + inputStream.readByte = function() { return input[this.pos++]; }; + inputStream.seek = function(pos) { this.pos = pos; }; + inputStream.eof = function() { return this.pos >= input.length; }; + return inputStream; }; - - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return key$1.fromSecret(this, secret); + var coerceOutputStream = function(output) { + var outputStream = new Stream(); + var resizeOk = true; + if (output) { + if (typeof(output)==='number') { + outputStream.buffer = new Uint8Array(output); + resizeOk = false; + } else if ('writeByte' in output) { + return output; + } else { + outputStream.buffer = output; + resizeOk = false; + } + } else { + outputStream.buffer = new Uint8Array(16384); + } + outputStream.pos = 0; + outputStream.writeByte = function(_byte) { + if (resizeOk && this.pos >= this.buffer.length) { + var newBuffer = new Uint8Array(this.buffer.length*2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + this.buffer[this.pos++] = _byte; + }; + outputStream.getBuffer = function() { + // trim buffer + if (this.pos !== this.buffer.length) { + if (!resizeOk) + throw new TypeError('outputsize does not match decoded input'); + var newBuffer = new Uint8Array(this.pos); + newBuffer.set(this.buffer.subarray(0, this.pos)); + this.buffer = newBuffer; + } + return this.buffer; + }; + outputStream._coerced = true; + return outputStream; }; - EDDSA.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.curve.n.toArray() - }); + /* Static helper functions */ + // 'input' can be a stream or a buffer + // 'output' can be a stream or a buffer or a number (buffer size) + const decode = function(input, output, multistream) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); - return this.keyFromSecret(drbg.generate(32)); + var bz = new Bunzip(inputStream, outputStream); + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + if (bz._init_block()) { + bz._read_bunzip(); + } else { + var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) + if (targetStreamCRC !== bz.streamCRC) { + _throw(Err.DATA_ERROR, "Bad stream CRC "+ + "(got "+bz.streamCRC.toString(16)+ + " expected "+targetStreamCRC.toString(16)+")"); + } + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + } else break; + } + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; + const decodeBlock = function(input, pos, output) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + var bz = new Bunzip(inputStream, outputStream); + bz.reader.seek(pos); + /* Fill the decode buffer for the block */ + var moreBlocks = bz._get_next_block(); + if (moreBlocks) { + /* Init the CRC for writing */ + bz.blockCRC = new CRC32(); - EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof signature$2) - return sig; - return new signature$2(this, sig); - }; + /* Zero this so the current byte from before the seek is not written */ + bz.writeCopies = 0; - /** - * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 - * - * EDDSA defines methods for encoding and decoding points and integers. These are - * helper convenience methods, that pass along to utility functions implied - * parameters. - * - */ - EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; + /* Decompress the block and write to stdout */ + bz._read_bunzip(); + // XXX keep writing? + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; + /* Reads bzip2 file from stream or buffer `input`, and invoke + * `callback(position, size)` once for each bzip2 block, + * where position gives the starting position (in *bits*) + * and size gives uncompressed size of the block (in *bytes*). */ + const table = function(input, callback, multistream) { + // make a stream from a buffer, if necessary + var inputStream = new Stream(); + inputStream.delegate = coerceInputStream(input); + inputStream.pos = 0; + inputStream.readByte = function() { + this.pos++; + return this.delegate.readByte(); + }; + if (inputStream.delegate.eof) { + inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); + } + var outputStream = new Stream(); + outputStream.pos = 0; + outputStream.writeByte = function() { this.pos++; }; - EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils_1$1.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils_1$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); - }; + var bz = new Bunzip(inputStream, outputStream); + var blockSize = bz.dbufSize; + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; - EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); - }; + var position = inputStream.pos*8 + bz.reader.bitOffset; + if (bz.reader.hasByte) { position -= 8; } - EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils_1$1.intFromLE(bytes); + if (bz._init_block()) { + var start = outputStream.pos; + bz._read_bunzip(); + callback(position, outputStream.pos - start); + } else { + bz.reader.read(32); // (but we ignore the crc) + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + console.assert(bz.dbufSize === blockSize, + "shouldn't change block size within multistream file"); + } else break; + } + } }; - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; + var lib = { + Bunzip, + Stream, + Err, + decode, + decodeBlock, + table }; - var elliptic_1 = createCommonjsModule(function (module, exports) { - - var elliptic = exports; - - elliptic.utils = utils_1$1; - elliptic.rand = brorand; - elliptic.curve = curve_1; - elliptic.curves = curves_1; - - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa$1; - }); - - var elliptic$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': elliptic_1, - __moduleExports: elliptic_1 - }); + var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null + }, [lib]); exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket; exports.CleartextMessage = CleartextMessage; @@ -44075,6 +28573,7 @@ var openpgp = (function (exports) { exports.Message = Message; exports.OnePassSignaturePacket = OnePassSignaturePacket; exports.PacketList = PacketList; + exports.PaddingPacket = PaddingPacket; exports.PrivateKey = PrivateKey; exports.PublicKey = PublicKey; exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket; @@ -44096,15 +28595,15 @@ var openpgp = (function (exports) { exports.config = config; exports.createCleartextMessage = createCleartextMessage; exports.createMessage = createMessage; - exports.decrypt = decrypt$5; + exports.decrypt = decrypt; exports.decryptKey = decryptKey; exports.decryptSessionKeys = decryptSessionKeys; - exports.encrypt = encrypt$5; + exports.encrypt = encrypt; exports.encryptKey = encryptKey; exports.encryptSessionKey = encryptSessionKey; exports.enums = enums; exports.generateKey = generateKey; - exports.generateSessionKey = generateSessionKey$1; + exports.generateSessionKey = generateSessionKey; exports.readCleartextMessage = readCleartextMessage; exports.readKey = readKey; exports.readKeys = readKeys; @@ -44114,12 +28613,10 @@ var openpgp = (function (exports) { exports.readSignature = readSignature; exports.reformatKey = reformatKey; exports.revokeKey = revokeKey; - exports.sign = sign$6; + exports.sign = sign; exports.unarmor = unarmor; - exports.verify = verify$6; - - Object.defineProperty(exports, '__esModule', { value: true }); + exports.verify = verify; return exports; -}({})); +})({}); diff --git a/app/node_modules/openpgp/dist/openpgp.min.js b/app/node_modules/openpgp/dist/openpgp.min.js index a4ec44ed6..ba10ccc82 100644 --- a/app/node_modules/openpgp/dist/openpgp.min.js +++ b/app/node_modules/openpgp/dist/openpgp.min.js @@ -1,17 +1,16 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -var openpgp=function(e){"use strict";const t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r=Symbol("doneWritingPromise"),i=Symbol("doneWritingResolve"),n=Symbol("doneWritingReject"),a=Symbol("readingIndex");class s extends Array{constructor(){super(),this[r]=new Promise(((e,t)=>{this[i]=e,this[n]=t})),this[r].catch((()=>{}))}}function o(e){return e&&e.getReader&&Array.isArray(e)}function c(e){if(!o(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}s.prototype.getReader=function(){return void 0===this[a]&&(this[a]=0),{read:async()=>(await this[r],this[a]===this.length?{value:void 0,done:!0}:{value:this[this[a]++],done:!1})}},s.prototype.readToEnd=async function(e){await this[r];const t=e(this.slice(this[a]));return this.length=0,t},s.prototype.clone=function(){const e=new s;return e[r]=this[r].then((()=>{e.push(...this)})),e},c.prototype.write=async function(e){this.stream.push(e)},c.prototype.close=async function(){this.stream[i]()},c.prototype.abort=async function(e){return this.stream[n](e),e},c.prototype.releaseLock=function(){};const u="object"==typeof t.process&&"object"==typeof t.process.versions,h=u&&void 0;function d(e){return o(e)?"array":t.ReadableStream&&t.ReadableStream.prototype.isPrototypeOf(e)?"web":A&&A.prototype.isPrototypeOf(e)?"ponyfill":h&&h.prototype.isPrototypeOf(e)?"node":!(!e||!e.getReader)&&"web-like"}function f(e){return Uint8Array.prototype.isPrototypeOf(e)}function l(e){if(1===e.length)return e[0];let t=0;for(let r=0;r{t||(p.isBuffer(i)&&(i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),r.enqueue(i),e.pause())})),e.on("end",(()=>{t||r.close()})),e.on("error",(e=>r.error(e)))},pull(){e.resume()},cancel(r){t=!0,e.destroy(r)}})};class e extends y{constructor(e,t){super(t),this._reader=D(e)}async _read(e){try{for(;;){const{done:e,value:t}=await this._reader.read();if(e){this.push(null);break}if(!this.push(t))break}}catch(e){this.destroy(e)}}async _destroy(e,t){this._reader.cancel(e).then(t,t)}}g=function(t,r){return new e(t,r)}}const m=new WeakSet,w=Symbol("externalBuffer");function v(e){if(this.stream=e,e[w]&&(this[w]=e[w].slice()),o(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=async()=>{})}let t=d(e);if("node"===t&&(e=b(e)),t){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let r=!1;this._read=async()=>r||m.has(e)?{value:void 0,done:!0}:(r=!0,{value:e,done:!1}),this._releaseLock=()=>{if(r)try{m.add(e)}catch(e){}}}v.prototype.read=async function(){if(this[w]&&this[w].length){return{done:!1,value:this[w].shift()}}return this._read()},v.prototype.releaseLock=function(){this[w]&&(this.stream[w]=this[w]),this._releaseLock()},v.prototype.cancel=function(e){return this._cancel(e)},v.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:i}=await this.read();if(i+="",r)return t.length?C(t):void 0;const n=i.indexOf("\n")+1;n&&(e=C(t.concat(i.substr(0,n))),t=[]),n!==i.length&&t.push(i.substr(n))}return this.unshift(...t),e},v.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(N(t,1)),r},v.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:i,value:n}=await this.read();if(i)return t.length?C(t):void 0;if(t.push(n),r+=n.length,r>=e){const r=C(t);return this.unshift(N(r,e)),N(r,0,e)}}},v.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},v.prototype.unshift=function(...e){this[w]||(this[w]=[]),1===e.length&&f(e[0])&&this[w].length&&e[0].length&&this[w][0].byteOffset>=e[0].length?this[w][0]=new Uint8Array(this[w][0].buffer,this[w][0].byteOffset-e[0].length,this[w][0].byteLength+e[0].length):this[w].unshift(...e.filter((e=>e&&e.length)))},v.prototype.readToEnd=async function(e=C){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};let _,k,{ReadableStream:A,WritableStream:S,TransformStream:E}=t;async function P(){if(E)return;const[e,r]=await Promise.all([Promise.resolve().then((function(){return yp})),Promise.resolve().then((function(){return Tp}))]);({ReadableStream:A,WritableStream:S,TransformStream:E}=e);const{createReadableStreamWrapper:i}=r;t.ReadableStream&&A!==t.ReadableStream&&(_=i(A),k=i(t.ReadableStream))}const x=u&&void 0;function M(e){let t=d(e);return"node"===t?b(e):"web"===t&&_?_(e):t?e:new A({start(t){t.enqueue(e),t.close()}})}function K(e){if(d(e))return e;const t=new s;return(async()=>{const r=U(t);await r.write(e),await r.close()})(),t}function C(e){return e.some((e=>d(e)&&!o(e)))?function(e){e=e.map(M);const t=B((async function(e){await Promise.all(i.map((t=>H(t,e))))}));let r=Promise.resolve();const i=e.map(((i,n)=>z(i,((i,a)=>(r=r.then((()=>R(i,t.writable,{preventClose:n!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>o(e)))?function(e){const t=new s;let r=Promise.resolve();return e.forEach(((i,n)=>(r=r.then((()=>R(i,t,{preventClose:n!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):x&&x.isBuffer(e[0])?x.concat(e):l(e)}function D(e){return new v(e)}function U(e){return new c(e)}async function R(e,t,{preventClose:r=!1,preventAbort:i=!1,preventCancel:n=!1}={}){if(d(e)&&!o(e)){e=M(e);try{if(e[w]){const r=U(t);for(let t=0;t{t=e,r=i})),t=null,r=null)},close:i.close.bind(i),abort:i.error.bind(i)})}}function T(e,t=(()=>{}),r=(()=>{})){if(o(e)){const i=new s;return(async()=>{const n=U(i);try{const i=await j(e),a=t(i),s=r();let o;o=void 0!==a&&void 0!==s?C([a,s]):void 0!==a?a:s,await n.write(o),await n.close()}catch(e){await n.abort(e)}})(),i}if(d(e))return I(e,{async transform(e,r){try{const i=await t(e);void 0!==i&&r.enqueue(i)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const i=t(e),n=r();return void 0!==i&&void 0!==n?C([i,n]):void 0!==i?i:n}function z(e,t){if(d(e)&&!o(e)){let r;const i=new E({start(e){r=e}}),n=R(e,i.writable),a=B((async function(e){r.error(e),await n,await new Promise(setTimeout)}));return t(i.readable,a.writable),a.readable}e=K(e);const r=new s;return t(e,r),r}function q(e,t){let r;const i=z(e,((e,n)=>{const a=D(e);a.remainder=()=>(a.releaseLock(),R(e,n),i),r=t(a)}));return r}function F(e){if(o(e))return e.clone();if(d(e)){const t=function(e){if(o(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(d(e)){const t=M(e).tee();return t[0][w]=t[1][w]=e[w],t}return[N(e),N(e)]}(e);return L(e,t[0]),t[1]}return N(e)}function O(e){return o(e)?F(e):d(e)?new A({start(t){const r=z(e,(async(e,r)=>{const i=D(e),n=U(r);try{for(;;){await n.ready;const{done:e,value:r}=await i.read();if(e){try{t.close()}catch(e){}return void await n.close()}try{t.enqueue(r)}catch(e){}await n.write(r)}}catch(e){t.error(e),await n.abort(e)}}));L(e,r)}}):N(e)}function L(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,i])=>{"constructor"!==r&&(i.value?i.value=i.value.bind(t):i.get=i.get.bind(t),Object.defineProperty(e,r,i))}))}function N(e,t=0,r=1/0){if(o(e))throw Error("Not implemented");if(d(e)){if(t>=0&&r>=0){let i=0;return I(e,{transform(e,n){i=t&&n.enqueue(N(e,Math.max(t-i,0),r-i)),i+=e.length):n.terminate()}})}if(t<0&&(r<0||r===1/0)){let i=[];return T(e,(e=>{e.length>=-t?i=[e]:i.push(e)}),(()=>N(C(i),t,r)))}if(0===t&&r<0){let i;return T(e,(e=>{const n=i?C([i,e]):e;if(n.length>=-r)return i=N(n,r),N(n,t,r);i=n}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),W((async()=>N(await j(e),t,r)))}return e[w]&&(e=C(e[w].concat([e]))),!f(e)||x&&x.isBuffer(e)?e.slice(t,r):(r===1/0&&(r=e.length),e.subarray(t,r))}async function j(e,t=C){return o(e)?e.readToEnd(t):d(e)?D(e).readToEnd(t):e}async function H(e,t){if(d(e)){if(e.cancel)return e.cancel(t);if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function W(e){const t=new s;return(async()=>{const r=U(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}class G{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");if(e instanceof Uint8Array){const t=e,r=Array(t.length);for(let e=0;eBigInt(0);){const e=r&BigInt(1);r>>=BigInt(1);const a=n*i%t.value;n=e?a:n,i=i*i%t.value}return new G(n)}modInv(e){const{gcd:t,x:r}=this._egcd(e);if(!t.isOne())throw Error("Inverse does not exist");return r.add(e).mod(e)}_egcd(e){let t=BigInt(0),r=BigInt(1),i=BigInt(1),n=BigInt(0),a=this.value;for(e=e.value;e!==BigInt(0);){const s=a/e;let o=t;t=i-s*t,i=o,o=r,r=n-s*r,n=o,o=e,e=a%e,a=o}return{x:new G(i),y:new G(n),gcd:new G(a)}}gcd(e){let t=this.value;for(e=e.value;e!==BigInt(0);){const r=e;e=t%e,t=r}return new G(t)}ileftShift(e){return this.value<<=e.value,this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value>>=e.value,this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value===e.value}lt(e){return this.valuee.value}gte(e){return this.value>=e.value}isZero(){return this.value===BigInt(0)}isOne(){return this.value===BigInt(1)}isNegative(){return this.valueNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return e}getBit(e){return(this.value>>BigInt(e)&BigInt(1))===BigInt(0)?0:1}bitLength(){const e=new G(0),t=new G(1),r=new G(-1),i=this.isNegative()?r:e;let n=1;const a=this.clone();for(;!a.irightShift(t).equal(i);)n++;return n}byteLength(){const e=new G(0),t=new G(-1),r=this.isNegative()?t:e,i=new G(8);let n=1;const a=this.clone();for(;!a.irightShift(i).equal(r);)n++;return n}toUint8Array(e="be",t){let r=this.value.toString(16);r.length%2==1&&(r="0"+r);const i=r.length/2,n=new Uint8Array(t||i),a=t?t-i:0;let s=0;for(;s"undefined"!=typeof BigInt;const $=Symbol("byValue");var Z={curve:{p256:"p256","P-256":"p256",secp256r1:"p256",prime256v1:"p256","1.2.840.10045.3.1.7":"p256","2a8648ce3d030107":"p256","2A8648CE3D030107":"p256",p384:"p384","P-384":"p384",secp384r1:"p384","1.3.132.0.34":"p384","2b81040022":"p384","2B81040022":"p384",p521:"p521","P-521":"p521",secp521r1:"p521","1.3.132.0.35":"p521","2b81040023":"p521","2B81040023":"p521",secp256k1:"secp256k1","1.3.132.0.10":"secp256k1","2b8104000a":"secp256k1","2B8104000A":"secp256k1",ed25519Legacy:"ed25519",ED25519:"ed25519",ed25519:"ed25519",Ed25519:"ed25519","1.3.6.1.4.1.11591.15.1":"ed25519","2b06010401da470f01":"ed25519","2B06010401DA470F01":"ed25519",curve25519Legacy:"curve25519",X25519:"curve25519",cv25519:"curve25519",curve25519:"curve25519",Curve25519:"curve25519","1.3.6.1.4.1.3029.1.5.1":"curve25519","2b060104019755010501":"curve25519","2B060104019755010501":"curve25519",brainpoolP256r1:"brainpoolP256r1","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1","2b2403030208010107":"brainpoolP256r1","2B2403030208010107":"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1","2b240303020801010b":"brainpoolP384r1","2B240303020801010B":"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1","2b240303020801010d":"brainpoolP512r1","2B240303020801010D":"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,ed25519Legacy:22,eddsa:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuer:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[$]||(e[$]=[],Object.entries(e).forEach((([t,r])=>{e[$][r]=t}))),void 0!==e[$][t])return e[$][t];throw Error("Invalid enum value.")}};const X=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),Y={isString:function(e){return"string"==typeof e||e instanceof String},isArray:function(e){return e instanceof Array},isUint8Array:f,isStream:d,readNumber:function(e){let t=0;for(let r=0;r>8*(t-i-1)&255;return r},readDate:function(e){const t=Y.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return Y.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return e.subarray(2,2+t)},leftPad(e,t){const r=new Uint8Array(t),i=t-e.length;return r.set(e,i),r},uint8ArrayToMPI:function(e){const t=Y.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),i=new Uint8Array([(65280&t)>>8,255&t]);return Y.concatUint8Array([i,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t=[],r=e.length;let i,n=0;for(;n{if(!Y.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return T(e,r,(()=>r(new Uint8Array,!0)))},concat:C,concatUint8Array:l,equalsUint8Array:function(e,t){if(!Y.isUint8Array(e)||!Y.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let i=0;i>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){return void 0!==t&&t.crypto&&t.crypto.subtle},getBigInteger:async function(){if(V())return G;{const{default:e}=await Promise.resolve().then((function(){return Lp}));return e}},getNodeCrypto:function(){},getNodeZlib:function(){},getNodeBuffer:function(){return{}.Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return(void 0).cpus().length},isEmailAddress:function(e){if(!Y.isString(e))return!1;return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/.test(e)},canonicalizeEOL:function(e){let t=!1;return T(e,(e=>{let r;t&&(e=Y.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const i=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&i.push(r);if(!i.length)return e;const n=new Uint8Array(e.length+i.length);let a=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return T(e,(e=>{let r;13===(e=t&&10!==e[0]?Y.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let i=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const n=r-(10===e[r]?1:0);t&&e.copyWithin(i,t,n),i+=n-t}return e.subarray(0,i)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let i;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){i=e}}))),r(i)}))},selectUint8Array:function(e,t,r){const i=Math.max(t.length,r.length),n=new Uint8Array(i);let a=0;for(let i=0;i{t=Y.concatUint8Array([t,e]);const r=[],i=Math.floor(t.length/45),n=45*i,a=J(t.subarray(0,n));for(let e=0;et.length?J(t)+"\n":""))}function re(e){let t="";return T(e,(e=>{t+=e;let r=0;const i=[" ","\t","\r","\n"];for(let e=0;e0&&(n-r)%4!=0;n--)i.includes(t[n])&&r--;const a=ee(t.substr(0,n));return t=t.substr(n),a}),(()=>ee(t)))}function ie(e){return re(e.replace(/-/g,"+").replace(/_/g,"/"))}function ne(e,t){let r=te(e).replace(/[\r\n]/g,"");return t&&(r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,"")),r}Q?(J=e=>Q.from(e).toString("base64"),ee=e=>{const t=Q.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(J=e=>btoa(Y.uint8ArrayToString(e)),ee=e=>Y.stringToUint8Array(atob(e)));var ae={preferredHashAlgorithm:Z.hash.sha256,preferredSymmetricAlgorithm:Z.symmetric.aes256,preferredCompressionAlgorithm:Z.compression.uncompressed,deflateLevel:6,aeadProtect:!1,preferredAEADAlgorithm:Z.aead.eax,aeadChunkSizeByte:12,v5Keys:!1,s2kIterationCountByte:224,allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,checksumRequired:!1,minRSABits:2047,passwordCollisionCheck:!1,revocationsExpire:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([Z.symmetric.aes128,Z.symmetric.aes192,Z.symmetric.aes256]),minBytesForWebCrypto:1e3,ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 5.11.2",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],useIndutnyElliptic:!0,rejectHashAlgorithms:new Set([Z.hash.md5,Z.hash.ripemd]),rejectMessageHashAlgorithms:new Set([Z.hash.md5,Z.hash.ripemd,Z.hash.sha1]),rejectPublicKeyAlgorithms:new Set([Z.publicKey.elgamal,Z.publicKey.dsa]),rejectCurves:new Set([Z.curve.secp256k1])};function se(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?Z.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?Z.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?Z.armor.signed:/MESSAGE/.test(t[1])?Z.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?Z.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?Z.armor.privateKey:/SIGNATURE/.test(t[1])?Z.armor.signature:void 0}function oe(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function ce(e){return te(function(e){let t=13501623;return T(e,(e=>{const r=he?Math.floor(e.length/4):0,i=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^ue[1][t>>16&255]^ue[2][t>>8&255]^ue[3][t>>0&255];for(let i=4*r;i>8^ue[0][255&t^e[i]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e))}const ue=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(0!=(8388608&t)?8801531:0);ue[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)ue[1][e]=ue[0][e]>>8^ue[0][255&ue[0][e]];for(let e=0;e<=255;e++)ue[2][e]=ue[1][e]>>8^ue[0][255&ue[1][e]];for(let e=0;e<=255;e++)ue[3][e]=ue[2][e]>>8^ue[0][255&ue[2][e]];const he=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function de(e){for(let t=0;t=0&&i!==e.length-1&&(t=e.slice(0,i),r=e.slice(i+1).substr(0,4)),{body:t,checksum:r}}function le(e,t=ae){return new Promise((async(r,i)=>{try{const n=/^-----[^-]+-----$/m,a=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const o=[];let c,u,h,d=o,f=[],l=re(z(e,(async(e,t)=>{const p=D(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=Y.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(c)u||2!==s||(n.test(e)?(f=f.join("\r\n"),u=!0,de(d),d=[],c=!1):f.push(e.replace(/^- /,"")));else if(n.test(e)&&i(Error("Mandatory blank line missing between armor headers and armor data")),a.test(e)){if(de(d),c=!0,u||2!==s){r({text:f,data:l,headers:o,type:s});break}}else d.push(e);else n.test(e)&&(s=se(e))}}catch(e){return void i(e)}const y=U(t);try{for(;;){await y.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=Y.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=fe(t[0].slice(0,-1));h=i.checksum,await y.write(i.body);break}await y.write(r)}await y.ready,await y.close()}catch(e){await y.abort(e)}})));l=z(l,(async(e,r)=>{const i=j(ce(O(e)));i.catch((()=>{})),await R(e,r,{preventClose:!0});const n=U(r);try{const e=(await i).replace("\n","");if(h!==e&&(h||t.checksumRequired))throw Error("Ascii armor integrity check failed");await n.ready,await n.close()}catch(e){await n.abort(e)}}))}catch(e){i(e)}})).then((async e=>(o(e.data)&&(e.data=await j(e.data)),e)))}function pe(e,t,r,i,n,a=ae){let s,o;e===Z.armor.signed&&(s=t.text,o=t.hash,t=t.data);const c=O(t),u=[];switch(e){case Z.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+i+"-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP MESSAGE, PART "+r+"/"+i+"-----\n");break;case Z.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case Z.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push("Hash: "+o+"\n\n"),u.push(s.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP SIGNATURE-----\n");break;case Z.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP MESSAGE-----\n");break;case Z.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case Z.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case Z.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(oe(n,a)),u.push(te(t)),u.push("=",ce(c)),u.push("-----END PGP SIGNATURE-----\n")}return Y.concat(u)}class ye{constructor(){this.bytes=""}read(e){return this.bytes=Y.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return Y.stringToUint8Array(this.bytes)}toHex(){return Y.uint8ArrayToHex(Y.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new ye;return t.read(Y.hexToUint8Array(e)),t}static wildcard(){const e=new ye;return e.read(new Uint8Array(8)),e}}var be=function(){var e,t,r=!1;function i(r,i){var n=e[(t[r]+t[i])%255];return 0!==r&&0!==i||(n=0),n}var n,a,s,o,c=!1;function u(){function u(r){var i,n,a;for(n=a=function(r){var i=e[255-t[r]];return 0===r&&(i=0),i}(r),i=0;i<4;i++)a^=n=255&(n<<1|n>>>7);return a^=99}r||function(){e=[],t=[];var i,n,a=1;for(i=0;i<255;i++)e[i]=a,n=128&a,a<<=1,a&=255,128===n&&(a^=27),a^=e[i],t[e[i]]=i;e[255]=e[0],t[0]=0,r=!0}(),n=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var h=0;h<256;h++){var d=u(h);n[h]=d,a[d]=h,s[0][h]=i(2,d)<<24|d<<16|d<<8|i(3,d),o[0][d]=i(14,h)<<24|i(9,h)<<16|i(13,h)<<8|i(11,h);for(var f=1;f<4;f++)s[f][h]=s[f-1][h]>>>8|s[f-1][h]<<24,o[f][d]=o[f-1][d]>>>8|o[f-1][d]<<24}c=!0}var h=function(e,t){c||u();var r=new Uint32Array(t);r.set(n,512),r.set(a,768);for(var i=0;i<4;i++)r.set(s[i],4096+1024*i>>2),r.set(o[i],8192+1024*i>>2);var h=function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0;var S=new e.Uint32Array(r),E=new e.Uint8Array(r);function P(e,t,r,o,c,u,h,d){e=e|0;t=t|0;r=r|0;o=o|0;c=c|0;u=u|0;h=h|0;d=d|0;var f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;f=r|0x400,l=r|0x800,p=r|0xc00;c=c^S[(e|0)>>2],u=u^S[(e|4)>>2],h=h^S[(e|8)>>2],d=d^S[(e|12)>>2];for(w=16;(w|0)<=o<<4;w=w+16|0){y=S[(r|c>>22&1020)>>2]^S[(f|u>>14&1020)>>2]^S[(l|h>>6&1020)>>2]^S[(p|d<<2&1020)>>2]^S[(e|w|0)>>2],b=S[(r|u>>22&1020)>>2]^S[(f|h>>14&1020)>>2]^S[(l|d>>6&1020)>>2]^S[(p|c<<2&1020)>>2]^S[(e|w|4)>>2],g=S[(r|h>>22&1020)>>2]^S[(f|d>>14&1020)>>2]^S[(l|c>>6&1020)>>2]^S[(p|u<<2&1020)>>2]^S[(e|w|8)>>2],m=S[(r|d>>22&1020)>>2]^S[(f|c>>14&1020)>>2]^S[(l|u>>6&1020)>>2]^S[(p|h<<2&1020)>>2]^S[(e|w|12)>>2];c=y,u=b,h=g,d=m}i=S[(t|c>>22&1020)>>2]<<24^S[(t|u>>14&1020)>>2]<<16^S[(t|h>>6&1020)>>2]<<8^S[(t|d<<2&1020)>>2]^S[(e|w|0)>>2],n=S[(t|u>>22&1020)>>2]<<24^S[(t|h>>14&1020)>>2]<<16^S[(t|d>>6&1020)>>2]<<8^S[(t|c<<2&1020)>>2]^S[(e|w|4)>>2],a=S[(t|h>>22&1020)>>2]<<24^S[(t|d>>14&1020)>>2]<<16^S[(t|c>>6&1020)>>2]<<8^S[(t|u<<2&1020)>>2]^S[(e|w|8)>>2],s=S[(t|d>>22&1020)>>2]<<24^S[(t|c>>14&1020)>>2]<<16^S[(t|u>>6&1020)>>2]<<8^S[(t|h<<2&1020)>>2]^S[(e|w|12)>>2]}function x(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;P(0x0000,0x0800,0x1000,A,e,t,r,i)}function M(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var a=0;P(0x0400,0x0c00,0x2000,A,e,i,r,t);a=n,n=s,s=a}function K(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o^e,c^t,u^r,h^d);o=i,c=n,u=a,h=s}function C(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;var f=0;P(0x0400,0x0c00,0x2000,A,e,d,r,t);f=n,n=s,s=f;i=i^o,n=n^c,a=a^u,s=s^h;o=e,c=t,u=r,h=d}function D(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i=i^e,c=n=n^t,u=a=a^r,h=s=s^d}function U(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);i=i^e,n=n^t,a=a^r,s=s^d;o=e,c=t,u=r,h=d}function R(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i,c=n,u=a,h=s;i=i^e,n=n^t,a=a^r,s=s^d}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;P(0x0000,0x0800,0x1000,A,d,f,l,p);p=~m&p|m&p+1;l=~g&l|g&l+((p|0)==0);f=~b&f|b&f+((l|0)==0);d=~y&d|y&d+((f|0)==0);i=i^e;n=n^t;a=a^r;s=s^o}function B(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,a=0,s=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0;e=e^o,t=t^c,r=r^u,i=i^h;n=w|0,a=v|0,s=_|0,d=k|0;for(;(b|0)<128;b=b+1|0){if(n>>>31){f=f^e,l=l^t,p=p^r,y=y^i}n=n<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|d>>>31,d=d<<1;g=i&1;i=i>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(g)e=e^0xe1000000}o=f,c=l,u=p,h=y}function T(e){e=e|0;A=e}function z(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;i=e,n=t,a=r,s=o}function q(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;o=e,c=t,u=r,h=i}function F(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;d=e,f=t,l=r,p=i}function O(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;y=e,b=t,g=r,m=i}function L(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;p=~m&p|m&i,l=~g&l|g&r,f=~b&f|b&t,d=~y&d|y&e}function N(e){e=e|0;if(e&15)return-1;E[e|0]=i>>>24,E[e|1]=i>>>16&255,E[e|2]=i>>>8&255,E[e|3]=i&255,E[e|4]=n>>>24,E[e|5]=n>>>16&255,E[e|6]=n>>>8&255,E[e|7]=n&255,E[e|8]=a>>>24,E[e|9]=a>>>16&255,E[e|10]=a>>>8&255,E[e|11]=a&255,E[e|12]=s>>>24,E[e|13]=s>>>16&255,E[e|14]=s>>>8&255,E[e|15]=s&255;return 16}function j(e){e=e|0;if(e&15)return-1;E[e|0]=o>>>24,E[e|1]=o>>>16&255,E[e|2]=o>>>8&255,E[e|3]=o&255,E[e|4]=c>>>24,E[e|5]=c>>>16&255,E[e|6]=c>>>8&255,E[e|7]=c&255,E[e|8]=u>>>24,E[e|9]=u>>>16&255,E[e|10]=u>>>8&255,E[e|11]=u&255,E[e|12]=h>>>24,E[e|13]=h>>>16&255,E[e|14]=h>>>8&255,E[e|15]=h&255;return 16}function H(){x(0,0,0,0);w=i,v=n,_=a,k=s}function W(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){V[e&7](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);E[t|0]=i>>>24,E[t|1]=i>>>16&255,E[t|2]=i>>>8&255,E[t|3]=i&255,E[t|4]=n>>>24,E[t|5]=n>>>16&255,E[t|6]=n>>>8&255,E[t|7]=n&255,E[t|8]=a>>>24,E[t|9]=a>>>16&255,E[t|10]=a>>>8&255,E[t|11]=a&255,E[t|12]=s>>>24,E[t|13]=s>>>16&255,E[t|14]=s>>>8&255,E[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function G(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t&15)return-1;while((r|0)>=16){$[e&1](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);i=i+16|0,t=t+16|0,r=r-16|0}return i|0}var V=[x,M,K,C,D,U,R,I];var $=[K,B];return{set_rounds:T,set_state:z,set_iv:q,set_nonce:F,set_mask:O,set_counter:L,get_state:N,get_iv:j,gcm_init:H,cipher:W,mac:G}}({Uint8Array,Uint32Array},e,t);return h.set_key=function(e,t,i,a,s,c,u,d,f){var l=r.subarray(0,60),p=r.subarray(256,316);l.set([t,i,a,s,c,u,d,f]);for(var y=e,b=1;y<4*e+28;y++){var g=l[y-1];(y%e==0||8===e&&y%e==4)&&(g=n[g>>>24]<<24^n[g>>>16&255]<<16^n[g>>>8&255]<<8^n[255&g]),y%e==0&&(g=g<<8^g>>>24^b<<24,b=b<<1^(128&b?27:0)),l[y]=l[y-e]^g}for(var m=0;m=y-4?g:o[0][n[g>>>24]]^o[1][n[g>>>16&255]]^o[2][n[g>>>8&255]]^o[3][n[255&g]]}h.set_rounds(e+5)},h};return h.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},h.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},h.MAC={CBC:0,GCM:1},h.HEAP_DATA=16384,h}();function ge(e){return e instanceof Uint8Array}function me(e,t){const r=e?e.byteLength:t||65536;if(4095&r||r<=0)throw Error("heap size must be a positive integer and a multiple of 4096");return e=e||new Uint8Array(new ArrayBuffer(r))}function we(e,t,r,i,n){const a=e.length-t,s=ae+t.length),0),r=new Uint8Array(t);let i=0;for(let t=0;t>2,n.getUint32(0),n.getUint32(4),n.getUint32(8),n.getUint32(12),i>16?n.getUint32(16):0,i>16?n.getUint32(20):0,i>24?n.getUint32(24):0,i>24?n.getUint32(28):0),void 0!==t){if(16!==t.length)throw new ke("illegal iv size");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);r.set_iv(e.getUint32(0),e.getUint32(4),e.getUint32(8),e.getUint32(12))}else r.set_iv(0,0,0,0)}AES_Encrypt_process(e){if(!ge(e))throw new TypeError("data isn't of expected type");let{heap:t,asm:r}=this.acquire_asm(),i=be.ENC[this.mode],n=be.HEAP_DATA,a=this.pos,s=this.len,o=0,c=e.length||0,u=0,h=0,d=new Uint8Array(s+c&-16);for(;c>0;)h=we(t,a+s,e,o,c),s+=h,o+=h,c-=h,h=r.cipher(i,n+a,s),h&&d.set(t.subarray(a,a+h),u),u+=h,h0;)f=we(t,a+s,e,o,c),s+=f,o+=f,c-=f,f=r.cipher(i,n+a,s-(c?0:d)),f&&l.set(t.subarray(a,a+f),u),u+=f,f0){if(a%16){if(this.hasOwnProperty("padding"))throw new ke("data length must be a multiple of the block size");a+=16-a%16}if(t.cipher(r,i+n,a),this.hasOwnProperty("padding")&&this.padding){let t=e[n+s-1];if(t<1||t>16||t>s)throw new Ae("bad padding");let r=0;for(let i=t;i>1;i--)r|=t^e[n+s-i];if(r)throw new Ae("bad padding");s-=t}}const o=new Uint8Array(s);return s>0&&o.set(e.subarray(n,n+s)),this.pos=0,this.len=0,this.release_asm(),o}}class xe{static encrypt(e,t,r=!1){return new xe(t,r).encrypt(e)}static decrypt(e,t,r=!1){return new xe(t,r).decrypt(e)}constructor(e,t=!1,r){this.aes=r||new Pe(e,void 0,t,"ECB")}encrypt(e){return ve(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return ve(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}function Me(e){const t=function(e){const t=new xe(e);this.encrypt=function(e){return t.encrypt(e)},this.decrypt=function(e){return t.decrypt(e)}};return t.blockSize=t.prototype.blockSize=16,t.keySize=t.prototype.keySize=e/8,t}function Ke(e,t,r,i,n,a){const s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],u=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],h=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],d=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],f=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],l=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,y,b,g,m,w,v,_,k,A,S,E,P,x,M=0,K=t.length;const C=32===e.length?3:9;_=3===C?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e,t){const r=8-e.length%8;let i;if(2===t&&r<8)i=32;else if(1===t)i=r;else{if(t||!(r<8)){if(8===r)return e;throw Error("des: invalid padding")}i=0}const n=new Uint8Array(e.length+r);for(let t=0;t>>4^v),v^=b,w^=b<<4,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,w=w<<1|w>>>31,v=v<<1|v>>>31,y=0;y>>4|v<<28)^e[p+1],b=w,w=v,v=b^(o[g>>>24&63]|u[g>>>16&63]|d[g>>>8&63]|l[63&g]|s[m>>>24&63]|c[m>>>16&63]|h[m>>>8&63]|f[63&m]);b=w,w=v,v=b}w=w>>>1|w<<31,v=v>>>1|v<<31,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=252645135&(w>>>4^v),v^=b,w^=b<<4,1===i&&(r?(k=w,S=v):(w^=A,v^=E)),D[U++]=w>>>24,D[U++]=w>>>16&255,D[U++]=w>>>8&255,D[U++]=255&w,D[U++]=v>>>24,D[U++]=v>>>16&255,D[U++]=v>>>8&255,D[U++]=255&v}return r||(D=function(e,t){let r,i=null;if(2===t)r=32;else if(1===t)i=e[e.length-1];else{if(t)throw Error("des: invalid padding");r=0}if(!i){for(i=1;e[e.length-i]===r;)i++;i--}return e.subarray(0,e.length-i)}(D,a)),D}function Ce(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],l=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length>8?3:1,b=Array(32*y),g=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let m,w,v,_=0,k=0;for(let A=0;A>>4^A),A^=v,y^=v<<4,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=858993459&(y>>>2^A),A^=v,y^=v<<2,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=16711935&(A>>>8^y),y^=v,A^=v<<8,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=y<<8|A>>>20&240,y=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=v;for(let e=0;e<16;e++)g[e]?(y=y<<2|y>>>26,A=A<<2|A>>>26):(y=y<<1|y>>>27,A=A<<1|A>>>27),y&=-15,A&=-15,m=t[y>>>28]|r[y>>>24&15]|i[y>>>20&15]|n[y>>>16&15]|a[y>>>12&15]|s[y>>>8&15]|o[y>>>4&15],w=c[A>>>28]|u[A>>>24&15]|h[A>>>20&15]|d[A>>>16&15]|f[A>>>12&15]|l[A>>>8&15]|p[A>>>4&15],v=65535&(w>>>16^m),b[k++]=m^v,b[k++]=w^v<<16}return b}function De(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Ke(Ce(this.key[2]),Ke(Ce(this.key[1]),Ke(Ce(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}function Ue(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>>16&255,t[a+6]=o>>>8&255,t[a+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>16&255,t[a+6]=o>>8&255,t[a+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const i=t+e,n=i<>>32-r;return(a[0][n>>>24]^a[1][n>>>16&255])-a[2][n>>>8&255]+a[3][255&n]}function i(e,t,r){const i=t^e,n=i<>>32-r;return a[0][n>>>24]-a[1][n>>>16&255]+a[2][n>>>8&255]^a[3][255&n]}function n(e,t,r){const i=t-e,n=i<>>32-r;return(a[0][n>>>24]+a[1][n>>>16&255]^a[2][n>>>8&255])-a[3][255&n]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const i=[,,,,,,,,],n=Array(32);let s;for(let e=0;e<4;e++)s=4*e,i[e]=r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3];const o=[6,7,4,5];let c,u=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(s=0;s<4;s++){const t=e[r][s];c=i[t[1]],c^=a[4][i[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=a[5][i[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=a[6][i[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=a[7][i[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=a[o[s]][i[t[6]>>>2]>>>24-8*(3&t[6])&255],i[t[0]]=c}for(s=0;s<4;s++){const e=t[r][s];c=a[4][i[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=a[5][i[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=a[6][i[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=a[7][i[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=a[4+s][i[e[4]>>>2]>>>24-8*(3&e[4])&255],n[u]=c,u++}}for(let e=0;e<16;e++)this.masking[e]=n[e],this.rotate[e]=31&n[16+e]};const a=[,,,,,,,,];a[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],a[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],a[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],a[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],a[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],a[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],a[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],a[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Re(e){this.cast5=new Ue,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}De.keySize=De.prototype.keySize=24,De.blockSize=De.prototype.blockSize=8,Re.blockSize=Re.prototype.blockSize=8,Re.keySize=Re.prototype.keySize=16;const Ie=4294967295;function Be(e,t){return(e<>>32-t)&Ie}function Te(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function ze(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function qe(e,t){return e>>>8*t&255}function Fe(e){this.tf=function(){let e=null,t=null,r=-1,i=[],n=[[],[],[],[]];function a(e){return n[0][qe(e,0)]^n[1][qe(e,1)]^n[2][qe(e,2)]^n[3][qe(e,3)]}function s(e){return n[0][qe(e,3)]^n[1][qe(e,0)]^n[2][qe(e,1)]^n[3][qe(e,2)]}function o(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Be(t[2]^r+n+i[4*e+8]&Ie,31),t[3]=Be(t[3],1)^r+2*n+i[4*e+9]&Ie,r=a(t[2]),n=s(t[3]),t[0]=Be(t[0]^r+n+i[4*e+10]&Ie,31),t[1]=Be(t[1],1)^r+2*n+i[4*e+11]&Ie}function c(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Be(t[2],1)^r+n+i[4*e+10]&Ie,t[3]=Be(t[3]^r+2*n+i[4*e+11]&Ie,31),r=a(t[2]),n=s(t[3]),t[0]=Be(t[0],1)^r+n+i[4*e+8]&Ie,t[1]=Be(t[1]^r+2*n+i[4*e+9]&Ie,31)}return{name:"twofish",blocksize:16,open:function(t){let r,a,s,o,c;e=t;const u=[],h=[],d=[];let f;const l=[];let p,y,b;const g=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],m=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],w=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],v=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],_=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],k=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],A=[[],[]],S=[[],[],[],[]];function E(e){return e^e>>2^[0,90,180,238][3&e]}function P(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function x(e,t){let r,i,n;for(r=0;r<8;r++)i=t>>>24,t=t<<8&Ie|e>>>24,e=e<<8&Ie,n=i<<1,128&i&&(n^=333),t^=i^n<<16,n^=i>>>1,1&i&&(n^=166),t^=n<<24|n<<8;return t}function M(e,t){const r=t>>4,i=15&t,n=g[e][r^i],a=m[e][_[i]^k[r]];return v[e][_[a]^k[n]]<<4|w[e][n^a]}function K(e,t){let r=qe(e,0),i=qe(e,1),n=qe(e,2),a=qe(e,3);switch(f){case 4:r=A[1][r]^qe(t[3],0),i=A[0][i]^qe(t[3],1),n=A[0][n]^qe(t[3],2),a=A[1][a]^qe(t[3],3);case 3:r=A[1][r]^qe(t[2],0),i=A[1][i]^qe(t[2],1),n=A[0][n]^qe(t[2],2),a=A[0][a]^qe(t[2],3);case 2:r=A[0][A[0][r]^qe(t[1],0)]^qe(t[0],0),i=A[0][A[1][i]^qe(t[1],1)]^qe(t[0],1),n=A[1][A[0][n]^qe(t[1],2)]^qe(t[0],2),a=A[1][A[1][a]^qe(t[1],3)]^qe(t[0],3)}return S[0][r]^S[1][i]^S[2][n]^S[3][a]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Te(e,r);for(r=0;r<256;r++)A[0][r]=M(0,r),A[1][r]=M(1,r);for(r=0;r<256;r++)p=A[1][r],y=E(p),b=P(p),S[0][r]=p+(y<<8)+(b<<16)+(b<<24),S[2][r]=y+(b<<8)+(p<<16)+(b<<24),p=A[0][r],y=E(p),b=P(p),S[1][r]=b+(b<<8)+(y<<16)+(p<<24),S[3][r]=y+(p<<8)+(b<<16)+(y<<24);for(f=d.length/2,r=0;r=0;e--)c(e,a);ze(t,r,a[2]^i[0]),ze(t,r+4,a[3]^i[1]),ze(t,r+8,a[0]^i[2]),ze(t,r+12,a[1]^i[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Oe(){}function Le(e){this.bf=new Oe,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}Fe.keySize=Fe.prototype.keySize=32,Fe.blockSize=Fe.prototype.blockSize=16,Oe.prototype.BLOCKSIZE=8,Oe.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Oe.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Oe.prototype.NN=16,Oe.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Oe.prototype._F=function(e){let t;const r=255&e,i=255&(e>>>=8),n=255&(e>>>=8),a=255&(e>>>=8);return t=this.sboxes[0][a]+this.sboxes[1][n],t^=this.sboxes[2][i],t+=this.sboxes[3][r],t},Oe.prototype._encryptBlock=function(e){let t,r=e[0],i=e[1];for(t=0;t>>24-8*t&255,n[t+i]=r[1]>>>24-8*t&255;return n},Oe.prototype._decryptBlock=function(e){let t,r=e[0],i=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],i=this._F(r)^i;const e=r;r=i,i=e}r^=this.parray[1],i^=this.parray[0],e[0]=this._clean(i),e[1]=this._clean(r)},Oe.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^i}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const i=[0,0];for(t=0;t>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=t+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=r+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=c+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=u+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=h+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=d+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=f+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=l+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=p+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=y+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a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>>>31;x=Be+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=Re^Me^ke^ve;Te=P<<1|P>>>31;x=Te+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;P=Ie^Ke^Ae^_e;ze=P<<1|P>>>31;x=ze+(_<<5|_>>>27)+E+(k^A^S)-0x359d3e2a|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;i=i+_|0;n=n+k|0;a=a+A|0;s=s+S|0;o=o+E|0}function k(e){e=e|0;_(v[e|0]<<24|v[e|1]<<16|v[e|2]<<8|v[e|3],v[e|4]<<24|v[e|5]<<16|v[e|6]<<8|v[e|7],v[e|8]<<24|v[e|9]<<16|v[e|10]<<8|v[e|11],v[e|12]<<24|v[e|13]<<16|v[e|14]<<8|v[e|15],v[e|16]<<24|v[e|17]<<16|v[e|18]<<8|v[e|19],v[e|20]<<24|v[e|21]<<16|v[e|22]<<8|v[e|23],v[e|24]<<24|v[e|25]<<16|v[e|26]<<8|v[e|27],v[e|28]<<24|v[e|29]<<16|v[e|30]<<8|v[e|31],v[e|32]<<24|v[e|33]<<16|v[e|34]<<8|v[e|35],v[e|36]<<24|v[e|37]<<16|v[e|38]<<8|v[e|39],v[e|40]<<24|v[e|41]<<16|v[e|42]<<8|v[e|43],v[e|44]<<24|v[e|45]<<16|v[e|46]<<8|v[e|47],v[e|48]<<24|v[e|49]<<16|v[e|50]<<8|v[e|51],v[e|52]<<24|v[e|53]<<16|v[e|54]<<8|v[e|55],v[e|56]<<24|v[e|57]<<16|v[e|58]<<8|v[e|59],v[e|60]<<24|v[e|61]<<16|v[e|62]<<8|v[e|63])}function A(e){e=e|0;v[e|0]=i>>>24;v[e|1]=i>>>16&255;v[e|2]=i>>>8&255;v[e|3]=i&255;v[e|4]=n>>>24;v[e|5]=n>>>16&255;v[e|6]=n>>>8&255;v[e|7]=n&255;v[e|8]=a>>>24;v[e|9]=a>>>16&255;v[e|10]=a>>>8&255;v[e|11]=a&255;v[e|12]=s>>>24;v[e|13]=s>>>16&255;v[e|14]=s>>>8&255;v[e|15]=s&255;v[e|16]=o>>>24;v[e|17]=o>>>16&255;v[e|18]=o>>>8&255;v[e|19]=o&255}function S(){i=0x67452301;n=0xefcdab89;a=0x98badcfe;s=0x10325476;o=0xc3d2e1f0;c=u=0}function E(e,t,r,h,d,f,l){e=e|0;t=t|0;r=r|0;h=h|0;d=d|0;f=f|0;l=l|0;i=e;n=t;a=r;s=h;o=d;c=f;u=l}function P(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){k(e);e=e+64|0;t=t-64|0;r=r+64|0}c=c+r|0;if(c>>>0>>0)u=u+1|0;return r|0}function x(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=P(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;c=c+t|0;if(c>>>0>>0)u=u+1|0;v[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)v[e|n]=0x00;k(e);t=0;v[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)v[e|n]=0;v[e|56]=u>>>21&255;v[e|57]=u>>>13&255;v[e|58]=u>>>5&255;v[e|59]=u<<3&255|c>>>29;v[e|60]=c>>>21&255;v[e|61]=c>>>13&255;v[e|62]=c>>>5&255;v[e|63]=c<<3&255;k(e);if(~r)A(r);return i|0}function M(){i=h;n=d;a=f;s=l;o=p;c=64;u=0}function K(){i=y;n=b;a=g;s=m;o=w;c=64;u=0}function C(e,t,r,v,k,A,E,P,x,M,K,C,D,U,R,I){e=e|0;t=t|0;r=r|0;v=v|0;k=k|0;A=A|0;E=E|0;P=P|0;x=x|0;M=M|0;K=K|0;C=C|0;D=D|0;U=U|0;R=R|0;I=I|0;S();_(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,v^0x5c5c5c5c,k^0x5c5c5c5c,A^0x5c5c5c5c,E^0x5c5c5c5c,P^0x5c5c5c5c,x^0x5c5c5c5c,M^0x5c5c5c5c,K^0x5c5c5c5c,C^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,R^0x5c5c5c5c,I^0x5c5c5c5c);y=i;b=n;g=a;m=s;w=o;S();_(e^0x36363636,t^0x36363636,r^0x36363636,v^0x36363636,k^0x36363636,A^0x36363636,E^0x36363636,P^0x36363636,x^0x36363636,M^0x36363636,K^0x36363636,C^0x36363636,D^0x36363636,U^0x36363636,R^0x36363636,I^0x36363636);h=i;d=n;f=a;l=s;p=o;c=64;u=0}function D(e,t,r){e=e|0;t=t|0;r=r|0;var c=0,u=0,h=0,d=0,f=0,l=0;if(e&63)return-1;if(~r)if(r&31)return-1;l=x(e,t,-1)|0;c=i,u=n,h=a,d=s,f=o;K();_(c,u,h,d,f,0x80000000,0,0,0,0,0,0,0,0,0,672);if(~r)A(r);return l|0}function U(e,t,r,c,u){e=e|0;t=t|0;r=r|0;c=c|0;u=u|0;var h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;if(e&63)return-1;if(~u)if(u&31)return-1;v[e+t|0]=r>>>24;v[e+t+1|0]=r>>>16&255;v[e+t+2|0]=r>>>8&255;v[e+t+3|0]=r&255;D(e,t+4|0,-1)|0;h=y=i,d=b=n,f=g=a,l=m=s,p=w=o;c=c-1|0;while((c|0)>0){M();_(y,b,g,m,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,g=a,m=s,w=o;K();_(y,b,g,m,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,g=a,m=s,w=o;h=h^i;d=d^n;f=f^a;l=l^s;p=p^o;c=c-1|0}i=h;n=d;a=f;s=l;o=p;if(~u)A(u);return 0}return{reset:S,init:E,process:P,finish:x,hmac_reset:M,hmac_init:C,hmac_finish:D,pbkdf2_generate_block:U}};class $e{constructor(){this.pos=0,this.len=0}reset(){const{asm:e}=this.acquire_asm();return this.result=null,this.pos=0,this.len=0,e.reset(),this}process(e){if(null!==this.result)throw new _e("state must be reset before processing new data");const{asm:t,heap:r}=this.acquire_asm();let i=this.pos,n=this.len,a=0,s=e.length,o=0;for(;s>0;)o=we(r,i+n,e,a,s),n+=o,a+=o,s-=o,o=t.process(i,n),i+=o,n-=o,n||(i=0);return this.pos=i,this.len=n,this}finish(){if(null!==this.result)throw new _e("state must be reset before processing new data");const{asm:e,heap:t}=this.acquire_asm();return e.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(t.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this.release_asm(),this}}const Ze=[],Xe=[];class Ye extends $e{constructor(){super(),this.NAME="sha1",this.BLOCK_SIZE=64,this.HASH_SIZE=20,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=Ze.pop()||me(),this.asm=Xe.pop()||Ve({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(Ze.push(this.heap),Xe.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new Ye).process(e).finish().result}}Ye.NAME="sha1",Ye.heap_pool=[],Ye.asm_pool=[],Ye.asm_function=Ve;const Qe=[],Je=[];class et extends $e{constructor(){super(),this.NAME="sha256",this.BLOCK_SIZE=64,this.HASH_SIZE=32,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=Qe.pop()||me(),this.asm=Je.pop()||function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=new e.Uint8Array(r);function C(e,t,r,d,f,l,p,y,b,g,m,w,v,_,k,A){e=e|0;t=t|0;r=r|0;d=d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K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xab1c5ed5|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xd807aa98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x12835b01|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x243185be|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x550c7dc3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x72be5d74|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x80deb1fe|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x9bdc06a7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc19bf174|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xe49b69c1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xefbe4786|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x0fc19dc6|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x240ca1cc|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x2de92c6f|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4a7484aa|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5cb0a9dc|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x76f988da|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x983e5152|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa831c66d|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb00327c8|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xbf597fc7|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xc6e00bf3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd5a79147|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x06ca6351|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x14292967|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x27b70a85|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x2e1b2138|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x4d2c6dfc|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x53380d13|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x650a7354|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x766a0abb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x81c2c92e|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x92722c85|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xa2bfe8a1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa81a664b|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xc24b8b70|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xc76c51a3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xd192e819|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd6990624|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xf40e3585|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x106aa070|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+g|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x19a4c116|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+m|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x1e376c08|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x2748774c|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x34b0bcb5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x391c0cb3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4ed8aa4a|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5b9cca4f|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x682e6ff3|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x748f82ee|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+r|0;C=g+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x78a5636f|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+m+d|0;K=m+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x84c87814|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x8cc70208|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x90befffa|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xa4506ceb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xbef9a3f7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc67178f2|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;i=i+S|0;n=n+E|0;a=a+P|0;s=s+x|0;o=o+M|0;c=c+K|0;u=u+C|0;h=h+D|0}function D(e){e=e|0;C(K[e|0]<<24|K[e|1]<<16|K[e|2]<<8|K[e|3],K[e|4]<<24|K[e|5]<<16|K[e|6]<<8|K[e|7],K[e|8]<<24|K[e|9]<<16|K[e|10]<<8|K[e|11],K[e|12]<<24|K[e|13]<<16|K[e|14]<<8|K[e|15],K[e|16]<<24|K[e|17]<<16|K[e|18]<<8|K[e|19],K[e|20]<<24|K[e|21]<<16|K[e|22]<<8|K[e|23],K[e|24]<<24|K[e|25]<<16|K[e|26]<<8|K[e|27],K[e|28]<<24|K[e|29]<<16|K[e|30]<<8|K[e|31],K[e|32]<<24|K[e|33]<<16|K[e|34]<<8|K[e|35],K[e|36]<<24|K[e|37]<<16|K[e|38]<<8|K[e|39],K[e|40]<<24|K[e|41]<<16|K[e|42]<<8|K[e|43],K[e|44]<<24|K[e|45]<<16|K[e|46]<<8|K[e|47],K[e|48]<<24|K[e|49]<<16|K[e|50]<<8|K[e|51],K[e|52]<<24|K[e|53]<<16|K[e|54]<<8|K[e|55],K[e|56]<<24|K[e|57]<<16|K[e|58]<<8|K[e|59],K[e|60]<<24|K[e|61]<<16|K[e|62]<<8|K[e|63])}function U(e){e=e|0;K[e|0]=i>>>24;K[e|1]=i>>>16&255;K[e|2]=i>>>8&255;K[e|3]=i&255;K[e|4]=n>>>24;K[e|5]=n>>>16&255;K[e|6]=n>>>8&255;K[e|7]=n&255;K[e|8]=a>>>24;K[e|9]=a>>>16&255;K[e|10]=a>>>8&255;K[e|11]=a&255;K[e|12]=s>>>24;K[e|13]=s>>>16&255;K[e|14]=s>>>8&255;K[e|15]=s&255;K[e|16]=o>>>24;K[e|17]=o>>>16&255;K[e|18]=o>>>8&255;K[e|19]=o&255;K[e|20]=c>>>24;K[e|21]=c>>>16&255;K[e|22]=c>>>8&255;K[e|23]=c&255;K[e|24]=u>>>24;K[e|25]=u>>>16&255;K[e|26]=u>>>8&255;K[e|27]=u&255;K[e|28]=h>>>24;K[e|29]=h>>>16&255;K[e|30]=h>>>8&255;K[e|31]=h&255}function R(){i=0x6a09e667;n=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;h=0x5be0cd19;d=f=0}function I(e,t,r,l,p,y,b,g,m,w){e=e|0;t=t|0;r=r|0;l=l|0;p=p|0;y=y|0;b=b|0;g=g|0;m=m|0;w=w|0;i=e;n=t;a=r;s=l;o=p;c=y;u=b;h=g;d=m;f=w}function B(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){D(e);e=e+64|0;t=t-64|0;r=r+64|0}d=d+r|0;if(d>>>0>>0)f=f+1|0;return r|0}function T(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=B(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;d=d+t|0;if(d>>>0>>0)f=f+1|0;K[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)K[e|n]=0x00;D(e);t=0;K[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)K[e|n]=0;K[e|56]=f>>>21&255;K[e|57]=f>>>13&255;K[e|58]=f>>>5&255;K[e|59]=f<<3&255|d>>>29;K[e|60]=d>>>21&255;K[e|61]=d>>>13&255;K[e|62]=d>>>5&255;K[e|63]=d<<3&255;D(e);if(~r)U(r);return i|0}function z(){i=l;n=p;a=y;s=b;o=g;c=m;u=w;h=v;d=64;f=0}function q(){i=_;n=k;a=A;s=S;o=E;c=P;u=x;h=M;d=64;f=0}function F(e,t,r,K,D,U,I,B,T,z,q,F,O,L,N,j){e=e|0;t=t|0;r=r|0;K=K|0;D=D|0;U=U|0;I=I|0;B=B|0;T=T|0;z=z|0;q=q|0;F=F|0;O=O|0;L=L|0;N=N|0;j=j|0;R();C(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,K^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,I^0x5c5c5c5c,B^0x5c5c5c5c,T^0x5c5c5c5c,z^0x5c5c5c5c,q^0x5c5c5c5c,F^0x5c5c5c5c,O^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,j^0x5c5c5c5c);_=i;k=n;A=a;S=s;E=o;P=c;x=u;M=h;R();C(e^0x36363636,t^0x36363636,r^0x36363636,K^0x36363636,D^0x36363636,U^0x36363636,I^0x36363636,B^0x36363636,T^0x36363636,z^0x36363636,q^0x36363636,F^0x36363636,O^0x36363636,L^0x36363636,N^0x36363636,j^0x36363636);l=i;p=n;y=a;b=s;g=o;m=c;w=u;v=h;d=64;f=0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0;if(e&63)return-1;if(~r)if(r&31)return-1;w=T(e,t,-1)|0;d=i,f=n,l=a,p=s,y=o,b=c,g=u,m=h;q();C(d,f,l,p,y,b,g,m,0x80000000,0,0,0,0,0,0,768);if(~r)U(r);return w|0}function L(e,t,r,d,f){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;var l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0;if(e&63)return-1;if(~f)if(f&31)return-1;K[e+t|0]=r>>>24;K[e+t+1|0]=r>>>16&255;K[e+t+2|0]=r>>>8&255;K[e+t+3|0]=r&255;O(e,t+4|0,-1)|0;l=_=i,p=k=n,y=A=a,b=S=s,g=E=o,m=P=c,w=x=u,v=M=h;d=d-1|0;while((d|0)>0){z();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;q();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;l=l^i;p=p^n;y=y^a;b=b^s;g=g^o;m=m^c;w=w^u;v=v^h;d=d-1|0}i=l;n=p;a=y;s=b;o=g;c=m;u=w;h=v;if(~f)U(f);return 0}return{reset:R,init:I,process:B,finish:T,hmac_reset:z,hmac_init:F,hmac_finish:O,pbkdf2_generate_block:L}}({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(Qe.push(this.heap),Je.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new et).process(e).finish().result}}et.NAME="sha256";var tt=rt;function rt(e,t){if(!e)throw Error(t||"Assertion failed")}rt.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)};var it=void 0!==t?t:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function nt(e,t){return e(t={exports:{}},t.exports),t.exports}function at(){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var st=nt((function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}));var ot=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>8,s=255&n;a?r.push(a,s):r.push(s)}else for(i=0;i>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}var ht=function(e,t){for(var r="",i=0;i>>0}return a};var pt=function(e,t){for(var r=Array(4*e.length),i=0,n=0;i>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r};var yt={inherits:st,toArray:ot,toHex:ct,htonl:ut,toHex32:ht,zero2:dt,zero8:ft,join32:lt,split32:pt,rotr32:function(e,t){return e>>>t|e<<32-t},rotl32:function(e,t){return e<>>32-t},sum32:function(e,t){return e+t>>>0},sum32_3:function(e,t,r){return e+t+r>>>0},sum32_4:function(e,t,r,i){return e+t+r+i>>>0},sum32_5:function(e,t,r,i,n){return e+t+r+i+n>>>0},sum64:function(e,t,r,i){var n=e[t],a=i+e[t+1]>>>0,s=(a>>0,e[t+1]=a},sum64_hi:function(e,t,r,i){return(t+i>>>0>>0},sum64_lo:function(e,t,r,i){return t+i>>>0},sum64_4_hi:function(e,t,r,i,n,a,s,o){var c=0,u=t;return c+=(u=u+i>>>0)>>0)>>0)>>0},sum64_4_lo:function(e,t,r,i,n,a,s,o){return t+i+a+o>>>0},sum64_5_hi:function(e,t,r,i,n,a,s,o,c,u){var h=0,d=t;return h+=(d=d+i>>>0)>>0)>>0)>>0)>>0},sum64_5_lo:function(e,t,r,i,n,a,s,o,c,u){return t+i+a+o+u>>>0},rotr64_hi:function(e,t,r){return(t<<32-r|e>>>r)>>>0},rotr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0},shr64_hi:function(e,t,r){return e>>>r},shr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0}};function bt(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var gt=bt;bt.prototype.update=function(e,t){if(e=yt.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=yt.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,a=8;a>>3},g1_256:function(e){return wt(e,17)^wt(e,19)^e>>>10}},Et=yt.sum32,Pt=yt.sum32_4,xt=yt.sum32_5,Mt=St.ch32,Kt=St.maj32,Ct=St.s0_256,Dt=St.s1_256,Ut=St.g0_256,Rt=St.g1_256,It=mt.BlockHash,Bt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Tt(){if(!(this instanceof Tt))return new Tt;It.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=Bt,this.W=Array(64)}yt.inherits(Tt,It);var zt=Tt;function qt(){if(!(this instanceof qt))return new qt;zt.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Tt.blockSize=512,Tt.outSize=256,Tt.hmacStrength=192,Tt.padLength=64,Tt.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i>>32-n,r)}function Ur(e,t,r,i,n,a,s){return Dr(t&r|~t&i,e,t,n,a,s)}function Rr(e,t,r,i,n,a,s){return Dr(t&i|r&~i,e,t,n,a,s)}function Ir(e,t,r,i,n,a,s){return Dr(t^r^i,e,t,n,a,s)}function Br(e,t,r,i,n,a,s){return Dr(r^(t|~i),e,t,n,a,s)}function Tr(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const zr="0123456789abcdef".split("");function qr(e){let t="",r=0;for(;r<4;r++)t+=zr[e>>8*r+4&15]+zr[e>>8*r&15];return t}function Fr(e,t){return e+t&4294967295}const Or=Y.getWebCrypto(),Lr=Y.getNodeCrypto(),Nr=Lr&&Lr.getHashes();function jr(e){if(Lr&&Nr.includes(e))return async function(t){const r=Lr.createHash(e);return T(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function Hr(e,t){return async function(r,i=ae){if(o(r)&&(r=await j(r)),!Y.isStream(r)&&Or&&t&&r.length>=i.minBytesForWebCrypto)return new Uint8Array(await Or.digest(t,r));const n=e();return T(r,(e=>{n.update(e)}),(()=>new Uint8Array(n.digest())))}}function Wr(e,t){return async function(r,i=ae){if(o(r)&&(r=await j(r)),Y.isStream(r)){const t=new e;return T(r,(e=>{t.process(e)}),(()=>t.finish().result))}return Or&&t&&r.length>=i.minBytesForWebCrypto?new Uint8Array(await Or.digest(t,r)):e.bytes(r)}}const Gr={md5:jr("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let i;for(i=64;i<=e.length;i+=64)Cr(r,Tr(e.substring(i-64,i)));e=e.substring(i-64);const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i>2]|=e.charCodeAt(i)<<(i%4<<3);if(n[i>>2]|=128<<(i%4<<3),i>55)for(Cr(r,n),i=0;i<16;i++)n[i]=0;return n[14]=8*t,Cr(r,n),r}(Y.uint8ArrayToString(e));return Y.hexToUint8Array(function(e){for(let t=0;tnew Uint8Array(a.update(e))))}(e,t,r,i);if(Y.isAES(e))return function(e,t,r,i,n){if(Y.getWebCrypto()&&24!==t.length&&!Y.isStream(r)&&r.length>=3e3*n.minBytesForWebCrypto)return async function(e,t,r,i){const n="AES-CBC",a=await Xr.importKey("raw",t,{name:n},!1,["encrypt"]),{blockSize:s}=Zr(e),o=Y.concatUint8Array([new Uint8Array(s),r]),c=new Uint8Array(await Xr.encrypt({name:n,iv:i},a,o)).subarray(0,r.length);return function(e,t){for(let r=0;ra.aes.AES_Encrypt_process(e)),(()=>a.aes.AES_Encrypt_finish()))}(e,t,r,i,n);const s=new(Zr(e))(t),o=s.blockSize,c=i.slice();let u=new Uint8Array;const h=e=>{e&&(u=Y.concatUint8Array([u,e]));const t=new Uint8Array(u.length);let r,i=0;for(;e?u.length>=o:u.length;){const e=s.encrypt(c);for(r=0;rnew Uint8Array(a.update(e))))}(e,t,r,i);if(Y.isAES(e))return function(e,t,r,i){if(Y.isStream(r)){const e=new $r(t,i);return T(r,(t=>e.aes.AES_Decrypt_process(t)),(()=>e.aes.AES_Decrypt_finish()))}return $r.decrypt(r,t,i)}(0,t,r,i);const a=new(Zr(e))(t),s=a.blockSize;let o=i,c=new Uint8Array;const u=e=>{e&&(c=Y.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,i=0;for(;e?c.length>=s:c.length;){const e=a.encrypt(o);for(o=c.subarray(0,s),r=0;r48)throw new ke("illegal counter size");let e=Math.pow(2,r)-1;i.set_mask(0,0,e/4294967296|0,0|e)}else r=48,i.set_mask(0,0,65535,4294967295);if(void 0===e)throw Error("nonce is required");{let t=e.length;if(!t||t>16)throw new ke("illegal nonce size");let r=new DataView(new ArrayBuffer(16));new Uint8Array(r.buffer).set(e),i.set_nonce(r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12))}if(void 0!==t){if(t<0||t>=Math.pow(2,r))throw new ke("illegal counter value");i.set_counter(0,0,t/4294967296|0,0|t)}}}class ri{static encrypt(e,t,r=!0,i){return new ri(t,i,r).encrypt(e)}static decrypt(e,t,r=!0,i){return new ri(t,i,r).decrypt(e)}constructor(e,t,r=!0,i){this.aes=i||new Pe(e,t,r,"CBC")}encrypt(e){return ve(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return ve(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}const ii=Y.getWebCrypto(),ni=Y.getNodeCrypto(),ai=16;function si(e,t){const r=e.length-ai;for(let i=0;i>3),17+(u>>3)),8-(7&u)).subarray(1),l=new Uint8Array(_i),p=new Uint8Array(t.length+Ai);let y,b=0;for(y=0;y16)throw new ke("illegal tagSize value");const o=t.length||0,c=new Uint8Array(16);12!==o?(this._gcm_mac_process(t),s[0]=0,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=0,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=0,s[11]=o>>>29,s[12]=o>>>21&255,s[13]=o>>>13&255,s[14]=o>>>5&255,s[15]=o<<3&255,a.mac(be.MAC.GCM,be.HEAP_DATA,16),a.get_iv(be.HEAP_DATA),a.set_iv(0,0,0,0),c.set(s.subarray(0,16))):(c.set(t),c[15]=1);const u=new DataView(c.buffer);if(this.gamma0=u.getUint32(12),a.set_nonce(u.getUint32(0),u.getUint32(4),u.getUint32(8),0),a.set_mask(0,0,0,4294967295),void 0!==r){if(r.length>Ci)throw new ke("illegal adata length");r.length?(this.adata=r,this._gcm_mac_process(r)):this.adata=void 0}else this.adata=void 0;if(this.counter<1||this.counter>4294967295)throw new RangeError("counter must be a positive 32-bit integer");a.set_counter(0,0,0,this.gamma0+this.counter|0)}static encrypt(e,t,r,i,n){return new Di(t,r,i,n).encrypt(e)}static decrypt(e,t,r,i,n){return new Di(t,r,i,n).decrypt(e)}encrypt(e){return this.AES_GCM_encrypt(e)}decrypt(e){return this.AES_GCM_decrypt(e)}AES_GCM_Encrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.aes.pos,o=this.aes.len,c=0,u=o+r&-16,h=0;if((a-1<<4)+o+r>Ci)throw new RangeError("counter overflow");const d=new Uint8Array(u);for(;r>0;)h=we(n,s+o,e,t,r),o+=h,t+=h,r-=h,h=i.cipher(be.ENC.CTR,be.HEAP_DATA+s,o),h=i.mac(be.MAC.GCM,be.HEAP_DATA+s,h),h&&d.set(n.subarray(s,s+h),c),a+=h>>>4,c+=h,h>>29,t[4]=u>>>21,t[5]=u>>>13&255,t[6]=u>>>5&255,t[7]=u<<3&255,t[8]=t[9]=t[10]=0,t[11]=h>>>29,t[12]=h>>>21&255,t[13]=h>>>13&255,t[14]=h>>>5&255,t[15]=h<<3&255,e.mac(be.MAC.GCM,be.HEAP_DATA,16),e.get_iv(be.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(be.ENC.CTR,be.HEAP_DATA,16),o.set(t.subarray(0,i),s),this.counter=1,this.aes.pos=0,this.aes.len=0,o}AES_GCM_Decrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.tagSize,o=this.aes.pos,c=this.aes.len,u=0,h=c+r>s?c+r-s&-16:0,d=c+r-h,f=0;if((a-1<<4)+c+r>Ci)throw new RangeError("counter overflow");const l=new Uint8Array(h);for(;r>d;)f=we(n,o+c,e,t,r-d),c+=f,t+=f,r-=f,f=i.mac(be.MAC.GCM,be.HEAP_DATA+o,f),f=i.cipher(be.DEC.CTR,be.HEAP_DATA+o,f),f&&l.set(n.subarray(o,o+f),u),a+=f>>>4,u+=f,o=0,c=0;return r>0&&(c+=we(n,0,e,t,r)),this.counter=a,this.aes.pos=o,this.aes.len=c,l}AES_GCM_Decrypt_finish(){let{asm:e,heap:t}=this.aes.acquire_asm(),r=this.tagSize,i=this.adata,n=this.counter,a=this.aes.pos,s=this.aes.len,o=s-r;if(s>>29,t[4]=d>>>21,t[5]=d>>>13&255,t[6]=d>>>5&255,t[7]=d<<3&255,t[8]=t[9]=t[10]=0,t[11]=f>>>29,t[12]=f>>>21&255,t[13]=f>>>13&255,t[14]=f>>>5&255,t[15]=f<<3&255,e.mac(be.MAC.GCM,be.HEAP_DATA,16),e.get_iv(be.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(be.ENC.CTR,be.HEAP_DATA,16);let l=0;for(let e=0;e0;){for(a=we(r,0,e,i,n),i+=a,n-=a;15&a;)r[a++]=0;t.mac(be.MAC.GCM,be.HEAP_DATA,a)}}}const Ui=Y.getWebCrypto(),Ri=Y.getNodeCrypto(),Ii=Y.getNodeBuffer(),Bi=16,Ti="AES-GCM";async function zi(e,t){if(e!==Z.symmetric.aes128&&e!==Z.symmetric.aes192&&e!==Z.symmetric.aes256)throw Error("GCM mode supports only AES cipher");if(Y.getNodeCrypto())return{encrypt:async function(e,r,i=new Uint8Array){const n=new Ri.createCipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i);const a=Ii.concat([n.update(e),n.final(),n.getAuthTag()]);return new Uint8Array(a)},decrypt:async function(e,r,i=new Uint8Array){const n=new Ri.createDecipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i),n.setAuthTag(e.slice(e.length-Bi,e.length));const a=Ii.concat([n.update(e.slice(0,e.length-Bi)),n.final()]);return new Uint8Array(a)}};if(Y.getWebCrypto()&&24!==t.length){const e=await Ui.importKey("raw",t,{name:Ti},!1,["encrypt","decrypt"]);return{encrypt:async function(r,i,n=new Uint8Array){if(!r.length)return Di.encrypt(r,t,i,n);const a=await Ui.encrypt({name:Ti,iv:i,additionalData:n,tagLength:8*Bi},e,r);return new Uint8Array(a)},decrypt:async function(r,i,n=new Uint8Array){if(r.length===Bi)return Di.decrypt(r,t,i,n);const a=await Ui.decrypt({name:Ti,iv:i,additionalData:n,tagLength:8*Bi},e,r);return new Uint8Array(a)}}}return{encrypt:async function(e,r,i){return Di.encrypt(e,t,r,i)},decrypt:async function(e,r,i){return Di.decrypt(e,t,r,i)}}}zi.getNonce=function(e,t){const r=e.slice();for(let e=0;e>>8)-1}(e,t,r,i,32)}function l(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function p(e){var t,r,i=1;for(t=0;t<16;t++)r=e[t]+i+65535,i=Math.floor(r/65536),e[t]=r-65536*i;e[0]+=i-1+37*(i-1)}function y(e,t,r){for(var i,n=~(r-1),a=0;a<16;a++)i=n&(e[a]^t[a]),e[a]^=i,t[a]^=i}function b(e,r){var i,n,a,s=t(),o=t();for(i=0;i<16;i++)o[i]=r[i];for(p(o),p(o),p(o),n=0;n<2;n++){for(s[0]=o[0]-65517,i=1;i<15;i++)s[i]=o[i]-65535-(s[i-1]>>16&1),s[i-1]&=65535;s[15]=o[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,y(o,s,1-a)}for(i=0;i<16;i++)e[2*i]=255&o[i],e[2*i+1]=o[i]>>8}function g(e,t){var r=new Uint8Array(32),i=new Uint8Array(32);return b(r,e),b(i,t),f(r,0,i,0)}function m(e){var t=new Uint8Array(32);return b(t,e),1&t[0]}function w(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function v(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]+r[i]}function _(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]-r[i]}function k(e,t,r){var i,n,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,g=0,m=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0,U=0,R=0,I=0,B=0,T=r[0],z=r[1],q=r[2],F=r[3],O=r[4],L=r[5],N=r[6],j=r[7],H=r[8],W=r[9],G=r[10],V=r[11],$=r[12],Z=r[13],X=r[14],Y=r[15];a+=(i=t[0])*T,s+=i*z,o+=i*q,c+=i*F,u+=i*O,h+=i*L,d+=i*N,f+=i*j,l+=i*H,p+=i*W,y+=i*G,b+=i*V,g+=i*$,m+=i*Z,w+=i*X,v+=i*Y,s+=(i=t[1])*T,o+=i*z,c+=i*q,u+=i*F,h+=i*O,d+=i*L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,K+=i*Y,y+=(i=t[10])*T,b+=i*z,g+=i*q,m+=i*F,w+=i*O,v+=i*L,_+=i*N,k+=i*j,A+=i*H,S+=i*W,E+=i*G,P+=i*V,x+=i*$,M+=i*Z,K+=i*X,C+=i*Y,b+=(i=t[11])*T,g+=i*z,m+=i*q,w+=i*F,v+=i*O,_+=i*L,k+=i*N,A+=i*j,S+=i*H,E+=i*W,P+=i*G,x+=i*V,M+=i*$,K+=i*Z,C+=i*X,D+=i*Y,g+=(i=t[12])*T,m+=i*z,w+=i*q,v+=i*F,_+=i*O,k+=i*L,A+=i*N,S+=i*j,E+=i*H,P+=i*W,x+=i*G,M+=i*V,K+=i*$,C+=i*Z,D+=i*X,U+=i*Y,m+=(i=t[13])*T,w+=i*z,v+=i*q,_+=i*F,k+=i*O,A+=i*L,S+=i*N,E+=i*j,P+=i*H,x+=i*W,M+=i*G,K+=i*V,C+=i*$,D+=i*Z,U+=i*X,R+=i*Y,w+=(i=t[14])*T,v+=i*z,_+=i*q,k+=i*F,A+=i*O,S+=i*L,E+=i*N,P+=i*j,x+=i*H,M+=i*W,K+=i*G,C+=i*V,D+=i*$,U+=i*Z,R+=i*X,I+=i*Y,v+=(i=t[15])*T,s+=38*(k+=i*q),o+=38*(A+=i*F),c+=38*(S+=i*O),u+=38*(E+=i*L),h+=38*(P+=i*N),d+=38*(x+=i*j),f+=38*(M+=i*H),l+=38*(K+=i*W),p+=38*(C+=i*G),y+=38*(D+=i*V),b+=38*(U+=i*$),g+=38*(R+=i*Z),m+=38*(I+=i*X),w+=38*(B+=i*Y),a=(i=(a+=38*(_+=i*z))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a=(i=(a+=n-1+37*(n-1))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a+=n-1+37*(n-1),e[0]=a,e[1]=s,e[2]=o,e[3]=c,e[4]=u,e[5]=h,e[6]=d,e[7]=f,e[8]=l,e[9]=p,e[10]=y,e[11]=b,e[12]=g,e[13]=m,e[14]=w,e[15]=v}function A(e,t){k(e,t,t)}function S(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=253;i>=0;i--)A(n,n),2!==i&&4!==i&&k(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}function E(e,r,i){var n,a,o=new Uint8Array(32),c=new Float64Array(80),u=t(),h=t(),d=t(),f=t(),l=t(),p=t();for(a=0;a<31;a++)o[a]=r[a];for(o[31]=127&r[31]|64,o[0]&=248,w(c,i),a=0;a<16;a++)h[a]=c[a],f[a]=u[a]=d[a]=0;for(u[0]=f[0]=1,a=254;a>=0;--a)y(u,h,n=o[a>>>3]>>>(7&a)&1),y(d,f,n),v(l,u,d),_(u,u,d),v(d,h,f),_(h,h,f),A(f,l),A(p,u),k(u,d,u),k(d,h,l),v(l,u,d),_(u,u,d),A(h,u),_(d,f,p),k(u,d,s),v(u,u,f),k(d,d,u),k(u,f,p),k(f,h,c),A(h,l),y(u,h,n),y(d,f,n);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=d[a],c[a+48]=h[a],c[a+64]=f[a];var g=c.subarray(32),m=c.subarray(16);return S(g,g),k(m,m,g),b(e,m),0}function P(e,t){return E(e,t,i)}function x(e,r){var i=t(),n=t(),a=t(),s=t(),o=t(),u=t(),h=t(),d=t(),f=t();_(i,e[1],e[0]),_(f,r[1],r[0]),k(i,i,f),v(n,e[0],e[1]),v(f,r[0],r[1]),k(n,n,f),k(a,e[3],r[3]),k(a,a,c),k(s,e[2],r[2]),v(s,s,s),_(o,n,i),_(u,s,a),v(h,s,a),v(d,n,i),k(e[0],o,u),k(e[1],d,h),k(e[2],h,u),k(e[3],o,d)}function M(e,t,r){var i;for(i=0;i<4;i++)y(e[i],t[i],r)}function K(e,r){var i=t(),n=t(),a=t();S(a,r[2]),k(i,r[0],a),k(n,r[1],a),b(e,n),e[31]^=m(i)<<7}function C(e,t,r){var i,s;for(l(e[0],n),l(e[1],a),l(e[2],a),l(e[3],n),s=255;s>=0;--s)M(e,t,i=r[s/8|0]>>(7&s)&1),x(t,e),x(e,e),M(e,t,i)}function D(e,r){var i=[t(),t(),t(),t()];l(i[0],u),l(i[1],h),l(i[2],a),k(i[3],u,h),C(e,i,r)}function U(i,n,a){var s,o,c=[t(),t(),t(),t()];for(a||r(n,32),(s=e.hash(n.subarray(0,32)))[0]&=248,s[31]&=127,s[31]|=64,D(c,s),K(i,c),o=0;o<32;o++)n[o+32]=i[o];return 0}var R=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function I(e,t){var r,i,n,a;for(i=63;i>=32;--i){for(r=0,n=i-32,a=i-12;n>4)*R[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*R[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function B(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;I(e,r)}function T(e,r){var i=t(),s=t(),c=t(),u=t(),h=t(),f=t(),p=t();return l(e[2],a),w(e[1],r),A(c,e[1]),k(u,c,o),_(c,c,e[2]),v(u,e[2],u),A(h,u),A(f,h),k(p,f,h),k(i,p,c),k(i,i,u),function(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=250;i>=0;i--)A(n,n),1!==i&&k(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}(i,i),k(i,i,c),k(i,i,u),k(i,i,u),k(e[0],i,u),A(s,e[0]),k(s,s,u),g(s,c)&&k(e[0],e[0],d),A(s,e[0]),k(s,s,u),g(s,c)?-1:(m(e[0])===r[31]>>7&&_(e[0],n,e[0]),k(e[3],e[0],e[1]),0)}var z=64;function q(){for(var e=0;e=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return U(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(q(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;re&&(c.imod(a.leftShift(n)).iadd(a),u=c.mod(s).toNumber())}while(!await Wi(c,t,r));return c}async function Wi(e,t,r){return!(t&&!e.dec().gcd(t).isOne())&&(!!await async function(e){const t=await Y.getBigInteger();return Gi.every((r=>0!==e.mod(new t(r))))}(e)&&(!!await async function(e,t){const r=await Y.getBigInteger();return t=t||new r(2),t.modExp(e.dec(),e).isOne()}(e)&&!!await async function(e,t,r){const i=await Y.getBigInteger(),n=e.bitLength();t||(t=Math.max(1,n/48|0));const a=e.dec();let s=0;for(;!a.getBit(s);)s++;const o=e.rightShift(new i(s));for(;t>0;t--){let t,n=(r?r():await Ni(new i(2),a)).modExp(o,e);if(!n.isOne()&&!n.equal(a)){for(t=1;tt-11)throw Error("Message too long");const i=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!i;if(t)return Y.selectUint8Array(s,a,t);if(s)return a;throw Error("Decryption error")}async function Xi(e,t,r){let i;if(t.length!==Vr.getHashByteLength(e))throw Error("Invalid hash length");const n=new Uint8Array(Vi[e].length);for(i=0;i{Ji.generateKeyPair("rsa",r,((r,i,n)=>{r?t(r):e(tn.decode(n,"der"))}))}));return{n:i.modulus.toArrayLike(Uint8Array),e:i.publicExponent.toArrayLike(Uint8Array),d:i.privateExponent.toArrayLike(Uint8Array),p:i.prime2.toArrayLike(Uint8Array),q:i.prime1.toArrayLike(Uint8Array),u:i.coefficient.toArrayLike(Uint8Array)}}let r,i,n;do{i=await Hi(e-(e>>1),t,40),r=await Hi(e>>1,t,40),n=r.mul(i)}while(n.bitLength()!==e);const a=r.dec().imul(i.dec());return i.lt(r)&&([r,i]=[i,r]),{n:n.toUint8Array(),e:t.toUint8Array(),d:t.modInv(a).toUint8Array(),p:r.toUint8Array(),q:i.toUint8Array(),u:r.modInv(i).toUint8Array()}},validateParams:async function(e,t,r,i,n,a){const s=await Y.getBigInteger();if(e=new s(e),i=new s(i),n=new s(n),!i.mul(n).equal(e))return!1;const o=new s(2);if(a=new s(a),!i.mul(a).mod(n).isOne())return!1;t=new s(t),r=new s(r);const c=new s(Math.floor(e.bitLength()/3)),u=await Ni(o,o.leftShift(c)),h=u.mul(r).mul(t);return!(!h.mod(i.dec()).equal(u)||!h.mod(n.dec()).equal(u))}});var an=/*#__PURE__*/Object.freeze({__proto__:null,encrypt:async function(e,t,r,i){const n=await Y.getBigInteger();t=new n(t),r=new n(r),i=new n(i);const a=new n($i(e,t.byteLength())),s=await Ni(new n(1),t.dec());return{c1:r.modExp(s,t).toUint8Array(),c2:i.modExp(s,t).imul(a).imod(t).toUint8Array()}},decrypt:async function(e,t,r,i,n){const a=await Y.getBigInteger();return e=new a(e),t=new a(t),r=new a(r),i=new a(i),Zi(e.modExp(i,r).modInv(r).imul(t).imod(r).toUint8Array("be",r.byteLength()),n)},validateParams:async function(e,t,r,i){const n=await Y.getBigInteger();e=new n(e),t=new n(t),r=new n(r);const a=new n(1);if(t.lte(a)||t.gte(e))return!1;const s=new n(e.bitLength()),o=new n(1023);if(s.lt(o))return!1;if(!t.modExp(e.dec(),e).isOne())return!1;let c=t;const u=new n(1),h=new n(2).leftShift(new n(17));for(;u.lt(h);){if(c=c.mul(t).imod(e),c.isOne())return!1;u.iinc()}i=new n(i);const d=new n(2),f=await Ni(d.leftShift(s.dec()),d.leftShift(s)),l=e.dec().imul(f).iadd(i);return!!r.equal(t.modExp(l,e))}});class sn{constructor(e){if(e instanceof sn)this.oid=e.oid;else if(Y.isArray(e)||Y.isUint8Array(e)){if(6===(e=new Uint8Array(e))[0]){if(e[1]!==e.length-2)throw Error("Length mismatch in DER encoded oid");e=e.subarray(2)}this.oid=e}else this.oid=""}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return Y.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return Y.uint8ArrayToHex(this.oid)}getName(){const e=this.toHex();if(Z.curve[e])return Z.write(Z.curve,e);throw Error("Unknown curve object identifier.")}}function on(e,t){return e.keyPair({priv:t})}function cn(e,t){const r=e.keyPair({pub:t});if(!0!==r.validate().result)throw Error("Invalid elliptic public key");return r}async function un(e){if(!ae.useIndutnyElliptic)throw Error("This curve is only supported in the full build of OpenPGP.js");const{default:t}=await Promise.resolve().then((function(){return ib}));return new t.ec(e)}function hn(e){let t,r=0;const i=e[0];return i<192?([r]=e,t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=Y.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function dn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):Y.concatUint8Array([new Uint8Array([255]),Y.writeNumber(e,4)])}function fn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function ln(e){return new Uint8Array([192|e])}function pn(e,t){return Y.concatUint8Array([ln(e),dn(t)])}function yn(e){return[Z.packet.literalData,Z.packet.compressedData,Z.packet.symmetricallyEncryptedData,Z.packet.symEncryptedIntegrityProtectedData,Z.packet.aeadEncryptedData].includes(e)}async function bn(e,t){const r=D(e);let i,n;try{const a=await r.peekBytes(2);if(!a||a.length<2||0==(128&a[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const o=await r.readByte();let c,u,h=-1,d=-1;d=0,0!=(64&o)&&(d=1),d?h=63&o:(h=(63&o)>>2,u=3&o);const f=yn(h);let l,p=null;if(f){if("array"===Y.isStream(e)){const e=new s;i=U(e),p=e}else{const e=new E;i=U(e.writable),p=e.readable}n=t({tag:h,packet:p})}else p=[];do{if(d){const e=await r.readByte();if(l=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),l=!0,!f)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(u){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){i&&await i.ready;const{done:t,value:n}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const a=c===1/0?n:n.subarray(0,c-e);if(i?await i.write(a):p.push(a),e+=n.length,e>=c){r.unshift(n.subarray(c-e+n.length));break}}}}while(l);const y=await r.peekBytes(f?1/0:2);return i?(await i.ready,await i.close()):(p=Y.concatUint8Array(p),await t({tag:h,packet:p})),!y||!y.length}catch(e){if(i)return await i.abort(e),!0;throw e}finally{i&&await n,r.releaseLock()}}class gn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,gn),this.name="UnsupportedError"}}class mn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}const wn=Y.getWebCrypto(),vn=Y.getNodeCrypto(),_n={p256:"P-256",p384:"P-384",p521:"P-521"},kn=vn?vn.getCurves():[],An=vn?{secp256k1:kn.includes("secp256k1")?"secp256k1":void 0,p256:kn.includes("prime256v1")?"prime256v1":void 0,p384:kn.includes("secp384r1")?"secp384r1":void 0,p521:kn.includes("secp521r1")?"secp521r1":void 0,ed25519:kn.includes("ED25519")?"ED25519":void 0,curve25519:kn.includes("X25519")?"X25519":void 0,brainpoolP256r1:kn.includes("brainpoolP256r1")?"brainpoolP256r1":void 0,brainpoolP384r1:kn.includes("brainpoolP384r1")?"brainpoolP384r1":void 0,brainpoolP512r1:kn.includes("brainpoolP512r1")?"brainpoolP512r1":void 0}:{},Sn={p256:{oid:[6,8,42,134,72,206,61,3,1,7],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha256,cipher:Z.symmetric.aes128,node:An.p256,web:_n.p256,payloadSize:32,sharedSize:256},p384:{oid:[6,5,43,129,4,0,34],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha384,cipher:Z.symmetric.aes192,node:An.p384,web:_n.p384,payloadSize:48,sharedSize:384},p521:{oid:[6,5,43,129,4,0,35],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha512,cipher:Z.symmetric.aes256,node:An.p521,web:_n.p521,payloadSize:66,sharedSize:528},secp256k1:{oid:[6,5,43,129,4,0,10],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha256,cipher:Z.symmetric.aes128,node:An.secp256k1,payloadSize:32},ed25519:{oid:[6,9,43,6,1,4,1,218,71,15,1],keyType:Z.publicKey.eddsaLegacy,hash:Z.hash.sha512,node:!1,payloadSize:32},curve25519:{oid:[6,10,43,6,1,4,1,151,85,1,5,1],keyType:Z.publicKey.ecdh,hash:Z.hash.sha256,cipher:Z.symmetric.aes128,node:!1,payloadSize:32},brainpoolP256r1:{oid:[6,9,43,36,3,3,2,8,1,1,7],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha256,cipher:Z.symmetric.aes128,node:An.brainpoolP256r1,payloadSize:32},brainpoolP384r1:{oid:[6,9,43,36,3,3,2,8,1,1,11],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha384,cipher:Z.symmetric.aes192,node:An.brainpoolP384r1,payloadSize:48},brainpoolP512r1:{oid:[6,9,43,36,3,3,2,8,1,1,13],keyType:Z.publicKey.ecdsa,hash:Z.hash.sha512,cipher:Z.symmetric.aes256,node:An.brainpoolP512r1,payloadSize:64}};class En{constructor(e,t){try{(Y.isArray(e)||Y.isUint8Array(e))&&(e=new sn(e)),e instanceof sn&&(e=e.getName()),this.name=Z.write(Z.curve,e)}catch(e){throw new gn("Unknown curve")}t=t||Sn[this.name],this.keyType=t.keyType,this.oid=t.oid,this.hash=t.hash,this.cipher=t.cipher,this.node=t.node&&Sn[this.name],this.web=t.web&&Sn[this.name],this.payloadSize=t.payloadSize,this.web&&Y.getWebCrypto()?this.type="web":this.node&&Y.getNodeCrypto()?this.type="node":"curve25519"===this.name?this.type="curve25519":"ed25519"===this.name&&(this.type="ed25519")}async genKeyPair(){let e;switch(this.type){case"web":try{return await async function(e){const t=await wn.generateKey({name:"ECDSA",namedCurve:_n[e]},!0,["sign","verify"]),r=await wn.exportKey("jwk",t.privateKey),i=await wn.exportKey("jwk",t.publicKey);return{publicKey:xn(i),privateKey:ie(r.d)}}(this.name)}catch(e){Y.printDebugError("Browser did not support generating ec key "+e.message);break}case"node":return async function(e){const t=vn.createECDH(An[e]);return await t.generateKeys(),{publicKey:new Uint8Array(t.getPublicKey()),privateKey:new Uint8Array(t.getPrivateKey())}}(this.name);case"curve25519":{const t=Li(32);t[0]=127&t[0]|64,t[31]&=248;const r=t.slice().reverse();e=Fi.box.keyPair.fromSecretKey(r);return{publicKey:Y.concatUint8Array([new Uint8Array([64]),e.publicKey]),privateKey:t}}case"ed25519":{const e=Li(32),t=Fi.sign.keyPair.fromSeed(e);return{publicKey:Y.concatUint8Array([new Uint8Array([64]),t.publicKey]),privateKey:e}}}const t=await un(this.name);return e=await t.genKeyPair({entropy:Y.uint8ArrayToString(Li(32))}),{publicKey:new Uint8Array(e.getPublic("array",!1)),privateKey:e.getPrivate().toArrayLike(Uint8Array)}}}async function Pn(e,t,r,i){const n={p256:!0,p384:!0,p521:!0,secp256k1:!0,curve25519:e===Z.publicKey.ecdh,brainpoolP256r1:!0,brainpoolP384r1:!0,brainpoolP512r1:!0},a=t.getName();if(!n[a])return!1;if("curve25519"===a){i=i.slice().reverse();const{publicKey:e}=Fi.box.keyPair.fromSecretKey(i);r=new Uint8Array(r);const t=new Uint8Array([64,...e]);return!!Y.equalsUint8Array(t,r)}const s=await un(a);try{r=cn(s,r).getPublic()}catch(e){return!1}return!!on(s,i).getPublic().eq(r)}function xn(e){const t=ie(e.x),r=ie(e.y),i=new Uint8Array(t.length+r.length+1);return i[0]=4,i.set(t,1),i.set(r,t.length+1),i}function Mn(e,t,r){const i=e,n=r.slice(1,i+1),a=r.slice(i+1,2*i+1);return{kty:"EC",crv:t,x:ne(n,!0),y:ne(a,!0),ext:!0}}function Kn(e,t,r,i){const n=Mn(e,t,r);return n.d=ne(i,!0),n}const Cn=Y.getWebCrypto(),Dn=Y.getNodeCrypto();async function Un(e,t,r,i,n,a){const s=new En(e);if(r&&!Y.isStream(r)){const e={publicKey:i,privateKey:n};switch(s.type){case"web":try{return await async function(e,t,r,i){const n=e.payloadSize,a=Kn(e.payloadSize,_n[e.name],i.publicKey,i.privateKey),s=await Cn.importKey("jwk",a,{name:"ECDSA",namedCurve:_n[e.name],hash:{name:Z.read(Z.webHash,e.hash)}},!1,["sign"]),o=new Uint8Array(await Cn.sign({name:"ECDSA",namedCurve:_n[e.name],hash:{name:Z.read(Z.webHash,t)}},s,r));return{r:o.slice(0,n),s:o.slice(n,n<<1)}}(s,t,r,e)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;Y.printDebugError("Browser did not support signing: "+e.message)}break;case"node":{const i=await async function(e,t,r,i){const n=Dn.createSign(Z.read(Z.hash,t));n.write(r),n.end();const a=Tn.encode({version:1,parameters:e.oid,privateKey:Array.from(i.privateKey),publicKey:{unused:0,data:Array.from(i.publicKey)}},"pem",{label:"EC PRIVATE KEY"});return Bn.decode(n.sign(a),"der")}(s,t,r,e);return{r:i.r.toArrayLike(Uint8Array),s:i.s.toArrayLike(Uint8Array)}}}}return async function(e,t,r){const i=await un(e.name),n=on(i,r),a=n.sign(t);return{r:a.r.toArrayLike(Uint8Array),s:a.s.toArrayLike(Uint8Array)}}(s,a,n)}async function Rn(e,t,r,i,n,a){const s=new En(e);if(i&&!Y.isStream(i))switch(s.type){case"web":try{return await async function(e,t,{r,s:i},n,a){const s=Mn(e.payloadSize,_n[e.name],a),o=await Cn.importKey("jwk",s,{name:"ECDSA",namedCurve:_n[e.name],hash:{name:Z.read(Z.webHash,e.hash)}},!1,["verify"]),c=Y.concatUint8Array([r,i]).buffer;return Cn.verify({name:"ECDSA",namedCurve:_n[e.name],hash:{name:Z.read(Z.webHash,t)}},o,c,n)}(s,t,r,i,n)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;Y.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":return async function(e,t,{r,s:i},n,a){const{default:s}=await Promise.resolve().then((function(){return qp})),o=Dn.createVerify(Z.read(Z.hash,t));o.write(n),o.end();const c=qn.encode({algorithm:{algorithm:[1,2,840,10045,2,1],parameters:e.oid},subjectPublicKey:{unused:0,data:Array.from(a)}},"pem",{label:"PUBLIC KEY"}),u=Bn.encode({r:new s(r),s:new s(i)},"der");try{return o.verify(c,u)}catch(e){return!1}}(s,t,r,i,n)}return async function(e,t,r,i){const n=await un(e.name),a=cn(n,i);return a.verify(r,t)}(s,r,void 0===t?i:a,n)}const In=void 0,Bn=Dn?In.define("ECDSASignature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())})):void 0,Tn=Dn?In.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().any(),this.key("publicKey").explicit(1).optional().bitstr())})):void 0,zn=Dn?In.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().any())})):void 0,qn=Dn?In.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(zn),this.key("subjectPublicKey").bitstr())})):void 0;var Fn=/*#__PURE__*/Object.freeze({__proto__:null,sign:Un,verify:Rn,validateParams:async function(e,t,r){const i=new En(e);if(i.keyType!==Z.publicKey.ecdsa)return!1;switch(i.type){case"web":case"node":{const i=Li(8),n=Z.hash.sha256,a=await Vr.digest(n,i);try{const s=await Un(e,n,i,t,r,a);return await Rn(e,n,s,i,t,a)}catch(e){return!1}}default:return Pn(Z.publicKey.ecdsa,e,t,r)}}});Fi.hash=e=>new Uint8Array(er().update(e).digest());var On=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){if(Vr.getHashByteLength(t)new Uint8Array(er().update(e).digest());var Nn=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===Z.publicKey.ed25519){const e=Li(32),{publicKey:t}=Fi.sign.keyPair.fromSeed(e);return{A:t,seed:e}}throw Error("Unsupported EdDSA algorithm")},sign:async function(e,t,r,i,n,a){if(Vr.getHashByteLength(t)=0;--e)for(let t=o-1;t>=0;--t)c[1]=o*e+(t+1),u[0]=a[0]^c[0],u[1]=a[1]^c[1],u[2]=s[2*t],u[3]=s[2*t+1],u=Wn(r.decrypt(Gn(u))),a=u.subarray(0,2),s[2*t]=u[2],s[2*t+1]=u[3];if(a[0]===i[0]&&a[1]===i[1])return Gn(s);throw Error("Key Data Integrity failed")}function Wn(e){const{length:t}=e,r=function(e){if(Y.isString(e)){const{length:t}=e,r=new ArrayBuffer(t),i=new Uint8Array(r);for(let r=0;r0){const r=e[t-1];if(r>=1){const i=e.subarray(t-r),n=new Uint8Array(r).fill(r);if(Y.equalsUint8Array(i,n))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Xn=/*#__PURE__*/Object.freeze({__proto__:null,encode:$n,decode:Zn});const Yn=Y.getWebCrypto(),Qn=Y.getNodeCrypto();function Jn(e,t,r,i){return Y.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),Y.stringToUint8Array("Anonymous Sender "),i.subarray(0,20)])}async function ea(e,t,r,i,n=!1,a=!1){let s;if(n){for(s=0;s=0&&0===t[s];s--);t=t.subarray(0,s+1)}return(await Vr.digest(e,Y.concatUint8Array([new Uint8Array([0,0,0,1]),t,i]))).subarray(0,r)}async function ta(e,t){switch(e.type){case"curve25519":{const r=Li(32),{secretKey:i,sharedKey:n}=await ra(e,t,null,r);let{publicKey:a}=Fi.box.keyPair.fromSecretKey(i);return a=Y.concatUint8Array([new Uint8Array([64]),a]),{publicKey:a,sharedKey:n}}case"web":if(e.web&&Y.getWebCrypto())try{return await async function(e,t){const r=Mn(e.payloadSize,e.web.web,t);let i=Yn.generateKey({name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]),n=Yn.importKey("jwk",r,{name:"ECDH",namedCurve:e.web.web},!1,[]);[i,n]=await Promise.all([i,n]);let a=Yn.deriveBits({name:"ECDH",namedCurve:e.web.web,public:n},i.privateKey,e.web.sharedSize),s=Yn.exportKey("jwk",i.publicKey);[a,s]=await Promise.all([a,s]);const o=new Uint8Array(a),c=new Uint8Array(xn(s));return{publicKey:c,sharedKey:o}}(e,t)}catch(e){Y.printDebugError(e)}break;case"node":return async function(e,t){const r=Qn.createECDH(e.node.node);r.generateKeys();const i=new Uint8Array(r.computeSecret(t)),n=new Uint8Array(r.getPublicKey());return{publicKey:n,sharedKey:i}}(e,t)}return async function(e,t){const r=await un(e.name),i=await e.genKeyPair();t=cn(r,t);const n=on(r,i.privateKey),a=i.publicKey,s=n.derive(t.getPublic()),o=r.curve.p.byteLength(),c=s.toArrayLike(Uint8Array,"be",o);return{publicKey:a,sharedKey:c}}(e,t)}async function ra(e,t,r,i){if(i.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(i,e.payloadSize-i.length),i=t}switch(e.type){case"curve25519":{const e=i.slice().reverse();return{secretKey:e,sharedKey:Fi.scalarMult(e,t.subarray(1))}}case"web":if(e.web&&Y.getWebCrypto())try{return await async function(e,t,r,i){const n=Kn(e.payloadSize,e.web.web,r,i);let a=Yn.importKey("jwk",n,{name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]);const s=Mn(e.payloadSize,e.web.web,t);let o=Yn.importKey("jwk",s,{name:"ECDH",namedCurve:e.web.web},!0,[]);[a,o]=await Promise.all([a,o]);let c=Yn.deriveBits({name:"ECDH",namedCurve:e.web.web,public:o},a,e.web.sharedSize),u=Yn.exportKey("jwk",a);[c,u]=await Promise.all([c,u]);const h=new Uint8Array(c);return{secretKey:ie(u.d),sharedKey:h}}(e,t,r,i)}catch(e){Y.printDebugError(e)}break;case"node":return async function(e,t,r){const i=Qn.createECDH(e.node.node);i.setPrivateKey(r);const n=new Uint8Array(i.computeSecret(t));return{secretKey:new Uint8Array(i.getPrivateKey()),sharedKey:n}}(e,t,i)}return async function(e,t,r){const i=await un(e.name);t=cn(i,t),r=on(i,r);const n=new Uint8Array(r.getPrivate()),a=r.derive(t.getPublic()),s=i.curve.p.byteLength(),o=a.toArrayLike(Uint8Array,"be",s);return{secretKey:n,sharedKey:o}}(e,t,i)}var ia=/*#__PURE__*/Object.freeze({__proto__:null,validateParams:async function(e,t,r){return Pn(Z.publicKey.ecdh,e,t,r)},encrypt:async function(e,t,r,i,n){const a=$n(r),s=new En(e),{publicKey:o,sharedKey:c}=await ta(s,i),u=Jn(Z.publicKey.ecdh,e,t,n),{keySize:h}=Zr(t.cipher);return{publicKey:o,wrappedKey:jn(await ea(t.hash,c,h,u),a)}},decrypt:async function(e,t,r,i,n,a,s){const o=new En(e),{sharedKey:c}=await ra(o,r,n,a),u=Jn(Z.publicKey.ecdh,e,t,s),{keySize:h}=Zr(t.cipher);let d;for(let e=0;e<3;e++)try{return Zn(Hn(await ea(t.hash,c,h,u,1===e,2===e),i))}catch(e){d=e}throw d}});const na=Y.getWebCrypto(),aa=Y.getNodeCrypto(),sa=aa&&aa.webcrypto&&aa.webcrypto.subtle;async function oa(e,t,r,i,n){const a=Z.read(Z.webHash,e);if(!a)throw Error("Hash algo not supported with HKDF");if(na||sa){const e=na||sa,s=await e.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await e.deriveBits({name:"HKDF",hash:a,salt:r,info:i},s,8*n);return new Uint8Array(o)}if(aa){const a=Z.read(Z.hash,e),s=(e,t)=>aa.createHmac(a,e).update(t).digest(),o=s(r,t),c=o.length,u=Math.ceil(n/c),h=new Uint8Array(u*c),d=new Uint8Array(c+i.length+1);d.set(i,c);for(let e=0;e0?d:d.subarray(c));d.set(t,0),h.set(t,e*c)}return h.subarray(0,n)}throw Error("No HKDF implementation available")}const ca={x25519:Y.encodeUTF8("OpenPGP X25519")};var ua=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===Z.publicKey.x25519){const e=Li(32),{publicKey:t}=Fi.box.keyPair.fromSecretKey(e);return{A:t,k:e}}throw Error("Unsupported ECDH algorithm")},validateParams:async function(e,t,r){if(e===Z.publicKey.x25519){const{publicKey:e}=Fi.box.keyPair.fromSecretKey(r);return Y.equalsUint8Array(t,e)}return!1},encrypt:async function(e,t,r){if(e===Z.publicKey.x25519){const e=Li(32),i=Fi.scalarMult(e,r),{publicKey:n}=Fi.box.keyPair.fromSecretKey(e),a=Y.concatUint8Array([n,r,i]),{keySize:s}=Zr(Z.symmetric.aes128);return{ephemeralPublicKey:n,wrappedKey:jn(await oa(Z.hash.sha256,a,new Uint8Array,ca.x25519,s),t)}}throw Error("Unsupported ECDH algorithm")},decrypt:async function(e,t,r,i,n){if(e===Z.publicKey.x25519){const e=Fi.scalarMult(n,t),a=Y.concatUint8Array([t,i,e]),{keySize:s}=Zr(Z.symmetric.aes128);return Hn(await oa(Z.hash.sha256,a,new Uint8Array,ca.x25519,s),r)}throw Error("Unsupported ECDH algorithm")}}),ha=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:En,ecdh:ia,ecdhX:ua,ecdsa:Fn,eddsaLegacy:On,eddsa:Nn,generate:async function(e){const t=await Y.getBigInteger();e=new En(e);const r=await e.genKeyPair(),i=new t(r.publicKey).toUint8Array(),n=new t(r.privateKey).toUint8Array("be",e.payloadSize);return{oid:e.oid,Q:i,secret:n,hash:e.hash,cipher:e.cipher}},getPreferredHashAlgo:function(e){return Sn[Z.write(Z.curve,e.toHex())].hash}});var da=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){const s=await Y.getBigInteger(),o=new s(1);let c,u,h,d;i=new s(i),n=new s(n),r=new s(r),a=new s(a),r=r.mod(i),a=a.mod(n);const f=new s(t.subarray(0,n.byteLength())).mod(n);for(;;){if(c=await Ni(o,n),u=r.modExp(c,i).imod(n),u.isZero())continue;const e=a.mul(u).imod(n);if(d=f.add(e).imod(n),h=c.modInv(n).imul(d).imod(n),!h.isZero())break}return{r:u.toUint8Array("be",n.byteLength()),s:h.toUint8Array("be",n.byteLength())}},verify:async function(e,t,r,i,n,a,s,o){const c=await Y.getBigInteger(),u=new c(0);if(t=new c(t),r=new c(r),a=new c(a),s=new c(s),n=new c(n),o=new c(o),t.lte(u)||t.gte(s)||r.lte(u)||r.gte(s))return Y.printDebug("invalid DSA Signature"),!1;const h=new c(i.subarray(0,s.byteLength())).imod(s),d=r.modInv(s);if(d.isZero())return Y.printDebug("invalid DSA Signature"),!1;n=n.mod(a),o=o.mod(a);const f=h.mul(d).imod(s),l=t.mul(d).imod(s),p=n.modExp(f,a),y=o.modExp(l,a);return p.mul(y).imod(a).imod(s).equal(t)},validateParams:async function(e,t,r,i,n){const a=await Y.getBigInteger();e=new a(e),t=new a(t),r=new a(r),i=new a(i);const s=new a(1);if(r.lte(s)||r.gte(e))return!1;if(!e.dec().mod(t).isZero())return!1;if(!r.modExp(t,e).isOne())return!1;const o=new a(t.bitLength()),c=new a(150);if(o.lt(c)||!await Wi(t,null,32))return!1;n=new a(n);const u=new a(2),h=await Ni(u.leftShift(o.dec()),u.leftShift(o)),d=t.mul(h).add(n);return!!i.equal(r.modExp(d,e))}}),fa={rsa:nn,elgamal:an,elliptic:ha,dsa:da,nacl:Fi};var la=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaSign:return{s:Y.readMPI(t.subarray(r))};case Z.publicKey.dsa:case Z.publicKey.ecdsa:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;return{r:e,s:Y.readMPI(t.subarray(r))}}case Z.publicKey.eddsaLegacy:{let e=Y.readMPI(t.subarray(r));r+=e.length+2,e=Y.leftPad(e,32);let i=Y.readMPI(t.subarray(r));return i=Y.leftPad(i,32),{r:e,s:i}}case Z.publicKey.ed25519:{const e=t.subarray(r,r+64);return r+=e.length,{RS:e}}default:throw new gn("Unknown signature algorithm.")}},verify:async function(e,t,r,i,n,a){switch(e){case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaSign:{const{n:e,e:s}=i,o=Y.leftPad(r.s,e.length);return fa.rsa.verify(t,n,o,e,s,a)}case Z.publicKey.dsa:{const{g:e,p:n,q:s,y:o}=i,{r:c,s:u}=r;return fa.dsa.verify(t,c,u,a,e,n,s,o)}case Z.publicKey.ecdsa:{const{oid:e,Q:s}=i,o=new fa.elliptic.CurveWithOID(e).payloadSize,c=Y.leftPad(r.r,o),u=Y.leftPad(r.s,o);return fa.elliptic.ecdsa.verify(e,t,{r:c,s:u},n,s,a)}case Z.publicKey.eddsaLegacy:{const{oid:e,Q:s}=i;return fa.elliptic.eddsaLegacy.verify(e,t,r,n,s,a)}case Z.publicKey.ed25519:{const{A:s}=i;return fa.elliptic.eddsa.verify(e,t,r,n,s,a)}default:throw Error("Unknown signature algorithm.")}},sign:async function(e,t,r,i,n,a){if(!r||!i)throw Error("Missing key parameters");switch(e){case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaSign:{const{n:e,e:s}=r,{d:o,p:c,q:u,u:h}=i;return{s:await fa.rsa.sign(t,n,e,s,o,c,u,h,a)}}case Z.publicKey.dsa:{const{g:e,p:n,q:s}=r,{x:o}=i;return fa.dsa.sign(t,a,e,n,s,o)}case Z.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case Z.publicKey.ecdsa:{const{oid:e,Q:s}=r,{d:o}=i;return fa.elliptic.ecdsa.sign(e,t,n,s,o,a)}case Z.publicKey.eddsaLegacy:{const{oid:e,Q:s}=r,{seed:o}=i;return fa.elliptic.eddsaLegacy.sign(e,t,n,s,o,a)}case Z.publicKey.ed25519:{const{A:s}=r,{seed:o}=i;return fa.elliptic.eddsa.sign(e,t,n,s,o,a)}default:throw Error("Unknown signature algorithm.")}}});class pa{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return Y.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class ya{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new gn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class ba{static fromObject({wrappedKey:e,algorithm:t}){const r=new ba;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=e.subarray(t,t+r),t+=r}write(){return Y.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function ga(e){try{e.getName()}catch(e){throw new gn("Unknown curve OID")}}var ma=/*#__PURE__*/Object.freeze({__proto__:null,publicKeyEncrypt:async function(e,t,r,i,n){switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await fa.rsa.encrypt(i,e,t)}}case Z.publicKey.elgamal:{const{p:e,g:t,y:n}=r;return fa.elgamal.encrypt(i,e,t,n)}case Z.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:a}=r,{publicKey:s,wrappedKey:o}=await fa.elliptic.ecdh.encrypt(e,a,i,t,n);return{V:s,C:new pa(o)}}case Z.publicKey.x25519:{if(!Y.isAES(t))throw Error("X25519 keys can only encrypt AES session keys");const{A:n}=r,{ephemeralPublicKey:a,wrappedKey:s}=await fa.elliptic.ecdhX.encrypt(e,i,n);return{ephemeralPublicKey:a,C:ba.fromObject({algorithm:t,wrappedKey:s})}}default:return[]}},publicKeyDecrypt:async function(e,t,r,i,n,a){switch(e){case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaEncrypt:{const{c:e}=i,{n,e:s}=t,{d:o,p:c,q:u,u:h}=r;return fa.rsa.decrypt(e,n,s,o,c,u,h,a)}case Z.publicKey.elgamal:{const{c1:e,c2:n}=i,s=t.p,o=r.x;return fa.elgamal.decrypt(e,n,s,o,a)}case Z.publicKey.ecdh:{const{oid:e,Q:a,kdfParams:s}=t,{d:o}=r,{V:c,C:u}=i;return fa.elliptic.ecdh.decrypt(e,s,c,u.data,a,o,n)}case Z.publicKey.x25519:{const{A:n}=t,{k:a}=r,{ephemeralPublicKey:s,C:o}=i;if(!Y.isAES(o.algorithm))throw Error("AES session key expected");return fa.elliptic.ecdhX.decrypt(e,s,o.wrappedKey,n,a)}default:throw Error("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaSign:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;const i=Y.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{n:e,e:i}}}case Z.publicKey.dsa:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;const i=Y.readMPI(t.subarray(r));r+=i.length+2;const n=Y.readMPI(t.subarray(r));r+=n.length+2;const a=Y.readMPI(t.subarray(r));return r+=a.length+2,{read:r,publicParams:{p:e,q:i,g:n,y:a}}}case Z.publicKey.elgamal:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;const i=Y.readMPI(t.subarray(r));r+=i.length+2;const n=Y.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{p:e,g:i,y:n}}}case Z.publicKey.ecdsa:{const e=new sn;r+=e.read(t),ga(e);const i=Y.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{oid:e,Q:i}}}case Z.publicKey.eddsaLegacy:{const e=new sn;r+=e.read(t),ga(e);let i=Y.readMPI(t.subarray(r));return r+=i.length+2,i=Y.leftPad(i,33),{read:r,publicParams:{oid:e,Q:i}}}case Z.publicKey.ecdh:{const e=new sn;r+=e.read(t),ga(e);const i=Y.readMPI(t.subarray(r));r+=i.length+2;const n=new ya;return r+=n.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:i,kdfParams:n}}}case Z.publicKey.ed25519:case Z.publicKey.x25519:{const e=t.subarray(r,r+32);return r+=e.length,{read:r,publicParams:{A:e}}}default:throw new gn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let i=0;switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaSign:{const e=Y.readMPI(t.subarray(i));i+=e.length+2;const r=Y.readMPI(t.subarray(i));i+=r.length+2;const n=Y.readMPI(t.subarray(i));i+=n.length+2;const a=Y.readMPI(t.subarray(i));return i+=a.length+2,{read:i,privateParams:{d:e,p:r,q:n,u:a}}}case Z.publicKey.dsa:case Z.publicKey.elgamal:{const e=Y.readMPI(t.subarray(i));return i+=e.length+2,{read:i,privateParams:{x:e}}}case Z.publicKey.ecdsa:case Z.publicKey.ecdh:{const e=new En(r.oid);let n=Y.readMPI(t.subarray(i));return i+=n.length+2,n=Y.leftPad(n,e.payloadSize),{read:i,privateParams:{d:n}}}case Z.publicKey.eddsaLegacy:{const e=new En(r.oid);let n=Y.readMPI(t.subarray(i));return i+=n.length+2,n=Y.leftPad(n,e.payloadSize),{read:i,privateParams:{seed:n}}}case Z.publicKey.ed25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{seed:e}}}case Z.publicKey.x25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{k:e}}}default:throw new gn("Unknown public key encryption algorithm.")}},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:return{c:Y.readMPI(t.subarray(r))};case Z.publicKey.elgamal:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:Y.readMPI(t.subarray(r))}}case Z.publicKey.ecdh:{const e=Y.readMPI(t.subarray(r));r+=e.length+2;const i=new pa;return i.read(t.subarray(r)),{V:e,C:i}}case Z.publicKey.x25519:{const e=t.subarray(r,r+32);r+=e.length;const i=new ba;return i.read(t.subarray(r)),{ephemeralPublicKey:e,C:i}}default:throw new gn("Unknown public key encryption algorithm.")}},serializeParams:function(e,t){const r=new Set([Z.publicKey.ed25519,Z.publicKey.x25519]),i=Object.keys(t).map((i=>{const n=t[i];return Y.isUint8Array(n)?r.has(e)?n:Y.uint8ArrayToMPI(n):n.write()}));return Y.concatUint8Array(i)},generateParams:function(e,t,r){switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaSign:return fa.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:i,q:n,u:a})=>({privateParams:{d:r,p:i,q:n,u:a},publicParams:{n:e,e:t}})));case Z.publicKey.ecdsa:return fa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new sn(e),Q:t}})));case Z.publicKey.eddsaLegacy:return fa.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new sn(e),Q:t}})));case Z.publicKey.ecdh:return fa.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:i,cipher:n})=>({privateParams:{d:r},publicParams:{oid:new sn(e),Q:t,kdfParams:new ya({hash:i,cipher:n})}})));case Z.publicKey.ed25519:return fa.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case Z.publicKey.x25519:return fa.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case Z.publicKey.dsa:case Z.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaSign:{const{n:e,e:i}=t,{d:n,p:a,q:s,u:o}=r;return fa.rsa.validateParams(e,i,n,a,s,o)}case Z.publicKey.dsa:{const{p:e,q:i,g:n,y:a}=t,{x:s}=r;return fa.dsa.validateParams(e,i,n,a,s)}case Z.publicKey.elgamal:{const{p:e,g:i,y:n}=t,{x:a}=r;return fa.elgamal.validateParams(e,i,n,a)}case Z.publicKey.ecdsa:case Z.publicKey.ecdh:{const i=fa.elliptic[Z.read(Z.publicKey,e)],{oid:n,Q:a}=t,{d:s}=r;return i.validateParams(n,a,s)}case Z.publicKey.eddsaLegacy:{const{Q:e,oid:i}=t,{seed:n}=r;return fa.elliptic.eddsaLegacy.validateParams(i,e,n)}case Z.publicKey.ed25519:{const{A:i}=t,{seed:n}=r;return fa.elliptic.eddsa.validateParams(e,i,n)}case Z.publicKey.x25519:{const{A:i}=t,{k:n}=r;return fa.elliptic.ecdhX.validateParams(e,i,n)}default:throw Error("Unknown public key algorithm.")}},getPrefixRandom:async function(e){const{blockSize:t}=Zr(e),r=await Li(t),i=new Uint8Array([r[r.length-2],r[r.length-1]]);return Y.concat([r,i])},generateSessionKey:function(e){const{keySize:t}=Zr(e);return Li(t)},getAEADMode:function(e){const t=Z.read(Z.aead,e);return qi[t]},getCipher:Zr,getPreferredCurveHashAlgo:function(e,t){switch(e){case Z.publicKey.ecdsa:case Z.publicKey.eddsaLegacy:return fa.elliptic.getPreferredHashAlgo(t);case Z.publicKey.ed25519:return fa.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}}});const wa={cipher:Ge,hash:Vr,mode:qi,publicKey:fa,signature:la,random:ji,pkcs1:Yi,pkcs5:Xn,aesKW:Vn};Object.assign(wa,ma);var va="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function _a(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)}const ka={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+i),n);else for(let a=0;a=0;)e[t]=0}const Qa=0,Ja=1,es=2,ts=29,rs=256,is=rs+1+ts,ns=30,as=19,ss=2*is+1,os=15,cs=16,us=7,hs=256,ds=16,fs=17,ls=18,ps=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ys=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],bs=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],gs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ms=Array(2*(is+2));Ya(ms);const ws=Array(2*ns);Ya(ws);const vs=Array(512);Ya(vs);const _s=Array(256);Ya(_s);const ks=Array(ts);Ya(ks);const As=Array(ns);function Ss(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}let Es,Ps,xs;function Ms(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Ks(e){return e<256?vs[e]:vs[256+(e>>>7)]}function Cs(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Ds(e,t,r){e.bi_valid>cs-r?(e.bi_buf|=t<>cs-e.bi_valid,e.bi_valid+=r-cs):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Is(e,t,r){const i=Array(os+1);let n,a,s=0;for(n=1;n<=os;n++)i[n]=s=s+r[n-1]<<1;for(a=0;a<=t;a++){const t=e[2*a+1];0!==t&&(e[2*a]=Rs(i[t]++,t))}}function Bs(e){let t;for(t=0;t8?Cs(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function zs(e,t,r,i){const n=2*t,a=2*r;return e[n]>1;s>=1;s--)qs(e,r,s);c=a;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],qs(e,r,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,r[2*c]=r[2*s]+r[2*o],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,r[2*s+1]=r[2*o+1]=c,e.heap[1]=c++,qs(e,r,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){const r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let u,h,d,f,l,p,y=0;for(f=0;f<=os;f++)e.bl_count[f]=0;for(r[2*e.heap[e.heap_max]+1]=0,u=e.heap_max+1;uc&&(f=c,y++),r[2*h+1]=f,h>i||(e.bl_count[f]++,l=0,h>=o&&(l=s[h-o]),p=r[2*h],e.opt_len+=p*(f+l),a&&(e.static_len+=p*(n[2*h+1]+l)));if(0!==y){do{for(f=c-1;0===e.bl_count[f];)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,y-=2}while(y>0);for(f=c;0!==f;f--)for(h=e.bl_count[f];0!==h;)d=e.heap[--u],d>i||(r[2*d+1]!==f&&(e.opt_len+=(f-r[2*d+1])*r[2*d],r[2*d+1]=f),h--)}}(e,t),Is(r,u,e.bl_count)}function Ls(e,t,r){let i,n,a=-1,s=t[1],o=0,c=7,u=4;for(0===s&&(c=138,u=3),t[2*(r+1)+1]=65535,i=0;i<=r;i++)n=s,s=t[2*(i+1)+1],++o>=7;i=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function Vs(e,t,r,i){let n,a,s=0;e.level>0?(e.strm.data_type===Za&&(e.strm.data_type=function(e){let t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return Va;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return $a;for(t=32;t=3&&0===e.bl_tree[2*gs[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),n=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=n&&(n=a)):n=a=r+5,r+4<=n&&-1!==t?Ws(e,t,r,i):e.strategy===Ga||a===n?(Ds(e,(Ja<<1)+(i?1:0),3),Fs(e,ms,ws)):(Ds(e,(es<<1)+(i?1:0),3),function(e,t,r,i){let n;for(Ds(e,t-257,5),Ds(e,r-1,5),Ds(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(_s[r]+rs+1)]++,e.dyn_dtree[2*Ks(t)]++),e.last_lit===e.lit_bufsize-1}function Zs(e,t,r,i){let n=65535&e|0,a=e>>>16&65535|0,s=0;for(;0!==r;){s=r>2e3?2e3:r,r-=s;do{n=n+t[i++]|0,a=a+n|0}while(--s);n%=65521,a%=65521}return n|a<<16|0}const Xs=function(){let e;const t=[];for(let r=0;r<256;r++){e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function Ys(e,t,r,i){const n=Xs,a=i+r;e^=-1;for(let r=i;r>>8^n[255&(e^t[r])];return-1^e}var Qs={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};const Js=9,eo=3,to=258,ro=to+eo+1,io=32,no=42,ao=69,so=73,oo=91,co=103,uo=113,ho=666,fo=1,lo=2,po=3,yo=4,bo=3;function go(e,t){return e.msg=Qs[t],t}function mo(e){return(e<<1)-(e>4?9:0)}function wo(e){let t=e.length;for(;--t>=0;)e[t]=0}function vo(e){const t=e.state;let r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(Ma(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function _o(e,t){Vs(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,vo(e.strm)}function ko(e,t){e.pending_buf[e.pending++]=t}function Ao(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function So(e,t,r,i){let n=e.avail_in;return n>i&&(n=i),0===n?0:(e.avail_in-=n,Ma(t,e.input,e.next_in,n,r),1===e.state.wrap?e.adler=Zs(e.adler,t,n,r):2===e.state.wrap&&(e.adler=Ys(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function Eo(e,t){let r,i,n=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-ro?e.strstart-(e.w_size-ro):0,u=e.window,h=e.w_mask,d=e.prev,f=e.strstart+to;let l=u[a+s-1],p=u[a+s];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do{if(r=t,u[r+s]===p&&u[r+s-1]===l&&u[r]===u[a]&&u[++r]===u[a+1]){a+=2,r++;do{}while(u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&as){if(e.match_start=t,s=i,i>=o)break;l=u[a+s-1],p=u[a+s]}}}while((t=d[t&h])>c&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Po(e){const t=e.w_size;let r,i,n,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ro)){Ma(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do{n=e.head[--r],e.head[r]=n>=t?n-t:0}while(--i);i=t,r=i;do{n=e.prev[--r],e.prev[r]=n>=t?n-t:0}while(--i);a+=t}if(0===e.strm.avail_in)break;if(i=So(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=i,e.lookahead+e.insert>=eo)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=eo&&(e.ins_h=(e.ins_h<=eo)if(i=$s(e,e.strstart-e.match_start,e.match_length-eo),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=eo){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=eo&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=eo-1)),e.prev_length>=eo&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-eo,i=$s(e,e.strstart-1-e.prev_match,e.prev_length-eo),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Po(e),0===e.lookahead&&t===Ka)return fo;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;const i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,_o(e,!1),0===e.strm.avail_out))return fo;if(e.strstart-e.block_start>=e.w_size-ro&&(_o(e,!1),0===e.strm.avail_out))return fo}return e.insert=0,t===Ra?(_o(e,!0),0===e.strm.avail_out?po:yo):(e.strstart>e.block_start&&(_o(e,!1),e.strm.avail_out),fo)})),new Ko(4,4,8,4,xo),new Ko(4,5,16,8,xo),new Ko(4,6,32,32,xo),new Ko(4,4,16,16,Mo),new Ko(8,16,32,32,Mo),new Ko(8,16,128,128,Mo),new Ko(8,32,128,256,Mo),new Ko(32,128,258,1024,Mo),new Ko(32,258,258,4096,Mo)];class Do{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Xa,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Ea(1146),this.dyn_dtree=new Ea(122),this.bl_tree=new Ea(78),wo(this.dyn_ltree),wo(this.dyn_dtree),wo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Ea(16),this.heap=new Ea(573),wo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Ea(573),wo(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}}function Uo(e){const t=function(e){let t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=Za,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?no:uo,e.adler=2===t.wrap?0:1,t.last_flush=Ka,Hs(t),Ta):go(e,Fa)}(e);return t===Ta&&function(e){e.window_size=2*e.w_size,wo(e.head),e.max_lazy_match=Co[e.level].max_lazy,e.good_match=Co[e.level].good_length,e.nice_match=Co[e.level].nice_length,e.max_chain_length=Co[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=eo-1,e.match_available=0,e.ins_h=0}(e.state),t}function Ro(e,t){let r,i,n,a;if(!e||!e.state||t>Ia||t<0)return e?go(e,Fa):Fa;if(i=e.state,!e.output||!e.input&&0!==e.avail_in||i.status===ho&&t!==Ra)return go(e,0===e.avail_out?La:Fa);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===no)if(2===i.wrap)e.adler=0,ko(i,31),ko(i,139),ko(i,8),i.gzhead?(ko(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),ko(i,255&i.gzhead.time),ko(i,i.gzhead.time>>8&255),ko(i,i.gzhead.time>>16&255),ko(i,i.gzhead.time>>24&255),ko(i,9===i.level?2:i.strategy>=Ha||i.level<2?4:0),ko(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ko(i,255&i.gzhead.extra.length),ko(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Ys(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=ao):(ko(i,0),ko(i,0),ko(i,0),ko(i,0),ko(i,0),ko(i,9===i.level?2:i.strategy>=Ha||i.level<2?4:0),ko(i,bo),i.status=uo);else{let t=Xa+(i.w_bits-8<<4)<<8,r=-1;r=i.strategy>=Ha||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=io),t+=31-t%31,i.status=uo,Ao(i,t),0!==i.strstart&&(Ao(i,e.adler>>>16),Ao(i,65535&e.adler)),e.adler=1}if(i.status===ao)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),vo(e),n=i.pending,i.pending!==i.pending_buf_size));)ko(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=so)}else i.status=so;if(i.status===so)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),vo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.gzindex=0,i.status=oo)}else i.status=oo;if(i.status===oo)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),vo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=Ys(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.status=co)}else i.status=co;if(i.status===co&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&vo(e),i.pending+2<=i.pending_buf_size&&(ko(i,255&e.adler),ko(i,e.adler>>8&255),e.adler=0,i.status=uo)):i.status=uo),0!==i.pending){if(vo(e),0===e.avail_out)return i.last_flush=-1,Ta}else if(0===e.avail_in&&mo(t)<=mo(r)&&t!==Ra)return go(e,La);if(i.status===ho&&0!==e.avail_in)return go(e,La);if(0!==e.avail_in||0!==i.lookahead||t!==Ka&&i.status!==ho){var s=i.strategy===Ha?function(e,t){let r;for(;;){if(0===e.lookahead&&(Po(e),0===e.lookahead)){if(t===Ka)return fo;break}if(e.match_length=0,r=$s(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(_o(e,!1),0===e.strm.avail_out))return fo}return e.insert=0,t===Ra?(_o(e,!0),0===e.strm.avail_out?po:yo):e.last_lit&&(_o(e,!1),0===e.strm.avail_out)?fo:lo}(i,t):i.strategy===Wa?function(e,t){let r,i,n,a;const s=e.window;for(;;){if(e.lookahead<=to){if(Po(e),e.lookahead<=to&&t===Ka)return fo;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=eo&&e.strstart>0&&(n=e.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){a=e.strstart+to;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&ne.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=eo?(r=$s(e,1,e.match_length-eo),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=$s(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(_o(e,!1),0===e.strm.avail_out))return fo}return e.insert=0,t===Ra?(_o(e,!0),0===e.strm.avail_out?po:yo):e.last_lit&&(_o(e,!1),0===e.strm.avail_out)?fo:lo}(i,t):Co[i.level].func(i,t);if(s!==po&&s!==yo||(i.status=ho),s===fo||s===po)return 0===e.avail_out&&(i.last_flush=-1),Ta;if(s===lo&&(t===Ca?Gs(i):t!==Ia&&(Ws(i,0,0,!1),t===Ua&&(wo(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),vo(e),0===e.avail_out))return i.last_flush=-1,Ta}return t!==Ra?Ta:i.wrap<=0?za:(2===i.wrap?(ko(i,255&e.adler),ko(i,e.adler>>8&255),ko(i,e.adler>>16&255),ko(i,e.adler>>24&255),ko(i,255&e.total_in),ko(i,e.total_in>>8&255),ko(i,e.total_in>>16&255),ko(i,e.total_in>>24&255)):(Ao(i,e.adler>>>16),Ao(i,65535&e.adler)),vo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Ta:za)}try{String.fromCharCode.call(null,0)}catch(e){}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}const Io=new Sa(256);for(let e=0;e<256;e++)Io[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;function Bo(e){let t,r,i,n,a=0;const s=e.length;for(i=0;i>>6,o[n++]=128|63&t):t<65536?(o[n++]=224|t>>>12,o[n++]=128|t>>>6&63,o[n++]=128|63&t):(o[n++]=240|t>>>18,o[n++]=128|t>>>12&63,o[n++]=128|t>>>6&63,o[n++]=128|63&t);return o}Io[254]=Io[254]=1;class To{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}class zo{constructor(e){this.options={level:Na,method:Xa,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,...e||{}};const t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new To,this.strm.avail_out=0;var r,i,n=function(e,t,r,i,n,a){if(!e)return Fa;let s=1;if(t===Na&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),n<1||n>Js||r!==Xa||i<8||i>15||t<0||t>9||a<0||a>Ga)return go(e,Fa);8===i&&(i=9);const o=new Do;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=i,o.w_size=1<=r.w_size&&(0===a&&(wo(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new Sa(r.w_size),Ma(u,t,h-r.w_size,r.w_size,0),t=u,h=r.w_size),s=e.avail_in,o=e.next_in,c=e.input,e.avail_in=h,e.next_in=0,e.input=t,Po(r);r.lookahead>=eo;){i=r.strstart,n=r.lookahead-(eo-1);do{r.ins_h=(r.ins_h<0||0===r.avail_out)&&n!==za);return a===Ra?(n=function(e){let t;return e&&e.state?(t=e.state.status,t!==no&&t!==ao&&t!==so&&t!==oo&&t!==co&&t!==uo&&t!==ho?go(e,Fa):(e.state=null,t===uo?go(e,Oa):Ta)):Fa}(this.strm),this.onEnd(n),this.ended=!0,n===Ta):a!==Da||(this.onEnd(Ta),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ta&&(this.result=xa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}const qo=30,Fo=12;function Oo(e,t){let r,i,n,a,s,o,c,u,h,d;const f=e.state;r=e.next_in;const l=e.input,p=r+(e.avail_in-5);i=e.next_out;const y=e.output,b=i-(t-e.avail_out),g=i+(e.avail_out-257),m=f.dmax,w=f.wsize,v=f.whave,_=f.wnext,k=f.window;n=f.hold,a=f.bits;const A=f.lencode,S=f.distcode,E=(1<>>24,n>>>=o,a-=o,o=s>>>16&255,0===o)y[i++]=65535&s;else{if(!(16&o)){if(0==(64&o)){s=A[(65535&s)+(n&(1<>>=o,a-=o),a<15&&(n+=l[r++]<>>24,n>>>=o,a-=o,o=s>>>16&255,!(16&o)){if(0==(64&o)){s=S[(65535&s)+(n&(1<m){e.msg="invalid distance too far back",f.mode=qo;break e}if(n>>>=o,a-=o,o=i-b,u>o){if(o=u-o,o>v&&f.sane){e.msg="invalid distance too far back",f.mode=qo;break e}if(h=0,d=k,0===_){if(h+=w-o,o2;)y[i++]=d[h++],y[i++]=d[h++],y[i++]=d[h++],c-=3;c&&(y[i++]=d[h++],c>1&&(y[i++]=d[h++]))}else{h=i-u;do{y[i++]=y[h++],y[i++]=y[h++],y[i++]=y[h++],c-=3}while(c>2);c&&(y[i++]=y[h++],c>1&&(y[i++]=y[h++]))}break}}break}}while(r>3,r-=c,a-=c<<3,n&=(1<=1&&0===P[g];g--);if(m>g&&(m=g),0===g)return n[a++]=20971520,n[a++]=20971520,o.bits=1,0;for(b=1;b0&&(e===Ho||1!==g))return-1;for(x[1]=0,p=1;pNo||e===Go&&k>jo)return 1;for(;;){M=p-v,s[y]l?(K=D[U+s[y]],C=S[E+s[y]]):(K=96,C=0),u=1<>v)+h]=M<<24|K<<16|C|0}while(0!==h);for(u=1<>=1;if(0!==u?(A&=u-1,A+=u):A=0,y++,0==--P[p]){if(p===g)break;p=t[r+s[y]]}if(p>m&&(A&R)!==d){for(0===v&&(v=m),f+=b,w=p-v,_=1<No||e===Go&&k>jo)return 1;d=A&R,n[d]=m<<24|w<<16|f-a|0}}return 0!==A&&(n[f+A]=p-v<<24|64<<16|0),o.bits=m,0}const Qo=0,Jo=1,ec=2,tc=1,rc=2,ic=3,nc=4,ac=5,sc=6,oc=7,cc=8,uc=9,hc=10,dc=11,fc=12,lc=13,pc=14,yc=15,bc=16,gc=17,mc=18,wc=19,vc=20,_c=21,kc=22,Ac=23,Sc=24,Ec=25,Pc=26,xc=27,Mc=28,Kc=29,Cc=30,Dc=852,Uc=592;function Rc(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}class Ic{constructor(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Ea(320),this.work=new Ea(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}}function Bc(e){let t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,function(e){let t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=tc,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Pa(Dc),t.distcode=t.distdyn=new Pa(Uc),t.sane=1,t.back=-1,Ta):Fa}(e)):Fa}function Tc(e,t){let r,i;return e?(i=new Ic,e.state=i,i.window=null,r=function(e,t){let r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Fa:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,Bc(e))):Fa}(e,t),r!==Ta&&(e.state=null),r):Fa}let zc,qc,Fc=!0;function Oc(e){if(Fc){let t;for(zc=new Pa(512),qc=new Pa(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Yo(Jo,e.lens,0,288,zc,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Yo(ec,e.lens,0,32,qc,0,e.work,{bits:5}),Fc=!1}e.lencode=zc,e.lenbits=9,e.distcode=qc,e.distbits=5}function Lc(e,t,r,i){let n;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(Ma(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>i&&(n=i),Ma(a.window,t,r-i,n,a.wnext),(i-=n)?(Ma(a.window,t,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=Ys(r.check,x,2,0),u=0,h=0,r.mode=rc;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=Cc;break}if((15&u)!==Xa){e.msg="unknown compression method",r.mode=Cc;break}if(u>>>=4,h-=4,k=8+(15&u),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=Cc;break}r.dmax=1<>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=Ys(r.check,x,2,0)),u=0,h=0,r.mode=ic;case ic:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=Ys(r.check,x,4,0)),u=0,h=0,r.mode=nc;case nc:for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=Ys(r.check,x,2,0)),u=0,h=0,r.mode=ac;case ac:if(1024&r.flags){for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>>8&255,r.check=Ys(r.check,x,2,0)),u=0,h=0}else r.head&&(r.head.extra=null);r.mode=sc;case sc:if(1024&r.flags&&(l=r.length,l>o&&(l=o),l&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=Array(r.head.extra_len)),Ma(r.head.extra,i,a,l,k)),512&r.flags&&(r.check=Ys(r.check,i,l,a)),o-=l,a+=l,r.length-=l),r.length))break e;r.length=0,r.mode=oc;case oc:if(2048&r.flags){if(0===o)break e;l=0;do{k=i[a+l++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k))}while(k&&l>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=fc;break;case hc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>=7&h,h-=7&h,r.mode=xc;break}for(;h<3;){if(0===o)break e;o--,u+=i[a++]<>>=1,h-=1,3&u){case 0:r.mode=pc;break;case 1:if(Oc(r),r.mode=vc,t===Ba){u>>>=2,h-=2;break e}break;case 2:r.mode=gc;break;case 3:e.msg="invalid block type",r.mode=Cc}u>>>=2,h-=2;break;case pc:for(u>>>=7&h,h-=7&h;h<32;){if(0===o)break e;o--,u+=i[a++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=Cc;break}if(r.length=65535&u,u=0,h=0,r.mode=yc,t===Ba)break e;case yc:r.mode=bc;case bc:if(l=r.length,l){if(l>o&&(l=o),l>c&&(l=c),0===l)break e;Ma(n,i,a,l,s),o-=l,a+=l,c-=l,s+=l,r.length-=l;break}r.mode=fc;break;case gc:for(;h<14;){if(0===o)break e;o--,u+=i[a++]<>>=5,h-=5,r.ndist=1+(31&u),u>>>=5,h-=5,r.ncode=4+(15&u),u>>>=4,h-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Cc;break}r.have=0,r.mode=mc;case mc:for(;r.have>>=3,h-=3}for(;r.have<19;)r.lens[M[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},A=Yo(Qo,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid code lengths set",r.mode=Cc;break}r.have=0,r.mode=wc;case wc:for(;r.have>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=b,h-=b,r.lens[r.have++]=m;else{if(16===m){for(E=b+2;h>>=b,h-=b,0===r.have){e.msg="invalid bit length repeat",r.mode=Cc;break}k=r.lens[r.have-1],l=3+(3&u),u>>>=2,h-=2}else if(17===m){for(E=b+3;h>>=b,h-=b,k=0,l=3+(7&u),u>>>=3,h-=3}else{for(E=b+7;h>>=b,h-=b,k=0,l=11+(127&u),u>>>=7,h-=7}if(r.have+l>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Cc;break}for(;l--;)r.lens[r.have++]=k}}if(r.mode===Cc)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=Cc;break}if(r.lenbits=9,S={bits:r.lenbits},A=Yo(Jo,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid literal/lengths set",r.mode=Cc;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},A=Yo(ec,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,A){e.msg="invalid distances set",r.mode=Cc;break}if(r.mode=vc,t===Ba)break e;case vc:r.mode=_c;case _c:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,r.hold=u,r.bits=h,Oo(e,f),s=e.next_out,n=e.output,c=e.avail_out,a=e.next_in,i=e.input,o=e.avail_in,u=r.hold,h=r.bits,r.mode===fc&&(r.back=-1);break}for(r.back=0;P=r.lencode[u&(1<>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,g=P>>>16&255,m=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,r.length=m,0===g){r.mode=Pc;break}if(32&g){r.back=-1,r.mode=fc;break}if(64&g){e.msg="invalid literal/length code",r.mode=Cc;break}r.extra=15&g,r.mode=kc;case kc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=Ac;case Ac:for(;P=r.distcode[u&(1<>>24,g=P>>>16&255,m=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,g=P>>>16&255,m=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,64&g){e.msg="invalid distance code",r.mode=Cc;break}r.offset=m,r.extra=15&g,r.mode=Sc;case Sc:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Cc;break}r.mode=Ec;case Ec:if(0===c)break e;if(l=f-c,r.offset>l){if(l=r.offset-l,l>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Cc;break}l>r.wnext?(l-=r.wnext,p=r.wsize-l):p=r.wnext-l,l>r.length&&(l=r.length),y=r.window}else y=n,p=s-r.offset,l=r.length;l>c&&(l=c),c-=l,r.length-=l;do{n[s++]=y[p++]}while(--l);0===r.length&&(r.mode=_c);break;case Pc:if(0===c)break e;n[s++]=r.length,c--,r.mode=_c;break;case xc:if(r.wrap){for(;h<32;){if(0===o)break e;o--,u|=i[a++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new To,this.strm.avail_out=0;let r=Tc(this.strm,t.windowBits);if(r!==Ta)throw Error(Qs[r]);if(this.header=new Hc,function(e,t){let r;e&&e.state&&(r=e.state,0==(2&r.wrap)||(r.head=t,t.done=!1))}(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Bo(t.dictionary):t.dictionary instanceof ArrayBuffer&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=jc(this.strm,t.dictionary),r!==Ta)))throw Error(Qs[r])}push(e,t){const{strm:r,options:{chunkSize:i,dictionary:n}}=this;let a,s,o=!1;if(this.ended)return!1;s=t===~~t?t:!0===t?Ra:Ka,"string"==typeof e?r.input=function(e){const t=new Sa(e.length);for(let r=0,i=t.length;r0||0===r.avail_out)&&a!==za);return a===za&&(s=Ra),s===Ra?(a=function(e){if(!e||!e.state)return Fa;const t=e.state;return t.window&&(t.window=null),e.state=null,Ta}(this.strm),this.onEnd(a),this.ended=!0,a===Ta):s!==Da||(this.onEnd(Ta),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ta&&(this.result=xa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}var Gc=[0,1,3,7,15,31,63,127,255],Vc=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};Vc.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},Vc.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Gc[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var i=r-e;t|=(this.curByte&Gc[e]<>i,this.bitOffset+=e,e=0}}return t},Vc.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},Vc.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var $c=Vc,Zc=function(){};Zc.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},Zc.prototype.read=function(e,t,r){for(var i=0;i>>0},this.updateCRC=function(t){e=e<<8^Xc[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^Xc[255&(e>>>24^t)]}}),Jc=function(e,t){var r,i=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=i,i},eu={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},tu={};tu[eu.LAST_BLOCK]="Bad file checksum",tu[eu.NOT_BZIP_DATA]="Not bzip data",tu[eu.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",tu[eu.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",tu[eu.DATA_ERROR]="Data error",tu[eu.OUT_OF_MEMORY]="Out of memory",tu[eu.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var ru=function(e,t){var r=tu[e]||"unknown error";t&&(r+=": "+t);var i=new TypeError(r);throw i.errorCode=e,i},iu=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};iu.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Qc,!0):(this.writeCount=-1,!1)},iu.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||ru(eu.NOT_BZIP_DATA,"bad magic");var i=r[3]-48;(i<1||i>9)&&ru(eu.NOT_BZIP_DATA,"level out of range"),this.reader=new $c(e),this.dbufSize=1e5*i,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},iu.prototype._get_next_block=function(){var e,t,r,i=this.reader,n=i.pi();if("177245385090"===n)return!1;"314159265359"!==n&&ru(eu.NOT_BZIP_DATA),this.targetBlockCRC=i.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,i.read(1)&&ru(eu.OBSOLETE_INPUT);var a=i.read(24);a>this.dbufSize&&ru(eu.DATA_ERROR,"initial position out of bounds");var s=i.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(s&1<<15-e){var u=16*e;for(r=i.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=u+t)}var h=i.read(3);(h<2||h>6)&&ru(eu.DATA_ERROR);var d=i.read(15);0===d&&ru(eu.DATA_ERROR);var f=new Uint8Array(256);for(e=0;e=h&&ru(eu.DATA_ERROR);l[e]=Jc(f,t)}var p,y=c+2,b=[];for(t=0;t20)&&ru(eu.DATA_ERROR),i.read(1);)i.read(1)?s--:s++;w[e]=s}for(g=m=w[0],e=1;em?m=w[e]:w[e]=d&&ru(eu.DATA_ERROR),p=b[l[P++]]),e=p.minLen,t=i.read(e);e>p.maxLen&&ru(eu.DATA_ERROR),!(t<=p.limit[e]);e++)t=t<<1|i.read(1);((t-=p.base[e])<0||t>=258)&&ru(eu.DATA_ERROR);var M=p.permute[t];if(0!==M&&1!==M){if(S)for(S=0,E+s>this.dbufSize&&ru(eu.DATA_ERROR),k[A=o[f[0]]]+=s;s--;)x[E++]=A;if(M>c)break;E>=this.dbufSize&&ru(eu.DATA_ERROR),k[A=o[A=Jc(f,e=M-1)]]++,x[E++]=A}else S||(S=1,s=0),s+=0===M?S:2*S,S<<=1}for((a<0||a>=E)&&ru(eu.DATA_ERROR),t=0,e=0;e<256;e++)r=t+k[e],k[e]=t,t=r;for(e=0;e>=8,D=-1),this.writePos=K,this.writeCurrent=C,this.writeCount=E,this.writeRun=D,!0},iu.prototype._read_bunzip=function(e,t){var r,i,n;if(this.writeCount<0)return 0;var a=this.dbuf,s=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var u=this.writeRun;c;){for(c--,i=o,o=255&(s=a[s]),s>>=8,3==u++?(r=o,n=i,o=-1):(r=1,n=o),this.blockCRC.updateCRCRun(n,r);r--;)this.outputStream.writeByte(n),this.nextoutput++;o!=i&&(u=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&ru(eu.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var nu=function(e){if("readByte"in e)return e;var t=new Yc;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},au=function(e){var t=new Yc,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var su=function(e,t,r){for(var i=nu(e),n=au(t),a=new iu(i,n);!("eof"in i)||!i.eof();)if(a._init_block())a._read_bunzip();else{var s=a.reader.read(32)>>>0;if(s!==a.streamCRC&&ru(eu.DATA_ERROR,"Bad stream CRC (got "+a.streamCRC.toString(16)+" expected "+s.toString(16)+")"),!r||!("eof"in i)||i.eof())break;a._start_bunzip(i,n)}if("getBuffer"in n)return n.getBuffer()};class ou{static get tag(){return Z.packet.literalData}constructor(e=new Date){this.format=Z.literal.utf8,this.date=Y.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=Z.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||Y.isStream(this.text))&&(this.text=Y.decodeUTF8(Y.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=Y.canonicalizeEOL(Y.encodeUTF8(this.text))),e?O(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await q(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=Y.decodeUTF8(await e.readBytes(r)),this.date=Y.readDate(await e.readBytes(4));let i=e.remainder();o(i)&&(i=await j(i)),this.setBytes(i,t)}))}writeHeader(){const e=Y.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),i=Y.writeDate(this.date);return Y.concatUint8Array([r,t,e,i])}write(){const e=this.writeHeader(),t=this.getBytes();return Y.concat([e,t])}}const cu=Symbol("verified"),uu=new Set([Z.signatureSubpacket.issuer,Z.signatureSubpacket.issuerFingerprint,Z.signatureSubpacket.embeddedSignature]);class hu{static get tag(){return Z.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.signedHashValue=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new ye,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.revoked=null,this[cu]=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version)throw new gn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[t++],this.publicKeyAlgorithm=e[t++],this.hashAlgorithm=e[t++],t+=this.readSubPackets(e.subarray(t,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");this.signatureData=e.subarray(0,t),t+=this.readSubPackets(e.subarray(t,e.length),!1),this.signedHashValue=e.subarray(t,t+2),t+=2,this.params=wa.signature.parseSignatureParams(this.publicKeyAlgorithm,e.subarray(t,e.length))}writeParams(){return this.params instanceof Promise?W((async()=>wa.serializeParams(this.publicKeyAlgorithm,await this.params))):wa.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),e.push(this.writeParams()),Y.concat(e)}async sign(e,t,r=new Date,i=!1){5===e.version?this.version=5:this.version=4;const n=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];this.created=Y.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID(),n.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=Y.concat(n);const a=this.toHash(this.signatureType,t,i),s=await this.hash(this.signatureType,t,a,i);this.signedHashValue=N(F(s),0,2);const o=async()=>wa.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await j(s));Y.isStream(s)?this.params=o():(this.params=await o(),this[cu]=!0)}writeHashedSubPackets(){const e=Z.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(du(e.signatureCreationTime,!0,Y.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(du(e.signatureExpirationTime,!0,Y.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(du(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(du(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(du(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(du(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(du(e.keyExpirationTime,!0,Y.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(du(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=Y.concat([r,this.revocationKeyFingerprint]),t.push(du(e.revocationKey,!1,r))),this.issuerKeyID.isNull()||5===this.issuerKeyVersion||t.push(du(e.issuer,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:i,value:n,humanReadable:a,critical:s})=>{r=[new Uint8Array([a?128:0,0,0,0])];const o=Y.encodeUTF8(i);r.push(Y.writeNumber(o.length,2)),r.push(Y.writeNumber(n.length,2)),r.push(o),r.push(n),r=Y.concat(r),t.push(du(e.notationData,s,r))})),null!==this.preferredHashAlgorithms&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(du(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(du(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.keyServerPreferences)),t.push(du(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(du(e.preferredKeyServer,!1,Y.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(du(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(du(e.policyURI,!1,Y.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.keyFlags)),t.push(du(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(du(e.signersUserID,!1,Y.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=Y.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(du(e.reasonForRevocation,!0,r))),null!==this.features&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.features)),t.push(du(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(Y.stringToUint8Array(this.signatureTargetHash)),r=Y.concat(r),t.push(du(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(du(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=Y.concat(r),t.push(du(e.issuerFingerprint,5===this.version,r))),null!==this.preferredAEADAlgorithms&&(r=Y.stringToUint8Array(Y.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(du(e.preferredAEADAlgorithms,!1,r)));const i=Y.concat(t),n=Y.writeNumber(i.length,2);return Y.concat([n,i])}writeUnhashedSubPackets(){const e=[];this.unhashedSubpackets.forEach((t=>{e.push(dn(t.length)),e.push(t)}));const t=Y.concat(e),r=Y.writeNumber(t.length,2);return Y.concat([r,t])}readSubPacket(e,t=!0){let r=0;const i=!!(128&e[r]),n=127&e[r];if(t||(this.unhashedSubpackets.push(e.subarray(r,e.length)),uu.has(n)))switch(r++,n){case Z.signatureSubpacket.signatureCreationTime:this.created=Y.readDate(e.subarray(r,e.length));break;case Z.signatureSubpacket.signatureExpirationTime:{const t=Y.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case Z.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case Z.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case Z.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case Z.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case Z.signatureSubpacket.keyExpirationTime:{const t=Y.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case Z.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case Z.signatureSubpacket.issuer:this.issuerKeyID.read(e.subarray(r,e.length));break;case Z.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const n=Y.readNumber(e.subarray(r,r+2));r+=2;const a=Y.readNumber(e.subarray(r,r+2));r+=2;const s=Y.decodeUTF8(e.subarray(r,r+n)),o=e.subarray(r+n,r+n+a);this.rawNotations.push({name:s,humanReadable:t,value:o,critical:i}),t&&(this.notations[s]=Y.decodeUTF8(o));break}case Z.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=Y.decodeUTF8(e.subarray(r,e.length));break;case Z.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case Z.signatureSubpacket.policyURI:this.policyURI=Y.decodeUTF8(e.subarray(r,e.length));break;case Z.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.signersUserID:this.signersUserID=Y.decodeUTF8(e.subarray(r,e.length));break;case Z.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=Y.decodeUTF8(e.subarray(r,e.length));break;case Z.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case Z.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=wa.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=Y.uint8ArrayToString(e.subarray(r,r+t));break}case Z.signatureSubpacket.embeddedSignature:this.embeddedSignature=new hu,this.embeddedSignature.read(e.subarray(r,e.length));break;case Z.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),5===this.issuerKeyVersion?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case Z.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;default:{const e=Error("Unknown signature subpacket type "+n);if(i)throw e;Y.printDebug(e)}}}readSubPackets(e,t=!0,r){const i=Y.readNumber(e.subarray(0,2));let n=2;for(;n<2+i;){const i=hn(e.subarray(n,e.length));n+=i.offset,this.readSubPacket(e.subarray(n,n+i.len),t,r),n+=i.len}return n}toSign(e,t){const r=Z.signature;switch(e){case r.binary:return null!==t.text?Y.encodeUTF8(t.getText(!0)):t.getBytes(!0);case r.text:{const e=t.getBytes(!0);return Y.canonicalizeEOL(e)}case r.standalone:return new Uint8Array(0);case r.certGeneric:case r.certPersona:case r.certCasual:case r.certPositive:case r.certRevocation:{let e,i;if(t.userID)i=180,e=t.userID;else{if(!t.userAttribute)throw Error("Either a userID or userAttribute packet needs to be supplied for certification.");i=209,e=t.userAttribute}const n=e.write();return Y.concat([this.toSign(r.key,t),new Uint8Array([i]),Y.writeNumber(n.length,4),n])}case r.subkeyBinding:case r.subkeyRevocation:case r.keyBinding:return Y.concat([this.toSign(r.key,t),this.toSign(r.key,{key:t.bind})]);case r.key:if(void 0===t.key)throw Error("Key packet is required for this signature.");return t.key.writeForHash(this.version);case r.keyRevocation:return this.toSign(r.key,t);case r.timestamp:return new Uint8Array(0);case r.thirdParty:throw Error("Not implemented");default:throw Error("Unknown signature type.")}}calculateTrailer(e,t){let r=0;return T(F(this.signatureData),(e=>{r+=e.length}),(()=>{const i=[];return 5!==this.version||this.signatureType!==Z.signature.binary&&this.signatureType!==Z.signature.text||(t?i.push(new Uint8Array(6)):i.push(e.writeHeader())),i.push(new Uint8Array([this.version,255])),5===this.version&&i.push(new Uint8Array(4)),i.push(Y.writeNumber(r,4)),Y.concat(i)}))}toHash(e,t,r=!1){const i=this.toSign(e,t);return Y.concat([i,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,i=!1){return r||(r=this.toHash(e,t,i)),wa.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,i=new Date,n=!1,a=ae){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const s=t===Z.signature.binary||t===Z.signature.text;if(!(this[cu]&&!s)){let i,a;if(this.hashed?a=await this.hashed:(i=this.toHash(t,r,n),a=await this.hash(t,r,i)),a=await j(a),this.signedHashValue[0]!==a[0]||this.signedHashValue[1]!==a[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[cu]=await wa.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,i,a),!this[cu])throw Error("Signature verification failed")}const o=Y.normalizeDate(i);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(a.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+Z.read(Z.hash,this.hashAlgorithm).toUpperCase());if(a.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[Z.signature.binary,Z.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+Z.read(Z.hash,this.hashAlgorithm).toUpperCase());if(this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&a.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=Y.normalizeDate(e);return null!==t&&!(this.created<=t&&thu.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==Z.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function lu(e,t){if(!t[e]){let t;try{t=Z.read(Z.packet,e)}catch(t){throw new gn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}fu.prototype.hash=hu.prototype.hash,fu.prototype.toHash=hu.prototype.toHash,fu.prototype.toSign=hu.prototype.toSign;class pu extends Array{static async fromBinary(e,t,r=ae){const i=new pu;return await i.read(e,t,r),i}async read(e,t,r=ae){r.additionalAllowedPackets.length&&(t={...t,...Y.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=z(e,(async(e,i)=>{const n=U(i);try{for(;;){await n.ready;if(await bn(e,(async e=>{try{if(e.tag===Z.packet.marker||e.tag===Z.packet.trust)return;const i=lu(e.tag,t);i.packets=new pu,i.fromStream=Y.isStream(e.packet),await i.read(e.packet,r),await n.write(i)}catch(t){const i=!r.ignoreUnsupportedPackets&&t instanceof gn,a=!(r.ignoreMalformedPackets||t instanceof gn);if(i||a||yn(e.tag))await n.abort(t);else{const t=new mn(e.tag,e.packet);await n.write(t)}Y.printDebugError(t)}})))return await n.ready,void await n.close()}}catch(e){await n.abort(e)}}));const i=D(this.stream);for(;;){const{done:e,value:t}=await i.read();if(e?this.stream=null:this.push(t),e||yn(t.constructor.tag))break}i.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),n+=e.length,n>=a){const e=Math.min(Math.log(n)/Math.LN2|0,30),r=2**e,i=Y.concat([fn(e)].concat(t));return t=[i.subarray(1+r)],n=t[0].length,i.subarray(0,1+r)}}),(()=>Y.concat([dn(n)].concat(t)))))}else{if(Y.isStream(i)){let t=0;e.push(T(F(i),(e=>{t+=e.length}),(()=>pn(r,t))))}else e.push(pn(r,i.length));e.push(i)}}return Y.concat(e)}filterByTag(...e){const t=new pu,r=e=>t=>e===t;for(let i=0;it.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,i=e=>t=>e===t;for(let n=0;n{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),Y.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=ae){const t=Z.read(Z.compression,this.algorithm),r=Au[t];if(!r)throw Error(t+" decompression not supported");this.packets=await pu.fromBinary(r(this.compressed),yu,e)}compress(){const e=Z.read(Z.compression,this.algorithm),t=ku[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write(),this.deflateLevel)}}const gu=Y.getNodeZlib();function mu(e){return e}function wu(e,t,r={}){return function(i){return!Y.isStream(i)||o(i)?W((()=>j(i).then((t=>new Promise(((i,n)=>{e(t,r,((e,t)=>{if(e)return n(e);i(t)}))})))))):b(g(i).pipe(t(r)))}}function vu(e,t={}){return function(r){const i=new e(t);return T(r,(e=>{if(e.length)return i.push(e,Da),i.result}),(()=>{if(e===zo)return i.push([],Ra),i.result}))}}function _u(e){return function(t){return W((async()=>e(await j(t))))}}const ku=gu?{zip:/*#__PURE__*/(e,t)=>wu(gu.deflateRaw,gu.createDeflateRaw,{level:t})(e),zlib:/*#__PURE__*/(e,t)=>wu(gu.deflate,gu.createDeflate,{level:t})(e)}:{zip:/*#__PURE__*/(e,t)=>vu(zo,{raw:!0,level:t})(e),zlib:/*#__PURE__*/(e,t)=>vu(zo,{level:t})(e)},Au=gu?{uncompressed:mu,zip:/*#__PURE__*/wu(gu.inflateRaw,gu.createInflateRaw),zlib:/*#__PURE__*/wu(gu.inflate,gu.createInflate),bzip2:/*#__PURE__*/_u(su)}:{uncompressed:mu,zip:/*#__PURE__*/vu(Wc,{raw:!0}),zlib:/*#__PURE__*/vu(Wc),bzip2:/*#__PURE__*/_u(su)},Su=/*#__PURE__*/Y.constructAllowedPackets([ou,bu,fu,hu]);class Eu{static get tag(){return Z.packet.symEncryptedIntegrityProtectedData}constructor(){this.version=1,this.encrypted=null,this.packets=null}async read(e){await q(e,(async e=>{const t=await e.readByte();if(1!==t)throw new gn(`Version ${t} of the SEIP packet is unsupported.`);this.encrypted=e.remainder()}))}write(){return Y.concat([new Uint8Array([1]),this.encrypted])}async encrypt(e,t,r=ae){const{blockSize:i}=wa.getCipher(e);let n=this.packets.write();o(n)&&(n=await j(n));const a=await wa.getPrefixRandom(e),s=new Uint8Array([211,20]),c=Y.concat([a,n,s]),u=await wa.hash.sha1(O(c)),h=Y.concat([c,u]);return this.encrypted=await wa.mode.cfb.encrypt(e,t,h,new Uint8Array(i),r),!0}async decrypt(e,t,r=ae){const{blockSize:i}=wa.getCipher(e);let n=F(this.encrypted);o(n)&&(n=await j(n));const a=await wa.mode.cfb.decrypt(e,t,n,new Uint8Array(i)),s=N(O(a),-20),c=N(a,0,-20),u=Promise.all([j(await wa.hash.sha1(O(c))),j(s)]).then((([e,t])=>{if(!Y.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),h=N(c,i+2);let d=N(h,0,-2);return d=C([d,W((()=>u))]),Y.isStream(n)&&r.allowUnauthenticatedStream||(d=await j(d)),this.packets=await pu.fromBinary(d,Su,r),!0}}const Pu=/*#__PURE__*/Y.constructAllowedPackets([ou,bu,fu,hu]);class xu{static get tag(){return Z.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=Z.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await q(e,(async e=>{const t=await e.readByte();if(1!==t)throw new gn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=wa.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return Y.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=ae){this.packets=await pu.fromBinary(await this.crypt("decrypt",t,F(this.encrypted)),Pu,r)}async encrypt(e,t,r=ae){this.cipherAlgorithm=e;const{ivLength:i}=wa.getAEADMode(this.aeadAlgorithm);this.iv=wa.random.getRandomBytes(i),this.chunkSizeByte=r.aeadChunkSizeByte;const n=this.packets.write();this.encrypted=await this.crypt("encrypt",t,n)}async crypt(e,t,r){const i=wa.getAEADMode(this.aeadAlgorithm),n=await i(this.cipherAlgorithm,t),a="decrypt"===e?i.tagLength:0,s="encrypt"===e?i.tagLength:0,o=2**(this.chunkSizeByte+6)+a,c=new ArrayBuffer(21),u=new Uint8Array(c,0,13),h=new Uint8Array(c),d=new DataView(c),f=new Uint8Array(c,5,8);u.set([192|xu.tag,this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte],0);let l=0,p=Promise.resolve(),y=0,b=0;const g=this.iv;return z(r,(async(t,r)=>{if("array"!==Y.isStream(t)){const e=new E({},{highWaterMark:Y.getHardwareConcurrency()*2**(this.chunkSizeByte+6),size:e=>e.length});R(e.readable,r),r=e.writable}const c=D(t),m=U(r);try{for(;;){let t=await c.readBytes(o+a)||new Uint8Array;const r=t.subarray(t.length-a);let w,v;if(t=t.subarray(0,t.length-a),!l||t.length?(c.unshift(r),w=n[e](t,i.getNonce(g,f),u),b+=t.length-a+s):(d.setInt32(17,y),w=n[e](r,i.getNonce(g,f),h),b+=s,v=!0),y+=t.length-a,p=p.then((()=>w)).then((async e=>{await m.ready,await m.write(e),b-=e.length})).catch((e=>m.abort(e))),(v||b>m.desiredSize)&&await p,v){await m.close();break}d.setInt32(9,++l)}}catch(e){await m.abort(e)}}))}}class Mu{static get tag(){return Z.packet.publicKeyEncryptedSessionKey}constructor(){this.version=3,this.publicKeyID=new ye,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}read(e){let t=0;if(this.version=e[t++],3!==this.version)throw new gn(`Version ${this.version} of the PKESK packet is unsupported.`);t+=this.publicKeyID.read(e.subarray(t)),this.publicKeyAlgorithm=e[t++],this.encrypted=wa.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t),this.version),this.publicKeyAlgorithm===Z.publicKey.x25519&&(this.sessionKeyAlgorithm=Z.write(Z.symmetric,this.encrypted.C.algorithm))}write(){const e=[new Uint8Array([this.version]),this.publicKeyID.write(),new Uint8Array([this.publicKeyAlgorithm]),wa.serializeParams(this.publicKeyAlgorithm,this.encrypted)];return Y.concatUint8Array(e)}async encrypt(e){const t=Z.write(Z.publicKey,this.publicKeyAlgorithm),r=Ku(this.version,t,this.sessionKeyAlgorithm,this.sessionKey);this.encrypted=await wa.publicKeyEncrypt(t,this.sessionKeyAlgorithm,e.publicParams,r,e.getFingerprintBytes())}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Ku(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,i=await wa.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,e.getFingerprintBytes(),r),{sessionKey:n,sessionKeyAlgorithm:a}=function(e,t,r,i){switch(t){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.elgamal:case Z.publicKey.ecdh:{const e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=Y.writeChecksum(e.subarray(e.length%8)),a=n[0]===t[0]&n[1]===t[1],s={sessionKeyAlgorithm:e[0],sessionKey:e.subarray(1)};if(i){const e=a&s.sessionKeyAlgorithm===i.sessionKeyAlgorithm&s.sessionKey.length===i.sessionKey.length;return{sessionKey:Y.selectUint8Array(e,s.sessionKey,i.sessionKey),sessionKeyAlgorithm:Y.selectUint8(e,s.sessionKeyAlgorithm,i.sessionKeyAlgorithm)}}if(a&&Z.read(Z.symmetric,s.sessionKeyAlgorithm))return s;throw Error("Decryption error")}case Z.publicKey.x25519:return{sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);this.publicKeyAlgorithm!==Z.publicKey.x25519&&(this.sessionKeyAlgorithm=a),this.sessionKey=n}}function Ku(e,t,r,i){switch(t){case Z.publicKey.rsaEncrypt:case Z.publicKey.rsaEncryptSign:case Z.publicKey.elgamal:case Z.publicKey.ecdh:return Y.concatUint8Array([new Uint8Array([r]),i,Y.writeChecksum(i.subarray(i.length%8))]);case Z.publicKey.x25519:return i;default:throw Error("Unsupported public key algorithm")}}class Cu{constructor(e=ae){this.algorithm=Z.hash.sha256,this.type="iterated",this.c=e.s2kIterationCountByte,this.salt=null}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;try{this.type=Z.read(Z.s2k,e[t++])}catch(e){throw new gn("Unknown S2K type.")}switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==Y.uint8ArrayToString(e.subarray(t,t+3)))throw new gn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new gn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new gn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...Y.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([Z.write(Z.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return Y.concatUint8Array(e)}async produceKey(e,t){e=Y.encodeUTF8(e);const r=[];let i=0,n=0;for(;i{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function qu(e,t,r){const{keySize:i}=wa.getCipher(r);return e.produceKey(t,i)}var Fu=nt((function(e){!function(t){function r(e){function t(){return Ae0&&(t.semantic=" "),t}}function b(e,t){return function(){var i,a,o,u,h;for(u=r(),i=s("star"),o=0,h=void 0===t?0:t;null!==(a=e());)o+=1,c(i,a);return o>=h?i:(n(u),null)}}function g(e){return e.charCodeAt(0)>=128}function m(){return o("cr",h("\r")())}function w(){return o("crlf",d(m,k)())}function v(){return o("dquote",h('"')())}function _(){return o("htab",h("\t")())}function k(){return o("lf",h("\n")())}function A(){return o("sp",h(" ")())}function S(){return o("vchar",u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i})))}function E(){return o("wsp",f(A,_)())}function P(){var e=o("quoted-pair",f(d(h("\\"),f(S,E)),ie)());return null===e?null:(e.semantic=e.semantic[1],e)}function x(){return o("fws",f(ae,d(l(d(b(E),p(w))),b(E,1)))())}function M(){return o("ctext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=39||42<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),te)())}function K(){return o("ccontent",f(M,P,C)())}function C(){return o("comment",d(h("("),b(d(l(x),K)),l(x),h(")"))())}function D(){return o("cfws",f(d(b(d(l(x),C),1),l(x)),x)())}function U(){return o("atext",u((function(t){var r="a"<=t&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||["!","#","$","%","&","'","*","+","-","/","=","?","^","_","`","{","|","}","~"].indexOf(t)>=0;return e.rfc6532&&(r=r||g(t)),r})))}function R(){return o("atom",d(y(l(D)),b(U,1),y(l(D)))())}function I(){var e,t;return null===(e=o("dot-atom-text",b(U,1)()))||null!==(t=b(d(h("."),b(U,1)))())&&c(e,t),e}function B(){return o("dot-atom",d(p(l(D)),I,p(l(D)))())}function T(){return o("qtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33===r||35<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),re)())}function z(){return o("qcontent",f(T,P)())}function q(){return o("quoted-string",d(p(l(D)),p(v),b(d(l(y(x)),z)),l(p(x)),p(v),p(l(D)))())}function F(){return o("word",f(R,q)())}function O(){return o("address",f(L,H)())}function L(){return o("mailbox",f(N,J)())}function N(){return o("name-addr",d(l(W),j)())}function j(){return o("angle-addr",f(d(p(l(D)),h("<"),J,h(">"),p(l(D))),se)())}function H(){return o("group",d(W,h(":"),l($),h(";"),p(l(D)))())}function W(){return o("display-name",(null!==(e=o("phrase",f(ne,b(F,1))()))&&(e.semantic=function(e){return e.replace(/([ \t]|\r\n)+/g," ").replace(/^\s*/,"").replace(/\s*$/,"")}(e.semantic)),e));var e}function G(){return o("mailbox-list",f(d(L,b(d(h(","),L))),ue)())}function V(){return o("address-list",f(d(O,b(d(h(","),O))),he)())}function $(){return o("group-list",f(G,p(D),de)())}function Z(){return o("local-part",f(fe,B,q)())}function X(){return o("dtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=90||94<=r&&r<=126;return e.rfc6532&&(i=i||g(t)),i}))}),pe)())}function Y(){return o("domain-literal",d(p(l(D)),h("["),b(d(l(x),X)),l(x),h("]"),p(l(D)))())}function Q(){return o("domain",(t=f(le,B,Y)(),e.rejectTLD&&t&&t.semantic&&t.semantic.indexOf(".")<0?null:(t&&(t.semantic=t.semantic.replace(/\s+/g,"")),t)));var t}function J(){return o("addr-spec",d(Z,h("@"),Q)())}function ee(){return e.strict?null:o("obs-NO-WS-CTL",u((function(e){var t=e.charCodeAt(0);return 1<=t&&t<=8||11===t||12===t||14<=t&&t<=31||127===t})))}function te(){return e.strict?null:o("obs-ctext",ee())}function re(){return e.strict?null:o("obs-qtext",ee())}function ie(){return e.strict?null:o("obs-qp",d(h("\\"),f(h("\0"),ee,k,m))())}function ne(){return e.strict?null:e.atInDisplayName?o("obs-phrase",d(F,b(f(F,h("."),h("@"),y(D))))()):o("obs-phrase",d(F,b(f(F,h("."),y(D))))())}function ae(){return e.strict?null:o("obs-FWS",b(d(p(l(w)),E),1)())}function se(){return e.strict?null:o("obs-angle-addr",d(p(l(D)),h("<"),oe,J,h(">"),p(l(D)))())}function oe(){return e.strict?null:o("obs-route",d(ce,h(":"))())}function ce(){return e.strict?null:o("obs-domain-list",d(b(f(p(D),h(","))),h("@"),Q,b(d(h(","),p(l(D)),l(d(h("@"),Q)))))())}function ue(){return e.strict?null:o("obs-mbox-list",d(b(d(p(l(D)),h(","))),L,b(d(h(","),l(d(L,p(D))))))())}function he(){return e.strict?null:o("obs-addr-list",d(b(d(p(l(D)),h(","))),O,b(d(h(","),l(d(O,p(D))))))())}function de(){return e.strict?null:o("obs-group-list",d(b(d(p(l(D)),h(",")),1),p(l(D)))())}function fe(){return e.strict?null:o("obs-local-part",d(F,b(d(h("."),F)))())}function le(){return e.strict?null:o("obs-domain",d(R,b(d(h("."),R)))())}function pe(){return e.strict?null:o("obs-dtext",f(ee,P)())}function ye(e,t){var r,i,n;if(null==t)return null;for(i=[t];i.length>0;){if((n=i.pop()).name===e)return n;for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r])}return null}function be(e,t){var r,i,n,a,s;if(null==t)return null;for(i=[t],a=[],s={},r=0;r0;)if((n=i.pop()).name in s)a.push(n);else for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}function ge(t){var r,i,n,a,s;if(null===t)return null;for(r=[],i=be(["group","mailbox"],t),n=0;n1)return null;return t.addresses&&t.addresses[0]}(s):e.simple?s&&s.addresses:s}function me(e){var t,r=ye("display-name",e),i=[],n=be(["mailbox"],e);for(t=0;t0;)for((n=i.pop()).name===e&&a.push(n),r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}("cfws",e),n=be(["comment"],e),a=ye("local-part",r),s=ye("domain",r);return{node:e,parts:{name:t,address:r,local:a,domain:s,comments:i},type:e.name,name:ve(t),address:ve(r),local:ve(a),domain:ve(s),comments:_e(n),groupName:ve(e.groupName)}}function ve(e){return null!=e?e.semantic:null}function _e(e){var t="";if(e)for(var r=0;r`),t.userID=r.join(" "),t}read(e,t=ae){const r=Y.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");try{const{name:e,address:t,comments:i}=Fu.parseOneAddress({input:r,atInDisplayName:!0});this.comment=i.replace(/^\(|\)$/g,""),this.name=e,this.email=t}catch(e){}this.userID=r}write(){return Y.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Lu extends zu{static get tag(){return Z.packet.secretSubkey}constructor(e=new Date,t=ae){super(e,t)}}const Nu=/*#__PURE__*/Y.constructAllowedPackets([hu]);class ju{constructor(e){this.packets=e||new pu}write(){return this.packets.write()}armor(e=ae){return pe(Z.armor.signature,this.write(),void 0,void 0,void 0,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Hu(e,t){const r=new Lu(e.date,t);return r.packets=null,r.algorithm=Z.write(Z.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function Wu(e,t){const r=new zu(e.date,t);return r.packets=null,r.algorithm=Z.write(Z.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Gu(e,t,r,i,n=new Date,a){let s,o;for(let c=e.length-1;c>=0;c--)try{(!s||e[c].created>=s.created)&&(await e[c].verify(t,r,i,n,void 0,a),s=e[c])}catch(e){o=e}if(!s)throw Y.wrapError(`Could not find valid ${Z.read(Z.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return s}function Vu(e,t,r=new Date){const i=Y.normalizeDate(r);if(null!==i){const r=eh(e,t);return!(e.created<=i&&i0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1);return await Yu(n,null,t,a,r.date,void 0,void 0,void 0,i)}async function Zu(e,t,r=new Date,i={},n){let a=n.preferredHashAlgorithm,s=a;if(e){const t=await e.getPrimaryUser(r,i,n);t.selfCertification.preferredHashAlgorithms&&([s]=t.selfCertification.preferredHashAlgorithms,a=wa.hash.getHashByteLength(a)<=wa.hash.getHashByteLength(s)?s:a)}switch(t.algorithm){case Z.publicKey.ecdsa:case Z.publicKey.eddsaLegacy:case Z.publicKey.ed25519:s=wa.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid)}return wa.hash.getHashByteLength(a)<=wa.hash.getHashByteLength(s)?s:a}async function Xu(e,t=[],r=new Date,i=[],n=ae){const a={symmetric:Z.symmetric.aes128,aead:Z.aead.eax,compression:Z.compression.uncompressed}[e],s={symmetric:n.preferredSymmetricAlgorithm,aead:n.preferredAEADAlgorithm,compression:n.preferredCompressionAlgorithm}[e],o={symmetric:"preferredSymmetricAlgorithms",aead:"preferredAEADAlgorithms",compression:"preferredCompressionAlgorithms"}[e],c=await Promise.all(t.map((async function(e,t){const a=(await e.getPrimaryUser(r,i[t],n)).selfCertification[o];return!!a&&a.indexOf(s)>=0})));return c.every(Boolean)?s:a}async function Yu(e,t,r,i,n,a,s=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const u=new hu;return Object.assign(u,i),u.publicKeyAlgorithm=r.algorithm,u.hashAlgorithm=await Zu(t,r,n,a,c),u.rawNotations=s,await u.sign(r,e,n,o),u}async function Qu(e,t,r,i=new Date,n){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(i)||n&&!await n(e)||t[r].some((function(t){return Y.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function Ju(e,t,r,i,n,a,s=new Date,o){a=a||e;const c=[];return await Promise.all(i.map((async function(e){try{n&&!e.issuerKeyID.equals(n.issuerKeyID)||(await e.verify(a,t,r,o.revocationsExpire?s:null,!1,o),c.push(e.issuerKeyID))}catch(e){}}))),n?(n.revoked=!!c.some((e=>e.equals(n.issuerKeyID)))||(n.revoked||!1),n.revoked):c.length>0}function eh(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function th(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=Y.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=Z.write(Z.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==Z.curve.ed25519Legacy&&e.curve!==Z.curve.curve25519Legacy||(e.curve=e.sign?Z.curve.ed25519Legacy:Z.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===Z.curve.ed25519Legacy?Z.publicKey.eddsaLegacy:Z.publicKey.ecdsa:e.algorithm=Z.publicKey.ecdh;break;case"rsa":e.algorithm=Z.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function rh(e,t){const r=e.algorithm;return r!==Z.publicKey.rsaEncrypt&&r!==Z.publicKey.elgamal&&r!==Z.publicKey.ecdh&&r!==Z.publicKey.x25519&&(!t.keyFlags||0!=(t.keyFlags[0]&Z.keyFlags.signData))}function ih(e,t){const r=e.algorithm;return r!==Z.publicKey.dsa&&r!==Z.publicKey.rsaSign&&r!==Z.publicKey.ecdsa&&r!==Z.publicKey.eddsaLegacy&&r!==Z.publicKey.ed25519&&(!t.keyFlags||0!=(t.keyFlags[0]&Z.keyFlags.encryptCommunication)||0!=(t.keyFlags[0]&Z.keyFlags.encryptStorage))}function nh(e,t){return!!t.allowInsecureDecryptionWithSigningKeys||(!e.keyFlags||0!=(e.keyFlags[0]&Z.keyFlags.encryptCommunication)||0!=(e.keyFlags[0]&Z.keyFlags.encryptStorage))}function ah(e,t){const r=Z.write(Z.publicKey,e.algorithm),i=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(i.algorithm+" keys are considered too weak.");switch(r){case Z.publicKey.rsaEncryptSign:case Z.publicKey.rsaSign:case Z.publicKey.rsaEncrypt:if(i.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const a=await t.getSigningKey(o,e.created,void 0,i);if(e.revoked||await n.isRevoked(e,a.keyPacket,r,i))throw Error("User certificate is revoked");try{await e.verify(a.keyPacket,Z.signature.certGeneric,s,r,void 0,i)}catch(e){throw Y.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const i=this,n=this.selfCertifications.concat(this.otherCertifications);return Promise.all(n.map((async n=>({keyID:n.issuerKeyID,valid:await i.verifyCertificate(n,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};let a;for(let s=this.selfCertifications.length-1;s>=0;s--)try{const a=this.selfCertifications[s];if(a.revoked||await r.isRevoked(a,void 0,e,t))throw Error("Self-certification is revoked");try{await a.verify(i,Z.signature.certGeneric,n,e,void 0,t)}catch(e){throw Y.wrapError("Self-certification is invalid",e)}return!0}catch(e){a=e}throw a}async update(e,t,r){const i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};await Qu(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(i,Z.signature.certGeneric,n,t,!1,r),!0}catch(e){return!1}})),await Qu(e,this,"otherCertifications",t),await Qu(e,this,"revocationSignatures",t,(function(e){return Ju(i,Z.signature.certRevocation,n,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=Z.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=ae){const a={userID:this.userID,userAttribute:this.userAttribute,key:e},s=new sh(a.userID||a.userAttribute,this.mainKey);return s.revocationSignatures.push(await Yu(a,null,e,{signatureType:Z.signature.certRevocation,reasonForRevocationFlag:Z.write(Z.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}}class oh{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new pu;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new oh(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,i=ae){const n=this.mainKey.keyPacket;return Ju(n,Z.signature.subkeyRevocation,{key:n,bind:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verify(e=new Date,t=ae){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket},n=await Gu(this.bindingSignatures,r,Z.signature.subkeyBinding,i,e,t);if(n.revoked||await this.isRevoked(n,null,e,t))throw Error("Subkey is revoked");if(Vu(this.keyPacket,n,e))throw Error("Subkey is expired");return n}async getExpirationTime(e=new Date,t=ae){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket};let n;try{n=await Gu(this.bindingSignatures,r,Z.signature.subkeyBinding,i,e,t)}catch(e){return null}const a=eh(this.keyPacket,n),s=n.getExpirationTime();return an.bindingSignatures[t].created&&(n.bindingSignatures[t]=e),!1;try{return await e.verify(i,Z.signature.subkeyBinding,a,t,void 0,r),!0}catch(e){return!1}})),await Qu(e,this,"revocationSignatures",t,(function(e){return Ju(i,Z.signature.subkeyRevocation,a,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=Z.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=ae){const a={key:e,bind:this.keyPacket},s=new oh(this.keyPacket,this.mainKey);return s.revocationSignatures.push(await Yu(a,null,e,{signatureType:Z.signature.subkeyRevocation,reasonForRevocationFlag:Z.write(Z.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{oh.prototype[e]=function(){return this.keyPacket[e]()}}));const ch=/*#__PURE__*/Y.constructAllowedPackets([hu]),uh=new Set([Z.packet.publicKey,Z.packet.privateKey]),hh=new Set([Z.packet.publicKey,Z.packet.privateKey,Z.packet.publicSubkey,Z.packet.privateSubkey]);class dh{packetListToStructure(e,t=new Set){let r,i,n,a;for(const s of e){if(s instanceof mn){hh.has(s.tag)&&!a&&(a=uh.has(s.tag)?uh:hh);continue}const e=s.constructor.tag;if(a){if(!a.has(e))continue;a=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case Z.packet.publicKey:case Z.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=s,i=this.getKeyID(),!i)throw Error("Missing Key ID");break;case Z.packet.userID:case Z.packet.userAttribute:r=new sh(s,this),this.users.push(r);break;case Z.packet.publicSubkey:case Z.packet.secretSubkey:r=null,n=new oh(s,this),this.subkeys.push(n);break;case Z.packet.signature:switch(s.signatureType){case Z.signature.certGeneric:case Z.signature.certPersona:case Z.signature.certCasual:case Z.signature.certPositive:if(!r){Y.printDebug("Dropping certification signatures without preceding user packet");continue}s.issuerKeyID.equals(i)?r.selfCertifications.push(s):r.otherCertifications.push(s);break;case Z.signature.certRevocation:r?r.revocationSignatures.push(s):this.directSignatures.push(s);break;case Z.signature.key:this.directSignatures.push(s);break;case Z.signature.subkeyBinding:if(!n){Y.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}n.bindingSignatures.push(s);break;case Z.signature.keyRevocation:this.revocationSignatures.push(s);break;case Z.signature.subkeyRevocation:if(!n){Y.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}n.revocationSignatures.push(s)}}}}toPacketList(){const e=new pu;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},i=ae){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await Gu(r.bindingSignatures,n,Z.signature.subkeyBinding,e,t,i);if(!rh(r.keyPacket,a))continue;if(!a.embeddedSignature)throw Error("Missing embedded signature");return await Gu([a.embeddedSignature],r.keyPacket,Z.signature.keyBinding,e,t,i),ah(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&rh(n,a.selfCertification))return ah(n,i),this}catch(e){s=e}throw Y.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),s)}async getEncryptionKey(e,t=new Date,r={},i=ae){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await Gu(r.bindingSignatures,n,Z.signature.subkeyBinding,e,t,i);if(ih(r.keyPacket,a))return ah(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&ih(n,a.selfCertification))return ah(n,i),this}catch(e){s=e}throw Y.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),s)}async isRevoked(e,t,r=new Date,i=ae){return Ju(this.keyPacket,Z.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verifyPrimaryKey(e=new Date,t={},r=ae){const i=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");const{selfCertification:n}=await this.getPrimaryUser(e,t,r);if(Vu(i,n,e))throw Error("Primary key is expired");const a=await Gu(this.directSignatures,i,Z.signature.key,{key:i},e,r).catch((()=>{}));if(a&&Vu(i,a,e))throw Error("Primary key is expired")}async getExpirationTime(e,t=ae){let r;try{const{selfCertification:i}=await this.getPrimaryUser(null,e,t),n=eh(this.keyPacket,i),a=i.getExpirationTime(),s=await Gu(this.directSignatures,this.keyPacket,Z.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(s){const e=eh(this.keyPacket,s);r=Math.min(n,a,e)}else r=ne.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const i=this.clone();return await Qu(e,i,"revocationSignatures",t,(n=>Ju(i.keyPacket,Z.signature.keyRevocation,i,[n],null,e.keyPacket,t,r))),await Qu(e,i,"directSignatures",t),await Promise.all(e.users.map((async e=>{const n=i.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const n=i.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.subkeys.push(t)}}))),i}async getRevocationCertificate(e=new Date,t=ae){const r={key:this.keyPacket},i=await Gu(this.revocationSignatures,this.keyPacket,Z.signature.keyRevocation,r,e,t),n=new pu;return n.push(i),pe(Z.armor.publicKey,n.write(),null,null,"This is a revocation certificate")}async applyRevocationCertificate(e,t=new Date,r=ae){const i=await le(e,r),n=(await pu.fromBinary(i.data,ch,r)).findPacket(Z.packet.signature);if(!n||n.signatureType!==Z.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!n.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await n.verify(this.keyPacket,Z.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw Y.wrapError("Could not verify revocation signature",e)}const a=this.clone();return a.revocationSignatures.push(n),a}async signPrimaryUser(e,t,r,i=ae){const{index:n,user:a}=await this.getPrimaryUser(t,r,i),s=await a.certify(e,t,i),o=this.clone();return o.users[n]=s,o}async signAllUsers(e,t=new Date,r=ae){const i=this.clone();return i.users=await Promise.all(this.users.map((function(i){return i.certify(e,t,r)}))),i}async verifyPrimaryUser(e,t=new Date,r,i=ae){const n=this.keyPacket,{user:a}=await this.getPrimaryUser(t,r,i);return e?await a.verifyAllCertifications(e,t,i):[{keyID:n.getKeyID(),valid:await a.verify(t,i).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=ae){const i=this.keyPacket,n=[];return await Promise.all(this.users.map((async a=>{const s=e?await a.verifyAllCertifications(e,t,r):[{keyID:i.getKeyID(),valid:await a.verify(t,r).catch((()=>!1))}];n.push(...s.map((e=>({userID:a.userID?a.userID.userID:null,userAttribute:a.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),n}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{dh.prototype[e]=oh.prototype[e]}));class fh extends dh{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([Z.packet.secretKey,Z.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=ae){return pe(Z.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,e)}}class lh extends fh{constructor(e){if(super(),this.packetListToStructure(e,new Set([Z.packet.publicKey,Z.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new pu,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case Z.packet.secretKey:{const t=Uu.fromSecretKeyPacket(r);e.push(t);break}case Z.packet.secretSubkey:{const t=Bu.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new fh(e)}armor(e=ae){return pe(Z.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,e)}async getDecryptionKeys(e,t=new Date,r={},i=ae){const n=this.keyPacket,a=[];for(let r=0;re.isDecrypted()))}async validate(e=ae){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys(),t=e.map((e=>e.keyPacket.isDummy())).every(Boolean);if(t)throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=Z.reasonForRevocation.noReason,string:t=""}={},r=new Date,i=ae){if(!this.isPrivate())throw Error("Need private key for revoking");const n={key:this.keyPacket},a=this.clone();return a.revocationSignatures.push(await Yu(n,null,this.keyPacket,{signatureType:Z.signature.keyRevocation,reasonForRevocationFlag:Z.write(Z.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,i)),a}async addSubkey(e={}){const t={...ae,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}const s=Ou.fromObject(t),o={};o.userID=s,o.key=e;const c={};c.signatureType=Z.signature.certGeneric,c.keyFlags=[Z.keyFlags.certifyKeys|Z.keyFlags.signData],c.preferredSymmetricAlgorithms=a([Z.symmetric.aes256,Z.symmetric.aes128,Z.symmetric.aes192],i.preferredSymmetricAlgorithm),i.aeadProtect&&(c.preferredAEADAlgorithms=a([Z.aead.eax,Z.aead.ocb],i.preferredAEADAlgorithm)),c.preferredHashAlgorithms=a([Z.hash.sha256,Z.hash.sha512],i.preferredHashAlgorithm),c.preferredCompressionAlgorithms=a([Z.compression.zlib,Z.compression.zip,Z.compression.uncompressed],i.preferredCompressionAlgorithm),0===n&&(c.isPrimaryUserID=!0),c.features=[0],c.features[0]|=Z.features.modificationDetection,i.aeadProtect&&(c.features[0]|=Z.features.aead),i.v5Keys&&(c.features[0]|=Z.features.v5Keys),r.keyExpirationTime>0&&(c.keyExpirationTime=r.keyExpirationTime,c.keyNeverExpires=!1);return{userIDPacket:s,signaturePacket:await Yu(o,null,e,c,r.date,void 0,void 0,void 0,i)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{n.push(e),n.push(t)}))})),await Promise.all(t.map((async function(t,n){const a=r.subkeys[n];return{secretSubkeyPacket:t,subkeySignaturePacket:await $u(t,e,a,i)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{n.push(e),n.push(t)}))}));const a={key:e};return n.push(await Yu(a,null,e,{signatureType:Z.signature.keyRevocation,reasonForRevocationFlag:Z.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,i)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new lh(n)}const gh=/*#__PURE__*/Y.constructAllowedPackets([ou,bu,xu,Eu,Iu,Mu,Du,fu,hu]),mh=/*#__PURE__*/Y.constructAllowedPackets([Du]),wh=/*#__PURE__*/Y.constructAllowedPackets([hu]);class vh{constructor(e){this.packets=e||new pu}getEncryptionKeyIDs(){const e=[];return this.packets.filterByTag(Z.packet.publicKeyEncryptedSessionKey).forEach((function(t){e.push(t.publicKeyID)})),e}getSigningKeyIDs(){const e=this.unwrapCompressed(),t=e.packets.filterByTag(Z.packet.onePassSignature);if(t.length>0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(Z.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,i=new Date,n=ae){const a=r||await this.decryptSessionKeys(e,t,i,n),s=this.packets.filterByTag(Z.packet.symmetricallyEncryptedData,Z.packet.symEncryptedIntegrityProtectedData,Z.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const o=s[0];let c=null;const u=Promise.all(a.map((async({algorithm:e,data:t})=>{if(!Y.isUint8Array(t)||!Y.isString(e))throw Error("Invalid session key for decryption.");try{const r=Z.write(Z.symmetric,e);await o.decrypt(r,t,n)}catch(e){Y.printDebugError(e),c=e}})));if(H(o.encrypted),o.encrypted=null,await u,!o.packets||!o.packets.length)throw c||Error("Decryption failed.");const h=new vh(o.packets);return o.packets=new pu,h}async decryptSessionKeys(e,t,r=new Date,i=ae){let n,a=[];if(t){const e=this.packets.filterByTag(Z.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await pu.fromBinary(e.write(),mh,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){Y.printDebugError(e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(Z.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let s=[Z.symmetric.aes256,Z.symmetric.aes128,Z.symmetric.tripledes,Z.symmetric.cast5];try{const t=await e.getPrimaryUser(r,void 0,i);t.selfCertification.preferredSymmetricAlgorithms&&(s=s.concat(t.selfCertification.preferredSymmetricAlgorithms))}catch(e){}const o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket));await Promise.all(o.map((async function(e){if(!e||e.isDummy())return;if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===Z.publicKey.rsaEncrypt||t.publicKeyAlgorithm===Z.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===Z.publicKey.rsaSign||t.publicKeyAlgorithm===Z.publicKey.elgamal)){const r=t.write();await Promise.all(Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map((async t=>{const i=new Mu;i.read(r);const s={sessionKeyAlgorithm:t,sessionKey:wa.generateSessionKey(t)};try{await i.decrypt(e,s),a.push(i)}catch(e){Y.printDebugError(e),n=e}})))}else try{if(await t.decrypt(e),!s.includes(Z.write(Z.symmetric,t.sessionKeyAlgorithm)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){Y.printDebugError(e),n=e}})))}))),H(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+Y.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:Z.read(Z.symmetric,e.sessionKeyAlgorithm)})))}throw n||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(Z.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(Z.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(Z.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],i=ae){const n=await Xu("symmetric",e,t,r,i),a=Z.read(Z.symmetric,n),s=i.aeadProtect&&await async function(e,t=new Date,r=[],i=ae){let n=!0;return await Promise.all(e.map((async function(e,a){const s=await e.getPrimaryUser(t,r[a],i);s.selfCertification.features&&s.selfCertification.features[0]&Z.features.aead||(n=!1)}))),n}(e,t,r,i)?Z.read(Z.aead,await Xu("aead",e,t,r,i)):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&e.keyPacket.algorithm===Z.publicKey.x25519&&!Y.isAES(n))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:wa.generateSessionKey(n),algorithm:a,aeadAlgorithm:s}}async encrypt(e,t,r,i=!1,n=[],a=new Date,s=[],o=ae){if(r){if(!Y.isUint8Array(r.data)||!Y.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await vh.generateSessionKey(e,a,s,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await vh.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:u,aeadAlgorithm:h}=r,d=await vh.encryptSessionKey(c,u,h,e,t,i,n,a,s,o);let f;h?(f=new xu,f.aeadAlgorithm=Z.write(Z.aead,h)):f=new Eu,f.packets=this.packets;const l=Z.write(Z.symmetric,u);return await f.encrypt(l,c,o),d.packets.push(f),f.packets=new pu,d}static async encryptSessionKey(e,t,r,i,n,a=!1,s=[],o=new Date,c=[],u=ae){const h=new pu,d=Z.write(Z.symmetric,t),f=r&&Z.write(Z.aead,r);if(i){const t=await Promise.all(i.map((async function(t,r){const i=await t.getEncryptionKey(s[r],o,c,u),n=new Mu;return n.publicKeyID=a?ye.wildcard():i.getKeyID(),n.publicKeyAlgorithm=i.keyPacket.algorithm,n.sessionKey=e,n.sessionKeyAlgorithm=d,await n.encrypt(i.keyPacket),delete n.sessionKey,n})));h.push(...t)}if(n){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,i=async function(e,a,s,o){const c=new Du(u);if(c.sessionKey=e,c.sessionKeyAlgorithm=a,s&&(c.aeadAlgorithm=s),await c.encrypt(o,u),u.passwordCollisionCheck){if(1!==(await Promise.all(n.map((e=>t(c,e))))).reduce(r))return i(e,a,o)}return delete c.sessionKey,c},a=await Promise.all(n.map((t=>i(e,d,f,t))));h.push(...a)}return new vh(h)}async sign(e=[],t=null,r=[],i=new Date,n=[],a=[],s=ae){const o=new pu,c=this.packets.findPacket(Z.packet.literalData);if(!c)throw Error("No literal data packet to sign.");let u,h;const d=null===c.text?Z.signature.binary:Z.signature.text;if(t)for(h=t.packets.filterByTag(Z.packet.signature),u=h.length-1;u>=0;u--){const t=h[u],r=new fu;r.signatureType=t.signatureType,r.hashAlgorithm=t.hashAlgorithm,r.publicKeyAlgorithm=t.publicKeyAlgorithm,r.issuerKeyID=t.issuerKeyID,e.length||0!==u||(r.flags=1),o.push(r)}return await Promise.all(Array.from(e).reverse().map((async function(t,a){if(!t.isPrivate())throw Error("Need private key for signing");const o=r[e.length-1-a],c=await t.getSigningKey(o,i,n,s),u=new fu;return u.signatureType=d,u.hashAlgorithm=await Zu(t,c.keyPacket,i,n,s),u.publicKeyAlgorithm=c.keyPacket.algorithm,u.issuerKeyID=c.getKeyID(),a===e.length-1&&(u.flags=1),u}))).then((e=>{e.forEach((e=>o.push(e)))})),o.push(c),o.push(...await _h(c,e,t,r,i,n,a,!1,s)),new vh(o)}compress(e,t=ae){if(e===Z.compression.uncompressed)return this;const r=new bu(t);r.algorithm=e,r.packets=this.packets;const i=new pu;return i.push(r),new vh(i)}async signDetached(e=[],t=null,r=[],i=new Date,n=[],a=[],s=ae){const o=this.packets.findPacket(Z.packet.literalData);if(!o)throw Error("No literal data packet to sign.");return new ju(await _h(o,e,t,r,i,n,a,!0,s))}async verify(e,t=new Date,r=ae){const i=this.unwrapCompressed(),n=i.packets.filterByTag(Z.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");o(i.packets.stream)&&i.packets.push(...await j(i.packets.stream,(e=>e||[])));const a=i.packets.filterByTag(Z.packet.onePassSignature).reverse(),s=i.packets.filterByTag(Z.packet.signature);return a.length&&!s.length&&Y.isStream(i.packets.stream)&&!o(i.packets.stream)?(await Promise.all(a.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=W((async()=>(await e.correspondingSig).signatureData)),e.hashed=j(await e.hash(e.signatureType,n[0],void 0,!1)),e.hashed.catch((()=>{}))}))),i.packets.stream=z(i.packets.stream,(async(e,t)=>{const r=D(e),i=U(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await i.abort(e)}})),kh(a,n,e,t,!1,r)):kh(s,n,e,t,!1,r)}verifyDetached(e,t,r=new Date,i=ae){const n=this.unwrapCompressed().packets.filterByTag(Z.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");return kh(e.packets.filterByTag(Z.packet.signature),n,t,r,!0,i)}unwrapCompressed(){const e=this.packets.filterByTag(Z.packet.compressedData);return e.length?new vh(e[0].packets):this}async appendSignature(e,t=ae){await this.packets.read(Y.isUint8Array(e)?e:(await le(e)).data,wh,t)}write(){return this.packets.write()}armor(e=ae){return pe(Z.armor.message,this.write(),null,null,null,e)}}async function _h(e,t,r=null,i=[],n=new Date,a=[],s=[],o=!1,c=ae){const u=new pu,h=null===e.text?Z.signature.binary:Z.signature.text;if(await Promise.all(t.map((async(t,r)=>{const u=a[r];if(!t.isPrivate())throw Error("Need private key for signing");const d=await t.getSigningKey(i[r],n,u,c);return Yu(e,t,d.keyPacket,{signatureType:h},n,u,s,o,c)}))).then((e=>{u.push(...e)})),r){const e=r.packets.filterByTag(Z.packet.signature);u.push(...e)}return u}async function kh(e,t,r,i=new Date,n=!1,a=ae){return Promise.all(e.filter((function(e){return["text","binary"].includes(Z.read(Z.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,i=new Date,n=!1,a=ae){let s,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){s=t,o=r[0];break}}const c=e instanceof fu?e.correspondingSig:e,u={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],i,n,a);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await s.getSigningKey(o.getKeyID(),r.created,void 0,a)}catch(e){if(!a.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await s.getSigningKey(o.getKeyID(),i,void 0,a)}return!0})(),signature:(async()=>{const e=await c,t=new pu;return e&&t.push(e),new ju(t)})()};return u.signature.catch((()=>{})),u.verified.catch((()=>{})),u}(e,t,r,i,n,a)})))}const Ah=/*#__PURE__*/Y.constructAllowedPackets([hu]);class Sh{constructor(e,t){if(this.text=Y.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof ju))throw Error("Invalid signature input");this.signature=t||new ju(new pu)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=null,r=[],i=new Date,n=[],a=[],s=ae){const o=new ou;o.setText(this.text);const c=new ju(await _h(o,e,t,r,i,n,a,!0,s));return new Sh(this.text,c)}verify(e,t=new Date,r=ae){const i=this.signature.packets.filterByTag(Z.packet.signature),n=new ou;return n.setText(this.text),kh(i,[n],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=ae){let t=this.signature.packets.map((function(e){return Z.read(Z.hash,e.hashAlgorithm).toUpperCase()}));t=t.filter((function(e,t,r){return r.indexOf(e)===t}));const r={hash:t.join(),text:this.text,data:this.signature.packets.write()};return pe(Z.armor.signed,r,void 0,void 0,void 0,e)}}function Eh(e){if(!(e instanceof vh))throw Error("Parameter [message] needs to be of type Message")}function Ph(e){if(!(e instanceof Sh||e instanceof vh))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function xh(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Mh=Object.keys(ae).length;function Kh(e){const t=Object.keys(e);if(t.length!==Mh)for(const e of t)if(void 0===ae[e])throw Error("Unknown config property: "+e)}function Ch(e){return e&&!Y.isArray(e)&&(e=[e]),e}async function Dh(e,t,r="utf8"){const i=Y.isStream(e);return"array"===i?j(e):"node"===t?(e=g(e),"binary"!==r&&e.setEncoding(r),e):"web"===t&&"ponyfill"===i?k(e):e}function Uh(e,t){e.data=z(t.packets.stream,(async(t,r)=>{await R(e.data,r,{preventClose:!0});const i=U(r);try{await j(t,(e=>e)),await i.close()}catch(e){await i.abort(e)}}))}function Rh(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}const Ih="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function Bh(){}const Th="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function zh(e){return"object"==typeof e&&null!==e||"function"==typeof e}const qh=Bh,Fh=Promise,Oh=Promise.prototype.then,Lh=Promise.resolve.bind(Fh),Nh=Promise.reject.bind(Fh);function jh(e){return new Fh(e)}function Hh(e){return Lh(e)}function Wh(e){return Nh(e)}function Gh(e,t,r){return Oh.call(e,t,r)}function Vh(e,t,r){Gh(Gh(e,t,r),void 0,qh)}function $h(e,t){Vh(e,t)}function Zh(e,t){Vh(e,void 0,t)}function Xh(e,t,r){return Gh(e,t,r)}function Yh(e){Gh(e,void 0,qh)}const Qh=(()=>{const e=Th&&Th.queueMicrotask;if("function"==typeof e)return e;const t=Hh(void 0);return e=>Gh(t,e)})();function Jh(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function ed(e,t,r){try{return Hh(Jh(e,t,r))}catch(e){return Wh(e)}}class td{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let i=r+1;const n=e._elements,a=n[r];return 16384===i&&(t=e._next,i=0),--this._size,this._cursor=i,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,i=r._elements;for(;!(t===i.length&&void 0===r._next||t===i.length&&(r=r._next,i=r._elements,t=0,0===i.length));)e(i[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function rd(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?sd(e):"closed"===t._state?function(e){sd(e),ud(e)}(e):od(e,t._storedError)}function id(e,t){return Ll(e._ownerReadableStream,t)}function nd(e){"readable"===e._ownerReadableStream._state?cd(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){od(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function ad(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function sd(e){e._closedPromise=jh(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function od(e,t){sd(e),cd(e,t)}function cd(e,t){void 0!==e._closedPromise_reject&&(Yh(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function ud(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const hd=Ih("[[AbortSteps]]"),dd=Ih("[[ErrorSteps]]"),fd=Ih("[[CancelSteps]]"),ld=Ih("[[PullSteps]]"),pd=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},yd=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function bd(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(t+" is not an object.");var r}function gd(e,t){if("function"!=typeof e)throw new TypeError(t+" is not a function.")}function md(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(t+" is not an object.")}function wd(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function vd(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function _d(e){return Number(e)}function kd(e){return 0===e?0:e}function Ad(e,t){const r=Number.MAX_SAFE_INTEGER;let i=Number(e);if(i=kd(i),!pd(i))throw new TypeError(t+" is not a finite number");if(i=function(e){return kd(yd(e))}(i),i<0||i>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return pd(i)&&0!==i?i:0}function Sd(e,t){if(!Fl(e))throw new TypeError(t+" is not a ReadableStream.")}function Ed(e){return new Cd(e)}function Pd(e,t){e._reader._readRequests.push(t)}function xd(e,t,r){const i=e._reader._readRequests.shift();r?i._closeSteps():i._chunkSteps(t)}function Md(e){return e._reader._readRequests.length}function Kd(e){const t=e._reader;return void 0!==t&&!!Dd(t)}class Cd{constructor(e){if(wd(e,1,"ReadableStreamDefaultReader"),Sd(e,"First parameter"),Ol(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");rd(this,e),this._readRequests=new td}get closed(){return Dd(this)?this._closedPromise:Wh(Rd("closed"))}cancel(e=undefined){return Dd(this)?void 0===this._ownerReadableStream?Wh(ad("cancel")):id(this,e):Wh(Rd("cancel"))}read(){if(!Dd(this))return Wh(Rd("read"));if(void 0===this._ownerReadableStream)return Wh(ad("read from"));let e,t;const r=jh(((r,i)=>{e=r,t=i}));return Ud(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!Dd(this))throw Rd("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");nd(this)}}}function Dd(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function Ud(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[ld](t)}function Rd(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let Id;Object.defineProperties(Cd.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Cd.prototype,Ih.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof Ih.asyncIterator&&(Id={[Ih.asyncIterator](){return this}},Object.defineProperty(Id,Ih.asyncIterator,{enumerable:!1}));class Bd{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?Xh(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?Xh(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return Wh(ad("iterate"));let t,r;const i=jh(((e,i)=>{t=e,r=i}));return Ud(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,Qh((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,nd(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,nd(e),r(t)}}),i}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return Wh(ad("finish iterating"));if(!this._preventCancel){const r=id(t,e);return nd(t),Xh(r,(()=>({value:e,done:!0})))}return nd(t),Hh({value:e,done:!0})}}const Td={next(){return zd(this)?this._asyncIteratorImpl.next():Wh(qd("next"))},return(e){return zd(this)?this._asyncIteratorImpl.return(e):Wh(qd("return"))}};function zd(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl")}function qd(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==Id&&Object.setPrototypeOf(Td,Id);const Fd=Number.isNaN||function(e){return e!=e};function Od(e){return!!function(e){if("number"!=typeof e)return!1;if(Fd(e))return!1;if(e<0)return!1;return!0}(e)&&e!==1/0}function Ld(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function Nd(e,t,r){if(!Od(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function jd(e){e._queue=new td,e._queueTotalSize=0}function Hd(e){return e.slice()}class Wd{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!$d(this))throw df("view");return this._view}respond(e){if(!$d(this))throw df("respond");if(wd(e,1,"respond"),e=Ad(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(t=Number(t),!Od(t))throw new RangeError("bytesWritten must be a finite");af(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!$d(this))throw df("respondWithNewView");if(wd(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");!function(e,t){const r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,af(e,t.byteLength)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(Wd.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Wd.prototype,Ih.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Gd{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Vd(this))throw ff("byobRequest");if(null===this._byobRequest&&this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(Wd.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest}get desiredSize(){if(!Vd(this))throw ff("desiredSize");return uf(this)}close(){if(!Vd(this))throw ff("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw cf(e,t),t}}of(e),Nl(t)}(this)}enqueue(e){if(!Vd(this))throw ff("enqueue");if(wd(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const i=t.buffer,n=t.byteOffset,a=t.byteLength,s=i;if(Kd(r))if(0===Md(r))Qd(e,s,n,a);else{xd(r,new Uint8Array(s,n,a),!1)}else yf(r)?(Qd(e,s,n,a),nf(e)):Qd(e,s,n,a);Zd(e)}(this,e)}error(e=undefined){if(!Vd(this))throw ff("error");cf(this,e)}[fd](e){if(this._pendingPullIntos.length>0){this._pendingPullIntos.peek().bytesFilled=0}jd(this);const t=this._cancelAlgorithm(e);return of(this),t}[ld](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,tf(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const i={buffer:t,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}Pd(t,e),Zd(this)}}function Vd(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function $d(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function Zd(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(Kd(t)&&Md(t)>0)return!0;if(yf(t)&&pf(t)>0)return!0;const r=uf(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;Vh(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Zd(e))}),(t=>{cf(e,t)}))}function Xd(e,t){let r=!1;"closed"===e._state&&(r=!0);const i=Yd(t);"default"===t.readerType?xd(e,i,r):function(e,t,r){const i=e._reader,n=i._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,i,r)}function Yd(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Qd(e,t,r,i){e._queue.push({buffer:t,byteOffset:r,byteLength:i}),e._queueTotalSize+=i}function Jd(e,t){const r=t.elementSize,i=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,s=a-a%r;let o=n,c=!1;s>i&&(o=s-t.bytesFilled,c=!0);const u=e._queue;for(;o>0;){const r=u.peek(),i=Math.min(o,r.byteLength),n=t.byteOffset+t.bytesFilled;h=t.buffer,d=n,f=r.buffer,l=r.byteOffset,p=i,new Uint8Array(h).set(new Uint8Array(f,l,p),d),r.byteLength===i?u.shift():(r.byteOffset+=i,r.byteLength-=i),e._queueTotalSize-=i,ef(e,i,t),o-=i}var h,d,f,l,p;return c}function ef(e,t,r){rf(e),r.bytesFilled+=t}function tf(e){0===e._queueTotalSize&&e._closeRequested?(of(e),Nl(e._controlledReadableByteStream)):Zd(e)}function rf(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function nf(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Jd(e,t)&&(sf(e),Xd(e._controlledReadableByteStream,t))}}function af(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;const r=e._controlledReadableByteStream;if(yf(r))for(;pf(r)>0;)Xd(r,sf(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(ef(e,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=r.buffer.slice(t-i,t);Qd(e,n,0,n.byteLength)}r.buffer=r.buffer,r.bytesFilled-=i,Xd(e._controlledReadableByteStream,r),nf(e)}(e,t,r);Zd(e)}function sf(e){const t=e._pendingPullIntos.shift();return rf(e),t}function of(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function cf(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(!function(e){rf(e),e._pendingPullIntos=new td}(e),jd(e),of(e),jl(r,t))}function uf(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function hf(e,t,r){const i=Object.create(Gd.prototype);let n=()=>{},a=()=>Hh(void 0),s=()=>Hh(void 0);void 0!==t.start&&(n=()=>t.start(i)),void 0!==t.pull&&(a=()=>t.pull(i)),void 0!==t.cancel&&(s=e=>t.cancel(e));const o=t.autoAllocateChunkSize;if(0===o)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,i,n,a,s){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,jd(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,t._autoAllocateChunkSize=s,t._pendingPullIntos=new td,e._readableStreamController=t,Vh(Hh(r()),(()=>{t._started=!0,Zd(t)}),(e=>{cf(t,e)}))}(e,i,n,a,s,r,o)}function df(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function ff(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function lf(e,t){e._reader._readIntoRequests.push(t)}function pf(e){return e._reader._readIntoRequests.length}function yf(e){const t=e._reader;return void 0!==t&&!!gf(t)}Object.defineProperties(Gd.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Gd.prototype,Ih.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class bf{constructor(e){if(wd(e,1,"ReadableStreamBYOBReader"),Sd(e,"First parameter"),Ol(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Vd(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");rd(this,e),this._readIntoRequests=new td}get closed(){return gf(this)?this._closedPromise:Wh(mf("closed"))}cancel(e=undefined){return gf(this)?void 0===this._ownerReadableStream?Wh(ad("cancel")):id(this,e):Wh(mf("cancel"))}read(e){if(!gf(this))return Wh(mf("read"));if(!ArrayBuffer.isView(e))return Wh(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return Wh(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return Wh(new TypeError("view's buffer must have non-zero byteLength"));if(void 0===this._ownerReadableStream)return Wh(ad("read from"));let t,r;const i=jh(((e,i)=>{t=e,r=i}));return function(e,t,r){const i=e._ownerReadableStream;i._disturbed=!0,"errored"===i._state?r._errorSteps(i._storedError):function(e,t,r){const i=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,s={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(s),void lf(i,r);if("closed"!==i._state){if(e._queueTotalSize>0){if(Jd(e,s)){const t=Yd(s);return tf(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return cf(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(s),lf(i,r),Zd(e)}else{const e=new a(s.buffer,s.byteOffset,0);r._closeSteps(e)}}(i._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),i}releaseLock(){if(!gf(this))throw mf("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");nd(this)}}}function gf(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function mf(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function wf(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(Fd(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function vf(e){const{size:t}=e;return t||(()=>1)}function _f(e,t){bd(e,t);const r=null==e?void 0:e.highWaterMark,i=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:_d(r),size:void 0===i?void 0:kf(i,t+" has member 'size' that")}}function kf(e,t){return gd(e,t),t=>_d(e(t))}function Af(e,t,r){return gd(e,r),r=>ed(e,t,[r])}function Sf(e,t,r){return gd(e,r),()=>ed(e,t,[])}function Ef(e,t,r){return gd(e,r),r=>Jh(e,t,[r])}function Pf(e,t,r){return gd(e,r),(r,i)=>ed(e,t,[r,i])}function xf(e,t){if(!Df(e))throw new TypeError(t+" is not a WritableStream.")}Object.defineProperties(bf.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(bf.prototype,Ih.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});class Mf{constructor(e={},t={}){void 0===e?e=null:md(e,"First parameter");const r=_f(t,"Second parameter"),i=function(e,t){bd(e,t);const r=null==e?void 0:e.abort,i=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,s=null==e?void 0:e.write;return{abort:void 0===r?void 0:Af(r,e,t+" has member 'abort' that"),close:void 0===i?void 0:Sf(i,e,t+" has member 'close' that"),start:void 0===n?void 0:Ef(n,e,t+" has member 'start' that"),write:void 0===s?void 0:Pf(s,e,t+" has member 'write' that"),type:a}}(e,"First parameter");Cf(this);if(void 0!==i.type)throw new RangeError("Invalid type is specified");const n=vf(r);!function(e,t,r,i){const n=Object.create(Zf.prototype);let a=()=>{},s=()=>Hh(void 0),o=()=>Hh(void 0),c=()=>Hh(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(s=e=>t.write(e,n));void 0!==t.close&&(o=()=>t.close());void 0!==t.abort&&(c=e=>t.abort(e));Xf(e,n,a,s,o,c,r,i)}(this,i,wf(r,1),n)}get locked(){if(!Df(this))throw il("locked");return Uf(this)}abort(e=undefined){return Df(this)?Uf(this)?Wh(new TypeError("Cannot abort a stream that already has a writer")):Rf(this,e):Wh(il("abort"))}close(){return Df(this)?Uf(this)?Wh(new TypeError("Cannot close a stream that already has a writer")):qf(this)?Wh(new TypeError("Cannot close an already-closing stream")):If(this):Wh(il("close"))}getWriter(){if(!Df(this))throw il("getWriter");return Kf(this)}}function Kf(e){return new Lf(e)}function Cf(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new td,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Df(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function Uf(e){return void 0!==e._writer}function Rf(e,t){const r=e._state;if("closed"===r||"errored"===r)return Hh(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let i=!1;"erroring"===r&&(i=!0,t=void 0);const n=jh(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:i}}));return e._pendingAbortRequest._promise=n,i||Tf(e,t),n}function If(e){const t=e._state;if("closed"===t||"errored"===t)return Wh(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=jh(((t,r)=>{const i={_resolve:t,_reject:r};e._closeRequest=i})),i=e._writer;var n;return void 0!==i&&e._backpressure&&"writable"===t&&pl(i),Nd(n=e._writableStreamController,$f,0),Jf(n),r}function Bf(e,t){"writable"!==e._state?zf(e):Tf(e,t)}function Tf(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const i=e._writer;void 0!==i&&Wf(i,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&zf(e)}function zf(e){e._state="errored",e._writableStreamController[dd]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new td,void 0===e._pendingAbortRequest)return void Ff(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Ff(e);Vh(e._writableStreamController[hd](r._reason),(()=>{r._resolve(),Ff(e)}),(t=>{r._reject(t),Ff(e)}))}function qf(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Ff(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&cl(t,e._storedError)}function Of(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){hl(e)}(r):pl(r)),e._backpressure=t}Object.defineProperties(Mf.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Mf.prototype,Ih.toStringTag,{value:"WritableStream",configurable:!0});class Lf{constructor(e){if(wd(e,1,"WritableStreamDefaultWriter"),xf(e,"First parameter"),Uf(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!qf(e)&&e._backpressure?hl(this):fl(this),sl(this);else if("erroring"===t)dl(this,e._storedError),sl(this);else if("closed"===t)fl(this),sl(r=this),ul(r);else{const t=e._storedError;dl(this,t),ol(this,t)}var r}get closed(){return Nf(this)?this._closedPromise:Wh(nl("closed"))}get desiredSize(){if(!Nf(this))throw nl("desiredSize");if(void 0===this._ownerWritableStream)throw al("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Qf(t._writableStreamController)}(this)}get ready(){return Nf(this)?this._readyPromise:Wh(nl("ready"))}abort(e=undefined){return Nf(this)?void 0===this._ownerWritableStream?Wh(al("abort")):function(e,t){const r=e._ownerWritableStream;return Rf(r,t)}(this,e):Wh(nl("abort"))}close(){if(!Nf(this))return Wh(nl("close"));const e=this._ownerWritableStream;return void 0===e?Wh(al("close")):qf(e)?Wh(new TypeError("Cannot close an already-closing stream")):jf(this)}releaseLock(){if(!Nf(this))throw nl("releaseLock");void 0!==this._ownerWritableStream&&Gf(this)}write(e=undefined){return Nf(this)?void 0===this._ownerWritableStream?Wh(al("write to")):Vf(this,e):Wh(nl("write"))}}function Nf(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function jf(e){return If(e._ownerWritableStream)}function Hf(e,t){"pending"===e._closedPromiseState?cl(e,t):function(e,t){ol(e,t)}(e,t)}function Wf(e,t){"pending"===e._readyPromiseState?ll(e,t):function(e,t){dl(e,t)}(e,t)}function Gf(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Wf(e,r),Hf(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Vf(e,t){const r=e._ownerWritableStream,i=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return el(e,t),1}}(i,t);if(r!==e._ownerWritableStream)return Wh(al("write to"));const a=r._state;if("errored"===a)return Wh(r._storedError);if(qf(r)||"closed"===a)return Wh(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return Wh(r._storedError);const s=function(e){return jh(((t,r)=>{const i={_resolve:t,_reject:r};e._writeRequests.push(i)}))}(r);return function(e,t,r){try{Nd(e,t,r)}catch(t){return void el(e,t)}const i=e._controlledWritableStream;if(!qf(i)&&"writable"===i._state){Of(i,tl(e))}Jf(e)}(i,t,n),s}Object.defineProperties(Lf.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Lf.prototype,Ih.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const $f={};class Zf{constructor(){throw new TypeError("Illegal constructor")}error(e=undefined){if(!function(e){if(!zh(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream"))return!1;return!0}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&rl(this,e)}[hd](e){const t=this._abortAlgorithm(e);return Yf(this),t}[dd](){jd(this)}}function Xf(e,t,r,i,n,a,s,o){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,jd(t),t._started=!1,t._strategySizeAlgorithm=o,t._strategyHWM=s,t._writeAlgorithm=i,t._closeAlgorithm=n,t._abortAlgorithm=a;const c=tl(t);Of(e,c);Vh(Hh(r()),(()=>{t._started=!0,Jf(t)}),(r=>{t._started=!0,Bf(e,r)}))}function Yf(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Qf(e){return e._strategyHWM-e._queueTotalSize}function Jf(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void zf(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===$f?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),Ld(e);const r=e._closeAlgorithm();Yf(e),Vh(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&ul(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Bf(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const i=e._writeAlgorithm(t);Vh(i,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(Ld(e),!qf(r)&&"writable"===t){const t=tl(e);Of(r,t)}Jf(e)}),(t=>{"writable"===r._state&&Yf(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Bf(e,t)}(r,t)}))}(e,r)}function el(e,t){"writable"===e._controlledWritableStream._state&&rl(e,t)}function tl(e){return Qf(e)<=0}function rl(e,t){const r=e._controlledWritableStream;Yf(e),Tf(r,t)}function il(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function nl(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function al(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function sl(e){e._closedPromise=jh(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function ol(e,t){sl(e),cl(e,t)}function cl(e,t){void 0!==e._closedPromise_reject&&(Yh(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function ul(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function hl(e){e._readyPromise=jh(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function dl(e,t){hl(e),ll(e,t)}function fl(e){hl(e),pl(e)}function ll(e,t){void 0!==e._readyPromise_reject&&(Yh(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function pl(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Zf.prototype,{error:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Zf.prototype,Ih.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const yl="undefined"!=typeof DOMException?DOMException:void 0;const bl=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(yl)?yl:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return Object.defineProperty(e.prototype=Object.create(Error.prototype),"constructor",{value:e,writable:!0,configurable:!0}),e}();function gl(e,t,r,i,n,a){const s=Ed(e),o=Kf(t);e._disturbed=!0;let c=!1,u=Hh(void 0);return jh(((h,d)=>{let f;if(void 0!==a){if(f=()=>{const r=new bl("Aborted","AbortError"),a=[];i||a.push((()=>"writable"===t._state?Rf(t,r):Hh(void 0))),n||a.push((()=>"readable"===e._state?Ll(e,r):Hh(void 0))),y((()=>Promise.all(a.map((e=>e())))),!0,r)},a.aborted)return void f();a.addEventListener("abort",f)}if(p(e,s._closedPromise,(e=>{i?b(!0,e):y((()=>Rf(t,e)),!0,e)})),p(t,o._closedPromise,(t=>{n?b(!0,t):y((()=>Ll(e,t)),!0,t)})),function(e,t,r){"closed"===e._state?r():$h(t,r)}(e,s._closedPromise,(()=>{r?b():y((()=>function(e){const t=e._ownerWritableStream,r=t._state;return qf(t)||"closed"===r?Hh(void 0):"errored"===r?Wh(t._storedError):jf(e)}(o)))})),qf(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");n?b(!0,t):y((()=>Ll(e,t)),!0,t)}function l(){const e=u;return Gh(u,(()=>e!==u?l():void 0))}function p(e,t,r){"errored"===e._state?r(e._storedError):Zh(t,r)}function y(e,r,i){function n(){Vh(e(),(()=>g(r,i)),(e=>g(!0,e)))}c||(c=!0,"writable"!==t._state||qf(t)?n():$h(l(),n))}function b(e,r){c||(c=!0,"writable"!==t._state||qf(t)?g(e,r):$h(l(),(()=>g(e,r))))}function g(e,t){Gf(o),nd(s),void 0!==a&&a.removeEventListener("abort",f),e?d(t):h(void 0)}Yh(jh(((e,t)=>{!function r(i){i?e():Gh(c?Hh(!0):Gh(o._readyPromise,(()=>jh(((e,t)=>{Ud(s,{_chunkSteps:t=>{u=Gh(Vf(o,t),void 0,Bh),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),r,t)}(!1)})))}))}class ml{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!wl(this))throw Kl("desiredSize");return Pl(this)}close(){if(!wl(this))throw Kl("close");if(!xl(this))throw new TypeError("The stream is not in a state that permits close");Al(this)}enqueue(e=undefined){if(!wl(this))throw Kl("enqueue");if(!xl(this))throw new TypeError("The stream is not in a state that permits enqueue");return Sl(this,e)}error(e=undefined){if(!wl(this))throw Kl("error");El(this,e)}[fd](e){jd(this);const t=this._cancelAlgorithm(e);return kl(this),t}[ld](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=Ld(this);this._closeRequested&&0===this._queue.length?(kl(this),Nl(t)):vl(this),e._chunkSteps(r)}else Pd(t,e),vl(this)}}function wl(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function vl(e){if(!_l(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;Vh(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,vl(e))}),(t=>{El(e,t)}))}function _l(e){const t=e._controlledReadableStream;if(!xl(e))return!1;if(!e._started)return!1;if(Ol(t)&&Md(t)>0)return!0;return Pl(e)>0}function kl(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Al(e){if(!xl(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(kl(e),Nl(t))}function Sl(e,t){if(!xl(e))return;const r=e._controlledReadableStream;if(Ol(r)&&Md(r)>0)xd(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw El(e,t),t}try{Nd(e,t,r)}catch(t){throw El(e,t),t}}vl(e)}function El(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(jd(e),kl(e),jl(r,t))}function Pl(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function xl(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Ml(e,t,r,i,n,a,s){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,jd(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=s,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,e._readableStreamController=t;Vh(Hh(r()),(()=>{t._started=!0,vl(t)}),(e=>{El(t,e)}))}function Kl(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Cl(e,t,r){return gd(e,r),r=>ed(e,t,[r])}function Dl(e,t,r){return gd(e,r),r=>ed(e,t,[r])}function Ul(e,t,r){return gd(e,r),r=>Jh(e,t,[r])}function Rl(e,t){if("bytes"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Il(e,t){if("byob"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Bl(e,t){bd(e,t);const r=null==e?void 0:e.preventAbort,i=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(t+" is not an AbortSignal.")}(a,t+" has member 'signal' that"),{preventAbort:!!r,preventCancel:!!i,preventClose:!!n,signal:a}}Object.defineProperties(ml.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(ml.prototype,Ih.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class Tl{constructor(e={},t={}){void 0===e?e=null:md(e,"First parameter");const r=_f(t,"Second parameter"),i=function(e,t){bd(e,t);const r=e,i=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,s=null==r?void 0:r.start,o=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===i?void 0:Ad(i,t+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:Cl(n,r,t+" has member 'cancel' that"),pull:void 0===a?void 0:Dl(a,r,t+" has member 'pull' that"),start:void 0===s?void 0:Ul(s,r,t+" has member 'start' that"),type:void 0===o?void 0:Rl(o,t+" has member 'type' that")}}(e,"First parameter");if(ql(this),"bytes"===i.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");hf(this,i,wf(r,0))}else{const e=vf(r);!function(e,t,r,i){const n=Object.create(ml.prototype);let a=()=>{},s=()=>Hh(void 0),o=()=>Hh(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(s=()=>t.pull(n)),void 0!==t.cancel&&(o=e=>t.cancel(e)),Ml(e,n,a,s,o,r,i)}(this,i,wf(r,1),e)}}get locked(){if(!Fl(this))throw Hl("locked");return Ol(this)}cancel(e=undefined){return Fl(this)?Ol(this)?Wh(new TypeError("Cannot cancel a stream that already has a reader")):Ll(this,e):Wh(Hl("cancel"))}getReader(e=undefined){if(!Fl(this))throw Hl("getReader");const t=function(e,t){bd(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Il(r,t+" has member 'mode' that")}}(e,"First parameter");return void 0===t.mode?Ed(this):function(e){return new bf(e)}(this)}pipeThrough(e,t={}){if(!Fl(this))throw Hl("pipeThrough");wd(e,1,"pipeThrough");const r=function(e,t){bd(e,t);const r=null==e?void 0:e.readable;vd(r,"readable","ReadableWritablePair"),Sd(r,t+" has member 'readable' that");const i=null==e?void 0:e.writable;return vd(i,"writable","ReadableWritablePair"),xf(i,t+" has member 'writable' that"),{readable:r,writable:i}}(e,"First parameter"),i=Bl(t,"Second parameter");if(Ol(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Uf(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return Yh(gl(this,r.writable,i.preventClose,i.preventAbort,i.preventCancel,i.signal)),r.readable}pipeTo(e,t={}){if(!Fl(this))return Wh(Hl("pipeTo"));if(void 0===e)return Wh("Parameter 1 is required in 'pipeTo'.");if(!Df(e))return Wh(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Bl(t,"Second parameter")}catch(e){return Wh(e)}return Ol(this)?Wh(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Uf(e)?Wh(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gl(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Fl(this))throw Hl("tee");const e=function(e,t){const r=Ed(e);let i,n,a,s,o,c=!1,u=!1,h=!1;const d=jh((e=>{o=e}));function f(){return c||(c=!0,Ud(r,{_chunkSteps:e=>{Qh((()=>{c=!1;const t=e,r=e;u||Sl(a._readableStreamController,t),h||Sl(s._readableStreamController,r)}))},_closeSteps:()=>{c=!1,u||Al(a._readableStreamController),h||Al(s._readableStreamController),u&&h||o(void 0)},_errorSteps:()=>{c=!1}})),Hh(void 0)}function l(){}return a=zl(l,f,(function(t){if(u=!0,i=t,h){const t=Hd([i,n]),r=Ll(e,t);o(r)}return d})),s=zl(l,f,(function(t){if(h=!0,n=t,u){const t=Hd([i,n]),r=Ll(e,t);o(r)}return d})),Zh(r._closedPromise,(e=>{El(a._readableStreamController,e),El(s._readableStreamController,e),u&&h||o(void 0)})),[a,s]}(this);return Hd(e)}values(e=undefined){if(!Fl(this))throw Hl("values");return function(e,t){const r=Ed(e),i=new Bd(r,t),n=Object.create(Td);return n._asyncIteratorImpl=i,n}(this,function(e,t){return bd(e,t),{preventCancel:!!(null==e?void 0:e.preventCancel)}}(e,"First parameter").preventCancel)}}function zl(e,t,r,i=1,n=(()=>1)){const a=Object.create(Tl.prototype);ql(a);return Ml(a,Object.create(ml.prototype),e,t,r,i,n),a}function ql(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Fl(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function Ol(e){return void 0!==e._reader}function Ll(e,t){if(e._disturbed=!0,"closed"===e._state)return Hh(void 0);if("errored"===e._state)return Wh(e._storedError);Nl(e);return Xh(e._readableStreamController[fd](t),Bh)}function Nl(e){e._state="closed";const t=e._reader;void 0!==t&&(ud(t),Dd(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new td))}function jl(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(cd(r,t),Dd(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new td):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new td))}function Hl(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Wl(e,t){bd(e,t);const r=null==e?void 0:e.highWaterMark;return vd(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:_d(r)}}Object.defineProperties(Tl.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Tl.prototype,Ih.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof Ih.asyncIterator&&Object.defineProperty(Tl.prototype,Ih.asyncIterator,{value:Tl.prototype.values,writable:!0,configurable:!0});const Gl=function(e){return e.byteLength};class Vl{constructor(e){wd(e,1,"ByteLengthQueuingStrategy"),e=Wl(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Zl(this))throw $l("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Zl(this))throw $l("size");return Gl}}function $l(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Zl(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")}Object.defineProperties(Vl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Vl.prototype,Ih.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Xl=function(){return 1};class Yl{constructor(e){wd(e,1,"CountQueuingStrategy"),e=Wl(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Jl(this))throw Ql("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Jl(this))throw Ql("size");return Xl}}function Ql(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Jl(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")}function ep(e,t,r){return gd(e,r),r=>ed(e,t,[r])}function tp(e,t,r){return gd(e,r),r=>Jh(e,t,[r])}function rp(e,t,r){return gd(e,r),(r,i)=>ed(e,t,[r,i])}Object.defineProperties(Yl.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(Yl.prototype,Ih.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class ip{constructor(e={},t={},r={}){void 0===e&&(e=null);const i=_f(t,"Second parameter"),n=_f(r,"Third parameter"),a=function(e,t){bd(e,t);const r=null==e?void 0:e.flush,i=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,s=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ep(r,e,t+" has member 'flush' that"),readableType:i,start:void 0===n?void 0:tp(n,e,t+" has member 'start' that"),transform:void 0===a?void 0:rp(a,e,t+" has member 'transform' that"),writableType:s}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const s=wf(n,0),o=vf(n),c=wf(i,1),u=vf(i);let h;!function(e,t,r,i,n,a){function s(){return t}function o(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return Xh(e._backpressureChangePromise,(()=>{const i=e._writable;if("erroring"===i._state)throw i._storedError;return fp(r,t)}))}return fp(r,t)}(e,t)}function c(t){return function(e,t){return ap(e,t),Hh(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,i=r._flushAlgorithm();return hp(r),Xh(i,(()=>{if("errored"===t._state)throw t._storedError;Al(t._readableStreamController)}),(r=>{throw ap(e,r),t._storedError}))}(e)}function h(){return function(e){return op(e,!1),e._backpressureChangePromise}(e)}function d(t){return sp(e,t),Hh(void 0)}e._writable=function(e,t,r,i,n=1,a=(()=>1)){const s=Object.create(Mf.prototype);return Cf(s),Xf(s,Object.create(Zf.prototype),e,t,r,i,n,a),s}(s,o,u,c,r,i),e._readable=zl(s,h,d,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,op(e,!0),e._transformStreamController=void 0}(this,jh((e=>{h=e})),c,u,s,o),function(e,t){const r=Object.create(cp.prototype);let i=e=>{try{return dp(r,e),Hh(void 0)}catch(e){return Wh(e)}},n=()=>Hh(void 0);void 0!==t.transform&&(i=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,i){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=i}(e,r,i,n)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!np(this))throw pp("readable");return this._readable}get writable(){if(!np(this))throw pp("writable");return this._writable}}function np(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function ap(e,t){El(e._readable._readableStreamController,t),sp(e,t)}function sp(e,t){hp(e._transformStreamController),el(e._writable._writableStreamController,t),e._backpressure&&op(e,!1)}function op(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=jh((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(ip.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(ip.prototype,Ih.toStringTag,{value:"TransformStream",configurable:!0});class cp{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!up(this))throw lp("desiredSize");return Pl(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=undefined){if(!up(this))throw lp("enqueue");dp(this,e)}error(e=undefined){if(!up(this))throw lp("error");var t;t=e,ap(this._controlledTransformStream,t)}terminate(){if(!up(this))throw lp("terminate");!function(e){const t=e._controlledTransformStream,r=t._readable._readableStreamController;Al(r);sp(t,new TypeError("TransformStream terminated"))}(this)}}function up(e){return!!zh(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function hp(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function dp(e,t){const r=e._controlledTransformStream,i=r._readable._readableStreamController;if(!xl(i))throw new TypeError("Readable side is not in a state that permits enqueue");try{Sl(i,t)}catch(e){throw sp(r,e),r._readable._storedError}const n=function(e){return!_l(e)}(i);n!==r._backpressure&&op(r,!0)}function fp(e,t){return Xh(e._transformAlgorithm(t),void 0,(t=>{throw ap(e._controlledTransformStream,t),t}))}function lp(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function pp(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(cp.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof Ih.toStringTag&&Object.defineProperty(cp.prototype,Ih.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var yp=/*#__PURE__*/Object.freeze({__proto__:null,ByteLengthQueuingStrategy:Vl,CountQueuingStrategy:Yl,ReadableByteStreamController:Gd,ReadableStream:Tl,ReadableStreamBYOBReader:bf,ReadableStreamBYOBRequest:Wd,ReadableStreamDefaultController:ml,ReadableStreamDefaultReader:Cd,TransformStream:ip,TransformStreamDefaultController:cp,WritableStream:Mf,WritableStreamDefaultController:Zf,WritableStreamDefaultWriter:Lf}),bp=function(e,t){return bp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},bp(e,t)}; -/*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */function gp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+t+" is not a constructor or null");function r(){this.constructor=e}bp(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function mp(e){if(!e)throw new TypeError("Assertion failed")}function wp(){}function vp(e){return"object"==typeof e&&null!==e||"function"==typeof e}function _p(e){if("function"!=typeof e)return!1;var t=!1;try{new e({start:function(){t=!0}})}catch(e){}return t}function kp(e){return!!vp(e)&&"function"==typeof e.getReader}function Ap(e){return!!vp(e)&&"function"==typeof e.getWriter}function Sp(e){return!!vp(e)&&(!!kp(e.readable)&&!!Ap(e.writable))}function Ep(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}function Pp(e,t){var r=(void 0===t?{}:t).type;return mp(kp(e)),mp(!1===e.locked),"bytes"===(r=xp(r))?new Dp(e):new Kp(e)}function xp(e){var t=e+"";if("bytes"===t)return t;if(void 0===e)return e;throw new RangeError("Invalid type is specified")}var Mp=function(){function e(e){this._underlyingReader=void 0,this._readerMode=void 0,this._readableStreamController=void 0,this._pendingRead=void 0,this._underlyingStream=e,this._attachDefaultReader()}return e.prototype.start=function(e){this._readableStreamController=e},e.prototype.cancel=function(e){return mp(void 0!==this._underlyingReader),this._underlyingReader.cancel(e)},e.prototype._attachDefaultReader=function(){if("default"!==this._readerMode){this._detachReader();var e=this._underlyingStream.getReader();this._readerMode="default",this._attachReader(e)}},e.prototype._attachReader=function(e){var t=this;mp(void 0===this._underlyingReader),this._underlyingReader=e;var r=this._underlyingReader.closed;r&&r.then((function(){return t._finishPendingRead()})).then((function(){e===t._underlyingReader&&t._readableStreamController.close()}),(function(r){e===t._underlyingReader&&t._readableStreamController.error(r)})).catch(wp)},e.prototype._detachReader=function(){void 0!==this._underlyingReader&&(this._underlyingReader.releaseLock(),this._underlyingReader=void 0,this._readerMode=void 0)},e.prototype._pullWithDefaultReader=function(){var e=this;this._attachDefaultReader();var t=this._underlyingReader.read().then((function(t){var r=e._readableStreamController;t.done?e._tryClose():r.enqueue(t.value)}));return this._setPendingRead(t),t},e.prototype._tryClose=function(){try{this._readableStreamController.close()}catch(e){}},e.prototype._setPendingRead=function(e){var t,r=this,i=function(){r._pendingRead===t&&(r._pendingRead=void 0)};this._pendingRead=t=e.then(i,i)},e.prototype._finishPendingRead=function(){var e=this;if(this._pendingRead){var t=function(){return e._finishPendingRead()};return this._pendingRead.then(t,t)}},e}(),Kp=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return gp(t,e),t.prototype.pull=function(){return this._pullWithDefaultReader()},t}(Mp);function Cp(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Dp=function(e){function t(t){var r=this,i=Ep(t);return(r=e.call(this,t)||this)._supportsByob=i,r}return gp(t,e),Object.defineProperty(t.prototype,"type",{get:function(){return"bytes"},enumerable:!1,configurable:!0}),t.prototype._attachByobReader=function(){if("byob"!==this._readerMode){mp(this._supportsByob),this._detachReader();var e=this._underlyingStream.getReader({mode:"byob"});this._readerMode="byob",this._attachReader(e)}},t.prototype.pull=function(){if(this._supportsByob){var e=this._readableStreamController.byobRequest;if(e)return this._pullWithByobRequest(e)}return this._pullWithDefaultReader()},t.prototype._pullWithByobRequest=function(e){var t=this;this._attachByobReader();var r=new Uint8Array(e.view.byteLength),i=this._underlyingReader.read(r).then((function(r){var i,n,a;t._readableStreamController,r.done?(t._tryClose(),e.respond(0)):(i=r.value,n=e.view,a=Cp(i),Cp(n).set(a,0),e.respond(r.value.byteLength))}));return this._setPendingRead(i),i},t}(Mp);function Up(e){mp(Ap(e)),mp(!1===e.locked);var t=e.getWriter();return new Rp(t)}var Rp=function(){function e(e){var t=this;this._writableStreamController=void 0,this._pendingWrite=void 0,this._state="writable",this._storedError=void 0,this._underlyingWriter=e,this._errorPromise=new Promise((function(e,r){t._errorPromiseReject=r})),this._errorPromise.catch(wp)}return e.prototype.start=function(e){var t=this;this._writableStreamController=e,this._underlyingWriter.closed.then((function(){t._state="closed"})).catch((function(e){return t._finishErroring(e)}))},e.prototype.write=function(e){var t=this,r=this._underlyingWriter;if(null===r.desiredSize)return r.ready;var i=r.write(e);i.catch((function(e){return t._finishErroring(e)})),r.ready.catch((function(e){return t._startErroring(e)}));var n=Promise.race([i,this._errorPromise]);return this._setPendingWrite(n),n},e.prototype.close=function(){var e=this;return void 0===this._pendingWrite?this._underlyingWriter.close():this._finishPendingWrite().then((function(){return e.close()}))},e.prototype.abort=function(e){if("errored"!==this._state)return this._underlyingWriter.abort(e)},e.prototype._setPendingWrite=function(e){var t,r=this,i=function(){r._pendingWrite===t&&(r._pendingWrite=void 0)};this._pendingWrite=t=e.then(i,i)},e.prototype._finishPendingWrite=function(){var e=this;if(void 0===this._pendingWrite)return Promise.resolve();var t=function(){return e._finishPendingWrite()};return this._pendingWrite.then(t,t)},e.prototype._startErroring=function(e){var t=this;if("writable"===this._state){this._state="erroring",this._storedError=e;var r=function(){return t._finishErroring(e)};void 0===this._pendingWrite?r():this._finishPendingWrite().then(r,r),this._writableStreamController.error(e)}},e.prototype._finishErroring=function(e){"writable"===this._state&&this._startErroring(e),"erroring"===this._state&&(this._state="errored",this._errorPromiseReject(this._storedError))},e}();function Ip(e){mp(Sp(e));var t=e.readable,r=e.writable;mp(!1===t.locked),mp(!1===r.locked);var i,n=t.getReader();try{i=r.getWriter()}catch(e){throw n.releaseLock(),e}return new Bp(n,i)}var Bp=function(){function e(e,t){var r=this;this._transformStreamController=void 0,this._onRead=function(e){if(!e.done)return r._transformStreamController.enqueue(e.value),r._reader.read().then(r._onRead)},this._onError=function(e){r._flushReject(e),r._transformStreamController.error(e),r._reader.cancel(e).catch(wp),r._writer.abort(e).catch(wp)},this._onTerminate=function(){r._flushResolve(),r._transformStreamController.terminate();var e=new TypeError("TransformStream terminated");r._writer.abort(e).catch(wp)},this._reader=e,this._writer=t,this._flushPromise=new Promise((function(e,t){r._flushResolve=e,r._flushReject=t}))}return e.prototype.start=function(e){this._transformStreamController=e,this._reader.read().then(this._onRead).then(this._onTerminate,this._onError);var t=this._reader.closed;t&&t.then(this._onTerminate,this._onError)},e.prototype.transform=function(e){return this._writer.write(e)},e.prototype.flush=function(){var e=this;return this._writer.close().then((function(){return e._flushPromise}))},e}(),Tp=/*#__PURE__*/Object.freeze({__proto__:null,createReadableStreamWrapper:function(e){mp(function(e){return!!_p(e)&&!!kp(new e)}(e));var t=function(e){try{return new e({type:"bytes"}),!0}catch(e){return!1}}(e);return function(r,i){var n=(void 0===i?{}:i).type;if("bytes"!==(n=xp(n))||t||(n=void 0),r.constructor===e&&("bytes"!==n||Ep(r)))return r;if("bytes"===n){var a=Pp(r,{type:n});return new e(a)}a=Pp(r);return new e(a)}},createTransformStreamWrapper:function(e){return mp(function(e){return!!_p(e)&&!!Sp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=Ip(t);return new e(r)}},createWrappingReadableSource:Pp,createWrappingTransformer:Ip,createWrappingWritableSink:Up,createWritableStreamWrapper:function(e){return mp(function(e){return!!_p(e)&&!!Ap(new e)}(e)),function(t){if(t.constructor===e)return t;var r=Up(t);return new e(r)}}}),zp=nt((function(e){!function(e,t){function r(e,t){if(!e)throw Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function n(e,t,r){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof e?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;try{a=void 0}catch(e){}function s(e,t,r){for(var i=0,n=Math.min(e.length,r),a=t;a=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return i}function o(e,t,r,i){for(var n=0,a=Math.min(e.length,r),s=t;s=49?o-49+10:o>=17?o-17+10:o}return n}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return e.cmp(t)<0?e:t},n.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&n++,16===t?this._parseHex(e,n):this._parseBase(e,t,n),"-"===e[0]&&(this.negative=1),this.strip(),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initNumber=function(e,t,i){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initArray=function(e,t,i){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var n=0;n=0;n-=3)s=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[a]|=s<>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);else if("le"===i)for(n=0,a=0;n>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);return this.strip()},n.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var r=0;r=t;r-=6)n=s(e,r,r+6),this.words[i]|=n<>>26-a&4194303,(a+=24)>=26&&(a-=26,i++);r+6!==t&&(n=s(e,t,r+6),this.words[i]|=n<>>26-a&4194303),this.strip()},n.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var a=e.length-r,s=a%i,c=Math.min(a,a-s)+r,u=0,h=r;h1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],a=0|t.words[0],s=n*a,o=67108863&s,c=s/67108864|0;r.words[0]=o;for(var u=1;u>>26,d=67108863&c,f=Math.min(u,t.length-1),l=Math.max(0,u-e.length+1);l<=f;l++){var p=u-l|0;h+=(s=(n=0|e.words[p])*(a=0|t.words[l])+d)/67108864|0,d=67108863&s}r.words[u]=0|d,c=0|h}return 0!==c?r.words[u]=0|c:r.length--,r.strip()}n.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var n=0,a=0,s=0;s>>24-n&16777215)||s!==this.length-1?c[6-d.length]+d+i:d+i,(n+=2)>=26&&(n-=26,s--)}for(0!==a&&(i=a.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var f=u[e],l=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var y=p.modn(l).toString(e);i=(p=p.idivn(l)).isZero()?y+i:c[f-y.length]+y+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return r(void 0!==a),this.toArrayLike(a,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,i){var n=this.byteLength(),a=i||Math.max(1,n);r(n<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var s,o,c="le"===t,u=new e(a),h=this.clone();if(c){for(o=0;!h.isZero();o++)s=h.andln(255),h.iushrn(8),u[o]=s;for(;o=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-i),this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var i=e/26|0,n=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,a=0;a>>26;for(;0!==n&&a>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;ae.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var a=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==a&&s>26,this.words[s]=67108863&t;if(0===a&&s>>13,l=0|s[1],p=8191&l,y=l>>>13,b=0|s[2],g=8191&b,m=b>>>13,w=0|s[3],v=8191&w,_=w>>>13,k=0|s[4],A=8191&k,S=k>>>13,E=0|s[5],P=8191&E,x=E>>>13,M=0|s[6],K=8191&M,C=M>>>13,D=0|s[7],U=8191&D,R=D>>>13,I=0|s[8],B=8191&I,T=I>>>13,z=0|s[9],q=8191&z,F=z>>>13,O=0|o[0],L=8191&O,N=O>>>13,j=0|o[1],H=8191&j,W=j>>>13,G=0|o[2],V=8191&G,$=G>>>13,Z=0|o[3],X=8191&Z,Y=Z>>>13,Q=0|o[4],J=8191&Q,ee=Q>>>13,te=0|o[5],re=8191&te,ie=te>>>13,ne=0|o[6],ae=8191&ne,se=ne>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,he=0|o[8],de=8191&he,fe=he>>>13,le=0|o[9],pe=8191&le,ye=le>>>13;r.negative=e.negative^t.negative,r.length=19;var be=(u+(i=Math.imul(d,L))|0)+((8191&(n=(n=Math.imul(d,N))+Math.imul(f,L)|0))<<13)|0;u=((a=Math.imul(f,N))+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(p,L),n=(n=Math.imul(p,N))+Math.imul(y,L)|0,a=Math.imul(y,N);var ge=(u+(i=i+Math.imul(d,H)|0)|0)+((8191&(n=(n=n+Math.imul(d,W)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,W)|0)+(n>>>13)|0)+(ge>>>26)|0,ge&=67108863,i=Math.imul(g,L),n=(n=Math.imul(g,N))+Math.imul(m,L)|0,a=Math.imul(m,N),i=i+Math.imul(p,H)|0,n=(n=n+Math.imul(p,W)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,W)|0;var me=(u+(i=i+Math.imul(d,V)|0)|0)+((8191&(n=(n=n+Math.imul(d,$)|0)+Math.imul(f,V)|0))<<13)|0;u=((a=a+Math.imul(f,$)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(v,L),n=(n=Math.imul(v,N))+Math.imul(_,L)|0,a=Math.imul(_,N),i=i+Math.imul(g,H)|0,n=(n=n+Math.imul(g,W)|0)+Math.imul(m,H)|0,a=a+Math.imul(m,W)|0,i=i+Math.imul(p,V)|0,n=(n=n+Math.imul(p,$)|0)+Math.imul(y,V)|0,a=a+Math.imul(y,$)|0;var we=(u+(i=i+Math.imul(d,X)|0)|0)+((8191&(n=(n=n+Math.imul(d,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(A,L),n=(n=Math.imul(A,N))+Math.imul(S,L)|0,a=Math.imul(S,N),i=i+Math.imul(v,H)|0,n=(n=n+Math.imul(v,W)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,W)|0,i=i+Math.imul(g,V)|0,n=(n=n+Math.imul(g,$)|0)+Math.imul(m,V)|0,a=a+Math.imul(m,$)|0,i=i+Math.imul(p,X)|0,n=(n=n+Math.imul(p,Y)|0)+Math.imul(y,X)|0,a=a+Math.imul(y,Y)|0;var ve=(u+(i=i+Math.imul(d,J)|0)|0)+((8191&(n=(n=n+Math.imul(d,ee)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,ee)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(P,L),n=(n=Math.imul(P,N))+Math.imul(x,L)|0,a=Math.imul(x,N),i=i+Math.imul(A,H)|0,n=(n=n+Math.imul(A,W)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,W)|0,i=i+Math.imul(v,V)|0,n=(n=n+Math.imul(v,$)|0)+Math.imul(_,V)|0,a=a+Math.imul(_,$)|0,i=i+Math.imul(g,X)|0,n=(n=n+Math.imul(g,Y)|0)+Math.imul(m,X)|0,a=a+Math.imul(m,Y)|0,i=i+Math.imul(p,J)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,ee)|0;var _e=(u+(i=i+Math.imul(d,re)|0)|0)+((8191&(n=(n=n+Math.imul(d,ie)|0)+Math.imul(f,re)|0))<<13)|0;u=((a=a+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(K,L),n=(n=Math.imul(K,N))+Math.imul(C,L)|0,a=Math.imul(C,N),i=i+Math.imul(P,H)|0,n=(n=n+Math.imul(P,W)|0)+Math.imul(x,H)|0,a=a+Math.imul(x,W)|0,i=i+Math.imul(A,V)|0,n=(n=n+Math.imul(A,$)|0)+Math.imul(S,V)|0,a=a+Math.imul(S,$)|0,i=i+Math.imul(v,X)|0,n=(n=n+Math.imul(v,Y)|0)+Math.imul(_,X)|0,a=a+Math.imul(_,Y)|0,i=i+Math.imul(g,J)|0,n=(n=n+Math.imul(g,ee)|0)+Math.imul(m,J)|0,a=a+Math.imul(m,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(y,re)|0,a=a+Math.imul(y,ie)|0;var ke=(u+(i=i+Math.imul(d,ae)|0)|0)+((8191&(n=(n=n+Math.imul(d,se)|0)+Math.imul(f,ae)|0))<<13)|0;u=((a=a+Math.imul(f,se)|0)+(n>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(U,L),n=(n=Math.imul(U,N))+Math.imul(R,L)|0,a=Math.imul(R,N),i=i+Math.imul(K,H)|0,n=(n=n+Math.imul(K,W)|0)+Math.imul(C,H)|0,a=a+Math.imul(C,W)|0,i=i+Math.imul(P,V)|0,n=(n=n+Math.imul(P,$)|0)+Math.imul(x,V)|0,a=a+Math.imul(x,$)|0,i=i+Math.imul(A,X)|0,n=(n=n+Math.imul(A,Y)|0)+Math.imul(S,X)|0,a=a+Math.imul(S,Y)|0,i=i+Math.imul(v,J)|0,n=(n=n+Math.imul(v,ee)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,ee)|0,i=i+Math.imul(g,re)|0,n=(n=n+Math.imul(g,ie)|0)+Math.imul(m,re)|0,a=a+Math.imul(m,ie)|0,i=i+Math.imul(p,ae)|0,n=(n=n+Math.imul(p,se)|0)+Math.imul(y,ae)|0,a=a+Math.imul(y,se)|0;var Ae=(u+(i=i+Math.imul(d,ce)|0)|0)+((8191&(n=(n=n+Math.imul(d,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((a=a+Math.imul(f,ue)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(B,L),n=(n=Math.imul(B,N))+Math.imul(T,L)|0,a=Math.imul(T,N),i=i+Math.imul(U,H)|0,n=(n=n+Math.imul(U,W)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,W)|0,i=i+Math.imul(K,V)|0,n=(n=n+Math.imul(K,$)|0)+Math.imul(C,V)|0,a=a+Math.imul(C,$)|0,i=i+Math.imul(P,X)|0,n=(n=n+Math.imul(P,Y)|0)+Math.imul(x,X)|0,a=a+Math.imul(x,Y)|0,i=i+Math.imul(A,J)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,ee)|0,i=i+Math.imul(v,re)|0,n=(n=n+Math.imul(v,ie)|0)+Math.imul(_,re)|0,a=a+Math.imul(_,ie)|0,i=i+Math.imul(g,ae)|0,n=(n=n+Math.imul(g,se)|0)+Math.imul(m,ae)|0,a=a+Math.imul(m,se)|0,i=i+Math.imul(p,ce)|0,n=(n=n+Math.imul(p,ue)|0)+Math.imul(y,ce)|0,a=a+Math.imul(y,ue)|0;var Se=(u+(i=i+Math.imul(d,de)|0)|0)+((8191&(n=(n=n+Math.imul(d,fe)|0)+Math.imul(f,de)|0))<<13)|0;u=((a=a+Math.imul(f,fe)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(q,L),n=(n=Math.imul(q,N))+Math.imul(F,L)|0,a=Math.imul(F,N),i=i+Math.imul(B,H)|0,n=(n=n+Math.imul(B,W)|0)+Math.imul(T,H)|0,a=a+Math.imul(T,W)|0,i=i+Math.imul(U,V)|0,n=(n=n+Math.imul(U,$)|0)+Math.imul(R,V)|0,a=a+Math.imul(R,$)|0,i=i+Math.imul(K,X)|0,n=(n=n+Math.imul(K,Y)|0)+Math.imul(C,X)|0,a=a+Math.imul(C,Y)|0,i=i+Math.imul(P,J)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(x,J)|0,a=a+Math.imul(x,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(S,re)|0,a=a+Math.imul(S,ie)|0,i=i+Math.imul(v,ae)|0,n=(n=n+Math.imul(v,se)|0)+Math.imul(_,ae)|0,a=a+Math.imul(_,se)|0,i=i+Math.imul(g,ce)|0,n=(n=n+Math.imul(g,ue)|0)+Math.imul(m,ce)|0,a=a+Math.imul(m,ue)|0,i=i+Math.imul(p,de)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(y,de)|0,a=a+Math.imul(y,fe)|0;var Ee=(u+(i=i+Math.imul(d,pe)|0)|0)+((8191&(n=(n=n+Math.imul(d,ye)|0)+Math.imul(f,pe)|0))<<13)|0;u=((a=a+Math.imul(f,ye)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(q,H),n=(n=Math.imul(q,W))+Math.imul(F,H)|0,a=Math.imul(F,W),i=i+Math.imul(B,V)|0,n=(n=n+Math.imul(B,$)|0)+Math.imul(T,V)|0,a=a+Math.imul(T,$)|0,i=i+Math.imul(U,X)|0,n=(n=n+Math.imul(U,Y)|0)+Math.imul(R,X)|0,a=a+Math.imul(R,Y)|0,i=i+Math.imul(K,J)|0,n=(n=n+Math.imul(K,ee)|0)+Math.imul(C,J)|0,a=a+Math.imul(C,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(x,re)|0,a=a+Math.imul(x,ie)|0,i=i+Math.imul(A,ae)|0,n=(n=n+Math.imul(A,se)|0)+Math.imul(S,ae)|0,a=a+Math.imul(S,se)|0,i=i+Math.imul(v,ce)|0,n=(n=n+Math.imul(v,ue)|0)+Math.imul(_,ce)|0,a=a+Math.imul(_,ue)|0,i=i+Math.imul(g,de)|0,n=(n=n+Math.imul(g,fe)|0)+Math.imul(m,de)|0,a=a+Math.imul(m,fe)|0;var Pe=(u+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ye)|0)+Math.imul(y,pe)|0))<<13)|0;u=((a=a+Math.imul(y,ye)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,V),n=(n=Math.imul(q,$))+Math.imul(F,V)|0,a=Math.imul(F,$),i=i+Math.imul(B,X)|0,n=(n=n+Math.imul(B,Y)|0)+Math.imul(T,X)|0,a=a+Math.imul(T,Y)|0,i=i+Math.imul(U,J)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,ee)|0,i=i+Math.imul(K,re)|0,n=(n=n+Math.imul(K,ie)|0)+Math.imul(C,re)|0,a=a+Math.imul(C,ie)|0,i=i+Math.imul(P,ae)|0,n=(n=n+Math.imul(P,se)|0)+Math.imul(x,ae)|0,a=a+Math.imul(x,se)|0,i=i+Math.imul(A,ce)|0,n=(n=n+Math.imul(A,ue)|0)+Math.imul(S,ce)|0,a=a+Math.imul(S,ue)|0,i=i+Math.imul(v,de)|0,n=(n=n+Math.imul(v,fe)|0)+Math.imul(_,de)|0,a=a+Math.imul(_,fe)|0;var xe=(u+(i=i+Math.imul(g,pe)|0)|0)+((8191&(n=(n=n+Math.imul(g,ye)|0)+Math.imul(m,pe)|0))<<13)|0;u=((a=a+Math.imul(m,ye)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,X),n=(n=Math.imul(q,Y))+Math.imul(F,X)|0,a=Math.imul(F,Y),i=i+Math.imul(B,J)|0,n=(n=n+Math.imul(B,ee)|0)+Math.imul(T,J)|0,a=a+Math.imul(T,ee)|0,i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(R,re)|0,a=a+Math.imul(R,ie)|0,i=i+Math.imul(K,ae)|0,n=(n=n+Math.imul(K,se)|0)+Math.imul(C,ae)|0,a=a+Math.imul(C,se)|0,i=i+Math.imul(P,ce)|0,n=(n=n+Math.imul(P,ue)|0)+Math.imul(x,ce)|0,a=a+Math.imul(x,ue)|0,i=i+Math.imul(A,de)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(S,de)|0,a=a+Math.imul(S,fe)|0;var Me=(u+(i=i+Math.imul(v,pe)|0)|0)+((8191&(n=(n=n+Math.imul(v,ye)|0)+Math.imul(_,pe)|0))<<13)|0;u=((a=a+Math.imul(_,ye)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,J),n=(n=Math.imul(q,ee))+Math.imul(F,J)|0,a=Math.imul(F,ee),i=i+Math.imul(B,re)|0,n=(n=n+Math.imul(B,ie)|0)+Math.imul(T,re)|0,a=a+Math.imul(T,ie)|0,i=i+Math.imul(U,ae)|0,n=(n=n+Math.imul(U,se)|0)+Math.imul(R,ae)|0,a=a+Math.imul(R,se)|0,i=i+Math.imul(K,ce)|0,n=(n=n+Math.imul(K,ue)|0)+Math.imul(C,ce)|0,a=a+Math.imul(C,ue)|0,i=i+Math.imul(P,de)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(x,de)|0,a=a+Math.imul(x,fe)|0;var Ke=(u+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ye)|0)+Math.imul(S,pe)|0))<<13)|0;u=((a=a+Math.imul(S,ye)|0)+(n>>>13)|0)+(Ke>>>26)|0,Ke&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(F,re)|0,a=Math.imul(F,ie),i=i+Math.imul(B,ae)|0,n=(n=n+Math.imul(B,se)|0)+Math.imul(T,ae)|0,a=a+Math.imul(T,se)|0,i=i+Math.imul(U,ce)|0,n=(n=n+Math.imul(U,ue)|0)+Math.imul(R,ce)|0,a=a+Math.imul(R,ue)|0,i=i+Math.imul(K,de)|0,n=(n=n+Math.imul(K,fe)|0)+Math.imul(C,de)|0,a=a+Math.imul(C,fe)|0;var Ce=(u+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ye)|0)+Math.imul(x,pe)|0))<<13)|0;u=((a=a+Math.imul(x,ye)|0)+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(q,ae),n=(n=Math.imul(q,se))+Math.imul(F,ae)|0,a=Math.imul(F,se),i=i+Math.imul(B,ce)|0,n=(n=n+Math.imul(B,ue)|0)+Math.imul(T,ce)|0,a=a+Math.imul(T,ue)|0,i=i+Math.imul(U,de)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(R,de)|0,a=a+Math.imul(R,fe)|0;var De=(u+(i=i+Math.imul(K,pe)|0)|0)+((8191&(n=(n=n+Math.imul(K,ye)|0)+Math.imul(C,pe)|0))<<13)|0;u=((a=a+Math.imul(C,ye)|0)+(n>>>13)|0)+(De>>>26)|0,De&=67108863,i=Math.imul(q,ce),n=(n=Math.imul(q,ue))+Math.imul(F,ce)|0,a=Math.imul(F,ue),i=i+Math.imul(B,de)|0,n=(n=n+Math.imul(B,fe)|0)+Math.imul(T,de)|0,a=a+Math.imul(T,fe)|0;var Ue=(u+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ye)|0)+Math.imul(R,pe)|0))<<13)|0;u=((a=a+Math.imul(R,ye)|0)+(n>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,i=Math.imul(q,de),n=(n=Math.imul(q,fe))+Math.imul(F,de)|0,a=Math.imul(F,fe);var Re=(u+(i=i+Math.imul(B,pe)|0)|0)+((8191&(n=(n=n+Math.imul(B,ye)|0)+Math.imul(T,pe)|0))<<13)|0;u=((a=a+Math.imul(T,ye)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Ie=(u+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ye))+Math.imul(F,pe)|0))<<13)|0;return u=((a=Math.imul(F,ye))+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,c[0]=be,c[1]=ge,c[2]=me,c[3]=we,c[4]=ve,c[5]=_e,c[6]=ke,c[7]=Ae,c[8]=Se,c[9]=Ee,c[10]=Pe,c[11]=xe,c[12]=Me,c[13]=Ke,c[14]=Ce,c[15]=De,c[16]=Ue,c[17]=Re,c[18]=Ie,0!==u&&(c[19]=u,r.length++),r};function l(e,t,r){return(new p).mulp(e,t,r)}function p(e,t){this.x=e,this.y=t}Math.imul||(f=d),n.prototype.mulTo=function(e,t){var r,i=this.length+e.length;return r=10===this.length&&10===e.length?f(this,e,t):i<63?d(this,e,t):i<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,a=0;a>>26)|0)>>>26,s&=67108863}r.words[a]=o,i=s,s=n}return 0!==i?r.words[a]=i:r.length--,r.strip()}(this,e,t):l(this,e,t),r},p.prototype.makeRBT=function(e){for(var t=Array(e),r=n.prototype._countBits(e)-1,i=0;i>=1;return i},p.prototype.permute=function(e,t,r,i,n,a){for(var s=0;s>>=1)n++;return 1<>>=13,i[2*s+1]=8191&a,a>>>=13;for(s=2*t;s>=26,t+=n/67108864|0,t+=a>>>26,this.words[i]=67108863&a}return 0!==t&&(this.words[i]=t,this.length++),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r>>n}return t}(e);if(0===t.length)return new n(1);for(var r=this,i=0;i=0);var t,i=e%26,n=(e-i)/26,a=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var a=e%26,s=Math.min((e-a)/26,this.length),o=67108863^67108863>>>a<s)for(this.length-=s,u=0;u=0&&(0!==h||u>=n);u--){var d=0|this.words[u];this.words[u]=h<<26-a|d>>>a,h=d&o}return c&&0!==h&&(c.words[c.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,i){return r(0===this.negative),this.iushrn(e,t,i)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,n=1<=0);var t=e%26,i=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[n+i]=67108863&a}for(;n>26,this.words[n+i]=67108863&a;if(0===o)return this.strip();for(r(-1===o),o=0,n=0;n>26,this.words[n]=67108863&a;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),a=e,s=0|a.words[a.length-1];0!==(r=26-this._countBits(s))&&(a=a.ushln(r),i.iushln(r),s=0|a.words[a.length-1]);var o,c=i.length-a.length;if("mod"!==t){(o=new n(null)).length=c+1,o.words=Array(o.length);for(var u=0;u=0;d--){var f=67108864*(0|i.words[a.length+d])+(0|i.words[a.length+d-1]);for(f=Math.min(f/s|0,67108863),i._ishlnsubmul(a,f,d);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(a,1,d),i.isZero()||(i.negative^=1);o&&(o.words[d]=f)}return o&&o.strip(),i.strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:o||null,mod:i}},n.prototype.divmod=function(e,t,i){return r(!e.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(a=o.div.neg()),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:a,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(a=o.div.neg()),{div:a,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t);var a,s,o},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),a=r.cmp(i);return a<0||1===n&&0===a?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},n.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,i=0,n=this.length-1;n>=0;n--)i=(t*i+(0|this.words[n]))%e;return i},n.prototype.idivn=function(e){r(e<=67108863);for(var t=0,i=this.length-1;i>=0;i--){var n=(0|this.words[i])+67108864*t;this.words[i]=n/e|0,t=n%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new n(1),s=new n(0),o=new n(0),c=new n(1),u=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++u;for(var h=i.clone(),d=t.clone();!t.isZero();){for(var f=0,l=1;0==(t.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(a.isOdd()||s.isOdd())&&(a.iadd(h),s.isub(d)),a.iushrn(1),s.iushrn(1);for(var p=0,y=1;0==(i.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(h),c.isub(d)),o.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),a.isub(o),s.isub(c)):(i.isub(t),o.isub(a),c.isub(s))}return{a:o,b:c,gcd:i.iushln(u)}},n.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a,s=new n(1),o=new n(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var u=0,h=1;0==(t.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,f=1;0==(i.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(i.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(o)):(i.isub(t),o.isub(s))}return(a=0===t.cmpn(1)?s:o).cmpn(0)<0&&a.iadd(e),a},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var a=t;t=r,r=a}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,i=(e-t)/26,n=1<>>26,o&=67108863,this.words[s]=o}return 0!==a&&(this.words[s]=a,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this.strip(),this.length>1)t=1;else{i&&(e=-e),r(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return-1===this.cmpn(e)},n.prototype.lt=function(e){return-1===this.cmp(e)},n.prototype.lten=function(e){return this.cmpn(e)<=0},n.prototype.lte=function(e){return this.cmp(e)<=0},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new _(e)},n.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function m(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function v(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function k(e){_.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}b.prototype._tmp=function(){var e=new n(null);return e.words=Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):r.strip(),r},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},i(g,b),g.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,a=s}a>>>=22,e.words[n-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},g.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new g;else if("p224"===e)t=new m;else if("p192"===e)t=new w;else{if("p25519"!==e)throw Error("Unknown prime "+e);t=new v}return y[e]=t,t},_.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},_.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},_.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},_.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},_.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},_.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},_.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},_.prototype.isqr=function(e){return this.imul(e,e.clone())},_.prototype.sqr=function(e){return this.mul(e,e)},_.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var i=this.m.add(new n(1)).iushrn(2);return this.pow(e,i)}for(var a=this.m.subn(1),s=0;!a.isZero()&&0===a.andln(1);)s++,a.iushrn(1);r(!a.isZero());var o=new n(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),h=this.m.bitLength();for(h=new n(2*h*h).toRed(this);0!==this.pow(h,u).cmp(c);)h.redIAdd(c);for(var d=this.pow(h,a),f=this.pow(e,a.addn(1).iushrn(1)),l=this.pow(e,a),p=s;0!==l.cmp(o);){for(var y=l,b=0;0!==y.cmp(o);b++)y=y.redSqr();r(b=0;i--){for(var u=t.words[i],h=c-1;h>=0;h--){var d=u>>h&1;a!==r[0]&&(a=this.sqr(a)),0!==d||0!==s?(s<<=1,s|=d,(4===++o||0===i&&0===h)&&(a=this.mul(a,r[s]),o=0,s=0)):o=0}c=26}return a},_.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},_.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new k(e)},i(k,_),k.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},k.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},k.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.iadd(this.m)),a._forceRed(this)},k.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),s=a;return a.cmp(this.m)>=0?s=a.isub(this.m):a.cmpn(0)<0&&(s=a.iadd(this.m)),s._forceRed(this)},k.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,it)})),qp=/*#__PURE__*/Object.freeze({__proto__:null,default:zp,__moduleExports:zp});class Fp{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");this.value=new zp(e)}clone(){const e=new Fp(null);return this.value.copy(e.value),e}iinc(){return this.value.iadd(new zp(1)),this}inc(){return this.clone().iinc()}idec(){return this.value.isub(new zp(1)),this}dec(){return this.clone().idec()}iadd(e){return this.value.iadd(e.value),this}add(e){return this.clone().iadd(e)}isub(e){return this.value.isub(e.value),this}sub(e){return this.clone().isub(e)}imul(e){return this.value.imul(e.value),this}mul(e){return this.clone().imul(e)}imod(e){return this.value=this.value.umod(e.value),this}mod(e){return this.clone().imod(e)}modExp(e,t){const r=t.isEven()?zp.red(t.value):zp.mont(t.value),i=this.clone();return i.value=i.value.toRed(r).redPow(e.value).fromRed(),i}modInv(e){if(!this.gcd(e).isOne())throw Error("Inverse does not exist");return new Fp(this.value.invm(e.value))}gcd(e){return new Fp(this.value.gcd(e.value))}ileftShift(e){return this.value.ishln(e.value.toNumber()),this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value.ishrn(e.value.toNumber()),this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value.eq(e.value)}lt(e){return this.value.lt(e.value)}lte(e){return this.value.lte(e.value)}gt(e){return this.value.gt(e.value)}gte(e){return this.value.gte(e.value)}isZero(){return this.value.isZero()}isOne(){return this.value.eq(new zp(1))}isNegative(){return this.value.isNeg()}isEven(){return this.value.isEven()}abs(){const e=this.clone();return e.value=e.value.abs(),e}toString(){return this.value.toString()}toNumber(){return this.value.toNumber()}getBit(e){return this.value.testn(e)?1:0}bitLength(){return this.value.bitLength()}byteLength(){return this.value.byteLength()}toUint8Array(e="be",t){return this.value.toArrayLike(Uint8Array,e,t)}}var Op,Lp=/*#__PURE__*/Object.freeze({__proto__:null,default:Fp}),Np=nt((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,s=255&n;a?r.push(a,s):r.push(s)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),jp=nt((function(e,t){var r=t;r.assert=tt,r.toArray=Np.toArray,r.zero2=Np.zero2,r.toHex=Np.toHex,r.encode=Np.encode,r.getNAF=function(e,t){for(var r=[],i=1<=0;){var a;if(n.isOdd()){var s=n.andln(i-1);a=s>(i>>1)-1?(i>>1)-s:s,n.isubn(a)}else a=0;r.push(a);for(var o=0!==n.cmpn(0)&&0===n.andln(i-1)?t+1:1,c=1;c0||t.cmpn(-n)>0;){var a,s,o,c=e.andln(3)+i&3,u=t.andln(3)+n&3;if(3===c&&(c=-1),3===u&&(u=-1),0==(1&c))a=0;else a=3!==(o=e.andln(7)+i&7)&&5!==o||2!==u?c:-c;if(r[0].push(a),0==(1&u))s=0;else s=3!==(o=t.andln(7)+n&7)&&5!==o||2!==c?u:-u;r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new zp(e,"hex","le")}})),Hp=function(e){return Op||(Op=new Wp(null)),Op.generate(e)};function Wp(e){this.rand=e}var Gp=Wp;if(Wp.prototype.generate=function(e){return this._rand(e)},Wp.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Qp=Yp;function Jp(e,t){this.curve=e,this.type=t,this.precomputed=null}Yp.prototype.point=function(){throw Error("Not implemented")},Yp.prototype.validate=function(){throw Error("Not implemented")},Yp.prototype._fixedNafMul=function(e,t){Xp(e.precomputed);var r=e._getDoubles(),i=$p(t,1),n=(1<=s;t--)o=(o<<1)+i[t];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),h=n;h>0;h--){for(s=0;s=0;o--){for(t=0;o>=0&&0===a[o];o--)t++;if(o>=0&&t++,s=s.dblp(t),o<0)break;var c=a[o];Xp(0!==c),s="affine"===e.type?c>0?s.mixedAdd(n[c-1>>1]):s.mixedAdd(n[-c-1>>1].neg()):c>0?s.add(n[c-1>>1]):s.add(n[-c-1>>1].neg())}return"affine"===e.type?s.toP():s},Yp.prototype._wnafMulAdd=function(e,t,r,i,n){for(var a=this._wnafT1,s=this._wnafT2,o=this._wnafT3,c=0,u=0;u=1;u-=2){var d=u-1,f=u;if(1===a[d]&&1===a[f]){var l=[t[d],null,null,t[f]];0===t[d].y.cmp(t[f].y)?(l[1]=t[d].add(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg())):0===t[d].y.cmp(t[f].y.redNeg())?(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].add(t[f].neg())):(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg()));var p=[-3,-1,-5,-7,0,7,5,1,3],y=Zp(r[d],r[f]);c=Math.max(y[0].length,c),o[d]=Array(c),o[f]=Array(c);for(var b=0;b=0;u--){for(var _=0;u>=0;){var k=!0;for(b=0;b=0&&_++,w=w.dblp(_),u<0)break;for(b=0;b0?A=s[b][S-1>>1]:S<0&&(A=s[b][-S-1>>1].neg()),w="affine"===A.type?w.mixedAdd(A):w.add(A))}}for(u=0;u=Math.ceil((e.bitLength()+1)/t.step)},Jp.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(a=t,s=r),i.negative&&(i=i.neg(),n=n.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a,b:s}]},ty.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),u=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(u).neg()}},ty.prototype.pointFromX=function(e,t){(e=new zp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},ty.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},ty.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,a=0;a":""},iy.prototype.isInfinity=function(){return this.inf},iy.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},iy.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),a=n.redSqr().redISub(this.x.redAdd(this.x)),s=n.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,s)},iy.prototype.getX=function(){return this.x.fromRed()},iy.prototype.getY=function(){return this.y.fromRed()},iy.prototype.mul=function(e){return e=new zp(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},iy.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},iy.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},iy.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},iy.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},iy.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},st(ny,Qp.BasePoint),ty.prototype.jpoint=function(e,t,r){return new ny(this,e,t,r)},ny.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},ny.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},ny.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=o.redSqr(),h=u.redMul(o),d=i.redMul(u),f=c.redSqr().redIAdd(h).redISub(d).redISub(d),l=c.redMul(d.redISub(f)).redISub(a.redMul(h)),p=this.z.redMul(e.z).redMul(o);return this.curve.jpoint(f,l,p)},ny.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))return 0!==o.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),u=c.redMul(s),h=r.redMul(c),d=o.redSqr().redIAdd(u).redISub(h).redISub(h),f=o.redMul(h.redISub(d)).redISub(n.redMul(u)),l=this.z.redMul(s);return this.curve.jpoint(d,f,l)},ny.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},ny.prototype.inspect=function(){return this.isInfinity()?"":""},ny.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},st(ay,Qp);var sy=ay;function oy(e,t,r){Qp.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new zp(t,16),this.z=new zp(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}ay.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),i=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===i.redSqrt().redSqr().cmp(i)},st(oy,Qp.BasePoint),ay.prototype.decodePoint=function(e,t){if(33===(e=jp.toArray(e,t)).length&&64===e[0]&&(e=e.slice(1,33).reverse()),32!==e.length)throw Error("Unknown point compression format");return this.point(e,1)},ay.prototype.point=function(e,t){return new oy(this,e,t)},ay.prototype.pointFromJSON=function(e){return oy.fromJSON(this,e)},oy.prototype.precompute=function(){},oy.prototype._encode=function(e){var t=this.curve.p.byteLength();return e?[64].concat(this.getX().toArray("le",t)):this.getX().toArray("be",t)},oy.fromJSON=function(e,t){return new oy(e,t[0],t[1]||e.one)},oy.prototype.inspect=function(){return this.isInfinity()?"":""},oy.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},oy.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),i=e.redMul(t),n=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(i,n)},oy.prototype.add=function(){throw Error("Not supported on Montgomery curve")},oy.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),i=this.x.redSub(this.z),n=e.x.redAdd(e.z),a=e.x.redSub(e.z).redMul(r),s=n.redMul(i),o=t.z.redMul(a.redAdd(s).redSqr()),c=t.x.redMul(a.redISub(s).redSqr());return this.curve.point(o,c)},oy.prototype.mul=function(e){for(var t=(e=new zp(e,16)).clone(),r=this,i=this.curve.point(null,null),n=[];0!==t.cmpn(0);t.iushrn(1))n.push(t.andln(1));for(var a=n.length-1;a>=0;a--)0===n[a]?(r=r.diffAdd(i,this),i=i.dbl()):(i=r.diffAdd(i,this),r=r.dbl());return i},oy.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},oy.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},oy.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},oy.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},oy.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var cy=jp.assert;function uy(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,Qp.call(this,"edwards",e),this.a=new zp(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new zp(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new zp(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),cy(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}st(uy,Qp);var hy=uy;function dy(e,t,r,i,n){Qp.BasePoint.call(this,e,"projective"),null===t&&null===r&&null===i?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new zp(t,16),this.y=new zp(r,16),this.z=i?new zp(i,16):this.curve.one,this.t=n&&new zp(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}uy.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},uy.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},uy.prototype.jpoint=function(e,t,r,i){return this.point(e,t,r,i)},uy.prototype.pointFromX=function(e,t){(e=new zp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=this.c2.redSub(this.a.redMul(r)),n=this.one.redSub(this.c2.redMul(this.d).redMul(r)),a=i.redMul(n.redInvm()),s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");var o=s.fromRed().isOdd();return(t&&!o||!t&&o)&&(s=s.redNeg()),this.point(e,s)},uy.prototype.pointFromY=function(e,t){(e=new zp(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=r.redSub(this.c2),n=r.redMul(this.d).redMul(this.c2).redSub(this.a),a=i.redMul(n.redInvm());if(0===a.cmp(this.zero)){if(t)throw Error("invalid point");return this.point(this.zero,e)}var s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");return s.fromRed().isOdd()!==t&&(s=s.redNeg()),this.point(s,e)},uy.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),r=e.y.redSqr(),i=t.redMul(this.a).redAdd(r),n=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(r)));return 0===i.cmp(n)},st(dy,Qp.BasePoint),uy.prototype.pointFromJSON=function(e){return dy.fromJSON(this,e)},uy.prototype.point=function(e,t,r,i){return new dy(this,e,t,r,i)},dy.fromJSON=function(e,t){return new dy(e,t[0],t[1],t[2])},dy.prototype.inspect=function(){return this.isInfinity()?"":""},dy.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},dy.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var i=this.curve._mulA(e),n=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=i.redAdd(t),s=a.redSub(r),o=i.redSub(t),c=n.redMul(s),u=a.redMul(o),h=n.redMul(o),d=s.redMul(a);return this.curve.point(c,u,d,h)},dy.prototype._projDbl=function(){var e,t,r,i=this.x.redAdd(this.y).redSqr(),n=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var s=(u=this.curve._mulA(n)).redAdd(a);if(this.zOne)e=i.redSub(n).redSub(a).redMul(s.redSub(this.curve.two)),t=s.redMul(u.redSub(a)),r=s.redSqr().redSub(s).redSub(s);else{var o=this.z.redSqr(),c=s.redSub(o).redISub(o);e=i.redSub(n).redISub(a).redMul(c),t=s.redMul(u.redSub(a)),r=s.redMul(c)}}else{var u=n.redAdd(a);o=this.curve._mulC(this.z).redSqr(),c=u.redSub(o).redSub(o);e=this.curve._mulC(i.redISub(u)).redMul(c),t=this.curve._mulC(u).redMul(n.redISub(a)),r=u.redMul(c)}return this.curve.point(e,t,r)},dy.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},dy.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),i=this.t.redMul(this.curve.dd).redMul(e.t),n=this.z.redMul(e.z.redAdd(e.z)),a=r.redSub(t),s=n.redSub(i),o=n.redAdd(i),c=r.redAdd(t),u=a.redMul(s),h=o.redMul(c),d=a.redMul(c),f=s.redMul(o);return this.curve.point(u,h,f,d)},dy.prototype._projAdd=function(e){var t,r,i=this.z.redMul(e.z),n=i.redSqr(),a=this.x.redMul(e.x),s=this.y.redMul(e.y),o=this.curve.d.redMul(a).redMul(s),c=n.redSub(o),u=n.redAdd(o),h=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(a).redISub(s),d=i.redMul(c).redMul(h);return this.curve.twisted?(t=i.redMul(u).redMul(s.redSub(this.curve._mulA(a))),r=c.redMul(u)):(t=i.redMul(u).redMul(s.redSub(a)),r=this.curve._mulC(c).redMul(u)),this.curve.point(d,t,r)},dy.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},dy.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},dy.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},dy.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},dy.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},dy.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},dy.prototype.getX=function(){return this.normalize(),this.x.fromRed()},dy.prototype.getY=function(){return this.normalize(),this.y.fromRed()},dy.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},dy.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),i=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(i),0===this.x.cmp(t))return!0}},dy.prototype.toP=dy.prototype.normalize,dy.prototype.mixedAdd=dy.prototype.add;var fy=nt((function(e,t){var r=t;r.base=Qp,r.short=ry,r.mont=sy,r.edwards=hy})),ly=yt.rotl32,py=yt.sum32,yy=yt.sum32_5,by=St.ft_1,gy=mt.BlockHash,my=[1518500249,1859775393,2400959708,3395469782];function wy(){if(!(this instanceof wy))return new wy;gy.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}yt.inherits(wy,gy);var vy=wy;wy.blockSize=512,wy.outSize=160,wy.hmacStrength=80,wy.padLength=64,wy.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;ithis.blockSize&&(e=(new this.Hash).update(e).digest()),tt(e.length<=this.blockSize);for(var t=e.length;t=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var My=xy;xy.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},xy.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=Np.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var Uy=jp.assert;function Ry(e,t){if(e instanceof Ry)return e;this._importDER(e,t)||(Uy(e.r&&e.s,"Signature without r or s"),this.r=new zp(e.r,16),this.s=new zp(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var Iy=Ry;function By(){this.place=0}function Ty(e,t){var r=e[t.place++];if(!(128&r))return r;for(var i=15&r,n=0,a=0,s=t.place;a>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}Ry.prototype._importDER=function(e,t){e=jp.toArray(e,t);var r=new By;if(48!==e[r.place++])return!1;if(Ty(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var i=Ty(e,r),n=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])return!1;var a=Ty(e,r);if(e.length!==a+r.place)return!1;var s=e.slice(r.place,a+r.place);return 0===n[0]&&128&n[1]&&(n=n.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new zp(n),this.s=new zp(s),this.recoveryParam=null,!0},Ry.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=zy(t),r=zy(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];qy(i,t.length),(i=i.concat(t)).push(2),qy(i,r.length);var n=i.concat(r),a=[48];return qy(a,n.length),a=a.concat(n),jp.encode(a,e)};var Fy=jp.assert;function Oy(e){if(!(this instanceof Oy))return new Oy(e);"string"==typeof e&&(Fy(Py.hasOwnProperty(e),"Unknown curve "+e),e=Py[e]),e instanceof Py.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var Ly=Oy;Oy.prototype.keyPair=function(e){return new Dy(this,e)},Oy.prototype.keyFromPrivate=function(e,t){return Dy.fromPrivate(this,e,t)},Oy.prototype.keyFromPublic=function(e,t){return Dy.fromPublic(this,e,t)},Oy.prototype.genKeyPair=function(e){e||(e={});var t=new My({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||Hp(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()});if("mont"===this.curve.type){var r=new zp(t.generate(32));return this.keyFromPrivate(r)}for(var i=this.n.byteLength(),n=this.n.sub(new zp(2));;){if(!((r=new zp(t.generate(i))).cmp(n)>0))return r.iaddn(1),this.keyFromPrivate(r)}},Oy.prototype._truncateToN=function(e,t,r){var i=(r=r||8*e.byteLength())-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},Oy.prototype.truncateMsg=function(e){var t;return e instanceof Uint8Array?(t=8*e.byteLength,e=this._truncateToN(new zp(e,16),!1,t)):"string"==typeof e?(t=4*e.length,e=this._truncateToN(new zp(e,16),!1,t)):e=this._truncateToN(new zp(e,16)),e},Oy.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this.truncateMsg(e);for(var n=this.n.byteLength(),a=t.getPrivate().toArray("be",n),s=e.toArray("be",n),o=new My({hash:this.hash,entropy:a,nonce:s,pers:i.pers,persEnc:i.persEnc||"utf8"}),c=this.n.sub(new zp(1)),u=0;;u++){var h=i.k?i.k(u):new zp(o.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(c)>=0)){var d=this.g.mul(h);if(!d.isInfinity()){var f=d.getX(),l=f.umod(this.n);if(0!==l.cmpn(0)){var p=h.invm(this.n).mul(l.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var y=(d.getY().isOdd()?1:0)|(0!==f.cmp(l)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),y^=1),new Iy({r:l,s:p,recoveryParam:y})}}}}}},Oy.prototype.verify=function(e,t,r,i){return r=this.keyFromPublic(r,i),t=new Iy(t,"hex"),this._verify(this.truncateMsg(e),t,r)||this._verify(this._truncateToN(new zp(e,16)),t,r)},Oy.prototype._verify=function(e,t,r){var i=t.r,n=t.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;var a,s=n.invm(this.n),o=s.mul(e).umod(this.n),c=s.mul(i).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(o,r.getPublic(),c)).isInfinity()&&a.eqXToP(i):!(a=this.g.mulAdd(o,r.getPublic(),c)).isInfinity()&&0===a.getX().umod(this.n).cmp(i)},Oy.prototype.recoverPubKey=function(e,t,r,i){Fy((3&r)===r,"The recovery param is more than two bits"),t=new Iy(t,i);var n=this.n,a=new zp(e),s=t.r,o=t.s,c=1&r,u=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw Error("Unable to find sencond key candinate");s=u?this.curve.pointFromX(s.add(this.curve.n),c):this.curve.pointFromX(s,c);var h=t.r.invm(n),d=n.sub(a).mul(h).umod(n),f=o.mul(h).umod(n);return this.g.mulAdd(d,s,f)},Oy.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new Iy(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(e,t,n)}catch(e){continue}if(a.eq(r))return n}throw Error("Unable to find valid recovery factor")};var Ny=jp.assert,jy=jp.parseBytes,Hy=jp.cachedProperty;function Wy(e,t){if(this.eddsa=e,t.hasOwnProperty("secret")&&(this._secret=jy(t.secret)),e.isPoint(t.pub))this._pub=t.pub;else if(this._pubBytes=jy(t.pub),this._pubBytes&&33===this._pubBytes.length&&64===this._pubBytes[0]&&(this._pubBytes=this._pubBytes.slice(1,33)),this._pubBytes&&32!==this._pubBytes.length)throw Error("Unknown point compression format")}Wy.fromPublic=function(e,t){return t instanceof Wy?t:new Wy(e,{pub:t})},Wy.fromSecret=function(e,t){return t instanceof Wy?t:new Wy(e,{secret:t})},Wy.prototype.secret=function(){return this._secret},Hy(Wy,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),Hy(Wy,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),Hy(Wy,"privBytes",(function(){var e=this.eddsa,t=this.hash(),r=e.encodingLength-1,i=t.slice(0,e.encodingLength);return i[0]&=248,i[r]&=127,i[r]|=64,i})),Hy(Wy,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),Hy(Wy,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),Hy(Wy,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),Wy.prototype.sign=function(e){return Ny(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},Wy.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},Wy.prototype.getSecret=function(e){return Ny(this._secret,"KeyPair is public only"),jp.encode(this.secret(),e)},Wy.prototype.getPublic=function(e,t){return jp.encode((t?[64]:[]).concat(this.pubBytes()),e)};var Gy=Wy,Vy=jp.assert,$y=jp.cachedProperty,Zy=jp.parseBytes;function Xy(e,t){this.eddsa=e,"object"!=typeof t&&(t=Zy(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),Vy(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof zp&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}$y(Xy,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),$y(Xy,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),$y(Xy,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),$y(Xy,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),Xy.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Xy.prototype.toHex=function(){return jp.encode(this.toBytes(),"hex").toUpperCase()};var Yy=Xy,Qy=jp.assert,Jy=jp.parseBytes;function eb(e){if(Qy("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof eb))return new eb(e);e=Py[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=Sy.sha512}var tb=eb;eb.prototype.sign=function(e,t){e=Jy(e);var r=this.keyFromSecret(t),i=this.hashInt(r.messagePrefix(),e),n=this.g.mul(i),a=this.encodePoint(n),s=this.hashInt(a,r.pubBytes(),e).mul(r.priv()),o=i.add(s).umod(this.curve.n);return this.makeSignature({R:n,S:o,Rencoded:a})},eb.prototype.verify=function(e,t,r){e=Jy(e),t=this.makeSignature(t);var i=this.keyFromPublic(r),n=this.hashInt(t.Rencoded(),i.pubBytes(),e),a=this.g.mul(t.S());return t.R().add(i.pub().mul(n)).eq(a)},eb.prototype.hashInt=function(){for(var e=this.hash(),t=0;t0)throw Error("Unknown option: "+r.join(", "));return new Sh(e)},e.createMessage=async function({text:e,binary:t,filename:r,date:i=new Date,format:n=(void 0!==e?"utf8":"binary"),...a}){let s=void 0!==e?e:t;if(void 0===s)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!Y.isString(e)&&!Y.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!Y.isUint8Array(t)&&!Y.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=Y.isStream(s);c&&(await P(),s=M(s));const u=new ou(i);void 0!==e?u.setText(s,Z.write(Z.literal,n)):u.setBytes(s,Z.write(Z.literal,n)),void 0!==r&&u.setFilename(r);const h=new pu;h.push(u);const d=new vh(h);return d.fromStream=c,d},e.decrypt=async function({message:e,decryptionKeys:t,passwords:r,sessionKeys:i,verificationKeys:n,expectSigned:a=!1,format:s="utf8",signature:o=null,date:c=new Date,config:u,...h}){if(Kh(u={...ae,...u}),Eh(e),n=Ch(n),t=Ch(t),r=Ch(r),i=Ch(i),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(h.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));try{const h=await e.decrypt(t,r,i,c,u);n||(n=[]);const d={};if(d.signatures=o?await h.verifyDetached(o,n,c,u):await h.verify(n,c,u),d.data="binary"===s?h.getLiteralData():h.getText(),d.filename=h.getFilename(),Uh(d,e),a){if(0===n.length)throw Error("Verification keys are required to verify message signatures");if(0===d.signatures.length)throw Error("Message is not signed");d.data=C([d.data,W((async()=>{await Y.anyPromise(d.signatures.map((e=>e.verified)))}))])}return d.data=await Dh(d.data,e.fromStream,s),d}catch(e){throw Y.wrapError("Error decrypting message",e)}},e.decryptKey=async function({privateKey:e,passphrase:t,config:r,...i}){Kh(r={...ae,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const a=e.clone(!0),s=Y.isArray(t)?t:[t];try{return await Promise.all(a.getKeys().map((e=>Y.anyPromise(s.map((t=>e.keyPacket.decrypt(t))))))),await a.validate(r),a}catch(e){throw a.clearPrivateParams(),Y.wrapError("Error decrypting private key",e)}},e.decryptSessionKeys=async function({message:e,decryptionKeys:t,passwords:r,date:i=new Date,config:n,...a}){if(Kh(n={...ae,...n}),Eh(e),t=Ch(t),r=Ch(r),a.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const s=Object.keys(a);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await e.decryptSessionKeys(t,r,i,n)}catch(e){throw Y.wrapError("Error decrypting session keys",e)}},e.encrypt=async function({message:e,encryptionKeys:t,signingKeys:r,passwords:i,sessionKey:n,format:a="armored",signature:s=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:u=[],date:h=new Date,signingUserIDs:d=[],encryptionUserIDs:f=[],signatureNotations:l=[],config:p,...y}){if(Kh(p={...ae,...p}),Eh(e),xh(a),t=Ch(t),r=Ch(r),i=Ch(i),c=Ch(c),u=Ch(u),d=Ch(d),f=Ch(f),l=Ch(l),y.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(y.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(y.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==y.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const b=Object.keys(y);if(b.length>0)throw Error("Unknown option: "+b.join(", "));r||(r=[]);const g=e.fromStream;try{if((r.length||s)&&(e=await e.sign(r,s,c,h,d,l,p)),e=e.compress(await Xu("compression",t,h,f,p),p),e=await e.encrypt(t,i,n,o,u,h,f,p),"object"===a)return e;const y="armored"===a;return Dh(y?e.armor(p):e.write(),g,y?"utf8":"binary")}catch(e){throw Y.wrapError("Error encrypting message",e)}},e.encryptKey=async function({privateKey:e,passphrase:t,config:r,...i}){Kh(r={...ae,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const a=e.clone(!0),s=a.getKeys(),o=Y.isArray(t)?t:Array(s.length).fill(t);if(o.length!==s.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(s.map((async(e,t)=>{const{keyPacket:i}=e;await i.encrypt(o[t],r),i.clearPrivateParams()}))),a}catch(e){throw a.clearPrivateParams(),Y.wrapError("Error encrypting private key",e)}},e.encryptSessionKey=async function({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:i,passwords:n,format:a="armored",wildcard:s=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:u=[],config:h,...d}){if(Kh(h={...ae,...h}),function(e,t){if(!Y.isUint8Array(e))throw Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(e),function(e,t){if(!Y.isString(e))throw Error("Parameter ["+(t||"data")+"] must be of type String")}(t,"algorithm"),xh(a),i=Ch(i),n=Ch(n),o=Ch(o),u=Ch(u),d.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const f=Object.keys(d);if(f.length>0)throw Error("Unknown option: "+f.join(", "));if(!(i&&0!==i.length||n&&0!==n.length))throw Error("No encryption keys or passwords provided.");try{return Rh(await vh.encryptSessionKey(e,t,r,i,n,s,o,c,u,h),a,h)}catch(e){throw Y.wrapError("Error encrypting session key",e)}},e.enums=Z,e.generateKey=async function({userIDs:e=[],passphrase:t,type:r="ecc",rsaBits:i=4096,curve:n="curve25519",keyExpirationTime:a=0,date:s=new Date,subkeys:o=[{}],format:c="armored",config:u,...h}){Kh(u={...ae,...u}),e=Ch(e);const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));if(0===e.length)throw Error("UserIDs are required for key generation");if("rsa"===r&&ith(e.subkeys[r],e)));let r=[Wu(e,t)];r=r.concat(e.subkeys.map((e=>Hu(e,t))));const i=await Promise.all(r),n=await bh(i[0],i.slice(1),e,t),a=await n.getRevocationCertificate(e.date,t);return n.revocationSignatures=[],{key:n,revocationCertificate:a}}(f,u);return e.getKeys().forEach((({keyPacket:e})=>ah(e,u))),{privateKey:Rh(e,c,u),publicKey:Rh(e.toPublic(),c,u),revocationCertificate:t}}catch(e){throw Y.wrapError("Error generating keypair",e)}},e.generateSessionKey=async function({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:i,...n}){if(Kh(i={...ae,...i}),e=Ch(e),r=Ch(r),n.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await vh.generateSessionKey(e,t,r,i)}catch(e){throw Y.wrapError("Error generating session key",e)}},e.readCleartextMessage=async function({cleartextMessage:e,config:t,...r}){if(t={...ae,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!Y.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const i=Object.keys(r);if(i.length>0)throw Error("Unknown option: "+i.join(", "));const n=await le(e);if(n.type!==Z.armor.signed)throw Error("No cleartext signed message.");const a=await pu.fromBinary(n.data,Ah,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let i=0;i0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await le(e,r);if(t!==Z.armor.publicKey&&t!==Z.armor.privateKey)throw Error("Armored text not of type key");a=i}else a=t;return yh(await pu.fromBinary(a,ph,r))},e.readKeys=async function({armoredKeys:e,binaryKeys:t,config:r,...i}){r={...ae,...r};let n=e||t;if(!n)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!Y.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!Y.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:t,data:i}=await le(e,r);if(t!==Z.armor.publicKey&&t!==Z.armor.privateKey)throw Error("Armored text not of type key");n=i}const s=[],o=await pu.fromBinary(n,ph,r),c=o.indexOfTag(Z.packet.publicKey,Z.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)throw Error("Unknown option: "+a.join(", "));const s=Y.isStream(n);if(s&&(await P(),n=M(n)),e){const{type:e,data:t}=await le(n,r);if(e!==Z.armor.message)throw Error("Armored text not of type message");n=t}const o=await pu.fromBinary(n,gh,r),c=new vh(o);return c.fromStream=s,c},e.readPrivateKey=async function({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...ae,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!Y.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!Y.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await le(e,r);if(t!==Z.armor.privateKey)throw Error("Armored text not of type private key");a=i}else a=t;const s=await pu.fromBinary(a,ph,r);return new lh(s)},e.readPrivateKeys=async function({armoredKeys:e,binaryKeys:t,config:r}){r={...ae,...r};let i=e||t;if(!i)throw Error("readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!Y.isString(e))throw Error("readPrivateKeys: options.armoredKeys must be a string");if(t&&!Y.isUint8Array(t))throw Error("readPrivateKeys: options.binaryKeys must be a Uint8Array");if(e){const{type:t,data:n}=await le(e,r);if(t!==Z.armor.privateKey)throw Error("Armored text not of type private key");i=n}const n=[],a=await pu.fromBinary(i,ph,r),s=a.indexOfTag(Z.packet.secretKey);if(0===s.length)throw Error("No secret key packet found");for(let e=0;e0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:e,data:t}=await le(n,r);if(e!==Z.armor.signature)throw Error("Armored text not of type signature");n=t}const s=await pu.fromBinary(n,Nu,r);return new ju(s)},e.reformatKey=async function({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:i=0,date:n,format:a="armored",config:s,...o}){Kh(s={...ae,...s}),t=Ch(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length)throw Error("UserIDs are required for key reformat");const u={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:i,date:n};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const i=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,n={key:i,bind:r},a=await Gu(e.bindingSignatures,i,Z.signature.subkeyBinding,n,null,t).catch((()=>({})));return{sign:a.keyFlags&&a.keyFlags[0]&Z.keyFlags.signData}}))));const n=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==n.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const a=await bh(i,n,e,t),s=await a.getRevocationCertificate(e.date,t);return a.revocationSignatures=[],{key:a,revocationCertificate:s};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=Y.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(u,s);return{privateKey:Rh(e,a,s),publicKey:Rh(e.toPublic(),a,s),revocationCertificate:t}}catch(e){throw Y.wrapError("Error reformatting keypair",e)}},e.revokeKey=async function({key:e,revocationCertificate:t,reasonForRevocation:r,date:i=new Date,format:n="armored",config:a,...s}){Kh(a={...ae,...a});const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const s=t?await e.applyRevocationCertificate(t,i,a):await e.revoke(r,i,a);return s.isPrivate()?{privateKey:Rh(s,n,a),publicKey:Rh(s.toPublic(),n,a)}:{privateKey:null,publicKey:Rh(s,n,a)}}catch(e){throw Y.wrapError("Error revoking key",e)}},e.sign=async function({message:e,signingKeys:t,format:r="armored",detached:i=!1,signingKeyIDs:n=[],date:a=new Date,signingUserIDs:s=[],signatureNotations:o=[],config:c,...u}){if(Kh(c={...ae,...c}),Ph(e),xh(r),t=Ch(t),n=Ch(n),s=Ch(s),o=Ch(o),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==u.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const h=Object.keys(u);if(h.length>0)throw Error("Unknown option: "+h.join(", "));if(e instanceof Sh&&"binary"===r)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Sh&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let u;if(u=i?await e.signDetached(t,void 0,n,a,s,o,c):await e.sign(t,void 0,n,a,s,o,c),"object"===r)return u;const h="armored"===r;return u=h?u.armor(c):u.write(),i&&(u=z(e.packets.write(),(async(e,t)=>{await Promise.all([R(u,t),j(e).catch((()=>{}))])}))),Dh(u,e.fromStream,h?"utf8":"binary")}catch(e){throw Y.wrapError("Error signing message",e)}},e.unarmor=le,e.verify=async function({message:e,verificationKeys:t,expectSigned:r=!1,format:i="utf8",signature:n=null,date:a=new Date,config:s,...o}){if(Kh(s={...ae,...s}),Ph(e),t=Ch(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Sh&&"binary"===i)throw Error("Can't return cleartext message data as binary");if(e instanceof Sh&&n)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=n?await e.verifyDetached(n,t,a,s):await e.verify(t,a,s),o.data="binary"===i?e.getLiteralData():e.getText(),e.fromStream&&!n&&Uh(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=C([o.data,W((async()=>{await Y.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Dh(o.data,e.fromStream,i),o}catch(e){throw Y.wrapError("Error verifying signed message",e)}},Object.defineProperty(e,"__esModule",{value:!0}),e}({}); +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +var openpgp=function(e){"use strict";const t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}const n=Symbol("doneWritingPromise"),i=Symbol("doneWritingResolve"),s=Symbol("doneWritingReject"),a=Symbol("readingIndex");class o extends Array{constructor(){super(),Object.setPrototypeOf(this,o.prototype),this[n]=new Promise(((e,t)=>{this[i]=e,this[s]=t})),this[n].catch((()=>{}))}}function c(e){return e&&e.getReader&&Array.isArray(e)}function h(e){if(!c(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}function u(e){if(c(e))return"array";if(t.ReadableStream&&t.ReadableStream.prototype.isPrototypeOf(e))return"web";if(e&&!(t.ReadableStream&&e instanceof t.ReadableStream)&&"function"==typeof e._read&&"object"==typeof e._readableState)throw Error("Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`");return!(!e||!e.getReader)&&"web-like"}function l(e){return Uint8Array.prototype.isPrototypeOf(e)}function y(e){if(1===e.length)return e[0];let t=0;for(let r=0;r(await this[n],this[a]===this.length?{value:void 0,done:!0}:{value:this[this[a]++],done:!1})}},o.prototype.readToEnd=async function(e){await this[n];const t=e(this.slice(this[a]));return this.length=0,t},o.prototype.clone=function(){const e=new o;return e[n]=this[n].then((()=>{e.push(...this)})),e},h.prototype.write=async function(e){this.stream.push(e)},h.prototype.close=async function(){this.stream[i]()},h.prototype.abort=async function(e){return this.stream[s](e),e},h.prototype.releaseLock=function(){},"object"==typeof t.process&&t.process.versions;const f=new WeakSet,g=Symbol("externalBuffer");function p(e){if(this.stream=e,e[g]&&(this[g]=e[g].slice()),c(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=()=>{})}if(u(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let t=!1;this._read=async()=>t||f.has(e)?{value:void 0,done:!0}:(t=!0,{value:e,done:!1}),this._releaseLock=()=>{if(t)try{f.add(e)}catch(e){}}}function d(e){return u(e)?e:new ReadableStream({start(t){t.enqueue(e),t.close()}})}function A(e){if(u(e))return e;const t=new o;return(async()=>{const r=Q(t);await r.write(e),await r.close()})(),t}function w(e){return e.some((e=>u(e)&&!c(e)))?function(e){e=e.map(d);const t=k((async function(e){await Promise.all(n.map((t=>D(t,e))))}));let r=Promise.resolve();const n=e.map(((n,i)=>v(n,((n,s)=>(r=r.then((()=>m(n,t.writable,{preventClose:i!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>c(e)))?function(e){const t=new o;let r=Promise.resolve();return e.forEach(((n,i)=>(r=r.then((()=>m(n,t,{preventClose:i!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):y(e)}async function m(e,t,{preventClose:r=!1,preventAbort:n=!1,preventCancel:i=!1}={}){if(u(e)&&!c(e)){e=d(e);try{if(e[g]){const r=Q(t);for(let t=0;t{t=e,r=n})),t=null,r=null)},close:n.close.bind(n),abort:n.error.bind(n)})}}function E(e,t=()=>{},r=()=>{}){if(c(e)){const n=new o;return(async()=>{const i=Q(n);try{const n=await P(e),s=t(n),a=r();let o;o=void 0!==s&&void 0!==a?w([s,a]):void 0!==s?s:a,await i.write(o),await i.close()}catch(e){await i.abort(e)}})(),n}if(u(e))return b(e,{async transform(e,r){try{const n=await t(e);void 0!==n&&r.enqueue(n)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const n=t(e),i=r();return void 0!==n&&void 0!==i?w([n,i]):void 0!==n?n:i}function v(e,t){if(u(e)&&!c(e)){let r;const n=new TransformStream({start(e){r=e}}),i=m(e,n.writable),s=k((async function(e){r.error(e),await i,await new Promise(setTimeout)}));return t(n.readable,s.writable),s.readable}e=A(e);const r=new o;return t(e,r),r}function B(e,t){let r;const n=v(e,((e,i)=>{const s=x(e);s.remainder=()=>(s.releaseLock(),m(e,i),n),r=t(s)}));return r}function I(e){if(c(e))return e.clone();if(u(e)){const t=function(e){if(c(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(u(e)){const t=d(e).tee();return t[0][g]=t[1][g]=e[g],t}return[C(e),C(e)]}(e);return K(e,t[0]),t[1]}return C(e)}function S(e){return c(e)?I(e):u(e)?new ReadableStream({start(t){const r=v(e,(async(e,r)=>{const n=x(e),i=Q(r);try{for(;;){await i.ready;const{done:e,value:r}=await n.read();if(e){try{t.close()}catch(e){}return void await i.close()}try{t.enqueue(r)}catch(e){}await i.write(r)}}catch(e){t.error(e),await i.abort(e)}}));K(e,r)}}):C(e)}function K(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,n])=>{"constructor"!==r&&(n.value?n.value=n.value.bind(t):n.get=n.get.bind(t),Object.defineProperty(e,r,n))}))}function C(e,t=0,r=1/0){if(c(e))throw Error("Not implemented");if(u(e)){if(t>=0&&r>=0){let n=0;return b(e,{transform(e,i){n=t&&i.enqueue(C(e,Math.max(t-n,0),r-n)),n+=e.length):i.terminate()}})}if(t<0&&(r<0||r===1/0)){let n=[];return E(e,(e=>{e.length>=-t?n=[e]:n.push(e)}),(()=>C(w(n),t,r)))}if(0===t&&r<0){let n;return E(e,(e=>{const i=n?w([n,e]):e;if(i.length>=-r)return n=C(i,r),C(i,t,r);n=i}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),U((async()=>C(await P(e),t,r)))}return e[g]&&(e=w(e[g].concat([e]))),l(e)?e.subarray(t,r===1/0?e.length:r):e.slice(t,r)}async function P(e,t=w){return c(e)?e.readToEnd(t):u(e)?x(e).readToEnd(t):e}async function D(e,t){if(u(e)){if(e.cancel){const r=await e.cancel(t);return await new Promise(setTimeout),r}if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function U(e){const t=new o;return(async()=>{const r=Q(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}function x(e){return new p(e)}function Q(e){return new h(e)}p.prototype.read=async function(){if(this[g]&&this[g].length){return{done:!1,value:this[g].shift()}}return this._read()},p.prototype.releaseLock=function(){this[g]&&(this.stream[g]=this[g]),this._releaseLock()},p.prototype.cancel=function(e){return this._cancel(e)},p.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:n}=await this.read();if(n+="",r)return t.length?w(t):void 0;const i=n.indexOf("\n")+1;i&&(e=w(t.concat(n.substr(0,i))),t=[]),i!==n.length&&t.push(n.substr(i))}return this.unshift(...t),e},p.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(C(t,1)),r},p.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:n,value:i}=await this.read();if(n)return t.length?w(t):void 0;if(t.push(i),r+=i.length,r>=e){const r=w(t);return this.unshift(C(r,e)),C(r,0,e)}}},p.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},p.prototype.unshift=function(...e){this[g]||(this[g]=[]),1===e.length&&l(e[0])&&this[g].length&&e[0].length&&this[g][0].byteOffset>=e[0].length?this[g][0]=new Uint8Array(this[g][0].buffer,this[g][0].byteOffset-e[0].length,this[g][0].byteLength+e[0].length):this[g].unshift(...e.filter((e=>e&&e.length)))},p.prototype.readToEnd=async function(e=w){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};const R=Symbol("byValue");var L={curve:{nistP256:"nistP256",p256:"nistP256",nistP384:"nistP384",p384:"nistP384",nistP521:"nistP521",p521:"nistP521",secp256k1:"secp256k1",ed25519Legacy:"ed25519Legacy",ed25519:"ed25519Legacy",curve25519Legacy:"curve25519Legacy",curve25519:"curve25519Legacy",brainpoolP256r1:"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,argon2:4,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11,sha3_256:12,sha3_512:14},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,gcm:3,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20,padding:21},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuerKeyID:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34,preferredCipherSuites:39},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4,seipdv2:8},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[R]||(e[R]=[],Object.entries(e).forEach((([t,r])=>{e[R][r]=t}))),void 0!==e[R][t])return e[R][t];throw Error("Invalid enum value.")}},T={preferredHashAlgorithm:L.hash.sha512,preferredSymmetricAlgorithm:L.symmetric.aes256,preferredCompressionAlgorithm:L.compression.uncompressed,aeadProtect:!1,parseAEADEncryptedV4KeysAsLegacy:!1,preferredAEADAlgorithm:L.aead.gcm,aeadChunkSizeByte:12,v6Keys:!1,enableParsingV5Entities:!1,s2kType:L.s2k.iterated,s2kIterationCountByte:224,s2kArgon2Params:{passes:3,parallelism:4,memoryExponent:16},allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,minRSABits:2047,passwordCollisionCheck:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,allowMissingKeyFlags:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([L.symmetric.aes128,L.symmetric.aes192,L.symmetric.aes256]),ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 6.0.0",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],nonDeterministicSignaturesViaNotation:!0,useEllipticFallback:!0,rejectHashAlgorithms:new Set([L.hash.md5,L.hash.ripemd]),rejectMessageHashAlgorithms:new Set([L.hash.md5,L.hash.ripemd,L.hash.sha1]),rejectPublicKeyAlgorithms:new Set([L.publicKey.elgamal,L.publicKey.dsa]),rejectCurves:new Set([L.curve.secp256k1])};const M=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),N={isString:function(e){return"string"==typeof e||e instanceof String},nodeRequire:()=>{},isArray:function(e){return e instanceof Array},isUint8Array:l,isStream:u,getNobleCurve:async(e,t)=>{if(!T.useEllipticFallback)throw Error("This curve is only supported in the full build of OpenPGP.js");const{nobleCurves:r}=await Promise.resolve().then((function(){return Vu}));switch(e){case L.publicKey.ecdh:case L.publicKey.ecdsa:{const e=r.get(t);if(!e)throw Error("Unsupported curve");return e}case L.publicKey.x448:return r.get("x448");case L.publicKey.ed448:return r.get("ed448");default:throw Error("Unsupported curve")}},readNumber:function(e){let t=0;for(let r=0;r>8*(t-n-1)&255;return r},readDate:function(e){const t=N.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return N.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return N.readExactSubarray(e,2,2+t)},readExactSubarray:function(e,t,r){if(e.lengtht)throw Error("Input array too long");const r=new Uint8Array(t),n=t-e.length;return r.set(e,n),r},uint8ArrayToMPI:function(e){const t=N.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),n=new Uint8Array([(65280&t)>>8,255&t]);return N.concatUint8Array([n,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t="0123456789abcdef";let r="";return e.forEach((e=>{r+=t[e>>4]+t[15&e]})),r},stringToUint8Array:function(e){return E(e,(e=>{if(!N.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return E(e,r,(()=>r(new Uint8Array,!0)))},concat:w,concatUint8Array:y,equalsUint8Array:function(e,t){if(!N.isUint8Array(e)||!N.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let n=0;n>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){const e=void 0!==t&&t.crypto&&t.crypto.subtle||this.getNodeCrypto()?.webcrypto.subtle;if(!e)throw Error("The WebCrypto API is not available");return e},getNodeCrypto:function(){return this.nodeRequire("crypto")},getNodeZlib:function(){return this.nodeRequire("zlib")},getNodeBuffer:function(){return(this.nodeRequire("buffer")||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return this.nodeRequire("os").cpus().length},isEmailAddress:function(e){if(!N.isString(e))return!1;return/^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u.test(e)},canonicalizeEOL:function(e){let t=!1;return E(e,(e=>{let r;t&&(e=N.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const n=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&n.push(r);if(!n.length)return e;const i=new Uint8Array(e.length+n.length);let s=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return E(e,(e=>{let r;13===(e=t&&10!==e[0]?N.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let n=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const i=r-(10===e[r]?1:0);t&&e.copyWithin(n,t,i),n+=i-t}return e.subarray(0,n)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let n;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){n=e}}))),r(n)}))},selectUint8Array:function(e,t,r){const n=Math.max(t.length,r.length),i=new Uint8Array(n);let s=0;for(let n=0;n{t=N.concatUint8Array([t,e]);const r=[],n=Math.floor(t.length/45),i=45*n,s=H(t.subarray(0,i));for(let e=0;et.length?H(t)+"\n":""))}function _(e){let t="";return E(e,(e=>{t+=e;let r=0;const n=[" ","\t","\r","\n"];for(let e=0;e0&&(i-r)%4!=0;i--)n.includes(t[i])&&r--;const s=O(t.substr(0,i));return t=t.substr(i),s}),(()=>O(t)))}function G(e){return _(e.replace(/-/g,"+").replace(/_/g,"/"))}function j(e,t){let r=z(e).replace(/[\r\n]/g,"");return r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,""),r}function q(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?L.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?L.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?L.armor.signed:/MESSAGE/.test(t[1])?L.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?L.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?L.armor.privateKey:/SIGNATURE/.test(t[1])?L.armor.signature:void 0}function V(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function J(e){const t=function(e){let t=13501623;return E(e,(e=>{const r=W?Math.floor(e.length/4):0,n=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^Y[1][t>>16&255]^Y[2][t>>8&255]^Y[3][255&t];for(let n=4*r;n>8^Y[0][255&t^e[n]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e);return z(t)}F?(H=e=>F.from(e).toString("base64"),O=e=>{const t=F.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(H=e=>btoa(N.uint8ArrayToString(e)),O=e=>N.stringToUint8Array(atob(e)));const Y=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(8388608&t?8801531:0);Y[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)Y[1][e]=Y[0][e]>>8^Y[0][255&Y[0][e]];for(let e=0;e<=255;e++)Y[2][e]=Y[1][e]>>8^Y[0][255&Y[1][e]];for(let e=0;e<=255;e++)Y[3][e]=Y[2][e]>>8^Y[0][255&Y[2][e]];const W=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function Z(e){for(let t=0;t=0&&r!==e.length-1&&(t=e.slice(0,r)),t}function X(e){return new Promise((async(t,r)=>{try{const n=/^-----[^-]+-----$/m,i=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const a=[];let o,c,h=a,u=[];const l=_(v(e,(async(e,y)=>{const f=x(e);try{for(;;){let e=await f.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=N.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(o)c||s!==L.armor.signed||(n.test(e)?(u=u.join("\r\n"),c=!0,Z(h),h=[],o=!1):u.push(e.replace(/^- /,"")));else if(n.test(e)&&r(Error("Mandatory blank line missing between armor headers and armor data")),i.test(e)){if(Z(h),o=!0,c||s!==L.armor.signed){t({text:u,data:l,headers:a,type:s});break}}else h.push(e);else n.test(e)&&(s=q(e))}}catch(e){return void r(e)}const g=Q(y);try{for(;;){await g.ready;const{done:e,value:t}=await f.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await f.readToEnd();e.length||(e=""),e=r+e,e=N.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=$(t[0].slice(0,-1));await g.write(i);break}await g.write(r)}await g.ready,await g.close()}catch(e){await g.abort(e)}})))}catch(e){r(e)}})).then((async e=>(c(e.data)&&(e.data=await P(e.data)),e)))}function ee(e,t,r,n,i,s=!1,a=T){let o,c;e===L.armor.signed&&(o=t.text,c=t.hash,t=t.data);const h=s&&S(t),u=[];switch(e){case L.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+n+"-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP MESSAGE, PART "+r+"/"+n+"-----\n");break;case L.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case L.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push(c?`Hash: ${c}\n\n`:"\n"),u.push(o.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP SIGNATURE-----\n");break;case L.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP MESSAGE-----\n");break;case L.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case L.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case L.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(V(i,a)),u.push(z(t)),h&&u.push("=",J(h)),u.push("-----END PGP SIGNATURE-----\n")}return N.concat(u)}async function te(e){switch(e){case L.symmetric.aes128:case L.symmetric.aes192:case L.symmetric.aes256:throw Error("Not a legacy cipher");case L.symmetric.cast5:case L.symmetric.blowfish:case L.symmetric.twofish:case L.symmetric.tripledes:{const{legacyCiphers:t}=await Promise.resolve().then((function(){return cl})),r=t.get(e);if(!r)throw Error("Unsupported cipher algorithm");return r}default:throw Error("Unsupported cipher algorithm")}}function re(e){switch(e){case L.symmetric.aes128:case L.symmetric.aes192:case L.symmetric.aes256:case L.symmetric.twofish:return 16;case L.symmetric.blowfish:case L.symmetric.cast5:case L.symmetric.tripledes:return 8;default:throw Error("Unsupported cipher")}}function ne(e){switch(e){case L.symmetric.aes128:case L.symmetric.blowfish:case L.symmetric.cast5:return 16;case L.symmetric.aes192:case L.symmetric.tripledes:return 24;case L.symmetric.aes256:case L.symmetric.twofish:return 32;default:throw Error("Unsupported cipher")}}function ie(e){return{keySize:ne(e),blockSize:re(e)}}var se=/*#__PURE__*/Object.freeze({__proto__:null,getCipherParams:ie,getLegacyCipher:te});function ae(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r=ce(r,n,i,s,t[0],7,-680876936),s=ce(s,r,n,i,t[1],12,-389564586),i=ce(i,s,r,n,t[2],17,606105819),n=ce(n,i,s,r,t[3],22,-1044525330),r=ce(r,n,i,s,t[4],7,-176418897),s=ce(s,r,n,i,t[5],12,1200080426),i=ce(i,s,r,n,t[6],17,-1473231341),n=ce(n,i,s,r,t[7],22,-45705983),r=ce(r,n,i,s,t[8],7,1770035416),s=ce(s,r,n,i,t[9],12,-1958414417),i=ce(i,s,r,n,t[10],17,-42063),n=ce(n,i,s,r,t[11],22,-1990404162),r=ce(r,n,i,s,t[12],7,1804603682),s=ce(s,r,n,i,t[13],12,-40341101),i=ce(i,s,r,n,t[14],17,-1502002290),n=ce(n,i,s,r,t[15],22,1236535329),r=he(r,n,i,s,t[1],5,-165796510),s=he(s,r,n,i,t[6],9,-1069501632),i=he(i,s,r,n,t[11],14,643717713),n=he(n,i,s,r,t[0],20,-373897302),r=he(r,n,i,s,t[5],5,-701558691),s=he(s,r,n,i,t[10],9,38016083),i=he(i,s,r,n,t[15],14,-660478335),n=he(n,i,s,r,t[4],20,-405537848),r=he(r,n,i,s,t[9],5,568446438),s=he(s,r,n,i,t[14],9,-1019803690),i=he(i,s,r,n,t[3],14,-187363961),n=he(n,i,s,r,t[8],20,1163531501),r=he(r,n,i,s,t[13],5,-1444681467),s=he(s,r,n,i,t[2],9,-51403784),i=he(i,s,r,n,t[7],14,1735328473),n=he(n,i,s,r,t[12],20,-1926607734),r=ue(r,n,i,s,t[5],4,-378558),s=ue(s,r,n,i,t[8],11,-2022574463),i=ue(i,s,r,n,t[11],16,1839030562),n=ue(n,i,s,r,t[14],23,-35309556),r=ue(r,n,i,s,t[1],4,-1530992060),s=ue(s,r,n,i,t[4],11,1272893353),i=ue(i,s,r,n,t[7],16,-155497632),n=ue(n,i,s,r,t[10],23,-1094730640),r=ue(r,n,i,s,t[13],4,681279174),s=ue(s,r,n,i,t[0],11,-358537222),i=ue(i,s,r,n,t[3],16,-722521979),n=ue(n,i,s,r,t[6],23,76029189),r=ue(r,n,i,s,t[9],4,-640364487),s=ue(s,r,n,i,t[12],11,-421815835),i=ue(i,s,r,n,t[15],16,530742520),n=ue(n,i,s,r,t[2],23,-995338651),r=le(r,n,i,s,t[0],6,-198630844),s=le(s,r,n,i,t[7],10,1126891415),i=le(i,s,r,n,t[14],15,-1416354905),n=le(n,i,s,r,t[5],21,-57434055),r=le(r,n,i,s,t[12],6,1700485571),s=le(s,r,n,i,t[3],10,-1894986606),i=le(i,s,r,n,t[10],15,-1051523),n=le(n,i,s,r,t[1],21,-2054922799),r=le(r,n,i,s,t[8],6,1873313359),s=le(s,r,n,i,t[15],10,-30611744),i=le(i,s,r,n,t[6],15,-1560198380),n=le(n,i,s,r,t[13],21,1309151649),r=le(r,n,i,s,t[4],6,-145523070),s=le(s,r,n,i,t[11],10,-1120210379),i=le(i,s,r,n,t[2],15,718787259),n=le(n,i,s,r,t[9],21,-343485551),e[0]=pe(r,e[0]),e[1]=pe(n,e[1]),e[2]=pe(i,e[2]),e[3]=pe(s,e[3])}function oe(e,t,r,n,i,s){return t=pe(pe(t,e),pe(n,s)),pe(t<>>32-i,r)}function ce(e,t,r,n,i,s,a){return oe(t&r|~t&n,e,t,i,s,a)}function he(e,t,r,n,i,s,a){return oe(t&n|r&~n,e,t,i,s,a)}function ue(e,t,r,n,i,s,a){return oe(t^r^n,e,t,i,s,a)}function le(e,t,r,n,i,s,a){return oe(r^(t|~n),e,t,i,s,a)}function ye(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const fe="0123456789abcdef".split("");function ge(e){let t="",r=0;for(;r<4;r++)t+=fe[e>>8*r+4&15]+fe[e>>8*r&15];return t}function pe(e,t){return e+t&4294967295}const de=N.getWebCrypto(),Ae=N.getNodeCrypto(),we=Ae&&Ae.getHashes();function me(e){if(Ae&&we.includes(e))return async function(t){const r=Ae.createHash(e);return E(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function be(e,t){const r=async()=>{const{nobleHashes:t}=await Promise.resolve().then((function(){return Kl})),r=t.get(e);if(!r)throw Error("Unsupported hash");return r};return async function(e){if(c(e)&&(e=await P(e)),N.isStream(e)){const t=(await r()).create();return E(e,(e=>{t.update(e)}),(()=>t.digest()))}if(de&&t)return new Uint8Array(await de.digest(t,e));return(await r())(e)}}var ke={md5:me("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let n;for(n=64;n<=e.length;n+=64)ae(r,ye(e.substring(n-64,n)));e=e.substring(n-64);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(ae(r,i),n=0;n<16;n++)i[n]=0;return i[14]=8*t,ae(r,i),r}(N.uint8ArrayToString(e));return N.hexToUint8Array(function(e){for(let t=0;t0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Be(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Ie(e,t){ve(e);const r=t.outputLen;if(e.lengthnew Uint8Array(e.buffer,e.byteOffset,e.byteLength),Ke=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ce=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw Error("Non little-endian hardware is not supported");function Pe(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Ee(e))throw Error("Uint8Array expected, got "+typeof e);e=Re(e)}return e}function De(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t);function xe(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s);e.setUint32(t+0,a,n),e.setUint32(t+4,o,n)}function Qe(e){return e.byteOffset%4==0}function Re(e){return Uint8Array.from(e)}function Le(...e){for(let t=0;t(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class He{constructor(e,t){this.blockLen=Te,this.outputLen=Te,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,ve(e=Pe(e),16);const r=Ce(e);let n=r.getUint32(0,!1),i=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:Fe(n),s1:Fe(i),s2:Fe(s),s3:Fe(a)}),({s0:n,s1:i,s2:s,s3:a}={s3:(u=s)<<31|(l=a)>>>1,s2:(h=i)<<31|u>>>1,s1:(c=n)<<31|h>>>1,s0:c>>>1^225<<24&-(1&l)});var c,h,u,l;const y=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(y))throw Error(`ghash: wrong window size=${y}, should be 2, 4 or 8`);this.W=y;const f=128/y,g=this.windowSize=2**y,p=[];for(let e=0;e>>y-a-1&1))continue;const{s0:c,s1:h,s2:u,s3:l}=o[y*e+a];r^=c,n^=h,i^=u,s^=l}p.push({s0:r,s1:n,s2:i,s3:s})}this.t=p}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:i,t:s,windowSize:a}=this;let o=0,c=0,h=0,u=0;const l=(1<>>8*e&255;for(let e=8/i-1;e>=0;e--){const r=t>>>i*e&l,{s0:n,s1:f,s2:g,s3:p}=s[y*a+r];o^=n,c^=f,h^=g,u^=p,y+=1}}this.s0=o,this.s1=c,this.s2=h,this.s3=u}update(e){e=Pe(e),Be(this);const t=Ke(e),r=Math.floor(e.length/Te),n=e.length%Te;for(let e=0;e>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Re(e=Pe(e)));super(r,t),Le(r)}update(e){e=Pe(e),Be(this);const t=Ke(e),r=e.length%Te,n=Math.floor(e.length/Te);for(let e=0;ee(r,t.length).update(Pe(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const _e=ze(((e,t)=>new He(e,t)));ze(((e,t)=>new Oe(e,t)));const Ge=16,je=new Uint8Array(Ge),qe=283;function Ve(e){return e<<1^qe&-(e>>7)}function Je(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Ve(e);return r}const Ye=/* @__PURE__ */(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Ve(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Le(e),t})(),We=/* @__PURE__ */Ye.map(((e,t)=>Ye.indexOf(t))),Ze=e=>e<<24|e>>>8,$e=e=>e<<8|e>>>24,Xe=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function et(e,t){if(256!==e.length)throw Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,n)=>t(e[n]))),n=r.map($e),i=n.map($e),s=i.map($e),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let h=0;h<256;h++){const u=256*t+h;a[u]=r[t]^n[h],o[u]=i[t]^s[h],c[u]=e[t]<<8|e[h]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:i,T3:s,T01:a,T23:o}}const tt=/* @__PURE__ */et(Ye,(e=>Je(e,3)<<24|e<<16|e<<8|Je(e,2))),rt=/* @__PURE__ */et(We,(e=>Je(e,11)<<24|Je(e,13)<<16|Je(e,9)<<8|Je(e,14))),nt=/* @__PURE__ */(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Ve(r))e[t]=r;return e})();function it(e){ve(e);const t=e.length;if(![16,24,32].includes(t))throw Error("aes: wrong key size: should be 16, 24 or 32, got: "+t);const{sbox2:r}=tt,n=[];Qe(e)||n.push(e=Re(e));const i=Ke(e),s=i.length,a=e=>ot(r,e,e,e,e),o=new Uint32Array(t+28);o.set(i);for(let e=s;e6&&e%s==4&&(t=a(t)),o[e]=o[e-s]^t}return Le(...n),o}function st(e){const t=it(e),r=t.slice(),n=t.length,{sbox2:i}=tt,{T0:s,T1:a,T2:o,T3:c}=rt;for(let e=0;e>>8&255]^o[n>>>16&255]^c[n>>>24]}return r}function at(e,t,r,n,i,s){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|s>>>24&255]}function ot(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function ct(e,t,r,n,i){const{sbox2:s,T01:a,T23:o}=tt;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],i^=e[c++];const h=e.length/4-2;for(let s=0;s=0;e--)r=r+(255&s[e])|0,s[e]=255&r,r>>>=8;({s0:o,s1:c,s2:h,s3:u}=ct(e,a[0],a[1],a[2],a[3]))}const f=Ge*Math.floor(l.length/4);if(f>>0,o.setUint32(u,y,t),({s0:f,s1:g,s2:p,s3:d}=ct(e,a[0],a[1],a[2],a[3]));const A=Ge*Math.floor(c.length/4);if(Ar(e,t),decrypt:(e,t)=>r(e,t)}}));const gt=Ue({blockSize:16,nonceLength:16},(function(e,t,r={}){ve(e),ve(t,16);const n=!r.disablePadding;return{encrypt(r,i){const s=it(e),{b:a,o,out:c}=function(e,t,r){ve(e);let n=e.length;const i=n%Ge;if(!t&&0!==i)throw Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Qe(e)||(e=Re(e));const s=Ke(e);if(t){let e=Ge-i;e||(e=Ge),n+=e}const a=ut(n,r);return{b:s,o:Ke(a),out:a}}(r,n,i);let h=t;const u=[s];Qe(h)||u.push(h=Re(h));const l=Ke(h);let y=l[0],f=l[1],g=l[2],p=l[3],d=0;for(;d+4<=a.length;)y^=a[d+0],f^=a[d+1],g^=a[d+2],p^=a[d+3],({s0:y,s1:f,s2:g,s3:p}=ct(s,y,f,g,p)),o[d++]=y,o[d++]=f,o[d++]=g,o[d++]=p;if(n){const e=function(e){const t=new Uint8Array(16),r=Ke(t);t.set(e);const n=Ge-e.length;for(let e=Ge-n;e16)throw Error("aes/pcks5: wrong padding");const i=e.subarray(0,-n);for(let t=0;tr(e,!0,t),decrypt:(e,t)=>r(e,!1,t)}}));const dt=Ue({blockSize:16,nonceLength:12,tagLength:16},(function(e,t,r){if(ve(e),ve(t),void 0!==r&&ve(r),t.length<8)throw Error("aes/gcm: invalid nonce length");const n=16;function i(e,t,n){const i=function(e,t,r,n,i){const s=null==i?0:i.length,a=e.create(r,n.length+s);i&&a.update(i),a.update(n);const o=new Uint8Array(16),c=Ce(o);i&&xe(c,0,BigInt(8*s),t),xe(c,8,BigInt(8*n.length),t),a.update(o);const h=a.digest();return Le(o),h}(_e,!1,e,n,r);for(let e=0;e=2**32)throw Error("plaintext should be less than 4gb");const r=it(e);if(16===t.length)wt(r,t);else{const e=Ke(t);let n=e[0],i=e[1];for(let t=0,s=1;t<6;t++)for(let t=2;t=2**32)throw Error("ciphertext should be less than 4gb");const r=st(e),n=t.length/8-1;if(1===n)mt(r,t);else{const e=Ke(t);let i=e[0],s=e[1];for(let t=0,a=6*n;t<6;t++)for(let t=2*n;t>=1;t-=2,a--){s^=Xe(a);const{s0:n,s1:o,s2:c,s3:h}=ht(r,i,s,e[t],e[t+1]);i=n,s=o,e[t]=c,e[t+1]=h}e[0]=i,e[1]=s}r.fill(0)}},kt=new Uint8Array(8).fill(166),Et=Ue({blockSize:8},(e=>({encrypt(t){if(ve(t),!t.length||t.length%8!=0)throw Error("invalid plaintext length");if(8===t.length)throw Error("8-byte keys not allowed in AESKW, use AESKWP instead");const r=function(...e){let t=0;for(let r=0;r!0),(()=>!1))}async _runCBC(e,t){const r="AES-CBC";this.keyRef=this.keyRef||await Bt.importKey("raw",this.key,r,!1,["encrypt"]);const n=await Bt.encrypt({name:r,iv:t||this.zeroBlock},this.keyRef,e);return new Uint8Array(n).subarray(0,e.length)}async encryptChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=N.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=N.concatUint8Array([this.prevBlock,n.subarray(0,n.length-this.blockSize)]),s=await this._runCBC(i);return Dt(s,n),this.prevBlock=s.slice(-this.blockSize),r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,s}let n;if(this.i+=r.length,this.i===this.nextBlock.length){const t=this.nextBlock;n=await this._runCBC(this.prevBlock),Dt(n,t),this.prevBlock=n.slice(),this.i=0;const i=e.subarray(r.length);this.nextBlock.set(i,this.i),this.i+=i.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{this.nextBlock=this.nextBlock.subarray(0,this.i);const t=this.nextBlock,r=await this._runCBC(this.prevBlock);Dt(r,t),e=r.subarray(0,t.length)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.keyRef=null,this.key=null}async encrypt(e){const t=(await this._runCBC(N.concatUint8Array([new Uint8Array(this.blockSize),e]),this.iv)).subarray(0,e.length);return Dt(t,e),this.clearSensitiveData(),t}}class Pt{constructor(e,t,r,n){this.forEncryption=e;const{blockSize:i}=ie(t);this.key=vt.expandKeyLE(r),n.byteOffset%4!=0&&(n=n.slice()),this.prevBlock=Ut(n),this.nextBlock=new Uint8Array(i),this.i=0,this.blockSize=i}_runCFB(e){const t=Ut(e),r=new Uint8Array(e.length),n=Ut(r);for(let e=0;e+4<=n.length;e+=4){const{s0:r,s1:i,s2:s,s3:a}=vt.encrypt(this.key,this.prevBlock[0],this.prevBlock[1],this.prevBlock[2],this.prevBlock[3]);n[e+0]=t[e+0]^r,n[e+1]=t[e+1]^i,n[e+2]=t[e+2]^s,n[e+3]=t[e+3]^a,this.prevBlock=(this.forEncryption?n:t).slice(e,e+4)}return r}async processChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=N.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=this._runCFB(n);return r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,i}let n;if(this.i+=r.length,this.i===this.nextBlock.length){n=this._runCFB(this.nextBlock),this.i=0;const t=e.subarray(r.length);this.nextBlock.set(t,this.i),this.i+=t.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{e=this._runCFB(this.nextBlock).subarray(0,this.i)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.key.fill(0)}}function Dt(e,t){const r=Math.min(e.length,t.length);for(let n=0;nnew Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));var xt=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n){const i=L.read(L.symmetric,e);if(It&&Kt[i])return function(e,t,r,n){const i=L.read(L.symmetric,e),s=new It.createDecipheriv(Kt[i],t,n);return E(r,(e=>new Uint8Array(s.update(e))))}(e,t,r,n);if(N.isAES(e))return async function(e,t,r,n){if(N.isStream(r)){const i=new Pt(!1,e,t,n);return E(r,(e=>i.processChunk(e)),(()=>i.finish()))}return pt(t,n).decrypt(r)}(e,t,r,n);const s=new(await te(e))(t),a=s.blockSize;let o=n,c=new Uint8Array;const h=e=>{e&&(c=N.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,n=0;for(;e?c.length>=a:c.length;){const e=s.encrypt(o);for(o=c.subarray(0,a),r=0;rnew Uint8Array(s.update(e))))}(e,t,r,n);if(N.isAES(e))return async function(e,t,r,n){if(Bt&&await Ct.isSupported(e)){const i=new Ct(e,t,n);return N.isStream(r)?E(r,(e=>i.encryptChunk(e)),(()=>i.finish())):i.encrypt(r)}if(N.isStream(r)){const i=new Pt(!0,e,t,n);return E(r,(e=>i.processChunk(e)),(()=>i.finish()))}return pt(t,n).encrypt(r)}(e,t,r,n);const a=new(await te(e))(t),o=a.blockSize,c=n.slice();let h=new Uint8Array;const u=e=>{e&&(h=N.concatUint8Array([h,e]));const t=new Uint8Array(h.length);let r,n=0;for(;e?h.length>=o:h.length;){const e=a.encrypt(c);for(r=0;ri.encrypt(e),a=e=>i.decrypt(e);let o;function c(e,t,r,i){const a=t.length/$t|0;!function(e,t){const r=N.nbits(Math.max(e.length,t.length)/$t|0)-1;for(let e=n+1;e<=r;e++)o[e]=N.double(o[e-1]);n=r}(t,i);const c=N.concatUint8Array([nr.subarray(0,15-r.length),ir,r]),h=63&c[15];c[15]&=192;const u=s(c),l=N.concatUint8Array([u,rr(u.subarray(0,8),u.subarray(1,9))]),y=N.shiftRight(l.subarray(0+(h>>3),17+(h>>3)),8-(7&h)).subarray(1),f=new Uint8Array($t),g=new Uint8Array(t.length+Xt);let p,d=0;for(p=0;p{r+=t[e>>4]+t[15&e]})),BigInt("0x0"+r)}function dr(e,t){const r=e%t;return rfr;){const e=n&gr;n>>=gr;s=e?s*i%r:s,i=i*i%r}return s}function wr(e){return e>=fr?e:-e}function mr(e,t){const{gcd:r,x:n}=function(e,t){let r=BigInt(0),n=BigInt(1),i=BigInt(1),s=BigInt(0),a=wr(e),o=wr(t);const c=eNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return t}function kr(e,t){return(e>>BigInt(t)&gr)===fr?0:1}function Er(e){const t=e>=gr)!==t;)r++;return r}function vr(e){const t=e>=r)!==t;)n++;return n}function Br(e,t="be",r){let n=e.toString(16);n.length%2==1&&(n="0"+n);const i=n.length/2,s=new Uint8Array(r||i),a=r?r-i:0;let o=0;for(;oe&&(a=dr(a,i<dr(e,r)!==t))}(e)&&(!!function(e,t=BigInt(2)){return Ar(t,e-Pr,e)===Pr}(e)&&!!function(e,t){const r=Er(e);t||(t=Math.max(1,r/48|0));const n=e-Pr;let i=0;for(;!kr(n,i);)i++;const s=e>>BigInt(i);for(;t>0;t--){let t,r=Ar(Kr(BigInt(2),n),s,e);if(r!==Pr&&r!==n){for(t=1;tBigInt(e)));const Qr=[];function Rr(e,t){const r=e.length;if(r>t-11)throw Error("Message too long");const n=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!n;if(t)return N.selectUint8Array(a,s,t);if(a)return s;throw Error("Decryption error")}function Tr(e,t,r){let n;if(t.length!==ke.getHashByteLength(e))throw Error("Invalid hash length");const i=new Uint8Array(Qr[e].length);for(n=0;n=t)throw Error("Data too large.");const c=dr(n,s-Hr),h=dr(n,i-Hr),u=Kr(BigInt(2),t),l=Ar(mr(u,t),r,t);e=dr(e*l,t);const y=Ar(e,h,i),f=Ar(e,c,s),g=dr(a*(f-y),s);let p=g*i+y;return p=dr(p*u,t),Lr(Br(p,"be",vr(t)),o)}(e,t,r,n,i,s,a,o)},encrypt:async function(e,t,r){return N.getNodeCrypto()?async function(e,t,r){const n=zr(t,r),i={key:n,format:"jwk",type:"pkcs1",padding:Fr.constants.RSA_PKCS1_PADDING};return new Uint8Array(Fr.publicEncrypt(i,e))}(e,t,r):async function(e,t,r){if(t=pr(t),e=pr(Rr(e,vr(t))),r=pr(r),e>=t)throw Error("Message size cannot exceed modulus size");return Br(Ar(e,r,t),"be",vr(t))}(e,t,r)},generate:async function(e,t){if(t=BigInt(t),N.getWebCrypto()){const r={name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Br(t),hash:{name:"SHA-1"}},n=await Nr.generateKey(r,!0,["sign","verify"]);return _r(await Nr.exportKey("jwk",n.privateKey),t)}if(N.getNodeCrypto()){const r={modulusLength:e,publicExponent:br(t),publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}},n=await new Promise(((e,t)=>{Fr.generateKeyPair("rsa",r,((r,n,i)=>{r?t(r):e(i)}))}));return _r(n,t)}let r,n,i;do{n=Dr(e-(e>>1),t,40),r=Dr(e>>1,t,40),i=r*n}while(Er(i)!==e);const s=(r-Hr)*(n-Hr);return n=r.length)throw Error("Digest size cannot exceed key modulus size");if(t&&!N.isStream(t))if(N.getWebCrypto())try{return await async function(e,t,r,n,i,s,a,o){const c=await Or(r,n,i,s,a,o),h={name:"RSASSA-PKCS1-v1_5",hash:{name:e}},u=await Nr.importKey("jwk",c,h,!1,["sign"]);return new Uint8Array(await Nr.sign("RSASSA-PKCS1-v1_5",u,t))}(L.read(L.webHash,e),t,r,n,i,s,a,o)}catch(e){N.printDebugError(e)}else if(N.getNodeCrypto())return async function(e,t,r,n,i,s,a,o){const c=Fr.createSign(L.read(L.hash,e));c.write(t),c.end();const h=await Or(r,n,i,s,a,o);return new Uint8Array(c.sign({key:h,format:"jwk",type:"pkcs1"}))}(e,t,r,n,i,s,a,o);return async function(e,t,r,n){t=pr(t);const i=pr(Tr(e,n,vr(t)));return r=pr(r),Br(Ar(i,r,t),"be",vr(t))}(e,r,i,c)},validateParams:async function(e,t,r,n,i,s){if(e=pr(e),(n=pr(n))*(i=pr(i))!==e)return!1;const a=BigInt(2);if(dr(n*(s=pr(s)),i)!==BigInt(1))return!1;t=pr(t),r=pr(r);const o=Kr(a,a<=r)throw Error("Signature size cannot exceed modulus size");const s=Br(Ar(t,n,r),"be",vr(r)),a=Tr(e,i,vr(r));return N.equalsUint8Array(s,a)}(e,r,n,i,s)}});const jr=BigInt(1);var qr=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i){return e=pr(e),t=pr(t),r=pr(r),Lr(Br(dr(mr(Ar(e,n=pr(n),r),r)*t,r),"be",vr(r)),i)},encrypt:async function(e,t,r,n){t=pr(t),r=pr(r),n=pr(n);const i=pr(Rr(e,vr(t))),s=Kr(jr,t-jr);return{c1:Br(Ar(r,s,t)),c2:Br(dr(Ar(n,s,t)*i,t))}},validateParams:async function(e,t,r,n){if(e=pr(e),t=pr(t),r=pr(r),t<=jr||t>=e)return!1;const i=BigInt(Er(e));if(i>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function cn(e,t,r,n){return function(e,t,r,n,i){var s,a=0;for(s=0;s>>8)-1}(e,t,r,n,32)}function hn(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function un(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function ln(e,t,r){for(var n,i=~(r-1),s=0;s<16;s++)n=i&(e[s]^t[s]),e[s]^=n,t[s]^=n}function yn(e,t){var r,n,i,s=Yr(),a=Yr();for(r=0;r<16;r++)a[r]=t[r];for(un(a),un(a),un(a),n=0;n<2;n++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,ln(a,s,1-i)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function fn(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return yn(r,e),yn(n,t),cn(r,0,n,0)}function gn(e){var t=new Uint8Array(32);return yn(t,e),1&t[0]}function pn(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function dn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function An(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function wn(e,t,r){var n,i,s=0,a=0,o=0,c=0,h=0,u=0,l=0,y=0,f=0,g=0,p=0,d=0,A=0,w=0,m=0,b=0,k=0,E=0,v=0,B=0,I=0,S=0,K=0,C=0,P=0,D=0,U=0,x=0,Q=0,R=0,L=0,T=r[0],M=r[1],N=r[2],F=r[3],H=r[4],O=r[5],z=r[6],_=r[7],G=r[8],j=r[9],q=r[10],V=r[11],J=r[12],Y=r[13],W=r[14],Z=r[15];s+=(n=t[0])*T,a+=n*M,o+=n*N,c+=n*F,h+=n*H,u+=n*O,l+=n*z,y+=n*_,f+=n*G,g+=n*j,p+=n*q,d+=n*V,A+=n*J,w+=n*Y,m+=n*W,b+=n*Z,a+=(n=t[1])*T,o+=n*M,c+=n*N,h+=n*F,u+=n*H,l+=n*O,y+=n*z,f+=n*_,g+=n*G,p+=n*j,d+=n*q,A+=n*V,w+=n*J,m+=n*Y,b+=n*W,k+=n*Z,o+=(n=t[2])*T,c+=n*M,h+=n*N,u+=n*F,l+=n*H,y+=n*O,f+=n*z,g+=n*_,p+=n*G,d+=n*j,A+=n*q,w+=n*V,m+=n*J,b+=n*Y,k+=n*W,E+=n*Z,c+=(n=t[3])*T,h+=n*M,u+=n*N,l+=n*F,y+=n*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y,D+=n*W,U+=n*Z,A+=(n=t[12])*T,w+=n*M,m+=n*N,b+=n*F,k+=n*H,E+=n*O,v+=n*z,B+=n*_,I+=n*G,S+=n*j,K+=n*q,C+=n*V,P+=n*J,D+=n*Y,U+=n*W,x+=n*Z,w+=(n=t[13])*T,m+=n*M,b+=n*N,k+=n*F,E+=n*H,v+=n*O,B+=n*z,I+=n*_,S+=n*G,K+=n*j,C+=n*q,P+=n*V,D+=n*J,U+=n*Y,x+=n*W,Q+=n*Z,m+=(n=t[14])*T,b+=n*M,k+=n*N,E+=n*F,v+=n*H,B+=n*O,I+=n*z,S+=n*_,K+=n*G,C+=n*j,P+=n*q,D+=n*V,U+=n*J,x+=n*Y,Q+=n*W,R+=n*Z,b+=(n=t[15])*T,a+=38*(E+=n*N),o+=38*(v+=n*F),c+=38*(B+=n*H),h+=38*(I+=n*O),u+=38*(S+=n*z),l+=38*(K+=n*_),y+=38*(C+=n*G),f+=38*(P+=n*j),g+=38*(D+=n*q),p+=38*(U+=n*V),d+=38*(x+=n*J),A+=38*(Q+=n*Y),w+=38*(R+=n*W),m+=38*(L+=n*Z),s=(n=(s+=38*(k+=n*M))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=(s+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=c,e[4]=h,e[5]=u,e[6]=l,e[7]=y,e[8]=f,e[9]=g,e[10]=p,e[11]=d,e[12]=A,e[13]=w,e[14]=m,e[15]=b}function mn(e,t){wn(e,t,t)}function bn(e,t){var r,n=Yr();for(r=0;r<16;r++)n[r]=t[r];for(r=253;r>=0;r--)mn(n,n),2!==r&&4!==r&&wn(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}function kn(e,t,r){var n,i,s=new Uint8Array(32),a=new Float64Array(80),o=Yr(),c=Yr(),h=Yr(),u=Yr(),l=Yr(),y=Yr();for(i=0;i<31;i++)s[i]=t[i];for(s[31]=127&t[31]|64,s[0]&=248,pn(a,r),i=0;i<16;i++)c[i]=a[i],u[i]=o[i]=h[i]=0;for(o[0]=u[0]=1,i=254;i>=0;--i)ln(o,c,n=s[i>>>3]>>>(7&i)&1),ln(h,u,n),dn(l,o,h),An(o,o,h),dn(h,c,u),An(c,c,u),mn(u,l),mn(y,o),wn(o,h,o),wn(h,c,l),dn(l,o,h),An(o,o,h),mn(c,o),An(h,u,y),wn(o,h,en),dn(o,o,u),wn(h,h,o),wn(o,u,y),wn(u,c,a),mn(c,l),ln(o,c,n),ln(h,u,n);for(i=0;i<16;i++)a[i+16]=o[i],a[i+32]=h[i],a[i+48]=c[i],a[i+64]=u[i];var f=a.subarray(32),g=a.subarray(16);return bn(f,f),wn(g,g,f),yn(e,g),0}function En(e,t){return kn(e,t,Zr)}var vn=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Bn(e,t,r,n){for(var i,s,a,o,c,h,u,l,y,f,g,p,d,A,w,m,b,k,E,v,B,I,S,K,C,P,D=new Int32Array(16),U=new Int32Array(16),x=e[0],Q=e[1],R=e[2],L=e[3],T=e[4],M=e[5],N=e[6],F=e[7],H=t[0],O=t[1],z=t[2],_=t[3],G=t[4],j=t[5],q=t[6],V=t[7],J=0;n>=128;){for(E=0;E<16;E++)v=8*E+J,D[E]=r[v+0]<<24|r[v+1]<<16|r[v+2]<<8|r[v+3],U[E]=r[v+4]<<24|r[v+5]<<16|r[v+6]<<8|r[v+7];for(E=0;E<80;E++)if(i=x,s=Q,a=R,o=L,c=T,h=M,u=N,F,y=H,f=O,g=z,p=_,d=G,A=j,w=q,V,S=65535&(I=V),K=I>>>16,C=65535&(B=F),P=B>>>16,S+=65535&(I=(G>>>14|T<<18)^(G>>>18|T<<14)^(T>>>9|G<<23)),K+=I>>>16,C+=65535&(B=(T>>>14|G<<18)^(T>>>18|G<<14)^(G>>>9|T<<23)),P+=B>>>16,S+=65535&(I=G&j^~G&q),K+=I>>>16,C+=65535&(B=T&M^~T&N),P+=B>>>16,B=vn[2*E],S+=65535&(I=vn[2*E+1]),K+=I>>>16,C+=65535&B,P+=B>>>16,B=D[E%16],K+=(I=U[E%16])>>>16,C+=65535&B,P+=B>>>16,C+=(K+=(S+=65535&I)>>>16)>>>16,S=65535&(I=k=65535&S|K<<16),K=I>>>16,C=65535&(B=b=65535&C|(P+=C>>>16)<<16),P=B>>>16,S+=65535&(I=(H>>>28|x<<4)^(x>>>2|H<<30)^(x>>>7|H<<25)),K+=I>>>16,C+=65535&(B=(x>>>28|H<<4)^(H>>>2|x<<30)^(H>>>7|x<<25)),P+=B>>>16,K+=(I=H&O^H&z^O&z)>>>16,C+=65535&(B=x&Q^x&R^Q&R),P+=B>>>16,l=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(P+=C>>>16)<<16,m=65535&S|K<<16,S=65535&(I=p),K=I>>>16,C=65535&(B=o),P=B>>>16,K+=(I=k)>>>16,C+=65535&(B=b),P+=B>>>16,Q=i,R=s,L=a,T=o=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(P+=C>>>16)<<16,M=c,N=h,F=u,x=l,O=y,z=f,_=g,G=p=65535&S|K<<16,j=d,q=A,V=w,H=m,E%16==15)for(v=0;v<16;v++)B=D[v],S=65535&(I=U[v]),K=I>>>16,C=65535&B,P=B>>>16,B=D[(v+9)%16],S+=65535&(I=U[(v+9)%16]),K+=I>>>16,C+=65535&B,P+=B>>>16,b=D[(v+1)%16],S+=65535&(I=((k=U[(v+1)%16])>>>1|b<<31)^(k>>>8|b<<24)^(k>>>7|b<<25)),K+=I>>>16,C+=65535&(B=(b>>>1|k<<31)^(b>>>8|k<<24)^b>>>7),P+=B>>>16,b=D[(v+14)%16],K+=(I=((k=U[(v+14)%16])>>>19|b<<13)^(b>>>29|k<<3)^(k>>>6|b<<26))>>>16,C+=65535&(B=(b>>>19|k<<13)^(k>>>29|b<<3)^b>>>6),P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,D[v]=65535&C|P<<16,U[v]=65535&S|K<<16;S=65535&(I=H),K=I>>>16,C=65535&(B=x),P=B>>>16,B=e[0],K+=(I=t[0])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[0]=x=65535&C|P<<16,t[0]=H=65535&S|K<<16,S=65535&(I=O),K=I>>>16,C=65535&(B=Q),P=B>>>16,B=e[1],K+=(I=t[1])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[1]=Q=65535&C|P<<16,t[1]=O=65535&S|K<<16,S=65535&(I=z),K=I>>>16,C=65535&(B=R),P=B>>>16,B=e[2],K+=(I=t[2])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[2]=R=65535&C|P<<16,t[2]=z=65535&S|K<<16,S=65535&(I=_),K=I>>>16,C=65535&(B=L),P=B>>>16,B=e[3],K+=(I=t[3])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[3]=L=65535&C|P<<16,t[3]=_=65535&S|K<<16,S=65535&(I=G),K=I>>>16,C=65535&(B=T),P=B>>>16,B=e[4],K+=(I=t[4])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[4]=T=65535&C|P<<16,t[4]=G=65535&S|K<<16,S=65535&(I=j),K=I>>>16,C=65535&(B=M),P=B>>>16,B=e[5],K+=(I=t[5])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[5]=M=65535&C|P<<16,t[5]=j=65535&S|K<<16,S=65535&(I=q),K=I>>>16,C=65535&(B=N),P=B>>>16,B=e[6],K+=(I=t[6])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[6]=N=65535&C|P<<16,t[6]=q=65535&S|K<<16,S=65535&(I=V),K=I>>>16,C=65535&(B=F),P=B>>>16,B=e[7],K+=(I=t[7])>>>16,C+=65535&B,P+=B>>>16,P+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[7]=F=65535&C|P<<16,t[7]=V=65535&S|K<<16,J+=128,n-=128}return n}function In(e,t,r){var n,i=new Int32Array(8),s=new Int32Array(8),a=new Uint8Array(256),o=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,Bn(i,s,t,r),r%=128,n=0;n=0;--i)Kn(e,t,n=r[i/8|0]>>(7&i)&1),Sn(t,e),Sn(e,e),Kn(e,t,n)}function Dn(e,t){var r=[Yr(),Yr(),Yr(),Yr()];hn(r[0],nn),hn(r[1],sn),hn(r[2],Xr),wn(r[3],nn,sn),Pn(e,r,t)}function Un(e,t,r){var n,i=new Uint8Array(64),s=[Yr(),Yr(),Yr(),Yr()];for(r||Wr(t,32),In(i,t,32),i[0]&=248,i[31]&=127,i[31]|=64,Dn(s,i),Cn(e,s),n=0;n<32;n++)t[n+32]=e[n];return 0}var xn=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Qn(e,t){var r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*xn[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*xn[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function Rn(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;Qn(e,r)}function Ln(e,t){var r=Yr(),n=Yr(),i=Yr(),s=Yr(),a=Yr(),o=Yr(),c=Yr();return hn(e[2],Xr),pn(e[1],t),mn(i,e[1]),wn(s,i,tn),An(i,i,e[2]),dn(s,e[2],s),mn(a,s),mn(o,a),wn(c,o,a),wn(r,c,i),wn(r,r,s),function(e,t){var r,n=Yr();for(r=0;r<16;r++)n[r]=t[r];for(r=250;r>=0;r--)mn(n,n),1!==r&&wn(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}(r,r),wn(r,r,i),wn(r,r,s),wn(r,r,s),wn(e[0],r,s),mn(n,e[0]),wn(n,n,s),fn(n,i)&&wn(e[0],e[0],an),mn(n,e[0]),wn(n,n,s),fn(n,i)?-1:(gn(e[0])===t[31]>>7&&An(e[0],$r,e[0]),wn(e[3],e[0],e[1]),0)}var Tn=64;function Mn(){for(var e=0;e=0},Jr.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return Un(e,t),{publicKey:e,secretKey:t}},Jr.sign.keyPair.fromSecretKey=function(e){if(Mn(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;r=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return N.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return N.uint8ArrayToHex(this.oid)}getName(){const e=Nn[this.toHex()];if(!e)throw Error("Unknown curve object identifier.");return e}}function Hn(e){let t,r=0;const n=e[0];return n<192?([r]=e,t=1):n<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===n&&(r=N.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function On(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):N.concatUint8Array([new Uint8Array([255]),N.writeNumber(e,4)])}function zn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function _n(e){return new Uint8Array([192|e])}function Gn(e,t){return N.concatUint8Array([_n(e),On(t)])}function jn(e){return[L.packet.literalData,L.packet.compressedData,L.packet.symmetricallyEncryptedData,L.packet.symEncryptedIntegrityProtectedData,L.packet.aeadEncryptedData].includes(e)}async function qn(e,t){const r=x(e);let n,i;try{const s=await r.peekBytes(2);if(!s||s.length<2||!(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const a=await r.readByte();let c,h,u=-1,l=-1;l=0,64&a&&(l=1),l?u=63&a:(u=(63&a)>>2,h=3&a);const y=jn(u);let f,g=null;if(y){if("array"===N.isStream(e)){const e=new o;n=Q(e),g=e}else{const e=new TransformStream;n=Q(e.writable),g=e.readable}i=t({tag:u,packet:g})}else g=[];do{if(l){const e=await r.readByte();if(f=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),f=!0,!y)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(h){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){n&&await n.ready;const{done:t,value:i}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const s=c===1/0?i:i.subarray(0,c-e);if(n?await n.write(s):g.push(s),e+=i.length,e>=c){r.unshift(i.subarray(c-e+i.length));break}}}}while(f);const p=await r.peekBytes(y?1/0:2);return n?(await n.ready,await n.close()):(g=N.concatUint8Array(g),await t({tag:u,packet:g})),!p||!p.length}catch(e){if(n)return await n.abort(e),!0;throw e}finally{n&&await i,r.releaseLock()}}class Vn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Vn),this.name="UnsupportedError"}}class Jn extends Vn{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,Vn),this.name="UnknownPacketError"}}class Yn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}async function Wn(e){switch(e){case L.publicKey.ed25519:try{const e=N.getWebCrypto(),t=await e.generateKey("Ed25519",!0,["sign","verify"]),r=await e.exportKey("jwk",t.privateKey),n=await e.exportKey("jwk",t.publicKey);return{A:new Uint8Array(G(n.x)),seed:G(r.d)}}catch(t){if("NotSupportedError"!==t.name&&"OperationError"!==t.name)throw t;const r=Sr(Xn(e)),{publicKey:n}=Jr.sign.keyPair.fromSeed(r);return{A:n,seed:r}}case L.publicKey.ed448:{const e=await N.getNobleCurve(L.publicKey.ed448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),seed:t}}default:throw Error("Unsupported EdDSA algorithm")}}async function Zn(e,t,r,n,i,s){if(ke.getHashByteLength(t){if(e===L.publicKey.ed25519){return{kty:"OKP",crv:"Ed25519",x:j(t),ext:!0}}throw Error("Unsupported EdDSA algorithm")},ri=(e,t,r)=>{if(e===L.publicKey.ed25519){const n=ti(e,t);return n.d=j(r),n}throw Error("Unsupported EdDSA algorithm")};var ni=/*#__PURE__*/Object.freeze({__proto__:null,generate:Wn,getPayloadSize:Xn,getPreferredHashAlgo:ei,sign:Zn,validateParams:async function(e,t,r){switch(e){case L.publicKey.ed25519:{const{publicKey:e}=Jr.sign.keyPair.fromSeed(r);return N.equalsUint8Array(t,e)}case L.publicKey.ed448:{const e=(await N.getNobleCurve(L.publicKey.ed448)).getPublicKey(r);return N.equalsUint8Array(t,e)}default:return!1}},verify:$n});const ii=N.getWebCrypto();async function si(e,t,r){const{keySize:n}=ie(e);if(!N.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");try{const e=await ii.importKey("raw",t,{name:"AES-KW"},!1,["wrapKey"]),n=await ii.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!0,["sign"]),i=await ii.wrapKey("raw",n,e,{name:"AES-KW"});return new Uint8Array(i)}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;N.printDebugError("Browser did not support operation: "+e.message)}return Et(t).encrypt(r)}async function ai(e,t,r){const{keySize:n}=ie(e);if(!N.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");let i;try{i=await ii.importKey("raw",t,{name:"AES-KW"},!1,["unwrapKey"])}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;return N.printDebugError("Browser did not support operation: "+e.message),Et(t).decrypt(r)}try{const e=await ii.unwrapKey("raw",r,i,{name:"AES-KW"},{name:"HMAC",hash:"SHA-256"},!0,["sign"]);return new Uint8Array(await ii.exportKey("raw",e))}catch(e){if("OperationError"===e.name)throw Error("Key Data Integrity failed");throw e}}var oi=/*#__PURE__*/Object.freeze({__proto__:null,unwrap:ai,wrap:si});const ci=N.getWebCrypto();async function hi(e,t,r,n,i){const s=L.read(L.webHash,e);if(!s)throw Error("Hash algo not supported with HKDF");const a=await ci.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await ci.deriveBits({name:"HKDF",hash:s,salt:r,info:n},a,8*i);return new Uint8Array(o)}const ui={x25519:N.encodeUTF8("OpenPGP X25519"),x448:N.encodeUTF8("OpenPGP X448")};async function li(e){switch(e){case L.publicKey.x25519:{const e=Sr(32),{publicKey:t}=Jr.box.keyPair.fromSecretKey(e);return{A:t,k:e}}case L.publicKey.x448:{const e=await N.getNobleCurve(L.publicKey.x448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),k:t}}default:throw Error("Unsupported ECDH algorithm")}}function yi(e){switch(e){case L.publicKey.x25519:return 32;case L.publicKey.x448:return 56;default:throw Error("Unsupported ECDH algorithm")}}async function fi(e,t){switch(e){case L.publicKey.x25519:{const r=Sr(yi(e)),n=Jr.scalarMult(r,t);pi(n);const{publicKey:i}=Jr.box.keyPair.fromSecretKey(r);return{ephemeralPublicKey:i,sharedSecret:n}}case L.publicKey.x448:{const e=await N.getNobleCurve(L.publicKey.x448),r=e.utils.randomPrivateKey(),n=e.getSharedSecret(r,t);pi(n);return{ephemeralPublicKey:e.getPublicKey(r),sharedSecret:n}}default:throw Error("Unsupported ECDH algorithm")}}async function gi(e,t,r,n){switch(e){case L.publicKey.x25519:{const e=Jr.scalarMult(n,t);return pi(e),e}case L.publicKey.x448:{const e=(await N.getNobleCurve(L.publicKey.x448)).getSharedSecret(n,t);return pi(e),e}default:throw Error("Unsupported ECDH algorithm")}}function pi(e){let t=0;for(let r=0;r0===s[0]&&Ri(a,r,s.subarray(1),i);if(n&&!N.isStream(n))switch(a.type){case"web":try{const e=await async function(e,t,{r,s:n},i,s){const a=Ci(e.payloadSize,mi[e.name],s),o=await Di.importKey("jwk",a,{name:"ECDSA",namedCurve:mi[e.name],hash:{name:L.read(L.webHash,e.hash)}},!1,["verify"]),c=N.concatUint8Array([r,n]).buffer;return Di.verify({name:"ECDSA",namedCurve:mi[e.name],hash:{name:L.read(L.webHash,t)}},o,c,i)}(a,t,r,n,i);return e||o()}catch(e){if("nistP521"!==a.name&&("DataError"===e.name||"OperationError"===e.name))throw e;N.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":{const e=await async function(e,t,{r,s:n},i,s){const a=N.nodeRequire("eckey-utils"),o=N.getNodeBuffer(),{publicKey:c}=a.generateDer({curveName:ki[e.name],publicKey:o.from(s)}),h=Ui.createVerify(L.read(L.hash,t));h.write(i),h.end();const u=N.concatUint8Array([r,n]);try{return h.verify({key:c,format:"der",type:"spki",dsaEncoding:"ieee-p1363"},u)}catch(e){return!1}}(a,t,r,n,i);return e||o()}}return await Ri(a,r,s,i)||o()}async function Ri(e,t,r,n){return(await N.getNobleCurve(L.publicKey.ecdsa,e.name)).verify(N.concatUint8Array([t.r,t.s]),r,n,{lowS:!1})}var Li=/*#__PURE__*/Object.freeze({__proto__:null,sign:xi,validateParams:async function(e,t,r){const n=new vi(e);if(n.keyType!==L.publicKey.ecdsa)return!1;switch(n.type){case"web":case"node":{const n=Sr(8),i=L.hash.sha256,s=await ke.digest(i,n);try{const a=await xi(e,i,n,t,r,s);return await Qi(e,i,a,n,t,s)}catch(e){return!1}}default:return Bi(L.publicKey.ecdsa,e,t,r)}},verify:Qi});var Ti=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){if(Ii(new vi(e),n),ke.getHashByteLength(t)0){const r=e[t-1];if(r>=1){const n=e.subarray(t-r),i=new Uint8Array(r).fill(r);if(N.equalsUint8Array(n,i))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Fi=/*#__PURE__*/Object.freeze({__proto__:null,decode:Ni,encode:Mi});const Hi=N.getWebCrypto(),Oi=N.getNodeCrypto();function zi(e,t,r,n){return N.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),N.stringToUint8Array("Anonymous Sender "),n])}async function _i(e,t,r,n,i=!1,s=!1){let a;if(i){for(a=0;a=0&&0===t[a];a--);t=t.subarray(0,a+1)}return(await ke.digest(e,N.concatUint8Array([new Uint8Array([0,0,0,1]),t,n]))).subarray(0,r)}async function Gi(e,t){switch(e.type){case"curve25519Legacy":{const{sharedSecret:r,ephemeralPublicKey:n}=await fi(L.publicKey.x25519,t.subarray(1));return{publicKey:N.concatUint8Array([new Uint8Array([e.wireFormatLeadingByte]),n]),sharedKey:r}}case"web":if(e.web&&N.getWebCrypto())try{return await async function(e,t){const r=Ci(e.payloadSize,e.web,t);let n=Hi.generateKey({name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]),i=Hi.importKey("jwk",r,{name:"ECDH",namedCurve:e.web},!1,[]);[n,i]=await Promise.all([n,i]);let s=Hi.deriveBits({name:"ECDH",namedCurve:e.web,public:i},n.privateKey,e.sharedSize),a=Hi.exportKey("jwk",n.publicKey);[s,a]=await Promise.all([s,a]);const o=new Uint8Array(s),c=new Uint8Array(Ki(a,e.wireFormatLeadingByte));return{publicKey:c,sharedKey:o}}(e,t)}catch(r){return N.printDebugError(r),Vi(e,t)}break;case"node":return async function(e,t){const r=Oi.createECDH(e.node);r.generateKeys();const n=new Uint8Array(r.computeSecret(t)),i=new Uint8Array(r.getPublicKey());return{publicKey:i,sharedKey:n}}(e,t);default:return Vi(e,t)}}async function ji(e,t,r,n){if(n.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(n,e.payloadSize-n.length),n=t}switch(e.type){case"curve25519Legacy":{const e=n.slice().reverse();return{secretKey:e,sharedKey:await gi(L.publicKey.x25519,t.subarray(1),r.subarray(1),e)}}case"web":if(e.web&&N.getWebCrypto())try{return await async function(e,t,r,n){const i=Pi(e.payloadSize,e.web,r,n);let s=Hi.importKey("jwk",i,{name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]);const a=Ci(e.payloadSize,e.web,t);let o=Hi.importKey("jwk",a,{name:"ECDH",namedCurve:e.web},!0,[]);[s,o]=await Promise.all([s,o]);let c=Hi.deriveBits({name:"ECDH",namedCurve:e.web,public:o},s,e.sharedSize),h=Hi.exportKey("jwk",s);[c,h]=await Promise.all([c,h]);const u=new Uint8Array(c);return{secretKey:G(h.d),sharedKey:u}}(e,t,r,n)}catch(r){return N.printDebugError(r),qi(e,t,n)}break;case"node":return async function(e,t,r){const n=Oi.createECDH(e.node);n.setPrivateKey(r);const i=new Uint8Array(n.computeSecret(t));return{secretKey:new Uint8Array(n.getPrivateKey()),sharedKey:i}}(e,t,n);default:return qi(e,t,n)}}async function qi(e,t,r){return{secretKey:r,sharedKey:(await N.getNobleCurve(L.publicKey.ecdh,e.name)).getSharedSecret(r,t).subarray(1)}}async function Vi(e,t){const r=await N.getNobleCurve(L.publicKey.ecdh,e.name),{publicKey:n,privateKey:i}=await e.genKeyPair();return{publicKey:n,sharedKey:r.getSharedSecret(i,t).subarray(1)}}var Ji=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i,s,a){const o=new vi(e);Ii(o,i),Ii(o,r);const{sharedKey:c}=await ji(o,r,i,s),h=zi(L.publicKey.ecdh,e,t,a),{keySize:u}=ie(t.cipher);let l;for(let e=0;e<3;e++)try{const r=await _i(t.hash,c,u,h,1===e,2===e);return Ni(await ai(t.cipher,r,n))}catch(e){l=e}throw l},encrypt:async function(e,t,r,n,i){const s=Mi(r),a=new vi(e);Ii(a,n);const{publicKey:o,sharedKey:c}=await Gi(a,n),h=zi(L.publicKey.ecdh,e,t,i),{keySize:u}=ie(t.cipher),l=await _i(t.hash,c,u,h);return{publicKey:o,wrappedKey:await si(t.cipher,l,s)}},validateParams:async function(e,t,r){return Bi(L.publicKey.ecdh,e,t,r)}}),Yi=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:vi,ecdh:Ji,ecdhX:di,ecdsa:Li,eddsa:ni,eddsaLegacy:Ti,generate:async function(e){const t=new vi(e),{oid:r,hash:n,cipher:i}=t,s=await t.genKeyPair();return{oid:r,Q:s.publicKey,secret:N.leftPad(s.privateKey,t.payloadSize),hash:n,cipher:i}},getPreferredHashAlgo:function(e){return Ei[e.getName()].hash}});const Wi=BigInt(0),Zi=BigInt(1);var $i=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){const a=BigInt(0);let o,c,h,u;n=pr(n),i=pr(i),r=pr(r),s=pr(s),r=dr(r,n),s=dr(s,i);const l=dr(pr(t.subarray(0,vr(i))),i);for(;;){if(o=Kr(Zi,i),c=dr(Ar(r,o,n),i),c===a)continue;const e=dr(s*c,i);if(u=dr(l+e,i),h=dr(mr(o,i)*u,i),h!==a)break}return{r:Br(c,"be",vr(n)),s:Br(h,"be",vr(n))}},validateParams:async function(e,t,r,n,i){if(e=pr(e),t=pr(t),r=pr(r),n=pr(n),r<=Zi||r>=e)return!1;if(dr(e-Zi,t)!==Wi)return!1;if(Ar(r,t,e)!==Zi)return!1;const s=BigInt(Er(t));if(s=a||r<=Wi||r>=a)return N.printDebug("invalid DSA Signature"),!1;const c=dr(pr(n.subarray(0,vr(a))),a),h=mr(r,a);if(h===Wi)return N.printDebug("invalid DSA Signature"),!1;i=dr(i,s),o=dr(o,s);const u=dr(c*h,a),l=dr(t*h,a);return dr(dr(Ar(i,u,s)*Ar(o,l,s),s),a)===t}}),Xi={rsa:Gr,elgamal:qr,elliptic:Yi,dsa:$i};var es=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:case L.publicKey.rsaSign:{const e=N.readMPI(t.subarray(r));return r+=e.length+2,{read:r,signatureParams:{s:e}}}case L.publicKey.dsa:case L.publicKey.ecdsa:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=N.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case L.publicKey.eddsaLegacy:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=N.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case L.publicKey.ed25519:case L.publicKey.ed448:{const n=2*Xi.elliptic.eddsa.getPayloadSize(e),i=N.readExactSubarray(t,r,r+n);return r+=i.length,{read:r,signatureParams:{RS:i}}}default:throw new Vn("Unknown signature algorithm.")}},sign:async function(e,t,r,n,i,s){if(!r||!n)throw Error("Missing key parameters");switch(e){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:case L.publicKey.rsaSign:{const{n:e,e:a}=r,{d:o,p:c,q:h,u}=n;return{s:await Xi.rsa.sign(t,i,e,a,o,c,h,u,s)}}case L.publicKey.dsa:{const{g:e,p:i,q:a}=r,{x:o}=n;return Xi.dsa.sign(t,s,e,i,a,o)}case L.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case L.publicKey.ecdsa:{const{oid:e,Q:a}=r,{d:o}=n;return Xi.elliptic.ecdsa.sign(e,t,i,a,o,s)}case L.publicKey.eddsaLegacy:{const{oid:e,Q:a}=r,{seed:o}=n;return Xi.elliptic.eddsaLegacy.sign(e,t,i,a,o,s)}case L.publicKey.ed25519:case L.publicKey.ed448:{const{A:a}=r,{seed:o}=n;return Xi.elliptic.eddsa.sign(e,t,i,a,o,s)}default:throw Error("Unknown signature algorithm.")}},verify:async function(e,t,r,n,i,s){switch(e){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:case L.publicKey.rsaSign:{const{n:e,e:a}=n,o=N.leftPad(r.s,e.length);return Xi.rsa.verify(t,i,o,e,a,s)}case L.publicKey.dsa:{const{g:e,p:i,q:a,y:o}=n,{r:c,s:h}=r;return Xi.dsa.verify(t,c,h,s,e,i,a,o)}case L.publicKey.ecdsa:{const{oid:e,Q:a}=n,o=new Xi.elliptic.CurveWithOID(e).payloadSize,c=N.leftPad(r.r,o),h=N.leftPad(r.s,o);return Xi.elliptic.ecdsa.verify(e,t,{r:c,s:h},i,a,s)}case L.publicKey.eddsaLegacy:{const{oid:e,Q:a}=n,o=new Xi.elliptic.CurveWithOID(e).payloadSize,c=N.leftPad(r.r,o),h=N.leftPad(r.s,o);return Xi.elliptic.eddsaLegacy.verify(e,t,{r:c,s:h},i,a,s)}case L.publicKey.ed25519:case L.publicKey.ed448:{const{A:a}=n;return Xi.elliptic.eddsa.verify(e,t,r,i,a,s)}default:throw Error("Unknown signature algorithm.")}}});class ts{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return N.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class rs{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new Vn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class ns{static fromObject({wrappedKey:e,algorithm:t}){const r=new ns;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=N.readExactSubarray(e,t,t+r),t+=r}write(){return N.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function is(e){try{e.getName()}catch(e){throw new Vn("Unknown curve OID")}}function ss(e,t){switch(e){case L.publicKey.ecdsa:case L.publicKey.ecdh:case L.publicKey.eddsaLegacy:return new Xi.elliptic.CurveWithOID(t).payloadSize;case L.publicKey.ed25519:case L.publicKey.ed448:return Xi.elliptic.eddsa.getPayloadSize(e);case L.publicKey.x25519:case L.publicKey.x448:return Xi.elliptic.ecdhX.getPayloadSize(e);default:throw Error("Unknown elliptic algo")}}var as=/*#__PURE__*/Object.freeze({__proto__:null,generateParams:function(e,t,r){switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:return Xi.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:n,q:i,u:s})=>({privateParams:{d:r,p:n,q:i,u:s},publicParams:{n:e,e:t}})));case L.publicKey.ecdsa:return Xi.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new Fn(e),Q:t}})));case L.publicKey.eddsaLegacy:return Xi.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new Fn(e),Q:t}})));case L.publicKey.ecdh:return Xi.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:n,cipher:i})=>({privateParams:{d:r},publicParams:{oid:new Fn(e),Q:t,kdfParams:new rs({hash:n,cipher:i})}})));case L.publicKey.ed25519:case L.publicKey.ed448:return Xi.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case L.publicKey.x25519:case L.publicKey.x448:return Xi.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case L.publicKey.dsa:case L.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},generateSessionKey:function(e){const{keySize:t}=ie(e);return Sr(t)},getAEADMode:function(e){const t=L.read(L.aead,e);return yr[t]},getCipherParams:ie,getCurvePayloadSize:ss,getPreferredCurveHashAlgo:function(e,t){switch(e){case L.publicKey.ecdsa:case L.publicKey.eddsaLegacy:return Xi.elliptic.getPreferredHashAlgo(t);case L.publicKey.ed25519:case L.publicKey.ed448:return Xi.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}},getPrefixRandom:async function(e){const{blockSize:t}=ie(e),r=await Sr(t),n=new Uint8Array([r[r.length-2],r[r.length-1]]);return N.concat([r,n])},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:return{c:N.readMPI(t.subarray(r))};case L.publicKey.elgamal:{const e=N.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:N.readMPI(t.subarray(r))}}case L.publicKey.ecdh:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=new ts;return n.read(t.subarray(r)),{V:e,C:n}}case L.publicKey.x25519:case L.publicKey.x448:{const n=ss(e),i=N.readExactSubarray(t,r,r+n);r+=i.length;const s=new ns;return s.read(t.subarray(r)),{ephemeralPublicKey:i,C:s}}default:throw new Vn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let n=0;switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:{const e=N.readMPI(t.subarray(n));n+=e.length+2;const r=N.readMPI(t.subarray(n));n+=r.length+2;const i=N.readMPI(t.subarray(n));n+=i.length+2;const s=N.readMPI(t.subarray(n));return n+=s.length+2,{read:n,privateParams:{d:e,p:r,q:i,u:s}}}case L.publicKey.dsa:case L.publicKey.elgamal:{const e=N.readMPI(t.subarray(n));return n+=e.length+2,{read:n,privateParams:{x:e}}}case L.publicKey.ecdsa:case L.publicKey.ecdh:{const i=ss(e,r.oid);let s=N.readMPI(t.subarray(n));return n+=s.length+2,s=N.leftPad(s,i),{read:n,privateParams:{d:s}}}case L.publicKey.eddsaLegacy:{const i=ss(e,r.oid);if(r.oid.getName()!==L.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let s=N.readMPI(t.subarray(n));return n+=s.length+2,s=N.leftPad(s,i),{read:n,privateParams:{seed:s}}}case L.publicKey.ed25519:case L.publicKey.ed448:{const r=ss(e),i=N.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{seed:i}}}case L.publicKey.x25519:case L.publicKey.x448:{const r=ss(e),i=N.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{k:i}}}default:throw new Vn("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=N.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{n:e,e:n}}}case L.publicKey.dsa:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=N.readMPI(t.subarray(r));r+=n.length+2;const i=N.readMPI(t.subarray(r));r+=i.length+2;const s=N.readMPI(t.subarray(r));return r+=s.length+2,{read:r,publicParams:{p:e,q:n,g:i,y:s}}}case L.publicKey.elgamal:{const e=N.readMPI(t.subarray(r));r+=e.length+2;const n=N.readMPI(t.subarray(r));r+=n.length+2;const i=N.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{p:e,g:n,y:i}}}case L.publicKey.ecdsa:{const e=new Fn;r+=e.read(t),is(e);const n=N.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{oid:e,Q:n}}}case L.publicKey.eddsaLegacy:{const e=new Fn;if(r+=e.read(t),is(e),e.getName()!==L.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let n=N.readMPI(t.subarray(r));return r+=n.length+2,n=N.leftPad(n,33),{read:r,publicParams:{oid:e,Q:n}}}case L.publicKey.ecdh:{const e=new Fn;r+=e.read(t),is(e);const n=N.readMPI(t.subarray(r));r+=n.length+2;const i=new rs;return r+=i.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:n,kdfParams:i}}}case L.publicKey.ed25519:case L.publicKey.ed448:case L.publicKey.x25519:case L.publicKey.x448:{const n=N.readExactSubarray(t,r,r+ss(e));return r+=n.length,{read:r,publicParams:{A:n}}}default:throw new Vn("Unknown public key encryption algorithm.")}},publicKeyDecrypt:async function(e,t,r,n,i,s){switch(e){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:{const{c:e}=n,{n:i,e:a}=t,{d:o,p:c,q:h,u}=r;return Xi.rsa.decrypt(e,i,a,o,c,h,u,s)}case L.publicKey.elgamal:{const{c1:e,c2:i}=n,a=t.p,o=r.x;return Xi.elgamal.decrypt(e,i,a,o,s)}case L.publicKey.ecdh:{const{oid:e,Q:s,kdfParams:a}=t,{d:o}=r,{V:c,C:h}=n;return Xi.elliptic.ecdh.decrypt(e,a,c,h.data,s,o,i)}case L.publicKey.x25519:case L.publicKey.x448:{const{A:i}=t,{k:s}=r,{ephemeralPublicKey:a,C:o}=n;if(null!==o.algorithm&&!N.isAES(o.algorithm))throw Error("AES session key expected");return Xi.elliptic.ecdhX.decrypt(e,a,o.wrappedKey,i,s)}default:throw Error("Unknown public key encryption algorithm.")}},publicKeyEncrypt:async function(e,t,r,n,i){switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await Xi.rsa.encrypt(n,e,t)}}case L.publicKey.elgamal:{const{p:e,g:t,y:i}=r;return Xi.elgamal.encrypt(n,e,t,i)}case L.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:s}=r,{publicKey:a,wrappedKey:o}=await Xi.elliptic.ecdh.encrypt(e,s,n,t,i);return{V:a,C:new ts(o)}}case L.publicKey.x25519:case L.publicKey.x448:{if(t&&!N.isAES(t))throw Error("X25519 and X448 keys can only encrypt AES session keys");const{A:i}=r,{ephemeralPublicKey:s,wrappedKey:a}=await Xi.elliptic.ecdhX.encrypt(e,n,i);return{ephemeralPublicKey:s,C:ns.fromObject({algorithm:t,wrappedKey:a})}}default:return[]}},serializeParams:function(e,t){const r=new Set([L.publicKey.ed25519,L.publicKey.x25519,L.publicKey.ed448,L.publicKey.x448]),n=Object.keys(t).map((n=>{const i=t[n];return N.isUint8Array(i)?r.has(e)?i:N.uint8ArrayToMPI(i):i.write()}));return N.concatUint8Array(n)},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:{const{n:e,e:n}=t,{d:i,p:s,q:a,u:o}=r;return Xi.rsa.validateParams(e,n,i,s,a,o)}case L.publicKey.dsa:{const{p:e,q:n,g:i,y:s}=t,{x:a}=r;return Xi.dsa.validateParams(e,n,i,s,a)}case L.publicKey.elgamal:{const{p:e,g:n,y:i}=t,{x:s}=r;return Xi.elgamal.validateParams(e,n,i,s)}case L.publicKey.ecdsa:case L.publicKey.ecdh:{const n=Xi.elliptic[L.read(L.publicKey,e)],{oid:i,Q:s}=t,{d:a}=r;return n.validateParams(i,s,a)}case L.publicKey.eddsaLegacy:{const{Q:e,oid:n}=t,{seed:i}=r;return Xi.elliptic.eddsaLegacy.validateParams(n,e,i)}case L.publicKey.ed25519:case L.publicKey.ed448:{const{A:n}=t,{seed:i}=r;return Xi.elliptic.eddsa.validateParams(e,n,i)}case L.publicKey.x25519:case L.publicKey.x448:{const{A:n}=t,{k:i}=r;return Xi.elliptic.ecdhX.validateParams(e,n,i)}default:throw Error("Unknown public key algorithm.")}}});const os={cipher:se,hash:ke,mode:yr,publicKey:Xi,signature:es,random:Cr,pkcs1:Mr,pkcs5:Fi,aesKW:oi};Object.assign(os,as);class cs extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,cs),this.name="Argon2OutOfMemoryError"}}let hs,us;class ls{constructor(e=T){const{passes:t,parallelism:r,memoryExponent:n}=e.s2kArgon2Params;this.type="argon2",this.salt=null,this.t=t,this.p=r,this.encodedM=n}generateSalt(){this.salt=os.random.getRandomBytes(16)}read(e){let t=0;return this.salt=e.subarray(t,t+16),t+=16,this.t=e[t++],this.p=e[t++],this.encodedM=e[t++],t}write(){const e=[new Uint8Array([L.write(L.s2k,this.type)]),this.salt,new Uint8Array([this.t,this.p,this.encodedM])];return N.concatUint8Array(e)}async produceKey(e,t){const r=2<1048576&&(us=hs(),us.catch((()=>{}))),i}catch(e){throw e.message&&(e.message.includes("Unable to grow instance memory")||e.message.includes("failed to grow memory")||e.message.includes("WebAssembly.Memory.grow")||e.message.includes("Out of memory"))?new cs("Could not allocate required memory for Argon2"):e}}}class ys{constructor(e,t=T){this.algorithm=L.hash.sha256,this.type=L.read(L.s2k,e),this.c=t.s2kIterationCountByte,this.salt=null}generateSalt(){switch(this.type){case"salted":case"iterated":this.salt=os.random.getRandomBytes(8)}}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==N.uint8ArrayToString(e.subarray(t,t+3)))throw new Vn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new Vn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new Vn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...N.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([L.write(L.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return N.concatUint8Array(e)}async produceKey(e,t){e=N.encodeUTF8(e);const r=[];let n=0,i=0;for(;n>>1|(21845&Ds)<<1;Us=(61680&(Us=(52428&Us)>>>2|(13107&Us)<<2))>>>4|(3855&Us)<<4,Ps[Ds]=((65280&Us)>>>8|(255&Us)<<8)>>>1}var xs=function(e,t,r){for(var n=e.length,i=0,s=new As(t);i>>c]=h}else for(a=new As(n),i=0;i>>15-e[i]);return a},Qs=new ds(288);for(Ds=0;Ds<144;++Ds)Qs[Ds]=8;for(Ds=144;Ds<256;++Ds)Qs[Ds]=9;for(Ds=256;Ds<280;++Ds)Qs[Ds]=7;for(Ds=280;Ds<288;++Ds)Qs[Ds]=8;var Rs=new ds(32);for(Ds=0;Ds<32;++Ds)Rs[Ds]=5;var Ls=/*#__PURE__*/xs(Qs,9,0),Ts=/*#__PURE__*/xs(Qs,9,1),Ms=/*#__PURE__*/xs(Rs,5,0),Ns=/*#__PURE__*/xs(Rs,5,1),Fs=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},Hs=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Os=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},zs=function(e){return(e+7)/8|0},_s=function(e,t,r){(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length);var n=new(2==e.BYTES_PER_ELEMENT?As:4==e.BYTES_PER_ELEMENT?ws:ds)(r-t);return n.set(e.subarray(t,r)),n},Gs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],js=function(e,t,r){var n=Error(t||Gs[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,js),!r)throw n;return n},qs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8},Vs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Js=function(e,t){for(var r=[],n=0;ny&&(y=s[n].s);var f=new As(y+1),g=Ys(r[u-1],f,0);if(g>t){n=0;var p=0,d=g-t,A=1<t))break;p+=A-(1<>>=d;p>0;){var m=s[n].s;f[m]=0&&p;--n){var b=s[n].s;f[b]==t&&(--f[b],++p)}g=t}return[new ds(f),g]},Ys=function(e,t,r){return-1==e.s?Math.max(Ys(e.l,t,r+1),Ys(e.r,t,r+1)):t[e.s]=r},Ws=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new As(++t),n=0,i=e[0],s=1,a=function(e){r[n++]=e},o=1;o<=t;++o)if(e[o]==i&&o!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(i),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(i);s=1,i=e[o]}return[r.subarray(0,n),t]},Zs=function(e,t){for(var r=0,n=0;n>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;s4&&!S[ks[C-1]];--C);var P,D,U,x,Q=h+5<<3,R=Zs(i,Qs)+Zs(s,Rs)+a,L=Zs(i,y)+Zs(s,p)+a+14+3*C+Zs(v,S)+(2*v[16]+3*v[17]+7*v[18]);if(Q<=R&&Q<=L)return $s(t,u,e.subarray(c,c+h));if(qs(t,u,1+(L15&&(qs(t,u,F[B]>>>5&127),u+=F[B]>>>12)}}}else P=Ls,D=Qs,U=Ms,x=Rs;for(B=0;B255){H=n[B]>>>18&31;Vs(t,u,P[H+257]),u+=D[H+257],H>7&&(qs(t,u,n[B]>>>23&31),u+=ms[H]);var O=31&n[B];Vs(t,u,U[O]),u+=x[O],O>3&&(Vs(t,u,n[B]>>>5&8191),u+=bs[O])}else Vs(t,u,P[n[B]]),u+=D[n[B]];return Vs(t,u,P[256]),u+D[256]},ea=/*#__PURE__*/new ws([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ta=/*#__PURE__*/new ds(0),ra=function(e,t,r,n,i){return function(e,t,r,n,i,s){var a=e.length,o=new ds(n+a+5*(1+Math.ceil(a/7e3))+i),c=o.subarray(n,o.length-i),h=0;if(!t||a<8)for(var u=0;u<=a;u+=65535){var l=u+65535;l>=a&&(c[h>>3]=s),h=$s(c,h+1,e.subarray(u,l))}else{for(var y=ea[t-1],f=y>>>13,g=8191&y,p=(1<7e3||S>24576)&&x>423){h=Xs(e,c,0,k,E,v,I,S,C,u-C,h),S=B=I=0,C=u;for(var Q=0;Q<286;++Q)E[Q]=0;for(Q=0;Q<30;++Q)v[Q]=0}var R=2,L=0,T=g,M=D-U&32767;if(x>2&&P==b(u-M))for(var N=Math.min(f,x)-1,F=Math.min(32767,u),H=Math.min(258,x);M<=F&&--T&&D!=U;){if(e[u+R]==e[u+R-M]){for(var O=0;OR){if(R=O,L=M,O>N)break;var z=Math.min(M,O-2),_=0;for(Q=0;Q_&&(_=j,U=G)}}}M+=(D=U)-(U=d[D])+32768&32767}if(L){k[S++]=268435456|Is[R]<<18|Cs[L];var q=31&Is[R],V=31&Cs[L];I+=ms[q]+bs[V],++E[257+q],++v[V],K=u+R,++B}else k[S++]=e[u],++E[e[u]]}}h=Xs(e,c,s,k,E,v,I,S,C,u-C,h),!s&&7&h&&(h=$s(c,h+1,ta))}return _s(o,0,n+zs(h)+i)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,r,n,!i)},na=/*#__PURE__*/function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(ra(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||js(5),this.d&&js(4),this.d=t,this.p(e,t||!1)},e}(),ia=/*#__PURE__*/function(){function e(e){this.s={},this.p=new ds(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||js(5),this.d&&js(4);var t=this.p.length,r=new ds(t+e.length);r.set(this.p),r.set(e,t),this.p=r},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,r=function(e,t,r){var n=e.length;if(!n||r&&r.f&&!r.l)return t||new ds(0);var i=!t||r,s=!r||r.i;r||(r={}),t||(t=new ds(3*n));var a=function(e){var r=t.length;if(e>r){var n=new ds(Math.max(2*r,e));n.set(t),t=n}},o=r.f||0,c=r.p||0,h=r.b||0,u=r.l,l=r.d,y=r.m,f=r.n,g=8*n;do{if(!u){o=Hs(e,c,1);var p=Hs(e,c+1,3);if(c+=3,!p){var d=e[(K=zs(c)+4)-4]|e[K-3]<<8,A=K+d;if(A>n){s&&js(0);break}i&&a(h+d),t.set(e.subarray(K,A),h),r.b=h+=d,r.p=c=8*A,r.f=o;continue}if(1==p)u=Ts,l=Ns,y=9,f=5;else if(2==p){var w=Hs(e,c,31)+257,m=Hs(e,c+10,15)+4,b=w+Hs(e,c+5,31)+1;c+=14;for(var k=new ds(b),E=new ds(19),v=0;v>>4)<16)k[v++]=K;else{var P=0,D=0;for(16==K?(D=3+Hs(e,c,3),c+=2,P=k[v-1]):17==K?(D=3+Hs(e,c,7),c+=3):18==K&&(D=11+Hs(e,c,127),c+=7);D--;)k[v++]=P}}var U=k.subarray(0,w),x=k.subarray(w);y=Fs(U),f=Fs(x),u=xs(U,y,1),l=xs(x,f,1)}else js(1);if(c>g){s&&js(0);break}}i&&a(h+131072);for(var Q=(1<>>4;if((c+=15&P)>g){s&&js(0);break}if(P||js(2),T<256)t[h++]=T;else{if(256==T){L=c,u=null;break}var M=T-254;if(T>264){var N=ms[v=T-257];M=Hs(e,c,(1<>>4;if(F||js(3),c+=15&F,x=Ks[H],H>3&&(N=bs[H],x+=Os(e,c)&(1<g){s&&js(0);break}i&&a(h+131072);for(var O=h+M;h>16),i=(65535&i)+15*(i>>16)}r=t,n=i},d:function(){return(255&(r%=65521))<<24|r>>>8<<16|(255&(n%=65521))<<8|n>>>8}}),this.v=1,na.call(this,e,t)}return e.prototype.push=function(e,t){na.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var r=ra(e,this.o,this.v&&2,t&&4,!t);this.v&&(function(e,t){var r=t.level,n=0==r?0:r<6?1:9==r?3:2;e[0]=120,e[1]=n<<6|(n?32-2*n:1)}(r,this.o),this.v=0),t&&function(e,t,r){for(;r;++t)e[t]=r,r>>>=8}(r,r.length-4,this.c.d()),this.ondata(r,t)},e}(),aa=/*#__PURE__*/function(){function e(e){this.v=1,ia.call(this,e)}return e.prototype.push=function(e,t){if(ia.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&js(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),ia.prototype.c.call(this,t)},e}(),oa="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{oa.decode(ta,{stream:!0}),1}catch(e){}class ca{static get tag(){return L.packet.literalData}constructor(e=new Date){this.format=L.literal.utf8,this.date=N.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=L.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||N.isStream(this.text))&&(this.text=N.decodeUTF8(N.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=N.canonicalizeEOL(N.encodeUTF8(this.text))),e?S(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await B(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=N.decodeUTF8(await e.readBytes(r)),this.date=N.readDate(await e.readBytes(4));let n=e.remainder();c(n)&&(n=await P(n)),this.setBytes(n,t)}))}writeHeader(){const e=N.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),n=N.writeDate(this.date);return N.concatUint8Array([r,t,e,n])}write(){const e=this.writeHeader(),t=this.getBytes();return N.concat([e,t])}}class ha{constructor(){this.bytes=""}read(e){return this.bytes=N.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return N.stringToUint8Array(this.bytes)}toHex(){return N.uint8ArrayToHex(N.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new ha;return t.read(N.hexToUint8Array(e)),t}static wildcard(){const e=new ha;return e.read(new Uint8Array(8)),e}}const ua=Symbol("verified"),la="salt@notations.openpgpjs.org",ya=new Set([L.signatureSubpacket.issuerKeyID,L.signatureSubpacket.issuerFingerprint,L.signatureSubpacket.embeddedSignature]);class fa{static get tag(){return L.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.unknownSubpackets=[],this.signedHashValue=null,this.salt=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new ha,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.preferredCipherSuites=null,this.revoked=null,this[ua]=null}read(e,t=T){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Vn("Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4!==this.version&&5!==this.version&&6!==this.version)throw new Vn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[r++],this.publicKeyAlgorithm=e[r++],this.hashAlgorithm=e[r++],r+=this.readSubPackets(e.subarray(r,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");if(this.signatureData=e.subarray(0,r),r+=this.readSubPackets(e.subarray(r,e.length),!1),this.signedHashValue=e.subarray(r,r+2),r+=2,6===this.version){const t=e[r++];this.salt=e.subarray(r,r+t),r+=t}const n=e.subarray(r,e.length),{read:i,signatureParams:s}=os.signature.parseSignatureParams(this.publicKeyAlgorithm,n);if(ios.serializeParams(this.publicKeyAlgorithm,await this.params))):os.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),6===this.version&&(e.push(new Uint8Array([this.salt.length])),e.push(this.salt)),e.push(this.writeParams()),N.concat(e)}async sign(e,t,r=new Date,n=!1,i){this.version=e.version,this.created=N.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID();const s=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];if(6===this.version){const e=pa(this.hashAlgorithm);if(null===this.salt)this.salt=os.random.getRandomBytes(e);else if(e!==this.salt.length)throw Error("Provided salt does not have the required length")}else if(i.nonDeterministicSignaturesViaNotation){if(0!==this.rawNotations.filter((({name:e})=>e===la)).length)throw Error("Unexpected existing salt notation");{const e=os.random.getRandomBytes(pa(this.hashAlgorithm));this.rawNotations.push({name:la,value:e,humanReadable:!1,critical:!1})}}s.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=N.concat(s);const a=this.toHash(this.signatureType,t,n),o=await this.hash(this.signatureType,t,a,n);this.signedHashValue=C(I(o),0,2);const c=async()=>os.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await P(o));N.isStream(o)?this.params=c():(this.params=await c(),this[ua]=!0)}writeHashedSubPackets(){const e=L.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(ga(e.signatureCreationTime,!0,N.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(ga(e.signatureExpirationTime,!0,N.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(ga(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(ga(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(ga(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(ga(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(ga(e.keyExpirationTime,!0,N.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(ga(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=N.concat([r,this.revocationKeyFingerprint]),t.push(ga(e.revocationKey,!1,r))),!this.issuerKeyID.isNull()&&this.issuerKeyVersion<5&&t.push(ga(e.issuerKeyID,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:n,value:i,humanReadable:s,critical:a})=>{r=[new Uint8Array([s?128:0,0,0,0])];const o=N.encodeUTF8(n);r.push(N.writeNumber(o.length,2)),r.push(N.writeNumber(i.length,2)),r.push(o),r.push(i),r=N.concat(r),t.push(ga(e.notationData,a,r))})),null!==this.preferredHashAlgorithms&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(ga(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(ga(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.keyServerPreferences)),t.push(ga(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(ga(e.preferredKeyServer,!1,N.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(ga(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(ga(e.policyURI,!1,N.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.keyFlags)),t.push(ga(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(ga(e.signersUserID,!1,N.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=N.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(ga(e.reasonForRevocation,!0,r))),null!==this.features&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.features)),t.push(ga(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(N.stringToUint8Array(this.signatureTargetHash)),r=N.concat(r),t.push(ga(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(ga(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=N.concat(r),t.push(ga(e.issuerFingerprint,this.version>=5,r))),null!==this.preferredAEADAlgorithms&&(r=N.stringToUint8Array(N.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(ga(e.preferredAEADAlgorithms,!1,r))),null!==this.preferredCipherSuites&&(r=new Uint8Array([].concat(...this.preferredCipherSuites)),t.push(ga(e.preferredCipherSuites,!1,r)));const n=N.concat(t),i=N.writeNumber(n.length,6===this.version?4:2);return N.concat([i,n])}writeUnhashedSubPackets(){const e=this.unhashedSubpackets.map((({type:e,critical:t,body:r})=>ga(e,t,r))),t=N.concat(e),r=N.writeNumber(t.length,6===this.version?4:2);return N.concat([r,t])}readSubPacket(e,t=!0){let r=0;const n=!!(128&e[r]),i=127&e[r];if(r++,t||(this.unhashedSubpackets.push({type:i,critical:n,body:e.subarray(r,e.length)}),ya.has(i)))switch(i){case L.signatureSubpacket.signatureCreationTime:this.created=N.readDate(e.subarray(r,e.length));break;case L.signatureSubpacket.signatureExpirationTime:{const t=N.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case L.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case L.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case L.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case L.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case L.signatureSubpacket.keyExpirationTime:{const t=N.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case L.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case L.signatureSubpacket.issuerKeyID:if(4===this.version)this.issuerKeyID.read(e.subarray(r,e.length));else if(t)throw Error("Unexpected Issuer Key ID subpacket");break;case L.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const i=N.readNumber(e.subarray(r,r+2));r+=2;const s=N.readNumber(e.subarray(r,r+2));r+=2;const a=N.decodeUTF8(e.subarray(r,r+i)),o=e.subarray(r+i,r+i+s);this.rawNotations.push({name:a,humanReadable:t,value:o,critical:n}),t&&(this.notations[a]=N.decodeUTF8(o));break}case L.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=N.decodeUTF8(e.subarray(r,e.length));break;case L.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case L.signatureSubpacket.policyURI:this.policyURI=N.decodeUTF8(e.subarray(r,e.length));break;case L.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.signersUserID:this.signersUserID=N.decodeUTF8(e.subarray(r,e.length));break;case L.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=N.decodeUTF8(e.subarray(r,e.length));break;case L.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=os.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=N.uint8ArrayToString(e.subarray(r,r+t));break}case L.signatureSubpacket.embeddedSignature:this.embeddedSignature=new fa,this.embeddedSignature.read(e.subarray(r,e.length));break;case L.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),this.issuerKeyVersion>=5?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case L.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;case L.signatureSubpacket.preferredCipherSuites:this.preferredCipherSuites=[];for(let t=r;t{r+=e.length}),(()=>{const n=[];return 5!==this.version||this.signatureType!==L.signature.binary&&this.signatureType!==L.signature.text||(t?n.push(new Uint8Array(6)):n.push(e.writeHeader())),n.push(new Uint8Array([this.version,255])),5===this.version&&n.push(new Uint8Array(4)),n.push(N.writeNumber(r,4)),N.concat(n)}))}toHash(e,t,r=!1){const n=this.toSign(e,t);return N.concat([this.salt||new Uint8Array,n,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,n=!1){if(6===this.version&&this.salt.length!==pa(this.hashAlgorithm))throw Error("Signature salt does not have the expected length");return r||(r=this.toHash(e,t,n)),os.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,n=new Date,i=!1,s=T){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const a=t===L.signature.binary||t===L.signature.text;if(!(this[ua]&&!a)){let n,s;if(this.hashed?s=await this.hashed:(n=this.toHash(t,r,i),s=await this.hash(t,r,n)),s=await P(s),this.signedHashValue[0]!==s[0]||this.signedHashValue[1]!==s[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[ua]=await os.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,n,s),!this[ua])throw Error("Signature verification failed")}const o=N.normalizeDate(n);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(s.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+L.read(L.hash,this.hashAlgorithm).toUpperCase());if(s.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[L.signature.binary,L.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+L.read(L.hash,this.hashAlgorithm).toUpperCase());if(this.unknownSubpackets.forEach((({type:e,critical:t})=>{if(t)throw Error("Unknown critical signature subpacket type "+e)})),this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&s.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=N.normalizeDate(e);return null!==t&&!(this.created<=t&&tfa.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==L.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID)||3===this.version&&6===e.version||6===this.version&&6!==e.version||6===this.version&&!N.equalsUint8Array(e.issuerFingerprint,this.issuerFingerprint)||6===this.version&&!N.equalsUint8Array(e.salt,this.salt))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function Aa(e,t){if(!t[e]){let t;try{t=L.read(L.packet,e)}catch(t){throw new Jn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}da.prototype.hash=fa.prototype.hash,da.prototype.toHash=fa.prototype.toHash,da.prototype.toSign=fa.prototype.toSign;class wa extends Array{static async fromBinary(e,t,r=T){const n=new wa;return await n.read(e,t,r),n}async read(e,t,r=T){r.additionalAllowedPackets.length&&(t={...t,...N.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=v(e,(async(e,n)=>{const i=Q(n);try{for(;;){await i.ready;if(await qn(e,(async e=>{try{if(e.tag===L.packet.marker||e.tag===L.packet.trust||e.tag===L.packet.padding)return;const n=Aa(e.tag,t);n.packets=new wa,n.fromStream=N.isStream(e.packet),await n.read(e.packet,r),await i.write(n)}catch(t){if(t instanceof Jn){if(!(e.tag<=39))return;await i.abort(t)}const n=!r.ignoreUnsupportedPackets&&t instanceof Vn,s=!(r.ignoreMalformedPackets||t instanceof Vn);if(n||s||jn(e.tag))await i.abort(t);else{const t=new Yn(e.tag,e.packet);await i.write(t)}N.printDebugError(t)}})))return await i.ready,void await i.close()}}catch(e){await i.abort(e)}}));const n=x(this.stream);for(;;){const{done:e,value:t}=await n.read();if(e?this.stream=null:this.push(t),e||jn(t.constructor.tag))break}n.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),i+=e.length,i>=s){const e=Math.min(Math.log(i)/Math.LN2|0,30),r=2**e,n=N.concat([zn(e)].concat(t));return t=[n.subarray(1+r)],i=t[0].length,n.subarray(0,1+r)}}),(()=>N.concat([On(i)].concat(t)))))}else{if(N.isStream(n)){let t=0;e.push(E(I(n),(e=>{t+=e.length}),(()=>Gn(r,t))))}else e.push(Gn(r,n.length));e.push(n)}}return N.concat(e)}filterByTag(...e){const t=new wa,r=e=>t=>e===t;for(let n=0;nt.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,n=e=>t=>e===t;for(let i=0;i{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),N.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=T){const t=L.read(L.compression,this.algorithm),r=Ia[t];if(!r)throw Error(t+" decompression not supported");this.packets=await wa.fromBinary(await r(this.compressed),ma,e)}compress(){const e=L.read(L.compression,this.algorithm),t=Ba[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write())}}function ka(e,t){return r=>{if(!N.isStream(r)||c(r))return U((()=>P(r).then((e=>new Promise(((r,n)=>{const i=new t;i.ondata=e=>{r(e)};try{i.push(e,!0)}catch(e){n(e)}}))))));if(e)try{const t=e();return r.pipeThrough(t)}catch(e){if("TypeError"!==e.name)throw e}const n=r.getReader(),i=new t;return new ReadableStream({async start(e){for(i.ondata=async(t,r)=>{e.enqueue(t),r&&e.close()};;){const{done:e,value:t}=await n.read();if(e)return void i.push(new Uint8Array,!0);t.length&&i.push(t)}}})}}function Ea(){return async function(e){const{decode:t}=await Promise.resolve().then((function(){return Dy}));return U((async()=>t(await P(e))))}}const va=e=>({compressor:"undefined"!=typeof CompressionStream&&(()=>new CompressionStream(e)),decompressor:"undefined"!=typeof DecompressionStream&&(()=>new DecompressionStream(e))}),Ba={zip:/*#__PURE__*/ka(va("deflate-raw").compressor,na),zlib:/*#__PURE__*/ka(va("deflate").compressor,sa)},Ia={uncompressed:e=>e,zip:/*#__PURE__*/ka(va("deflate-raw").decompressor,ia),zlib:/*#__PURE__*/ka(va("deflate").decompressor,aa),bzip2:/*#__PURE__*/Ea()},Sa=/*#__PURE__*/N.constructAllowedPackets([ca,ba,da,fa]);class Ka{static get tag(){return L.packet.symEncryptedIntegrityProtectedData}static fromObject({version:e,aeadAlgorithm:t}){if(1!==e&&2!==e)throw Error("Unsupported SEIPD version");const r=new Ka;return r.version=e,2===e&&(r.aeadAlgorithm=t),r}constructor(){this.version=null,this.cipherAlgorithm=null,this.aeadAlgorithm=null,this.chunkSizeByte=null,this.salt=null,this.encrypted=null,this.packets=null}async read(e){await B(e,(async e=>{if(this.version=await e.readByte(),1!==this.version&&2!==this.version)throw new Vn(`Version ${this.version} of the SEIP packet is unsupported.`);2===this.version&&(this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte(),this.salt=await e.readBytes(32)),this.encrypted=e.remainder()}))}write(){return 2===this.version?N.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.salt,this.encrypted]):N.concat([new Uint8Array([this.version]),this.encrypted])}async encrypt(e,t,r=T){const{blockSize:n,keySize:i}=os.getCipherParams(e);if(t.length!==i)throw Error("Unexpected session key size");let s=this.packets.write();if(c(s)&&(s=await P(s)),2===this.version)this.cipherAlgorithm=e,this.salt=os.random.getRandomBytes(32),this.chunkSizeByte=r.aeadChunkSizeByte,this.encrypted=await Ca(this,"encrypt",t,s);else{const i=await os.getPrefixRandom(e),a=new Uint8Array([211,20]),o=N.concat([i,s,a]),c=await os.hash.sha1(S(o)),h=N.concat([o,c]);this.encrypted=await os.mode.cfb.encrypt(e,t,h,new Uint8Array(n),r)}return!0}async decrypt(e,t,r=T){if(t.length!==os.getCipherParams(e).keySize)throw Error("Unexpected session key size");let n,i=I(this.encrypted);if(c(i)&&(i=await P(i)),2===this.version){if(this.cipherAlgorithm!==e)throw Error("Unexpected session key algorithm");n=await Ca(this,"decrypt",t,i)}else{const{blockSize:s}=os.getCipherParams(e),a=await os.mode.cfb.decrypt(e,t,i,new Uint8Array(s)),o=C(S(a),-20),c=C(a,0,-20),h=Promise.all([P(await os.hash.sha1(S(c))),P(o)]).then((([e,t])=>{if(!N.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=C(c,s+2);n=C(u,0,-2),n=w([n,U((()=>h))]),N.isStream(i)&&r.allowUnauthenticatedStream||(n=await P(n))}return this.packets=await wa.fromBinary(n,Sa,r),!0}}async function Ca(e,t,r,n){const i=e instanceof Ka&&2===e.version,s=!i&&e.constructor.tag===L.packet.aeadEncryptedData;if(!i&&!s)throw Error("Unexpected packet type");const a=os.getAEADMode(e.aeadAlgorithm),o="decrypt"===t?a.tagLength:0,c="encrypt"===t?a.tagLength:0,h=2**(e.chunkSizeByte+6)+o,u=s?8:0,l=new ArrayBuffer(13+u),y=new Uint8Array(l,0,5+u),f=new Uint8Array(l),g=new DataView(l),p=new Uint8Array(l,5,8);y.set([192|e.constructor.tag,e.version,e.cipherAlgorithm,e.aeadAlgorithm,e.chunkSizeByte],0);let d,A,w=0,b=Promise.resolve(),k=0,E=0;if(i){const{keySize:t}=os.getCipherParams(e.cipherAlgorithm),{ivLength:n}=a,i=new Uint8Array(l,0,5),s=await hi(L.hash.sha256,r,e.salt,i,t+n);r=s.subarray(0,t),d=s.subarray(t),d.fill(0,d.length-8),A=new DataView(d.buffer,d.byteOffset,d.byteLength)}else d=e.iv;const B=await a(e.cipherAlgorithm,r);return v(n,(async(r,n)=>{if("array"!==N.isStream(r)){const t=new TransformStream({},{highWaterMark:N.getHardwareConcurrency()*2**(e.chunkSizeByte+6),size:e=>e.length});m(t.readable,n),n=t.writable}const s=x(r),a=Q(n);try{for(;;){let e=await s.readBytes(h+o)||new Uint8Array;const r=e.subarray(e.length-o);let n,l,m;if(e=e.subarray(0,e.length-o),i)m=d;else{m=d.slice();for(let e=0;e<8;e++)m[d.length-8+e]^=p[e]}if(!w||e.length?(s.unshift(r),n=B[t](e,m,y),n.catch((()=>{})),E+=e.length-o+c):(g.setInt32(5+u+4,k),n=B[t](r,m,f),n.catch((()=>{})),E+=c,l=!0),k+=e.length-o,b=b.then((()=>n)).then((async e=>{await a.ready,await a.write(e),E-=e.length})).catch((e=>a.abort(e))),(l||E>a.desiredSize)&&await b,l){await a.close();break}i?A.setInt32(d.length-4,++w):g.setInt32(9,++w)}}catch(e){await a.ready.catch((()=>{})),await a.abort(e)}}))}const Pa=/*#__PURE__*/N.constructAllowedPackets([ca,ba,da,fa]);class Da{static get tag(){return L.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=L.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await B(e,(async e=>{const t=await e.readByte();if(1!==t)throw new Vn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=os.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return N.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=T){this.packets=await wa.fromBinary(await Ca(this,"decrypt",t,I(this.encrypted)),Pa,r)}async encrypt(e,t,r=T){this.cipherAlgorithm=e;const{ivLength:n}=os.getAEADMode(this.aeadAlgorithm);this.iv=os.random.getRandomBytes(n),this.chunkSizeByte=r.aeadChunkSizeByte;const i=this.packets.write();this.encrypted=await Ca(this,"encrypt",t,i)}}class Ua{static get tag(){return L.packet.publicKeyEncryptedSessionKey}constructor(){this.version=null,this.publicKeyID=new ha,this.publicKeyVersion=null,this.publicKeyFingerprint=null,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}static fromObject({version:e,encryptionKeyPacket:t,anonymousRecipient:r,sessionKey:n,sessionKeyAlgorithm:i}){const s=new Ua;if(3!==e&&6!==e)throw Error("Unsupported PKESK version");return s.version=e,6===e&&(s.publicKeyVersion=r?null:t.version,s.publicKeyFingerprint=r?null:t.getFingerprintBytes()),s.publicKeyID=r?ha.wildcard():t.getKeyID(),s.publicKeyAlgorithm=t.algorithm,s.sessionKey=n,s.sessionKeyAlgorithm=i,s}read(e){let t=0;if(this.version=e[t++],3!==this.version&&6!==this.version)throw new Vn(`Version ${this.version} of the PKESK packet is unsupported.`);if(6===this.version){const r=e[t++];if(r){this.publicKeyVersion=e[t++];const n=r-1;this.publicKeyFingerprint=e.subarray(t,t+n),t+=n,this.publicKeyVersion>=5?this.publicKeyID.read(this.publicKeyFingerprint):this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8))}else this.publicKeyID=ha.wildcard()}else t+=this.publicKeyID.read(e.subarray(t,t+8));if(this.publicKeyAlgorithm=e[t++],this.encrypted=os.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t)),this.publicKeyAlgorithm===L.publicKey.x25519||this.publicKeyAlgorithm===L.publicKey.x448)if(3===this.version)this.sessionKeyAlgorithm=L.write(L.symmetric,this.encrypted.C.algorithm);else if(null!==this.encrypted.C.algorithm)throw Error("Unexpected cleartext symmetric algorithm")}write(){const e=[new Uint8Array([this.version])];return 6===this.version?null!==this.publicKeyFingerprint?(e.push(new Uint8Array([this.publicKeyFingerprint.length+1,this.publicKeyVersion])),e.push(this.publicKeyFingerprint)):e.push(new Uint8Array([0])):e.push(this.publicKeyID.write()),e.push(new Uint8Array([this.publicKeyAlgorithm]),os.serializeParams(this.publicKeyAlgorithm,this.encrypted)),N.concatUint8Array(e)}async encrypt(e){const t=L.write(L.publicKey,this.publicKeyAlgorithm),r=3===this.version?this.sessionKeyAlgorithm:null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=xa(this.version,t,r,this.sessionKey);this.encrypted=await os.publicKeyEncrypt(t,r,e.publicParams,i,n)}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?xa(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=await os.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,n,r),{sessionKey:s,sessionKeyAlgorithm:a}=function(e,t,r,n){switch(t){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.elgamal:case L.publicKey.ecdh:{const t=r.subarray(0,r.length-2),i=r.subarray(r.length-2),s=N.writeChecksum(t.subarray(t.length%8)),a=s[0]===i[0]&s[1]===i[1],o=6===e?{sessionKeyAlgorithm:null,sessionKey:t}:{sessionKeyAlgorithm:t[0],sessionKey:t.subarray(1)};if(n){const t=a&o.sessionKeyAlgorithm===n.sessionKeyAlgorithm&o.sessionKey.length===n.sessionKey.length;return{sessionKey:N.selectUint8Array(t,o.sessionKey,n.sessionKey),sessionKeyAlgorithm:6===e?null:N.selectUint8(t,o.sessionKeyAlgorithm,n.sessionKeyAlgorithm)}}if(a&&(6===e||L.read(L.symmetric,o.sessionKeyAlgorithm)))return o;throw Error("Decryption error")}case L.publicKey.x25519:case L.publicKey.x448:return{sessionKeyAlgorithm:null,sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);if(3===this.version){const e=this.publicKeyAlgorithm!==L.publicKey.x25519&&this.publicKeyAlgorithm!==L.publicKey.x448;if(this.sessionKeyAlgorithm=e?a:this.sessionKeyAlgorithm,s.length!==os.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}this.sessionKey=s}}function xa(e,t,r,n){switch(t){case L.publicKey.rsaEncrypt:case L.publicKey.rsaEncryptSign:case L.publicKey.elgamal:case L.publicKey.ecdh:return N.concatUint8Array([new Uint8Array(6===e?[]:[r]),n,N.writeChecksum(n.subarray(n.length%8))]);case L.publicKey.x25519:case L.publicKey.x448:return n;default:throw Error("Unsupported public key algorithm")}}class Qa{static get tag(){return L.packet.symEncryptedSessionKey}constructor(e=T){this.version=e.aeadProtect?6:4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm=null,this.aeadAlgorithm=L.write(L.aead,e.preferredAEADAlgorithm),this.encrypted=null,this.s2k=null,this.iv=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version&&6!==this.version)throw new Vn(`Version ${this.version} of the SKESK packet is unsupported.`);6===this.version&&t++;const r=e[t++];this.version>=5&&(this.aeadAlgorithm=e[t++],6===this.version&&t++);const n=e[t++];if(this.s2k=gs(n),t+=this.s2k.read(e.subarray(t,e.length)),this.version>=5){const r=os.getAEADMode(this.aeadAlgorithm);this.iv=e.subarray(t,t+=r.ivLength)}this.version>=5||t=5){const e=os.getAEADMode(this.aeadAlgorithm),r=new Uint8Array([192|Qa.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),s=6===this.version?await hi(L.hash.sha256,i,new Uint8Array,r,n):i,a=await e(t,s);this.sessionKey=await a.decrypt(this.encrypted,this.iv,r)}else if(null!==this.encrypted){const e=await os.mode.cfb.decrypt(t,i,this.encrypted,new Uint8Array(r));if(this.sessionKeyAlgorithm=L.write(L.symmetric,e[0]),this.sessionKey=e.subarray(1,e.length),this.sessionKey.length!==os.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}else this.sessionKey=i}async encrypt(e,t=T){const r=null!==this.sessionKeyEncryptionAlgorithm?this.sessionKeyEncryptionAlgorithm:this.sessionKeyAlgorithm;this.sessionKeyEncryptionAlgorithm=r,this.s2k=ps(t),this.s2k.generateSalt();const{blockSize:n,keySize:i}=os.getCipherParams(r),s=await this.s2k.produceKey(e,i);if(null===this.sessionKey&&(this.sessionKey=os.generateSessionKey(this.sessionKeyAlgorithm)),this.version>=5){const e=os.getAEADMode(this.aeadAlgorithm);this.iv=os.random.getRandomBytes(e.ivLength);const t=new Uint8Array([192|Qa.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),n=6===this.version?await hi(L.hash.sha256,s,new Uint8Array,t,i):s,a=await e(r,n);this.encrypted=await a.encrypt(this.sessionKey,this.iv,t)}else{const e=N.concatUint8Array([new Uint8Array([this.sessionKeyAlgorithm]),this.sessionKey]);this.encrypted=await os.mode.cfb.encrypt(r,s,e,new Uint8Array(n),t)}}}class Ra{static get tag(){return L.packet.publicKey}constructor(e=new Date,t=T){this.version=t.v6Keys?6:4,this.created=N.normalizeDate(e),this.algorithm=null,this.publicParams=null,this.expirationTimeV3=0,this.fingerprint=null,this.keyID=null}static fromSecretKeyPacket(e){const t=new Ra,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}async read(e,t=T){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new Vn("Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4===this.version||5===this.version||6===this.version){this.created=N.readDate(e.subarray(r,r+4)),r+=4,this.algorithm=e[r++],this.version>=5&&(r+=4);const{read:t,publicParams:n}=os.parsePublicKeyParams(this.algorithm,e.subarray(r));if(6===this.version&&n.oid&&(n.oid.getName()===L.curve.curve25519Legacy||n.oid.getName()===L.curve.ed25519Legacy))throw Error("Legacy curve25519 cannot be used with v6 keys");return this.publicParams=n,r+=t,await this.computeFingerprintAndKeyID(),r}throw new Vn(`Version ${this.version} of the key packet is unsupported.`)}write(){const e=[];e.push(new Uint8Array([this.version])),e.push(N.writeDate(this.created)),e.push(new Uint8Array([this.algorithm]));const t=os.serializeParams(this.algorithm,this.publicParams);return this.version>=5&&e.push(N.writeNumber(t.length,4)),e.push(t),N.concatUint8Array(e)}writeForHash(e){const t=this.writePublicKey(),r=149+e,n=e>=5?4:2;return N.concatUint8Array([new Uint8Array([r]),N.writeNumber(t.length,n),t])}isDecrypted(){return null}getCreationTime(){return this.created}getKeyID(){return this.keyID}async computeFingerprintAndKeyID(){if(await this.computeFingerprint(),this.keyID=new ha,this.version>=5)this.keyID.read(this.fingerprint.subarray(0,8));else{if(4!==this.version)throw Error("Unsupported key version");this.keyID.read(this.fingerprint.subarray(12,20))}}async computeFingerprint(){const e=this.writeForHash(this.version);if(this.version>=5)this.fingerprint=await os.hash.sha256(e);else{if(4!==this.version)throw Error("Unsupported key version");this.fingerprint=await os.hash.sha1(e)}}getFingerprintBytes(){return this.fingerprint}getFingerprint(){return N.uint8ArrayToHex(this.getFingerprintBytes())}hasSameFingerprintAs(e){return this.version===e.version&&N.equalsUint8Array(this.writePublicKey(),e.writePublicKey())}getAlgorithmInfo(){const e={};e.algorithm=L.read(L.publicKey,this.algorithm);const t=this.publicParams.n||this.publicParams.p;return t?e.bits=N.uint8ArrayBitLength(t):this.publicParams.oid&&(e.curve=this.publicParams.oid.getName()),e}}Ra.prototype.readPublicKey=Ra.prototype.read,Ra.prototype.writePublicKey=Ra.prototype.write;const La=/*#__PURE__*/N.constructAllowedPackets([ca,ba,da,fa]);class Ta{static get tag(){return L.packet.symmetricallyEncryptedData}constructor(){this.encrypted=null,this.packets=null}read(e){this.encrypted=e}write(){return this.encrypted}async decrypt(e,t,r=T){if(!r.allowUnauthenticatedMessages)throw Error("Message is not authenticated.");const{blockSize:n}=os.getCipherParams(e),i=await P(I(this.encrypted)),s=await os.mode.cfb.decrypt(e,t,i.subarray(n+2),i.subarray(2,n+2));this.packets=await wa.fromBinary(s,La,r)}async encrypt(e,t,r=T){const n=this.packets.write(),{blockSize:i}=os.getCipherParams(e),s=await os.getPrefixRandom(e),a=await os.mode.cfb.encrypt(e,t,s,new Uint8Array(i),r),o=await os.mode.cfb.encrypt(e,t,n,a.subarray(2),r);this.encrypted=N.concat([a,o])}}class Ma extends Ra{static get tag(){return L.packet.publicSubkey}constructor(e,t){super(e,t)}static fromSecretSubkeyPacket(e){const t=new Ma,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}}class Na{static get tag(){return L.packet.userAttribute}constructor(){this.attributes=[]}read(e){let t=0;for(;t{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function Ha(e,t,r,n,i,s,a){if("argon2"===t.type&&!i)throw Error("Using Argon2 S2K without AEAD is not allowed");if("simple"===t.type&&6===e)throw Error("Using Simple S2K with version 6 keys is not allowed");const{keySize:o}=os.getCipherParams(n),c=await t.produceKey(r,o);if(!i||5===e||a)return c;const h=N.concatUint8Array([s,new Uint8Array([e,n,i])]);return hi(L.hash.sha256,c,new Uint8Array,h,o)}class Oa{static get tag(){return L.packet.userID}constructor(){this.userID="",this.name="",this.email="",this.comment=""}static fromObject(e){if(N.isString(e)||e.name&&!N.isString(e.name)||e.email&&!N.isEmailAddress(e.email)||e.comment&&!N.isString(e.comment))throw Error("Invalid user ID format");const t=new Oa;Object.assign(t,e);const r=[];return t.name&&r.push(t.name),t.comment&&r.push(`(${t.comment})`),t.email&&r.push(`<${t.email}>`),t.userID=r.join(" "),t}read(e,t=T){const r=N.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");const n=/^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/.exec(r);if(null!==n){const{name:e,comment:t,email:r}=n.groups;this.comment=t?.replace(/^\(|\)|\s$/g,"").trim()||"",this.name=e?.trim()||"",this.email=r.substring(1,r.length-1)}else/^[^\s@]+@[^\s@]+$/.test(r)&&(this.email=r);this.userID=r}write(){return N.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class za extends Fa{static get tag(){return L.packet.secretSubkey}constructor(e=new Date,t=T){super(e,t)}}const _a=/*#__PURE__*/N.constructAllowedPackets([fa]);class Ga{constructor(e){this.packets=e||new wa}write(){return this.packets.write()}armor(e=T){const t=this.packets.some((e=>e.constructor.tag===fa.tag&&6!==e.version));return ee(L.armor.signature,this.write(),void 0,void 0,void 0,t,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function ja(e,t){const r=new za(e.date,t);return r.packets=null,r.algorithm=L.write(L.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function qa(e,t){const r=new Fa(e.date,t);return r.packets=null,r.algorithm=L.write(L.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Va(e,t,r,n,i=new Date,s){let a,o;for(let c=e.length-1;c>=0;c--)try{(!a||e[c].created>=a.created)&&(await e[c].verify(t,r,n,i,void 0,s),a=e[c])}catch(e){o=e}if(!a)throw N.wrapError(`Could not find valid ${L.read(L.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return a}function Ja(e,t,r=new Date){const n=N.normalizeDate(r);if(null!==n){const r=Xa(e,t);return!(e.created<=n&&n0&&(s.keyExpirationTime=r.keyExpirationTime,s.keyNeverExpires=!1);return await Wa(i,[],t,s,r.date,void 0,void 0,void 0,n)}async function Wa(e,t,r,n,i,s,a=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const h=new fa;return Object.assign(h,n),h.publicKeyAlgorithm=r.algorithm,h.hashAlgorithm=await async function(e,t,r=new Date,n=[],i){const s=L.hash.sha256,a=i.preferredHashAlgorithm,o=await Promise.all(e.map((async(e,t)=>(await e.getPrimarySelfSignature(r,n[t],i)).preferredHashAlgorithms))),c=new Map;for(const e of o)for(const t of e)try{const e=L.write(L.hash,t);c.set(e,c.has(e)?c.get(e)+1:1)}catch{}const h=t=>0===e.length||c.get(t)===e.length||t===s,u=()=>{if(0===c.size)return s;const e=Array.from(c.keys()).filter((e=>h(e))).sort(((e,t)=>os.hash.getHashByteLength(e)-os.hash.getHashByteLength(t)))[0];return os.hash.getHashByteLength(e)>=os.hash.getHashByteLength(s)?e:s};if(new Set([L.publicKey.ecdsa,L.publicKey.eddsaLegacy,L.publicKey.ed25519,L.publicKey.ed448]).has(t.algorithm)){const e=os.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid),r=h(a),n=os.hash.getHashByteLength(a)>=os.hash.getHashByteLength(e);if(r&&n)return a;{const t=u();return os.hash.getHashByteLength(t)>=os.hash.getHashByteLength(e)?t:e}}return h(a)?a:u()}(t,r,i,s,c),h.rawNotations=[...a],await h.sign(r,e,i,o,c),h}async function Za(e,t,r,n=new Date,i){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(n)||i&&!await i(e)||t[r].some((function(t){return N.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function $a(e,t,r,n,i,s,a=new Date,o){s=s||e;const c=[];return await Promise.all(n.map((async function(e){try{if(!i||e.issuerKeyID.equals(i.issuerKeyID)){const n=![L.reasonForRevocation.keyRetired,L.reasonForRevocation.keySuperseded,L.reasonForRevocation.userIDInvalid].includes(e.reasonForRevocationFlag);await e.verify(s,t,r,n?null:a,!1,o),c.push(e.issuerKeyID)}}catch(e){}}))),i?(i.revoked=!!c.some((e=>e.equals(i.issuerKeyID)))||(i.revoked||!1),i.revoked):c.length>0}function Xa(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function eo(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=N.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=L.write(L.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==L.curve.ed25519Legacy&&e.curve!==L.curve.curve25519Legacy&&"ed25519"!==e.curve&&"curve25519"!==e.curve||(e.curve=e.sign?L.curve.ed25519Legacy:L.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===L.curve.ed25519Legacy?L.publicKey.eddsaLegacy:L.publicKey.ecdsa:e.algorithm=L.publicKey.ecdh;break;case"curve25519":e.algorithm=e.sign?L.publicKey.ed25519:L.publicKey.x25519;break;case"curve448":e.algorithm=e.sign?L.publicKey.ed448:L.publicKey.x448;break;case"rsa":e.algorithm=L.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function to(e,t,r){switch(e.algorithm){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:case L.publicKey.dsa:case L.publicKey.ecdsa:case L.publicKey.eddsaLegacy:case L.publicKey.ed25519:case L.publicKey.ed448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&L.keyFlags.signData);default:return!1}}function ro(e,t,r){switch(e.algorithm){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:case L.publicKey.elgamal:case L.publicKey.ecdh:case L.publicKey.x25519:case L.publicKey.x448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&L.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&L.keyFlags.encryptStorage);default:return!1}}function no(e,t,r){if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");switch(e.algorithm){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaEncrypt:case L.publicKey.elgamal:case L.publicKey.ecdh:case L.publicKey.x25519:case L.publicKey.x448:return!(!(!t.keyFlags||!!(t.keyFlags[0]&L.keyFlags.signData))||!r.allowInsecureDecryptionWithSigningKeys)||(!t.keyFlags||!!(t.keyFlags[0]&L.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&L.keyFlags.encryptStorage));default:return!1}}function io(e,t){const r=L.write(L.publicKey,e.algorithm),n=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(n.algorithm+" keys are considered too weak.");switch(r){case L.publicKey.rsaEncryptSign:case L.publicKey.rsaSign:case L.publicKey.rsaEncrypt:if(n.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const s=await t.getSigningKey(o,e.created,void 0,n);if(e.revoked||await i.isRevoked(e,s.keyPacket,r,n))throw Error("User certificate is revoked");try{await e.verify(s.keyPacket,L.signature.certGeneric,a,r,void 0,n)}catch(e){throw N.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const n=this,i=this.selfCertifications.concat(this.otherCertifications);return Promise.all(i.map((async i=>({keyID:i.issuerKeyID,valid:await n.verifyCertificate(i,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};let s;for(let a=this.selfCertifications.length-1;a>=0;a--)try{const s=this.selfCertifications[a];if(s.revoked||await r.isRevoked(s,void 0,e,t))throw Error("Self-certification is revoked");try{await s.verify(n,L.signature.certGeneric,i,e,void 0,t)}catch(e){throw N.wrapError("Self-certification is invalid",e)}return!0}catch(e){s=e}throw s}async update(e,t,r){const n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};await Za(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(n,L.signature.certGeneric,i,t,!1,r),!0}catch(e){return!1}})),await Za(e,this,"otherCertifications",t),await Za(e,this,"revocationSignatures",t,(function(e){return $a(n,L.signature.certRevocation,i,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=L.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=T){const s={userID:this.userID,userAttribute:this.userAttribute,key:e},a=new so(s.userID||s.userAttribute,this.mainKey);return a.revocationSignatures.push(await Wa(s,[],e,{signatureType:L.signature.certRevocation,reasonForRevocationFlag:L.write(L.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}}class ao{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new wa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new ao(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,n=T){const i=this.mainKey.keyPacket;return $a(i,L.signature.subkeyRevocation,{key:i,bind:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verify(e=new Date,t=T){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket},i=await Va(this.bindingSignatures,r,L.signature.subkeyBinding,n,e,t);if(i.revoked||await this.isRevoked(i,null,e,t))throw Error("Subkey is revoked");if(Ja(this.keyPacket,i,e))throw Error("Subkey is expired");return i}async getExpirationTime(e=new Date,t=T){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket};let i;try{i=await Va(this.bindingSignatures,r,L.signature.subkeyBinding,n,e,t)}catch(e){return null}const s=Xa(this.keyPacket,i),a=i.getExpirationTime();return si.bindingSignatures[t].created&&(i.bindingSignatures[t]=e),!1;try{return await e.verify(n,L.signature.subkeyBinding,s,t,void 0,r),!0}catch(e){return!1}})),await Za(e,this,"revocationSignatures",t,(function(e){return $a(n,L.signature.subkeyRevocation,s,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=L.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=T){const s={key:e,bind:this.keyPacket},a=new ao(this.keyPacket,this.mainKey);return a.revocationSignatures.push(await Wa(s,[],e,{signatureType:L.signature.subkeyRevocation,reasonForRevocationFlag:L.write(L.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{ao.prototype[e]=function(){return this.keyPacket[e]()}}));const oo=/*#__PURE__*/N.constructAllowedPackets([fa]),co=new Set([L.packet.publicKey,L.packet.privateKey]),ho=new Set([L.packet.publicKey,L.packet.privateKey,L.packet.publicSubkey,L.packet.privateSubkey]);class uo{packetListToStructure(e,t=new Set){let r,n,i,s;for(const a of e){if(a instanceof Yn){ho.has(a.tag)&&!s&&(s=co.has(a.tag)?co:ho);continue}const e=a.constructor.tag;if(s){if(!s.has(e))continue;s=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case L.packet.publicKey:case L.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=a,n=this.getKeyID(),!n)throw Error("Missing Key ID");break;case L.packet.userID:case L.packet.userAttribute:r=new so(a,this),this.users.push(r);break;case L.packet.publicSubkey:case L.packet.secretSubkey:r=null,i=new ao(a,this),this.subkeys.push(i);break;case L.packet.signature:switch(a.signatureType){case L.signature.certGeneric:case L.signature.certPersona:case L.signature.certCasual:case L.signature.certPositive:if(!r){N.printDebug("Dropping certification signatures without preceding user packet");continue}a.issuerKeyID.equals(n)?r.selfCertifications.push(a):r.otherCertifications.push(a);break;case L.signature.certRevocation:r?r.revocationSignatures.push(a):this.directSignatures.push(a);break;case L.signature.key:this.directSignatures.push(a);break;case L.signature.subkeyBinding:if(!i){N.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}i.bindingSignatures.push(a);break;case L.signature.keyRevocation:this.revocationSignatures.push(a);break;case L.signature.subkeyRevocation:if(!i){N.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}i.revocationSignatures.push(a)}}}}toPacketList(){const e=new wa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},n=T){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{io(i,n)}catch(e){throw N.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Va(r.bindingSignatures,i,L.signature.subkeyBinding,e,t,n);if(!to(r.keyPacket,s,n))continue;if(!s.embeddedSignature)throw Error("Missing embedded signature");return await Va([s.embeddedSignature],r.keyPacket,L.signature.keyBinding,e,t,n),io(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&to(i,s,n))return io(i,n),this}catch(e){a=e}throw N.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),a)}async getEncryptionKey(e,t=new Date,r={},n=T){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{io(i,n)}catch(e){throw N.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Va(r.bindingSignatures,i,L.signature.subkeyBinding,e,t,n);if(ro(r.keyPacket,s,n))return io(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&ro(i,s,n))return io(i,n),this}catch(e){a=e}throw N.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),a)}async isRevoked(e,t,r=new Date,n=T){return $a(this.keyPacket,L.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verifyPrimaryKey(e=new Date,t={},r=T){const n=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");if(Ja(n,await this.getPrimarySelfSignature(e,t,r),e))throw Error("Primary key is expired");if(6!==n.version){const t=await Va(this.directSignatures,n,L.signature.key,{key:n},e,r).catch((()=>{}));if(t&&Ja(n,t,e))throw Error("Primary key is expired")}}async getExpirationTime(e,t=T){let r;try{const n=await this.getPrimarySelfSignature(null,e,t),i=Xa(this.keyPacket,n),s=n.getExpirationTime(),a=6!==this.keyPacket.version&&await Va(this.directSignatures,this.keyPacket,L.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(a){const e=Xa(this.keyPacket,a);r=Math.min(i,s,e)}else r=ie.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const n=this.clone();return await Za(e,n,"revocationSignatures",t,(i=>$a(n.keyPacket,L.signature.keyRevocation,n,[i],null,e.keyPacket,t,r))),await Za(e,n,"directSignatures",t),await Promise.all(e.users.map((async e=>{const i=n.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const i=n.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.subkeys.push(t)}}))),n}async getRevocationCertificate(e=new Date,t=T){const r={key:this.keyPacket},n=await Va(this.revocationSignatures,this.keyPacket,L.signature.keyRevocation,r,e,t),i=new wa;i.push(n);const s=6!==this.keyPacket.version;return ee(L.armor.publicKey,i.write(),null,null,"This is a revocation certificate",s,t)}async applyRevocationCertificate(e,t=new Date,r=T){const n=await X(e),i=(await wa.fromBinary(n.data,oo,r)).findPacket(L.packet.signature);if(!i||i.signatureType!==L.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!i.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await i.verify(this.keyPacket,L.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw N.wrapError("Could not verify revocation signature",e)}const s=this.clone();return s.revocationSignatures.push(i),s}async signPrimaryUser(e,t,r,n=T){const{index:i,user:s}=await this.getPrimaryUser(t,r,n),a=await s.certify(e,t,n),o=this.clone();return o.users[i]=a,o}async signAllUsers(e,t=new Date,r=T){const n=this.clone();return n.users=await Promise.all(this.users.map((function(n){return n.certify(e,t,r)}))),n}async verifyPrimaryUser(e,t=new Date,r,n=T){const i=this.keyPacket,{user:s}=await this.getPrimaryUser(t,r,n);return e?await s.verifyAllCertifications(e,t,n):[{keyID:i.getKeyID(),valid:await s.verify(t,n).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=T){const n=this.keyPacket,i=[];return await Promise.all(this.users.map((async s=>{const a=e?await s.verifyAllCertifications(e,t,r):[{keyID:n.getKeyID(),valid:await s.verify(t,r).catch((()=>!1))}];i.push(...a.map((e=>({userID:s.userID?s.userID.userID:null,userAttribute:s.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),i}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{uo.prototype[e]=ao.prototype[e]}));class lo extends uo{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([L.packet.secretKey,L.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=T){const t=6!==this.keyPacket.version;return ee(L.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}}class yo extends lo{constructor(e){if(super(),this.packetListToStructure(e,new Set([L.packet.publicKey,L.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new wa,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case L.packet.secretKey:{const t=Ra.fromSecretKeyPacket(r);e.push(t);break}case L.packet.secretSubkey:{const t=Ma.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new lo(e)}armor(e=T){const t=6!==this.keyPacket.version;return ee(L.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}async getDecryptionKeys(e,t=new Date,r={},n=T){const i=this.keyPacket,s=[];let a=null;for(let r=0;re.isDecrypted()))}async validate(e=T){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=L.reasonForRevocation.noReason,string:t=""}={},r=new Date,n=T){if(!this.isPrivate())throw Error("Need private key for revoking");const i={key:this.keyPacket},s=this.clone();return s.revocationSignatures.push(await Wa(i,[],this.keyPacket,{signatureType:L.signature.keyRevocation,reasonForRevocationFlag:L.write(L.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,n)),s}async addSubkey(e={}){const t={...T,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}function a(){const e={};e.keyFlags=[L.keyFlags.certifyKeys|L.keyFlags.signData];const t=s([L.symmetric.aes256,L.symmetric.aes128],n.preferredSymmetricAlgorithm);if(e.preferredSymmetricAlgorithms=t,n.aeadProtect){const r=s([L.aead.gcm,L.aead.eax,L.aead.ocb],n.preferredAEADAlgorithm);e.preferredCipherSuites=r.flatMap((e=>t.map((t=>[t,e]))))}return e.preferredHashAlgorithms=s([L.hash.sha256,L.hash.sha512,L.hash.sha3_256,L.hash.sha3_512],n.preferredHashAlgorithm),e.preferredCompressionAlgorithms=s([L.compression.uncompressed,L.compression.zlib,L.compression.zip],n.preferredCompressionAlgorithm),e.features=[0],e.features[0]|=L.features.modificationDetection,n.aeadProtect&&(e.features[0]|=L.features.seipdv2),r.keyExpirationTime>0&&(e.keyExpirationTime=r.keyExpirationTime,e.keyNeverExpires=!1),e}if(i.push(e),6===e.version){const t={key:e},s=a();s.signatureType=L.signature.key;const o=await Wa(t,[],e,s,r.date,void 0,void 0,void 0,n);i.push(o)}await Promise.all(r.userIDs.map((async function(t,i){const s=Oa.fromObject(t),o={userID:s,key:e},c=6!==e.version?a():{};c.signatureType=L.signature.certPositive,0===i&&(c.isPrimaryUserID=!0);return{userIDPacket:s,signaturePacket:await Wa(o,[],e,c,r.date,void 0,void 0,void 0,n)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{i.push(e),i.push(t)}))})),await Promise.all(t.map((async function(t,i){const s=r.subkeys[i];return{secretSubkeyPacket:t,subkeySignaturePacket:await Ya(t,e,s,n)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{i.push(e),i.push(t)}))}));const o={key:e};return i.push(await Wa(o,[],e,{signatureType:L.signature.keyRevocation,reasonForRevocationFlag:L.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,n)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new yo(i)}const Ao=/*#__PURE__*/N.constructAllowedPackets([ca,ba,Da,Ka,Ta,Ua,Qa,da,fa]),wo=/*#__PURE__*/N.constructAllowedPackets([Qa]),mo=/*#__PURE__*/N.constructAllowedPackets([fa]);class bo{constructor(e){this.packets=e||new wa}getEncryptionKeyIDs(){const e=[];return this.packets.filterByTag(L.packet.publicKeyEncryptedSessionKey).forEach((function(t){e.push(t.publicKeyID)})),e}getSigningKeyIDs(){const e=this.unwrapCompressed(),t=e.packets.filterByTag(L.packet.onePassSignature);if(t.length>0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(L.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,n=new Date,i=T){const s=this.packets.filterByTag(L.packet.symmetricallyEncryptedData,L.packet.symEncryptedIntegrityProtectedData,L.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const a=s[0],o=a.cipherAlgorithm,c=r||await this.decryptSessionKeys(e,t,o,n,i);let h=null;const u=Promise.all(c.map((async({algorithm:e,data:t})=>{if(!N.isUint8Array(t)||!a.cipherAlgorithm&&!N.isString(e))throw Error("Invalid session key for decryption.");try{const r=a.cipherAlgorithm||L.write(L.symmetric,e);await a.decrypt(r,t,i)}catch(e){N.printDebugError(e),h=e}})));if(D(a.encrypted),a.encrypted=null,await u,!a.packets||!a.packets.length)throw h||Error("Decryption failed.");const l=new bo(a.packets);return a.packets=new wa,l}async decryptSessionKeys(e,t,r,n=new Date,i=T){let s,a=[];if(t){const e=this.packets.filterByTag(L.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await wa.fromBinary(e.write(),wo,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){N.printDebugError(e),e instanceof cs&&(s=e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(L.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let o;try{o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket))}catch(e){return void(s=e)}let c=[L.symmetric.aes256,L.symmetric.aes128,L.symmetric.tripledes,L.symmetric.cast5];try{const t=await e.getPrimarySelfSignature(n,void 0,i);t.preferredSymmetricAlgorithms&&(c=c.concat(t.preferredSymmetricAlgorithms))}catch(e){}await Promise.all(o.map((async function(e){if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===L.publicKey.rsaEncrypt||t.publicKeyAlgorithm===L.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===L.publicKey.rsaSign||t.publicKeyAlgorithm===L.publicKey.elgamal)){const n=t.write();await Promise.all((r?[r]:Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map((async t=>{const r=new Ua;r.read(n);const i={sessionKeyAlgorithm:t,sessionKey:os.generateSessionKey(t)};try{await r.decrypt(e,i),a.push(r)}catch(e){N.printDebugError(e),s=e}})))}else try{await t.decrypt(e);const n=r||t.sessionKeyAlgorithm;if(n&&!c.includes(L.write(L.symmetric,n)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){N.printDebugError(e),s=e}})))}))),D(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+N.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:e.sessionKeyAlgorithm&&L.read(L.symmetric,e.sessionKeyAlgorithm)})))}throw s||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(L.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(L.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(L.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],n=T){const{symmetricAlgo:i,aeadAlgo:s}=await async function(e=[],t=new Date,r=[],n=T){const i=await Promise.all(e.map(((e,i)=>e.getPrimarySelfSignature(t,r[i],n))));if(e.length?i.every((e=>e.features&&e.features[0]&L.features.seipdv2)):n.aeadProtect){const e={symmetricAlgo:L.symmetric.aes128,aeadAlgo:L.aead.ocb},t=[{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:n.preferredAEADAlgorithm},{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:L.aead.ocb},{symmetricAlgo:L.symmetric.aes128,aeadAlgo:n.preferredAEADAlgorithm}];for(const e of t)if(i.every((t=>t.preferredCipherSuites&&t.preferredCipherSuites.some((t=>t[0]===e.symmetricAlgo&&t[1]===e.aeadAlgo)))))return e;return e}const s=L.symmetric.aes128,a=n.preferredSymmetricAlgorithm;return{symmetricAlgo:i.every((e=>e.preferredSymmetricAlgorithms&&e.preferredSymmetricAlgorithms.includes(a)))?a:s,aeadAlgo:void 0}}(e,t,r,n),a=L.read(L.symmetric,i),o=s?L.read(L.aead,s):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&(e.keyPacket.algorithm===L.publicKey.x25519||e.keyPacket.algorithm===L.publicKey.x448)&&!o&&!N.isAES(i))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:os.generateSessionKey(i),algorithm:a,aeadAlgorithm:o}}async encrypt(e,t,r,n=!1,i=[],s=new Date,a=[],o=T){if(r){if(!N.isUint8Array(r.data)||!N.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await bo.generateSessionKey(e,s,a,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await bo.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:h,aeadAlgorithm:u}=r,l=await bo.encryptSessionKey(c,h,u,e,t,n,i,s,a,o),y=Ka.fromObject({version:u?2:1,aeadAlgorithm:u?L.write(L.aead,u):null});y.packets=this.packets;const f=L.write(L.symmetric,h);return await y.encrypt(f,c,o),l.packets.push(y),y.packets=new wa,l}static async encryptSessionKey(e,t,r,n,i,s=!1,a=[],o=new Date,c=[],h=T){const u=new wa,l=L.write(L.symmetric,t),y=r&&L.write(L.aead,r);if(n){const t=await Promise.all(n.map((async function(t,r){const n=await t.getEncryptionKey(a[r],o,c,h),i=Ua.fromObject({version:y?6:3,encryptionKeyPacket:n.keyPacket,anonymousRecipient:s,sessionKey:e,sessionKeyAlgorithm:l});return await i.encrypt(n.keyPacket),delete i.sessionKey,i})));u.push(...t)}if(i){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,n=async function(e,s,a,o){const c=new Qa(h);if(c.sessionKey=e,c.sessionKeyAlgorithm=s,a&&(c.aeadAlgorithm=a),await c.encrypt(o,h),h.passwordCollisionCheck){if(1!==(await Promise.all(i.map((e=>t(c,e))))).reduce(r))return n(e,s,o)}return delete c.sessionKey,c},s=await Promise.all(i.map((t=>n(e,l,y,t))));u.push(...s)}return new bo(u)}async sign(e=[],t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=T){const h=new wa,u=this.packets.findPacket(L.packet.literalData);if(!u)throw Error("No literal data packet to sign.");const l=await ko(u,e,t,r,n,i,s,a,o,!1,c),y=l.map(((e,t)=>da.fromSignaturePacket(e,0===t))).reverse();return h.push(...y),h.push(u),h.push(...l),new bo(h)}compress(e,t=T){if(e===L.compression.uncompressed)return this;const r=new ba(t);r.algorithm=e,r.packets=this.packets;const n=new wa;return n.push(r),new bo(n)}async signDetached(e=[],t=[],r=null,n=[],i=[],s=new Date,a=[],o=[],c=T){const h=this.packets.findPacket(L.packet.literalData);if(!h)throw Error("No literal data packet to sign.");return new Ga(await ko(h,e,t,r,n,i,s,a,o,!0,c))}async verify(e,t=new Date,r=T){const n=this.unwrapCompressed(),i=n.packets.filterByTag(L.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");c(n.packets.stream)&&n.packets.push(...await P(n.packets.stream,(e=>e||[])));const s=n.packets.filterByTag(L.packet.onePassSignature).reverse(),a=n.packets.filterByTag(L.packet.signature);return s.length&&!a.length&&N.isStream(n.packets.stream)&&!c(n.packets.stream)?(await Promise.all(s.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=U((async()=>(await e.correspondingSig).signatureData)),e.hashed=P(await e.hash(e.signatureType,i[0],void 0,!1)),e.hashed.catch((()=>{}))}))),n.packets.stream=v(n.packets.stream,(async(e,t)=>{const r=x(e),n=Q(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await n.abort(e)}})),Eo(s,i,e,t,!1,r)):Eo(a,i,e,t,!1,r)}verifyDetached(e,t,r=new Date,n=T){const i=this.unwrapCompressed().packets.filterByTag(L.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");return Eo(e.packets.filterByTag(L.packet.signature),i,t,r,!0,n)}unwrapCompressed(){const e=this.packets.filterByTag(L.packet.compressedData);return e.length?new bo(e[0].packets):this}async appendSignature(e,t=T){await this.packets.read(N.isUint8Array(e)?e:(await X(e)).data,mo,t)}write(){return this.packets.write()}armor(e=T){const t=this.packets[this.packets.length-1],r=t.constructor.tag===Ka.tag?2!==t.version:this.packets.some((e=>e.constructor.tag===fa.tag&&6!==e.version));return ee(L.armor.message,this.write(),null,null,null,r,e)}}async function ko(e,t,r=[],n=null,i=[],s=new Date,a=[],o=[],c=[],h=!1,u=T){const l=new wa,y=null===e.text?L.signature.binary:L.signature.text;if(await Promise.all(t.map((async(t,n)=>{const l=a[n];if(!t.isPrivate())throw Error("Need private key for signing");const f=await t.getSigningKey(i[n],s,l,u);return Wa(e,r.length?r:[t],f.keyPacket,{signatureType:y},s,o,c,h,u)}))).then((e=>{l.push(...e)})),n){const e=n.packets.filterByTag(L.packet.signature);l.push(...e)}return l}async function Eo(e,t,r,n=new Date,i=!1,s=T){return Promise.all(e.filter((function(e){return["text","binary"].includes(L.read(L.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,n=new Date,i=!1,s=T){let a,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){a=t,o=r[0];break}}const c=e instanceof da?e.correspondingSig:e,h={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],n,i,s);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await a.getSigningKey(o.getKeyID(),r.created,void 0,s)}catch(e){if(!s.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await a.getSigningKey(o.getKeyID(),n,void 0,s)}return!0})(),signature:(async()=>{const e=await c,t=new wa;return e&&t.push(e),new Ga(t)})()};return h.signature.catch((()=>{})),h.verified.catch((()=>{})),h}(e,t,r,n,i,s)})))}const vo=/*#__PURE__*/N.constructAllowedPackets([fa]);class Bo{constructor(e,t){if(this.text=N.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof Ga))throw Error("Invalid signature input");this.signature=t||new Ga(new wa)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=T){const h=new ca;h.setText(this.text);const u=new Ga(await ko(h,e,t,r,n,i,s,a,o,!0,c));return new Bo(this.text,u)}verify(e,t=new Date,r=T){const n=this.signature.packets.filterByTag(L.packet.signature),i=new ca;return i.setText(this.text),Eo(n,[i],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=T){const t=this.signature.packets.some((e=>6!==e.version)),r={hash:t?Array.from(new Set(this.signature.packets.map((e=>L.read(L.hash,e.hashAlgorithm).toUpperCase())))).join():null,text:this.text,data:this.signature.packets.write()};return ee(L.armor.signed,r,void 0,void 0,void 0,t,e)}}function Io(e){if(!(e instanceof bo))throw Error("Parameter [message] needs to be of type Message")}function So(e){if(!(e instanceof Bo||e instanceof bo))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Ko(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Co=Object.keys(T).length;function Po(e){const t=Object.keys(e);if(t.length!==Co)for(const e of t)if(void 0===T[e])throw Error("Unknown config property: "+e)}function Do(e){return e&&!N.isArray(e)&&(e=[e]),e}async function Uo(e){return"array"===N.isStream(e)?P(e):e}function xo(e,t){e.data=v(t.packets.stream,(async(t,r)=>{await m(e.data,r,{preventClose:!0});const n=Q(r);try{await P(t,(e=>e)),await n.close()}catch(e){await n.abort(e)}}))}function Qo(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}function Ro(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, not "+e)}function Lo(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function To(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Mo(e,t){Lo(e);const r=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),Ho=(e,t)=>e<<32-t|e>>>t,Oo=(e,t)=>e<>>32-t>>>0,zo=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function _o(e){for(let r=0;r>>8&65280|t>>>24&255;var t}function Go(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function jo(e){return"string"==typeof e&&(e=Go(e)),Lo(e),e}function qo(...e){let t=0;for(let r=0;re().update(jo(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Yo(e=32){if(No&&"function"==typeof No.getRandomValues)return No.getRandomValues(new Uint8Array(e));if(No&&"function"==typeof No.randomBytes)return No.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}const Wo=(e,t,r)=>e&t^~e&r,Zo=(e,t,r)=>e&t^e&r^t&r;class $o extends Vo{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Fo(this.buffer)}update(e){To(this);const{view:t,buffer:r,blockLen:n}=this,i=(e=jo(e)).length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let e=s;e>i&s),o=Number(r&s),c=n?4:0,h=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+h,o,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const a=Fo(e),o=this.outputLen;if(o%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=Ho(r,17)^Ho(r,19)^r>>>10;tc[e]=i+tc[e-7]+n+tc[e-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(Ho(a,6)^Ho(a,11)^Ho(a,25))+Wo(a,o,c)+Xo[e]+tc[e]|0,u=(Ho(r,2)^Ho(r,13)^Ho(r,22))+Zo(r,n,i)|0;h=c,c=o,o=a,a=s+t|0,s=i,i=n,n=r,r=t+u|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(r,n,i,s,a,o,c,h)}roundClean(){tc.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class nc extends rc{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const ic=/* @__PURE__ */Jo((()=>new rc)),sc=/* @__PURE__ */Jo((()=>new nc));class ac extends Vo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.wrapConstructor");Ro(e.outputLen),Ro(e.blockLen)}(e);const r=jo(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew ac(e,t).update(r).digest();oc.create=(e,t)=>new ac(e,t) +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const cc=/* @__PURE__ */BigInt(0),hc=/* @__PURE__ */BigInt(1),uc=/* @__PURE__ */BigInt(2);function lc(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function yc(e){if(!lc(e))throw Error("Uint8Array expected")}function fc(e,t){if("boolean"!=typeof t)throw Error(`${e} must be valid boolean, got "${t}".`)}const gc=/* @__PURE__ */Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function pc(e){yc(e);let t="";for(let r=0;r=wc._0&&e<=wc._9?e-wc._0:e>=wc._A&&e<=wc._F?e-(wc._A-10):e>=wc._a&&e<=wc._f?e-(wc._a-10):void 0}function bc(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t"bigint"==typeof e&&cc<=e;function Cc(e,t,r){return Kc(e)&&Kc(t)&&Kc(r)&&t<=e&&ecc;e>>=hc,t+=1);return t}const Uc=e=>(uc<new Uint8Array(e),Qc=e=>Uint8Array.from(e);function Rc(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");let n=xc(e),i=xc(e),s=0;const a=()=>{n.fill(1),i.fill(0),s=0},o=(...e)=>r(i,n,...e),c=(e=xc())=>{i=o(Qc([0]),e),n=o(),0!==e.length&&(i=o(Qc([1]),e),n=o())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(a(),c(e);!(r=t(h()));)c();return a(),r}}const Lc={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||lc(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Tc(e,t,r={}){const n=(t,r,n)=>{const i=Lc[r];if("function"!=typeof i)throw Error(`Invalid validator "${r}", expected function`);const s=e[t];if(!(n&&void 0===s||i(s,e)))throw Error(`Invalid param ${t+""}=${s} (${typeof s}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function Mc(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}var Nc=/*#__PURE__*/Object.freeze({__proto__:null,aInRange:Pc,abool:fc,abytes:yc,bitGet:function(e,t){return e>>BigInt(t)&hc},bitLen:Dc,bitMask:Uc,bitSet:function(e,t,r){return e|(r?hc:cc)<{throw Error("not implemented")},numberToBytesBE:vc,numberToBytesLE:Bc,numberToHexUnpadded:dc,numberToVarBytesBE:function(e){return bc(dc(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:Tc}); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Fc=BigInt(0),Hc=BigInt(1),Oc=BigInt(2),zc=BigInt(3),_c=BigInt(4),Gc=BigInt(5),jc=BigInt(8);function qc(e,t){const r=e%t;return r>=Fc?r:t+r}function Vc(e,t,r){if(r<=Fc||t 0");if(r===Hc)return Fc;let n=Hc;for(;t>Fc;)t&Hc&&(n=n*e%r),e=e*e%r,t>>=Hc;return n}function Jc(e,t,r){let n=e;for(;t-- >Fc;)n*=n,n%=r;return n}function Yc(e,t){if(e===Fc||t<=Fc)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=qc(e,t),n=t,i=Fc,s=Hc;for(;r!==Fc;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==Hc)throw Error("invert: does not exist");return qc(i,t)}function Wc(e){if(e%_c===zc){const t=(e+Hc)/_c;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}if(e%jc===Gc){const t=(e-Gc)/jc;return function(e,r){const n=e.mul(r,Oc),i=e.pow(n,t),s=e.mul(r,i),a=e.mul(e.mul(s,Oc),i),o=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),r))throw Error("Cannot find square root");return o}}return function(e){const t=(e-Hc)/Oc;let r,n,i;for(r=e-Hc,n=0;r%Oc===Fc;r/=Oc,n++);for(i=Oc;i 0, got "+e);const{nBitLength:i,nByteLength:s}=$c(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const a=Wc(e),o=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:Uc(i),ZERO:Fc,ONE:Hc,create:t=>qc(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("Invalid field element: expected bigint, got "+typeof t);return Fc<=t&&te===Fc,isOdd:e=>(e&Hc)===Hc,neg:t=>qc(-t,e),eql:(e,t)=>e===t,sqr:t=>qc(t*t,e),add:(t,r)=>qc(t+r,e),sub:(t,r)=>qc(t-r,e),mul:(t,r)=>qc(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===Fc)return e.ONE;if(r===Hc)return t;let n=e.ONE,i=t;for(;r>Fc;)r&Hc&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Hc;return n}(o,e,t),div:(t,r)=>qc(t*Yc(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Yc(t,e),sqrt:n.sqrt||(e=>a(o,e)),invertBatch:e=>function(e,t){const r=Array(t.length),n=t.reduce(((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n))),e.ONE),i=e.inv(n);return t.reduceRight(((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n))),i),r}(o,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Bc(e,s):vc(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?Ec(e):kc(e)}});return Object.freeze(o)}function eh(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function th(e){const t=eh(e);return t+Math.ceil(t/2)} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const rh=BigInt(0),nh=BigInt(1),ih=new WeakMap,sh=new WeakMap;function ah(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`Wrong window size=${e}, should be [1..${t}]`)},i=e=>{n(e);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}};return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,i=t;for(;r>rh;)r&nh&&(n=n.add(i)),i=i.double(),r>>=nh;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=i(t),s=[];let a=e,o=a;for(let e=0;e>=y,i>o&&(i-=l,s+=nh);const a=t,f=t+Math.abs(i)-1,g=e%2!=0,p=i<0;0===i?h=h.add(r(g,n[a])):c=c.add(r(p,n[f]))}return{p:c,f:h}},wNAFCached(e,t,r){const n=sh.get(e)||1;let i=ih.get(e);return i||(i=this.precomputeWindow(e,n),1!==n&&ih.set(e,r(i))),this.wNAF(n,i,t)},setWindowSize(e,t){n(t),sh.set(e,t),ih.delete(e)}}}function oh(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw Error("wrong scalar at index "+r)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw Error("wrong point at index "+r)}));const i=Dc(BigInt(r.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<=0;t-=s){o.fill(e.ZERO);for(let e=0;e>BigInt(t)&BigInt(a));o[s]=o[s].add(r[e])}let i=e.ZERO;for(let t=o.length-1,r=e.ZERO;t>0;t--)r=r.add(o[t]),i=i.add(r);if(h=h.add(i),0!==t)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Tc(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$c(e.n,e.nBitLength),...e,p:e.Fp.ORDER})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hh(e){void 0!==e.lowS&&fc("lowS",e.lowS),void 0!==e.prehash&&fc("prehash",e.prehash)}const{bytesToNumberBE:uh,hexToBytes:lh}=Nc,yh={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=yh;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=dc(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?dc(i.length/2|128):"";return`${dc(e)}${s}${i}${t}`},decode(e,t){const{Err:r}=yh;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let s=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const a=t.subarray(n,n+e);if(a.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=yh;if(e{const i=t.toAffine();return Sc(Uint8Array.from([4]),r.toBytes(i.x),r.toBytes(i.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function a(e){const{a:n,b:i}=t,s=r.sqr(e),a=r.mul(s,e);return r.add(r.add(a,r.mul(e,n)),i)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:i,n:s}=t;if(r&&"bigint"!=typeof e){if(lc(e)&&(e=pc(e)),"string"!=typeof e||!r.includes(e.length))throw Error("Invalid key");e=e.padStart(2*n,"0")}let a;try{a="bigint"==typeof e?e:kc(Ic("private key",e,n))}catch(t){throw Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return i&&(a=qc(a,s)),Pc("private key",a,gh,s),a}function c(e){if(!(e instanceof l))throw Error("ProjectivePoint expected")}const h=Mc(((e,t)=>{const{px:n,py:i,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),c=r.mul(i,t),h=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(h,r.ONE))throw Error("invZ was invalid");return{x:o,y:c}})),u=Mc((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error("bad point: x or y not FE");const s=r.sqr(i),o=a(n);if(!r.eql(s,o))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));class l{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t))throw Error("y required");if(null==n||!r.isValid(n))throw Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error("invalid affine point");if(e instanceof l)throw Error("projective point not allowed");const i=e=>r.eql(e,r.ZERO);return i(t)&&i(n)?l.ZERO:new l(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(l.fromAffine)}static fromHex(e){const t=l.fromAffine(s(Ic("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return l.BASE.multiply(o(e))}static msm(e,t){return oh(l,n,e,t)}_setWindowSize(e){f.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:i}=this,{px:s,py:a,pz:o}=e,h=r.eql(r.mul(t,o),r.mul(s,i)),u=r.eql(r.mul(n,o),r.mul(a,i));return h&&u}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,i=r.mul(n,ph),{px:s,py:a,pz:o}=this;let c=r.ZERO,h=r.ZERO,u=r.ZERO,y=r.mul(s,s),f=r.mul(a,a),g=r.mul(o,o),p=r.mul(s,a);return p=r.add(p,p),u=r.mul(s,o),u=r.add(u,u),c=r.mul(e,u),h=r.mul(i,g),h=r.add(c,h),c=r.sub(f,h),h=r.add(f,h),h=r.mul(c,h),c=r.mul(p,c),u=r.mul(i,u),g=r.mul(e,g),p=r.sub(y,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(y,y),y=r.add(u,y),y=r.add(y,g),y=r.mul(y,p),h=r.add(h,y),g=r.mul(a,o),g=r.add(g,g),y=r.mul(g,p),c=r.sub(c,y),u=r.mul(g,f),u=r.add(u,u),u=r.add(u,u),new l(c,h,u)}add(e){c(e);const{px:n,py:i,pz:s}=this,{px:a,py:o,pz:h}=e;let u=r.ZERO,y=r.ZERO,f=r.ZERO;const g=t.a,p=r.mul(t.b,ph);let d=r.mul(n,a),A=r.mul(i,o),w=r.mul(s,h),m=r.add(n,i),b=r.add(a,o);m=r.mul(m,b),b=r.add(d,A),m=r.sub(m,b),b=r.add(n,s);let k=r.add(a,h);return b=r.mul(b,k),k=r.add(d,w),b=r.sub(b,k),k=r.add(i,s),u=r.add(o,h),k=r.mul(k,u),u=r.add(A,w),k=r.sub(k,u),f=r.mul(g,b),u=r.mul(p,w),f=r.add(u,f),u=r.sub(A,f),f=r.add(A,f),y=r.mul(u,f),A=r.add(d,d),A=r.add(A,d),w=r.mul(g,w),b=r.mul(p,b),A=r.add(A,w),w=r.sub(d,w),w=r.mul(g,w),b=r.add(b,w),d=r.mul(A,b),y=r.add(y,d),d=r.mul(k,b),u=r.mul(m,u),u=r.sub(u,d),d=r.mul(m,A),f=r.mul(k,f),f=r.add(f,d),new l(u,y,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(l.ZERO)}wNAF(e){return f.wNAFCached(this,e,l.normalizeZ)}multiplyUnsafe(e){Pc("scalar",e,fh,t.n);const n=l.ZERO;if(e===fh)return n;if(e===gh)return this;const{endo:i}=t;if(!i)return f.unsafeLadder(this,e);let{k1neg:s,k1:a,k2neg:o,k2:c}=i.splitScalar(e),h=n,u=n,y=this;for(;a>fh||c>fh;)a&gh&&(h=h.add(y)),c&gh&&(u=u.add(y)),y=y.double(),a>>=gh,c>>=gh;return s&&(h=h.negate()),o&&(u=u.negate()),u=new l(r.mul(u.px,i.beta),u.py,u.pz),h.add(u)}multiply(e){const{endo:n,n:i}=t;let s,a;if(Pc("scalar",e,gh,i),n){const{k1neg:t,k1:i,k2neg:o,k2:c}=n.splitScalar(e);let{p:h,f:u}=this.wNAF(i),{p:y,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),y=f.constTimeNegate(o,y),y=new l(r.mul(y.px,n.beta),y.py,y.pz),s=h.add(y),a=u.add(g)}else{const{p:t,f:r}=this.wNAF(e);s=t,a=r}return l.normalizeZ([s,a])[0]}multiplyAndAddUnsafe(e,t,r){const n=l.BASE,i=(e,t)=>t!==fh&&t!==gh&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=i(this,t).add(i(e,r));return s.is0()?void 0:s}toAffine(e){return h(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===gh)return!0;if(r)return r(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===gh?this:r?r(l,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return fc("isCompressed",e),this.assertValidity(),i(l,this,e)}toHex(e=!0){return fc("isCompressed",e),pc(this.toRawBytes(e))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);const y=t.nBitLength,f=ah(l,t.endo?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:o,weierstrassEquation:a,isWithinCurveOrder:function(e){return Cc(e,gh,t.n)}}}function Ah(e){const t=function(e){const t=ch(e);return Tc(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,i=r.BYTES+1,s=2*r.BYTES+1;function a(e){return qc(e,n)}function o(e){return Yc(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:l}=dh({...t,toBytes(e,t,n){const i=t.toAffine(),s=r.toBytes(i.x),a=Sc;return fc("isCompressed",n),n?a(Uint8Array.from([t.hasEvenY()?2:3]),s):a(Uint8Array.from([4]),s,r.toBytes(i.y))},fromBytes(e){const t=e.length,n=e[0],a=e.subarray(1);if(t!==i||2!==n&&3!==n){if(t===s&&4===n){return{x:r.fromBytes(a.subarray(0,r.BYTES)),y:r.fromBytes(a.subarray(r.BYTES,2*r.BYTES))}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const e=kc(a);if(!Cc(e,gh,r.ORDER))throw Error("Point is not on curve");const t=u(e);let i;try{i=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+t)}return!(1&~n)!==((i&gh)===gh)&&(i=r.neg(i)),{x:e,y:i}}}}),y=e=>pc(vc(e,t.nByteLength));function f(e){return e>n>>gh}const g=(e,t,r)=>kc(e.slice(t,r));class p{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Ic("compactSignature",e,2*r),new p(g(e,0,r),g(e,r,2*r))}static fromDER(e){const{r:t,s:r}=yh.toSig(Ic("DER",e));return new p(t,r)}assertValidity(){Pc("r",this.r,gh,n),Pc("s",this.s,gh,n)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:i,recovery:s}=this,h=m(Ic("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+y(u)),g=o(u),p=a(-h*g),d=a(i*g),A=c.BASE.multiplyAndAddUnsafe(f,p,d);if(!A)throw Error("point at infinify");return A.assertValidity(),A}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return bc(this.toDERHex())}toDERHex(){return yh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return bc(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}const d={isValidPrivateKey(e){try{return h(e),!0}catch(e){return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const e=th(t.n);return function(e,t,r=!1){const n=e.length,i=eh(t),s=th(t);if(n<16||n1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);const a=qc(r?kc(e):Ec(e),t-Hc)+Hc;return r?Bc(a,i):vc(a,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function A(e){const t=lc(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===i||n===s:r?n===2*i||n===2*s:e instanceof c}const w=t.bits2int||function(e){const r=kc(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},m=t.bits2int_modN||function(e){return a(w(e))},b=Uc(t.nBitLength);function k(e){return Pc("num < 2^"+t.nBitLength,e,fh,b),vc(e,t.nByteLength)}function E(e,n,i=v){if(["recovered","canonical"].some((e=>e in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:y,prehash:g,extraEntropy:d}=i;null==y&&(y=!0),e=Ic("msgHash",e),hh(i),g&&(e=Ic("prehashed msgHash",s(e)));const A=m(e),b=h(n),E=[k(b),k(A)];if(null!=d&&!1!==d){const e=!0===d?u(r.BYTES):d;E.push(Ic("extraEntropy",e))}const B=Sc(...E),I=A;return{seed:B,k2sig:function(e){const t=w(e);if(!l(t))return;const r=o(t),n=c.BASE.multiply(t).toAffine(),i=a(n.x);if(i===fh)return;const s=a(r*a(I+i*b));if(s===fh)return;let h=(n.x===i?0:2)|Number(n.y&gh),u=s;return y&&f(s)&&(u=function(e){return f(e)?a(-e):e}(s),h^=1),new p(i,u,h)}}}const v={lowS:t.lowS,prehash:!1},B={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(A(e))throw Error("first arg must be private key");if(!A(t))throw Error("second arg must be public key");return c.fromHex(t).multiply(h(e)).toRawBytes(r)},sign:function(e,r,n=v){const{seed:i,k2sig:s}=E(e,r,n),a=t;return Rc(a.hash.outputLen,a.nByteLength,a.hmac)(i,s)},verify:function(e,r,n,i=B){const s=e;if(r=Ic("msgHash",r),n=Ic("publicKey",n),"strict"in i)throw Error("options.strict was renamed to lowS");hh(i);const{lowS:h,prehash:u}=i;let l,y;try{if("string"==typeof s||lc(s))try{l=p.fromDER(s)}catch(e){if(!(e instanceof yh.Err))throw e;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:e,s:t}=s;l=new p(e,t)}}y=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;u&&(r=t.hash(r));const{r:f,s:g}=l,d=m(r),A=o(g),w=a(d*A),b=a(f*A),k=c.BASE.multiplyAndAddUnsafe(y,w,b)?.toAffine();return!!k&&a(k.x)===f},ProjectivePoint:c,Signature:p,utils:d}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function wh(e){return{hash:e,hmac:(t,...r)=>oc(e,t,qo(...r)),randomBytes:Yo}}function mh(e,t){const r=t=>Ah({...e,...wh(t)});return Object.freeze({...r(t),create:r})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const bh=Xc(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),kh=mh({a:bh.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:bh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ic),Eh=/* @__PURE__ */BigInt(2**32-1),vh=/* @__PURE__ */BigInt(32);function Bh(e,t=!1){return t?{h:Number(e&Eh),l:Number(e>>vh&Eh)}:{h:0|Number(e>>vh&Eh),l:0|Number(e&Eh)}}function Ih(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;ie<>>32-r,Kh=(e,t,r)=>t<>>32-r,Ch=(e,t,r)=>t<>>64-r,Ph=(e,t,r)=>e<>>64-r;const Dh={fromBig:Bh,split:Ih,toBig:(e,t)=>BigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:Sh,rotlSL:Kh,rotlBH:Ch,rotlBL:Ph,add:function(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,add5H:(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},[Uh,xh]=/* @__PURE__ */(()=>Dh.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),Qh=/* @__PURE__ */new Uint32Array(80),Rh=/* @__PURE__ */new Uint32Array(80);class Lh extends $o{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:l,Gh:y,Gl:f,Hh:g,Hl:p}=this;return[e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p]}set(e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|l,this.Gh=0|y,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(e,t){for(let r=0;r<16;r++,t+=4)Qh[r]=e.getUint32(t),Rh[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Qh[e-15],r=0|Rh[e-15],n=Dh.rotrSH(t,r,1)^Dh.rotrSH(t,r,8)^Dh.shrSH(t,r,7),i=Dh.rotrSL(t,r,1)^Dh.rotrSL(t,r,8)^Dh.shrSL(t,r,7),s=0|Qh[e-2],a=0|Rh[e-2],o=Dh.rotrSH(s,a,19)^Dh.rotrBH(s,a,61)^Dh.shrSH(s,a,6),c=Dh.rotrSL(s,a,19)^Dh.rotrBL(s,a,61)^Dh.shrSL(s,a,6),h=Dh.add4L(i,c,Rh[e-7],Rh[e-16]),u=Dh.add4H(h,n,o,Qh[e-7],Qh[e-16]);Qh[e]=0|u,Rh[e]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:l,Fh:y,Fl:f,Gh:g,Gl:p,Hh:d,Hl:A}=this;for(let e=0;e<80;e++){const t=Dh.rotrSH(u,l,14)^Dh.rotrSH(u,l,18)^Dh.rotrBH(u,l,41),w=Dh.rotrSL(u,l,14)^Dh.rotrSL(u,l,18)^Dh.rotrBL(u,l,41),m=u&y^~u&g,b=l&f^~l&p,k=Dh.add5L(A,w,b,xh[e],Rh[e]),E=Dh.add5H(k,d,t,m,Uh[e],Qh[e]),v=0|k,B=Dh.rotrSH(r,n,28)^Dh.rotrBH(r,n,34)^Dh.rotrBH(r,n,39),I=Dh.rotrSL(r,n,28)^Dh.rotrBL(r,n,34)^Dh.rotrBL(r,n,39),S=r&i^r&a^i&a,K=n&s^n&o^s&o;d=0|g,A=0|p,g=0|y,p=0|f,y=0|u,f=0|l,({h:u,l}=Dh.add(0|c,0|h,0|E,0|v)),c=0|a,h=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const C=Dh.add3L(v,I,K);r=Dh.add3H(C,E,B,S),n=0|C}({h:r,l:n}=Dh.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Dh.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Dh.add(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:h}=Dh.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:u,l}=Dh.add(0|this.Eh,0|this.El,0|u,0|l)),({h:y,l:f}=Dh.add(0|this.Fh,0|this.Fl,0|y,0|f)),({h:g,l:p}=Dh.add(0|this.Gh,0|this.Gl,0|g,0|p)),({h:d,l:A}=Dh.add(0|this.Hh,0|this.Hl,0|d,0|A)),this.set(r,n,i,s,a,o,c,h,u,l,y,f,g,p,d,A)}roundClean(){Qh.fill(0),Rh.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Th extends Lh{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const Mh=/* @__PURE__ */Jo((()=>new Lh)),Nh=/* @__PURE__ */Jo((()=>new Th)),Fh=Xc(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),Hh=mh({a:Fh.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:Fh,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},Nh),Oh=Xc(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),zh={a:Oh.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:Oh,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1)},_h=mh({a:zh.a,b:zh.b,Fp:Oh,n:zh.n,Gx:zh.Gx,Gy:zh.Gy,h:zh.h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Mh),Gh=[],jh=[],qh=[],Vh=/* @__PURE__ */BigInt(0),Jh=/* @__PURE__ */BigInt(1),Yh=/* @__PURE__ */BigInt(2),Wh=/* @__PURE__ */BigInt(7),Zh=/* @__PURE__ */BigInt(256),$h=/* @__PURE__ */BigInt(113);for(let e=0,t=Jh,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Gh.push(2*(5*n+r)),jh.push((e+1)*(e+2)/2%64);let i=Vh;for(let e=0;e<7;e++)t=(t<>Wh)*$h)%Zh,t&Yh&&(i^=Jh<<(Jh<r>32?Ch(e,t,r):Sh(e,t,r),ru=(e,t,r)=>r>32?Ph(e,t,r):Kh(e,t,r);class nu extends Vo{constructor(e,t,r,n=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ro(r),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}keccak(){zo||_o(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,i=(t+2)%10,s=r[i],a=r[i+1],o=tu(s,a,1)^r[n],c=ru(s,a,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=jh[r],s=tu(t,i,n),a=ru(t,i,n),o=Gh[r];t=e[o],i=e[o+1],e[o]=s,e[o+1]=a}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=Xh[n],e[1]^=eu[n]}r.fill(0)}(this.state32,this.rounds),zo||_o(this.state32),this.posOut=0,this.pos=0}update(e){To(this);const{blockLen:t,state:r}=this,n=(e=jo(e)).length;for(let i=0;i=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ro(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Mo(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return e||(e=new nu(t,r,n,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=s,e.destroyed=this.destroyed,e}}const iu=(e,t,r)=>Jo((()=>new nu(t,e,r))),su=/* @__PURE__ */iu(6,136,32),au=/* @__PURE__ */iu(6,72,64),ou=/* @__PURE__ */((e,t,r)=>function(e){const t=(t,r)=>e(r).update(jo(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(((n={})=>new nu(t,e,void 0===n.dkLen?r:n.dkLen,!0))))(31,136,32),cu=BigInt(0),hu=BigInt(1),uu=BigInt(2),lu=BigInt(8),yu={zip215:!0};function fu(e){const t=function(e){const t=ch(e);return Tc(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:i,hash:s,randomBytes:a,nByteLength:o,h:c}=t,h=uu<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:cu}}}),f=t.adjustScalarBytes||(e=>e),g=t.domain||((e,t,r)=>{if(fc("phflag",r),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function p(e,t){Pc("coordinate "+e,t,cu,h)}function d(e){if(!(e instanceof m))throw Error("ExtendedPoint expected")}const A=Mc(((e,t)=>{const{ex:n,ey:i,ez:s}=e,a=e.is0();null==t&&(t=a?lu:r.inv(s));const o=u(n*t),c=u(i*t),h=u(s*t);if(a)return{x:cu,y:hu};if(h!==hu)throw Error("invZ was invalid");return{x:o,y:c}})),w=Mc((e=>{const{a:r,d:n}=t;if(e.is0())throw Error("bad point: ZERO");const{ex:i,ey:s,ez:a,et:o}=e,c=u(i*i),h=u(s*s),l=u(a*a),y=u(l*l),f=u(c*r);if(u(l*u(f+h))!==u(y+u(n*u(c*h))))throw Error("bad point: equation left != right (1)");if(u(i*s)!==u(a*o))throw Error("bad point: equation left != right (2)");return!0}));class m{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,p("x",e),p("y",t),p("z",r),p("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof m)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return p("x",t),p("y",r),new m(t,r,hu,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(m.fromAffine)}static msm(e,t){return oh(m,l,e,t)}_setWindowSize(e){E.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){d(e);const{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:a}=e,o=u(t*a),c=u(i*n),h=u(r*a),l=u(s*n);return o===c&&h===l}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:i}=this,s=u(r*r),a=u(n*n),o=u(uu*u(i*i)),c=u(e*s),h=r+n,l=u(u(h*h)-s-a),y=c+a,f=y-o,g=c-a,p=u(l*f),d=u(y*g),A=u(l*g),w=u(f*y);return new m(p,d,w,A)}add(e){d(e);const{a:r,d:n}=t,{ex:i,ey:s,ez:a,et:o}=this,{ex:c,ey:h,ez:l,et:y}=e;if(r===BigInt(-1)){const e=u((s-i)*(h+c)),t=u((s+i)*(h-c)),r=u(t-e);if(r===cu)return this.double();const n=u(a*uu*y),f=u(o*uu*l),g=f+n,p=t+e,d=f-n,A=u(g*r),w=u(p*d),b=u(g*d),k=u(r*p);return new m(A,w,k,b)}const f=u(i*c),g=u(s*h),p=u(o*n*y),A=u(a*l),w=u((i+s)*(c+h)-f-g),b=A-p,k=A+p,E=u(g-r*f),v=u(w*b),B=u(k*E),I=u(w*E),S=u(b*k);return new m(v,B,S,I)}subtract(e){return this.add(e.negate())}wNAF(e){return E.wNAFCached(this,e,m.normalizeZ)}multiply(e){const t=e;Pc("scalar",t,hu,n);const{p:r,f:i}=this.wNAF(t);return m.normalizeZ([r,i])[0]}multiplyUnsafe(e){const t=e;return Pc("scalar",t,cu,n),t===cu?k:this.equals(k)||t===hu?this:this.equals(b)?this.wNAF(t).p:E.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(e){return A(this,e)}clearCofactor(){const{h:e}=t;return e===hu?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:i,a:s}=t,a=r.BYTES;e=Ic("pointHex",e,a),fc("zip215",n);const o=e.slice(),c=e[a-1];o[a-1]=-129&c;const l=Ec(o),f=n?h:r.ORDER;Pc("pointHex.y",l,cu,f);const g=u(l*l),p=u(g-hu),d=u(i*g-s);let{isValid:A,value:w}=y(p,d);if(!A)throw Error("Point.fromHex: invalid y coordinate");const b=(w&hu)===hu,k=!!(128&c);if(!n&&w===cu&&k)throw Error("Point.fromHex: x=0 and x_0=1");return k!==b&&(w=u(-w)),m.fromAffine({x:w,y:l})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Bc(t,r.BYTES);return n[n.length-1]|=e&hu?128:0,n}toHex(){return pc(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,hu,u(t.Gx*t.Gy)),m.ZERO=new m(cu,hu,hu,cu);const{BASE:b,ZERO:k}=m,E=ah(m,8*o);function v(e){return qc(e,n)}function B(e){return v(Ec(e))}function I(e){const t=o;e=Ic("private key",e,t);const r=Ic("hashed private key",s(e),2*t),n=f(r.slice(0,t)),i=r.slice(t,2*t),a=B(n),c=b.multiply(a),h=c.toRawBytes();return{head:n,prefix:i,scalar:a,point:c,pointBytes:h}}function S(e=new Uint8Array,...t){const r=Sc(...t);return B(s(g(r,Ic("context",e),!!i)))}const K=yu;b._setWindowSize(8);return{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Ic("message",e),i&&(e=i(e));const{prefix:a,scalar:c,pointBytes:h}=I(t),u=S(s.context,a,e),l=b.multiply(u).toRawBytes(),y=v(u+S(s.context,l,h,e)*c);return Pc("signature.s",y,cu,n),Ic("result",Sc(l,Bc(y,r.BYTES)),2*o)},verify:function(e,t,n,s=K){const{context:a,zip215:o}=s,c=r.BYTES;e=Ic("signature",e,2*c),t=Ic("message",t),void 0!==o&&fc("zip215",o),i&&(t=i(t));const h=Ec(e.slice(c,2*c));let u,l,y;try{u=m.fromHex(n,o),l=m.fromHex(e.slice(0,c),o),y=b.multiplyUnsafe(h)}catch(e){return!1}if(!o&&u.isSmallOrder())return!1;const f=S(a,l.toRawBytes(),u.toRawBytes(),t);return l.add(u.multiplyUnsafe(f)).subtract(y).clearCofactor().equals(m.ZERO)},ExtendedPoint:m,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>a(r.BYTES),precompute:(e=8,t=m.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gu=BigInt(0),pu=BigInt(1);function du(e){const t=(Tc(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,i=e=>qc(e,n),s=t.montgomeryBits,a=Math.ceil(s/8),o=t.nByteLength,c=t.adjustScalarBytes||(e=>e),h=t.powPminus2||(e=>Vc(e,n-BigInt(2),n));function u(e,t,r){const n=i(e*(t-r));return[t=i(t-n),r=i(r+n)]}const l=(t.a-BigInt(2))/BigInt(4);function y(e){return Bc(i(e),a)}function f(e,t){const r=function(e){const t=Ic("u coordinate",e,a);return 32===o&&(t[31]&=127),Ec(t)}(t),f=function(e){const t=Ic("scalar",e),r=t.length;if(r!==a&&r!==o)throw Error(`Expected ${a} or ${o} bytes, got ${r}`);return Ec(c(t))}(e),g=function(e,t){Pc("u",e,gu,n),Pc("scalar",t,gu,n);const r=t,a=e;let o,c=pu,y=gu,f=e,g=pu,p=gu;for(let e=BigInt(s-1);e>=gu;e--){const t=r>>e&pu;p^=t,o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1],p=t;const n=c+y,s=i(n*n),h=c-y,d=i(h*h),A=s-d,w=f+g,m=i((f-g)*n),b=i(w*h),k=m+b,E=m-b;f=i(k*k),g=i(a*i(E*E)),c=i(s*d),y=i(A*(s+i(l*A)))}o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1];const d=h(y);return i(c*d)}(r,f);if(g===gu)throw Error("Invalid private or public key received");return y(g)}const g=y(t.Gu);function p(e){return f(e,g)}return{scalarMult:f,scalarMultBase:p,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>p(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Au=Jo((()=>ou.create({dkLen:114}))),wu=(Jo((()=>ou.create({dkLen:64}))),BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439")),mu=BigInt(1),bu=BigInt(2),ku=BigInt(3);BigInt(4);const Eu=BigInt(11),vu=BigInt(22),Bu=BigInt(44),Iu=BigInt(88),Su=BigInt(223);function Ku(e){const t=wu,r=e*e*e%t,n=r*r*e%t,i=Jc(n,ku,t)*n%t,s=Jc(i,ku,t)*n%t,a=Jc(s,bu,t)*r%t,o=Jc(a,Eu,t)*a%t,c=Jc(o,vu,t)*o%t,h=Jc(c,Bu,t)*c%t,u=Jc(h,Iu,t)*h%t,l=Jc(u,Bu,t)*c%t,y=Jc(l,bu,t)*r%t,f=Jc(y,mu,t)*e%t;return Jc(f,Su,t)*y%t}function Cu(e){return e[0]&=252,e[55]|=128,e[56]=0,e}const Pu=Xc(wu,456,!0),Du={a:BigInt(1),d:BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"),Fp:Pu,n:BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"),nBitLength:456,h:BigInt(4),Gx:BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"),Gy:BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"),hash:Au,randomBytes:Yo,adjustScalarBytes:Cu,domain:(e,t,r)=>{if(t.length>255)throw Error("Context is too big: "+t.length);return qo(Go("SigEd448"),new Uint8Array([r?1:0,t.length]),t,e)},uvRatio:function(e,t){const r=wu,n=qc(e*e*t,r),i=qc(n*e,r),s=qc(i*n*t,r),a=qc(i*Ku(s),r),o=qc(a*a,r);return{isValid:qc(o*t,r)===e,value:a}}},Uu=/* @__PURE__ */fu(Du),xu=/* @__PURE__ */(()=>du({a:BigInt(156326),montgomeryBits:448,nByteLength:56,P:wu,Gu:BigInt(5),powPminus2:e=>{const t=wu;return qc(Jc(Ku(e),BigInt(2),t)*e,t)},adjustScalarBytes:Cu,randomBytes:Yo}))();Pu.ORDER,BigInt(3),BigInt(4),BigInt(156326),BigInt("39082"),BigInt("78163"),BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"),BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"),BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const Qu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ru=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Lu=BigInt(1),Tu=BigInt(2),Mu=(e,t)=>(e+t/Tu)/t;const Nu=Xc(Qu,void 0,void 0,{sqrt:function(e){const t=Qu,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),h=e*e*e%t,u=h*h*e%t,l=Jc(u,r,t)*u%t,y=Jc(l,r,t)*u%t,f=Jc(y,Tu,t)*h%t,g=Jc(f,i,t)*f%t,p=Jc(g,s,t)*g%t,d=Jc(p,o,t)*p%t,A=Jc(d,c,t)*d%t,w=Jc(A,o,t)*p%t,m=Jc(w,r,t)*u%t,b=Jc(m,a,t)*g%t,k=Jc(b,n,t)*h%t,E=Jc(k,Tu,t);if(!Nu.eql(Nu.sqr(E),e))throw Error("Cannot find square root");return E}}),Fu=mh({a:BigInt(0),b:BigInt(7),Fp:Nu,n:Ru,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ru,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Lu*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,a=BigInt("0x100000000000000000000000000000000"),o=Mu(s*e,t),c=Mu(-n*e,t);let h=qc(e-o*r-c*i,t),u=qc(-o*n-c*s,t);const l=h>a,y=u>a;if(l&&(h=t-h),y&&(u=t-u),h>a||u>a)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:h,k2neg:y,k2:u}}}},ic);BigInt(0),Fu.ProjectivePoint;const Hu=Xc(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377")),Ou=mh({a:Hu.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),b:BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),Fp:Hu,n:BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),Gx:BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),Gy:BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),h:BigInt(1),lowS:!1},ic),zu=Xc(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53")),_u=mh({a:zu.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),b:BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),Fp:zu,n:BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),Gx:BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),Gy:BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),h:BigInt(1),lowS:!1},Nh),Gu=Xc(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3")),ju=mh({a:Gu.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),b:BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),Fp:Gu,n:BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),Gx:BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),Gy:BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),h:BigInt(1),lowS:!1},Mh),qu=new Map(Object.entries({nistP256:kh,nistP384:Hh,nistP521:_h,brainpoolP256r1:Ou,brainpoolP384r1:_u,brainpoolP512r1:ju,secp256k1:Fu,x448:xu,ed448:Uu}));var Vu=/*#__PURE__*/Object.freeze({__proto__:null,nobleCurves:qu});function Ju(e,t,r,n,i,s){const a=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],h=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],y=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let g,p,d,A,w,m,b,k,E,v,B=0,I=t.length;const S=32===e.length?3:9;k=3===S?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e){const t=8-e.length%8;let r;if(!(t<8)){if(8===t)return e;throw Error("des: invalid padding")}r=0;const n=new Uint8Array(e.length+t);for(let t=0;t>>4^b),b^=d,m^=d<<4,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,m=m<<1|m>>>31,b=b<<1|b>>>31,p=0;p>>4|b<<28)^e[g+1],d=m,m=b,b=d^(o[A>>>24&63]|h[A>>>16&63]|l[A>>>8&63]|f[63&A]|a[w>>>24&63]|c[w>>>16&63]|u[w>>>8&63]|y[63&w]);d=m,m=b,b=d}m=m>>>1|m<<31,b=b>>>1|b<<31,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=252645135&(m>>>4^b),b^=d,m^=d<<4,K[C++]=m>>>24,K[C++]=m>>>16&255,K[C++]=m>>>8&255,K[C++]=255&m,K[C++]=b>>>24,K[C++]=b>>>16&255,K[C++]=b>>>8&255,K[C++]=255&b}return r||(K=function(e){let t,r=null;if(t=0,!r){for(r=1;e[e.length-r]===t;)r++;r--}return e.subarray(0,e.length-r)}(K)),K}function Yu(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],h=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],p=e.length>8?3:1,d=Array(32*p),A=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let w,m,b,k=0,E=0;for(let v=0;v>>4^v),v^=b,p^=b<<4,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=858993459&(p>>>2^v),v^=b,p^=b<<2,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=16711935&(v>>>8^p),p^=b,v^=b<<8,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=p<<8|v>>>20&240,p=v<<24|v<<8&16711680|v>>>8&65280|v>>>24&240,v=b;for(let e=0;e<16;e++)A[e]?(p=p<<2|p>>>26,v=v<<2|v>>>26):(p=p<<1|p>>>27,v=v<<1|v>>>27),p&=-15,v&=-15,w=t[p>>>28]|r[p>>>24&15]|n[p>>>20&15]|i[p>>>16&15]|s[p>>>12&15]|a[p>>>8&15]|o[p>>>4&15],m=c[v>>>28]|h[v>>>24&15]|u[v>>>20&15]|l[v>>>16&15]|y[v>>>12&15]|f[v>>>8&15]|g[v>>>4&15],b=65535&(m>>>16^w),d[E++]=w^b,d[E++]=m^b<<16}return d}function Wu(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Ju(Yu(this.key[2]),Ju(Yu(this.key[1]),Ju(Yu(this.key[0]),e,!0),!1),!0)}}function Zu(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>>16&255,t[s+6]=o>>>8&255,t[s+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>16&255,t[s+6]=o>>8&255,t[s+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const n=t+e,i=n<>>32-r;return(s[0][i>>>24]^s[1][i>>>16&255])-s[2][i>>>8&255]+s[3][255&i]}function n(e,t,r){const n=t^e,i=n<>>32-r;return s[0][i>>>24]-s[1][i>>>16&255]+s[2][i>>>8&255]^s[3][255&i]}function i(e,t,r){const n=t-e,i=n<>>32-r;return(s[0][i>>>24]+s[1][i>>>16&255]^s[2][i>>>8&255])-s[3][255&i]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const n=[,,,,,,,,],i=Array(32);let a;for(let e=0;e<4;e++)a=4*e,n[e]=r[a]<<24|r[a+1]<<16|r[a+2]<<8|r[a+3];const o=[6,7,4,5];let c,h=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(a=0;a<4;a++){const t=e[r][a];c=n[t[1]],c^=s[4][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=s[5][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=s[6][n[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=s[7][n[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=s[o[a]][n[t[6]>>>2]>>>24-8*(3&t[6])&255],n[t[0]]=c}for(a=0;a<4;a++){const e=t[r][a];c=s[4][n[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=s[5][n[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=s[6][n[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=s[7][n[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=s[4+a][n[e[4]>>>2]>>>24-8*(3&e[4])&255],i[h]=c,h++}}for(let e=0;e<16;e++)this.masking[e]=i[e],this.rotate[e]=31&i[16+e]};const s=[,,,,,,,,];s[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],s[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],s[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],s[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],s[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],s[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],s[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],s[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function $u(e){this.cast5=new Zu,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}Wu.keySize=Wu.prototype.keySize=24,Wu.blockSize=Wu.prototype.blockSize=8,$u.blockSize=$u.prototype.blockSize=8,$u.keySize=$u.prototype.keySize=16;const Xu=4294967295;function el(e,t){return(e<>>32-t)&Xu}function tl(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function rl(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function nl(e,t){return e>>>8*t&255}function il(e){this.tf=function(){let e=null,t=null,r=-1,n=[],i=[[],[],[],[]];function s(e){return i[0][nl(e,0)]^i[1][nl(e,1)]^i[2][nl(e,2)]^i[3][nl(e,3)]}function a(e){return i[0][nl(e,3)]^i[1][nl(e,0)]^i[2][nl(e,1)]^i[3][nl(e,2)]}function o(e,t){let r=s(t[0]),i=a(t[1]);t[2]=el(t[2]^r+i+n[4*e+8]&Xu,31),t[3]=el(t[3],1)^r+2*i+n[4*e+9]&Xu,r=s(t[2]),i=a(t[3]),t[0]=el(t[0]^r+i+n[4*e+10]&Xu,31),t[1]=el(t[1],1)^r+2*i+n[4*e+11]&Xu}function c(e,t){let r=s(t[0]),i=a(t[1]);t[2]=el(t[2],1)^r+i+n[4*e+10]&Xu,t[3]=el(t[3]^r+2*i+n[4*e+11]&Xu,31),r=s(t[2]),i=a(t[3]),t[0]=el(t[0],1)^r+i+n[4*e+8]&Xu,t[1]=el(t[1]^r+2*i+n[4*e+9]&Xu,31)}return{name:"twofish",blocksize:16,open:function(t){let r,s,a,o,c;e=t;const h=[],u=[],l=[];let y;const f=[];let g,p,d;const A=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],m=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],b=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],k=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],E=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],v=[[],[]],B=[[],[],[],[]];function I(e){return e^e>>2^[0,90,180,238][3&e]}function S(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function K(e,t){let r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&Xu|e>>>24,e=e<<8&Xu,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function C(e,t){const r=t>>4,n=15&t,i=A[e][r^n],s=w[e][k[n]^E[r]];return b[e][k[s]^E[i]]<<4|m[e][i^s]}function P(e,t){let r=nl(e,0),n=nl(e,1),i=nl(e,2),s=nl(e,3);switch(y){case 4:r=v[1][r]^nl(t[3],0),n=v[0][n]^nl(t[3],1),i=v[0][i]^nl(t[3],2),s=v[1][s]^nl(t[3],3);case 3:r=v[1][r]^nl(t[2],0),n=v[1][n]^nl(t[2],1),i=v[0][i]^nl(t[2],2),s=v[0][s]^nl(t[2],3);case 2:r=v[0][v[0][r]^nl(t[1],0)]^nl(t[0],0),n=v[0][v[1][n]^nl(t[1],1)]^nl(t[0],1),i=v[1][v[0][i]^nl(t[1],2)]^nl(t[0],2),s=v[1][v[1][s]^nl(t[1],3)]^nl(t[0],3)}return B[0][r]^B[1][n]^B[2][i]^B[3][s]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=tl(e,r);for(r=0;r<256;r++)v[0][r]=C(0,r),v[1][r]=C(1,r);for(r=0;r<256;r++)g=v[1][r],p=I(g),d=S(g),B[0][r]=g+(p<<8)+(d<<16)+(d<<24),B[2][r]=p+(d<<8)+(g<<16)+(d<<24),g=v[0][r],p=I(g),d=S(g),B[1][r]=d+(d<<8)+(p<<16)+(g<<24),B[3][r]=p+(g<<8)+(d<<16)+(p<<24);for(y=l.length/2,r=0;r=0;e--)c(e,s);rl(t,r,s[2]^n[0]),rl(t,r+4,s[3]^n[1]),rl(t,r+8,s[0]^n[2]),rl(t,r+12,s[1]^n[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function sl(){}function al(e){this.bf=new sl,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}il.keySize=il.prototype.keySize=32,il.blockSize=il.prototype.blockSize=16,sl.prototype.BLOCKSIZE=8,sl.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],sl.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],sl.prototype.NN=16,sl.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},sl.prototype._F=function(e){let t;const r=255&e,n=255&(e>>>=8),i=255&(e>>>=8),s=255&(e>>>=8);return t=this.sboxes[0][s]+this.sboxes[1][i],t^=this.sboxes[2][n],t+=this.sboxes[3][r],t},sl.prototype._encryptBlock=function(e){let t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},sl.prototype._decryptBlock=function(e){let t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],n=this._F(r)^n;const e=r;r=n,n=e}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},sl.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^n}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const n=[0,0];for(t=0;tnew ll)),fl=/* @__PURE__ */new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),gl=/* @__PURE__ */new Uint8Array(Array(16).fill(0).map(((e,t)=>t))),pl=/* @__PURE__ */gl.map((e=>(9*e+5)%16));let dl=[gl],Al=[pl];for(let e=0;e<4;e++)for(let t of[dl,Al])t.push(t[e].map((e=>fl[e])));const wl=/* @__PURE__ */[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>new Uint8Array(e))),ml=/* @__PURE__ */dl.map(((e,t)=>e.map((e=>wl[t][e])))),bl=/* @__PURE__ */Al.map(((e,t)=>e.map((e=>wl[t][e])))),kl=/* @__PURE__ */new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),El=/* @__PURE__ */new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function vl(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}const Bl=/* @__PURE__ */new Uint32Array(16);class Il extends $o{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)Bl[r]=e.getUint32(t,!0);let r=0|this.h0,n=r,i=0|this.h1,s=i,a=0|this.h2,o=a,c=0|this.h3,h=c,u=0|this.h4,l=u;for(let e=0;e<5;e++){const t=4-e,y=kl[e],f=El[e],g=dl[e],p=Al[e],d=ml[e],A=bl[e];for(let t=0;t<16;t++){const n=Oo(r+vl(e,i,a,c)+Bl[g[t]]+y,d[t])+u|0;r=u,u=c,c=0|Oo(a,10),a=i,i=n}for(let e=0;e<16;e++){const r=Oo(n+vl(t,s,o,h)+Bl[p[e]]+f,A[e])+l|0;n=l,l=h,h=0|Oo(o,10),o=s,s=r}}this.set(this.h1+a+h|0,this.h2+c+l|0,this.h3+u+n|0,this.h4+r+s|0,this.h0+i+o|0)}roundClean(){Bl.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Sl=new Map(Object.entries({sha1:yl,sha224:sc,sha256:ic,sha384:Nh,sha512:Mh,sha3_256:su,sha3_512:au,ripemd160:/* @__PURE__ */Jo((()=>new Il))}));var Kl=/*#__PURE__*/Object.freeze({__proto__:null,nobleHashes:Sl});function Cl(e,t,r,n){e[t]+=r[n],e[t+1]+=r[n+1]+(e[t]>>24^h<<8,e[n+1]=h>>>24^c<<8,Cl(e,r,e,n),Cl(e,r,t,o),c=e[s]^e[r],h=e[s+1]^e[r+1],e[s]=c>>>16^h<<16,e[s+1]=h>>>16^c<<16,Cl(e,i,e,s),c=e[n]^e[i],h=e[n+1]^e[i+1],e[n]=h>>>31^c<<1,e[n+1]=c>>>31^h<<1}const Ul=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),xl=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((e=>2*e)));function Ql(e,t){const r=new Uint32Array(32),n=new Uint32Array(e.b.buffer,e.b.byteOffset,32);for(let t=0;t<16;t++)r[t]=e.h[t],r[t+16]=Ul[t];r[24]^=e.t0[0],r[25]^=e.t0[1];const i=t?4294967295:0;r[28]^=i,r[29]^=i;for(let e=0;e<12;e++){const t=e<<4;Dl(r,n,0,8,16,24,xl[t+0],xl[t+1]),Dl(r,n,2,10,18,26,xl[t+2],xl[t+3]),Dl(r,n,4,12,20,28,xl[t+4],xl[t+5]),Dl(r,n,6,14,22,30,xl[t+6],xl[t+7]),Dl(r,n,0,10,20,30,xl[t+8],xl[t+9]),Dl(r,n,2,12,22,24,xl[t+10],xl[t+11]),Dl(r,n,4,14,16,26,xl[t+12],xl[t+13]),Dl(r,n,6,8,18,28,xl[t+14],xl[t+15])}for(let t=0;t<16;t++)e.h[t]^=r[t]^r[t+16]}class Rl{constructor(e,t,r,n){const i=new Uint8Array(64);this.S={b:new Uint8Array(Ml),h:new Uint32Array(Tl/4),t0:new Uint32Array(2),c:0,outlen:e},i[0]=e,t&&(i[1]=t.length),i[2]=1,i[3]=1,r&&i.set(r,32),n&&i.set(n,48);const s=new Uint32Array(i.buffer,i.byteOffset,i.length/Uint32Array.BYTES_PER_ELEMENT);for(let e=0;e<16;e++)this.S.h[e]=Ul[e]^s[e];if(t){const e=new Uint8Array(Ml);e.set(t),this.update(e)}}update(e){if(!(e instanceof Uint8Array))throw Error("Input must be Uint8Array or Buffer");let t=0;for(;t>2]>>8*(3&e);return this.S.h=null,t.buffer}}function Ll(e,t,r,n){if(e>Tl)throw Error(`outlen must be at most ${Tl} (given: ${e})`);return new Rl(e,t,r,n)}const Tl=64,Ml=128,Nl=2,Fl=19,Hl=4294967295,Ol=4,zl=4294967295,_l=8,Gl=4294967295,jl=8,ql=4294967295,Vl=4294967295,Jl=32,Yl=1024,Wl=64,Zl=205===new Uint8Array(new Uint16Array([43981]).buffer)[0];function $l(e,t,r){return e[r+0]=t,e[r+1]=t>>8,e[r+2]=t>>16,e[r+3]=t>>24,e}function Xl(e,t,r){if(t>Number.MAX_SAFE_INTEGER)throw Error("LE64: large numbers unsupported");let n=t;for(let t=r;t{if(tn)throw Error(`${e} size should be between ${r} and ${n} bytes`)};if(e!==Nl||t!==Fl)throw Error("Unsupported type or version");return u("password",n,jl,Gl),u("salt",i,_l,zl),u("tag",r,Ol,Hl),u("memory",c,8*o,ql),s&&u("associated data",s,0,Vl),a&&u("secret",a,0,Jl),{type:e,version:t,tagLength:r,password:n,salt:i,ad:s,secret:a,lanes:o,memorySize:c,passes:h}}({type:Nl,version:Fl,...e}),{G:i,G2:s,xor:a,getLZ:o}=r.exports,c={},h={};h.G=i,h.G2=s,h.XOR=a;const u=4*n.lanes*Math.floor(n.memorySize/(4*n.lanes)),l=u*Yl+10*sy;if(t.buffer.byteLength{r.set(e,n),n+=e.length})),r}(i));const s=t.digest();return new Uint8Array(s)}(n),m=u/n.lanes,b=Array(n.lanes).fill(null).map((()=>Array(m))),k=(e,t)=>(b[e][t]=d.subarray(e*m*1024+1024*t,e*m*1024+1024*t+Yl),b[e][t]);for(let e=0;e0?b[i][c-1]:b[i][m-1],u=r?a.next().value:h;o(f.byteOffset,u.byteOffset,i,n.lanes,e,t,s,4,E);const l=f[0],y=f[1];0===e&&k(i,c),ry(g,h,b[l][y],e>0?p:b[i][c]),e>0&&ty(g,b[i][c],p,b[i][c])}}}const v=b[0][m-1];for(let e=1;eoy(e,{instance:n.instance,memory:r})}function uy(e,r,n,i){var s=null,a=t.atob(n),o=a.length;s=new Uint8Array(new ArrayBuffer(o));for(var c=0;chy((e=>uy(0,0,"AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEUCIG/c4BIAkgCf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAX9USIFQSj9ywEgBUEY/c0B/VAiCCAE/c4BIAggCP0NAAECAwgJCgsAAQIDCAkK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YABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==",e)))}),yy=[0,1,3,7,15,31,63,127,255],fy=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};fy.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},fy.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=yy[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var n=r-e;t|=(this.curByte&yy[e]<>n,this.bitOffset+=e,e=0}}return t},fy.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},fy.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var gy=fy,py=function(){};py.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},py.prototype.read=function(e,t,r){for(var n=0;n>>0},this.updateCRC=function(t){e=e<<8^dy[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^dy[255&(e>>>24^t)]}}),my=gy,by=Ay,ky=wy,Ey=function(e,t){var r,n=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=n,n},vy={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},By={};By[vy.LAST_BLOCK]="Bad file checksum",By[vy.NOT_BZIP_DATA]="Not bzip data",By[vy.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",By[vy.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",By[vy.DATA_ERROR]="Data error",By[vy.OUT_OF_MEMORY]="Out of memory",By[vy.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var Iy=function(e,t){var r=By[e]||"unknown error";t&&(r+=": "+t);var n=new TypeError(r);throw n.errorCode=e,n},Sy=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};Sy.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new ky,!0):(this.writeCount=-1,!1)},Sy.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||Iy(vy.NOT_BZIP_DATA,"bad magic");var n=r[3]-48;(n<1||n>9)&&Iy(vy.NOT_BZIP_DATA,"level out of range"),this.reader=new my(e),this.dbufSize=1e5*n,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},Sy.prototype._get_next_block=function(){var e,t,r,n=this.reader,i=n.pi();if("177245385090"===i)return!1;"314159265359"!==i&&Iy(vy.NOT_BZIP_DATA),this.targetBlockCRC=n.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,n.read(1)&&Iy(vy.OBSOLETE_INPUT);var s=n.read(24);s>this.dbufSize&&Iy(vy.DATA_ERROR,"initial position out of bounds");var a=n.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(a&1<<15-e){var h=16*e;for(r=n.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=h+t)}var u=n.read(3);(u<2||u>6)&&Iy(vy.DATA_ERROR);var l=n.read(15);0===l&&Iy(vy.DATA_ERROR);var y=new Uint8Array(256);for(e=0;e=u&&Iy(vy.DATA_ERROR);f[e]=Ey(y,t)}var g,p=c+2,d=[];for(t=0;t20)&&Iy(vy.DATA_ERROR),n.read(1);)n.read(1)?a--:a++;m[e]=a}for(A=w=m[0],e=1;ew?w=m[e]:m[e]=l&&Iy(vy.DATA_ERROR),g=d[f[S++]]),e=g.minLen,t=n.read(e);e>g.maxLen&&Iy(vy.DATA_ERROR),!(t<=g.limit[e]);e++)t=t<<1|n.read(1);((t-=g.base[e])<0||t>=258)&&Iy(vy.DATA_ERROR);var C=g.permute[t];if(0!==C&&1!==C){if(B)for(B=0,I+a>this.dbufSize&&Iy(vy.DATA_ERROR),E[v=o[y[0]]]+=a;a--;)K[I++]=v;if(C>c)break;I>=this.dbufSize&&Iy(vy.DATA_ERROR),E[v=o[v=Ey(y,e=C-1)]]++,K[I++]=v}else B||(B=1,a=0),a+=0===C?B:2*B,B<<=1}for((s<0||s>=I)&&Iy(vy.DATA_ERROR),t=0,e=0;e<256;e++)r=t+E[e],E[e]=t,t=r;for(e=0;e>=8,U=-1),this.writePos=P,this.writeCurrent=D,this.writeCount=I,this.writeRun=U,!0},Sy.prototype._read_bunzip=function(e,t){var r,n,i;if(this.writeCount<0)return 0;var s=this.dbuf,a=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var h=this.writeRun;c;){for(c--,n=o,o=255&(a=s[a]),a>>=8,3==h++?(r=o,i=n,o=-1):(r=1,i=o),this.blockCRC.updateCRCRun(i,r);r--;)this.outputStream.writeByte(i),this.nextoutput++;o!=n&&(h=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&Iy(vy.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var Ky=function(e){if("readByte"in e)return e;var t=new by;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},Cy=function(e){var t=new by,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var Py={Bunzip:Sy,Stream:by,Err:vy,decode:function(e,t,r){for(var n=Ky(e),i=Cy(t),s=new Sy(n,i);!("eof"in n)||!n.eof();)if(s._init_block())s._read_bunzip();else{var a=s.reader.read(32)>>>0;if(a!==s.streamCRC&&Iy(vy.DATA_ERROR,"Bad stream CRC (got "+s.streamCRC.toString(16)+" expected "+a.toString(16)+")"),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i)}if("getBuffer"in i)return i.getBuffer()},decodeBlock:function(e,t,r){var n=Ky(e),i=Cy(r),s=new Sy(n,i);if(s.reader.seek(t),s._get_next_block()&&(s.blockCRC=new ky,s.writeCopies=0,s._read_bunzip()),"getBuffer"in i)return i.getBuffer()},table:function(e,t,r){var n=new by;n.delegate=Ky(e),n.pos=0,n.readByte=function(){return this.pos++,this.delegate.readByte()},n.delegate.eof&&(n.eof=n.delegate.eof.bind(n.delegate));var i=new by;i.pos=0,i.writeByte=function(){this.pos++};for(var s=new Sy(n,i),a=s.dbufSize;!("eof"in n)||!n.eof();){var o=8*n.pos+s.reader.bitOffset;if(s.reader.hasByte&&(o-=8),s._init_block()){var c=i.pos;s._read_bunzip(),t(o,i.pos-c)}else{if(s.reader.read(32),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i),console.assert(s.dbufSize===a,"shouldn't change block size within multistream file")}}}},Dy=/*#__PURE__*/r({__proto__:null},[Py]);return e.AEADEncryptedDataPacket=Da,e.CleartextMessage=Bo,e.CompressedDataPacket=ba,e.LiteralDataPacket=ca,e.MarkerPacket=class{static get tag(){return L.packet.marker}read(e){return 80===e[0]&&71===e[1]&&80===e[2]}write(){return new Uint8Array([80,71,80])}},e.Message=bo,e.OnePassSignaturePacket=da,e.PacketList=wa,e.PaddingPacket=class{static get tag(){return L.packet.padding}constructor(){this.padding=null}read(e){}write(){return this.padding}async createPadding(e){this.padding=await os.random.getRandomBytes(e)}},e.PrivateKey=yo,e.PublicKey=lo,e.PublicKeyEncryptedSessionKeyPacket=Ua,e.PublicKeyPacket=Ra,e.PublicSubkeyPacket=Ma,e.SecretKeyPacket=Fa,e.SecretSubkeyPacket=za,e.Signature=Ga,e.SignaturePacket=fa,e.Subkey=ao,e.SymEncryptedIntegrityProtectedDataPacket=Ka,e.SymEncryptedSessionKeyPacket=Qa,e.SymmetricallyEncryptedDataPacket=Ta,e.TrustPacket=class{static get tag(){return L.packet.trust}read(){throw new Vn("Trust packets are not supported")}write(){throw new Vn("Trust packets are not supported")}},e.UnparseablePacket=Yn,e.UserAttributePacket=Na,e.UserIDPacket=Oa,e.armor=ee,e.config=T,e.createCleartextMessage=async function({text:e,...t}){if(!e)throw Error("createCleartextMessage: must pass options object containing `text`");if(!N.isString(e))throw Error("createCleartextMessage: options.text must be a string");const r=Object.keys(t);if(r.length>0)throw Error("Unknown option: "+r.join(", "));return new Bo(e)},e.createMessage=async function({text:e,binary:t,filename:r,date:n=new Date,format:i=(void 0!==e?"utf8":"binary"),...s}){const a=void 0!==e?e:t;if(void 0===a)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!N.isString(e)&&!N.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!N.isUint8Array(t)&&!N.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=N.isStream(a),h=new ca(n);void 0!==e?h.setText(a,L.write(L.literal,i)):h.setBytes(a,L.write(L.literal,i)),void 0!==r&&h.setFilename(r);const u=new wa;u.push(h);const l=new bo(u);return l.fromStream=c,l},e.decrypt=async function({message:e,decryptionKeys:t,passwords:r,sessionKeys:n,verificationKeys:i,expectSigned:s=!1,format:a="utf8",signature:o=null,date:c=new Date,config:h,...u}){if(Po(h={...T,...h}),Io(e),i=Do(i),t=Do(t),r=Do(r),n=Do(n),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(u.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));try{const u=await e.decrypt(t,r,n,c,h);i||(i=[]);const l={};if(l.signatures=o?await u.verifyDetached(o,i,c,h):await u.verify(i,c,h),l.data="binary"===a?u.getLiteralData():u.getText(),l.filename=u.getFilename(),xo(l,e),s){if(0===i.length)throw Error("Verification keys are required to verify message signatures");if(0===l.signatures.length)throw Error("Message is not signed");l.data=w([l.data,U((async()=>{await N.anyPromise(l.signatures.map((e=>e.verified)))}))])}return l.data=await Uo(l.data),l}catch(e){throw N.wrapError("Error decrypting message",e)}},e.decryptKey=async function({privateKey:e,passphrase:t,config:r,...n}){Po(r={...T,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const s=e.clone(!0),a=N.isArray(t)?t:[t];try{return await Promise.all(s.getKeys().map((e=>N.anyPromise(a.map((t=>e.keyPacket.decrypt(t))))))),await s.validate(r),s}catch(e){throw s.clearPrivateParams(),N.wrapError("Error decrypting private key",e)}},e.decryptSessionKeys=async function({message:e,decryptionKeys:t,passwords:r,date:n=new Date,config:i,...s}){if(Po(i={...T,...i}),Io(e),t=Do(t),r=Do(r),s.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const a=Object.keys(s);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await e.decryptSessionKeys(t,r,void 0,n,i)}catch(e){throw N.wrapError("Error decrypting session keys",e)}},e.encrypt=async function({message:e,encryptionKeys:t,signingKeys:r,passwords:n,sessionKey:i,format:s="armored",signature:a=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:h=[],date:u=new Date,signingUserIDs:l=[],encryptionUserIDs:y=[],signatureNotations:f=[],config:g,...p}){if(Po(g={...T,...g}),Io(e),Ko(s),t=Do(t),r=Do(r),n=Do(n),c=Do(c),h=Do(h),l=Do(l),y=Do(y),f=Do(f),p.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(p.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(p.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==p.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const d=Object.keys(p);if(d.length>0)throw Error("Unknown option: "+d.join(", "));r||(r=[]);try{if((r.length||a)&&(e=await e.sign(r,t,a,c,u,l,h,f,g)),e=e.compress(await async function(e=[],t=new Date,r=[],n=T){const i=L.compression.uncompressed,s=n.preferredCompressionAlgorithm,a=await Promise.all(e.map((async function(e,i){const a=(await e.getPrimarySelfSignature(t,r[i],n)).preferredCompressionAlgorithms;return!!a&&a.indexOf(s)>=0})));return a.every(Boolean)?s:i}(t,u,y,g),g),e=await e.encrypt(t,n,i,o,h,u,y,g),"object"===s)return e;const p="armored"===s?e.armor(g):e.write();return await Uo(p)}catch(e){throw N.wrapError("Error encrypting message",e)}},e.encryptKey=async function({privateKey:e,passphrase:t,config:r,...n}){Po(r={...T,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const s=e.clone(!0),a=s.getKeys(),o=N.isArray(t)?t:Array(a.length).fill(t);if(o.length!==a.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(a.map((async(e,t)=>{const{keyPacket:n}=e;await n.encrypt(o[t],r),n.clearPrivateParams()}))),s}catch(e){throw s.clearPrivateParams(),N.wrapError("Error encrypting private key",e)}},e.encryptSessionKey=async function({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:n,passwords:i,format:s="armored",wildcard:a=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:h=[],config:u,...l}){if(Po(u={...T,...u}),function(e){if(!N.isUint8Array(e))throw Error("Parameter [data] must be of type Uint8Array")}(e),function(e,t){if(!N.isString(e))throw Error("Parameter ["+t+"] must be of type String")}(t,"algorithm"),Ko(s),n=Do(n),i=Do(i),o=Do(o),h=Do(h),l.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(!(n&&0!==n.length||i&&0!==i.length))throw Error("No encryption keys or passwords provided.");try{return Qo(await bo.encryptSessionKey(e,t,r,n,i,a,o,c,h,u),s,u)}catch(e){throw N.wrapError("Error encrypting session key",e)}},e.enums=L,e.generateKey=async function({userIDs:e=[],passphrase:t,type:r,curve:n,rsaBits:i=4096,keyExpirationTime:s=0,date:a=new Date,subkeys:o=[{}],format:c="armored",config:h,...u}){Po(h={...T,...h}),r||n?(r=r||"ecc",n=n||"curve25519Legacy"):(r=h.v6Keys?"curve25519":"ecc",n="curve25519Legacy"),e=Do(e);const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(0===e.length&&!h.v6Keys)throw Error("UserIDs are required for V4 keys");if("rsa"===r&&ieo(e.subkeys[r],e)));let r=[qa(e,t)];r=r.concat(e.subkeys.map((e=>ja(e,t))));const n=await Promise.all(r),i=await po(n[0],n.slice(1),e,t),s=await i.getRevocationCertificate(e.date,t);return i.revocationSignatures=[],{key:i,revocationCertificate:s}}(y,h);return e.getKeys().forEach((({keyPacket:e})=>io(e,h))),{privateKey:Qo(e,c,h),publicKey:Qo(e.toPublic(),c,h),revocationCertificate:t}}catch(e){throw N.wrapError("Error generating keypair",e)}},e.generateSessionKey=async function({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:n,...i}){if(Po(n={...T,...n}),e=Do(e),r=Do(r),i.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await bo.generateSessionKey(e,t,r,n)}catch(e){throw N.wrapError("Error generating session key",e)}},e.readCleartextMessage=async function({cleartextMessage:e,config:t,...r}){if(t={...T,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!N.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const n=Object.keys(r);if(n.length>0)throw Error("Unknown option: "+n.join(", "));const i=await X(e);if(i.type!==L.armor.signed)throw Error("No cleartext signed message.");const s=await wa.fromBinary(i.data,vo,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let n=0;n{const t=e.match(/^Hash: (.+)$/);if(!t)throw Error('Only "Hash" header allowed in cleartext signed message');{const e=t[1].replace(/\s/g,"").split(",").map((e=>{try{return L.write(L.hash,e.toLowerCase())}catch(t){throw Error("Unknown hash algorithm in armor header: "+e.toLowerCase())}}));n.push(...e)}})),n.length&&!r(n))throw Error("Hash algorithm mismatch in armor header and signature")}(i.headers,s);const a=new Ga(s);return new Bo(i.text,a)},e.readKey=async function({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...T,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!N.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!N.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await X(e);if(t!==L.armor.publicKey&&t!==L.armor.privateKey)throw Error("Armored text not of type key");s=r}else s=t;const a=await wa.fromBinary(s,fo,r),o=a.indexOfTag(L.packet.publicKey,L.packet.secretKey);if(0===o.length)throw Error("No key packet found");return go(a.slice(o[0],o[1]))},e.readKeys=async function({armoredKeys:e,binaryKeys:t,config:r,...n}){r={...T,...r};let i=e||t;if(!i)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!N.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!N.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:t,data:r}=await X(e);if(t!==L.armor.publicKey&&t!==L.armor.privateKey)throw Error("Armored text not of type key");i=r}const a=[],o=await wa.fromBinary(i,fo,r),c=o.indexOfTag(L.packet.publicKey,L.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));const a=N.isStream(i);if(e){const{type:e,data:t}=await X(i);if(e!==L.armor.message)throw Error("Armored text not of type message");i=t}const o=await wa.fromBinary(i,Ao,r),c=new bo(o);return c.fromStream=a,c},e.readPrivateKey=async function({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...T,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!N.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!N.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await X(e);if(t!==L.armor.privateKey)throw Error("Armored text not of type private key");s=r}else s=t;const a=await wa.fromBinary(s,fo,r),o=a.indexOfTag(L.packet.publicKey,L.packet.secretKey);for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:e,data:t}=await X(i);if(e!==L.armor.signature)throw Error("Armored text not of type signature");i=t}const a=await wa.fromBinary(i,_a,r);return new Ga(a)},e.reformatKey=async function({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:n=0,date:i,format:s="armored",config:a,...o}){Po(a={...T,...a}),t=Do(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length&&6!==e.keyPacket.version)throw Error("UserIDs are required for V4 keys");const h={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:n,date:i};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const n=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,i={key:n,bind:r},s=await Va(e.bindingSignatures,n,L.signature.subkeyBinding,i,null,t).catch((()=>({})));return{sign:s.keyFlags&&s.keyFlags[0]&L.keyFlags.signData}}))));const i=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==i.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const s=await po(n,i,e,t),a=await s.getRevocationCertificate(e.date,t);return s.revocationSignatures=[],{key:s,revocationCertificate:a};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=N.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(h,a);return{privateKey:Qo(e,s,a),publicKey:Qo(e.toPublic(),s,a),revocationCertificate:t}}catch(e){throw N.wrapError("Error reformatting keypair",e)}},e.revokeKey=async function({key:e,revocationCertificate:t,reasonForRevocation:r,date:n=new Date,format:i="armored",config:s,...a}){Po(s={...T,...s});const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const a=t?await e.applyRevocationCertificate(t,n,s):await e.revoke(r,n,s);return a.isPrivate()?{privateKey:Qo(a,i,s),publicKey:Qo(a.toPublic(),i,s)}:{privateKey:null,publicKey:Qo(a,i,s)}}catch(e){throw N.wrapError("Error revoking key",e)}},e.sign=async function({message:e,signingKeys:t,recipientKeys:r=[],format:n="armored",detached:i=!1,signingKeyIDs:s=[],date:a=new Date,signingUserIDs:o=[],recipientUserIDs:c=[],signatureNotations:h=[],config:u,...l}){if(Po(u={...T,...u}),So(e),Ko(n),t=Do(t),s=Do(s),o=Do(o),r=Do(r),c=Do(c),h=Do(h),l.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==l.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(e instanceof Bo&&"binary"===n)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Bo&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let l;if(l=i?await e.signDetached(t,r,void 0,s,a,o,c,h,u):await e.sign(t,r,void 0,s,a,o,c,h,u),"object"===n)return l;return l="armored"===n?l.armor(u):l.write(),i&&(l=v(e.packets.write(),(async(e,t)=>{await Promise.all([m(l,t),P(e).catch((()=>{}))])}))),await Uo(l)}catch(e){throw N.wrapError("Error signing message",e)}},e.unarmor=X,e.verify=async function({message:e,verificationKeys:t,expectSigned:r=!1,format:n="utf8",signature:i=null,date:s=new Date,config:a,...o}){if(Po(a={...T,...a}),So(e),t=Do(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Bo&&"binary"===n)throw Error("Can't return cleartext message data as binary");if(e instanceof Bo&&i)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=i?await e.verifyDetached(i,t,s,a):await e.verify(t,s,a),o.data="binary"===n?e.getLiteralData():e.getText(),e.fromStream&&!i&&xo(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=w([o.data,U((async()=>{await N.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Uo(o.data),o}catch(e){throw N.wrapError("Error verifying signed message",e)}},e}({}); //# sourceMappingURL=openpgp.min.js.map diff --git a/app/node_modules/openpgp/dist/openpgp.min.js.map b/app/node_modules/openpgp/dist/openpgp.min.js.map index 4140a59a3..c9f37c5ad 100644 --- a/app/node_modules/openpgp/dist/openpgp.min.js.map +++ b/app/node_modules/openpgp/dist/openpgp.min.js.map @@ -1 +1 @@ -{"version":3,"file":"openpgp.min.js","sources":["../node_modules/@openpgp/web-stream-tools/lib/writer.js","../node_modules/@openpgp/web-stream-tools/lib/util.js","../node_modules/@openpgp/web-stream-tools/lib/node-conversions.js","../node_modules/@openpgp/web-stream-tools/lib/reader.js","../node_modules/@openpgp/web-stream-tools/lib/streams.js","../src/biginteger/native.interface.js","../src/biginteger/index.js","../src/enums.js","../src/util.js","../src/encoding/base64.js","../src/config/config.js","../src/encoding/armor.js","../src/type/keyid.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.asm.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/other/utils.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/other/errors.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ecb.js","../src/crypto/cipher/aes.js","../src/crypto/cipher/des.js","../src/crypto/cipher/cast5.js","../src/crypto/cipher/twofish.js","../src/crypto/cipher/blowfish.js","../src/crypto/cipher/index.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.asm.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/hash.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.asm.js","../node_modules/minimalistic-assert/index.js","../node_modules/inherits/inherits_browser.js","../node_modules/hash.js/lib/hash/utils.js","../node_modules/hash.js/lib/hash/common.js","../node_modules/hash.js/lib/hash/sha/common.js","../node_modules/hash.js/lib/hash/sha/256.js","../node_modules/hash.js/lib/hash/sha/224.js","../node_modules/hash.js/lib/hash/sha/512.js","../node_modules/hash.js/lib/hash/sha/384.js","../node_modules/hash.js/lib/hash/ripemd.js","../src/crypto/hash/md5.js","../src/crypto/hash/index.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cfb.js","../src/crypto/cipher/getCipher.js","../src/crypto/mode/cfb.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ctr.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cbc.js","../src/crypto/cmac.js","../src/crypto/mode/eax.js","../src/crypto/mode/ocb.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/gcm.js","../src/crypto/mode/gcm.js","../src/crypto/mode/index.js","../node_modules/@openpgp/tweetnacl/nacl-fast-light.js","../src/crypto/random.js","../src/crypto/public_key/prime.js","../src/crypto/pkcs1.js","../src/crypto/public_key/rsa.js","../src/crypto/public_key/elgamal.js","../src/type/oid.js","../src/crypto/public_key/elliptic/indutnyKey.js","../src/packet/packet.js","../src/crypto/public_key/elliptic/oid_curves.js","../src/crypto/public_key/elliptic/ecdsa.js","../src/crypto/public_key/elliptic/eddsa_legacy.js","../src/crypto/public_key/elliptic/eddsa.js","../src/crypto/aes_kw.js","../src/crypto/pkcs5.js","../src/crypto/public_key/elliptic/ecdh.js","../src/crypto/hkdf.js","../src/crypto/public_key/elliptic/ecdh_x.js","../src/crypto/public_key/dsa.js","../src/crypto/public_key/index.js","../src/crypto/signature.js","../src/type/ecdh_symkey.js","../src/type/kdf_params.js","../src/type/ecdh_x_symkey.js","../src/crypto/crypto.js","../src/crypto/index.js","../node_modules/@openpgp/pako/lib/utils/common.js","../node_modules/@openpgp/pako/lib/zlib/constants.js","../node_modules/@openpgp/pako/lib/zlib/trees.js","../node_modules/@openpgp/pako/lib/zlib/adler32.js","../node_modules/@openpgp/pako/lib/zlib/crc32.js","../node_modules/@openpgp/pako/lib/zlib/messages.js","../node_modules/@openpgp/pako/lib/zlib/deflate.js","../node_modules/@openpgp/pako/lib/utils/strings.js","../node_modules/@openpgp/pako/lib/zlib/zstream.js","../node_modules/@openpgp/pako/lib/deflate.js","../node_modules/@openpgp/pako/lib/zlib/inffast.js","../node_modules/@openpgp/pako/lib/zlib/inftrees.js","../node_modules/@openpgp/pako/lib/zlib/inflate.js","../node_modules/@openpgp/pako/lib/zlib/gzheader.js","../node_modules/@openpgp/pako/lib/inflate.js","../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../node_modules/@openpgp/seek-bzip/lib/stream.js","../node_modules/@openpgp/seek-bzip/lib/crc32.js","../node_modules/@openpgp/seek-bzip/lib/index.js","../src/packet/literal_data.js","../src/packet/signature.js","../src/packet/one_pass_signature.js","../src/packet/packetlist.js","../src/packet/compressed_data.js","../src/packet/sym_encrypted_integrity_protected_data.js","../src/packet/aead_encrypted_data.js","../src/packet/public_key_encrypted_session_key.js","../src/type/s2k.js","../src/packet/sym_encrypted_session_key.js","../src/packet/public_key.js","../src/packet/symmetrically_encrypted_data.js","../src/packet/public_subkey.js","../src/packet/user_attribute.js","../src/packet/secret_key.js","../node_modules/email-addresses/lib/email-addresses.js","../src/packet/userid.js","../src/packet/secret_subkey.js","../src/signature.js","../src/key/helper.js","../src/key/user.js","../src/key/subkey.js","../src/key/key.js","../src/key/public_key.js","../src/key/private_key.js","../src/key/factory.js","../src/message.js","../src/cleartext.js","../src/openpgp.js","../node_modules/@openpgp/web-stream-tools/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs","../node_modules/@mattiasbuelens/web-streams-adapter/dist/web-streams-adapter.mjs","../node_modules/bn.js/lib/bn.js","../src/biginteger/bn.interface.js","../node_modules/brorand/index.js","../node_modules/minimalistic-crypto-utils/lib/utils.js","../node_modules/@openpgp/elliptic/lib/elliptic/utils.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/base.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/short.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/mont.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/edwards.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/index.js","../node_modules/hash.js/lib/hash/sha/1.js","../node_modules/hash.js/lib/hash/sha.js","../node_modules/hash.js/lib/hash/hmac.js","../node_modules/hash.js/lib/hash.js","../node_modules/@openpgp/elliptic/lib/elliptic/precomputed/secp256k1.js","../node_modules/@openpgp/elliptic/lib/elliptic/curves.js","../node_modules/hmac-drbg/lib/hmac-drbg.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/key.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/signature.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/index.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/key.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/signature.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/index.js","../node_modules/@openpgp/elliptic/lib/elliptic.js","../src/packet/marker.js","../src/packet/trust.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","import * as streams from './streams';\nimport { isArrayStream } from './writer';\n\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n if (streams.ReadableStream && streams.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'ponyfill';\n }\n if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {\n return 'node';\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isNode } from './util';\nimport * as streams from './streams';\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Web / node stream conversion functions\n * From https://github.com/gwicke/node-web-streams\n */\n\nlet nodeToWeb;\nlet webToNode;\n\nif (NodeReadableStream) {\n\n /**\n * Convert a Node Readable Stream to a Web ReadableStream\n * @param {Readable} nodeStream\n * @returns {ReadableStream}\n */\n nodeToWeb = function(nodeStream) {\n let canceled = false;\n return new streams.ReadableStream({\n start(controller) {\n nodeStream.pause();\n nodeStream.on('data', chunk => {\n if (canceled) {\n return;\n }\n if (NodeBuffer.isBuffer(chunk)) {\n chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n controller.enqueue(chunk);\n nodeStream.pause();\n });\n nodeStream.on('end', () => {\n if (canceled) {\n return;\n }\n controller.close();\n });\n nodeStream.on('error', e => controller.error(e));\n },\n pull() {\n nodeStream.resume();\n },\n cancel(reason) {\n canceled = true;\n nodeStream.destroy(reason);\n }\n });\n };\n\n\n class NodeReadable extends NodeReadableStream {\n constructor(webStream, options) {\n super(options);\n this._reader = streams.getReader(webStream);\n }\n\n async _read(size) {\n try {\n while (true) {\n const { done, value } = await this._reader.read();\n if (done) {\n this.push(null);\n break;\n }\n if (!this.push(value)) {\n break;\n }\n }\n } catch (e) {\n this.destroy(e);\n }\n }\n\n async _destroy(error, callback) {\n this._reader.cancel(error).then(callback, callback);\n }\n }\n\n /**\n * Convert a Web ReadableStream to a Node Readable Stream\n * @param {ReadableStream} webStream\n * @param {Object} options\n * @returns {Readable}\n */\n webToNode = function(webStream, options) {\n return new NodeReadable(webStream, options);\n };\n\n}\n\nexport { nodeToWeb, webToNode };\n","import * as streams from './streams';\nimport { isUint8Array } from './util';\n\nconst doneReadingSet = new WeakSet();\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (streams.isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = async () => {};\n return;\n }\n let streamType = streams.isStream(input);\n if (streamType === 'node') {\n input = streams.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array } from './util';\nimport { nodeToWeb, webToNode } from './node-conversions';\nimport { Reader, externalBuffer } from './reader';\nimport { ArrayStream, Writer } from './writer';\n\nlet { ReadableStream, WritableStream, TransformStream } = globalThis;\n\nlet toPonyfillReadable, toNativeReadable;\n\nasync function loadStreamsPonyfill() {\n if (TransformStream) {\n return;\n }\n\n const [ponyfill, adapter] = await Promise.all([\n import('web-streams-polyfill/ponyfill/es6'),\n import('@mattiasbuelens/web-streams-adapter')\n ]);\n\n ({ ReadableStream, WritableStream, TransformStream } = ponyfill);\n\n const { createReadableStreamWrapper } = adapter;\n\n if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {\n toPonyfillReadable = createReadableStreamWrapper(ReadableStream);\n toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);\n }\n}\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType === 'node') {\n return nodeToWeb(input);\n }\n if (streamType === 'web' && toPonyfillReadable) {\n return toPonyfillReadable(input);\n }\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert data to ArrayStream\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {\n return NodeBuffer.concat(list);\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n } else {\n lastBytes = returnValue;\n }\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {\n if (end === Infinity) end = input.length;\n return input.subarray(begin, end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n return input.cancel(reason);\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n\nexport { ReadableStream, WritableStream, TransformStream, ArrayStream, loadStreamsPonyfill, isStream, isArrayStream, isUint8Array, toStream, toPonyfillReadable, toNativeReadable, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };\n","/* eslint-disable new-cap */\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * that wraps the native BigInt library.\n * Operations are not constant time,\n * but we try and limit timing leakage where we can\n * @module biginteger/native\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on null or undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n if (n instanceof Uint8Array) {\n const bytes = n;\n const hex = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n const hexByte = bytes[i].toString(16);\n hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;\n }\n this.value = BigInt('0x0' + hex.join(''));\n } else {\n this.value = BigInt(n);\n }\n }\n\n clone() {\n return new BigInteger(this.value);\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value++;\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value--;\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value += x.value;\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value -= x.value;\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value *= x.value;\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value %= m.value;\n if (this.isNegative()) {\n this.iadd(m);\n }\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation using square and multiply\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n if (n.isZero()) throw Error('Modulo cannot be zero');\n if (n.isOne()) return new BigInteger(0);\n if (e.isNegative()) throw Error('Unsopported negative exponent');\n\n let exp = e.value;\n let x = this.value;\n\n x %= n.value;\n let r = BigInt(1);\n while (exp > BigInt(0)) {\n const lsb = exp & BigInt(1);\n exp >>= BigInt(1); // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n.value;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n.value; // Square\n }\n return new BigInteger(r);\n }\n\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n const { gcd, x } = this._egcd(n);\n if (!gcd.isOne()) {\n throw new Error('Inverse does not exist');\n }\n return x.add(n).mod(n);\n }\n\n /**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)\n * @param {BigInteger} b - Second operand\n * @returns {{ gcd, x, y: BigInteger }}\n */\n _egcd(b) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n let a = this.value;\n b = b.value;\n\n while (b !== BigInt(0)) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: new BigInteger(xPrev),\n y: new BigInteger(yPrev),\n gcd: new BigInteger(a)\n };\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} b - Operand\n * @returns {BigInteger} gcd\n */\n gcd(b) {\n let a = this.value;\n b = b.value;\n while (b !== BigInt(0)) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return new BigInteger(a);\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value <<= x.value;\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value >>= x.value;\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value === x.value;\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value < x.value;\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value <= x.value;\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value > x.value;\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value >= x.value;\n }\n\n isZero() {\n return this.value === BigInt(0);\n }\n\n isOne() {\n return this.value === BigInt(1);\n }\n\n isNegative() {\n return this.value < BigInt(0);\n }\n\n isEven() {\n return !(this.value & BigInt(1));\n }\n\n abs() {\n const res = this.clone();\n if (this.isNegative()) {\n res.value = -res.value;\n }\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n const number = Number(this.value);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n const bit = (this.value >> BigInt(i)) & BigInt(1);\n return (bit === BigInt(0)) ? 0 : 1;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n const zero = new BigInteger(0);\n const one = new BigInteger(1);\n const negOne = new BigInteger(-1);\n\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = this.isNegative() ? negOne : zero;\n let bitlen = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(one).equal(target)) {\n bitlen++;\n }\n return bitlen;\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n const zero = new BigInteger(0);\n const negOne = new BigInteger(-1);\n\n const target = this.isNegative() ? negOne : zero;\n const eight = new BigInteger(8);\n let len = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(eight).equal(target)) {\n len++;\n }\n return len;\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = this.value.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? (length - rawLength) : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n }\n}\n","import BigInteger from './native.interface';\n\nconst detectBigInt = () => typeof BigInt !== 'undefined';\n\nasync function getBigInteger() {\n if (detectBigInt()) {\n return BigInteger;\n } else {\n const { default: BigInteger } = await import('./bn.interface');\n return BigInteger;\n }\n}\n\nexport { getBigInteger };\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'p256': 'p256',\n 'P-256': 'p256',\n 'secp256r1': 'p256',\n 'prime256v1': 'p256',\n '1.2.840.10045.3.1.7': 'p256',\n '2a8648ce3d030107': 'p256',\n '2A8648CE3D030107': 'p256',\n\n /** NIST P-384 Curve */\n 'p384': 'p384',\n 'P-384': 'p384',\n 'secp384r1': 'p384',\n '1.3.132.0.34': 'p384',\n '2b81040022': 'p384',\n '2B81040022': 'p384',\n\n /** NIST P-521 Curve */\n 'p521': 'p521',\n 'P-521': 'p521',\n 'secp521r1': 'p521',\n '1.3.132.0.35': 'p521',\n '2b81040023': 'p521',\n '2B81040023': 'p521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n '1.3.132.0.10': 'secp256k1',\n '2b8104000a': 'secp256k1',\n '2B8104000A': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519',\n 'ED25519': 'ed25519',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519',\n 'Ed25519': 'ed25519',\n '1.3.6.1.4.1.11591.15.1': 'ed25519',\n '2b06010401da470f01': 'ed25519',\n '2B06010401DA470F01': 'ed25519',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519',\n 'X25519': 'curve25519',\n 'cv25519': 'curve25519',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519',\n 'Curve25519': 'curve25519',\n '1.3.6.1.4.1.3029.1.5.1': 'curve25519',\n '2b060104019755010501': 'curve25519',\n '2B060104019755010501': 'curve25519',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',\n '2b2403030208010107': 'brainpoolP256r1',\n '2B2403030208010107': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',\n '2b240303020801010b': 'brainpoolP384r1',\n '2B240303020801010B': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1',\n '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',\n '2b240303020801010d': 'brainpoolP512r1',\n '2B240303020801010D': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility\n /** @deprecated use `eddsaLegacy` instead */\n ed25519Legacy: 22,\n /** @deprecated use `eddsaLegacy` instead */\n eddsa: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n plaintext: 0,\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuer: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { getBigInteger } from './biginteger';\nimport enums from './enums';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n return bytes.subarray(2, 2 + bytelen);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const r = [];\n const e = bytes.length;\n let c = 0;\n let h;\n while (c < e) {\n h = bytes[c++].toString(16);\n while (h.length < 2) {\n h = '0' + h;\n }\n r.push('' + h);\n }\n return r.join('');\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography api, only the current version of the spec.\n * @returns {Object} The SubtleCrypto api or 'undefined'.\n */\n getWebCrypto: function() {\n return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n },\n\n /**\n * Get BigInteger class\n * It wraps the native BigInt type if it's available\n * Otherwise it relies on bn.js\n * @returns {BigInteger}\n * @async\n */\n getBigInteger,\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return require('crypto');\n },\n\n getNodeZlib: function() {\n return require('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (require('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = require('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\\-0-9]+)))$/;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha256,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * @memberof module:config\n * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9\n */\n deflateLevel: 6,\n\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.eax,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use V5 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v5Keys\n */\n v5Keys: false,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:\n * Iteration Count Byte for S2K (String to Key)\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * @memberof module:config\n * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum\n */\n checksumRequired: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * @memberof module:config\n * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored\n */\n revocationsExpire: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n\n /**\n * @memberof module:config\n * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available\n */\n minBytesForWebCrypto: 1000,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * Note: the indutny/elliptic curve library is not designed to be constant time.\n * @memberof module:config\n * @property {Boolean} useIndutnyElliptic\n */\n useIndutnyElliptic: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n } else\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n } else\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n } else\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n } else\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n } else\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n } else\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Splits a message into two parts, the body and the checksum. This is an internal function\n * @param {String} text - OpenPGP armored message part\n * @returns {Object} An object with attribute \"body\" containing the body.\n * and an attribute \"checksum\" containing the checksum.\n * @private\n */\nfunction splitChecksum(text) {\n let body = text;\n let checksum = '';\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n checksum = text.slice(lastEquals + 1).substr(0, 4);\n }\n\n return { body: body, checksum: checksum };\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input, config = defaultConfig) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n let checksum;\n let data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== 2) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === 2) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const split = splitChecksum(parts[0].slice(0, -1));\n checksum = split.checksum;\n await writer.write(split.body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n data = stream.transformPair(data, async (readable, writable) => {\n const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));\n checksumVerified.catch(() => {});\n await stream.pipe(readable, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n const checksumVerifiedString = (await checksumVerified).replace('\\n', '');\n if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {\n throw new Error('Ascii armor integrity check failed');\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n const bodyClone = stream.passiveClone(body);\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push('Hash: ' + hash + '\\n\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n * @private\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","/**\n * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.\n * @author Artem S Vybornov \n * @license MIT\n */\nexport var AES_asm = function () {\n \"use strict\";\n\n /**\n * Galois Field stuff init flag\n */\n var ginit_done = false;\n\n /**\n * Galois Field exponentiation and logarithm tables for 3 (the generator)\n */\n var gexp3, glog3;\n\n /**\n * Init Galois Field tables\n */\n function ginit() {\n gexp3 = [],\n glog3 = [];\n\n var a = 1, c, d;\n for (c = 0; c < 255; c++) {\n gexp3[c] = a;\n\n // Multiply by three\n d = a & 0x80, a <<= 1, a &= 255;\n if (d === 0x80) a ^= 0x1b;\n a ^= gexp3[c];\n\n // Set the log table value\n glog3[gexp3[c]] = c;\n }\n gexp3[255] = gexp3[0];\n glog3[0] = 0;\n\n ginit_done = true;\n }\n\n /**\n * Galois Field multiplication\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\n function gmul(a, b) {\n var c = gexp3[(glog3[a] + glog3[b]) % 255];\n if (a === 0 || b === 0) c = 0;\n return c;\n }\n\n /**\n * Galois Field reciprocal\n * @param {number} a\n * @return {number}\n */\n function ginv(a) {\n var i = gexp3[255 - glog3[a]];\n if (a === 0) i = 0;\n return i;\n }\n\n /**\n * AES stuff init flag\n */\n var aes_init_done = false;\n\n /**\n * Encryption, Decryption, S-Box and KeyTransform tables\n *\n * @type {number[]}\n */\n var aes_sbox;\n\n /**\n * @type {number[]}\n */\n var aes_sinv;\n\n /**\n * @type {number[][]}\n */\n var aes_enc;\n\n /**\n * @type {number[][]}\n */\n var aes_dec;\n\n /**\n * Init AES tables\n */\n function aes_init() {\n if (!ginit_done) ginit();\n\n // Calculates AES S-Box value\n function _s(a) {\n var c, s, x;\n s = x = ginv(a);\n for (c = 0; c < 4; c++) {\n s = ((s << 1) | (s >>> 7)) & 255;\n x ^= s;\n }\n x ^= 99;\n return x;\n }\n\n // Tables\n aes_sbox = [],\n aes_sinv = [],\n aes_enc = [[], [], [], []],\n aes_dec = [[], [], [], []];\n\n for (var i = 0; i < 256; i++) {\n var s = _s(i);\n\n // S-Box and its inverse\n aes_sbox[i] = s;\n aes_sinv[s] = i;\n\n // Ecryption and Decryption tables\n aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);\n aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);\n // Rotate tables\n for (var t = 1; t < 4; t++) {\n aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);\n aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);\n }\n }\n\n aes_init_done = true;\n }\n\n /**\n * Asm.js module constructor.\n *\n *

\n * Heap buffer layout by offset:\n *

\n   * 0x0000   encryption key schedule\n   * 0x0400   decryption key schedule\n   * 0x0800   sbox\n   * 0x0c00   inv sbox\n   * 0x1000   encryption tables\n   * 0x2000   decryption tables\n   * 0x3000   reserved (future GCM multiplication lookup table)\n   * 0x4000   data\n   * 
\n * Don't touch anything before 0x400.\n *

\n *\n * @alias AES_asm\n * @class\n * @param foreign - ignored\n * @param buffer - heap buffer to link with\n */\n var wrapper = function (foreign, buffer) {\n // Init AES stuff for the first time\n if (!aes_init_done) aes_init();\n\n // Fill up AES tables\n var heap = new Uint32Array(buffer);\n heap.set(aes_sbox, 0x0800 >> 2);\n heap.set(aes_sinv, 0x0c00 >> 2);\n for (var i = 0; i < 4; i++) {\n heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);\n heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);\n }\n\n /**\n * Calculate AES key schedules.\n * @instance\n * @memberof AES_asm\n * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)\n * @param {number} k0 - key vector components\n * @param {number} k1 - key vector components\n * @param {number} k2 - key vector components\n * @param {number} k3 - key vector components\n * @param {number} k4 - key vector components\n * @param {number} k5 - key vector components\n * @param {number} k6 - key vector components\n * @param {number} k7 - key vector components\n */\n function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {\n var ekeys = heap.subarray(0x000, 60),\n dkeys = heap.subarray(0x100, 0x100 + 60);\n\n // Encryption key schedule\n ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);\n for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {\n var k = ekeys[i - 1];\n if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {\n k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];\n }\n if (i % ks === 0) {\n k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);\n }\n ekeys[i] = ekeys[i - ks] ^ k;\n }\n\n // Decryption key schedule\n for (var j = 0; j < i; j += 4) {\n for (var jj = 0; jj < 4; jj++) {\n var k = ekeys[i - (4 + j) + (4 - jj) % 4];\n if (j < 4 || j >= i - 4) {\n dkeys[j + jj] = k;\n } else {\n dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]\n ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]\n ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]\n ^ aes_dec[3][aes_sbox[k & 255]];\n }\n }\n }\n\n // Set rounds number\n asm.set_rounds(ks + 5);\n }\n\n // create library object with necessary properties\n var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};\n\n var asm = function (stdlib, foreign, buffer) {\n \"use asm\";\n\n var S0 = 0, S1 = 0, S2 = 0, S3 = 0,\n I0 = 0, I1 = 0, I2 = 0, I3 = 0,\n N0 = 0, N1 = 0, N2 = 0, N3 = 0,\n M0 = 0, M1 = 0, M2 = 0, M3 = 0,\n H0 = 0, H1 = 0, H2 = 0, H3 = 0,\n R = 0;\n\n var HEAP = new stdlib.Uint32Array(buffer),\n DATA = new stdlib.Uint8Array(buffer);\n\n /**\n * AES core\n * @param {number} k - precomputed key schedule offset\n * @param {number} s - precomputed sbox table offset\n * @param {number} t - precomputed round table offset\n * @param {number} r - number of inner rounds to perform\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _core(k, s, t, r, x0, x1, x2, x3) {\n k = k | 0;\n s = s | 0;\n t = t | 0;\n r = r | 0;\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t1 = 0, t2 = 0, t3 = 0,\n y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n i = 0;\n\n t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;\n\n // round 0\n x0 = x0 ^ HEAP[(k | 0) >> 2],\n x1 = x1 ^ HEAP[(k | 4) >> 2],\n x2 = x2 ^ HEAP[(k | 8) >> 2],\n x3 = x3 ^ HEAP[(k | 12) >> 2];\n\n // round 1..r\n for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {\n y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n x0 = y0, x1 = y1, x2 = y2, x3 = y3;\n }\n\n // final round\n S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n }\n\n /**\n * ECB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n x0,\n x1,\n x2,\n x3\n );\n }\n\n /**\n * ECB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n }\n\n\n /**\n * CBC mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0 ^ x0,\n I1 ^ x1,\n I2 ^ x2,\n I3 ^ x3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n }\n\n /**\n * CBC mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n\n S0 = S0 ^ I0,\n S1 = S1 ^ I1,\n S2 = S2 ^ I2,\n S3 = S3 ^ I3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * CFB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0 = S0 ^ x0,\n I1 = S1 = S1 ^ x1,\n I2 = S2 = S2 ^ x2,\n I3 = S3 = S3 ^ x3;\n }\n\n\n /**\n * CFB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * OFB mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ofb(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n }\n\n /**\n * CTR mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ctr(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n N0,\n N1,\n N2,\n N3\n );\n\n N3 = (~M3 & N3) | M3 & (N3 + 1);\n N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));\n N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));\n N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));\n\n S0 = S0 ^ x0;\n S1 = S1 ^ x1;\n S2 = S2 ^ x2;\n S3 = S3 ^ x3;\n }\n\n /**\n * GCM mode MAC calculation\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _gcm_mac(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n z0 = 0, z1 = 0, z2 = 0, z3 = 0,\n i = 0, c = 0;\n\n x0 = x0 ^ I0,\n x1 = x1 ^ I1,\n x2 = x2 ^ I2,\n x3 = x3 ^ I3;\n\n y0 = H0 | 0,\n y1 = H1 | 0,\n y2 = H2 | 0,\n y3 = H3 | 0;\n\n for (; (i | 0) < 128; i = (i + 1) | 0) {\n if (y0 >>> 31) {\n z0 = z0 ^ x0,\n z1 = z1 ^ x1,\n z2 = z2 ^ x2,\n z3 = z3 ^ x3;\n }\n\n y0 = (y0 << 1) | (y1 >>> 31),\n y1 = (y1 << 1) | (y2 >>> 31),\n y2 = (y2 << 1) | (y3 >>> 31),\n y3 = (y3 << 1);\n\n c = x3 & 1;\n\n x3 = (x3 >>> 1) | (x2 << 31),\n x2 = (x2 >>> 1) | (x1 << 31),\n x1 = (x1 >>> 1) | (x0 << 31),\n x0 = (x0 >>> 1);\n\n if (c) x0 = x0 ^ 0xe1000000;\n }\n\n I0 = z0,\n I1 = z1,\n I2 = z2,\n I3 = z3;\n }\n\n /**\n * Set the internal rounds number.\n * @instance\n * @memberof AES_asm\n * @param {number} r - number if inner AES rounds\n */\n function set_rounds(r) {\n r = r | 0;\n R = r;\n }\n\n /**\n * Populate the internal state of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} s0 - state vector\n * @param {number} s1 - state vector\n * @param {number} s2 - state vector\n * @param {number} s3 - state vector\n */\n function set_state(s0, s1, s2, s3) {\n s0 = s0 | 0;\n s1 = s1 | 0;\n s2 = s2 | 0;\n s3 = s3 | 0;\n\n S0 = s0,\n S1 = s1,\n S2 = s2,\n S3 = s3;\n }\n\n /**\n * Populate the internal iv of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} i0 - iv vector\n * @param {number} i1 - iv vector\n * @param {number} i2 - iv vector\n * @param {number} i3 - iv vector\n */\n function set_iv(i0, i1, i2, i3) {\n i0 = i0 | 0;\n i1 = i1 | 0;\n i2 = i2 | 0;\n i3 = i3 | 0;\n\n I0 = i0,\n I1 = i1,\n I2 = i2,\n I3 = i3;\n }\n\n /**\n * Set nonce for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} n0 - nonce vector\n * @param {number} n1 - nonce vector\n * @param {number} n2 - nonce vector\n * @param {number} n3 - nonce vector\n */\n function set_nonce(n0, n1, n2, n3) {\n n0 = n0 | 0;\n n1 = n1 | 0;\n n2 = n2 | 0;\n n3 = n3 | 0;\n\n N0 = n0,\n N1 = n1,\n N2 = n2,\n N3 = n3;\n }\n\n /**\n * Set counter mask for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} m0 - counter mask vector\n * @param {number} m1 - counter mask vector\n * @param {number} m2 - counter mask vector\n * @param {number} m3 - counter mask vector\n */\n function set_mask(m0, m1, m2, m3) {\n m0 = m0 | 0;\n m1 = m1 | 0;\n m2 = m2 | 0;\n m3 = m3 | 0;\n\n M0 = m0,\n M1 = m1,\n M2 = m2,\n M3 = m3;\n }\n\n /**\n * Set counter for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} c0 - counter vector\n * @param {number} c1 - counter vector\n * @param {number} c2 - counter vector\n * @param {number} c3 - counter vector\n */\n function set_counter(c0, c1, c2, c3) {\n c0 = c0 | 0;\n c1 = c1 | 0;\n c2 = c2 | 0;\n c3 = c3 | 0;\n\n N3 = (~M3 & N3) | M3 & c3,\n N2 = (~M2 & N2) | M2 & c2,\n N1 = (~M1 & N1) | M1 & c1,\n N0 = (~M0 & N0) | M0 & c0;\n }\n\n /**\n * Store the internal state vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_state(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n return 16;\n }\n\n /**\n * Store the internal iv vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_iv(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = I0 >>> 24,\n DATA[pos | 1] = I0 >>> 16 & 255,\n DATA[pos | 2] = I0 >>> 8 & 255,\n DATA[pos | 3] = I0 & 255,\n DATA[pos | 4] = I1 >>> 24,\n DATA[pos | 5] = I1 >>> 16 & 255,\n DATA[pos | 6] = I1 >>> 8 & 255,\n DATA[pos | 7] = I1 & 255,\n DATA[pos | 8] = I2 >>> 24,\n DATA[pos | 9] = I2 >>> 16 & 255,\n DATA[pos | 10] = I2 >>> 8 & 255,\n DATA[pos | 11] = I2 & 255,\n DATA[pos | 12] = I3 >>> 24,\n DATA[pos | 13] = I3 >>> 16 & 255,\n DATA[pos | 14] = I3 >>> 8 & 255,\n DATA[pos | 15] = I3 & 255;\n\n return 16;\n }\n\n /**\n * GCM initialization.\n * @instance\n * @memberof AES_asm\n */\n function gcm_init() {\n _ecb_enc(0, 0, 0, 0);\n H0 = S0,\n H1 = S1,\n H2 = S2,\n H3 = S3;\n }\n\n /**\n * Perform ciphering operation on the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function cipher(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _cipher_modes[mode & 7](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * Calculates MAC of the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function mac(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _mac_modes[mode & 1](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * AES cipher modes table (virual methods)\n */\n var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];\n\n /**\n * AES MAC modes table (virual methods)\n */\n var _mac_modes = [_cbc_enc, _gcm_mac];\n\n /**\n * Asm.js module exports\n */\n return {\n set_rounds: set_rounds,\n set_state: set_state,\n set_iv: set_iv,\n set_nonce: set_nonce,\n set_mask: set_mask,\n set_counter: set_counter,\n get_state: get_state,\n get_iv: get_iv,\n gcm_init: gcm_init,\n cipher: cipher,\n mac: mac,\n };\n }(stdlib, foreign, buffer);\n\n asm.set_key = set_key;\n\n return asm;\n };\n\n /**\n * AES enciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.ENC = {\n ECB: 0,\n CBC: 2,\n CFB: 4,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES deciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.DEC = {\n ECB: 1,\n CBC: 3,\n CFB: 5,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES MAC mode constants\n * @enum {number}\n * @const\n */\n wrapper.MAC = {\n CBC: 0,\n GCM: 1,\n };\n\n /**\n * Heap data offset\n * @type {number}\n * @const\n */\n wrapper.HEAP_DATA = 0x4000;\n\n return wrapper;\n}();\n","const local_atob = typeof atob === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'base64').toString('binary') : atob;\nconst local_btoa = typeof btoa === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'binary').toString('base64') : btoa;\nexport function string_to_bytes(str, utf8 = false) {\n var len = str.length, bytes = new Uint8Array(utf8 ? 4 * len : len);\n for (var i = 0, j = 0; i < len; i++) {\n var c = str.charCodeAt(i);\n if (utf8 && 0xd800 <= c && c <= 0xdbff) {\n if (++i >= len)\n throw new Error('Malformed string, low surrogate expected at position ' + i);\n c = ((c ^ 0xd800) << 10) | 0x10000 | (str.charCodeAt(i) ^ 0xdc00);\n }\n else if (!utf8 && c >>> 8) {\n throw new Error('Wide characters are not allowed.');\n }\n if (!utf8 || c <= 0x7f) {\n bytes[j++] = c;\n }\n else if (c <= 0x7ff) {\n bytes[j++] = 0xc0 | (c >> 6);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else if (c <= 0xffff) {\n bytes[j++] = 0xe0 | (c >> 12);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else {\n bytes[j++] = 0xf0 | (c >> 18);\n bytes[j++] = 0x80 | ((c >> 12) & 0x3f);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n }\n return bytes.subarray(0, j);\n}\nexport function hex_to_bytes(str) {\n var len = str.length;\n if (len & 1) {\n str = '0' + str;\n len++;\n }\n var bytes = new Uint8Array(len >> 1);\n for (var i = 0; i < len; i += 2) {\n bytes[i >> 1] = parseInt(str.substr(i, 2), 16);\n }\n return bytes;\n}\nexport function base64_to_bytes(str) {\n return string_to_bytes(local_atob(str));\n}\nexport function bytes_to_string(bytes, utf8 = false) {\n var len = bytes.length, chars = new Array(len);\n for (var i = 0, j = 0; i < len; i++) {\n var b = bytes[i];\n if (!utf8 || b < 128) {\n chars[j++] = b;\n }\n else if (b >= 192 && b < 224 && i + 1 < len) {\n chars[j++] = ((b & 0x1f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 224 && b < 240 && i + 2 < len) {\n chars[j++] = ((b & 0xf) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 240 && b < 248 && i + 3 < len) {\n var c = ((b & 7) << 18) | ((bytes[++i] & 0x3f) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n if (c <= 0xffff) {\n chars[j++] = c;\n }\n else {\n c ^= 0x10000;\n chars[j++] = 0xd800 | (c >> 10);\n chars[j++] = 0xdc00 | (c & 0x3ff);\n }\n }\n else {\n throw new Error('Malformed UTF8 character at byte offset ' + i);\n }\n }\n var str = '', bs = 16384;\n for (var i = 0; i < j; i += bs) {\n str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));\n }\n return str;\n}\nexport function bytes_to_hex(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var h = (arr[i] & 0xff).toString(16);\n if (h.length < 2)\n str += '0';\n str += h;\n }\n return str;\n}\nexport function bytes_to_base64(arr) {\n return local_btoa(bytes_to_string(arr));\n}\nexport function pow2_ceil(a) {\n a -= 1;\n a |= a >>> 1;\n a |= a >>> 2;\n a |= a >>> 4;\n a |= a >>> 8;\n a |= a >>> 16;\n a += 1;\n return a;\n}\nexport function is_number(a) {\n return typeof a === 'number';\n}\nexport function is_string(a) {\n return typeof a === 'string';\n}\nexport function is_buffer(a) {\n return a instanceof ArrayBuffer;\n}\nexport function is_bytes(a) {\n return a instanceof Uint8Array;\n}\nexport function is_typed_array(a) {\n return (a instanceof Int8Array ||\n a instanceof Uint8Array ||\n a instanceof Int16Array ||\n a instanceof Uint16Array ||\n a instanceof Int32Array ||\n a instanceof Uint32Array ||\n a instanceof Float32Array ||\n a instanceof Float64Array);\n}\nexport function _heap_init(heap, heapSize) {\n const size = heap ? heap.byteLength : heapSize || 65536;\n if (size & 0xfff || size <= 0)\n throw new Error('heap size must be a positive integer and a multiple of 4096');\n heap = heap || new Uint8Array(new ArrayBuffer(size));\n return heap;\n}\nexport function _heap_write(heap, hpos, data, dpos, dlen) {\n const hlen = heap.length - hpos;\n const wlen = hlen < dlen ? hlen : dlen;\n heap.set(data.subarray(dpos, dpos + wlen), hpos);\n return wlen;\n}\nexport function joinBytes(...arg) {\n const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);\n const ret = new Uint8Array(totalLenght);\n let cursor = 0;\n for (let i = 0; i < arg.length; i++) {\n ret.set(arg[i], cursor);\n cursor += arg[i].length;\n }\n return ret;\n}\n","export class IllegalStateError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });\n }\n}\nexport class IllegalArgumentError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });\n }\n}\nexport class SecurityError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'SecurityError' } });\n }\n}\n","import { AES_asm } from './aes.asm';\nimport { _heap_init, _heap_write, is_bytes } from '../other/utils';\nimport { IllegalArgumentError, SecurityError } from '../other/errors';\nconst heap_pool = [];\nconst asm_pool = [];\nexport class AES {\n constructor(key, iv, padding = true, mode, heap, asm) {\n this.pos = 0;\n this.len = 0;\n this.mode = mode;\n // The AES object state\n this.pos = 0;\n this.len = 0;\n this.key = key;\n this.iv = iv;\n this.padding = padding;\n // The AES \"worker\"\n this.acquire_asm(heap, asm);\n }\n acquire_asm(heap, asm) {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);\n this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);\n this.reset(this.key, this.iv);\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n reset(key, iv) {\n const { asm } = this.acquire_asm();\n // Key\n const keylen = key.length;\n if (keylen !== 16 && keylen !== 24 && keylen !== 32)\n throw new IllegalArgumentError('illegal key size');\n const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);\n asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);\n // IV\n if (iv !== undefined) {\n if (iv.length !== 16)\n throw new IllegalArgumentError('illegal iv size');\n let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));\n }\n else {\n asm.set_iv(0, 0, 0, 0);\n }\n }\n AES_Encrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n let result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Encrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let plen = 16 - (len % 16);\n let rlen = len;\n if (this.hasOwnProperty('padding')) {\n if (this.padding) {\n for (let p = 0; p < plen; ++p) {\n heap[pos + len + p] = plen;\n }\n len += plen;\n rlen = len;\n }\n else if (len % 16) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n }\n else {\n len += plen;\n }\n const result = new Uint8Array(rlen);\n if (len)\n asm.cipher(amode, hpos + pos, len);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n AES_Decrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let plen = 0;\n let wlen = 0;\n if (this.padding) {\n plen = len + dlen - rlen || 16;\n rlen -= plen;\n }\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Decrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let rlen = len;\n if (len > 0) {\n if (len % 16) {\n if (this.hasOwnProperty('padding')) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n else {\n len += 16 - (len % 16);\n }\n }\n asm.cipher(amode, hpos + pos, len);\n if (this.hasOwnProperty('padding') && this.padding) {\n let pad = heap[pos + rlen - 1];\n if (pad < 1 || pad > 16 || pad > rlen)\n throw new SecurityError('bad padding');\n let pcheck = 0;\n for (let i = pad; i > 1; i--)\n pcheck |= pad ^ heap[pos + rlen - i];\n if (pcheck)\n throw new SecurityError('bad padding');\n rlen -= pad;\n }\n }\n const result = new Uint8Array(rlen);\n if (rlen > 0) {\n result.set(heap.subarray(pos, pos + rlen));\n }\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_ECB {\n static encrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).encrypt(data);\n }\n static decrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).decrypt(data);\n }\n constructor(key, padding = false, aes) {\n this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';\n\n/**\n * Javascript AES implementation.\n * This is used as fallback if the native Crypto APIs are not available.\n */\nfunction aes(length) {\n const C = function(key) {\n const aesECB = new AES_ECB(key);\n\n this.encrypt = function(block) {\n return aesECB.encrypt(block);\n };\n\n this.decrypt = function(block) {\n return aesECB.decrypt(block);\n };\n };\n\n C.blockSize = C.prototype.blockSize = 16;\n C.keySize = C.prototype.keySize = length / 8;\n\n return C;\n}\n\nexport default aes;\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * @fileoverview Symmetric cryptography functions\n * @module crypto/cipher\n * @private\n */\n\nimport aes from './aes';\nimport { DES, TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TF from './twofish';\nimport BF from './blowfish';\n\n/**\n * AES-128 encryption and decryption (ID 7)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes128 = aes(128);\n/**\n * AES-128 Block Cipher (ID 8)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes192 = aes(192);\n/**\n * AES-128 Block Cipher (ID 9)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes256 = aes(256);\n// Not in OpenPGP specifications\nexport const des = DES;\n/**\n * Triple DES Block Cipher (ID 2)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}\n * @returns {Object}\n */\nexport const tripledes = TripleDES;\n/**\n * CAST-128 Block Cipher (ID 3)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}\n * @returns {Object}\n */\nexport const cast5 = CAST5;\n/**\n * Twofish Block Cipher (ID 10)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}\n * @returns {Object}\n */\nexport const twofish = TF;\n/**\n * Blowfish Block Cipher (ID 4)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}\n * @returns {Object}\n */\nexport const blowfish = BF;\n/**\n * Not implemented\n * @function\n * @throws {Error}\n */\nexport const idea = function() {\n throw new Error('IDEA symmetric-key algorithm not implemented');\n};\n","export var sha1_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,\n w16 = 0, w17 = 0, w18 = 0, w19 = 0,\n w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,\n w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,\n w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,\n w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,\n w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,\n w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n\n // 0\n t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 1\n t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 2\n t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 3\n t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 4\n t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 5\n t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 6\n t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 7\n t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 8\n t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 9\n t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 10\n t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 11\n t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 12\n t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 13\n t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 14\n t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 15\n t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 16\n n = w13 ^ w8 ^ w2 ^ w0;\n w16 = (n << 1) | (n >>> 31);\n t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 17\n n = w14 ^ w9 ^ w3 ^ w1;\n w17 = (n << 1) | (n >>> 31);\n t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 18\n n = w15 ^ w10 ^ w4 ^ w2;\n w18 = (n << 1) | (n >>> 31);\n t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 19\n n = w16 ^ w11 ^ w5 ^ w3;\n w19 = (n << 1) | (n >>> 31);\n t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 20\n n = w17 ^ w12 ^ w6 ^ w4;\n w20 = (n << 1) | (n >>> 31);\n t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 21\n n = w18 ^ w13 ^ w7 ^ w5;\n w21 = (n << 1) | (n >>> 31);\n t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 22\n n = w19 ^ w14 ^ w8 ^ w6;\n w22 = (n << 1) | (n >>> 31);\n t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 23\n n = w20 ^ w15 ^ w9 ^ w7;\n w23 = (n << 1) | (n >>> 31);\n t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 24\n n = w21 ^ w16 ^ w10 ^ w8;\n w24 = (n << 1) | (n >>> 31);\n t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 25\n n = w22 ^ w17 ^ w11 ^ w9;\n w25 = (n << 1) | (n >>> 31);\n t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 26\n n = w23 ^ w18 ^ w12 ^ w10;\n w26 = (n << 1) | (n >>> 31);\n t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 27\n n = w24 ^ w19 ^ w13 ^ w11;\n w27 = (n << 1) | (n >>> 31);\n t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 28\n n = w25 ^ w20 ^ w14 ^ w12;\n w28 = (n << 1) | (n >>> 31);\n t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 29\n n = w26 ^ w21 ^ w15 ^ w13;\n w29 = (n << 1) | (n >>> 31);\n t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 30\n n = w27 ^ w22 ^ w16 ^ w14;\n w30 = (n << 1) | (n >>> 31);\n t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 31\n n = w28 ^ w23 ^ w17 ^ w15;\n w31 = (n << 1) | (n >>> 31);\n t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 32\n n = w29 ^ w24 ^ w18 ^ w16;\n w32 = (n << 1) | (n >>> 31);\n t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 33\n n = w30 ^ w25 ^ w19 ^ w17;\n w33 = (n << 1) | (n >>> 31);\n t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 34\n n = w31 ^ w26 ^ w20 ^ w18;\n w34 = (n << 1) | (n >>> 31);\n t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 35\n n = w32 ^ w27 ^ w21 ^ w19;\n w35 = (n << 1) | (n >>> 31);\n t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 36\n n = w33 ^ w28 ^ w22 ^ w20;\n w36 = (n << 1) | (n >>> 31);\n t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 37\n n = w34 ^ w29 ^ w23 ^ w21;\n w37 = (n << 1) | (n >>> 31);\n t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 38\n n = w35 ^ w30 ^ w24 ^ w22;\n w38 = (n << 1) | (n >>> 31);\n t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 39\n n = w36 ^ w31 ^ w25 ^ w23;\n w39 = (n << 1) | (n >>> 31);\n t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 40\n n = w37 ^ w32 ^ w26 ^ w24;\n w40 = (n << 1) | (n >>> 31);\n t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 41\n n = w38 ^ w33 ^ w27 ^ w25;\n w41 = (n << 1) | (n >>> 31);\n t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 42\n n = w39 ^ w34 ^ w28 ^ w26;\n w42 = (n << 1) | (n >>> 31);\n t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 43\n n = w40 ^ w35 ^ w29 ^ w27;\n w43 = (n << 1) | (n >>> 31);\n t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 44\n n = w41 ^ w36 ^ w30 ^ w28;\n w44 = (n << 1) | (n >>> 31);\n t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 45\n n = w42 ^ w37 ^ w31 ^ w29;\n w45 = (n << 1) | (n >>> 31);\n t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 46\n n = w43 ^ w38 ^ w32 ^ w30;\n w46 = (n << 1) | (n >>> 31);\n t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 47\n n = w44 ^ w39 ^ w33 ^ w31;\n w47 = (n << 1) | (n >>> 31);\n t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 48\n n = w45 ^ w40 ^ w34 ^ w32;\n w48 = (n << 1) | (n >>> 31);\n t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 49\n n = w46 ^ w41 ^ w35 ^ w33;\n w49 = (n << 1) | (n >>> 31);\n t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 50\n n = w47 ^ w42 ^ w36 ^ w34;\n w50 = (n << 1) | (n >>> 31);\n t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 51\n n = w48 ^ w43 ^ w37 ^ w35;\n w51 = (n << 1) | (n >>> 31);\n t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 52\n n = w49 ^ w44 ^ w38 ^ w36;\n w52 = (n << 1) | (n >>> 31);\n t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 53\n n = w50 ^ w45 ^ w39 ^ w37;\n w53 = (n << 1) | (n >>> 31);\n t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 54\n n = w51 ^ w46 ^ w40 ^ w38;\n w54 = (n << 1) | (n >>> 31);\n t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 55\n n = w52 ^ w47 ^ w41 ^ w39;\n w55 = (n << 1) | (n >>> 31);\n t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 56\n n = w53 ^ w48 ^ w42 ^ w40;\n w56 = (n << 1) | (n >>> 31);\n t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 57\n n = w54 ^ w49 ^ w43 ^ w41;\n w57 = (n << 1) | (n >>> 31);\n t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 58\n n = w55 ^ w50 ^ w44 ^ w42;\n w58 = (n << 1) | (n >>> 31);\n t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 59\n n = w56 ^ w51 ^ w45 ^ w43;\n w59 = (n << 1) | (n >>> 31);\n t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 60\n n = w57 ^ w52 ^ w46 ^ w44;\n w60 = (n << 1) | (n >>> 31);\n t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 61\n n = w58 ^ w53 ^ w47 ^ w45;\n w61 = (n << 1) | (n >>> 31);\n t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 62\n n = w59 ^ w54 ^ w48 ^ w46;\n w62 = (n << 1) | (n >>> 31);\n t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 63\n n = w60 ^ w55 ^ w49 ^ w47;\n w63 = (n << 1) | (n >>> 31);\n t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 64\n n = w61 ^ w56 ^ w50 ^ w48;\n w64 = (n << 1) | (n >>> 31);\n t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 65\n n = w62 ^ w57 ^ w51 ^ w49;\n w65 = (n << 1) | (n >>> 31);\n t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 66\n n = w63 ^ w58 ^ w52 ^ w50;\n w66 = (n << 1) | (n >>> 31);\n t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 67\n n = w64 ^ w59 ^ w53 ^ w51;\n w67 = (n << 1) | (n >>> 31);\n t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 68\n n = w65 ^ w60 ^ w54 ^ w52;\n w68 = (n << 1) | (n >>> 31);\n t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 69\n n = w66 ^ w61 ^ w55 ^ w53;\n w69 = (n << 1) | (n >>> 31);\n t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 70\n n = w67 ^ w62 ^ w56 ^ w54;\n w70 = (n << 1) | (n >>> 31);\n t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 71\n n = w68 ^ w63 ^ w57 ^ w55;\n w71 = (n << 1) | (n >>> 31);\n t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 72\n n = w69 ^ w64 ^ w58 ^ w56;\n w72 = (n << 1) | (n >>> 31);\n t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 73\n n = w70 ^ w65 ^ w59 ^ w57;\n w73 = (n << 1) | (n >>> 31);\n t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 74\n n = w71 ^ w66 ^ w60 ^ w58;\n w74 = (n << 1) | (n >>> 31);\n t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 75\n n = w72 ^ w67 ^ w61 ^ w59;\n w75 = (n << 1) | (n >>> 31);\n t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 76\n n = w73 ^ w68 ^ w62 ^ w60;\n w76 = (n << 1) | (n >>> 31);\n t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 77\n n = w74 ^ w69 ^ w63 ^ w61;\n w77 = (n << 1) | (n >>> 31);\n t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 78\n n = w75 ^ w70 ^ w64 ^ w62;\n w78 = (n << 1) | (n >>> 31);\n t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 79\n n = w76 ^ w71 ^ w65 ^ w63;\n w79 = (n << 1) | (n >>> 31);\n t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n }\n\n function reset () {\n H0 = 0x67452301;\n H1 = 0xefcdab89;\n H2 = 0x98badcfe;\n H3 = 0x10325476;\n H4 = 0xc3d2e1f0;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA1\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA1\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA1\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","import { _heap_write } from '../other/utils';\nimport { IllegalStateError } from '../other/errors';\nexport class Hash {\n constructor() {\n this.pos = 0;\n this.len = 0;\n }\n reset() {\n const { asm } = this.acquire_asm();\n this.result = null;\n this.pos = 0;\n this.len = 0;\n asm.reset();\n return this;\n }\n process(data) {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n let hpos = this.pos;\n let hlen = this.len;\n let dpos = 0;\n let dlen = data.length;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);\n hlen += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.process(hpos, hlen);\n hpos += wlen;\n hlen -= wlen;\n if (!hlen)\n hpos = 0;\n }\n this.pos = hpos;\n this.len = hlen;\n return this;\n }\n finish() {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n asm.finish(this.pos, this.len, 0);\n this.result = new Uint8Array(this.HASH_SIZE);\n this.result.set(heap.subarray(0, this.HASH_SIZE));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return this;\n }\n}\n","import { sha1_asm } from './sha1.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha1_block_size = 64;\nexport const _sha1_hash_size = 20;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha1 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha1';\n this.BLOCK_SIZE = _sha1_block_size;\n this.HASH_SIZE = _sha1_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha1().process(data).finish().result;\n }\n}\nSha1.NAME = 'sha1';\nSha1.heap_pool = [];\nSha1.asm_pool = [];\nSha1.asm_function = sha1_asm;\n","import { sha256_asm } from './sha256.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha256_block_size = 64;\nexport const _sha256_hash_size = 32;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha256 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha256';\n this.BLOCK_SIZE = _sha256_block_size;\n this.HASH_SIZE = _sha256_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha256().process(data).finish().result;\n }\n}\nSha256.NAME = 'sha256';\n","export var sha256_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n f = H5;\n g = H6;\n h = H7;\n \n // 0\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 1\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 2\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 3\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 4\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 5\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 6\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 7\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 8\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 9\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 10\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 11\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 12\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 13\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 14\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 15\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 16\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 17\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 18\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 19\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 20\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 21\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 22\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 23\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 24\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 25\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 26\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 27\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 28\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 29\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 30\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 31\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 32\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 33\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 34\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 35\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 36\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 37\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 38\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 39\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 40\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 41\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 42\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 43\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 44\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 45\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 46\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 47\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 48\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 49\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 50\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 51\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 52\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 53\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 54\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 55\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 56\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 57\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 58\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 59\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 60\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 61\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 62\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 63\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n H5 = ( H5 + f )|0;\n H6 = ( H6 + g )|0;\n H7 = ( H7 + h )|0;\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n HEAP[output|20] = H5>>>24;\n HEAP[output|21] = H5>>>16&255;\n HEAP[output|22] = H5>>>8&255;\n HEAP[output|23] = H5&255;\n HEAP[output|24] = H6>>>24;\n HEAP[output|25] = H6>>>16&255;\n HEAP[output|26] = H6>>>8&255;\n HEAP[output|27] = H6&255;\n HEAP[output|28] = H7>>>24;\n HEAP[output|29] = H7>>>16&255;\n HEAP[output|30] = H7>>>8&255;\n HEAP[output|31] = H7&255;\n }\n\n function reset () {\n H0 = 0x6a09e667;\n H1 = 0xbb67ae85;\n H2 = 0x3c6ef372;\n H3 = 0xa54ff53a;\n H4 = 0x510e527f;\n H5 = 0x9b05688c;\n H6 = 0x1f83d9ab;\n H7 = 0x5be0cd19;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n h5 = h5|0;\n h6 = h6|0;\n h7 = h7|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n H5 = I5;\n H6 = I6;\n H7 = I7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n H5 = O5;\n H6 = O6;\n H7 = O7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n O5 = H5;\n O6 = H6;\n O7 = H7;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n I5 = H5;\n I6 = H6;\n I7 = H7;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n h5 = h5 ^ H5;\n h6 = h6 ^ H6;\n h7 = h7 ^ H7;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA256\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA256\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA256\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n * @private\n */\n\nimport { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1';\nimport { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256';\nimport sha224 from 'hash.js/lib/hash/sha/224';\nimport sha384 from 'hash.js/lib/hash/sha/384';\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport { ripemd160 } from 'hash.js/lib/hash/ripemd';\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport defaultConfig from '../../config';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction hashjsHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n }\n const hashInstance = hash();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => new Uint8Array(hashInstance.digest()));\n };\n}\n\nfunction asmcryptoHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hashInstance = new hash();\n return stream.transform(data, value => {\n hashInstance.process(value);\n }, () => hashInstance.finish().result);\n } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n } else {\n return hash.bytes(data);\n }\n };\n}\n\nconst hashFunctions = {\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),\n sha224: nodeHash('sha224') || hashjsHash(sha224),\n sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),\n sha384: nodeHash('sha384') || hashjsHash(sha384, 'SHA-384'),\n sha512: nodeHash('sha512') || hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge.\n ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)\n};\n\nexport default {\n\n /** @see module:md5 */\n md5: hashFunctions.md5,\n /** @see asmCrypto */\n sha1: hashFunctions.sha1,\n /** @see hash.js */\n sha224: hashFunctions.sha224,\n /** @see asmCrypto */\n sha256: hashFunctions.sha256,\n /** @see hash.js */\n sha384: hashFunctions.sha384,\n /** @see asmCrypto */\n sha512: hashFunctions.sha512,\n /** @see hash.js */\n ripemd: hashFunctions.ripemd,\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n default:\n throw new Error('Invalid hash function.');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CFB {\n static encrypt(data, key, iv) {\n return new AES_CFB(key, iv).encrypt(data);\n }\n static decrypt(data, key, iv) {\n return new AES_CFB(key, iv).decrypt(data);\n }\n constructor(key, iv, aes) {\n this.aes = aes ? aes : new AES(key, iv, true, 'CFB');\n delete this.aes.padding;\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import * as cipher from '.';\nimport enums from '../../enums';\n\n/**\n * Get implementation of the given cipher\n * @param {enums.symmetric} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport default function getCipher(algo) {\n const algoName = enums.read(enums.symmetric, algo);\n return cipher[algoName];\n}\n","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n * @private\n */\n\nimport { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb';\nimport * as stream from '@openpgp/web-stream-tools';\nimport getCipher from '../cipher/getCipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nfunction aesEncrypt(algo, key, pt, iv, config) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support\n !util.isStream(pt) &&\n pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2\n ) { // Web Crypto\n return webEncrypt(algo, key, pt, iv);\n }\n // asm.js fallback\n const cfb = new AES_CFB(key, iv);\n return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());\n}\n\nfunction aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new AES_CFB(key, iv);\n return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());\n }\n return AES_CFB.decrypt(ct, key, iv);\n}\n\nfunction xorMut(a, b) {\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nasync function webEncrypt(algo, key, pt, iv) {\n const ALGO = 'AES-CBC';\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);\n const { blockSize } = getCipher(algo);\n const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);\n const ct = new Uint8Array(await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);\n xorMut(ct, pt);\n return ct;\n}\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","import { AES } from './aes';\nimport { IllegalArgumentError } from '../other/errors';\nimport { joinBytes } from '../other/utils';\nexport class AES_CTR {\n static encrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n static decrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n constructor(key, nonce, aes) {\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n delete this.aes.padding;\n this.AES_CTR_set_options(nonce);\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n AES_CTR_set_options(nonce, counter, size) {\n let { asm } = this.aes.acquire_asm();\n if (size !== undefined) {\n if (size < 8 || size > 48)\n throw new IllegalArgumentError('illegal counter size');\n let mask = Math.pow(2, size) - 1;\n asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);\n }\n else {\n size = 48;\n asm.set_mask(0, 0, 0xffff, 0xffffffff);\n }\n if (nonce !== undefined) {\n let len = nonce.length;\n if (!len || len > 16)\n throw new IllegalArgumentError('illegal nonce size');\n let view = new DataView(new ArrayBuffer(16));\n new Uint8Array(view.buffer).set(nonce);\n asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));\n }\n else {\n throw new Error('nonce is required');\n }\n if (counter !== undefined) {\n if (counter < 0 || counter >= Math.pow(2, size))\n throw new IllegalArgumentError('illegal counter value');\n asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);\n }\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CBC {\n static encrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).encrypt(data);\n }\n static decrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).decrypt(data);\n }\n constructor(key, iv, padding = true, aes) {\n this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n * @private\n */\n\nimport { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt) {\n return AES_CBC.encrypt(pt, key, false, zeroBlock);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n * @private\n */\n\nimport { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n ) {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt, iv) {\n return AES_CTR.encrypt(pt, key, iv);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n * @private\n */\n\nimport * as ciphers from '../cipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n\n let maxNtz = 0;\n let encipher;\n let decipher;\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables(cipher, key) {\n const cipherName = enums.read(enums.symmetric, cipher);\n const aes = new ciphers[cipherName](key);\n encipher = aes.encrypt.bind(aes);\n decipher = aes.decrypt.bind(aes);\n\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors';\nimport { _heap_write } from '../other/utils';\nimport { AES } from './aes';\nimport { AES_asm } from './aes.asm';\nconst _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5\nexport class AES_GCM {\n constructor(key, nonce, adata, tagSize = 16, aes) {\n this.tagSize = tagSize;\n this.gamma0 = 0;\n this.counter = 1;\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n let { asm, heap } = this.aes.acquire_asm();\n // Init GCM\n asm.gcm_init();\n // Tag size\n if (this.tagSize < 4 || this.tagSize > 16)\n throw new IllegalArgumentError('illegal tagSize value');\n // Nonce\n const noncelen = nonce.length || 0;\n const noncebuf = new Uint8Array(16);\n if (noncelen !== 12) {\n this._gcm_mac_process(nonce);\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = 0;\n heap[4] = 0;\n heap[5] = 0;\n heap[6] = 0;\n heap[7] = 0;\n heap[8] = 0;\n heap[9] = 0;\n heap[10] = 0;\n heap[11] = noncelen >>> 29;\n heap[12] = (noncelen >>> 21) & 255;\n heap[13] = (noncelen >>> 13) & 255;\n heap[14] = (noncelen >>> 5) & 255;\n heap[15] = (noncelen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_iv(0, 0, 0, 0);\n noncebuf.set(heap.subarray(0, 16));\n }\n else {\n noncebuf.set(nonce);\n noncebuf[15] = 1;\n }\n const nonceview = new DataView(noncebuf.buffer);\n this.gamma0 = nonceview.getUint32(12);\n asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);\n asm.set_mask(0, 0, 0, 0xffffffff);\n // Associated data\n if (adata !== undefined) {\n if (adata.length > _AES_GCM_data_maxLength)\n throw new IllegalArgumentError('illegal adata length');\n if (adata.length) {\n this.adata = adata;\n this._gcm_mac_process(adata);\n }\n else {\n this.adata = undefined;\n }\n }\n else {\n this.adata = undefined;\n }\n // Counter\n if (this.counter < 1 || this.counter > 0xffffffff)\n throw new RangeError('counter must be a positive 32-bit integer');\n asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);\n }\n static encrypt(cleartext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);\n }\n static decrypt(ciphertext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);\n }\n encrypt(data) {\n return this.AES_GCM_encrypt(data);\n }\n decrypt(data) {\n return this.AES_GCM_decrypt(data);\n }\n AES_GCM_Encrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Encrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let adata = this.adata;\n let pos = this.aes.pos;\n let len = this.aes.len;\n const result = new Uint8Array(len + tagSize);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);\n if (len)\n result.set(heap.subarray(pos, pos + len));\n let i = len;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n result.set(heap.subarray(0, tagSize), len);\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_Decrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;\n let tlen = len + dlen - rlen;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > tlen) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n pos = 0;\n len = 0;\n }\n if (dlen > 0) {\n len += _heap_write(heap, 0, data, dpos, dlen);\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Decrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let tagSize = this.tagSize;\n let adata = this.adata;\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rlen = len - tagSize;\n if (len < tagSize)\n throw new IllegalStateError('authentication tag not found');\n const result = new Uint8Array(rlen);\n const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));\n let i = rlen;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len - tagSize;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n let acheck = 0;\n for (let i = 0; i < tagSize; ++i)\n acheck |= atag[i] ^ heap[i];\n if (acheck)\n throw new SecurityError('data integrity check failed');\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_decrypt(data) {\n const result1 = this.AES_GCM_Decrypt_process(data);\n const result2 = this.AES_GCM_Decrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n AES_GCM_encrypt(data) {\n const result1 = this.AES_GCM_Encrypt_process(data);\n const result2 = this.AES_GCM_Encrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n _gcm_mac_process(data) {\n let { asm, heap } = this.aes.acquire_asm();\n let dpos = 0;\n let dlen = data.length || 0;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, 0, data, dpos, dlen);\n dpos += wlen;\n dlen -= wlen;\n while (wlen & 15)\n heap[wlen++] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);\n }\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n * @private\n */\n\nimport { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.encrypt(pt, key, iv, adata);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (ct.length === tagLength) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n }\n };\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return AES_GCM.encrypt(pt, key, iv, adata);\n },\n\n decrypt: async function(ct, iv, adata) {\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n * @private\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","/*jshint bitwise: false*/\n\n(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d;\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d, h, r;\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n r = nacl.hash(sm.subarray(32, smlen));\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n h = nacl.hash(sm.subarray(0, smlen));\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h;\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n h = nacl.hash(m.subarray(0, n));\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n * @private\n */\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const buf = new Uint8Array(length);\n if (nodeCrypto) {\n const bytes = nodeCrypto.randomBytes(buf.length);\n buf.set(bytes);\n } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n return buf;\n}\n\n/**\n * Create a secure random BigInteger that is greater than or equal to min and less than max.\n * @param {module:BigInteger} min - Lower bound, included\n * @param {module:BigInteger} max - Upper bound, excluded\n * @returns {Promise} Random BigInteger.\n * @async\n */\nexport async function getRandomBigInteger(min, max) {\n const BigInteger = await util.getBigInteger();\n\n if (max.lt(min)) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max.sub(min);\n const bytes = modulus.byteLength();\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = new BigInteger(await getRandomBytes(bytes + 8));\n return r.mod(modulus).add(min);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\n\n/**\n * Generate a probably prime random number\n * @param {Integer} bits - Bit length of the prime\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns BigInteger\n * @async\n */\nexport async function randomProbablePrime(bits, e, k) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n const min = one.leftShift(new BigInteger(bits - 1));\n const thirty = new BigInteger(30);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n const n = await getRandomBigInteger(min, min.leftShift(one));\n let i = n.mod(thirty).toNumber();\n\n do {\n n.iadd(new BigInteger(adds[i]));\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (n.bitLength() > bits) {\n n.imod(min.leftShift(one)).iadd(min);\n i = n.mod(thirty).toNumber();\n }\n } while (!await isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns {boolean}\n * @async\n */\nexport async function isProbablePrime(n, e, k) {\n if (e && !n.dec().gcd(e).isOne()) {\n return false;\n }\n if (!await divisionTest(n)) {\n return false;\n }\n if (!await fermat(n)) {\n return false;\n }\n if (!await millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} b - Optional Fermat test base\n * @returns {boolean}\n */\nexport async function fermat(n, b) {\n const BigInteger = await util.getBigInteger();\n b = b || new BigInteger(2);\n return b.modExp(n.dec(), n).isOne();\n}\n\nexport async function divisionTest(n) {\n const BigInteger = await util.getBigInteger();\n return smallPrimes.every(m => {\n return n.mod(new BigInteger(m)) !== 0;\n });\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n];\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param {BigInteger} n - Number to test\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @param {Function} rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport async function millerRabin(n, k, rand) {\n const BigInteger = await util.getBigInteger();\n const len = n.bitLength();\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n.dec(); // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!n1.getBit(s)) { s++; }\n const d = n.rightShift(new BigInteger(s));\n\n for (; k > 0; k--) {\n const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);\n\n let x = a.modExp(d, n);\n if (x.isOne() || x.equal(n1)) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = x.mul(x).mod(n);\n\n if (x.isOne()) {\n return false;\n }\n if (x.equal(n1)) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n * @private\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport async function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n * @private\n */\n\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\n/* eslint-disable no-invalid-this */\nconst RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('version').int(), // 0\n this.key('modulus').int(), // n\n this.key('publicExponent').int(), // e\n this.key('privateExponent').int(), // d\n this.key('prime1').int(), // p\n this.key('prime2').int(), // q\n this.key('exponent1').int(), // dp\n this.key('exponent2').int(), // dq\n this.key('coefficient').int() // u\n );\n}) : undefined;\n\nconst RSAPublicKey = nodeCrypto ? asn1.define('RSAPubliceKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('modulus').int(), // n\n this.key('publicExponent').int() // e\n );\n}) : undefined;\n/* eslint-enable no-invalid-this */\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n const BigInteger = await util.getBigInteger();\n\n e = new BigInteger(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return {\n n: b64ToUint8Array(jwk.n),\n e: e.toUint8Array(),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {\n const opts = {\n modulusLength: bits,\n publicExponent: e.toNumber(),\n publicKeyEncoding: { type: 'pkcs1', format: 'der' },\n privateKeyEncoding: { type: 'pkcs1', format: 'der' }\n };\n const prv = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {\n if (err) {\n reject(err);\n } else {\n resolve(RSAPrivateKey.decode(der, 'der'));\n }\n });\n });\n /**\n * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.\n * @link https://tools.ietf.org/html/rfc3447#section-3.2\n * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1\n */\n return {\n n: prv.modulus.toArrayLike(Uint8Array),\n e: prv.publicExponent.toArrayLike(Uint8Array),\n d: prv.privateExponent.toArrayLike(Uint8Array),\n // switch p and q\n p: prv.prime2.toArrayLike(Uint8Array),\n q: prv.prime1.toArrayLike(Uint8Array),\n // Since p and q are switched in places, we can keep u as defined by DER\n u: prv.coefficient.toArrayLike(Uint8Array)\n };\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = await randomProbablePrime(bits - (bits >> 1), e, 40);\n p = await randomProbablePrime(bits >> 1, e, 40);\n n = p.mul(q);\n } while (n.bitLength() !== bits);\n\n const phi = p.dec().imul(q.dec());\n\n if (q.lt(p)) {\n [p, q] = [q, p];\n }\n\n return {\n n: n.toUint8Array(),\n e: e.toUint8Array(),\n d: e.modInv(phi).toUint8Array(),\n p: p.toUint8Array(),\n q: q.toUint8Array(),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: p.modInv(q).toUint8Array()\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n p = new BigInteger(p);\n q = new BigInteger(q);\n\n // expect pq = n\n if (!p.mul(q).equal(n)) {\n return false;\n }\n\n const two = new BigInteger(2);\n // expect p*u = 1 mod q\n u = new BigInteger(u);\n if (!p.mul(u).mod(q).isOne()) {\n return false;\n }\n\n e = new BigInteger(e);\n d = new BigInteger(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));\n const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r.mul(d).mul(e);\n\n const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));\n d = new BigInteger(d);\n if (m.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return m.modExp(d, n).toUint8Array('be', n.byteLength());\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPrivateKey.encode(keyObject, 'der');\n return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));\n }\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n return new Uint8Array(sign.sign(pem));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n s = new BigInteger(s);\n e = new BigInteger(e);\n if (s.gte(n)) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());\n const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1' };\n } else {\n key = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n }\n try {\n return await verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const { default: BN } = await import('bn.js');\n\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n data = new BigInteger(emeEncode(data, n.byteLength()));\n e = new BigInteger(e);\n if (data.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return data.modExp(e, n).toUint8Array('be', n.byteLength());\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPrivateKey.encode(keyObject, 'der');\n key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n const BigInteger = await util.getBigInteger();\n data = new BigInteger(data);\n n = new BigInteger(n);\n e = new BigInteger(e);\n d = new BigInteger(d);\n p = new BigInteger(p);\n q = new BigInteger(q);\n u = new BigInteger(u);\n if (data.gte(n)) {\n throw new Error('Data too large.');\n }\n const dq = d.mod(q.dec()); // d mod (q-1)\n const dp = d.mod(p.dec()); // d mod (p-1)\n\n const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);\n const blinder = unblinder.modInv(n).modExp(e, n);\n data = data.mul(blinder).mod(n);\n\n\n const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p\n const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q\n const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h.mul(p).add(mp); // result < n due to relations above\n\n result = result.mul(unblinder).mod(n);\n\n\n return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n const pNum = new BigInteger(p);\n const qNum = new BigInteger(q);\n const dNum = new BigInteger(d);\n\n let dq = dNum.mod(qNum.dec()); // d mod (q-1)\n let dp = dNum.mod(pNum.dec()); // d mod (p-1)\n dp = dp.toUint8Array();\n dq = dq.toUint8Array();\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const padded = emeEncode(data, p.byteLength());\n const m = new BigInteger(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = await getRandomBigInteger(new BigInteger(1), p.dec());\n return {\n c1: g.modExp(k, p).toUint8Array(),\n c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n const BigInteger = await util.getBigInteger();\n c1 = new BigInteger(c1);\n c2 = new BigInteger(c2);\n p = new BigInteger(p);\n x = new BigInteger(x);\n\n const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);\n return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = new BigInteger(p.bitLength());\n const n1023 = new BigInteger(1023);\n if (pSize.lt(n1023)) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (!g.modExp(p.dec(), p).isOne()) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n const i = new BigInteger(1);\n const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold\n while (i.lt(threshold)) {\n res = res.mul(g).imod(p);\n if (res.isOne()) {\n return false;\n }\n i.iinc();\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1\n const rqx = p.dec().imul(r).iadd(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n * @private\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {string} String with the canonical name of the curve.\n */\n getName() {\n const hex = this.toHex();\n if (enums.curve[hex]) {\n return enums.write(enums.curve, hex);\n } else {\n throw new Error('Unknown curve object identifier.');\n }\n }\n}\n\nexport default OID;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library\n * @module crypto/public_key/elliptic/indutnyKey\n * @private\n */\n\nimport config from '../../../config';\n\nexport function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}\n\nexport function keyFromPublic(indutnyCurve, pub) {\n const keyPair = indutnyCurve.keyPair({ pub: pub });\n if (keyPair.validate().result !== true) {\n throw new Error('Invalid elliptic public key');\n }\n return keyPair;\n}\n\nexport async function getIndutnyCurve(name) {\n if (!config.useIndutnyElliptic) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n const { default: elliptic } = await import('@openpgp/elliptic');\n return new elliptic.ec(name);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new stream.TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { getRandomBytes } from '../../random';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport { UnsupportedError } from '../../../packet/packet';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n 'p256': 'P-256',\n 'p384': 'P-384',\n 'p521': 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,\n brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n p256: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.p256,\n web: webCurves.p256,\n payloadSize: 32,\n sharedSize: 256\n },\n p384: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.p384,\n web: webCurves.p384,\n payloadSize: 48,\n sharedSize: 384\n },\n p521: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.p521,\n web: webCurves.p521,\n payloadSize: 66,\n sharedSize: 528\n },\n secp256k1: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.secp256k1,\n payloadSize: 32\n },\n ed25519: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32\n },\n curve25519: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32\n },\n brainpoolP256r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.brainpoolP256r1,\n payloadSize: 32\n },\n brainpoolP384r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.brainpoolP384r1,\n payloadSize: 48\n },\n brainpoolP512r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.brainpoolP512r1,\n payloadSize: 64\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName, params) {\n try {\n if (util.isArray(oidOrName) ||\n util.isUint8Array(oidOrName)) {\n // by oid byte array\n oidOrName = new OID(oidOrName);\n }\n if (oidOrName instanceof OID) {\n // by curve OID\n oidOrName = oidOrName.getName();\n }\n // by curve name or oid string\n this.name = enums.write(enums.curve, oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n params = params || curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node && curves[this.name];\n this.web = params.web && curves[this.name];\n this.payloadSize = params.payloadSize;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === 'curve25519') {\n this.type = 'curve25519';\n } else if (this.name === 'ed25519') {\n this.type = 'ed25519';\n }\n }\n\n async genKeyPair() {\n let keyPair;\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n break;\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519': {\n const privateKey = getRandomBytes(32);\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const secretKey = privateKey.slice().reverse();\n keyPair = nacl.box.keyPair.fromSecretKey(secretKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n case 'ed25519': {\n const privateKey = getRandomBytes(32);\n const keyPair = nacl.sign.keyPair.fromSeed(privateKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n }\n const indutnyCurve = await getIndutnyCurve(this.name);\n keyPair = await indutnyCurve.genKeyPair({\n entropy: util.uint8ArrayToString(getRandomBytes(32))\n });\n return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };\n }\n}\n\nasync function generate(curve) {\n const BigInteger = await util.getBigInteger();\n\n curve = new CurveWithOID(curve);\n const keyPair = await curve.genKeyPair();\n const Q = new BigInteger(keyPair.publicKey).toUint8Array();\n const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);\n return {\n oid: curve.oid,\n Q,\n secret,\n hash: curve.hash,\n cipher: curve.cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[enums.write(enums.curve, oid.toHex())].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n p256: true,\n p384: true,\n p521: true,\n secp256k1: true,\n curve25519: algo === enums.publicKey.ecdh,\n brainpoolP256r1: true,\n brainpoolP384r1: true,\n brainpoolP512r1: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === 'curve25519') {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const curve = await getIndutnyCurve(curveName);\n try {\n // Parse Q and check that it is on the curve but not at infinity\n Q = keyFromPublic(curve, Q).getPublic();\n } catch (validationErrors) {\n return false;\n }\n\n /**\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = keyFromPrivate(curve, d).getPublic();\n if (!dG.eq(Q)) {\n return false;\n }\n\n return true;\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nasync function webGenKeyPair(name) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = 0x04;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n * @private\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './oid_curves';\nimport { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web': {\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n }\n case 'node': {\n const signature = await nodeSign(curve, hashAlgo, message, keyPair);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n }\n }\n }\n return ellipticSign(curve, hashed, privateKey);\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n return await webVerify(curve, hashAlgo, signature, message, publicKey);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node':\n return nodeVerify(curve, hashAlgo, signature, message, publicKey);\n }\n }\n const digest = (typeof hashAlgo === 'undefined') ? message : hashed;\n return ellipticVerify(curve, signature, digest, publicKey);\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\nasync function ellipticSign(curve, hashed, privateKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPrivate(indutnyCurve, privateKey);\n const signature = key.sign(hashed);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n}\n\nasync function ellipticVerify(curve, signature, digest, publicKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPublic(indutnyCurve, publicKey);\n return key.verify(digest, signature);\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, keyPair) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n const key = ECPrivateKey.encode({\n version: 1,\n parameters: curve.oid,\n privateKey: Array.from(keyPair.privateKey),\n publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }\n }, 'pem', {\n label: 'EC PRIVATE KEY'\n });\n\n return ECDSASignature.decode(sign.sign(key), 'der');\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n const key = SubjectPublicKeyInfo.encode({\n algorithm: {\n algorithm: [1, 2, 840, 10045, 2, 1],\n parameters: curve.oid\n },\n subjectPublicKey: { unused: 0, data: Array.from(publicKey) }\n }, 'pem', {\n label: 'PUBLIC KEY'\n });\n const signature = ECDSASignature.encode({\n r: new BN(r), s: new BN(s)\n }, 'der');\n\n try {\n return verify.verify(key, signature);\n } catch (err) {\n return false;\n }\n}\n\n// Originally written by Owen Smith https://github.com/omsmith\n// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/\n\n/* eslint-disable no-invalid-this */\n\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\nconst ECDSASignature = nodeCrypto ?\n asn1.define('ECDSASignature', function() {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n );\n }) : undefined;\n\nconst ECPrivateKey = nodeCrypto ?\n asn1.define('ECPrivateKey', function() {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').explicit(0).optional().any(),\n this.key('publicKey').explicit(1).optional().bitstr()\n );\n }) : undefined;\n\nconst AlgorithmIdentifier = nodeCrypto ?\n asn1.define('AlgorithmIdentifier', function() {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional().any()\n );\n }) : undefined;\n\nconst SubjectPublicKeyInfo = nodeCrypto ?\n asn1.define('SubjectPublicKeyInfo', function() {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n );\n }) : undefined;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);\n const signature = nacl.sign.detached(hashed, secretKey);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const signature = util.concatUint8Array([r, s]);\n return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1));\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== 'ed25519') {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const seed = getRandomBytes(32);\n const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = nacl.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n return nacl.sign.detached.verify(hashed, RS, publicKey);\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: // unsupported\n default:\n return false;\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n * @private\n */\n\nimport * as cipher from './cipher';\nimport util from '../util';\n\n/**\n * AES key wrap\n * @function\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nexport function wrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const P = unpack(data);\n let A = IV;\n const R = P;\n const n = P.length / 2;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 0; j <= 5; ++j) {\n for (let i = 0; i < n; ++i) {\n t[1] = n * j + (1 + i);\n // B = A\n B[0] = A[0];\n B[1] = A[1];\n // B = A || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES(K, B)\n B = unpack(aes.encrypt(pack(B)));\n // A = MSB(64, B) ^ t\n A = B.subarray(0, 2);\n A[0] ^= t[0];\n A[1] ^= t[1];\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n return pack(A, R);\n}\n\n/**\n * AES key unwrap\n * @function\n * @param {String} key\n * @param {String} data\n * @returns {Uint8Array}\n * @throws {Error}\n */\nexport function unwrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const C = unpack(data);\n let A = C.subarray(0, 2);\n const R = C.subarray(2);\n const n = C.length / 2 - 1;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 5; j >= 0; --j) {\n for (let i = n - 1; i >= 0; --i) {\n t[1] = n * j + (i + 1);\n // B = A ^ t\n B[0] = A[0] ^ t[0];\n B[1] = A[1] ^ t[1];\n // B = (A ^ t) || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES-1(B)\n B = unpack(aes.decrypt(pack(B)));\n // A = MSB(64, B)\n A = B.subarray(0, 2);\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n if (A[0] === IV[0] && A[1] === IV[1]) {\n return pack(R);\n }\n throw new Error('Key Data Integrity failed');\n}\n\nfunction createArrayBuffer(data) {\n if (util.isString(data)) {\n const { length } = data;\n const buffer = new ArrayBuffer(length);\n const view = new Uint8Array(buffer);\n for (let j = 0; j < length; ++j) {\n view[j] = data.charCodeAt(j);\n }\n return buffer;\n }\n return new Uint8Array(data).buffer;\n}\n\nfunction unpack(data) {\n const { length } = data;\n const buffer = createArrayBuffer(data);\n const view = new DataView(buffer);\n const arr = new Uint32Array(length / 4);\n for (let i = 0; i < length / 4; ++i) {\n arr[i] = view.getUint32(4 * i);\n }\n return arr;\n}\n\nfunction pack() {\n let length = 0;\n for (let k = 0; k < arguments.length; ++k) {\n length += 4 * arguments[k].length;\n }\n const buffer = new ArrayBuffer(length);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < arguments.length; ++i) {\n for (let j = 0; j < arguments[i].length; ++j) {\n view.setUint32(offset + 4 * j, arguments[i][j]);\n }\n offset += 4 * arguments[i].length;\n }\n return new Uint8Array(buffer);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport getCipher from '../../cipher/getCipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint.subarray(0, 20)\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519': {\n const d = getRandomBytes(32);\n const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);\n let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);\n publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n }\n return ellipticPublicEphemeralKey(curve, Q);\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = aesKW.wrap(Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519': {\n const secretKey = d.slice().reverse();\n const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n }\n return ellipticPrivateEphemeralKey(curve, V, d);\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(aesKW.unwrap(Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: sender\n },\n privateKey,\n curve.web.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.web.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPrivateEphemeralKey(curve, V, d) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n V = keyFromPublic(indutnyCurve, V);\n d = keyFromPrivate(indutnyCurve, d);\n const secretKey = new Uint8Array(d.getPrivate());\n const S = d.derive(V.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPublicEphemeralKey(curve, Q) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const v = await curve.genKeyPair();\n Q = keyFromPublic(indutnyCurve, Q);\n const V = keyFromPrivate(indutnyCurve, v.privateKey);\n const publicKey = v.publicKey;\n const S = V.derive(Q.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeSubtleCrypto = nodeCrypto && nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle;\n\nexport default async function HKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n if (webCrypto || nodeSubtleCrypto) {\n const crypto = webCrypto || nodeSubtleCrypto;\n const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n }\n\n if (nodeCrypto) {\n const hashAlgoName = enums.read(enums.hash, hashAlgo);\n // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869\n\n const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();\n // Step 1: Extract\n // PRK = HMAC-Hash(salt, IKM)\n const pseudoRandomKey = computeHMAC(salt, inputKey);\n\n const hashLen = pseudoRandomKey.length;\n\n // Step 2: Expand\n // HKDF-Expand(PRK, info, L) -> OKM\n const n = Math.ceil(outLen / hashLen);\n const outputKeyingMaterial = new Uint8Array(n * hashLen);\n\n // HMAC input buffer updated at each iteration\n const roundInput = new Uint8Array(hashLen + info.length + 1);\n // T_i and last byte are updated at each iteration, but `info` remains constant\n roundInput.set(info, hashLen);\n\n for (let i = 0; i < n; i++) {\n // T(0) = empty string (zero length)\n // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)\n roundInput[roundInput.length - 1] = i + 1;\n // t = T(i+1)\n const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));\n roundInput.set(t, 0);\n\n outputKeyingMaterial.set(t, i * hashLen);\n }\n\n return outputKeyingMaterial.subarray(0, outLen);\n }\n\n throw new Error('No HKDF implementation available');\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport getCipher from '../../cipher/getCipher';\nimport computeHKDF from '../../hkdf';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(32);\n const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA);\n const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = aesKW.wrap(encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n * @private\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n x = new BigInteger(x);\n\n let k;\n let r;\n let s;\n let t;\n g = g.mod(p);\n x = x.mod(q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = await getRandomBigInteger(one, q); // returns in [1, q-1]\n r = g.modExp(k, p).imod(q); // (g**k mod p) mod q\n if (r.isZero()) {\n continue;\n }\n const xr = x.mul(r).imod(q);\n t = h.add(xr).imod(q); // H(m) + x*r mod q\n s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q\n if (s.isZero()) {\n continue;\n }\n break;\n }\n return {\n r: r.toUint8Array('be', q.byteLength()),\n s: s.toUint8Array('be', q.byteLength())\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n const BigInteger = await util.getBigInteger();\n const zero = new BigInteger(0);\n r = new BigInteger(r);\n s = new BigInteger(s);\n\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n if (r.lte(zero) || r.gte(q) ||\n s.lte(zero) || s.gte(q)) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);\n const w = s.modInv(q); // s**-1 mod q\n if (w.isZero()) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = g.mod(p);\n y = y.mod(p);\n const u1 = h.mul(w).imod(q); // H(m) * w mod q\n const u2 = r.mul(w).imod(q); // r * w mod q\n const t1 = g.modExp(u1, p); // g**u1 mod p\n const t2 = y.modExp(u2, p); // y**u2 mod p\n const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q\n return v.equal(r);\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (!p.dec().mod(q).isZero()) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (!g.modExp(q, p).isOne()) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = new BigInteger(q.bitLength());\n const n150 = new BigInteger(150);\n if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q\n const rqx = q.mul(r).add(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa,\n /** @see tweetnacl */\n nacl: nacl\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n * @private\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read));\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { s };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read));\n return { r, s };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n let r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n r = util.leftPad(r, 32);\n let s = util.readMPI(signature.subarray(read));\n s = util.leftPad(s, 32);\n return { r, s };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n case enums.publicKey.ed25519: {\n const RS = signature.subarray(read, read + 64); read += RS.length;\n return { RS };\n }\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n // signature already padded on parsing\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal: {\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n * @private\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n * @private\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport getCipher from './cipher/getCipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { CurveWithOID } from './public_key/elliptic/oid_curves';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519: {\n if (!util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (!util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.x25519: {\n const A = bytes.subarray(read, read + 32); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const curve = new CurveWithOID(publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, curve.payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const curve = new CurveWithOID(publicParams.oid);\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, curve.payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519: {\n const seed = bytes.subarray(read, read + 32); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519: {\n const k = bytes.subarray(read, read + 32); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key.\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519: {\n const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n }\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipher(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipher(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\nexport { getCipher };\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get preferred hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n * @private\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","\n\n\nvar TYPED_OK = typeof Uint8Array !== \"undefined\" &&\n typeof Uint16Array !== \"undefined\" &&\n typeof Int32Array !== \"undefined\";\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function assign(obj /*...args obj, from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue; \n }\n\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n //return Object.assign(...args);\n}\n\n\n// reduce buffer size, avoiding mem copy\nexport function shrinkBuf(buf, size) {\n if (buf.length === size) {\n return buf; \n }\n if (buf.subarray) {\n return buf.subarray(0, size); \n }\n buf.length = size;\n return buf;\n}\n\n\nconst fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n let i, l, len, pos, chunk;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nconst fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\n\nexport let Buf8 = TYPED_OK ? Uint8Array : Array;\nexport let Buf16 = TYPED_OK ? Uint16Array : Array;\nexport let Buf32 = TYPED_OK ? Int32Array : Array;\nexport let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;\nexport let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;\nexport function setTyped(on) {\n if (on) {\n Buf8 = Uint8Array;\n Buf16 = Uint16Array;\n Buf32 = Int32Array;\n ({ flattenChunks, arraySet } = fnTyped);\n } else {\n Buf8 = Array;\n Buf16 = Array;\n Buf32 = Array;\n ({ flattenChunks, arraySet } = fnUntyped);\n }\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nexport const Z_NO_FLUSH = 0;\nexport const Z_PARTIAL_FLUSH = 1;\nexport const Z_SYNC_FLUSH = 2;\nexport const Z_FULL_FLUSH = 3;\nexport const Z_FINISH = 4;\nexport const Z_BLOCK = 5;\nexport const Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nexport const Z_OK = 0;\nexport const Z_STREAM_END = 1;\nexport const Z_NEED_DICT = 2;\nexport const Z_ERRNO = -1;\nexport const Z_STREAM_ERROR = -2;\nexport const Z_DATA_ERROR = -3;\n//export const Z_MEM_ERROR = -4;\nexport const Z_BUF_ERROR = -5;\n//export const Z_VERSION_ERROR = -6;\n\n /* compression levels */\nexport const Z_NO_COMPRESSION = 0;\nexport const Z_BEST_SPEED = 1;\nexport const Z_BEST_COMPRESSION = 9;\nexport const Z_DEFAULT_COMPRESSION = -1;\n\n\nexport const Z_FILTERED = 1;\nexport const Z_HUFFMAN_ONLY = 2;\nexport const Z_RLE = 3;\nexport const Z_FIXED = 4;\nexport const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nexport const Z_BINARY = 0;\nexport const Z_TEXT = 1;\n//export const Z_ASCII = 1; // = Z_TEXT (deprecated)\nexport const Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nexport const Z_DEFLATED = 8;\n//export const Z_NULL = null // Use -1 or null inline, depending on var type\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nimport * as utils from \"../utils/common.js\";\nimport {\n Z_FIXED,\n Z_BINARY,\n Z_TEXT,\n Z_UNKNOWN\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nfunction zero(buf) {\n let len = buf.length; while (--len >= 0) {\n buf[len] = 0; \n } \n}\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nconst extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nconst extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nconst bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = w & 0xff;\n s.pending_buf[s.pending++] = w >>> 8 & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) {\n continue; \n } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) {\n return; \n }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--; \n }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue; \n }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2]/*.Freq*/ = 0; \n }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n // while (len--) {\n // put_byte(s, *buf++);\n // }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n const _n2 = n * 2;\n const _m2 = m * 2;\n return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break; \n }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {\n pqdownheap(s, tree, n); \n }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]/*.Freq*/++; \n }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree); \n } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb; \n }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n\n //#ifdef TRUNCATE_BLOCK\n // /* Try to guess if it is profitable to stop the current block here */\n // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n // /* Compute an upper bound for the compressed length */\n // out_length = s.last_lit*8;\n // in_length = s.strstart - s.block_start;\n //\n // for (dcode = 0; dcode < D_CODES; dcode++) {\n // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n // }\n // out_length >>>= 3;\n // //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n // // s->last_lit, in_length, out_length,\n // // 100L - out_length*100L/in_length));\n // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n // return true;\n // }\n // }\n //#endif\n\n return s.last_lit === s.lit_bufsize - 1;\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexport {\n _tr_init,\n _tr_stored_block,\n _tr_flush_block,\n _tr_tally,\n _tr_align\n};","\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default function adler32(adler, buf, len, pos) {\n let s1 = adler & 0xffff |0,\n s2 = adler >>> 16 & 0xffff |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = s1 + buf[pos++] |0;\n s2 = s2 + s1 |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return s1 | s2 << 16 |0;\n}\n","\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n let c;\n const table = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = makeTable();\n\n\nexport default function crc32(crc, buf, len, pos) {\n const t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return crc ^ -1; // >>> 0;\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default {\n 2: \"need dictionary\", /* Z_NEED_DICT 2 */\n 1: \"stream end\", /* Z_STREAM_END 1 */\n 0: \"\", /* Z_OK 0 */\n \"-1\": \"file error\", /* Z_ERRNO (-1) */\n \"-2\": \"stream error\", /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\", /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\", /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\", /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\" /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport * as trees from \"./trees.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport msg from \"./messages.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_NO_FLUSH,\n Z_PARTIAL_FLUSH,\n Z_FULL_FLUSH,\n Z_FINISH,\n Z_BLOCK,\n Z_OK,\n Z_STREAM_END,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED,\n Z_HUFFMAN_ONLY,\n Z_RLE,\n Z_FIXED,\n Z_DEFAULT_STRATEGY,\n Z_UNKNOWN,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n // put_byte(s, (Byte)(b >> 8));\n // put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n //#if MIN_MATCH != 3\n // Call update_hash() MIN_MATCH-3 more times\n //#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n // if (s.high_water < s.window_size) {\n // var curr = s.strstart + s.lookahead;\n // var init = 0;\n //\n // if (s.high_water < curr) {\n // /* Previous high water mark below current data -- zero WIN_INIT\n // * bytes or up to end of window, whichever is less.\n // */\n // init = s.window_size - curr;\n // if (init > WIN_INIT)\n // init = WIN_INIT;\n // zmemzero(s->window + curr, (unsigned)init);\n // s->high_water = curr + init;\n // }\n // else if (s->high_water < (ulg)curr + WIN_INIT) {\n // /* High water mark at or above current data, but below current data\n // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n // * to end of window, whichever is less.\n // */\n // init = (ulg)curr + WIN_INIT - s->high_water;\n // if (init > s->window_size - s->high_water)\n // init = s->window_size - s->high_water;\n // zmemzero(s->window + s->high_water, (unsigned)init);\n // s->high_water += init;\n // }\n // }\n //\n // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n // \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (; ;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n // s.block_start >= s.w_size)) {\n // throw new Error(\"slide too late\");\n // }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n // if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n //#if MIN_MATCH != 3\n // Call UPDATE_HASH() MIN_MATCH-3 more times\n //#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nclass Config {\n constructor(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n};\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\nclass DeflateState {\n constructor() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n }\n}\n\nfunction deflateResetKeep(strm) {\n let s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n let old_flush, s;\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n //#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n //#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n let status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n let dictLength = dictionary.length;\n\n let s;\n let str, n;\n let wrap;\n let avail;\n let next;\n let input;\n let tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\nconst deflateInfo = 'pako deflate (from Nodeca project)';\nexport {\n deflateInit,\n deflateInit2,\n deflateReset,\n deflateResetKeep,\n deflateSetHeader,\n deflate,\n deflateEnd,\n deflateSetDictionary,\n deflateInfo\n};\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n\n\n\nimport * as utils from \"./common.js\";\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_OK = true;\nlet STR_APPLY_UIA_OK = true;\n\ntry {\n String.fromCharCode.apply(null, [ 0 ]); \n} catch (__) {\n STR_APPLY_OK = false; \n}\ntry {\n String.fromCharCode.apply(null, new Uint8Array(1)); \n} catch (__) {\n STR_APPLY_UIA_OK = false; \n}\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new utils.Buf8(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexport function string2buf (str) {\n let c, c2, m_pos, i, buf_len = 0;\n const str_len = str.length;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n const buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | c >>> 6;\n buf[i++] = 0x80 | c & 0x3f;\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | c >>> 12;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | c >>> 18;\n buf[i++] = 0x80 | c >>> 12 & 0x3f;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n let result = \"\";\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexport function buf2binstring (buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nexport function binstring2buf (str) {\n const buf = new utils.Buf8(str.length);\n for (let i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nexport function buf2string (buf, max) {\n let i, out, c, c_len;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n // var utf16buf = new Array(len * 2);\n // try Uint16Array\n const utf16buf = new Uint16Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) {\n utf16buf[out++] = c; continue; \n }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) {\n utf16buf[out++] = 0xfffd; i += c_len - 1; continue; \n }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 0x3f;\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) {\n utf16buf[out++] = 0xfffd; continue; \n }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;\n utf16buf[out++] = 0xdc00 | c & 0x3ff;\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexport function utf8border (buf, max) {\n let pos;\n\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length; \n }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {\n pos--; \n }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) {\n return max; \n }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) {\n return max; \n }\n\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class ZStream {\n constructor() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n }\n}","'use strict';\n\nimport * as zlib_deflate from \"./zlib/deflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\nimport { Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED } from \"./zlib/constants.js\"\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\n\nclass Deflate {\n constructor(options) {\n this.options = {\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n ...(options || {})\n };\n\n const opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n }\n\n /**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize } } = this;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n /**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n /**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw new Error(deflator.msg || msg[deflator.err]); }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\nexport { Deflate, deflate, deflateRaw, gzip };\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nexport default function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let _out; /* local strm.output */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n const input = strm.input;\n const last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n const output = strm.output;\n const beg = _out - (start - strm.avail_out);\n const end = _out + (strm.avail_out - 257);\n //#ifdef INFLATE_STRICT\n const dmax = state.dmax;\n //#endif\n const wsize = state.wsize;\n const whave = state.whave;\n const wnext = state.wnext;\n const s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n const lcode = state.lencode;\n const dcode = state.distcode;\n const lmask = (1 << state.lenbits) - 1;\n const dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n } else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n //#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n //#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n // if (len <= op - whave) {\n // do {\n // output[_out++] = 0;\n // } while (--len);\n // continue top;\n // }\n // len -= op - whave;\n // do {\n // output[_out++] = 0;\n // } while (--op > whave);\n // if (op === 0) {\n // from = _out - dist;\n // do {\n // output[_out++] = output[from++];\n // } while (--len);\n // continue top;\n // }\n //#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n } else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n } else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nconst lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nconst dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nconst dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nexport default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n // var shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break; \n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break; \n }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n const mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break; \n }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break; \n }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = root << 24 | curr << 16 | next - table_index |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = len - drop << 24 | 64 << 16 |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport inflate_fast from \"./inffast.js\";\nimport inflate_table from \"./inftrees.js\";\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_FINISH,\n Z_BLOCK,\n Z_TREES,\n Z_OK,\n Z_STREAM_END,\n Z_NEED_DICT,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\n//const MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nclass InflateState {\n constructor() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n }\n}\n\nfunction inflateResetKeep(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n let wrap;\n let state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n let ret;\n let state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n let sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n let hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary var for NEED_BITS\n\n const order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n // case MEM:\n // return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n const state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n let state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n // if (ret) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n // }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nconst inflateInfo = 'pako inflate (from Nodeca project)';\n\nexport {\n inflateReset,\n inflateReset2,\n inflateResetKeep,\n inflateInit,\n inflateInit2,\n inflate,\n inflateEnd,\n inflateGetHeader,\n inflateSetDictionary,\n inflateInfo\n};\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class GZheader {\n constructor() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n }\n}","'use strict';\n\nimport * as zlib_inflate from \"./zlib/inflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport * as c from \"./zlib/constants.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\nimport GZheader from \"./zlib/gzheader.js\";\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nclass Inflate {\n constructor(options) {\n this.options = {\n chunkSize: 16384,\n windowBits: 0,\n ...(options || {})\n };\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n let status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n }\n /**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize, dictionary } } = this;\n let status, _mode;\n let next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n let allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n\n /**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n\n\n /**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === c.Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw new Error(inflator.msg || msg[inflator.err]); }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\nexport { Inflate, inflate, inflateRaw, inflate as ungzip };\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuer,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.signedHashValue = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n this.params = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false) {\n if (key.version === 5) {\n this.version = 5;\n } else {\n this.version = 4;\n }\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = [];\n this.unhashedSubpackets.forEach(data => {\n arr.push(writeSimpleLength(data.length));\n arr.push(data);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n // V4 signature sub packets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n if (!hashed) {\n this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n mypos++;\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuer:\n // Issuer\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion === 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n default: {\n const err = new Error(`Unknown signature subpacket type ${type}`);\n if (critical) {\n throw err;\n } else {\n util.printDebug(err);\n }\n }\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, 2));\n\n let i = 2;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n constructor() {\n /** A one-octet version number. The current version is 3. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** An eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current version is 3.\n this.version = bytes[mypos++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n // An eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);\n\n const end = new Uint8Array([this.flags]);\n\n return util.concatUint8Array([start, this.issuerKeyID.write(), end]);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID)\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Deflate } from '@openpgp/pako/lib/deflate';\nimport { Inflate } from '@openpgp/pako/lib/inflate';\nimport { Z_SYNC_FLUSH, Z_FINISH } from '@openpgp/pako/lib/zlib/constants';\nimport { decode as BunzipDecode } from '@openpgp/seek-bzip';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n\n /**\n * zip/zlib compression level, between 1 and 9\n */\n this.deflateLevel = config.deflateLevel;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName];\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write(), this.deflateLevel);\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nconst nodeZlib = util.getNodeZlib();\n\nfunction uncompressed(data) {\n return data;\n}\n\nfunction node_zlib(func, create, options = {}) {\n return function (data) {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(data => {\n return new Promise((resolve, reject) => {\n func(data, options, (err, result) => {\n if (err) return reject(err);\n resolve(result);\n });\n });\n }));\n }\n return stream.nodeToWeb(stream.webToNode(data).pipe(create(options)));\n };\n}\n\nfunction pako_zlib(constructor, options = {}) {\n return function(data) {\n const obj = new constructor(options);\n return stream.transform(data, value => {\n if (value.length) {\n obj.push(value, Z_SYNC_FLUSH);\n return obj.result;\n }\n }, () => {\n if (constructor === Deflate) {\n obj.push([], Z_FINISH);\n return obj.result;\n }\n });\n };\n}\n\nfunction bzip2(func) {\n return function(data) {\n return stream.fromAsync(async () => func(await stream.readToEnd(data)));\n };\n}\n\nconst compress_fns = nodeZlib ? {\n zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)\n} : {\n zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)\n};\n\nconst decompress_fns = nodeZlib ? {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),\n zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n} : {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),\n zlib: /*#__PURE__*/ pako_zlib(Inflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n constructor() {\n this.version = VERSION;\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n // - A one-octet version number. The only currently defined value is 1.\n if (version !== VERSION) {\n throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);\n }\n\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n return util.concat([new Uint8Array([VERSION]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await this.crypt('decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await this.crypt('encrypt', key, data);\n }\n\n /**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\n async crypt(fn, key, data) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const modeInstance = await mode(this.cipherAlgorithm, key);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const adataBuffer = new ArrayBuffer(21);\n const adataArray = new Uint8Array(adataBuffer, 0, 13);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n const iv = this.iv;\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new stream.TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)\n cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = 3;\n\n this.publicKeyID = new KeyID();\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n i += this.publicKeyID.read(bytes.subarray(i));\n this.publicKeyAlgorithm = bytes[i++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);\n if (this.publicKeyAlgorithm === enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version]),\n this.publicKeyID.write(),\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n // v3 Montgomery curves have cleartext cipher algo\n if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = sessionKeyAlgorithm;\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // add checksum\n return util.concatUint8Array([\n new Uint8Array([cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n }\n case enums.publicKey.x25519:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n return {\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n * @private\n */\n\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport { UnsupportedError } from '../packet/packet';\nimport util from '../util';\n\nclass S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = 'iterated';\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n try {\n this.type = enums.read(enums.s2k, bytes[i++]);\n } catch (err) {\n throw new UnsupportedError('Unknown S2K type.');\n }\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport S2K from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 5 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = enums.symmetric.aes256;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number. The only currently defined version is 4.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version === 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n this.s2k = new S2K();\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version === 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, key);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n } else {\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const encryptionKey = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v5Keys ? 5 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes) {\n let pos = 0;\n // A one-octet version number (3, 4 or 5).\n this.version = bytes[pos++];\n\n if (this.version === 4 || this.version === 5) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version === 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version === 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n if (version === 5) {\n return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);\n }\n return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version === 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version === 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport S2K from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n this.s2k = new S2K();\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipher(this.symmetric).blockSize\n );\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n const cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...this.s2k.write());\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = new S2K(config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n\n const { blockSize } = crypto.getCipher(this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = enums.aead.eax;\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } else {\n this.s2kUsage = 254;\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\nasync function produceEncryptionKey(s2k, passphrase, algorithm) {\n const { keySize } = crypto.getCipher(algorithm);\n return s2k.produceKey(passphrase, keySize);\n}\n\nexport default SecretKeyPacket;\n","\n// email-addresses.js - RFC 5322 email address parser\n// v 3.1.0\n//\n// http://tools.ietf.org/html/rfc5322\n//\n// This library does not validate email addresses.\n// emailAddresses attempts to parse addresses using the (fairly liberal)\n// grammar specified in RFC 5322.\n//\n// email-addresses returns {\n// ast: ,\n// addresses: [{\n// node: ,\n// name: ,\n// address: ,\n// local: ,\n// domain: \n// }, ...]\n// }\n//\n// emailAddresses.parseOneAddress and emailAddresses.parseAddressList\n// work as you might expect. Try it out.\n//\n// Many thanks to Dominic Sayers and his documentation on the is_email function,\n// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.\n\n(function (global) {\n\"use strict\";\n\nfunction parse5322(opts) {\n\n // tokenizing functions\n\n function inStr() { return pos < len; }\n function curTok() { return parseString[pos]; }\n function getPos() { return pos; }\n function setPos(i) { pos = i; }\n function nextTok() { pos += 1; }\n function initialize() {\n pos = 0;\n len = parseString.length;\n }\n\n // parser helper functions\n\n function o(name, value) {\n return {\n name: name,\n tokens: value || \"\",\n semantic: value || \"\",\n children: []\n };\n }\n\n function wrap(name, ast) {\n var n;\n if (ast === null) { return null; }\n n = o(name);\n n.tokens = ast.tokens;\n n.semantic = ast.semantic;\n n.children.push(ast);\n return n;\n }\n\n function add(parent, child) {\n if (child !== null) {\n parent.tokens += child.tokens;\n parent.semantic += child.semantic;\n }\n parent.children.push(child);\n return parent;\n }\n\n function compareToken(fxnCompare) {\n var tok;\n if (!inStr()) { return null; }\n tok = curTok();\n if (fxnCompare(tok)) {\n nextTok();\n return o('token', tok);\n }\n return null;\n }\n\n function literal(lit) {\n return function literalFunc() {\n return wrap('literal', compareToken(function (tok) {\n return tok === lit;\n }));\n };\n }\n\n function and() {\n var args = arguments;\n return function andFunc() {\n var i, s, result, start;\n start = getPos();\n s = o('and');\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result === null) {\n setPos(start);\n return null;\n }\n add(s, result);\n }\n return s;\n };\n }\n\n function or() {\n var args = arguments;\n return function orFunc() {\n var i, result, start;\n start = getPos();\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result !== null) {\n return result;\n }\n setPos(start);\n }\n return null;\n };\n }\n\n function opt(prod) {\n return function optFunc() {\n var result, start;\n start = getPos();\n result = prod();\n if (result !== null) {\n return result;\n }\n else {\n setPos(start);\n return o('opt');\n }\n };\n }\n\n function invis(prod) {\n return function invisFunc() {\n var result = prod();\n if (result !== null) {\n result.semantic = \"\";\n }\n return result;\n };\n }\n\n function colwsp(prod) {\n return function collapseSemanticWhitespace() {\n var result = prod();\n if (result !== null && result.semantic.length > 0) {\n result.semantic = \" \";\n }\n return result;\n };\n }\n\n function star(prod, minimum) {\n return function starFunc() {\n var s, result, count, start, min;\n start = getPos();\n s = o('star');\n count = 0;\n min = minimum === undefined ? 0 : minimum;\n while ((result = prod()) !== null) {\n count = count + 1;\n add(s, result);\n }\n if (count >= min) {\n return s;\n }\n else {\n setPos(start);\n return null;\n }\n };\n }\n\n // One expects names to get normalized like this:\n // \" First Last \" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n function collapseWhitespace(s) {\n return s.replace(/([ \\t]|\\r\\n)+/g, ' ').replace(/^\\s*/, '').replace(/\\s*$/, '');\n }\n\n // UTF-8 pseudo-production (RFC 6532)\n // RFC 6532 extends RFC 5322 productions to include UTF-8\n // using the following productions:\n // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4\n // UTF8-2 = \n // UTF8-3 = \n // UTF8-4 = \n //\n // For reference, the extended RFC 5322 productions are:\n // VCHAR =/ UTF8-non-ascii\n // ctext =/ UTF8-non-ascii\n // atext =/ UTF8-non-ascii\n // qtext =/ UTF8-non-ascii\n // dtext =/ UTF8-non-ascii\n function isUTF8NonAscii(tok) {\n // In JavaScript, we just deal directly with Unicode code points,\n // so we aren't checking individual bytes for UTF-8 encoding.\n // Just check that the character is non-ascii.\n return tok.charCodeAt(0) >= 128;\n }\n\n\n // common productions (RFC 5234)\n // http://tools.ietf.org/html/rfc5234\n // B.1. Core Rules\n\n // CR = %x0D\n // ; carriage return\n function cr() { return wrap('cr', literal('\\r')()); }\n\n // CRLF = CR LF\n // ; Internet standard newline\n function crlf() { return wrap('crlf', and(cr, lf)()); }\n\n // DQUOTE = %x22\n // ; \" (Double Quote)\n function dquote() { return wrap('dquote', literal('\"')()); }\n\n // HTAB = %x09\n // ; horizontal tab\n function htab() { return wrap('htab', literal('\\t')()); }\n\n // LF = %x0A\n // ; linefeed\n function lf() { return wrap('lf', literal('\\n')()); }\n\n // SP = %x20\n function sp() { return wrap('sp', literal(' ')()); }\n\n // VCHAR = %x21-7E\n // ; visible (printing) characters\n function vchar() {\n return wrap('vchar', compareToken(function vcharFunc(tok) {\n var code = tok.charCodeAt(0);\n var accept = (0x21 <= code && code <= 0x7E);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // WSP = SP / HTAB\n // ; white space\n function wsp() { return wrap('wsp', or(sp, htab)()); }\n\n\n // email productions (RFC 5322)\n // http://tools.ietf.org/html/rfc5322\n // 3.2.1. Quoted characters\n\n // quoted-pair = (\"\\\" (VCHAR / WSP)) / obs-qp\n function quotedPair() {\n var qp = wrap('quoted-pair',\n or(\n and(literal('\\\\'), or(vchar, wsp)),\n obsQP\n )());\n if (qp === null) { return null; }\n // a quoted pair will be two characters, and the \"\\\" character\n // should be semantically \"invisible\" (RFC 5322 3.2.1)\n qp.semantic = qp.semantic[1];\n return qp;\n }\n\n // 3.2.2. Folding White Space and Comments\n\n // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS\n function fws() {\n return wrap('fws', or(\n obsFws,\n and(\n opt(and(\n star(wsp),\n invis(crlf)\n )),\n star(wsp, 1)\n )\n )());\n }\n\n // ctext = %d33-39 / ; Printable US-ASCII\n // %d42-91 / ; characters not including\n // %d93-126 / ; \"(\", \")\", or \"\\\"\n // obs-ctext\n function ctext() {\n return wrap('ctext', or(\n function ctextFunc1() {\n return compareToken(function ctextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 39) ||\n (42 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsCtext\n )());\n }\n\n // ccontent = ctext / quoted-pair / comment\n function ccontent() {\n return wrap('ccontent', or(ctext, quotedPair, comment)());\n }\n\n // comment = \"(\" *([FWS] ccontent) [FWS] \")\"\n function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }\n\n // CFWS = (1*([FWS] comment) [FWS]) / FWS\n function cfws() {\n return wrap('cfws', or(\n and(\n star(\n and(opt(fws), comment),\n 1\n ),\n opt(fws)\n ),\n fws\n )());\n }\n\n // 3.2.3. Atom\n\n //atext = ALPHA / DIGIT / ; Printable US-ASCII\n // \"!\" / \"#\" / ; characters not including\n // \"$\" / \"%\" / ; specials. Used for atoms.\n // \"&\" / \"'\" /\n // \"*\" / \"+\" /\n // \"-\" / \"/\" /\n // \"=\" / \"?\" /\n // \"^\" / \"_\" /\n // \"`\" / \"{\" /\n // \"|\" / \"}\" /\n // \"~\"\n function atext() {\n return wrap('atext', compareToken(function atextFunc(tok) {\n var accept =\n ('a' <= tok && tok <= 'z') ||\n ('A' <= tok && tok <= 'Z') ||\n ('0' <= tok && tok <= '9') ||\n (['!', '#', '$', '%', '&', '\\'', '*', '+', '-', '/',\n '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // atom = [CFWS] 1*atext [CFWS]\n function atom() {\n return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());\n }\n\n // dot-atom-text = 1*atext *(\".\" 1*atext)\n function dotAtomText() {\n var s, maybeText;\n s = wrap('dot-atom-text', star(atext, 1)());\n if (s === null) { return s; }\n maybeText = star(and(literal('.'), star(atext, 1)))();\n if (maybeText !== null) {\n add(s, maybeText);\n }\n return s;\n }\n\n // dot-atom = [CFWS] dot-atom-text [CFWS]\n function dotAtom() {\n return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());\n }\n\n // 3.2.4. Quoted Strings\n\n // qtext = %d33 / ; Printable US-ASCII\n // %d35-91 / ; characters not including\n // %d93-126 / ; \"\\\" or the quote character\n // obs-qtext\n function qtext() {\n return wrap('qtext', or(\n function qtextFunc1() {\n return compareToken(function qtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 === code) ||\n (35 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsQtext\n )());\n }\n\n // qcontent = qtext / quoted-pair\n function qcontent() {\n return wrap('qcontent', or(qtext, quotedPair)());\n }\n\n // quoted-string = [CFWS]\n // DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n // [CFWS]\n function quotedString() {\n return wrap('quoted-string', and(\n invis(opt(cfws)),\n invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),\n invis(opt(cfws))\n )());\n }\n\n // 3.2.5 Miscellaneous Tokens\n\n // word = atom / quoted-string\n function word() {\n return wrap('word', or(atom, quotedString)());\n }\n\n // phrase = 1*word / obs-phrase\n function phrase() {\n return wrap('phrase', or(obsPhrase, star(word, 1))());\n }\n\n // 3.4. Address Specification\n // address = mailbox / group\n function address() {\n return wrap('address', or(mailbox, group)());\n }\n\n // mailbox = name-addr / addr-spec\n function mailbox() {\n return wrap('mailbox', or(nameAddr, addrSpec)());\n }\n\n // name-addr = [display-name] angle-addr\n function nameAddr() {\n return wrap('name-addr', and(opt(displayName), angleAddr)());\n }\n\n // angle-addr = [CFWS] \"<\" addr-spec \">\" [CFWS] /\n // obs-angle-addr\n function angleAddr() {\n return wrap('angle-addr', or(\n and(\n invis(opt(cfws)),\n literal('<'),\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n ),\n obsAngleAddr\n )());\n }\n\n // group = display-name \":\" [group-list] \";\" [CFWS]\n function group() {\n return wrap('group', and(\n displayName,\n literal(':'),\n opt(groupList),\n literal(';'),\n invis(opt(cfws))\n )());\n }\n\n // display-name = phrase\n function displayName() {\n return wrap('display-name', function phraseFixedSemantic() {\n var result = phrase();\n if (result !== null) {\n result.semantic = collapseWhitespace(result.semantic);\n }\n return result;\n }());\n }\n\n // mailbox-list = (mailbox *(\",\" mailbox)) / obs-mbox-list\n function mailboxList() {\n return wrap('mailbox-list', or(\n and(\n mailbox,\n star(and(literal(','), mailbox))\n ),\n obsMboxList\n )());\n }\n\n // address-list = (address *(\",\" address)) / obs-addr-list\n function addressList() {\n return wrap('address-list', or(\n and(\n address,\n star(and(literal(','), address))\n ),\n obsAddrList\n )());\n }\n\n // group-list = mailbox-list / CFWS / obs-group-list\n function groupList() {\n return wrap('group-list', or(\n mailboxList,\n invis(cfws),\n obsGroupList\n )());\n }\n\n // 3.4.1 Addr-Spec Specification\n\n // local-part = dot-atom / quoted-string / obs-local-part\n function localPart() {\n // note: quoted-string, dotAtom are proper subsets of obs-local-part\n // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree\n return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());\n }\n\n // dtext = %d33-90 / ; Printable US-ASCII\n // %d94-126 / ; characters not including\n // obs-dtext ; \"[\", \"]\", or \"\\\"\n function dtext() {\n return wrap('dtext', or(\n function dtextFunc1() {\n return compareToken(function dtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 90) ||\n (94 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsDtext\n )()\n );\n }\n\n // domain-literal = [CFWS] \"[\" *([FWS] dtext) [FWS] \"]\" [CFWS]\n function domainLiteral() {\n return wrap('domain-literal', and(\n invis(opt(cfws)),\n literal('['),\n star(and(opt(fws), dtext)),\n opt(fws),\n literal(']'),\n invis(opt(cfws))\n )());\n }\n\n // domain = dot-atom / domain-literal / obs-domain\n function domain() {\n return wrap('domain', function domainCheckTLD() {\n var result = or(obsDomain, dotAtom, domainLiteral)();\n if (opts.rejectTLD) {\n if (result && result.semantic && result.semantic.indexOf('.') < 0) {\n return null;\n }\n }\n // strip all whitespace from domains\n if (result) {\n result.semantic = result.semantic.replace(/\\s+/g, '');\n }\n return result;\n }());\n }\n\n // addr-spec = local-part \"@\" domain\n function addrSpec() {\n return wrap('addr-spec', and(\n localPart, literal('@'), domain\n )());\n }\n\n // 3.6.2 Originator Fields\n // Below we only parse the field body, not the name of the field\n // like \"From:\", \"Sender:\", or \"Reply-To:\". Other libraries that\n // parse email headers can parse those and defer to these productions\n // for the \"RFC 5322\" part.\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // from = \"From:\" (mailbox-list / address-list) CRLF\n function fromSpec() {\n return wrap('from', or(\n mailboxList,\n addressList\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // sender = \"Sender:\" (mailbox / address) CRLF\n function senderSpec() {\n return wrap('sender', or(\n mailbox,\n address\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // reply-to = \"Reply-To:\" address-list CRLF\n function replyToSpec() {\n return wrap('reply-to', addressList());\n }\n\n // 4.1. Miscellaneous Obsolete Tokens\n\n // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control\n // %d11 / ; characters that do not\n // %d12 / ; include the carriage\n // %d14-31 / ; return, line feed, and\n // %d127 ; white space characters\n function obsNoWsCtl() {\n return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {\n var code = tok.charCodeAt(0);\n return ((1 <= code && code <= 8) ||\n (11 === code || 12 === code) ||\n (14 <= code && code <= 31) ||\n (127 === code));\n }));\n }\n\n // obs-ctext = obs-NO-WS-CTL\n function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }\n\n // obs-qtext = obs-NO-WS-CTL\n function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }\n\n // obs-qp = \"\\\" (%d0 / obs-NO-WS-CTL / LF / CR)\n function obsQP() {\n return opts.strict ? null : wrap('obs-qp', and(\n literal('\\\\'),\n or(literal('\\0'), obsNoWsCtl, lf, cr)\n )());\n }\n\n // obs-phrase = word *(word / \".\" / CFWS)\n function obsPhrase() {\n if (opts.strict ) return null;\n return opts.atInDisplayName ? wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), literal('@'), colwsp(cfws)))\n )()) :\n wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), colwsp(cfws)))\n )());\n }\n\n // 4.2. Obsolete Folding White Space\n\n // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908\n // obs-FWS = 1*([CRLF] WSP)\n function obsFws() {\n return opts.strict ? null : wrap('obs-FWS', star(\n and(invis(opt(crlf)), wsp),\n 1\n )());\n }\n\n // 4.4. Obsolete Addressing\n\n // obs-angle-addr = [CFWS] \"<\" obs-route addr-spec \">\" [CFWS]\n function obsAngleAddr() {\n return opts.strict ? null : wrap('obs-angle-addr', and(\n invis(opt(cfws)),\n literal('<'),\n obsRoute,\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n )());\n }\n\n // obs-route = obs-domain-list \":\"\n function obsRoute() {\n return opts.strict ? null : wrap('obs-route', and(\n obsDomainList,\n literal(':')\n )());\n }\n\n // obs-domain-list = *(CFWS / \",\") \"@\" domain\n // *(\",\" [CFWS] [\"@\" domain])\n function obsDomainList() {\n return opts.strict ? null : wrap('obs-domain-list', and(\n star(or(invis(cfws), literal(','))),\n literal('@'),\n domain,\n star(and(\n literal(','),\n invis(opt(cfws)),\n opt(and(literal('@'), domain))\n ))\n )());\n }\n\n // obs-mbox-list = *([CFWS] \",\") mailbox *(\",\" [mailbox / CFWS])\n function obsMboxList() {\n return opts.strict ? null : wrap('obs-mbox-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n mailbox,\n star(and(\n literal(','),\n opt(and(\n mailbox,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-addr-list = *([CFWS] \",\") address *(\",\" [address / CFWS])\n function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n address,\n star(and(\n literal(','),\n opt(and(\n address,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-group-list = 1*([CFWS] \",\") [CFWS]\n function obsGroupList() {\n return opts.strict ? null : wrap('obs-group-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n ), 1),\n invis(opt(cfws))\n )());\n }\n\n // obs-local-part = word *(\".\" word)\n function obsLocalPart() {\n return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());\n }\n\n // obs-domain = atom *(\".\" atom)\n function obsDomain() {\n return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());\n }\n\n // obs-dtext = obs-NO-WS-CTL / quoted-pair\n function obsDtext() {\n return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());\n }\n\n /////////////////////////////////////////////////////\n\n // ast analysis\n\n function findNode(name, root) {\n var i, stack, node;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n return node;\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return null;\n }\n\n function findAllNodes(name, root) {\n var i, stack, node, result;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n result.push(node);\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return result;\n }\n\n function findAllNodesNoChildren(names, root) {\n var i, stack, node, result, namesLookup;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n namesLookup = {};\n for (i = 0; i < names.length; i += 1) {\n namesLookup[names[i]] = true;\n }\n\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name in namesLookup) {\n result.push(node);\n // don't look at children (hence findAllNodesNoChildren)\n } else {\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n }\n return result;\n }\n\n function giveResult(ast) {\n var addresses, groupsAndMailboxes, i, groupOrMailbox, result;\n if (ast === null) {\n return null;\n }\n addresses = [];\n\n // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.\n groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);\n for (i = 0; i < groupsAndMailboxes.length; i += 1) {\n groupOrMailbox = groupsAndMailboxes[i];\n if (groupOrMailbox.name === 'group') {\n addresses.push(giveResultGroup(groupOrMailbox));\n } else if (groupOrMailbox.name === 'mailbox') {\n addresses.push(giveResultMailbox(groupOrMailbox));\n }\n }\n\n result = {\n ast: ast,\n addresses: addresses,\n };\n if (opts.simple) {\n result = simplifyResult(result);\n }\n if (opts.oneResult) {\n return oneResult(result);\n }\n if (opts.simple) {\n return result && result.addresses;\n } else {\n return result;\n }\n }\n\n function giveResultGroup(group) {\n var i;\n var groupName = findNode('display-name', group);\n var groupResultMailboxes = [];\n var mailboxes = findAllNodesNoChildren(['mailbox'], group);\n for (i = 0; i < mailboxes.length; i += 1) {\n groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));\n }\n return {\n node: group,\n parts: {\n name: groupName,\n },\n type: group.name, // 'group'\n name: grabSemantic(groupName),\n addresses: groupResultMailboxes,\n };\n }\n\n function giveResultMailbox(mailbox) {\n var name = findNode('display-name', mailbox);\n var aspec = findNode('addr-spec', mailbox);\n var cfws = findAllNodes('cfws', mailbox);\n var comments = findAllNodesNoChildren(['comment'], mailbox);\n\n\n var local = findNode('local-part', aspec);\n var domain = findNode('domain', aspec);\n return {\n node: mailbox,\n parts: {\n name: name,\n address: aspec,\n local: local,\n domain: domain,\n comments: cfws\n },\n type: mailbox.name, // 'mailbox'\n name: grabSemantic(name),\n address: grabSemantic(aspec),\n local: grabSemantic(local),\n domain: grabSemantic(domain),\n comments: concatComments(comments),\n groupName: grabSemantic(mailbox.groupName),\n };\n }\n\n function grabSemantic(n) {\n return n !== null && n !== undefined ? n.semantic : null;\n }\n\n function simplifyResult(result) {\n var i;\n if (result && result.addresses) {\n for (i = 0; i < result.addresses.length; i += 1) {\n delete result.addresses[i].node;\n }\n }\n return result;\n }\n\n function concatComments(comments) {\n var result = '';\n if (comments) {\n for (var i = 0; i < comments.length; i += 1) {\n result += grabSemantic(comments[i]);\n }\n }\n return result;\n }\n\n function oneResult(result) {\n if (!result) { return null; }\n if (!opts.partial && result.addresses.length > 1) { return null; }\n return result.addresses && result.addresses[0];\n }\n\n /////////////////////////////////////////////////////\n\n var parseString, pos, len, parsed, startProduction;\n\n opts = handleOpts(opts, {});\n if (opts === null) { return null; }\n\n parseString = opts.input;\n\n startProduction = {\n 'address': address,\n 'address-list': addressList,\n 'angle-addr': angleAddr,\n 'from': fromSpec,\n 'group': group,\n 'mailbox': mailbox,\n 'mailbox-list': mailboxList,\n 'reply-to': replyToSpec,\n 'sender': senderSpec,\n }[opts.startAt] || addressList;\n\n if (!opts.strict) {\n initialize();\n opts.strict = true;\n parsed = startProduction(parseString);\n if (opts.partial || !inStr()) {\n return giveResult(parsed);\n }\n opts.strict = false;\n }\n\n initialize();\n parsed = startProduction(parseString);\n if (!opts.partial && inStr()) { return null; }\n return giveResult(parsed);\n}\n\nfunction parseOneAddressSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseAddressListSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseFromSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'from',\n }));\n}\n\nfunction parseSenderSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'sender',\n }));\n}\n\nfunction parseReplyToSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'reply-to',\n }));\n}\n\nfunction handleOpts(opts, defs) {\n function isString(str) {\n return Object.prototype.toString.call(str) === '[object String]';\n }\n\n function isObject(o) {\n return o === Object(o);\n }\n\n function isNullUndef(o) {\n return o === null || o === undefined;\n }\n\n var defaults, o;\n\n if (isString(opts)) {\n opts = { input: opts };\n } else if (!isObject(opts)) {\n return null;\n }\n\n if (!isString(opts.input)) { return null; }\n if (!defs) { return null; }\n\n defaults = {\n oneResult: false,\n partial: false,\n rejectTLD: false,\n rfc6532: false,\n simple: false,\n startAt: 'address-list',\n strict: false,\n atInDisplayName: false\n };\n\n for (o in defaults) {\n if (isNullUndef(opts[o])) {\n opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];\n }\n }\n return opts;\n}\n\nparse5322.parseOneAddress = parseOneAddressSimple;\nparse5322.parseAddressList = parseAddressListSimple;\nparse5322.parseFrom = parseFromSimple;\nparse5322.parseSender = parseSenderSimple;\nparse5322.parseReplyTo = parseReplyToSimple;\n\nif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = parse5322;\n} else {\n global.emailAddresses = parse5322;\n}\n\n}(this));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport emailAddresses from 'email-addresses';\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n try {\n const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });\n this.comment = comments.replace(/^\\(|\\)$/g, '');\n this.name = name;\n this.email = email;\n } catch (e) {}\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n * @private\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm of a key\n * @param {Key} [key] - The key to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) {\n let hashAlgo = config.preferredHashAlgorithm;\n let prefAlgo = hashAlgo;\n if (key) {\n const primaryUser = await key.getPrimaryUser(date, userID, config);\n if (primaryUser.selfCertification.preferredHashAlgorithms) {\n [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;\n hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n }\n }\n switch (keyPacket.algorithm) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n prefAlgo = crypto.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);\n }\n return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n}\n\n/**\n * Returns the preferred symmetric/aead/compression algorithm for a set of keys\n * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred algorithm\n * @async\n */\nexport async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = { // these are all must-implement in rfc4880bis\n 'symmetric': enums.symmetric.aes128,\n 'aead': enums.aead.eax,\n 'compression': enums.compression.uncompressed\n }[type];\n const preferredSenderAlgo = {\n 'symmetric': config.preferredSymmetricAlgorithm,\n 'aead': config.preferredAEADAlgorithm,\n 'compression': config.preferredCompressionAlgorithm\n }[type];\n const prefPropertyName = {\n 'symmetric': 'preferredSymmetricAlgorithms',\n 'aead': 'preferredAEADAlgorithms',\n 'compression': 'preferredCompressionAlgorithms'\n }[type];\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n const recipientPrefs = primaryUser.selfCertification[prefPropertyName];\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {PrivateKey} privateKey - key to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config);\n signaturePacket.rawNotations = notations;\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n await revocationSignature.verify(\n key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\n/**\n * Returns whether aead is supported by all keys in the set\n * @param {Array} keys - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {\n let supported = true;\n // TODO replace when Promise.some or Promise.any are implemented\n await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n if (!primaryUser.selfCertification.features ||\n !(primaryUser.selfCertification.features[0] & enums.features.aead)) {\n supported = false;\n }\n }));\n return supported;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc':\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function isValidSigningKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.rsaEncrypt &&\n keyAlgo !== enums.publicKey.elgamal &&\n keyAlgo !== enums.publicKey.ecdh &&\n keyAlgo !== enums.publicKey.x25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);\n}\n\nexport function isValidEncryptionKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.dsa &&\n keyAlgo !== enums.publicKey.rsaSign &&\n keyAlgo !== enums.publicKey.ecdsa &&\n keyAlgo !== enums.publicKey.eddsaLegacy &&\n keyAlgo !== enums.publicKey.ed25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);\n}\n\nexport function isValidDecryptionKeyPacket(signature, config) {\n if (config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n * @private\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n // check for expiration time in direct signatures\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const { selfCertification } = await this.getPrimaryUser(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidDecryptionKeyPacket(bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {}\n }\n }\n\n // evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&\n helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {\n keys.push(this);\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n const keyPacket = await helper.generateSecretSubkey(options);\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {};\n dataToSign.userID = userIDPacket;\n dataToSign.key = secretKeyPacket;\n\n const signatureProperties = {};\n signatureProperties.signatureType = enums.signature.certGeneric;\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128,\n enums.symmetric.aes192\n ], config.preferredSymmetricAlgorithm);\n if (config.aeadProtect) {\n signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.zlib,\n enums.compression.zip,\n enums.compression.uncompressed\n ], config.preferredCompressionAlgorithm);\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.aead;\n }\n if (config.v5Keys) {\n signatureProperties.features[0] |= enums.features.v5Keys;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return createKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No secret key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport KeyID from './type/keyid';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);\n\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || !util.isString(algorithmName)) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.\n if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n // do not check key expiration to allow decryption of old messages\n const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {\n return;\n }\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);\n const algorithmName = enums.read(enums.symmetric, algo);\n const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?\n enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :\n undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(algo);\n return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n let symEncryptedPacket;\n if (aeadAlgorithmName) {\n symEncryptedPacket = new AEADEncryptedDataPacket();\n symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);\n } else {\n symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();\n }\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const algorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();\n pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();\n pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;\n pkESKeyPacket.sessionKey = sessionKey;\n pkESKeyPacket.sessionKeyAlgorithm = algorithm;\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n let i;\n let existingSigPacketlist;\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n if (signature) {\n existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n for (i = existingSigPacketlist.length - 1; i >= 0; i--) {\n const signaturePacket = existingSigPacketlist[i];\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n if (!signingKeys.length && i === 0) {\n onePassSig.flags = 1;\n }\n packetlist.push(onePassSig);\n }\n }\n\n await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];\n const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signatureType;\n onePassSig.hashAlgorithm = await getPreferredHashAlgo(primaryKey, signingKey.keyPacket, date, userIDs, config);\n onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;\n onePassSig.issuerKeyID = signingKey.getKeyID();\n if (i === signingKeys.length - 1) {\n onePassSig.flags = 1;\n }\n return onePassSig;\n })).then(onePassSignatureList => {\n onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));\n });\n\n packetlist.push(literalDataPacket);\n packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config)));\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.message, this.write(), null, null, null, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const userID = userIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);\n return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n let input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} privateKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n let hashes = this.signature.packets.map(function(packet) {\n return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();\n });\n hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });\n const body = {\n hash: hashes.join(),\n text: this.text,\n data: this.signature.packets.write()\n };\n return armor(enums.armor.signed, body, undefined, undefined, undefined, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n let oneHeader = null;\n let hashAlgos = [];\n headers.forEach(function(header) {\n oneHeader = header.match(/^Hash: (.+)$/); // get header value\n if (oneHeader) {\n oneHeader = oneHeader[1].replace(/\\s/g, ''); // remove whitespace\n oneHeader = oneHeader.split(',');\n oneHeader = oneHeader.map(function(hash) {\n hash = hash.toLowerCase();\n try {\n return enums.write(enums.hash, hash);\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hash);\n }\n });\n hashAlgos = hashAlgos.concat(oneHeader);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {\n throw new Error('If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed');\n } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:\n * curve25519 (default), p256, p384, p521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key generation');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key reformat');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n const streaming = message.fromStream;\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return convertStream(data, streaming, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type\n * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data, streaming, encoding = 'utf8') {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n if (streaming === 'node') {\n data = stream.webToNode(data);\n if (encoding !== 'binary') data.setEncoding(encoding);\n return data;\n }\n if (streaming === 'web' && streamType === 'ponyfill') {\n return stream.toNativeReadable(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","/**\n * web-streams-polyfill v3.0.3\n */\n/// \nconst SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})`;\n\n/// \nfunction noop() {\n return undefined;\n}\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n }\n else if (typeof window !== 'undefined') {\n return window;\n }\n else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\nconst globals = getGlobals();\n\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nconst rethrowAssertionErrorRejection = noop;\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\nfunction newPromise(executor) {\n return new originalPromise(executor);\n}\nfunction promiseResolvedWith(value) {\n return originalPromiseResolve(value);\n}\nfunction promiseRejectedWith(reason) {\n return originalPromiseReject(reason);\n}\nfunction PerformPromiseThen(promise, onFulfilled, onRejected) {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected);\n}\nfunction uponPromise(promise, onFulfilled, onRejected) {\n PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);\n}\nfunction uponFulfillment(promise, onFulfilled) {\n uponPromise(promise, onFulfilled);\n}\nfunction uponRejection(promise, onRejected) {\n uponPromise(promise, undefined, onRejected);\n}\nfunction transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\nfunction setPromiseIsHandledToTrue(promise) {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\nconst queueMicrotask = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn) => PerformPromiseThen(resolvedPromise, fn);\n})();\nfunction reflectCall(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\nfunction promiseCall(F, V, args) {\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n }\n catch (value) {\n return promiseRejectedWith(value);\n }\n}\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nclass SimpleQueue {\n constructor() {\n this._cursor = 0;\n this._size = 0;\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n get length() {\n return this._size;\n }\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback) {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n node = node._next;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n }\n else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n }\n else {\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n const stream = reader._ownerReadableStream;\n return ReadableStreamCancel(stream, reason);\n}\nfunction ReadableStreamReaderGenericRelease(reader) {\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n// Helper functions for the readers.\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\nfunction defaultReaderClosedPromiseResolve(reader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nconst AbortSteps = SymbolPolyfill('[[AbortSteps]]');\nconst ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');\nconst CancelSteps = SymbolPolyfill('[[CancelSteps]]');\nconst PullSteps = SymbolPolyfill('[[PullSteps]]');\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nfunction isDictionary(x) {\n return typeof x === 'object' || typeof x === 'function';\n}\nfunction assertDictionary(obj, context) {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-callback-functions\nfunction assertFunction(x, context) {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-object\nfunction isObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nfunction assertObject(x, context) {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\nfunction assertRequiredArgument(x, position, context) {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\nfunction assertRequiredField(x, field, context) {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nfunction convertUnrestrictedDouble(value) {\n return Number(value);\n}\nfunction censorNegativeZero(x) {\n return x === 0 ? 0 : x;\n}\nfunction integerPart(x) {\n return censorNegativeZero(MathTrunc(x));\n}\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nfunction convertUnsignedLongLongWithEnforceRange(value, context) {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n let x = Number(value);\n x = censorNegativeZero(x);\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n x = integerPart(x);\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n return x;\n}\n\nfunction assertReadableStream(x, context) {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadRequest(stream, readRequest) {\n stream._reader._readRequests.push(readRequest);\n}\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readRequest = reader._readRequests.shift();\n if (done) {\n readRequest._closeSteps();\n }\n else {\n readRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\nfunction ReadableStreamHasDefaultReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamDefaultReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultReaderRead(reader, readRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n }\n else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n }\n else {\n stream._readableStreamController[PullSteps](readRequest);\n }\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n\n/// \nlet AsyncIteratorPrototype;\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolPolyfill.asyncIterator]() {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });\n}\n\n/// \nclass ReadableStreamAsyncIteratorImpl {\n constructor(reader, preventCancel) {\n this._ongoingPromise = undefined;\n this._isFinished = false;\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n next() {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n return(value) {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n _nextSteps() {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n _returnSteps(value) {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\nconst ReadableStreamAsyncIteratorPrototype = {\n next() {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n return(value) {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n};\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamAsyncIterator(stream, preventCancel) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\nfunction IsReadableStreamAsyncIterator(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n return true;\n}\n// Helper functions for the ReadableStream.\nfunction streamAsyncIteratorBrandCheckException(name) {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nfunction IsFiniteNonNegativeNumber(v) {\n if (!IsNonNegativeNumber(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n return true;\n}\nfunction IsNonNegativeNumber(v) {\n if (typeof v !== 'number') {\n return false;\n }\n if (NumberIsNaN(v)) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n return true;\n}\n\nfunction DequeueValue(container) {\n const pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n return pair.value;\n}\nfunction EnqueueValueWithSize(container, value, size) {\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\nfunction PeekQueueValue(container) {\n const pair = container._queue.peek();\n return pair.value;\n}\nfunction ResetQueue(container) {\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n\nfunction CreateArrayFromList(elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n}\nfunction CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n// Not implemented correctly\nfunction TransferArrayBuffer(O) {\n return O;\n}\n// Not implemented correctly\nfunction IsDetachedBuffer(O) {\n return false;\n}\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nclass ReadableStreamBYOBRequest {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view() {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n return this._view;\n }\n respond(bytesWritten) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n if (IsDetachedBuffer(this._view.buffer)) ;\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n respondWithNewView(view) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n if (view.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (view.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableByteStreamController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n if (this._byobRequest === null && this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, this, view);\n this._byobRequest = byobRequest;\n }\n return this._byobRequest;\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n ReadableByteStreamControllerClose(this);\n }\n enqueue(chunk) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n ReadableByteStreamControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n if (this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n firstDescriptor.bytesFilled = 0;\n }\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableByteStream;\n if (this._queueTotalSize > 0) {\n const entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n ReadableByteStreamControllerHandleQueueDrain(this);\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view);\n return;\n }\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n }\n catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n const pullIntoDescriptor = {\n buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableByteStreamController.\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n return true;\n}\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableByteStreamControllerError(controller, e);\n });\n}\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n let done = false;\n if (stream._state === 'closed') {\n done = true;\n }\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n }\n else {\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n const queue = controller._queue;\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n }\n else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n return ready;\n}\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n }\n else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === null) {\n return;\n }\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = null;\n controller._byobRequest = null;\n}\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {\n const stream = controller._controlledReadableByteStream;\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n const ctor = view.constructor;\n const buffer = TransferArrayBuffer(view.buffer);\n const pullIntoDescriptor = {\n buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n ReadableByteStreamControllerHandleQueueDrain(controller);\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n controller._pendingPullIntos.push(pullIntoDescriptor);\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n }\n else {\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n const descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return false;\n }\n if (controller._closeRequested) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableByteStreamControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n}\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\nfunction ReadableByteStreamControllerClose(controller) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n return;\n }\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n throw e;\n }\n }\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n const transferredBuffer = TransferArrayBuffer(buffer);\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n else {\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n }\n else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n }\n else {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerError(controller, e) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return;\n }\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableByteStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (!IsFiniteNonNegativeNumber(bytesWritten)) {\n throw new RangeError('bytesWritten must be a finite');\n }\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n firstDescriptor.buffer = view.buffer;\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\nfunction SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {\n controller._controlledReadableByteStream = stream;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._byobRequest = null;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._closeRequested = false;\n controller._started = false;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n controller._pendingPullIntos = new SimpleQueue();\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableByteStreamControllerError(controller, r);\n });\n}\nfunction SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {\n const controller = Object.create(ReadableByteStreamController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel(reason);\n }\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);\n}\nfunction SetUpReadableStreamBYOBRequest(request, controller, view) {\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n// Helper functions for the ReadableStreamBYOBRequest.\nfunction byobRequestBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n// Helper functions for the ReadableByteStreamController.\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {\n stream._reader._readIntoRequests.push(readIntoRequest);\n}\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readIntoRequest = reader._readIntoRequests.shift();\n if (done) {\n readIntoRequest._closeSteps(chunk);\n }\n else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\nfunction ReadableStreamHasBYOBReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamBYOBReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readIntoRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n }\n else {\n ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);\n }\n}\n// Helper functions for the ReadableStreamBYOBReader.\nfunction byobReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n\nfunction ExtractHighWaterMark(strategy, defaultHWM) {\n const { highWaterMark } = strategy;\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n return highWaterMark;\n}\nfunction ExtractSizeAlgorithm(strategy) {\n const { size } = strategy;\n if (!size) {\n return () => 1;\n }\n return size;\n}\n\nfunction convertQueuingStrategy(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n const size = init === null || init === void 0 ? void 0 : init.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\nfunction convertQueuingStrategySize(fn, context) {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n\nfunction convertUnderlyingSink(original, context) {\n assertDictionary(original, context);\n const abort = original === null || original === void 0 ? void 0 : original.abort;\n const close = original === null || original === void 0 ? void 0 : original.close;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n const write = original === null || original === void 0 ? void 0 : original.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),\n type\n };\n}\nfunction convertUnderlyingSinkAbortCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSinkCloseCallback(fn, original, context) {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\nfunction convertUnderlyingSinkStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSinkWriteCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction assertWritableStream(x, context) {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n constructor(rawUnderlyingSink = {}, rawStrategy = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n }\n else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n InitializeWritableStream(this);\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('locked');\n }\n return IsWritableStreamLocked(this);\n }\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason = undefined) {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('abort'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n return WritableStreamAbort(this, reason);\n }\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('close'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamClose(this);\n }\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('getWriter');\n }\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n// Abstract operations for the WritableStream.\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n const controller = Object.create(WritableStreamDefaultController.prototype);\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeWritableStream(stream) {\n stream._state = 'writable';\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n stream._writer = undefined;\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined;\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsWritableStreamLocked(stream) {\n if (stream._writer === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamAbort(stream, reason) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest._promise = promise;\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n return promise;\n}\nfunction WritableStreamClose(stream) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n const promise = newPromise((resolve, reject) => {\n const closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._closeRequest = closeRequest;\n });\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n return promise;\n}\n// WritableStream API exposed for controllers.\nfunction WritableStreamAddWriteRequest(stream) {\n const promise = newPromise((resolve, reject) => {\n const writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._writeRequests.push(writeRequest);\n });\n return promise;\n}\nfunction WritableStreamDealWithRejection(stream, error) {\n const state = stream._state;\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n WritableStreamFinishErroring(stream);\n}\nfunction WritableStreamStartErroring(stream, reason) {\n const controller = stream._writableStreamController;\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\nfunction WritableStreamFinishErroring(stream) {\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(promise, () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, (reason) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\nfunction WritableStreamFinishInFlightWrite(stream) {\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n WritableStreamDealWithRejection(stream, error);\n}\nfunction WritableStreamFinishInFlightClose(stream) {\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n const state = stream._state;\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n stream._state = 'closed';\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n}\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n if (stream._closeRequest !== undefined) {\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n }\n else {\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n stream._backpressure = backpressure;\n}\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nclass WritableStreamDefaultWriter {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n this._ownerWritableStream = stream;\n stream._writer = this;\n const state = stream._state;\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n }\n else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n }\n else {\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n return this._readyPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamDefaultWriterClose(this);\n }\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return;\n }\n WritableStreamDefaultWriterRelease(this);\n }\n write(chunk = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n// Abstract operations for the WritableStreamDefaultWriter.\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n return true;\n}\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n const stream = writer._ownerWritableStream;\n return WritableStreamAbort(stream, reason);\n}\nfunction WritableStreamDefaultWriterClose(writer) {\n const stream = writer._ownerWritableStream;\n return WritableStreamClose(stream);\n}\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n return WritableStreamDefaultWriterClose(writer);\n}\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n }\n else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n }\n else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\nfunction WritableStreamDefaultWriterRelease(writer) {\n const stream = writer._ownerWritableStream;\n const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n const stream = writer._ownerWritableStream;\n const controller = stream._writableStreamController;\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n const promise = WritableStreamAddWriteRequest(stream);\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n return promise;\n}\nconst closeSentinel = {};\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nclass WritableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e = undefined) {\n if (!IsWritableStreamDefaultController(this)) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n WritableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [AbortSteps](reason) {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n error: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations implementing interface required by the WritableStream.\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(startPromise, () => {\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, r => {\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n });\n}\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let writeAlgorithm = () => promiseResolvedWith(undefined);\n let closeAlgorithm = () => promiseResolvedWith(undefined);\n let abortAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort(reason);\n }\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller) {\n controller._writeAlgorithm = undefined;\n controller._closeAlgorithm = undefined;\n controller._abortAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n try {\n return controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n// Abstract operations for the WritableStreamDefaultController.\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n const stream = controller._controlledWritableStream;\n if (!controller._started) {\n return;\n }\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n const state = stream._state;\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n if (controller._queue.length === 0) {\n return;\n }\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n }\n else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkCloseRequestInFlight(stream);\n DequeueValue(controller);\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(sinkClosePromise, () => {\n WritableStreamFinishInFlightClose(stream);\n }, reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(sinkWritePromise, () => {\n WritableStreamFinishInFlightWrite(stream);\n const state = stream._state;\n DequeueValue(controller);\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\nfunction WritableStreamDefaultControllerError(controller, error) {\n const stream = controller._controlledWritableStream;\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n// Helper functions for the WritableStream.\nfunction streamBrandCheckException$2(name) {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n// Helper functions for the WritableStreamDefaultWriter.\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterClosedPromiseResolve(writer) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\nfunction defaultWriterReadyPromiseReset(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n}\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterReadyPromiseResolve(writer) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction isAbortSignal(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof value.aborted === 'boolean';\n }\n catch (_a) {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/// \nconst NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;\n\n/// \nfunction isDOMExceptionConstructor(ctor) {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new ctor();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createDOMExceptionPolyfill() {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(message, name) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n };\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n// eslint-disable-next-line no-redeclare\nconst DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nfunction ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n source._disturbed = true;\n let shuttingDown = false;\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n return newPromise((resolve, reject) => {\n let abortAlgorithm;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException$1('Aborted', 'AbortError');\n const actions = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n signal.addEventListener('abort', abortAlgorithm);\n }\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done) {\n if (done) {\n resolveLoop();\n }\n else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n next(false);\n });\n }\n function pipeStep() {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(reader, {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n });\n });\n });\n }\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n }\n else {\n shutdown();\n }\n });\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n }\n else {\n shutdown(true, destClosed);\n }\n }\n setPromiseIsHandledToTrue(pipeLoop());\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);\n }\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n }\n else {\n uponRejection(promise, action);\n }\n }\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n }\n else {\n uponFulfillment(promise, action);\n }\n }\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n }\n else {\n doTheRest();\n }\n function doTheRest() {\n uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));\n }\n }\n function shutdown(isError, error) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n }\n else {\n finalize(isError, error);\n }\n }\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n }\n else {\n resolve(undefined);\n }\n }\n });\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('desiredSize');\n }\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('close');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n ReadableStreamDefaultControllerClose(this);\n }\n enqueue(chunk = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('enqueue');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('error');\n }\n ReadableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableStream;\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n }\n else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n readRequest._chunkSteps(chunk);\n }\n else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableStreamDefaultController.\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableStreamDefaultControllerError(controller, e);\n });\n}\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableStream;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\nfunction ReadableStreamDefaultControllerClose(controller) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n controller._closeRequested = true;\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n }\n else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\nfunction ReadableStreamDefaultControllerError(controller, e) {\n const stream = controller._controlledReadableStream;\n if (stream._state !== 'readable') {\n return;\n }\n ResetQueue(controller);\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\n// This is used in the implementation of TransformStream.\nfunction ReadableStreamDefaultControllerHasBackpressure(controller) {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {\n const state = controller._controlledReadableStream._state;\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n return false;\n}\nfunction SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledReadableStream = stream;\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableStreamDefaultControllerError(controller, r);\n });\n}\nfunction SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel(reason);\n }\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// Helper functions for the ReadableStreamDefaultController.\nfunction defaultControllerBrandCheckException$1(name) {\n return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let branch1;\n let branch2;\n let resolveCancelPromise;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n function pullAlgorithm() {\n if (reading) {\n return promiseResolvedWith(undefined);\n }\n reading = true;\n const readRequest = {\n _chunkSteps: value => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n reading = false;\n const value1 = value;\n const value2 = value;\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promiseResolvedWith(undefined);\n }\n function cancel1Algorithm(reason) {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function cancel2Algorithm(reason) {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function startAlgorithm() {\n // do nothing\n }\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n uponRejection(reader._closedPromise, (r) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n return [branch1, branch2];\n}\n\nfunction convertUnderlyingDefaultOrByteSource(source, context) {\n assertDictionary(source, context);\n const original = source;\n const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;\n const cancel = original === null || original === void 0 ? void 0 : original.cancel;\n const pull = original === null || original === void 0 ? void 0 : original.pull;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\nfunction convertUnderlyingSourceCancelCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSourcePullCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSourceStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertReadableStreamType(type, context) {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n\nfunction convertReaderOptions(options, context) {\n assertDictionary(options, context);\n const mode = options === null || options === void 0 ? void 0 : options.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\nfunction convertReadableStreamReaderMode(mode, context) {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nfunction convertIteratorOptions(options, context) {\n assertDictionary(options, context);\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n\nfunction convertPipeOptions(options, context) {\n assertDictionary(options, context);\n const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;\n const signal = options === null || options === void 0 ? void 0 : options.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\nfunction assertAbortSignal(signal, context) {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n\nfunction convertReadableWritablePair(pair, context) {\n assertDictionary(pair, context);\n const readable = pair === null || pair === void 0 ? void 0 : pair.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n const writable = pair === null || pair === void 0 ? void 0 : pair.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n return { readable, writable };\n}\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nclass ReadableStream {\n constructor(rawUnderlyingSource = {}, rawStrategy = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n }\n else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n InitializeReadableStream(this);\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);\n }\n else {\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);\n }\n }\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('locked');\n }\n return IsReadableStreamLocked(this);\n }\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason = undefined) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('cancel'));\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n return ReadableStreamCancel(this, reason);\n }\n getReader(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('getReader');\n }\n const options = convertReaderOptions(rawOptions, 'First parameter');\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n return AcquireReadableStreamBYOBReader(this);\n }\n pipeThrough(rawTransform, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n setPromiseIsHandledToTrue(promise);\n return transform.readable;\n }\n pipeTo(destination, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));\n }\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));\n }\n let options;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n }\n catch (e) {\n return promiseRejectedWith(e);\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n }\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('tee');\n }\n const branches = ReadableStreamTee(this);\n return CreateArrayFromList(branches);\n }\n values(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('values');\n }\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n}\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n// Abstract operations for the ReadableStream.\n// Throws if and only if startAlgorithm throws.\nfunction CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeReadableStream(stream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamLocked(stream) {\n if (stream._reader === undefined) {\n return false;\n }\n return true;\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n ReadableStreamClose(stream);\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\nfunction ReadableStreamClose(stream) {\n stream._state = 'closed';\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseResolve(reader);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\nfunction ReadableStreamError(stream, e) {\n stream._state = 'errored';\n stream._storedError = e;\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseReject(reader, e);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n reader._readRequests = new SimpleQueue();\n }\n else {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n// Helper functions for the ReadableStream.\nfunction streamBrandCheckException$1(name) {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n\nfunction convertQueuingStrategyInit(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n\nconst byteLengthSizeFunction = function size(chunk) {\n return chunk.byteLength;\n};\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nclass ByteLengthQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the ByteLengthQueuingStrategy.\nfunction byteLengthBrandCheckException(name) {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\nfunction IsByteLengthQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nconst countSizeFunction = function size() {\n return 1;\n};\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nclass CountQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the CountQueuingStrategy.\nfunction countBrandCheckException(name) {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\nfunction IsCountQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nfunction convertTransformer(original, context) {\n assertDictionary(original, context);\n const flush = original === null || original === void 0 ? void 0 : original.flush;\n const readableType = original === null || original === void 0 ? void 0 : original.readableType;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const transform = original === null || original === void 0 ? void 0 : original.transform;\n const writableType = original === null || original === void 0 ? void 0 : original.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),\n writableType\n };\n}\nfunction convertTransformerFlushCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertTransformerStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertTransformerTransformCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\n// Class TransformStream\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nclass TransformStream {\n constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n let startPromise_resolve;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n }\n else {\n startPromise_resolve(undefined);\n }\n }\n /**\n * The readable side of the transform stream.\n */\n get readable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n return this._readable;\n }\n /**\n * The writable side of the transform stream.\n */\n get writable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n return this._writable;\n }\n}\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\nfunction InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {\n function startAlgorithm() {\n return startPromise;\n }\n function writeAlgorithm(chunk) {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n function abortAlgorithm(reason) {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n function closeAlgorithm() {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);\n function pullAlgorithm() {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n function cancelAlgorithm(reason) {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined;\n stream._backpressureChangePromise = undefined;\n stream._backpressureChangePromise_resolve = undefined;\n TransformStreamSetBackpressure(stream, true);\n stream._transformStreamController = undefined;\n}\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n return true;\n}\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream, e) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\nfunction TransformStreamErrorWritableAndUnblockWrite(stream, e) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\nfunction TransformStreamSetBackpressure(stream, backpressure) {\n // Passes also when called during construction.\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n stream._backpressure = backpressure;\n}\n// Class TransformStreamDefaultController\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nclass TransformStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n enqueue(chunk = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n TransformStreamDefaultControllerError(this, reason);\n }\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n TransformStreamDefaultControllerTerminate(this);\n }\n}\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n// Transform Stream Default Controller Abstract Operations\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {\n const controller = Object.create(TransformStreamDefaultController.prototype);\n let transformAlgorithm = (chunk) => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk);\n return promiseResolvedWith(undefined);\n }\n catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n let flushAlgorithm = () => promiseResolvedWith(undefined);\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush(controller);\n }\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\nfunction TransformStreamDefaultControllerClearAlgorithms(controller) {\n controller._transformAlgorithm = undefined;\n controller._flushAlgorithm = undefined;\n}\nfunction TransformStreamDefaultControllerEnqueue(controller, chunk) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n }\n catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n throw stream._readable._storedError;\n }\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n TransformStreamSetBackpressure(stream, true);\n }\n}\nfunction TransformStreamDefaultControllerError(controller, e) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\nfunction TransformStreamDefaultControllerPerformTransform(controller, chunk) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\nfunction TransformStreamDefaultControllerTerminate(controller) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n ReadableStreamDefaultControllerClose(readableController);\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n// TransformStreamDefaultSink Algorithms\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {\n const controller = stream._transformStreamController;\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream) {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n// TransformStreamDefaultSource Algorithms\nfunction TransformStreamDefaultSourcePullAlgorithm(stream) {\n // Invariant. Enforced by the promises returned by start() and pull().\n TransformStreamSetBackpressure(stream, false);\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n// Helper functions for the TransformStreamDefaultController.\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n// Helper functions for the TransformStream.\nfunction streamBrandCheckException(name) {\n return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n\nexport { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };\n//# sourceMappingURL=ponyfill.es6.mjs.map\n","/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nfunction assert(test) {\n if (!test) {\n throw new TypeError('Assertion failed');\n }\n}\n\nfunction noop() {\n return;\n}\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nfunction isStreamConstructor(ctor) {\n if (typeof ctor !== 'function') {\n return false;\n }\n var startCalled = false;\n try {\n new ctor({\n start: function () {\n startCalled = true;\n }\n });\n }\n catch (e) {\n // ignore\n }\n return startCalled;\n}\nfunction isReadableStream(readable) {\n if (!typeIsObject(readable)) {\n return false;\n }\n if (typeof readable.getReader !== 'function') {\n return false;\n }\n return true;\n}\nfunction isReadableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isReadableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isWritableStream(writable) {\n if (!typeIsObject(writable)) {\n return false;\n }\n if (typeof writable.getWriter !== 'function') {\n return false;\n }\n return true;\n}\nfunction isWritableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isWritableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isTransformStream(transform) {\n if (!typeIsObject(transform)) {\n return false;\n }\n if (!isReadableStream(transform.readable)) {\n return false;\n }\n if (!isWritableStream(transform.writable)) {\n return false;\n }\n return true;\n}\nfunction isTransformStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isTransformStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction supportsByobReader(readable) {\n try {\n var reader = readable.getReader({ mode: 'byob' });\n reader.releaseLock();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction supportsByteSource(ctor) {\n try {\n new ctor({ type: 'bytes' });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\nfunction createReadableStreamWrapper(ctor) {\n assert(isReadableStreamConstructor(ctor));\n var byteSourceSupported = supportsByteSource(ctor);\n return function (readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n type = parseReadableType(type);\n if (type === 'bytes' && !byteSourceSupported) {\n type = undefined;\n }\n if (readable.constructor === ctor) {\n if (type !== 'bytes' || supportsByobReader(readable)) {\n return readable;\n }\n }\n if (type === 'bytes') {\n var source = createWrappingReadableSource(readable, { type: type });\n return new ctor(source);\n }\n else {\n var source = createWrappingReadableSource(readable);\n return new ctor(source);\n }\n };\n}\nfunction createWrappingReadableSource(readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n assert(isReadableStream(readable));\n assert(readable.locked === false);\n type = parseReadableType(type);\n var source;\n if (type === 'bytes') {\n source = new WrappingReadableByteStreamSource(readable);\n }\n else {\n source = new WrappingReadableStreamDefaultSource(readable);\n }\n return source;\n}\nfunction parseReadableType(type) {\n var typeString = String(type);\n if (typeString === 'bytes') {\n return typeString;\n }\n else if (type === undefined) {\n return type;\n }\n else {\n throw new RangeError('Invalid type is specified');\n }\n}\nvar AbstractWrappingReadableStreamSource = /** @class */ (function () {\n function AbstractWrappingReadableStreamSource(underlyingStream) {\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n this._readableStreamController = undefined;\n this._pendingRead = undefined;\n this._underlyingStream = underlyingStream;\n // always keep a reader attached to detect close/error\n this._attachDefaultReader();\n }\n AbstractWrappingReadableStreamSource.prototype.start = function (controller) {\n this._readableStreamController = controller;\n };\n AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {\n assert(this._underlyingReader !== undefined);\n return this._underlyingReader.cancel(reason);\n };\n AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {\n if (this._readerMode === \"default\" /* DEFAULT */) {\n return;\n }\n this._detachReader();\n var reader = this._underlyingStream.getReader();\n this._readerMode = \"default\" /* DEFAULT */;\n this._attachReader(reader);\n };\n AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {\n var _this = this;\n assert(this._underlyingReader === undefined);\n this._underlyingReader = reader;\n var closed = this._underlyingReader.closed;\n if (!closed) {\n return;\n }\n closed\n .then(function () { return _this._finishPendingRead(); })\n .then(function () {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.close();\n }\n }, function (reason) {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.error(reason);\n }\n })\n .catch(noop);\n };\n AbstractWrappingReadableStreamSource.prototype._detachReader = function () {\n if (this._underlyingReader === undefined) {\n return;\n }\n this._underlyingReader.releaseLock();\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n };\n AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {\n var _this = this;\n this._attachDefaultReader();\n // TODO Backpressure?\n var read = this._underlyingReader.read()\n .then(function (result) {\n var controller = _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n }\n else {\n controller.enqueue(result.value);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n AbstractWrappingReadableStreamSource.prototype._tryClose = function () {\n try {\n this._readableStreamController.close();\n }\n catch (_a) {\n // already errored or closed\n }\n };\n AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {\n var _this = this;\n var pendingRead;\n var finishRead = function () {\n if (_this._pendingRead === pendingRead) {\n _this._pendingRead = undefined;\n }\n };\n this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);\n };\n AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {\n var _this = this;\n if (!this._pendingRead) {\n return undefined;\n }\n var afterRead = function () { return _this._finishPendingRead(); };\n return this._pendingRead.then(afterRead, afterRead);\n };\n return AbstractWrappingReadableStreamSource;\n}());\nvar WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {\n __extends(WrappingReadableStreamDefaultSource, _super);\n function WrappingReadableStreamDefaultSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WrappingReadableStreamDefaultSource.prototype.pull = function () {\n return this._pullWithDefaultReader();\n };\n return WrappingReadableStreamDefaultSource;\n}(AbstractWrappingReadableStreamSource));\nfunction toUint8Array(view) {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\nfunction copyArrayBufferView(from, to) {\n var fromArray = toUint8Array(from);\n var toArray = toUint8Array(to);\n toArray.set(fromArray, 0);\n}\nvar WrappingReadableByteStreamSource = /** @class */ (function (_super) {\n __extends(WrappingReadableByteStreamSource, _super);\n function WrappingReadableByteStreamSource(underlyingStream) {\n var _this = this;\n var supportsByob = supportsByobReader(underlyingStream);\n _this = _super.call(this, underlyingStream) || this;\n _this._supportsByob = supportsByob;\n return _this;\n }\n Object.defineProperty(WrappingReadableByteStreamSource.prototype, \"type\", {\n get: function () {\n return 'bytes';\n },\n enumerable: false,\n configurable: true\n });\n WrappingReadableByteStreamSource.prototype._attachByobReader = function () {\n if (this._readerMode === \"byob\" /* BYOB */) {\n return;\n }\n assert(this._supportsByob);\n this._detachReader();\n var reader = this._underlyingStream.getReader({ mode: 'byob' });\n this._readerMode = \"byob\" /* BYOB */;\n this._attachReader(reader);\n };\n WrappingReadableByteStreamSource.prototype.pull = function () {\n if (this._supportsByob) {\n var byobRequest = this._readableStreamController.byobRequest;\n if (byobRequest) {\n return this._pullWithByobRequest(byobRequest);\n }\n }\n return this._pullWithDefaultReader();\n };\n WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {\n var _this = this;\n this._attachByobReader();\n // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly\n // create a separate buffer to read into, then copy that to byobRequest.view\n var buffer = new Uint8Array(byobRequest.view.byteLength);\n // TODO Backpressure?\n var read = this._underlyingReader.read(buffer)\n .then(function (result) {\n _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n byobRequest.respond(0);\n }\n else {\n copyArrayBufferView(result.value, byobRequest.view);\n byobRequest.respond(result.value.byteLength);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n return WrappingReadableByteStreamSource;\n}(AbstractWrappingReadableStreamSource));\n\nfunction createWritableStreamWrapper(ctor) {\n assert(isWritableStreamConstructor(ctor));\n return function (writable) {\n if (writable.constructor === ctor) {\n return writable;\n }\n var sink = createWrappingWritableSink(writable);\n return new ctor(sink);\n };\n}\nfunction createWrappingWritableSink(writable) {\n assert(isWritableStream(writable));\n assert(writable.locked === false);\n var writer = writable.getWriter();\n return new WrappingWritableStreamSink(writer);\n}\nvar WrappingWritableStreamSink = /** @class */ (function () {\n function WrappingWritableStreamSink(underlyingWriter) {\n var _this = this;\n this._writableStreamController = undefined;\n this._pendingWrite = undefined;\n this._state = \"writable\" /* WRITABLE */;\n this._storedError = undefined;\n this._underlyingWriter = underlyingWriter;\n this._errorPromise = new Promise(function (resolve, reject) {\n _this._errorPromiseReject = reject;\n });\n this._errorPromise.catch(noop);\n }\n WrappingWritableStreamSink.prototype.start = function (controller) {\n var _this = this;\n this._writableStreamController = controller;\n this._underlyingWriter.closed\n .then(function () {\n _this._state = \"closed\" /* CLOSED */;\n })\n .catch(function (reason) { return _this._finishErroring(reason); });\n };\n WrappingWritableStreamSink.prototype.write = function (chunk) {\n var _this = this;\n var writer = this._underlyingWriter;\n // Detect past errors\n if (writer.desiredSize === null) {\n return writer.ready;\n }\n var writeRequest = writer.write(chunk);\n // Detect future errors\n writeRequest.catch(function (reason) { return _this._finishErroring(reason); });\n writer.ready.catch(function (reason) { return _this._startErroring(reason); });\n // Reject write when errored\n var write = Promise.race([writeRequest, this._errorPromise]);\n this._setPendingWrite(write);\n return write;\n };\n WrappingWritableStreamSink.prototype.close = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return this._underlyingWriter.close();\n }\n return this._finishPendingWrite().then(function () { return _this.close(); });\n };\n WrappingWritableStreamSink.prototype.abort = function (reason) {\n if (this._state === \"errored\" /* ERRORED */) {\n return undefined;\n }\n var writer = this._underlyingWriter;\n return writer.abort(reason);\n };\n WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {\n var _this = this;\n var pendingWrite;\n var finishWrite = function () {\n if (_this._pendingWrite === pendingWrite) {\n _this._pendingWrite = undefined;\n }\n };\n this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);\n };\n WrappingWritableStreamSink.prototype._finishPendingWrite = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return Promise.resolve();\n }\n var afterWrite = function () { return _this._finishPendingWrite(); };\n return this._pendingWrite.then(afterWrite, afterWrite);\n };\n WrappingWritableStreamSink.prototype._startErroring = function (reason) {\n var _this = this;\n if (this._state === \"writable\" /* WRITABLE */) {\n this._state = \"erroring\" /* ERRORING */;\n this._storedError = reason;\n var afterWrite = function () { return _this._finishErroring(reason); };\n if (this._pendingWrite === undefined) {\n afterWrite();\n }\n else {\n this._finishPendingWrite().then(afterWrite, afterWrite);\n }\n this._writableStreamController.error(reason);\n }\n };\n WrappingWritableStreamSink.prototype._finishErroring = function (reason) {\n if (this._state === \"writable\" /* WRITABLE */) {\n this._startErroring(reason);\n }\n if (this._state === \"erroring\" /* ERRORING */) {\n this._state = \"errored\" /* ERRORED */;\n this._errorPromiseReject(this._storedError);\n }\n };\n return WrappingWritableStreamSink;\n}());\n\nfunction createTransformStreamWrapper(ctor) {\n assert(isTransformStreamConstructor(ctor));\n return function (transform) {\n if (transform.constructor === ctor) {\n return transform;\n }\n var transformer = createWrappingTransformer(transform);\n return new ctor(transformer);\n };\n}\nfunction createWrappingTransformer(transform) {\n assert(isTransformStream(transform));\n var readable = transform.readable, writable = transform.writable;\n assert(readable.locked === false);\n assert(writable.locked === false);\n var reader = readable.getReader();\n var writer;\n try {\n writer = writable.getWriter();\n }\n catch (e) {\n reader.releaseLock(); // do not leak reader\n throw e;\n }\n return new WrappingTransformStreamTransformer(reader, writer);\n}\nvar WrappingTransformStreamTransformer = /** @class */ (function () {\n function WrappingTransformStreamTransformer(reader, writer) {\n var _this = this;\n this._transformStreamController = undefined;\n this._onRead = function (result) {\n if (result.done) {\n return;\n }\n _this._transformStreamController.enqueue(result.value);\n return _this._reader.read().then(_this._onRead);\n };\n this._onError = function (reason) {\n _this._flushReject(reason);\n _this._transformStreamController.error(reason);\n _this._reader.cancel(reason).catch(noop);\n _this._writer.abort(reason).catch(noop);\n };\n this._onTerminate = function () {\n _this._flushResolve();\n _this._transformStreamController.terminate();\n var error = new TypeError('TransformStream terminated');\n _this._writer.abort(error).catch(noop);\n };\n this._reader = reader;\n this._writer = writer;\n this._flushPromise = new Promise(function (resolve, reject) {\n _this._flushResolve = resolve;\n _this._flushReject = reject;\n });\n }\n WrappingTransformStreamTransformer.prototype.start = function (controller) {\n this._transformStreamController = controller;\n this._reader.read()\n .then(this._onRead)\n .then(this._onTerminate, this._onError);\n var readerClosed = this._reader.closed;\n if (readerClosed) {\n readerClosed\n .then(this._onTerminate, this._onError);\n }\n };\n WrappingTransformStreamTransformer.prototype.transform = function (chunk) {\n return this._writer.write(chunk);\n };\n WrappingTransformStreamTransformer.prototype.flush = function () {\n var _this = this;\n return this._writer.close()\n .then(function () { return _this._flushPromise; });\n };\n return WrappingTransformStreamTransformer;\n}());\n\nexport { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper };\n//# sourceMappingURL=web-streams-adapter.mjs.map\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n r.strip();\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)\n * @module biginteger/bn\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n this.value = new BN(n);\n }\n\n clone() {\n const clone = new BigInteger(null);\n this.value.copy(clone.value);\n return clone;\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value.iadd(new BN(1));\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value.isub(new BN(1));\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value.iadd(x.value);\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value.isub(x.value);\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value.imul(x.value);\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value = this.value.umod(m.value);\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation\n * Much faster than this.exp(e).mod(n)\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n // We use either Montgomery or normal reduction context\n // Montgomery requires coprime n and R (montogmery multiplier)\n // bn.js picks R as power of 2, so n must be odd\n const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);\n const x = this.clone();\n x.value = x.value.toRed(nred).redPow(e.value).fromRed();\n return x;\n }\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n // invm returns a wrong result if the inverse does not exist\n if (!this.gcd(n).isOne()) {\n throw new Error('Inverse does not exist');\n }\n return new BigInteger(this.value.invm(n.value));\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} n - Operand\n * @returns {BigInteger} gcd\n */\n gcd(n) {\n return new BigInteger(this.value.gcd(n.value));\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value.ishln(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value.ishrn(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value.eq(x.value);\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value.lt(x.value);\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value.lte(x.value);\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value.gt(x.value);\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value.gte(x.value);\n }\n\n isZero() {\n return this.value.isZero();\n }\n\n isOne() {\n return this.value.eq(new BN(1));\n }\n\n isNegative() {\n return this.value.isNeg();\n }\n\n isEven() {\n return this.value.isEven();\n }\n\n abs() {\n const res = this.clone();\n res.value = res.value.abs();\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n return this.value.toNumber();\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n return this.value.testn(i) ? 1 : 0;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n return this.value.bitLength();\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n return this.value.byteLength();\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n return this.value.toArrayLike(Uint8Array, endian, length);\n }\n}\n","var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n","'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w) {\n var naf = [];\n var ws = 1 << (w + 1);\n var k = num.clone();\n while (k.cmpn(1) >= 0) {\n var z;\n if (k.isOdd()) {\n var mod = k.andln(ws - 1);\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n naf.push(z);\n\n // Optimization, shift by word if possible\n var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;\n for (var i = 1; i < shift; i++)\n naf.push(0);\n k.iushrn(shift);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n []\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n var m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n var m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n for (var j = 0; j < naf.length; j += doubles.step) {\n var nafW = 0;\n for (var k = j + doubles.step - 1; k >= j; k--)\n nafW = (nafW << 1) + naf[k];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (var j = 0; j < repr.length; j++) {\n var nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var k = 0; i >= 0 && naf[i] === 0; i--)\n k++;\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n for (var i = 0; i < len; i++) {\n var p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (var i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a]);\n naf[b] = getNAF(coeffs[b], wndWidth[b]);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b] /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3 /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (var j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (var i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (var j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (var j = 0; j < len; j++) {\n var z = tmp[j];\n var p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (var i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16)\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n};\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point))\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point))\n }\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate)\n }\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (var i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (var i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n // Note: this implementation is according to the original paper\n // by P. Montgomery, NOT the one by D. J. Bernstein.\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n var bytes = utils.toArray(bytes, enc);\n\n // TODO Curve448\n // Montgomery curve points must be represented in the compressed format\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (bytes.length === 33 && bytes[0] === 0x40)\n bytes = bytes.slice(1, 33).reverse(); // point must be little-endian\n if (bytes.length !== 32)\n throw new Error('Unknown point compression format');\n return this.point(bytes, 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n\n // Note: the output should always be little-endian\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (compact) {\n return [ 0x40 ].concat(this.getX().toArray('le', len));\n } else {\n return this.getX().toArray('be', len);\n }\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n if (this.curve.twisted) {\n // E = a * C\n var e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n var h = this.z.redSqr();\n // J = F - 2 * H\n var j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n var e = c.redAdd(d);\n // H = (c * Z1)^2\n var h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n var j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else if (options.type === 'mont')\n this.curve = new curve.mont(options);\n else throw new Error('Unknown curve type.');\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve\n });\n return curve;\n }\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'\n ]\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'\n ]\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'\n ]\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'\n ]\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650'\n ]\n});\n\n// https://tools.ietf.org/html/rfc7748#section-4.1\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9'\n ]\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.4\ndefineCurve('brainpoolP256r1', {\n type: 'short',\n prime: null,\n p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',\n a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',\n b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',\n n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',\n hash: hash.sha256, // or 384, or 512\n gRed: false,\n g: [\n '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',\n '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.6\ndefineCurve('brainpoolP384r1', {\n type: 'short',\n prime: null,\n p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +\n 'ACD3A729 901D1A71 87470013 3107EC53',\n a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +\n '8AA5814A 503AD4EB 04A8C7DD 22CE2826',\n b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +\n '7CB43902 95DBC994 3AB78696 FA504C11',\n n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +\n 'CF3AB6AF 6B7FC310 3B883202 E9046565',\n hash: hash.sha384, // or 512\n gRed: false,\n g: [\n '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +\n 'E8E826E03436D646AAEF87B2E247D4AF1E',\n '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +\n '280E4646217791811142820341263C5315'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.7\ndefineCurve('brainpoolP512r1', {\n type: 'short',\n prime: null,\n p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +\n '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',\n a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +\n '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',\n b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +\n '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',\n n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +\n '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',\n hash: hash.sha512,\n gRed: false,\n g: [\n '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +\n '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',\n '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +\n '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'\n ]\n});\n\n// https://en.bitcoin.it/wiki/Secp256k1\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre\n ]\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc\n });\n};\n\n// TODO: should not validate for X25519\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // For Curve25519/Curve448 we have a specific procedure.\n // TODO Curve448\n if (this.ec.curve.type === 'mont') {\n var one = this.ec.curve.one;\n var mask = one.ushln(255 - 3).sub(one).ushln(3);\n this.priv = this.priv.or(one.ushln(255 - 1));\n this.priv = this.priv.and(mask);\n } else\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n }\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0 && (r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] === 0 && (s[1] & 0x80)) {\n s = s.slice(1);\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray()\n });\n\n // Key generation for curve25519 is simpler\n if (this.curve.type === 'mont') {\n var priv = new BN(drbg.generate(32));\n return this.keyFromPrivate(priv);\n }\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n do {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n } while (true);\n};\n\nEC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {\n bitSize = bitSize || msg.byteLength() * 8;\n var delta = bitSize - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.truncateMsg = function truncateMSG(msg) {\n // Bit size is only determined correctly for Uint8Arrays and hex strings\n var bitSize;\n if (msg instanceof Uint8Array) {\n bitSize = msg.byteLength * 8;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else if (typeof msg === 'string') {\n bitSize = msg.length * 4;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else {\n msg = this._truncateToN(new BN(msg, 16));\n }\n return msg;\n}\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this.truncateMsg(msg);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8'\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; true; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n // Fallback to the old code\n var ret = this._verify(this.truncateMsg(msg), signature, key) ||\n this._verify(this._truncateToN(new BN(msg, 16)), signature, key);\n return ret;\n};\n\nEC.prototype._verify = function _verify(msg, signature, key) {\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n\n if (!this.curve._maxwellTrick) {\n var p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n var p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n if (params.hasOwnProperty('secret'))\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else {\n this._pubBytes = parseBytes(params.pub);\n if (this._pubBytes && this._pubBytes.length === 33 &&\n this._pubBytes[0] === 0x40)\n this._pubBytes = this._pubBytes.slice(1, 33);\n if (this._pubBytes && this._pubBytes.length !== 32)\n throw new Error('Unknown point compression format');\n }\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n // https://tools.ietf.org/html/rfc8032#section-5.1.5\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength)\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar HmacDRBG = require('hmac-drbg');\nvar rand = require('brorand');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n var curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.curve.n.toArray()\n });\n\n return this.keyFromSecret(drbg.generate(32));\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","this","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","prototype","undefined","read","async","length","value","done","readToEnd","join","result","slice","clone","then","push","write","chunk","close","abort","reason","isNode","globalThis","process","versions","NodeReadableStream","isStream","ReadableStream","isPrototypeOf","streams.ReadableStream","isUint8Array","Uint8Array","concatUint8Array","arrays","totalLength","i","Error","pos","forEach","element","set","NodeBuffer","nodeToWeb","webToNode","nodeStream","canceled","start","controller","pause","on","isBuffer","buffer","byteOffset","byteLength","enqueue","e","error","pull","resume","cancel","destroy","NodeReadable","webStream","options","_reader","streams.getReader","size","callback","doneReadingSet","WeakSet","externalBuffer","Reader","streams.isArrayStream","reader","_read","bind","_releaseLock","_cancel","streamType","streams.isStream","streams.nodeToWeb","doneReading","has","add","shift","readLine","returnVal","streams.concat","lineEndIndex","indexOf","concat","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","filter","toPonyfillReadable","toNativeReadable","WritableStream","TransformStream","loadStreamsPonyfill","ponyfill","adapter","all","createReadableStreamWrapper","toStream","toArrayStream","list","some","map","transform","transformWithCancel","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","transformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","highWaterMark","finish","output","data","result1","result2","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","Object","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","arrayStream","BigInteger","n","hex","hexByte","toString","BigInt","iinc","inc","idec","dec","iadd","x","isub","sub","imul","mul","imod","m","isNegative","mod","modExp","isZero","isOne","exp","r","lsb","rx","modInv","gcd","_egcd","b","y","xPrev","yPrev","a","q","tmp","ileftShift","leftShift","irightShift","rightShift","equal","lt","lte","gt","gte","isEven","abs","res","toNumber","number","Number","MAX_SAFE_INTEGER","getBit","bitLength","zero","one","negOne","bitlen","eight","len","toUint8Array","endian","rawLength","offset","parseInt","reverse","detectBigInt","byValue","curve","p256","secp256r1","prime256v1","p384","secp384r1","p521","secp521r1","secp256k1","ed25519Legacy","ED25519","ed25519","Ed25519","curve25519Legacy","X25519","cv25519","curve25519","Curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","eddsa","aedh","aedsa","x25519","x448","ed448","symmetric","plaintext","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","webHash","aead","eax","ocb","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuer","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","type","debugMode","env","NODE_ENV","util","isString","String","stream.isUint8Array","stream.isStream","readNumber","writeNumber","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","leftPad","padded","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","k","uint8ArrayToHex","h","c","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","s","printDebug","log","printDebugError","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","crypto","subtle","getBigInteger","default","getNodeCrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","selectUint8","isAES","cipherAlgo","enums","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","from","btoa","atob","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","deflateLevel","aeadProtect","preferredAEADAlgorithm","aeadChunkSizeByte","s2kIterationCountByte","allowUnauthenticatedMessages","allowUnauthenticatedStream","checksumRequired","minRSABits","passwordCollisionCheck","revocationsExpire","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","minBytesForWebCrypto","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","useIndutnyElliptic","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","getType","header","match","addheader","customComment","config","getCheckSum","base64.encode","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","splitChecksum","body","checksum","lastEquals","lastIndexOf","unarmor","defaultConfig","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","checksumVerified","stream.readToEnd","stream.passiveClone","stream.pipe","checksumVerifiedString","stream.isArrayStream","messageType","partIndex","partTotal","bodyClone","KeyID","toHex","equals","keyID","matchWildcard","isWildcard","isNull","static","AES_asm","gexp3","glog3","ginit_done","gmul","aes_sbox","aes_sinv","aes_enc","aes_dec","aes_init_done","aes_init","_s","ginv","d","ginit","wrapper","foreign","heap","asm","stdlib","S0","S1","S2","S3","I0","I1","I2","I3","N0","N1","N2","N3","M0","M1","M2","M3","H0","H1","H2","H3","R","HEAP","DATA","_core","x0","x1","x2","x3","t1","t2","t3","y0","y1","y2","y3","_ecb_enc","_ecb_dec","_cbc_enc","_cbc_dec","_cfb_enc","_cfb_dec","_ofb","_ctr","_gcm_mac","z0","z1","z2","z3","set_rounds","set_state","s0","s1","s2","s3","set_iv","i0","i1","i2","i3","set_nonce","n0","n1","n2","n3","set_mask","m0","m1","m2","m3","set_counter","c0","c1","c2","c3","get_state","get_iv","gcm_init","cipher","mode","ret","_cipher_modes","mac","_mac_modes","set_key","ks","k0","k1","k2","k3","k4","k5","k6","k7","ekeys","dkeys","rcon","jj","ENC","ECB","CBC","CFB","OFB","CTR","DEC","MAC","GCM","HEAP_DATA","is_bytes","_heap_init","heapSize","_heap_write","hpos","dpos","dlen","hlen","wlen","joinBytes","arg","totalLenght","reduce","sum","curr","cursor","IllegalStateError","args","IllegalArgumentError","SecurityError","heap_pool","asm_pool","AES","iv","padding","acquire_asm","pop","reset","release_asm","keylen","keyview","getUint32","ivview","AES_Encrypt_process","TypeError","amode","rpos","AES_Encrypt_finish","plen","rlen","hasOwnProperty","p","AES_Decrypt_process","AES_Decrypt_finish","pad","pcheck","AES_ECB","encrypt","decrypt","aes","C","aesECB","block","blockSize","keySize","des","keys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","left","right","looping","cbcleft","cbcleft2","cbcright","cbcright2","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","src","dst","l","f1","f2","f3","scheduleA","scheduleB","I","sBox","inn","w","ki","half","round","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","u","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","vector","off","_decryptBlock","kk","sha1_asm","H4","TOTAL0","TOTAL1","I4","O0","O1","O2","O3","O4","w0","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32","w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61","w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","_core_heap","_state_to_heap","h0","h1","h2","h3","h4","total0","total1","hashed","hmac_reset","_hmac_opad","hmac_init","p0","p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","hmac_finish","t0","t4","pbkdf2_generate_block","count","Hash","HASH_SIZE","Sha1","NAME","BLOCK_SIZE","asm_function","Sha256","H5","H6","H7","I5","I6","I7","O5","O6","O7","f","g","h5","h6","h7","t5","t6","t7","sha256_asm","assert","val","msg","module","create","ctor","superCtor","super_","enumerable","configurable","TempCtor","enc","hi","lo","zero2","htonl","zero8","word","inherits","ah","al","bh","bl","ch","cl","dh","dl","carry","eh","el","num","BlockHash","pending","pendingTotal","outSize","hmacStrength","_delta8","_delta32","update","utils","toArray","join32","_update","digest","_pad","_digest","rotr32","z","ch32","p32","maj32","sum32","sum32_4","sum32_5","shaCommon","s0_256","s1_256","g0_256","g1_256","common","sha256_K","SHA256","W","SHA224","T1","T2","toHex32","split32","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","SHA512","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","SHA384","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotl32","sum32_3","RIPEMD160","K","Kh","A","B","D","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","md5cycle","ff","gg","add32","cmn","md5blk","md5blks","hex_chr","rhex","webCrypto","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","hashjsHash","webCryptoHash","hashInstance","asmcryptoHash","hashFunctions","entree","state","substring","tail","md51","ripemd160","algo","getHashByteLength","AES_CFB","getCipher","algoName","knownAlgos","getCiphers","nodeAlgos","pt","cipherObj","createCipheriv","nodeEncrypt","ALGO","_key","importKey","cbc_pt","ct","xorMut","webEncrypt","cfb","aesEncrypt","cipherfn","block_size","blockc","ciphertext","encblock","decipherObj","createDecipheriv","nodeDecrypt","aesDecrypt","blockp","decblock","AES_CTR","nonce","AES_CTR_set_options","counter","mask","pow","view","AES_CBC","blockLength","rightXORMut","zeroBlock","CMAC","cbc","padding2","ivLength","tagLength","two","OMAC","cmac","en","final","EAX","omac","ctr","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","xor","OCB","encipher","decipher","maxNtz","crypt","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","xorInput","$","cipherInput","cipherName","ciphers","mask_x","mask_$","constructKeyVariables","crypted","_AES_GCM_data_maxLength","AES_GCM","tagSize","gamma0","noncelen","noncebuf","_gcm_mac_process","nonceview","RangeError","cleartext","tagsize","AES_GCM_encrypt","AES_GCM_decrypt","AES_GCM_Encrypt_process","AES_GCM_Encrypt_finish","alen","clen","AES_GCM_Decrypt_process","tlen","AES_GCM_Decrypt_finish","atag","acheck","setAAD","getAuthTag","de","setAuthTag","additionalData","gcm","nacl","gf","Float64Array","randombytes","_9","gf0","gf1","_121665","D2","X","Y","crypto_verify_32","xi","yi","vn","set25519","car25519","o","v","sel25519","pack25519","neq25519","par25519","unpack25519","Z","M","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","x32","x16","crypto_scalarmult_base","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","cleanup","arr","scalarMult","box","keyPair","fromSecretKey","sign","signedMsg","sm","smlen","crypto_sign","detached","sig","verify","crypto_sign_open","fromSeed","seed","setPRNG","self","msCrypto","getRandomValues","min","require","randomBytes","exports","getRandomBytes","getRandomBigInteger","modulus","randomProbablePrime","thirty","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","rand","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","emLen","hashPrefix","tLen","fill","EM","asn1","RSAPrivateKey","define","seq","obj","int","RSAPublicKey","hashAlgo","hashName","jwk","pNum","qNum","dNum","dq","dp","kty","qi","ext","privateToJWK","webSign","err","BN","pBNum","qBNum","dBNum","subn","createSign","keyObject","version","publicExponent","privateExponent","prime1","prime2","exponent1","exponent2","coefficient","createPrivateKey","der","format","pem","label","nodeSign","bnSign","publicToJWK","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","constants","RSA_PKCS1_PADDING","publicEncrypt","bnEncrypt","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","keyGenOpt","modulusLength","generateKey","exportKey","generateKeyPair","opts","publicKeyEncoding","privateKeyEncoding","prv","_","toArrayLike","phi","nSizeOver3","rde","pSize","n1023","threshold","rqx","OID","oid","getName","keyFromPrivate","indutnyCurve","priv","keyFromPublic","pub","validate","getIndutnyCurve","elliptic","ec","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","stream.TransformStream","lengthByte","nextPacket","UnsupportedError","params","captureStackTrace","UnparseablePacket","rawContent","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","CurveWithOID","oidOrName","webCryptoKey","namedCurve","jwkToRawPublic","webGenKeyPair","createECDH","generateKeys","getPublicKey","getPrivateKey","nodeGenKeyPair","genKeyPair","entropy","getPublic","getPrivate","validateStandardParams","Q","supportedCurves","curveName","dG","validationErrors","eq","bufX","bufY","rawPublicToJWK","crv","ECPrivateKey","parameters","unused","ECDSASignature","ellipticSign","SubjectPublicKeyInfo","algorithm","subjectPublicKey","ellipticVerify","octstr","explicit","optional","any","bitstr","AlgorithmIdentifier","objid","use","getPreferredHashAlgo","RS","wrap","IV","P","unpack","unwrap","createArrayBuffer","setUint32","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","genPrivateEphemeralKey","recipient","deriveBits","public","webPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","V","derive","ellipticPublicEphemeralKey","secret","webPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","ellipticPrivateEphemeralKey","pkcs5.encode","wrappedKey","aesKW.wrap","pkcs5.decode","aesKW.unwrap","nodeSubtleCrypto","webcrypto","HKDF","inputKey","salt","info","outLen","importedKey","hashAlgoName","computeHMAC","hmacKey","hmacMessage","createHmac","pseudoRandomKey","hashLen","outputKeyingMaterial","roundInput","HKDF_INFO","recipientA","ephemeralSecretKey","sharedSecret","ephemeralPublicKey","hkdfInput","computeHKDF","xr","u1","u2","qSize","n150","rsa","publicParams","curveSize","publicKeyParams","privateKeyParams","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","instance","followLength","checkSupportedCurve","keyAlgo","symmetricAlgo","ECDHSymkey","ecdhX","fromObject","sessionKeyParams","privateParams","algosWithNativeRepresentation","orderedParams","generate","validateParams","algoModule","prefixrandom","repeat","random","pkcs1","pkcs5","aesKW","assign","TYPED_OK","Uint16Array","Int32Array","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","fnUntyped","Buf8","Buf16","Buf32","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","STORED_BLOCK","STATIC_TREES","DYN_TREES","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","MAX_MATCH","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","max_code","d_code","dist","put_short","pending_buf","send_bits","bi_valid","bi_buf","send_code","tree","bi_reverse","code","gen_codes","bl_count","next_code","init_block","dyn_ltree","dyn_dtree","bl_tree","opt_len","static_len","last_lit","matches","bi_windup","smaller","depth","_n2","_m2","pqdownheap","heap_len","compress_block","ltree","dtree","lc","extra","lx","d_buf","l_buf","build_tree","desc","stree","heap_max","base","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","_tr_init","tr_static_init","l_desc","d_desc","bl_desc","_tr_stored_block","stored_len","utils.arraySet","window","copy_block","_tr_align","bi_flush","_tr_flush_block","opt_lenb","static_lenb","max_blindex","level","strm","data_type","black_mask","detect_data_type","build_bl_tree","strategy","lcodes","dcodes","blcodes","rank","send_all_trees","_tr_tally","lit_bufsize","adler32","adler","crcTable","table","makeTable","crc32","MAX_MEM_LEVEL","MIN_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","errorCode","flush_pending","avail_out","pending_out","next_out","total_out","flush_block_only","trees._tr_flush_block","block_start","strstart","put_byte","putShortMSB","read_buf","avail_in","next_in","total_in","longest_match","cur_match","chain_length","max_chain_length","scan","best_len","prev_length","nice_match","limit","w_size","_win","wmask","w_mask","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","_w_size","more","window_size","hash_size","head","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","trees._tr_tally","max_lazy_match","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","max_block_size","pending_buf_size","max_start","DeflateState","status","gzhead","gzindex","method","last_flush","w_bits","hash_bits","utils.Buf16","deflateReset","trees._tr_init","deflateResetKeep","lm_init","deflate","old_flush","beg","hcrc","comment","os","level_flags","bstate","deflate_huff","deflate_rle","trees._tr_align","trees._tr_stored_block","__","_utf8len","utils.Buf8","string2buf","m_pos","buf_len","str_len","ZStream","Deflate","chunkSize","windowBits","memLevel","opt","raw","gzip","ended","zlib_deflate.deflateInit2","dictionary","dict","strings.string2buf","avail","next","tmpDict","dictLength","zlib_deflate.deflateSetDictionary","_dict_set","_mode","zlib_deflate.deflate","onEnd","onData","utils.shrinkBuf","zlib_deflate.deflateEnd","utils.flattenChunks","BAD","TYPE","inflate_fast","_in","_out","hold","here","op","from_source","dmax","wsize","whave","wnext","s_window","lcode","lencode","dcode","distcode","lmask","lenbits","dmask","distbits","top","dolen","dodist","sane","MAXBITS","ENOUGH_LENS","ENOUGH_DISTS","CODES","LENS","DISTS","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","incr","low","sym","root","drop","used","huff","base_index","offs","here_bits","here_op","here_val","extra_index","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","zswap32","InflateState","havedict","flags","check","total","wbits","ncode","nlen","ndist","have","lendyn","distdyn","back","was","inflateReset","utils.Buf32","inflateResetKeep","inflateInit2","inflateReset2","lenfix","distfix","virgin","fixedtables","updatewindow","copy","inflate","put","last_bits","last_op","last_val","hbuf","order","inf_leave","xflags","extra_len","inflateSetDictionary","dictid","GZheader","Inflate","zlib_inflate.inflateInit2","c.Z_OK","zlib_inflate.inflateGetHeader","zlib_inflate.inflateSetDictionary","allowBufError","c.Z_FINISH","c.Z_NO_FLUSH","strings.binstring2buf","zlib_inflate.inflate","c.Z_NEED_DICT","c.Z_BUF_ERROR","c.Z_STREAM_END","c.Z_SYNC_FLUSH","zlib_inflate.inflateEnd","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","remaining","seek","n_bit","n_byte","pi","bufToHex","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","getCRC","updateCRC","updateCRCRun","mtf","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","optDetail","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","CRC32","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","MAX_HUFCODE_BITS","permute","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","multistream","bz","targetStreamCRC","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","verified","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","issuerKeyID","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","writeHashedSubPackets","toHash","stream.slice","stream.clone","writeSubPacket","humanReadable","critical","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","fromBinary","compressionFn","compress_fns","nodeZlib","node_zlib","stream.nodeToWeb","stream.webToNode","pako_zlib","deflateRaw","createDeflateRaw","createDeflate","inflateRaw","createInflateRaw","createInflate","BunzipDecode","SymEncryptedIntegrityProtectedDataPacket","encrypted","sessionKeyAlgorithm","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","AEADEncryptedDataPacket","cipherAlgorithm","aeadAlgorithm","chunkSizeByte","getAEADMode","modeInstance","tagLengthIfDecrypting","tagLengthIfEncrypting","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","latestPromise","cryptedBytes","queuedBytes","finalChunk","cryptedPromise","setInt32","desiredSize","PublicKeyEncryptedSessionKeyPacket","publicKeyID","sessionKey","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","sessionKeyData","S2K","getCount","passphrase","numBytes","rlength","prefixlen","datalen","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","produceKey","encryptionKey","generateSessionKey","associatedData","toEncrypt","PublicKeyPacket","expirationTimeV3","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","PublicSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","startOfSecretKeyData","unparseableKeyMaterial","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","produceEncryptionKey","cleartextWithHash","validParams","generateParams","global","parse5322","inStr","getPos","setPos","initialize","parseString","tokens","semantic","children","ast","parent","child","compareToken","fxnCompare","tok","lit","and","or","prod","invis","colwsp","star","minimum","isUTF8NonAscii","cr","crlf","lf","dquote","htab","sp","vchar","accept","rfc6532","wsp","quotedPair","obsQP","fws","obsFws","ctext","obsCtext","ccontent","cfws","atext","atom","dotAtomText","maybeText","dotAtom","qtext","obsQtext","qcontent","quotedString","address","mailbox","group","nameAddr","addrSpec","displayName","angleAddr","obsAngleAddr","groupList","obsPhrase","collapseWhitespace","mailboxList","obsMboxList","addressList","obsAddrList","obsGroupList","localPart","obsLocalPart","dtext","obsDtext","domainLiteral","domain","obsDomain","rejectTLD","obsNoWsCtl","strict","atInDisplayName","obsRoute","obsDomainList","findNode","stack","findAllNodesNoChildren","names","namesLookup","giveResult","addresses","groupsAndMailboxes","groupOrMailbox","giveResultGroup","giveResultMailbox","simplifyResult","oneResult","partial","groupName","groupResultMailboxes","mailboxes","grabSemantic","aspec","findAllNodes","comments","local","concatComments","startProduction","handleOpts","startAt","defs","isNullUndef","defaults","isObject","parseOneAddress","parseAddressList","parseFrom","parseSender","parseReplyTo","UserIDPacket","email","components","emailAddresses","otherUserID","SecretSubkeyPacket","Signature","packetlist","getSigningKeyIDs","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","prefAlgo","primaryUser","getPrimaryUser","selfCertification","getPreferredCurveHashAlgo","getPreferredAlgo","userIDs","defaultAlgo","preferredSenderAlgo","prefPropertyName","senderAlgoSupport","recipientPrefs","Boolean","signingKeyPacket","signaturePacket","mergeSignatures","source","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","sanitizeKeyOptions","subkeyDefaults","isValidSigningKeyPacket","isValidEncryptionKeyPacket","isValidDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","signingKeys","isPrivate","signingKey","getSigningKey","certificate","verificationKeys","issuerKeys","getKeys","isRevoked","certifications","certification","valid","verifyCertificate","sourceUser","srcSelfSig","srcRevSig","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","sort","helper.isValidSigningKeyPacket","helper.checkKeyRequirements","helper.isValidEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","revocationCertificate","privateKeys","userSign","certify","verifyAllCertifications","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","fromSecretKeyPacket","pubSubkeyPacket","fromSecretSubkeyPacket","helper.isValidDecryptionKeyPacket","allDummies","defaultOptions","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","userIDPacket","subkeyOptions","subkeySignaturePacket","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","sessionKeyObjects","decryptSessionKeys","symEncryptedPacketlist","symEncryptedPacket","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","password","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","getDecryptionKeys","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgorithmName","supported","isAEADSupported","getEncryptionKey","maybeKey","wildcard","encryptionKeyIDs","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","literalDataPacket","existingSigPacketlist","onePassSig","signingKeyID","onePassSignatureList","createSignaturePackets","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","detachedSignature","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","CleartextMessage","newSignature","hashes","ar","checkMessage","checkCleartextOrMessage","checkOutputMessageFormat","defaultConfigPropsCount","checkConfig","inputConfigProps","inputProp","convertStream","streaming","encoding","setEncoding","stream.toNativeReadable","linkStreams","formatObject","object","SymbolPolyfill","iterator","description","noop","globals","typeIsObject","rethrowAssertionErrorRejection","originalPromise","originalPromiseThen","originalPromiseResolve","originalPromiseReject","newPromise","executor","promiseResolvedWith","promiseRejectedWith","PerformPromiseThen","onFulfilled","onRejected","uponPromise","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","reflectCall","F","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","peek","front","ReadableStreamReaderGenericInitialize","_ownerReadableStream","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","isFinite","MathTrunc","trunc","assertDictionary","context","assertFunction","assertObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","toStringTag","asyncIterator","ReadableStreamAsyncIteratorImpl","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","return","returnSteps","_returnSteps","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","IsFiniteNonNegativeNumber","IsNonNegativeNumber","DequeueValue","container","pair","_queue","_queueTotalSize","EnqueueValueWithSize","ResetQueue","CreateArrayFromList","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespond","respondWithNewView","isView","firstDescriptor","_pendingPullIntos","bytesFilled","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","_byobRequest","request","SetUpReadableStreamBYOBRequest","ReadableByteStreamControllerGetDesiredSize","_closeRequested","_controlledReadableByteStream","ReadableByteStreamControllerError","ReadableByteStreamControllerClearAlgorithms","ReadableStreamClose","ReadableByteStreamControllerClose","transferredBuffer","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableStreamHasBYOBReader","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerEnqueue","_cancelAlgorithm","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","elementSize","viewConstructor","readerType","shouldPull","_started","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","queue","headOfQueue","bytesToCopy","destStart","destOffset","srcOffset","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","ReadableByteStreamControllerClearPendingPullIntos","ReadableStreamError","_strategyHWM","SetUpReadableByteStreamControllerFromUnderlyingSource","underlyingByteSource","startAlgorithm","pullAlgorithm","cancelAlgorithm","SetUpReadableByteStreamController","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","ReadableStreamBYOBReader","byobReaderBrandCheckException","BYTES_PER_ELEMENT","emptyView","ReadableByteStreamControllerPullInto","ReadableStreamBYOBReaderRead","ExtractHighWaterMark","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException$2","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","DOMException$1","_a","isDOMExceptionConstructor","createDOMExceptionPolyfill","ReadableStreamPipeTo","signal","shuttingDown","currentWrite","actions","shutdownWithAction","action","aborted","addEventListener","isOrBecomesErrored","shutdown","isOrBecomesClosed","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","defaultControllerBrandCheckException$1","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","convertPipeOptions","isAbortSignal","assertAbortSignal","rawUnderlyingSource","underlyingSource","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","SetUpReadableStreamDefaultControllerFromUnderlyingSource","streamBrandCheckException$1","rawOptions","convertReaderOptions","AcquireReadableStreamBYOBReader","pipeThrough","rawTransform","convertReadableWritablePair","destination","branches","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","canceled1","canceled2","cancelPromise","value1","value2","CreateReadableStream","compositeReason","cancelResult","ReadableStreamTee","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","streamBrandCheckException","IsTransformStreamDefaultController","defaultControllerBrandCheckException","readableController","TransformStreamDefaultControllerTerminate","ReadableStreamDefaultControllerHasBackpressure","extendStatics","__proto__","__extends","isStreamConstructor","startCalled","isReadableStream","isWritableStream","isTransformStream","supportsByobReader","createWrappingReadableSource","parseReadableType","WrappingReadableByteStreamSource","WrappingReadableStreamDefaultSource","typeString","AbstractWrappingReadableStreamSource","underlyingStream","_underlyingReader","_readerMode","_pendingRead","_underlyingStream","_attachDefaultReader","_detachReader","_attachReader","_this","_finishPendingRead","_pullWithDefaultReader","_tryClose","_setPendingRead","readPromise","pendingRead","finishRead","afterRead","_super","supportsByob","_supportsByob","_attachByobReader","_pullWithByobRequest","to","fromArray","createWrappingWritableSink","WrappingWritableStreamSink","underlyingWriter","_pendingWrite","_underlyingWriter","_errorPromise","_errorPromiseReject","_finishErroring","_startErroring","race","_setPendingWrite","_finishPendingWrite","writePromise","pendingWrite","finishWrite","afterWrite","createWrappingTransformer","WrappingTransformStreamTransformer","_onRead","_onError","_flushReject","_onTerminate","_flushResolve","_flushPromise","readerClosed","isReadableStreamConstructor","byteSourceSupported","supportsByteSource","isTransformStreamConstructor","isWritableStreamConstructor","sink","isBN","negative","words","red","_init","wordSize","parseHex","parseBase","cmp","_initNumber","_initArray","_parseHex","_parseBase","strip","limbLen","limbPow","imuln","_iaddn","_expand","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","out","ncarry","rword","maxJ","groupSize","groupBase","modn","idivn","toJSON","toBuffer","ArrayType","reqLength","littleEndian","andln","iushrn","_countBits","clz32","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","uor","iuand","iand","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","comb10MulTo","mid","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","bl7","bh7","bl8","bh8","bl9","bh9","jumboMulTo","FFTM","mulp","mulTo","hncarry","bigMulTo","makeRBT","N","revBin","rb","rbt","rws","iws","rtws","itws","rtwdf","cos","PI","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","carryMask","newCarry","ishln","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","iabs","_ishlnsubmul","_wordDiv","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","r2","acc","egcd","yp","xp","im","isOdd","jm","_invmp","delta","cmpn","invm","bincn","ucmp","gtn","gten","ltn","lten","eqn","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","rinv","minv","ireduce","imulK","mod3","nOne","lpow","inv","wnd","currentLen","mont","nred","minAssert","minUtils","getNAF","naf","getJSF","jsf","d1","d2","m8","m14","m24","cachedProperty","computer","parseBytes","intFromLE","Rand","_rand","getByte","BaseCurve","conf","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","adjustCount","redN","_maxwellTrick","BasePoint","precomputed","point","_fixedNafMul","doubles","_getDoubles","step","repr","nafW","jpoint","mixedAdd","points","toP","_wnafMul","nafPoints","_getNAFPoints","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","comb","toJ","ja","jb","decodePoint","pointFromX","encodeCompressed","_encode","compact","getX","getY","precompute","beta","_getBeta","_hasDoubles","dbl","ShortCurve","Base","tinv","zeroA","threeA","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","Point","isRed","inf","JPoint","zOne","MontCurve","i4","a24","lambda","betas","_getEndoRoots","lambdas","basis","vec","_getEndoBasis","ntinv","prevR","aprxSqrt","len1","_endoSplit","v1","v2","ax","rhs","_endoWnafMulAdd","npoints","ncoeffs","fromJSON","pre","endoMul","JSON","obj2point","isInfinity","nx","ny","ys1","dyinv","mulAdd","jmulAdd","_precompute","negate","zinv","zinv2","ay","pz2","nz","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","dny","_zeroDbl","_threeDbl","_dbl","yyyy","yyyy8","c8","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","pz3","eqXToP","zs","xc","normalize","diffAdd","da","cb","jumlAdd","EdwardsCurve","twisted","mOneA","oneC","_mulA","_mulC","lhs","pointFromY","_extDbl","nt","_projDbl","_extAdd","_projAdd","require$$0","short","require$$1","require$$2","edwards","require$$3","ft_1","sha1_K","SHA1","require$$4","Hmac","inner","outer","sha","hmac","PresetCurve","defineCurve","cofactor","HmacDRBG","predResist","minEntropy","_reseed","reseedInterval","entropyEnc","nonceEnc","pers","persEnc","_hmac","kmac","reseed","addEnc","KeyPair","_importPrivate","privEnc","_importPublic","pubEnc","fromPublic","fromPrivate","_importDER","recoveryParam","Position","place","getLength","initial","octetLen","rmPadding","constructLength","octets","slen","toDER","backHalf","EC","nh","drbg","ns2","_truncateToN","truncOnly","truncateMsg","bkey","ns1","iter","kp","kpX","canonical","_verify","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Qprime","_secret","isPoint","_pub","_pubBytes","fromSecret","encodePoint","lastIx","encodingLength","decodeInt","privBytes","getSecret","pubBytes","_R","_S","_Rencoded","Rencoded","_Sencoded","Sencoded","encodeInt","toBytes","EDDSA","pointClass","keyFromSecret","hashInt","messagePrefix","s_","makeSignature","SG","normed","xIsOdd","require$$5","rest","unknownOptions","stream.loadStreamsPonyfill","stream.toStream","literalDataPacketlist","expectSigned","publicKeys","clonedPrivateKey","passphrases","signingUserIDs","encryptionUserIDs","signatureNotations","checkBinary","checkString","helper.generateSecretKey","getRevocationCertificate","cleartextMessage","checkHashAlgos","hashAlgos","oneHeader","armoredKey","binaryKey","armoredKeys","binaryKeys","keyIndex","newKey","armoredMessage","binaryMessage","oneKeyList","armoredSignature","binarySignature","reformattedKey","sanitize","reformat","revokedKey","applyRevocationCertificate","revoke","signDetached"],"mappings":";kJAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OA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,KAAOF,EAAKyiH,IAAIviH,KACrBF,EAAKI,OAASJ,EAAKyiH,IAAIriH,OACvBJ,EAAKO,OAASP,EAAKyiH,IAAIliH,OACvBP,EAAKK,OAASL,EAAKyiH,IAAIpiH,OACvBL,EAAKM,OAASN,EAAKyiH,IAAIniH,OACvBN,EAAKu7B,UAAYv7B,EAAKG,OAAOo7B,gBCdZ,CACfy9E,QAAS,CACPE,KAAM,EACNK,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAINrC,IAAK,CACHP,IAAK,EACL4C,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CAC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CAEtE,IACE,MAAMzB,EAAS,GAQf,GANEA,EAAOqmF,WADL/yE,QACwBwE,EAAQm8E,eAAe3gF,EAAW02E,EAAkBnZ,EAAM7tD,SAE1DlL,EAAQ8jC,OAAOouC,EAAkBnZ,EAAM7tD,GAEnEhjB,EAAOqI,KAAkB,WAAXw4C,EAAsB/oC,EAAQs6E,iBAAmBt6E,EAAQk5D,UACnEl5D,EAAQ49D,aAAepiE,GAAWiiF,GAAYv1F,EAAQ8X,GACtDijH,EAAc,CAChB,GAAiC,IAA7B/6H,EAAOqmF,WAAW1mF,OACpB,MAAU8B,MAAM,yBAElBzB,EAAOqI,KAAOyT,EAAc,CAC1B9b,EAAOqI,KACPmrE,GAAiB9zE,gBACTiZ,EAAKkG,WAAW7e,EAAOqmF,WAAW5/E,KAAIk1C,GAAOA,EAAI61B,WAAU,MAKvE,OADAxxE,EAAOqI,WAAa6sF,GAAcl1F,EAAOqI,KAAMyP,EAAQ49D,WAAY70B,GAC5D7gD,EACP,MAAO2/C,GACP,MAAMhnC,EAAK6F,UAAU,iCAAkCmhC,GAE3D"} \ No newline at end of file +{"version":3,"file":"openpgp.min.js","sources":["../node_modules/@openpgp/web-stream-tools/lib/writer.js","../node_modules/@openpgp/web-stream-tools/lib/util.js","../node_modules/@openpgp/web-stream-tools/lib/reader.js","../node_modules/@openpgp/web-stream-tools/lib/streams.js","../src/enums.js","../src/config/config.js","../src/util.js","../src/encoding/base64.js","../src/encoding/armor.js","../src/crypto/cipher/index.js","../src/crypto/hash/md5.js","../src/crypto/hash/index.js","../node_modules/@noble/ciphers/esm/_assert.js","../node_modules/@noble/ciphers/esm/utils.js","../node_modules/@noble/ciphers/esm/_polyval.js","../node_modules/@noble/ciphers/esm/aes.js","../src/crypto/mode/cfb.js","../src/crypto/cmac.js","../src/crypto/mode/eax.js","../src/crypto/mode/ocb.js","../src/crypto/mode/gcm.js","../src/crypto/mode/index.js","../../../src/crypto/biginteger.ts","../src/crypto/random.js","../../../src/crypto/public_key/prime.ts","../src/crypto/pkcs1.js","../src/crypto/public_key/rsa.js","../src/crypto/public_key/elgamal.js","../node_modules/@openpgp/tweetnacl/cryptoBrowser.js","../node_modules/@openpgp/tweetnacl/nacl-fast.js","../src/type/oid.js","../src/packet/packet.js","../src/crypto/public_key/elliptic/eddsa.js","../src/crypto/aes_kw.js","../src/crypto/hkdf.js","../src/crypto/public_key/elliptic/ecdh_x.js","../src/crypto/public_key/elliptic/oid_curves.js","../src/crypto/public_key/elliptic/ecdsa.js","../src/crypto/public_key/elliptic/eddsa_legacy.js","../src/crypto/pkcs5.js","../src/crypto/public_key/elliptic/ecdh.js","../src/crypto/public_key/dsa.js","../src/crypto/public_key/index.js","../src/crypto/signature.js","../src/type/ecdh_symkey.js","../src/type/kdf_params.js","../src/type/ecdh_x_symkey.js","../src/crypto/crypto.js","../src/crypto/index.js","../src/type/s2k/argon2.js","../src/type/s2k/generic.js","../src/type/s2k/index.js","../node_modules/fflate/esm/browser.js","../src/packet/literal_data.js","../src/type/keyid.js","../src/packet/signature.js","../src/packet/one_pass_signature.js","../src/packet/packetlist.js","../src/packet/compressed_data.js","../src/packet/sym_encrypted_integrity_protected_data.js","../src/packet/aead_encrypted_data.js","../src/packet/public_key_encrypted_session_key.js","../src/packet/sym_encrypted_session_key.js","../src/packet/public_key.js","../src/packet/symmetrically_encrypted_data.js","../src/packet/public_subkey.js","../src/packet/user_attribute.js","../src/packet/secret_key.js","../src/packet/userid.js","../src/packet/secret_subkey.js","../src/signature.js","../src/key/helper.js","../src/key/user.js","../src/key/subkey.js","../src/key/key.js","../src/key/public_key.js","../src/key/private_key.js","../src/key/factory.js","../src/message.js","../src/cleartext.js","../src/openpgp.js","../node_modules/@noble/hashes/esm/_assert.js","../node_modules/@noble/hashes/esm/crypto.js","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/_md.js","../node_modules/@noble/hashes/esm/sha256.js","../node_modules/@noble/hashes/esm/hmac.js","../node_modules/@noble/curves/esm/abstract/utils.js","../node_modules/@noble/curves/esm/abstract/modular.js","../node_modules/@noble/curves/esm/abstract/curve.js","../node_modules/@noble/curves/esm/abstract/weierstrass.js","../node_modules/@noble/curves/esm/_shortw_utils.js","../node_modules/@noble/curves/esm/p256.js","../node_modules/@noble/hashes/esm/_u64.js","../node_modules/@noble/hashes/esm/sha512.js","../node_modules/@noble/curves/esm/p384.js","../node_modules/@noble/curves/esm/p521.js","../node_modules/@noble/hashes/esm/sha3.js","../node_modules/@noble/curves/esm/abstract/edwards.js","../node_modules/@noble/curves/esm/abstract/montgomery.js","../node_modules/@noble/curves/esm/ed448.js","../node_modules/@noble/curves/esm/secp256k1.js","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP256r1.ts","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP384r1.ts","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP512r1.ts","../src/crypto/public_key/elliptic/noble_curves.js","../src/crypto/cipher/des.js","../src/crypto/cipher/cast5.js","../src/crypto/cipher/twofish.js","../src/crypto/cipher/blowfish.js","../src/crypto/cipher/legacy_ciphers.js","../node_modules/@noble/hashes/esm/sha1.js","../node_modules/@noble/hashes/esm/ripemd160.js","../src/crypto/hash/noble_hashes.js","../node_modules/argon2id/lib/blake2b.js","../node_modules/argon2id/lib/argon2id.js","../node_modules/argon2id/lib/setup.js","../node_modules/argon2id/index.js","../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../node_modules/@openpgp/seek-bzip/lib/stream.js","../node_modules/@openpgp/seek-bzip/lib/crc32.js","../node_modules/@openpgp/seek-bzip/lib/index.js","../src/packet/marker.js","../src/packet/padding.js","../src/packet/trust.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n Object.setPrototypeOf(this, ArrayStream.prototype);\n\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","/* eslint-disable no-prototype-builtins */\nimport { isArrayStream } from './writer.js';\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n // try and detect a node native stream without having to import its class\n if (input &&\n !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&\n typeof input._read === 'function' && typeof input._readableState === 'object') {\n throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isUint8Array, isStream, isArrayStream } from './util.js';\nimport * as streams from './streams.js';\n\nconst doneReadingSet = new WeakSet();\n/**\n * The external buffer is used to store values that have been peeked or unshifted from the original stream.\n * Because of how streams are implemented, such values cannot be \"put back\" in the original stream,\n * but they need to be returned first when reading from the input again.\n */\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = () => {};\n return;\n }\n let streamType = isStream(input);\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isStream, isArrayStream, isUint8Array, concatUint8Array } from './util.js';\nimport { Reader, externalBuffer } from './reader.js';\nimport { ArrayStream, Writer } from './writer.js';\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n }\n lastBytes = returnValue;\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input)) {\n return input.subarray(begin, end === Infinity ? input.length : end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n const cancelled = await input.cancel(reason);\n // the stream is not always cancelled at this point, so we wait some more\n await new Promise(setTimeout);\n return cancelled;\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n\nexport {\n ArrayStream,\n toStream,\n concatStream,\n concat,\n getReader,\n getWriter,\n pipe,\n transformRaw,\n transform,\n transformPair,\n parse,\n clone,\n passiveClone,\n slice,\n readToEnd,\n cancel,\n fromAsync\n};\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'nistP256': 'nistP256',\n /** @deprecated use `nistP256` instead */\n 'p256': 'nistP256',\n\n /** NIST P-384 Curve */\n 'nistP384': 'nistP384',\n /** @deprecated use `nistP384` instead */\n 'p384': 'nistP384',\n\n /** NIST P-521 Curve */\n 'nistP521': 'nistP521',\n /** @deprecated use `nistP521` instead */\n 'p521': 'nistP521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519Legacy',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519Legacy',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519Legacy',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519Legacy',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n argon2: 4,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11,\n sha3_256: 12,\n sha3_512: 14\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n gcm: 3,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n padding: 21\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuerKeyID: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34,\n preferredCipherSuites: 39\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4,\n seipdv2: 8\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha512,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * This option is applicable to:\n * - key generation (encryption key preferences),\n * - password-based message encryption, and\n * - private key encryption.\n * In the case of message encryption using public keys, the encryption key preferences are respected instead.\n * Note: not all OpenPGP implementations are compatible with this option.\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)\n * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,\n * this option must be set, otherwise key parsing and/or key decryption will fail.\n * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys\n * will be processed incorrectly.\n */\n parseAEADEncryptedV4KeysAsLegacy: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.gcm,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use v6 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v6Keys\n */\n v6Keys: false,\n /**\n * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).\n * These are non-standard entities, which in the crypto-refresh have been superseded\n * by v6 keys and v6 signatures, respectively.\n * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,\n * hence parsing them might be necessary in some cases.\n */\n enableParsingV5Entities: false,\n /**\n * S2K (String to Key) type, used for key derivation in the context of secret key encryption\n * and password-encrypted data. Weaker s2k options are not allowed.\n * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it\n * (pending standardisation).\n * @memberof module:config\n * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}\n */\n s2kType: enums.s2k.iterated,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:\n * Iteration Count Byte for Iterated and Salted S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.\n * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:\n * Argon2 parameters for S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.\n * Default settings correspond to the second recommendation from RFC9106 (\"uniformly safe option\"),\n * to ensure compatibility with memory-constrained environments.\n * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.\n * @memberof module:config\n * @property {Object} params\n * @property {Integer} params.passes - number of iterations t\n * @property {Integer} params.parallelism - degree of parallelism p\n * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.\n */\n s2kArgon2Params: {\n passes: 3,\n parallelism: 4, // lanes\n memoryExponent: 16 // 64 MiB of RAM\n },\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:\n * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL\n * (see https://efail.de/).\n * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.\n *\n * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n /**\n * Allow using keys that do not have any key flags set.\n * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages\n * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).\n * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.\n * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.\n */\n allowMissingKeyFlags: false,\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).\n * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur\n * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of\n * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.\n * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.\n */\n nonDeterministicSignaturesViaNotation: true,\n /**\n * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * @memberof module:config\n * @property {Boolean} useEllipticFallback\n */\n useEllipticFallback: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { createRequire } from 'module'; // Must be stripped in browser built\nimport enums from './enums';\nimport defaultConfig from './config';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n nodeRequire: createRequire(import.meta.url),\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n /**\n * Load noble-curves lib on demand and return the requested curve function\n * @param {enums.publicKey} publicKeyAlgo\n * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)\n * @returns curve implementation\n * @throws on unrecognized curve, or curve not implemented by noble-curve\n */\n getNobleCurve: async (publicKeyAlgo, curveName) => {\n if (!defaultConfig.useEllipticFallback) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n\n const { nobleCurves } = await import('./crypto/public_key/elliptic/noble_curves');\n switch (publicKeyAlgo) {\n case enums.publicKey.ecdh:\n case enums.publicKey.ecdsa: {\n const curve = nobleCurves.get(curveName);\n if (!curve) throw new Error('Unsupported curve');\n return curve;\n }\n case enums.publicKey.x448:\n return nobleCurves.get('x448');\n case enums.publicKey.ed448:\n return nobleCurves.get('ed448');\n default:\n throw new Error('Unsupported curve');\n }\n },\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,\n // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed\n // has not been authenticated (yet).\n // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.\n // Also, AEAD is also not affected.\n return util.readExactSubarray(bytes, 2, 2 + bytelen);\n },\n\n /**\n * Read exactly `end - start` bytes from input.\n * This is a stricter version of `.subarray`.\n * @param {Uint8Array} input - Input data to parse\n * @returns {Uint8Array} subarray of size always equal to `end - start`\n * @throws if the input array is too short.\n */\n readExactSubarray: function (input, start, end) {\n if (input.length < (end - start)) {\n throw new Error('Input array too short');\n }\n return input.subarray(start, end);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n if (bytes.length > length) {\n throw new Error('Input array too long');\n }\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const hexAlphabet = '0123456789abcdef';\n let s = '';\n bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });\n return s;\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography API.\n * @returns {Object} The SubtleCrypto API\n * @throws if the API is not available\n */\n getWebCrypto: function() {\n const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n // Fallback for Node 16, which does not expose WebCrypto as a global\n const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;\n if (!webCrypto) {\n throw new Error('The WebCrypto API is not available');\n }\n return webCrypto;\n },\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return this.nodeRequire('crypto');\n },\n\n getNodeZlib: function() {\n return this.nodeRequire('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (this.nodeRequire('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = this.nodeRequire('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n /**\n * Test email format to ensure basic compliance:\n * - must include a single @\n * - no control or space unicode chars allowed\n * - no backslash and square brackets (as the latter can mess with the userID parsing)\n * - cannot end with a punctuation char\n * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,\n * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).\n */\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^[^\\p{C}\\p{Z}@<>\\\\]+@[^\\p{C}\\p{Z}@<>\\\\]+[^\\p{C}\\p{Z}\\p{P}]$/u;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n }\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n }\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n }\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n }\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n }\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n }\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Remove the (optional) checksum from an armored message.\n * @param {String} text - OpenPGP armored message\n * @returns {String} The body of the armored message.\n * @private\n */\nfunction removeChecksum(text) {\n let body = text;\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n }\n\n return body;\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n const data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== enums.armor.signed) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === enums.armor.signed) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const body = removeChecksum(parts[0].slice(0, -1));\n await writer.write(body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum\n * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug\n // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)\n const maybeBodyClone = emitChecksum && stream.passiveClone(body);\n\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push(hash ? `Hash: ${hash}\\n\\n` : '\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","import enums from '../../enums';\n\nexport async function getLegacyCipher(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n throw new Error('Not a legacy cipher');\n case enums.symmetric.cast5:\n case enums.symmetric.blowfish:\n case enums.symmetric.twofish:\n case enums.symmetric.tripledes: {\n const { legacyCiphers } = await import('./legacy_ciphers');\n const cipher = legacyCiphers.get(algo);\n if (!cipher) {\n throw new Error('Unsupported cipher algorithm');\n }\n return cipher;\n }\n default:\n throw new Error('Unsupported cipher algorithm');\n }\n}\n\n/**\n * Get block size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherBlockSize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 16;\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n case enums.symmetric.tripledes:\n return 8;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherKeySize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n return 16;\n case enums.symmetric.aes192:\n case enums.symmetric.tripledes:\n return 24;\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 32;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get block and key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nexport function getCipherParams(algo) {\n return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };\n}\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction nobleHash(nobleHashName, webCryptoHashName) {\n const getNobleHash = async () => {\n const { nobleHashes } = await import('./noble_hashes');\n const hash = nobleHashes.get(nobleHashName);\n if (!hash) throw new Error('Unsupported hash');\n return hash;\n };\n\n return async function(data) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hash = await getNobleHash();\n\n const hashInstance = hash.create();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => hashInstance.digest());\n } else if (webCrypto && webCryptoHashName) {\n return new Uint8Array(await webCrypto.digest(webCryptoHashName, data));\n } else {\n const hash = await getNobleHash();\n\n return hash(data);\n }\n };\n}\n\nexport default {\n\n /** @see module:md5 */\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'),\n sha224: nodeHash('sha224') || nobleHash('sha224'),\n sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'),\n sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'),\n sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'),\n ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'),\n sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'),\n sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'),\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n case enums.hash.sha3_256:\n return this.sha3_256(data);\n case enums.hash.sha3_512:\n return this.sha3_512(data);\n default:\n throw new Error('Unsupported hash function');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n case enums.hash.sha3_256:\n return 32;\n case enums.hash.sha3_512:\n return 64;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, copyBytes, createView, toBytes, u32 } from './utils.js';\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\nclass GHASH {\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n this.blockLen = BLOCK_SIZE;\n this.outputLen = BLOCK_SIZE;\n this.s0 = 0;\n this.s1 = 0;\n this.s2 = 0;\n this.s3 = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\nclass Polyval extends GHASH {\n constructor(key, expectedLength) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\nfunction wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key, expectedLength) => hashCons(key, expectedLength);\n return hashC;\n}\nexport const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));\nexport const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));\n//# sourceMappingURL=_polyval.js.map","// prettier-ignore\nimport { bytes as abytes } from './_assert.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { clean, concatBytes, copyBytes, createView, equalBytes, isAligned32, setBigUint64, u32, u8, wrapCipher, } from './utils.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (dst === undefined)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n if (!isAligned32(dst))\n throw new Error('unaligned dst');\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n const out = getDst(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD == null ? 0 : AAD.length;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(aadLength * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(key);\n abytes(nonce);\n if (AAD !== undefined)\n abytes(AAD);\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\n// Private, unsafe low-level methods. Can change at any time.\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n */\n\nimport { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../../util';\nimport enums from '../../enums';\nimport { getLegacyCipher, getCipherParams } from '../cipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (nodeCrypto && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nclass WebCryptoEncryptor {\n constructor(algo, key, iv) {\n const { blockSize } = getCipherParams(algo);\n this.key = key;\n this.prevBlock = iv;\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n this.zeroBlock = new Uint8Array(this.blockSize);\n }\n\n static async isSupported(algo) {\n const { keySize } = getCipherParams(algo);\n return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])\n .then(() => true, () => false);\n }\n\n async _runCBC(plaintext, nonZeroIV) {\n const mode = 'AES-CBC';\n this.keyRef = this.keyRef || await webCrypto.importKey('raw', this.key, mode, false, ['encrypt']);\n const ciphertext = await webCrypto.encrypt(\n { name: mode, iv: nonZeroIV || this.zeroBlock },\n this.keyRef,\n plaintext\n );\n return new Uint8Array(ciphertext).subarray(0, plaintext.length);\n }\n\n async encryptChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const plaintext = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n const toEncrypt = util.concatUint8Array([\n this.prevBlock,\n plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block \"early\", since we only need to xor the plaintext and pass it over as prevBlock\n ]);\n\n const encryptedBlocks = await this._runCBC(toEncrypt);\n xorMut(encryptedBlocks, plaintext);\n this.prevBlock = encryptedBlocks.slice(-this.blockSize);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return encryptedBlocks;\n }\n\n this.i += added.length;\n let encryptedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n const curBlock = this.nextBlock;\n encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n this.prevBlock = encryptedBlock.slice();\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n encryptedBlock = new Uint8Array();\n }\n\n return encryptedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n this.nextBlock = this.nextBlock.subarray(0, this.i);\n const curBlock = this.nextBlock;\n const encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n result = encryptedBlock.subarray(0, curBlock.length);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.keyRef = null;\n this.key = null;\n }\n\n async encrypt(plaintext) {\n // plaintext is internally padded to block length before encryption\n const encryptedWithPadding = await this._runCBC(\n util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]),\n this.iv\n );\n // drop encrypted padding\n const ct = encryptedWithPadding.subarray(0, plaintext.length);\n xorMut(ct, plaintext);\n this.clearSensitiveData();\n return ct;\n }\n}\n\nclass NobleStreamProcessor {\n constructor(forEncryption, algo, key, iv) {\n this.forEncryption = forEncryption;\n const { blockSize } = getCipherParams(algo);\n this.key = nobleAesHelpers.expandKeyLE(key);\n\n if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers\n this.prevBlock = getUint32Array(iv);\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n }\n\n _runCFB(src) {\n const src32 = getUint32Array(src);\n const dst = new Uint8Array(src.length);\n const dst32 = getUint32Array(dst);\n for (let i = 0; i + 4 <= dst32.length; i += 4) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);\n }\n return dst;\n }\n\n async processChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const toProcess = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n\n const processedBlocks = this._runCFB(toProcess);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return processedBlocks;\n }\n\n this.i += added.length;\n\n let processedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n processedBlock = this._runCFB(this.nextBlock);\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n processedBlock = new Uint8Array();\n }\n\n return processedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n const processedBlock = this._runCFB(this.nextBlock);\n\n result = processedBlock.subarray(0, this.i);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.key.fill(0);\n }\n}\n\n\nasync function aesEncrypt(algo, key, pt, iv) {\n if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys\n const cfb = new WebCryptoEncryptor(algo, key, iv);\n return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);\n } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream\n const cfb = new NobleStreamProcessor(true, algo, key, iv);\n return stream.transform(pt, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).encrypt(pt);\n}\n\nasync function aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new NobleStreamProcessor(false, algo, key, iv);\n return stream.transform(ct, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).decrypt(ct);\n}\n\nfunction xorMut(a, b) {\n const aLength = Math.min(a.length, b.length);\n for (let i = 0; i < aLength; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nconst getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt) {\n return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n */\n\nimport { ctr as nobleAesCtr } from '@noble/ciphers/aes';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const keyRef = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, keyRef, pt);\n return new Uint8Array(ct);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt, iv) {\n return nobleAesCtr(key, iv).encrypt(pt);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport { getCipherParams } from '../cipher';\nimport util from '../../util';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n const { keySize } = getCipherParams(cipher);\n // sanity checks\n if (!util.isAES(cipher) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let maxNtz = 0;\n\n // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,\n // hence its execution cannot be broken up.\n // As a result, WebCrypto cannot currently be used for `encipher`.\n const aes = nobleAesCbc(key, zeroBlock, { disablePadding: true });\n const encipher = block => aes.encrypt(block);\n const decipher = block => aes.decrypt(block);\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables() {\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n */\n\nimport { gcm as nobleAesGcm } from '@noble/ciphers/aes';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages\n const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\\/13\\.\\d(\\.\\d)* Safari/) ||\n navigator.userAgent.match(/Version\\/(13|14)\\.\\d(\\.\\d)* Mobile\\/\\S* Safari/);\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && !pt.length) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n try {\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n } catch (e) {\n if (e.name === 'OperationError') {\n throw new Error('Authentication tag mismatch');\n }\n }\n }\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n },\n\n decrypt: async function(ct, iv, adata) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","// Operations are not constant time, but we try and limit timing leakage where we can\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport function uint8ArrayToBigInt(bytes: Uint8Array) {\n const hexAlphabet = '0123456789ABCDEF';\n let s = '';\n bytes.forEach(v => {\n s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];\n });\n return BigInt('0x0' + s);\n}\n\nexport function mod(a: bigint, m: bigint) {\n const reduced = a % m;\n return reduced < _0n ? reduced + m : reduced;\n}\n\n/**\n * Compute modular exponentiation using square and multiply\n * @param {BigInt} a - Base\n * @param {BigInt} e - Exponent\n * @param {BigInt} n - Modulo\n * @returns {BigInt} b ** e mod n.\n */\nexport function modExp(b: bigint, e: bigint, n: bigint) {\n if (n === _0n) throw Error('Modulo cannot be zero');\n if (n === _1n) return BigInt(0);\n if (e < _0n) throw Error('Unsopported negative exponent');\n\n let exp = e;\n let x = b;\n\n x %= n;\n let r = BigInt(1);\n while (exp > _0n) {\n const lsb = exp & _1n;\n exp >>= _1n; // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n; // Square\n }\n return r;\n}\n\n\nfunction abs(x: bigint) {\n return x >= _0n ? x : -x;\n}\n\n/**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a and b, compute (x, y) such that ax + by = gdc(a, b).\n * Negative numbers are also supported.\n * @param {BigInt} a - First operand\n * @param {BigInt} b - Second operand\n * @returns {{ gcd, x, y: bigint }}\n */\nfunction _egcd(aInput: bigint, bInput: bigint) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n // Deal with negative numbers: run algo over absolute values,\n // and \"move\" the sign to the returned x and/or y.\n // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers\n let a = abs(aInput);\n let b = abs(bInput);\n const aNegated = aInput < _0n;\n const bNegated = bInput < _0n;\n\n while (b !== _0n) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: aNegated ? -xPrev : xPrev,\n y: bNegated ? -yPrev : yPrev,\n gcd: a\n };\n}\n\n/**\n * Compute the inverse of `a` modulo `n`\n * Note: `a` and and `n` must be relatively prime\n * @param {BigInt} a\n * @param {BigInt} n - Modulo\n * @returns {BigInt} x such that a*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\nexport function modInv(a: bigint, n: bigint) {\n const { gcd, x } = _egcd(a, n);\n if (gcd !== _1n) {\n throw new Error('Inverse does not exist');\n }\n return mod(x + n, n);\n}\n\n/**\n * Compute greatest common divisor between this and n\n * @param {BigInt} aInput - Operand\n * @param {BigInt} bInput - Operand\n * @returns {BigInt} gcd\n */\nexport function gcd(aInput: bigint, bInput: bigint) {\n let a = aInput;\n let b = bInput;\n while (b !== _0n) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\n/**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\nexport function bigIntToNumber(x: bigint) {\n const number = Number(x);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n}\n\n/**\n * Get value of i-th bit\n * @param {BigInt} x\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\nexport function getBit(x:bigint, i: number) {\n const bit = (x >> BigInt(i)) & _1n;\n return bit === _0n ? 0 : 1;\n}\n\n/**\n * Compute bit length\n */\nexport function bitLength(x: bigint) {\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = x < _0n ? BigInt(-1) : _0n;\n let bitlen = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _1n) !== target) {\n bitlen++;\n }\n return bitlen;\n}\n\n/**\n * Compute byte length\n */\nexport function byteLength(x: bigint) {\n const target = x < _0n ? BigInt(-1) : _0n;\n const _8n = BigInt(8);\n let len = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _8n) !== target) {\n len++;\n }\n return len;\n}\n\n/**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\nexport function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = x.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? length - rawLength : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n */\nimport { byteLength, mod, uint8ArrayToBigInt } from './biginteger';\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto?.webcrypto;\n if (webcrypto?.getRandomValues) {\n const buf = new Uint8Array(length);\n return webcrypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n}\n\n/**\n * Create a secure random BigInt that is greater than or equal to min and less than max.\n * @param {bigint} min - Lower bound, included\n * @param {bigint} max - Upper bound, excluded\n * @returns {bigint} Random BigInt.\n * @async\n */\nexport function getRandomBigInteger(min, max) {\n if (max < min) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max - min;\n const bytes = byteLength(modulus);\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));\n return mod(r, modulus) + min;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n */\nimport { bigIntToNumber, bitLength, gcd, getBit, mod, modExp } from '../biginteger';\nimport { getRandomBigInteger } from '../random';\n\nconst _1n = BigInt(1);\n\n/**\n * Generate a probably prime random number\n * @param bits - Bit length of the prime\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function randomProbablePrime(bits: number, e: bigint, k: number) {\n const _30n = BigInt(30);\n const min = _1n << BigInt(bits - 1);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n let n = getRandomBigInteger(min, min << _1n);\n let i = bigIntToNumber(mod(n, _30n));\n\n do {\n n += BigInt(adds[i]);\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (bitLength(n) > bits) {\n n = mod(n, min << _1n); n += min;\n i = bigIntToNumber(mod(n, _30n));\n }\n } while (!isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param n - Number to test\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function isProbablePrime(n: bigint, e: bigint, k: number) {\n if (e && gcd(n - _1n, e) !== _1n) {\n return false;\n }\n if (!divisionTest(n)) {\n return false;\n }\n if (!fermat(n)) {\n return false;\n }\n if (!millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param n - Number to test\n * @param b - Optional Fermat test base\n */\nexport function fermat(n: bigint, b = BigInt(2)) {\n return modExp(b, n - _1n, n) === _1n;\n}\n\nexport function divisionTest(n: bigint) {\n const _0n = BigInt(0);\n return smallPrimes.every(m => mod(n, m) !== _0n);\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n].map(n => BigInt(n));\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param n - Number to test\n * @param k - Optional number of iterations of Miller-Rabin test\n * @param rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport function millerRabin(n: bigint, k: number, rand?: () => bigint) {\n const len = bitLength(n);\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n - _1n; // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!getBit(n1, s)) { s++; }\n const d = n >> BigInt(s);\n\n for (; k > 0; k--) {\n const a = rand ? rand() : getRandomBigInteger(BigInt(2), n1);\n\n let x = modExp(a, d, n);\n if (x === _1n || x === n1) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = mod(x * x, n);\n\n if (x === _1n) {\n return false;\n }\n if (x === n1) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n */\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\nimport { bigIntToNumber, bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\nimport hash from '../hash';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst _1n = BigInt(1);\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (hash.getHashByteLength(hashAlgo) >= n.length) {\n // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error\n // e.g. if a 512-bit RSA key is used with a SHA-512 digest.\n // The size limit is actually slightly different but here we only care about throwing\n // on common key sizes.\n throw new Error('Digest size cannot exceed key modulus size');\n }\n\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n e = BigInt(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return jwkToPrivate(jwk, e);\n } else if (util.getNodeCrypto()) {\n const opts = {\n modulusLength: bits,\n publicExponent: bigIntToNumber(e),\n publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },\n privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }\n };\n const jwk = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {\n if (err) {\n reject(err);\n } else {\n resolve(jwkPrivateKey);\n }\n });\n });\n return jwkToPrivate(jwk, e);\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = randomProbablePrime(bits - (bits >> 1), e, 40);\n p = randomProbablePrime(bits >> 1, e, 40);\n n = p * q;\n } while (bitLength(n) !== bits);\n\n const phi = (p - _1n) * (q - _1n);\n\n if (q < p) {\n [p, q] = [q, p];\n }\n\n return {\n n: bigIntToUint8Array(n),\n e: bigIntToUint8Array(e),\n d: bigIntToUint8Array(modInv(e, phi)),\n p: bigIntToUint8Array(p),\n q: bigIntToUint8Array(q),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: bigIntToUint8Array(modInv(p, q))\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n n = uint8ArrayToBigInt(n);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n\n // expect pq = n\n if ((p * q) !== n) {\n return false;\n }\n\n const _2n = BigInt(2);\n // expect p*u = 1 mod q\n u = uint8ArrayToBigInt(u);\n if (mod(p * u, q) !== BigInt(1)) {\n return false;\n }\n\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));\n const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r * d * e;\n\n const areInverses = mod(rde, p - _1n) === r && mod(rde, q - _1n) === r;\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n n = uint8ArrayToBigInt(n);\n const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));\n d = uint8ArrayToBigInt(d);\n return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n\n const jwk = await privateToJWK(n, e, d, p, q, u);\n return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n n = uint8ArrayToBigInt(n);\n s = uint8ArrayToBigInt(s);\n e = uint8ArrayToBigInt(e);\n if (s >= n) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));\n const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1' };\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n\n try {\n return verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n n = uint8ArrayToBigInt(n);\n data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));\n e = uint8ArrayToBigInt(e);\n if (data >= n) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n data = uint8ArrayToBigInt(data);\n n = uint8ArrayToBigInt(n);\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n u = uint8ArrayToBigInt(u);\n if (data >= n) {\n throw new Error('Data too large.');\n }\n const dq = mod(d, q - _1n); // d mod (q-1)\n const dp = mod(d, p - _1n); // d mod (p-1)\n\n const unblinder = getRandomBigInteger(BigInt(2), n);\n const blinder = modExp(modInv(unblinder, n), e, n);\n data = mod(data * blinder, n);\n\n const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p\n const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q\n const h = mod(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h * p + mp; // result < n due to relations above\n\n result = mod(result * unblinder, n);\n\n return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const pNum = uint8ArrayToBigInt(p);\n const qNum = uint8ArrayToBigInt(q);\n const dNum = uint8ArrayToBigInt(d);\n\n let dq = mod(dNum, qNum - _1n); // d mod (q-1)\n let dp = mod(dNum, pNum - _1n); // d mod (p-1)\n dp = bigIntToUint8Array(dp);\n dq = bigIntToUint8Array(dq);\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n\n/** Convert JWK private key to OpenPGP private key params */\nfunction jwkToPrivate(jwk, e) {\n return {\n n: b64ToUint8Array(jwk.n),\n e: bigIntToUint8Array(e),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n */\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\nconst _1n = BigInt(1);\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n const padded = emeEncode(data, byteLength(p));\n const m = uint8ArrayToBigInt(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = getRandomBigInteger(_1n, p - _1n);\n return {\n c1: bigIntToUint8Array(modExp(g, k, p)),\n c2: bigIntToUint8Array(mod(modExp(y, k, p) * m, p))\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n c1 = uint8ArrayToBigInt(c1);\n c2 = uint8ArrayToBigInt(c2);\n p = uint8ArrayToBigInt(p);\n x = uint8ArrayToBigInt(x);\n\n const padded = mod(modInv(modExp(c1, x, p), p) * c2, p);\n return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = BigInt(bitLength(p));\n const _1023n = BigInt(1023);\n if (pSize < _1023n) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (modExp(g, p - _1n, p) !== _1n) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n let i = BigInt(1);\n const _2n = BigInt(2);\n const threshold = _2n << BigInt(17); // we want order > threshold\n while (i < threshold) {\n res = mod(res * g, p);\n if (res === _1n) {\n return false;\n }\n i++;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const r = getRandomBigInteger(_2n << (pSize - _1n), _2n << pSize); // draw r of same size as p-1\n const rqx = (p - _1n) * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","// declare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import { crypto } from './crypto.js';\n\n'use strict';\nconst nacl = {};\nexport default nacl;\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n if (crypto && crypto.getRandomValues) {\n // Browsers and Node v16+\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n})();\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nconst knownOIDs = {\n '2a8648ce3d030107': enums.curve.nistP256,\n '2b81040022': enums.curve.nistP384,\n '2b81040023': enums.curve.nistP521,\n '2b8104000a': enums.curve.secp256k1,\n '2b06010401da470f01': enums.curve.ed25519Legacy,\n '2b060104019755010501': enums.curve.curve25519Legacy,\n '2b2403030208010107': enums.curve.brainpoolP256r1,\n '2b240303020801010b': enums.curve.brainpoolP384r1,\n '2b240303020801010d': enums.curve.brainpoolP512r1\n};\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {enums.curve} String with the canonical name of the curve\n * @throws if unknown\n */\n getName() {\n const name = knownOIDs[this.toHex()];\n if (!name) {\n throw new Error('Unknown curve object identifier.');\n }\n\n return name;\n }\n}\n\nexport default OID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\n// unknown packet types are handled differently depending on the packet criticality\nexport class UnknownPacketError extends UnsupportedError {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnknownPacketError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n */\n\nimport ed25519 from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\nimport { b64ToUint8Array, uint8ArrayToB64 } from '../../../encoding/base64';\n\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n A: new Uint8Array(b64ToUint8Array(publicKey.x)),\n seed: b64ToUint8Array(privateKey.d, true)\n };\n } catch (err) {\n if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux\n throw err;\n }\n const seed = getRandomBytes(getPayloadSize(algo));\n const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const seed = ed448.utils.randomPrivateKey();\n const A = ed448.getPublicKey(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = privateKeyToJWK(algo, publicKey, privateKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);\n\n const signature = new Uint8Array(\n await webCrypto.sign('Ed25519', key, hashed)\n );\n\n return { RS: signature };\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = ed25519.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const signature = ed448.sign(hashed, privateKey);\n return { RS: signature };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = publicKeyToJWK(algo, publicKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);\n const verified = await webCrypto.verify('Ed25519', key, RS, hashed);\n return verified;\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n return ed25519.sign.detached.verify(hashed, RS, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n return ed448.verify(RS, hashed, publicKey);\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented\n */\n const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n\n const publicKey = ed448.getPublicKey(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n default:\n return false;\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return 32;\n\n case enums.publicKey.ed448:\n return 57;\n\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n case enums.publicKey.ed448:\n return enums.hash.sha512;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n\nconst publicKeyToJWK = (algo, publicKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = {\n kty: 'OKP',\n crv: 'Ed25519',\n x: uint8ArrayToB64(publicKey, true),\n ext: true\n };\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n\nconst privateKeyToJWK = (algo, publicKey, privateKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = publicKeyToJWK(algo, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n */\n\nimport { aeskw as nobleAesKW } from '@noble/ciphers/aes';\nimport { getCipherParams } from './cipher';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n/**\n * AES key wrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} dataToWrap\n * @returns {Uint8Array} wrapped key\n */\nexport async function wrap(algo, key, dataToWrap) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n try {\n const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);\n // Import data as HMAC key, as it has no key length requirements\n const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });\n return new Uint8Array(wrapped);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n\n return nobleAesKW(key).encrypt(dataToWrap);\n}\n\n/**\n * AES key unwrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} wrappedData\n * @returns {Uint8Array} unwrapped data\n */\nexport async function unwrap(algo, key, wrappedData) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let wrappingKey;\n try {\n wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n return nobleAesKW(key).decrypt(wrappedData);\n }\n\n try {\n const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));\n } catch (err) {\n if (err.name === 'OperationError') {\n throw new Error('Key Data Integrity failed');\n }\n throw err;\n }\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n\nexport default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport x25519 from '@openpgp/tweetnacl';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport computeHKDF from '../../hkdf';\nimport { getCipherParams } from '../../cipher';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519'),\n x448: util.encodeUTF8('OpenPGP X448')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = x25519.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const k = x448.utils.randomPrivateKey();\n const A = x448.getPublicKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = x25519.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const publicKey = x448.getPublicKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.x25519:\n return 32;\n\n case enums.publicKey.x448:\n return 56;\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Generate shared secret and ephemeral public key for encryption\n * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret\n * @async\n */\nexport async function generateEphemeralEncryptionMaterial(algo, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo));\n const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const { publicKey: ephemeralPublicKey } = x25519.box.keyPair.fromSecretKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const ephemeralSecretKey = x448.utils.randomPrivateKey();\n const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * x25519 and x448 produce an all-zero value when given as input a point with small order.\n * This does not lead to a security issue in the context of ECDH, but it is still unexpected,\n * hence we throw.\n * @param {Uint8Array} sharedSecret\n */\nfunction assertNonZeroArray(sharedSecret) {\n let acc = 0;\n for (let i = 0; i < sharedSecret.length; i++) {\n acc |= sharedSecret[i];\n }\n if (acc === 0) {\n throw new Error('Unexpected low order point');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n */\nimport nacl from '@openpgp/tweetnacl';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { UnsupportedError } from '../../../packet/packet';\nimport { generate as eddsaGenerate } from './eddsa';\nimport { generate as ecdhXGenerate } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n [enums.curve.nistP256]: 'P-256',\n [enums.curve.nistP384]: 'P-384',\n [enums.curve.nistP521]: 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,\n [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n [enums.curve.nistP256]: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.nistP256],\n web: webCurves[enums.curve.nistP256],\n payloadSize: 32,\n sharedSize: 256,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP384]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.nistP384],\n web: webCurves[enums.curve.nistP384],\n payloadSize: 48,\n sharedSize: 384,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP521]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.nistP521],\n web: webCurves[enums.curve.nistP521],\n payloadSize: 66,\n sharedSize: 528,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.secp256k1]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.secp256k1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.ed25519Legacy]: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.curve25519Legacy]: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.brainpoolP256r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.brainpoolP256r1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP384r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.brainpoolP384r1],\n payloadSize: 48,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP512r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.brainpoolP512r1],\n payloadSize: 64,\n wireFormatLeadingByte: 0x04\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName) {\n try {\n this.name = oidOrName instanceof OID ?\n oidOrName.getName() :\n enums.write(enums.curve,oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n const params = curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node;\n this.web = params.web;\n this.payloadSize = params.payloadSize;\n this.sharedSize = params.sharedSize;\n this.wireFormatLeadingByte = params.wireFormatLeadingByte;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === enums.curve.curve25519Legacy) {\n this.type = 'curve25519Legacy';\n } else if (this.name === enums.curve.ed25519Legacy) {\n this.type = 'ed25519Legacy';\n }\n }\n\n async genKeyPair() {\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name, this.wireFormatLeadingByte);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n return jsGenKeyPair(this.name);\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519Legacy': {\n // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3\n const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);\n const privateKey = k.slice().reverse();\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n case 'ed25519Legacy': {\n const { seed: privateKey, A } = await eddsaGenerate(enums.publicKey.ed25519);\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n default:\n return jsGenKeyPair(this.name);\n }\n }\n}\n\nasync function generate(curveName) {\n const curve = new CurveWithOID(curveName);\n const { oid, hash, cipher } = curve;\n const keyPair = await curve.genKeyPair();\n return {\n oid,\n Q: keyPair.publicKey,\n secret: util.leftPad(keyPair.privateKey, curve.payloadSize),\n hash,\n cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[oid.getName()].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n [enums.curve.nistP256]: true,\n [enums.curve.nistP384]: true,\n [enums.curve.nistP521]: true,\n [enums.curve.secp256k1]: true,\n [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,\n [enums.curve.brainpoolP256r1]: true,\n [enums.curve.brainpoolP384r1]: true,\n [enums.curve.brainpoolP512r1]: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === enums.curve.curve25519Legacy) {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n /*\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = nobleCurve.getPublicKey(d, false);\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check whether the public point has a valid encoding.\n * NB: this function does not check e.g. whether the point belongs to the curve.\n */\nfunction checkPublicPointEnconding(curve, V) {\n const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;\n\n const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;\n\n if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {\n throw new Error('Invalid point encoding');\n }\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\nasync function jsGenKeyPair(name) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n const privateKey = nobleCurve.utils.randomPrivateKey();\n const publicKey = nobleCurve.getPublicKey(privateKey, false);\n return { publicKey, privateKey };\n}\n\nasync function webGenKeyPair(name, wireFormatLeadingByte) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk, wireFormatLeadingByte) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = wireFormatLeadingByte;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams, nodeCurves, checkPublicPointEnconding } from './oid_curves';\nimport { bigIntToUint8Array } from '../../biginteger';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web':\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n case 'node':\n return nodeSign(curve, hashAlgo, message, privateKey);\n }\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });\n return {\n r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),\n s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)\n };\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n // See https://github.com/openpgpjs/openpgpjs/pull/948.\n // NB: the impact was more likely limited to Brainpool curves, since thanks\n // to WebCrypto availability, NIST curve should not have been affected.\n // Similarly, secp256k1 should have been used rarely enough.\n // However, we implement the fix for all curves, since it's only needed in case of\n // verification failure, which is unexpected, hence a minor slowdown is acceptable.\n const tryFallbackVerificationForOldBug = async () => (\n hashed[0] === 0 ?\n jsVerify(curve, signature, hashed.subarray(1), publicKey) :\n false\n );\n\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node': {\n const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n }\n }\n }\n\n const verified = await jsVerify(curve, signature, hashed, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n // eslint-disable-next-line @typescript-eslint/return-await\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Fallback javascript implementation of ECDSA verification.\n * To be used if no native implementation is available for the given curve/operation.\n */\nasync function jsVerify(curve, signature, hashed, publicKey) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, privateKey) {\n // JWT encoding cannot be used for now, as Brainpool curves are not supported\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n privateKey: nodeBuffer.from(privateKey)\n });\n\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n\n const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));\n const len = curve.payloadSize;\n\n return {\n r: signature.subarray(0, len),\n s: signature.subarray(len, len << 1)\n };\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { publicKey: derPublicKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n publicKey: nodeBuffer.from(publicKey)\n });\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n\n const signature = util.concatUint8Array([r, s]);\n\n try {\n return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);\n } catch (err) {\n return false;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n */\n\nimport nacl from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { CurveWithOID, checkPublicPointEnconding } from './oid_curves';\nimport { sign as eddsaSign, verify as eddsaVerify } from './eddsa';\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const { RS: signature } = await eddsaSign(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const RS = util.concatUint8Array([r, s]);\n return eddsaVerify(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { getCipherParams } from '../../cipher';\nimport { generateEphemeralEncryptionMaterial as ecdhXGenerateEphemeralEncryptionMaterial, recomputeSharedSecret as ecdhXRecomputeSharedSecret } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519Legacy': {\n const { sharedSecret: sharedKey, ephemeralPublicKey } = await ecdhXGenerateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));\n const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n return jsPublicEphemeralKey(curve, Q);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n default:\n return jsPublicEphemeralKey(curve, Q);\n\n }\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = await aesKW.wrap(kdfParams.cipher, Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519Legacy': {\n const secretKey = d.slice().reverse();\n const sharedKey = await ecdhXRecomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n return jsPrivateEphemeralKey(curve, V, d);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n default:\n return jsPrivateEphemeralKey(curve, V, d);\n }\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n checkPublicPointEnconding(curve, V);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(await aesKW.unwrap(kdfParams.cipher, Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\nasync function jsPrivateEphemeralKey(curve, V, d) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { secretKey: d, sharedKey };\n}\n\nasync function jsPublicEphemeralKey(curve, Q) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n const { publicKey: V, privateKey: v } = await curve.genKeyPair();\n\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { publicKey: V, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: sender\n },\n privateKey,\n curve.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const _0n = BigInt(0);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n x = uint8ArrayToBigInt(x);\n\n let k;\n let r;\n let s;\n let t;\n g = mod(g, p);\n x = mod(x, q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = getRandomBigInteger(_1n, q); // returns in [1, q-1]\n r = mod(modExp(g, k, p), q); // (g**k mod p) mod q\n if (r === _0n) {\n continue;\n }\n const xr = mod(x * r, q);\n t = mod(h + xr, q); // H(m) + x*r mod q\n s = mod(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q\n if (s === _0n) {\n continue;\n }\n break;\n }\n return {\n r: bigIntToUint8Array(r, 'be', byteLength(p)),\n s: bigIntToUint8Array(s, 'be', byteLength(p))\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n r = uint8ArrayToBigInt(r);\n s = uint8ArrayToBigInt(s);\n\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n if (r <= _0n || r >= q ||\n s <= _0n || s >= q) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n const w = modInv(s, q); // s**-1 mod q\n if (w === _0n) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = mod(g, p);\n y = mod(y, p);\n const u1 = mod(h * w, q); // H(m) * w mod q\n const u2 = mod(r * w, q); // r * w mod q\n const t1 = modExp(g, u1, p); // g**u1 mod p\n const t2 = modExp(y, u2, p); // y**u2 mod p\n const v = mod(mod(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q\n return v === r;\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (mod(p - _1n, q) !== _0n) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (modExp(g, q, p) !== _1n) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = BigInt(bitLength(q));\n const _150n = BigInt(150);\n if (qSize < _150n || !isProbablePrime(q, null, 32)) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const _2n = BigInt(2);\n const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q\n const rqx = q * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n */\n\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { read, signatureParams: { s } };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n // If the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature\n // verification: if the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n // Algorithm-Specific Fields for Ed448 signatures:\n // - 114 octets of the native signature\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo);\n const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length;\n return { read, signatureParams: { RS } };\n }\n\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal:\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport { getCipherParams } from './cipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n if (symmetricAlgo && !util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 and X448 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (C.algorithm !== null && !util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const payloadSize = getCurvePayloadSize(algo);\n const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const payloadSize = getCurvePayloadSize(algo);\n const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 or X448 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const pointSize = getCurvePayloadSize(algo);\n const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([\n enums.publicKey.ed25519,\n enums.publicKey.x25519,\n enums.publicKey.ed448,\n enums.publicKey.x448\n ]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipherParams(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipherParams(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get encoded secret size for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getCurvePayloadSize(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh:\n case enums.publicKey.eddsaLegacy:\n return new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPayloadSize(algo);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.getPayloadSize(algo);\n default:\n throw new Error('Unknown elliptic algo');\n }\n}\n\n/**\n * Get preferred signing hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n\n\nexport { getCipherParams };\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","import defaultConfig from '../../config';\nimport enums from '../../enums';\nimport util from '../../util';\nimport crypto from '../../crypto';\n\nconst ARGON2_TYPE = 0x02; // id\nconst ARGON2_VERSION = 0x13;\nconst ARGON2_SALT_SIZE = 16;\n\nexport class Argon2OutOfMemoryError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Argon2OutOfMemoryError);\n }\n\n this.name = 'Argon2OutOfMemoryError';\n }\n}\n\n// cache argon wasm module\nlet loadArgonWasmModule;\nlet argon2Promise;\n// reload wasm module above this treshold, to deallocated used memory\nconst ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;\n\nclass Argon2S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n const { passes, parallelism, memoryExponent } = config.s2kArgon2Params;\n\n this.type = 'argon2';\n /**\n * 16 bytes of salt\n * @type {Uint8Array}\n */\n this.salt = null;\n /**\n * number of passes\n * @type {Integer}\n */\n this.t = passes;\n /**\n * degree of parallelism (lanes)\n * @type {Integer}\n */\n this.p = parallelism;\n /**\n * exponent indicating memory size\n * @type {Integer}\n */\n this.encodedM = memoryExponent;\n }\n\n generateSalt() {\n this.salt = crypto.random.getRandomBytes(ARGON2_SALT_SIZE);\n }\n\n /**\n * Parsing function for argon2 string-to-key specifier.\n * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n\n this.salt = bytes.subarray(i, i + 16);\n i += 16;\n\n this.t = bytes[i++];\n this.p = bytes[i++];\n this.encodedM = bytes[i++]; // memory size exponent, one-octect\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n const arr = [\n new Uint8Array([enums.write(enums.s2k, this.type)]),\n this.salt,\n new Uint8Array([this.t, this.p, this.encodedM])\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to `keySize`\n * @throws {Argon2OutOfMemoryError|Errors}\n * @async\n */\n async produceKey(passphrase, keySize) {\n const decodedM = 2 << (this.encodedM - 1);\n\n try {\n // on first load, the argon2 lib is imported and the WASM module is initialized.\n // the two steps need to be atomic to avoid race conditions causing multiple wasm modules\n // being loaded when `argon2Promise` is not initialized.\n loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;\n argon2Promise = argon2Promise || loadArgonWasmModule();\n\n // important to keep local ref to argon2 in case the module is reloaded by another instance\n const argon2 = await argon2Promise;\n\n const passwordBytes = util.encodeUTF8(passphrase);\n const hash = argon2({\n version: ARGON2_VERSION,\n type: ARGON2_TYPE,\n password: passwordBytes,\n salt: this.salt,\n tagLength: keySize,\n memorySize: decodedM,\n parallelism: this.p,\n passes: this.t\n });\n\n // a lot of memory was used, reload to deallocate\n if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {\n // it will be awaited if needed at the next `produceKey` invocation\n argon2Promise = loadArgonWasmModule();\n argon2Promise.catch(() => {});\n }\n return hash;\n } catch (e) {\n if (e.message && (\n e.message.includes('Unable to grow instance memory') || // Chrome\n e.message.includes('failed to grow memory') || // Firefox\n e.message.includes('WebAssembly.Memory.grow') || // Safari\n e.message.includes('Out of memory') // Safari iOS\n )) {\n throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');\n } else {\n throw e;\n }\n }\n }\n}\n\nexport default Argon2S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n */\n\nimport defaultConfig from '../../config';\nimport crypto from '../../crypto';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\nimport util from '../../util';\n\nclass GenericS2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(s2kType, config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = enums.read(enums.s2k, s2kType);\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n generateSalt() {\n switch (this.type) {\n case 'salted':\n case 'iterated':\n this.salt = crypto.random.getRandomBytes(8);\n }\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default GenericS2K;\n","import defaultConfig from '../../config';\nimport Argon2S2K, { Argon2OutOfMemoryError } from './argon2';\nimport GenericS2K from './generic';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\n\nconst allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);\n\n/**\n * Instantiate a new S2K instance of the given type\n * @param {module:enums.s2k} type\n * @oaram {Object} [config]\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromType(type, config = defaultConfig) {\n switch (type) {\n case enums.s2k.argon2:\n return new Argon2S2K(config);\n case enums.s2k.iterated:\n case enums.s2k.gnu:\n case enums.s2k.salted:\n case enums.s2k.simple:\n return new GenericS2K(type, config);\n default:\n throw new UnsupportedError('Unsupported S2K type');\n }\n}\n\n/**\n * Instantiate a new S2K instance based on the config settings\n * @oaram {Object} config\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromConfig(config) {\n const { s2kType } = config;\n\n if (!allowedS2KTypesForEncryption.has(s2kType)) {\n throw new Error('The provided `config.s2kType` value is not allowed');\n }\n\n return newS2KFromType(s2kType, config);\n}\n\nexport { Argon2OutOfMemoryError };\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n ], { type: 'text/javascript' }))));\n w.onmessage = function (e) {\n var d = e.data, ed = d.$e$;\n if (ed) {\n var err = new Error(ed[0]);\n err['code'] = ed[1];\n err.stack = ed[2];\n cb(err, null);\n }\n else\n cb(null, d);\n };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n ,\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && st.f && !st.l))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[pos >> 3] = lst;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if (d[1] & 32)\n err(6, 'invalid zlib data: preset dictionaries not supported');\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n err(6, 'invalid gzip data');\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (val instanceof u8)\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n err(8);\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n err(8);\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this_1.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this_1.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_3 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// A salt notation is used to randomize signatures.\n// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks\n// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).\n// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.\n// some chosen-prefix attacks.\n// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.\nconst SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuerKeyID,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.unknownSubpackets = [];\n this.signedHashValue = null;\n this.salt = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n this.preferredCipherSuites = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes, config = defaultConfig) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n // Only for v6 signatures, a variable-length field containing:\n if (this.version === 6) {\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[i++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(i, i + saltLength);\n i += saltLength;\n }\n\n const signatureMaterial = bytes.subarray(i, bytes.length);\n const { read, signatureParams } = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);\n if (read < signatureMaterial.length) {\n throw new Error('Error reading MPIs');\n }\n this.params = signatureParams;\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n if (this.version === 6) {\n arr.push(new Uint8Array([this.salt.length]));\n arr.push(this.salt);\n }\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false, config) {\n this.version = key.version;\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n // add randomness to the signature\n if (this.version === 6) {\n const saltLength = saltLengthForHash(this.hashAlgorithm);\n if (this.salt === null) {\n this.salt = crypto.random.getRandomBytes(saltLength);\n } else if (saltLength !== this.salt.length) {\n throw new Error('Provided salt does not have the required length');\n }\n } else if (config.nonDeterministicSignaturesViaNotation) {\n const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));\n // since re-signing the same object is not supported, it's not expected to have multiple salt notations,\n // but we guard against it as a sanity check\n if (saltNotations.length === 0) {\n const saltValue = crypto.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm));\n this.rawNotations.push({\n name: SALT_NOTATION_NAME,\n value: saltValue,\n humanReadable: false,\n critical: false\n });\n } else {\n throw new Error('Unexpected existing salt notation');\n }\n }\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n if (this.preferredCipherSuites !== null) {\n bytes = new Uint8Array([].concat(...this.preferredCipherSuites));\n arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {\n return writeSubPacket(type, critical, body);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n // Signature subpackets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n mypos++;\n\n if (!hashed) {\n this.unhashedSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuerKeyID:\n // Issuer\n if (this.version === 4) {\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n } else if (hashed) {\n // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,\n // since the Issuer Fingerprint subpacket is to be used instead.\n // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.\n // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,\n // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)\n // issuerFingerprint.\n // If the packet is hashed, then we reject the signature, to avoid verifying data different from\n // what was parsed.\n throw new Error('Unexpected Issuer Key ID subpacket');\n }\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion >= 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCipherSuites:\n // Preferred AEAD Cipher Suites\n this.preferredCipherSuites = [];\n for (let i = mypos; i < bytes.length; i += 2) {\n this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);\n }\n break;\n default:\n this.unknownSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n break;\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n const subpacketLengthBytes = this.version === 6 ? 4 : 2;\n\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));\n\n let i = subpacketLengthBytes;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {\n // avoid hashing unexpected salt size\n throw new Error('Signature salt does not have the expected length');\n }\n\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.unknownSubpackets.forEach(({ type, critical }) => {\n if (critical) {\n throw new Error(`Unknown critical signature subpacket type ${type}`);\n }\n });\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n\n/**\n * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}\n * @param {enums.hash} hashAlgorithm - Hash algorithm.\n * @returns {Integer} Salt length.\n * @private\n */\nfunction saltLengthForHash(hashAlgorithm) {\n switch (hashAlgorithm) {\n case enums.hash.sha256: return 16;\n case enums.hash.sha384: return 24;\n case enums.hash.sha512: return 32;\n case enums.hash.sha224: return 16;\n case enums.hash.sha3_256: return 16;\n case enums.hash.sha3_512: return 32;\n default: throw new Error('Unsupported hash function');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n static fromSignaturePacket(signaturePacket, isLast) {\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.version = signaturePacket.version === 6 ? 6 : 3;\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n onePassSig.salt = signaturePacket.salt; // v6 only\n onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only\n\n onePassSig.flags = isLast ? 1 : 0;\n return onePassSig;\n }\n\n constructor() {\n /** A one-octet version number. The current versions are 3 and 6. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** Only for v6, a variable-length field containing the salt. */\n this.salt = null;\n /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */\n this.issuerFingerprint = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current versions are 3 or 6.\n this.version = bytes[mypos++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n if (this.version === 6) {\n // Only for v6 signatures, a variable-length field containing:\n\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[mypos++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(mypos, mypos + saltLength);\n mypos += saltLength;\n\n // Only for v6 packets, 32 octets of the fingerprint of the signing key.\n this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);\n mypos += 32;\n this.issuerKeyID = new KeyID();\n // For v6 the Key ID is the high-order 64 bits of the fingerprint.\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n }\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const arr = [new Uint8Array([\n this.version,\n this.signatureType,\n this.hashAlgorithm,\n this.publicKeyAlgorithm\n ])];\n if (this.version === 6) {\n arr.push(\n new Uint8Array([this.salt.length]),\n this.salt,\n this.issuerFingerprint\n );\n } else {\n arr.push(this.issuerKeyID.write());\n }\n arr.push(new Uint8Array([this.flags]));\n return util.concatUint8Array(arr);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||\n (this.version === 3 && correspondingSig.version === 6) ||\n (this.version === 6 && correspondingSig.version !== 6) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError,\n UnknownPacketError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,\n // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.\n // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.\n if (e instanceof UnknownPacketError) {\n if (parsed.tag <= 39) {\n await writer.abort(e);\n } else {\n return;\n }\n }\n\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Inflate, Deflate, Zlib, Unzlib } from 'fflate';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write());\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.\n * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator\n * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor\n * @returns {ReadableStream} compressed or decompressed data\n */\nfunction zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {\n return data => {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(inputData => {\n return new Promise((resolve, reject) => {\n const zlibStream = new ZlibStreamedConstructor();\n zlibStream.ondata = processedData => {\n resolve(processedData);\n };\n try {\n zlibStream.push(inputData, true); // only one chunk to push\n } catch (err) {\n reject(err);\n }\n });\n }));\n }\n\n // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)\n if (compressionStreamInstantiator) {\n try {\n const compressorOrDecompressor = compressionStreamInstantiator();\n return data.pipeThrough(compressorOrDecompressor);\n } catch (err) {\n // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate.\n if (err.name !== 'TypeError') {\n throw err;\n }\n }\n }\n\n // JS fallback\n const inputReader = data.getReader();\n const zlibStream = new ZlibStreamedConstructor();\n\n return new ReadableStream({\n async start(controller) {\n zlibStream.ondata = async (value, isLast) => {\n controller.enqueue(value);\n if (isLast) {\n controller.close();\n }\n };\n\n while (true) {\n const { done, value } = await inputReader.read();\n if (done) {\n zlibStream.push(new Uint8Array(), true);\n return;\n } else if (value.length) {\n zlibStream.push(value);\n }\n }\n }\n });\n };\n}\n\nfunction bzip2Decompress() {\n return async function(data) {\n const { decode: bunzipDecode } = await import('@openpgp/seek-bzip');\n return stream.fromAsync(async () => bunzipDecode(await stream.readToEnd(data)));\n };\n}\n\n/**\n * Get Compression Stream API instatiators if the constructors are implemented.\n * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported\n * (supported formats cannot be determined in advance).\n * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat\n * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}\n */\nconst getCompressionStreamInstantiators = compressionFormat => ({\n compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),\n decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))\n});\n\nconst compress_fns = {\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)\n};\n\nconst decompress_fns = {\n uncompressed: data => data,\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),\n bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n static fromObject({ version, aeadAlgorithm }) {\n if (version !== 1 && version !== 2) {\n throw new Error('Unsupported SEIPD version');\n }\n\n const seip = new SymEncryptedIntegrityProtectedDataPacket();\n seip.version = version;\n if (version === 2) {\n seip.aeadAlgorithm = aeadAlgorithm;\n }\n\n return seip;\n }\n\n constructor() {\n this.version = null;\n\n // The following 4 fields are for V2 only.\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = null;\n this.chunkSizeByte = null;\n this.salt = null;\n\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n this.version = await reader.readByte();\n // - A one-octet version number with value 1 or 2.\n if (this.version !== 1 && this.version !== 2) {\n throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);\n }\n\n if (this.version === 2) {\n // - A one-octet cipher algorithm.\n this.cipherAlgorithm = await reader.readByte();\n // - A one-octet AEAD algorithm.\n this.aeadAlgorithm = await reader.readByte();\n // - A one-octet chunk size.\n this.chunkSizeByte = await reader.readByte();\n // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.\n this.salt = await reader.readBytes(32);\n }\n\n // For V1:\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n // For V2:\n // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.\n // - A final, summary authentication tag for the AEAD mode.\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n if (this.version === 2) {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);\n }\n return util.concat([new Uint8Array([this.version]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n const { blockSize, keySize } = crypto.getCipherParams(sessionKeyAlgorithm);\n if (key.length !== keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n\n if (this.version === 2) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n this.salt = crypto.random.getRandomBytes(32);\n this.chunkSizeByte = config.aeadChunkSizeByte;\n this.encrypted = await runAEAD(this, 'encrypt', key, bytes);\n } else {\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n }\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n if (key.length !== crypto.getCipherParams(sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n\n let packetbytes;\n if (this.version === 2) {\n if (this.cipherAlgorithm !== sessionKeyAlgorithm) {\n // sanity check\n throw new Error('Unexpected session key algorithm');\n }\n packetbytes = await runAEAD(this, 'decrypt', key, encrypted);\n } else {\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n }\n\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n\n/**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\nexport async function runAEAD(packet, fn, key, data) {\n const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;\n const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)\n if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type');\n\n const mode = crypto.getAEADMode(packet.aeadAlgorithm);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;\n const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);\n const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n let iv;\n let ivView;\n if (isSEIPDv2) {\n const { keySize } = crypto.getCipherParams(packet.cipherAlgorithm);\n const { ivLength } = mode;\n const info = new Uint8Array(adataBuffer, 0, 5);\n const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);\n key = derived.subarray(0, keySize);\n iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.\n iv.fill(0, iv.length - 8);\n ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n } else { // AEADEncryptedDataPacket\n iv = packet.iv;\n // ivView is unused in this case\n }\n const modeInstance = await mode(packet.cipherAlgorithm, key);\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n let nonce;\n if (isSEIPDv2) { // SEIPD V2\n nonce = iv;\n } else { // AEADEncryptedDataPacket\n nonce = iv.slice();\n for (let i = 0; i < 8; i++) {\n nonce[iv.length - 8 + i] ^= chunkIndexArray[i];\n }\n }\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);\n cryptedPromise.catch(() => {});\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...)\n cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);\n cryptedPromise.catch(() => {});\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n if (isSEIPDv2) { // SEIPD V2\n ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...)\n } else { // AEADEncryptedDataPacket\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n }\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.ready.catch(() => {});\n await writer.abort(e);\n }\n });\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\nimport { runAEAD } from './sym_encrypted_integrity_protected_data';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await runAEAD(this, 'decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await runAEAD(this, 'encrypt', key, data);\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = null;\n\n // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`\n this.publicKeyID = new KeyID();\n\n // For version 6:\n this.publicKeyVersion = null;\n this.publicKeyFingerprint = null;\n\n // For all versions:\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n static fromObject({\n version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm\n }) {\n const pkesk = new PublicKeyEncryptedSessionKeyPacket();\n\n if (version !== 3 && version !== 6) {\n throw new Error('Unsupported PKESK version');\n }\n\n pkesk.version = version;\n\n if (version === 6) {\n pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;\n pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();\n }\n\n pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();\n pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;\n pkesk.sessionKey = sessionKey;\n pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;\n\n return pkesk;\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let offset = 0;\n this.version = bytes[offset++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n if (this.version === 6) {\n // A one-octet size of the following two fields:\n // - A one octet key version number.\n // - The fingerprint of the public key or subkey to which the session key is encrypted.\n // The size may also be zero.\n const versionAndFingerprintLength = bytes[offset++];\n if (versionAndFingerprintLength) {\n this.publicKeyVersion = bytes[offset++];\n const fingerprintLength = versionAndFingerprintLength - 1;\n this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength;\n if (this.publicKeyVersion >= 5) {\n // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint);\n } else {\n // For v4 The Key ID is the low-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));\n }\n } else {\n // The size may also be zero, and the key version and\n // fingerprint omitted for an \"anonymous recipient\"\n this.publicKeyID = KeyID.wildcard();\n }\n } else {\n offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));\n }\n this.publicKeyAlgorithm = bytes[offset++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));\n if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {\n if (this.version === 3) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n } else if (this.encrypted.C.algorithm !== null) {\n throw new Error('Unexpected cleartext symmetric algorithm');\n }\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version])\n ];\n\n if (this.version === 6) {\n if (this.publicKeyFingerprint !== null) {\n arr.push(new Uint8Array([\n this.publicKeyFingerprint.length + 1,\n this.publicKeyVersion]\n ));\n arr.push(this.publicKeyFingerprint);\n } else {\n arr.push(new Uint8Array([0]));\n }\n } else {\n arr.push(this.publicKeyID.write());\n }\n\n arr.push(\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n );\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a\n // v6 PKESK packet, as it is included in the v2 SEIPD packet.\n const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n if (this.version === 3) {\n // v3 Montgomery curves have cleartext cipher algo\n const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;\n this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;\n\n if (sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n // add checksum\n return util.concatUint8Array([\n new Uint8Array(version === 6 ? [] : [cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = version === 6 ?\n { sessionKeyAlgorithm: null, sessionKey: result } :\n { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && (\n version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return {\n sessionKeyAlgorithm: null,\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 6 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number with value 4, 5 or 6.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following 5 fields.\n offset++;\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version >= 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following field.\n offset++;\n }\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n const s2kType = bytes[offset++];\n this.s2k = newS2KFromType(s2kType);\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version >= 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n const s2k = this.s2k.write();\n if (this.version === 6) {\n const s2kLen = s2k.length;\n const fieldsLen = 3 + s2kLen + this.iv.length;\n bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);\n } else if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n if (this.sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n } else {\n // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v6Keys ? 6 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes, config = defaultConfig) {\n let pos = 0;\n // A one-octet version number (4, 5 or 6).\n this.version = bytes[pos++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version === 4 || this.version === 5 || this.version === 6) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version >= 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (\n this.version === 6 &&\n publicParams.oid && (\n publicParams.oid.getName() === enums.curve.curve25519Legacy ||\n publicParams.oid.getName() === enums.curve.ed25519Legacy\n )\n ) {\n throw new Error('Legacy curve25519 cannot be used with v6 keys');\n }\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version >= 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n const versionOctet = 0x95 + version;\n const lengthOctets = version >= 5 ? 4 : 2;\n return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version >= 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version >= 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError, writeTag } from './packet';\nimport computeHKDF from '../crypto/hkdf';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis\n * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).\n * This value is only relevant to know how to decrypt the key:\n * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.\n * @type {Boolean}\n * @private\n */\n this.isLegacyAEAD = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n /**\n * `true` for keys whose integrity is already confirmed, based on\n * the AEAD encryption mechanism\n * @type {Boolean}\n * @private\n */\n this.usedModernAEAD = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes, config = defaultConfig) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes, config);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n // - Only for a version 6 packet where the secret key material is\n // encrypted (that is, where the previous octet is not zero), a one-\n // octet scalar octet count of the cumulative length of all the\n // following optional string-to-key parameter fields.\n if (this.version === 6 && this.s2kUsage) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n i++;\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n const s2kType = bytes[i++];\n this.s2k = newS2KFromType(s2kType);\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n\n if (this.s2kUsage) {\n // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).\n // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).\n // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always\n // fail if the key was parsed according to the wrong format, since the keys are processed differently.\n // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.\n this.isLegacyAEAD = this.s2kUsage === 253 && (\n this.version === 5 || (this.version === 4 && config.parseAEADEncryptedV4KeysAsLegacy));\n // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)\n // of the same length as the cipher's block size.\n // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the\n // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.\n // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero\n if (this.s2kUsage !== 253 || this.isLegacyAEAD) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipherParams(this.symmetric).blockSize\n );\n this.usedModernAEAD = false;\n } else {\n // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),\n // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which\n // is used as the nonce for the AEAD algorithm.\n this.iv = bytes.subarray(\n i,\n i + crypto.getAEADMode(this.aead).ivLength\n );\n // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.\n this.usedModernAEAD = true;\n }\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n let cleartext;\n if (this.version === 6) {\n cleartext = this.keyMaterial;\n } else {\n cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n }\n try {\n const { read, privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n if (read < cleartext.length) {\n throw new Error('Error reading MPIs');\n }\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n const s2k = this.s2k.write();\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n optionalFieldsArr.push(s2k.length);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...s2k);\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage && this.version !== 6) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = newS2KFromType(enums.s2k.gnu, config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n this.isLegacyAEAD = null;\n this.usedModernAEAD = null;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n\n const { blockSize } = crypto.getCipherParams(this.symmetric);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = config.preferredAEADAlgorithm;\n const mode = crypto.getAEADMode(this.aead);\n this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.\n this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material\n\n const serializedPacketTag = writeTag(this.constructor.tag);\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n\n const modeInstance = await mode(this.symmetric, key);\n this.iv = this.isLegacyAEAD ? crypto.random.getRandomBytes(blockSize) : crypto.random.getRandomBytes(mode.ivLength);\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);\n } else {\n this.s2kUsage = 254;\n this.usedModernAEAD = false;\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(\n this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n this.aead = null;\n this.symmetric = null;\n this.isLegacyAEAD = null;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n if (this.usedModernAEAD) {\n // key integrity confirmed by successful AEAD decryption\n return;\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (this.version === 6 && (\n (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||\n this.algorithm === enums.publicKey.eddsaLegacy\n )) {\n throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);\n }\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\n/**\n * Derive encryption key\n * @param {Number} keyVersion - key derivation differs for v5 keys\n * @param {module:type/s2k} s2k\n * @param {String} passphrase\n * @param {module:enums.symmetric} cipherAlgo\n * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)\n * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)\n * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)\n * @returns encryption key\n */\nasync function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) {\n if (s2k.type === 'argon2' && !aeadMode) {\n throw new Error('Using Argon2 S2K without AEAD is not allowed');\n }\n if (s2k.type === 'simple' && keyVersion === 6) {\n throw new Error('Using Simple S2K with version 6 keys is not allowed');\n }\n const { keySize } = crypto.getCipherParams(cipherAlgo);\n const derivedKey = await s2k.produceKey(passphrase, keySize);\n if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {\n return derivedKey;\n }\n const info = util.concatUint8Array([\n serializedPacketTag,\n new Uint8Array([keyVersion, cipherAlgo, aeadMode])\n ]);\n return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);\n}\n\nexport default SecretKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n\n /**\n * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,\n * as well comments placed between the name (if present) and the bracketed email address:\n * - name (comment) \n * - email\n * In the first case, the `email` is the only required part, and it must contain the `@` symbol.\n * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,\n * since they interfere with `comment` parsing.\n */\n const re = /^(?[^()]+\\s+)?(?\\([^()]+\\)\\s+)?(?<\\S+@\\S+>)$/;\n const matches = re.exec(userID);\n if (matches !== null) {\n const { name, comment, email } = matches.groups;\n this.comment = comment?.replace(/^\\(|\\)|\\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace\n this.name = name?.trim() || '';\n this.email = email.substring(1, email.length - 1); // remove brackets\n } else if (/^[^\\s@]+@[^\\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace\n this.email = userID;\n }\n\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,\n * `enums.signatures.certGeneric` should be given regardless of the actual trust level)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm for a set of keys.\n * @param {Array} [targetKeys] - The keys to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {\n /**\n * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the\n * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).\n * if no keys are available, `preferredSenderAlgo` is returned.\n * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).\n */\n const defaultAlgo = enums.hash.sha256; // MUST implement\n const preferredSenderAlgo = config.preferredHashAlgorithm;\n\n const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {\n const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);\n const targetPrefs = selfCertification.preferredHashAlgorithms;\n return targetPrefs;\n }));\n const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys\n for (const supportedAlgos of supportedAlgosPerTarget) {\n for (const hashAlgo of supportedAlgos) {\n try {\n // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on\n const supportedAlgo = enums.write(enums.hash, hashAlgo);\n supportedAlgosMap.set(\n supportedAlgo,\n supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1\n );\n } catch {}\n }\n }\n const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;\n const getStrongestSupportedHashAlgo = () => {\n if (supportedAlgosMap.size === 0) {\n return defaultAlgo;\n }\n const sortedHashAlgos = Array.from(supportedAlgosMap.keys())\n .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))\n .sort((algoA, algoB) => crypto.hash.getHashByteLength(algoA) - crypto.hash.getHashByteLength(algoB));\n const strongestHashAlgo = sortedHashAlgos[0];\n // defaultAlgo is always implicilty supported, and might be stronger than the rest\n return crypto.hash.getHashByteLength(strongestHashAlgo) >= crypto.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;\n };\n\n const eccAlgos = new Set([\n enums.publicKey.ecdsa,\n enums.publicKey.eddsaLegacy,\n enums.publicKey.ed25519,\n enums.publicKey.ed448\n ]);\n\n if (eccAlgos.has(signingKeyPacket.algorithm)) {\n // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:\n // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5\n // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;\n // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve\n // preferred algo, even if not supported by all targets.\n const preferredCurveAlgo = crypto.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);\n\n const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);\n const preferredSenderAlgoStrongerThanCurveAlgo = crypto.hash.getHashByteLength(preferredSenderAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo);\n\n if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {\n return preferredSenderAlgo;\n } else {\n const strongestSupportedAlgo = getStrongestSupportedHashAlgo();\n return crypto.hash.getHashByteLength(strongestSupportedAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo) ?\n strongestSupportedAlgo :\n preferredCurveAlgo;\n }\n }\n\n // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,\n // since it was manually set by the sender.\n return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();\n}\n\n/**\n * Returns the preferred compression algorithm for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred compression algorithm\n * @async\n */\nexport async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = enums.compression.uncompressed;\n const preferredSenderAlgo = config.preferredCompressionAlgorithm;\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config);\n const recipientPrefs = selfCertification.preferredCompressionAlgorithms;\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred\n * @async\n */\nexport async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config)));\n const withAEAD = keys.length ?\n selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :\n config.aeadProtect;\n\n if (withAEAD) {\n const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };\n const desiredCipherSuites = [\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: config.preferredAEADAlgorithm },\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },\n { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config.preferredAEADAlgorithm }\n ];\n for (const desiredCipherSuite of desiredCipherSuites) {\n if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(\n cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo\n ))) {\n return desiredCipherSuite;\n }\n }\n return defaultCipherSuite;\n }\n const defaultSymAlgo = enums.symmetric.aes128;\n const desiredSymAlgo = config.preferredSymmetricAlgorithm;\n return {\n symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?\n desiredSymAlgo :\n defaultSymAlgo,\n aeadAlgo: undefined\n };\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {Array} recipientKeys - keys to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);\n signaturePacket.rawNotations = [...notations];\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n const isHardRevocation = ![\n enums.reasonForRevocation.keyRetired,\n enums.reasonForRevocation.keySuperseded,\n enums.reasonForRevocation.userIDInvalid\n ].includes(revocationSignature.reasonForRevocationFlag);\n\n await revocationSignature.verify(\n key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||\n options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'curve25519':\n options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;\n break;\n case 'curve448':\n options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function validateSigningKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateEncryptionKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateDecryptionKeyPacket(keyPacket, signature, config) {\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateSigningKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateEncryptionKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n if (primaryKey.version !== 6) {\n // check for expiration time in direct signatures (for V6 keys, the above already did so)\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const selfCertification = await this.getPrimarySelfSignature(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.\n await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * For V4 keys, returns the self-signature of the primary user.\n * For V5 keys, returns the latest valid direct-key self-signature.\n * This self-signature is to be used to check the key expiration,\n * algorithm preferences, and so on.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} The primary self-signature\n * @async\n */\n async getPrimarySelfSignature(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n if (primaryKey.version === 6) {\n return helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n );\n }\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n return selfCertification;\n }\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config);\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @throws {Error} if no decryption key is found\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n let exception = null;\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n if (this.subkeys[i].keyPacket.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n continue;\n }\n\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n // evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.validateDecryptionKeyPacket(primaryKey, selfCertification, config)) {\n if (primaryKey.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n } else {\n keys.push(this);\n }\n }\n\n if (keys.length === 0) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('No decryption key packets found');\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.\n * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).\n * Note: Curve448 and Curve25519 are not widely supported yet.\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n // Every subkey for a v4 primary key MUST be a v4 subkey.\n // Every subkey for a v6 primary key MUST be a v6 subkey.\n // For v5 keys, since we dropped generation support, a v4 subkey is added.\n // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.\n const keyPacket = await helper.generateSecretSubkey(options, { ...config, v6Keys: this.keyPacket.version === 6 });\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nfunction getDefaultSubkeyType(algoName) {\n const algo = enums.write(enums.publicKey, algoName);\n // NB: no encryption-only algos, since they cannot be in primary keys\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n return 'rsa';\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return 'ecc';\n case enums.publicKey.ed25519:\n return 'curve25519';\n case enums.publicKey.ed448:\n return 'curve448';\n default:\n throw new Error('Unsupported algorithm');\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n function getKeySignatureProperties() {\n const signatureProperties = {};\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n const symmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128\n ], config.preferredSymmetricAlgorithm);\n signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;\n if (config.aeadProtect) {\n const aeadAlgorithms = createPreferredAlgos([\n enums.aead.gcm,\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {\n return symmetricAlgorithms.map(symmetricAlgorithm => {\n return [symmetricAlgorithm, aeadAlgorithm];\n });\n });\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512,\n enums.hash.sha3_256,\n enums.hash.sha3_512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.uncompressed,\n enums.compression.zlib,\n enums.compression.zip\n ], config.preferredCompressionAlgorithm);\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.seipdv2;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n return signatureProperties;\n }\n\n if (secretKeyPacket.version === 6) { // add direct key signature with key prefs\n const dataToSign = {\n key: secretKeyPacket\n };\n\n const signatureProperties = getKeySignatureProperties();\n signatureProperties.signatureType = enums.signature.key;\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n packetlist.push(signaturePacket);\n }\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {\n userID: userIDPacket,\n key: secretKeyPacket\n };\n const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};\n signatureProperties.signatureType = enums.signature.certPositive;\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);\n return createKey(firstKeyPacketList);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n return new PrivateKey(firstPrivateKeyList);\n }\n throw new Error('No secret key packet found');\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n if (keys.length === 0) {\n throw new Error('No secret key packet found');\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport { Argon2OutOfMemoryError } from './type/s2k';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredCipherSuite, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;\n\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config);\n\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n if (err instanceof Argon2OutOfMemoryError) {\n exception = err;\n }\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let decryptionKeyPackets;\n try {\n // do not check key expiration to allow decryption of old messages\n decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n } catch (err) {\n exception = err;\n return;\n }\n\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config); // TODO: Pass userID from somewhere.\n if (selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all((\n expectedSymmetricAlgorithm ?\n [expectedSymmetricAlgorithm] :\n Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)\n ).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;\n if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config);\n const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);\n const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&\n !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(symmetricAlgo);\n return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({\n version: aeadAlgorithmName ? 2 : 1,\n aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null\n });\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n\n const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({\n version: aeadAlgorithm ? 6 : 3,\n encryptionKeyPacket: encryptionKey.keyPacket,\n anonymousRecipient: wildcard,\n sessionKey,\n sessionKeyAlgorithm: symmetricAlgorithm\n });\n\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config); // this returns the existing signature packets as well\n const onePassSignaturePackets = signaturePackets.map(\n (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))\n .reverse(); // innermost OPS refers to the first signature packet\n\n packetlist.push(...onePassSignaturePackets);\n packetlist.push(literalDataPacket);\n packetlist.push(...signaturePackets);\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n const trailingPacket = this.packets[this.packets.length - 1];\n // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?\n trailingPacket.version !== 2 :\n this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const signingUserID = signingUserIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config);\n return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n const input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // emit header and checksum if one of the signatures has a version not 6\n const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);\n const hash = emitHeaderAndChecksum ?\n Array.from(new Set(this.signature.packets.map(\n packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()\n ))).join() :\n null;\n\n const body = {\n hash,\n text: this.text,\n data: this.signature.packets.write()\n };\n\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n const hashAlgos = [];\n headers.forEach(header => {\n const hashHeader = header.match(/^Hash: (.+)$/); // get header value\n if (hashHeader) {\n const parsedHashIDs = hashHeader[1]\n .replace(/\\s/g, '') // remove whitespace\n .split(',')\n .map(hashName => {\n try {\n return enums.write(enums.hash, hashName.toLowerCase());\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());\n }\n });\n hashAlgos.push(...parsedHashIDs);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredCompressionAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).\n * Note: Curve448 and Curve25519 (new format) are not widely supported yet.\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:\n * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n if (!type && !curve) {\n type = config.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)\n curve = 'curve25519Legacy'; // unused with type != 'ecc'\n } else {\n type = type || 'ecc';\n curve = curve || 'curve25519Legacy';\n }\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && !config.v6Keys) {\n throw new Error('UserIDs are required for V4 keys');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {\n throw new Error('UserIDs are required for V4 keys');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return await convertStream(data);\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return await convertStream(signature);\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data) {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\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// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n}, sha256);\nexport const secp256r1 = p256;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha384 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp384r1 aka p384\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');\nconst Fp = Field(P);\nconst CURVE_A = Fp.create(BigInt('-3'));\n// prettier-ignore\nconst CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n// prettier-ignore\nexport const p384 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\n // Curve order, total count of valid points in the field.\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n // Base (generator) point (x, y)\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n h: BigInt(1),\n lowS: false,\n}, sha384);\nexport const secp384r1 = p384;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-12')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p384.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp521r1 aka p521\n// Note that it's 521, which differs from 512 of its hash function.\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst Fp = Field(P);\nconst CURVE = {\n a: Fp.create(BigInt('-3')),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Fp,\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n h: BigInt(1),\n};\n// prettier-ignore\nexport const p521 = createCurve({\n a: CURVE.a, // Equation params: a, b\n b: CURVE.b,\n Fp, // Field: 2n**521n - 1n\n // Curve order, total count of valid points in the field\n n: CURVE.n,\n Gx: CURVE.Gx, // Base point (x, y) aka generator point\n Gy: CURVE.Gy,\n h: CURVE.h,\n lowS: false,\n allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\nexport const secp521r1 = p521;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE.a,\n B: CURVE.b,\n Z: Fp.create(BigInt('-4')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p521.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3';\nimport { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xof } from './abstract/hash-to-curve.js';\nimport { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * Edwards448 (not Ed448-Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n */\nconst shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));\nconst ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');\n// prettier-ignore\nconst _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);\n// prettier-ignore\nconst _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448P;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most\n // significant bit of the last byte to 1.\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.\n// Uses algo from RFC8032 5.1.3.\nfunction uvRatio(u, v) {\n const P = ed448P;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u²v\n const u3v = mod(u2v * u, P); // u³v\n const u5v3 = mod(u3v * u2v * v, P); // u⁵v³\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x²\n // If vx² = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\nconst Fp = Field(ed448P, 456, true);\nconst ED448_DEF = {\n // Param: a\n a: BigInt(1),\n // -39081. Negative number is P - number\n d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'),\n // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n\n Fp,\n // Subgroup order: how many points curve has;\n // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\n n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n nBitLength: 456,\n // Cofactor\n h: BigInt(4),\n // Base point (x, y) aka generator point\n Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'),\n Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'),\n // SHAKE256(dom4(phflag,context)||x, 114)\n hash: shake256_114,\n randomBytes,\n adjustScalarBytes,\n // dom4\n domain: (data, ctx, phflag) => {\n if (ctx.length > 255)\n throw new Error(`Context is too big: ${ctx.length}`);\n return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n },\n uvRatio,\n};\nexport const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF);\n// NOTE: there is no ed448ctx, since ed448 supports ctx by default\nexport const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 });\nexport const x448 = /* @__PURE__ */ (() => montgomery({\n a: BigInt(156326),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n montgomeryBits: 448,\n nByteLength: 56,\n P: ed448P,\n Gu: BigInt(5),\n powPminus2: (x) => {\n const P = ed448P;\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, BigInt(2), P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts edwards448 public key to x448 public key. Uses formula:\n * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n * @example\n * const aPub = ed448.getPublicKey(utils.randomPrivateKey());\n * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed448.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version\n// Hash To Curve Elligator2 Map\nconst ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic\nconst ELL2_J = BigInt(156326);\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\nfunction map_to_curve_elligator2_edwards448(u) {\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = Fp.invertBatch([xEd, yEd]); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertDcfPoint(other) {\n if (!(other instanceof DcfPoint))\n throw new Error('DecafPoint expected');\n}\n// 1-d\nconst ONE_MINUS_D = BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = BigInt('78163');\n// √(-d)\nconst SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / √(-d)\nconst INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B);\n// Computes Elligator map for Decaf\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const r = mod(-(r0 * r0)); // 1\n const u0 = mod(d * (r - _1n)); // 2\n const u1 = mod((u0 + _1n) * (u0 - r)); // 3\n const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = mod(r0 * v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = mod(-_1n);\n const s = mod(v_prime * (r + _1n)); // 7\n let s_abs = s;\n if (isNegativeLE(s, P))\n s_abs = mod(-s);\n const s2 = s * s;\n const W0 = mod(s_abs * _2n); // 8\n const W1 = mod(s2 + _1n); // 9\n const W2 = mod(s2 - _1n); // 10\n const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11\n return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed448/ExtendedPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass DcfPoint {\n // Private property to discourage combining ExtendedPoint + DecafPoint\n // Always use Decaf encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\n * @param hex 112-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('decafHash', hex, 112);\n const r1 = bytes448ToNumberLE(hex.slice(0, 56));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = bytes448ToNumberLE(hex.slice(56, 112));\n const R2 = calcElligatorDecafMap(r2);\n return new DcfPoint(R1.add(R2));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2\n * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('decafHex', hex, 56);\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint';\n const s = bytes448ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s); // 1\n const u1 = mod(_1n + s2); // 2\n const u1sq = mod(u1 * u1);\n const u2 = mod(u1sq - _4n * d * s2); // 3\n const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4\n let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5\n if (isNegativeLE(u3, P))\n u3 = mod(-u3);\n const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6\n const y = mod((_1n - s2) * invsqrt * u1); // 7\n const t = mod(x * y); // 8\n if (!isValid)\n throw new Error(emsg);\n return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2\n */\n toRawBytes() {\n let { ex: x, ey: _y, ez: z, et: t } = this.ep;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const u1 = mod(mod(x + t) * mod(x - t)); // 1\n const x2 = mod(x * x);\n const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2\n let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3\n if (isNegativeLE(ratio, P))\n ratio = mod(-ratio);\n const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4\n let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 56);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2\n equals(other) {\n assertDcfPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed448.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2)\n return mod(X1 * Y2) === mod(Y1 * X2);\n }\n add(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new DcfPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new DcfPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new DcfPoint(this.ep.double());\n }\n negate() {\n return new DcfPoint(this.ep.negate());\n }\n}\nexport const DecafPoint = /* @__PURE__ */ (() => {\n // decaf448 base point is ed448 base x 2\n // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699\n if (!DcfPoint.BASE)\n DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n);\n if (!DcfPoint.ZERO)\n DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO);\n return DcfPoint;\n})();\n// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C\nexport const hashToDecaf448 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256);\n const P = DcfPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_decaf448 = hashToDecaf448; // legacy\n//# sourceMappingURL=ed448.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));\nconst CURVE_A = Fp.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));\nconst CURVE_B = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');\n\n// prettier-ignore\nexport const brainpoolP256r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),\n Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),\n h: BigInt(1),\n lowS: false\n} as const, sha256);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha384 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));\nconst CURVE_A = Fp.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));\nconst CURVE_B = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');\n\n// prettier-ignore\nexport const brainpoolP384r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),\n Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),\n h: BigInt(1),\n lowS: false\n} as const, sha384);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));\nconst CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));\nconst CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');\n\n// prettier-ignore\nexport const brainpoolP512r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),\n Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),\n h: BigInt(1),\n lowS: false\n} as const, sha512);\n","/**\n * This file is needed to dynamic import the noble-curves.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { p256 as nistP256 } from '@noble/curves/p256';\nimport { p384 as nistP384 } from '@noble/curves/p384';\nimport { p521 as nistP521 } from '@noble/curves/p521';\nimport { x448, ed448 } from '@noble/curves/ed448';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { brainpoolP256r1 } from './brainpool/brainpoolP256r1';\nimport { brainpoolP384r1 } from './brainpool/brainpoolP384r1';\nimport { brainpoolP512r1 } from './brainpool/brainpoolP512r1';\n\nexport const nobleCurves = new Map(Object.entries({\n nistP256,\n nistP384,\n nistP521,\n brainpoolP256r1,\n brainpoolP384r1,\n brainpoolP512r1,\n secp256k1,\n x448,\n ed448\n}));\n\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * This file is needed to dynamic import the legacy ciphers.\n * Separate dynamic imports are not convenient as they result in multiple chunks.\n */\n\nimport { TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TwoFish from './twofish';\nimport BlowFish from './blowfish';\nimport enums from '../../enums';\n\nexport const legacyCiphers = new Map([\n [enums.symmetric.tripledes, TripleDES],\n [enums.symmetric.cast5, CAST5],\n [enums.symmetric.blowfish, BlowFish],\n [enums.symmetric.twofish, TwoFish]\n]);\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms.\n// Initial state\nconst SHA1_IV = /* @__PURE__ */ new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n SHA1_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * SHA1 (RFC 3174) hash function.\n * It was cryptographically broken: prefer newer algorithms.\n * @param message - data that would be hashed\n */\nexport const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());\n//# sourceMappingURL=sha1.js.map","import { HashMD } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n R_BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.js.map","/**\n * This file is needed to dynamic import the noble-hashes.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { sha1 } from '@noble/hashes/sha1';\nimport { sha224, sha256 } from '@noble/hashes/sha256';\nimport { sha384, sha512 } from '@noble/hashes/sha512';\nimport { sha3_256, sha3_512 } from '@noble/hashes/sha3';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\n\nexport const nobleHashes = new Map(Object.entries({\n sha1,\n sha224,\n sha256,\n sha384,\n sha512,\n sha3_256,\n sha3_512,\n ripemd160\n}));\n","// Adapted from the reference implementation in RFC7693\n// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes\n\n// Uint64 values are represented using two Uint32s, stored as little endian\n// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays\n// need to be manually handled\n\n// 64-bit unsigned addition (little endian, in place)\n// Sets a[i,i+1] += b[j,j+1]\n// `a` and `b` must be Uint32Array(2)\nfunction ADD64 (a, i, b, j) {\n a[i] += b[j];\n a[i+1] += b[j+1] + (a[i] < b[j]); // add carry\n}\n\n// Increment 64-bit little-endian unsigned value by `c` (in place)\n// `a` must be Uint32Array(2)\nfunction INC64 (a, c) {\n a[0] += c;\n a[1] += (a[0] < c);\n}\n\n// G Mixing function\n// The ROTRs are inlined for speed\nfunction G (v, m, a, b, c, d, ix, iy) {\n ADD64(v, a, v, b) // v[a,a+1] += v[b,b+1]\n ADD64(v, a, m, ix) // v[a, a+1] += x ... x0\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n let xor0 = v[d] ^ v[a]\n let xor1 = v[d + 1] ^ v[a + 1]\n v[d] = xor1\n v[d + 1] = xor0\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor0 >>> 24) ^ (xor1 << 8)\n v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)\n\n ADD64(v, a, v, b)\n ADD64(v, a, m, iy)\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = v[d] ^ v[a]\n xor1 = v[d + 1] ^ v[a + 1]\n v[d] = (xor0 >>> 16) ^ (xor1 << 16)\n v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor1 >>> 31) ^ (xor0 << 1)\n v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)\n}\n\n// Initialization Vector\nconst BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n])\n\n// These are offsets into a Uint64 buffer.\n// Multiply them all by 2 to make them offsets into a Uint32 buffer\nconst SIGMA = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n].map(x => x * 2))\n\n// Compression function. 'last' flag indicates last block.\n// Note: we're representing 16 uint64s as 32 uint32s\nfunction compress(S, last) {\n const v = new Uint32Array(32)\n const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32)\n\n // init work variables\n for (let i = 0; i < 16; i++) {\n v[i] = S.h[i]\n v[i + 16] = BLAKE2B_IV32[i]\n }\n\n // low 64 bits of offset\n v[24] ^= S.t0[0]\n v[25] ^= S.t0[1]\n // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1\n\n // if last block\n const f0 = last ? 0xFFFFFFFF : 0;\n v[28] ^= f0;\n v[29] ^= f0;\n\n // twelve rounds of mixing\n for (let i = 0; i < 12; i++) {\n // ROUND(r)\n const i16 = i << 4;\n G(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1])\n G(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3])\n G(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5])\n G(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7])\n G(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9])\n G(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11])\n G(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13])\n G(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15])\n }\n\n for (let i = 0; i < 16; i++) {\n S.h[i] ^= v[i] ^ v[i + 16]\n }\n}\n\n// Creates a BLAKE2b hashing context\n// Requires an output length between 1 and 64 bytes\n// Takes an optional Uint8Array key\nclass Blake2b {\n constructor(outlen, key, salt, personal) {\n const params = new Uint8Array(64)\n // 0: outlen, keylen, fanout, depth\n // 4: leaf length, sequential mode\n // 8: node offset\n // 12: node offset\n // 16: node depth, inner length, rfu\n // 20: rfu\n // 24: rfu\n // 28: rfu\n // 32: salt\n // 36: salt\n // 40: salt\n // 44: salt\n // 48: personal\n // 52: personal\n // 56: personal\n // 60: personal\n\n // init internal state\n this.S = {\n b: new Uint8Array(BLOCKBYTES),\n h: new Uint32Array(OUTBYTES_MAX / 4),\n t0: new Uint32Array(2), // input counter `t`, lower 64-bits only\n c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`\n outlen // output length in bytes\n }\n\n // init parameter block\n params[0] = outlen\n if (key) params[1] = key.length\n params[2] = 1 // fanout\n params[3] = 1 // depth\n if (salt) params.set(salt, 32)\n if (personal) params.set(personal, 48)\n const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];\n }\n\n // key the hash, if applicable\n if (key) {\n const block = new Uint8Array(BLOCKBYTES)\n block.set(key)\n this.update(block)\n }\n }\n\n // Updates a BLAKE2b streaming hash\n // Requires Uint8Array (byte array)\n update(input) {\n if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')\n // for (let i = 0; i < input.length; i++) {\n // if (this.S.c === BLOCKBYTES) { // buffer full\n // INC64(this.S.t0, this.S.c) // add counters\n // compress(this.S, false)\n // this.S.c = 0 // empty buffer\n // }\n // this.S.b[this.S.c++] = input[i]\n // }\n let i = 0\n while(i < input.length) {\n if (this.S.c === BLOCKBYTES) { // buffer full\n INC64(this.S.t0, this.S.c) // add counters\n compress(this.S, false)\n this.S.c = 0 // empty buffer\n }\n let left = BLOCKBYTES - this.S.c\n this.S.b.set(input.subarray(i, i + left), this.S.c) // end index can be out of bounds\n const fill = Math.min(left, input.length - i)\n this.S.c += fill\n i += fill\n }\n return this\n }\n\n /**\n * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one\n * @param {Uint8Array} [prealloc] - optional preallocated buffer\n * @returns {ArrayBuffer} message digest\n */\n digest(prealloc) {\n INC64(this.S.t0, this.S.c) // mark last block offset\n\n // final block, padded\n this.S.b.fill(0, this.S.c);\n this.S.c = BLOCKBYTES;\n compress(this.S, true)\n\n const out = prealloc || new Uint8Array(this.S.outlen);\n for (let i = 0; i < this.S.outlen; i++) {\n // must be loaded individually since default Uint32 endianness is platform dependant\n out[i] = this.S.h[i >> 2] >> (8 * (i & 3))\n }\n this.S.h = null; // prevent calling `update` after `digest`\n return out.buffer;\n }\n}\n\n\nexport default function createHash(outlen, key, salt, personal) {\n if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)\n if (key) {\n if (!(key instanceof Uint8Array)) throw new Error('key must be Uint8Array or Buffer')\n if (key.length > KEYBYTES_MAX) throw new Error(`key size must be at most ${KEYBYTES_MAX} (given: ${key.length})`)\n }\n if (salt) {\n if (!(salt instanceof Uint8Array)) throw new Error('salt must be Uint8Array or Buffer')\n if (salt.length !== SALTBYTES) throw new Error(`salt must be exactly ${SALTBYTES} (given: ${salt.length}`)\n }\n if (personal) {\n if (!(personal instanceof Uint8Array)) throw new Error('personal must be Uint8Array or Buffer')\n if (personal.length !== PERSONALBYTES) throw new Error(`salt must be exactly ${PERSONALBYTES} (given: ${personal.length}`)\n }\n\n return new Blake2b(outlen, key, salt, personal)\n}\n\nconst OUTBYTES_MAX = 64;\nconst KEYBYTES_MAX = 64;\nconst SALTBYTES = 16;\nconst PERSONALBYTES = 16;\nconst BLOCKBYTES = 128;\n\n","import blake2b from \"./blake2b.js\"\nconst TYPE = 2; // Argon2id\nconst VERSION = 0x13;\nconst TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MIN = 8;\nconst passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst passwordBYTES_MIN = 8;\nconst MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)\nconst SECRETBYTES_MAX = 32; // key (optional)\n\nconst ARGON2_BLOCK_SIZE = 1024;\nconst ARGON2_PREHASH_DIGEST_LENGTH = 64;\n\nconst isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;\n\n// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])\nfunction LE32(buf, n, i) {\n buf[i+0] = n;\n buf[i+1] = n >> 8;\n buf[i+2] = n >> 16;\n buf[i+3] = n >> 24;\n return buf;\n}\n\n/**\n * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])\n * @param {Uint8Array} buf\n * @param {Number} n\n * @param {Number} i\n */\nfunction LE64(buf, n, i) {\n if (n > Number.MAX_SAFE_INTEGER) throw new Error(\"LE64: large numbers unsupported\");\n // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations\n // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)\n // so we manually extract each byte\n let remainder = n;\n for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER\n buf[offset] = remainder; // implicit & 0xff\n remainder = (remainder - buf[offset]) / 256;\n }\n return buf;\n}\n\n/**\n * Variable-Length Hash Function H'\n * @param {Number} outlen - T\n * @param {Uint8Array} X - value to hash\n * @param {Uint8Array} res - output buffer, of length `outlength` or larger\n */\nfunction H_(outlen, X, res) {\n const V = new Uint8Array(64); // no need to keep around all V_i\n\n const V1_in = new Uint8Array(4 + X.length);\n LE32(V1_in, outlen, 0);\n V1_in.set(X, 4);\n if (outlen <= 64) {\n // H'^T(A) = H^T(LE32(T)||A)\n blake2b(outlen).update(V1_in).digest(res);\n return res\n }\n\n const r = Math.ceil(outlen / 32) - 2;\n\n // Let V_i be a 64-byte block and W_i be its first 32 bytes.\n // V_1 = H^(64)(LE32(T)||A)\n // V_2 = H^(64)(V_1)\n // ...\n // V_r = H^(64)(V_{r-1})\n // V_{r+1} = H^(T-32*r)(V_{r})\n // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}\n for (let i = 0; i < r; i++) {\n blake2b(64).update(i === 0 ? V1_in : V).digest(V);\n // store W_i in result buffer already\n res.set(V.subarray(0, 32), i*32)\n }\n // V_{r+1}\n const V_r1 = new Uint8Array(blake2b(outlen - 32*r).update(V).digest());\n res.set(V_r1, r*32);\n\n return res;\n}\n\n// compute buf = xs ^ ys\nfunction XOR(wasmContext, buf, xs, ys) {\n wasmContext.fn.XOR(\n buf.byteOffset,\n xs.byteOffset,\n ys.byteOffset,\n );\n return buf\n}\n\n/**\n * @param {Uint8Array} X (read-only)\n * @param {Uint8Array} Y (read-only)\n * @param {Uint8Array} R - output buffer\n * @returns\n */\nfunction G(wasmContext, X, Y, R) {\n wasmContext.fn.G(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\nfunction G2(wasmContext, X, Y, R) {\n wasmContext.fn.G2(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\n// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.\nfunction* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {\n // For each segment, we do the following. First, we compute the value Z as:\n // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )\n wasmContext.refs.prngTmp.fill(0);\n const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);\n LE64(Z, pass, 0);\n LE64(Z, lane, 8);\n LE64(Z, slice, 16);\n LE64(Z, m_, 24);\n LE64(Z, totalPasses, 32);\n LE64(Z, TYPE, 40);\n\n // Then we compute q/(128*SL) 1024-byte values\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),\n // ...,\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),\n for(let i = 1; i <= segmentLength; i++) {\n // tmp.set(Z); // no need to re-copy\n LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed\n const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );\n\n // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2\n // NB: the first generated pair must be used for the first block of the segment, and so on.\n // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.\n for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {\n yield g2.subarray(k, k+8);\n }\n }\n return [];\n}\n\nfunction validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {\n const assertLength = (name, value, min, max) => {\n if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }\n }\n\n if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');\n assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);\n assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);\n assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);\n assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);\n // optional fields\n ad && assertLength('associated data', ad, 0, ADBYTES_MAX);\n secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);\n\n return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };\n}\n\nconst KB = 1024;\nconst WASM_PAGE_SIZE = 64 * KB;\n\nexport default function argon2id(params, { memory, instance: wasmInstance }) {\n if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system\n\n const ctx = validateParams({ type: TYPE, version: VERSION, ...params });\n\n const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;\n const wasmRefs = {};\n const wasmFn = {};\n wasmFn.G = wasmG;\n wasmFn.G2 = wasmG2;\n wasmFn.XOR = wasmXOR;\n\n // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.\n const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));\n const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references\n if (memory.buffer.byteLength < requiredMemory) {\n const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE)\n // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.\n // Otherwise, the operation fails, and the original memory can still be used.\n memory.grow(missing)\n }\n\n let offset = 0;\n // Init wasm memory needed in other functions\n wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;\n wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;\n wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;\n wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;\n // Init wasm memory needed locally\n const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;\n const wasmContext = { fn: wasmFn, refs: wasmRefs };\n const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;\n const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);\n const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);\n\n // 1. Establish H_0\n const H0 = getH0(ctx);\n\n // 2. Allocate the memory as m' 1024-byte blocks\n // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.\n const q = m_ / ctx.lanes;\n const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));\n const initBlock = (i, j) => {\n B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);\n return B[i][j];\n }\n\n for (let i = 0; i < ctx.lanes; i++) {\n // const LEi = LE0; // since p = 1 for us\n const tmp = new Uint8Array(H0.length + 8);\n // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p\n // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))\n tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));\n // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p\n // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))\n LE32(tmp, 1, H0.length);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));\n }\n\n // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2\n // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes\n // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.\n const SL = 4; // vertical slices\n const segmentLength = q / SL;\n for (let pass = 0; pass < ctx.passes; pass++) {\n // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel\n for (let sl = 0; sl < SL; sl++) {\n const isDataIndependent = pass === 0 && sl <= 1;\n for (let i = 0; i < ctx.lanes; i++) { // lane\n // On the first slice of the first pass, blocks 0 and 1 are already filled\n let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;\n // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)\n const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;\n for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {\n const j = sl * segmentLength + segmentOffset;\n const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]\n\n // we can assume the PRNG is never done\n const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength)\n const l = lz[0]; const z = lz[1];\n // for (let i = 0; i < p; i++ )\n // B[i][j] = G(B[i][j-1], B[l][z])\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n if (pass === 0) initBlock(i, j);\n G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);\n\n // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one\n if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j])\n }\n }\n }\n }\n\n // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:\n // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]\n const C = B[0][q-1];\n for(let i = 1; i < ctx.lanes; i++) {\n XOR(wasmContext, C, C, B[i][q-1])\n }\n\n const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));\n // clear memory since the module might be cached\n allocatedMemory.fill(0) // clear sensitive contents\n memory.grow(0) // allow deallocation\n // 8. The output tag is computed as H'^T(C).\n return tag;\n\n}\n\nfunction getH0(ctx) {\n const H = blake2b(ARGON2_PREHASH_DIGEST_LENGTH);\n const ZERO32 = new Uint8Array(4);\n const params = new Uint8Array(24);\n LE32(params, ctx.lanes, 0);\n LE32(params, ctx.tagLength, 4);\n LE32(params, ctx.memorySize, 8);\n LE32(params, ctx.passes, 12);\n LE32(params, ctx.version, 16);\n LE32(params, ctx.type, 20);\n\n const toHash = [params];\n if (ctx.password) {\n toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0))\n toHash.push(ctx.password)\n } else {\n toHash.push(ZERO32) // context.password.length\n }\n\n if (ctx.salt) {\n toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0))\n toHash.push(ctx.salt)\n } else {\n toHash.push(ZERO32) // context.salt.length\n }\n\n if (ctx.secret) {\n toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0))\n toHash.push(ctx.secret)\n // todo clear secret?\n } else {\n toHash.push(ZERO32) // context.secret.length\n }\n\n if (ctx.ad) {\n toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0))\n toHash.push(ctx.ad)\n } else {\n toHash.push(ZERO32) // context.ad.length\n }\n H.update(concatArrays(toHash))\n\n const outputBuffer = H.digest();\n return new Uint8Array(outputBuffer);\n}\n\nfunction concatArrays(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!(arrays[i] instanceof Uint8Array)) {\n throw new Error('concatArrays: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach((element) => {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n","import argon2id from \"./argon2id.js\";\n\nlet isSIMDSupported;\nasync function wasmLoader(memory, getSIMD, getNonSIMD) {\n const importObject = { env: { memory } };\n if (isSIMDSupported === undefined) {\n try {\n const loaded = await getSIMD(importObject);\n isSIMDSupported = true;\n return loaded;\n } catch(e) {\n isSIMDSupported = false;\n }\n }\n\n const loader = isSIMDSupported ? getSIMD : getNonSIMD;\n return loader(importObject);\n}\n\nexport default async function setupWasm(getSIMD, getNonSIMD) {\n const memory = new WebAssembly.Memory({\n // in pages of 64KiB each\n // these values need to be compatible with those declared when building in `build-wasm`\n initial: 1040, // 65MB\n maximum: 65536, // 4GB\n });\n const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);\n\n /**\n * Argon2id hash function\n * @callback computeHash\n * @param {Object} params\n * @param {Uint8Array} params.password - password\n * @param {Uint8Array} params.salt - salt\n * @param {Integer} params.parallelism\n * @param {Integer} params.passes\n * @param {Integer} params.memorySize - in kibibytes\n * @param {Integer} params.tagLength - output tag length\n * @param {Uint8Array} [params.ad] - associated data (optional)\n * @param {Uint8Array} [params.secret] - secret data (optional)\n * @return {Uint8Array} argon2id hash\n */\n const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });\n\n return computeHash;\n}\n","import setupWasm from './lib/setup.js';\nimport wasmSIMD from './dist/simd.wasm';\nimport wasmNonSIMD from './dist/no-simd.wasm';\n\nconst loadWasm = async () => setupWasm(\n (instanceObject) => wasmSIMD(instanceObject),\n (instanceObject) => wasmNonSIMD(instanceObject),\n);\n\nexport default loadWasm;\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2022 Proton AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport crypto from '../crypto';\nimport enums from '../enums';\n\n/**\n * Implementation of the Padding Packet\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:\n * Padding Packet\n */\nclass PaddingPacket {\n static get tag() {\n return enums.packet.padding;\n }\n\n constructor() {\n this.padding = null;\n }\n\n /**\n * Read a padding packet\n * @param {Uint8Array | ReadableStream} bytes\n */\n read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars\n // Padding packets are ignored, so this function is never called.\n }\n\n /**\n * Write the padding packet\n * @returns {Uint8Array} The padding packet.\n */\n write() {\n return this.padding;\n }\n\n /**\n * Create random padding.\n * @param {Number} length - The length of padding to be generated.\n * @throws {Error} if padding generation was not successful\n * @async\n */\n async createPadding(length) {\n this.padding = await crypto.random.getRandomBytes(length);\n }\n}\n\nexport default PaddingPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","Object","setPrototypeOf","this","prototype","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","isStream","globalThis","ReadableStream","isPrototypeOf","_read","_readableState","Error","isUint8Array","Uint8Array","concatUint8Array","arrays","length","totalLength","i","result","pos","forEach","element","set","undefined","read","async","value","done","readToEnd","join","slice","clone","then","push","write","chunk","close","abort","reason","process","versions","doneReadingSet","WeakSet","externalBuffer","Reader","reader","bind","_releaseLock","_cancel","cancel","doneReading","has","add","e","toStream","start","controller","enqueue","toArrayStream","concat","list","some","map","transform","transformWithCancel","all","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","options","transformStream","TransformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","pull","highWaterMark","WritableStream","error","finish","output","data","result1","result2","flush","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","destroy","arrayStream","shift","readLine","returnVal","buffer","streams.concat","lineEndIndex","indexOf","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","byteOffset","byteLength","filter","byValue","enums","curve","nistP256","p256","nistP384","p384","nistP521","p521","secp256k1","ed25519Legacy","ed25519","curve25519Legacy","curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","argon2","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","aedh","aedsa","x25519","x448","ed448","symmetric","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","sha3_256","sha3_512","webHash","aead","eax","ocb","gcm","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","padding","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuerKeyID","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","preferredCipherSuites","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","seipdv2","type","config","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","aeadProtect","parseAEADEncryptedV4KeysAsLegacy","preferredAEADAlgorithm","aeadChunkSizeByte","v6Keys","enableParsingV5Entities","s2kType","s2kIterationCountByte","s2kArgon2Params","passes","parallelism","memoryExponent","allowUnauthenticatedMessages","allowUnauthenticatedStream","minRSABits","passwordCollisionCheck","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","allowMissingKeyFlags","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","nonDeterministicSignaturesViaNotation","useEllipticFallback","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","debugMode","env","NODE_ENV","util","isString","String","nodeRequire","stream.isUint8Array","stream.isStream","getNobleCurve","publicKeyAlgo","curveName","defaultConfig","nobleCurves","noble_curves","readNumber","n","writeNumber","b","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","readExactSubarray","leftPad","padded","offset","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","hex","k","parseInt","uint8ArrayToHex","hexAlphabet","s","v","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","printDebug","log","printDebugError","x","r","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","webCrypto","crypto","subtle","getNodeCrypto","webcrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","sub","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","a","selectUint8","isAES","cipherAlgo","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","getType","header","match","addheader","customComment","getCheckSum","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","base64.encode","from","toString","btoa","atob","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","removeChecksum","body","lastEquals","lastIndexOf","unarmor","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","stream.isArrayStream","stream.readToEnd","messageType","partIndex","partTotal","emitChecksum","maybeBodyClone","stream.passiveClone","getLegacyCipher","algo","legacyCiphers","legacy_ciphers","cipher","getCipherBlockSize","getCipherKeySize","getCipherParams","keySize","blockSize","md5cycle","c","d","ff","gg","hh","ii","add32","cmn","q","md5blk","md5blks","hex_chr","rhex","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","update","digest","nobleHash","nobleHashName","webCryptoHashName","getNobleHash","nobleHashes","noble_hashes","hashInstance","create","hash$1","entree","state","substring","tail","md51","getHashByteLength","isBytes","lengths","exists","instance","checkFinished","destroyed","finished","out","min","outputLen","u8","arr","u32","createView","toBytes","utf8ToBytes","copyBytes","equalBytes","diff","wrapCipher","params","assign","setBigUint64","view","isLE","_32n","BigInt","_u32_max","wh","Number","wl","setUint32","isAligned32","clean","fill","BLOCK_SIZE","ZEROS16","ZEROS32","swapLE","GHASH","expectedLength","blockLen","s0","s1","s2","s3","abytes","kView","k0","getUint32","k1","k2","k3","doubles","W","estimateWindow","windows","windowSize","items","w","d0","d1","d2","d3","_updateBlock","o0","o1","o2","o3","mask","num","bytePos","bitPos","bit","e0","e1","e2","e3","aexists","b32","blocks","left","elm","digestInto","aoutput","o32","res","Polyval","ghKey","reverse","hiBit","carry","_toGHASHKey","wrapConstructorWithKey","hashCons","hashC","msg","tmp","ghash","EMPTY_BLOCK","POLY","mul2","mul","sbox","box","invSbox","_","rotr32_8","rotl32_8","byteSwap","word","genTtable","T0","T1","T2","T3","T01","T23","sbox2","Uint16Array","idx","tableEncoding","tableDecoding","xPowers","p","expandKeyLE","len","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","encrypt","rounds","t0","t1","t2","t3","decrypt","getDst","dst","ctrCounter","nonce","src","srcLen","ctr","c32","src32","dst32","ctr32","ctrPos","ctrNum","nonceLength","processCtr","plaintext","ciphertext","cbc","iv","opts","pcks5","disablePadding","o","_out","outLen","remaining","validateBlockEncrypt","_iv","n32","tmp32","paddingByte","padPCKS","validateBlockDecrypt","ps0","ps1","ps2","ps3","lastByte","validatePCKS","cfb","processCfb","isEncrypt","next32","tagLength","AAD","_computeTag","authKey","tagMask","aadLength","h","computeTag","deriveKeys","counter","nonceLen","g","passedTag","isBytes32","encryptBlock","block","decryptBlock","AESW","kek","a0","a1","chunks","AESKW_IV","aeskw","sum","pad","concatBytes","unsafe","knownAlgos","getCiphers","nodeAlgos","WebCryptoEncryptor","prevBlock","nextBlock","zeroBlock","isSupported","importKey","_runCBC","nonZeroIV","mode","keyRef","encryptChunk","missing","added","leftover","toEncrypt","encryptedBlocks","xorMut","encryptedBlock","curBlock","clearSensitiveData","ct","NobleStreamProcessor","forEncryption","nobleAesHelpers","getUint32Array","_runCFB","processChunk","toProcess","processedBlocks","processedBlock","aLength","algoName","decipherObj","createDecipheriv","nodeDecrypt","nobleAesCfb","aesDecrypt","cipherfn","block_size","blockp","decblock","pt","cipherObj","createCipheriv","nodeEncrypt","aesEncrypt","blockc","encblock","blockLength","rightXORMut","CMAC","CBC","padding2","err","nobleAesCbc","ivLength","zero","one","two","OMAC","cmac","CTR","en","final","nobleAesCtr","EAX","omac","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","T","xor","OCB","maxNtz","aes","encipher","decipher","crypt","m","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","checksum","xorInput","$","cipherInput","mask_x","mask_$","constructKeyVariables","crypted","ALGO","GCM","setAAD","getAuthTag","de","setAuthTag","_key","webcryptoEmptyMessagesUnsupported","userAgent","nobleAesGcm","additionalData","_0n","_1n","uint8ArrayToBigInt","mod","reduced","modExp","exp","lsb","abs","modInv","gcd","aInput","bInput","y","xPrev","yPrev","aNegated","bNegated","_egcd","bigIntToNumber","number","MAX_SAFE_INTEGER","getBit","bitLength","bitlen","_8n","bigIntToUint8Array","endian","rawLength","getRandomBytes","getRandomValues","getRandomBigInteger","modulus","randomProbablePrime","_30n","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","n1","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","count","randomBytes","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","hashed","emLen","hashPrefix","tLen","EM","privateToJWK","u","pNum","qNum","dNum","dq","dp","kty","qi","ext","publicToJWK","jwkToPrivate","jwk","format","constants","RSA_PKCS1_PADDING","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","publicEncrypt","bnEncrypt","keyGenOpt","modulusLength","publicExponent","keyPair","generateKey","exportKey","publicKeyEncoding","privateKeyEncoding","generateKeyPair","jwkPrivateKey","phi","hashAlgo","hashName","sign","webSign","createSign","nodeSign","bnSign","_2n","rde","verify","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","c1","c2","pSize","threshold","nacl","gf","init","Float64Array","randombytes","_9","gf0","gf1","_121665","D","D2","X","Y","I","ts64","l","crypto_verify_32","xi","yi","vn","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","A","Z","M","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","z","f","x32","x16","crypto_scalarmult_base","K","crypto_hashblocks_hl","hl","bh0","bh1","bh2","bh3","bh4","bh5","bh6","bh7","bl0","bl1","bl2","bl3","bl4","bl5","bl6","bl7","th","tl","Int32Array","ah0","ah1","ah2","ah3","ah4","ah5","ah6","ah7","al0","al1","al2","al3","al4","al5","al6","al7","crypto_hash","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","reduce","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","TypeError","scalarMult","crypto_box_keypair","fromSecretKey","signedMsg","sm","smlen","crypto_sign","detached","sig","crypto_sign_open","fromSeed","seed","setPRNG","cleanup","knownOIDs","OID","oid","toHex","getName","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callback","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","lengthByte","nextPacket","UnsupportedError","captureStackTrace","UnknownPacketError","UnparseablePacket","rawContent","generate","webCryptoKey","getPayloadSize","utils","randomPrivateKey","getPublicKey","getPreferredHashAlgo","privateKeyToJWK","RS","publicKeyToJWK","crv","wrap","dataToWrap","wrappingKey","keyToWrap","wrapped","wrapKey","nobleAesKW","unwrap","wrappedData","unwrapped","unwrapKey","computeHKDF","inputKey","salt","info","importedKey","deriveBits","HKDF_INFO","generateEphemeralEncryptionMaterial","recipientA","ephemeralSecretKey","sharedSecret","assertNonZeroArray","ephemeralPublicKey","getSharedSecret","recomputeSharedSecret","acc","wrappedKey","hkdfInput","aesKW.unwrap","encryptionKey","aesKW.wrap","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","wireFormatLeadingByte","CurveWithOID","oidOrName","genKeyPair","namedCurve","jwkToRawPublic","webGenKeyPair","jsGenKeyPair","createECDH","generateKeys","getPrivateKey","nodeGenKeyPair","ecdhXGenerate","eddsaGenerate","validateStandardParams","Q","supportedCurves","dG","checkPublicPointEnconding","V","pointSize","nobleCurve","bufX","bufY","rawPublicToJWK","ecKeyUtils","nodeBuffer","derPrivateKey","generateDer","dsaEncoding","lowS","tryFallbackVerificationForOldBug","jsVerify","verified","derPublicKey","eddsaSign","eddsaVerify","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","ecdhXGenerateEphemeralEncryptionMaterial","recipient","public","webPublicEphemeralKey","jsPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","genPrivateEphemeralKey","ecdhXRecomputeSharedSecret","secret","webPrivateEphemeralKey","jsPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","C","pkcs5.decode","pkcs5.encode","xr","qSize","u1","u2","rsa","elliptic","signatureParams","rsSize","eddsa","publicKeyParams","privateKeyParams","publicParams","curveSize","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","fromObject","algorithm","followLength","checkSupportedCurve","getCurvePayloadSize","ecdhX","privateParams","prefixrandom","repeat","ECDHSymkey","sessionKeyParams","keyAlgo","symmetricAlgo","algosWithNativeRepresentation","orderedParams","keys","validateParams","algoModule","random","pkcs1","pkcs5","aesKW","Argon2OutOfMemoryError","loadArgonWasmModule","argon2Promise","Argon2S2K","encodedM","generateSalt","produceKey","passphrase","decodedM","index$1","default","version","password","memorySize","GenericS2K","getCount","numBytes","rlength","prefixlen","toHash","datalen","allowedS2KTypesForEncryption","newS2KFromType","newS2KFromConfig","u16","fleb","fdeb","clim","freb","eb","_a","fl","revfl","_b","fd","revfd","rev","hMap","cd","mb","co","le","rvb","sv","r_1","flt","fdt","flm","flrm","fdm","fdrm","bits16","shft","slc","BYTES_PER_ELEMENT","ec","ind","nt","code","wbits","wbits16","hTree","et","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","cl","cli","cln","cls","clen","cf","wfblk","dat","wblk","syms","lf","df","li","bl","dlt","mlb","ddt","mdb","_c","lclt","nlc","_d","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","deo","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","head","bs1_1","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","level","mem","Deflate","cb","ondata","Inflate","bts","sl","noBuf","noSt","cbuf","nbuf","bt","lbt","dbt","tbts","hLit","hcLen","ldt","clt","clb","clbmsk","clm","lt","lms","dms","lpos","sym","dsym","inflt","Zlib","raw","lv","zlh","wbytes","Unzlib","td","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","KeyID","equals","keyID","matchWildcard","isWildcard","isNull","mapToHex","fromID","wildcard","SALT_NOTATION_NAME","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","unknownSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","saltLength","signatureMaterial","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","saltLengthForHash","saltValue","humanReadable","critical","writeHashedSubPackets","stream.slice","stream.clone","writeSubPacket","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLengthBytes","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","fromSignaturePacket","signaturePacket","isLast","onePassSig","flags","args","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","fromBinary","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","chunkSize","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","compressionFn","compress_fns","compressionStreamInstantiator","ZlibStreamedConstructor","inputData","zlibStream","processedData","compressorOrDecompressor","pipeThrough","inputReader","bzip2Decompress","bunzipDecode","getCompressionStreamInstantiators","compressionFormat","compressor","CompressionStream","decompressor","DecompressionStream","SymEncryptedIntegrityProtectedDataPacket","aeadAlgorithm","seip","cipherAlgorithm","chunkSizeByte","encrypted","sessionKeyAlgorithm","runAEAD","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","isSEIPDv2","isAEADP","getAEADMode","tagLengthIfDecrypting","tagLengthIfEncrypting","chunkIndexSizeIfAEADEP","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","ivView","latestPromise","cryptedBytes","queuedBytes","derived","modeInstance","size","stream.pipe","finalChunk","cryptedPromise","setInt32","desiredSize","AEADEncryptedDataPacket","PublicKeyEncryptedSessionKeyPacket","publicKeyID","publicKeyVersion","publicKeyFingerprint","sessionKey","encryptionKeyPacket","anonymousRecipient","pkesk","versionAndFingerprintLength","fingerprintLength","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","hasEncryptedAlgo","sessionKeyData","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","s2kLen","fieldsLen","generateSessionKey","PublicKeyPacket","expirationTimeV3","fromSecretKeyPacket","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","versionOctet","lengthOctets","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","PublicSubkeyPacket","fromSecretSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","isLegacyAEAD","usedModernAEAD","startOfSecretKeyData","unparseableKeyMaterial","cleartext","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","serializedPacketTag","produceEncryptionKey","associateData","cleartextWithHash","validate","validParams","generateParams","keyVersion","aeadMode","derivedKey","UserIDPacket","email","comment","components","matches","exec","groups","trim","otherUserID","SecretSubkeyPacket","Signature","packetlist","getSigningKeyIDs","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","recipientKeys","signingKeyPacket","recipientUserIDs","targetKeys","targetUserIDs","defaultAlgo","preferredSenderAlgo","supportedAlgosPerTarget","getPrimarySelfSignature","supportedAlgosMap","Map","supportedAlgos","supportedAlgo","isSupportedHashAlgo","getStrongestSupportedHashAlgo","strongestHashAlgo","algoA","algoB","preferredCurveAlgo","getPreferredCurveHashAlgo","preferredSenderAlgoIsSupported","preferredSenderAlgoStrongerThanCurveAlgo","strongestSupportedAlgo","mergeSignatures","source","dest","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","isHardRevocation","sanitizeKeyOptions","subkeyDefaults","validateSigningKeyPacket","validateEncryptionKeyPacket","validateDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","certify","signingKeys","isPrivate","signingKey","getSigningKey","isRevoked","certificate","verifyCertificate","verificationKeys","issuerKeys","getKeys","verifyAllCertifications","certifications","certification","valid","selfCertification","sourceUser","srcSelfSig","srcRevSig","revoke","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","helper.checkKeyRequirements","helper.validateSigningKeyPacket","getEncryptionKey","helper.validateEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","getPrimaryUser","primaryUser","B","pop","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","getRevocationCertificate","applyRevocationCertificate","revocationCertificate","signPrimaryUser","privateKeys","userSign","signAllUsers","verifyPrimaryUser","verifyAllUsers","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","pubSubkeyPacket","getDecryptionKeys","helper.validateDecryptionKeyPacket","Boolean","addSubkey","defaultOptions","getDefaultSubkeyType","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","getKeySignatureProperties","symmetricAlgorithms","aeadAlgorithms","flatMap","symmetricAlgorithm","userIDs","userIDPacket","subkeyOptions","subkeySignaturePacket","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","symEncryptedPacketlist","symEncryptedPacket","expectedSymmetricAlgorithm","sessionKeyObjects","decryptSessionKeys","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgo","selfSigs","selfSig","defaultCipherSuite","desiredCipherSuites","desiredCipherSuite","cipherSuite","defaultSymAlgo","desiredSymAlgo","getPreferredCipherSuite","symmetricAlgoName","aeadAlgoName","maybeKey","encryptionKeyIDs","aeadAlgorithmName","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","signingUserIDs","literalDataPacket","signaturePackets","createSignaturePackets","onePassSignaturePackets","signDetached","recipientKeyIDs","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","appendSignature","detachedSignature","trailingPacket","signingUserID","existingSigPacketlist","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","CleartextMessage","newSignature","emitHeaderAndChecksum","checkMessage","checkCleartextOrMessage","checkOutputMessageFormat","defaultConfigPropsCount","checkConfig","inputConfigProps","inputProp","toArray","convertStream","linkStreams","formatObject","object","isSafeInteger","rotr","rotl","byteSwap32","Hash","_cloneInto","wrapConstructor","bytesLength","Chi","Maj","HashMD","padOffset","take","dataView","roundClean","oview","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","E","F","G","H","W15","W2","SHA224","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","hmac","abool","title","hexes","padStart","bytesToHex","numberToHexUnpadded","hexToNumber","asciis","_0","_A","_F","_f","asciiToBase16","char","hexToBytes","al","ai","hi","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","isPosBig","inRange","aInRange","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reset","reseed","gen","pred","validatorFns","bigint","val","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","memoized","WeakMap","arg","_3n","_4n","_5n","pow","pow2","invert","FpSqrt","P","p1div4","root","eql","sqr","nv","ONE","legendreC","Q1div2","neg","ZERO","ge","tonelliShanks","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","freeze","MASK","is0","isOdd","lhs","rhs","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","constTimeNegate","condition","negate","validateW","unsafeLadder","precomputeWindow","points","base","window","precomputes","BASE","maxNumber","shiftBy","offset1","offset2","cond1","cond2","wNAFCached","comp","setWindowSize","delete","pippenger","scalars","buckets","lastBits","scalar","resI","sumI","validateBasic","Gx","Gy","validateSigVerOpts","prehash","b2n","h2b","ut","DER","Err","_tlv","dataLen","ut.numberToHexUnpadded","lenLen","first","lengthBytes","_int","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","point","_isCompressed","toAffine","ut.concatBytes","weierstrassEquation","x2","x3","normPrivateKeyToScalar","N","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","ut.aInRange","assertPrjPoint","Point","toAffineMemo","iz","px","py","pz","ax","ay","zz","assertValidMemo","right","fromAffine","normalizeZ","toInv","fromHex","assertValidity","fromPrivateKey","multiply","msm","_setWindowSize","wnaf","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","subtract","multiplyUnsafe","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","cofactor","toRawBytes","isCompressed","_bits","ProjectivePoint","isWithinCurveOrder","ut.inRange","weierstrass","curveDef","bits2int","bits2int_modN","validateOpts","compressedLen","uncompressedLen","modN","CURVE_ORDER","invN","mod.invert","cat","y2","sqrtError","suffix","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","R","ir","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","mod.getMinHashLength","fieldLen","minLen","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","privateA","publicB","privKey","ut.createHmacDrbg","drbg","sg","_sig","derError","is","getHash","msgs","createCurve","defHash","U32_MASK64","fromBig","Ah","Al","rotlSH","rotlSL","rotlBH","rotlBL","u64","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","SHA384","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_7n","_256n","_0x71n","round","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","enableXOF","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","writeInto","bufferOut","xofInto","xof","shake256","wrapXOFConstructorWithOpts","dkLen","genShake","VERIFY_DEFAULT","zip215","twistedEdwards","adjustScalarBytes","domain","uvRatio","mapToCurve","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","isSmallOrder","normed","ut.bytesToNumberLE","isXOdd","isLastByteOdd","getExtendedPublicKey","ut.numberToBytesLE","modN_LE","pointBytes","hashDomainToScalar","context","verifyOpts","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","swap","x_2","x_3","dummy","a24","encodeUCoordinate","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","shake256_114","ed448P","_11n","_22n","_44n","_88n","_223n","ed448_pow_Pminus3div4","b22","b44","b88","b176","b220","b222","b223","ED448_DEF","u2v","u3v","u5v3","secp256k1P","secp256k1N","divNearest","_6n","_23n","a2","POW_2_128","des","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","looping","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","f1","f2","f3","scheduleA","scheduleB","sBox","inn","ki","half","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","dataL","dataR","parray","vector","off","ret","_decryptBlock","jj","kk","BlowFish","TwoFish","SHA1_IV","SHA1_W","SHA1","Rho","Id","Pi","idxL","idxR","shiftsL","shiftsR","Kl","Kr","group","R_BUF","RIPEMD160","h0","h1","h2","h3","h4","ar","br","cr","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","ripemd160","ADD64","INC64","ix","iy","xor0","xor1","BLAKE2B_IV32","SIGMA","f0","i16","Blake2b","outlen","personal","BLOCKBYTES","OUTBYTES_MAX","params32","prealloc","TYPE","VERSION","TAGBYTES_MAX","TAGBYTES_MIN","SALTBYTES_MAX","SALTBYTES_MIN","passwordBYTES_MAX","passwordBYTES_MIN","MEMBYTES_MAX","ADBYTES_MAX","SECRETBYTES_MAX","ARGON2_BLOCK_SIZE","ARGON2_PREHASH_DIGEST_LENGTH","LE32","LE64","H_","V1_in","blake2b","V_r1","XOR","wasmContext","xs","ys","refs","gZ","G2","makePRNG","pass","lane","m_","totalPasses","segmentLength","segmentOffset","prngTmp","g2","ZERO1024","prngR","KB","WASM_PAGE_SIZE","argon2id","memory","wasmInstance","ad","assertLength","lanes","wasmG","wasmG2","wasmXOR","getLZ","wasmLZ","exports","wasmRefs","wasmFn","requiredMemory","grow","lz","newBlock","blockMemory","allocatedMemory","H0","ZERO32","concatArrays","outputBuffer","getH0","initBlock","isDataIndependent","PRNG","J1J2","next","isSIMDSupported","setupWasm","getSIMD","getNonSIMD","WebAssembly","Memory","initial","maximum","wasmModule","importObject","loaded","wasmLoader","instanceObject","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","seek","n_bit","n_byte","pi","bufToHex","bitreader","Stream","Stream$1","bufOffset","new_pos","writeByte","_byte","crc32Lookup","crc32","getCRC","updateCRC","updateCRCRun","require$$0","require$$1","CRC32","require$$2","mtf","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","status","optDetail","errorCode","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","maxLen","MAX_HUFCODE_BITS","permute","limit","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","lib","multistream","bz","targetStreamCRC","decodeBlock","writeCopies","table","delegate","position","assert","createPadding","rest","unknownOptions","streamType","literalDataPacketlist","expectSigned","publicKeys","clonedPrivateKey","passphrases","encryptionUserIDs","signatureNotations","senderAlgoSupport","recipientPrefs","getPreferredCompressionAlgo","checkBinary","checkString","helper.generateSecretKey","cleartextMessage","checkHashAlgos","hashAlgos","check","hashHeader","parsedHashIDs","armoredKey","binaryKey","keyIndex","armoredKeys","binaryKeys","newKey","armoredMessage","binaryMessage","firstPrivateKeyList","oneKeyList","armoredSignature","binarySignature","reformattedKey","sanitize","reformat","revokedKey"],"mappings":";6bAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxB,WAAAC,GACEC,QAEAC,OAAOC,eAAeC,KAAMN,EAAYO,WAExCD,KAAKX,GAAsB,IAAIa,SAAQ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OAAEA,KAAWirF,IAG/I,GAF0Cj6B,GAA1ChxD,EAAS,IAAKqD,KAAkBrD,IAChC6wD,GAAwBxxD,GAAUilD,EAAmB6M,GAAQ7M,GACzD2mC,EAAKK,WAAY,MAAUj+F,MAAM,iGACrC,MAAM69F,EAAiBt/F,OAAO02C,KAAK2oD,GAAO,GAAIC,EAAex9F,OAAS,EAAG,MAAUL,MAAM,mBAAmB69F,EAAe18F,KAAK,OAEhI,GAAI6Q,aAAmBoxD,IAA+B,WAAXhmC,EAAqB,MAAUp9B,MAAM,iDAChF,GAAIgS,aAAmBoxD,IAAoB91D,EAAW,MAAUtN,MAAM,6CAEtE,IACE,MAAMQ,EAAS,CAAE,EAQjB,GANEA,EAAOiyD,WADLnlD,QACwB0E,EAAQ0wD,eAAep1D,EAAW2pD,EAAkB7V,EAAMzuC,SAE1DX,EAAQmtB,OAAO83B,EAAkB7V,EAAMzuC,GAEnEnS,EAAO8E,KAAkB,WAAX83B,EAAsBprB,EAAQouD,iBAAmBpuD,EAAQuvC,UACnEvvC,EAAQq1C,aAAe/5C,GAAW02D,GAAYxjE,EAAQwR,GACtDgsF,EAAc,CAChB,GAAiC,IAA7Bx9F,EAAOiyD,WAAWpyD,OACpB,MAAUL,MAAM,yBAElBQ,EAAO8E,KAAOkU,EAAc,CAC1BhZ,EAAO8E,KACPo/C,GAAiB3jD,gBACTwU,EAAKkH,WAAWjc,EAAOiyD,WAAWrvD,KAAIkmC,GAAOA,EAAI0H,WAAU,KAG3E,CAEI,OADAxwC,EAAO8E,WAAay+D,GAAcvjE,EAAO8E,MAClC9E,CACR,CAAC,MAAOs0B,GACP,MAAMvf,EAAK6G,UAAU,iCAAkC0Y,EAC3D,CACA","x_google_ignoreList":[0,1,2,3,12,13,14,15,28,29,52,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,111,112,114,115,116,117,118,119,120,121]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/openpgp.min.mjs b/app/node_modules/openpgp/dist/openpgp.min.mjs index e8efc8982..bd7693ed4 100644 --- a/app/node_modules/openpgp/dist/openpgp.min.mjs +++ b/app/node_modules/openpgp/dist/openpgp.min.mjs @@ -1,17 +1,16 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -const e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=Symbol("doneWritingPromise"),r=Symbol("doneWritingResolve"),i=Symbol("doneWritingReject"),n=Symbol("readingIndex");class a extends Array{constructor(){super(),this[t]=new Promise(((e,t)=>{this[r]=e,this[i]=t})),this[t].catch((()=>{}))}}function s(e){return e&&e.getReader&&Array.isArray(e)}function o(e){if(!s(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}a.prototype.getReader=function(){return void 0===this[n]&&(this[n]=0),{read:async()=>(await this[t],this[n]===this.length?{value:void 0,done:!0}:{value:this[this[n]++],done:!1})}},a.prototype.readToEnd=async function(e){await this[t];const r=e(this.slice(this[n]));return this.length=0,r},a.prototype.clone=function(){const e=new a;return e[t]=this[t].then((()=>{e.push(...this)})),e},o.prototype.write=async function(e){this.stream.push(e)},o.prototype.close=async function(){this.stream[r]()},o.prototype.abort=async function(e){return this.stream[i](e),e},o.prototype.releaseLock=function(){};const c="object"==typeof e.process&&"object"==typeof e.process.versions,u=c&&void 0;function h(t){return s(t)?"array":e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t)?"web":k&&k.prototype.isPrototypeOf(t)?"ponyfill":u&&u.prototype.isPrototypeOf(t)?"node":!(!t||!t.getReader)&&"web-like"}function d(e){return Uint8Array.prototype.isPrototypeOf(e)}function f(e){if(1===e.length)return e[0];let t=0;for(let r=0;r{t||(l.isBuffer(i)&&(i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),r.enqueue(i),e.pause())})),e.on("end",(()=>{t||r.close()})),e.on("error",(e=>r.error(e)))},pull(){e.resume()},cancel(r){t=!0,e.destroy(r)}})};class e extends p{constructor(e,t){super(t),this._reader=C(e)}async _read(e){try{for(;;){const{done:e,value:t}=await this._reader.read();if(e){this.push(null);break}if(!this.push(t))break}}catch(e){this.destroy(e)}}async _destroy(e,t){this._reader.cancel(e).then(t,t)}}b=function(t,r){return new e(t,r)}}const m=new WeakSet,g=Symbol("externalBuffer");function w(e){if(this.stream=e,e[g]&&(this[g]=e[g].slice()),s(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=async()=>{})}let t=h(e);if("node"===t&&(e=y(e)),t){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let r=!1;this._read=async()=>r||m.has(e)?{value:void 0,done:!0}:(r=!0,{value:e,done:!1}),this._releaseLock=()=>{if(r)try{m.add(e)}catch(e){}}}w.prototype.read=async function(){if(this[g]&&this[g].length){return{done:!1,value:this[g].shift()}}return this._read()},w.prototype.releaseLock=function(){this[g]&&(this.stream[g]=this[g]),this._releaseLock()},w.prototype.cancel=function(e){return this._cancel(e)},w.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:i}=await this.read();if(i+="",r)return t.length?K(t):void 0;const n=i.indexOf("\n")+1;n&&(e=K(t.concat(i.substr(0,n))),t=[]),n!==i.length&&t.push(i.substr(n))}return this.unshift(...t),e},w.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(L(t,1)),r},w.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:i,value:n}=await this.read();if(i)return t.length?K(t):void 0;if(t.push(n),r+=n.length,r>=e){const r=K(t);return this.unshift(L(r,e)),L(r,0,e)}}},w.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},w.prototype.unshift=function(...e){this[g]||(this[g]=[]),1===e.length&&d(e[0])&&this[g].length&&e[0].length&&this[g][0].byteOffset>=e[0].length?this[g][0]=new Uint8Array(this[g][0].buffer,this[g][0].byteOffset-e[0].length,this[g][0].byteLength+e[0].length):this[g].unshift(...e.filter((e=>e&&e.length)))},w.prototype.readToEnd=async function(e=K){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};let v,_,{ReadableStream:k,WritableStream:A,TransformStream:S}=e;async function E(){if(S)return;const[t,r]=await Promise.all([Promise.resolve().then((function(){return zp})),Promise.resolve().then((function(){return ny}))]);({ReadableStream:k,WritableStream:A,TransformStream:S}=t);const{createReadableStreamWrapper:i}=r;e.ReadableStream&&k!==e.ReadableStream&&(v=i(k),_=i(e.ReadableStream))}const P=c&&void 0;function x(e){let t=h(e);return"node"===t?y(e):"web"===t&&v?v(e):t?e:new k({start(t){t.enqueue(e),t.close()}})}function M(e){if(h(e))return e;const t=new a;return(async()=>{const r=D(t);await r.write(e),await r.close()})(),t}function K(e){return e.some((e=>h(e)&&!s(e)))?function(e){e=e.map(x);const t=I((async function(e){await Promise.all(i.map((t=>j(t,e))))}));let r=Promise.resolve();const i=e.map(((i,n)=>T(i,((i,a)=>(r=r.then((()=>U(i,t.writable,{preventClose:n!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>s(e)))?function(e){const t=new a;let r=Promise.resolve();return e.forEach(((i,n)=>(r=r.then((()=>U(i,t,{preventClose:n!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):P&&P.isBuffer(e[0])?P.concat(e):f(e)}function C(e){return new w(e)}function D(e){return new o(e)}async function U(e,t,{preventClose:r=!1,preventAbort:i=!1,preventCancel:n=!1}={}){if(h(e)&&!s(e)){e=x(e);try{if(e[g]){const r=D(t);for(let t=0;t{t=e,r=i})),t=null,r=null)},close:i.close.bind(i),abort:i.error.bind(i)})}}function B(e,t=(()=>{}),r=(()=>{})){if(s(e)){const i=new a;return(async()=>{const n=D(i);try{const i=await N(e),a=t(i),s=r();let o;o=void 0!==a&&void 0!==s?K([a,s]):void 0!==a?a:s,await n.write(o),await n.close()}catch(e){await n.abort(e)}})(),i}if(h(e))return R(e,{async transform(e,r){try{const i=await t(e);void 0!==i&&r.enqueue(i)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const i=t(e),n=r();return void 0!==i&&void 0!==n?K([i,n]):void 0!==i?i:n}function T(e,t){if(h(e)&&!s(e)){let r;const i=new S({start(e){r=e}}),n=U(e,i.writable),a=I((async function(e){r.error(e),await n,await new Promise(setTimeout)}));return t(i.readable,a.writable),a.readable}e=M(e);const r=new a;return t(e,r),r}function z(e,t){let r;const i=T(e,((e,n)=>{const a=C(e);a.remainder=()=>(a.releaseLock(),U(e,n),i),r=t(a)}));return r}function q(e){if(s(e))return e.clone();if(h(e)){const t=function(e){if(s(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(h(e)){const t=x(e).tee();return t[0][g]=t[1][g]=e[g],t}return[L(e),L(e)]}(e);return O(e,t[0]),t[1]}return L(e)}function F(e){return s(e)?q(e):h(e)?new k({start(t){const r=T(e,(async(e,r)=>{const i=C(e),n=D(r);try{for(;;){await n.ready;const{done:e,value:r}=await i.read();if(e){try{t.close()}catch(e){}return void await n.close()}try{t.enqueue(r)}catch(e){}await n.write(r)}}catch(e){t.error(e),await n.abort(e)}}));O(e,r)}}):L(e)}function O(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,i])=>{"constructor"!==r&&(i.value?i.value=i.value.bind(t):i.get=i.get.bind(t),Object.defineProperty(e,r,i))}))}function L(e,t=0,r=1/0){if(s(e))throw Error("Not implemented");if(h(e)){if(t>=0&&r>=0){let i=0;return R(e,{transform(e,n){i=t&&n.enqueue(L(e,Math.max(t-i,0),r-i)),i+=e.length):n.terminate()}})}if(t<0&&(r<0||r===1/0)){let i=[];return B(e,(e=>{e.length>=-t?i=[e]:i.push(e)}),(()=>L(K(i),t,r)))}if(0===t&&r<0){let i;return B(e,(e=>{const n=i?K([i,e]):e;if(n.length>=-r)return i=L(n,r),L(n,t,r);i=n}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),H((async()=>L(await N(e),t,r)))}return e[g]&&(e=K(e[g].concat([e]))),!d(e)||P&&P.isBuffer(e)?e.slice(t,r):(r===1/0&&(r=e.length),e.subarray(t,r))}async function N(e,t=K){return s(e)?e.readToEnd(t):h(e)?C(e).readToEnd(t):e}async function j(e,t){if(h(e)){if(e.cancel)return e.cancel(t);if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function H(e){const t=new a;return(async()=>{const r=D(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}class W{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");if(e instanceof Uint8Array){const t=e,r=Array(t.length);for(let e=0;eBigInt(0);){const e=r&BigInt(1);r>>=BigInt(1);const a=n*i%t.value;n=e?a:n,i=i*i%t.value}return new W(n)}modInv(e){const{gcd:t,x:r}=this._egcd(e);if(!t.isOne())throw Error("Inverse does not exist");return r.add(e).mod(e)}_egcd(e){let t=BigInt(0),r=BigInt(1),i=BigInt(1),n=BigInt(0),a=this.value;for(e=e.value;e!==BigInt(0);){const s=a/e;let o=t;t=i-s*t,i=o,o=r,r=n-s*r,n=o,o=e,e=a%e,a=o}return{x:new W(i),y:new W(n),gcd:new W(a)}}gcd(e){let t=this.value;for(e=e.value;e!==BigInt(0);){const r=e;e=t%e,t=r}return new W(t)}ileftShift(e){return this.value<<=e.value,this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value>>=e.value,this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value===e.value}lt(e){return this.valuee.value}gte(e){return this.value>=e.value}isZero(){return this.value===BigInt(0)}isOne(){return this.value===BigInt(1)}isNegative(){return this.valueNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return e}getBit(e){return(this.value>>BigInt(e)&BigInt(1))===BigInt(0)?0:1}bitLength(){const e=new W(0),t=new W(1),r=new W(-1),i=this.isNegative()?r:e;let n=1;const a=this.clone();for(;!a.irightShift(t).equal(i);)n++;return n}byteLength(){const e=new W(0),t=new W(-1),r=this.isNegative()?t:e,i=new W(8);let n=1;const a=this.clone();for(;!a.irightShift(i).equal(r);)n++;return n}toUint8Array(e="be",t){let r=this.value.toString(16);r.length%2==1&&(r="0"+r);const i=r.length/2,n=new Uint8Array(t||i),a=t?t-i:0;let s=0;for(;s"undefined"!=typeof BigInt;const V=Symbol("byValue");var $={curve:{p256:"p256","P-256":"p256",secp256r1:"p256",prime256v1:"p256","1.2.840.10045.3.1.7":"p256","2a8648ce3d030107":"p256","2A8648CE3D030107":"p256",p384:"p384","P-384":"p384",secp384r1:"p384","1.3.132.0.34":"p384","2b81040022":"p384","2B81040022":"p384",p521:"p521","P-521":"p521",secp521r1:"p521","1.3.132.0.35":"p521","2b81040023":"p521","2B81040023":"p521",secp256k1:"secp256k1","1.3.132.0.10":"secp256k1","2b8104000a":"secp256k1","2B8104000A":"secp256k1",ed25519Legacy:"ed25519",ED25519:"ed25519",ed25519:"ed25519",Ed25519:"ed25519","1.3.6.1.4.1.11591.15.1":"ed25519","2b06010401da470f01":"ed25519","2B06010401DA470F01":"ed25519",curve25519Legacy:"curve25519",X25519:"curve25519",cv25519:"curve25519",curve25519:"curve25519",Curve25519:"curve25519","1.3.6.1.4.1.3029.1.5.1":"curve25519","2b060104019755010501":"curve25519","2B060104019755010501":"curve25519",brainpoolP256r1:"brainpoolP256r1","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1","2b2403030208010107":"brainpoolP256r1","2B2403030208010107":"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1","2b240303020801010b":"brainpoolP384r1","2B240303020801010B":"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1","2b240303020801010d":"brainpoolP512r1","2B240303020801010D":"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,ed25519Legacy:22,eddsa:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuer:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[V]||(e[V]=[],Object.entries(e).forEach((([t,r])=>{e[V][r]=t}))),void 0!==e[V][t])return e[V][t];throw Error("Invalid enum value.")}};const Z=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),X={isString:function(e){return"string"==typeof e||e instanceof String},isArray:function(e){return e instanceof Array},isUint8Array:d,isStream:h,readNumber:function(e){let t=0;for(let r=0;r>8*(t-i-1)&255;return r},readDate:function(e){const t=X.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return X.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return e.subarray(2,2+t)},leftPad(e,t){const r=new Uint8Array(t),i=t-e.length;return r.set(e,i),r},uint8ArrayToMPI:function(e){const t=X.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),i=new Uint8Array([(65280&t)>>8,255&t]);return X.concatUint8Array([i,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t=[],r=e.length;let i,n=0;for(;n{if(!X.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return B(e,r,(()=>r(new Uint8Array,!0)))},concat:K,concatUint8Array:f,equalsUint8Array:function(e,t){if(!X.isUint8Array(e)||!X.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let i=0;i>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){return void 0!==e&&e.crypto&&e.crypto.subtle},getBigInteger:async function(){if(G())return W;{const{default:e}=await Promise.resolve().then((function(){return uy}));return e}},getNodeCrypto:function(){},getNodeZlib:function(){},getNodeBuffer:function(){return{}.Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return(void 0).cpus().length},isEmailAddress:function(e){if(!X.isString(e))return!1;return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/.test(e)},canonicalizeEOL:function(e){let t=!1;return B(e,(e=>{let r;t&&(e=X.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const i=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&i.push(r);if(!i.length)return e;const n=new Uint8Array(e.length+i.length);let a=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return B(e,(e=>{let r;13===(e=t&&10!==e[0]?X.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let i=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const n=r-(10===e[r]?1:0);t&&e.copyWithin(i,t,n),i+=n-t}return e.subarray(0,i)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let i;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){i=e}}))),r(i)}))},selectUint8Array:function(e,t,r){const i=Math.max(t.length,r.length),n=new Uint8Array(i);let a=0;for(let i=0;i{t=X.concatUint8Array([t,e]);const r=[],i=Math.floor(t.length/45),n=45*i,a=Q(t.subarray(0,n));for(let e=0;et.length?Q(t)+"\n":""))}function te(e){let t="";return B(e,(e=>{t+=e;let r=0;const i=[" ","\t","\r","\n"];for(let e=0;e0&&(n-r)%4!=0;n--)i.includes(t[n])&&r--;const a=J(t.substr(0,n));return t=t.substr(n),a}),(()=>J(t)))}function re(e){return te(e.replace(/-/g,"+").replace(/_/g,"/"))}function ie(e,t){let r=ee(e).replace(/[\r\n]/g,"");return t&&(r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,"")),r}Y?(Q=e=>Y.from(e).toString("base64"),J=e=>{const t=Y.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(Q=e=>btoa(X.uint8ArrayToString(e)),J=e=>X.stringToUint8Array(atob(e)));var ne={preferredHashAlgorithm:$.hash.sha256,preferredSymmetricAlgorithm:$.symmetric.aes256,preferredCompressionAlgorithm:$.compression.uncompressed,deflateLevel:6,aeadProtect:!1,preferredAEADAlgorithm:$.aead.eax,aeadChunkSizeByte:12,v5Keys:!1,s2kIterationCountByte:224,allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,checksumRequired:!1,minRSABits:2047,passwordCollisionCheck:!1,revocationsExpire:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([$.symmetric.aes128,$.symmetric.aes192,$.symmetric.aes256]),minBytesForWebCrypto:1e3,ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 5.11.2",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],useIndutnyElliptic:!0,rejectHashAlgorithms:new Set([$.hash.md5,$.hash.ripemd]),rejectMessageHashAlgorithms:new Set([$.hash.md5,$.hash.ripemd,$.hash.sha1]),rejectPublicKeyAlgorithms:new Set([$.publicKey.elgamal,$.publicKey.dsa]),rejectCurves:new Set([$.curve.secp256k1])};function ae(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?$.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?$.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?$.armor.signed:/MESSAGE/.test(t[1])?$.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?$.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?$.armor.privateKey:/SIGNATURE/.test(t[1])?$.armor.signature:void 0}function se(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function oe(e){return ee(function(e){let t=13501623;return B(e,(e=>{const r=ue?Math.floor(e.length/4):0,i=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^ce[1][t>>16&255]^ce[2][t>>8&255]^ce[3][t>>0&255];for(let i=4*r;i>8^ce[0][255&t^e[i]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e))}const ce=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(0!=(8388608&t)?8801531:0);ce[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)ce[1][e]=ce[0][e]>>8^ce[0][255&ce[0][e]];for(let e=0;e<=255;e++)ce[2][e]=ce[1][e]>>8^ce[0][255&ce[1][e]];for(let e=0;e<=255;e++)ce[3][e]=ce[2][e]>>8^ce[0][255&ce[2][e]];const ue=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function he(e){for(let t=0;t=0&&i!==e.length-1&&(t=e.slice(0,i),r=e.slice(i+1).substr(0,4)),{body:t,checksum:r}}function fe(e,t=ne){return new Promise((async(r,i)=>{try{const n=/^-----[^-]+-----$/m,a=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const o=[];let c,u,h,d=o,f=[],l=te(T(e,(async(e,t)=>{const p=C(e);try{for(;;){let e=await p.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=X.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(c)u||2!==s||(n.test(e)?(f=f.join("\r\n"),u=!0,he(d),d=[],c=!1):f.push(e.replace(/^- /,"")));else if(n.test(e)&&i(Error("Mandatory blank line missing between armor headers and armor data")),a.test(e)){if(he(d),c=!0,u||2!==s){r({text:f,data:l,headers:o,type:s});break}}else d.push(e);else n.test(e)&&(s=ae(e))}}catch(e){return void i(e)}const y=D(t);try{for(;;){await y.ready;const{done:e,value:t}=await p.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await p.readToEnd();e.length||(e=""),e=r+e,e=X.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=de(t[0].slice(0,-1));h=i.checksum,await y.write(i.body);break}await y.write(r)}await y.ready,await y.close()}catch(e){await y.abort(e)}})));l=T(l,(async(e,r)=>{const i=N(oe(F(e)));i.catch((()=>{})),await U(e,r,{preventClose:!0});const n=D(r);try{const e=(await i).replace("\n","");if(h!==e&&(h||t.checksumRequired))throw Error("Ascii armor integrity check failed");await n.ready,await n.close()}catch(e){await n.abort(e)}}))}catch(e){i(e)}})).then((async e=>(s(e.data)&&(e.data=await N(e.data)),e)))}function le(e,t,r,i,n,a=ne){let s,o;e===$.armor.signed&&(s=t.text,o=t.hash,t=t.data);const c=F(t),u=[];switch(e){case $.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+i+"-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP MESSAGE, PART "+r+"/"+i+"-----\n");break;case $.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case $.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push("Hash: "+o+"\n\n"),u.push(s.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP SIGNATURE-----\n");break;case $.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP MESSAGE-----\n");break;case $.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case $.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case $.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(se(n,a)),u.push(ee(t)),u.push("=",oe(c)),u.push("-----END PGP SIGNATURE-----\n")}return X.concat(u)}class pe{constructor(){this.bytes=""}read(e){return this.bytes=X.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return X.stringToUint8Array(this.bytes)}toHex(){return X.uint8ArrayToHex(X.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new pe;return t.read(X.hexToUint8Array(e)),t}static wildcard(){const e=new pe;return e.read(new Uint8Array(8)),e}}var ye=function(){var e,t,r=!1;function i(r,i){var n=e[(t[r]+t[i])%255];return 0!==r&&0!==i||(n=0),n}var n,a,s,o,c=!1;function u(){function u(r){var i,n,a;for(n=a=function(r){var i=e[255-t[r]];return 0===r&&(i=0),i}(r),i=0;i<4;i++)a^=n=255&(n<<1|n>>>7);return a^=99}r||function(){e=[],t=[];var i,n,a=1;for(i=0;i<255;i++)e[i]=a,n=128&a,a<<=1,a&=255,128===n&&(a^=27),a^=e[i],t[e[i]]=i;e[255]=e[0],t[0]=0,r=!0}(),n=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var h=0;h<256;h++){var d=u(h);n[h]=d,a[d]=h,s[0][h]=i(2,d)<<24|d<<16|d<<8|i(3,d),o[0][d]=i(14,h)<<24|i(9,h)<<16|i(13,h)<<8|i(11,h);for(var f=1;f<4;f++)s[f][h]=s[f-1][h]>>>8|s[f-1][h]<<24,o[f][d]=o[f-1][d]>>>8|o[f-1][d]<<24}c=!0}var h=function(e,t){c||u();var r=new Uint32Array(t);r.set(n,512),r.set(a,768);for(var i=0;i<4;i++)r.set(s[i],4096+1024*i>>2),r.set(o[i],8192+1024*i>>2);var h=function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0;var S=new e.Uint32Array(r),E=new e.Uint8Array(r);function P(e,t,r,o,c,u,h,d){e=e|0;t=t|0;r=r|0;o=o|0;c=c|0;u=u|0;h=h|0;d=d|0;var f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;f=r|0x400,l=r|0x800,p=r|0xc00;c=c^S[(e|0)>>2],u=u^S[(e|4)>>2],h=h^S[(e|8)>>2],d=d^S[(e|12)>>2];for(w=16;(w|0)<=o<<4;w=w+16|0){y=S[(r|c>>22&1020)>>2]^S[(f|u>>14&1020)>>2]^S[(l|h>>6&1020)>>2]^S[(p|d<<2&1020)>>2]^S[(e|w|0)>>2],b=S[(r|u>>22&1020)>>2]^S[(f|h>>14&1020)>>2]^S[(l|d>>6&1020)>>2]^S[(p|c<<2&1020)>>2]^S[(e|w|4)>>2],m=S[(r|h>>22&1020)>>2]^S[(f|d>>14&1020)>>2]^S[(l|c>>6&1020)>>2]^S[(p|u<<2&1020)>>2]^S[(e|w|8)>>2],g=S[(r|d>>22&1020)>>2]^S[(f|c>>14&1020)>>2]^S[(l|u>>6&1020)>>2]^S[(p|h<<2&1020)>>2]^S[(e|w|12)>>2];c=y,u=b,h=m,d=g}i=S[(t|c>>22&1020)>>2]<<24^S[(t|u>>14&1020)>>2]<<16^S[(t|h>>6&1020)>>2]<<8^S[(t|d<<2&1020)>>2]^S[(e|w|0)>>2],n=S[(t|u>>22&1020)>>2]<<24^S[(t|h>>14&1020)>>2]<<16^S[(t|d>>6&1020)>>2]<<8^S[(t|c<<2&1020)>>2]^S[(e|w|4)>>2],a=S[(t|h>>22&1020)>>2]<<24^S[(t|d>>14&1020)>>2]<<16^S[(t|c>>6&1020)>>2]<<8^S[(t|u<<2&1020)>>2]^S[(e|w|8)>>2],s=S[(t|d>>22&1020)>>2]<<24^S[(t|c>>14&1020)>>2]<<16^S[(t|u>>6&1020)>>2]<<8^S[(t|h<<2&1020)>>2]^S[(e|w|12)>>2]}function x(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;P(0x0000,0x0800,0x1000,A,e,t,r,i)}function M(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var a=0;P(0x0400,0x0c00,0x2000,A,e,i,r,t);a=n,n=s,s=a}function K(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o^e,c^t,u^r,h^d);o=i,c=n,u=a,h=s}function C(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;var f=0;P(0x0400,0x0c00,0x2000,A,e,d,r,t);f=n,n=s,s=f;i=i^o,n=n^c,a=a^u,s=s^h;o=e,c=t,u=r,h=d}function D(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i=i^e,c=n=n^t,u=a=a^r,h=s=s^d}function U(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);i=i^e,n=n^t,a=a^r,s=s^d;o=e,c=t,u=r,h=d}function R(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;P(0x0000,0x0800,0x1000,A,o,c,u,h);o=i,c=n,u=a,h=s;i=i^e,n=n^t,a=a^r,s=s^d}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;P(0x0000,0x0800,0x1000,A,d,f,l,p);p=~g&p|g&p+1;l=~m&l|m&l+((p|0)==0);f=~b&f|b&f+((l|0)==0);d=~y&d|y&d+((f|0)==0);i=i^e;n=n^t;a=a^r;s=s^o}function B(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,a=0,s=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0;e=e^o,t=t^c,r=r^u,i=i^h;n=w|0,a=v|0,s=_|0,d=k|0;for(;(b|0)<128;b=b+1|0){if(n>>>31){f=f^e,l=l^t,p=p^r,y=y^i}n=n<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|d>>>31,d=d<<1;m=i&1;i=i>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(m)e=e^0xe1000000}o=f,c=l,u=p,h=y}function T(e){e=e|0;A=e}function z(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;i=e,n=t,a=r,s=o}function q(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;o=e,c=t,u=r,h=i}function F(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;d=e,f=t,l=r,p=i}function O(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;y=e,b=t,m=r,g=i}function L(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;p=~g&p|g&i,l=~m&l|m&r,f=~b&f|b&t,d=~y&d|y&e}function N(e){e=e|0;if(e&15)return-1;E[e|0]=i>>>24,E[e|1]=i>>>16&255,E[e|2]=i>>>8&255,E[e|3]=i&255,E[e|4]=n>>>24,E[e|5]=n>>>16&255,E[e|6]=n>>>8&255,E[e|7]=n&255,E[e|8]=a>>>24,E[e|9]=a>>>16&255,E[e|10]=a>>>8&255,E[e|11]=a&255,E[e|12]=s>>>24,E[e|13]=s>>>16&255,E[e|14]=s>>>8&255,E[e|15]=s&255;return 16}function j(e){e=e|0;if(e&15)return-1;E[e|0]=o>>>24,E[e|1]=o>>>16&255,E[e|2]=o>>>8&255,E[e|3]=o&255,E[e|4]=c>>>24,E[e|5]=c>>>16&255,E[e|6]=c>>>8&255,E[e|7]=c&255,E[e|8]=u>>>24,E[e|9]=u>>>16&255,E[e|10]=u>>>8&255,E[e|11]=u&255,E[e|12]=h>>>24,E[e|13]=h>>>16&255,E[e|14]=h>>>8&255,E[e|15]=h&255;return 16}function H(){x(0,0,0,0);w=i,v=n,_=a,k=s}function W(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){V[e&7](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);E[t|0]=i>>>24,E[t|1]=i>>>16&255,E[t|2]=i>>>8&255,E[t|3]=i&255,E[t|4]=n>>>24,E[t|5]=n>>>16&255,E[t|6]=n>>>8&255,E[t|7]=n&255,E[t|8]=a>>>24,E[t|9]=a>>>16&255,E[t|10]=a>>>8&255,E[t|11]=a&255,E[t|12]=s>>>24,E[t|13]=s>>>16&255,E[t|14]=s>>>8&255,E[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function G(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t&15)return-1;while((r|0)>=16){$[e&1](E[t|0]<<24|E[t|1]<<16|E[t|2]<<8|E[t|3],E[t|4]<<24|E[t|5]<<16|E[t|6]<<8|E[t|7],E[t|8]<<24|E[t|9]<<16|E[t|10]<<8|E[t|11],E[t|12]<<24|E[t|13]<<16|E[t|14]<<8|E[t|15]);i=i+16|0,t=t+16|0,r=r-16|0}return i|0}var V=[x,M,K,C,D,U,R,I];var $=[K,B];return{set_rounds:T,set_state:z,set_iv:q,set_nonce:F,set_mask:O,set_counter:L,get_state:N,get_iv:j,gcm_init:H,cipher:W,mac:G}}({Uint8Array,Uint32Array},e,t);return h.set_key=function(e,t,i,a,s,c,u,d,f){var l=r.subarray(0,60),p=r.subarray(256,316);l.set([t,i,a,s,c,u,d,f]);for(var y=e,b=1;y<4*e+28;y++){var m=l[y-1];(y%e==0||8===e&&y%e==4)&&(m=n[m>>>24]<<24^n[m>>>16&255]<<16^n[m>>>8&255]<<8^n[255&m]),y%e==0&&(m=m<<8^m>>>24^b<<24,b=b<<1^(128&b?27:0)),l[y]=l[y-e]^m}for(var g=0;g=y-4?m:o[0][n[m>>>24]]^o[1][n[m>>>16&255]]^o[2][n[m>>>8&255]]^o[3][n[255&m]]}h.set_rounds(e+5)},h};return h.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},h.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},h.MAC={CBC:0,GCM:1},h.HEAP_DATA=16384,h}();function be(e){return e instanceof Uint8Array}function me(e,t){const r=e?e.byteLength:t||65536;if(4095&r||r<=0)throw Error("heap size must be a positive integer and a multiple of 4096");return e=e||new Uint8Array(new ArrayBuffer(r))}function ge(e,t,r,i,n){const a=e.length-t,s=ae+t.length),0),r=new Uint8Array(t);let i=0;for(let t=0;t>2,n.getUint32(0),n.getUint32(4),n.getUint32(8),n.getUint32(12),i>16?n.getUint32(16):0,i>16?n.getUint32(20):0,i>24?n.getUint32(24):0,i>24?n.getUint32(28):0),void 0!==t){if(16!==t.length)throw new _e("illegal iv size");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);r.set_iv(e.getUint32(0),e.getUint32(4),e.getUint32(8),e.getUint32(12))}else r.set_iv(0,0,0,0)}AES_Encrypt_process(e){if(!be(e))throw new TypeError("data isn't of expected type");let{heap:t,asm:r}=this.acquire_asm(),i=ye.ENC[this.mode],n=ye.HEAP_DATA,a=this.pos,s=this.len,o=0,c=e.length||0,u=0,h=0,d=new Uint8Array(s+c&-16);for(;c>0;)h=ge(t,a+s,e,o,c),s+=h,o+=h,c-=h,h=r.cipher(i,n+a,s),h&&d.set(t.subarray(a,a+h),u),u+=h,h0;)f=ge(t,a+s,e,o,c),s+=f,o+=f,c-=f,f=r.cipher(i,n+a,s-(c?0:d)),f&&l.set(t.subarray(a,a+f),u),u+=f,f0){if(a%16){if(this.hasOwnProperty("padding"))throw new _e("data length must be a multiple of the block size");a+=16-a%16}if(t.cipher(r,i+n,a),this.hasOwnProperty("padding")&&this.padding){let t=e[n+s-1];if(t<1||t>16||t>s)throw new ke("bad padding");let r=0;for(let i=t;i>1;i--)r|=t^e[n+s-i];if(r)throw new ke("bad padding");s-=t}}const o=new Uint8Array(s);return s>0&&o.set(e.subarray(n,n+s)),this.pos=0,this.len=0,this.release_asm(),o}}class Pe{static encrypt(e,t,r=!1){return new Pe(t,r).encrypt(e)}static decrypt(e,t,r=!1){return new Pe(t,r).decrypt(e)}constructor(e,t=!1,r){this.aes=r||new Ee(e,void 0,t,"ECB")}encrypt(e){return we(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return we(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}function xe(e){const t=function(e){const t=new Pe(e);this.encrypt=function(e){return t.encrypt(e)},this.decrypt=function(e){return t.decrypt(e)}};return t.blockSize=t.prototype.blockSize=16,t.keySize=t.prototype.keySize=e/8,t}function Me(e,t,r,i,n,a){const s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],u=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],h=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],d=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],f=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],l=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let p,y,b,m,g,w,v,_,k,A,S,E,P,x,M=0,K=t.length;const C=32===e.length?3:9;_=3===C?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e,t){const r=8-e.length%8;let i;if(2===t&&r<8)i=32;else if(1===t)i=r;else{if(t||!(r<8)){if(8===r)return e;throw Error("des: invalid padding")}i=0}const n=new Uint8Array(e.length+r);for(let t=0;t>>4^v),v^=b,w^=b<<4,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,w=w<<1|w>>>31,v=v<<1|v>>>31,y=0;y>>4|v<<28)^e[p+1],b=w,w=v,v=b^(o[m>>>24&63]|u[m>>>16&63]|d[m>>>8&63]|l[63&m]|s[g>>>24&63]|c[g>>>16&63]|h[g>>>8&63]|f[63&g]);b=w,w=v,v=b}w=w>>>1|w<<31,v=v>>>1|v<<31,b=1431655765&(w>>>1^v),v^=b,w^=b<<1,b=16711935&(v>>>8^w),w^=b,v^=b<<8,b=858993459&(v>>>2^w),w^=b,v^=b<<2,b=65535&(w>>>16^v),v^=b,w^=b<<16,b=252645135&(w>>>4^v),v^=b,w^=b<<4,1===i&&(r?(k=w,S=v):(w^=A,v^=E)),D[U++]=w>>>24,D[U++]=w>>>16&255,D[U++]=w>>>8&255,D[U++]=255&w,D[U++]=v>>>24,D[U++]=v>>>16&255,D[U++]=v>>>8&255,D[U++]=255&v}return r||(D=function(e,t){let r,i=null;if(2===t)r=32;else if(1===t)i=e[e.length-1];else{if(t)throw Error("des: invalid padding");r=0}if(!i){for(i=1;e[e.length-i]===r;)i++;i--}return e.subarray(0,e.length-i)}(D,a)),D}function Ke(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],l=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length>8?3:1,b=Array(32*y),m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let g,w,v,_=0,k=0;for(let A=0;A>>4^A),A^=v,y^=v<<4,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=858993459&(y>>>2^A),A^=v,y^=v<<2,v=65535&(A>>>-16^y),y^=v,A^=v<<-16,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=16711935&(A>>>8^y),y^=v,A^=v<<8,v=1431655765&(y>>>1^A),A^=v,y^=v<<1,v=y<<8|A>>>20&240,y=A<<24|A<<8&16711680|A>>>8&65280|A>>>24&240,A=v;for(let e=0;e<16;e++)m[e]?(y=y<<2|y>>>26,A=A<<2|A>>>26):(y=y<<1|y>>>27,A=A<<1|A>>>27),y&=-15,A&=-15,g=t[y>>>28]|r[y>>>24&15]|i[y>>>20&15]|n[y>>>16&15]|a[y>>>12&15]|s[y>>>8&15]|o[y>>>4&15],w=c[A>>>28]|u[A>>>24&15]|h[A>>>20&15]|d[A>>>16&15]|f[A>>>12&15]|l[A>>>8&15]|p[A>>>4&15],v=65535&(w>>>16^g),b[k++]=g^v,b[k++]=w^v<<16}return b}function Ce(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Me(Ke(this.key[2]),Me(Ke(this.key[1]),Me(Ke(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}function De(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>>16&255,t[a+6]=o>>>8&255,t[a+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let a=0;a>>24&255,t[a+1]=c>>>16&255,t[a+2]=c>>>8&255,t[a+3]=255&c,t[a+4]=o>>>24&255,t[a+5]=o>>16&255,t[a+6]=o>>8&255,t[a+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const i=t+e,n=i<>>32-r;return(a[0][n>>>24]^a[1][n>>>16&255])-a[2][n>>>8&255]+a[3][255&n]}function i(e,t,r){const i=t^e,n=i<>>32-r;return a[0][n>>>24]-a[1][n>>>16&255]+a[2][n>>>8&255]^a[3][255&n]}function n(e,t,r){const i=t-e,n=i<>>32-r;return(a[0][n>>>24]+a[1][n>>>16&255]^a[2][n>>>8&255])-a[3][255&n]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const i=[,,,,,,,,],n=Array(32);let s;for(let e=0;e<4;e++)s=4*e,i[e]=r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3];const o=[6,7,4,5];let c,u=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(s=0;s<4;s++){const t=e[r][s];c=i[t[1]],c^=a[4][i[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=a[5][i[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=a[6][i[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=a[7][i[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=a[o[s]][i[t[6]>>>2]>>>24-8*(3&t[6])&255],i[t[0]]=c}for(s=0;s<4;s++){const e=t[r][s];c=a[4][i[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=a[5][i[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=a[6][i[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=a[7][i[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=a[4+s][i[e[4]>>>2]>>>24-8*(3&e[4])&255],n[u]=c,u++}}for(let e=0;e<16;e++)this.masking[e]=n[e],this.rotate[e]=31&n[16+e]};const a=[,,,,,,,,];a[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],a[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],a[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],a[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],a[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],a[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],a[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],a[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function Ue(e){this.cast5=new De,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}Ce.keySize=Ce.prototype.keySize=24,Ce.blockSize=Ce.prototype.blockSize=8,Ue.blockSize=Ue.prototype.blockSize=8,Ue.keySize=Ue.prototype.keySize=16;const Re=4294967295;function Ie(e,t){return(e<>>32-t)&Re}function Be(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Te(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function ze(e,t){return e>>>8*t&255}function qe(e){this.tf=function(){let e=null,t=null,r=-1,i=[],n=[[],[],[],[]];function a(e){return n[0][ze(e,0)]^n[1][ze(e,1)]^n[2][ze(e,2)]^n[3][ze(e,3)]}function s(e){return n[0][ze(e,3)]^n[1][ze(e,0)]^n[2][ze(e,1)]^n[3][ze(e,2)]}function o(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Ie(t[2]^r+n+i[4*e+8]&Re,31),t[3]=Ie(t[3],1)^r+2*n+i[4*e+9]&Re,r=a(t[2]),n=s(t[3]),t[0]=Ie(t[0]^r+n+i[4*e+10]&Re,31),t[1]=Ie(t[1],1)^r+2*n+i[4*e+11]&Re}function c(e,t){let r=a(t[0]),n=s(t[1]);t[2]=Ie(t[2],1)^r+n+i[4*e+10]&Re,t[3]=Ie(t[3]^r+2*n+i[4*e+11]&Re,31),r=a(t[2]),n=s(t[3]),t[0]=Ie(t[0],1)^r+n+i[4*e+8]&Re,t[1]=Ie(t[1]^r+2*n+i[4*e+9]&Re,31)}return{name:"twofish",blocksize:16,open:function(t){let r,a,s,o,c;e=t;const u=[],h=[],d=[];let f;const l=[];let p,y,b;const m=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],g=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],w=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],v=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],_=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],k=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],A=[[],[]],S=[[],[],[],[]];function E(e){return e^e>>2^[0,90,180,238][3&e]}function P(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function x(e,t){let r,i,n;for(r=0;r<8;r++)i=t>>>24,t=t<<8&Re|e>>>24,e=e<<8&Re,n=i<<1,128&i&&(n^=333),t^=i^n<<16,n^=i>>>1,1&i&&(n^=166),t^=n<<24|n<<8;return t}function M(e,t){const r=t>>4,i=15&t,n=m[e][r^i],a=g[e][_[i]^k[r]];return v[e][_[a]^k[n]]<<4|w[e][n^a]}function K(e,t){let r=ze(e,0),i=ze(e,1),n=ze(e,2),a=ze(e,3);switch(f){case 4:r=A[1][r]^ze(t[3],0),i=A[0][i]^ze(t[3],1),n=A[0][n]^ze(t[3],2),a=A[1][a]^ze(t[3],3);case 3:r=A[1][r]^ze(t[2],0),i=A[1][i]^ze(t[2],1),n=A[0][n]^ze(t[2],2),a=A[0][a]^ze(t[2],3);case 2:r=A[0][A[0][r]^ze(t[1],0)]^ze(t[0],0),i=A[0][A[1][i]^ze(t[1],1)]^ze(t[0],1),n=A[1][A[0][n]^ze(t[1],2)]^ze(t[0],2),a=A[1][A[1][a]^ze(t[1],3)]^ze(t[0],3)}return S[0][r]^S[1][i]^S[2][n]^S[3][a]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Be(e,r);for(r=0;r<256;r++)A[0][r]=M(0,r),A[1][r]=M(1,r);for(r=0;r<256;r++)p=A[1][r],y=E(p),b=P(p),S[0][r]=p+(y<<8)+(b<<16)+(b<<24),S[2][r]=y+(b<<8)+(p<<16)+(b<<24),p=A[0][r],y=E(p),b=P(p),S[1][r]=b+(b<<8)+(y<<16)+(p<<24),S[3][r]=y+(p<<8)+(b<<16)+(y<<24);for(f=d.length/2,r=0;r=0;e--)c(e,a);Te(t,r,a[2]^i[0]),Te(t,r+4,a[3]^i[1]),Te(t,r+8,a[0]^i[2]),Te(t,r+12,a[1]^i[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Fe(){}function Oe(e){this.bf=new Fe,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}qe.keySize=qe.prototype.keySize=32,qe.blockSize=qe.prototype.blockSize=16,Fe.prototype.BLOCKSIZE=8,Fe.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Fe.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Fe.prototype.NN=16,Fe.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Fe.prototype._F=function(e){let t;const r=255&e,i=255&(e>>>=8),n=255&(e>>>=8),a=255&(e>>>=8);return t=this.sboxes[0][a]+this.sboxes[1][n],t^=this.sboxes[2][i],t+=this.sboxes[3][r],t},Fe.prototype._encryptBlock=function(e){let t,r=e[0],i=e[1];for(t=0;t>>24-8*t&255,n[t+i]=r[1]>>>24-8*t&255;return n},Fe.prototype._decryptBlock=function(e){let t,r=e[0],i=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],i=this._F(r)^i;const e=r;r=i,i=e}r^=this.parray[1],i^=this.parray[0],e[0]=this._clean(i),e[1]=this._clean(r)},Fe.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^i}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const i=[0,0];for(t=0;t>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=t+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=r+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=c+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=u+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=h+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=d+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=f+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=l+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=p+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=y+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=b+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=m+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=g+(_<<5|_>>>27)+E+(k&A|~k&S)+0x5a827999|0;E=S;S=A;A=k<<30|k>>>2;k=_;_=x;x=w+(_<<5|_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k<<30|k>>>2;k=_;_=x;i=i+_|0;n=n+k|0;a=a+A|0;s=s+S|0;o=o+E|0}function k(e){e=e|0;_(v[e|0]<<24|v[e|1]<<16|v[e|2]<<8|v[e|3],v[e|4]<<24|v[e|5]<<16|v[e|6]<<8|v[e|7],v[e|8]<<24|v[e|9]<<16|v[e|10]<<8|v[e|11],v[e|12]<<24|v[e|13]<<16|v[e|14]<<8|v[e|15],v[e|16]<<24|v[e|17]<<16|v[e|18]<<8|v[e|19],v[e|20]<<24|v[e|21]<<16|v[e|22]<<8|v[e|23],v[e|24]<<24|v[e|25]<<16|v[e|26]<<8|v[e|27],v[e|28]<<24|v[e|29]<<16|v[e|30]<<8|v[e|31],v[e|32]<<24|v[e|33]<<16|v[e|34]<<8|v[e|35],v[e|36]<<24|v[e|37]<<16|v[e|38]<<8|v[e|39],v[e|40]<<24|v[e|41]<<16|v[e|42]<<8|v[e|43],v[e|44]<<24|v[e|45]<<16|v[e|46]<<8|v[e|47],v[e|48]<<24|v[e|49]<<16|v[e|50]<<8|v[e|51],v[e|52]<<24|v[e|53]<<16|v[e|54]<<8|v[e|55],v[e|56]<<24|v[e|57]<<16|v[e|58]<<8|v[e|59],v[e|60]<<24|v[e|61]<<16|v[e|62]<<8|v[e|63])}function A(e){e=e|0;v[e|0]=i>>>24;v[e|1]=i>>>16&255;v[e|2]=i>>>8&255;v[e|3]=i&255;v[e|4]=n>>>24;v[e|5]=n>>>16&255;v[e|6]=n>>>8&255;v[e|7]=n&255;v[e|8]=a>>>24;v[e|9]=a>>>16&255;v[e|10]=a>>>8&255;v[e|11]=a&255;v[e|12]=s>>>24;v[e|13]=s>>>16&255;v[e|14]=s>>>8&255;v[e|15]=s&255;v[e|16]=o>>>24;v[e|17]=o>>>16&255;v[e|18]=o>>>8&255;v[e|19]=o&255}function S(){i=0x67452301;n=0xefcdab89;a=0x98badcfe;s=0x10325476;o=0xc3d2e1f0;c=u=0}function E(e,t,r,h,d,f,l){e=e|0;t=t|0;r=r|0;h=h|0;d=d|0;f=f|0;l=l|0;i=e;n=t;a=r;s=h;o=d;c=f;u=l}function P(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){k(e);e=e+64|0;t=t-64|0;r=r+64|0}c=c+r|0;if(c>>>0>>0)u=u+1|0;return r|0}function x(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=P(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;c=c+t|0;if(c>>>0>>0)u=u+1|0;v[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)v[e|n]=0x00;k(e);t=0;v[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)v[e|n]=0;v[e|56]=u>>>21&255;v[e|57]=u>>>13&255;v[e|58]=u>>>5&255;v[e|59]=u<<3&255|c>>>29;v[e|60]=c>>>21&255;v[e|61]=c>>>13&255;v[e|62]=c>>>5&255;v[e|63]=c<<3&255;k(e);if(~r)A(r);return i|0}function M(){i=h;n=d;a=f;s=l;o=p;c=64;u=0}function K(){i=y;n=b;a=m;s=g;o=w;c=64;u=0}function C(e,t,r,v,k,A,E,P,x,M,K,C,D,U,R,I){e=e|0;t=t|0;r=r|0;v=v|0;k=k|0;A=A|0;E=E|0;P=P|0;x=x|0;M=M|0;K=K|0;C=C|0;D=D|0;U=U|0;R=R|0;I=I|0;S();_(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,v^0x5c5c5c5c,k^0x5c5c5c5c,A^0x5c5c5c5c,E^0x5c5c5c5c,P^0x5c5c5c5c,x^0x5c5c5c5c,M^0x5c5c5c5c,K^0x5c5c5c5c,C^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,R^0x5c5c5c5c,I^0x5c5c5c5c);y=i;b=n;m=a;g=s;w=o;S();_(e^0x36363636,t^0x36363636,r^0x36363636,v^0x36363636,k^0x36363636,A^0x36363636,E^0x36363636,P^0x36363636,x^0x36363636,M^0x36363636,K^0x36363636,C^0x36363636,D^0x36363636,U^0x36363636,R^0x36363636,I^0x36363636);h=i;d=n;f=a;l=s;p=o;c=64;u=0}function D(e,t,r){e=e|0;t=t|0;r=r|0;var c=0,u=0,h=0,d=0,f=0,l=0;if(e&63)return-1;if(~r)if(r&31)return-1;l=x(e,t,-1)|0;c=i,u=n,h=a,d=s,f=o;K();_(c,u,h,d,f,0x80000000,0,0,0,0,0,0,0,0,0,672);if(~r)A(r);return l|0}function U(e,t,r,c,u){e=e|0;t=t|0;r=r|0;c=c|0;u=u|0;var h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;if(e&63)return-1;if(~u)if(u&31)return-1;v[e+t|0]=r>>>24;v[e+t+1|0]=r>>>16&255;v[e+t+2|0]=r>>>8&255;v[e+t+3|0]=r&255;D(e,t+4|0,-1)|0;h=y=i,d=b=n,f=m=a,l=g=s,p=w=o;c=c-1|0;while((c|0)>0){M();_(y,b,m,g,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,m=a,g=s,w=o;K();_(y,b,m,g,w,0x80000000,0,0,0,0,0,0,0,0,0,672);y=i,b=n,m=a,g=s,w=o;h=h^i;d=d^n;f=f^a;l=l^s;p=p^o;c=c-1|0}i=h;n=d;a=f;s=l;o=p;if(~u)A(u);return 0}return{reset:S,init:E,process:P,finish:x,hmac_reset:M,hmac_init:C,hmac_finish:D,pbkdf2_generate_block:U}};class Ve{constructor(){this.pos=0,this.len=0}reset(){const{asm:e}=this.acquire_asm();return this.result=null,this.pos=0,this.len=0,e.reset(),this}process(e){if(null!==this.result)throw new ve("state must be reset before processing new data");const{asm:t,heap:r}=this.acquire_asm();let i=this.pos,n=this.len,a=0,s=e.length,o=0;for(;s>0;)o=ge(r,i+n,e,a,s),n+=o,a+=o,s-=o,o=t.process(i,n),i+=o,n-=o,n||(i=0);return this.pos=i,this.len=n,this}finish(){if(null!==this.result)throw new ve("state must be reset before processing new data");const{asm:e,heap:t}=this.acquire_asm();return e.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(t.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this.release_asm(),this}}const $e=[],Ze=[];class Xe extends Ve{constructor(){super(),this.NAME="sha1",this.BLOCK_SIZE=64,this.HASH_SIZE=20,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=$e.pop()||me(),this.asm=Ze.pop()||Ge({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&($e.push(this.heap),Ze.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new Xe).process(e).finish().result}}Xe.NAME="sha1",Xe.heap_pool=[],Xe.asm_pool=[],Xe.asm_function=Ge;const Ye=[],Qe=[];class Je extends Ve{constructor(){super(),this.NAME="sha256",this.BLOCK_SIZE=64,this.HASH_SIZE=32,this.acquire_asm()}acquire_asm(){return void 0!==this.heap&&void 0!==this.asm||(this.heap=Ye.pop()||me(),this.asm=Qe.pop()||function(e,t,r){"use asm";var i=0,n=0,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=new e.Uint8Array(r);function C(e,t,r,d,f,l,p,y,b,m,g,w,v,_,k,A){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;l=l|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;w=w|0;v=v|0;_=_|0;k=k|0;A=A|0;var S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0;S=i;E=n;P=a;x=s;M=o;K=c;C=u;D=h;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x428a2f98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x71374491|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb5c0fbcf|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xe9b5dba5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x3956c25b|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x59f111f1|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x923f82a4|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xab1c5ed5|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xd807aa98|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x12835b01|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x243185be|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x550c7dc3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x72be5d74|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x80deb1fe|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x9bdc06a7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc19bf174|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xe49b69c1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xefbe4786|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x0fc19dc6|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x240ca1cc|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x2de92c6f|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4a7484aa|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5cb0a9dc|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x76f988da|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x983e5152|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa831c66d|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xb00327c8|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xbf597fc7|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xc6e00bf3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd5a79147|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x06ca6351|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x14292967|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x27b70a85|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x2e1b2138|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x4d2c6dfc|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x53380d13|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x650a7354|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x766a0abb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x81c2c92e|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x92722c85|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0xa2bfe8a1|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0xa81a664b|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0xc24b8b70|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0xc76c51a3|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0xd192e819|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xd6990624|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xf40e3585|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x106aa070|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;D=e+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x19a4c116|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+t+g|0;C=t+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x1e376c08|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;K=r+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x2748774c|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;d=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+v|0;M=d+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x34b0bcb5|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;f=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+f+_|0;x=f+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x391c0cb3|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;l=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+l+k|0;P=l+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0x4ed8aa4a|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+p+A|0;E=p+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0x5b9cca4f|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+y+e|0;S=y+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0x682e6ff3|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;D=b+D+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(C^M&(K^C))+0x748f82ee|0;x=x+D|0;D=D+(S&E^P&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;C=m+C+(x>>>6^x>>>11^x>>>25^x<<26^x<<21^x<<7)+(K^x&(M^K))+0x78a5636f|0;P=P+C|0;C=C+(D&S^E&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;K=g+K+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(M^P&(x^M))+0x84c87814|0;E=E+K|0;K=K+(C&D^S&(C^D))+(C>>>2^C>>>13^C>>>22^C<<30^C<<19^C<<10)|0;w=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+f|0;M=w+M+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(x^E&(P^x))+0x8cc70208|0;S=S+M|0;M=M+(K&C^D&(K^C))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;x=v+x+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(P^S&(E^P))+0x90befffa|0;D=D+x|0;x=x+(M&K^C&(M^K))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;_=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+_+p|0;P=_+P+(D>>>6^D>>>11^D>>>25^D<<26^D<<21^D<<7)+(E^D&(S^E))+0xa4506ceb|0;C=C+P|0;P=P+(x&M^K&(x^M))+(x>>>2^x>>>13^x>>>22^x<<30^x<<19^x<<10)|0;k=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+k+y|0;E=k+E+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(S^C&(D^S))+0xbef9a3f7|0;K=K+E|0;E=E+(P&x^M&(P^x))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;A=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+A+b|0;S=A+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(D^K&(C^D))+0xc67178f2|0;M=M+S|0;S=S+(E&P^x&(E^P))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;i=i+S|0;n=n+E|0;a=a+P|0;s=s+x|0;o=o+M|0;c=c+K|0;u=u+C|0;h=h+D|0}function D(e){e=e|0;C(K[e|0]<<24|K[e|1]<<16|K[e|2]<<8|K[e|3],K[e|4]<<24|K[e|5]<<16|K[e|6]<<8|K[e|7],K[e|8]<<24|K[e|9]<<16|K[e|10]<<8|K[e|11],K[e|12]<<24|K[e|13]<<16|K[e|14]<<8|K[e|15],K[e|16]<<24|K[e|17]<<16|K[e|18]<<8|K[e|19],K[e|20]<<24|K[e|21]<<16|K[e|22]<<8|K[e|23],K[e|24]<<24|K[e|25]<<16|K[e|26]<<8|K[e|27],K[e|28]<<24|K[e|29]<<16|K[e|30]<<8|K[e|31],K[e|32]<<24|K[e|33]<<16|K[e|34]<<8|K[e|35],K[e|36]<<24|K[e|37]<<16|K[e|38]<<8|K[e|39],K[e|40]<<24|K[e|41]<<16|K[e|42]<<8|K[e|43],K[e|44]<<24|K[e|45]<<16|K[e|46]<<8|K[e|47],K[e|48]<<24|K[e|49]<<16|K[e|50]<<8|K[e|51],K[e|52]<<24|K[e|53]<<16|K[e|54]<<8|K[e|55],K[e|56]<<24|K[e|57]<<16|K[e|58]<<8|K[e|59],K[e|60]<<24|K[e|61]<<16|K[e|62]<<8|K[e|63])}function U(e){e=e|0;K[e|0]=i>>>24;K[e|1]=i>>>16&255;K[e|2]=i>>>8&255;K[e|3]=i&255;K[e|4]=n>>>24;K[e|5]=n>>>16&255;K[e|6]=n>>>8&255;K[e|7]=n&255;K[e|8]=a>>>24;K[e|9]=a>>>16&255;K[e|10]=a>>>8&255;K[e|11]=a&255;K[e|12]=s>>>24;K[e|13]=s>>>16&255;K[e|14]=s>>>8&255;K[e|15]=s&255;K[e|16]=o>>>24;K[e|17]=o>>>16&255;K[e|18]=o>>>8&255;K[e|19]=o&255;K[e|20]=c>>>24;K[e|21]=c>>>16&255;K[e|22]=c>>>8&255;K[e|23]=c&255;K[e|24]=u>>>24;K[e|25]=u>>>16&255;K[e|26]=u>>>8&255;K[e|27]=u&255;K[e|28]=h>>>24;K[e|29]=h>>>16&255;K[e|30]=h>>>8&255;K[e|31]=h&255}function R(){i=0x6a09e667;n=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;h=0x5be0cd19;d=f=0}function I(e,t,r,l,p,y,b,m,g,w){e=e|0;t=t|0;r=r|0;l=l|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;w=w|0;i=e;n=t;a=r;s=l;o=p;c=y;u=b;h=m;d=g;f=w}function B(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){D(e);e=e+64|0;t=t-64|0;r=r+64|0}d=d+r|0;if(d>>>0>>0)f=f+1|0;return r|0}function T(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){i=B(e,t)|0;if((i|0)==-1)return-1;e=e+i|0;t=t-i|0}i=i+t|0;d=d+t|0;if(d>>>0>>0)f=f+1|0;K[e|t]=0x80;if((t|0)>=56){for(n=t+1|0;(n|0)<64;n=n+1|0)K[e|n]=0x00;D(e);t=0;K[e|0]=0}for(n=t+1|0;(n|0)<59;n=n+1|0)K[e|n]=0;K[e|56]=f>>>21&255;K[e|57]=f>>>13&255;K[e|58]=f>>>5&255;K[e|59]=f<<3&255|d>>>29;K[e|60]=d>>>21&255;K[e|61]=d>>>13&255;K[e|62]=d>>>5&255;K[e|63]=d<<3&255;D(e);if(~r)U(r);return i|0}function z(){i=l;n=p;a=y;s=b;o=m;c=g;u=w;h=v;d=64;f=0}function q(){i=_;n=k;a=A;s=S;o=E;c=P;u=x;h=M;d=64;f=0}function F(e,t,r,K,D,U,I,B,T,z,q,F,O,L,N,j){e=e|0;t=t|0;r=r|0;K=K|0;D=D|0;U=U|0;I=I|0;B=B|0;T=T|0;z=z|0;q=q|0;F=F|0;O=O|0;L=L|0;N=N|0;j=j|0;R();C(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,K^0x5c5c5c5c,D^0x5c5c5c5c,U^0x5c5c5c5c,I^0x5c5c5c5c,B^0x5c5c5c5c,T^0x5c5c5c5c,z^0x5c5c5c5c,q^0x5c5c5c5c,F^0x5c5c5c5c,O^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,j^0x5c5c5c5c);_=i;k=n;A=a;S=s;E=o;P=c;x=u;M=h;R();C(e^0x36363636,t^0x36363636,r^0x36363636,K^0x36363636,D^0x36363636,U^0x36363636,I^0x36363636,B^0x36363636,T^0x36363636,z^0x36363636,q^0x36363636,F^0x36363636,O^0x36363636,L^0x36363636,N^0x36363636,j^0x36363636);l=i;p=n;y=a;b=s;m=o;g=c;w=u;v=h;d=64;f=0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0;if(e&63)return-1;if(~r)if(r&31)return-1;w=T(e,t,-1)|0;d=i,f=n,l=a,p=s,y=o,b=c,m=u,g=h;q();C(d,f,l,p,y,b,m,g,0x80000000,0,0,0,0,0,0,768);if(~r)U(r);return w|0}function L(e,t,r,d,f){e=e|0;t=t|0;r=r|0;d=d|0;f=f|0;var l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0;if(e&63)return-1;if(~f)if(f&31)return-1;K[e+t|0]=r>>>24;K[e+t+1|0]=r>>>16&255;K[e+t+2|0]=r>>>8&255;K[e+t+3|0]=r&255;O(e,t+4|0,-1)|0;l=_=i,p=k=n,y=A=a,b=S=s,m=E=o,g=P=c,w=x=u,v=M=h;d=d-1|0;while((d|0)>0){z();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;q();C(_,k,A,S,E,P,x,M,0x80000000,0,0,0,0,0,0,768);_=i,k=n,A=a,S=s,E=o,P=c,x=u,M=h;l=l^i;p=p^n;y=y^a;b=b^s;m=m^o;g=g^c;w=w^u;v=v^h;d=d-1|0}i=l;n=p;a=y;s=b;o=m;c=g;u=w;h=v;if(~f)U(f);return 0}return{reset:R,init:I,process:B,finish:T,hmac_reset:z,hmac_init:F,hmac_finish:O,pbkdf2_generate_block:L}}({Uint8Array},null,this.heap.buffer),this.reset()),{heap:this.heap,asm:this.asm}}release_asm(){void 0!==this.heap&&void 0!==this.asm&&(Ye.push(this.heap),Qe.push(this.asm)),this.heap=void 0,this.asm=void 0}static bytes(e){return(new Je).process(e).finish().result}}Je.NAME="sha256";var et=tt;function tt(e,t){if(!e)throw Error(t||"Assertion failed")}tt.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)};var rt=void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function it(e,t){return e(t={exports:{}},t.exports),t.exports}function nt(){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var at=it((function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}));var st=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>8,s=255&n;a?r.push(a,s):r.push(s)}else for(i=0;i>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}var ut=function(e,t){for(var r="",i=0;i>>0}return a};var lt=function(e,t){for(var r=Array(4*e.length),i=0,n=0;i>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r};var pt={inherits:at,toArray:st,toHex:ot,htonl:ct,toHex32:ut,zero2:ht,zero8:dt,join32:ft,split32:lt,rotr32:function(e,t){return e>>>t|e<<32-t},rotl32:function(e,t){return e<>>32-t},sum32:function(e,t){return e+t>>>0},sum32_3:function(e,t,r){return e+t+r>>>0},sum32_4:function(e,t,r,i){return e+t+r+i>>>0},sum32_5:function(e,t,r,i,n){return e+t+r+i+n>>>0},sum64:function(e,t,r,i){var n=e[t],a=i+e[t+1]>>>0,s=(a>>0,e[t+1]=a},sum64_hi:function(e,t,r,i){return(t+i>>>0>>0},sum64_lo:function(e,t,r,i){return t+i>>>0},sum64_4_hi:function(e,t,r,i,n,a,s,o){var c=0,u=t;return c+=(u=u+i>>>0)>>0)>>0)>>0},sum64_4_lo:function(e,t,r,i,n,a,s,o){return t+i+a+o>>>0},sum64_5_hi:function(e,t,r,i,n,a,s,o,c,u){var h=0,d=t;return h+=(d=d+i>>>0)>>0)>>0)>>0)>>0},sum64_5_lo:function(e,t,r,i,n,a,s,o,c,u){return t+i+a+o+u>>>0},rotr64_hi:function(e,t,r){return(t<<32-r|e>>>r)>>>0},rotr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0},shr64_hi:function(e,t,r){return e>>>r},shr64_lo:function(e,t,r){return(e<<32-r|t>>>r)>>>0}};function yt(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var bt=yt;yt.prototype.update=function(e,t){if(e=pt.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=pt.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,a=8;a>>3},g1_256:function(e){return gt(e,17)^gt(e,19)^e>>>10}},St=pt.sum32,Et=pt.sum32_4,Pt=pt.sum32_5,xt=At.ch32,Mt=At.maj32,Kt=At.s0_256,Ct=At.s1_256,Dt=At.g0_256,Ut=At.g1_256,Rt=mt.BlockHash,It=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Bt(){if(!(this instanceof Bt))return new Bt;Rt.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=It,this.W=Array(64)}pt.inherits(Bt,Rt);var Tt=Bt;function zt(){if(!(this instanceof zt))return new zt;Tt.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Bt.blockSize=512,Bt.outSize=256,Bt.hmacStrength=192,Bt.padLength=64,Bt.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;i>>32-n,r)}function Dr(e,t,r,i,n,a,s){return Cr(t&r|~t&i,e,t,n,a,s)}function Ur(e,t,r,i,n,a,s){return Cr(t&i|r&~i,e,t,n,a,s)}function Rr(e,t,r,i,n,a,s){return Cr(t^r^i,e,t,n,a,s)}function Ir(e,t,r,i,n,a,s){return Cr(r^(t|~i),e,t,n,a,s)}function Br(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const Tr="0123456789abcdef".split("");function zr(e){let t="",r=0;for(;r<4;r++)t+=Tr[e>>8*r+4&15]+Tr[e>>8*r&15];return t}function qr(e,t){return e+t&4294967295}const Fr=X.getWebCrypto(),Or=X.getNodeCrypto(),Lr=Or&&Or.getHashes();function Nr(e){if(Or&&Lr.includes(e))return async function(t){const r=Or.createHash(e);return B(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function jr(e,t){return async function(r,i=ne){if(s(r)&&(r=await N(r)),!X.isStream(r)&&Fr&&t&&r.length>=i.minBytesForWebCrypto)return new Uint8Array(await Fr.digest(t,r));const n=e();return B(r,(e=>{n.update(e)}),(()=>new Uint8Array(n.digest())))}}function Hr(e,t){return async function(r,i=ne){if(s(r)&&(r=await N(r)),X.isStream(r)){const t=new e;return B(r,(e=>{t.process(e)}),(()=>t.finish().result))}return Fr&&t&&r.length>=i.minBytesForWebCrypto?new Uint8Array(await Fr.digest(t,r)):e.bytes(r)}}const Wr={md5:Nr("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let i;for(i=64;i<=e.length;i+=64)Kr(r,Br(e.substring(i-64,i)));e=e.substring(i-64);const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i>2]|=e.charCodeAt(i)<<(i%4<<3);if(n[i>>2]|=128<<(i%4<<3),i>55)for(Kr(r,n),i=0;i<16;i++)n[i]=0;return n[14]=8*t,Kr(r,n),r}(X.uint8ArrayToString(e));return X.hexToUint8Array(function(e){for(let t=0;tnew Uint8Array(a.update(e))))}(e,t,r,i);if(X.isAES(e))return function(e,t,r,i,n){if(X.getWebCrypto()&&24!==t.length&&!X.isStream(r)&&r.length>=3e3*n.minBytesForWebCrypto)return async function(e,t,r,i){const n="AES-CBC",a=await Zr.importKey("raw",t,{name:n},!1,["encrypt"]),{blockSize:s}=$r(e),o=X.concatUint8Array([new Uint8Array(s),r]),c=new Uint8Array(await Zr.encrypt({name:n,iv:i},a,o)).subarray(0,r.length);return function(e,t){for(let r=0;ra.aes.AES_Encrypt_process(e)),(()=>a.aes.AES_Encrypt_finish()))}(e,t,r,i,n);const s=new($r(e))(t),o=s.blockSize,c=i.slice();let u=new Uint8Array;const h=e=>{e&&(u=X.concatUint8Array([u,e]));const t=new Uint8Array(u.length);let r,i=0;for(;e?u.length>=o:u.length;){const e=s.encrypt(c);for(r=0;rnew Uint8Array(a.update(e))))}(e,t,r,i);if(X.isAES(e))return function(e,t,r,i){if(X.isStream(r)){const e=new Vr(t,i);return B(r,(t=>e.aes.AES_Decrypt_process(t)),(()=>e.aes.AES_Decrypt_finish()))}return Vr.decrypt(r,t,i)}(0,t,r,i);const a=new($r(e))(t),s=a.blockSize;let o=i,c=new Uint8Array;const u=e=>{e&&(c=X.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,i=0;for(;e?c.length>=s:c.length;){const e=a.encrypt(o);for(o=c.subarray(0,s),r=0;r48)throw new _e("illegal counter size");let e=Math.pow(2,r)-1;i.set_mask(0,0,e/4294967296|0,0|e)}else r=48,i.set_mask(0,0,65535,4294967295);if(void 0===e)throw Error("nonce is required");{let t=e.length;if(!t||t>16)throw new _e("illegal nonce size");let r=new DataView(new ArrayBuffer(16));new Uint8Array(r.buffer).set(e),i.set_nonce(r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12))}if(void 0!==t){if(t<0||t>=Math.pow(2,r))throw new _e("illegal counter value");i.set_counter(0,0,t/4294967296|0,0|t)}}}class ti{static encrypt(e,t,r=!0,i){return new ti(t,i,r).encrypt(e)}static decrypt(e,t,r=!0,i){return new ti(t,i,r).decrypt(e)}constructor(e,t,r=!0,i){this.aes=i||new Ee(e,t,r,"CBC")}encrypt(e){return we(this.aes.AES_Encrypt_process(e),this.aes.AES_Encrypt_finish())}decrypt(e){return we(this.aes.AES_Decrypt_process(e),this.aes.AES_Decrypt_finish())}}const ri=X.getWebCrypto(),ii=X.getNodeCrypto(),ni=16;function ai(e,t){const r=e.length-ni;for(let i=0;i>3),17+(u>>3)),8-(7&u)).subarray(1),l=new Uint8Array(vi),p=new Uint8Array(t.length+ki);let y,b=0;for(y=0;y16)throw new _e("illegal tagSize value");const o=t.length||0,c=new Uint8Array(16);12!==o?(this._gcm_mac_process(t),s[0]=0,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=0,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=0,s[11]=o>>>29,s[12]=o>>>21&255,s[13]=o>>>13&255,s[14]=o>>>5&255,s[15]=o<<3&255,a.mac(ye.MAC.GCM,ye.HEAP_DATA,16),a.get_iv(ye.HEAP_DATA),a.set_iv(0,0,0,0),c.set(s.subarray(0,16))):(c.set(t),c[15]=1);const u=new DataView(c.buffer);if(this.gamma0=u.getUint32(12),a.set_nonce(u.getUint32(0),u.getUint32(4),u.getUint32(8),0),a.set_mask(0,0,0,4294967295),void 0!==r){if(r.length>Ki)throw new _e("illegal adata length");r.length?(this.adata=r,this._gcm_mac_process(r)):this.adata=void 0}else this.adata=void 0;if(this.counter<1||this.counter>4294967295)throw new RangeError("counter must be a positive 32-bit integer");a.set_counter(0,0,0,this.gamma0+this.counter|0)}static encrypt(e,t,r,i,n){return new Ci(t,r,i,n).encrypt(e)}static decrypt(e,t,r,i,n){return new Ci(t,r,i,n).decrypt(e)}encrypt(e){return this.AES_GCM_encrypt(e)}decrypt(e){return this.AES_GCM_decrypt(e)}AES_GCM_Encrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.aes.pos,o=this.aes.len,c=0,u=o+r&-16,h=0;if((a-1<<4)+o+r>Ki)throw new RangeError("counter overflow");const d=new Uint8Array(u);for(;r>0;)h=ge(n,s+o,e,t,r),o+=h,t+=h,r-=h,h=i.cipher(ye.ENC.CTR,ye.HEAP_DATA+s,o),h=i.mac(ye.MAC.GCM,ye.HEAP_DATA+s,h),h&&d.set(n.subarray(s,s+h),c),a+=h>>>4,c+=h,h>>29,t[4]=u>>>21,t[5]=u>>>13&255,t[6]=u>>>5&255,t[7]=u<<3&255,t[8]=t[9]=t[10]=0,t[11]=h>>>29,t[12]=h>>>21&255,t[13]=h>>>13&255,t[14]=h>>>5&255,t[15]=h<<3&255,e.mac(ye.MAC.GCM,ye.HEAP_DATA,16),e.get_iv(ye.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(ye.ENC.CTR,ye.HEAP_DATA,16),o.set(t.subarray(0,i),s),this.counter=1,this.aes.pos=0,this.aes.len=0,o}AES_GCM_Decrypt_process(e){let t=0,r=e.length||0,{asm:i,heap:n}=this.aes.acquire_asm(),a=this.counter,s=this.tagSize,o=this.aes.pos,c=this.aes.len,u=0,h=c+r>s?c+r-s&-16:0,d=c+r-h,f=0;if((a-1<<4)+c+r>Ki)throw new RangeError("counter overflow");const l=new Uint8Array(h);for(;r>d;)f=ge(n,o+c,e,t,r-d),c+=f,t+=f,r-=f,f=i.mac(ye.MAC.GCM,ye.HEAP_DATA+o,f),f=i.cipher(ye.DEC.CTR,ye.HEAP_DATA+o,f),f&&l.set(n.subarray(o,o+f),u),a+=f>>>4,u+=f,o=0,c=0;return r>0&&(c+=ge(n,0,e,t,r)),this.counter=a,this.aes.pos=o,this.aes.len=c,l}AES_GCM_Decrypt_finish(){let{asm:e,heap:t}=this.aes.acquire_asm(),r=this.tagSize,i=this.adata,n=this.counter,a=this.aes.pos,s=this.aes.len,o=s-r;if(s>>29,t[4]=d>>>21,t[5]=d>>>13&255,t[6]=d>>>5&255,t[7]=d<<3&255,t[8]=t[9]=t[10]=0,t[11]=f>>>29,t[12]=f>>>21&255,t[13]=f>>>13&255,t[14]=f>>>5&255,t[15]=f<<3&255,e.mac(ye.MAC.GCM,ye.HEAP_DATA,16),e.get_iv(ye.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(ye.ENC.CTR,ye.HEAP_DATA,16);let l=0;for(let e=0;e0;){for(a=ge(r,0,e,i,n),i+=a,n-=a;15&a;)r[a++]=0;t.mac(ye.MAC.GCM,ye.HEAP_DATA,a)}}}const Di=X.getWebCrypto(),Ui=X.getNodeCrypto(),Ri=X.getNodeBuffer(),Ii=16,Bi="AES-GCM";async function Ti(e,t){if(e!==$.symmetric.aes128&&e!==$.symmetric.aes192&&e!==$.symmetric.aes256)throw Error("GCM mode supports only AES cipher");if(X.getNodeCrypto())return{encrypt:async function(e,r,i=new Uint8Array){const n=new Ui.createCipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i);const a=Ri.concat([n.update(e),n.final(),n.getAuthTag()]);return new Uint8Array(a)},decrypt:async function(e,r,i=new Uint8Array){const n=new Ui.createDecipheriv("aes-"+8*t.length+"-gcm",t,r);n.setAAD(i),n.setAuthTag(e.slice(e.length-Ii,e.length));const a=Ri.concat([n.update(e.slice(0,e.length-Ii)),n.final()]);return new Uint8Array(a)}};if(X.getWebCrypto()&&24!==t.length){const e=await Di.importKey("raw",t,{name:Bi},!1,["encrypt","decrypt"]);return{encrypt:async function(r,i,n=new Uint8Array){if(!r.length)return Ci.encrypt(r,t,i,n);const a=await Di.encrypt({name:Bi,iv:i,additionalData:n,tagLength:8*Ii},e,r);return new Uint8Array(a)},decrypt:async function(r,i,n=new Uint8Array){if(r.length===Ii)return Ci.decrypt(r,t,i,n);const a=await Di.decrypt({name:Bi,iv:i,additionalData:n,tagLength:8*Ii},e,r);return new Uint8Array(a)}}}return{encrypt:async function(e,r,i){return Ci.encrypt(e,t,r,i)},decrypt:async function(e,r,i){return Ci.decrypt(e,t,r,i)}}}Ti.getNonce=function(e,t){const r=e.slice();for(let e=0;e>>8)-1}(e,t,r,i,32)}function l(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function p(e){var t,r,i=1;for(t=0;t<16;t++)r=e[t]+i+65535,i=Math.floor(r/65536),e[t]=r-65536*i;e[0]+=i-1+37*(i-1)}function y(e,t,r){for(var i,n=~(r-1),a=0;a<16;a++)i=n&(e[a]^t[a]),e[a]^=i,t[a]^=i}function b(e,r){var i,n,a,s=t(),o=t();for(i=0;i<16;i++)o[i]=r[i];for(p(o),p(o),p(o),n=0;n<2;n++){for(s[0]=o[0]-65517,i=1;i<15;i++)s[i]=o[i]-65535-(s[i-1]>>16&1),s[i-1]&=65535;s[15]=o[15]-32767-(s[14]>>16&1),a=s[15]>>16&1,s[14]&=65535,y(o,s,1-a)}for(i=0;i<16;i++)e[2*i]=255&o[i],e[2*i+1]=o[i]>>8}function m(e,t){var r=new Uint8Array(32),i=new Uint8Array(32);return b(r,e),b(i,t),f(r,0,i,0)}function g(e){var t=new Uint8Array(32);return b(t,e),1&t[0]}function w(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function v(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]+r[i]}function _(e,t,r){for(var i=0;i<16;i++)e[i]=t[i]-r[i]}function k(e,t,r){var i,n,a=0,s=0,o=0,c=0,u=0,h=0,d=0,f=0,l=0,p=0,y=0,b=0,m=0,g=0,w=0,v=0,_=0,k=0,A=0,S=0,E=0,P=0,x=0,M=0,K=0,C=0,D=0,U=0,R=0,I=0,B=0,T=r[0],z=r[1],q=r[2],F=r[3],O=r[4],L=r[5],N=r[6],j=r[7],H=r[8],W=r[9],G=r[10],V=r[11],$=r[12],Z=r[13],X=r[14],Y=r[15];a+=(i=t[0])*T,s+=i*z,o+=i*q,c+=i*F,u+=i*O,h+=i*L,d+=i*N,f+=i*j,l+=i*H,p+=i*W,y+=i*G,b+=i*V,m+=i*$,g+=i*Z,w+=i*X,v+=i*Y,s+=(i=t[1])*T,o+=i*z,c+=i*q,u+=i*F,h+=i*O,d+=i*L,f+=i*N,l+=i*j,p+=i*H,y+=i*W,b+=i*G,m+=i*V,g+=i*$,w+=i*Z,v+=i*X,_+=i*Y,o+=(i=t[2])*T,c+=i*z,u+=i*q,h+=i*F,d+=i*O,f+=i*L,l+=i*N,p+=i*j,y+=i*H,b+=i*W,m+=i*G,g+=i*V,w+=i*$,v+=i*Z,_+=i*X,k+=i*Y,c+=(i=t[3])*T,u+=i*z,h+=i*q,d+=i*F,f+=i*O,l+=i*L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,D+=i*Y,m+=(i=t[12])*T,g+=i*z,w+=i*q,v+=i*F,_+=i*O,k+=i*L,A+=i*N,S+=i*j,E+=i*H,P+=i*W,x+=i*G,M+=i*V,K+=i*$,C+=i*Z,D+=i*X,U+=i*Y,g+=(i=t[13])*T,w+=i*z,v+=i*q,_+=i*F,k+=i*O,A+=i*L,S+=i*N,E+=i*j,P+=i*H,x+=i*W,M+=i*G,K+=i*V,C+=i*$,D+=i*Z,U+=i*X,R+=i*Y,w+=(i=t[14])*T,v+=i*z,_+=i*q,k+=i*F,A+=i*O,S+=i*L,E+=i*N,P+=i*j,x+=i*H,M+=i*W,K+=i*G,C+=i*V,D+=i*$,U+=i*Z,R+=i*X,I+=i*Y,v+=(i=t[15])*T,s+=38*(k+=i*q),o+=38*(A+=i*F),c+=38*(S+=i*O),u+=38*(E+=i*L),h+=38*(P+=i*N),d+=38*(x+=i*j),f+=38*(M+=i*H),l+=38*(K+=i*W),p+=38*(C+=i*G),y+=38*(D+=i*V),b+=38*(U+=i*$),m+=38*(R+=i*Z),g+=38*(I+=i*X),w+=38*(B+=i*Y),a=(i=(a+=38*(_+=i*z))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a=(i=(a+=n-1+37*(n-1))+(n=1)+65535)-65536*(n=Math.floor(i/65536)),s=(i=s+n+65535)-65536*(n=Math.floor(i/65536)),o=(i=o+n+65535)-65536*(n=Math.floor(i/65536)),c=(i=c+n+65535)-65536*(n=Math.floor(i/65536)),u=(i=u+n+65535)-65536*(n=Math.floor(i/65536)),h=(i=h+n+65535)-65536*(n=Math.floor(i/65536)),d=(i=d+n+65535)-65536*(n=Math.floor(i/65536)),f=(i=f+n+65535)-65536*(n=Math.floor(i/65536)),l=(i=l+n+65535)-65536*(n=Math.floor(i/65536)),p=(i=p+n+65535)-65536*(n=Math.floor(i/65536)),y=(i=y+n+65535)-65536*(n=Math.floor(i/65536)),b=(i=b+n+65535)-65536*(n=Math.floor(i/65536)),m=(i=m+n+65535)-65536*(n=Math.floor(i/65536)),g=(i=g+n+65535)-65536*(n=Math.floor(i/65536)),w=(i=w+n+65535)-65536*(n=Math.floor(i/65536)),v=(i=v+n+65535)-65536*(n=Math.floor(i/65536)),a+=n-1+37*(n-1),e[0]=a,e[1]=s,e[2]=o,e[3]=c,e[4]=u,e[5]=h,e[6]=d,e[7]=f,e[8]=l,e[9]=p,e[10]=y,e[11]=b,e[12]=m,e[13]=g,e[14]=w,e[15]=v}function A(e,t){k(e,t,t)}function S(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=253;i>=0;i--)A(n,n),2!==i&&4!==i&&k(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}function E(e,r,i){var n,a,o=new Uint8Array(32),c=new Float64Array(80),u=t(),h=t(),d=t(),f=t(),l=t(),p=t();for(a=0;a<31;a++)o[a]=r[a];for(o[31]=127&r[31]|64,o[0]&=248,w(c,i),a=0;a<16;a++)h[a]=c[a],f[a]=u[a]=d[a]=0;for(u[0]=f[0]=1,a=254;a>=0;--a)y(u,h,n=o[a>>>3]>>>(7&a)&1),y(d,f,n),v(l,u,d),_(u,u,d),v(d,h,f),_(h,h,f),A(f,l),A(p,u),k(u,d,u),k(d,h,l),v(l,u,d),_(u,u,d),A(h,u),_(d,f,p),k(u,d,s),v(u,u,f),k(d,d,u),k(u,f,p),k(f,h,c),A(h,l),y(u,h,n),y(d,f,n);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=d[a],c[a+48]=h[a],c[a+64]=f[a];var m=c.subarray(32),g=c.subarray(16);return S(m,m),k(g,g,m),b(e,g),0}function P(e,t){return E(e,t,i)}function x(e,r){var i=t(),n=t(),a=t(),s=t(),o=t(),u=t(),h=t(),d=t(),f=t();_(i,e[1],e[0]),_(f,r[1],r[0]),k(i,i,f),v(n,e[0],e[1]),v(f,r[0],r[1]),k(n,n,f),k(a,e[3],r[3]),k(a,a,c),k(s,e[2],r[2]),v(s,s,s),_(o,n,i),_(u,s,a),v(h,s,a),v(d,n,i),k(e[0],o,u),k(e[1],d,h),k(e[2],h,u),k(e[3],o,d)}function M(e,t,r){var i;for(i=0;i<4;i++)y(e[i],t[i],r)}function K(e,r){var i=t(),n=t(),a=t();S(a,r[2]),k(i,r[0],a),k(n,r[1],a),b(e,n),e[31]^=g(i)<<7}function C(e,t,r){var i,s;for(l(e[0],n),l(e[1],a),l(e[2],a),l(e[3],n),s=255;s>=0;--s)M(e,t,i=r[s/8|0]>>(7&s)&1),x(t,e),x(e,e),M(e,t,i)}function D(e,r){var i=[t(),t(),t(),t()];l(i[0],u),l(i[1],h),l(i[2],a),k(i[3],u,h),C(e,i,r)}function U(i,n,a){var s,o,c=[t(),t(),t(),t()];for(a||r(n,32),(s=e.hash(n.subarray(0,32)))[0]&=248,s[31]&=127,s[31]|=64,D(c,s),K(i,c),o=0;o<32;o++)n[o+32]=i[o];return 0}var R=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function I(e,t){var r,i,n,a;for(i=63;i>=32;--i){for(r=0,n=i-32,a=i-12;n>4)*R[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;n++)t[n]-=r*R[n];for(i=0;i<32;i++)t[i+1]+=t[i]>>8,e[i]=255&t[i]}function B(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;I(e,r)}function T(e,r){var i=t(),s=t(),c=t(),u=t(),h=t(),f=t(),p=t();return l(e[2],a),w(e[1],r),A(c,e[1]),k(u,c,o),_(c,c,e[2]),v(u,e[2],u),A(h,u),A(f,h),k(p,f,h),k(i,p,c),k(i,i,u),function(e,r){var i,n=t();for(i=0;i<16;i++)n[i]=r[i];for(i=250;i>=0;i--)A(n,n),1!==i&&k(n,n,r);for(i=0;i<16;i++)e[i]=n[i]}(i,i),k(i,i,c),k(i,i,u),k(i,i,u),k(e[0],i,u),A(s,e[0]),k(s,s,u),m(s,c)&&k(e[0],e[0],d),A(s,e[0]),k(s,s,u),m(s,c)?-1:(g(e[0])===r[31]>>7&&_(e[0],n,e[0]),k(e[3],e[0],e[1]),0)}var z=64;function q(){for(var e=0;e=0},e.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return U(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(q(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;re&&(c.imod(a.leftShift(n)).iadd(a),u=c.mod(s).toNumber())}while(!await Hi(c,t,r));return c}async function Hi(e,t,r){return!(t&&!e.dec().gcd(t).isOne())&&(!!await async function(e){const t=await X.getBigInteger();return Wi.every((r=>0!==e.mod(new t(r))))}(e)&&(!!await async function(e,t){const r=await X.getBigInteger();return t=t||new r(2),t.modExp(e.dec(),e).isOne()}(e)&&!!await async function(e,t,r){const i=await X.getBigInteger(),n=e.bitLength();t||(t=Math.max(1,n/48|0));const a=e.dec();let s=0;for(;!a.getBit(s);)s++;const o=e.rightShift(new i(s));for(;t>0;t--){let t,n=(r?r():await Li(new i(2),a)).modExp(o,e);if(!n.isOne()&&!n.equal(a)){for(t=1;tt-11)throw Error("Message too long");const i=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!i;if(t)return X.selectUint8Array(s,a,t);if(s)return a;throw Error("Decryption error")}async function Zi(e,t,r){let i;if(t.length!==Gr.getHashByteLength(e))throw Error("Invalid hash length");const n=new Uint8Array(Gi[e].length);for(i=0;i{Qi.generateKeyPair("rsa",r,((r,i,n)=>{r?t(r):e(en.decode(n,"der"))}))}));return{n:i.modulus.toArrayLike(Uint8Array),e:i.publicExponent.toArrayLike(Uint8Array),d:i.privateExponent.toArrayLike(Uint8Array),p:i.prime2.toArrayLike(Uint8Array),q:i.prime1.toArrayLike(Uint8Array),u:i.coefficient.toArrayLike(Uint8Array)}}let r,i,n;do{i=await ji(e-(e>>1),t,40),r=await ji(e>>1,t,40),n=r.mul(i)}while(n.bitLength()!==e);const a=r.dec().imul(i.dec());return i.lt(r)&&([r,i]=[i,r]),{n:n.toUint8Array(),e:t.toUint8Array(),d:t.modInv(a).toUint8Array(),p:r.toUint8Array(),q:i.toUint8Array(),u:r.modInv(i).toUint8Array()}},validateParams:async function(e,t,r,i,n,a){const s=await X.getBigInteger();if(e=new s(e),i=new s(i),n=new s(n),!i.mul(n).equal(e))return!1;const o=new s(2);if(a=new s(a),!i.mul(a).mod(n).isOne())return!1;t=new s(t),r=new s(r);const c=new s(Math.floor(e.bitLength()/3)),u=await Li(o,o.leftShift(c)),h=u.mul(r).mul(t);return!(!h.mod(i.dec()).equal(u)||!h.mod(n.dec()).equal(u))}});var nn=/*#__PURE__*/Object.freeze({__proto__:null,encrypt:async function(e,t,r,i){const n=await X.getBigInteger();t=new n(t),r=new n(r),i=new n(i);const a=new n(Vi(e,t.byteLength())),s=await Li(new n(1),t.dec());return{c1:r.modExp(s,t).toUint8Array(),c2:i.modExp(s,t).imul(a).imod(t).toUint8Array()}},decrypt:async function(e,t,r,i,n){const a=await X.getBigInteger();return e=new a(e),t=new a(t),r=new a(r),i=new a(i),$i(e.modExp(i,r).modInv(r).imul(t).imod(r).toUint8Array("be",r.byteLength()),n)},validateParams:async function(e,t,r,i){const n=await X.getBigInteger();e=new n(e),t=new n(t),r=new n(r);const a=new n(1);if(t.lte(a)||t.gte(e))return!1;const s=new n(e.bitLength()),o=new n(1023);if(s.lt(o))return!1;if(!t.modExp(e.dec(),e).isOne())return!1;let c=t;const u=new n(1),h=new n(2).leftShift(new n(17));for(;u.lt(h);){if(c=c.mul(t).imod(e),c.isOne())return!1;u.iinc()}i=new n(i);const d=new n(2),f=await Li(d.leftShift(s.dec()),d.leftShift(s)),l=e.dec().imul(f).iadd(i);return!!r.equal(t.modExp(l,e))}});class an{constructor(e){if(e instanceof an)this.oid=e.oid;else if(X.isArray(e)||X.isUint8Array(e)){if(6===(e=new Uint8Array(e))[0]){if(e[1]!==e.length-2)throw Error("Length mismatch in DER encoded oid");e=e.subarray(2)}this.oid=e}else this.oid=""}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return X.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return X.uint8ArrayToHex(this.oid)}getName(){const e=this.toHex();if($.curve[e])return $.write($.curve,e);throw Error("Unknown curve object identifier.")}}function sn(e,t){return e.keyPair({priv:t})}function on(e,t){const r=e.keyPair({pub:t});if(!0!==r.validate().result)throw Error("Invalid elliptic public key");return r}async function cn(e){if(!ne.useIndutnyElliptic)throw Error("This curve is only supported in the full build of OpenPGP.js");const{default:t}=await Promise.resolve().then((function(){return Eb}));return new t.ec(e)}function un(e){let t,r=0;const i=e[0];return i<192?([r]=e,t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=X.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function hn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):X.concatUint8Array([new Uint8Array([255]),X.writeNumber(e,4)])}function dn(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function fn(e){return new Uint8Array([192|e])}function ln(e,t){return X.concatUint8Array([fn(e),hn(t)])}function pn(e){return[$.packet.literalData,$.packet.compressedData,$.packet.symmetricallyEncryptedData,$.packet.symEncryptedIntegrityProtectedData,$.packet.aeadEncryptedData].includes(e)}async function yn(e,t){const r=C(e);let i,n;try{const s=await r.peekBytes(2);if(!s||s.length<2||0==(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const o=await r.readByte();let c,u,h=-1,d=-1;d=0,0!=(64&o)&&(d=1),d?h=63&o:(h=(63&o)>>2,u=3&o);const f=pn(h);let l,p=null;if(f){if("array"===X.isStream(e)){const e=new a;i=D(e),p=e}else{const e=new S;i=D(e.writable),p=e.readable}n=t({tag:h,packet:p})}else p=[];do{if(d){const e=await r.readByte();if(l=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),l=!0,!f)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(u){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){i&&await i.ready;const{done:t,value:n}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const a=c===1/0?n:n.subarray(0,c-e);if(i?await i.write(a):p.push(a),e+=n.length,e>=c){r.unshift(n.subarray(c-e+n.length));break}}}}while(l);const y=await r.peekBytes(f?1/0:2);return i?(await i.ready,await i.close()):(p=X.concatUint8Array(p),await t({tag:h,packet:p})),!y||!y.length}catch(e){if(i)return await i.abort(e),!0;throw e}finally{i&&await n,r.releaseLock()}}class bn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,bn),this.name="UnsupportedError"}}class mn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}const gn=X.getWebCrypto(),wn=X.getNodeCrypto(),vn={p256:"P-256",p384:"P-384",p521:"P-521"},_n=wn?wn.getCurves():[],kn=wn?{secp256k1:_n.includes("secp256k1")?"secp256k1":void 0,p256:_n.includes("prime256v1")?"prime256v1":void 0,p384:_n.includes("secp384r1")?"secp384r1":void 0,p521:_n.includes("secp521r1")?"secp521r1":void 0,ed25519:_n.includes("ED25519")?"ED25519":void 0,curve25519:_n.includes("X25519")?"X25519":void 0,brainpoolP256r1:_n.includes("brainpoolP256r1")?"brainpoolP256r1":void 0,brainpoolP384r1:_n.includes("brainpoolP384r1")?"brainpoolP384r1":void 0,brainpoolP512r1:_n.includes("brainpoolP512r1")?"brainpoolP512r1":void 0}:{},An={p256:{oid:[6,8,42,134,72,206,61,3,1,7],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:kn.p256,web:vn.p256,payloadSize:32,sharedSize:256},p384:{oid:[6,5,43,129,4,0,34],keyType:$.publicKey.ecdsa,hash:$.hash.sha384,cipher:$.symmetric.aes192,node:kn.p384,web:vn.p384,payloadSize:48,sharedSize:384},p521:{oid:[6,5,43,129,4,0,35],keyType:$.publicKey.ecdsa,hash:$.hash.sha512,cipher:$.symmetric.aes256,node:kn.p521,web:vn.p521,payloadSize:66,sharedSize:528},secp256k1:{oid:[6,5,43,129,4,0,10],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:kn.secp256k1,payloadSize:32},ed25519:{oid:[6,9,43,6,1,4,1,218,71,15,1],keyType:$.publicKey.eddsaLegacy,hash:$.hash.sha512,node:!1,payloadSize:32},curve25519:{oid:[6,10,43,6,1,4,1,151,85,1,5,1],keyType:$.publicKey.ecdh,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:!1,payloadSize:32},brainpoolP256r1:{oid:[6,9,43,36,3,3,2,8,1,1,7],keyType:$.publicKey.ecdsa,hash:$.hash.sha256,cipher:$.symmetric.aes128,node:kn.brainpoolP256r1,payloadSize:32},brainpoolP384r1:{oid:[6,9,43,36,3,3,2,8,1,1,11],keyType:$.publicKey.ecdsa,hash:$.hash.sha384,cipher:$.symmetric.aes192,node:kn.brainpoolP384r1,payloadSize:48},brainpoolP512r1:{oid:[6,9,43,36,3,3,2,8,1,1,13],keyType:$.publicKey.ecdsa,hash:$.hash.sha512,cipher:$.symmetric.aes256,node:kn.brainpoolP512r1,payloadSize:64}};class Sn{constructor(e,t){try{(X.isArray(e)||X.isUint8Array(e))&&(e=new an(e)),e instanceof an&&(e=e.getName()),this.name=$.write($.curve,e)}catch(e){throw new bn("Unknown curve")}t=t||An[this.name],this.keyType=t.keyType,this.oid=t.oid,this.hash=t.hash,this.cipher=t.cipher,this.node=t.node&&An[this.name],this.web=t.web&&An[this.name],this.payloadSize=t.payloadSize,this.web&&X.getWebCrypto()?this.type="web":this.node&&X.getNodeCrypto()?this.type="node":"curve25519"===this.name?this.type="curve25519":"ed25519"===this.name&&(this.type="ed25519")}async genKeyPair(){let e;switch(this.type){case"web":try{return await async function(e){const t=await gn.generateKey({name:"ECDSA",namedCurve:vn[e]},!0,["sign","verify"]),r=await gn.exportKey("jwk",t.privateKey),i=await gn.exportKey("jwk",t.publicKey);return{publicKey:Pn(i),privateKey:re(r.d)}}(this.name)}catch(e){X.printDebugError("Browser did not support generating ec key "+e.message);break}case"node":return async function(e){const t=wn.createECDH(kn[e]);return await t.generateKeys(),{publicKey:new Uint8Array(t.getPublicKey()),privateKey:new Uint8Array(t.getPrivateKey())}}(this.name);case"curve25519":{const t=Oi(32);t[0]=127&t[0]|64,t[31]&=248;const r=t.slice().reverse();e=qi.box.keyPair.fromSecretKey(r);return{publicKey:X.concatUint8Array([new Uint8Array([64]),e.publicKey]),privateKey:t}}case"ed25519":{const e=Oi(32),t=qi.sign.keyPair.fromSeed(e);return{publicKey:X.concatUint8Array([new Uint8Array([64]),t.publicKey]),privateKey:e}}}const t=await cn(this.name);return e=await t.genKeyPair({entropy:X.uint8ArrayToString(Oi(32))}),{publicKey:new Uint8Array(e.getPublic("array",!1)),privateKey:e.getPrivate().toArrayLike(Uint8Array)}}}async function En(e,t,r,i){const n={p256:!0,p384:!0,p521:!0,secp256k1:!0,curve25519:e===$.publicKey.ecdh,brainpoolP256r1:!0,brainpoolP384r1:!0,brainpoolP512r1:!0},a=t.getName();if(!n[a])return!1;if("curve25519"===a){i=i.slice().reverse();const{publicKey:e}=qi.box.keyPair.fromSecretKey(i);r=new Uint8Array(r);const t=new Uint8Array([64,...e]);return!!X.equalsUint8Array(t,r)}const s=await cn(a);try{r=on(s,r).getPublic()}catch(e){return!1}return!!sn(s,i).getPublic().eq(r)}function Pn(e){const t=re(e.x),r=re(e.y),i=new Uint8Array(t.length+r.length+1);return i[0]=4,i.set(t,1),i.set(r,t.length+1),i}function xn(e,t,r){const i=e,n=r.slice(1,i+1),a=r.slice(i+1,2*i+1);return{kty:"EC",crv:t,x:ie(n,!0),y:ie(a,!0),ext:!0}}function Mn(e,t,r,i){const n=xn(e,t,r);return n.d=ie(i,!0),n}const Kn=X.getWebCrypto(),Cn=X.getNodeCrypto();async function Dn(e,t,r,i,n,a){const s=new Sn(e);if(r&&!X.isStream(r)){const e={publicKey:i,privateKey:n};switch(s.type){case"web":try{return await async function(e,t,r,i){const n=e.payloadSize,a=Mn(e.payloadSize,vn[e.name],i.publicKey,i.privateKey),s=await Kn.importKey("jwk",a,{name:"ECDSA",namedCurve:vn[e.name],hash:{name:$.read($.webHash,e.hash)}},!1,["sign"]),o=new Uint8Array(await Kn.sign({name:"ECDSA",namedCurve:vn[e.name],hash:{name:$.read($.webHash,t)}},s,r));return{r:o.slice(0,n),s:o.slice(n,n<<1)}}(s,t,r,e)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;X.printDebugError("Browser did not support signing: "+e.message)}break;case"node":{const i=await async function(e,t,r,i){const n=Cn.createSign($.read($.hash,t));n.write(r),n.end();const a=Bn.encode({version:1,parameters:e.oid,privateKey:Array.from(i.privateKey),publicKey:{unused:0,data:Array.from(i.publicKey)}},"pem",{label:"EC PRIVATE KEY"});return In.decode(n.sign(a),"der")}(s,t,r,e);return{r:i.r.toArrayLike(Uint8Array),s:i.s.toArrayLike(Uint8Array)}}}}return async function(e,t,r){const i=await cn(e.name),n=sn(i,r),a=n.sign(t);return{r:a.r.toArrayLike(Uint8Array),s:a.s.toArrayLike(Uint8Array)}}(s,a,n)}async function Un(e,t,r,i,n,a){const s=new Sn(e);if(i&&!X.isStream(i))switch(s.type){case"web":try{return await async function(e,t,{r,s:i},n,a){const s=xn(e.payloadSize,vn[e.name],a),o=await Kn.importKey("jwk",s,{name:"ECDSA",namedCurve:vn[e.name],hash:{name:$.read($.webHash,e.hash)}},!1,["verify"]),c=X.concatUint8Array([r,i]).buffer;return Kn.verify({name:"ECDSA",namedCurve:vn[e.name],hash:{name:$.read($.webHash,t)}},o,c,n)}(s,t,r,i,n)}catch(e){if("p521"!==s.name&&("DataError"===e.name||"OperationError"===e.name))throw e;X.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":return async function(e,t,{r,s:i},n,a){const{default:s}=await Promise.resolve().then((function(){return sy})),o=Cn.createVerify($.read($.hash,t));o.write(n),o.end();const c=zn.encode({algorithm:{algorithm:[1,2,840,10045,2,1],parameters:e.oid},subjectPublicKey:{unused:0,data:Array.from(a)}},"pem",{label:"PUBLIC KEY"}),u=In.encode({r:new s(r),s:new s(i)},"der");try{return o.verify(c,u)}catch(e){return!1}}(s,t,r,i,n)}return async function(e,t,r,i){const n=await cn(e.name),a=on(n,i);return a.verify(r,t)}(s,r,void 0===t?i:a,n)}const Rn=void 0,In=Cn?Rn.define("ECDSASignature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())})):void 0,Bn=Cn?Rn.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().any(),this.key("publicKey").explicit(1).optional().bitstr())})):void 0,Tn=Cn?Rn.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().any())})):void 0,zn=Cn?Rn.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(Tn),this.key("subjectPublicKey").bitstr())})):void 0;var qn=/*#__PURE__*/Object.freeze({__proto__:null,sign:Dn,verify:Un,validateParams:async function(e,t,r){const i=new Sn(e);if(i.keyType!==$.publicKey.ecdsa)return!1;switch(i.type){case"web":case"node":{const i=Oi(8),n=$.hash.sha256,a=await Gr.digest(n,i);try{const s=await Dn(e,n,i,t,r,a);return await Un(e,n,s,i,t,a)}catch(e){return!1}}default:return En($.publicKey.ecdsa,e,t,r)}}});qi.hash=e=>new Uint8Array(Jt().update(e).digest());var Fn=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){if(Gr.getHashByteLength(t)new Uint8Array(Jt().update(e).digest());var Ln=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===$.publicKey.ed25519){const e=Oi(32),{publicKey:t}=qi.sign.keyPair.fromSeed(e);return{A:t,seed:e}}throw Error("Unsupported EdDSA algorithm")},sign:async function(e,t,r,i,n,a){if(Gr.getHashByteLength(t)=0;--e)for(let t=o-1;t>=0;--t)c[1]=o*e+(t+1),u[0]=a[0]^c[0],u[1]=a[1]^c[1],u[2]=s[2*t],u[3]=s[2*t+1],u=Hn(r.decrypt(Wn(u))),a=u.subarray(0,2),s[2*t]=u[2],s[2*t+1]=u[3];if(a[0]===i[0]&&a[1]===i[1])return Wn(s);throw Error("Key Data Integrity failed")}function Hn(e){const{length:t}=e,r=function(e){if(X.isString(e)){const{length:t}=e,r=new ArrayBuffer(t),i=new Uint8Array(r);for(let r=0;r0){const r=e[t-1];if(r>=1){const i=e.subarray(t-r),n=new Uint8Array(r).fill(r);if(X.equalsUint8Array(i,n))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Zn=/*#__PURE__*/Object.freeze({__proto__:null,encode:Vn,decode:$n});const Xn=X.getWebCrypto(),Yn=X.getNodeCrypto();function Qn(e,t,r,i){return X.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),X.stringToUint8Array("Anonymous Sender "),i.subarray(0,20)])}async function Jn(e,t,r,i,n=!1,a=!1){let s;if(n){for(s=0;s=0&&0===t[s];s--);t=t.subarray(0,s+1)}return(await Gr.digest(e,X.concatUint8Array([new Uint8Array([0,0,0,1]),t,i]))).subarray(0,r)}async function ea(e,t){switch(e.type){case"curve25519":{const r=Oi(32),{secretKey:i,sharedKey:n}=await ta(e,t,null,r);let{publicKey:a}=qi.box.keyPair.fromSecretKey(i);return a=X.concatUint8Array([new Uint8Array([64]),a]),{publicKey:a,sharedKey:n}}case"web":if(e.web&&X.getWebCrypto())try{return await async function(e,t){const r=xn(e.payloadSize,e.web.web,t);let i=Xn.generateKey({name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]),n=Xn.importKey("jwk",r,{name:"ECDH",namedCurve:e.web.web},!1,[]);[i,n]=await Promise.all([i,n]);let a=Xn.deriveBits({name:"ECDH",namedCurve:e.web.web,public:n},i.privateKey,e.web.sharedSize),s=Xn.exportKey("jwk",i.publicKey);[a,s]=await Promise.all([a,s]);const o=new Uint8Array(a),c=new Uint8Array(Pn(s));return{publicKey:c,sharedKey:o}}(e,t)}catch(e){X.printDebugError(e)}break;case"node":return async function(e,t){const r=Yn.createECDH(e.node.node);r.generateKeys();const i=new Uint8Array(r.computeSecret(t)),n=new Uint8Array(r.getPublicKey());return{publicKey:n,sharedKey:i}}(e,t)}return async function(e,t){const r=await cn(e.name),i=await e.genKeyPair();t=on(r,t);const n=sn(r,i.privateKey),a=i.publicKey,s=n.derive(t.getPublic()),o=r.curve.p.byteLength(),c=s.toArrayLike(Uint8Array,"be",o);return{publicKey:a,sharedKey:c}}(e,t)}async function ta(e,t,r,i){if(i.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(i,e.payloadSize-i.length),i=t}switch(e.type){case"curve25519":{const e=i.slice().reverse();return{secretKey:e,sharedKey:qi.scalarMult(e,t.subarray(1))}}case"web":if(e.web&&X.getWebCrypto())try{return await async function(e,t,r,i){const n=Mn(e.payloadSize,e.web.web,r,i);let a=Xn.importKey("jwk",n,{name:"ECDH",namedCurve:e.web.web},!0,["deriveKey","deriveBits"]);const s=xn(e.payloadSize,e.web.web,t);let o=Xn.importKey("jwk",s,{name:"ECDH",namedCurve:e.web.web},!0,[]);[a,o]=await Promise.all([a,o]);let c=Xn.deriveBits({name:"ECDH",namedCurve:e.web.web,public:o},a,e.web.sharedSize),u=Xn.exportKey("jwk",a);[c,u]=await Promise.all([c,u]);const h=new Uint8Array(c);return{secretKey:re(u.d),sharedKey:h}}(e,t,r,i)}catch(e){X.printDebugError(e)}break;case"node":return async function(e,t,r){const i=Yn.createECDH(e.node.node);i.setPrivateKey(r);const n=new Uint8Array(i.computeSecret(t));return{secretKey:new Uint8Array(i.getPrivateKey()),sharedKey:n}}(e,t,i)}return async function(e,t,r){const i=await cn(e.name);t=on(i,t),r=sn(i,r);const n=new Uint8Array(r.getPrivate()),a=r.derive(t.getPublic()),s=i.curve.p.byteLength(),o=a.toArrayLike(Uint8Array,"be",s);return{secretKey:n,sharedKey:o}}(e,t,i)}var ra=/*#__PURE__*/Object.freeze({__proto__:null,validateParams:async function(e,t,r){return En($.publicKey.ecdh,e,t,r)},encrypt:async function(e,t,r,i,n){const a=Vn(r),s=new Sn(e),{publicKey:o,sharedKey:c}=await ea(s,i),u=Qn($.publicKey.ecdh,e,t,n),{keySize:h}=$r(t.cipher);return{publicKey:o,wrappedKey:Nn(await Jn(t.hash,c,h,u),a)}},decrypt:async function(e,t,r,i,n,a,s){const o=new Sn(e),{sharedKey:c}=await ta(o,r,n,a),u=Qn($.publicKey.ecdh,e,t,s),{keySize:h}=$r(t.cipher);let d;for(let e=0;e<3;e++)try{return $n(jn(await Jn(t.hash,c,h,u,1===e,2===e),i))}catch(e){d=e}throw d}});const ia=X.getWebCrypto(),na=X.getNodeCrypto(),aa=na&&na.webcrypto&&na.webcrypto.subtle;async function sa(e,t,r,i,n){const a=$.read($.webHash,e);if(!a)throw Error("Hash algo not supported with HKDF");if(ia||aa){const e=ia||aa,s=await e.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await e.deriveBits({name:"HKDF",hash:a,salt:r,info:i},s,8*n);return new Uint8Array(o)}if(na){const a=$.read($.hash,e),s=(e,t)=>na.createHmac(a,e).update(t).digest(),o=s(r,t),c=o.length,u=Math.ceil(n/c),h=new Uint8Array(u*c),d=new Uint8Array(c+i.length+1);d.set(i,c);for(let e=0;e0?d:d.subarray(c));d.set(t,0),h.set(t,e*c)}return h.subarray(0,n)}throw Error("No HKDF implementation available")}const oa={x25519:X.encodeUTF8("OpenPGP X25519")};var ca=/*#__PURE__*/Object.freeze({__proto__:null,generate:async function(e){if(e===$.publicKey.x25519){const e=Oi(32),{publicKey:t}=qi.box.keyPair.fromSecretKey(e);return{A:t,k:e}}throw Error("Unsupported ECDH algorithm")},validateParams:async function(e,t,r){if(e===$.publicKey.x25519){const{publicKey:e}=qi.box.keyPair.fromSecretKey(r);return X.equalsUint8Array(t,e)}return!1},encrypt:async function(e,t,r){if(e===$.publicKey.x25519){const e=Oi(32),i=qi.scalarMult(e,r),{publicKey:n}=qi.box.keyPair.fromSecretKey(e),a=X.concatUint8Array([n,r,i]),{keySize:s}=$r($.symmetric.aes128);return{ephemeralPublicKey:n,wrappedKey:Nn(await sa($.hash.sha256,a,new Uint8Array,oa.x25519,s),t)}}throw Error("Unsupported ECDH algorithm")},decrypt:async function(e,t,r,i,n){if(e===$.publicKey.x25519){const e=qi.scalarMult(n,t),a=X.concatUint8Array([t,i,e]),{keySize:s}=$r($.symmetric.aes128);return jn(await sa($.hash.sha256,a,new Uint8Array,oa.x25519,s),r)}throw Error("Unsupported ECDH algorithm")}}),ua=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:Sn,ecdh:ra,ecdhX:ca,ecdsa:qn,eddsaLegacy:Fn,eddsa:Ln,generate:async function(e){const t=await X.getBigInteger();e=new Sn(e);const r=await e.genKeyPair(),i=new t(r.publicKey).toUint8Array(),n=new t(r.privateKey).toUint8Array("be",e.payloadSize);return{oid:e.oid,Q:i,secret:n,hash:e.hash,cipher:e.cipher}},getPreferredHashAlgo:function(e){return An[$.write($.curve,e.toHex())].hash}});var ha=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,i,n,a){const s=await X.getBigInteger(),o=new s(1);let c,u,h,d;i=new s(i),n=new s(n),r=new s(r),a=new s(a),r=r.mod(i),a=a.mod(n);const f=new s(t.subarray(0,n.byteLength())).mod(n);for(;;){if(c=await Li(o,n),u=r.modExp(c,i).imod(n),u.isZero())continue;const e=a.mul(u).imod(n);if(d=f.add(e).imod(n),h=c.modInv(n).imul(d).imod(n),!h.isZero())break}return{r:u.toUint8Array("be",n.byteLength()),s:h.toUint8Array("be",n.byteLength())}},verify:async function(e,t,r,i,n,a,s,o){const c=await X.getBigInteger(),u=new c(0);if(t=new c(t),r=new c(r),a=new c(a),s=new c(s),n=new c(n),o=new c(o),t.lte(u)||t.gte(s)||r.lte(u)||r.gte(s))return X.printDebug("invalid DSA Signature"),!1;const h=new c(i.subarray(0,s.byteLength())).imod(s),d=r.modInv(s);if(d.isZero())return X.printDebug("invalid DSA Signature"),!1;n=n.mod(a),o=o.mod(a);const f=h.mul(d).imod(s),l=t.mul(d).imod(s),p=n.modExp(f,a),y=o.modExp(l,a);return p.mul(y).imod(a).imod(s).equal(t)},validateParams:async function(e,t,r,i,n){const a=await X.getBigInteger();e=new a(e),t=new a(t),r=new a(r),i=new a(i);const s=new a(1);if(r.lte(s)||r.gte(e))return!1;if(!e.dec().mod(t).isZero())return!1;if(!r.modExp(t,e).isOne())return!1;const o=new a(t.bitLength()),c=new a(150);if(o.lt(c)||!await Hi(t,null,32))return!1;n=new a(n);const u=new a(2),h=await Li(u.leftShift(o.dec()),u.leftShift(o)),d=t.mul(h).add(n);return!!i.equal(r.modExp(d,e))}}),da={rsa:rn,elgamal:nn,elliptic:ua,dsa:ha,nacl:qi};var fa=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:return{s:X.readMPI(t.subarray(r))};case $.publicKey.dsa:case $.publicKey.ecdsa:{const e=X.readMPI(t.subarray(r));r+=e.length+2;return{r:e,s:X.readMPI(t.subarray(r))}}case $.publicKey.eddsaLegacy:{let e=X.readMPI(t.subarray(r));r+=e.length+2,e=X.leftPad(e,32);let i=X.readMPI(t.subarray(r));return i=X.leftPad(i,32),{r:e,s:i}}case $.publicKey.ed25519:{const e=t.subarray(r,r+64);return r+=e.length,{RS:e}}default:throw new bn("Unknown signature algorithm.")}},verify:async function(e,t,r,i,n,a){switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:{const{n:e,e:s}=i,o=X.leftPad(r.s,e.length);return da.rsa.verify(t,n,o,e,s,a)}case $.publicKey.dsa:{const{g:e,p:n,q:s,y:o}=i,{r:c,s:u}=r;return da.dsa.verify(t,c,u,a,e,n,s,o)}case $.publicKey.ecdsa:{const{oid:e,Q:s}=i,o=new da.elliptic.CurveWithOID(e).payloadSize,c=X.leftPad(r.r,o),u=X.leftPad(r.s,o);return da.elliptic.ecdsa.verify(e,t,{r:c,s:u},n,s,a)}case $.publicKey.eddsaLegacy:{const{oid:e,Q:s}=i;return da.elliptic.eddsaLegacy.verify(e,t,r,n,s,a)}case $.publicKey.ed25519:{const{A:s}=i;return da.elliptic.eddsa.verify(e,t,r,n,s,a)}default:throw Error("Unknown signature algorithm.")}},sign:async function(e,t,r,i,n,a){if(!r||!i)throw Error("Missing key parameters");switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:case $.publicKey.rsaSign:{const{n:e,e:s}=r,{d:o,p:c,q:u,u:h}=i;return{s:await da.rsa.sign(t,n,e,s,o,c,u,h,a)}}case $.publicKey.dsa:{const{g:e,p:n,q:s}=r,{x:o}=i;return da.dsa.sign(t,a,e,n,s,o)}case $.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case $.publicKey.ecdsa:{const{oid:e,Q:s}=r,{d:o}=i;return da.elliptic.ecdsa.sign(e,t,n,s,o,a)}case $.publicKey.eddsaLegacy:{const{oid:e,Q:s}=r,{seed:o}=i;return da.elliptic.eddsaLegacy.sign(e,t,n,s,o,a)}case $.publicKey.ed25519:{const{A:s}=r,{seed:o}=i;return da.elliptic.eddsa.sign(e,t,n,s,o,a)}default:throw Error("Unknown signature algorithm.")}}});class la{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return X.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class pa{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new bn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class ya{static fromObject({wrappedKey:e,algorithm:t}){const r=new ya;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=e.subarray(t,t+r),t+=r}write(){return X.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function ba(e){try{e.getName()}catch(e){throw new bn("Unknown curve OID")}}var ma=/*#__PURE__*/Object.freeze({__proto__:null,publicKeyEncrypt:async function(e,t,r,i,n){switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await da.rsa.encrypt(i,e,t)}}case $.publicKey.elgamal:{const{p:e,g:t,y:n}=r;return da.elgamal.encrypt(i,e,t,n)}case $.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:a}=r,{publicKey:s,wrappedKey:o}=await da.elliptic.ecdh.encrypt(e,a,i,t,n);return{V:s,C:new la(o)}}case $.publicKey.x25519:{if(!X.isAES(t))throw Error("X25519 keys can only encrypt AES session keys");const{A:n}=r,{ephemeralPublicKey:a,wrappedKey:s}=await da.elliptic.ecdhX.encrypt(e,i,n);return{ephemeralPublicKey:a,C:ya.fromObject({algorithm:t,wrappedKey:s})}}default:return[]}},publicKeyDecrypt:async function(e,t,r,i,n,a){switch(e){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaEncrypt:{const{c:e}=i,{n,e:s}=t,{d:o,p:c,q:u,u:h}=r;return da.rsa.decrypt(e,n,s,o,c,u,h,a)}case $.publicKey.elgamal:{const{c1:e,c2:n}=i,s=t.p,o=r.x;return da.elgamal.decrypt(e,n,s,o,a)}case $.publicKey.ecdh:{const{oid:e,Q:a,kdfParams:s}=t,{d:o}=r,{V:c,C:u}=i;return da.elliptic.ecdh.decrypt(e,s,c,u.data,a,o,n)}case $.publicKey.x25519:{const{A:n}=t,{k:a}=r,{ephemeralPublicKey:s,C:o}=i;if(!X.isAES(o.algorithm))throw Error("AES session key expected");return da.elliptic.ecdhX.decrypt(e,s,o.wrappedKey,n,a)}default:throw Error("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const i=X.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{n:e,e:i}}}case $.publicKey.dsa:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const i=X.readMPI(t.subarray(r));r+=i.length+2;const n=X.readMPI(t.subarray(r));r+=n.length+2;const a=X.readMPI(t.subarray(r));return r+=a.length+2,{read:r,publicParams:{p:e,q:i,g:n,y:a}}}case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const i=X.readMPI(t.subarray(r));r+=i.length+2;const n=X.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{p:e,g:i,y:n}}}case $.publicKey.ecdsa:{const e=new an;r+=e.read(t),ba(e);const i=X.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{oid:e,Q:i}}}case $.publicKey.eddsaLegacy:{const e=new an;r+=e.read(t),ba(e);let i=X.readMPI(t.subarray(r));return r+=i.length+2,i=X.leftPad(i,33),{read:r,publicParams:{oid:e,Q:i}}}case $.publicKey.ecdh:{const e=new an;r+=e.read(t),ba(e);const i=X.readMPI(t.subarray(r));r+=i.length+2;const n=new pa;return r+=n.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:i,kdfParams:n}}}case $.publicKey.ed25519:case $.publicKey.x25519:{const e=t.subarray(r,r+32);return r+=e.length,{read:r,publicParams:{A:e}}}default:throw new bn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let i=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const e=X.readMPI(t.subarray(i));i+=e.length+2;const r=X.readMPI(t.subarray(i));i+=r.length+2;const n=X.readMPI(t.subarray(i));i+=n.length+2;const a=X.readMPI(t.subarray(i));return i+=a.length+2,{read:i,privateParams:{d:e,p:r,q:n,u:a}}}case $.publicKey.dsa:case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(i));return i+=e.length+2,{read:i,privateParams:{x:e}}}case $.publicKey.ecdsa:case $.publicKey.ecdh:{const e=new Sn(r.oid);let n=X.readMPI(t.subarray(i));return i+=n.length+2,n=X.leftPad(n,e.payloadSize),{read:i,privateParams:{d:n}}}case $.publicKey.eddsaLegacy:{const e=new Sn(r.oid);let n=X.readMPI(t.subarray(i));return i+=n.length+2,n=X.leftPad(n,e.payloadSize),{read:i,privateParams:{seed:n}}}case $.publicKey.ed25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{seed:e}}}case $.publicKey.x25519:{const e=t.subarray(i,i+32);return i+=e.length,{read:i,privateParams:{k:e}}}default:throw new bn("Unknown public key encryption algorithm.")}},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:return{c:X.readMPI(t.subarray(r))};case $.publicKey.elgamal:{const e=X.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:X.readMPI(t.subarray(r))}}case $.publicKey.ecdh:{const e=X.readMPI(t.subarray(r));r+=e.length+2;const i=new la;return i.read(t.subarray(r)),{V:e,C:i}}case $.publicKey.x25519:{const e=t.subarray(r,r+32);r+=e.length;const i=new ya;return i.read(t.subarray(r)),{ephemeralPublicKey:e,C:i}}default:throw new bn("Unknown public key encryption algorithm.")}},serializeParams:function(e,t){const r=new Set([$.publicKey.ed25519,$.publicKey.x25519]),i=Object.keys(t).map((i=>{const n=t[i];return X.isUint8Array(n)?r.has(e)?n:X.uint8ArrayToMPI(n):n.write()}));return X.concatUint8Array(i)},generateParams:function(e,t,r){switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:return da.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:i,q:n,u:a})=>({privateParams:{d:r,p:i,q:n,u:a},publicParams:{n:e,e:t}})));case $.publicKey.ecdsa:return da.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new an(e),Q:t}})));case $.publicKey.eddsaLegacy:return da.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new an(e),Q:t}})));case $.publicKey.ecdh:return da.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:i,cipher:n})=>({privateParams:{d:r},publicParams:{oid:new an(e),Q:t,kdfParams:new pa({hash:i,cipher:n})}})));case $.publicKey.ed25519:return da.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case $.publicKey.x25519:return da.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case $.publicKey.dsa:case $.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:{const{n:e,e:i}=t,{d:n,p:a,q:s,u:o}=r;return da.rsa.validateParams(e,i,n,a,s,o)}case $.publicKey.dsa:{const{p:e,q:i,g:n,y:a}=t,{x:s}=r;return da.dsa.validateParams(e,i,n,a,s)}case $.publicKey.elgamal:{const{p:e,g:i,y:n}=t,{x:a}=r;return da.elgamal.validateParams(e,i,n,a)}case $.publicKey.ecdsa:case $.publicKey.ecdh:{const i=da.elliptic[$.read($.publicKey,e)],{oid:n,Q:a}=t,{d:s}=r;return i.validateParams(n,a,s)}case $.publicKey.eddsaLegacy:{const{Q:e,oid:i}=t,{seed:n}=r;return da.elliptic.eddsaLegacy.validateParams(i,e,n)}case $.publicKey.ed25519:{const{A:i}=t,{seed:n}=r;return da.elliptic.eddsa.validateParams(e,i,n)}case $.publicKey.x25519:{const{A:i}=t,{k:n}=r;return da.elliptic.ecdhX.validateParams(e,i,n)}default:throw Error("Unknown public key algorithm.")}},getPrefixRandom:async function(e){const{blockSize:t}=$r(e),r=await Oi(t),i=new Uint8Array([r[r.length-2],r[r.length-1]]);return X.concat([r,i])},generateSessionKey:function(e){const{keySize:t}=$r(e);return Oi(t)},getAEADMode:function(e){const t=$.read($.aead,e);return zi[t]},getCipher:$r,getPreferredCurveHashAlgo:function(e,t){switch(e){case $.publicKey.ecdsa:case $.publicKey.eddsaLegacy:return da.elliptic.getPreferredHashAlgo(t);case $.publicKey.ed25519:return da.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}}});const ga={cipher:We,hash:Gr,mode:zi,publicKey:da,signature:fa,random:Ni,pkcs1:Xi,pkcs5:Zn,aesKW:Gn};Object.assign(ga,ma);var wa="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function va(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)}const _a={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+i),n);else for(let a=0;a=0;)e[t]=0}const Ya=0,Qa=1,Ja=2,es=29,ts=256,rs=ts+1+es,is=30,ns=19,as=2*rs+1,ss=15,os=16,cs=7,us=256,hs=16,ds=17,fs=18,ls=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ps=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ys=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ms=Array(2*(rs+2));Xa(ms);const gs=Array(2*is);Xa(gs);const ws=Array(512);Xa(ws);const vs=Array(256);Xa(vs);const _s=Array(es);Xa(_s);const ks=Array(is);function As(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}let Ss,Es,Ps;function xs(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Ms(e){return e<256?ws[e]:ws[256+(e>>>7)]}function Ks(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Cs(e,t,r){e.bi_valid>os-r?(e.bi_buf|=t<>os-e.bi_valid,e.bi_valid+=r-os):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Rs(e,t,r){const i=Array(ss+1);let n,a,s=0;for(n=1;n<=ss;n++)i[n]=s=s+r[n-1]<<1;for(a=0;a<=t;a++){const t=e[2*a+1];0!==t&&(e[2*a]=Us(i[t]++,t))}}function Is(e){let t;for(t=0;t8?Ks(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Ts(e,t,r,i){const n=2*t,a=2*r;return e[n]>1;s>=1;s--)zs(e,r,s);c=a;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],zs(e,r,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,r[2*c]=r[2*s]+r[2*o],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,r[2*s+1]=r[2*o+1]=c,e.heap[1]=c++,zs(e,r,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){const r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let u,h,d,f,l,p,y=0;for(f=0;f<=ss;f++)e.bl_count[f]=0;for(r[2*e.heap[e.heap_max]+1]=0,u=e.heap_max+1;uc&&(f=c,y++),r[2*h+1]=f,h>i||(e.bl_count[f]++,l=0,h>=o&&(l=s[h-o]),p=r[2*h],e.opt_len+=p*(f+l),a&&(e.static_len+=p*(n[2*h+1]+l)));if(0!==y){do{for(f=c-1;0===e.bl_count[f];)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,y-=2}while(y>0);for(f=c;0!==f;f--)for(h=e.bl_count[f];0!==h;)d=e.heap[--u],d>i||(r[2*d+1]!==f&&(e.opt_len+=(f-r[2*d+1])*r[2*d],r[2*d+1]=f),h--)}}(e,t),Rs(r,u,e.bl_count)}function Os(e,t,r){let i,n,a=-1,s=t[1],o=0,c=7,u=4;for(0===s&&(c=138,u=3),t[2*(r+1)+1]=65535,i=0;i<=r;i++)n=s,s=t[2*(i+1)+1],++o>=7;i=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function Gs(e,t,r,i){let n,a,s=0;e.level>0?(e.strm.data_type===$a&&(e.strm.data_type=function(e){let t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return Ga;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return Va;for(t=32;t=3&&0===e.bl_tree[2*bs[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),n=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=n&&(n=a)):n=a=r+5,r+4<=n&&-1!==t?Hs(e,t,r,i):e.strategy===Wa||a===n?(Cs(e,(Qa<<1)+(i?1:0),3),qs(e,ms,gs)):(Cs(e,(Ja<<1)+(i?1:0),3),function(e,t,r,i){let n;for(Cs(e,t-257,5),Cs(e,r-1,5),Cs(e,i-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(vs[r]+ts+1)]++,e.dyn_dtree[2*Ms(t)]++),e.last_lit===e.lit_bufsize-1}function $s(e,t,r,i){let n=65535&e|0,a=e>>>16&65535|0,s=0;for(;0!==r;){s=r>2e3?2e3:r,r-=s;do{n=n+t[i++]|0,a=a+n|0}while(--s);n%=65521,a%=65521}return n|a<<16|0}const Zs=function(){let e;const t=[];for(let r=0;r<256;r++){e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function Xs(e,t,r,i){const n=Zs,a=i+r;e^=-1;for(let r=i;r>>8^n[255&(e^t[r])];return-1^e}var Ys={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};const Qs=9,Js=3,eo=258,to=eo+Js+1,ro=32,io=42,no=69,ao=73,so=91,oo=103,co=113,uo=666,ho=1,fo=2,lo=3,po=4,yo=3;function bo(e,t){return e.msg=Ys[t],t}function mo(e){return(e<<1)-(e>4?9:0)}function go(e){let t=e.length;for(;--t>=0;)e[t]=0}function wo(e){const t=e.state;let r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(xa(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function vo(e,t){Gs(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,wo(e.strm)}function _o(e,t){e.pending_buf[e.pending++]=t}function ko(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Ao(e,t,r,i){let n=e.avail_in;return n>i&&(n=i),0===n?0:(e.avail_in-=n,xa(t,e.input,e.next_in,n,r),1===e.state.wrap?e.adler=$s(e.adler,t,n,r):2===e.state.wrap&&(e.adler=Xs(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function So(e,t){let r,i,n=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-to?e.strstart-(e.w_size-to):0,u=e.window,h=e.w_mask,d=e.prev,f=e.strstart+eo;let l=u[a+s-1],p=u[a+s];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do{if(r=t,u[r+s]===p&&u[r+s-1]===l&&u[r]===u[a]&&u[++r]===u[a+1]){a+=2,r++;do{}while(u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&u[++a]===u[++r]&&as){if(e.match_start=t,s=i,i>=o)break;l=u[a+s-1],p=u[a+s]}}}while((t=d[t&h])>c&&0!=--n);return s<=e.lookahead?s:e.lookahead}function Eo(e){const t=e.w_size;let r,i,n,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-to)){xa(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do{n=e.head[--r],e.head[r]=n>=t?n-t:0}while(--i);i=t,r=i;do{n=e.prev[--r],e.prev[r]=n>=t?n-t:0}while(--i);a+=t}if(0===e.strm.avail_in)break;if(i=Ao(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=i,e.lookahead+e.insert>=Js)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=Js&&(e.ins_h=(e.ins_h<=Js)if(i=Vs(e,e.strstart-e.match_start,e.match_length-Js),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=Js){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=Js&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=Js-1)),e.prev_length>=Js&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-Js,i=Vs(e,e.strstart-1-e.prev_match,e.prev_length-Js),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Eo(e),0===e.lookahead&&t===Ma)return ho;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;const i=e.block_start+r;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,vo(e,!1),0===e.strm.avail_out))return ho;if(e.strstart-e.block_start>=e.w_size-to&&(vo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ua?(vo(e,!0),0===e.strm.avail_out?lo:po):(e.strstart>e.block_start&&(vo(e,!1),e.strm.avail_out),ho)})),new Mo(4,4,8,4,Po),new Mo(4,5,16,8,Po),new Mo(4,6,32,32,Po),new Mo(4,4,16,16,xo),new Mo(8,16,32,32,xo),new Mo(8,16,128,128,xo),new Mo(8,32,128,256,xo),new Mo(32,128,258,1024,xo),new Mo(32,258,258,4096,xo)];class Co{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Za,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Sa(1146),this.dyn_dtree=new Sa(122),this.bl_tree=new Sa(78),go(this.dyn_ltree),go(this.dyn_dtree),go(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Sa(16),this.heap=new Sa(573),go(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Sa(573),go(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}}function Do(e){const t=function(e){let t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=$a,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?io:co,e.adler=2===t.wrap?0:1,t.last_flush=Ma,js(t),Ba):bo(e,qa)}(e);return t===Ba&&function(e){e.window_size=2*e.w_size,go(e.head),e.max_lazy_match=Ko[e.level].max_lazy,e.good_match=Ko[e.level].good_length,e.nice_match=Ko[e.level].nice_length,e.max_chain_length=Ko[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=Js-1,e.match_available=0,e.ins_h=0}(e.state),t}function Uo(e,t){let r,i,n,a;if(!e||!e.state||t>Ra||t<0)return e?bo(e,qa):qa;if(i=e.state,!e.output||!e.input&&0!==e.avail_in||i.status===uo&&t!==Ua)return bo(e,0===e.avail_out?Oa:qa);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===io)if(2===i.wrap)e.adler=0,_o(i,31),_o(i,139),_o(i,8),i.gzhead?(_o(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),_o(i,255&i.gzhead.time),_o(i,i.gzhead.time>>8&255),_o(i,i.gzhead.time>>16&255),_o(i,i.gzhead.time>>24&255),_o(i,9===i.level?2:i.strategy>=ja||i.level<2?4:0),_o(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(_o(i,255&i.gzhead.extra.length),_o(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Xs(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=no):(_o(i,0),_o(i,0),_o(i,0),_o(i,0),_o(i,0),_o(i,9===i.level?2:i.strategy>=ja||i.level<2?4:0),_o(i,yo),i.status=co);else{let t=Za+(i.w_bits-8<<4)<<8,r=-1;r=i.strategy>=ja||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=ro),t+=31-t%31,i.status=co,ko(i,t),0!==i.strstart&&(ko(i,e.adler>>>16),ko(i,65535&e.adler)),e.adler=1}if(i.status===no)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),wo(e),n=i.pending,i.pending!==i.pending_buf_size));)_o(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=ao)}else i.status=ao;if(i.status===ao)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),wo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.gzindex=0,i.status=so)}else i.status=so;if(i.status===so)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),wo(e),n=i.pending,i.pending===i.pending_buf_size)){a=1;break}a=i.gzindexn&&(e.adler=Xs(e.adler,i.pending_buf,i.pending-n,n)),0===a&&(i.status=oo)}else i.status=oo;if(i.status===oo&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&wo(e),i.pending+2<=i.pending_buf_size&&(_o(i,255&e.adler),_o(i,e.adler>>8&255),e.adler=0,i.status=co)):i.status=co),0!==i.pending){if(wo(e),0===e.avail_out)return i.last_flush=-1,Ba}else if(0===e.avail_in&&mo(t)<=mo(r)&&t!==Ua)return bo(e,Oa);if(i.status===uo&&0!==e.avail_in)return bo(e,Oa);if(0!==e.avail_in||0!==i.lookahead||t!==Ma&&i.status!==uo){var s=i.strategy===ja?function(e,t){let r;for(;;){if(0===e.lookahead&&(Eo(e),0===e.lookahead)){if(t===Ma)return ho;break}if(e.match_length=0,r=Vs(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(vo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ua?(vo(e,!0),0===e.strm.avail_out?lo:po):e.last_lit&&(vo(e,!1),0===e.strm.avail_out)?ho:fo}(i,t):i.strategy===Ha?function(e,t){let r,i,n,a;const s=e.window;for(;;){if(e.lookahead<=eo){if(Eo(e),e.lookahead<=eo&&t===Ma)return ho;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=Js&&e.strstart>0&&(n=e.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){a=e.strstart+eo;do{}while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&ne.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=Js?(r=Vs(e,1,e.match_length-Js),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=Vs(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(vo(e,!1),0===e.strm.avail_out))return ho}return e.insert=0,t===Ua?(vo(e,!0),0===e.strm.avail_out?lo:po):e.last_lit&&(vo(e,!1),0===e.strm.avail_out)?ho:fo}(i,t):Ko[i.level].func(i,t);if(s!==lo&&s!==po||(i.status=uo),s===ho||s===lo)return 0===e.avail_out&&(i.last_flush=-1),Ba;if(s===fo&&(t===Ka?Ws(i):t!==Ra&&(Hs(i,0,0,!1),t===Da&&(go(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),wo(e),0===e.avail_out))return i.last_flush=-1,Ba}return t!==Ua?Ba:i.wrap<=0?Ta:(2===i.wrap?(_o(i,255&e.adler),_o(i,e.adler>>8&255),_o(i,e.adler>>16&255),_o(i,e.adler>>24&255),_o(i,255&e.total_in),_o(i,e.total_in>>8&255),_o(i,e.total_in>>16&255),_o(i,e.total_in>>24&255)):(ko(i,e.adler>>>16),ko(i,65535&e.adler)),wo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Ba:Ta)}try{String.fromCharCode.call(null,0)}catch(e){}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}const Ro=new Aa(256);for(let e=0;e<256;e++)Ro[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;function Io(e){let t,r,i,n,a=0;const s=e.length;for(i=0;i>>6,o[n++]=128|63&t):t<65536?(o[n++]=224|t>>>12,o[n++]=128|t>>>6&63,o[n++]=128|63&t):(o[n++]=240|t>>>18,o[n++]=128|t>>>12&63,o[n++]=128|t>>>6&63,o[n++]=128|63&t);return o}Ro[254]=Ro[254]=1;class Bo{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}class To{constructor(e){this.options={level:La,method:Za,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,...e||{}};const t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Bo,this.strm.avail_out=0;var r,i,n=function(e,t,r,i,n,a){if(!e)return qa;let s=1;if(t===La&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),n<1||n>Qs||r!==Za||i<8||i>15||t<0||t>9||a<0||a>Wa)return bo(e,qa);8===i&&(i=9);const o=new Co;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=i,o.w_size=1<=r.w_size&&(0===a&&(go(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new Aa(r.w_size),xa(u,t,h-r.w_size,r.w_size,0),t=u,h=r.w_size),s=e.avail_in,o=e.next_in,c=e.input,e.avail_in=h,e.next_in=0,e.input=t,Eo(r);r.lookahead>=Js;){i=r.strstart,n=r.lookahead-(Js-1);do{r.ins_h=(r.ins_h<0||0===r.avail_out)&&n!==Ta);return a===Ua?(n=function(e){let t;return e&&e.state?(t=e.state.status,t!==io&&t!==no&&t!==ao&&t!==so&&t!==oo&&t!==co&&t!==uo?bo(e,qa):(e.state=null,t===co?bo(e,Fa):Ba)):qa}(this.strm),this.onEnd(n),this.ended=!0,n===Ba):a!==Ca||(this.onEnd(Ba),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ba&&(this.result=Pa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}const zo=30,qo=12;function Fo(e,t){let r,i,n,a,s,o,c,u,h,d;const f=e.state;r=e.next_in;const l=e.input,p=r+(e.avail_in-5);i=e.next_out;const y=e.output,b=i-(t-e.avail_out),m=i+(e.avail_out-257),g=f.dmax,w=f.wsize,v=f.whave,_=f.wnext,k=f.window;n=f.hold,a=f.bits;const A=f.lencode,S=f.distcode,E=(1<>>24,n>>>=o,a-=o,o=s>>>16&255,0===o)y[i++]=65535&s;else{if(!(16&o)){if(0==(64&o)){s=A[(65535&s)+(n&(1<>>=o,a-=o),a<15&&(n+=l[r++]<>>24,n>>>=o,a-=o,o=s>>>16&255,!(16&o)){if(0==(64&o)){s=S[(65535&s)+(n&(1<g){e.msg="invalid distance too far back",f.mode=zo;break e}if(n>>>=o,a-=o,o=i-b,u>o){if(o=u-o,o>v&&f.sane){e.msg="invalid distance too far back",f.mode=zo;break e}if(h=0,d=k,0===_){if(h+=w-o,o2;)y[i++]=d[h++],y[i++]=d[h++],y[i++]=d[h++],c-=3;c&&(y[i++]=d[h++],c>1&&(y[i++]=d[h++]))}else{h=i-u;do{y[i++]=y[h++],y[i++]=y[h++],y[i++]=y[h++],c-=3}while(c>2);c&&(y[i++]=y[h++],c>1&&(y[i++]=y[h++]))}break}}break}}while(r>3,r-=c,a-=c<<3,n&=(1<=1&&0===P[m];m--);if(g>m&&(g=m),0===m)return n[a++]=20971520,n[a++]=20971520,o.bits=1,0;for(b=1;b0&&(e===jo||1!==m))return-1;for(x[1]=0,p=1;pLo||e===Wo&&k>No)return 1;for(;;){M=p-v,s[y]l?(K=D[U+s[y]],C=S[E+s[y]]):(K=96,C=0),u=1<>v)+h]=M<<24|K<<16|C|0}while(0!==h);for(u=1<>=1;if(0!==u?(A&=u-1,A+=u):A=0,y++,0==--P[p]){if(p===m)break;p=t[r+s[y]]}if(p>g&&(A&R)!==d){for(0===v&&(v=g),f+=b,w=p-v,_=1<Lo||e===Wo&&k>No)return 1;d=A&R,n[d]=g<<24|w<<16|f-a|0}}return 0!==A&&(n[f+A]=p-v<<24|64<<16|0),o.bits=g,0}const Yo=0,Qo=1,Jo=2,ec=1,tc=2,rc=3,ic=4,nc=5,ac=6,sc=7,oc=8,cc=9,uc=10,hc=11,dc=12,fc=13,lc=14,pc=15,yc=16,bc=17,mc=18,gc=19,wc=20,vc=21,_c=22,kc=23,Ac=24,Sc=25,Ec=26,Pc=27,xc=28,Mc=29,Kc=30,Cc=852,Dc=592;function Uc(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}class Rc{constructor(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Sa(320),this.work=new Sa(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}}function Ic(e){let t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,function(e){let t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=ec,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Ea(Cc),t.distcode=t.distdyn=new Ea(Dc),t.sane=1,t.back=-1,Ba):qa}(e)):qa}function Bc(e,t){let r,i;return e?(i=new Rc,e.state=i,i.window=null,r=function(e,t){let r,i;return e&&e.state?(i=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?qa:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,Ic(e))):qa}(e,t),r!==Ba&&(e.state=null),r):qa}let Tc,zc,qc=!0;function Fc(e){if(qc){let t;for(Tc=new Ea(512),zc=new Ea(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Xo(Qo,e.lens,0,288,Tc,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Xo(Jo,e.lens,0,32,zc,0,e.work,{bits:5}),qc=!1}e.lencode=Tc,e.lenbits=9,e.distcode=zc,e.distbits=5}function Oc(e,t,r,i){let n;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(xa(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>i&&(n=i),xa(a.window,t,r-i,n,a.wnext),(i-=n)?(xa(a.window,t,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=Xs(r.check,x,2,0),u=0,h=0,r.mode=tc;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=Kc;break}if((15&u)!==Za){e.msg="unknown compression method",r.mode=Kc;break}if(u>>>=4,h-=4,k=8+(15&u),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=Kc;break}r.dmax=1<>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=Xs(r.check,x,2,0)),u=0,h=0,r.mode=rc;case rc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=Xs(r.check,x,4,0)),u=0,h=0,r.mode=ic;case ic:for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=Xs(r.check,x,2,0)),u=0,h=0,r.mode=nc;case nc:if(1024&r.flags){for(;h<16;){if(0===o)break e;o--,u+=i[a++]<>>8&255,r.check=Xs(r.check,x,2,0)),u=0,h=0}else r.head&&(r.head.extra=null);r.mode=ac;case ac:if(1024&r.flags&&(l=r.length,l>o&&(l=o),l&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=Array(r.head.extra_len)),xa(r.head.extra,i,a,l,k)),512&r.flags&&(r.check=Xs(r.check,i,l,a)),o-=l,a+=l,r.length-=l),r.length))break e;r.length=0,r.mode=sc;case sc:if(2048&r.flags){if(0===o)break e;l=0;do{k=i[a+l++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k))}while(k&&l>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=dc;break;case uc:for(;h<32;){if(0===o)break e;o--,u+=i[a++]<>>=7&h,h-=7&h,r.mode=Pc;break}for(;h<3;){if(0===o)break e;o--,u+=i[a++]<>>=1,h-=1,3&u){case 0:r.mode=lc;break;case 1:if(Fc(r),r.mode=wc,t===Ia){u>>>=2,h-=2;break e}break;case 2:r.mode=bc;break;case 3:e.msg="invalid block type",r.mode=Kc}u>>>=2,h-=2;break;case lc:for(u>>>=7&h,h-=7&h;h<32;){if(0===o)break e;o--,u+=i[a++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=Kc;break}if(r.length=65535&u,u=0,h=0,r.mode=pc,t===Ia)break e;case pc:r.mode=yc;case yc:if(l=r.length,l){if(l>o&&(l=o),l>c&&(l=c),0===l)break e;xa(n,i,a,l,s),o-=l,a+=l,c-=l,s+=l,r.length-=l;break}r.mode=dc;break;case bc:for(;h<14;){if(0===o)break e;o--,u+=i[a++]<>>=5,h-=5,r.ndist=1+(31&u),u>>>=5,h-=5,r.ncode=4+(15&u),u>>>=4,h-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Kc;break}r.have=0,r.mode=mc;case mc:for(;r.have>>=3,h-=3}for(;r.have<19;)r.lens[M[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},A=Xo(Yo,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid code lengths set",r.mode=Kc;break}r.have=0,r.mode=gc;case gc:for(;r.have>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=b,h-=b,r.lens[r.have++]=g;else{if(16===g){for(E=b+2;h>>=b,h-=b,0===r.have){e.msg="invalid bit length repeat",r.mode=Kc;break}k=r.lens[r.have-1],l=3+(3&u),u>>>=2,h-=2}else if(17===g){for(E=b+3;h>>=b,h-=b,k=0,l=3+(7&u),u>>>=3,h-=3}else{for(E=b+7;h>>=b,h-=b,k=0,l=11+(127&u),u>>>=7,h-=7}if(r.have+l>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Kc;break}for(;l--;)r.lens[r.have++]=k}}if(r.mode===Kc)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=Kc;break}if(r.lenbits=9,S={bits:r.lenbits},A=Xo(Qo,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,A){e.msg="invalid literal/lengths set",r.mode=Kc;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},A=Xo(Jo,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,A){e.msg="invalid distances set",r.mode=Kc;break}if(r.mode=wc,t===Ia)break e;case wc:r.mode=vc;case vc:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,r.hold=u,r.bits=h,Fo(e,f),s=e.next_out,n=e.output,c=e.avail_out,a=e.next_in,i=e.input,o=e.avail_in,u=r.hold,h=r.bits,r.mode===dc&&(r.back=-1);break}for(r.back=0;P=r.lencode[u&(1<>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,m=P>>>16&255,g=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,r.length=g,0===m){r.mode=Ec;break}if(32&m){r.back=-1,r.mode=dc;break}if(64&m){e.msg="invalid literal/length code",r.mode=Kc;break}r.extra=15&m,r.mode=_c;case _c:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=kc;case kc:for(;P=r.distcode[u&(1<>>24,m=P>>>16&255,g=65535&P,!(b<=h);){if(0===o)break e;o--,u+=i[a++]<>w)],b=P>>>24,m=P>>>16&255,g=65535&P,!(w+b<=h);){if(0===o)break e;o--,u+=i[a++]<>>=w,h-=w,r.back+=w}if(u>>>=b,h-=b,r.back+=b,64&m){e.msg="invalid distance code",r.mode=Kc;break}r.offset=g,r.extra=15&m,r.mode=Ac;case Ac:if(r.extra){for(E=r.extra;h>>=r.extra,h-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Kc;break}r.mode=Sc;case Sc:if(0===c)break e;if(l=f-c,r.offset>l){if(l=r.offset-l,l>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Kc;break}l>r.wnext?(l-=r.wnext,p=r.wsize-l):p=r.wnext-l,l>r.length&&(l=r.length),y=r.window}else y=n,p=s-r.offset,l=r.length;l>c&&(l=c),c-=l,r.length-=l;do{n[s++]=y[p++]}while(--l);0===r.length&&(r.mode=vc);break;case Ec:if(0===c)break e;n[s++]=r.length,c--,r.mode=vc;break;case Pc:if(r.wrap){for(;h<32;){if(0===o)break e;o--,u|=i[a++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Bo,this.strm.avail_out=0;let r=Bc(this.strm,t.windowBits);if(r!==Ba)throw Error(Ys[r]);if(this.header=new jc,function(e,t){let r;e&&e.state&&(r=e.state,0==(2&r.wrap)||(r.head=t,t.done=!1))}(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Io(t.dictionary):t.dictionary instanceof ArrayBuffer&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=Nc(this.strm,t.dictionary),r!==Ba)))throw Error(Ys[r])}push(e,t){const{strm:r,options:{chunkSize:i,dictionary:n}}=this;let a,s,o=!1;if(this.ended)return!1;s=t===~~t?t:!0===t?Ua:Ma,"string"==typeof e?r.input=function(e){const t=new Aa(e.length);for(let r=0,i=t.length;r0||0===r.avail_out)&&a!==Ta);return a===Ta&&(s=Ua),s===Ua?(a=function(e){if(!e||!e.state)return qa;const t=e.state;return t.window&&(t.window=null),e.state=null,Ba}(this.strm),this.onEnd(a),this.ended=!0,a===Ba):s!==Ca||(this.onEnd(Ba),r.avail_out=0,!0)}onData(e){this.chunks.push(e)}onEnd(e){e===Ba&&(this.result=Pa(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg}}var Wc=[0,1,3,7,15,31,63,127,255],Gc=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};Gc.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},Gc.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Wc[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var i=r-e;t|=(this.curByte&Wc[e]<>i,this.bitOffset+=e,e=0}}return t},Gc.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},Gc.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var Vc=Gc,$c=function(){};$c.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},$c.prototype.read=function(e,t,r){for(var i=0;i>>0},this.updateCRC=function(t){e=e<<8^Zc[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^Zc[255&(e>>>24^t)]}}),Qc=function(e,t){var r,i=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=i,i},Jc={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},eu={};eu[Jc.LAST_BLOCK]="Bad file checksum",eu[Jc.NOT_BZIP_DATA]="Not bzip data",eu[Jc.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",eu[Jc.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",eu[Jc.DATA_ERROR]="Data error",eu[Jc.OUT_OF_MEMORY]="Out of memory",eu[Jc.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var tu=function(e,t){var r=eu[e]||"unknown error";t&&(r+=": "+t);var i=new TypeError(r);throw i.errorCode=e,i},ru=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};ru.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Yc,!0):(this.writeCount=-1,!1)},ru.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||tu(Jc.NOT_BZIP_DATA,"bad magic");var i=r[3]-48;(i<1||i>9)&&tu(Jc.NOT_BZIP_DATA,"level out of range"),this.reader=new Vc(e),this.dbufSize=1e5*i,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},ru.prototype._get_next_block=function(){var e,t,r,i=this.reader,n=i.pi();if("177245385090"===n)return!1;"314159265359"!==n&&tu(Jc.NOT_BZIP_DATA),this.targetBlockCRC=i.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,i.read(1)&&tu(Jc.OBSOLETE_INPUT);var a=i.read(24);a>this.dbufSize&&tu(Jc.DATA_ERROR,"initial position out of bounds");var s=i.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(s&1<<15-e){var u=16*e;for(r=i.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=u+t)}var h=i.read(3);(h<2||h>6)&&tu(Jc.DATA_ERROR);var d=i.read(15);0===d&&tu(Jc.DATA_ERROR);var f=new Uint8Array(256);for(e=0;e=h&&tu(Jc.DATA_ERROR);l[e]=Qc(f,t)}var p,y=c+2,b=[];for(t=0;t20)&&tu(Jc.DATA_ERROR),i.read(1);)i.read(1)?s--:s++;w[e]=s}for(m=g=w[0],e=1;eg?g=w[e]:w[e]=d&&tu(Jc.DATA_ERROR),p=b[l[P++]]),e=p.minLen,t=i.read(e);e>p.maxLen&&tu(Jc.DATA_ERROR),!(t<=p.limit[e]);e++)t=t<<1|i.read(1);((t-=p.base[e])<0||t>=258)&&tu(Jc.DATA_ERROR);var M=p.permute[t];if(0!==M&&1!==M){if(S)for(S=0,E+s>this.dbufSize&&tu(Jc.DATA_ERROR),k[A=o[f[0]]]+=s;s--;)x[E++]=A;if(M>c)break;E>=this.dbufSize&&tu(Jc.DATA_ERROR),k[A=o[A=Qc(f,e=M-1)]]++,x[E++]=A}else S||(S=1,s=0),s+=0===M?S:2*S,S<<=1}for((a<0||a>=E)&&tu(Jc.DATA_ERROR),t=0,e=0;e<256;e++)r=t+k[e],k[e]=t,t=r;for(e=0;e>=8,D=-1),this.writePos=K,this.writeCurrent=C,this.writeCount=E,this.writeRun=D,!0},ru.prototype._read_bunzip=function(e,t){var r,i,n;if(this.writeCount<0)return 0;var a=this.dbuf,s=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var u=this.writeRun;c;){for(c--,i=o,o=255&(s=a[s]),s>>=8,3==u++?(r=o,n=i,o=-1):(r=1,n=o),this.blockCRC.updateCRCRun(n,r);r--;)this.outputStream.writeByte(n),this.nextoutput++;o!=i&&(u=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&tu(Jc.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var iu=function(e){if("readByte"in e)return e;var t=new Xc;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},nu=function(e){var t=new Xc,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var au=function(e,t,r){for(var i=iu(e),n=nu(t),a=new ru(i,n);!("eof"in i)||!i.eof();)if(a._init_block())a._read_bunzip();else{var s=a.reader.read(32)>>>0;if(s!==a.streamCRC&&tu(Jc.DATA_ERROR,"Bad stream CRC (got "+a.streamCRC.toString(16)+" expected "+s.toString(16)+")"),!r||!("eof"in i)||i.eof())break;a._start_bunzip(i,n)}if("getBuffer"in n)return n.getBuffer()};class su{static get tag(){return $.packet.literalData}constructor(e=new Date){this.format=$.literal.utf8,this.date=X.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=$.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||X.isStream(this.text))&&(this.text=X.decodeUTF8(X.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=X.canonicalizeEOL(X.encodeUTF8(this.text))),e?F(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await z(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=X.decodeUTF8(await e.readBytes(r)),this.date=X.readDate(await e.readBytes(4));let i=e.remainder();s(i)&&(i=await N(i)),this.setBytes(i,t)}))}writeHeader(){const e=X.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),i=X.writeDate(this.date);return X.concatUint8Array([r,t,e,i])}write(){const e=this.writeHeader(),t=this.getBytes();return X.concat([e,t])}}const ou=Symbol("verified"),cu=new Set([$.signatureSubpacket.issuer,$.signatureSubpacket.issuerFingerprint,$.signatureSubpacket.embeddedSignature]);class uu{static get tag(){return $.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.signedHashValue=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new pe,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.revoked=null,this[ou]=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version)throw new bn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[t++],this.publicKeyAlgorithm=e[t++],this.hashAlgorithm=e[t++],t+=this.readSubPackets(e.subarray(t,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");this.signatureData=e.subarray(0,t),t+=this.readSubPackets(e.subarray(t,e.length),!1),this.signedHashValue=e.subarray(t,t+2),t+=2,this.params=ga.signature.parseSignatureParams(this.publicKeyAlgorithm,e.subarray(t,e.length))}writeParams(){return this.params instanceof Promise?H((async()=>ga.serializeParams(this.publicKeyAlgorithm,await this.params))):ga.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),e.push(this.writeParams()),X.concat(e)}async sign(e,t,r=new Date,i=!1){5===e.version?this.version=5:this.version=4;const n=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];this.created=X.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID(),n.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=X.concat(n);const a=this.toHash(this.signatureType,t,i),s=await this.hash(this.signatureType,t,a,i);this.signedHashValue=L(q(s),0,2);const o=async()=>ga.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await N(s));X.isStream(s)?this.params=o():(this.params=await o(),this[ou]=!0)}writeHashedSubPackets(){const e=$.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(hu(e.signatureCreationTime,!0,X.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(hu(e.signatureExpirationTime,!0,X.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(hu(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(hu(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(hu(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(hu(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(hu(e.keyExpirationTime,!0,X.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(hu(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=X.concat([r,this.revocationKeyFingerprint]),t.push(hu(e.revocationKey,!1,r))),this.issuerKeyID.isNull()||5===this.issuerKeyVersion||t.push(hu(e.issuer,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:i,value:n,humanReadable:a,critical:s})=>{r=[new Uint8Array([a?128:0,0,0,0])];const o=X.encodeUTF8(i);r.push(X.writeNumber(o.length,2)),r.push(X.writeNumber(n.length,2)),r.push(o),r.push(n),r=X.concat(r),t.push(hu(e.notationData,s,r))})),null!==this.preferredHashAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(hu(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(hu(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.keyServerPreferences)),t.push(hu(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(hu(e.preferredKeyServer,!1,X.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(hu(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(hu(e.policyURI,!1,X.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.keyFlags)),t.push(hu(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(hu(e.signersUserID,!1,X.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=X.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(hu(e.reasonForRevocation,!0,r))),null!==this.features&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.features)),t.push(hu(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(X.stringToUint8Array(this.signatureTargetHash)),r=X.concat(r),t.push(hu(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(hu(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=X.concat(r),t.push(hu(e.issuerFingerprint,5===this.version,r))),null!==this.preferredAEADAlgorithms&&(r=X.stringToUint8Array(X.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(hu(e.preferredAEADAlgorithms,!1,r)));const i=X.concat(t),n=X.writeNumber(i.length,2);return X.concat([n,i])}writeUnhashedSubPackets(){const e=[];this.unhashedSubpackets.forEach((t=>{e.push(hn(t.length)),e.push(t)}));const t=X.concat(e),r=X.writeNumber(t.length,2);return X.concat([r,t])}readSubPacket(e,t=!0){let r=0;const i=!!(128&e[r]),n=127&e[r];if(t||(this.unhashedSubpackets.push(e.subarray(r,e.length)),cu.has(n)))switch(r++,n){case $.signatureSubpacket.signatureCreationTime:this.created=X.readDate(e.subarray(r,e.length));break;case $.signatureSubpacket.signatureExpirationTime:{const t=X.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case $.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case $.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case $.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case $.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case $.signatureSubpacket.keyExpirationTime:{const t=X.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case $.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case $.signatureSubpacket.issuer:this.issuerKeyID.read(e.subarray(r,e.length));break;case $.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const n=X.readNumber(e.subarray(r,r+2));r+=2;const a=X.readNumber(e.subarray(r,r+2));r+=2;const s=X.decodeUTF8(e.subarray(r,r+n)),o=e.subarray(r+n,r+n+a);this.rawNotations.push({name:s,humanReadable:t,value:o,critical:i}),t&&(this.notations[s]=X.decodeUTF8(o));break}case $.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case $.signatureSubpacket.policyURI:this.policyURI=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.signersUserID:this.signersUserID=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=X.decodeUTF8(e.subarray(r,e.length));break;case $.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case $.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=ga.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=X.uint8ArrayToString(e.subarray(r,r+t));break}case $.signatureSubpacket.embeddedSignature:this.embeddedSignature=new uu,this.embeddedSignature.read(e.subarray(r,e.length));break;case $.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),5===this.issuerKeyVersion?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case $.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;default:{const e=Error("Unknown signature subpacket type "+n);if(i)throw e;X.printDebug(e)}}}readSubPackets(e,t=!0,r){const i=X.readNumber(e.subarray(0,2));let n=2;for(;n<2+i;){const i=un(e.subarray(n,e.length));n+=i.offset,this.readSubPacket(e.subarray(n,n+i.len),t,r),n+=i.len}return n}toSign(e,t){const r=$.signature;switch(e){case r.binary:return null!==t.text?X.encodeUTF8(t.getText(!0)):t.getBytes(!0);case r.text:{const e=t.getBytes(!0);return X.canonicalizeEOL(e)}case r.standalone:return new Uint8Array(0);case r.certGeneric:case r.certPersona:case r.certCasual:case r.certPositive:case r.certRevocation:{let e,i;if(t.userID)i=180,e=t.userID;else{if(!t.userAttribute)throw Error("Either a userID or userAttribute packet needs to be supplied for certification.");i=209,e=t.userAttribute}const n=e.write();return X.concat([this.toSign(r.key,t),new Uint8Array([i]),X.writeNumber(n.length,4),n])}case r.subkeyBinding:case r.subkeyRevocation:case r.keyBinding:return X.concat([this.toSign(r.key,t),this.toSign(r.key,{key:t.bind})]);case r.key:if(void 0===t.key)throw Error("Key packet is required for this signature.");return t.key.writeForHash(this.version);case r.keyRevocation:return this.toSign(r.key,t);case r.timestamp:return new Uint8Array(0);case r.thirdParty:throw Error("Not implemented");default:throw Error("Unknown signature type.")}}calculateTrailer(e,t){let r=0;return B(q(this.signatureData),(e=>{r+=e.length}),(()=>{const i=[];return 5!==this.version||this.signatureType!==$.signature.binary&&this.signatureType!==$.signature.text||(t?i.push(new Uint8Array(6)):i.push(e.writeHeader())),i.push(new Uint8Array([this.version,255])),5===this.version&&i.push(new Uint8Array(4)),i.push(X.writeNumber(r,4)),X.concat(i)}))}toHash(e,t,r=!1){const i=this.toSign(e,t);return X.concat([i,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,i=!1){return r||(r=this.toHash(e,t,i)),ga.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,i=new Date,n=!1,a=ne){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const s=t===$.signature.binary||t===$.signature.text;if(!(this[ou]&&!s)){let i,a;if(this.hashed?a=await this.hashed:(i=this.toHash(t,r,n),a=await this.hash(t,r,i)),a=await N(a),this.signedHashValue[0]!==a[0]||this.signedHashValue[1]!==a[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[ou]=await ga.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,i,a),!this[ou])throw Error("Signature verification failed")}const o=X.normalizeDate(i);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(a.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+$.read($.hash,this.hashAlgorithm).toUpperCase());if(a.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[$.signature.binary,$.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+$.read($.hash,this.hashAlgorithm).toUpperCase());if(this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&a.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=X.normalizeDate(e);return null!==t&&!(this.created<=t&&tuu.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==$.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function fu(e,t){if(!t[e]){let t;try{t=$.read($.packet,e)}catch(t){throw new bn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}du.prototype.hash=uu.prototype.hash,du.prototype.toHash=uu.prototype.toHash,du.prototype.toSign=uu.prototype.toSign;class lu extends Array{static async fromBinary(e,t,r=ne){const i=new lu;return await i.read(e,t,r),i}async read(e,t,r=ne){r.additionalAllowedPackets.length&&(t={...t,...X.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=T(e,(async(e,i)=>{const n=D(i);try{for(;;){await n.ready;if(await yn(e,(async e=>{try{if(e.tag===$.packet.marker||e.tag===$.packet.trust)return;const i=fu(e.tag,t);i.packets=new lu,i.fromStream=X.isStream(e.packet),await i.read(e.packet,r),await n.write(i)}catch(t){const i=!r.ignoreUnsupportedPackets&&t instanceof bn,a=!(r.ignoreMalformedPackets||t instanceof bn);if(i||a||pn(e.tag))await n.abort(t);else{const t=new mn(e.tag,e.packet);await n.write(t)}X.printDebugError(t)}})))return await n.ready,void await n.close()}}catch(e){await n.abort(e)}}));const i=C(this.stream);for(;;){const{done:e,value:t}=await i.read();if(e?this.stream=null:this.push(t),e||pn(t.constructor.tag))break}i.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),n+=e.length,n>=a){const e=Math.min(Math.log(n)/Math.LN2|0,30),r=2**e,i=X.concat([dn(e)].concat(t));return t=[i.subarray(1+r)],n=t[0].length,i.subarray(0,1+r)}}),(()=>X.concat([hn(n)].concat(t)))))}else{if(X.isStream(i)){let t=0;e.push(B(q(i),(e=>{t+=e.length}),(()=>ln(r,t))))}else e.push(ln(r,i.length));e.push(i)}}return X.concat(e)}filterByTag(...e){const t=new lu,r=e=>t=>e===t;for(let i=0;it.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,i=e=>t=>e===t;for(let n=0;n{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),X.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=ne){const t=$.read($.compression,this.algorithm),r=ku[t];if(!r)throw Error(t+" decompression not supported");this.packets=await lu.fromBinary(r(this.compressed),pu,e)}compress(){const e=$.read($.compression,this.algorithm),t=_u[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write(),this.deflateLevel)}}const bu=X.getNodeZlib();function mu(e){return e}function gu(e,t,r={}){return function(i){return!X.isStream(i)||s(i)?H((()=>N(i).then((t=>new Promise(((i,n)=>{e(t,r,((e,t)=>{if(e)return n(e);i(t)}))})))))):y(b(i).pipe(t(r)))}}function wu(e,t={}){return function(r){const i=new e(t);return B(r,(e=>{if(e.length)return i.push(e,Ca),i.result}),(()=>{if(e===To)return i.push([],Ua),i.result}))}}function vu(e){return function(t){return H((async()=>e(await N(t))))}}const _u=bu?{zip:/*#__PURE__*/(e,t)=>gu(bu.deflateRaw,bu.createDeflateRaw,{level:t})(e),zlib:/*#__PURE__*/(e,t)=>gu(bu.deflate,bu.createDeflate,{level:t})(e)}:{zip:/*#__PURE__*/(e,t)=>wu(To,{raw:!0,level:t})(e),zlib:/*#__PURE__*/(e,t)=>wu(To,{level:t})(e)},ku=bu?{uncompressed:mu,zip:/*#__PURE__*/gu(bu.inflateRaw,bu.createInflateRaw),zlib:/*#__PURE__*/gu(bu.inflate,bu.createInflate),bzip2:/*#__PURE__*/vu(au)}:{uncompressed:mu,zip:/*#__PURE__*/wu(Hc,{raw:!0}),zlib:/*#__PURE__*/wu(Hc),bzip2:/*#__PURE__*/vu(au)},Au=/*#__PURE__*/X.constructAllowedPackets([su,yu,du,uu]);class Su{static get tag(){return $.packet.symEncryptedIntegrityProtectedData}constructor(){this.version=1,this.encrypted=null,this.packets=null}async read(e){await z(e,(async e=>{const t=await e.readByte();if(1!==t)throw new bn(`Version ${t} of the SEIP packet is unsupported.`);this.encrypted=e.remainder()}))}write(){return X.concat([new Uint8Array([1]),this.encrypted])}async encrypt(e,t,r=ne){const{blockSize:i}=ga.getCipher(e);let n=this.packets.write();s(n)&&(n=await N(n));const a=await ga.getPrefixRandom(e),o=new Uint8Array([211,20]),c=X.concat([a,n,o]),u=await ga.hash.sha1(F(c)),h=X.concat([c,u]);return this.encrypted=await ga.mode.cfb.encrypt(e,t,h,new Uint8Array(i),r),!0}async decrypt(e,t,r=ne){const{blockSize:i}=ga.getCipher(e);let n=q(this.encrypted);s(n)&&(n=await N(n));const a=await ga.mode.cfb.decrypt(e,t,n,new Uint8Array(i)),o=L(F(a),-20),c=L(a,0,-20),u=Promise.all([N(await ga.hash.sha1(F(c))),N(o)]).then((([e,t])=>{if(!X.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),h=L(c,i+2);let d=L(h,0,-2);return d=K([d,H((()=>u))]),X.isStream(n)&&r.allowUnauthenticatedStream||(d=await N(d)),this.packets=await lu.fromBinary(d,Au,r),!0}}const Eu=/*#__PURE__*/X.constructAllowedPackets([su,yu,du,uu]);class Pu{static get tag(){return $.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=$.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await z(e,(async e=>{const t=await e.readByte();if(1!==t)throw new bn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=ga.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return X.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=ne){this.packets=await lu.fromBinary(await this.crypt("decrypt",t,q(this.encrypted)),Eu,r)}async encrypt(e,t,r=ne){this.cipherAlgorithm=e;const{ivLength:i}=ga.getAEADMode(this.aeadAlgorithm);this.iv=ga.random.getRandomBytes(i),this.chunkSizeByte=r.aeadChunkSizeByte;const n=this.packets.write();this.encrypted=await this.crypt("encrypt",t,n)}async crypt(e,t,r){const i=ga.getAEADMode(this.aeadAlgorithm),n=await i(this.cipherAlgorithm,t),a="decrypt"===e?i.tagLength:0,s="encrypt"===e?i.tagLength:0,o=2**(this.chunkSizeByte+6)+a,c=new ArrayBuffer(21),u=new Uint8Array(c,0,13),h=new Uint8Array(c),d=new DataView(c),f=new Uint8Array(c,5,8);u.set([192|Pu.tag,this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte],0);let l=0,p=Promise.resolve(),y=0,b=0;const m=this.iv;return T(r,(async(t,r)=>{if("array"!==X.isStream(t)){const e=new S({},{highWaterMark:X.getHardwareConcurrency()*2**(this.chunkSizeByte+6),size:e=>e.length});U(e.readable,r),r=e.writable}const c=C(t),g=D(r);try{for(;;){let t=await c.readBytes(o+a)||new Uint8Array;const r=t.subarray(t.length-a);let w,v;if(t=t.subarray(0,t.length-a),!l||t.length?(c.unshift(r),w=n[e](t,i.getNonce(m,f),u),b+=t.length-a+s):(d.setInt32(17,y),w=n[e](r,i.getNonce(m,f),h),b+=s,v=!0),y+=t.length-a,p=p.then((()=>w)).then((async e=>{await g.ready,await g.write(e),b-=e.length})).catch((e=>g.abort(e))),(v||b>g.desiredSize)&&await p,v){await g.close();break}d.setInt32(9,++l)}}catch(e){await g.abort(e)}}))}}class xu{static get tag(){return $.packet.publicKeyEncryptedSessionKey}constructor(){this.version=3,this.publicKeyID=new pe,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}read(e){let t=0;if(this.version=e[t++],3!==this.version)throw new bn(`Version ${this.version} of the PKESK packet is unsupported.`);t+=this.publicKeyID.read(e.subarray(t)),this.publicKeyAlgorithm=e[t++],this.encrypted=ga.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t),this.version),this.publicKeyAlgorithm===$.publicKey.x25519&&(this.sessionKeyAlgorithm=$.write($.symmetric,this.encrypted.C.algorithm))}write(){const e=[new Uint8Array([this.version]),this.publicKeyID.write(),new Uint8Array([this.publicKeyAlgorithm]),ga.serializeParams(this.publicKeyAlgorithm,this.encrypted)];return X.concatUint8Array(e)}async encrypt(e){const t=$.write($.publicKey,this.publicKeyAlgorithm),r=Mu(this.version,t,this.sessionKeyAlgorithm,this.sessionKey);this.encrypted=await ga.publicKeyEncrypt(t,this.sessionKeyAlgorithm,e.publicParams,r,e.getFingerprintBytes())}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Mu(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,i=await ga.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,e.getFingerprintBytes(),r),{sessionKey:n,sessionKeyAlgorithm:a}=function(e,t,r,i){switch(t){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.elgamal:case $.publicKey.ecdh:{const e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=X.writeChecksum(e.subarray(e.length%8)),a=n[0]===t[0]&n[1]===t[1],s={sessionKeyAlgorithm:e[0],sessionKey:e.subarray(1)};if(i){const e=a&s.sessionKeyAlgorithm===i.sessionKeyAlgorithm&s.sessionKey.length===i.sessionKey.length;return{sessionKey:X.selectUint8Array(e,s.sessionKey,i.sessionKey),sessionKeyAlgorithm:X.selectUint8(e,s.sessionKeyAlgorithm,i.sessionKeyAlgorithm)}}if(a&&$.read($.symmetric,s.sessionKeyAlgorithm))return s;throw Error("Decryption error")}case $.publicKey.x25519:return{sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);this.publicKeyAlgorithm!==$.publicKey.x25519&&(this.sessionKeyAlgorithm=a),this.sessionKey=n}}function Mu(e,t,r,i){switch(t){case $.publicKey.rsaEncrypt:case $.publicKey.rsaEncryptSign:case $.publicKey.elgamal:case $.publicKey.ecdh:return X.concatUint8Array([new Uint8Array([r]),i,X.writeChecksum(i.subarray(i.length%8))]);case $.publicKey.x25519:return i;default:throw Error("Unsupported public key algorithm")}}class Ku{constructor(e=ne){this.algorithm=$.hash.sha256,this.type="iterated",this.c=e.s2kIterationCountByte,this.salt=null}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;try{this.type=$.read($.s2k,e[t++])}catch(e){throw new bn("Unknown S2K type.")}switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==X.uint8ArrayToString(e.subarray(t,t+3)))throw new bn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new bn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new bn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...X.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([$.write($.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return X.concatUint8Array(e)}async produceKey(e,t){e=X.encodeUTF8(e);const r=[];let i=0,n=0;for(;i{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function qu(e,t,r){const{keySize:i}=ga.getCipher(r);return e.produceKey(t,i)}var Fu=it((function(e){!function(t){function r(e){function t(){return Ae0&&(t.semantic=" "),t}}function b(e,t){return function(){var i,a,o,u,h;for(u=r(),i=s("star"),o=0,h=void 0===t?0:t;null!==(a=e());)o+=1,c(i,a);return o>=h?i:(n(u),null)}}function m(e){return e.charCodeAt(0)>=128}function g(){return o("cr",h("\r")())}function w(){return o("crlf",d(g,k)())}function v(){return o("dquote",h('"')())}function _(){return o("htab",h("\t")())}function k(){return o("lf",h("\n")())}function A(){return o("sp",h(" ")())}function S(){return o("vchar",u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i})))}function E(){return o("wsp",f(A,_)())}function P(){var e=o("quoted-pair",f(d(h("\\"),f(S,E)),ie)());return null===e?null:(e.semantic=e.semantic[1],e)}function x(){return o("fws",f(ae,d(l(d(b(E),p(w))),b(E,1)))())}function M(){return o("ctext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=39||42<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),te)())}function K(){return o("ccontent",f(M,P,C)())}function C(){return o("comment",d(h("("),b(d(l(x),K)),l(x),h(")"))())}function D(){return o("cfws",f(d(b(d(l(x),C),1),l(x)),x)())}function U(){return o("atext",u((function(t){var r="a"<=t&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||["!","#","$","%","&","'","*","+","-","/","=","?","^","_","`","{","|","}","~"].indexOf(t)>=0;return e.rfc6532&&(r=r||m(t)),r})))}function R(){return o("atom",d(y(l(D)),b(U,1),y(l(D)))())}function I(){var e,t;return null===(e=o("dot-atom-text",b(U,1)()))||null!==(t=b(d(h("."),b(U,1)))())&&c(e,t),e}function B(){return o("dot-atom",d(p(l(D)),I,p(l(D)))())}function T(){return o("qtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33===r||35<=r&&r<=91||93<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),re)())}function z(){return o("qcontent",f(T,P)())}function q(){return o("quoted-string",d(p(l(D)),p(v),b(d(l(y(x)),z)),l(p(x)),p(v),p(l(D)))())}function F(){return o("word",f(R,q)())}function O(){return o("address",f(L,H)())}function L(){return o("mailbox",f(N,J)())}function N(){return o("name-addr",d(l(W),j)())}function j(){return o("angle-addr",f(d(p(l(D)),h("<"),J,h(">"),p(l(D))),se)())}function H(){return o("group",d(W,h(":"),l($),h(";"),p(l(D)))())}function W(){return o("display-name",(null!==(e=o("phrase",f(ne,b(F,1))()))&&(e.semantic=function(e){return e.replace(/([ \t]|\r\n)+/g," ").replace(/^\s*/,"").replace(/\s*$/,"")}(e.semantic)),e));var e}function G(){return o("mailbox-list",f(d(L,b(d(h(","),L))),ue)())}function V(){return o("address-list",f(d(O,b(d(h(","),O))),he)())}function $(){return o("group-list",f(G,p(D),de)())}function Z(){return o("local-part",f(fe,B,q)())}function X(){return o("dtext",f((function(){return u((function(t){var r=t.charCodeAt(0),i=33<=r&&r<=90||94<=r&&r<=126;return e.rfc6532&&(i=i||m(t)),i}))}),pe)())}function Y(){return o("domain-literal",d(p(l(D)),h("["),b(d(l(x),X)),l(x),h("]"),p(l(D)))())}function Q(){return o("domain",(t=f(le,B,Y)(),e.rejectTLD&&t&&t.semantic&&t.semantic.indexOf(".")<0?null:(t&&(t.semantic=t.semantic.replace(/\s+/g,"")),t)));var t}function J(){return o("addr-spec",d(Z,h("@"),Q)())}function ee(){return e.strict?null:o("obs-NO-WS-CTL",u((function(e){var t=e.charCodeAt(0);return 1<=t&&t<=8||11===t||12===t||14<=t&&t<=31||127===t})))}function te(){return e.strict?null:o("obs-ctext",ee())}function re(){return e.strict?null:o("obs-qtext",ee())}function ie(){return e.strict?null:o("obs-qp",d(h("\\"),f(h("\0"),ee,k,g))())}function ne(){return e.strict?null:e.atInDisplayName?o("obs-phrase",d(F,b(f(F,h("."),h("@"),y(D))))()):o("obs-phrase",d(F,b(f(F,h("."),y(D))))())}function ae(){return e.strict?null:o("obs-FWS",b(d(p(l(w)),E),1)())}function se(){return e.strict?null:o("obs-angle-addr",d(p(l(D)),h("<"),oe,J,h(">"),p(l(D)))())}function oe(){return e.strict?null:o("obs-route",d(ce,h(":"))())}function ce(){return e.strict?null:o("obs-domain-list",d(b(f(p(D),h(","))),h("@"),Q,b(d(h(","),p(l(D)),l(d(h("@"),Q)))))())}function ue(){return e.strict?null:o("obs-mbox-list",d(b(d(p(l(D)),h(","))),L,b(d(h(","),l(d(L,p(D))))))())}function he(){return e.strict?null:o("obs-addr-list",d(b(d(p(l(D)),h(","))),O,b(d(h(","),l(d(O,p(D))))))())}function de(){return e.strict?null:o("obs-group-list",d(b(d(p(l(D)),h(",")),1),p(l(D)))())}function fe(){return e.strict?null:o("obs-local-part",d(F,b(d(h("."),F)))())}function le(){return e.strict?null:o("obs-domain",d(R,b(d(h("."),R)))())}function pe(){return e.strict?null:o("obs-dtext",f(ee,P)())}function ye(e,t){var r,i,n;if(null==t)return null;for(i=[t];i.length>0;){if((n=i.pop()).name===e)return n;for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r])}return null}function be(e,t){var r,i,n,a,s;if(null==t)return null;for(i=[t],a=[],s={},r=0;r0;)if((n=i.pop()).name in s)a.push(n);else for(r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}function me(t){var r,i,n,a,s;if(null===t)return null;for(r=[],i=be(["group","mailbox"],t),n=0;n1)return null;return t.addresses&&t.addresses[0]}(s):e.simple?s&&s.addresses:s}function ge(e){var t,r=ye("display-name",e),i=[],n=be(["mailbox"],e);for(t=0;t0;)for((n=i.pop()).name===e&&a.push(n),r=n.children.length-1;r>=0;r-=1)i.push(n.children[r]);return a}("cfws",e),n=be(["comment"],e),a=ye("local-part",r),s=ye("domain",r);return{node:e,parts:{name:t,address:r,local:a,domain:s,comments:i},type:e.name,name:ve(t),address:ve(r),local:ve(a),domain:ve(s),comments:_e(n),groupName:ve(e.groupName)}}function ve(e){return null!=e?e.semantic:null}function _e(e){var t="";if(e)for(var r=0;r`),t.userID=r.join(" "),t}read(e,t=ne){const r=X.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");try{const{name:e,address:t,comments:i}=Fu.parseOneAddress({input:r,atInDisplayName:!0});this.comment=i.replace(/^\(|\)$/g,""),this.name=e,this.email=t}catch(e){}this.userID=r}write(){return X.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class Lu extends zu{static get tag(){return $.packet.secretSubkey}constructor(e=new Date,t=ne){super(e,t)}}class Nu{static get tag(){return $.packet.trust}read(){throw new bn("Trust packets are not supported")}write(){throw new bn("Trust packets are not supported")}}const ju=/*#__PURE__*/X.constructAllowedPackets([uu]);class Hu{constructor(e){this.packets=e||new lu}write(){return this.packets.write()}armor(e=ne){return le($.armor.signature,this.write(),void 0,void 0,void 0,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Wu({armoredSignature:e,binarySignature:t,config:r,...i}){r={...ne,...r};let n=e||t;if(!n)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!X.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!X.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:e,data:t}=await fe(n,r);if(e!==$.armor.signature)throw Error("Armored text not of type signature");n=t}const s=await lu.fromBinary(n,ju,r);return new Hu(s)}async function Gu(e,t){const r=new Lu(e.date,t);return r.packets=null,r.algorithm=$.write($.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function Vu(e,t){const r=new zu(e.date,t);return r.packets=null,r.algorithm=$.write($.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function $u(e,t,r,i,n=new Date,a){let s,o;for(let c=e.length-1;c>=0;c--)try{(!s||e[c].created>=s.created)&&(await e[c].verify(t,r,i,n,void 0,a),s=e[c])}catch(e){o=e}if(!s)throw X.wrapError(`Could not find valid ${$.read($.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return s}function Zu(e,t,r=new Date){const i=X.normalizeDate(r);if(null!==i){const r=rh(e,t);return!(e.created<=i&&i0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1);return await Ju(n,null,t,a,r.date,void 0,void 0,void 0,i)}async function Yu(e,t,r=new Date,i={},n){let a=n.preferredHashAlgorithm,s=a;if(e){const t=await e.getPrimaryUser(r,i,n);t.selfCertification.preferredHashAlgorithms&&([s]=t.selfCertification.preferredHashAlgorithms,a=ga.hash.getHashByteLength(a)<=ga.hash.getHashByteLength(s)?s:a)}switch(t.algorithm){case $.publicKey.ecdsa:case $.publicKey.eddsaLegacy:case $.publicKey.ed25519:s=ga.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid)}return ga.hash.getHashByteLength(a)<=ga.hash.getHashByteLength(s)?s:a}async function Qu(e,t=[],r=new Date,i=[],n=ne){const a={symmetric:$.symmetric.aes128,aead:$.aead.eax,compression:$.compression.uncompressed}[e],s={symmetric:n.preferredSymmetricAlgorithm,aead:n.preferredAEADAlgorithm,compression:n.preferredCompressionAlgorithm}[e],o={symmetric:"preferredSymmetricAlgorithms",aead:"preferredAEADAlgorithms",compression:"preferredCompressionAlgorithms"}[e],c=await Promise.all(t.map((async function(e,t){const a=(await e.getPrimaryUser(r,i[t],n)).selfCertification[o];return!!a&&a.indexOf(s)>=0})));return c.every(Boolean)?s:a}async function Ju(e,t,r,i,n,a,s=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const u=new uu;return Object.assign(u,i),u.publicKeyAlgorithm=r.algorithm,u.hashAlgorithm=await Yu(t,r,n,a,c),u.rawNotations=s,await u.sign(r,e,n,o),u}async function eh(e,t,r,i=new Date,n){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(i)||n&&!await n(e)||t[r].some((function(t){return X.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function th(e,t,r,i,n,a,s=new Date,o){a=a||e;const c=[];return await Promise.all(i.map((async function(e){try{n&&!e.issuerKeyID.equals(n.issuerKeyID)||(await e.verify(a,t,r,o.revocationsExpire?s:null,!1,o),c.push(e.issuerKeyID))}catch(e){}}))),n?(n.revoked=!!c.some((e=>e.equals(n.issuerKeyID)))||(n.revoked||!1),n.revoked):c.length>0}function rh(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function ih(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=X.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=$.write($.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==$.curve.ed25519Legacy&&e.curve!==$.curve.curve25519Legacy||(e.curve=e.sign?$.curve.ed25519Legacy:$.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===$.curve.ed25519Legacy?$.publicKey.eddsaLegacy:$.publicKey.ecdsa:e.algorithm=$.publicKey.ecdh;break;case"rsa":e.algorithm=$.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function nh(e,t){const r=e.algorithm;return r!==$.publicKey.rsaEncrypt&&r!==$.publicKey.elgamal&&r!==$.publicKey.ecdh&&r!==$.publicKey.x25519&&(!t.keyFlags||0!=(t.keyFlags[0]&$.keyFlags.signData))}function ah(e,t){const r=e.algorithm;return r!==$.publicKey.dsa&&r!==$.publicKey.rsaSign&&r!==$.publicKey.ecdsa&&r!==$.publicKey.eddsaLegacy&&r!==$.publicKey.ed25519&&(!t.keyFlags||0!=(t.keyFlags[0]&$.keyFlags.encryptCommunication)||0!=(t.keyFlags[0]&$.keyFlags.encryptStorage))}function sh(e,t){return!!t.allowInsecureDecryptionWithSigningKeys||(!e.keyFlags||0!=(e.keyFlags[0]&$.keyFlags.encryptCommunication)||0!=(e.keyFlags[0]&$.keyFlags.encryptStorage))}function oh(e,t){const r=$.write($.publicKey,e.algorithm),i=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(i.algorithm+" keys are considered too weak.");switch(r){case $.publicKey.rsaEncryptSign:case $.publicKey.rsaSign:case $.publicKey.rsaEncrypt:if(i.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const a=await t.getSigningKey(o,e.created,void 0,i);if(e.revoked||await n.isRevoked(e,a.keyPacket,r,i))throw Error("User certificate is revoked");try{await e.verify(a.keyPacket,$.signature.certGeneric,s,r,void 0,i)}catch(e){throw X.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const i=this,n=this.selfCertifications.concat(this.otherCertifications);return Promise.all(n.map((async n=>({keyID:n.issuerKeyID,valid:await i.verifyCertificate(n,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};let a;for(let s=this.selfCertifications.length-1;s>=0;s--)try{const a=this.selfCertifications[s];if(a.revoked||await r.isRevoked(a,void 0,e,t))throw Error("Self-certification is revoked");try{await a.verify(i,$.signature.certGeneric,n,e,void 0,t)}catch(e){throw X.wrapError("Self-certification is invalid",e)}return!0}catch(e){a=e}throw a}async update(e,t,r){const i=this.mainKey.keyPacket,n={userID:this.userID,userAttribute:this.userAttribute,key:i};await eh(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(i,$.signature.certGeneric,n,t,!1,r),!0}catch(e){return!1}})),await eh(e,this,"otherCertifications",t),await eh(e,this,"revocationSignatures",t,(function(e){return th(i,$.signature.certRevocation,n,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=$.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=ne){const a={userID:this.userID,userAttribute:this.userAttribute,key:e},s=new ch(a.userID||a.userAttribute,this.mainKey);return s.revocationSignatures.push(await Ju(a,null,e,{signatureType:$.signature.certRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}}class uh{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new lu;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new uh(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,i=ne){const n=this.mainKey.keyPacket;return th(n,$.signature.subkeyRevocation,{key:n,bind:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verify(e=new Date,t=ne){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket},n=await $u(this.bindingSignatures,r,$.signature.subkeyBinding,i,e,t);if(n.revoked||await this.isRevoked(n,null,e,t))throw Error("Subkey is revoked");if(Zu(this.keyPacket,n,e))throw Error("Subkey is expired");return n}async getExpirationTime(e=new Date,t=ne){const r=this.mainKey.keyPacket,i={key:r,bind:this.keyPacket};let n;try{n=await $u(this.bindingSignatures,r,$.signature.subkeyBinding,i,e,t)}catch(e){return null}const a=rh(this.keyPacket,n),s=n.getExpirationTime();return an.bindingSignatures[t].created&&(n.bindingSignatures[t]=e),!1;try{return await e.verify(i,$.signature.subkeyBinding,a,t,void 0,r),!0}catch(e){return!1}})),await eh(e,this,"revocationSignatures",t,(function(e){return th(i,$.signature.subkeyRevocation,a,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=$.reasonForRevocation.noReason,string:r=""}={},i=new Date,n=ne){const a={key:e,bind:this.keyPacket},s=new uh(this.keyPacket,this.mainKey);return s.revocationSignatures.push(await Ju(a,null,e,{signatureType:$.signature.subkeyRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,t),reasonForRevocationString:r},i,void 0,void 0,!1,n)),await s.update(this),s}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{uh.prototype[e]=function(){return this.keyPacket[e]()}}));const hh=/*#__PURE__*/X.constructAllowedPackets([uu]),dh=new Set([$.packet.publicKey,$.packet.privateKey]),fh=new Set([$.packet.publicKey,$.packet.privateKey,$.packet.publicSubkey,$.packet.privateSubkey]);class lh{packetListToStructure(e,t=new Set){let r,i,n,a;for(const s of e){if(s instanceof mn){fh.has(s.tag)&&!a&&(a=dh.has(s.tag)?dh:fh);continue}const e=s.constructor.tag;if(a){if(!a.has(e))continue;a=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case $.packet.publicKey:case $.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=s,i=this.getKeyID(),!i)throw Error("Missing Key ID");break;case $.packet.userID:case $.packet.userAttribute:r=new ch(s,this),this.users.push(r);break;case $.packet.publicSubkey:case $.packet.secretSubkey:r=null,n=new uh(s,this),this.subkeys.push(n);break;case $.packet.signature:switch(s.signatureType){case $.signature.certGeneric:case $.signature.certPersona:case $.signature.certCasual:case $.signature.certPositive:if(!r){X.printDebug("Dropping certification signatures without preceding user packet");continue}s.issuerKeyID.equals(i)?r.selfCertifications.push(s):r.otherCertifications.push(s);break;case $.signature.certRevocation:r?r.revocationSignatures.push(s):this.directSignatures.push(s);break;case $.signature.key:this.directSignatures.push(s);break;case $.signature.subkeyBinding:if(!n){X.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}n.bindingSignatures.push(s);break;case $.signature.keyRevocation:this.revocationSignatures.push(s);break;case $.signature.subkeyRevocation:if(!n){X.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}n.revocationSignatures.push(s)}}}}toPacketList(){const e=new lu;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},i=ne){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await $u(r.bindingSignatures,n,$.signature.subkeyBinding,e,t,i);if(!nh(r.keyPacket,a))continue;if(!a.embeddedSignature)throw Error("Missing embedded signature");return await $u([a.embeddedSignature],r.keyPacket,$.signature.keyBinding,e,t,i),oh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&nh(n,a.selfCertification))return oh(n,i),this}catch(e){s=e}throw X.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),s)}async getEncryptionKey(e,t=new Date,r={},i=ne){await this.verifyPrimaryKey(t,r,i);const n=this.keyPacket,a=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let s;for(const r of a)if(!e||r.getKeyID().equals(e))try{await r.verify(t,i);const e={key:n,bind:r.keyPacket},a=await $u(r.bindingSignatures,n,$.signature.subkeyBinding,e,t,i);if(ah(r.keyPacket,a))return oh(r.keyPacket,i),r}catch(e){s=e}try{const a=await this.getPrimaryUser(t,r,i);if((!e||n.getKeyID().equals(e))&&ah(n,a.selfCertification))return oh(n,i),this}catch(e){s=e}throw X.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),s)}async isRevoked(e,t,r=new Date,i=ne){return th(this.keyPacket,$.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,i)}async verifyPrimaryKey(e=new Date,t={},r=ne){const i=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");const{selfCertification:n}=await this.getPrimaryUser(e,t,r);if(Zu(i,n,e))throw Error("Primary key is expired");const a=await $u(this.directSignatures,i,$.signature.key,{key:i},e,r).catch((()=>{}));if(a&&Zu(i,a,e))throw Error("Primary key is expired")}async getExpirationTime(e,t=ne){let r;try{const{selfCertification:i}=await this.getPrimaryUser(null,e,t),n=rh(this.keyPacket,i),a=i.getExpirationTime(),s=await $u(this.directSignatures,this.keyPacket,$.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(s){const e=rh(this.keyPacket,s);r=Math.min(n,a,e)}else r=ne.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const i=this.clone();return await eh(e,i,"revocationSignatures",t,(n=>th(i.keyPacket,$.signature.keyRevocation,i,[n],null,e.keyPacket,t,r))),await eh(e,i,"directSignatures",t),await Promise.all(e.users.map((async e=>{const n=i.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const n=i.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(n.length>0)await Promise.all(n.map((i=>i.update(e,t,r))));else{const t=e.clone();t.mainKey=i,i.subkeys.push(t)}}))),i}async getRevocationCertificate(e=new Date,t=ne){const r={key:this.keyPacket},i=await $u(this.revocationSignatures,this.keyPacket,$.signature.keyRevocation,r,e,t),n=new lu;return n.push(i),le($.armor.publicKey,n.write(),null,null,"This is a revocation certificate")}async applyRevocationCertificate(e,t=new Date,r=ne){const i=await fe(e,r),n=(await lu.fromBinary(i.data,hh,r)).findPacket($.packet.signature);if(!n||n.signatureType!==$.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!n.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await n.verify(this.keyPacket,$.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw X.wrapError("Could not verify revocation signature",e)}const a=this.clone();return a.revocationSignatures.push(n),a}async signPrimaryUser(e,t,r,i=ne){const{index:n,user:a}=await this.getPrimaryUser(t,r,i),s=await a.certify(e,t,i),o=this.clone();return o.users[n]=s,o}async signAllUsers(e,t=new Date,r=ne){const i=this.clone();return i.users=await Promise.all(this.users.map((function(i){return i.certify(e,t,r)}))),i}async verifyPrimaryUser(e,t=new Date,r,i=ne){const n=this.keyPacket,{user:a}=await this.getPrimaryUser(t,r,i);return e?await a.verifyAllCertifications(e,t,i):[{keyID:n.getKeyID(),valid:await a.verify(t,i).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=ne){const i=this.keyPacket,n=[];return await Promise.all(this.users.map((async a=>{const s=e?await a.verifyAllCertifications(e,t,r):[{keyID:i.getKeyID(),valid:await a.verify(t,r).catch((()=>!1))}];n.push(...s.map((e=>({userID:a.userID?a.userID.userID:null,userAttribute:a.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),n}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{lh.prototype[e]=uh.prototype[e]}));class ph extends lh{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([$.packet.secretKey,$.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=ne){return le($.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,e)}}class yh extends ph{constructor(e){if(super(),this.packetListToStructure(e,new Set([$.packet.publicKey,$.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new lu,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case $.packet.secretKey:{const t=Du.fromSecretKeyPacket(r);e.push(t);break}case $.packet.secretSubkey:{const t=Bu.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new ph(e)}armor(e=ne){return le($.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,e)}async getDecryptionKeys(e,t=new Date,r={},i=ne){const n=this.keyPacket,a=[];for(let r=0;re.isDecrypted()))}async validate(e=ne){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys(),t=e.map((e=>e.keyPacket.isDummy())).every(Boolean);if(t)throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=$.reasonForRevocation.noReason,string:t=""}={},r=new Date,i=ne){if(!this.isPrivate())throw Error("Need private key for revoking");const n={key:this.keyPacket},a=this.clone();return a.revocationSignatures.push(await Ju(n,null,this.keyPacket,{signatureType:$.signature.keyRevocation,reasonForRevocationFlag:$.write($.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,i)),a}async addSubkey(e={}){const t={...ne,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}const s=Ou.fromObject(t),o={};o.userID=s,o.key=e;const c={};c.signatureType=$.signature.certGeneric,c.keyFlags=[$.keyFlags.certifyKeys|$.keyFlags.signData],c.preferredSymmetricAlgorithms=a([$.symmetric.aes256,$.symmetric.aes128,$.symmetric.aes192],i.preferredSymmetricAlgorithm),i.aeadProtect&&(c.preferredAEADAlgorithms=a([$.aead.eax,$.aead.ocb],i.preferredAEADAlgorithm)),c.preferredHashAlgorithms=a([$.hash.sha256,$.hash.sha512],i.preferredHashAlgorithm),c.preferredCompressionAlgorithms=a([$.compression.zlib,$.compression.zip,$.compression.uncompressed],i.preferredCompressionAlgorithm),0===n&&(c.isPrimaryUserID=!0),c.features=[0],c.features[0]|=$.features.modificationDetection,i.aeadProtect&&(c.features[0]|=$.features.aead),i.v5Keys&&(c.features[0]|=$.features.v5Keys),r.keyExpirationTime>0&&(c.keyExpirationTime=r.keyExpirationTime,c.keyNeverExpires=!1);return{userIDPacket:s,signaturePacket:await Ju(o,null,e,c,r.date,void 0,void 0,void 0,i)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{n.push(e),n.push(t)}))})),await Promise.all(t.map((async function(t,n){const a=r.subkeys[n];return{secretSubkeyPacket:t,subkeySignaturePacket:await Xu(t,e,a,i)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{n.push(e),n.push(t)}))}));const a={key:e};return n.push(await Ju(a,null,e,{signatureType:$.signature.keyRevocation,reasonForRevocationFlag:$.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,i)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new yh(n)}async function wh({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...ne,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!X.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!X.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await fe(e,r);if(t!==$.armor.publicKey&&t!==$.armor.privateKey)throw Error("Armored text not of type key");a=i}else a=t;return mh(await lu.fromBinary(a,bh,r))}async function vh({armoredKey:e,binaryKey:t,config:r,...i}){if(r={...ne,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!X.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!X.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));let a;if(e){const{type:t,data:i}=await fe(e,r);if(t!==$.armor.privateKey)throw Error("Armored text not of type private key");a=i}else a=t;const s=await lu.fromBinary(a,bh,r);return new yh(s)}async function _h({armoredKeys:e,binaryKeys:t,config:r,...i}){r={...ne,...r};let n=e||t;if(!n)throw Error("readKeys: must pass options object containing `armoredKeys` or `binaryKeys`");if(e&&!X.isString(e))throw Error("readKeys: options.armoredKeys must be a string");if(t&&!X.isUint8Array(t))throw Error("readKeys: options.binaryKeys must be a Uint8Array");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));if(e){const{type:t,data:i}=await fe(e,r);if(t!==$.armor.publicKey&&t!==$.armor.privateKey)throw Error("Armored text not of type key");n=i}const s=[],o=await lu.fromBinary(n,bh,r),c=o.indexOfTag($.packet.publicKey,$.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag($.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,i=new Date,n=ne){const a=r||await this.decryptSessionKeys(e,t,i,n),s=this.packets.filterByTag($.packet.symmetricallyEncryptedData,$.packet.symEncryptedIntegrityProtectedData,$.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const o=s[0];let c=null;const u=Promise.all(a.map((async({algorithm:e,data:t})=>{if(!X.isUint8Array(t)||!X.isString(e))throw Error("Invalid session key for decryption.");try{const r=$.write($.symmetric,e);await o.decrypt(r,t,n)}catch(e){X.printDebugError(e),c=e}})));if(j(o.encrypted),o.encrypted=null,await u,!o.packets||!o.packets.length)throw c||Error("Decryption failed.");const h=new Ph(o.packets);return o.packets=new lu,h}async decryptSessionKeys(e,t,r=new Date,i=ne){let n,a=[];if(t){const e=this.packets.filterByTag($.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await lu.fromBinary(e.write(),Sh,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){X.printDebugError(e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag($.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let s=[$.symmetric.aes256,$.symmetric.aes128,$.symmetric.tripledes,$.symmetric.cast5];try{const t=await e.getPrimaryUser(r,void 0,i);t.selfCertification.preferredSymmetricAlgorithms&&(s=s.concat(t.selfCertification.preferredSymmetricAlgorithms))}catch(e){}const o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket));await Promise.all(o.map((async function(e){if(!e||e.isDummy())return;if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===$.publicKey.rsaEncrypt||t.publicKeyAlgorithm===$.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===$.publicKey.rsaSign||t.publicKeyAlgorithm===$.publicKey.elgamal)){const r=t.write();await Promise.all(Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map((async t=>{const i=new xu;i.read(r);const s={sessionKeyAlgorithm:t,sessionKey:ga.generateSessionKey(t)};try{await i.decrypt(e,s),a.push(i)}catch(e){X.printDebugError(e),n=e}})))}else try{if(await t.decrypt(e),!s.includes($.write($.symmetric,t.sessionKeyAlgorithm)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){X.printDebugError(e),n=e}})))}))),j(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+X.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:$.read($.symmetric,e.sessionKeyAlgorithm)})))}throw n||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket($.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],i=ne){const n=await Qu("symmetric",e,t,r,i),a=$.read($.symmetric,n),s=i.aeadProtect&&await async function(e,t=new Date,r=[],i=ne){let n=!0;return await Promise.all(e.map((async function(e,a){const s=await e.getPrimaryUser(t,r[a],i);s.selfCertification.features&&s.selfCertification.features[0]&$.features.aead||(n=!1)}))),n}(e,t,r,i)?$.read($.aead,await Qu("aead",e,t,r,i)):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&e.keyPacket.algorithm===$.publicKey.x25519&&!X.isAES(n))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:ga.generateSessionKey(n),algorithm:a,aeadAlgorithm:s}}async encrypt(e,t,r,i=!1,n=[],a=new Date,s=[],o=ne){if(r){if(!X.isUint8Array(r.data)||!X.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Ph.generateSessionKey(e,a,s,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Ph.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:u,aeadAlgorithm:h}=r,d=await Ph.encryptSessionKey(c,u,h,e,t,i,n,a,s,o);let f;h?(f=new Pu,f.aeadAlgorithm=$.write($.aead,h)):f=new Su,f.packets=this.packets;const l=$.write($.symmetric,u);return await f.encrypt(l,c,o),d.packets.push(f),f.packets=new lu,d}static async encryptSessionKey(e,t,r,i,n,a=!1,s=[],o=new Date,c=[],u=ne){const h=new lu,d=$.write($.symmetric,t),f=r&&$.write($.aead,r);if(i){const t=await Promise.all(i.map((async function(t,r){const i=await t.getEncryptionKey(s[r],o,c,u),n=new xu;return n.publicKeyID=a?pe.wildcard():i.getKeyID(),n.publicKeyAlgorithm=i.keyPacket.algorithm,n.sessionKey=e,n.sessionKeyAlgorithm=d,await n.encrypt(i.keyPacket),delete n.sessionKey,n})));h.push(...t)}if(n){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,i=async function(e,a,s,o){const c=new Cu(u);if(c.sessionKey=e,c.sessionKeyAlgorithm=a,s&&(c.aeadAlgorithm=s),await c.encrypt(o,u),u.passwordCollisionCheck){if(1!==(await Promise.all(n.map((e=>t(c,e))))).reduce(r))return i(e,a,o)}return delete c.sessionKey,c},a=await Promise.all(n.map((t=>i(e,d,f,t))));h.push(...a)}return new Ph(h)}async sign(e=[],t=null,r=[],i=new Date,n=[],a=[],s=ne){const o=new lu,c=this.packets.findPacket($.packet.literalData);if(!c)throw Error("No literal data packet to sign.");let u,h;const d=null===c.text?$.signature.binary:$.signature.text;if(t)for(h=t.packets.filterByTag($.packet.signature),u=h.length-1;u>=0;u--){const t=h[u],r=new du;r.signatureType=t.signatureType,r.hashAlgorithm=t.hashAlgorithm,r.publicKeyAlgorithm=t.publicKeyAlgorithm,r.issuerKeyID=t.issuerKeyID,e.length||0!==u||(r.flags=1),o.push(r)}return await Promise.all(Array.from(e).reverse().map((async function(t,a){if(!t.isPrivate())throw Error("Need private key for signing");const o=r[e.length-1-a],c=await t.getSigningKey(o,i,n,s),u=new du;return u.signatureType=d,u.hashAlgorithm=await Yu(t,c.keyPacket,i,n,s),u.publicKeyAlgorithm=c.keyPacket.algorithm,u.issuerKeyID=c.getKeyID(),a===e.length-1&&(u.flags=1),u}))).then((e=>{e.forEach((e=>o.push(e)))})),o.push(c),o.push(...await xh(c,e,t,r,i,n,a,!1,s)),new Ph(o)}compress(e,t=ne){if(e===$.compression.uncompressed)return this;const r=new yu(t);r.algorithm=e,r.packets=this.packets;const i=new lu;return i.push(r),new Ph(i)}async signDetached(e=[],t=null,r=[],i=new Date,n=[],a=[],s=ne){const o=this.packets.findPacket($.packet.literalData);if(!o)throw Error("No literal data packet to sign.");return new Hu(await xh(o,e,t,r,i,n,a,!0,s))}async verify(e,t=new Date,r=ne){const i=this.unwrapCompressed(),n=i.packets.filterByTag($.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");s(i.packets.stream)&&i.packets.push(...await N(i.packets.stream,(e=>e||[])));const a=i.packets.filterByTag($.packet.onePassSignature).reverse(),o=i.packets.filterByTag($.packet.signature);return a.length&&!o.length&&X.isStream(i.packets.stream)&&!s(i.packets.stream)?(await Promise.all(a.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=H((async()=>(await e.correspondingSig).signatureData)),e.hashed=N(await e.hash(e.signatureType,n[0],void 0,!1)),e.hashed.catch((()=>{}))}))),i.packets.stream=T(i.packets.stream,(async(e,t)=>{const r=C(e),i=D(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await i.abort(e)}})),Mh(a,n,e,t,!1,r)):Mh(o,n,e,t,!1,r)}verifyDetached(e,t,r=new Date,i=ne){const n=this.unwrapCompressed().packets.filterByTag($.packet.literalData);if(1!==n.length)throw Error("Can only verify message with one literal data packet.");return Mh(e.packets.filterByTag($.packet.signature),n,t,r,!0,i)}unwrapCompressed(){const e=this.packets.filterByTag($.packet.compressedData);return e.length?new Ph(e[0].packets):this}async appendSignature(e,t=ne){await this.packets.read(X.isUint8Array(e)?e:(await fe(e)).data,Eh,t)}write(){return this.packets.write()}armor(e=ne){return le($.armor.message,this.write(),null,null,null,e)}}async function xh(e,t,r=null,i=[],n=new Date,a=[],s=[],o=!1,c=ne){const u=new lu,h=null===e.text?$.signature.binary:$.signature.text;if(await Promise.all(t.map((async(t,r)=>{const u=a[r];if(!t.isPrivate())throw Error("Need private key for signing");const d=await t.getSigningKey(i[r],n,u,c);return Ju(e,t,d.keyPacket,{signatureType:h},n,u,s,o,c)}))).then((e=>{u.push(...e)})),r){const e=r.packets.filterByTag($.packet.signature);u.push(...e)}return u}async function Mh(e,t,r,i=new Date,n=!1,a=ne){return Promise.all(e.filter((function(e){return["text","binary"].includes($.read($.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,i=new Date,n=!1,a=ne){let s,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){s=t,o=r[0];break}}const c=e instanceof du?e.correspondingSig:e,u={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],i,n,a);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await s.getSigningKey(o.getKeyID(),r.created,void 0,a)}catch(e){if(!a.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await s.getSigningKey(o.getKeyID(),i,void 0,a)}return!0})(),signature:(async()=>{const e=await c,t=new lu;return e&&t.push(e),new Hu(t)})()};return u.signature.catch((()=>{})),u.verified.catch((()=>{})),u}(e,t,r,i,n,a)})))}async function Kh({armoredMessage:e,binaryMessage:t,config:r,...i}){r={...ne,...r};let n=e||t;if(!n)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!X.isString(e)&&!X.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!X.isUint8Array(t)&&!X.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const a=Object.keys(i);if(a.length>0)throw Error("Unknown option: "+a.join(", "));const s=X.isStream(n);if(s&&(await E(),n=x(n)),e){const{type:e,data:t}=await fe(n,r);if(e!==$.armor.message)throw Error("Armored text not of type message");n=t}const o=await lu.fromBinary(n,Ah,r),c=new Ph(o);return c.fromStream=s,c}async function Ch({text:e,binary:t,filename:r,date:i=new Date,format:n=(void 0!==e?"utf8":"binary"),...a}){let s=void 0!==e?e:t;if(void 0===s)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!X.isString(e)&&!X.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!X.isUint8Array(t)&&!X.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=X.isStream(s);c&&(await E(),s=x(s));const u=new su(i);void 0!==e?u.setText(s,$.write($.literal,n)):u.setBytes(s,$.write($.literal,n)),void 0!==r&&u.setFilename(r);const h=new lu;h.push(u);const d=new Ph(h);return d.fromStream=c,d}const Dh=/*#__PURE__*/X.constructAllowedPackets([uu]);class Uh{constructor(e,t){if(this.text=X.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof Hu))throw Error("Invalid signature input");this.signature=t||new Hu(new lu)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=null,r=[],i=new Date,n=[],a=[],s=ne){const o=new su;o.setText(this.text);const c=new Hu(await xh(o,e,t,r,i,n,a,!0,s));return new Uh(this.text,c)}verify(e,t=new Date,r=ne){const i=this.signature.packets.filterByTag($.packet.signature),n=new su;return n.setText(this.text),Mh(i,[n],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=ne){let t=this.signature.packets.map((function(e){return $.read($.hash,e.hashAlgorithm).toUpperCase()}));t=t.filter((function(e,t,r){return r.indexOf(e)===t}));const r={hash:t.join(),text:this.text,data:this.signature.packets.write()};return le($.armor.signed,r,void 0,void 0,void 0,e)}}async function Rh({cleartextMessage:e,config:t,...r}){if(t={...ne,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!X.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const i=Object.keys(r);if(i.length>0)throw Error("Unknown option: "+i.join(", "));const n=await fe(e);if(n.type!==$.armor.signed)throw Error("No cleartext signed message.");const a=await lu.fromBinary(n.data,Dh,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let i=0;i0)throw Error("Unknown option: "+r.join(", "));return new Uh(e)}async function Bh({userIDs:e=[],passphrase:t,type:r="ecc",rsaBits:i=4096,curve:n="curve25519",keyExpirationTime:a=0,date:s=new Date,subkeys:o=[{}],format:c="armored",config:u,...h}){Yh(u={...ne,...u}),e=Qh(e);const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));if(0===e.length)throw Error("UserIDs are required for key generation");if("rsa"===r&&iih(e.subkeys[r],e)));let r=[Vu(e,t)];r=r.concat(e.subkeys.map((e=>Gu(e,t))));const i=await Promise.all(r),n=await gh(i[0],i.slice(1),e,t),a=await n.getRevocationCertificate(e.date,t);return n.revocationSignatures=[],{key:n,revocationCertificate:a}}(f,u);return e.getKeys().forEach((({keyPacket:e})=>oh(e,u))),{privateKey:td(e,c,u),publicKey:td(e.toPublic(),c,u),revocationCertificate:t}}catch(e){throw X.wrapError("Error generating keypair",e)}}async function Th({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:i=0,date:n,format:a="armored",config:s,...o}){Yh(s={...ne,...s}),t=Qh(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length)throw Error("UserIDs are required for key reformat");const u={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:i,date:n};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const i=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,n={key:i,bind:r},a=await $u(e.bindingSignatures,i,$.signature.subkeyBinding,n,null,t).catch((()=>({})));return{sign:a.keyFlags&&a.keyFlags[0]&$.keyFlags.signData}}))));const n=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==n.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const a=await gh(i,n,e,t),s=await a.getRevocationCertificate(e.date,t);return a.revocationSignatures=[],{key:a,revocationCertificate:s};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=X.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(u,s);return{privateKey:td(e,a,s),publicKey:td(e.toPublic(),a,s),revocationCertificate:t}}catch(e){throw X.wrapError("Error reformatting keypair",e)}}async function zh({key:e,revocationCertificate:t,reasonForRevocation:r,date:i=new Date,format:n="armored",config:a,...s}){Yh(a={...ne,...a});const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const s=t?await e.applyRevocationCertificate(t,i,a):await e.revoke(r,i,a);return s.isPrivate()?{privateKey:td(s,n,a),publicKey:td(s.toPublic(),n,a)}:{privateKey:null,publicKey:td(s,n,a)}}catch(e){throw X.wrapError("Error revoking key",e)}}async function qh({privateKey:e,passphrase:t,config:r,...i}){Yh(r={...ne,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const a=e.clone(!0),s=X.isArray(t)?t:[t];try{return await Promise.all(a.getKeys().map((e=>X.anyPromise(s.map((t=>e.keyPacket.decrypt(t))))))),await a.validate(r),a}catch(e){throw a.clearPrivateParams(),X.wrapError("Error decrypting private key",e)}}async function Fh({privateKey:e,passphrase:t,config:r,...i}){Yh(r={...ne,...r});const n=Object.keys(i);if(n.length>0)throw Error("Unknown option: "+n.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const a=e.clone(!0),s=a.getKeys(),o=X.isArray(t)?t:Array(s.length).fill(t);if(o.length!==s.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(s.map((async(e,t)=>{const{keyPacket:i}=e;await i.encrypt(o[t],r),i.clearPrivateParams()}))),a}catch(e){throw a.clearPrivateParams(),X.wrapError("Error encrypting private key",e)}}async function Oh({message:e,encryptionKeys:t,signingKeys:r,passwords:i,sessionKey:n,format:a="armored",signature:s=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:u=[],date:h=new Date,signingUserIDs:d=[],encryptionUserIDs:f=[],signatureNotations:l=[],config:p,...y}){if(Yh(p={...ne,...p}),Vh(e),Zh(a),t=Qh(t),r=Qh(r),i=Qh(i),c=Qh(c),u=Qh(u),d=Qh(d),f=Qh(f),l=Qh(l),y.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(y.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(y.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==y.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const b=Object.keys(y);if(b.length>0)throw Error("Unknown option: "+b.join(", "));r||(r=[]);const m=e.fromStream;try{if((r.length||s)&&(e=await e.sign(r,s,c,h,d,l,p)),e=e.compress(await Qu("compression",t,h,f,p),p),e=await e.encrypt(t,i,n,o,u,h,f,p),"object"===a)return e;const y="armored"===a;return Jh(y?e.armor(p):e.write(),m,y?"utf8":"binary")}catch(e){throw X.wrapError("Error encrypting message",e)}}async function Lh({message:e,decryptionKeys:t,passwords:r,sessionKeys:i,verificationKeys:n,expectSigned:a=!1,format:s="utf8",signature:o=null,date:c=new Date,config:u,...h}){if(Yh(u={...ne,...u}),Vh(e),n=Qh(n),t=Qh(t),r=Qh(r),i=Qh(i),h.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(h.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const d=Object.keys(h);if(d.length>0)throw Error("Unknown option: "+d.join(", "));try{const h=await e.decrypt(t,r,i,c,u);n||(n=[]);const d={};if(d.signatures=o?await h.verifyDetached(o,n,c,u):await h.verify(n,c,u),d.data="binary"===s?h.getLiteralData():h.getText(),d.filename=h.getFilename(),ed(d,e),a){if(0===n.length)throw Error("Verification keys are required to verify message signatures");if(0===d.signatures.length)throw Error("Message is not signed");d.data=K([d.data,H((async()=>{await X.anyPromise(d.signatures.map((e=>e.verified)))}))])}return d.data=await Jh(d.data,e.fromStream,s),d}catch(e){throw X.wrapError("Error decrypting message",e)}}async function Nh({message:e,signingKeys:t,format:r="armored",detached:i=!1,signingKeyIDs:n=[],date:a=new Date,signingUserIDs:s=[],signatureNotations:o=[],config:c,...u}){if(Yh(c={...ne,...c}),$h(e),Zh(r),t=Qh(t),n=Qh(n),s=Qh(s),o=Qh(o),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==u.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const h=Object.keys(u);if(h.length>0)throw Error("Unknown option: "+h.join(", "));if(e instanceof Uh&&"binary"===r)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Uh&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let u;if(u=i?await e.signDetached(t,void 0,n,a,s,o,c):await e.sign(t,void 0,n,a,s,o,c),"object"===r)return u;const h="armored"===r;return u=h?u.armor(c):u.write(),i&&(u=T(e.packets.write(),(async(e,t)=>{await Promise.all([U(u,t),N(e).catch((()=>{}))])}))),Jh(u,e.fromStream,h?"utf8":"binary")}catch(e){throw X.wrapError("Error signing message",e)}}async function jh({message:e,verificationKeys:t,expectSigned:r=!1,format:i="utf8",signature:n=null,date:a=new Date,config:s,...o}){if(Yh(s={...ne,...s}),$h(e),t=Qh(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Uh&&"binary"===i)throw Error("Can't return cleartext message data as binary");if(e instanceof Uh&&n)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=n?await e.verifyDetached(n,t,a,s):await e.verify(t,a,s),o.data="binary"===i?e.getLiteralData():e.getText(),e.fromStream&&!n&&ed(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=K([o.data,H((async()=>{await X.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await Jh(o.data,e.fromStream,i),o}catch(e){throw X.wrapError("Error verifying signed message",e)}}async function Hh({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:i,...n}){if(Yh(i={...ne,...i}),e=Qh(e),r=Qh(r),n.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const a=Object.keys(n);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await Ph.generateSessionKey(e,t,r,i)}catch(e){throw X.wrapError("Error generating session key",e)}}async function Wh({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:i,passwords:n,format:a="armored",wildcard:s=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:u=[],config:h,...d}){if(Yh(h={...ne,...h}),function(e,t){if(!X.isUint8Array(e))throw Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(e),function(e,t){if(!X.isString(e))throw Error("Parameter ["+(t||"data")+"] must be of type String")}(t,"algorithm"),Zh(a),i=Qh(i),n=Qh(n),o=Qh(o),u=Qh(u),d.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const f=Object.keys(d);if(f.length>0)throw Error("Unknown option: "+f.join(", "));if(!(i&&0!==i.length||n&&0!==n.length))throw Error("No encryption keys or passwords provided.");try{return td(await Ph.encryptSessionKey(e,t,r,i,n,s,o,c,u,h),a,h)}catch(e){throw X.wrapError("Error encrypting session key",e)}}async function Gh({message:e,decryptionKeys:t,passwords:r,date:i=new Date,config:n,...a}){if(Yh(n={...ne,...n}),Vh(e),t=Qh(t),r=Qh(r),a.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const s=Object.keys(a);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await e.decryptSessionKeys(t,r,i,n)}catch(e){throw X.wrapError("Error decrypting session keys",e)}}function Vh(e){if(!(e instanceof Ph))throw Error("Parameter [message] needs to be of type Message")}function $h(e){if(!(e instanceof Uh||e instanceof Ph))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Zh(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Xh=Object.keys(ne).length;function Yh(e){const t=Object.keys(e);if(t.length!==Xh)for(const e of t)if(void 0===ne[e])throw Error("Unknown config property: "+e)}function Qh(e){return e&&!X.isArray(e)&&(e=[e]),e}async function Jh(e,t,r="utf8"){const i=X.isStream(e);return"array"===i?N(e):"node"===t?(e=b(e),"binary"!==r&&e.setEncoding(r),e):"web"===t&&"ponyfill"===i?_(e):e}function ed(e,t){e.data=T(t.packets.stream,(async(t,r)=>{await U(e.data,r,{preventClose:!0});const i=D(r);try{await N(t,(e=>e)),await i.close()}catch(e){await i.abort(e)}}))}function td(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}const rd="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function id(){}const nd="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function ad(e){return"object"==typeof e&&null!==e||"function"==typeof e}const sd=id,od=Promise,cd=Promise.prototype.then,ud=Promise.resolve.bind(od),hd=Promise.reject.bind(od);function dd(e){return new od(e)}function fd(e){return ud(e)}function ld(e){return hd(e)}function pd(e,t,r){return cd.call(e,t,r)}function yd(e,t,r){pd(pd(e,t,r),void 0,sd)}function bd(e,t){yd(e,t)}function md(e,t){yd(e,void 0,t)}function gd(e,t,r){return pd(e,t,r)}function wd(e){pd(e,void 0,sd)}const vd=(()=>{const e=nd&&nd.queueMicrotask;if("function"==typeof e)return e;const t=fd(void 0);return e=>pd(t,e)})();function _d(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function kd(e,t,r){try{return fd(_d(e,t,r))}catch(e){return ld(e)}}class Ad{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let i=r+1;const n=e._elements,a=n[r];return 16384===i&&(t=e._next,i=0),--this._size,this._cursor=i,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,i=r._elements;for(;!(t===i.length&&void 0===r._next||t===i.length&&(r=r._next,i=r._elements,t=0,0===i.length));)e(i[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function Sd(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?Md(e):"closed"===t._state?function(e){Md(e),Dd(e)}(e):Kd(e,t._storedError)}function Ed(e,t){return up(e._ownerReadableStream,t)}function Pd(e){"readable"===e._ownerReadableStream._state?Cd(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){Kd(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function xd(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function Md(e){e._closedPromise=dd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function Kd(e,t){Md(e),Cd(e,t)}function Cd(e,t){void 0!==e._closedPromise_reject&&(wd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function Dd(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const Ud=rd("[[AbortSteps]]"),Rd=rd("[[ErrorSteps]]"),Id=rd("[[CancelSteps]]"),Bd=rd("[[PullSteps]]"),Td=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},zd=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function qd(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(t+" is not an object.");var r}function Fd(e,t){if("function"!=typeof e)throw new TypeError(t+" is not a function.")}function Od(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(t+" is not an object.")}function Ld(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function Nd(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function jd(e){return Number(e)}function Hd(e){return 0===e?0:e}function Wd(e,t){const r=Number.MAX_SAFE_INTEGER;let i=Number(e);if(i=Hd(i),!Td(i))throw new TypeError(t+" is not a finite number");if(i=function(e){return Hd(zd(e))}(i),i<0||i>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return Td(i)&&0!==i?i:0}function Gd(e,t){if(!op(e))throw new TypeError(t+" is not a ReadableStream.")}function Vd(e){return new Qd(e)}function $d(e,t){e._reader._readRequests.push(t)}function Zd(e,t,r){const i=e._reader._readRequests.shift();r?i._closeSteps():i._chunkSteps(t)}function Xd(e){return e._reader._readRequests.length}function Yd(e){const t=e._reader;return void 0!==t&&!!Jd(t)}class Qd{constructor(e){if(Ld(e,1,"ReadableStreamDefaultReader"),Gd(e,"First parameter"),cp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");Sd(this,e),this._readRequests=new Ad}get closed(){return Jd(this)?this._closedPromise:ld(tf("closed"))}cancel(e=undefined){return Jd(this)?void 0===this._ownerReadableStream?ld(xd("cancel")):Ed(this,e):ld(tf("cancel"))}read(){if(!Jd(this))return ld(tf("read"));if(void 0===this._ownerReadableStream)return ld(xd("read from"));let e,t;const r=dd(((r,i)=>{e=r,t=i}));return ef(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!Jd(this))throw tf("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");Pd(this)}}}function Jd(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function ef(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[Bd](t)}function tf(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let rf;Object.defineProperties(Qd.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(Qd.prototype,rd.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof rd.asyncIterator&&(rf={[rd.asyncIterator](){return this}},Object.defineProperty(rf,rd.asyncIterator,{enumerable:!1}));class nf{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?gd(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?gd(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return ld(xd("iterate"));let t,r;const i=dd(((e,i)=>{t=e,r=i}));return ef(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,vd((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Pd(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,Pd(e),r(t)}}),i}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return ld(xd("finish iterating"));if(!this._preventCancel){const r=Ed(t,e);return Pd(t),gd(r,(()=>({value:e,done:!0})))}return Pd(t),fd({value:e,done:!0})}}const af={next(){return sf(this)?this._asyncIteratorImpl.next():ld(of("next"))},return(e){return sf(this)?this._asyncIteratorImpl.return(e):ld(of("return"))}};function sf(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl")}function of(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==rf&&Object.setPrototypeOf(af,rf);const cf=Number.isNaN||function(e){return e!=e};function uf(e){return!!function(e){if("number"!=typeof e)return!1;if(cf(e))return!1;if(e<0)return!1;return!0}(e)&&e!==1/0}function hf(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function df(e,t,r){if(!uf(r=Number(r)))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ff(e){e._queue=new Ad,e._queueTotalSize=0}function lf(e){return e.slice()}class pf{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!mf(this))throw Rf("view");return this._view}respond(e){if(!mf(this))throw Rf("respond");if(Ld(e,1,"respond"),e=Wd(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){if(t=Number(t),!uf(t))throw new RangeError("bytesWritten must be a finite");xf(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!mf(this))throw Rf("respondWithNewView");if(Ld(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");!function(e,t){const r=e._pendingPullIntos.peek();if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==t.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=t.buffer,xf(e,t.byteLength)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(pf.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(pf.prototype,rd.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class yf{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!bf(this))throw If("byobRequest");if(null===this._byobRequest&&this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek(),t=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled),r=Object.create(pf.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(r,this,t),this._byobRequest=r}return this._byobRequest}get desiredSize(){if(!bf(this))throw If("desiredSize");return Df(this)}close(){if(!bf(this))throw If("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Cf(e,t),t}}Kf(e),hp(t)}(this)}enqueue(e){if(!bf(this))throw If("enqueue");if(Ld(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const i=t.buffer,n=t.byteOffset,a=t.byteLength,s=i;if(Yd(r))if(0===Xd(r))_f(e,s,n,a);else{Zd(r,new Uint8Array(s,n,a),!1)}else zf(r)?(_f(e,s,n,a),Pf(e)):_f(e,s,n,a);gf(e)}(this,e)}error(e=undefined){if(!bf(this))throw If("error");Cf(this,e)}[Id](e){if(this._pendingPullIntos.length>0){this._pendingPullIntos.peek().bytesFilled=0}ff(this);const t=this._cancelAlgorithm(e);return Kf(this),t}[Bd](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,Sf(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const i={buffer:t,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(i)}$d(t,e),gf(this)}}function bf(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")}function mf(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function gf(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(Yd(t)&&Xd(t)>0)return!0;if(zf(t)&&Tf(t)>0)return!0;const r=Df(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;yd(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,gf(e))}),(t=>{Cf(e,t)}))}function wf(e,t){let r=!1;"closed"===e._state&&(r=!0);const i=vf(t);"default"===t.readerType?Zd(e,i,r):function(e,t,r){const i=e._reader,n=i._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,i,r)}function vf(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function _f(e,t,r,i){e._queue.push({buffer:t,byteOffset:r,byteLength:i}),e._queueTotalSize+=i}function kf(e,t){const r=t.elementSize,i=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,s=a-a%r;let o=n,c=!1;s>i&&(o=s-t.bytesFilled,c=!0);const u=e._queue;for(;o>0;){const r=u.peek(),i=Math.min(o,r.byteLength),n=t.byteOffset+t.bytesFilled;h=t.buffer,d=n,f=r.buffer,l=r.byteOffset,p=i,new Uint8Array(h).set(new Uint8Array(f,l,p),d),r.byteLength===i?u.shift():(r.byteOffset+=i,r.byteLength-=i),e._queueTotalSize-=i,Af(e,i,t),o-=i}var h,d,f,l,p;return c}function Af(e,t,r){Ef(e),r.bytesFilled+=t}function Sf(e){0===e._queueTotalSize&&e._closeRequested?(Kf(e),hp(e._controlledReadableByteStream)):gf(e)}function Ef(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Pf(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();kf(e,t)&&(Mf(e),wf(e._controlledReadableByteStream,t))}}function xf(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function(e,t){t.buffer=t.buffer;const r=e._controlledReadableByteStream;if(zf(r))for(;Tf(r)>0;)wf(r,Mf(e))}(e,r)}else!function(e,t,r){if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range");if(Af(e,t,r),r.bytesFilled0){const t=r.byteOffset+r.bytesFilled,n=r.buffer.slice(t-i,t);_f(e,n,0,n.byteLength)}r.buffer=r.buffer,r.bytesFilled-=i,wf(e._controlledReadableByteStream,r),Pf(e)}(e,t,r);gf(e)}function Mf(e){const t=e._pendingPullIntos.shift();return Ef(e),t}function Kf(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Cf(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(!function(e){Ef(e),e._pendingPullIntos=new Ad}(e),ff(e),Kf(e),dp(r,t))}function Df(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Uf(e,t,r){const i=Object.create(yf.prototype);let n=()=>{},a=()=>fd(void 0),s=()=>fd(void 0);void 0!==t.start&&(n=()=>t.start(i)),void 0!==t.pull&&(a=()=>t.pull(i)),void 0!==t.cancel&&(s=e=>t.cancel(e));const o=t.autoAllocateChunkSize;if(0===o)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,i,n,a,s){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ff(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,t._autoAllocateChunkSize=s,t._pendingPullIntos=new Ad,e._readableStreamController=t,yd(fd(r()),(()=>{t._started=!0,gf(t)}),(e=>{Cf(t,e)}))}(e,i,n,a,s,r,o)}function Rf(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function If(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Bf(e,t){e._reader._readIntoRequests.push(t)}function Tf(e){return e._reader._readIntoRequests.length}function zf(e){const t=e._reader;return void 0!==t&&!!Ff(t)}Object.defineProperties(yf.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(yf.prototype,rd.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class qf{constructor(e){if(Ld(e,1,"ReadableStreamBYOBReader"),Gd(e,"First parameter"),cp(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!bf(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");Sd(this,e),this._readIntoRequests=new Ad}get closed(){return Ff(this)?this._closedPromise:ld(Of("closed"))}cancel(e=undefined){return Ff(this)?void 0===this._ownerReadableStream?ld(xd("cancel")):Ed(this,e):ld(Of("cancel"))}read(e){if(!Ff(this))return ld(Of("read"));if(!ArrayBuffer.isView(e))return ld(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return ld(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return ld(new TypeError("view's buffer must have non-zero byteLength"));if(void 0===this._ownerReadableStream)return ld(xd("read from"));let t,r;const i=dd(((e,i)=>{t=e,r=i}));return function(e,t,r){const i=e._ownerReadableStream;i._disturbed=!0,"errored"===i._state?r._errorSteps(i._storedError):function(e,t,r){const i=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,s={buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(s),void Bf(i,r);if("closed"!==i._state){if(e._queueTotalSize>0){if(kf(e,s)){const t=vf(s);return Sf(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Cf(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(s),Bf(i,r),gf(e)}else{const e=new a(s.buffer,s.byteOffset,0);r._closeSteps(e)}}(i._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),i}releaseLock(){if(!Ff(this))throw Of("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");Pd(this)}}}function Ff(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function Of(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Lf(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(cf(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Nf(e){const{size:t}=e;return t||(()=>1)}function jf(e,t){qd(e,t);const r=null==e?void 0:e.highWaterMark,i=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:jd(r),size:void 0===i?void 0:Hf(i,t+" has member 'size' that")}}function Hf(e,t){return Fd(e,t),t=>jd(e(t))}function Wf(e,t,r){return Fd(e,r),r=>kd(e,t,[r])}function Gf(e,t,r){return Fd(e,r),()=>kd(e,t,[])}function Vf(e,t,r){return Fd(e,r),r=>_d(e,t,[r])}function $f(e,t,r){return Fd(e,r),(r,i)=>kd(e,t,[r,i])}function Zf(e,t){if(!Jf(e))throw new TypeError(t+" is not a WritableStream.")}Object.defineProperties(qf.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(qf.prototype,rd.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});class Xf{constructor(e={},t={}){void 0===e?e=null:Od(e,"First parameter");const r=jf(t,"Second parameter"),i=function(e,t){qd(e,t);const r=null==e?void 0:e.abort,i=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,s=null==e?void 0:e.write;return{abort:void 0===r?void 0:Wf(r,e,t+" has member 'abort' that"),close:void 0===i?void 0:Gf(i,e,t+" has member 'close' that"),start:void 0===n?void 0:Vf(n,e,t+" has member 'start' that"),write:void 0===s?void 0:$f(s,e,t+" has member 'write' that"),type:a}}(e,"First parameter");Qf(this);if(void 0!==i.type)throw new RangeError("Invalid type is specified");const n=Nf(r);!function(e,t,r,i){const n=Object.create(ml.prototype);let a=()=>{},s=()=>fd(void 0),o=()=>fd(void 0),c=()=>fd(void 0);void 0!==t.start&&(a=()=>t.start(n));void 0!==t.write&&(s=e=>t.write(e,n));void 0!==t.close&&(o=()=>t.close());void 0!==t.abort&&(c=e=>t.abort(e));gl(e,n,a,s,o,c,r,i)}(this,i,Lf(r,1),n)}get locked(){if(!Jf(this))throw El("locked");return el(this)}abort(e=undefined){return Jf(this)?el(this)?ld(new TypeError("Cannot abort a stream that already has a writer")):tl(this,e):ld(El("abort"))}close(){return Jf(this)?el(this)?ld(new TypeError("Cannot close a stream that already has a writer")):sl(this)?ld(new TypeError("Cannot close an already-closing stream")):rl(this):ld(El("close"))}getWriter(){if(!Jf(this))throw El("getWriter");return Yf(this)}}function Yf(e){return new ul(e)}function Qf(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new Ad,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function Jf(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function el(e){return void 0!==e._writer}function tl(e,t){const r=e._state;if("closed"===r||"errored"===r)return fd(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let i=!1;"erroring"===r&&(i=!0,t=void 0);const n=dd(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:i}}));return e._pendingAbortRequest._promise=n,i||nl(e,t),n}function rl(e){const t=e._state;if("closed"===t||"errored"===t)return ld(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=dd(((t,r)=>{const i={_resolve:t,_reject:r};e._closeRequest=i})),i=e._writer;var n;return void 0!==i&&e._backpressure&&"writable"===t&&Tl(i),df(n=e._writableStreamController,bl,0),_l(n),r}function il(e,t){"writable"!==e._state?al(e):nl(e,t)}function nl(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const i=e._writer;void 0!==i&&ll(i,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&al(e)}function al(e){e._state="errored",e._writableStreamController[Rd]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new Ad,void 0===e._pendingAbortRequest)return void ol(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ol(e);yd(e._writableStreamController[Ud](r._reason),(()=>{r._resolve(),ol(e)}),(t=>{r._reject(t),ol(e)}))}function sl(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ol(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Cl(t,e._storedError)}function cl(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Ul(e)}(r):Tl(r)),e._backpressure=t}Object.defineProperties(Xf.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(Xf.prototype,rd.toStringTag,{value:"WritableStream",configurable:!0});class ul{constructor(e){if(Ld(e,1,"WritableStreamDefaultWriter"),Zf(e,"First parameter"),el(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!sl(e)&&e._backpressure?Ul(this):Il(this),Ml(this);else if("erroring"===t)Rl(this,e._storedError),Ml(this);else if("closed"===t)Il(this),Ml(r=this),Dl(r);else{const t=e._storedError;Rl(this,t),Kl(this,t)}var r}get closed(){return hl(this)?this._closedPromise:ld(Pl("closed"))}get desiredSize(){if(!hl(this))throw Pl("desiredSize");if(void 0===this._ownerWritableStream)throw xl("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return vl(t._writableStreamController)}(this)}get ready(){return hl(this)?this._readyPromise:ld(Pl("ready"))}abort(e=undefined){return hl(this)?void 0===this._ownerWritableStream?ld(xl("abort")):function(e,t){const r=e._ownerWritableStream;return tl(r,t)}(this,e):ld(Pl("abort"))}close(){if(!hl(this))return ld(Pl("close"));const e=this._ownerWritableStream;return void 0===e?ld(xl("close")):sl(e)?ld(new TypeError("Cannot close an already-closing stream")):dl(this)}releaseLock(){if(!hl(this))throw Pl("releaseLock");void 0!==this._ownerWritableStream&&pl(this)}write(e=undefined){return hl(this)?void 0===this._ownerWritableStream?ld(xl("write to")):yl(this,e):ld(Pl("write"))}}function hl(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function dl(e){return rl(e._ownerWritableStream)}function fl(e,t){"pending"===e._closedPromiseState?Cl(e,t):function(e,t){Kl(e,t)}(e,t)}function ll(e,t){"pending"===e._readyPromiseState?Bl(e,t):function(e,t){Rl(e,t)}(e,t)}function pl(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");ll(e,r),fl(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function yl(e,t){const r=e._ownerWritableStream,i=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return kl(e,t),1}}(i,t);if(r!==e._ownerWritableStream)return ld(xl("write to"));const a=r._state;if("errored"===a)return ld(r._storedError);if(sl(r)||"closed"===a)return ld(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return ld(r._storedError);const s=function(e){return dd(((t,r)=>{const i={_resolve:t,_reject:r};e._writeRequests.push(i)}))}(r);return function(e,t,r){try{df(e,t,r)}catch(t){return void kl(e,t)}const i=e._controlledWritableStream;if(!sl(i)&&"writable"===i._state){cl(i,Al(e))}_l(e)}(i,t,n),s}Object.defineProperties(ul.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(ul.prototype,rd.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const bl={};class ml{constructor(){throw new TypeError("Illegal constructor")}error(e=undefined){if(!function(e){if(!ad(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream"))return!1;return!0}(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&Sl(this,e)}[Ud](e){const t=this._abortAlgorithm(e);return wl(this),t}[Rd](){ff(this)}}function gl(e,t,r,i,n,a,s,o){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ff(t),t._started=!1,t._strategySizeAlgorithm=o,t._strategyHWM=s,t._writeAlgorithm=i,t._closeAlgorithm=n,t._abortAlgorithm=a;const c=Al(t);cl(e,c);yd(fd(r()),(()=>{t._started=!0,_l(t)}),(r=>{t._started=!0,il(e,r)}))}function wl(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function vl(e){return e._strategyHWM-e._queueTotalSize}function _l(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void al(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===bl?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),hf(e);const r=e._closeAlgorithm();wl(e),yd(r,(()=>{!function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Dl(t)}(t)}),(e=>{!function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),il(e,t)}(t,e)}))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const i=e._writeAlgorithm(t);yd(i,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(hf(e),!sl(r)&&"writable"===t){const t=Al(e);cl(r,t)}_l(e)}),(t=>{"writable"===r._state&&wl(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,il(e,t)}(r,t)}))}(e,r)}function kl(e,t){"writable"===e._controlledWritableStream._state&&Sl(e,t)}function Al(e){return vl(e)<=0}function Sl(e,t){const r=e._controlledWritableStream;wl(e),nl(r,t)}function El(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Pl(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function xl(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Ml(e){e._closedPromise=dd(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Kl(e,t){Ml(e),Cl(e,t)}function Cl(e,t){void 0!==e._closedPromise_reject&&(wd(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Dl(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Ul(e){e._readyPromise=dd(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Rl(e,t){Ul(e),Bl(e,t)}function Il(e){Ul(e),Tl(e)}function Bl(e,t){void 0!==e._readyPromise_reject&&(wd(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Tl(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(ml.prototype,{error:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(ml.prototype,rd.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const zl="undefined"!=typeof DOMException?DOMException:void 0;const ql=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(zl)?zl:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return Object.defineProperty(e.prototype=Object.create(Error.prototype),"constructor",{value:e,writable:!0,configurable:!0}),e}();function Fl(e,t,r,i,n,a){const s=Vd(e),o=Yf(t);e._disturbed=!0;let c=!1,u=fd(void 0);return dd(((h,d)=>{let f;if(void 0!==a){if(f=()=>{const r=new ql("Aborted","AbortError"),a=[];i||a.push((()=>"writable"===t._state?tl(t,r):fd(void 0))),n||a.push((()=>"readable"===e._state?up(e,r):fd(void 0))),y((()=>Promise.all(a.map((e=>e())))),!0,r)},a.aborted)return void f();a.addEventListener("abort",f)}if(p(e,s._closedPromise,(e=>{i?b(!0,e):y((()=>tl(t,e)),!0,e)})),p(t,o._closedPromise,(t=>{n?b(!0,t):y((()=>up(e,t)),!0,t)})),function(e,t,r){"closed"===e._state?r():bd(t,r)}(e,s._closedPromise,(()=>{r?b():y((()=>function(e){const t=e._ownerWritableStream,r=t._state;return sl(t)||"closed"===r?fd(void 0):"errored"===r?ld(t._storedError):dl(e)}(o)))})),sl(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");n?b(!0,t):y((()=>up(e,t)),!0,t)}function l(){const e=u;return pd(u,(()=>e!==u?l():void 0))}function p(e,t,r){"errored"===e._state?r(e._storedError):md(t,r)}function y(e,r,i){function n(){yd(e(),(()=>m(r,i)),(e=>m(!0,e)))}c||(c=!0,"writable"!==t._state||sl(t)?n():bd(l(),n))}function b(e,r){c||(c=!0,"writable"!==t._state||sl(t)?m(e,r):bd(l(),(()=>m(e,r))))}function m(e,t){pl(o),Pd(s),void 0!==a&&a.removeEventListener("abort",f),e?d(t):h(void 0)}wd(dd(((e,t)=>{!function r(i){i?e():pd(c?fd(!0):pd(o._readyPromise,(()=>dd(((e,t)=>{ef(s,{_chunkSteps:t=>{u=pd(yl(o,t),void 0,id),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),r,t)}(!1)})))}))}class Ol{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ll(this))throw Yl("desiredSize");return $l(this)}close(){if(!Ll(this))throw Yl("close");if(!Zl(this))throw new TypeError("The stream is not in a state that permits close");Wl(this)}enqueue(e=undefined){if(!Ll(this))throw Yl("enqueue");if(!Zl(this))throw new TypeError("The stream is not in a state that permits enqueue");return Gl(this,e)}error(e=undefined){if(!Ll(this))throw Yl("error");Vl(this,e)}[Id](e){ff(this);const t=this._cancelAlgorithm(e);return Hl(this),t}[Bd](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=hf(this);this._closeRequested&&0===this._queue.length?(Hl(this),hp(t)):Nl(this),e._chunkSteps(r)}else $d(t,e),Nl(this)}}function Ll(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")}function Nl(e){if(!jl(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;yd(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Nl(e))}),(t=>{Vl(e,t)}))}function jl(e){const t=e._controlledReadableStream;if(!Zl(e))return!1;if(!e._started)return!1;if(cp(t)&&Xd(t)>0)return!0;return $l(e)>0}function Hl(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Wl(e){if(!Zl(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Hl(e),hp(t))}function Gl(e,t){if(!Zl(e))return;const r=e._controlledReadableStream;if(cp(r)&&Xd(r)>0)Zd(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Vl(e,t),t}try{df(e,t,r)}catch(t){throw Vl(e,t),t}}Nl(e)}function Vl(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ff(e),Hl(e),dp(r,t))}function $l(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Zl(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Xl(e,t,r,i,n,a,s){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ff(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=s,t._strategyHWM=a,t._pullAlgorithm=i,t._cancelAlgorithm=n,e._readableStreamController=t;yd(fd(r()),(()=>{t._started=!0,Nl(t)}),(e=>{Vl(t,e)}))}function Yl(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Ql(e,t,r){return Fd(e,r),r=>kd(e,t,[r])}function Jl(e,t,r){return Fd(e,r),r=>kd(e,t,[r])}function ep(e,t,r){return Fd(e,r),r=>_d(e,t,[r])}function tp(e,t){if("bytes"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function rp(e,t){if("byob"!==(e=""+e))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function ip(e,t){qd(e,t);const r=null==e?void 0:e.preventAbort,i=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(t+" is not an AbortSignal.")}(a,t+" has member 'signal' that"),{preventAbort:!!r,preventCancel:!!i,preventClose:!!n,signal:a}}Object.defineProperties(Ol.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(Ol.prototype,rd.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class np{constructor(e={},t={}){void 0===e?e=null:Od(e,"First parameter");const r=jf(t,"Second parameter"),i=function(e,t){qd(e,t);const r=e,i=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,s=null==r?void 0:r.start,o=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===i?void 0:Wd(i,t+" has member 'autoAllocateChunkSize' that"),cancel:void 0===n?void 0:Ql(n,r,t+" has member 'cancel' that"),pull:void 0===a?void 0:Jl(a,r,t+" has member 'pull' that"),start:void 0===s?void 0:ep(s,r,t+" has member 'start' that"),type:void 0===o?void 0:tp(o,t+" has member 'type' that")}}(e,"First parameter");if(sp(this),"bytes"===i.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Uf(this,i,Lf(r,0))}else{const e=Nf(r);!function(e,t,r,i){const n=Object.create(Ol.prototype);let a=()=>{},s=()=>fd(void 0),o=()=>fd(void 0);void 0!==t.start&&(a=()=>t.start(n)),void 0!==t.pull&&(s=()=>t.pull(n)),void 0!==t.cancel&&(o=e=>t.cancel(e)),Xl(e,n,a,s,o,r,i)}(this,i,Lf(r,1),e)}}get locked(){if(!op(this))throw fp("locked");return cp(this)}cancel(e=undefined){return op(this)?cp(this)?ld(new TypeError("Cannot cancel a stream that already has a reader")):up(this,e):ld(fp("cancel"))}getReader(e=undefined){if(!op(this))throw fp("getReader");const t=function(e,t){qd(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:rp(r,t+" has member 'mode' that")}}(e,"First parameter");return void 0===t.mode?Vd(this):function(e){return new qf(e)}(this)}pipeThrough(e,t={}){if(!op(this))throw fp("pipeThrough");Ld(e,1,"pipeThrough");const r=function(e,t){qd(e,t);const r=null==e?void 0:e.readable;Nd(r,"readable","ReadableWritablePair"),Gd(r,t+" has member 'readable' that");const i=null==e?void 0:e.writable;return Nd(i,"writable","ReadableWritablePair"),Zf(i,t+" has member 'writable' that"),{readable:r,writable:i}}(e,"First parameter"),i=ip(t,"Second parameter");if(cp(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(el(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return wd(Fl(this,r.writable,i.preventClose,i.preventAbort,i.preventCancel,i.signal)),r.readable}pipeTo(e,t={}){if(!op(this))return ld(fp("pipeTo"));if(void 0===e)return ld("Parameter 1 is required in 'pipeTo'.");if(!Jf(e))return ld(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=ip(t,"Second parameter")}catch(e){return ld(e)}return cp(this)?ld(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):el(e)?ld(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Fl(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!op(this))throw fp("tee");const e=function(e,t){const r=Vd(e);let i,n,a,s,o,c=!1,u=!1,h=!1;const d=dd((e=>{o=e}));function f(){return c||(c=!0,ef(r,{_chunkSteps:e=>{vd((()=>{c=!1;const t=e,r=e;u||Gl(a._readableStreamController,t),h||Gl(s._readableStreamController,r)}))},_closeSteps:()=>{c=!1,u||Wl(a._readableStreamController),h||Wl(s._readableStreamController),u&&h||o(void 0)},_errorSteps:()=>{c=!1}})),fd(void 0)}function l(){}return a=ap(l,f,(function(t){if(u=!0,i=t,h){const t=lf([i,n]),r=up(e,t);o(r)}return d})),s=ap(l,f,(function(t){if(h=!0,n=t,u){const t=lf([i,n]),r=up(e,t);o(r)}return d})),md(r._closedPromise,(e=>{Vl(a._readableStreamController,e),Vl(s._readableStreamController,e),u&&h||o(void 0)})),[a,s]}(this);return lf(e)}values(e=undefined){if(!op(this))throw fp("values");return function(e,t){const r=Vd(e),i=new nf(r,t),n=Object.create(af);return n._asyncIteratorImpl=i,n}(this,function(e,t){return qd(e,t),{preventCancel:!!(null==e?void 0:e.preventCancel)}}(e,"First parameter").preventCancel)}}function ap(e,t,r,i=1,n=(()=>1)){const a=Object.create(np.prototype);sp(a);return Xl(a,Object.create(Ol.prototype),e,t,r,i,n),a}function sp(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function op(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function cp(e){return void 0!==e._reader}function up(e,t){if(e._disturbed=!0,"closed"===e._state)return fd(void 0);if("errored"===e._state)return ld(e._storedError);hp(e);return gd(e._readableStreamController[Id](t),id)}function hp(e){e._state="closed";const t=e._reader;void 0!==t&&(Dd(t),Jd(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new Ad))}function dp(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(Cd(r,t),Jd(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new Ad):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new Ad))}function fp(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function lp(e,t){qd(e,t);const r=null==e?void 0:e.highWaterMark;return Nd(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:jd(r)}}Object.defineProperties(np.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(np.prototype,rd.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof rd.asyncIterator&&Object.defineProperty(np.prototype,rd.asyncIterator,{value:np.prototype.values,writable:!0,configurable:!0});const pp=function(e){return e.byteLength};class yp{constructor(e){Ld(e,1,"ByteLengthQueuingStrategy"),e=lp(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!mp(this))throw bp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!mp(this))throw bp("size");return pp}}function bp(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function mp(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")}Object.defineProperties(yp.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(yp.prototype,rd.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const gp=function(){return 1};class wp{constructor(e){Ld(e,1,"CountQueuingStrategy"),e=lp(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!_p(this))throw vp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!_p(this))throw vp("size");return gp}}function vp(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function _p(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")}function kp(e,t,r){return Fd(e,r),r=>kd(e,t,[r])}function Ap(e,t,r){return Fd(e,r),r=>_d(e,t,[r])}function Sp(e,t,r){return Fd(e,r),(r,i)=>kd(e,t,[r,i])}Object.defineProperties(wp.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(wp.prototype,rd.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class Ep{constructor(e={},t={},r={}){void 0===e&&(e=null);const i=jf(t,"Second parameter"),n=jf(r,"Third parameter"),a=function(e,t){qd(e,t);const r=null==e?void 0:e.flush,i=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,s=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:kp(r,e,t+" has member 'flush' that"),readableType:i,start:void 0===n?void 0:Ap(n,e,t+" has member 'start' that"),transform:void 0===a?void 0:Sp(a,e,t+" has member 'transform' that"),writableType:s}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const s=Lf(n,0),o=Nf(n),c=Lf(i,1),u=Nf(i);let h;!function(e,t,r,i,n,a){function s(){return t}function o(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return gd(e._backpressureChangePromise,(()=>{const i=e._writable;if("erroring"===i._state)throw i._storedError;return Ip(r,t)}))}return Ip(r,t)}(e,t)}function c(t){return function(e,t){return xp(e,t),fd(void 0)}(e,t)}function u(){return function(e){const t=e._readable,r=e._transformStreamController,i=r._flushAlgorithm();return Up(r),gd(i,(()=>{if("errored"===t._state)throw t._storedError;Wl(t._readableStreamController)}),(r=>{throw xp(e,r),t._storedError}))}(e)}function h(){return function(e){return Kp(e,!1),e._backpressureChangePromise}(e)}function d(t){return Mp(e,t),fd(void 0)}e._writable=function(e,t,r,i,n=1,a=(()=>1)){const s=Object.create(Xf.prototype);return Qf(s),gl(s,Object.create(ml.prototype),e,t,r,i,n,a),s}(s,o,u,c,r,i),e._readable=ap(s,h,d,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Kp(e,!0),e._transformStreamController=void 0}(this,dd((e=>{h=e})),c,u,s,o),function(e,t){const r=Object.create(Cp.prototype);let i=e=>{try{return Rp(r,e),fd(void 0)}catch(e){return ld(e)}},n=()=>fd(void 0);void 0!==t.transform&&(i=e=>t.transform(e,r));void 0!==t.flush&&(n=()=>t.flush(r));!function(e,t,r,i){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=i}(e,r,i,n)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!Pp(this))throw Tp("readable");return this._readable}get writable(){if(!Pp(this))throw Tp("writable");return this._writable}}function Pp(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")}function xp(e,t){Vl(e._readable._readableStreamController,t),Mp(e,t)}function Mp(e,t){Up(e._transformStreamController),kl(e._writable._writableStreamController,t),e._backpressure&&Kp(e,!1)}function Kp(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=dd((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(Ep.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(Ep.prototype,rd.toStringTag,{value:"TransformStream",configurable:!0});class Cp{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Dp(this))throw Bp("desiredSize");return $l(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=undefined){if(!Dp(this))throw Bp("enqueue");Rp(this,e)}error(e=undefined){if(!Dp(this))throw Bp("error");var t;t=e,xp(this._controlledTransformStream,t)}terminate(){if(!Dp(this))throw Bp("terminate");!function(e){const t=e._controlledTransformStream,r=t._readable._readableStreamController;Wl(r);Mp(t,new TypeError("TransformStream terminated"))}(this)}}function Dp(e){return!!ad(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")}function Up(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Rp(e,t){const r=e._controlledTransformStream,i=r._readable._readableStreamController;if(!Zl(i))throw new TypeError("Readable side is not in a state that permits enqueue");try{Gl(i,t)}catch(e){throw Mp(r,e),r._readable._storedError}const n=function(e){return!jl(e)}(i);n!==r._backpressure&&Kp(r,!0)}function Ip(e,t){return gd(e._transformAlgorithm(t),void 0,(t=>{throw xp(e._controlledTransformStream,t),t}))}function Bp(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Tp(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(Cp.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof rd.toStringTag&&Object.defineProperty(Cp.prototype,rd.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var zp=/*#__PURE__*/Object.freeze({__proto__:null,ByteLengthQueuingStrategy:yp,CountQueuingStrategy:wp,ReadableByteStreamController:yf,ReadableStream:np,ReadableStreamBYOBReader:qf,ReadableStreamBYOBRequest:pf,ReadableStreamDefaultController:Ol,ReadableStreamDefaultReader:Qd,TransformStream:Ep,TransformStreamDefaultController:Cp,WritableStream:Xf,WritableStreamDefaultController:ml,WritableStreamDefaultWriter:ul}),qp=function(e,t){return qp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},qp(e,t)}; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */function Fp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+t+" is not a constructor or null");function r(){this.constructor=e}qp(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Op(e){if(!e)throw new TypeError("Assertion failed")}function Lp(){}function Np(e){return"object"==typeof e&&null!==e||"function"==typeof e}function jp(e){if("function"!=typeof e)return!1;var t=!1;try{new e({start:function(){t=!0}})}catch(e){}return t}function Hp(e){return!!Np(e)&&"function"==typeof e.getReader}function Wp(e){return!!Np(e)&&"function"==typeof e.getWriter}function Gp(e){return!!Np(e)&&(!!Hp(e.readable)&&!!Wp(e.writable))}function Vp(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}function $p(e,t){var r=(void 0===t?{}:t).type;return Op(Hp(e)),Op(!1===e.locked),"bytes"===(r=Zp(r))?new Jp(e):new Yp(e)}function Zp(e){var t=e+"";if("bytes"===t)return t;if(void 0===e)return e;throw new RangeError("Invalid type is specified")}var Xp=function(){function e(e){this._underlyingReader=void 0,this._readerMode=void 0,this._readableStreamController=void 0,this._pendingRead=void 0,this._underlyingStream=e,this._attachDefaultReader()}return e.prototype.start=function(e){this._readableStreamController=e},e.prototype.cancel=function(e){return Op(void 0!==this._underlyingReader),this._underlyingReader.cancel(e)},e.prototype._attachDefaultReader=function(){if("default"!==this._readerMode){this._detachReader();var e=this._underlyingStream.getReader();this._readerMode="default",this._attachReader(e)}},e.prototype._attachReader=function(e){var t=this;Op(void 0===this._underlyingReader),this._underlyingReader=e;var r=this._underlyingReader.closed;r&&r.then((function(){return t._finishPendingRead()})).then((function(){e===t._underlyingReader&&t._readableStreamController.close()}),(function(r){e===t._underlyingReader&&t._readableStreamController.error(r)})).catch(Lp)},e.prototype._detachReader=function(){void 0!==this._underlyingReader&&(this._underlyingReader.releaseLock(),this._underlyingReader=void 0,this._readerMode=void 0)},e.prototype._pullWithDefaultReader=function(){var e=this;this._attachDefaultReader();var t=this._underlyingReader.read().then((function(t){var r=e._readableStreamController;t.done?e._tryClose():r.enqueue(t.value)}));return this._setPendingRead(t),t},e.prototype._tryClose=function(){try{this._readableStreamController.close()}catch(e){}},e.prototype._setPendingRead=function(e){var t,r=this,i=function(){r._pendingRead===t&&(r._pendingRead=void 0)};this._pendingRead=t=e.then(i,i)},e.prototype._finishPendingRead=function(){var e=this;if(this._pendingRead){var t=function(){return e._finishPendingRead()};return this._pendingRead.then(t,t)}},e}(),Yp=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Fp(t,e),t.prototype.pull=function(){return this._pullWithDefaultReader()},t}(Xp);function Qp(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Jp=function(e){function t(t){var r=this,i=Vp(t);return(r=e.call(this,t)||this)._supportsByob=i,r}return Fp(t,e),Object.defineProperty(t.prototype,"type",{get:function(){return"bytes"},enumerable:!1,configurable:!0}),t.prototype._attachByobReader=function(){if("byob"!==this._readerMode){Op(this._supportsByob),this._detachReader();var e=this._underlyingStream.getReader({mode:"byob"});this._readerMode="byob",this._attachReader(e)}},t.prototype.pull=function(){if(this._supportsByob){var e=this._readableStreamController.byobRequest;if(e)return this._pullWithByobRequest(e)}return this._pullWithDefaultReader()},t.prototype._pullWithByobRequest=function(e){var t=this;this._attachByobReader();var r=new Uint8Array(e.view.byteLength),i=this._underlyingReader.read(r).then((function(r){var i,n,a;t._readableStreamController,r.done?(t._tryClose(),e.respond(0)):(i=r.value,n=e.view,a=Qp(i),Qp(n).set(a,0),e.respond(r.value.byteLength))}));return this._setPendingRead(i),i},t}(Xp);function ey(e){Op(Wp(e)),Op(!1===e.locked);var t=e.getWriter();return new ty(t)}var ty=function(){function e(e){var t=this;this._writableStreamController=void 0,this._pendingWrite=void 0,this._state="writable",this._storedError=void 0,this._underlyingWriter=e,this._errorPromise=new Promise((function(e,r){t._errorPromiseReject=r})),this._errorPromise.catch(Lp)}return e.prototype.start=function(e){var t=this;this._writableStreamController=e,this._underlyingWriter.closed.then((function(){t._state="closed"})).catch((function(e){return t._finishErroring(e)}))},e.prototype.write=function(e){var t=this,r=this._underlyingWriter;if(null===r.desiredSize)return r.ready;var i=r.write(e);i.catch((function(e){return t._finishErroring(e)})),r.ready.catch((function(e){return t._startErroring(e)}));var n=Promise.race([i,this._errorPromise]);return this._setPendingWrite(n),n},e.prototype.close=function(){var e=this;return void 0===this._pendingWrite?this._underlyingWriter.close():this._finishPendingWrite().then((function(){return e.close()}))},e.prototype.abort=function(e){if("errored"!==this._state)return this._underlyingWriter.abort(e)},e.prototype._setPendingWrite=function(e){var t,r=this,i=function(){r._pendingWrite===t&&(r._pendingWrite=void 0)};this._pendingWrite=t=e.then(i,i)},e.prototype._finishPendingWrite=function(){var e=this;if(void 0===this._pendingWrite)return Promise.resolve();var t=function(){return e._finishPendingWrite()};return this._pendingWrite.then(t,t)},e.prototype._startErroring=function(e){var t=this;if("writable"===this._state){this._state="erroring",this._storedError=e;var r=function(){return t._finishErroring(e)};void 0===this._pendingWrite?r():this._finishPendingWrite().then(r,r),this._writableStreamController.error(e)}},e.prototype._finishErroring=function(e){"writable"===this._state&&this._startErroring(e),"erroring"===this._state&&(this._state="errored",this._errorPromiseReject(this._storedError))},e}();function ry(e){Op(Gp(e));var t=e.readable,r=e.writable;Op(!1===t.locked),Op(!1===r.locked);var i,n=t.getReader();try{i=r.getWriter()}catch(e){throw n.releaseLock(),e}return new iy(n,i)}var iy=function(){function e(e,t){var r=this;this._transformStreamController=void 0,this._onRead=function(e){if(!e.done)return r._transformStreamController.enqueue(e.value),r._reader.read().then(r._onRead)},this._onError=function(e){r._flushReject(e),r._transformStreamController.error(e),r._reader.cancel(e).catch(Lp),r._writer.abort(e).catch(Lp)},this._onTerminate=function(){r._flushResolve(),r._transformStreamController.terminate();var e=new TypeError("TransformStream terminated");r._writer.abort(e).catch(Lp)},this._reader=e,this._writer=t,this._flushPromise=new Promise((function(e,t){r._flushResolve=e,r._flushReject=t}))}return e.prototype.start=function(e){this._transformStreamController=e,this._reader.read().then(this._onRead).then(this._onTerminate,this._onError);var t=this._reader.closed;t&&t.then(this._onTerminate,this._onError)},e.prototype.transform=function(e){return this._writer.write(e)},e.prototype.flush=function(){var e=this;return this._writer.close().then((function(){return e._flushPromise}))},e}(),ny=/*#__PURE__*/Object.freeze({__proto__:null,createReadableStreamWrapper:function(e){Op(function(e){return!!jp(e)&&!!Hp(new e)}(e));var t=function(e){try{return new e({type:"bytes"}),!0}catch(e){return!1}}(e);return function(r,i){var n=(void 0===i?{}:i).type;if("bytes"!==(n=Zp(n))||t||(n=void 0),r.constructor===e&&("bytes"!==n||Vp(r)))return r;if("bytes"===n){var a=$p(r,{type:n});return new e(a)}a=$p(r);return new e(a)}},createTransformStreamWrapper:function(e){return Op(function(e){return!!jp(e)&&!!Gp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=ry(t);return new e(r)}},createWrappingReadableSource:$p,createWrappingTransformer:ry,createWrappingWritableSink:ey,createWritableStreamWrapper:function(e){return Op(function(e){return!!jp(e)&&!!Wp(new e)}(e)),function(t){if(t.constructor===e)return t;var r=ey(t);return new e(r)}}}),ay=it((function(e){!function(e,t){function r(e,t){if(!e)throw Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function n(e,t,r){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof e?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;try{a=void 0}catch(e){}function s(e,t,r){for(var i=0,n=Math.min(e.length,r),a=t;a=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return i}function o(e,t,r,i){for(var n=0,a=Math.min(e.length,r),s=t;s=49?o-49+10:o>=17?o-17+10:o}return n}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return e.cmp(t)<0?e:t},n.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var n=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&n++,16===t?this._parseHex(e,n):this._parseBase(e,t,n),"-"===e[0]&&(this.negative=1),this.strip(),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initNumber=function(e,t,i){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===i&&this._initArray(this.toArray(),t,i)},n.prototype._initArray=function(e,t,i){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var n=0;n=0;n-=3)s=e[n]|e[n-1]<<8|e[n-2]<<16,this.words[a]|=s<>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);else if("le"===i)for(n=0,a=0;n>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);return this.strip()},n.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var r=0;r=t;r-=6)n=s(e,r,r+6),this.words[i]|=n<>>26-a&4194303,(a+=24)>=26&&(a-=26,i++);r+6!==t&&(n=s(e,t,r+6),this.words[i]|=n<>>26-a&4194303),this.strip()},n.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,n=1;n<=67108863;n*=t)i++;i--,n=n/t|0;for(var a=e.length-r,s=a%i,c=Math.min(a,a-s)+r,u=0,h=r;h1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var n=0|e.words[0],a=0|t.words[0],s=n*a,o=67108863&s,c=s/67108864|0;r.words[0]=o;for(var u=1;u>>26,d=67108863&c,f=Math.min(u,t.length-1),l=Math.max(0,u-e.length+1);l<=f;l++){var p=u-l|0;h+=(s=(n=0|e.words[p])*(a=0|t.words[l])+d)/67108864|0,d=67108863&s}r.words[u]=0|d,c=0|h}return 0!==c?r.words[u]=0|c:r.length--,r.strip()}n.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var n=0,a=0,s=0;s>>24-n&16777215)||s!==this.length-1?c[6-d.length]+d+i:d+i,(n+=2)>=26&&(n-=26,s--)}for(0!==a&&(i=a.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var f=u[e],l=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var y=p.modn(l).toString(e);i=(p=p.idivn(l)).isZero()?y+i:c[f-y.length]+y+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return r(void 0!==a),this.toArrayLike(a,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,i){var n=this.byteLength(),a=i||Math.max(1,n);r(n<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var s,o,c="le"===t,u=new e(a),h=this.clone();if(c){for(o=0;!h.isZero();o++)s=h.andln(255),h.iushrn(8),u[o]=s;for(;o=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var n=0;n0&&(this.words[n]=~this.words[n]&67108863>>26-i),this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var i=e/26|0,n=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(r=this,i=e):(r=e,i=this);for(var n=0,a=0;a>>26;for(;0!==n&&a>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;ae.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,i,n=this.cmp(e);if(0===n)return this.negative=0,this.length=1,this.words[0]=0,this;n>0?(r=this,i=e):(r=e,i=this);for(var a=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==a&&s>26,this.words[s]=67108863&t;if(0===a&&s>>13,l=0|s[1],p=8191&l,y=l>>>13,b=0|s[2],m=8191&b,g=b>>>13,w=0|s[3],v=8191&w,_=w>>>13,k=0|s[4],A=8191&k,S=k>>>13,E=0|s[5],P=8191&E,x=E>>>13,M=0|s[6],K=8191&M,C=M>>>13,D=0|s[7],U=8191&D,R=D>>>13,I=0|s[8],B=8191&I,T=I>>>13,z=0|s[9],q=8191&z,F=z>>>13,O=0|o[0],L=8191&O,N=O>>>13,j=0|o[1],H=8191&j,W=j>>>13,G=0|o[2],V=8191&G,$=G>>>13,Z=0|o[3],X=8191&Z,Y=Z>>>13,Q=0|o[4],J=8191&Q,ee=Q>>>13,te=0|o[5],re=8191&te,ie=te>>>13,ne=0|o[6],ae=8191&ne,se=ne>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,he=0|o[8],de=8191&he,fe=he>>>13,le=0|o[9],pe=8191&le,ye=le>>>13;r.negative=e.negative^t.negative,r.length=19;var be=(u+(i=Math.imul(d,L))|0)+((8191&(n=(n=Math.imul(d,N))+Math.imul(f,L)|0))<<13)|0;u=((a=Math.imul(f,N))+(n>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(p,L),n=(n=Math.imul(p,N))+Math.imul(y,L)|0,a=Math.imul(y,N);var me=(u+(i=i+Math.imul(d,H)|0)|0)+((8191&(n=(n=n+Math.imul(d,W)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,W)|0)+(n>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(m,L),n=(n=Math.imul(m,N))+Math.imul(g,L)|0,a=Math.imul(g,N),i=i+Math.imul(p,H)|0,n=(n=n+Math.imul(p,W)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,W)|0;var ge=(u+(i=i+Math.imul(d,V)|0)|0)+((8191&(n=(n=n+Math.imul(d,$)|0)+Math.imul(f,V)|0))<<13)|0;u=((a=a+Math.imul(f,$)|0)+(n>>>13)|0)+(ge>>>26)|0,ge&=67108863,i=Math.imul(v,L),n=(n=Math.imul(v,N))+Math.imul(_,L)|0,a=Math.imul(_,N),i=i+Math.imul(m,H)|0,n=(n=n+Math.imul(m,W)|0)+Math.imul(g,H)|0,a=a+Math.imul(g,W)|0,i=i+Math.imul(p,V)|0,n=(n=n+Math.imul(p,$)|0)+Math.imul(y,V)|0,a=a+Math.imul(y,$)|0;var we=(u+(i=i+Math.imul(d,X)|0)|0)+((8191&(n=(n=n+Math.imul(d,Y)|0)+Math.imul(f,X)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(n>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(A,L),n=(n=Math.imul(A,N))+Math.imul(S,L)|0,a=Math.imul(S,N),i=i+Math.imul(v,H)|0,n=(n=n+Math.imul(v,W)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,W)|0,i=i+Math.imul(m,V)|0,n=(n=n+Math.imul(m,$)|0)+Math.imul(g,V)|0,a=a+Math.imul(g,$)|0,i=i+Math.imul(p,X)|0,n=(n=n+Math.imul(p,Y)|0)+Math.imul(y,X)|0,a=a+Math.imul(y,Y)|0;var ve=(u+(i=i+Math.imul(d,J)|0)|0)+((8191&(n=(n=n+Math.imul(d,ee)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,ee)|0)+(n>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(P,L),n=(n=Math.imul(P,N))+Math.imul(x,L)|0,a=Math.imul(x,N),i=i+Math.imul(A,H)|0,n=(n=n+Math.imul(A,W)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,W)|0,i=i+Math.imul(v,V)|0,n=(n=n+Math.imul(v,$)|0)+Math.imul(_,V)|0,a=a+Math.imul(_,$)|0,i=i+Math.imul(m,X)|0,n=(n=n+Math.imul(m,Y)|0)+Math.imul(g,X)|0,a=a+Math.imul(g,Y)|0,i=i+Math.imul(p,J)|0,n=(n=n+Math.imul(p,ee)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,ee)|0;var _e=(u+(i=i+Math.imul(d,re)|0)|0)+((8191&(n=(n=n+Math.imul(d,ie)|0)+Math.imul(f,re)|0))<<13)|0;u=((a=a+Math.imul(f,ie)|0)+(n>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(K,L),n=(n=Math.imul(K,N))+Math.imul(C,L)|0,a=Math.imul(C,N),i=i+Math.imul(P,H)|0,n=(n=n+Math.imul(P,W)|0)+Math.imul(x,H)|0,a=a+Math.imul(x,W)|0,i=i+Math.imul(A,V)|0,n=(n=n+Math.imul(A,$)|0)+Math.imul(S,V)|0,a=a+Math.imul(S,$)|0,i=i+Math.imul(v,X)|0,n=(n=n+Math.imul(v,Y)|0)+Math.imul(_,X)|0,a=a+Math.imul(_,Y)|0,i=i+Math.imul(m,J)|0,n=(n=n+Math.imul(m,ee)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,ee)|0,i=i+Math.imul(p,re)|0,n=(n=n+Math.imul(p,ie)|0)+Math.imul(y,re)|0,a=a+Math.imul(y,ie)|0;var ke=(u+(i=i+Math.imul(d,ae)|0)|0)+((8191&(n=(n=n+Math.imul(d,se)|0)+Math.imul(f,ae)|0))<<13)|0;u=((a=a+Math.imul(f,se)|0)+(n>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(U,L),n=(n=Math.imul(U,N))+Math.imul(R,L)|0,a=Math.imul(R,N),i=i+Math.imul(K,H)|0,n=(n=n+Math.imul(K,W)|0)+Math.imul(C,H)|0,a=a+Math.imul(C,W)|0,i=i+Math.imul(P,V)|0,n=(n=n+Math.imul(P,$)|0)+Math.imul(x,V)|0,a=a+Math.imul(x,$)|0,i=i+Math.imul(A,X)|0,n=(n=n+Math.imul(A,Y)|0)+Math.imul(S,X)|0,a=a+Math.imul(S,Y)|0,i=i+Math.imul(v,J)|0,n=(n=n+Math.imul(v,ee)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,ee)|0,i=i+Math.imul(m,re)|0,n=(n=n+Math.imul(m,ie)|0)+Math.imul(g,re)|0,a=a+Math.imul(g,ie)|0,i=i+Math.imul(p,ae)|0,n=(n=n+Math.imul(p,se)|0)+Math.imul(y,ae)|0,a=a+Math.imul(y,se)|0;var Ae=(u+(i=i+Math.imul(d,ce)|0)|0)+((8191&(n=(n=n+Math.imul(d,ue)|0)+Math.imul(f,ce)|0))<<13)|0;u=((a=a+Math.imul(f,ue)|0)+(n>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(B,L),n=(n=Math.imul(B,N))+Math.imul(T,L)|0,a=Math.imul(T,N),i=i+Math.imul(U,H)|0,n=(n=n+Math.imul(U,W)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,W)|0,i=i+Math.imul(K,V)|0,n=(n=n+Math.imul(K,$)|0)+Math.imul(C,V)|0,a=a+Math.imul(C,$)|0,i=i+Math.imul(P,X)|0,n=(n=n+Math.imul(P,Y)|0)+Math.imul(x,X)|0,a=a+Math.imul(x,Y)|0,i=i+Math.imul(A,J)|0,n=(n=n+Math.imul(A,ee)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,ee)|0,i=i+Math.imul(v,re)|0,n=(n=n+Math.imul(v,ie)|0)+Math.imul(_,re)|0,a=a+Math.imul(_,ie)|0,i=i+Math.imul(m,ae)|0,n=(n=n+Math.imul(m,se)|0)+Math.imul(g,ae)|0,a=a+Math.imul(g,se)|0,i=i+Math.imul(p,ce)|0,n=(n=n+Math.imul(p,ue)|0)+Math.imul(y,ce)|0,a=a+Math.imul(y,ue)|0;var Se=(u+(i=i+Math.imul(d,de)|0)|0)+((8191&(n=(n=n+Math.imul(d,fe)|0)+Math.imul(f,de)|0))<<13)|0;u=((a=a+Math.imul(f,fe)|0)+(n>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(q,L),n=(n=Math.imul(q,N))+Math.imul(F,L)|0,a=Math.imul(F,N),i=i+Math.imul(B,H)|0,n=(n=n+Math.imul(B,W)|0)+Math.imul(T,H)|0,a=a+Math.imul(T,W)|0,i=i+Math.imul(U,V)|0,n=(n=n+Math.imul(U,$)|0)+Math.imul(R,V)|0,a=a+Math.imul(R,$)|0,i=i+Math.imul(K,X)|0,n=(n=n+Math.imul(K,Y)|0)+Math.imul(C,X)|0,a=a+Math.imul(C,Y)|0,i=i+Math.imul(P,J)|0,n=(n=n+Math.imul(P,ee)|0)+Math.imul(x,J)|0,a=a+Math.imul(x,ee)|0,i=i+Math.imul(A,re)|0,n=(n=n+Math.imul(A,ie)|0)+Math.imul(S,re)|0,a=a+Math.imul(S,ie)|0,i=i+Math.imul(v,ae)|0,n=(n=n+Math.imul(v,se)|0)+Math.imul(_,ae)|0,a=a+Math.imul(_,se)|0,i=i+Math.imul(m,ce)|0,n=(n=n+Math.imul(m,ue)|0)+Math.imul(g,ce)|0,a=a+Math.imul(g,ue)|0,i=i+Math.imul(p,de)|0,n=(n=n+Math.imul(p,fe)|0)+Math.imul(y,de)|0,a=a+Math.imul(y,fe)|0;var Ee=(u+(i=i+Math.imul(d,pe)|0)|0)+((8191&(n=(n=n+Math.imul(d,ye)|0)+Math.imul(f,pe)|0))<<13)|0;u=((a=a+Math.imul(f,ye)|0)+(n>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(q,H),n=(n=Math.imul(q,W))+Math.imul(F,H)|0,a=Math.imul(F,W),i=i+Math.imul(B,V)|0,n=(n=n+Math.imul(B,$)|0)+Math.imul(T,V)|0,a=a+Math.imul(T,$)|0,i=i+Math.imul(U,X)|0,n=(n=n+Math.imul(U,Y)|0)+Math.imul(R,X)|0,a=a+Math.imul(R,Y)|0,i=i+Math.imul(K,J)|0,n=(n=n+Math.imul(K,ee)|0)+Math.imul(C,J)|0,a=a+Math.imul(C,ee)|0,i=i+Math.imul(P,re)|0,n=(n=n+Math.imul(P,ie)|0)+Math.imul(x,re)|0,a=a+Math.imul(x,ie)|0,i=i+Math.imul(A,ae)|0,n=(n=n+Math.imul(A,se)|0)+Math.imul(S,ae)|0,a=a+Math.imul(S,se)|0,i=i+Math.imul(v,ce)|0,n=(n=n+Math.imul(v,ue)|0)+Math.imul(_,ce)|0,a=a+Math.imul(_,ue)|0,i=i+Math.imul(m,de)|0,n=(n=n+Math.imul(m,fe)|0)+Math.imul(g,de)|0,a=a+Math.imul(g,fe)|0;var Pe=(u+(i=i+Math.imul(p,pe)|0)|0)+((8191&(n=(n=n+Math.imul(p,ye)|0)+Math.imul(y,pe)|0))<<13)|0;u=((a=a+Math.imul(y,ye)|0)+(n>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(q,V),n=(n=Math.imul(q,$))+Math.imul(F,V)|0,a=Math.imul(F,$),i=i+Math.imul(B,X)|0,n=(n=n+Math.imul(B,Y)|0)+Math.imul(T,X)|0,a=a+Math.imul(T,Y)|0,i=i+Math.imul(U,J)|0,n=(n=n+Math.imul(U,ee)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,ee)|0,i=i+Math.imul(K,re)|0,n=(n=n+Math.imul(K,ie)|0)+Math.imul(C,re)|0,a=a+Math.imul(C,ie)|0,i=i+Math.imul(P,ae)|0,n=(n=n+Math.imul(P,se)|0)+Math.imul(x,ae)|0,a=a+Math.imul(x,se)|0,i=i+Math.imul(A,ce)|0,n=(n=n+Math.imul(A,ue)|0)+Math.imul(S,ce)|0,a=a+Math.imul(S,ue)|0,i=i+Math.imul(v,de)|0,n=(n=n+Math.imul(v,fe)|0)+Math.imul(_,de)|0,a=a+Math.imul(_,fe)|0;var xe=(u+(i=i+Math.imul(m,pe)|0)|0)+((8191&(n=(n=n+Math.imul(m,ye)|0)+Math.imul(g,pe)|0))<<13)|0;u=((a=a+Math.imul(g,ye)|0)+(n>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(q,X),n=(n=Math.imul(q,Y))+Math.imul(F,X)|0,a=Math.imul(F,Y),i=i+Math.imul(B,J)|0,n=(n=n+Math.imul(B,ee)|0)+Math.imul(T,J)|0,a=a+Math.imul(T,ee)|0,i=i+Math.imul(U,re)|0,n=(n=n+Math.imul(U,ie)|0)+Math.imul(R,re)|0,a=a+Math.imul(R,ie)|0,i=i+Math.imul(K,ae)|0,n=(n=n+Math.imul(K,se)|0)+Math.imul(C,ae)|0,a=a+Math.imul(C,se)|0,i=i+Math.imul(P,ce)|0,n=(n=n+Math.imul(P,ue)|0)+Math.imul(x,ce)|0,a=a+Math.imul(x,ue)|0,i=i+Math.imul(A,de)|0,n=(n=n+Math.imul(A,fe)|0)+Math.imul(S,de)|0,a=a+Math.imul(S,fe)|0;var Me=(u+(i=i+Math.imul(v,pe)|0)|0)+((8191&(n=(n=n+Math.imul(v,ye)|0)+Math.imul(_,pe)|0))<<13)|0;u=((a=a+Math.imul(_,ye)|0)+(n>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(q,J),n=(n=Math.imul(q,ee))+Math.imul(F,J)|0,a=Math.imul(F,ee),i=i+Math.imul(B,re)|0,n=(n=n+Math.imul(B,ie)|0)+Math.imul(T,re)|0,a=a+Math.imul(T,ie)|0,i=i+Math.imul(U,ae)|0,n=(n=n+Math.imul(U,se)|0)+Math.imul(R,ae)|0,a=a+Math.imul(R,se)|0,i=i+Math.imul(K,ce)|0,n=(n=n+Math.imul(K,ue)|0)+Math.imul(C,ce)|0,a=a+Math.imul(C,ue)|0,i=i+Math.imul(P,de)|0,n=(n=n+Math.imul(P,fe)|0)+Math.imul(x,de)|0,a=a+Math.imul(x,fe)|0;var Ke=(u+(i=i+Math.imul(A,pe)|0)|0)+((8191&(n=(n=n+Math.imul(A,ye)|0)+Math.imul(S,pe)|0))<<13)|0;u=((a=a+Math.imul(S,ye)|0)+(n>>>13)|0)+(Ke>>>26)|0,Ke&=67108863,i=Math.imul(q,re),n=(n=Math.imul(q,ie))+Math.imul(F,re)|0,a=Math.imul(F,ie),i=i+Math.imul(B,ae)|0,n=(n=n+Math.imul(B,se)|0)+Math.imul(T,ae)|0,a=a+Math.imul(T,se)|0,i=i+Math.imul(U,ce)|0,n=(n=n+Math.imul(U,ue)|0)+Math.imul(R,ce)|0,a=a+Math.imul(R,ue)|0,i=i+Math.imul(K,de)|0,n=(n=n+Math.imul(K,fe)|0)+Math.imul(C,de)|0,a=a+Math.imul(C,fe)|0;var Ce=(u+(i=i+Math.imul(P,pe)|0)|0)+((8191&(n=(n=n+Math.imul(P,ye)|0)+Math.imul(x,pe)|0))<<13)|0;u=((a=a+Math.imul(x,ye)|0)+(n>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(q,ae),n=(n=Math.imul(q,se))+Math.imul(F,ae)|0,a=Math.imul(F,se),i=i+Math.imul(B,ce)|0,n=(n=n+Math.imul(B,ue)|0)+Math.imul(T,ce)|0,a=a+Math.imul(T,ue)|0,i=i+Math.imul(U,de)|0,n=(n=n+Math.imul(U,fe)|0)+Math.imul(R,de)|0,a=a+Math.imul(R,fe)|0;var De=(u+(i=i+Math.imul(K,pe)|0)|0)+((8191&(n=(n=n+Math.imul(K,ye)|0)+Math.imul(C,pe)|0))<<13)|0;u=((a=a+Math.imul(C,ye)|0)+(n>>>13)|0)+(De>>>26)|0,De&=67108863,i=Math.imul(q,ce),n=(n=Math.imul(q,ue))+Math.imul(F,ce)|0,a=Math.imul(F,ue),i=i+Math.imul(B,de)|0,n=(n=n+Math.imul(B,fe)|0)+Math.imul(T,de)|0,a=a+Math.imul(T,fe)|0;var Ue=(u+(i=i+Math.imul(U,pe)|0)|0)+((8191&(n=(n=n+Math.imul(U,ye)|0)+Math.imul(R,pe)|0))<<13)|0;u=((a=a+Math.imul(R,ye)|0)+(n>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,i=Math.imul(q,de),n=(n=Math.imul(q,fe))+Math.imul(F,de)|0,a=Math.imul(F,fe);var Re=(u+(i=i+Math.imul(B,pe)|0)|0)+((8191&(n=(n=n+Math.imul(B,ye)|0)+Math.imul(T,pe)|0))<<13)|0;u=((a=a+Math.imul(T,ye)|0)+(n>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Ie=(u+(i=Math.imul(q,pe))|0)+((8191&(n=(n=Math.imul(q,ye))+Math.imul(F,pe)|0))<<13)|0;return u=((a=Math.imul(F,ye))+(n>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,c[0]=be,c[1]=me,c[2]=ge,c[3]=we,c[4]=ve,c[5]=_e,c[6]=ke,c[7]=Ae,c[8]=Se,c[9]=Ee,c[10]=Pe,c[11]=xe,c[12]=Me,c[13]=Ke,c[14]=Ce,c[15]=De,c[16]=Ue,c[17]=Re,c[18]=Ie,0!==u&&(c[19]=u,r.length++),r};function l(e,t,r){return(new p).mulp(e,t,r)}function p(e,t){this.x=e,this.y=t}Math.imul||(f=d),n.prototype.mulTo=function(e,t){var r,i=this.length+e.length;return r=10===this.length&&10===e.length?f(this,e,t):i<63?d(this,e,t):i<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,n=0,a=0;a>>26)|0)>>>26,s&=67108863}r.words[a]=o,i=s,s=n}return 0!==i?r.words[a]=i:r.length--,r.strip()}(this,e,t):l(this,e,t),r},p.prototype.makeRBT=function(e){for(var t=Array(e),r=n.prototype._countBits(e)-1,i=0;i>=1;return i},p.prototype.permute=function(e,t,r,i,n,a){for(var s=0;s>>=1)n++;return 1<>>=13,i[2*s+1]=8191&a,a>>>=13;for(s=2*t;s>=26,t+=n/67108864|0,t+=a>>>26,this.words[i]=67108863&a}return 0!==t&&(this.words[i]=t,this.length++),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r>>n}return t}(e);if(0===t.length)return new n(1);for(var r=this,i=0;i=0);var t,i=e%26,n=(e-i)/26,a=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==n){for(t=this.length-1;t>=0;t--)this.words[t+n]=this.words[t];for(t=0;t=0),n=t?(t-t%26)/26:0;var a=e%26,s=Math.min((e-a)/26,this.length),o=67108863^67108863>>>a<s)for(this.length-=s,u=0;u=0&&(0!==h||u>=n);u--){var d=0|this.words[u];this.words[u]=h<<26-a|d>>>a,h=d&o}return c&&0!==h&&(c.words[c.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,i){return r(0===this.negative),this.iushrn(e,t,i)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,n=1<=0);var t=e%26,i=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var n=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[n+i]=67108863&a}for(;n>26,this.words[n+i]=67108863&a;if(0===o)return this.strip();for(r(-1===o),o=0,n=0;n>26,this.words[n]=67108863&a;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var r=(this.length,e.length),i=this.clone(),a=e,s=0|a.words[a.length-1];0!==(r=26-this._countBits(s))&&(a=a.ushln(r),i.iushln(r),s=0|a.words[a.length-1]);var o,c=i.length-a.length;if("mod"!==t){(o=new n(null)).length=c+1,o.words=Array(o.length);for(var u=0;u=0;d--){var f=67108864*(0|i.words[a.length+d])+(0|i.words[a.length+d-1]);for(f=Math.min(f/s|0,67108863),i._ishlnsubmul(a,f,d);0!==i.negative;)f--,i.negative=0,i._ishlnsubmul(a,1,d),i.isZero()||(i.negative^=1);o&&(o.words[d]=f)}return o&&o.strip(),i.strip(),"div"!==t&&0!==r&&i.iushrn(r),{div:o||null,mod:i}},n.prototype.divmod=function(e,t,i){return r(!e.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(a=o.div.neg()),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:a,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(a=o.div.neg()),{div:a,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t);var a,s,o},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),n=e.andln(1),a=r.cmp(i);return a<0||1===n&&0===a?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},n.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,i=0,n=this.length-1;n>=0;n--)i=(t*i+(0|this.words[n]))%e;return i},n.prototype.idivn=function(e){r(e<=67108863);for(var t=0,i=this.length-1;i>=0;i--){var n=(0|this.words[i])+67108864*t;this.words[i]=n/e|0,t=n%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new n(1),s=new n(0),o=new n(0),c=new n(1),u=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++u;for(var h=i.clone(),d=t.clone();!t.isZero();){for(var f=0,l=1;0==(t.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(t.iushrn(f);f-- >0;)(a.isOdd()||s.isOdd())&&(a.iadd(h),s.isub(d)),a.iushrn(1),s.iushrn(1);for(var p=0,y=1;0==(i.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(h),c.isub(d)),o.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),a.isub(o),s.isub(c)):(i.isub(t),o.isub(a),c.isub(s))}return{a:o,b:c,gcd:i.iushln(u)}},n.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a,s=new n(1),o=new n(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var u=0,h=1;0==(t.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,f=1;0==(i.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(i.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(o)):(i.isub(t),o.isub(s))}return(a=0===t.cmpn(1)?s:o).cmpn(0)<0&&a.iadd(e),a},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var n=t.cmp(r);if(n<0){var a=t;t=r,r=a}else if(0===n||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,i=(e-t)/26,n=1<>>26,o&=67108863,this.words[s]=o}return 0!==a&&(this.words[s]=a,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this.strip(),this.length>1)t=1;else{i&&(e=-e),r(e<=67108863,"Number is too big");var n=0|this.words[0];t=n===e?0:ne.length)return 1;if(this.length=0;r--){var i=0|this.words[r],n=0|e.words[r];if(i!==n){in&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return-1===this.cmpn(e)},n.prototype.lt=function(e){return-1===this.cmp(e)},n.prototype.lten=function(e){return this.cmpn(e)<=0},n.prototype.lte=function(e){return this.cmp(e)<=0},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new _(e)},n.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function v(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function k(e){_.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}b.prototype._tmp=function(){var e=new n(null);return e.words=Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?r.isub(this.p):r.strip(),r},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},i(m,b),m.prototype.split=function(e,t){for(var r=4194303,i=Math.min(e.length,9),n=0;n>>22,a=s}a>>>=22,e.words[n-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},m.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=n,t=i}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new m;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw Error("Unknown prime "+e);t=new v}return y[e]=t,t},_.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},_.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},_.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},_.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},_.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},_.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},_.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},_.prototype.isqr=function(e){return this.imul(e,e.clone())},_.prototype.sqr=function(e){return this.mul(e,e)},_.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var i=this.m.add(new n(1)).iushrn(2);return this.pow(e,i)}for(var a=this.m.subn(1),s=0;!a.isZero()&&0===a.andln(1);)s++,a.iushrn(1);r(!a.isZero());var o=new n(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),h=this.m.bitLength();for(h=new n(2*h*h).toRed(this);0!==this.pow(h,u).cmp(c);)h.redIAdd(c);for(var d=this.pow(h,a),f=this.pow(e,a.addn(1).iushrn(1)),l=this.pow(e,a),p=s;0!==l.cmp(o);){for(var y=l,b=0;0!==y.cmp(o);b++)y=y.redSqr();r(b=0;i--){for(var u=t.words[i],h=c-1;h>=0;h--){var d=u>>h&1;a!==r[0]&&(a=this.sqr(a)),0!==d||0!==s?(s<<=1,s|=d,(4===++o||0===i&&0===h)&&(a=this.mul(a,r[s]),o=0,s=0)):o=0}c=26}return a},_.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},_.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new k(e)},i(k,_),k.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},k.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},k.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):n.cmpn(0)<0&&(a=n.iadd(this.m)),a._forceRed(this)},k.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),s=a;return a.cmp(this.m)>=0?s=a.isub(this.m):a.cmpn(0)<0&&(s=a.iadd(this.m)),s._forceRed(this)},k.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,rt)})),sy=/*#__PURE__*/Object.freeze({__proto__:null,default:ay,__moduleExports:ay});class oy{constructor(e){if(void 0===e)throw Error("Invalid BigInteger input");this.value=new ay(e)}clone(){const e=new oy(null);return this.value.copy(e.value),e}iinc(){return this.value.iadd(new ay(1)),this}inc(){return this.clone().iinc()}idec(){return this.value.isub(new ay(1)),this}dec(){return this.clone().idec()}iadd(e){return this.value.iadd(e.value),this}add(e){return this.clone().iadd(e)}isub(e){return this.value.isub(e.value),this}sub(e){return this.clone().isub(e)}imul(e){return this.value.imul(e.value),this}mul(e){return this.clone().imul(e)}imod(e){return this.value=this.value.umod(e.value),this}mod(e){return this.clone().imod(e)}modExp(e,t){const r=t.isEven()?ay.red(t.value):ay.mont(t.value),i=this.clone();return i.value=i.value.toRed(r).redPow(e.value).fromRed(),i}modInv(e){if(!this.gcd(e).isOne())throw Error("Inverse does not exist");return new oy(this.value.invm(e.value))}gcd(e){return new oy(this.value.gcd(e.value))}ileftShift(e){return this.value.ishln(e.value.toNumber()),this}leftShift(e){return this.clone().ileftShift(e)}irightShift(e){return this.value.ishrn(e.value.toNumber()),this}rightShift(e){return this.clone().irightShift(e)}equal(e){return this.value.eq(e.value)}lt(e){return this.value.lt(e.value)}lte(e){return this.value.lte(e.value)}gt(e){return this.value.gt(e.value)}gte(e){return this.value.gte(e.value)}isZero(){return this.value.isZero()}isOne(){return this.value.eq(new ay(1))}isNegative(){return this.value.isNeg()}isEven(){return this.value.isEven()}abs(){const e=this.clone();return e.value=e.value.abs(),e}toString(){return this.value.toString()}toNumber(){return this.value.toNumber()}getBit(e){return this.value.testn(e)?1:0}bitLength(){return this.value.bitLength()}byteLength(){return this.value.byteLength()}toUint8Array(e="be",t){return this.value.toArrayLike(Uint8Array,e,t)}}var cy,uy=/*#__PURE__*/Object.freeze({__proto__:null,default:oy}),hy=it((function(e,t){var r=t;function i(e){return 1===e.length?"0"+e:e}function n(e){for(var t="",r=0;r>8,s=255&n;a?r.push(a,s):r.push(s)}return r},r.zero2=i,r.toHex=n,r.encode=function(e,t){return"hex"===t?n(e):e}})),dy=it((function(e,t){var r=t;r.assert=et,r.toArray=hy.toArray,r.zero2=hy.zero2,r.toHex=hy.toHex,r.encode=hy.encode,r.getNAF=function(e,t){for(var r=[],i=1<=0;){var a;if(n.isOdd()){var s=n.andln(i-1);a=s>(i>>1)-1?(i>>1)-s:s,n.isubn(a)}else a=0;r.push(a);for(var o=0!==n.cmpn(0)&&0===n.andln(i-1)?t+1:1,c=1;c0||t.cmpn(-n)>0;){var a,s,o,c=e.andln(3)+i&3,u=t.andln(3)+n&3;if(3===c&&(c=-1),3===u&&(u=-1),0==(1&c))a=0;else a=3!==(o=e.andln(7)+i&7)&&5!==o||2!==u?c:-c;if(r[0].push(a),0==(1&u))s=0;else s=3!==(o=t.andln(7)+n&7)&&5!==o||2!==c?u:-u;r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r},r.cachedProperty=function(e,t,r){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new ay(e,"hex","le")}})),fy=function(e){return cy||(cy=new ly(null)),cy.generate(e)};function ly(e){this.rand=e}var py=ly;if(ly.prototype.generate=function(e){return this._rand(e)},ly.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var vy=wy;function _y(e,t){this.curve=e,this.type=t,this.precomputed=null}wy.prototype.point=function(){throw Error("Not implemented")},wy.prototype.validate=function(){throw Error("Not implemented")},wy.prototype._fixedNafMul=function(e,t){gy(e.precomputed);var r=e._getDoubles(),i=by(t,1),n=(1<=s;t--)o=(o<<1)+i[t];a.push(o)}for(var c=this.jpoint(null,null,null),u=this.jpoint(null,null,null),h=n;h>0;h--){for(s=0;s=0;o--){for(t=0;o>=0&&0===a[o];o--)t++;if(o>=0&&t++,s=s.dblp(t),o<0)break;var c=a[o];gy(0!==c),s="affine"===e.type?c>0?s.mixedAdd(n[c-1>>1]):s.mixedAdd(n[-c-1>>1].neg()):c>0?s.add(n[c-1>>1]):s.add(n[-c-1>>1].neg())}return"affine"===e.type?s.toP():s},wy.prototype._wnafMulAdd=function(e,t,r,i,n){for(var a=this._wnafT1,s=this._wnafT2,o=this._wnafT3,c=0,u=0;u=1;u-=2){var d=u-1,f=u;if(1===a[d]&&1===a[f]){var l=[t[d],null,null,t[f]];0===t[d].y.cmp(t[f].y)?(l[1]=t[d].add(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg())):0===t[d].y.cmp(t[f].y.redNeg())?(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].add(t[f].neg())):(l[1]=t[d].toJ().mixedAdd(t[f]),l[2]=t[d].toJ().mixedAdd(t[f].neg()));var p=[-3,-1,-5,-7,0,7,5,1,3],y=my(r[d],r[f]);c=Math.max(y[0].length,c),o[d]=Array(c),o[f]=Array(c);for(var b=0;b=0;u--){for(var _=0;u>=0;){var k=!0;for(b=0;b=0&&_++,w=w.dblp(_),u<0)break;for(b=0;b0?A=s[b][S-1>>1]:S<0&&(A=s[b][-S-1>>1].neg()),w="affine"===A.type?w.mixedAdd(A):w.add(A))}}for(u=0;u=Math.ceil((e.bitLength()+1)/t.step)},_y.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n=0&&(a=t,s=r),i.negative&&(i=i.neg(),n=n.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a,b:s}]},Ay.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),u=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(u).neg()}},Ay.prototype.pointFromX=function(e,t){(e=new ay(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(0!==i.redSqr().redSub(r).cmp(this.zero))throw Error("invalid point");var n=i.fromRed().isOdd();return(t&&!n||!t&&n)&&(i=i.redNeg()),this.point(e,i)},Ay.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)},Ay.prototype._endoWnafMulAdd=function(e,t,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,a=0;a":""},Ey.prototype.isInfinity=function(){return this.inf},Ey.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},Ey.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),a=n.redSqr().redISub(this.x.redAdd(this.x)),s=n.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,s)},Ey.prototype.getX=function(){return this.x.fromRed()},Ey.prototype.getY=function(){return this.y.fromRed()},Ey.prototype.mul=function(e){return e=new ay(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},Ey.prototype.mulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},Ey.prototype.jmulAdd=function(e,t,r){var i=[this,t],n=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},Ey.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},Ey.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return t},Ey.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},at(Py,vy.BasePoint),Ay.prototype.jpoint=function(e,t,r){return new Py(this,e,t,r)},Py.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(r,i)},Py.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Py.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=o.redSqr(),h=u.redMul(o),d=i.redMul(u),f=c.redSqr().redIAdd(h).redISub(d).redISub(d),l=c.redMul(d.redISub(f)).redISub(a.redMul(h)),p=this.z.redMul(e.z).redMul(o);return this.curve.jpoint(f,l,p)},Py.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))return 0!==o.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),u=c.redMul(s),h=r.redMul(c),d=o.redSqr().redIAdd(u).redISub(h).redISub(h),f=o.redMul(h.redISub(d)).redISub(n.redMul(u)),l=this.z.redMul(s);return this.curve.jpoint(d,f,l)},Py.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))return!0}},Py.prototype.inspect=function(){return this.isInfinity()?"":""},Py.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},at(xy,vy);var My=xy;function Ky(e,t,r){vy.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new ay(t,16),this.z=new ay(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}xy.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),i=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===i.redSqrt().redSqr().cmp(i)},at(Ky,vy.BasePoint),xy.prototype.decodePoint=function(e,t){if(33===(e=dy.toArray(e,t)).length&&64===e[0]&&(e=e.slice(1,33).reverse()),32!==e.length)throw Error("Unknown point compression format");return this.point(e,1)},xy.prototype.point=function(e,t){return new Ky(this,e,t)},xy.prototype.pointFromJSON=function(e){return Ky.fromJSON(this,e)},Ky.prototype.precompute=function(){},Ky.prototype._encode=function(e){var t=this.curve.p.byteLength();return e?[64].concat(this.getX().toArray("le",t)):this.getX().toArray("be",t)},Ky.fromJSON=function(e,t){return new Ky(e,t[0],t[1]||e.one)},Ky.prototype.inspect=function(){return this.isInfinity()?"":""},Ky.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Ky.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),i=e.redMul(t),n=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(i,n)},Ky.prototype.add=function(){throw Error("Not supported on Montgomery curve")},Ky.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),i=this.x.redSub(this.z),n=e.x.redAdd(e.z),a=e.x.redSub(e.z).redMul(r),s=n.redMul(i),o=t.z.redMul(a.redAdd(s).redSqr()),c=t.x.redMul(a.redISub(s).redSqr());return this.curve.point(o,c)},Ky.prototype.mul=function(e){for(var t=(e=new ay(e,16)).clone(),r=this,i=this.curve.point(null,null),n=[];0!==t.cmpn(0);t.iushrn(1))n.push(t.andln(1));for(var a=n.length-1;a>=0;a--)0===n[a]?(r=r.diffAdd(i,this),i=i.dbl()):(i=r.diffAdd(i,this),r=r.dbl());return i},Ky.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},Ky.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},Ky.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},Ky.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Ky.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Cy=dy.assert;function Dy(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,vy.call(this,"edwards",e),this.a=new ay(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new ay(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new ay(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Cy(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}at(Dy,vy);var Uy=Dy;function Ry(e,t,r,i,n){vy.BasePoint.call(this,e,"projective"),null===t&&null===r&&null===i?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new ay(t,16),this.y=new ay(r,16),this.z=i?new ay(i,16):this.curve.one,this.t=n&&new ay(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}Dy.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},Dy.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},Dy.prototype.jpoint=function(e,t,r,i){return this.point(e,t,r,i)},Dy.prototype.pointFromX=function(e,t){(e=new ay(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=this.c2.redSub(this.a.redMul(r)),n=this.one.redSub(this.c2.redMul(this.d).redMul(r)),a=i.redMul(n.redInvm()),s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");var o=s.fromRed().isOdd();return(t&&!o||!t&&o)&&(s=s.redNeg()),this.point(e,s)},Dy.prototype.pointFromY=function(e,t){(e=new ay(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr(),i=r.redSub(this.c2),n=r.redMul(this.d).redMul(this.c2).redSub(this.a),a=i.redMul(n.redInvm());if(0===a.cmp(this.zero)){if(t)throw Error("invalid point");return this.point(this.zero,e)}var s=a.redSqrt();if(0!==s.redSqr().redSub(a).cmp(this.zero))throw Error("invalid point");return s.fromRed().isOdd()!==t&&(s=s.redNeg()),this.point(s,e)},Dy.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),r=e.y.redSqr(),i=t.redMul(this.a).redAdd(r),n=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(r)));return 0===i.cmp(n)},at(Ry,vy.BasePoint),Dy.prototype.pointFromJSON=function(e){return Ry.fromJSON(this,e)},Dy.prototype.point=function(e,t,r,i){return new Ry(this,e,t,r,i)},Ry.fromJSON=function(e,t){return new Ry(e,t[0],t[1],t[2])},Ry.prototype.inspect=function(){return this.isInfinity()?"":""},Ry.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ry.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var i=this.curve._mulA(e),n=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=i.redAdd(t),s=a.redSub(r),o=i.redSub(t),c=n.redMul(s),u=a.redMul(o),h=n.redMul(o),d=s.redMul(a);return this.curve.point(c,u,d,h)},Ry.prototype._projDbl=function(){var e,t,r,i=this.x.redAdd(this.y).redSqr(),n=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var s=(u=this.curve._mulA(n)).redAdd(a);if(this.zOne)e=i.redSub(n).redSub(a).redMul(s.redSub(this.curve.two)),t=s.redMul(u.redSub(a)),r=s.redSqr().redSub(s).redSub(s);else{var o=this.z.redSqr(),c=s.redSub(o).redISub(o);e=i.redSub(n).redISub(a).redMul(c),t=s.redMul(u.redSub(a)),r=s.redMul(c)}}else{var u=n.redAdd(a);o=this.curve._mulC(this.z).redSqr(),c=u.redSub(o).redSub(o);e=this.curve._mulC(i.redISub(u)).redMul(c),t=this.curve._mulC(u).redMul(n.redISub(a)),r=u.redMul(c)}return this.curve.point(e,t,r)},Ry.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ry.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),i=this.t.redMul(this.curve.dd).redMul(e.t),n=this.z.redMul(e.z.redAdd(e.z)),a=r.redSub(t),s=n.redSub(i),o=n.redAdd(i),c=r.redAdd(t),u=a.redMul(s),h=o.redMul(c),d=a.redMul(c),f=s.redMul(o);return this.curve.point(u,h,f,d)},Ry.prototype._projAdd=function(e){var t,r,i=this.z.redMul(e.z),n=i.redSqr(),a=this.x.redMul(e.x),s=this.y.redMul(e.y),o=this.curve.d.redMul(a).redMul(s),c=n.redSub(o),u=n.redAdd(o),h=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(a).redISub(s),d=i.redMul(c).redMul(h);return this.curve.twisted?(t=i.redMul(u).redMul(s.redSub(this.curve._mulA(a))),r=c.redMul(u)):(t=i.redMul(u).redMul(s.redSub(a)),r=this.curve._mulC(c).redMul(u)),this.curve.point(d,t,r)},Ry.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},Ry.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},Ry.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},Ry.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},Ry.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},Ry.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ry.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ry.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ry.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},Ry.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),i=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(i),0===this.x.cmp(t))return!0}},Ry.prototype.toP=Ry.prototype.normalize,Ry.prototype.mixedAdd=Ry.prototype.add;var Iy=it((function(e,t){var r=t;r.base=vy,r.short=Sy,r.mont=My,r.edwards=Uy})),By=pt.rotl32,Ty=pt.sum32,zy=pt.sum32_5,qy=At.ft_1,Fy=mt.BlockHash,Oy=[1518500249,1859775393,2400959708,3395469782];function Ly(){if(!(this instanceof Ly))return new Ly;Fy.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}pt.inherits(Ly,Fy);var Ny=Ly;Ly.blockSize=512,Ly.outSize=160,Ly.hmacStrength=80,Ly.padLength=64,Ly.prototype._update=function(e,t){for(var r=this.W,i=0;i<16;i++)r[i]=e[t+i];for(;ithis.blockSize&&(e=(new this.Hash).update(e).digest()),et(e.length<=this.blockSize);for(var t=e.length;t=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,i)}var Xy=Zy;Zy.prototype._init=function(e,t,r){var i=e.concat(t).concat(r);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var n=0;n=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},Zy.prototype.generate=function(e,t,r,i){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");"string"!=typeof t&&(i=r,r=t,t=null),r&&(r=hy.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length"};var eb=dy.assert;function tb(e,t){if(e instanceof tb)return e;this._importDER(e,t)||(eb(e.r&&e.s,"Signature without r or s"),this.r=new ay(e.r,16),this.s=new ay(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}var rb=tb;function ib(){this.place=0}function nb(e,t){var r=e[t.place++];if(!(128&r))return r;for(var i=15&r,n=0,a=0,s=t.place;a>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}tb.prototype._importDER=function(e,t){e=dy.toArray(e,t);var r=new ib;if(48!==e[r.place++])return!1;if(nb(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var i=nb(e,r),n=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])return!1;var a=nb(e,r);if(e.length!==a+r.place)return!1;var s=e.slice(r.place,a+r.place);return 0===n[0]&&128&n[1]&&(n=n.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new ay(n),this.s=new ay(s),this.recoveryParam=null,!0},tb.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=ab(t),r=ab(r);!(r[0]||128&r[1]);)r=r.slice(1);var i=[2];sb(i,t.length),(i=i.concat(t)).push(2),sb(i,r.length);var n=i.concat(r),a=[48];return sb(a,n.length),a=a.concat(n),dy.encode(a,e)};var ob=dy.assert;function cb(e){if(!(this instanceof cb))return new cb(e);"string"==typeof e&&(ob($y.hasOwnProperty(e),"Unknown curve "+e),e=$y[e]),e instanceof $y.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}var ub=cb;cb.prototype.keyPair=function(e){return new Jy(this,e)},cb.prototype.keyFromPrivate=function(e,t){return Jy.fromPrivate(this,e,t)},cb.prototype.keyFromPublic=function(e,t){return Jy.fromPublic(this,e,t)},cb.prototype.genKeyPair=function(e){e||(e={});var t=new Xy({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||fy(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()});if("mont"===this.curve.type){var r=new ay(t.generate(32));return this.keyFromPrivate(r)}for(var i=this.n.byteLength(),n=this.n.sub(new ay(2));;){if(!((r=new ay(t.generate(i))).cmp(n)>0))return r.iaddn(1),this.keyFromPrivate(r)}},cb.prototype._truncateToN=function(e,t,r){var i=(r=r||8*e.byteLength())-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},cb.prototype.truncateMsg=function(e){var t;return e instanceof Uint8Array?(t=8*e.byteLength,e=this._truncateToN(new ay(e,16),!1,t)):"string"==typeof e?(t=4*e.length,e=this._truncateToN(new ay(e,16),!1,t)):e=this._truncateToN(new ay(e,16)),e},cb.prototype.sign=function(e,t,r,i){"object"==typeof r&&(i=r,r=null),i||(i={}),t=this.keyFromPrivate(t,r),e=this.truncateMsg(e);for(var n=this.n.byteLength(),a=t.getPrivate().toArray("be",n),s=e.toArray("be",n),o=new Xy({hash:this.hash,entropy:a,nonce:s,pers:i.pers,persEnc:i.persEnc||"utf8"}),c=this.n.sub(new ay(1)),u=0;;u++){var h=i.k?i.k(u):new ay(o.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(c)>=0)){var d=this.g.mul(h);if(!d.isInfinity()){var f=d.getX(),l=f.umod(this.n);if(0!==l.cmpn(0)){var p=h.invm(this.n).mul(l.mul(t.getPrivate()).iadd(e));if(0!==(p=p.umod(this.n)).cmpn(0)){var y=(d.getY().isOdd()?1:0)|(0!==f.cmp(l)?2:0);return i.canonical&&p.cmp(this.nh)>0&&(p=this.n.sub(p),y^=1),new rb({r:l,s:p,recoveryParam:y})}}}}}},cb.prototype.verify=function(e,t,r,i){return r=this.keyFromPublic(r,i),t=new rb(t,"hex"),this._verify(this.truncateMsg(e),t,r)||this._verify(this._truncateToN(new ay(e,16)),t,r)},cb.prototype._verify=function(e,t,r){var i=t.r,n=t.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(n.cmpn(1)<0||n.cmp(this.n)>=0)return!1;var a,s=n.invm(this.n),o=s.mul(e).umod(this.n),c=s.mul(i).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(o,r.getPublic(),c)).isInfinity()&&a.eqXToP(i):!(a=this.g.mulAdd(o,r.getPublic(),c)).isInfinity()&&0===a.getX().umod(this.n).cmp(i)},cb.prototype.recoverPubKey=function(e,t,r,i){ob((3&r)===r,"The recovery param is more than two bits"),t=new rb(t,i);var n=this.n,a=new ay(e),s=t.r,o=t.s,c=1&r,u=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw Error("Unable to find sencond key candinate");s=u?this.curve.pointFromX(s.add(this.curve.n),c):this.curve.pointFromX(s,c);var h=t.r.invm(n),d=n.sub(a).mul(h).umod(n),f=o.mul(h).umod(n);return this.g.mulAdd(d,s,f)},cb.prototype.getKeyRecoveryParam=function(e,t,r,i){if(null!==(t=new rb(t,i)).recoveryParam)return t.recoveryParam;for(var n=0;n<4;n++){var a;try{a=this.recoverPubKey(e,t,n)}catch(e){continue}if(a.eq(r))return n}throw Error("Unable to find valid recovery factor")};var hb=dy.assert,db=dy.parseBytes,fb=dy.cachedProperty;function lb(e,t){if(this.eddsa=e,t.hasOwnProperty("secret")&&(this._secret=db(t.secret)),e.isPoint(t.pub))this._pub=t.pub;else if(this._pubBytes=db(t.pub),this._pubBytes&&33===this._pubBytes.length&&64===this._pubBytes[0]&&(this._pubBytes=this._pubBytes.slice(1,33)),this._pubBytes&&32!==this._pubBytes.length)throw Error("Unknown point compression format")}lb.fromPublic=function(e,t){return t instanceof lb?t:new lb(e,{pub:t})},lb.fromSecret=function(e,t){return t instanceof lb?t:new lb(e,{secret:t})},lb.prototype.secret=function(){return this._secret},fb(lb,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),fb(lb,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),fb(lb,"privBytes",(function(){var e=this.eddsa,t=this.hash(),r=e.encodingLength-1,i=t.slice(0,e.encodingLength);return i[0]&=248,i[r]&=127,i[r]|=64,i})),fb(lb,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),fb(lb,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),fb(lb,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),lb.prototype.sign=function(e){return hb(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},lb.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},lb.prototype.getSecret=function(e){return hb(this._secret,"KeyPair is public only"),dy.encode(this.secret(),e)},lb.prototype.getPublic=function(e,t){return dy.encode((t?[64]:[]).concat(this.pubBytes()),e)};var pb=lb,yb=dy.assert,bb=dy.cachedProperty,mb=dy.parseBytes;function gb(e,t){this.eddsa=e,"object"!=typeof t&&(t=mb(t)),Array.isArray(t)&&(t={R:t.slice(0,e.encodingLength),S:t.slice(e.encodingLength)}),yb(t.R&&t.S,"Signature without R or S"),e.isPoint(t.R)&&(this._R=t.R),t.S instanceof ay&&(this._S=t.S),this._Rencoded=Array.isArray(t.R)?t.R:t.Rencoded,this._Sencoded=Array.isArray(t.S)?t.S:t.Sencoded}bb(gb,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),bb(gb,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),bb(gb,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),bb(gb,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),gb.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},gb.prototype.toHex=function(){return dy.encode(this.toBytes(),"hex").toUpperCase()};var wb=gb,vb=dy.assert,_b=dy.parseBytes;function kb(e){if(vb("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof kb))return new kb(e);e=$y[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=Gy.sha512}var Ab=kb;kb.prototype.sign=function(e,t){e=_b(e);var r=this.keyFromSecret(t),i=this.hashInt(r.messagePrefix(),e),n=this.g.mul(i),a=this.encodePoint(n),s=this.hashInt(a,r.pubBytes(),e).mul(r.priv()),o=i.add(s).umod(this.curve.n);return this.makeSignature({R:n,S:o,Rencoded:a})},kb.prototype.verify=function(e,t,r){e=_b(e),t=this.makeSignature(t);var i=this.keyFromPublic(r),n=this.hashInt(t.Rencoded(),i.pubBytes(),e),a=this.g.mul(t.S());return t.R().add(i.pub().mul(n)).eq(a)},kb.prototype.hashInt=function(){for(var e=this.hash(),t=0;t{this[n]=e,this[i]=t})),this[r].catch((()=>{}))}}function o(e){return e&&e.getReader&&Array.isArray(e)}function c(e){if(!o(e)){const t=e.getWriter(),r=t.releaseLock;return t.releaseLock=()=>{t.closed.catch((function(){})),r.call(t)},t}this.stream=e}function h(t){if(o(t))return"array";if(e.ReadableStream&&e.ReadableStream.prototype.isPrototypeOf(t))return"web";if(t&&!(e.ReadableStream&&t instanceof e.ReadableStream)&&"function"==typeof t._read&&"object"==typeof t._readableState)throw Error("Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`");return!(!t||!t.getReader)&&"web-like"}function u(e){return Uint8Array.prototype.isPrototypeOf(e)}function l(e){if(1===e.length)return e[0];let t=0;for(let r=0;r(await this[r],this[s]===this.length?{value:void 0,done:!0}:{value:this[this[s]++],done:!1})}},a.prototype.readToEnd=async function(e){await this[r];const t=e(this.slice(this[s]));return this.length=0,t},a.prototype.clone=function(){const e=new a;return e[r]=this[r].then((()=>{e.push(...this)})),e},c.prototype.write=async function(e){this.stream.push(e)},c.prototype.close=async function(){this.stream[n]()},c.prototype.abort=async function(e){return this.stream[i](e),e},c.prototype.releaseLock=function(){},"object"==typeof e.process&&e.process.versions;const y=new WeakSet,f=Symbol("externalBuffer");function g(e){if(this.stream=e,e[f]&&(this[f]=e[f].slice()),o(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{},void(this._cancel=()=>{})}if(h(e)){const t=e.getReader();return this._read=t.read.bind(t),this._releaseLock=()=>{t.closed.catch((function(){})),t.releaseLock()},void(this._cancel=t.cancel.bind(t))}let t=!1;this._read=async()=>t||y.has(e)?{value:void 0,done:!0}:(t=!0,{value:e,done:!1}),this._releaseLock=()=>{if(t)try{y.add(e)}catch(e){}}}function p(e){return h(e)?e:new ReadableStream({start(t){t.enqueue(e),t.close()}})}function d(e){if(h(e))return e;const t=new a;return(async()=>{const r=x(t);await r.write(e),await r.close()})(),t}function A(e){return e.some((e=>h(e)&&!o(e)))?function(e){e=e.map(p);const t=b((async function(e){await Promise.all(n.map((t=>D(t,e))))}));let r=Promise.resolve();const n=e.map(((n,i)=>E(n,((n,s)=>(r=r.then((()=>w(n,t.writable,{preventClose:i!==e.length-1}))),r)))));return t.readable}(e):e.some((e=>o(e)))?function(e){const t=new a;let r=Promise.resolve();return e.forEach(((n,i)=>(r=r.then((()=>w(n,t,{preventClose:i!==e.length-1}))),r))),t}(e):"string"==typeof e[0]?e.join(""):l(e)}async function w(e,t,{preventClose:r=!1,preventAbort:n=!1,preventCancel:i=!1}={}){if(h(e)&&!o(e)){e=p(e);try{if(e[f]){const r=x(t);for(let t=0;t{t=e,r=n})),t=null,r=null)},close:n.close.bind(n),abort:n.error.bind(n)})}}function k(e,t=()=>{},r=()=>{}){if(o(e)){const n=new a;return(async()=>{const i=x(n);try{const n=await C(e),s=t(n),a=r();let o;o=void 0!==s&&void 0!==a?A([s,a]):void 0!==s?s:a,await i.write(o),await i.close()}catch(e){await i.abort(e)}})(),n}if(h(e))return m(e,{async transform(e,r){try{const n=await t(e);void 0!==n&&r.enqueue(n)}catch(e){r.error(e)}},async flush(e){try{const t=await r();void 0!==t&&e.enqueue(t)}catch(t){e.error(t)}}});const n=t(e),i=r();return void 0!==n&&void 0!==i?A([n,i]):void 0!==n?n:i}function E(e,t){if(h(e)&&!o(e)){let r;const n=new TransformStream({start(e){r=e}}),i=w(e,n.writable),s=b((async function(e){r.error(e),await i,await new Promise(setTimeout)}));return t(n.readable,s.writable),s.readable}e=d(e);const r=new a;return t(e,r),r}function v(e,t){let r;const n=E(e,((e,i)=>{const s=U(e);s.remainder=()=>(s.releaseLock(),w(e,i),n),r=t(s)}));return r}function B(e){if(o(e))return e.clone();if(h(e)){const t=function(e){if(o(e))throw Error("ArrayStream cannot be tee()d, use clone() instead");if(h(e)){const t=p(e).tee();return t[0][f]=t[1][f]=e[f],t}return[K(e),K(e)]}(e);return S(e,t[0]),t[1]}return K(e)}function I(e){return o(e)?B(e):h(e)?new ReadableStream({start(t){const r=E(e,(async(e,r)=>{const n=U(e),i=x(r);try{for(;;){await i.ready;const{done:e,value:r}=await n.read();if(e){try{t.close()}catch(e){}return void await i.close()}try{t.enqueue(r)}catch(e){}await i.write(r)}}catch(e){t.error(e),await i.abort(e)}}));S(e,r)}}):K(e)}function S(e,t){Object.entries(Object.getOwnPropertyDescriptors(e.constructor.prototype)).forEach((([r,n])=>{"constructor"!==r&&(n.value?n.value=n.value.bind(t):n.get=n.get.bind(t),Object.defineProperty(e,r,n))}))}function K(e,t=0,r=1/0){if(o(e))throw Error("Not implemented");if(h(e)){if(t>=0&&r>=0){let n=0;return m(e,{transform(e,i){n=t&&i.enqueue(K(e,Math.max(t-n,0),r-n)),n+=e.length):i.terminate()}})}if(t<0&&(r<0||r===1/0)){let n=[];return k(e,(e=>{e.length>=-t?n=[e]:n.push(e)}),(()=>K(A(n),t,r)))}if(0===t&&r<0){let n;return k(e,(e=>{const i=n?A([n,e]):e;if(i.length>=-r)return n=K(i,r),K(i,t,r);n=i}))}return console.warn(`stream.slice(input, ${t}, ${r}) not implemented efficiently.`),P((async()=>K(await C(e),t,r)))}return e[f]&&(e=A(e[f].concat([e]))),u(e)?e.subarray(t,r===1/0?e.length:r):e.slice(t,r)}async function C(e,t=A){return o(e)?e.readToEnd(t):h(e)?U(e).readToEnd(t):e}async function D(e,t){if(h(e)){if(e.cancel){const r=await e.cancel(t);return await new Promise(setTimeout),r}if(e.destroy)return e.destroy(t),await new Promise(setTimeout),t}}function P(e){const t=new a;return(async()=>{const r=x(t);try{await r.write(await e()),await r.close()}catch(e){await r.abort(e)}})(),t}function U(e){return new g(e)}function x(e){return new c(e)}g.prototype.read=async function(){if(this[f]&&this[f].length){return{done:!1,value:this[f].shift()}}return this._read()},g.prototype.releaseLock=function(){this[f]&&(this.stream[f]=this[f]),this._releaseLock()},g.prototype.cancel=function(e){return this._cancel(e)},g.prototype.readLine=async function(){let e,t=[];for(;!e;){let{done:r,value:n}=await this.read();if(n+="",r)return t.length?A(t):void 0;const i=n.indexOf("\n")+1;i&&(e=A(t.concat(n.substr(0,i))),t=[]),i!==n.length&&t.push(n.substr(i))}return this.unshift(...t),e},g.prototype.readByte=async function(){const{done:e,value:t}=await this.read();if(e)return;const r=t[0];return this.unshift(K(t,1)),r},g.prototype.readBytes=async function(e){const t=[];let r=0;for(;;){const{done:n,value:i}=await this.read();if(n)return t.length?A(t):void 0;if(t.push(i),r+=i.length,r>=e){const r=A(t);return this.unshift(K(r,e)),K(r,0,e)}}},g.prototype.peekBytes=async function(e){const t=await this.readBytes(e);return this.unshift(t),t},g.prototype.unshift=function(...e){this[f]||(this[f]=[]),1===e.length&&u(e[0])&&this[f].length&&e[0].length&&this[f][0].byteOffset>=e[0].length?this[f][0]=new Uint8Array(this[f][0].buffer,this[f][0].byteOffset-e[0].length,this[f][0].byteLength+e[0].length):this[f].unshift(...e.filter((e=>e&&e.length)))},g.prototype.readToEnd=async function(e=A){const t=[];for(;;){const{done:e,value:r}=await this.read();if(e)break;t.push(r)}return e(t)};const Q=Symbol("byValue");var R={curve:{nistP256:"nistP256",p256:"nistP256",nistP384:"nistP384",p384:"nistP384",nistP521:"nistP521",p521:"nistP521",secp256k1:"secp256k1",ed25519Legacy:"ed25519Legacy",ed25519:"ed25519Legacy",curve25519Legacy:"curve25519Legacy",curve25519:"curve25519Legacy",brainpoolP256r1:"brainpoolP256r1",brainpoolP384r1:"brainpoolP384r1",brainpoolP512r1:"brainpoolP512r1"},s2k:{simple:0,salted:1,iterated:3,argon2:4,gnu:101},publicKey:{rsaEncryptSign:1,rsaEncrypt:2,rsaSign:3,elgamal:16,dsa:17,ecdh:18,ecdsa:19,eddsaLegacy:22,aedh:23,aedsa:24,x25519:25,x448:26,ed25519:27,ed448:28},symmetric:{idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11,sha3_256:12,sha3_512:14},webHash:{"SHA-1":2,"SHA-256":8,"SHA-384":9,"SHA-512":10},aead:{eax:1,ocb:2,gcm:3,experimentalGCM:100},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressedData:8,symmetricallyEncryptedData:9,marker:10,literalData:11,trust:12,userID:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtectedData:18,modificationDetectionCode:19,aeadEncryptedData:20,padding:21},literal:{binary:98,text:116,utf8:117,mime:109},signature:{binary:0,text:1,standalone:2,certGeneric:16,certPersona:17,certCasual:18,certPositive:19,certRevocation:48,subkeyBinding:24,keyBinding:25,key:31,keyRevocation:32,subkeyRevocation:40,timestamp:64,thirdParty:80},signatureSubpacket:{signatureCreationTime:2,signatureExpirationTime:3,exportableCertification:4,trustSignature:5,regularExpression:6,revocable:7,keyExpirationTime:9,placeholderBackwardsCompatibility:10,preferredSymmetricAlgorithms:11,revocationKey:12,issuerKeyID:16,notationData:20,preferredHashAlgorithms:21,preferredCompressionAlgorithms:22,keyServerPreferences:23,preferredKeyServer:24,primaryUserID:25,policyURI:26,keyFlags:27,signersUserID:28,reasonForRevocation:29,features:30,signatureTarget:31,embeddedSignature:32,issuerFingerprint:33,preferredAEADAlgorithms:34,preferredCipherSuites:39},keyFlags:{certifyKeys:1,signData:2,encryptCommunication:4,encryptStorage:8,splitPrivateKey:16,authentication:32,sharedPrivateKey:128},armor:{multipartSection:0,multipartLast:1,signed:2,message:3,publicKey:4,privateKey:5,signature:6},reasonForRevocation:{noReason:0,keySuperseded:1,keyCompromised:2,keyRetired:3,userIDInvalid:32},features:{modificationDetection:1,aead:2,v5Keys:4,seipdv2:8},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw Error("Invalid enum value.")},read:function(e,t){if(e[Q]||(e[Q]=[],Object.entries(e).forEach((([t,r])=>{e[Q][r]=t}))),void 0!==e[Q][t])return e[Q][t];throw Error("Invalid enum value.")}},L={preferredHashAlgorithm:R.hash.sha512,preferredSymmetricAlgorithm:R.symmetric.aes256,preferredCompressionAlgorithm:R.compression.uncompressed,aeadProtect:!1,parseAEADEncryptedV4KeysAsLegacy:!1,preferredAEADAlgorithm:R.aead.gcm,aeadChunkSizeByte:12,v6Keys:!1,enableParsingV5Entities:!1,s2kType:R.s2k.iterated,s2kIterationCountByte:224,s2kArgon2Params:{passes:3,parallelism:4,memoryExponent:16},allowUnauthenticatedMessages:!1,allowUnauthenticatedStream:!1,minRSABits:2047,passwordCollisionCheck:!1,allowInsecureDecryptionWithSigningKeys:!1,allowInsecureVerificationWithReformattedKeys:!1,allowMissingKeyFlags:!1,constantTimePKCS1Decryption:!1,constantTimePKCS1DecryptionSupportedSymmetricAlgorithms:new Set([R.symmetric.aes128,R.symmetric.aes192,R.symmetric.aes256]),ignoreUnsupportedPackets:!0,ignoreMalformedPackets:!1,additionalAllowedPackets:[],showVersion:!1,showComment:!1,versionString:"OpenPGP.js 6.0.0",commentString:"https://openpgpjs.org",maxUserIDLength:5120,knownNotations:[],nonDeterministicSignaturesViaNotation:!0,useEllipticFallback:!0,rejectHashAlgorithms:new Set([R.hash.md5,R.hash.ripemd]),rejectMessageHashAlgorithms:new Set([R.hash.md5,R.hash.ripemd,R.hash.sha1]),rejectPublicKeyAlgorithms:new Set([R.publicKey.elgamal,R.publicKey.dsa]),rejectCurves:new Set([R.curve.secp256k1])};const T=(()=>{try{return"development"===process.env.NODE_ENV}catch(e){}return!1})(),M={isString:function(e){return"string"==typeof e||e instanceof String},nodeRequire:()=>{},isArray:function(e){return e instanceof Array},isUint8Array:u,isStream:h,getNobleCurve:async(e,t)=>{if(!L.useEllipticFallback)throw Error("This curve is only supported in the full build of OpenPGP.js");const{nobleCurves:r}=await Promise.resolve().then((function(){return dl}));switch(e){case R.publicKey.ecdh:case R.publicKey.ecdsa:{const e=r.get(t);if(!e)throw Error("Unsupported curve");return e}case R.publicKey.x448:return r.get("x448");case R.publicKey.ed448:return r.get("ed448");default:throw Error("Unsupported curve")}},readNumber:function(e){let t=0;for(let r=0;r>8*(t-n-1)&255;return r},readDate:function(e){const t=M.readNumber(e);return new Date(1e3*t)},writeDate:function(e){const t=Math.floor(e.getTime()/1e3);return M.writeNumber(t,4)},normalizeDate:function(e=Date.now()){return null===e||e===1/0?e:new Date(1e3*Math.floor(+e/1e3))},readMPI:function(e){const t=(e[0]<<8|e[1])+7>>>3;return M.readExactSubarray(e,2,2+t)},readExactSubarray:function(e,t,r){if(e.lengtht)throw Error("Input array too long");const r=new Uint8Array(t),n=t-e.length;return r.set(e,n),r},uint8ArrayToMPI:function(e){const t=M.uint8ArrayBitLength(e);if(0===t)throw Error("Zero MPI");const r=e.subarray(e.length-Math.ceil(t/8)),n=new Uint8Array([(65280&t)>>8,255&t]);return M.concatUint8Array([n,r])},uint8ArrayBitLength:function(e){let t;for(t=0;t>1);for(let r=0;r>1;r++)t[r]=parseInt(e.substr(r<<1,2),16);return t},uint8ArrayToHex:function(e){const t="0123456789abcdef";let r="";return e.forEach((e=>{r+=t[e>>4]+t[15&e]})),r},stringToUint8Array:function(e){return k(e,(e=>{if(!M.isString(e))throw Error("stringToUint8Array: Data must be in the form of a string");const t=new Uint8Array(e.length);for(let r=0;rr("",!0)))},decodeUTF8:function(e){const t=new TextDecoder("utf-8");function r(e,r=!1){return t.decode(e,{stream:!r})}return k(e,r,(()=>r(new Uint8Array,!0)))},concat:A,concatUint8Array:l,equalsUint8Array:function(e,t){if(!M.isUint8Array(e)||!M.isUint8Array(t))throw Error("Data must be in the form of a Uint8Array");if(e.length!==t.length)return!1;for(let r=0;r>>16;return 0!==r&&(e=r,t+=16),r=e>>8,0!==r&&(e=r,t+=8),r=e>>4,0!==r&&(e=r,t+=4),r=e>>2,0!==r&&(e=r,t+=2),r=e>>1,0!==r&&(e=r,t+=1),t},double:function(e){const t=new Uint8Array(e.length),r=e.length-1;for(let n=0;n>7;return t[r]=e[r]<<1^135*(e[0]>>7),t},shiftRight:function(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]>>=t,r>0&&(e[r]|=e[r-1]<<8-t);return e},getWebCrypto:function(){const t=void 0!==e&&e.crypto&&e.crypto.subtle||this.getNodeCrypto()?.webcrypto.subtle;if(!t)throw Error("The WebCrypto API is not available");return t},getNodeCrypto:function(){return this.nodeRequire("crypto")},getNodeZlib:function(){return this.nodeRequire("zlib")},getNodeBuffer:function(){return(this.nodeRequire("buffer")||{}).Buffer},getHardwareConcurrency:function(){if("undefined"!=typeof navigator)return navigator.hardwareConcurrency||1;return this.nodeRequire("os").cpus().length},isEmailAddress:function(e){if(!M.isString(e))return!1;return/^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u.test(e)},canonicalizeEOL:function(e){let t=!1;return k(e,(e=>{let r;t&&(e=M.concatUint8Array([new Uint8Array([13]),e])),13===e[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;const n=[];for(let t=0;r=e.indexOf(10,t)+1,r;t=r)13!==e[r-2]&&n.push(r);if(!n.length)return e;const i=new Uint8Array(e.length+n.length);let s=0;for(let t=0;tt?new Uint8Array([13]):void 0))},nativeEOL:function(e){let t=!1;return k(e,(e=>{let r;13===(e=t&&10!==e[0]?M.concatUint8Array([new Uint8Array([13]),e]):new Uint8Array(e))[e.length-1]?(t=!0,e=e.subarray(0,-1)):t=!1;let n=0;for(let t=0;t!==e.length;t=r){r=e.indexOf(13,t)+1,r||(r=e.length);const i=r-(10===e[r]?1:0);t&&e.copyWithin(n,t,i),n+=i-t}return e.subarray(0,n)}),(()=>t?new Uint8Array([13]):void 0))},removeTrailingSpaces:function(e){return e.split("\n").map((e=>{let t=e.length-1;for(;t>=0&&(" "===e[t]||"\t"===e[t]||"\r"===e[t]);t--);return e.substr(0,t+1)})).join("\n")},wrapError:function(e,t){if(!t)return Error(e);try{t.message=e+": "+t.message}catch(e){}return t},constructAllowedPackets:function(e){const t={};return e.forEach((e=>{if(!e.tag)throw Error("Invalid input: expected a packet class");t[e.tag]=e})),t},anyPromise:function(e){return new Promise((async(t,r)=>{let n;await Promise.all(e.map((async e=>{try{t(await e)}catch(e){n=e}}))),r(n)}))},selectUint8Array:function(e,t,r){const n=Math.max(t.length,r.length),i=new Uint8Array(n);let s=0;for(let n=0;n{t=M.concatUint8Array([t,e]);const r=[],n=Math.floor(t.length/45),i=45*n,s=F(t.subarray(0,i));for(let e=0;et.length?F(t)+"\n":""))}function z(e){let t="";return k(e,(e=>{t+=e;let r=0;const n=[" ","\t","\r","\n"];for(let e=0;e0&&(i-r)%4!=0;i--)n.includes(t[i])&&r--;const s=H(t.substr(0,i));return t=t.substr(i),s}),(()=>H(t)))}function _(e){return z(e.replace(/-/g,"+").replace(/_/g,"/"))}function G(e,t){let r=O(e).replace(/[\r\n]/g,"");return r=r.replace(/[+]/g,"-").replace(/[/]/g,"_").replace(/[=]/g,""),r}function j(e){const t=e.match(/^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m);if(!t)throw Error("Unknown ASCII armor type");return/MESSAGE, PART \d+\/\d+/.test(t[1])?R.armor.multipartSection:/MESSAGE, PART \d+/.test(t[1])?R.armor.multipartLast:/SIGNED MESSAGE/.test(t[1])?R.armor.signed:/MESSAGE/.test(t[1])?R.armor.message:/PUBLIC KEY BLOCK/.test(t[1])?R.armor.publicKey:/PRIVATE KEY BLOCK/.test(t[1])?R.armor.privateKey:/SIGNATURE/.test(t[1])?R.armor.signature:void 0}function q(e,t){let r="";return t.showVersion&&(r+="Version: "+t.versionString+"\n"),t.showComment&&(r+="Comment: "+t.commentString+"\n"),e&&(r+="Comment: "+e+"\n"),r+="\n",r}function V(e){const t=function(e){let t=13501623;return k(e,(e=>{const r=Y?Math.floor(e.length/4):0,n=new Uint32Array(e.buffer,e.byteOffset,r);for(let e=0;e>24&255]^J[1][t>>16&255]^J[2][t>>8&255]^J[3][255&t];for(let n=4*r;n>8^J[0][255&t^e[n]]}),(()=>new Uint8Array([t,t>>8,t>>16])))}(e);return O(t)}N?(F=e=>N.from(e).toString("base64"),H=e=>{const t=N.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}):(F=e=>btoa(M.uint8ArrayToString(e)),H=e=>M.stringToUint8Array(atob(e)));const J=[Array(255),Array(255),Array(255),Array(255)];for(let e=0;e<=255;e++){let t=e<<16;for(let e=0;e<8;e++)t=t<<1^(8388608&t?8801531:0);J[0][e]=(16711680&t)>>16|65280&t|(255&t)<<16}for(let e=0;e<=255;e++)J[1][e]=J[0][e]>>8^J[0][255&J[0][e]];for(let e=0;e<=255;e++)J[2][e]=J[1][e]>>8^J[0][255&J[1][e]];for(let e=0;e<=255;e++)J[3][e]=J[2][e]>>8^J[0][255&J[2][e]];const Y=function(){const e=new ArrayBuffer(2);return new DataView(e).setInt16(0,255,!0),255===new Int16Array(e)[0]}();function W(e){for(let t=0;t=0&&r!==e.length-1&&(t=e.slice(0,r)),t}function $(e){return new Promise((async(t,r)=>{try{const n=/^-----[^-]+-----$/m,i=/^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;let s;const a=[];let o,c,h=a,u=[];const l=z(E(e,(async(e,y)=>{const f=U(e);try{for(;;){let e=await f.readLine();if(void 0===e)throw Error("Misformed armored text");if(e=M.removeTrailingSpaces(e.replace(/[\r\n]/g,"")),s)if(o)c||s!==R.armor.signed||(n.test(e)?(u=u.join("\r\n"),c=!0,W(h),h=[],o=!1):u.push(e.replace(/^- /,"")));else if(n.test(e)&&r(Error("Mandatory blank line missing between armor headers and armor data")),i.test(e)){if(W(h),o=!0,c||s!==R.armor.signed){t({text:u,data:l,headers:a,type:s});break}}else h.push(e);else n.test(e)&&(s=j(e))}}catch(e){return void r(e)}const g=x(y);try{for(;;){await g.ready;const{done:e,value:t}=await f.read();if(e)throw Error("Misformed armored text");const r=t+"";if(-1!==r.indexOf("=")||-1!==r.indexOf("-")){let e=await f.readToEnd();e.length||(e=""),e=r+e,e=M.removeTrailingSpaces(e.replace(/\r/g,""));const t=e.split(n);if(1===t.length)throw Error("Misformed armored text");const i=Z(t[0].slice(0,-1));await g.write(i);break}await g.write(r)}await g.ready,await g.close()}catch(e){await g.abort(e)}})))}catch(e){r(e)}})).then((async e=>(o(e.data)&&(e.data=await C(e.data)),e)))}function X(e,t,r,n,i,s=!1,a=L){let o,c;e===R.armor.signed&&(o=t.text,c=t.hash,t=t.data);const h=s&&I(t),u=[];switch(e){case R.armor.multipartSection:u.push("-----BEGIN PGP MESSAGE, PART "+r+"/"+n+"-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP MESSAGE, PART "+r+"/"+n+"-----\n");break;case R.armor.multipartLast:u.push("-----BEGIN PGP MESSAGE, PART "+r+"-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP MESSAGE, PART "+r+"-----\n");break;case R.armor.signed:u.push("-----BEGIN PGP SIGNED MESSAGE-----\n"),u.push(c?`Hash: ${c}\n\n`:"\n"),u.push(o.replace(/^-/gm,"- -")),u.push("\n-----BEGIN PGP SIGNATURE-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP SIGNATURE-----\n");break;case R.armor.message:u.push("-----BEGIN PGP MESSAGE-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP MESSAGE-----\n");break;case R.armor.publicKey:u.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP PUBLIC KEY BLOCK-----\n");break;case R.armor.privateKey:u.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP PRIVATE KEY BLOCK-----\n");break;case R.armor.signature:u.push("-----BEGIN PGP SIGNATURE-----\n"),u.push(q(i,a)),u.push(O(t)),h&&u.push("=",V(h)),u.push("-----END PGP SIGNATURE-----\n")}return M.concat(u)}async function ee(e){switch(e){case R.symmetric.aes128:case R.symmetric.aes192:case R.symmetric.aes256:throw Error("Not a legacy cipher");case R.symmetric.cast5:case R.symmetric.blowfish:case R.symmetric.twofish:case R.symmetric.tripledes:{const{legacyCiphers:t}=await Promise.resolve().then((function(){return Ul})),r=t.get(e);if(!r)throw Error("Unsupported cipher algorithm");return r}default:throw Error("Unsupported cipher algorithm")}}function te(e){switch(e){case R.symmetric.aes128:case R.symmetric.aes192:case R.symmetric.aes256:case R.symmetric.twofish:return 16;case R.symmetric.blowfish:case R.symmetric.cast5:case R.symmetric.tripledes:return 8;default:throw Error("Unsupported cipher")}}function re(e){switch(e){case R.symmetric.aes128:case R.symmetric.blowfish:case R.symmetric.cast5:return 16;case R.symmetric.aes192:case R.symmetric.tripledes:return 24;case R.symmetric.aes256:case R.symmetric.twofish:return 32;default:throw Error("Unsupported cipher")}}function ne(e){return{keySize:re(e),blockSize:te(e)}}var ie=/*#__PURE__*/Object.freeze({__proto__:null,getCipherParams:ne,getLegacyCipher:ee});function se(e,t){let r=e[0],n=e[1],i=e[2],s=e[3];r=oe(r,n,i,s,t[0],7,-680876936),s=oe(s,r,n,i,t[1],12,-389564586),i=oe(i,s,r,n,t[2],17,606105819),n=oe(n,i,s,r,t[3],22,-1044525330),r=oe(r,n,i,s,t[4],7,-176418897),s=oe(s,r,n,i,t[5],12,1200080426),i=oe(i,s,r,n,t[6],17,-1473231341),n=oe(n,i,s,r,t[7],22,-45705983),r=oe(r,n,i,s,t[8],7,1770035416),s=oe(s,r,n,i,t[9],12,-1958414417),i=oe(i,s,r,n,t[10],17,-42063),n=oe(n,i,s,r,t[11],22,-1990404162),r=oe(r,n,i,s,t[12],7,1804603682),s=oe(s,r,n,i,t[13],12,-40341101),i=oe(i,s,r,n,t[14],17,-1502002290),n=oe(n,i,s,r,t[15],22,1236535329),r=ce(r,n,i,s,t[1],5,-165796510),s=ce(s,r,n,i,t[6],9,-1069501632),i=ce(i,s,r,n,t[11],14,643717713),n=ce(n,i,s,r,t[0],20,-373897302),r=ce(r,n,i,s,t[5],5,-701558691),s=ce(s,r,n,i,t[10],9,38016083),i=ce(i,s,r,n,t[15],14,-660478335),n=ce(n,i,s,r,t[4],20,-405537848),r=ce(r,n,i,s,t[9],5,568446438),s=ce(s,r,n,i,t[14],9,-1019803690),i=ce(i,s,r,n,t[3],14,-187363961),n=ce(n,i,s,r,t[8],20,1163531501),r=ce(r,n,i,s,t[13],5,-1444681467),s=ce(s,r,n,i,t[2],9,-51403784),i=ce(i,s,r,n,t[7],14,1735328473),n=ce(n,i,s,r,t[12],20,-1926607734),r=he(r,n,i,s,t[5],4,-378558),s=he(s,r,n,i,t[8],11,-2022574463),i=he(i,s,r,n,t[11],16,1839030562),n=he(n,i,s,r,t[14],23,-35309556),r=he(r,n,i,s,t[1],4,-1530992060),s=he(s,r,n,i,t[4],11,1272893353),i=he(i,s,r,n,t[7],16,-155497632),n=he(n,i,s,r,t[10],23,-1094730640),r=he(r,n,i,s,t[13],4,681279174),s=he(s,r,n,i,t[0],11,-358537222),i=he(i,s,r,n,t[3],16,-722521979),n=he(n,i,s,r,t[6],23,76029189),r=he(r,n,i,s,t[9],4,-640364487),s=he(s,r,n,i,t[12],11,-421815835),i=he(i,s,r,n,t[15],16,530742520),n=he(n,i,s,r,t[2],23,-995338651),r=ue(r,n,i,s,t[0],6,-198630844),s=ue(s,r,n,i,t[7],10,1126891415),i=ue(i,s,r,n,t[14],15,-1416354905),n=ue(n,i,s,r,t[5],21,-57434055),r=ue(r,n,i,s,t[12],6,1700485571),s=ue(s,r,n,i,t[3],10,-1894986606),i=ue(i,s,r,n,t[10],15,-1051523),n=ue(n,i,s,r,t[1],21,-2054922799),r=ue(r,n,i,s,t[8],6,1873313359),s=ue(s,r,n,i,t[15],10,-30611744),i=ue(i,s,r,n,t[6],15,-1560198380),n=ue(n,i,s,r,t[13],21,1309151649),r=ue(r,n,i,s,t[4],6,-145523070),s=ue(s,r,n,i,t[11],10,-1120210379),i=ue(i,s,r,n,t[2],15,718787259),n=ue(n,i,s,r,t[9],21,-343485551),e[0]=ge(r,e[0]),e[1]=ge(n,e[1]),e[2]=ge(i,e[2]),e[3]=ge(s,e[3])}function ae(e,t,r,n,i,s){return t=ge(ge(t,e),ge(n,s)),ge(t<>>32-i,r)}function oe(e,t,r,n,i,s,a){return ae(t&r|~t&n,e,t,i,s,a)}function ce(e,t,r,n,i,s,a){return ae(t&n|r&~n,e,t,i,s,a)}function he(e,t,r,n,i,s,a){return ae(t^r^n,e,t,i,s,a)}function ue(e,t,r,n,i,s,a){return ae(r^(t|~n),e,t,i,s,a)}function le(e){const t=[];let r;for(r=0;r<64;r+=4)t[r>>2]=e.charCodeAt(r)+(e.charCodeAt(r+1)<<8)+(e.charCodeAt(r+2)<<16)+(e.charCodeAt(r+3)<<24);return t}const ye="0123456789abcdef".split("");function fe(e){let t="",r=0;for(;r<4;r++)t+=ye[e>>8*r+4&15]+ye[e>>8*r&15];return t}function ge(e,t){return e+t&4294967295}const pe=M.getWebCrypto(),de=M.getNodeCrypto(),Ae=de&&de.getHashes();function we(e){if(de&&Ae.includes(e))return async function(t){const r=de.createHash(e);return k(t,(e=>{r.update(e)}),(()=>new Uint8Array(r.digest())))}}function me(e,t){const r=async()=>{const{nobleHashes:t}=await Promise.resolve().then((function(){return Wl})),r=t.get(e);if(!r)throw Error("Unsupported hash");return r};return async function(e){if(o(e)&&(e=await C(e)),M.isStream(e)){const t=(await r()).create();return k(e,(e=>{t.update(e)}),(()=>t.digest()))}if(pe&&t)return new Uint8Array(await pe.digest(t,e));return(await r())(e)}}var be={md5:we("md5")||async function(e){const t=function(e){const t=e.length,r=[1732584193,-271733879,-1732584194,271733878];let n;for(n=64;n<=e.length;n+=64)se(r,le(e.substring(n-64,n)));e=e.substring(n-64);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(se(r,i),n=0;n<16;n++)i[n]=0;return i[14]=8*t,se(r,i),r}(M.uint8ArrayToString(e));return M.hexToUint8Array(function(e){for(let t=0;t0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function ve(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Be(e,t){Ee(e);const r=t.outputLen;if(e.lengthnew Uint8Array(e.buffer,e.byteOffset,e.byteLength),Se=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ke=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw Error("Non little-endian hardware is not supported");function Ce(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!ke(e))throw Error("Uint8Array expected, got "+typeof e);e=Qe(e)}return e}function De(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t);function Ue(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(r>>i&s),o=Number(r&s);e.setUint32(t+0,a,n),e.setUint32(t+4,o,n)}function xe(e){return e.byteOffset%4==0}function Qe(e){return Uint8Array.from(e)}function Re(...e){for(let t=0;t(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Fe{constructor(e,t){this.blockLen=Le,this.outputLen=Le,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Ee(e=Ce(e),16);const r=Ke(e);let n=r.getUint32(0,!1),i=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:Ne(n),s1:Ne(i),s2:Ne(s),s3:Ne(a)}),({s0:n,s1:i,s2:s,s3:a}={s3:(u=s)<<31|(l=a)>>>1,s2:(h=i)<<31|u>>>1,s1:(c=n)<<31|h>>>1,s0:c>>>1^225<<24&-(1&l)});var c,h,u,l;const y=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(y))throw Error(`ghash: wrong window size=${y}, should be 2, 4 or 8`);this.W=y;const f=128/y,g=this.windowSize=2**y,p=[];for(let e=0;e>>y-a-1&1))continue;const{s0:c,s1:h,s2:u,s3:l}=o[y*e+a];r^=c,n^=h,i^=u,s^=l}p.push({s0:r,s1:n,s2:i,s3:s})}this.t=p}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:i,t:s,windowSize:a}=this;let o=0,c=0,h=0,u=0;const l=(1<>>8*e&255;for(let e=8/i-1;e>=0;e--){const r=t>>>i*e&l,{s0:n,s1:f,s2:g,s3:p}=s[y*a+r];o^=n,c^=f,h^=g,u^=p,y+=1}}this.s0=o,this.s1=c,this.s2=h,this.s3=u}update(e){e=Ce(e),ve(this);const t=Se(e),r=Math.floor(e.length/Le),n=e.length%Le;for(let e=0;e>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Qe(e=Ce(e)));super(r,t),Re(r)}update(e){e=Ce(e),ve(this);const t=Se(e),r=e.length%Le,n=Math.floor(e.length/Le);for(let e=0;ee(r,t.length).update(Ce(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const ze=Oe(((e,t)=>new Fe(e,t)));Oe(((e,t)=>new He(e,t)));const _e=16,Ge=new Uint8Array(_e),je=283;function qe(e){return e<<1^je&-(e>>7)}function Ve(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=qe(e);return r}const Je=/* @__PURE__ */(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=qe(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Re(e),t})(),Ye=/* @__PURE__ */Je.map(((e,t)=>Je.indexOf(t))),We=e=>e<<24|e>>>8,Ze=e=>e<<8|e>>>24,$e=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function Xe(e,t){if(256!==e.length)throw Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,n)=>t(e[n]))),n=r.map(Ze),i=n.map(Ze),s=i.map(Ze),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let h=0;h<256;h++){const u=256*t+h;a[u]=r[t]^n[h],o[u]=i[t]^s[h],c[u]=e[t]<<8|e[h]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:i,T3:s,T01:a,T23:o}}const et=/* @__PURE__ */Xe(Je,(e=>Ve(e,3)<<24|e<<16|e<<8|Ve(e,2))),tt=/* @__PURE__ */Xe(Ye,(e=>Ve(e,11)<<24|Ve(e,13)<<16|Ve(e,9)<<8|Ve(e,14))),rt=/* @__PURE__ */(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=qe(r))e[t]=r;return e})();function nt(e){Ee(e);const t=e.length;if(![16,24,32].includes(t))throw Error("aes: wrong key size: should be 16, 24 or 32, got: "+t);const{sbox2:r}=et,n=[];xe(e)||n.push(e=Qe(e));const i=Se(e),s=i.length,a=e=>at(r,e,e,e,e),o=new Uint32Array(t+28);o.set(i);for(let e=s;e6&&e%s==4&&(t=a(t)),o[e]=o[e-s]^t}return Re(...n),o}function it(e){const t=nt(e),r=t.slice(),n=t.length,{sbox2:i}=et,{T0:s,T1:a,T2:o,T3:c}=tt;for(let e=0;e>>8&255]^o[n>>>16&255]^c[n>>>24]}return r}function st(e,t,r,n,i,s){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|s>>>24&255]}function at(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function ot(e,t,r,n,i){const{sbox2:s,T01:a,T23:o}=et;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],i^=e[c++];const h=e.length/4-2;for(let s=0;s=0;e--)r=r+(255&s[e])|0,s[e]=255&r,r>>>=8;({s0:o,s1:c,s2:h,s3:u}=ot(e,a[0],a[1],a[2],a[3]))}const f=_e*Math.floor(l.length/4);if(f>>0,o.setUint32(u,y,t),({s0:f,s1:g,s2:p,s3:d}=ot(e,a[0],a[1],a[2],a[3]));const A=_e*Math.floor(c.length/4);if(Ar(e,t),decrypt:(e,t)=>r(e,t)}}));const ft=Pe({blockSize:16,nonceLength:16},(function(e,t,r={}){Ee(e),Ee(t,16);const n=!r.disablePadding;return{encrypt(r,i){const s=nt(e),{b:a,o,out:c}=function(e,t,r){Ee(e);let n=e.length;const i=n%_e;if(!t&&0!==i)throw Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");xe(e)||(e=Qe(e));const s=Se(e);if(t){let e=_e-i;e||(e=_e),n+=e}const a=ht(n,r);return{b:s,o:Se(a),out:a}}(r,n,i);let h=t;const u=[s];xe(h)||u.push(h=Qe(h));const l=Se(h);let y=l[0],f=l[1],g=l[2],p=l[3],d=0;for(;d+4<=a.length;)y^=a[d+0],f^=a[d+1],g^=a[d+2],p^=a[d+3],({s0:y,s1:f,s2:g,s3:p}=ot(s,y,f,g,p)),o[d++]=y,o[d++]=f,o[d++]=g,o[d++]=p;if(n){const e=function(e){const t=new Uint8Array(16),r=Se(t);t.set(e);const n=_e-e.length;for(let e=_e-n;e<_e;e++)t[e]=n;return r}(r.subarray(4*d));y^=e[0],f^=e[1],g^=e[2],p^=e[3],({s0:y,s1:f,s2:g,s3:p}=ot(s,y,f,g,p)),o[d++]=y,o[d++]=f,o[d++]=g,o[d++]=p}return Re(...u),c},decrypt(r,i){!function(e){if(Ee(e),e.length%_e!=0)throw Error("aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const s=it(e);let a=t;const o=[s];xe(a)||o.push(a=Qe(a));const c=Se(a),h=ht(r.length,i);xe(r)||o.push(r=Qe(r));const u=Se(r),l=Se(h);let y=c[0],f=c[1],g=c[2],p=c[3];for(let e=0;e+4<=u.length;){const t=y,r=f,n=g,i=p;y=u[e+0],f=u[e+1],g=u[e+2],p=u[e+3];const{s0:a,s1:o,s2:c,s3:h}=ct(s,y,f,g,p);l[e++]=a^t,l[e++]=o^r,l[e++]=c^n,l[e++]=h^i}return Re(...o),function(e,t){if(!t)return e;const r=e.length;if(!r)throw Error("aes/pcks5: empty ciphertext not allowed");const n=e[r-1];if(n<=0||n>16)throw Error("aes/pcks5: wrong padding");const i=e.subarray(0,-n);for(let t=0;tr(e,!0,t),decrypt:(e,t)=>r(e,!1,t)}}));const pt=Pe({blockSize:16,nonceLength:12,tagLength:16},(function(e,t,r){if(Ee(e),Ee(t),void 0!==r&&Ee(r),t.length<8)throw Error("aes/gcm: invalid nonce length");const n=16;function i(e,t,n){const i=function(e,t,r,n,i){const s=null==i?0:i.length,a=e.create(r,n.length+s);i&&a.update(i),a.update(n);const o=new Uint8Array(16),c=Ke(o);i&&Ue(c,0,BigInt(8*s),t),Ue(c,8,BigInt(8*n.length),t),a.update(o);const h=a.digest();return Re(o),h}(ze,!1,e,n,r);for(let e=0;e=2**32)throw Error("plaintext should be less than 4gb");const r=nt(e);if(16===t.length)At(r,t);else{const e=Se(t);let n=e[0],i=e[1];for(let t=0,s=1;t<6;t++)for(let t=2;t=2**32)throw Error("ciphertext should be less than 4gb");const r=it(e),n=t.length/8-1;if(1===n)wt(r,t);else{const e=Se(t);let i=e[0],s=e[1];for(let t=0,a=6*n;t<6;t++)for(let t=2*n;t>=1;t-=2,a--){s^=$e(a);const{s0:n,s1:o,s2:c,s3:h}=ct(r,i,s,e[t],e[t+1]);i=n,s=o,e[t]=c,e[t+1]=h}e[0]=i,e[1]=s}r.fill(0)}},bt=new Uint8Array(8).fill(166),kt=Pe({blockSize:8},(e=>({encrypt(t){if(Ee(t),!t.length||t.length%8!=0)throw Error("invalid plaintext length");if(8===t.length)throw Error("8-byte keys not allowed in AESKW, use AESKWP instead");const r=function(...e){let t=0;for(let r=0;r!0),(()=>!1))}async _runCBC(e,t){const r="AES-CBC";this.keyRef=this.keyRef||await vt.importKey("raw",this.key,r,!1,["encrypt"]);const n=await vt.encrypt({name:r,iv:t||this.zeroBlock},this.keyRef,e);return new Uint8Array(n).subarray(0,e.length)}async encryptChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=M.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=M.concatUint8Array([this.prevBlock,n.subarray(0,n.length-this.blockSize)]),s=await this._runCBC(i);return Dt(s,n),this.prevBlock=s.slice(-this.blockSize),r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,s}let n;if(this.i+=r.length,this.i===this.nextBlock.length){const t=this.nextBlock;n=await this._runCBC(this.prevBlock),Dt(n,t),this.prevBlock=n.slice(),this.i=0;const i=e.subarray(r.length);this.nextBlock.set(i,this.i),this.i+=i.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{this.nextBlock=this.nextBlock.subarray(0,this.i);const t=this.nextBlock,r=await this._runCBC(this.prevBlock);Dt(r,t),e=r.subarray(0,t.length)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.keyRef=null,this.key=null}async encrypt(e){const t=(await this._runCBC(M.concatUint8Array([new Uint8Array(this.blockSize),e]),this.iv)).subarray(0,e.length);return Dt(t,e),this.clearSensitiveData(),t}}class Ct{constructor(e,t,r,n){this.forEncryption=e;const{blockSize:i}=ne(t);this.key=Et.expandKeyLE(r),n.byteOffset%4!=0&&(n=n.slice()),this.prevBlock=Pt(n),this.nextBlock=new Uint8Array(i),this.i=0,this.blockSize=i}_runCFB(e){const t=Pt(e),r=new Uint8Array(e.length),n=Pt(r);for(let e=0;e+4<=n.length;e+=4){const{s0:r,s1:i,s2:s,s3:a}=Et.encrypt(this.key,this.prevBlock[0],this.prevBlock[1],this.prevBlock[2],this.prevBlock[3]);n[e+0]=t[e+0]^r,n[e+1]=t[e+1]^i,n[e+2]=t[e+2]^s,n[e+3]=t[e+3]^a,this.prevBlock=(this.forEncryption?n:t).slice(e,e+4)}return r}async processChunk(e){const t=this.nextBlock.length-this.i,r=e.subarray(0,t);if(this.nextBlock.set(r,this.i),this.i+e.length>=2*this.blockSize){const r=(e.length-t)%this.blockSize,n=M.concatUint8Array([this.nextBlock,e.subarray(t,e.length-r)]),i=this._runCFB(n);return r>0&&this.nextBlock.set(e.subarray(-r)),this.i=r,i}let n;if(this.i+=r.length,this.i===this.nextBlock.length){n=this._runCFB(this.nextBlock),this.i=0;const t=e.subarray(r.length);this.nextBlock.set(t,this.i),this.i+=t.length}else n=new Uint8Array;return n}async finish(){let e;if(0===this.i)e=new Uint8Array;else{e=this._runCFB(this.nextBlock).subarray(0,this.i)}return this.clearSensitiveData(),e}clearSensitiveData(){this.nextBlock.fill(0),this.prevBlock.fill(0),this.key.fill(0)}}function Dt(e,t){const r=Math.min(e.length,t.length);for(let n=0;nnew Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));var Ut=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n){const i=R.read(R.symmetric,e);if(Bt&&St[i])return function(e,t,r,n){const i=R.read(R.symmetric,e),s=new Bt.createDecipheriv(St[i],t,n);return k(r,(e=>new Uint8Array(s.update(e))))}(e,t,r,n);if(M.isAES(e))return async function(e,t,r,n){if(M.isStream(r)){const i=new Ct(!1,e,t,n);return k(r,(e=>i.processChunk(e)),(()=>i.finish()))}return gt(t,n).decrypt(r)}(e,t,r,n);const s=new(await ee(e))(t),a=s.blockSize;let o=n,c=new Uint8Array;const h=e=>{e&&(c=M.concatUint8Array([c,e]));const t=new Uint8Array(c.length);let r,n=0;for(;e?c.length>=a:c.length;){const e=s.encrypt(o);for(o=c.subarray(0,a),r=0;rnew Uint8Array(s.update(e))))}(e,t,r,n);if(M.isAES(e))return async function(e,t,r,n){if(vt&&await Kt.isSupported(e)){const i=new Kt(e,t,n);return M.isStream(r)?k(r,(e=>i.encryptChunk(e)),(()=>i.finish())):i.encrypt(r)}if(M.isStream(r)){const i=new Ct(!0,e,t,n);return k(r,(e=>i.processChunk(e)),(()=>i.finish()))}return gt(t,n).encrypt(r)}(e,t,r,n);const a=new(await ee(e))(t),o=a.blockSize,c=n.slice();let h=new Uint8Array;const u=e=>{e&&(h=M.concatUint8Array([h,e]));const t=new Uint8Array(h.length);let r,n=0;for(;e?h.length>=o:h.length;){const e=a.encrypt(c);for(r=0;ri.encrypt(e),a=e=>i.decrypt(e);let o;function c(e,t,r,i){const a=t.length/Zt|0;!function(e,t){const r=M.nbits(Math.max(e.length,t.length)/Zt|0)-1;for(let e=n+1;e<=r;e++)o[e]=M.double(o[e-1]);n=r}(t,i);const c=M.concatUint8Array([rr.subarray(0,15-r.length),nr,r]),h=63&c[15];c[15]&=192;const u=s(c),l=M.concatUint8Array([u,tr(u.subarray(0,8),u.subarray(1,9))]),y=M.shiftRight(l.subarray(0+(h>>3),17+(h>>3)),8-(7&h)).subarray(1),f=new Uint8Array(Zt),g=new Uint8Array(t.length+$t);let p,d=0;for(p=0;p{r+=t[e>>4]+t[15&e]})),BigInt("0x0"+r)}function pr(e,t){const r=e%t;return ryr;){const e=n&fr;n>>=fr;s=e?s*i%r:s,i=i*i%r}return s}function Ar(e){return e>=yr?e:-e}function wr(e,t){const{gcd:r,x:n}=function(e,t){let r=BigInt(0),n=BigInt(1),i=BigInt(1),s=BigInt(0),a=Ar(e),o=Ar(t);const c=eNumber.MAX_SAFE_INTEGER)throw Error("Number can only safely store up to 53 bits");return t}function br(e,t){return(e>>BigInt(t)&fr)===yr?0:1}function kr(e){const t=e>=fr)!==t;)r++;return r}function Er(e){const t=e>=r)!==t;)n++;return n}function vr(e,t="be",r){let n=e.toString(16);n.length%2==1&&(n="0"+n);const i=n.length/2,s=new Uint8Array(r||i),a=r?r-i:0;let o=0;for(;oe&&(a=pr(a,i<pr(e,r)!==t))}(e)&&(!!function(e,t=BigInt(2)){return dr(t,e-Cr,e)===Cr}(e)&&!!function(e,t){const r=kr(e);t||(t=Math.max(1,r/48|0));const n=e-Cr;let i=0;for(;!br(n,i);)i++;const s=e>>BigInt(i);for(;t>0;t--){let t,r=dr(Sr(BigInt(2),n),s,e);if(r!==Cr&&r!==n){for(t=1;tBigInt(e)));const xr=[];function Qr(e,t){const r=e.length;if(r>t-11)throw Error("Message too long");const n=function(e){const t=new Uint8Array(e);let r=0;for(;r=8&!n;if(t)return M.selectUint8Array(a,s,t);if(a)return s;throw Error("Decryption error")}function Lr(e,t,r){let n;if(t.length!==be.getHashByteLength(e))throw Error("Invalid hash length");const i=new Uint8Array(xr[e].length);for(n=0;n=t)throw Error("Data too large.");const c=pr(n,s-Fr),h=pr(n,i-Fr),u=Sr(BigInt(2),t),l=dr(wr(u,t),r,t);e=pr(e*l,t);const y=dr(e,h,i),f=dr(e,c,s),g=pr(a*(f-y),s);let p=g*i+y;return p=pr(p*u,t),Rr(vr(p,"be",Er(t)),o)}(e,t,r,n,i,s,a,o)},encrypt:async function(e,t,r){return M.getNodeCrypto()?async function(e,t,r){const n=Or(t,r),i={key:n,format:"jwk",type:"pkcs1",padding:Nr.constants.RSA_PKCS1_PADDING};return new Uint8Array(Nr.publicEncrypt(i,e))}(e,t,r):async function(e,t,r){if(t=gr(t),e=gr(Qr(e,Er(t))),r=gr(r),e>=t)throw Error("Message size cannot exceed modulus size");return vr(dr(e,r,t),"be",Er(t))}(e,t,r)},generate:async function(e,t){if(t=BigInt(t),M.getWebCrypto()){const r={name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:vr(t),hash:{name:"SHA-1"}},n=await Mr.generateKey(r,!0,["sign","verify"]);return zr(await Mr.exportKey("jwk",n.privateKey),t)}if(M.getNodeCrypto()){const r={modulusLength:e,publicExponent:mr(t),publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}},n=await new Promise(((e,t)=>{Nr.generateKeyPair("rsa",r,((r,n,i)=>{r?t(r):e(i)}))}));return zr(n,t)}let r,n,i;do{n=Dr(e-(e>>1),t,40),r=Dr(e>>1,t,40),i=r*n}while(kr(i)!==e);const s=(r-Fr)*(n-Fr);return n=r.length)throw Error("Digest size cannot exceed key modulus size");if(t&&!M.isStream(t))if(M.getWebCrypto())try{return await async function(e,t,r,n,i,s,a,o){const c=await Hr(r,n,i,s,a,o),h={name:"RSASSA-PKCS1-v1_5",hash:{name:e}},u=await Mr.importKey("jwk",c,h,!1,["sign"]);return new Uint8Array(await Mr.sign("RSASSA-PKCS1-v1_5",u,t))}(R.read(R.webHash,e),t,r,n,i,s,a,o)}catch(e){M.printDebugError(e)}else if(M.getNodeCrypto())return async function(e,t,r,n,i,s,a,o){const c=Nr.createSign(R.read(R.hash,e));c.write(t),c.end();const h=await Hr(r,n,i,s,a,o);return new Uint8Array(c.sign({key:h,format:"jwk",type:"pkcs1"}))}(e,t,r,n,i,s,a,o);return async function(e,t,r,n){t=gr(t);const i=gr(Lr(e,n,Er(t)));return r=gr(r),vr(dr(i,r,t),"be",Er(t))}(e,r,i,c)},validateParams:async function(e,t,r,n,i,s){if(e=gr(e),(n=gr(n))*(i=gr(i))!==e)return!1;const a=BigInt(2);if(pr(n*(s=gr(s)),i)!==BigInt(1))return!1;t=gr(t),r=gr(r);const o=Sr(a,a<=r)throw Error("Signature size cannot exceed modulus size");const s=vr(dr(t,n,r),"be",Er(r)),a=Lr(e,i,Er(r));return M.equalsUint8Array(s,a)}(e,r,n,i,s)}});const Gr=BigInt(1);var jr=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i){return e=gr(e),t=gr(t),r=gr(r),Rr(vr(pr(wr(dr(e,n=gr(n),r),r)*t,r),"be",Er(r)),i)},encrypt:async function(e,t,r,n){t=gr(t),r=gr(r),n=gr(n);const i=gr(Qr(e,Er(t))),s=Sr(Gr,t-Gr);return{c1:vr(dr(r,s,t)),c2:vr(pr(dr(n,s,t)*i,t))}},validateParams:async function(e,t,r,n){if(e=gr(e),t=gr(t),r=gr(r),t<=Gr||t>=e)return!1;const i=BigInt(kr(e));if(i>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function on(e,t,r,n){return function(e,t,r,n,i){var s,a=0;for(s=0;s>>8)-1}(e,t,r,n,32)}function cn(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function hn(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function un(e,t,r){for(var n,i=~(r-1),s=0;s<16;s++)n=i&(e[s]^t[s]),e[s]^=n,t[s]^=n}function ln(e,t){var r,n,i,s=Jr(),a=Jr();for(r=0;r<16;r++)a[r]=t[r];for(hn(a),hn(a),hn(a),n=0;n<2;n++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,un(a,s,1-i)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function yn(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return ln(r,e),ln(n,t),on(r,0,n,0)}function fn(e){var t=new Uint8Array(32);return ln(t,e),1&t[0]}function gn(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function pn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function dn(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function An(e,t,r){var n,i,s=0,a=0,o=0,c=0,h=0,u=0,l=0,y=0,f=0,g=0,p=0,d=0,A=0,w=0,m=0,b=0,k=0,E=0,v=0,B=0,I=0,S=0,K=0,C=0,D=0,P=0,U=0,x=0,Q=0,R=0,L=0,T=r[0],M=r[1],N=r[2],F=r[3],H=r[4],O=r[5],z=r[6],_=r[7],G=r[8],j=r[9],q=r[10],V=r[11],J=r[12],Y=r[13],W=r[14],Z=r[15];s+=(n=t[0])*T,a+=n*M,o+=n*N,c+=n*F,h+=n*H,u+=n*O,l+=n*z,y+=n*_,f+=n*G,g+=n*j,p+=n*q,d+=n*V,A+=n*J,w+=n*Y,m+=n*W,b+=n*Z,a+=(n=t[1])*T,o+=n*M,c+=n*N,h+=n*F,u+=n*H,l+=n*O,y+=n*z,f+=n*_,g+=n*G,p+=n*j,d+=n*q,A+=n*V,w+=n*J,m+=n*Y,b+=n*W,k+=n*Z,o+=(n=t[2])*T,c+=n*M,h+=n*N,u+=n*F,l+=n*H,y+=n*O,f+=n*z,g+=n*_,p+=n*G,d+=n*j,A+=n*q,w+=n*V,m+=n*J,b+=n*Y,k+=n*W,E+=n*Z,c+=(n=t[3])*T,h+=n*M,u+=n*N,l+=n*F,y+=n*H,f+=n*O,g+=n*z,p+=n*_,d+=n*G,A+=n*j,w+=n*q,m+=n*V,b+=n*J,k+=n*Y,E+=n*W,v+=n*Z,h+=(n=t[4])*T,u+=n*M,l+=n*N,y+=n*F,f+=n*H,g+=n*O,p+=n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*Z,w+=(n=t[13])*T,m+=n*M,b+=n*N,k+=n*F,E+=n*H,v+=n*O,B+=n*z,I+=n*_,S+=n*G,K+=n*j,C+=n*q,D+=n*V,P+=n*J,U+=n*Y,x+=n*W,Q+=n*Z,m+=(n=t[14])*T,b+=n*M,k+=n*N,E+=n*F,v+=n*H,B+=n*O,I+=n*z,S+=n*_,K+=n*G,C+=n*j,D+=n*q,P+=n*V,U+=n*J,x+=n*Y,Q+=n*W,R+=n*Z,b+=(n=t[15])*T,a+=38*(E+=n*N),o+=38*(v+=n*F),c+=38*(B+=n*H),h+=38*(I+=n*O),u+=38*(S+=n*z),l+=38*(K+=n*_),y+=38*(C+=n*G),f+=38*(D+=n*j),g+=38*(P+=n*q),p+=38*(U+=n*V),d+=38*(x+=n*J),A+=38*(Q+=n*Y),w+=38*(R+=n*W),m+=38*(L+=n*Z),s=(n=(s+=38*(k+=n*M))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=(s+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=o+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),A=(n=A+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=c,e[4]=h,e[5]=u,e[6]=l,e[7]=y,e[8]=f,e[9]=g,e[10]=p,e[11]=d,e[12]=A,e[13]=w,e[14]=m,e[15]=b}function wn(e,t){An(e,t,t)}function mn(e,t){var r,n=Jr();for(r=0;r<16;r++)n[r]=t[r];for(r=253;r>=0;r--)wn(n,n),2!==r&&4!==r&&An(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}function bn(e,t,r){var n,i,s=new Uint8Array(32),a=new Float64Array(80),o=Jr(),c=Jr(),h=Jr(),u=Jr(),l=Jr(),y=Jr();for(i=0;i<31;i++)s[i]=t[i];for(s[31]=127&t[31]|64,s[0]&=248,gn(a,r),i=0;i<16;i++)c[i]=a[i],u[i]=o[i]=h[i]=0;for(o[0]=u[0]=1,i=254;i>=0;--i)un(o,c,n=s[i>>>3]>>>(7&i)&1),un(h,u,n),pn(l,o,h),dn(o,o,h),pn(h,c,u),dn(c,c,u),wn(u,l),wn(y,o),An(o,h,o),An(h,c,l),pn(l,o,h),dn(o,o,h),wn(c,o),dn(h,u,y),An(o,h,Xr),pn(o,o,u),An(h,h,o),An(o,u,y),An(u,c,a),wn(c,l),un(o,c,n),un(h,u,n);for(i=0;i<16;i++)a[i+16]=o[i],a[i+32]=h[i],a[i+48]=c[i],a[i+64]=u[i];var f=a.subarray(32),g=a.subarray(16);return mn(f,f),An(g,g,f),ln(e,g),0}function kn(e,t){return bn(e,t,Wr)}var En=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function vn(e,t,r,n){for(var i,s,a,o,c,h,u,l,y,f,g,p,d,A,w,m,b,k,E,v,B,I,S,K,C,D,P=new Int32Array(16),U=new Int32Array(16),x=e[0],Q=e[1],R=e[2],L=e[3],T=e[4],M=e[5],N=e[6],F=e[7],H=t[0],O=t[1],z=t[2],_=t[3],G=t[4],j=t[5],q=t[6],V=t[7],J=0;n>=128;){for(E=0;E<16;E++)v=8*E+J,P[E]=r[v+0]<<24|r[v+1]<<16|r[v+2]<<8|r[v+3],U[E]=r[v+4]<<24|r[v+5]<<16|r[v+6]<<8|r[v+7];for(E=0;E<80;E++)if(i=x,s=Q,a=R,o=L,c=T,h=M,u=N,F,y=H,f=O,g=z,p=_,d=G,A=j,w=q,V,S=65535&(I=V),K=I>>>16,C=65535&(B=F),D=B>>>16,S+=65535&(I=(G>>>14|T<<18)^(G>>>18|T<<14)^(T>>>9|G<<23)),K+=I>>>16,C+=65535&(B=(T>>>14|G<<18)^(T>>>18|G<<14)^(G>>>9|T<<23)),D+=B>>>16,S+=65535&(I=G&j^~G&q),K+=I>>>16,C+=65535&(B=T&M^~T&N),D+=B>>>16,B=En[2*E],S+=65535&(I=En[2*E+1]),K+=I>>>16,C+=65535&B,D+=B>>>16,B=P[E%16],K+=(I=U[E%16])>>>16,C+=65535&B,D+=B>>>16,C+=(K+=(S+=65535&I)>>>16)>>>16,S=65535&(I=k=65535&S|K<<16),K=I>>>16,C=65535&(B=b=65535&C|(D+=C>>>16)<<16),D=B>>>16,S+=65535&(I=(H>>>28|x<<4)^(x>>>2|H<<30)^(x>>>7|H<<25)),K+=I>>>16,C+=65535&(B=(x>>>28|H<<4)^(H>>>2|x<<30)^(H>>>7|x<<25)),D+=B>>>16,K+=(I=H&O^H&z^O&z)>>>16,C+=65535&(B=x&Q^x&R^Q&R),D+=B>>>16,l=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(D+=C>>>16)<<16,m=65535&S|K<<16,S=65535&(I=p),K=I>>>16,C=65535&(B=o),D=B>>>16,K+=(I=k)>>>16,C+=65535&(B=b),D+=B>>>16,Q=i,R=s,L=a,T=o=65535&(C+=(K+=(S+=65535&I)>>>16)>>>16)|(D+=C>>>16)<<16,M=c,N=h,F=u,x=l,O=y,z=f,_=g,G=p=65535&S|K<<16,j=d,q=A,V=w,H=m,E%16==15)for(v=0;v<16;v++)B=P[v],S=65535&(I=U[v]),K=I>>>16,C=65535&B,D=B>>>16,B=P[(v+9)%16],S+=65535&(I=U[(v+9)%16]),K+=I>>>16,C+=65535&B,D+=B>>>16,b=P[(v+1)%16],S+=65535&(I=((k=U[(v+1)%16])>>>1|b<<31)^(k>>>8|b<<24)^(k>>>7|b<<25)),K+=I>>>16,C+=65535&(B=(b>>>1|k<<31)^(b>>>8|k<<24)^b>>>7),D+=B>>>16,b=P[(v+14)%16],K+=(I=((k=U[(v+14)%16])>>>19|b<<13)^(b>>>29|k<<3)^(k>>>6|b<<26))>>>16,C+=65535&(B=(b>>>19|k<<13)^(k>>>29|b<<3)^b>>>6),D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,P[v]=65535&C|D<<16,U[v]=65535&S|K<<16;S=65535&(I=H),K=I>>>16,C=65535&(B=x),D=B>>>16,B=e[0],K+=(I=t[0])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[0]=x=65535&C|D<<16,t[0]=H=65535&S|K<<16,S=65535&(I=O),K=I>>>16,C=65535&(B=Q),D=B>>>16,B=e[1],K+=(I=t[1])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[1]=Q=65535&C|D<<16,t[1]=O=65535&S|K<<16,S=65535&(I=z),K=I>>>16,C=65535&(B=R),D=B>>>16,B=e[2],K+=(I=t[2])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[2]=R=65535&C|D<<16,t[2]=z=65535&S|K<<16,S=65535&(I=_),K=I>>>16,C=65535&(B=L),D=B>>>16,B=e[3],K+=(I=t[3])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[3]=L=65535&C|D<<16,t[3]=_=65535&S|K<<16,S=65535&(I=G),K=I>>>16,C=65535&(B=T),D=B>>>16,B=e[4],K+=(I=t[4])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[4]=T=65535&C|D<<16,t[4]=G=65535&S|K<<16,S=65535&(I=j),K=I>>>16,C=65535&(B=M),D=B>>>16,B=e[5],K+=(I=t[5])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[5]=M=65535&C|D<<16,t[5]=j=65535&S|K<<16,S=65535&(I=q),K=I>>>16,C=65535&(B=N),D=B>>>16,B=e[6],K+=(I=t[6])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[6]=N=65535&C|D<<16,t[6]=q=65535&S|K<<16,S=65535&(I=V),K=I>>>16,C=65535&(B=F),D=B>>>16,B=e[7],K+=(I=t[7])>>>16,C+=65535&B,D+=B>>>16,D+=(C+=(K+=(S+=65535&I)>>>16)>>>16)>>>16,e[7]=F=65535&C|D<<16,t[7]=V=65535&S|K<<16,J+=128,n-=128}return n}function Bn(e,t,r){var n,i=new Int32Array(8),s=new Int32Array(8),a=new Uint8Array(256),o=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,s[0]=4089235720,s[1]=2227873595,s[2]=4271175723,s[3]=1595750129,s[4]=2917565137,s[5]=725511199,s[6]=4215389547,s[7]=327033209,vn(i,s,t,r),r%=128,n=0;n=0;--i)Sn(e,t,n=r[i/8|0]>>(7&i)&1),In(t,e),In(e,e),Sn(e,t,n)}function Dn(e,t){var r=[Jr(),Jr(),Jr(),Jr()];cn(r[0],rn),cn(r[1],nn),cn(r[2],$r),An(r[3],rn,nn),Cn(e,r,t)}function Pn(e,t,r){var n,i=new Uint8Array(64),s=[Jr(),Jr(),Jr(),Jr()];for(r||Yr(t,32),Bn(i,t,32),i[0]&=248,i[31]&=127,i[31]|=64,Dn(s,i),Kn(e,s),n=0;n<32;n++)t[n+32]=e[n];return 0}var Un=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function xn(e,t){var r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*Un[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*Un[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function Qn(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;xn(e,r)}function Rn(e,t){var r=Jr(),n=Jr(),i=Jr(),s=Jr(),a=Jr(),o=Jr(),c=Jr();return cn(e[2],$r),gn(e[1],t),wn(i,e[1]),An(s,i,en),dn(i,i,e[2]),pn(s,e[2],s),wn(a,s),wn(o,a),An(c,o,a),An(r,c,i),An(r,r,s),function(e,t){var r,n=Jr();for(r=0;r<16;r++)n[r]=t[r];for(r=250;r>=0;r--)wn(n,n),1!==r&&An(n,n,t);for(r=0;r<16;r++)e[r]=n[r]}(r,r),An(r,r,i),An(r,r,s),An(r,r,s),An(e[0],r,s),wn(n,e[0]),An(n,n,s),yn(n,i)&&An(e[0],e[0],sn),wn(n,e[0]),An(n,n,s),yn(n,i)?-1:(fn(e[0])===t[31]>>7&&dn(e[0],Zr,e[0]),An(e[3],e[0],e[1]),0)}var Ln=64;function Tn(){for(var e=0;e=0},Vr.sign.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(64);return Pn(e,t),{publicKey:e,secretKey:t}},Vr.sign.keyPair.fromSecretKey=function(e){if(Tn(e),64!==e.length)throw Error("bad secret key size");for(var t=new Uint8Array(32),r=0;r=1){const t=e[0];if(e.length>=1+t)return this.oid=e.subarray(1,1+t),1+this.oid.length}throw Error("Invalid oid")}write(){return M.concatUint8Array([new Uint8Array([this.oid.length]),this.oid])}toHex(){return M.uint8ArrayToHex(this.oid)}getName(){const e=Mn[this.toHex()];if(!e)throw Error("Unknown curve object identifier.");return e}}function Fn(e){let t,r=0;const n=e[0];return n<192?([r]=e,t=1):n<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===n&&(r=M.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}}function Hn(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):M.concatUint8Array([new Uint8Array([255]),M.writeNumber(e,4)])}function On(e){if(e<0||e>30)throw Error("Partial Length power must be between 1 and 30");return new Uint8Array([224+e])}function zn(e){return new Uint8Array([192|e])}function _n(e,t){return M.concatUint8Array([zn(e),Hn(t)])}function Gn(e){return[R.packet.literalData,R.packet.compressedData,R.packet.symmetricallyEncryptedData,R.packet.symEncryptedIntegrityProtectedData,R.packet.aeadEncryptedData].includes(e)}async function jn(e,t){const r=U(e);let n,i;try{const s=await r.peekBytes(2);if(!s||s.length<2||!(128&s[0]))throw Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");const o=await r.readByte();let c,h,u=-1,l=-1;l=0,64&o&&(l=1),l?u=63&o:(u=(63&o)>>2,h=3&o);const y=Gn(u);let f,g=null;if(y){if("array"===M.isStream(e)){const e=new a;n=x(e),g=e}else{const e=new TransformStream;n=x(e.writable),g=e.readable}i=t({tag:u,packet:g})}else g=[];do{if(l){const e=await r.readByte();if(f=!1,e<192)c=e;else if(e>=192&&e<224)c=(e-192<<8)+await r.readByte()+192;else if(e>223&&e<255){if(c=1<<(31&e),f=!0,!y)throw new TypeError("This packet type does not support partial lengths.")}else c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte()}else switch(h){case 0:c=await r.readByte();break;case 1:c=await r.readByte()<<8|await r.readByte();break;case 2:c=await r.readByte()<<24|await r.readByte()<<16|await r.readByte()<<8|await r.readByte();break;default:c=1/0}if(c>0){let e=0;for(;;){n&&await n.ready;const{done:t,value:i}=await r.read();if(t){if(c===1/0)break;throw Error("Unexpected end of packet")}const s=c===1/0?i:i.subarray(0,c-e);if(n?await n.write(s):g.push(s),e+=i.length,e>=c){r.unshift(i.subarray(c-e+i.length));break}}}}while(f);const p=await r.peekBytes(y?1/0:2);return n?(await n.ready,await n.close()):(g=M.concatUint8Array(g),await t({tag:u,packet:g})),!p||!p.length}catch(e){if(n)return await n.abort(e),!0;throw e}finally{n&&await i,r.releaseLock()}}class qn extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,qn),this.name="UnsupportedError"}}class Vn extends qn{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,qn),this.name="UnknownPacketError"}}class Jn{constructor(e,t){this.tag=e,this.rawContent=t}write(){return this.rawContent}}async function Yn(e){switch(e){case R.publicKey.ed25519:try{const e=M.getWebCrypto(),t=await e.generateKey("Ed25519",!0,["sign","verify"]),r=await e.exportKey("jwk",t.privateKey),n=await e.exportKey("jwk",t.publicKey);return{A:new Uint8Array(_(n.x)),seed:_(r.d)}}catch(t){if("NotSupportedError"!==t.name&&"OperationError"!==t.name)throw t;const r=Ir($n(e)),{publicKey:n}=Vr.sign.keyPair.fromSeed(r);return{A:n,seed:r}}case R.publicKey.ed448:{const e=await M.getNobleCurve(R.publicKey.ed448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),seed:t}}default:throw Error("Unsupported EdDSA algorithm")}}async function Wn(e,t,r,n,i,s){if(be.getHashByteLength(t){if(e===R.publicKey.ed25519){return{kty:"OKP",crv:"Ed25519",x:G(t),ext:!0}}throw Error("Unsupported EdDSA algorithm")},ti=(e,t,r)=>{if(e===R.publicKey.ed25519){const n=ei(e,t);return n.d=G(r),n}throw Error("Unsupported EdDSA algorithm")};var ri=/*#__PURE__*/Object.freeze({__proto__:null,generate:Yn,getPayloadSize:$n,getPreferredHashAlgo:Xn,sign:Wn,validateParams:async function(e,t,r){switch(e){case R.publicKey.ed25519:{const{publicKey:e}=Vr.sign.keyPair.fromSeed(r);return M.equalsUint8Array(t,e)}case R.publicKey.ed448:{const e=(await M.getNobleCurve(R.publicKey.ed448)).getPublicKey(r);return M.equalsUint8Array(t,e)}default:return!1}},verify:Zn});const ni=M.getWebCrypto();async function ii(e,t,r){const{keySize:n}=ne(e);if(!M.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");try{const e=await ni.importKey("raw",t,{name:"AES-KW"},!1,["wrapKey"]),n=await ni.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!0,["sign"]),i=await ni.wrapKey("raw",n,e,{name:"AES-KW"});return new Uint8Array(i)}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;M.printDebugError("Browser did not support operation: "+e.message)}return kt(t).encrypt(r)}async function si(e,t,r){const{keySize:n}=ne(e);if(!M.isAES(e)||t.length!==n)throw Error("Unexpected algorithm or key size");let i;try{i=await ni.importKey("raw",t,{name:"AES-KW"},!1,["unwrapKey"])}catch(e){if("NotSupportedError"!==e.name&&(24!==t.length||"OperationError"!==e.name))throw e;return M.printDebugError("Browser did not support operation: "+e.message),kt(t).decrypt(r)}try{const e=await ni.unwrapKey("raw",r,i,{name:"AES-KW"},{name:"HMAC",hash:"SHA-256"},!0,["sign"]);return new Uint8Array(await ni.exportKey("raw",e))}catch(e){if("OperationError"===e.name)throw Error("Key Data Integrity failed");throw e}}var ai=/*#__PURE__*/Object.freeze({__proto__:null,unwrap:si,wrap:ii});const oi=M.getWebCrypto();async function ci(e,t,r,n,i){const s=R.read(R.webHash,e);if(!s)throw Error("Hash algo not supported with HKDF");const a=await oi.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=await oi.deriveBits({name:"HKDF",hash:s,salt:r,info:n},a,8*i);return new Uint8Array(o)}const hi={x25519:M.encodeUTF8("OpenPGP X25519"),x448:M.encodeUTF8("OpenPGP X448")};async function ui(e){switch(e){case R.publicKey.x25519:{const e=Ir(32),{publicKey:t}=Vr.box.keyPair.fromSecretKey(e);return{A:t,k:e}}case R.publicKey.x448:{const e=await M.getNobleCurve(R.publicKey.x448),t=e.utils.randomPrivateKey();return{A:e.getPublicKey(t),k:t}}default:throw Error("Unsupported ECDH algorithm")}}function li(e){switch(e){case R.publicKey.x25519:return 32;case R.publicKey.x448:return 56;default:throw Error("Unsupported ECDH algorithm")}}async function yi(e,t){switch(e){case R.publicKey.x25519:{const r=Ir(li(e)),n=Vr.scalarMult(r,t);gi(n);const{publicKey:i}=Vr.box.keyPair.fromSecretKey(r);return{ephemeralPublicKey:i,sharedSecret:n}}case R.publicKey.x448:{const e=await M.getNobleCurve(R.publicKey.x448),r=e.utils.randomPrivateKey(),n=e.getSharedSecret(r,t);gi(n);return{ephemeralPublicKey:e.getPublicKey(r),sharedSecret:n}}default:throw Error("Unsupported ECDH algorithm")}}async function fi(e,t,r,n){switch(e){case R.publicKey.x25519:{const e=Vr.scalarMult(n,t);return gi(e),e}case R.publicKey.x448:{const e=(await M.getNobleCurve(R.publicKey.x448)).getSharedSecret(n,t);return gi(e),e}default:throw Error("Unsupported ECDH algorithm")}}function gi(e){let t=0;for(let r=0;r0===s[0]&&Qi(a,r,s.subarray(1),i);if(n&&!M.isStream(n))switch(a.type){case"web":try{const e=await async function(e,t,{r,s:n},i,s){const a=Ki(e.payloadSize,wi[e.name],s),o=await Di.importKey("jwk",a,{name:"ECDSA",namedCurve:wi[e.name],hash:{name:R.read(R.webHash,e.hash)}},!1,["verify"]),c=M.concatUint8Array([r,n]).buffer;return Di.verify({name:"ECDSA",namedCurve:wi[e.name],hash:{name:R.read(R.webHash,t)}},o,c,i)}(a,t,r,n,i);return e||o()}catch(e){if("nistP521"!==a.name&&("DataError"===e.name||"OperationError"===e.name))throw e;M.printDebugError("Browser did not support verifying: "+e.message)}break;case"node":{const e=await async function(e,t,{r,s:n},i,s){const a=M.nodeRequire("eckey-utils"),o=M.getNodeBuffer(),{publicKey:c}=a.generateDer({curveName:bi[e.name],publicKey:o.from(s)}),h=Pi.createVerify(R.read(R.hash,t));h.write(i),h.end();const u=M.concatUint8Array([r,n]);try{return h.verify({key:c,format:"der",type:"spki",dsaEncoding:"ieee-p1363"},u)}catch(e){return!1}}(a,t,r,n,i);return e||o()}}return await Qi(a,r,s,i)||o()}async function Qi(e,t,r,n){return(await M.getNobleCurve(R.publicKey.ecdsa,e.name)).verify(M.concatUint8Array([t.r,t.s]),r,n,{lowS:!1})}var Ri=/*#__PURE__*/Object.freeze({__proto__:null,sign:Ui,validateParams:async function(e,t,r){const n=new Ei(e);if(n.keyType!==R.publicKey.ecdsa)return!1;switch(n.type){case"web":case"node":{const n=Ir(8),i=R.hash.sha256,s=await be.digest(i,n);try{const a=await Ui(e,i,n,t,r,s);return await xi(e,i,a,n,t,s)}catch(e){return!1}}default:return vi(R.publicKey.ecdsa,e,t,r)}},verify:xi});var Li=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){if(Bi(new Ei(e),n),be.getHashByteLength(t)0){const r=e[t-1];if(r>=1){const n=e.subarray(t-r),i=new Uint8Array(r).fill(r);if(M.equalsUint8Array(n,i))return e.subarray(0,t-r)}}throw Error("Invalid padding")}var Ni=/*#__PURE__*/Object.freeze({__proto__:null,decode:Mi,encode:Ti});const Fi=M.getWebCrypto(),Hi=M.getNodeCrypto();function Oi(e,t,r,n){return M.concatUint8Array([t.write(),new Uint8Array([e]),r.write(),M.stringToUint8Array("Anonymous Sender "),n])}async function zi(e,t,r,n,i=!1,s=!1){let a;if(i){for(a=0;a=0&&0===t[a];a--);t=t.subarray(0,a+1)}return(await be.digest(e,M.concatUint8Array([new Uint8Array([0,0,0,1]),t,n]))).subarray(0,r)}async function _i(e,t){switch(e.type){case"curve25519Legacy":{const{sharedSecret:r,ephemeralPublicKey:n}=await yi(R.publicKey.x25519,t.subarray(1));return{publicKey:M.concatUint8Array([new Uint8Array([e.wireFormatLeadingByte]),n]),sharedKey:r}}case"web":if(e.web&&M.getWebCrypto())try{return await async function(e,t){const r=Ki(e.payloadSize,e.web,t);let n=Fi.generateKey({name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]),i=Fi.importKey("jwk",r,{name:"ECDH",namedCurve:e.web},!1,[]);[n,i]=await Promise.all([n,i]);let s=Fi.deriveBits({name:"ECDH",namedCurve:e.web,public:i},n.privateKey,e.sharedSize),a=Fi.exportKey("jwk",n.publicKey);[s,a]=await Promise.all([s,a]);const o=new Uint8Array(s),c=new Uint8Array(Si(a,e.wireFormatLeadingByte));return{publicKey:c,sharedKey:o}}(e,t)}catch(r){return M.printDebugError(r),qi(e,t)}break;case"node":return async function(e,t){const r=Hi.createECDH(e.node);r.generateKeys();const n=new Uint8Array(r.computeSecret(t)),i=new Uint8Array(r.getPublicKey());return{publicKey:i,sharedKey:n}}(e,t);default:return qi(e,t)}}async function Gi(e,t,r,n){if(n.length!==e.payloadSize){const t=new Uint8Array(e.payloadSize);t.set(n,e.payloadSize-n.length),n=t}switch(e.type){case"curve25519Legacy":{const e=n.slice().reverse();return{secretKey:e,sharedKey:await fi(R.publicKey.x25519,t.subarray(1),r.subarray(1),e)}}case"web":if(e.web&&M.getWebCrypto())try{return await async function(e,t,r,n){const i=Ci(e.payloadSize,e.web,r,n);let s=Fi.importKey("jwk",i,{name:"ECDH",namedCurve:e.web},!0,["deriveKey","deriveBits"]);const a=Ki(e.payloadSize,e.web,t);let o=Fi.importKey("jwk",a,{name:"ECDH",namedCurve:e.web},!0,[]);[s,o]=await Promise.all([s,o]);let c=Fi.deriveBits({name:"ECDH",namedCurve:e.web,public:o},s,e.sharedSize),h=Fi.exportKey("jwk",s);[c,h]=await Promise.all([c,h]);const u=new Uint8Array(c);return{secretKey:_(h.d),sharedKey:u}}(e,t,r,n)}catch(r){return M.printDebugError(r),ji(e,t,n)}break;case"node":return async function(e,t,r){const n=Hi.createECDH(e.node);n.setPrivateKey(r);const i=new Uint8Array(n.computeSecret(t));return{secretKey:new Uint8Array(n.getPrivateKey()),sharedKey:i}}(e,t,n);default:return ji(e,t,n)}}async function ji(e,t,r){return{secretKey:r,sharedKey:(await M.getNobleCurve(R.publicKey.ecdh,e.name)).getSharedSecret(r,t).subarray(1)}}async function qi(e,t){const r=await M.getNobleCurve(R.publicKey.ecdh,e.name),{publicKey:n,privateKey:i}=await e.genKeyPair();return{publicKey:n,sharedKey:r.getSharedSecret(i,t).subarray(1)}}var Vi=/*#__PURE__*/Object.freeze({__proto__:null,decrypt:async function(e,t,r,n,i,s,a){const o=new Ei(e);Bi(o,i),Bi(o,r);const{sharedKey:c}=await Gi(o,r,i,s),h=Oi(R.publicKey.ecdh,e,t,a),{keySize:u}=ne(t.cipher);let l;for(let e=0;e<3;e++)try{const r=await zi(t.hash,c,u,h,1===e,2===e);return Mi(await si(t.cipher,r,n))}catch(e){l=e}throw l},encrypt:async function(e,t,r,n,i){const s=Ti(r),a=new Ei(e);Bi(a,n);const{publicKey:o,sharedKey:c}=await _i(a,n),h=Oi(R.publicKey.ecdh,e,t,i),{keySize:u}=ne(t.cipher),l=await zi(t.hash,c,u,h);return{publicKey:o,wrappedKey:await ii(t.cipher,l,s)}},validateParams:async function(e,t,r){return vi(R.publicKey.ecdh,e,t,r)}}),Ji=/*#__PURE__*/Object.freeze({__proto__:null,CurveWithOID:Ei,ecdh:Vi,ecdhX:pi,ecdsa:Ri,eddsa:ri,eddsaLegacy:Li,generate:async function(e){const t=new Ei(e),{oid:r,hash:n,cipher:i}=t,s=await t.genKeyPair();return{oid:r,Q:s.publicKey,secret:M.leftPad(s.privateKey,t.payloadSize),hash:n,cipher:i}},getPreferredHashAlgo:function(e){return ki[e.getName()].hash}});const Yi=BigInt(0),Wi=BigInt(1);var Zi=/*#__PURE__*/Object.freeze({__proto__:null,sign:async function(e,t,r,n,i,s){const a=BigInt(0);let o,c,h,u;n=gr(n),i=gr(i),r=gr(r),s=gr(s),r=pr(r,n),s=pr(s,i);const l=pr(gr(t.subarray(0,Er(i))),i);for(;;){if(o=Sr(Wi,i),c=pr(dr(r,o,n),i),c===a)continue;const e=pr(s*c,i);if(u=pr(l+e,i),h=pr(wr(o,i)*u,i),h!==a)break}return{r:vr(c,"be",Er(n)),s:vr(h,"be",Er(n))}},validateParams:async function(e,t,r,n,i){if(e=gr(e),t=gr(t),r=gr(r),n=gr(n),r<=Wi||r>=e)return!1;if(pr(e-Wi,t)!==Yi)return!1;if(dr(r,t,e)!==Wi)return!1;const s=BigInt(kr(t));if(s=a||r<=Yi||r>=a)return M.printDebug("invalid DSA Signature"),!1;const c=pr(gr(n.subarray(0,Er(a))),a),h=wr(r,a);if(h===Yi)return M.printDebug("invalid DSA Signature"),!1;i=pr(i,s),o=pr(o,s);const u=pr(c*h,a),l=pr(t*h,a);return pr(pr(dr(i,u,s)*dr(o,l,s),s),a)===t}}),$i={rsa:_r,elgamal:jr,elliptic:Ji,dsa:Zi};var Xi=/*#__PURE__*/Object.freeze({__proto__:null,parseSignatureParams:function(e,t){let r=0;switch(e){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:case R.publicKey.rsaSign:{const e=M.readMPI(t.subarray(r));return r+=e.length+2,{read:r,signatureParams:{s:e}}}case R.publicKey.dsa:case R.publicKey.ecdsa:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=M.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case R.publicKey.eddsaLegacy:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=M.readMPI(t.subarray(r));return r+=n.length+2,{read:r,signatureParams:{r:e,s:n}}}case R.publicKey.ed25519:case R.publicKey.ed448:{const n=2*$i.elliptic.eddsa.getPayloadSize(e),i=M.readExactSubarray(t,r,r+n);return r+=i.length,{read:r,signatureParams:{RS:i}}}default:throw new qn("Unknown signature algorithm.")}},sign:async function(e,t,r,n,i,s){if(!r||!n)throw Error("Missing key parameters");switch(e){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:case R.publicKey.rsaSign:{const{n:e,e:a}=r,{d:o,p:c,q:h,u}=n;return{s:await $i.rsa.sign(t,i,e,a,o,c,h,u,s)}}case R.publicKey.dsa:{const{g:e,p:i,q:a}=r,{x:o}=n;return $i.dsa.sign(t,s,e,i,a,o)}case R.publicKey.elgamal:throw Error("Signing with Elgamal is not defined in the OpenPGP standard.");case R.publicKey.ecdsa:{const{oid:e,Q:a}=r,{d:o}=n;return $i.elliptic.ecdsa.sign(e,t,i,a,o,s)}case R.publicKey.eddsaLegacy:{const{oid:e,Q:a}=r,{seed:o}=n;return $i.elliptic.eddsaLegacy.sign(e,t,i,a,o,s)}case R.publicKey.ed25519:case R.publicKey.ed448:{const{A:a}=r,{seed:o}=n;return $i.elliptic.eddsa.sign(e,t,i,a,o,s)}default:throw Error("Unknown signature algorithm.")}},verify:async function(e,t,r,n,i,s){switch(e){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:case R.publicKey.rsaSign:{const{n:e,e:a}=n,o=M.leftPad(r.s,e.length);return $i.rsa.verify(t,i,o,e,a,s)}case R.publicKey.dsa:{const{g:e,p:i,q:a,y:o}=n,{r:c,s:h}=r;return $i.dsa.verify(t,c,h,s,e,i,a,o)}case R.publicKey.ecdsa:{const{oid:e,Q:a}=n,o=new $i.elliptic.CurveWithOID(e).payloadSize,c=M.leftPad(r.r,o),h=M.leftPad(r.s,o);return $i.elliptic.ecdsa.verify(e,t,{r:c,s:h},i,a,s)}case R.publicKey.eddsaLegacy:{const{oid:e,Q:a}=n,o=new $i.elliptic.CurveWithOID(e).payloadSize,c=M.leftPad(r.r,o),h=M.leftPad(r.s,o);return $i.elliptic.eddsaLegacy.verify(e,t,{r:c,s:h},i,a,s)}case R.publicKey.ed25519:case R.publicKey.ed448:{const{A:a}=n;return $i.elliptic.eddsa.verify(e,t,r,i,a,s)}default:throw Error("Unknown signature algorithm.")}}});class es{constructor(e){e&&(this.data=e)}read(e){if(e.length>=1){const t=e[0];if(e.length>=1+t)return this.data=e.subarray(1,1+t),1+this.data.length}throw Error("Invalid symmetric key")}write(){return M.concatUint8Array([new Uint8Array([this.data.length]),this.data])}}class ts{constructor(e){if(e){const{hash:t,cipher:r}=e;this.hash=t,this.cipher=r}else this.hash=null,this.cipher=null}read(e){if(e.length<4||3!==e[0]||1!==e[1])throw new qn("Cannot read KDFParams");return this.hash=e[2],this.cipher=e[3],4}write(){return new Uint8Array([3,1,this.hash,this.cipher])}}class rs{static fromObject({wrappedKey:e,algorithm:t}){const r=new rs;return r.wrappedKey=e,r.algorithm=t,r}read(e){let t=0,r=e[t++];this.algorithm=r%2?e[t++]:null,r-=r%2,this.wrappedKey=M.readExactSubarray(e,t,t+r),t+=r}write(){return M.concatUint8Array([this.algorithm?new Uint8Array([this.wrappedKey.length+1,this.algorithm]):new Uint8Array([this.wrappedKey.length]),this.wrappedKey])}}function ns(e){try{e.getName()}catch(e){throw new qn("Unknown curve OID")}}function is(e,t){switch(e){case R.publicKey.ecdsa:case R.publicKey.ecdh:case R.publicKey.eddsaLegacy:return new $i.elliptic.CurveWithOID(t).payloadSize;case R.publicKey.ed25519:case R.publicKey.ed448:return $i.elliptic.eddsa.getPayloadSize(e);case R.publicKey.x25519:case R.publicKey.x448:return $i.elliptic.ecdhX.getPayloadSize(e);default:throw Error("Unknown elliptic algo")}}var ss=/*#__PURE__*/Object.freeze({__proto__:null,generateParams:function(e,t,r){switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:return $i.rsa.generate(t,65537).then((({n:e,e:t,d:r,p:n,q:i,u:s})=>({privateParams:{d:r,p:n,q:i,u:s},publicParams:{n:e,e:t}})));case R.publicKey.ecdsa:return $i.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{d:r},publicParams:{oid:new Nn(e),Q:t}})));case R.publicKey.eddsaLegacy:return $i.elliptic.generate(r).then((({oid:e,Q:t,secret:r})=>({privateParams:{seed:r},publicParams:{oid:new Nn(e),Q:t}})));case R.publicKey.ecdh:return $i.elliptic.generate(r).then((({oid:e,Q:t,secret:r,hash:n,cipher:i})=>({privateParams:{d:r},publicParams:{oid:new Nn(e),Q:t,kdfParams:new ts({hash:n,cipher:i})}})));case R.publicKey.ed25519:case R.publicKey.ed448:return $i.elliptic.eddsa.generate(e).then((({A:e,seed:t})=>({privateParams:{seed:t},publicParams:{A:e}})));case R.publicKey.x25519:case R.publicKey.x448:return $i.elliptic.ecdhX.generate(e).then((({A:e,k:t})=>({privateParams:{k:t},publicParams:{A:e}})));case R.publicKey.dsa:case R.publicKey.elgamal:throw Error("Unsupported algorithm for key generation.");default:throw Error("Unknown public key algorithm.")}},generateSessionKey:function(e){const{keySize:t}=ne(e);return Ir(t)},getAEADMode:function(e){const t=R.read(R.aead,e);return lr[t]},getCipherParams:ne,getCurvePayloadSize:is,getPreferredCurveHashAlgo:function(e,t){switch(e){case R.publicKey.ecdsa:case R.publicKey.eddsaLegacy:return $i.elliptic.getPreferredHashAlgo(t);case R.publicKey.ed25519:case R.publicKey.ed448:return $i.elliptic.eddsa.getPreferredHashAlgo(e);default:throw Error("Unknown elliptic signing algo")}},getPrefixRandom:async function(e){const{blockSize:t}=ne(e),r=await Ir(t),n=new Uint8Array([r[r.length-2],r[r.length-1]]);return M.concat([r,n])},parseEncSessionKeyParams:function(e,t){let r=0;switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:return{c:M.readMPI(t.subarray(r))};case R.publicKey.elgamal:{const e=M.readMPI(t.subarray(r));r+=e.length+2;return{c1:e,c2:M.readMPI(t.subarray(r))}}case R.publicKey.ecdh:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=new es;return n.read(t.subarray(r)),{V:e,C:n}}case R.publicKey.x25519:case R.publicKey.x448:{const n=is(e),i=M.readExactSubarray(t,r,r+n);r+=i.length;const s=new rs;return s.read(t.subarray(r)),{ephemeralPublicKey:i,C:s}}default:throw new qn("Unknown public key encryption algorithm.")}},parsePrivateKeyParams:function(e,t,r){let n=0;switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:{const e=M.readMPI(t.subarray(n));n+=e.length+2;const r=M.readMPI(t.subarray(n));n+=r.length+2;const i=M.readMPI(t.subarray(n));n+=i.length+2;const s=M.readMPI(t.subarray(n));return n+=s.length+2,{read:n,privateParams:{d:e,p:r,q:i,u:s}}}case R.publicKey.dsa:case R.publicKey.elgamal:{const e=M.readMPI(t.subarray(n));return n+=e.length+2,{read:n,privateParams:{x:e}}}case R.publicKey.ecdsa:case R.publicKey.ecdh:{const i=is(e,r.oid);let s=M.readMPI(t.subarray(n));return n+=s.length+2,s=M.leftPad(s,i),{read:n,privateParams:{d:s}}}case R.publicKey.eddsaLegacy:{const i=is(e,r.oid);if(r.oid.getName()!==R.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let s=M.readMPI(t.subarray(n));return n+=s.length+2,s=M.leftPad(s,i),{read:n,privateParams:{seed:s}}}case R.publicKey.ed25519:case R.publicKey.ed448:{const r=is(e),i=M.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{seed:i}}}case R.publicKey.x25519:case R.publicKey.x448:{const r=is(e),i=M.readExactSubarray(t,n,n+r);return n+=i.length,{read:n,privateParams:{k:i}}}default:throw new qn("Unknown public key encryption algorithm.")}},parsePublicKeyParams:function(e,t){let r=0;switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=M.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{n:e,e:n}}}case R.publicKey.dsa:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=M.readMPI(t.subarray(r));r+=n.length+2;const i=M.readMPI(t.subarray(r));r+=i.length+2;const s=M.readMPI(t.subarray(r));return r+=s.length+2,{read:r,publicParams:{p:e,q:n,g:i,y:s}}}case R.publicKey.elgamal:{const e=M.readMPI(t.subarray(r));r+=e.length+2;const n=M.readMPI(t.subarray(r));r+=n.length+2;const i=M.readMPI(t.subarray(r));return r+=i.length+2,{read:r,publicParams:{p:e,g:n,y:i}}}case R.publicKey.ecdsa:{const e=new Nn;r+=e.read(t),ns(e);const n=M.readMPI(t.subarray(r));return r+=n.length+2,{read:r,publicParams:{oid:e,Q:n}}}case R.publicKey.eddsaLegacy:{const e=new Nn;if(r+=e.read(t),ns(e),e.getName()!==R.curve.ed25519Legacy)throw Error("Unexpected OID for eddsaLegacy");let n=M.readMPI(t.subarray(r));return r+=n.length+2,n=M.leftPad(n,33),{read:r,publicParams:{oid:e,Q:n}}}case R.publicKey.ecdh:{const e=new Nn;r+=e.read(t),ns(e);const n=M.readMPI(t.subarray(r));r+=n.length+2;const i=new ts;return r+=i.read(t.subarray(r)),{read:r,publicParams:{oid:e,Q:n,kdfParams:i}}}case R.publicKey.ed25519:case R.publicKey.ed448:case R.publicKey.x25519:case R.publicKey.x448:{const n=M.readExactSubarray(t,r,r+is(e));return r+=n.length,{read:r,publicParams:{A:n}}}default:throw new qn("Unknown public key encryption algorithm.")}},publicKeyDecrypt:async function(e,t,r,n,i,s){switch(e){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:{const{c:e}=n,{n:i,e:a}=t,{d:o,p:c,q:h,u}=r;return $i.rsa.decrypt(e,i,a,o,c,h,u,s)}case R.publicKey.elgamal:{const{c1:e,c2:i}=n,a=t.p,o=r.x;return $i.elgamal.decrypt(e,i,a,o,s)}case R.publicKey.ecdh:{const{oid:e,Q:s,kdfParams:a}=t,{d:o}=r,{V:c,C:h}=n;return $i.elliptic.ecdh.decrypt(e,a,c,h.data,s,o,i)}case R.publicKey.x25519:case R.publicKey.x448:{const{A:i}=t,{k:s}=r,{ephemeralPublicKey:a,C:o}=n;if(null!==o.algorithm&&!M.isAES(o.algorithm))throw Error("AES session key expected");return $i.elliptic.ecdhX.decrypt(e,a,o.wrappedKey,i,s)}default:throw Error("Unknown public key encryption algorithm.")}},publicKeyEncrypt:async function(e,t,r,n,i){switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:{const{n:e,e:t}=r;return{c:await $i.rsa.encrypt(n,e,t)}}case R.publicKey.elgamal:{const{p:e,g:t,y:i}=r;return $i.elgamal.encrypt(n,e,t,i)}case R.publicKey.ecdh:{const{oid:e,Q:t,kdfParams:s}=r,{publicKey:a,wrappedKey:o}=await $i.elliptic.ecdh.encrypt(e,s,n,t,i);return{V:a,C:new es(o)}}case R.publicKey.x25519:case R.publicKey.x448:{if(t&&!M.isAES(t))throw Error("X25519 and X448 keys can only encrypt AES session keys");const{A:i}=r,{ephemeralPublicKey:s,wrappedKey:a}=await $i.elliptic.ecdhX.encrypt(e,n,i);return{ephemeralPublicKey:s,C:rs.fromObject({algorithm:t,wrappedKey:a})}}default:return[]}},serializeParams:function(e,t){const r=new Set([R.publicKey.ed25519,R.publicKey.x25519,R.publicKey.ed448,R.publicKey.x448]),n=Object.keys(t).map((n=>{const i=t[n];return M.isUint8Array(i)?r.has(e)?i:M.uint8ArrayToMPI(i):i.write()}));return M.concatUint8Array(n)},validateParams:async function(e,t,r){if(!t||!r)throw Error("Missing key parameters");switch(e){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:{const{n:e,e:n}=t,{d:i,p:s,q:a,u:o}=r;return $i.rsa.validateParams(e,n,i,s,a,o)}case R.publicKey.dsa:{const{p:e,q:n,g:i,y:s}=t,{x:a}=r;return $i.dsa.validateParams(e,n,i,s,a)}case R.publicKey.elgamal:{const{p:e,g:n,y:i}=t,{x:s}=r;return $i.elgamal.validateParams(e,n,i,s)}case R.publicKey.ecdsa:case R.publicKey.ecdh:{const n=$i.elliptic[R.read(R.publicKey,e)],{oid:i,Q:s}=t,{d:a}=r;return n.validateParams(i,s,a)}case R.publicKey.eddsaLegacy:{const{Q:e,oid:n}=t,{seed:i}=r;return $i.elliptic.eddsaLegacy.validateParams(n,e,i)}case R.publicKey.ed25519:case R.publicKey.ed448:{const{A:n}=t,{seed:i}=r;return $i.elliptic.eddsa.validateParams(e,n,i)}case R.publicKey.x25519:case R.publicKey.x448:{const{A:n}=t,{k:i}=r;return $i.elliptic.ecdhX.validateParams(e,n,i)}default:throw Error("Unknown public key algorithm.")}}});const as={cipher:ie,hash:be,mode:lr,publicKey:$i,signature:Xi,random:Kr,pkcs1:Tr,pkcs5:Ni,aesKW:ai};Object.assign(as,ss);class os extends Error{constructor(...e){super(...e),Error.captureStackTrace&&Error.captureStackTrace(this,os),this.name="Argon2OutOfMemoryError"}}let cs,hs;class us{constructor(e=L){const{passes:t,parallelism:r,memoryExponent:n}=e.s2kArgon2Params;this.type="argon2",this.salt=null,this.t=t,this.p=r,this.encodedM=n}generateSalt(){this.salt=as.random.getRandomBytes(16)}read(e){let t=0;return this.salt=e.subarray(t,t+16),t+=16,this.t=e[t++],this.p=e[t++],this.encodedM=e[t++],t}write(){const e=[new Uint8Array([R.write(R.s2k,this.type)]),this.salt,new Uint8Array([this.t,this.p,this.encodedM])];return M.concatUint8Array(e)}async produceKey(e,t){const r=2<1048576&&(hs=cs(),hs.catch((()=>{}))),i}catch(e){throw e.message&&(e.message.includes("Unable to grow instance memory")||e.message.includes("failed to grow memory")||e.message.includes("WebAssembly.Memory.grow")||e.message.includes("Out of memory"))?new os("Could not allocate required memory for Argon2"):e}}}class ls{constructor(e,t=L){this.algorithm=R.hash.sha256,this.type=R.read(R.s2k,e),this.c=t.s2kIterationCountByte,this.salt=null}generateSalt(){switch(this.type){case"salted":case"iterated":this.salt=as.random.getRandomBytes(8)}}getCount(){return 16+(15&this.c)<<6+(this.c>>4)}read(e){let t=0;switch(this.algorithm=e[t++],this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==M.uint8ArrayToString(e.subarray(t,t+3)))throw new qn("Unknown s2k type.");t+=3;if(1001!==1e3+e[t++])throw new qn("Unknown s2k gnu protection mode.");this.type="gnu-dummy";break;default:throw new qn("Unknown s2k type.")}return t}write(){if("gnu-dummy"===this.type)return new Uint8Array([101,0,...M.stringToUint8Array("GNU"),1]);const e=[new Uint8Array([R.write(R.s2k,this.type),this.algorithm])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw Error("GNU s2k type not supported.");default:throw Error("Unknown s2k type.")}return M.concatUint8Array(e)}async produceKey(e,t){e=M.encodeUTF8(e);const r=[];let n=0,i=0;for(;n>>1|(21845&Ds)<<1;Ps=(61680&(Ps=(52428&Ps)>>>2|(13107&Ps)<<2))>>>4|(3855&Ps)<<4,Cs[Ds]=((65280&Ps)>>>8|(255&Ps)<<8)>>>1}var Us=function(e,t,r){for(var n=e.length,i=0,s=new ds(t);i>>c]=h}else for(a=new ds(n),i=0;i>>15-e[i]);return a},xs=new ps(288);for(Ds=0;Ds<144;++Ds)xs[Ds]=8;for(Ds=144;Ds<256;++Ds)xs[Ds]=9;for(Ds=256;Ds<280;++Ds)xs[Ds]=7;for(Ds=280;Ds<288;++Ds)xs[Ds]=8;var Qs=new ps(32);for(Ds=0;Ds<32;++Ds)Qs[Ds]=5;var Rs=/*#__PURE__*/Us(xs,9,0),Ls=/*#__PURE__*/Us(xs,9,1),Ts=/*#__PURE__*/Us(Qs,5,0),Ms=/*#__PURE__*/Us(Qs,5,1),Ns=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},Fs=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Hs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Os=function(e){return(e+7)/8|0},zs=function(e,t,r){(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length);var n=new(2==e.BYTES_PER_ELEMENT?ds:4==e.BYTES_PER_ELEMENT?As:ps)(r-t);return n.set(e.subarray(t,r)),n},_s=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Gs=function(e,t,r){var n=Error(t||_s[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Gs),!r)throw n;return n},js=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8},qs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Vs=function(e,t){for(var r=[],n=0;ny&&(y=s[n].s);var f=new ds(y+1),g=Js(r[u-1],f,0);if(g>t){n=0;var p=0,d=g-t,A=1<t))break;p+=A-(1<>>=d;p>0;){var m=s[n].s;f[m]=0&&p;--n){var b=s[n].s;f[b]==t&&(--f[b],++p)}g=t}return[new ps(f),g]},Js=function(e,t,r){return-1==e.s?Math.max(Js(e.l,t,r+1),Js(e.r,t,r+1)):t[e.s]=r},Ys=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new ds(++t),n=0,i=e[0],s=1,a=function(e){r[n++]=e},o=1;o<=t;++o)if(e[o]==i&&o!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(i),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(i);s=1,i=e[o]}return[r.subarray(0,n),t]},Ws=function(e,t){for(var r=0,n=0;n>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;s4&&!S[bs[C-1]];--C);var D,P,U,x,Q=h+5<<3,R=Ws(i,xs)+Ws(s,Qs)+a,L=Ws(i,y)+Ws(s,p)+a+14+3*C+Ws(v,S)+(2*v[16]+3*v[17]+7*v[18]);if(Q<=R&&Q<=L)return Zs(t,u,e.subarray(c,c+h));if(js(t,u,1+(L15&&(js(t,u,F[B]>>>5&127),u+=F[B]>>>12)}}}else D=Rs,P=xs,U=Ts,x=Qs;for(B=0;B255){H=n[B]>>>18&31;qs(t,u,D[H+257]),u+=P[H+257],H>7&&(js(t,u,n[B]>>>23&31),u+=ws[H]);var O=31&n[B];qs(t,u,U[O]),u+=x[O],O>3&&(qs(t,u,n[B]>>>5&8191),u+=ms[O])}else qs(t,u,D[n[B]]),u+=P[n[B]];return qs(t,u,D[256]),u+P[256]},Xs=/*#__PURE__*/new As([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ea=/*#__PURE__*/new ps(0),ta=function(e,t,r,n,i){return function(e,t,r,n,i,s){var a=e.length,o=new ps(n+a+5*(1+Math.ceil(a/7e3))+i),c=o.subarray(n,o.length-i),h=0;if(!t||a<8)for(var u=0;u<=a;u+=65535){var l=u+65535;l>=a&&(c[h>>3]=s),h=Zs(c,h+1,e.subarray(u,l))}else{for(var y=Xs[t-1],f=y>>>13,g=8191&y,p=(1<7e3||S>24576)&&x>423){h=$s(e,c,0,k,E,v,I,S,C,u-C,h),S=B=I=0,C=u;for(var Q=0;Q<286;++Q)E[Q]=0;for(Q=0;Q<30;++Q)v[Q]=0}var R=2,L=0,T=g,M=P-U&32767;if(x>2&&D==b(u-M))for(var N=Math.min(f,x)-1,F=Math.min(32767,u),H=Math.min(258,x);M<=F&&--T&&P!=U;){if(e[u+R]==e[u+R-M]){for(var O=0;OR){if(R=O,L=M,O>N)break;var z=Math.min(M,O-2),_=0;for(Q=0;Q_&&(_=j,U=G)}}}M+=(P=U)-(U=d[P])+32768&32767}if(L){k[S++]=268435456|Bs[R]<<18|Ks[L];var q=31&Bs[R],V=31&Ks[L];I+=ws[q]+ms[V],++E[257+q],++v[V],K=u+R,++B}else k[S++]=e[u],++E[e[u]]}}h=$s(e,c,s,k,E,v,I,S,C,u-C,h),!s&&7&h&&(h=Zs(c,h+1,ea))}return zs(o,0,n+Os(h)+i)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,r,n,!i)},ra=/*#__PURE__*/function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(ta(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||Gs(5),this.d&&Gs(4),this.d=t,this.p(e,t||!1)},e}(),na=/*#__PURE__*/function(){function e(e){this.s={},this.p=new ps(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||Gs(5),this.d&&Gs(4);var t=this.p.length,r=new ps(t+e.length);r.set(this.p),r.set(e,t),this.p=r},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,r=function(e,t,r){var n=e.length;if(!n||r&&r.f&&!r.l)return t||new ps(0);var i=!t||r,s=!r||r.i;r||(r={}),t||(t=new ps(3*n));var a=function(e){var r=t.length;if(e>r){var n=new ps(Math.max(2*r,e));n.set(t),t=n}},o=r.f||0,c=r.p||0,h=r.b||0,u=r.l,l=r.d,y=r.m,f=r.n,g=8*n;do{if(!u){o=Fs(e,c,1);var p=Fs(e,c+1,3);if(c+=3,!p){var d=e[(K=Os(c)+4)-4]|e[K-3]<<8,A=K+d;if(A>n){s&&Gs(0);break}i&&a(h+d),t.set(e.subarray(K,A),h),r.b=h+=d,r.p=c=8*A,r.f=o;continue}if(1==p)u=Ls,l=Ms,y=9,f=5;else if(2==p){var w=Fs(e,c,31)+257,m=Fs(e,c+10,15)+4,b=w+Fs(e,c+5,31)+1;c+=14;for(var k=new ps(b),E=new ps(19),v=0;v>>4)<16)k[v++]=K;else{var D=0,P=0;for(16==K?(P=3+Fs(e,c,3),c+=2,D=k[v-1]):17==K?(P=3+Fs(e,c,7),c+=3):18==K&&(P=11+Fs(e,c,127),c+=7);P--;)k[v++]=D}}var U=k.subarray(0,w),x=k.subarray(w);y=Ns(U),f=Ns(x),u=Us(U,y,1),l=Us(x,f,1)}else Gs(1);if(c>g){s&&Gs(0);break}}i&&a(h+131072);for(var Q=(1<>>4;if((c+=15&D)>g){s&&Gs(0);break}if(D||Gs(2),T<256)t[h++]=T;else{if(256==T){L=c,u=null;break}var M=T-254;if(T>264){var N=ws[v=T-257];M=Fs(e,c,(1<>>4;if(F||Gs(3),c+=15&F,x=Ss[H],H>3&&(N=ms[H],x+=Hs(e,c)&(1<g){s&&Gs(0);break}i&&a(h+131072);for(var O=h+M;h>16),i=(65535&i)+15*(i>>16)}r=t,n=i},d:function(){return(255&(r%=65521))<<24|r>>>8<<16|(255&(n%=65521))<<8|n>>>8}}),this.v=1,ra.call(this,e,t)}return e.prototype.push=function(e,t){ra.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var r=ta(e,this.o,this.v&&2,t&&4,!t);this.v&&(function(e,t){var r=t.level,n=0==r?0:r<6?1:9==r?3:2;e[0]=120,e[1]=n<<6|(n?32-2*n:1)}(r,this.o),this.v=0),t&&function(e,t,r){for(;r;++t)e[t]=r,r>>>=8}(r,r.length-4,this.c.d()),this.ondata(r,t)},e}(),sa=/*#__PURE__*/function(){function e(e){this.v=1,na.call(this,e)}return e.prototype.push=function(e,t){if(na.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&Gs(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),na.prototype.c.call(this,t)},e}(),aa="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{aa.decode(ea,{stream:!0}),1}catch(e){}class oa{static get tag(){return R.packet.literalData}constructor(e=new Date){this.format=R.literal.utf8,this.date=M.normalizeDate(e),this.text=null,this.data=null,this.filename=""}setText(e,t=R.literal.utf8){this.format=t,this.text=e,this.data=null}getText(e=!1){return(null===this.text||M.isStream(this.text))&&(this.text=M.decodeUTF8(M.nativeEOL(this.getBytes(e)))),this.text}setBytes(e,t){this.format=t,this.data=e,this.text=null}getBytes(e=!1){return null===this.data&&(this.data=M.canonicalizeEOL(M.encodeUTF8(this.text))),e?I(this.data):this.data}setFilename(e){this.filename=e}getFilename(){return this.filename}async read(e){await v(e,(async e=>{const t=await e.readByte(),r=await e.readByte();this.filename=M.decodeUTF8(await e.readBytes(r)),this.date=M.readDate(await e.readBytes(4));let n=e.remainder();o(n)&&(n=await C(n)),this.setBytes(n,t)}))}writeHeader(){const e=M.encodeUTF8(this.filename),t=new Uint8Array([e.length]),r=new Uint8Array([this.format]),n=M.writeDate(this.date);return M.concatUint8Array([r,t,e,n])}write(){const e=this.writeHeader(),t=this.getBytes();return M.concat([e,t])}}class ca{constructor(){this.bytes=""}read(e){return this.bytes=M.uint8ArrayToString(e.subarray(0,8)),this.bytes.length}write(){return M.stringToUint8Array(this.bytes)}toHex(){return M.uint8ArrayToHex(M.stringToUint8Array(this.bytes))}equals(e,t=!1){return t&&(e.isWildcard()||this.isWildcard())||this.bytes===e.bytes}isNull(){return""===this.bytes}isWildcard(){return/^0+$/.test(this.toHex())}static mapToHex(e){return e.toHex()}static fromID(e){const t=new ca;return t.read(M.hexToUint8Array(e)),t}static wildcard(){const e=new ca;return e.read(new Uint8Array(8)),e}}const ha=Symbol("verified"),ua="salt@notations.openpgpjs.org",la=new Set([R.signatureSubpacket.issuerKeyID,R.signatureSubpacket.issuerFingerprint,R.signatureSubpacket.embeddedSignature]);class ya{static get tag(){return R.packet.signature}constructor(){this.version=null,this.signatureType=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signatureData=null,this.unhashedSubpackets=[],this.unknownSubpackets=[],this.signedHashValue=null,this.salt=null,this.created=null,this.signatureExpirationTime=null,this.signatureNeverExpires=!0,this.exportable=null,this.trustLevel=null,this.trustAmount=null,this.regularExpression=null,this.revocable=null,this.keyExpirationTime=null,this.keyNeverExpires=null,this.preferredSymmetricAlgorithms=null,this.revocationKeyClass=null,this.revocationKeyAlgorithm=null,this.revocationKeyFingerprint=null,this.issuerKeyID=new ca,this.rawNotations=[],this.notations={},this.preferredHashAlgorithms=null,this.preferredCompressionAlgorithms=null,this.keyServerPreferences=null,this.preferredKeyServer=null,this.isPrimaryUserID=null,this.policyURI=null,this.keyFlags=null,this.signersUserID=null,this.reasonForRevocationFlag=null,this.reasonForRevocationString=null,this.features=null,this.signatureTargetPublicKeyAlgorithm=null,this.signatureTargetHashAlgorithm=null,this.signatureTargetHash=null,this.embeddedSignature=null,this.issuerKeyVersion=null,this.issuerFingerprint=null,this.preferredAEADAlgorithms=null,this.preferredCipherSuites=null,this.revoked=null,this[ha]=null}read(e,t=L){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new qn("Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4!==this.version&&5!==this.version&&6!==this.version)throw new qn(`Version ${this.version} of the signature packet is unsupported.`);if(this.signatureType=e[r++],this.publicKeyAlgorithm=e[r++],this.hashAlgorithm=e[r++],r+=this.readSubPackets(e.subarray(r,e.length),!0),!this.created)throw Error("Missing signature creation time subpacket.");if(this.signatureData=e.subarray(0,r),r+=this.readSubPackets(e.subarray(r,e.length),!1),this.signedHashValue=e.subarray(r,r+2),r+=2,6===this.version){const t=e[r++];this.salt=e.subarray(r,r+t),r+=t}const n=e.subarray(r,e.length),{read:i,signatureParams:s}=as.signature.parseSignatureParams(this.publicKeyAlgorithm,n);if(ias.serializeParams(this.publicKeyAlgorithm,await this.params))):as.serializeParams(this.publicKeyAlgorithm,this.params)}write(){const e=[];return e.push(this.signatureData),e.push(this.writeUnhashedSubPackets()),e.push(this.signedHashValue),6===this.version&&(e.push(new Uint8Array([this.salt.length])),e.push(this.salt)),e.push(this.writeParams()),M.concat(e)}async sign(e,t,r=new Date,n=!1,i){this.version=e.version,this.created=M.normalizeDate(r),this.issuerKeyVersion=e.version,this.issuerFingerprint=e.getFingerprintBytes(),this.issuerKeyID=e.getKeyID();const s=[new Uint8Array([this.version,this.signatureType,this.publicKeyAlgorithm,this.hashAlgorithm])];if(6===this.version){const e=ga(this.hashAlgorithm);if(null===this.salt)this.salt=as.random.getRandomBytes(e);else if(e!==this.salt.length)throw Error("Provided salt does not have the required length")}else if(i.nonDeterministicSignaturesViaNotation){if(0!==this.rawNotations.filter((({name:e})=>e===ua)).length)throw Error("Unexpected existing salt notation");{const e=as.random.getRandomBytes(ga(this.hashAlgorithm));this.rawNotations.push({name:ua,value:e,humanReadable:!1,critical:!1})}}s.push(this.writeHashedSubPackets()),this.unhashedSubpackets=[],this.signatureData=M.concat(s);const a=this.toHash(this.signatureType,t,n),o=await this.hash(this.signatureType,t,a,n);this.signedHashValue=K(B(o),0,2);const c=async()=>as.signature.sign(this.publicKeyAlgorithm,this.hashAlgorithm,e.publicParams,e.privateParams,a,await C(o));M.isStream(o)?this.params=c():(this.params=await c(),this[ha]=!0)}writeHashedSubPackets(){const e=R.signatureSubpacket,t=[];let r;if(null===this.created)throw Error("Missing signature creation time");t.push(fa(e.signatureCreationTime,!0,M.writeDate(this.created))),null!==this.signatureExpirationTime&&t.push(fa(e.signatureExpirationTime,!0,M.writeNumber(this.signatureExpirationTime,4))),null!==this.exportable&&t.push(fa(e.exportableCertification,!0,new Uint8Array([this.exportable?1:0]))),null!==this.trustLevel&&(r=new Uint8Array([this.trustLevel,this.trustAmount]),t.push(fa(e.trustSignature,!0,r))),null!==this.regularExpression&&t.push(fa(e.regularExpression,!0,this.regularExpression)),null!==this.revocable&&t.push(fa(e.revocable,!0,new Uint8Array([this.revocable?1:0]))),null!==this.keyExpirationTime&&t.push(fa(e.keyExpirationTime,!0,M.writeNumber(this.keyExpirationTime,4))),null!==this.preferredSymmetricAlgorithms&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.preferredSymmetricAlgorithms)),t.push(fa(e.preferredSymmetricAlgorithms,!1,r))),null!==this.revocationKeyClass&&(r=new Uint8Array([this.revocationKeyClass,this.revocationKeyAlgorithm]),r=M.concat([r,this.revocationKeyFingerprint]),t.push(fa(e.revocationKey,!1,r))),!this.issuerKeyID.isNull()&&this.issuerKeyVersion<5&&t.push(fa(e.issuerKeyID,!0,this.issuerKeyID.write())),this.rawNotations.forEach((({name:n,value:i,humanReadable:s,critical:a})=>{r=[new Uint8Array([s?128:0,0,0,0])];const o=M.encodeUTF8(n);r.push(M.writeNumber(o.length,2)),r.push(M.writeNumber(i.length,2)),r.push(o),r.push(i),r=M.concat(r),t.push(fa(e.notationData,a,r))})),null!==this.preferredHashAlgorithms&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.preferredHashAlgorithms)),t.push(fa(e.preferredHashAlgorithms,!1,r))),null!==this.preferredCompressionAlgorithms&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.preferredCompressionAlgorithms)),t.push(fa(e.preferredCompressionAlgorithms,!1,r))),null!==this.keyServerPreferences&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.keyServerPreferences)),t.push(fa(e.keyServerPreferences,!1,r))),null!==this.preferredKeyServer&&t.push(fa(e.preferredKeyServer,!1,M.encodeUTF8(this.preferredKeyServer))),null!==this.isPrimaryUserID&&t.push(fa(e.primaryUserID,!1,new Uint8Array([this.isPrimaryUserID?1:0]))),null!==this.policyURI&&t.push(fa(e.policyURI,!1,M.encodeUTF8(this.policyURI))),null!==this.keyFlags&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.keyFlags)),t.push(fa(e.keyFlags,!0,r))),null!==this.signersUserID&&t.push(fa(e.signersUserID,!1,M.encodeUTF8(this.signersUserID))),null!==this.reasonForRevocationFlag&&(r=M.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag)+this.reasonForRevocationString),t.push(fa(e.reasonForRevocation,!0,r))),null!==this.features&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.features)),t.push(fa(e.features,!1,r))),null!==this.signatureTargetPublicKeyAlgorithm&&(r=[new Uint8Array([this.signatureTargetPublicKeyAlgorithm,this.signatureTargetHashAlgorithm])],r.push(M.stringToUint8Array(this.signatureTargetHash)),r=M.concat(r),t.push(fa(e.signatureTarget,!0,r))),null!==this.embeddedSignature&&t.push(fa(e.embeddedSignature,!0,this.embeddedSignature.write())),null!==this.issuerFingerprint&&(r=[new Uint8Array([this.issuerKeyVersion]),this.issuerFingerprint],r=M.concat(r),t.push(fa(e.issuerFingerprint,this.version>=5,r))),null!==this.preferredAEADAlgorithms&&(r=M.stringToUint8Array(M.uint8ArrayToString(this.preferredAEADAlgorithms)),t.push(fa(e.preferredAEADAlgorithms,!1,r))),null!==this.preferredCipherSuites&&(r=new Uint8Array([].concat(...this.preferredCipherSuites)),t.push(fa(e.preferredCipherSuites,!1,r)));const n=M.concat(t),i=M.writeNumber(n.length,6===this.version?4:2);return M.concat([i,n])}writeUnhashedSubPackets(){const e=this.unhashedSubpackets.map((({type:e,critical:t,body:r})=>fa(e,t,r))),t=M.concat(e),r=M.writeNumber(t.length,6===this.version?4:2);return M.concat([r,t])}readSubPacket(e,t=!0){let r=0;const n=!!(128&e[r]),i=127&e[r];if(r++,t||(this.unhashedSubpackets.push({type:i,critical:n,body:e.subarray(r,e.length)}),la.has(i)))switch(i){case R.signatureSubpacket.signatureCreationTime:this.created=M.readDate(e.subarray(r,e.length));break;case R.signatureSubpacket.signatureExpirationTime:{const t=M.readNumber(e.subarray(r,e.length));this.signatureNeverExpires=0===t,this.signatureExpirationTime=t;break}case R.signatureSubpacket.exportableCertification:this.exportable=1===e[r++];break;case R.signatureSubpacket.trustSignature:this.trustLevel=e[r++],this.trustAmount=e[r++];break;case R.signatureSubpacket.regularExpression:this.regularExpression=e[r];break;case R.signatureSubpacket.revocable:this.revocable=1===e[r++];break;case R.signatureSubpacket.keyExpirationTime:{const t=M.readNumber(e.subarray(r,e.length));this.keyExpirationTime=t,this.keyNeverExpires=0===t;break}case R.signatureSubpacket.preferredSymmetricAlgorithms:this.preferredSymmetricAlgorithms=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.revocationKey:this.revocationKeyClass=e[r++],this.revocationKeyAlgorithm=e[r++],this.revocationKeyFingerprint=e.subarray(r,r+20);break;case R.signatureSubpacket.issuerKeyID:if(4===this.version)this.issuerKeyID.read(e.subarray(r,e.length));else if(t)throw Error("Unexpected Issuer Key ID subpacket");break;case R.signatureSubpacket.notationData:{const t=!!(128&e[r]);r+=4;const i=M.readNumber(e.subarray(r,r+2));r+=2;const s=M.readNumber(e.subarray(r,r+2));r+=2;const a=M.decodeUTF8(e.subarray(r,r+i)),o=e.subarray(r+i,r+i+s);this.rawNotations.push({name:a,humanReadable:t,value:o,critical:n}),t&&(this.notations[a]=M.decodeUTF8(o));break}case R.signatureSubpacket.preferredHashAlgorithms:this.preferredHashAlgorithms=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.preferredCompressionAlgorithms:this.preferredCompressionAlgorithms=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.keyServerPreferences:this.keyServerPreferences=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.preferredKeyServer:this.preferredKeyServer=M.decodeUTF8(e.subarray(r,e.length));break;case R.signatureSubpacket.primaryUserID:this.isPrimaryUserID=0!==e[r++];break;case R.signatureSubpacket.policyURI:this.policyURI=M.decodeUTF8(e.subarray(r,e.length));break;case R.signatureSubpacket.keyFlags:this.keyFlags=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.signersUserID:this.signersUserID=M.decodeUTF8(e.subarray(r,e.length));break;case R.signatureSubpacket.reasonForRevocation:this.reasonForRevocationFlag=e[r++],this.reasonForRevocationString=M.decodeUTF8(e.subarray(r,e.length));break;case R.signatureSubpacket.features:this.features=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.signatureTarget:{this.signatureTargetPublicKeyAlgorithm=e[r++],this.signatureTargetHashAlgorithm=e[r++];const t=as.getHashByteLength(this.signatureTargetHashAlgorithm);this.signatureTargetHash=M.uint8ArrayToString(e.subarray(r,r+t));break}case R.signatureSubpacket.embeddedSignature:this.embeddedSignature=new ya,this.embeddedSignature.read(e.subarray(r,e.length));break;case R.signatureSubpacket.issuerFingerprint:this.issuerKeyVersion=e[r++],this.issuerFingerprint=e.subarray(r,e.length),this.issuerKeyVersion>=5?this.issuerKeyID.read(this.issuerFingerprint):this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));break;case R.signatureSubpacket.preferredAEADAlgorithms:this.preferredAEADAlgorithms=[...e.subarray(r,e.length)];break;case R.signatureSubpacket.preferredCipherSuites:this.preferredCipherSuites=[];for(let t=r;t{r+=e.length}),(()=>{const n=[];return 5!==this.version||this.signatureType!==R.signature.binary&&this.signatureType!==R.signature.text||(t?n.push(new Uint8Array(6)):n.push(e.writeHeader())),n.push(new Uint8Array([this.version,255])),5===this.version&&n.push(new Uint8Array(4)),n.push(M.writeNumber(r,4)),M.concat(n)}))}toHash(e,t,r=!1){const n=this.toSign(e,t);return M.concat([this.salt||new Uint8Array,n,this.signatureData,this.calculateTrailer(t,r)])}async hash(e,t,r,n=!1){if(6===this.version&&this.salt.length!==ga(this.hashAlgorithm))throw Error("Signature salt does not have the expected length");return r||(r=this.toHash(e,t,n)),as.hash.digest(this.hashAlgorithm,r)}async verify(e,t,r,n=new Date,i=!1,s=L){if(!this.issuerKeyID.equals(e.getKeyID()))throw Error("Signature was not issued by the given public key");if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Public key algorithm used to sign signature does not match issuer key algorithm.");const a=t===R.signature.binary||t===R.signature.text;if(!(this[ha]&&!a)){let n,s;if(this.hashed?s=await this.hashed:(n=this.toHash(t,r,i),s=await this.hash(t,r,n)),s=await C(s),this.signedHashValue[0]!==s[0]||this.signedHashValue[1]!==s[1])throw Error("Signed digest did not match");if(this.params=await this.params,this[ha]=await as.signature.verify(this.publicKeyAlgorithm,this.hashAlgorithm,this.params,e.publicParams,n,s),!this[ha])throw Error("Signature verification failed")}const o=M.normalizeDate(n);if(o&&this.created>o)throw Error("Signature creation time is in the future");if(o&&o>=this.getExpirationTime())throw Error("Signature is expired");if(s.rejectHashAlgorithms.has(this.hashAlgorithm))throw Error("Insecure hash algorithm: "+R.read(R.hash,this.hashAlgorithm).toUpperCase());if(s.rejectMessageHashAlgorithms.has(this.hashAlgorithm)&&[R.signature.binary,R.signature.text].includes(this.signatureType))throw Error("Insecure message hash algorithm: "+R.read(R.hash,this.hashAlgorithm).toUpperCase());if(this.unknownSubpackets.forEach((({type:e,critical:t})=>{if(t)throw Error("Unknown critical signature subpacket type "+e)})),this.rawNotations.forEach((({name:e,critical:t})=>{if(t&&s.knownNotations.indexOf(e)<0)throw Error("Unknown critical notation: "+e)})),null!==this.revocationKeyClass)throw Error("This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.")}isExpired(e=new Date){const t=M.normalizeDate(e);return null!==t&&!(this.created<=t&&tya.prototype.calculateTrailer.apply(await this.correspondingSig,e)))}async verify(){const e=await this.correspondingSig;if(!e||e.constructor.tag!==R.packet.signature)throw Error("Corresponding signature packet missing");if(e.signatureType!==this.signatureType||e.hashAlgorithm!==this.hashAlgorithm||e.publicKeyAlgorithm!==this.publicKeyAlgorithm||!e.issuerKeyID.equals(this.issuerKeyID)||3===this.version&&6===e.version||6===this.version&&6!==e.version||6===this.version&&!M.equalsUint8Array(e.issuerFingerprint,this.issuerFingerprint)||6===this.version&&!M.equalsUint8Array(e.salt,this.salt))throw Error("Corresponding signature packet does not match one-pass signature packet");return e.hashed=this.hashed,e.verify.apply(e,arguments)}}function da(e,t){if(!t[e]){let t;try{t=R.read(R.packet,e)}catch(t){throw new Vn("Unknown packet type with tag: "+e)}throw Error("Packet not allowed in this context: "+t)}return new t[e]}pa.prototype.hash=ya.prototype.hash,pa.prototype.toHash=ya.prototype.toHash,pa.prototype.toSign=ya.prototype.toSign;class Aa extends Array{static async fromBinary(e,t,r=L){const n=new Aa;return await n.read(e,t,r),n}async read(e,t,r=L){r.additionalAllowedPackets.length&&(t={...t,...M.constructAllowedPackets(r.additionalAllowedPackets)}),this.stream=E(e,(async(e,n)=>{const i=x(n);try{for(;;){await i.ready;if(await jn(e,(async e=>{try{if(e.tag===R.packet.marker||e.tag===R.packet.trust||e.tag===R.packet.padding)return;const n=da(e.tag,t);n.packets=new Aa,n.fromStream=M.isStream(e.packet),await n.read(e.packet,r),await i.write(n)}catch(t){if(t instanceof Vn){if(!(e.tag<=39))return;await i.abort(t)}const n=!r.ignoreUnsupportedPackets&&t instanceof qn,s=!(r.ignoreMalformedPackets||t instanceof qn);if(n||s||Gn(e.tag))await i.abort(t);else{const t=new Jn(e.tag,e.packet);await i.write(t)}M.printDebugError(t)}})))return await i.ready,void await i.close()}}catch(e){await i.abort(e)}}));const n=U(this.stream);for(;;){const{done:e,value:t}=await n.read();if(e?this.stream=null:this.push(t),e||Gn(t.constructor.tag))break}n.releaseLock()}write(){const e=[];for(let t=0;t{if(t.push(e),i+=e.length,i>=s){const e=Math.min(Math.log(i)/Math.LN2|0,30),r=2**e,n=M.concat([On(e)].concat(t));return t=[n.subarray(1+r)],i=t[0].length,n.subarray(0,1+r)}}),(()=>M.concat([Hn(i)].concat(t)))))}else{if(M.isStream(n)){let t=0;e.push(k(B(n),(e=>{t+=e.length}),(()=>_n(r,t))))}else e.push(_n(r,n.length));e.push(n)}}return M.concat(e)}filterByTag(...e){const t=new Aa,r=e=>t=>e===t;for(let n=0;nt.constructor.tag===e))}indexOfTag(...e){const t=[],r=this,n=e=>t=>e===t;for(let i=0;i{this.algorithm=await e.readByte(),this.compressed=e.remainder(),await this.decompress(t)}))}write(){return null===this.compressed&&this.compress(),M.concat([new Uint8Array([this.algorithm]),this.compressed])}async decompress(e=L){const t=R.read(R.compression,this.algorithm),r=Ba[t];if(!r)throw Error(t+" decompression not supported");this.packets=await Aa.fromBinary(await r(this.compressed),wa,e)}compress(){const e=R.read(R.compression,this.algorithm),t=va[e];if(!t)throw Error(e+" compression not supported");this.compressed=t(this.packets.write())}}function ba(e,t){return r=>{if(!M.isStream(r)||o(r))return P((()=>C(r).then((e=>new Promise(((r,n)=>{const i=new t;i.ondata=e=>{r(e)};try{i.push(e,!0)}catch(e){n(e)}}))))));if(e)try{const t=e();return r.pipeThrough(t)}catch(e){if("TypeError"!==e.name)throw e}const n=r.getReader(),i=new t;return new ReadableStream({async start(e){for(i.ondata=async(t,r)=>{e.enqueue(t),r&&e.close()};;){const{done:e,value:t}=await n.read();if(e)return void i.push(new Uint8Array,!0);t.length&&i.push(t)}}})}}function ka(){return async function(e){const{decode:t}=await Promise.resolve().then((function(){return Xy}));return P((async()=>t(await C(e))))}}const Ea=e=>({compressor:"undefined"!=typeof CompressionStream&&(()=>new CompressionStream(e)),decompressor:"undefined"!=typeof DecompressionStream&&(()=>new DecompressionStream(e))}),va={zip:/*#__PURE__*/ba(Ea("deflate-raw").compressor,ra),zlib:/*#__PURE__*/ba(Ea("deflate").compressor,ia)},Ba={uncompressed:e=>e,zip:/*#__PURE__*/ba(Ea("deflate-raw").decompressor,na),zlib:/*#__PURE__*/ba(Ea("deflate").decompressor,sa),bzip2:/*#__PURE__*/ka()},Ia=/*#__PURE__*/M.constructAllowedPackets([oa,ma,pa,ya]);class Sa{static get tag(){return R.packet.symEncryptedIntegrityProtectedData}static fromObject({version:e,aeadAlgorithm:t}){if(1!==e&&2!==e)throw Error("Unsupported SEIPD version");const r=new Sa;return r.version=e,2===e&&(r.aeadAlgorithm=t),r}constructor(){this.version=null,this.cipherAlgorithm=null,this.aeadAlgorithm=null,this.chunkSizeByte=null,this.salt=null,this.encrypted=null,this.packets=null}async read(e){await v(e,(async e=>{if(this.version=await e.readByte(),1!==this.version&&2!==this.version)throw new qn(`Version ${this.version} of the SEIP packet is unsupported.`);2===this.version&&(this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte(),this.salt=await e.readBytes(32)),this.encrypted=e.remainder()}))}write(){return 2===this.version?M.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.salt,this.encrypted]):M.concat([new Uint8Array([this.version]),this.encrypted])}async encrypt(e,t,r=L){const{blockSize:n,keySize:i}=as.getCipherParams(e);if(t.length!==i)throw Error("Unexpected session key size");let s=this.packets.write();if(o(s)&&(s=await C(s)),2===this.version)this.cipherAlgorithm=e,this.salt=as.random.getRandomBytes(32),this.chunkSizeByte=r.aeadChunkSizeByte,this.encrypted=await Ka(this,"encrypt",t,s);else{const i=await as.getPrefixRandom(e),a=new Uint8Array([211,20]),o=M.concat([i,s,a]),c=await as.hash.sha1(I(o)),h=M.concat([o,c]);this.encrypted=await as.mode.cfb.encrypt(e,t,h,new Uint8Array(n),r)}return!0}async decrypt(e,t,r=L){if(t.length!==as.getCipherParams(e).keySize)throw Error("Unexpected session key size");let n,i=B(this.encrypted);if(o(i)&&(i=await C(i)),2===this.version){if(this.cipherAlgorithm!==e)throw Error("Unexpected session key algorithm");n=await Ka(this,"decrypt",t,i)}else{const{blockSize:s}=as.getCipherParams(e),a=await as.mode.cfb.decrypt(e,t,i,new Uint8Array(s)),o=K(I(a),-20),c=K(a,0,-20),h=Promise.all([C(await as.hash.sha1(I(c))),C(o)]).then((([e,t])=>{if(!M.equalsUint8Array(e,t))throw Error("Modification detected.");return new Uint8Array})),u=K(c,s+2);n=K(u,0,-2),n=A([n,P((()=>h))]),M.isStream(i)&&r.allowUnauthenticatedStream||(n=await C(n))}return this.packets=await Aa.fromBinary(n,Ia,r),!0}}async function Ka(e,t,r,n){const i=e instanceof Sa&&2===e.version,s=!i&&e.constructor.tag===R.packet.aeadEncryptedData;if(!i&&!s)throw Error("Unexpected packet type");const a=as.getAEADMode(e.aeadAlgorithm),o="decrypt"===t?a.tagLength:0,c="encrypt"===t?a.tagLength:0,h=2**(e.chunkSizeByte+6)+o,u=s?8:0,l=new ArrayBuffer(13+u),y=new Uint8Array(l,0,5+u),f=new Uint8Array(l),g=new DataView(l),p=new Uint8Array(l,5,8);y.set([192|e.constructor.tag,e.version,e.cipherAlgorithm,e.aeadAlgorithm,e.chunkSizeByte],0);let d,A,m=0,b=Promise.resolve(),k=0,v=0;if(i){const{keySize:t}=as.getCipherParams(e.cipherAlgorithm),{ivLength:n}=a,i=new Uint8Array(l,0,5),s=await ci(R.hash.sha256,r,e.salt,i,t+n);r=s.subarray(0,t),d=s.subarray(t),d.fill(0,d.length-8),A=new DataView(d.buffer,d.byteOffset,d.byteLength)}else d=e.iv;const B=await a(e.cipherAlgorithm,r);return E(n,(async(r,n)=>{if("array"!==M.isStream(r)){const t=new TransformStream({},{highWaterMark:M.getHardwareConcurrency()*2**(e.chunkSizeByte+6),size:e=>e.length});w(t.readable,n),n=t.writable}const s=U(r),a=x(n);try{for(;;){let e=await s.readBytes(h+o)||new Uint8Array;const r=e.subarray(e.length-o);let n,l,w;if(e=e.subarray(0,e.length-o),i)w=d;else{w=d.slice();for(let e=0;e<8;e++)w[d.length-8+e]^=p[e]}if(!m||e.length?(s.unshift(r),n=B[t](e,w,y),n.catch((()=>{})),v+=e.length-o+c):(g.setInt32(5+u+4,k),n=B[t](r,w,f),n.catch((()=>{})),v+=c,l=!0),k+=e.length-o,b=b.then((()=>n)).then((async e=>{await a.ready,await a.write(e),v-=e.length})).catch((e=>a.abort(e))),(l||v>a.desiredSize)&&await b,l){await a.close();break}i?A.setInt32(d.length-4,++m):g.setInt32(9,++m)}}catch(e){await a.ready.catch((()=>{})),await a.abort(e)}}))}const Ca=/*#__PURE__*/M.constructAllowedPackets([oa,ma,pa,ya]);class Da{static get tag(){return R.packet.aeadEncryptedData}constructor(){this.version=1,this.cipherAlgorithm=null,this.aeadAlgorithm=R.aead.eax,this.chunkSizeByte=null,this.iv=null,this.encrypted=null,this.packets=null}async read(e){await v(e,(async e=>{const t=await e.readByte();if(1!==t)throw new qn(`Version ${t} of the AEAD-encrypted data packet is not supported.`);this.cipherAlgorithm=await e.readByte(),this.aeadAlgorithm=await e.readByte(),this.chunkSizeByte=await e.readByte();const r=as.getAEADMode(this.aeadAlgorithm);this.iv=await e.readBytes(r.ivLength),this.encrypted=e.remainder()}))}write(){return M.concat([new Uint8Array([this.version,this.cipherAlgorithm,this.aeadAlgorithm,this.chunkSizeByte]),this.iv,this.encrypted])}async decrypt(e,t,r=L){this.packets=await Aa.fromBinary(await Ka(this,"decrypt",t,B(this.encrypted)),Ca,r)}async encrypt(e,t,r=L){this.cipherAlgorithm=e;const{ivLength:n}=as.getAEADMode(this.aeadAlgorithm);this.iv=as.random.getRandomBytes(n),this.chunkSizeByte=r.aeadChunkSizeByte;const i=this.packets.write();this.encrypted=await Ka(this,"encrypt",t,i)}}class Pa{static get tag(){return R.packet.publicKeyEncryptedSessionKey}constructor(){this.version=null,this.publicKeyID=new ca,this.publicKeyVersion=null,this.publicKeyFingerprint=null,this.publicKeyAlgorithm=null,this.sessionKey=null,this.sessionKeyAlgorithm=null,this.encrypted={}}static fromObject({version:e,encryptionKeyPacket:t,anonymousRecipient:r,sessionKey:n,sessionKeyAlgorithm:i}){const s=new Pa;if(3!==e&&6!==e)throw Error("Unsupported PKESK version");return s.version=e,6===e&&(s.publicKeyVersion=r?null:t.version,s.publicKeyFingerprint=r?null:t.getFingerprintBytes()),s.publicKeyID=r?ca.wildcard():t.getKeyID(),s.publicKeyAlgorithm=t.algorithm,s.sessionKey=n,s.sessionKeyAlgorithm=i,s}read(e){let t=0;if(this.version=e[t++],3!==this.version&&6!==this.version)throw new qn(`Version ${this.version} of the PKESK packet is unsupported.`);if(6===this.version){const r=e[t++];if(r){this.publicKeyVersion=e[t++];const n=r-1;this.publicKeyFingerprint=e.subarray(t,t+n),t+=n,this.publicKeyVersion>=5?this.publicKeyID.read(this.publicKeyFingerprint):this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8))}else this.publicKeyID=ca.wildcard()}else t+=this.publicKeyID.read(e.subarray(t,t+8));if(this.publicKeyAlgorithm=e[t++],this.encrypted=as.parseEncSessionKeyParams(this.publicKeyAlgorithm,e.subarray(t)),this.publicKeyAlgorithm===R.publicKey.x25519||this.publicKeyAlgorithm===R.publicKey.x448)if(3===this.version)this.sessionKeyAlgorithm=R.write(R.symmetric,this.encrypted.C.algorithm);else if(null!==this.encrypted.C.algorithm)throw Error("Unexpected cleartext symmetric algorithm")}write(){const e=[new Uint8Array([this.version])];return 6===this.version?null!==this.publicKeyFingerprint?(e.push(new Uint8Array([this.publicKeyFingerprint.length+1,this.publicKeyVersion])),e.push(this.publicKeyFingerprint)):e.push(new Uint8Array([0])):e.push(this.publicKeyID.write()),e.push(new Uint8Array([this.publicKeyAlgorithm]),as.serializeParams(this.publicKeyAlgorithm,this.encrypted)),M.concatUint8Array(e)}async encrypt(e){const t=R.write(R.publicKey,this.publicKeyAlgorithm),r=3===this.version?this.sessionKeyAlgorithm:null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=Ua(this.version,t,r,this.sessionKey);this.encrypted=await as.publicKeyEncrypt(t,r,e.publicParams,i,n)}async decrypt(e,t){if(this.publicKeyAlgorithm!==e.algorithm)throw Error("Decryption error");const r=t?Ua(this.version,this.publicKeyAlgorithm,t.sessionKeyAlgorithm,t.sessionKey):null,n=5===e.version?e.getFingerprintBytes().subarray(0,20):e.getFingerprintBytes(),i=await as.publicKeyDecrypt(this.publicKeyAlgorithm,e.publicParams,e.privateParams,this.encrypted,n,r),{sessionKey:s,sessionKeyAlgorithm:a}=function(e,t,r,n){switch(t){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.elgamal:case R.publicKey.ecdh:{const t=r.subarray(0,r.length-2),i=r.subarray(r.length-2),s=M.writeChecksum(t.subarray(t.length%8)),a=s[0]===i[0]&s[1]===i[1],o=6===e?{sessionKeyAlgorithm:null,sessionKey:t}:{sessionKeyAlgorithm:t[0],sessionKey:t.subarray(1)};if(n){const t=a&o.sessionKeyAlgorithm===n.sessionKeyAlgorithm&o.sessionKey.length===n.sessionKey.length;return{sessionKey:M.selectUint8Array(t,o.sessionKey,n.sessionKey),sessionKeyAlgorithm:6===e?null:M.selectUint8(t,o.sessionKeyAlgorithm,n.sessionKeyAlgorithm)}}if(a&&(6===e||R.read(R.symmetric,o.sessionKeyAlgorithm)))return o;throw Error("Decryption error")}case R.publicKey.x25519:case R.publicKey.x448:return{sessionKeyAlgorithm:null,sessionKey:r};default:throw Error("Unsupported public key algorithm")}}(this.version,this.publicKeyAlgorithm,i,t);if(3===this.version){const e=this.publicKeyAlgorithm!==R.publicKey.x25519&&this.publicKeyAlgorithm!==R.publicKey.x448;if(this.sessionKeyAlgorithm=e?a:this.sessionKeyAlgorithm,s.length!==as.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}this.sessionKey=s}}function Ua(e,t,r,n){switch(t){case R.publicKey.rsaEncrypt:case R.publicKey.rsaEncryptSign:case R.publicKey.elgamal:case R.publicKey.ecdh:return M.concatUint8Array([new Uint8Array(6===e?[]:[r]),n,M.writeChecksum(n.subarray(n.length%8))]);case R.publicKey.x25519:case R.publicKey.x448:return n;default:throw Error("Unsupported public key algorithm")}}class xa{static get tag(){return R.packet.symEncryptedSessionKey}constructor(e=L){this.version=e.aeadProtect?6:4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm=null,this.aeadAlgorithm=R.write(R.aead,e.preferredAEADAlgorithm),this.encrypted=null,this.s2k=null,this.iv=null}read(e){let t=0;if(this.version=e[t++],4!==this.version&&5!==this.version&&6!==this.version)throw new qn(`Version ${this.version} of the SKESK packet is unsupported.`);6===this.version&&t++;const r=e[t++];this.version>=5&&(this.aeadAlgorithm=e[t++],6===this.version&&t++);const n=e[t++];if(this.s2k=fs(n),t+=this.s2k.read(e.subarray(t,e.length)),this.version>=5){const r=as.getAEADMode(this.aeadAlgorithm);this.iv=e.subarray(t,t+=r.ivLength)}this.version>=5||t=5){const e=as.getAEADMode(this.aeadAlgorithm),r=new Uint8Array([192|xa.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),s=6===this.version?await ci(R.hash.sha256,i,new Uint8Array,r,n):i,a=await e(t,s);this.sessionKey=await a.decrypt(this.encrypted,this.iv,r)}else if(null!==this.encrypted){const e=await as.mode.cfb.decrypt(t,i,this.encrypted,new Uint8Array(r));if(this.sessionKeyAlgorithm=R.write(R.symmetric,e[0]),this.sessionKey=e.subarray(1,e.length),this.sessionKey.length!==as.getCipherParams(this.sessionKeyAlgorithm).keySize)throw Error("Unexpected session key size")}else this.sessionKey=i}async encrypt(e,t=L){const r=null!==this.sessionKeyEncryptionAlgorithm?this.sessionKeyEncryptionAlgorithm:this.sessionKeyAlgorithm;this.sessionKeyEncryptionAlgorithm=r,this.s2k=gs(t),this.s2k.generateSalt();const{blockSize:n,keySize:i}=as.getCipherParams(r),s=await this.s2k.produceKey(e,i);if(null===this.sessionKey&&(this.sessionKey=as.generateSessionKey(this.sessionKeyAlgorithm)),this.version>=5){const e=as.getAEADMode(this.aeadAlgorithm);this.iv=as.random.getRandomBytes(e.ivLength);const t=new Uint8Array([192|xa.tag,this.version,this.sessionKeyEncryptionAlgorithm,this.aeadAlgorithm]),n=6===this.version?await ci(R.hash.sha256,s,new Uint8Array,t,i):s,a=await e(r,n);this.encrypted=await a.encrypt(this.sessionKey,this.iv,t)}else{const e=M.concatUint8Array([new Uint8Array([this.sessionKeyAlgorithm]),this.sessionKey]);this.encrypted=await as.mode.cfb.encrypt(r,s,e,new Uint8Array(n),t)}}}class Qa{static get tag(){return R.packet.publicKey}constructor(e=new Date,t=L){this.version=t.v6Keys?6:4,this.created=M.normalizeDate(e),this.algorithm=null,this.publicParams=null,this.expirationTimeV3=0,this.fingerprint=null,this.keyID=null}static fromSecretKeyPacket(e){const t=new Qa,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}async read(e,t=L){let r=0;if(this.version=e[r++],5===this.version&&!t.enableParsingV5Entities)throw new qn("Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed");if(4===this.version||5===this.version||6===this.version){this.created=M.readDate(e.subarray(r,r+4)),r+=4,this.algorithm=e[r++],this.version>=5&&(r+=4);const{read:t,publicParams:n}=as.parsePublicKeyParams(this.algorithm,e.subarray(r));if(6===this.version&&n.oid&&(n.oid.getName()===R.curve.curve25519Legacy||n.oid.getName()===R.curve.ed25519Legacy))throw Error("Legacy curve25519 cannot be used with v6 keys");return this.publicParams=n,r+=t,await this.computeFingerprintAndKeyID(),r}throw new qn(`Version ${this.version} of the key packet is unsupported.`)}write(){const e=[];e.push(new Uint8Array([this.version])),e.push(M.writeDate(this.created)),e.push(new Uint8Array([this.algorithm]));const t=as.serializeParams(this.algorithm,this.publicParams);return this.version>=5&&e.push(M.writeNumber(t.length,4)),e.push(t),M.concatUint8Array(e)}writeForHash(e){const t=this.writePublicKey(),r=149+e,n=e>=5?4:2;return M.concatUint8Array([new Uint8Array([r]),M.writeNumber(t.length,n),t])}isDecrypted(){return null}getCreationTime(){return this.created}getKeyID(){return this.keyID}async computeFingerprintAndKeyID(){if(await this.computeFingerprint(),this.keyID=new ca,this.version>=5)this.keyID.read(this.fingerprint.subarray(0,8));else{if(4!==this.version)throw Error("Unsupported key version");this.keyID.read(this.fingerprint.subarray(12,20))}}async computeFingerprint(){const e=this.writeForHash(this.version);if(this.version>=5)this.fingerprint=await as.hash.sha256(e);else{if(4!==this.version)throw Error("Unsupported key version");this.fingerprint=await as.hash.sha1(e)}}getFingerprintBytes(){return this.fingerprint}getFingerprint(){return M.uint8ArrayToHex(this.getFingerprintBytes())}hasSameFingerprintAs(e){return this.version===e.version&&M.equalsUint8Array(this.writePublicKey(),e.writePublicKey())}getAlgorithmInfo(){const e={};e.algorithm=R.read(R.publicKey,this.algorithm);const t=this.publicParams.n||this.publicParams.p;return t?e.bits=M.uint8ArrayBitLength(t):this.publicParams.oid&&(e.curve=this.publicParams.oid.getName()),e}}Qa.prototype.readPublicKey=Qa.prototype.read,Qa.prototype.writePublicKey=Qa.prototype.write;const Ra=/*#__PURE__*/M.constructAllowedPackets([oa,ma,pa,ya]);class La{static get tag(){return R.packet.symmetricallyEncryptedData}constructor(){this.encrypted=null,this.packets=null}read(e){this.encrypted=e}write(){return this.encrypted}async decrypt(e,t,r=L){if(!r.allowUnauthenticatedMessages)throw Error("Message is not authenticated.");const{blockSize:n}=as.getCipherParams(e),i=await C(B(this.encrypted)),s=await as.mode.cfb.decrypt(e,t,i.subarray(n+2),i.subarray(2,n+2));this.packets=await Aa.fromBinary(s,Ra,r)}async encrypt(e,t,r=L){const n=this.packets.write(),{blockSize:i}=as.getCipherParams(e),s=await as.getPrefixRandom(e),a=await as.mode.cfb.encrypt(e,t,s,new Uint8Array(i),r),o=await as.mode.cfb.encrypt(e,t,n,a.subarray(2),r);this.encrypted=M.concat([a,o])}}class Ta{static get tag(){return R.packet.marker}read(e){return 80===e[0]&&71===e[1]&&80===e[2]}write(){return new Uint8Array([80,71,80])}}class Ma extends Qa{static get tag(){return R.packet.publicSubkey}constructor(e,t){super(e,t)}static fromSecretSubkeyPacket(e){const t=new Ma,{version:r,created:n,algorithm:i,publicParams:s,keyID:a,fingerprint:o}=e;return t.version=r,t.created=n,t.algorithm=i,t.publicParams=s,t.keyID=a,t.fingerprint=o,t}}class Na{static get tag(){return R.packet.userAttribute}constructor(){this.attributes=[]}read(e){let t=0;for(;t{this.privateParams[e].fill(0),delete this.privateParams[e]})),this.privateParams=null,this.isEncrypted=!0)}}async function Ha(e,t,r,n,i,s,a){if("argon2"===t.type&&!i)throw Error("Using Argon2 S2K without AEAD is not allowed");if("simple"===t.type&&6===e)throw Error("Using Simple S2K with version 6 keys is not allowed");const{keySize:o}=as.getCipherParams(n),c=await t.produceKey(r,o);if(!i||5===e||a)return c;const h=M.concatUint8Array([s,new Uint8Array([e,n,i])]);return ci(R.hash.sha256,c,new Uint8Array,h,o)}class Oa{static get tag(){return R.packet.userID}constructor(){this.userID="",this.name="",this.email="",this.comment=""}static fromObject(e){if(M.isString(e)||e.name&&!M.isString(e.name)||e.email&&!M.isEmailAddress(e.email)||e.comment&&!M.isString(e.comment))throw Error("Invalid user ID format");const t=new Oa;Object.assign(t,e);const r=[];return t.name&&r.push(t.name),t.comment&&r.push(`(${t.comment})`),t.email&&r.push(`<${t.email}>`),t.userID=r.join(" "),t}read(e,t=L){const r=M.decodeUTF8(e);if(r.length>t.maxUserIDLength)throw Error("User ID string is too long");const n=/^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/.exec(r);if(null!==n){const{name:e,comment:t,email:r}=n.groups;this.comment=t?.replace(/^\(|\)|\s$/g,"").trim()||"",this.name=e?.trim()||"",this.email=r.substring(1,r.length-1)}else/^[^\s@]+@[^\s@]+$/.test(r)&&(this.email=r);this.userID=r}write(){return M.encodeUTF8(this.userID)}equals(e){return e&&e.userID===this.userID}}class za extends Fa{static get tag(){return R.packet.secretSubkey}constructor(e=new Date,t=L){super(e,t)}}class _a{static get tag(){return R.packet.trust}read(){throw new qn("Trust packets are not supported")}write(){throw new qn("Trust packets are not supported")}}class Ga{static get tag(){return R.packet.padding}constructor(){this.padding=null}read(e){}write(){return this.padding}async createPadding(e){this.padding=await as.random.getRandomBytes(e)}}const ja=/*#__PURE__*/M.constructAllowedPackets([ya]);class qa{constructor(e){this.packets=e||new Aa}write(){return this.packets.write()}armor(e=L){const t=this.packets.some((e=>e.constructor.tag===ya.tag&&6!==e.version));return X(R.armor.signature,this.write(),void 0,void 0,void 0,t,e)}getSigningKeyIDs(){return this.packets.map((e=>e.issuerKeyID))}}async function Va({armoredSignature:e,binarySignature:t,config:r,...n}){r={...L,...r};let i=e||t;if(!i)throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");if(e&&!M.isString(e))throw Error("readSignature: options.armoredSignature must be a string");if(t&&!M.isUint8Array(t))throw Error("readSignature: options.binarySignature must be a Uint8Array");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:e,data:t}=await $(i);if(e!==R.armor.signature)throw Error("Armored text not of type signature");i=t}const a=await Aa.fromBinary(i,ja,r);return new qa(a)}async function Ja(e,t){const r=new za(e.date,t);return r.packets=null,r.algorithm=R.write(R.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve),await r.computeFingerprintAndKeyID(),r}async function Ya(e,t){const r=new Fa(e.date,t);return r.packets=null,r.algorithm=R.write(R.publicKey,e.algorithm),await r.generate(e.rsaBits,e.curve,e.config),await r.computeFingerprintAndKeyID(),r}async function Wa(e,t,r,n,i=new Date,s){let a,o;for(let c=e.length-1;c>=0;c--)try{(!a||e[c].created>=a.created)&&(await e[c].verify(t,r,n,i,void 0,s),a=e[c])}catch(e){o=e}if(!a)throw M.wrapError(`Could not find valid ${R.read(R.signature,r)} signature in key ${t.getKeyID().toHex()}`.replace("certGeneric ","self-").replace(/([a-z])([A-Z])/g,((e,t,r)=>t+" "+r.toLowerCase())),o);return a}function Za(e,t,r=new Date){const n=M.normalizeDate(r);if(null!==n){const r=ro(e,t);return!(e.created<=n&&n0&&(s.keyExpirationTime=r.keyExpirationTime,s.keyNeverExpires=!1);return await Xa(i,[],t,s,r.date,void 0,void 0,void 0,n)}async function Xa(e,t,r,n,i,s,a=[],o=!1,c){if(r.isDummy())throw Error("Cannot sign with a gnu-dummy key.");if(!r.isDecrypted())throw Error("Signing key is not decrypted.");const h=new ya;return Object.assign(h,n),h.publicKeyAlgorithm=r.algorithm,h.hashAlgorithm=await async function(e,t,r=new Date,n=[],i){const s=R.hash.sha256,a=i.preferredHashAlgorithm,o=await Promise.all(e.map((async(e,t)=>(await e.getPrimarySelfSignature(r,n[t],i)).preferredHashAlgorithms))),c=new Map;for(const e of o)for(const t of e)try{const e=R.write(R.hash,t);c.set(e,c.has(e)?c.get(e)+1:1)}catch{}const h=t=>0===e.length||c.get(t)===e.length||t===s,u=()=>{if(0===c.size)return s;const e=Array.from(c.keys()).filter((e=>h(e))).sort(((e,t)=>as.hash.getHashByteLength(e)-as.hash.getHashByteLength(t)))[0];return as.hash.getHashByteLength(e)>=as.hash.getHashByteLength(s)?e:s};if(new Set([R.publicKey.ecdsa,R.publicKey.eddsaLegacy,R.publicKey.ed25519,R.publicKey.ed448]).has(t.algorithm)){const e=as.getPreferredCurveHashAlgo(t.algorithm,t.publicParams.oid),r=h(a),n=as.hash.getHashByteLength(a)>=as.hash.getHashByteLength(e);if(r&&n)return a;{const t=u();return as.hash.getHashByteLength(t)>=as.hash.getHashByteLength(e)?t:e}}return h(a)?a:u()}(t,r,i,s,c),h.rawNotations=[...a],await h.sign(r,e,i,o,c),h}async function eo(e,t,r,n=new Date,i){(e=e[r])&&(t[r].length?await Promise.all(e.map((async function(e){e.isExpired(n)||i&&!await i(e)||t[r].some((function(t){return M.equalsUint8Array(t.writeParams(),e.writeParams())}))||t[r].push(e)}))):t[r]=e)}async function to(e,t,r,n,i,s,a=new Date,o){s=s||e;const c=[];return await Promise.all(n.map((async function(e){try{if(!i||e.issuerKeyID.equals(i.issuerKeyID)){const n=![R.reasonForRevocation.keyRetired,R.reasonForRevocation.keySuperseded,R.reasonForRevocation.userIDInvalid].includes(e.reasonForRevocationFlag);await e.verify(s,t,r,n?null:a,!1,o),c.push(e.issuerKeyID)}}catch(e){}}))),i?(i.revoked=!!c.some((e=>e.equals(i.issuerKeyID)))||(i.revoked||!1),i.revoked):c.length>0}function ro(e,t){let r;return!1===t.keyNeverExpires&&(r=e.created.getTime()+1e3*t.keyExpirationTime),r?new Date(r):1/0}function no(e,t={}){switch(e.type=e.type||t.type,e.curve=e.curve||t.curve,e.rsaBits=e.rsaBits||t.rsaBits,e.keyExpirationTime=void 0!==e.keyExpirationTime?e.keyExpirationTime:t.keyExpirationTime,e.passphrase=M.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e.sign=e.sign||!1,e.type){case"ecc":try{e.curve=R.write(R.curve,e.curve)}catch(e){throw Error("Unknown curve")}e.curve!==R.curve.ed25519Legacy&&e.curve!==R.curve.curve25519Legacy&&"ed25519"!==e.curve&&"curve25519"!==e.curve||(e.curve=e.sign?R.curve.ed25519Legacy:R.curve.curve25519Legacy),e.sign?e.algorithm=e.curve===R.curve.ed25519Legacy?R.publicKey.eddsaLegacy:R.publicKey.ecdsa:e.algorithm=R.publicKey.ecdh;break;case"curve25519":e.algorithm=e.sign?R.publicKey.ed25519:R.publicKey.x25519;break;case"curve448":e.algorithm=e.sign?R.publicKey.ed448:R.publicKey.x448;break;case"rsa":e.algorithm=R.publicKey.rsaEncryptSign;break;default:throw Error("Unsupported key type "+e.type)}return e}function io(e,t,r){switch(e.algorithm){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:case R.publicKey.dsa:case R.publicKey.ecdsa:case R.publicKey.eddsaLegacy:case R.publicKey.ed25519:case R.publicKey.ed448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&R.keyFlags.signData);default:return!1}}function so(e,t,r){switch(e.algorithm){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:case R.publicKey.elgamal:case R.publicKey.ecdh:case R.publicKey.x25519:case R.publicKey.x448:if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");return!t.keyFlags||!!(t.keyFlags[0]&R.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&R.keyFlags.encryptStorage);default:return!1}}function ao(e,t,r){if(!t.keyFlags&&!r.allowMissingKeyFlags)throw Error("None of the key flags is set: consider passing `config.allowMissingKeyFlags`");switch(e.algorithm){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaEncrypt:case R.publicKey.elgamal:case R.publicKey.ecdh:case R.publicKey.x25519:case R.publicKey.x448:return!(!(!t.keyFlags||!!(t.keyFlags[0]&R.keyFlags.signData))||!r.allowInsecureDecryptionWithSigningKeys)||(!t.keyFlags||!!(t.keyFlags[0]&R.keyFlags.encryptCommunication)||!!(t.keyFlags[0]&R.keyFlags.encryptStorage));default:return!1}}function oo(e,t){const r=R.write(R.publicKey,e.algorithm),n=e.getAlgorithmInfo();if(t.rejectPublicKeyAlgorithms.has(r))throw Error(n.algorithm+" keys are considered too weak.");switch(r){case R.publicKey.rsaEncryptSign:case R.publicKey.rsaSign:case R.publicKey.rsaEncrypt:if(n.bitse.getKeys(o).length>0));return 0===c.length?null:(await Promise.all(c.map((async t=>{const s=await t.getSigningKey(o,e.created,void 0,n);if(e.revoked||await i.isRevoked(e,s.keyPacket,r,n))throw Error("User certificate is revoked");try{await e.verify(s.keyPacket,R.signature.certGeneric,a,r,void 0,n)}catch(e){throw M.wrapError("User certificate is invalid",e)}}))),!0)}async verifyAllCertifications(e,t=new Date,r){const n=this,i=this.selfCertifications.concat(this.otherCertifications);return Promise.all(i.map((async i=>({keyID:i.issuerKeyID,valid:await n.verifyCertificate(i,e,t,r).catch((()=>!1))}))))}async verify(e=new Date,t){if(!this.selfCertifications.length)throw Error("No self-certifications found");const r=this,n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};let s;for(let a=this.selfCertifications.length-1;a>=0;a--)try{const s=this.selfCertifications[a];if(s.revoked||await r.isRevoked(s,void 0,e,t))throw Error("Self-certification is revoked");try{await s.verify(n,R.signature.certGeneric,i,e,void 0,t)}catch(e){throw M.wrapError("Self-certification is invalid",e)}return!0}catch(e){s=e}throw s}async update(e,t,r){const n=this.mainKey.keyPacket,i={userID:this.userID,userAttribute:this.userAttribute,key:n};await eo(e,this,"selfCertifications",t,(async function(e){try{return await e.verify(n,R.signature.certGeneric,i,t,!1,r),!0}catch(e){return!1}})),await eo(e,this,"otherCertifications",t),await eo(e,this,"revocationSignatures",t,(function(e){return to(n,R.signature.certRevocation,i,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=R.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=L){const s={userID:this.userID,userAttribute:this.userAttribute,key:e},a=new co(s.userID||s.userAttribute,this.mainKey);return a.revocationSignatures.push(await Xa(s,[],e,{signatureType:R.signature.certRevocation,reasonForRevocationFlag:R.write(R.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}}class ho{constructor(e,t){this.keyPacket=e,this.bindingSignatures=[],this.revocationSignatures=[],this.mainKey=t}toPacketList(){const e=new Aa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.bindingSignatures),e}clone(){const e=new ho(this.keyPacket,this.mainKey);return e.bindingSignatures=[...this.bindingSignatures],e.revocationSignatures=[...this.revocationSignatures],e}async isRevoked(e,t,r=new Date,n=L){const i=this.mainKey.keyPacket;return to(i,R.signature.subkeyRevocation,{key:i,bind:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verify(e=new Date,t=L){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket},i=await Wa(this.bindingSignatures,r,R.signature.subkeyBinding,n,e,t);if(i.revoked||await this.isRevoked(i,null,e,t))throw Error("Subkey is revoked");if(Za(this.keyPacket,i,e))throw Error("Subkey is expired");return i}async getExpirationTime(e=new Date,t=L){const r=this.mainKey.keyPacket,n={key:r,bind:this.keyPacket};let i;try{i=await Wa(this.bindingSignatures,r,R.signature.subkeyBinding,n,e,t)}catch(e){return null}const s=ro(this.keyPacket,i),a=i.getExpirationTime();return si.bindingSignatures[t].created&&(i.bindingSignatures[t]=e),!1;try{return await e.verify(n,R.signature.subkeyBinding,s,t,void 0,r),!0}catch(e){return!1}})),await eo(e,this,"revocationSignatures",t,(function(e){return to(n,R.signature.subkeyRevocation,s,[e],void 0,void 0,t,r)}))}async revoke(e,{flag:t=R.reasonForRevocation.noReason,string:r=""}={},n=new Date,i=L){const s={key:e,bind:this.keyPacket},a=new ho(this.keyPacket,this.mainKey);return a.revocationSignatures.push(await Xa(s,[],e,{signatureType:R.signature.subkeyRevocation,reasonForRevocationFlag:R.write(R.reasonForRevocation,t),reasonForRevocationString:r},n,void 0,void 0,!1,i)),await a.update(this),a}hasSameFingerprintAs(e){return this.keyPacket.hasSameFingerprintAs(e.keyPacket||e)}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","isDecrypted"].forEach((e=>{ho.prototype[e]=function(){return this.keyPacket[e]()}}));const uo=/*#__PURE__*/M.constructAllowedPackets([ya]),lo=new Set([R.packet.publicKey,R.packet.privateKey]),yo=new Set([R.packet.publicKey,R.packet.privateKey,R.packet.publicSubkey,R.packet.privateSubkey]);class fo{packetListToStructure(e,t=new Set){let r,n,i,s;for(const a of e){if(a instanceof Jn){yo.has(a.tag)&&!s&&(s=lo.has(a.tag)?lo:yo);continue}const e=a.constructor.tag;if(s){if(!s.has(e))continue;s=null}if(t.has(e))throw Error("Unexpected packet type: "+e);switch(e){case R.packet.publicKey:case R.packet.secretKey:if(this.keyPacket)throw Error("Key block contains multiple keys");if(this.keyPacket=a,n=this.getKeyID(),!n)throw Error("Missing Key ID");break;case R.packet.userID:case R.packet.userAttribute:r=new co(a,this),this.users.push(r);break;case R.packet.publicSubkey:case R.packet.secretSubkey:r=null,i=new ho(a,this),this.subkeys.push(i);break;case R.packet.signature:switch(a.signatureType){case R.signature.certGeneric:case R.signature.certPersona:case R.signature.certCasual:case R.signature.certPositive:if(!r){M.printDebug("Dropping certification signatures without preceding user packet");continue}a.issuerKeyID.equals(n)?r.selfCertifications.push(a):r.otherCertifications.push(a);break;case R.signature.certRevocation:r?r.revocationSignatures.push(a):this.directSignatures.push(a);break;case R.signature.key:this.directSignatures.push(a);break;case R.signature.subkeyBinding:if(!i){M.printDebug("Dropping subkey binding signature without preceding subkey packet");continue}i.bindingSignatures.push(a);break;case R.signature.keyRevocation:this.revocationSignatures.push(a);break;case R.signature.subkeyRevocation:if(!i){M.printDebug("Dropping subkey revocation signature without preceding subkey packet");continue}i.revocationSignatures.push(a)}}}}toPacketList(){const e=new Aa;return e.push(this.keyPacket),e.push(...this.revocationSignatures),e.push(...this.directSignatures),this.users.map((t=>e.push(...t.toPacketList()))),this.subkeys.map((t=>e.push(...t.toPacketList()))),e}clone(e=!1){const t=new this.constructor(this.toPacketList());return e&&t.getKeys().forEach((e=>{if(e.keyPacket=Object.create(Object.getPrototypeOf(e.keyPacket),Object.getOwnPropertyDescriptors(e.keyPacket)),!e.keyPacket.isDecrypted())return;const t={};Object.keys(e.keyPacket.privateParams).forEach((r=>{t[r]=new Uint8Array(e.keyPacket.privateParams[r])})),e.keyPacket.privateParams=t})),t}getSubkeys(e=null){return this.subkeys.filter((t=>!e||t.getKeyID().equals(e,!0)))}getKeys(e=null){const t=[];return e&&!this.getKeyID().equals(e,!0)||t.push(this),t.concat(this.getSubkeys(e))}getKeyIDs(){return this.getKeys().map((e=>e.getKeyID()))}getUserIDs(){return this.users.map((e=>e.userID?e.userID.userID:null)).filter((e=>null!==e))}write(){return this.toPacketList().write()}async getSigningKey(e=null,t=new Date,r={},n=L){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{oo(i,n)}catch(e){throw M.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Wa(r.bindingSignatures,i,R.signature.subkeyBinding,e,t,n);if(!io(r.keyPacket,s,n))continue;if(!s.embeddedSignature)throw Error("Missing embedded signature");return await Wa([s.embeddedSignature],r.keyPacket,R.signature.keyBinding,e,t,n),oo(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&io(i,s,n))return oo(i,n),this}catch(e){a=e}throw M.wrapError("Could not find valid signing key packet in key "+this.getKeyID().toHex(),a)}async getEncryptionKey(e,t=new Date,r={},n=L){await this.verifyPrimaryKey(t,r,n);const i=this.keyPacket;try{oo(i,n)}catch(e){throw M.wrapError("Could not verify primary key",e)}const s=this.subkeys.slice().sort(((e,t)=>t.keyPacket.created-e.keyPacket.created));let a;for(const r of s)if(!e||r.getKeyID().equals(e))try{await r.verify(t,n);const e={key:i,bind:r.keyPacket},s=await Wa(r.bindingSignatures,i,R.signature.subkeyBinding,e,t,n);if(so(r.keyPacket,s,n))return oo(r.keyPacket,n),r}catch(e){a=e}try{const s=await this.getPrimarySelfSignature(t,r,n);if((!e||i.getKeyID().equals(e))&&so(i,s,n))return oo(i,n),this}catch(e){a=e}throw M.wrapError("Could not find valid encryption key packet in key "+this.getKeyID().toHex(),a)}async isRevoked(e,t,r=new Date,n=L){return to(this.keyPacket,R.signature.keyRevocation,{key:this.keyPacket},this.revocationSignatures,e,t,r,n)}async verifyPrimaryKey(e=new Date,t={},r=L){const n=this.keyPacket;if(await this.isRevoked(null,null,e,r))throw Error("Primary key is revoked");if(Za(n,await this.getPrimarySelfSignature(e,t,r),e))throw Error("Primary key is expired");if(6!==n.version){const t=await Wa(this.directSignatures,n,R.signature.key,{key:n},e,r).catch((()=>{}));if(t&&Za(n,t,e))throw Error("Primary key is expired")}}async getExpirationTime(e,t=L){let r;try{const n=await this.getPrimarySelfSignature(null,e,t),i=ro(this.keyPacket,n),s=n.getExpirationTime(),a=6!==this.keyPacket.version&&await Wa(this.directSignatures,this.keyPacket,R.signature.key,{key:this.keyPacket},null,t).catch((()=>{}));if(a){const e=ro(this.keyPacket,a);r=Math.min(i,s,e)}else r=ie.subkeys.some((e=>t.hasSameFingerprintAs(e)))))))throw Error("Cannot update public key with private key if subkeys mismatch");return e.update(this,r)}const n=this.clone();return await eo(e,n,"revocationSignatures",t,(i=>to(n.keyPacket,R.signature.keyRevocation,n,[i],null,e.keyPacket,t,r))),await eo(e,n,"directSignatures",t),await Promise.all(e.users.map((async e=>{const i=n.users.filter((t=>e.userID&&e.userID.equals(t.userID)||e.userAttribute&&e.userAttribute.equals(t.userAttribute)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.users.push(t)}}))),await Promise.all(e.subkeys.map((async e=>{const i=n.subkeys.filter((t=>t.hasSameFingerprintAs(e)));if(i.length>0)await Promise.all(i.map((n=>n.update(e,t,r))));else{const t=e.clone();t.mainKey=n,n.subkeys.push(t)}}))),n}async getRevocationCertificate(e=new Date,t=L){const r={key:this.keyPacket},n=await Wa(this.revocationSignatures,this.keyPacket,R.signature.keyRevocation,r,e,t),i=new Aa;i.push(n);const s=6!==this.keyPacket.version;return X(R.armor.publicKey,i.write(),null,null,"This is a revocation certificate",s,t)}async applyRevocationCertificate(e,t=new Date,r=L){const n=await $(e),i=(await Aa.fromBinary(n.data,uo,r)).findPacket(R.packet.signature);if(!i||i.signatureType!==R.signature.keyRevocation)throw Error("Could not find revocation signature packet");if(!i.issuerKeyID.equals(this.getKeyID()))throw Error("Revocation signature does not match key");try{await i.verify(this.keyPacket,R.signature.keyRevocation,{key:this.keyPacket},t,void 0,r)}catch(e){throw M.wrapError("Could not verify revocation signature",e)}const s=this.clone();return s.revocationSignatures.push(i),s}async signPrimaryUser(e,t,r,n=L){const{index:i,user:s}=await this.getPrimaryUser(t,r,n),a=await s.certify(e,t,n),o=this.clone();return o.users[i]=a,o}async signAllUsers(e,t=new Date,r=L){const n=this.clone();return n.users=await Promise.all(this.users.map((function(n){return n.certify(e,t,r)}))),n}async verifyPrimaryUser(e,t=new Date,r,n=L){const i=this.keyPacket,{user:s}=await this.getPrimaryUser(t,r,n);return e?await s.verifyAllCertifications(e,t,n):[{keyID:i.getKeyID(),valid:await s.verify(t,n).catch((()=>!1))}]}async verifyAllUsers(e,t=new Date,r=L){const n=this.keyPacket,i=[];return await Promise.all(this.users.map((async s=>{const a=e?await s.verifyAllCertifications(e,t,r):[{keyID:n.getKeyID(),valid:await s.verify(t,r).catch((()=>!1))}];i.push(...a.map((e=>({userID:s.userID?s.userID.userID:null,userAttribute:s.userAttribute,keyID:e.keyID,valid:e.valid}))))}))),i}}["getKeyID","getFingerprint","getAlgorithmInfo","getCreationTime","hasSameFingerprintAs"].forEach((e=>{fo.prototype[e]=ho.prototype[e]}));class go extends fo{constructor(e){if(super(),this.keyPacket=null,this.revocationSignatures=[],this.directSignatures=[],this.users=[],this.subkeys=[],e&&(this.packetListToStructure(e,new Set([R.packet.secretKey,R.packet.secretSubkey])),!this.keyPacket))throw Error("Invalid key: missing public-key packet")}isPrivate(){return!1}toPublic(){return this}armor(e=L){const t=6!==this.keyPacket.version;return X(R.armor.publicKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}}class po extends go{constructor(e){if(super(),this.packetListToStructure(e,new Set([R.packet.publicKey,R.packet.publicSubkey])),!this.keyPacket)throw Error("Invalid key: missing private-key packet")}isPrivate(){return!0}toPublic(){const e=new Aa,t=this.toPacketList();for(const r of t)switch(r.constructor.tag){case R.packet.secretKey:{const t=Qa.fromSecretKeyPacket(r);e.push(t);break}case R.packet.secretSubkey:{const t=Ma.fromSecretSubkeyPacket(r);e.push(t);break}default:e.push(r)}return new go(e)}armor(e=L){const t=6!==this.keyPacket.version;return X(R.armor.privateKey,this.toPacketList().write(),void 0,void 0,void 0,t,e)}async getDecryptionKeys(e,t=new Date,r={},n=L){const i=this.keyPacket,s=[];let a=null;for(let r=0;re.isDecrypted()))}async validate(e=L){if(!this.isPrivate())throw Error("Cannot validate a public key");let t;if(this.keyPacket.isDummy()){const r=await this.getSigningKey(null,null,void 0,{...e,rejectPublicKeyAlgorithms:new Set,minRSABits:0});r&&!r.keyPacket.isDummy()&&(t=r.keyPacket)}else t=this.keyPacket;if(t)return t.validate();{const e=this.getKeys();if(e.map((e=>e.keyPacket.isDummy())).every(Boolean))throw Error("Cannot validate an all-gnu-dummy key");return Promise.all(e.map((async e=>e.keyPacket.validate())))}}clearPrivateParams(){this.getKeys().forEach((({keyPacket:e})=>{e.isDecrypted()&&e.clearPrivateParams()}))}async revoke({flag:e=R.reasonForRevocation.noReason,string:t=""}={},r=new Date,n=L){if(!this.isPrivate())throw Error("Need private key for revoking");const i={key:this.keyPacket},s=this.clone();return s.revocationSignatures.push(await Xa(i,[],this.keyPacket,{signatureType:R.signature.keyRevocation,reasonForRevocationFlag:R.write(R.reasonForRevocation,e),reasonForRevocationString:t},r,void 0,void 0,void 0,n)),s}async addSubkey(e={}){const t={...L,...e.config};if(e.passphrase)throw Error("Subkey could not be encrypted here, please encrypt whole key");if(e.rsaBitse!==t))]}function a(){const e={};e.keyFlags=[R.keyFlags.certifyKeys|R.keyFlags.signData];const t=s([R.symmetric.aes256,R.symmetric.aes128],n.preferredSymmetricAlgorithm);if(e.preferredSymmetricAlgorithms=t,n.aeadProtect){const r=s([R.aead.gcm,R.aead.eax,R.aead.ocb],n.preferredAEADAlgorithm);e.preferredCipherSuites=r.flatMap((e=>t.map((t=>[t,e]))))}return e.preferredHashAlgorithms=s([R.hash.sha256,R.hash.sha512,R.hash.sha3_256,R.hash.sha3_512],n.preferredHashAlgorithm),e.preferredCompressionAlgorithms=s([R.compression.uncompressed,R.compression.zlib,R.compression.zip],n.preferredCompressionAlgorithm),e.features=[0],e.features[0]|=R.features.modificationDetection,n.aeadProtect&&(e.features[0]|=R.features.seipdv2),r.keyExpirationTime>0&&(e.keyExpirationTime=r.keyExpirationTime,e.keyNeverExpires=!1),e}if(i.push(e),6===e.version){const t={key:e},s=a();s.signatureType=R.signature.key;const o=await Xa(t,[],e,s,r.date,void 0,void 0,void 0,n);i.push(o)}await Promise.all(r.userIDs.map((async function(t,i){const s=Oa.fromObject(t),o={userID:s,key:e},c=6!==e.version?a():{};c.signatureType=R.signature.certPositive,0===i&&(c.isPrimaryUserID=!0);return{userIDPacket:s,signaturePacket:await Xa(o,[],e,c,r.date,void 0,void 0,void 0,n)}}))).then((e=>{e.forEach((({userIDPacket:e,signaturePacket:t})=>{i.push(e),i.push(t)}))})),await Promise.all(t.map((async function(t,i){const s=r.subkeys[i];return{secretSubkeyPacket:t,subkeySignaturePacket:await $a(t,e,s,n)}}))).then((e=>{e.forEach((({secretSubkeyPacket:e,subkeySignaturePacket:t})=>{i.push(e),i.push(t)}))}));const o={key:e};return i.push(await Xa(o,[],e,{signatureType:R.signature.keyRevocation,reasonForRevocationFlag:R.reasonForRevocation.noReason,reasonForRevocationString:""},r.date,void 0,void 0,void 0,n)),r.passphrase&&e.clearPrivateParams(),await Promise.all(t.map((async function(e,t){r.subkeys[t].passphrase&&e.clearPrivateParams()}))),new po(i)}async function bo({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...L,...r},!e&&!t)throw Error("readKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!M.isString(e))throw Error("readKey: options.armoredKey must be a string");if(t&&!M.isUint8Array(t))throw Error("readKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await $(e);if(t!==R.armor.publicKey&&t!==R.armor.privateKey)throw Error("Armored text not of type key");s=r}else s=t;const a=await Aa.fromBinary(s,Ao,r),o=a.indexOfTag(R.packet.publicKey,R.packet.secretKey);if(0===o.length)throw Error("No key packet found");return wo(a.slice(o[0],o[1]))}async function ko({armoredKey:e,binaryKey:t,config:r,...n}){if(r={...L,...r},!e&&!t)throw Error("readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`");if(e&&!M.isString(e))throw Error("readPrivateKey: options.armoredKey must be a string");if(t&&!M.isUint8Array(t))throw Error("readPrivateKey: options.binaryKey must be a Uint8Array");const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));let s;if(e){const{type:t,data:r}=await $(e);if(t!==R.armor.privateKey)throw Error("Armored text not of type private key");s=r}else s=t;const a=await Aa.fromBinary(s,Ao,r),o=a.indexOfTag(R.packet.publicKey,R.packet.secretKey);for(let e=0;e0)throw Error("Unknown option: "+s.join(", "));if(e){const{type:t,data:r}=await $(e);if(t!==R.armor.publicKey&&t!==R.armor.privateKey)throw Error("Armored text not of type key");i=r}const a=[],o=await Aa.fromBinary(i,Ao,r),c=o.indexOfTag(R.packet.publicKey,R.packet.secretKey);if(0===c.length)throw Error("No key packet found");for(let e=0;e0)return t.map((e=>e.issuerKeyID));return e.packets.filterByTag(R.packet.signature).map((e=>e.issuerKeyID))}async decrypt(e,t,r,n=new Date,i=L){const s=this.packets.filterByTag(R.packet.symmetricallyEncryptedData,R.packet.symEncryptedIntegrityProtectedData,R.packet.aeadEncryptedData);if(0===s.length)throw Error("No encrypted data found");const a=s[0],o=a.cipherAlgorithm,c=r||await this.decryptSessionKeys(e,t,o,n,i);let h=null;const u=Promise.all(c.map((async({algorithm:e,data:t})=>{if(!M.isUint8Array(t)||!a.cipherAlgorithm&&!M.isString(e))throw Error("Invalid session key for decryption.");try{const r=a.cipherAlgorithm||R.write(R.symmetric,e);await a.decrypt(r,t,i)}catch(e){M.printDebugError(e),h=e}})));if(D(a.encrypted),a.encrypted=null,await u,!a.packets||!a.packets.length)throw h||Error("Decryption failed.");const l=new Ko(a.packets);return a.packets=new Aa,l}async decryptSessionKeys(e,t,r,n=new Date,i=L){let s,a=[];if(t){const e=this.packets.filterByTag(R.packet.symEncryptedSessionKey);if(0===e.length)throw Error("No symmetrically encrypted session key packet found.");await Promise.all(t.map((async function(t,r){let n;n=r?await Aa.fromBinary(e.write(),Io,i):e,await Promise.all(n.map((async function(e){try{await e.decrypt(t),a.push(e)}catch(e){M.printDebugError(e),e instanceof os&&(s=e)}})))})))}else{if(!e)throw Error("No key or password specified.");{const t=this.packets.filterByTag(R.packet.publicKeyEncryptedSessionKey);if(0===t.length)throw Error("No public key encrypted session key packet found.");await Promise.all(t.map((async function(t){await Promise.all(e.map((async function(e){let o;try{o=(await e.getDecryptionKeys(t.publicKeyID,null,void 0,i)).map((e=>e.keyPacket))}catch(e){return void(s=e)}let c=[R.symmetric.aes256,R.symmetric.aes128,R.symmetric.tripledes,R.symmetric.cast5];try{const t=await e.getPrimarySelfSignature(n,void 0,i);t.preferredSymmetricAlgorithms&&(c=c.concat(t.preferredSymmetricAlgorithms))}catch(e){}await Promise.all(o.map((async function(e){if(!e.isDecrypted())throw Error("Decryption key is not decrypted.");if(i.constantTimePKCS1Decryption&&(t.publicKeyAlgorithm===R.publicKey.rsaEncrypt||t.publicKeyAlgorithm===R.publicKey.rsaEncryptSign||t.publicKeyAlgorithm===R.publicKey.rsaSign||t.publicKeyAlgorithm===R.publicKey.elgamal)){const n=t.write();await Promise.all((r?[r]:Array.from(i.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map((async t=>{const r=new Pa;r.read(n);const i={sessionKeyAlgorithm:t,sessionKey:as.generateSessionKey(t)};try{await r.decrypt(e,i),a.push(r)}catch(e){M.printDebugError(e),s=e}})))}else try{await t.decrypt(e);const n=r||t.sessionKeyAlgorithm;if(n&&!c.includes(R.write(R.symmetric,n)))throw Error("A non-preferred symmetric algorithm was used.");a.push(t)}catch(e){M.printDebugError(e),s=e}})))}))),D(t.encrypted),t.encrypted=null})))}}if(a.length>0){if(a.length>1){const e=new Set;a=a.filter((t=>{const r=t.sessionKeyAlgorithm+M.uint8ArrayToString(t.sessionKey);return!e.has(r)&&(e.add(r),!0)}))}return a.map((e=>({data:e.sessionKey,algorithm:e.sessionKeyAlgorithm&&R.read(R.symmetric,e.sessionKeyAlgorithm)})))}throw s||Error("Session key decryption failed.")}getLiteralData(){const e=this.unwrapCompressed().packets.findPacket(R.packet.literalData);return e&&e.getBytes()||null}getFilename(){const e=this.unwrapCompressed().packets.findPacket(R.packet.literalData);return e&&e.getFilename()||null}getText(){const e=this.unwrapCompressed().packets.findPacket(R.packet.literalData);return e?e.getText():null}static async generateSessionKey(e=[],t=new Date,r=[],n=L){const{symmetricAlgo:i,aeadAlgo:s}=await async function(e=[],t=new Date,r=[],n=L){const i=await Promise.all(e.map(((e,i)=>e.getPrimarySelfSignature(t,r[i],n))));if(e.length?i.every((e=>e.features&&e.features[0]&R.features.seipdv2)):n.aeadProtect){const e={symmetricAlgo:R.symmetric.aes128,aeadAlgo:R.aead.ocb},t=[{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:n.preferredAEADAlgorithm},{symmetricAlgo:n.preferredSymmetricAlgorithm,aeadAlgo:R.aead.ocb},{symmetricAlgo:R.symmetric.aes128,aeadAlgo:n.preferredAEADAlgorithm}];for(const e of t)if(i.every((t=>t.preferredCipherSuites&&t.preferredCipherSuites.some((t=>t[0]===e.symmetricAlgo&&t[1]===e.aeadAlgo)))))return e;return e}const s=R.symmetric.aes128,a=n.preferredSymmetricAlgorithm;return{symmetricAlgo:i.every((e=>e.preferredSymmetricAlgorithms&&e.preferredSymmetricAlgorithms.includes(a)))?a:s,aeadAlgo:void 0}}(e,t,r,n),a=R.read(R.symmetric,i),o=s?R.read(R.aead,s):void 0;await Promise.all(e.map((e=>e.getEncryptionKey().catch((()=>null)).then((e=>{if(e&&(e.keyPacket.algorithm===R.publicKey.x25519||e.keyPacket.algorithm===R.publicKey.x448)&&!o&&!M.isAES(i))throw Error("Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.")})))));return{data:as.generateSessionKey(i),algorithm:a,aeadAlgorithm:o}}async encrypt(e,t,r,n=!1,i=[],s=new Date,a=[],o=L){if(r){if(!M.isUint8Array(r.data)||!M.isString(r.algorithm))throw Error("Invalid session key for encryption.")}else if(e&&e.length)r=await Ko.generateSessionKey(e,s,a,o);else{if(!t||!t.length)throw Error("No keys, passwords, or session key provided.");r=await Ko.generateSessionKey(void 0,void 0,void 0,o)}const{data:c,algorithm:h,aeadAlgorithm:u}=r,l=await Ko.encryptSessionKey(c,h,u,e,t,n,i,s,a,o),y=Sa.fromObject({version:u?2:1,aeadAlgorithm:u?R.write(R.aead,u):null});y.packets=this.packets;const f=R.write(R.symmetric,h);return await y.encrypt(f,c,o),l.packets.push(y),y.packets=new Aa,l}static async encryptSessionKey(e,t,r,n,i,s=!1,a=[],o=new Date,c=[],h=L){const u=new Aa,l=R.write(R.symmetric,t),y=r&&R.write(R.aead,r);if(n){const t=await Promise.all(n.map((async function(t,r){const n=await t.getEncryptionKey(a[r],o,c,h),i=Pa.fromObject({version:y?6:3,encryptionKeyPacket:n.keyPacket,anonymousRecipient:s,sessionKey:e,sessionKeyAlgorithm:l});return await i.encrypt(n.keyPacket),delete i.sessionKey,i})));u.push(...t)}if(i){const t=async function(e,t){try{return await e.decrypt(t),1}catch(e){return 0}},r=(e,t)=>e+t,n=async function(e,s,a,o){const c=new xa(h);if(c.sessionKey=e,c.sessionKeyAlgorithm=s,a&&(c.aeadAlgorithm=a),await c.encrypt(o,h),h.passwordCollisionCheck){if(1!==(await Promise.all(i.map((e=>t(c,e))))).reduce(r))return n(e,s,o)}return delete c.sessionKey,c},s=await Promise.all(i.map((t=>n(e,l,y,t))));u.push(...s)}return new Ko(u)}async sign(e=[],t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=L){const h=new Aa,u=this.packets.findPacket(R.packet.literalData);if(!u)throw Error("No literal data packet to sign.");const l=await Co(u,e,t,r,n,i,s,a,o,!1,c),y=l.map(((e,t)=>pa.fromSignaturePacket(e,0===t))).reverse();return h.push(...y),h.push(u),h.push(...l),new Ko(h)}compress(e,t=L){if(e===R.compression.uncompressed)return this;const r=new ma(t);r.algorithm=e,r.packets=this.packets;const n=new Aa;return n.push(r),new Ko(n)}async signDetached(e=[],t=[],r=null,n=[],i=[],s=new Date,a=[],o=[],c=L){const h=this.packets.findPacket(R.packet.literalData);if(!h)throw Error("No literal data packet to sign.");return new qa(await Co(h,e,t,r,n,i,s,a,o,!0,c))}async verify(e,t=new Date,r=L){const n=this.unwrapCompressed(),i=n.packets.filterByTag(R.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");o(n.packets.stream)&&n.packets.push(...await C(n.packets.stream,(e=>e||[])));const s=n.packets.filterByTag(R.packet.onePassSignature).reverse(),a=n.packets.filterByTag(R.packet.signature);return s.length&&!a.length&&M.isStream(n.packets.stream)&&!o(n.packets.stream)?(await Promise.all(s.map((async e=>{e.correspondingSig=new Promise(((t,r)=>{e.correspondingSigResolve=t,e.correspondingSigReject=r})),e.signatureData=P((async()=>(await e.correspondingSig).signatureData)),e.hashed=C(await e.hash(e.signatureType,i[0],void 0,!1)),e.hashed.catch((()=>{}))}))),n.packets.stream=E(n.packets.stream,(async(e,t)=>{const r=U(e),n=x(t);try{for(let e=0;e{t.correspondingSigReject(e)})),await n.abort(e)}})),Do(s,i,e,t,!1,r)):Do(a,i,e,t,!1,r)}verifyDetached(e,t,r=new Date,n=L){const i=this.unwrapCompressed().packets.filterByTag(R.packet.literalData);if(1!==i.length)throw Error("Can only verify message with one literal data packet.");return Do(e.packets.filterByTag(R.packet.signature),i,t,r,!0,n)}unwrapCompressed(){const e=this.packets.filterByTag(R.packet.compressedData);return e.length?new Ko(e[0].packets):this}async appendSignature(e,t=L){await this.packets.read(M.isUint8Array(e)?e:(await $(e)).data,So,t)}write(){return this.packets.write()}armor(e=L){const t=this.packets[this.packets.length-1],r=t.constructor.tag===Sa.tag?2!==t.version:this.packets.some((e=>e.constructor.tag===ya.tag&&6!==e.version));return X(R.armor.message,this.write(),null,null,null,r,e)}}async function Co(e,t,r=[],n=null,i=[],s=new Date,a=[],o=[],c=[],h=!1,u=L){const l=new Aa,y=null===e.text?R.signature.binary:R.signature.text;if(await Promise.all(t.map((async(t,n)=>{const l=a[n];if(!t.isPrivate())throw Error("Need private key for signing");const f=await t.getSigningKey(i[n],s,l,u);return Xa(e,r.length?r:[t],f.keyPacket,{signatureType:y},s,o,c,h,u)}))).then((e=>{l.push(...e)})),n){const e=n.packets.filterByTag(R.packet.signature);l.push(...e)}return l}async function Do(e,t,r,n=new Date,i=!1,s=L){return Promise.all(e.filter((function(e){return["text","binary"].includes(R.read(R.signature,e.signatureType))})).map((async function(e){return async function(e,t,r,n=new Date,i=!1,s=L){let a,o;for(const t of r){const r=t.getKeys(e.issuerKeyID);if(r.length>0){a=t,o=r[0];break}}const c=e instanceof pa?e.correspondingSig:e,h={keyID:e.issuerKeyID,verified:(async()=>{if(!o)throw Error("Could not find signing key with key ID "+e.issuerKeyID.toHex());await e.verify(o.keyPacket,e.signatureType,t[0],n,i,s);const r=await c;if(o.getCreationTime()>r.created)throw Error("Key is newer than the signature");try{await a.getSigningKey(o.getKeyID(),r.created,void 0,s)}catch(e){if(!s.allowInsecureVerificationWithReformattedKeys||!e.message.match(/Signature creation time is in the future/))throw e;await a.getSigningKey(o.getKeyID(),n,void 0,s)}return!0})(),signature:(async()=>{const e=await c,t=new Aa;return e&&t.push(e),new qa(t)})()};return h.signature.catch((()=>{})),h.verified.catch((()=>{})),h}(e,t,r,n,i,s)})))}async function Po({armoredMessage:e,binaryMessage:t,config:r,...n}){r={...L,...r};let i=e||t;if(!i)throw Error("readMessage: must pass options object containing `armoredMessage` or `binaryMessage`");if(e&&!M.isString(e)&&!M.isStream(e))throw Error("readMessage: options.armoredMessage must be a string or stream");if(t&&!M.isUint8Array(t)&&!M.isStream(t))throw Error("readMessage: options.binaryMessage must be a Uint8Array or stream");const s=Object.keys(n);if(s.length>0)throw Error("Unknown option: "+s.join(", "));const a=M.isStream(i);if(e){const{type:e,data:t}=await $(i);if(e!==R.armor.message)throw Error("Armored text not of type message");i=t}const o=await Aa.fromBinary(i,Bo,r),c=new Ko(o);return c.fromStream=a,c}async function Uo({text:e,binary:t,filename:r,date:n=new Date,format:i=(void 0!==e?"utf8":"binary"),...s}){const a=void 0!==e?e:t;if(void 0===a)throw Error("createMessage: must pass options object containing `text` or `binary`");if(e&&!M.isString(e)&&!M.isStream(e))throw Error("createMessage: options.text must be a string or stream");if(t&&!M.isUint8Array(t)&&!M.isStream(t))throw Error("createMessage: options.binary must be a Uint8Array or stream");const o=Object.keys(s);if(o.length>0)throw Error("Unknown option: "+o.join(", "));const c=M.isStream(a),h=new oa(n);void 0!==e?h.setText(a,R.write(R.literal,i)):h.setBytes(a,R.write(R.literal,i)),void 0!==r&&h.setFilename(r);const u=new Aa;u.push(h);const l=new Ko(u);return l.fromStream=c,l}const xo=/*#__PURE__*/M.constructAllowedPackets([ya]);class Qo{constructor(e,t){if(this.text=M.removeTrailingSpaces(e).replace(/\r?\n/g,"\r\n"),t&&!(t instanceof qa))throw Error("Invalid signature input");this.signature=t||new qa(new Aa)}getSigningKeyIDs(){const e=[];return this.signature.packets.forEach((function(t){e.push(t.issuerKeyID)})),e}async sign(e,t=[],r=null,n=[],i=new Date,s=[],a=[],o=[],c=L){const h=new oa;h.setText(this.text);const u=new qa(await Co(h,e,t,r,n,i,s,a,o,!0,c));return new Qo(this.text,u)}verify(e,t=new Date,r=L){const n=this.signature.packets.filterByTag(R.packet.signature),i=new oa;return i.setText(this.text),Do(n,[i],e,t,!0,r)}getText(){return this.text.replace(/\r\n/g,"\n")}armor(e=L){const t=this.signature.packets.some((e=>6!==e.version)),r={hash:t?Array.from(new Set(this.signature.packets.map((e=>R.read(R.hash,e.hashAlgorithm).toUpperCase())))).join():null,text:this.text,data:this.signature.packets.write()};return X(R.armor.signed,r,void 0,void 0,void 0,t,e)}}async function Ro({cleartextMessage:e,config:t,...r}){if(t={...L,...t},!e)throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");if(!M.isString(e))throw Error("readCleartextMessage: options.cleartextMessage must be a string");const n=Object.keys(r);if(n.length>0)throw Error("Unknown option: "+n.join(", "));const i=await $(e);if(i.type!==R.armor.signed)throw Error("No cleartext signed message.");const s=await Aa.fromBinary(i.data,xo,t);!function(e,t){const r=function(e){const r=e=>t=>e.hashAlgorithm===t;for(let n=0;n{const t=e.match(/^Hash: (.+)$/);if(!t)throw Error('Only "Hash" header allowed in cleartext signed message');{const e=t[1].replace(/\s/g,"").split(",").map((e=>{try{return R.write(R.hash,e.toLowerCase())}catch(t){throw Error("Unknown hash algorithm in armor header: "+e.toLowerCase())}}));n.push(...e)}})),n.length&&!r(n))throw Error("Hash algorithm mismatch in armor header and signature")}(i.headers,s);const a=new qa(s);return new Qo(i.text,a)}async function Lo({text:e,...t}){if(!e)throw Error("createCleartextMessage: must pass options object containing `text`");if(!M.isString(e))throw Error("createCleartextMessage: options.text must be a string");const r=Object.keys(t);if(r.length>0)throw Error("Unknown option: "+r.join(", "));return new Qo(e)}async function To({userIDs:e=[],passphrase:t,type:r,curve:n,rsaBits:i=4096,keyExpirationTime:s=0,date:a=new Date,subkeys:o=[{}],format:c="armored",config:h,...u}){$o(h={...L,...h}),r||n?(r=r||"ecc",n=n||"curve25519Legacy"):(r=h.v6Keys?"curve25519":"ecc",n="curve25519Legacy"),e=Xo(e);const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));if(0===e.length&&!h.v6Keys)throw Error("UserIDs are required for V4 keys");if("rsa"===r&&ino(e.subkeys[r],e)));let r=[Ya(e,t)];r=r.concat(e.subkeys.map((e=>Ja(e,t))));const n=await Promise.all(r),i=await mo(n[0],n.slice(1),e,t),s=await i.getRevocationCertificate(e.date,t);return i.revocationSignatures=[],{key:i,revocationCertificate:s}}(y,h);return e.getKeys().forEach((({keyPacket:e})=>oo(e,h))),{privateKey:rc(e,c,h),publicKey:rc(e.toPublic(),c,h),revocationCertificate:t}}catch(e){throw M.wrapError("Error generating keypair",e)}}async function Mo({privateKey:e,userIDs:t=[],passphrase:r,keyExpirationTime:n=0,date:i,format:s="armored",config:a,...o}){$o(a={...L,...a}),t=Xo(t);const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(0===t.length&&6!==e.keyPacket.version)throw Error("UserIDs are required for V4 keys");const h={privateKey:e,userIDs:t,passphrase:r,keyExpirationTime:n,date:i};try{const{key:e,revocationCertificate:t}=await async function(e,t){e=o(e);const{privateKey:r}=e;if(!r.isPrivate())throw Error("Cannot reformat a public key");if(r.keyPacket.isDummy())throw Error("Cannot reformat a gnu-dummy primary key");if(!r.getKeys().every((({keyPacket:e})=>e.isDecrypted())))throw Error("Key is not decrypted");const n=r.keyPacket;e.subkeys||(e.subkeys=await Promise.all(r.subkeys.map((async e=>{const r=e.keyPacket,i={key:n,bind:r},s=await Wa(e.bindingSignatures,n,R.signature.subkeyBinding,i,null,t).catch((()=>({})));return{sign:s.keyFlags&&s.keyFlags[0]&R.keyFlags.signData}}))));const i=r.subkeys.map((e=>e.keyPacket));if(e.subkeys.length!==i.length)throw Error("Number of subkey options does not match number of subkeys");e.subkeys=e.subkeys.map((t=>o(t,e)));const s=await mo(n,i,e,t),a=await s.getRevocationCertificate(e.date,t);return s.revocationSignatures=[],{key:s,revocationCertificate:a};function o(e,t={}){return e.keyExpirationTime=e.keyExpirationTime||t.keyExpirationTime,e.passphrase=M.isString(e.passphrase)?e.passphrase:t.passphrase,e.date=e.date||t.date,e}}(h,a);return{privateKey:rc(e,s,a),publicKey:rc(e.toPublic(),s,a),revocationCertificate:t}}catch(e){throw M.wrapError("Error reformatting keypair",e)}}async function No({key:e,revocationCertificate:t,reasonForRevocation:r,date:n=new Date,format:i="armored",config:s,...a}){$o(s={...L,...s});const o=Object.keys(a);if(o.length>0)throw Error("Unknown option: "+o.join(", "));try{const a=t?await e.applyRevocationCertificate(t,n,s):await e.revoke(r,n,s);return a.isPrivate()?{privateKey:rc(a,i,s),publicKey:rc(a.toPublic(),i,s)}:{privateKey:null,publicKey:rc(a,i,s)}}catch(e){throw M.wrapError("Error revoking key",e)}}async function Fo({privateKey:e,passphrase:t,config:r,...n}){$o(r={...L,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot decrypt a public key");const s=e.clone(!0),a=M.isArray(t)?t:[t];try{return await Promise.all(s.getKeys().map((e=>M.anyPromise(a.map((t=>e.keyPacket.decrypt(t))))))),await s.validate(r),s}catch(e){throw s.clearPrivateParams(),M.wrapError("Error decrypting private key",e)}}async function Ho({privateKey:e,passphrase:t,config:r,...n}){$o(r={...L,...r});const i=Object.keys(n);if(i.length>0)throw Error("Unknown option: "+i.join(", "));if(!e.isPrivate())throw Error("Cannot encrypt a public key");const s=e.clone(!0),a=s.getKeys(),o=M.isArray(t)?t:Array(a.length).fill(t);if(o.length!==a.length)throw Error("Invalid number of passphrases given for key encryption");try{return await Promise.all(a.map((async(e,t)=>{const{keyPacket:n}=e;await n.encrypt(o[t],r),n.clearPrivateParams()}))),s}catch(e){throw s.clearPrivateParams(),M.wrapError("Error encrypting private key",e)}}async function Oo({message:e,encryptionKeys:t,signingKeys:r,passwords:n,sessionKey:i,format:s="armored",signature:a=null,wildcard:o=!1,signingKeyIDs:c=[],encryptionKeyIDs:h=[],date:u=new Date,signingUserIDs:l=[],encryptionUserIDs:y=[],signatureNotations:f=[],config:g,...p}){if($o(g={...L,...g}),Jo(e),Wo(s),t=Xo(t),r=Xo(r),n=Xo(n),c=Xo(c),h=Xo(h),l=Xo(l),y=Xo(y),f=Xo(f),p.detached)throw Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");if(p.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead");if(p.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead");if(void 0!==p.armor)throw Error("The `armor` option has been removed from openpgp.encrypt, pass `format` instead.");const d=Object.keys(p);if(d.length>0)throw Error("Unknown option: "+d.join(", "));r||(r=[]);try{if((r.length||a)&&(e=await e.sign(r,t,a,c,u,l,h,f,g)),e=e.compress(await async function(e=[],t=new Date,r=[],n=L){const i=R.compression.uncompressed,s=n.preferredCompressionAlgorithm,a=await Promise.all(e.map((async function(e,i){const a=(await e.getPrimarySelfSignature(t,r[i],n)).preferredCompressionAlgorithms;return!!a&&a.indexOf(s)>=0})));return a.every(Boolean)?s:i}(t,u,y,g),g),e=await e.encrypt(t,n,i,o,h,u,y,g),"object"===s)return e;const p="armored"===s?e.armor(g):e.write();return await ec(p)}catch(e){throw M.wrapError("Error encrypting message",e)}}async function zo({message:e,decryptionKeys:t,passwords:r,sessionKeys:n,verificationKeys:i,expectSigned:s=!1,format:a="utf8",signature:o=null,date:c=new Date,config:h,...u}){if($o(h={...L,...h}),Jo(e),i=Xo(i),t=Xo(t),r=Xo(r),n=Xo(n),u.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead");if(u.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead");const l=Object.keys(u);if(l.length>0)throw Error("Unknown option: "+l.join(", "));try{const u=await e.decrypt(t,r,n,c,h);i||(i=[]);const l={};if(l.signatures=o?await u.verifyDetached(o,i,c,h):await u.verify(i,c,h),l.data="binary"===a?u.getLiteralData():u.getText(),l.filename=u.getFilename(),tc(l,e),s){if(0===i.length)throw Error("Verification keys are required to verify message signatures");if(0===l.signatures.length)throw Error("Message is not signed");l.data=A([l.data,P((async()=>{await M.anyPromise(l.signatures.map((e=>e.verified)))}))])}return l.data=await ec(l.data),l}catch(e){throw M.wrapError("Error decrypting message",e)}}async function _o({message:e,signingKeys:t,recipientKeys:r=[],format:n="armored",detached:i=!1,signingKeyIDs:s=[],date:a=new Date,signingUserIDs:o=[],recipientUserIDs:c=[],signatureNotations:h=[],config:u,...l}){if($o(u={...L,...u}),Yo(e),Wo(n),t=Xo(t),s=Xo(s),o=Xo(o),r=Xo(r),c=Xo(c),h=Xo(h),l.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead");if(void 0!==l.armor)throw Error("The `armor` option has been removed from openpgp.sign, pass `format` instead.");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(e instanceof Qo&&"binary"===n)throw Error("Cannot return signed cleartext message in binary format");if(e instanceof Qo&&i)throw Error("Cannot detach-sign a cleartext message");if(!t||0===t.length)throw Error("No signing keys provided");try{let l;if(l=i?await e.signDetached(t,r,void 0,s,a,o,c,h,u):await e.sign(t,r,void 0,s,a,o,c,h,u),"object"===n)return l;return l="armored"===n?l.armor(u):l.write(),i&&(l=E(e.packets.write(),(async(e,t)=>{await Promise.all([w(l,t),C(e).catch((()=>{}))])}))),await ec(l)}catch(e){throw M.wrapError("Error signing message",e)}}async function Go({message:e,verificationKeys:t,expectSigned:r=!1,format:n="utf8",signature:i=null,date:s=new Date,config:a,...o}){if($o(a={...L,...a}),Yo(e),t=Xo(t),o.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");const c=Object.keys(o);if(c.length>0)throw Error("Unknown option: "+c.join(", "));if(e instanceof Qo&&"binary"===n)throw Error("Can't return cleartext message data as binary");if(e instanceof Qo&&i)throw Error("Can't verify detached cleartext signature");try{const o={};if(o.signatures=i?await e.verifyDetached(i,t,s,a):await e.verify(t,s,a),o.data="binary"===n?e.getLiteralData():e.getText(),e.fromStream&&!i&&tc(o,e),r){if(0===o.signatures.length)throw Error("Message is not signed");o.data=A([o.data,P((async()=>{await M.anyPromise(o.signatures.map((e=>e.verified)))}))])}return o.data=await ec(o.data),o}catch(e){throw M.wrapError("Error verifying signed message",e)}}async function jo({encryptionKeys:e,date:t=new Date,encryptionUserIDs:r=[],config:n,...i}){if($o(n={...L,...n}),e=Xo(e),r=Xo(r),i.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead");const s=Object.keys(i);if(s.length>0)throw Error("Unknown option: "+s.join(", "));try{return await Ko.generateSessionKey(e,t,r,n)}catch(e){throw M.wrapError("Error generating session key",e)}}async function qo({data:e,algorithm:t,aeadAlgorithm:r,encryptionKeys:n,passwords:i,format:s="armored",wildcard:a=!1,encryptionKeyIDs:o=[],date:c=new Date,encryptionUserIDs:h=[],config:u,...l}){if($o(u={...L,...u}),function(e){if(!M.isUint8Array(e))throw Error("Parameter [data] must be of type Uint8Array")}(e),function(e,t){if(!M.isString(e))throw Error("Parameter ["+t+"] must be of type String")}(t,"algorithm"),Wo(s),n=Xo(n),i=Xo(i),o=Xo(o),h=Xo(h),l.publicKeys)throw Error("The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead");const y=Object.keys(l);if(y.length>0)throw Error("Unknown option: "+y.join(", "));if(!(n&&0!==n.length||i&&0!==i.length))throw Error("No encryption keys or passwords provided.");try{return rc(await Ko.encryptSessionKey(e,t,r,n,i,a,o,c,h,u),s,u)}catch(e){throw M.wrapError("Error encrypting session key",e)}}async function Vo({message:e,decryptionKeys:t,passwords:r,date:n=new Date,config:i,...s}){if($o(i={...L,...i}),Jo(e),t=Xo(t),r=Xo(r),s.privateKeys)throw Error("The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead");const a=Object.keys(s);if(a.length>0)throw Error("Unknown option: "+a.join(", "));try{return await e.decryptSessionKeys(t,r,void 0,n,i)}catch(e){throw M.wrapError("Error decrypting session keys",e)}}function Jo(e){if(!(e instanceof Ko))throw Error("Parameter [message] needs to be of type Message")}function Yo(e){if(!(e instanceof Qo||e instanceof Ko))throw Error("Parameter [message] needs to be of type Message or CleartextMessage")}function Wo(e){if("armored"!==e&&"binary"!==e&&"object"!==e)throw Error("Unsupported format "+e)}const Zo=Object.keys(L).length;function $o(e){const t=Object.keys(e);if(t.length!==Zo)for(const e of t)if(void 0===L[e])throw Error("Unknown config property: "+e)}function Xo(e){return e&&!M.isArray(e)&&(e=[e]),e}async function ec(e){return"array"===M.isStream(e)?C(e):e}function tc(e,t){e.data=E(t.packets.stream,(async(t,r)=>{await w(e.data,r,{preventClose:!0});const n=x(r);try{await C(t,(e=>e)),await n.close()}catch(e){await n.abort(e)}}))}function rc(e,t,r){switch(t){case"object":return e;case"armored":return e.armor(r);case"binary":return e.write();default:throw Error("Unsupported format "+t)}}function nc(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, not "+e)}function ic(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function sc(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ac(e,t){ic(e);const r=t.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),hc=(e,t)=>e<<32-t|e>>>t,uc=(e,t)=>e<>>32-t>>>0,lc=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yc(e){for(let r=0;r>>8&65280|t>>>24&255;var t}function fc(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function gc(e){return"string"==typeof e&&(e=fc(e)),ic(e),e}function pc(...e){let t=0;for(let r=0;re().update(gc(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function wc(e=32){if(oc&&"function"==typeof oc.getRandomValues)return oc.getRandomValues(new Uint8Array(e));if(oc&&"function"==typeof oc.randomBytes)return oc.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}const mc=(e,t,r)=>e&t^~e&r,bc=(e,t,r)=>e&t^e&r^t&r;class kc extends dc{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=cc(this.buffer)}update(e){sc(this);const{view:t,buffer:r,blockLen:n}=this,i=(e=gc(e)).length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let e=s;e>i&s),o=Number(r&s),c=n?4:0,h=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+h,o,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const a=cc(e),o=this.outputLen;if(o%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=hc(r,17)^hc(r,19)^r>>>10;Bc[e]=i+Bc[e-7]+n+Bc[e-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(hc(a,6)^hc(a,11)^hc(a,25))+mc(a,o,c)+Ec[e]+Bc[e]|0,u=(hc(r,2)^hc(r,13)^hc(r,22))+bc(r,n,i)|0;h=c,c=o,o=a,a=s+t|0,s=i,i=n,n=r,r=t+u|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(r,n,i,s,a,o,c,h)}roundClean(){Bc.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Sc extends Ic{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Kc=/* @__PURE__ */Ac((()=>new Ic)),Cc=/* @__PURE__ */Ac((()=>new Sc));class Dc extends dc{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.wrapConstructor");nc(e.outputLen),nc(e.blockLen)}(e);const r=gc(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew Dc(e,t).update(r).digest();Pc.create=(e,t)=>new Dc(e,t) +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const Uc=/* @__PURE__ */BigInt(0),xc=/* @__PURE__ */BigInt(1),Qc=/* @__PURE__ */BigInt(2);function Rc(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Lc(e){if(!Rc(e))throw Error("Uint8Array expected")}function Tc(e,t){if("boolean"!=typeof t)throw Error(`${e} must be valid boolean, got "${t}".`)}const Mc=/* @__PURE__ */Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Nc(e){Lc(e);let t="";for(let r=0;r=Oc._0&&e<=Oc._9?e-Oc._0:e>=Oc._A&&e<=Oc._F?e-(Oc._A-10):e>=Oc._a&&e<=Oc._f?e-(Oc._a-10):void 0}function _c(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,i=0;t"bigint"==typeof e&&Uc<=e;function Zc(e,t,r){return Wc(e)&&Wc(t)&&Wc(r)&&t<=e&&eUc;e>>=xc,t+=1);return t}const eh=e=>(Qc<new Uint8Array(e),rh=e=>Uint8Array.from(e);function nh(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");let n=th(e),i=th(e),s=0;const a=()=>{n.fill(1),i.fill(0),s=0},o=(...e)=>r(i,n,...e),c=(e=th())=>{i=o(rh([0]),e),n=o(),0!==e.length&&(i=o(rh([1]),e),n=o())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(a(),c(e);!(r=t(h()));)c();return a(),r}}const ih={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Rc(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function sh(e,t,r={}){const n=(t,r,n)=>{const i=ih[r];if("function"!=typeof i)throw Error(`Invalid validator "${r}", expected function`);const s=e[t];if(!(n&&void 0===s||i(s,e)))throw Error(`Invalid param ${t+""}=${s} (${typeof s}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function ah(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const s=e(r,...n);return t.set(r,s),s}}var oh=/*#__PURE__*/Object.freeze({__proto__:null,aInRange:$c,abool:Tc,abytes:Lc,bitGet:function(e,t){return e>>BigInt(t)&xc},bitLen:Xc,bitMask:eh,bitSet:function(e,t,r){return e|(r?xc:Uc)<{throw Error("not implemented")},numberToBytesBE:qc,numberToBytesLE:Vc,numberToHexUnpadded:Fc,numberToVarBytesBE:function(e){return _c(Fc(e))},utf8ToBytes:function(e){if("string"!=typeof e)throw Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))},validateObject:sh}); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ch=BigInt(0),hh=BigInt(1),uh=BigInt(2),lh=BigInt(3),yh=BigInt(4),fh=BigInt(5),gh=BigInt(8);function ph(e,t){const r=e%t;return r>=ch?r:t+r}function dh(e,t,r){if(r<=ch||t 0");if(r===hh)return ch;let n=hh;for(;t>ch;)t&hh&&(n=n*e%r),e=e*e%r,t>>=hh;return n}function Ah(e,t,r){let n=e;for(;t-- >ch;)n*=n,n%=r;return n}function wh(e,t){if(e===ch||t<=ch)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ph(e,t),n=t,i=ch,s=hh;for(;r!==ch;){const e=n%r,t=i-s*(n/r);n=r,r=e,i=s,s=t}if(n!==hh)throw Error("invert: does not exist");return ph(i,t)}function mh(e){if(e%yh===lh){const t=(e+hh)/yh;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}if(e%gh===fh){const t=(e-fh)/gh;return function(e,r){const n=e.mul(r,uh),i=e.pow(n,t),s=e.mul(r,i),a=e.mul(e.mul(s,uh),i),o=e.mul(s,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),r))throw Error("Cannot find square root");return o}}return function(e){const t=(e-hh)/uh;let r,n,i;for(r=e-hh,n=0;r%uh===ch;r/=uh,n++);for(i=uh;i 0, got "+e);const{nBitLength:i,nByteLength:s}=kh(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const a=mh(e),o=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:eh(i),ZERO:ch,ONE:hh,create:t=>ph(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("Invalid field element: expected bigint, got "+typeof t);return ch<=t&&te===ch,isOdd:e=>(e&hh)===hh,neg:t=>ph(-t,e),eql:(e,t)=>e===t,sqr:t=>ph(t*t,e),add:(t,r)=>ph(t+r,e),sub:(t,r)=>ph(t-r,e),mul:(t,r)=>ph(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===ch)return e.ONE;if(r===hh)return t;let n=e.ONE,i=t;for(;r>ch;)r&hh&&(n=e.mul(n,i)),i=e.sqr(i),r>>=hh;return n}(o,e,t),div:(t,r)=>ph(t*wh(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>wh(t,e),sqrt:n.sqrt||(e=>a(o,e)),invertBatch:e=>function(e,t){const r=Array(t.length),n=t.reduce(((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n))),e.ONE),i=e.inv(n);return t.reduceRight(((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n))),i),r}(o,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Vc(e,s):qc(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?jc(e):Gc(e)}});return Object.freeze(o)}function vh(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Bh(e){const t=vh(e);return t+Math.ceil(t/2)} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const Ih=BigInt(0),Sh=BigInt(1),Kh=new WeakMap,Ch=new WeakMap;function Dh(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`Wrong window size=${e}, should be [1..${t}]`)},i=e=>{n(e);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}};return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,i=t;for(;r>Ih;)r&Sh&&(n=n.add(i)),i=i.double(),r>>=Sh;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=i(t),s=[];let a=e,o=a;for(let e=0;e>=y,i>o&&(i-=l,s+=Sh);const a=t,f=t+Math.abs(i)-1,g=e%2!=0,p=i<0;0===i?h=h.add(r(g,n[a])):c=c.add(r(p,n[f]))}return{p:c,f:h}},wNAFCached(e,t,r){const n=Ch.get(e)||1;let i=Kh.get(e);return i||(i=this.precomputeWindow(e,n),1!==n&&Kh.set(e,r(i))),this.wNAF(n,i,t)},setWindowSize(e,t){n(t),Ch.set(e,t),Kh.delete(e)}}}function Ph(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw Error("wrong scalar at index "+r)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw Error("wrong point at index "+r)}));const i=Xc(BigInt(r.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<=0;t-=s){o.fill(e.ZERO);for(let e=0;e>BigInt(t)&BigInt(a));o[s]=o[s].add(r[e])}let i=e.ZERO;for(let t=o.length-1,r=e.ZERO;t>0;t--)r=r.add(o[t]),i=i.add(r);if(h=h.add(i),0!==t)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),sh(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...kh(e.n,e.nBitLength),...e,p:e.Fp.ORDER})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xh(e){void 0!==e.lowS&&Tc("lowS",e.lowS),void 0!==e.prehash&&Tc("prehash",e.prehash)}const{bytesToNumberBE:Qh,hexToBytes:Rh}=oh,Lh={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=Lh;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=Fc(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Fc(i.length/2|128):"";return`${Fc(e)}${s}${i}${t}`},decode(e,t){const{Err:r}=Lh;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let s=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const a=t.subarray(n,n+e);if(a.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=Lh;if(e{const i=t.toAffine();return Yc(Uint8Array.from([4]),r.toBytes(i.x),r.toBytes(i.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function a(e){const{a:n,b:i}=t,s=r.sqr(e),a=r.mul(s,e);return r.add(r.add(a,r.mul(e,n)),i)}if(!r.eql(r.sqr(t.Gy),a(t.Gx)))throw Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:i,n:s}=t;if(r&&"bigint"!=typeof e){if(Rc(e)&&(e=Nc(e)),"string"!=typeof e||!r.includes(e.length))throw Error("Invalid key");e=e.padStart(2*n,"0")}let a;try{a="bigint"==typeof e?e:Gc(Jc("private key",e,n))}catch(t){throw Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return i&&(a=ph(a,s)),$c("private key",a,Mh,s),a}function c(e){if(!(e instanceof l))throw Error("ProjectivePoint expected")}const h=ah(((e,t)=>{const{px:n,py:i,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),c=r.mul(i,t),h=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(h,r.ONE))throw Error("invZ was invalid");return{x:o,y:c}})),u=ah((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error("bad point: x or y not FE");const s=r.sqr(i),o=a(n);if(!r.eql(s,o))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));class l{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t))throw Error("y required");if(null==n||!r.isValid(n))throw Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error("invalid affine point");if(e instanceof l)throw Error("projective point not allowed");const i=e=>r.eql(e,r.ZERO);return i(t)&&i(n)?l.ZERO:new l(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(l.fromAffine)}static fromHex(e){const t=l.fromAffine(s(Jc("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return l.BASE.multiply(o(e))}static msm(e,t){return Ph(l,n,e,t)}_setWindowSize(e){f.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:i}=this,{px:s,py:a,pz:o}=e,h=r.eql(r.mul(t,o),r.mul(s,i)),u=r.eql(r.mul(n,o),r.mul(a,i));return h&&u}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,i=r.mul(n,Nh),{px:s,py:a,pz:o}=this;let c=r.ZERO,h=r.ZERO,u=r.ZERO,y=r.mul(s,s),f=r.mul(a,a),g=r.mul(o,o),p=r.mul(s,a);return p=r.add(p,p),u=r.mul(s,o),u=r.add(u,u),c=r.mul(e,u),h=r.mul(i,g),h=r.add(c,h),c=r.sub(f,h),h=r.add(f,h),h=r.mul(c,h),c=r.mul(p,c),u=r.mul(i,u),g=r.mul(e,g),p=r.sub(y,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(y,y),y=r.add(u,y),y=r.add(y,g),y=r.mul(y,p),h=r.add(h,y),g=r.mul(a,o),g=r.add(g,g),y=r.mul(g,p),c=r.sub(c,y),u=r.mul(g,f),u=r.add(u,u),u=r.add(u,u),new l(c,h,u)}add(e){c(e);const{px:n,py:i,pz:s}=this,{px:a,py:o,pz:h}=e;let u=r.ZERO,y=r.ZERO,f=r.ZERO;const g=t.a,p=r.mul(t.b,Nh);let d=r.mul(n,a),A=r.mul(i,o),w=r.mul(s,h),m=r.add(n,i),b=r.add(a,o);m=r.mul(m,b),b=r.add(d,A),m=r.sub(m,b),b=r.add(n,s);let k=r.add(a,h);return b=r.mul(b,k),k=r.add(d,w),b=r.sub(b,k),k=r.add(i,s),u=r.add(o,h),k=r.mul(k,u),u=r.add(A,w),k=r.sub(k,u),f=r.mul(g,b),u=r.mul(p,w),f=r.add(u,f),u=r.sub(A,f),f=r.add(A,f),y=r.mul(u,f),A=r.add(d,d),A=r.add(A,d),w=r.mul(g,w),b=r.mul(p,b),A=r.add(A,w),w=r.sub(d,w),w=r.mul(g,w),b=r.add(b,w),d=r.mul(A,b),y=r.add(y,d),d=r.mul(k,b),u=r.mul(m,u),u=r.sub(u,d),d=r.mul(m,A),f=r.mul(k,f),f=r.add(f,d),new l(u,y,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(l.ZERO)}wNAF(e){return f.wNAFCached(this,e,l.normalizeZ)}multiplyUnsafe(e){$c("scalar",e,Th,t.n);const n=l.ZERO;if(e===Th)return n;if(e===Mh)return this;const{endo:i}=t;if(!i)return f.unsafeLadder(this,e);let{k1neg:s,k1:a,k2neg:o,k2:c}=i.splitScalar(e),h=n,u=n,y=this;for(;a>Th||c>Th;)a&Mh&&(h=h.add(y)),c&Mh&&(u=u.add(y)),y=y.double(),a>>=Mh,c>>=Mh;return s&&(h=h.negate()),o&&(u=u.negate()),u=new l(r.mul(u.px,i.beta),u.py,u.pz),h.add(u)}multiply(e){const{endo:n,n:i}=t;let s,a;if($c("scalar",e,Mh,i),n){const{k1neg:t,k1:i,k2neg:o,k2:c}=n.splitScalar(e);let{p:h,f:u}=this.wNAF(i),{p:y,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),y=f.constTimeNegate(o,y),y=new l(r.mul(y.px,n.beta),y.py,y.pz),s=h.add(y),a=u.add(g)}else{const{p:t,f:r}=this.wNAF(e);s=t,a=r}return l.normalizeZ([s,a])[0]}multiplyAndAddUnsafe(e,t,r){const n=l.BASE,i=(e,t)=>t!==Th&&t!==Mh&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=i(this,t).add(i(e,r));return s.is0()?void 0:s}toAffine(e){return h(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Mh)return!0;if(r)return r(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===Mh?this:r?r(l,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Tc("isCompressed",e),this.assertValidity(),i(l,this,e)}toHex(e=!0){return Tc("isCompressed",e),Nc(this.toRawBytes(e))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);const y=t.nBitLength,f=Dh(l,t.endo?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:o,weierstrassEquation:a,isWithinCurveOrder:function(e){return Zc(e,Mh,t.n)}}}function Hh(e){const t=function(e){const t=Uh(e);return sh(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,i=r.BYTES+1,s=2*r.BYTES+1;function a(e){return ph(e,n)}function o(e){return wh(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:l}=Fh({...t,toBytes(e,t,n){const i=t.toAffine(),s=r.toBytes(i.x),a=Yc;return Tc("isCompressed",n),n?a(Uint8Array.from([t.hasEvenY()?2:3]),s):a(Uint8Array.from([4]),s,r.toBytes(i.y))},fromBytes(e){const t=e.length,n=e[0],a=e.subarray(1);if(t!==i||2!==n&&3!==n){if(t===s&&4===n){return{x:r.fromBytes(a.subarray(0,r.BYTES)),y:r.fromBytes(a.subarray(r.BYTES,2*r.BYTES))}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const e=Gc(a);if(!Zc(e,Mh,r.ORDER))throw Error("Point is not on curve");const t=u(e);let i;try{i=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+t)}return!(1&~n)!==((i&Mh)===Mh)&&(i=r.neg(i)),{x:e,y:i}}}}),y=e=>Nc(qc(e,t.nByteLength));function f(e){return e>n>>Mh}const g=(e,t,r)=>Gc(e.slice(t,r));class p{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Jc("compactSignature",e,2*r),new p(g(e,0,r),g(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Lh.toSig(Jc("DER",e));return new p(t,r)}assertValidity(){$c("r",this.r,Mh,n),$c("s",this.s,Mh,n)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:i,recovery:s}=this,h=m(Jc("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+y(u)),g=o(u),p=a(-h*g),d=a(i*g),A=c.BASE.multiplyAndAddUnsafe(f,p,d);if(!A)throw Error("point at infinify");return A.assertValidity(),A}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return _c(this.toDERHex())}toDERHex(){return Lh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return _c(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}const d={isValidPrivateKey(e){try{return h(e),!0}catch(e){return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const e=Bh(t.n);return function(e,t,r=!1){const n=e.length,i=vh(t),s=Bh(t);if(n<16||n1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);const a=ph(r?Gc(e):jc(e),t-hh)+hh;return r?Vc(a,i):qc(a,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function A(e){const t=Rc(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===i||n===s:r?n===2*i||n===2*s:e instanceof c}const w=t.bits2int||function(e){const r=Gc(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},m=t.bits2int_modN||function(e){return a(w(e))},b=eh(t.nBitLength);function k(e){return $c("num < 2^"+t.nBitLength,e,Th,b),qc(e,t.nByteLength)}function E(e,n,i=v){if(["recovered","canonical"].some((e=>e in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:y,prehash:g,extraEntropy:d}=i;null==y&&(y=!0),e=Jc("msgHash",e),xh(i),g&&(e=Jc("prehashed msgHash",s(e)));const A=m(e),b=h(n),E=[k(b),k(A)];if(null!=d&&!1!==d){const e=!0===d?u(r.BYTES):d;E.push(Jc("extraEntropy",e))}const B=Yc(...E),I=A;return{seed:B,k2sig:function(e){const t=w(e);if(!l(t))return;const r=o(t),n=c.BASE.multiply(t).toAffine(),i=a(n.x);if(i===Th)return;const s=a(r*a(I+i*b));if(s===Th)return;let h=(n.x===i?0:2)|Number(n.y&Mh),u=s;return y&&f(s)&&(u=function(e){return f(e)?a(-e):e}(s),h^=1),new p(i,u,h)}}}const v={lowS:t.lowS,prehash:!1},B={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(A(e))throw Error("first arg must be private key");if(!A(t))throw Error("second arg must be public key");return c.fromHex(t).multiply(h(e)).toRawBytes(r)},sign:function(e,r,n=v){const{seed:i,k2sig:s}=E(e,r,n),a=t;return nh(a.hash.outputLen,a.nByteLength,a.hmac)(i,s)},verify:function(e,r,n,i=B){const s=e;if(r=Jc("msgHash",r),n=Jc("publicKey",n),"strict"in i)throw Error("options.strict was renamed to lowS");xh(i);const{lowS:h,prehash:u}=i;let l,y;try{if("string"==typeof s||Rc(s))try{l=p.fromDER(s)}catch(e){if(!(e instanceof Lh.Err))throw e;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:e,s:t}=s;l=new p(e,t)}}y=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;u&&(r=t.hash(r));const{r:f,s:g}=l,d=m(r),A=o(g),w=a(d*A),b=a(f*A),k=c.BASE.multiplyAndAddUnsafe(y,w,b)?.toAffine();return!!k&&a(k.x)===f},ProjectivePoint:c,Signature:p,utils:d}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Oh(e){return{hash:e,hmac:(t,...r)=>Pc(e,t,pc(...r)),randomBytes:wc}}function zh(e,t){const r=t=>Hh({...e,...Oh(t)});return Object.freeze({...r(t),create:r})} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const _h=Eh(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Gh=zh({a:_h.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:_h,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Kc),jh=/* @__PURE__ */BigInt(2**32-1),qh=/* @__PURE__ */BigInt(32);function Vh(e,t=!1){return t?{h:Number(e&jh),l:Number(e>>qh&jh)}:{h:0|Number(e>>qh&jh),l:0|Number(e&jh)}}function Jh(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;ie<>>32-r,Wh=(e,t,r)=>t<>>32-r,Zh=(e,t,r)=>t<>>64-r,$h=(e,t,r)=>e<>>64-r;const Xh={fromBig:Vh,split:Jh,toBig:(e,t)=>BigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:Yh,rotlSL:Wh,rotlBH:Zh,rotlBL:$h,add:function(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,add5H:(e,t,r,n,i,s)=>t+r+n+i+s+(e/2**32|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},[eu,tu]=/* @__PURE__ */(()=>Xh.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),ru=/* @__PURE__ */new Uint32Array(80),nu=/* @__PURE__ */new Uint32Array(80);class iu extends kc{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:h,Fh:u,Fl:l,Gh:y,Gl:f,Hh:g,Hl:p}=this;return[e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p]}set(e,t,r,n,i,s,a,o,c,h,u,l,y,f,g,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|h,this.Fh=0|u,this.Fl=0|l,this.Gh=0|y,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(e,t){for(let r=0;r<16;r++,t+=4)ru[r]=e.getUint32(t),nu[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ru[e-15],r=0|nu[e-15],n=Xh.rotrSH(t,r,1)^Xh.rotrSH(t,r,8)^Xh.shrSH(t,r,7),i=Xh.rotrSL(t,r,1)^Xh.rotrSL(t,r,8)^Xh.shrSL(t,r,7),s=0|ru[e-2],a=0|nu[e-2],o=Xh.rotrSH(s,a,19)^Xh.rotrBH(s,a,61)^Xh.shrSH(s,a,6),c=Xh.rotrSL(s,a,19)^Xh.rotrBL(s,a,61)^Xh.shrSL(s,a,6),h=Xh.add4L(i,c,nu[e-7],nu[e-16]),u=Xh.add4H(h,n,o,ru[e-7],ru[e-16]);ru[e]=0|u,nu[e]=0|h}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:h,Eh:u,El:l,Fh:y,Fl:f,Gh:g,Gl:p,Hh:d,Hl:A}=this;for(let e=0;e<80;e++){const t=Xh.rotrSH(u,l,14)^Xh.rotrSH(u,l,18)^Xh.rotrBH(u,l,41),w=Xh.rotrSL(u,l,14)^Xh.rotrSL(u,l,18)^Xh.rotrBL(u,l,41),m=u&y^~u&g,b=l&f^~l&p,k=Xh.add5L(A,w,b,tu[e],nu[e]),E=Xh.add5H(k,d,t,m,eu[e],ru[e]),v=0|k,B=Xh.rotrSH(r,n,28)^Xh.rotrBH(r,n,34)^Xh.rotrBH(r,n,39),I=Xh.rotrSL(r,n,28)^Xh.rotrBL(r,n,34)^Xh.rotrBL(r,n,39),S=r&i^r&a^i&a,K=n&s^n&o^s&o;d=0|g,A=0|p,g=0|y,p=0|f,y=0|u,f=0|l,({h:u,l}=Xh.add(0|c,0|h,0|E,0|v)),c=0|a,h=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const C=Xh.add3L(v,I,K);r=Xh.add3H(C,E,B,S),n=0|C}({h:r,l:n}=Xh.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Xh.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Xh.add(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:h}=Xh.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:u,l}=Xh.add(0|this.Eh,0|this.El,0|u,0|l)),({h:y,l:f}=Xh.add(0|this.Fh,0|this.Fl,0|y,0|f)),({h:g,l:p}=Xh.add(0|this.Gh,0|this.Gl,0|g,0|p)),({h:d,l:A}=Xh.add(0|this.Hh,0|this.Hl,0|d,0|A)),this.set(r,n,i,s,a,o,c,h,u,l,y,f,g,p,d,A)}roundClean(){ru.fill(0),nu.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class su extends iu{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const au=/* @__PURE__ */Ac((()=>new iu)),ou=/* @__PURE__ */Ac((()=>new su)),cu=Eh(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),hu=zh({a:cu.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:cu,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},ou),uu=Eh(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),lu={a:uu.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:uu,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1)},yu=zh({a:lu.a,b:lu.b,Fp:uu,n:lu.n,Gx:lu.Gx,Gy:lu.Gy,h:lu.h,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},au),fu=[],gu=[],pu=[],du=/* @__PURE__ */BigInt(0),Au=/* @__PURE__ */BigInt(1),wu=/* @__PURE__ */BigInt(2),mu=/* @__PURE__ */BigInt(7),bu=/* @__PURE__ */BigInt(256),ku=/* @__PURE__ */BigInt(113);for(let e=0,t=Au,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],fu.push(2*(5*n+r)),gu.push((e+1)*(e+2)/2%64);let i=du;for(let e=0;e<7;e++)t=(t<>mu)*ku)%bu,t&wu&&(i^=Au<<(Au<r>32?Zh(e,t,r):Yh(e,t,r),Iu=(e,t,r)=>r>32?$h(e,t,r):Wh(e,t,r);class Su extends dc{constructor(e,t,r,n=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,nc(r),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}keccak(){lc||yc(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,i=(t+2)%10,s=r[i],a=r[i+1],o=Bu(s,a,1)^r[n],c=Iu(s,a,1)^r[n+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=gu[r],s=Bu(t,i,n),a=Iu(t,i,n),o=fu[r];t=e[o],i=e[o+1],e[o]=s,e[o+1]=a}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=Eu[n],e[1]^=vu[n]}r.fill(0)}(this.state32,this.rounds),lc||yc(this.state32),this.posOut=0,this.pos=0}update(e){sc(this);const{blockLen:t,state:r}=this,n=(e=gc(e)).length;for(let i=0;i=r&&this.keccak();const s=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+s),n),this.posOut+=s,n+=s}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return nc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ac(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:s}=this;return e||(e=new Su(t,r,n,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=s,e.destroyed=this.destroyed,e}}const Ku=(e,t,r)=>Ac((()=>new Su(t,e,r))),Cu=/* @__PURE__ */Ku(6,136,32),Du=/* @__PURE__ */Ku(6,72,64),Pu=/* @__PURE__ */((e,t,r)=>function(e){const t=(t,r)=>e(r).update(gc(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(((n={})=>new Su(t,e,void 0===n.dkLen?r:n.dkLen,!0))))(31,136,32),Uu=BigInt(0),xu=BigInt(1),Qu=BigInt(2),Ru=BigInt(8),Lu={zip215:!0};function Tu(e){const t=function(e){const t=Uh(e);return sh(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:i,hash:s,randomBytes:a,nByteLength:o,h:c}=t,h=Qu<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:Uu}}}),f=t.adjustScalarBytes||(e=>e),g=t.domain||((e,t,r)=>{if(Tc("phflag",r),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function p(e,t){$c("coordinate "+e,t,Uu,h)}function d(e){if(!(e instanceof m))throw Error("ExtendedPoint expected")}const A=ah(((e,t)=>{const{ex:n,ey:i,ez:s}=e,a=e.is0();null==t&&(t=a?Ru:r.inv(s));const o=u(n*t),c=u(i*t),h=u(s*t);if(a)return{x:Uu,y:xu};if(h!==xu)throw Error("invZ was invalid");return{x:o,y:c}})),w=ah((e=>{const{a:r,d:n}=t;if(e.is0())throw Error("bad point: ZERO");const{ex:i,ey:s,ez:a,et:o}=e,c=u(i*i),h=u(s*s),l=u(a*a),y=u(l*l),f=u(c*r);if(u(l*u(f+h))!==u(y+u(n*u(c*h))))throw Error("bad point: equation left != right (1)");if(u(i*s)!==u(a*o))throw Error("bad point: equation left != right (2)");return!0}));class m{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,p("x",e),p("y",t),p("z",r),p("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof m)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return p("x",t),p("y",r),new m(t,r,xu,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(m.fromAffine)}static msm(e,t){return Ph(m,l,e,t)}_setWindowSize(e){E.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){d(e);const{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:a}=e,o=u(t*a),c=u(i*n),h=u(r*a),l=u(s*n);return o===c&&h===l}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:i}=this,s=u(r*r),a=u(n*n),o=u(Qu*u(i*i)),c=u(e*s),h=r+n,l=u(u(h*h)-s-a),y=c+a,f=y-o,g=c-a,p=u(l*f),d=u(y*g),A=u(l*g),w=u(f*y);return new m(p,d,w,A)}add(e){d(e);const{a:r,d:n}=t,{ex:i,ey:s,ez:a,et:o}=this,{ex:c,ey:h,ez:l,et:y}=e;if(r===BigInt(-1)){const e=u((s-i)*(h+c)),t=u((s+i)*(h-c)),r=u(t-e);if(r===Uu)return this.double();const n=u(a*Qu*y),f=u(o*Qu*l),g=f+n,p=t+e,d=f-n,A=u(g*r),w=u(p*d),b=u(g*d),k=u(r*p);return new m(A,w,k,b)}const f=u(i*c),g=u(s*h),p=u(o*n*y),A=u(a*l),w=u((i+s)*(c+h)-f-g),b=A-p,k=A+p,E=u(g-r*f),v=u(w*b),B=u(k*E),I=u(w*E),S=u(b*k);return new m(v,B,S,I)}subtract(e){return this.add(e.negate())}wNAF(e){return E.wNAFCached(this,e,m.normalizeZ)}multiply(e){const t=e;$c("scalar",t,xu,n);const{p:r,f:i}=this.wNAF(t);return m.normalizeZ([r,i])[0]}multiplyUnsafe(e){const t=e;return $c("scalar",t,Uu,n),t===Uu?k:this.equals(k)||t===xu?this:this.equals(b)?this.wNAF(t).p:E.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(e){return A(this,e)}clearCofactor(){const{h:e}=t;return e===xu?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:i,a:s}=t,a=r.BYTES;e=Jc("pointHex",e,a),Tc("zip215",n);const o=e.slice(),c=e[a-1];o[a-1]=-129&c;const l=jc(o),f=n?h:r.ORDER;$c("pointHex.y",l,Uu,f);const g=u(l*l),p=u(g-xu),d=u(i*g-s);let{isValid:A,value:w}=y(p,d);if(!A)throw Error("Point.fromHex: invalid y coordinate");const b=(w&xu)===xu,k=!!(128&c);if(!n&&w===Uu&&k)throw Error("Point.fromHex: x=0 and x_0=1");return k!==b&&(w=u(-w)),m.fromAffine({x:w,y:l})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Vc(t,r.BYTES);return n[n.length-1]|=e&xu?128:0,n}toHex(){return Nc(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,xu,u(t.Gx*t.Gy)),m.ZERO=new m(Uu,xu,xu,Uu);const{BASE:b,ZERO:k}=m,E=Dh(m,8*o);function v(e){return ph(e,n)}function B(e){return v(jc(e))}function I(e){const t=o;e=Jc("private key",e,t);const r=Jc("hashed private key",s(e),2*t),n=f(r.slice(0,t)),i=r.slice(t,2*t),a=B(n),c=b.multiply(a),h=c.toRawBytes();return{head:n,prefix:i,scalar:a,point:c,pointBytes:h}}function S(e=new Uint8Array,...t){const r=Yc(...t);return B(s(g(r,Jc("context",e),!!i)))}const K=Lu;b._setWindowSize(8);return{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,s={}){e=Jc("message",e),i&&(e=i(e));const{prefix:a,scalar:c,pointBytes:h}=I(t),u=S(s.context,a,e),l=b.multiply(u).toRawBytes(),y=v(u+S(s.context,l,h,e)*c);return $c("signature.s",y,Uu,n),Jc("result",Yc(l,Vc(y,r.BYTES)),2*o)},verify:function(e,t,n,s=K){const{context:a,zip215:o}=s,c=r.BYTES;e=Jc("signature",e,2*c),t=Jc("message",t),void 0!==o&&Tc("zip215",o),i&&(t=i(t));const h=jc(e.slice(c,2*c));let u,l,y;try{u=m.fromHex(n,o),l=m.fromHex(e.slice(0,c),o),y=b.multiplyUnsafe(h)}catch(e){return!1}if(!o&&u.isSmallOrder())return!1;const f=S(a,l.toRawBytes(),u.toRawBytes(),t);return l.add(u.multiplyUnsafe(f)).subtract(y).clearCofactor().equals(m.ZERO)},ExtendedPoint:m,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>a(r.BYTES),precompute:(e=8,t=m.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mu=BigInt(0),Nu=BigInt(1);function Fu(e){const t=(sh(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,i=e=>ph(e,n),s=t.montgomeryBits,a=Math.ceil(s/8),o=t.nByteLength,c=t.adjustScalarBytes||(e=>e),h=t.powPminus2||(e=>dh(e,n-BigInt(2),n));function u(e,t,r){const n=i(e*(t-r));return[t=i(t-n),r=i(r+n)]}const l=(t.a-BigInt(2))/BigInt(4);function y(e){return Vc(i(e),a)}function f(e,t){const r=function(e){const t=Jc("u coordinate",e,a);return 32===o&&(t[31]&=127),jc(t)}(t),f=function(e){const t=Jc("scalar",e),r=t.length;if(r!==a&&r!==o)throw Error(`Expected ${a} or ${o} bytes, got ${r}`);return jc(c(t))}(e),g=function(e,t){$c("u",e,Mu,n),$c("scalar",t,Mu,n);const r=t,a=e;let o,c=Nu,y=Mu,f=e,g=Nu,p=Mu;for(let e=BigInt(s-1);e>=Mu;e--){const t=r>>eΝp^=t,o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1],p=t;const n=c+y,s=i(n*n),h=c-y,d=i(h*h),A=s-d,w=f+g,m=i((f-g)*n),b=i(w*h),k=m+b,E=m-b;f=i(k*k),g=i(a*i(E*E)),c=i(s*d),y=i(A*(s+i(l*A)))}o=u(p,c,f),c=o[0],f=o[1],o=u(p,y,g),y=o[0],g=o[1];const d=h(y);return i(c*d)}(r,f);if(g===Mu)throw Error("Invalid private or public key received");return y(g)}const g=y(t.Gu);function p(e){return f(e,g)}return{scalarMult:f,scalarMultBase:p,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>p(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}} +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hu=Ac((()=>Pu.create({dkLen:114}))),Ou=(Ac((()=>Pu.create({dkLen:64}))),BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439")),zu=BigInt(1),_u=BigInt(2),Gu=BigInt(3);BigInt(4);const ju=BigInt(11),qu=BigInt(22),Vu=BigInt(44),Ju=BigInt(88),Yu=BigInt(223);function Wu(e){const t=Ou,r=e*e*e%t,n=r*r*e%t,i=Ah(n,Gu,t)*n%t,s=Ah(i,Gu,t)*n%t,a=Ah(s,_u,t)*r%t,o=Ah(a,ju,t)*a%t,c=Ah(o,qu,t)*o%t,h=Ah(c,Vu,t)*c%t,u=Ah(h,Ju,t)*h%t,l=Ah(u,Vu,t)*c%t,y=Ah(l,_u,t)*r%t,f=Ah(y,zu,t)*e%t;return Ah(f,Yu,t)*y%t}function Zu(e){return e[0]&=252,e[55]|=128,e[56]=0,e}const $u=Eh(Ou,456,!0),Xu={a:BigInt(1),d:BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"),Fp:$u,n:BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"),nBitLength:456,h:BigInt(4),Gx:BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"),Gy:BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"),hash:Hu,randomBytes:wc,adjustScalarBytes:Zu,domain:(e,t,r)=>{if(t.length>255)throw Error("Context is too big: "+t.length);return pc(fc("SigEd448"),new Uint8Array([r?1:0,t.length]),t,e)},uvRatio:function(e,t){const r=Ou,n=ph(e*e*t,r),i=ph(n*e,r),s=ph(i*n*t,r),a=ph(i*Wu(s),r),o=ph(a*a,r);return{isValid:ph(o*t,r)===e,value:a}}},el=/* @__PURE__ */Tu(Xu),tl=/* @__PURE__ */(()=>Fu({a:BigInt(156326),montgomeryBits:448,nByteLength:56,P:Ou,Gu:BigInt(5),powPminus2:e=>{const t=Ou;return ph(Ah(Wu(e),BigInt(2),t)*e,t)},adjustScalarBytes:Zu,randomBytes:wc}))();$u.ORDER,BigInt(3),BigInt(4),BigInt(156326),BigInt("39082"),BigInt("78163"),BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"),BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"),BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const rl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),il=BigInt(1),sl=BigInt(2),al=(e,t)=>(e+t/sl)/t;const ol=Eh(rl,void 0,void 0,{sqrt:function(e){const t=rl,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),h=e*e*e%t,u=h*h*e%t,l=Ah(u,r,t)*u%t,y=Ah(l,r,t)*u%t,f=Ah(y,sl,t)*h%t,g=Ah(f,i,t)*f%t,p=Ah(g,s,t)*g%t,d=Ah(p,o,t)*p%t,A=Ah(d,c,t)*d%t,w=Ah(A,o,t)*p%t,m=Ah(w,r,t)*u%t,b=Ah(m,a,t)*g%t,k=Ah(b,n,t)*h%t,E=Ah(k,sl,t);if(!ol.eql(ol.sqr(E),e))throw Error("Cannot find square root");return E}}),cl=zh({a:BigInt(0),b:BigInt(7),Fp:ol,n:nl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=nl,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-il*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,a=BigInt("0x100000000000000000000000000000000"),o=al(s*e,t),c=al(-n*e,t);let h=ph(e-o*r-c*i,t),u=ph(-o*n-c*s,t);const l=h>a,y=u>a;if(l&&(h=t-h),y&&(u=t-u),h>a||u>a)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:h,k2neg:y,k2:u}}}},Kc);BigInt(0),cl.ProjectivePoint;const hl=Eh(BigInt("0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377")),ul=zh({a:hl.create(BigInt("0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9")),b:BigInt("0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6"),Fp:hl,n:BigInt("0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7"),Gx:BigInt("0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262"),Gy:BigInt("0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997"),h:BigInt(1),lowS:!1},Kc),ll=Eh(BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53")),yl=zh({a:ll.create(BigInt("0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826")),b:BigInt("0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11"),Fp:ll,n:BigInt("0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565"),Gx:BigInt("0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e"),Gy:BigInt("0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315"),h:BigInt(1),lowS:!1},ou),fl=Eh(BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3")),gl=zh({a:fl.create(BigInt("0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca")),b:BigInt("0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"),Fp:fl,n:BigInt("0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"),Gx:BigInt("0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"),Gy:BigInt("0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"),h:BigInt(1),lowS:!1},au),pl=new Map(Object.entries({nistP256:Gh,nistP384:hu,nistP521:yu,brainpoolP256r1:ul,brainpoolP384r1:yl,brainpoolP512r1:gl,secp256k1:cl,x448:tl,ed448:el}));var dl=/*#__PURE__*/Object.freeze({__proto__:null,nobleCurves:pl});function Al(e,t,r,n,i,s){const a=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],c=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],h=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],u=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],l=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],y=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],f=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];let g,p,d,A,w,m,b,k,E,v,B=0,I=t.length;const S=32===e.length?3:9;k=3===S?r?[0,32,2]:[30,-2,-2]:r?[0,32,2,62,30,-2,64,96,2]:[94,62,-2,32,64,2,30,-2,-2],r&&(t=function(e){const t=8-e.length%8;let r;if(!(t<8)){if(8===t)return e;throw Error("des: invalid padding")}r=0;const n=new Uint8Array(e.length+t);for(let t=0;t>>4^b),b^=d,m^=d<<4,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,m=m<<1|m>>>31,b=b<<1|b>>>31,p=0;p>>4|b<<28)^e[g+1],d=m,m=b,b=d^(o[A>>>24&63]|h[A>>>16&63]|l[A>>>8&63]|f[63&A]|a[w>>>24&63]|c[w>>>16&63]|u[w>>>8&63]|y[63&w]);d=m,m=b,b=d}m=m>>>1|m<<31,b=b>>>1|b<<31,d=1431655765&(m>>>1^b),b^=d,m^=d<<1,d=16711935&(b>>>8^m),m^=d,b^=d<<8,d=858993459&(b>>>2^m),m^=d,b^=d<<2,d=65535&(m>>>16^b),b^=d,m^=d<<16,d=252645135&(m>>>4^b),b^=d,m^=d<<4,K[C++]=m>>>24,K[C++]=m>>>16&255,K[C++]=m>>>8&255,K[C++]=255&m,K[C++]=b>>>24,K[C++]=b>>>16&255,K[C++]=b>>>8&255,K[C++]=255&b}return r||(K=function(e){let t,r=null;if(t=0,!r){for(r=1;e[e.length-r]===t;)r++;r--}return e.subarray(0,e.length-r)}(K)),K}function wl(e){const t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],r=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],h=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],l=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],p=e.length>8?3:1,d=Array(32*p),A=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];let w,m,b,k=0,E=0;for(let v=0;v>>4^v),v^=b,p^=b<<4,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=858993459&(p>>>2^v),v^=b,p^=b<<2,b=65535&(v>>>-16^p),p^=b,v^=b<<-16,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=16711935&(v>>>8^p),p^=b,v^=b<<8,b=1431655765&(p>>>1^v),v^=b,p^=b<<1,b=p<<8|v>>>20&240,p=v<<24|v<<8&16711680|v>>>8&65280|v>>>24&240,v=b;for(let e=0;e<16;e++)A[e]?(p=p<<2|p>>>26,v=v<<2|v>>>26):(p=p<<1|p>>>27,v=v<<1|v>>>27),p&=-15,v&=-15,w=t[p>>>28]|r[p>>>24&15]|n[p>>>20&15]|i[p>>>16&15]|s[p>>>12&15]|a[p>>>8&15]|o[p>>>4&15],m=c[v>>>28]|h[v>>>24&15]|u[v>>>20&15]|l[v>>>16&15]|y[v>>>12&15]|f[v>>>8&15]|g[v>>>4&15],b=65535&(m>>>16^w),d[E++]=w^b,d[E++]=m^b<<16}return d}function ml(e){this.key=[];for(let t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return Al(wl(this.key[2]),Al(wl(this.key[1]),Al(wl(this.key[0]),e,!0),!1),!0)}}function bl(){this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=Array(16),this.rotate=Array(16),this.reset(),e.length!==this.KeySize)throw Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(let e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>>16&255,t[s+6]=o>>>8&255,t[s+7]=255&o}return t},this.decrypt=function(e){const t=Array(e.length);for(let s=0;s>>24&255,t[s+1]=c>>>16&255,t[s+2]=c>>>8&255,t[s+3]=255&c,t[s+4]=o>>>24&255,t[s+5]=o>>16&255,t[s+6]=o>>8&255,t[s+7]=255&o}return t};const e=[,,,,];e[0]=[,,,,],e[0][0]=[4,0,13,15,12,14,8],e[0][1]=[5,2,16,18,17,19,10],e[0][2]=[6,3,23,22,21,20,9],e[0][3]=[7,1,26,25,27,24,11],e[1]=[,,,,],e[1][0]=[0,6,21,23,20,22,16],e[1][1]=[1,4,0,2,1,3,18],e[1][2]=[2,5,7,6,5,4,17],e[1][3]=[3,7,10,9,11,8,19],e[2]=[,,,,],e[2][0]=[4,0,13,15,12,14,8],e[2][1]=[5,2,16,18,17,19,10],e[2][2]=[6,3,23,22,21,20,9],e[2][3]=[7,1,26,25,27,24,11],e[3]=[,,,,],e[3][0]=[0,6,21,23,20,22,16],e[3][1]=[1,4,0,2,1,3,18],e[3][2]=[2,5,7,6,5,4,17],e[3][3]=[3,7,10,9,11,8,19];const t=[,,,,];function r(e,t,r){const n=t+e,i=n<>>32-r;return(s[0][i>>>24]^s[1][i>>>16&255])-s[2][i>>>8&255]+s[3][255&i]}function n(e,t,r){const n=t^e,i=n<>>32-r;return s[0][i>>>24]-s[1][i>>>16&255]+s[2][i>>>8&255]^s[3][255&i]}function i(e,t,r){const n=t-e,i=n<>>32-r;return(s[0][i>>>24]+s[1][i>>>16&255]^s[2][i>>>8&255])-s[3][255&i]}t[0]=[,,,,],t[0][0]=[24,25,23,22,18],t[0][1]=[26,27,21,20,22],t[0][2]=[28,29,19,18,25],t[0][3]=[30,31,17,16,28],t[1]=[,,,,],t[1][0]=[3,2,12,13,8],t[1][1]=[1,0,14,15,13],t[1][2]=[7,6,8,9,3],t[1][3]=[5,4,10,11,7],t[2]=[,,,,],t[2][0]=[19,18,28,29,25],t[2][1]=[17,16,30,31,28],t[2][2]=[23,22,24,25,18],t[2][3]=[21,20,26,27,22],t[3]=[,,,,],t[3][0]=[8,9,7,6,3],t[3][1]=[10,11,5,4,7],t[3][2]=[12,13,3,2,8],t[3][3]=[14,15,1,0,13],this.keySchedule=function(r){const n=[,,,,,,,,],i=Array(32);let a;for(let e=0;e<4;e++)a=4*e,n[e]=r[a]<<24|r[a+1]<<16|r[a+2]<<8|r[a+3];const o=[6,7,4,5];let c,h=0;for(let r=0;r<2;r++)for(let r=0;r<4;r++){for(a=0;a<4;a++){const t=e[r][a];c=n[t[1]],c^=s[4][n[t[2]>>>2]>>>24-8*(3&t[2])&255],c^=s[5][n[t[3]>>>2]>>>24-8*(3&t[3])&255],c^=s[6][n[t[4]>>>2]>>>24-8*(3&t[4])&255],c^=s[7][n[t[5]>>>2]>>>24-8*(3&t[5])&255],c^=s[o[a]][n[t[6]>>>2]>>>24-8*(3&t[6])&255],n[t[0]]=c}for(a=0;a<4;a++){const e=t[r][a];c=s[4][n[e[0]>>>2]>>>24-8*(3&e[0])&255],c^=s[5][n[e[1]>>>2]>>>24-8*(3&e[1])&255],c^=s[6][n[e[2]>>>2]>>>24-8*(3&e[2])&255],c^=s[7][n[e[3]>>>2]>>>24-8*(3&e[3])&255],c^=s[4+a][n[e[4]>>>2]>>>24-8*(3&e[4])&255],i[h]=c,h++}}for(let e=0;e<16;e++)this.masking[e]=i[e],this.rotate[e]=31&i[16+e]};const s=[,,,,,,,,];s[0]=[821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063],s[1]=[522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321],s[2]=[2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027],s[3]=[2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730],s[4]=[2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860],s[5]=[4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975],s[6]=[2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875],s[7]=[3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926]}function kl(e){this.cast5=new bl,this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}ml.keySize=ml.prototype.keySize=24,ml.blockSize=ml.prototype.blockSize=8,kl.blockSize=kl.prototype.blockSize=8,kl.keySize=kl.prototype.keySize=16;const El=4294967295;function vl(e,t){return(e<>>32-t)&El}function Bl(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Il(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function Sl(e,t){return e>>>8*t&255}function Kl(e){this.tf=function(){let e=null,t=null,r=-1,n=[],i=[[],[],[],[]];function s(e){return i[0][Sl(e,0)]^i[1][Sl(e,1)]^i[2][Sl(e,2)]^i[3][Sl(e,3)]}function a(e){return i[0][Sl(e,3)]^i[1][Sl(e,0)]^i[2][Sl(e,1)]^i[3][Sl(e,2)]}function o(e,t){let r=s(t[0]),i=a(t[1]);t[2]=vl(t[2]^r+i+n[4*e+8]&El,31),t[3]=vl(t[3],1)^r+2*i+n[4*e+9]&El,r=s(t[2]),i=a(t[3]),t[0]=vl(t[0]^r+i+n[4*e+10]&El,31),t[1]=vl(t[1],1)^r+2*i+n[4*e+11]&El}function c(e,t){let r=s(t[0]),i=a(t[1]);t[2]=vl(t[2],1)^r+i+n[4*e+10]&El,t[3]=vl(t[3]^r+2*i+n[4*e+11]&El,31),r=s(t[2]),i=a(t[3]),t[0]=vl(t[0],1)^r+i+n[4*e+8]&El,t[1]=vl(t[1]^r+2*i+n[4*e+9]&El,31)}return{name:"twofish",blocksize:16,open:function(t){let r,s,a,o,c;e=t;const h=[],u=[],l=[];let y;const f=[];let g,p,d;const A=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],w=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],m=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],b=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],k=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],E=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],v=[[],[]],B=[[],[],[],[]];function I(e){return e^e>>2^[0,90,180,238][3&e]}function S(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function K(e,t){let r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&El|e>>>24,e=e<<8&El,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function C(e,t){const r=t>>4,n=15&t,i=A[e][r^n],s=w[e][k[n]^E[r]];return b[e][k[s]^E[i]]<<4|m[e][i^s]}function D(e,t){let r=Sl(e,0),n=Sl(e,1),i=Sl(e,2),s=Sl(e,3);switch(y){case 4:r=v[1][r]^Sl(t[3],0),n=v[0][n]^Sl(t[3],1),i=v[0][i]^Sl(t[3],2),s=v[1][s]^Sl(t[3],3);case 3:r=v[1][r]^Sl(t[2],0),n=v[1][n]^Sl(t[2],1),i=v[0][i]^Sl(t[2],2),s=v[0][s]^Sl(t[2],3);case 2:r=v[0][v[0][r]^Sl(t[1],0)]^Sl(t[0],0),n=v[0][v[1][n]^Sl(t[1],1)]^Sl(t[0],1),i=v[1][v[0][i]^Sl(t[1],2)]^Sl(t[0],2),s=v[1][v[1][s]^Sl(t[1],3)]^Sl(t[0],3)}return B[0][r]^B[1][n]^B[2][i]^B[3][s]}for(e=e.slice(0,32),r=e.length;16!==r&&24!==r&&32!==r;)e[r++]=0;for(r=0;r>2]=Bl(e,r);for(r=0;r<256;r++)v[0][r]=C(0,r),v[1][r]=C(1,r);for(r=0;r<256;r++)g=v[1][r],p=I(g),d=S(g),B[0][r]=g+(p<<8)+(d<<16)+(d<<24),B[2][r]=p+(d<<8)+(g<<16)+(d<<24),g=v[0][r],p=I(g),d=S(g),B[1][r]=d+(d<<8)+(p<<16)+(g<<24),B[3][r]=p+(g<<8)+(d<<16)+(p<<24);for(y=l.length/2,r=0;r=0;e--)c(e,s);Il(t,r,s[2]^n[0]),Il(t,r+4,s[3]^n[1]),Il(t,r+8,s[0]^n[2]),Il(t,r+12,s[1]^n[3]),r+=16},finalize:function(){return t}}}(),this.tf.open(Array.from(e),0),this.encrypt=function(e){return this.tf.encrypt(Array.from(e),0)}}function Cl(){}function Dl(e){this.bf=new Cl,this.bf.init(e),this.encrypt=function(e){return this.bf.encryptBlock(e)}}Kl.keySize=Kl.prototype.keySize=32,Kl.blockSize=Kl.prototype.blockSize=16,Cl.prototype.BLOCKSIZE=8,Cl.prototype.SBOXES=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]],Cl.prototype.PARRAY=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Cl.prototype.NN=16,Cl.prototype._clean=function(e){if(e<0){e=(2147483647&e)+2147483648}return e},Cl.prototype._F=function(e){let t;const r=255&e,n=255&(e>>>=8),i=255&(e>>>=8),s=255&(e>>>=8);return t=this.sboxes[0][s]+this.sboxes[1][i],t^=this.sboxes[2][n],t+=this.sboxes[3][r],t},Cl.prototype._encryptBlock=function(e){let t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},Cl.prototype._decryptBlock=function(e){let t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){r^=this.parray[t],n=this._F(r)^n;const e=r;r=n,n=e}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},Cl.prototype.init=function(e){let t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^n}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];const n=[0,0];for(t=0;tnew Rl)),Tl=/* @__PURE__ */new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ml=/* @__PURE__ */new Uint8Array(Array(16).fill(0).map(((e,t)=>t))),Nl=/* @__PURE__ */Ml.map((e=>(9*e+5)%16));let Fl=[Ml],Hl=[Nl];for(let e=0;e<4;e++)for(let t of[Fl,Hl])t.push(t[e].map((e=>Tl[e])));const Ol=/* @__PURE__ */[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>new Uint8Array(e))),zl=/* @__PURE__ */Fl.map(((e,t)=>e.map((e=>Ol[t][e])))),_l=/* @__PURE__ */Hl.map(((e,t)=>e.map((e=>Ol[t][e])))),Gl=/* @__PURE__ */new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),jl=/* @__PURE__ */new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function ql(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}const Vl=/* @__PURE__ */new Uint32Array(16);class Jl extends kc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)Vl[r]=e.getUint32(t,!0);let r=0|this.h0,n=r,i=0|this.h1,s=i,a=0|this.h2,o=a,c=0|this.h3,h=c,u=0|this.h4,l=u;for(let e=0;e<5;e++){const t=4-e,y=Gl[e],f=jl[e],g=Fl[e],p=Hl[e],d=zl[e],A=_l[e];for(let t=0;t<16;t++){const n=uc(r+ql(e,i,a,c)+Vl[g[t]]+y,d[t])+u|0;r=u,u=c,c=0|uc(a,10),a=i,i=n}for(let e=0;e<16;e++){const r=uc(n+ql(t,s,o,h)+Vl[p[e]]+f,A[e])+l|0;n=l,l=h,h=0|uc(o,10),o=s,s=r}}this.set(this.h1+a+h|0,this.h2+c+l|0,this.h3+u+n|0,this.h4+r+s|0,this.h0+i+o|0)}roundClean(){Vl.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const Yl=new Map(Object.entries({sha1:Ll,sha224:Cc,sha256:Kc,sha384:ou,sha512:au,sha3_256:Cu,sha3_512:Du,ripemd160:/* @__PURE__ */Ac((()=>new Jl))}));var Wl=/*#__PURE__*/Object.freeze({__proto__:null,nobleHashes:Yl});function Zl(e,t,r,n){e[t]+=r[n],e[t+1]+=r[n+1]+(e[t]>>24^h<<8,e[n+1]=h>>>24^c<<8,Zl(e,r,e,n),Zl(e,r,t,o),c=e[s]^e[r],h=e[s+1]^e[r+1],e[s]=c>>>16^h<<16,e[s+1]=h>>>16^c<<16,Zl(e,i,e,s),c=e[n]^e[i],h=e[n+1]^e[i+1],e[n]=h>>>31^c<<1,e[n+1]=c>>>31^h<<1}const ey=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ty=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((e=>2*e)));function ry(e,t){const r=new Uint32Array(32),n=new Uint32Array(e.b.buffer,e.b.byteOffset,32);for(let t=0;t<16;t++)r[t]=e.h[t],r[t+16]=ey[t];r[24]^=e.t0[0],r[25]^=e.t0[1];const i=t?4294967295:0;r[28]^=i,r[29]^=i;for(let e=0;e<12;e++){const t=e<<4;Xl(r,n,0,8,16,24,ty[t+0],ty[t+1]),Xl(r,n,2,10,18,26,ty[t+2],ty[t+3]),Xl(r,n,4,12,20,28,ty[t+4],ty[t+5]),Xl(r,n,6,14,22,30,ty[t+6],ty[t+7]),Xl(r,n,0,10,20,30,ty[t+8],ty[t+9]),Xl(r,n,2,12,22,24,ty[t+10],ty[t+11]),Xl(r,n,4,14,16,26,ty[t+12],ty[t+13]),Xl(r,n,6,8,18,28,ty[t+14],ty[t+15])}for(let t=0;t<16;t++)e.h[t]^=r[t]^r[t+16]}class ny{constructor(e,t,r,n){const i=new Uint8Array(64);this.S={b:new Uint8Array(ay),h:new Uint32Array(sy/4),t0:new Uint32Array(2),c:0,outlen:e},i[0]=e,t&&(i[1]=t.length),i[2]=1,i[3]=1,r&&i.set(r,32),n&&i.set(n,48);const s=new Uint32Array(i.buffer,i.byteOffset,i.length/Uint32Array.BYTES_PER_ELEMENT);for(let e=0;e<16;e++)this.S.h[e]=ey[e]^s[e];if(t){const e=new Uint8Array(ay);e.set(t),this.update(e)}}update(e){if(!(e instanceof Uint8Array))throw Error("Input must be Uint8Array or Buffer");let t=0;for(;t>2]>>8*(3&e);return this.S.h=null,t.buffer}}function iy(e,t,r,n){if(e>sy)throw Error(`outlen must be at most ${sy} (given: ${e})`);return new ny(e,t,r,n)}const sy=64,ay=128,oy=2,cy=19,hy=4294967295,uy=4,ly=4294967295,yy=8,fy=4294967295,gy=8,py=4294967295,dy=4294967295,Ay=32,wy=1024,my=64,by=205===new Uint8Array(new Uint16Array([43981]).buffer)[0];function ky(e,t,r){return e[r+0]=t,e[r+1]=t>>8,e[r+2]=t>>16,e[r+3]=t>>24,e}function Ey(e,t,r){if(t>Number.MAX_SAFE_INTEGER)throw Error("LE64: large numbers unsupported");let n=t;for(let t=r;t{if(tn)throw Error(`${e} size should be between ${r} and ${n} bytes`)};if(e!==oy||t!==cy)throw Error("Unsupported type or version");return u("password",n,gy,fy),u("salt",i,yy,ly),u("tag",r,uy,hy),u("memory",c,8*o,py),s&&u("associated data",s,0,dy),a&&u("secret",a,0,Ay),{type:e,version:t,tagLength:r,password:n,salt:i,ad:s,secret:a,lanes:o,memorySize:c,passes:h}}({type:oy,version:cy,...e}),{G:i,G2:s,xor:a,getLZ:o}=r.exports,c={},h={};h.G=i,h.G2=s,h.XOR=a;const u=4*n.lanes*Math.floor(n.memorySize/(4*n.lanes)),l=u*wy+10*Cy;if(t.buffer.byteLength{r.set(e,n),n+=e.length})),r}(i));const s=t.digest();return new Uint8Array(s)}(n),m=u/n.lanes,b=Array(n.lanes).fill(null).map((()=>Array(m))),k=(e,t)=>(b[e][t]=d.subarray(e*m*1024+1024*t,e*m*1024+1024*t+wy),b[e][t]);for(let e=0;e0?b[i][c-1]:b[i][m-1],u=r?a.next().value:h;o(f.byteOffset,u.byteOffset,i,n.lanes,e,t,s,4,E);const l=f[0],y=f[1];0===e&&k(i,c),Iy(g,h,b[l][y],e>0?p:b[i][c]),e>0&&By(g,b[i][c],p,b[i][c])}}}const v=b[0][m-1];for(let e=1;ePy(e,{instance:n.instance,memory:r})}function Qy(t,r,n,i){var s=null,a=e.atob(n),o=a.length;s=new Uint8Array(new ArrayBuffer(o));for(var c=0;cxy((e=>Qy(0,0,"AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQA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f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMg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0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==",e)))}),Ly=[0,1,3,7,15,31,63,127,255],Ty=function(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1};Ty.prototype._ensureByte=function(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)},Ty.prototype.read=function(e){for(var t=0;e>0;){this._ensureByte();var r=8-this.bitOffset;if(e>=r)t<<=r,t|=Ly[r]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=r;else{t<<=e;var n=r-e;t|=(this.curByte&Ly[e]<>n,this.bitOffset+=e,e=0}}return t},Ty.prototype.seek=function(e){var t=e%8,r=(e-t)/8;this.bitOffset=t,this.stream.seek(r),this.hasByte=!1},Ty.prototype.pi=function(){var e,t=new Uint8Array(6);for(e=0;e("00"+e.toString(16)).slice(-2))).join("")}(t)};var My=Ty,Ny=function(){};Ny.prototype.readByte=function(){throw Error("abstract method readByte() not implemented")},Ny.prototype.read=function(e,t,r){for(var n=0;n>>0},this.updateCRC=function(t){e=e<<8^Fy[255&(e>>>24^t)]},this.updateCRCRun=function(t,r){for(;r-- >0;)e=e<<8^Fy[255&(e>>>24^t)]}}),zy=My,_y=Hy,Gy=Oy,jy=function(e,t){var r,n=e[t];for(r=t;r>0;r--)e[r]=e[r-1];return e[0]=n,n},qy={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},Vy={};Vy[qy.LAST_BLOCK]="Bad file checksum",Vy[qy.NOT_BZIP_DATA]="Not bzip data",Vy[qy.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",Vy[qy.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",Vy[qy.DATA_ERROR]="Data error",Vy[qy.OUT_OF_MEMORY]="Out of memory",Vy[qy.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";var Jy=function(e,t){var r=Vy[e]||"unknown error";t&&(r+=": "+t);var n=new TypeError(r);throw n.errorCode=e,n},Yy=function(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)};Yy.prototype._init_block=function(){return this._get_next_block()?(this.blockCRC=new Gy,!0):(this.writeCount=-1,!1)},Yy.prototype._start_bunzip=function(e,t){var r=new Uint8Array(4);4===e.read(r,0,4)&&"BZh"===String.fromCharCode(r[0],r[1],r[2])||Jy(qy.NOT_BZIP_DATA,"bad magic");var n=r[3]-48;(n<1||n>9)&&Jy(qy.NOT_BZIP_DATA,"level out of range"),this.reader=new zy(e),this.dbufSize=1e5*n,this.nextoutput=0,this.outputStream=t,this.streamCRC=0},Yy.prototype._get_next_block=function(){var e,t,r,n=this.reader,i=n.pi();if("177245385090"===i)return!1;"314159265359"!==i&&Jy(qy.NOT_BZIP_DATA),this.targetBlockCRC=n.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,n.read(1)&&Jy(qy.OBSOLETE_INPUT);var s=n.read(24);s>this.dbufSize&&Jy(qy.DATA_ERROR,"initial position out of bounds");var a=n.read(16),o=new Uint8Array(256),c=0;for(e=0;e<16;e++)if(a&1<<15-e){var h=16*e;for(r=n.read(16),t=0;t<16;t++)r&1<<15-t&&(o[c++]=h+t)}var u=n.read(3);(u<2||u>6)&&Jy(qy.DATA_ERROR);var l=n.read(15);0===l&&Jy(qy.DATA_ERROR);var y=new Uint8Array(256);for(e=0;e=u&&Jy(qy.DATA_ERROR);f[e]=jy(y,t)}var g,p=c+2,d=[];for(t=0;t20)&&Jy(qy.DATA_ERROR),n.read(1);)n.read(1)?a--:a++;m[e]=a}for(A=w=m[0],e=1;ew?w=m[e]:m[e]=l&&Jy(qy.DATA_ERROR),g=d[f[S++]]),e=g.minLen,t=n.read(e);e>g.maxLen&&Jy(qy.DATA_ERROR),!(t<=g.limit[e]);e++)t=t<<1|n.read(1);((t-=g.base[e])<0||t>=258)&&Jy(qy.DATA_ERROR);var C=g.permute[t];if(0!==C&&1!==C){if(B)for(B=0,I+a>this.dbufSize&&Jy(qy.DATA_ERROR),E[v=o[y[0]]]+=a;a--;)K[I++]=v;if(C>c)break;I>=this.dbufSize&&Jy(qy.DATA_ERROR),E[v=o[v=jy(y,e=C-1)]]++,K[I++]=v}else B||(B=1,a=0),a+=0===C?B:2*B,B<<=1}for((s<0||s>=I)&&Jy(qy.DATA_ERROR),t=0,e=0;e<256;e++)r=t+E[e],E[e]=t,t=r;for(e=0;e>=8,U=-1),this.writePos=D,this.writeCurrent=P,this.writeCount=I,this.writeRun=U,!0},Yy.prototype._read_bunzip=function(e,t){var r,n,i;if(this.writeCount<0)return 0;var s=this.dbuf,a=this.writePos,o=this.writeCurrent,c=this.writeCount;this.outputsize;for(var h=this.writeRun;c;){for(c--,n=o,o=255&(a=s[a]),a>>=8,3==h++?(r=o,i=n,o=-1):(r=1,i=o),this.blockCRC.updateCRCRun(i,r);r--;)this.outputStream.writeByte(i),this.nextoutput++;o!=n&&(h=0)}return this.writeCount=c,this.blockCRC.getCRC()!==this.targetBlockCRC&&Jy(qy.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput};var Wy=function(e){if("readByte"in e)return e;var t=new _y;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},Zy=function(e){var t=new _y,r=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),r=!1;else{if("writeByte"in e)return e;t.buffer=e,r=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(r&&this.pos>=this.buffer.length){var t=new Uint8Array(2*this.buffer.length);t.set(this.buffer),this.buffer=t}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!r)throw new TypeError("outputsize does not match decoded input");var e=new Uint8Array(this.pos);e.set(this.buffer.subarray(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};var $y={Bunzip:Yy,Stream:_y,Err:qy,decode:function(e,t,r){for(var n=Wy(e),i=Zy(t),s=new Yy(n,i);!("eof"in n)||!n.eof();)if(s._init_block())s._read_bunzip();else{var a=s.reader.read(32)>>>0;if(a!==s.streamCRC&&Jy(qy.DATA_ERROR,"Bad stream CRC (got "+s.streamCRC.toString(16)+" expected "+a.toString(16)+")"),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i)}if("getBuffer"in i)return i.getBuffer()},decodeBlock:function(e,t,r){var n=Wy(e),i=Zy(r),s=new Yy(n,i);if(s.reader.seek(t),s._get_next_block()&&(s.blockCRC=new Gy,s.writeCopies=0,s._read_bunzip()),"getBuffer"in i)return i.getBuffer()},table:function(e,t,r){var n=new _y;n.delegate=Wy(e),n.pos=0,n.readByte=function(){return this.pos++,this.delegate.readByte()},n.delegate.eof&&(n.eof=n.delegate.eof.bind(n.delegate));var i=new _y;i.pos=0,i.writeByte=function(){this.pos++};for(var s=new Yy(n,i),a=s.dbufSize;!("eof"in n)||!n.eof();){var o=8*n.pos+s.reader.bitOffset;if(s.reader.hasByte&&(o-=8),s._init_block()){var c=i.pos;s._read_bunzip(),t(o,i.pos-c)}else{if(s.reader.read(32),!r||!("eof"in n)||n.eof())break;s._start_bunzip(n,i),console.assert(s.dbufSize===a,"shouldn't change block size within multistream file")}}}},Xy=/*#__PURE__*/t({__proto__:null},[$y]);export{Da as AEADEncryptedDataPacket,Qo as CleartextMessage,ma as CompressedDataPacket,oa as LiteralDataPacket,Ta as MarkerPacket,Ko as Message,pa as OnePassSignaturePacket,Aa as PacketList,Ga as PaddingPacket,po as PrivateKey,go as PublicKey,Pa as PublicKeyEncryptedSessionKeyPacket,Qa as PublicKeyPacket,Ma as PublicSubkeyPacket,Fa as SecretKeyPacket,za as SecretSubkeyPacket,qa as Signature,ya as SignaturePacket,ho as Subkey,Sa as SymEncryptedIntegrityProtectedDataPacket,xa as SymEncryptedSessionKeyPacket,La as SymmetricallyEncryptedDataPacket,_a as TrustPacket,Jn as UnparseablePacket,Na as UserAttributePacket,Oa as UserIDPacket,X as armor,L as config,Lo as createCleartextMessage,Uo as createMessage,zo as decrypt,Fo as decryptKey,Vo as decryptSessionKeys,Oo as encrypt,Ho as encryptKey,qo as encryptSessionKey,R as enums,To as generateKey,jo as generateSessionKey,Ro as readCleartextMessage,bo as readKey,Eo as readKeys,Po as readMessage,ko as readPrivateKey,vo as readPrivateKeys,Va as readSignature,Mo as reformatKey,No as revokeKey,_o as sign,$ as unarmor,Go as verify}; //# sourceMappingURL=openpgp.min.mjs.map diff --git a/app/node_modules/openpgp/dist/openpgp.min.mjs.map b/app/node_modules/openpgp/dist/openpgp.min.mjs.map index 7339f5647..f1fe36e80 100644 --- a/app/node_modules/openpgp/dist/openpgp.min.mjs.map +++ b/app/node_modules/openpgp/dist/openpgp.min.mjs.map @@ -1 +1 @@ -{"version":3,"file":"openpgp.min.mjs","sources":["../node_modules/@openpgp/web-stream-tools/lib/writer.js","../node_modules/@openpgp/web-stream-tools/lib/util.js","../node_modules/@openpgp/web-stream-tools/lib/node-conversions.js","../node_modules/@openpgp/web-stream-tools/lib/reader.js","../node_modules/@openpgp/web-stream-tools/lib/streams.js","../src/biginteger/native.interface.js","../src/biginteger/index.js","../src/enums.js","../src/util.js","../src/encoding/base64.js","../src/config/config.js","../src/encoding/armor.js","../src/type/keyid.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.asm.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/other/utils.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/other/errors.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/aes.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ecb.js","../src/crypto/cipher/aes.js","../src/crypto/cipher/des.js","../src/crypto/cipher/cast5.js","../src/crypto/cipher/twofish.js","../src/crypto/cipher/blowfish.js","../src/crypto/cipher/index.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.asm.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/hash.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256.asm.js","../node_modules/minimalistic-assert/index.js","../node_modules/inherits/inherits_browser.js","../node_modules/hash.js/lib/hash/utils.js","../node_modules/hash.js/lib/hash/common.js","../node_modules/hash.js/lib/hash/sha/common.js","../node_modules/hash.js/lib/hash/sha/256.js","../node_modules/hash.js/lib/hash/sha/224.js","../node_modules/hash.js/lib/hash/sha/512.js","../node_modules/hash.js/lib/hash/sha/384.js","../node_modules/hash.js/lib/hash/ripemd.js","../src/crypto/hash/md5.js","../src/crypto/hash/index.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cfb.js","../src/crypto/cipher/getCipher.js","../src/crypto/mode/cfb.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/ctr.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/cbc.js","../src/crypto/cmac.js","../src/crypto/mode/eax.js","../src/crypto/mode/ocb.js","../node_modules/@openpgp/asmcrypto.js/dist_es8/aes/gcm.js","../src/crypto/mode/gcm.js","../src/crypto/mode/index.js","../node_modules/@openpgp/tweetnacl/nacl-fast-light.js","../src/crypto/random.js","../src/crypto/public_key/prime.js","../src/crypto/pkcs1.js","../src/crypto/public_key/rsa.js","../src/crypto/public_key/elgamal.js","../src/type/oid.js","../src/crypto/public_key/elliptic/indutnyKey.js","../src/packet/packet.js","../src/crypto/public_key/elliptic/oid_curves.js","../src/crypto/public_key/elliptic/ecdsa.js","../src/crypto/public_key/elliptic/eddsa_legacy.js","../src/crypto/public_key/elliptic/eddsa.js","../src/crypto/aes_kw.js","../src/crypto/pkcs5.js","../src/crypto/public_key/elliptic/ecdh.js","../src/crypto/hkdf.js","../src/crypto/public_key/elliptic/ecdh_x.js","../src/crypto/public_key/dsa.js","../src/crypto/public_key/index.js","../src/crypto/signature.js","../src/type/ecdh_symkey.js","../src/type/kdf_params.js","../src/type/ecdh_x_symkey.js","../src/crypto/crypto.js","../src/crypto/index.js","../node_modules/@openpgp/pako/lib/utils/common.js","../node_modules/@openpgp/pako/lib/zlib/constants.js","../node_modules/@openpgp/pako/lib/zlib/trees.js","../node_modules/@openpgp/pako/lib/zlib/adler32.js","../node_modules/@openpgp/pako/lib/zlib/crc32.js","../node_modules/@openpgp/pako/lib/zlib/messages.js","../node_modules/@openpgp/pako/lib/zlib/deflate.js","../node_modules/@openpgp/pako/lib/utils/strings.js","../node_modules/@openpgp/pako/lib/zlib/zstream.js","../node_modules/@openpgp/pako/lib/deflate.js","../node_modules/@openpgp/pako/lib/zlib/inffast.js","../node_modules/@openpgp/pako/lib/zlib/inftrees.js","../node_modules/@openpgp/pako/lib/zlib/inflate.js","../node_modules/@openpgp/pako/lib/zlib/gzheader.js","../node_modules/@openpgp/pako/lib/inflate.js","../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../node_modules/@openpgp/seek-bzip/lib/stream.js","../node_modules/@openpgp/seek-bzip/lib/crc32.js","../node_modules/@openpgp/seek-bzip/lib/index.js","../src/packet/literal_data.js","../src/packet/signature.js","../src/packet/one_pass_signature.js","../src/packet/packetlist.js","../src/packet/compressed_data.js","../src/packet/sym_encrypted_integrity_protected_data.js","../src/packet/aead_encrypted_data.js","../src/packet/public_key_encrypted_session_key.js","../src/type/s2k.js","../src/packet/sym_encrypted_session_key.js","../src/packet/public_key.js","../src/packet/symmetrically_encrypted_data.js","../src/packet/marker.js","../src/packet/public_subkey.js","../src/packet/user_attribute.js","../src/packet/secret_key.js","../node_modules/email-addresses/lib/email-addresses.js","../src/packet/userid.js","../src/packet/secret_subkey.js","../src/packet/trust.js","../src/signature.js","../src/key/helper.js","../src/key/user.js","../src/key/subkey.js","../src/key/key.js","../src/key/public_key.js","../src/key/private_key.js","../src/key/factory.js","../src/message.js","../src/cleartext.js","../src/openpgp.js","../node_modules/@openpgp/web-stream-tools/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs","../node_modules/@mattiasbuelens/web-streams-adapter/dist/web-streams-adapter.mjs","../node_modules/bn.js/lib/bn.js","../src/biginteger/bn.interface.js","../node_modules/brorand/index.js","../node_modules/minimalistic-crypto-utils/lib/utils.js","../node_modules/@openpgp/elliptic/lib/elliptic/utils.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/base.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/short.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/mont.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/edwards.js","../node_modules/@openpgp/elliptic/lib/elliptic/curve/index.js","../node_modules/hash.js/lib/hash/sha/1.js","../node_modules/hash.js/lib/hash/sha.js","../node_modules/hash.js/lib/hash/hmac.js","../node_modules/hash.js/lib/hash.js","../node_modules/@openpgp/elliptic/lib/elliptic/precomputed/secp256k1.js","../node_modules/@openpgp/elliptic/lib/elliptic/curves.js","../node_modules/hmac-drbg/lib/hmac-drbg.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/key.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/signature.js","../node_modules/@openpgp/elliptic/lib/elliptic/ec/index.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/key.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/signature.js","../node_modules/@openpgp/elliptic/lib/elliptic/eddsa/index.js","../node_modules/@openpgp/elliptic/lib/elliptic.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","import * as streams from './streams';\nimport { isArrayStream } from './writer';\n\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n if (streams.ReadableStream && streams.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'ponyfill';\n }\n if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {\n return 'node';\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isNode } from './util';\nimport * as streams from './streams';\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\nconst NodeReadableStream = isNode && require('stream').Readable;\n\n/**\n * Web / node stream conversion functions\n * From https://github.com/gwicke/node-web-streams\n */\n\nlet nodeToWeb;\nlet webToNode;\n\nif (NodeReadableStream) {\n\n /**\n * Convert a Node Readable Stream to a Web ReadableStream\n * @param {Readable} nodeStream\n * @returns {ReadableStream}\n */\n nodeToWeb = function(nodeStream) {\n let canceled = false;\n return new streams.ReadableStream({\n start(controller) {\n nodeStream.pause();\n nodeStream.on('data', chunk => {\n if (canceled) {\n return;\n }\n if (NodeBuffer.isBuffer(chunk)) {\n chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n controller.enqueue(chunk);\n nodeStream.pause();\n });\n nodeStream.on('end', () => {\n if (canceled) {\n return;\n }\n controller.close();\n });\n nodeStream.on('error', e => controller.error(e));\n },\n pull() {\n nodeStream.resume();\n },\n cancel(reason) {\n canceled = true;\n nodeStream.destroy(reason);\n }\n });\n };\n\n\n class NodeReadable extends NodeReadableStream {\n constructor(webStream, options) {\n super(options);\n this._reader = streams.getReader(webStream);\n }\n\n async _read(size) {\n try {\n while (true) {\n const { done, value } = await this._reader.read();\n if (done) {\n this.push(null);\n break;\n }\n if (!this.push(value)) {\n break;\n }\n }\n } catch (e) {\n this.destroy(e);\n }\n }\n\n async _destroy(error, callback) {\n this._reader.cancel(error).then(callback, callback);\n }\n }\n\n /**\n * Convert a Web ReadableStream to a Node Readable Stream\n * @param {ReadableStream} webStream\n * @param {Object} options\n * @returns {Readable}\n */\n webToNode = function(webStream, options) {\n return new NodeReadable(webStream, options);\n };\n\n}\n\nexport { nodeToWeb, webToNode };\n","import * as streams from './streams';\nimport { isUint8Array } from './util';\n\nconst doneReadingSet = new WeakSet();\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (streams.isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = async () => {};\n return;\n }\n let streamType = streams.isStream(input);\n if (streamType === 'node') {\n input = streams.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array } from './util';\nimport { nodeToWeb, webToNode } from './node-conversions';\nimport { Reader, externalBuffer } from './reader';\nimport { ArrayStream, Writer } from './writer';\n\nlet { ReadableStream, WritableStream, TransformStream } = globalThis;\n\nlet toPonyfillReadable, toNativeReadable;\n\nasync function loadStreamsPonyfill() {\n if (TransformStream) {\n return;\n }\n\n const [ponyfill, adapter] = await Promise.all([\n import('web-streams-polyfill/ponyfill/es6'),\n import('@mattiasbuelens/web-streams-adapter')\n ]);\n\n ({ ReadableStream, WritableStream, TransformStream } = ponyfill);\n\n const { createReadableStreamWrapper } = adapter;\n\n if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {\n toPonyfillReadable = createReadableStreamWrapper(ReadableStream);\n toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);\n }\n}\n\nconst NodeBuffer = isNode && require('buffer').Buffer;\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType === 'node') {\n return nodeToWeb(input);\n }\n if (streamType === 'web' && toPonyfillReadable) {\n return toPonyfillReadable(input);\n }\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert data to ArrayStream\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {\n return NodeBuffer.concat(list);\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n } else {\n lastBytes = returnValue;\n }\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {\n if (end === Infinity) end = input.length;\n return input.subarray(begin, end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n return input.cancel(reason);\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n\nexport { ReadableStream, WritableStream, TransformStream, ArrayStream, loadStreamsPonyfill, isStream, isArrayStream, isUint8Array, toStream, toPonyfillReadable, toNativeReadable, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };\n","/* eslint-disable new-cap */\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * that wraps the native BigInt library.\n * Operations are not constant time,\n * but we try and limit timing leakage where we can\n * @module biginteger/native\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on null or undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n if (n instanceof Uint8Array) {\n const bytes = n;\n const hex = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n const hexByte = bytes[i].toString(16);\n hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;\n }\n this.value = BigInt('0x0' + hex.join(''));\n } else {\n this.value = BigInt(n);\n }\n }\n\n clone() {\n return new BigInteger(this.value);\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value++;\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value--;\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value += x.value;\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value -= x.value;\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value *= x.value;\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value %= m.value;\n if (this.isNegative()) {\n this.iadd(m);\n }\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation using square and multiply\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n if (n.isZero()) throw Error('Modulo cannot be zero');\n if (n.isOne()) return new BigInteger(0);\n if (e.isNegative()) throw Error('Unsopported negative exponent');\n\n let exp = e.value;\n let x = this.value;\n\n x %= n.value;\n let r = BigInt(1);\n while (exp > BigInt(0)) {\n const lsb = exp & BigInt(1);\n exp >>= BigInt(1); // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n.value;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n.value; // Square\n }\n return new BigInteger(r);\n }\n\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n const { gcd, x } = this._egcd(n);\n if (!gcd.isOne()) {\n throw new Error('Inverse does not exist');\n }\n return x.add(n).mod(n);\n }\n\n /**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)\n * @param {BigInteger} b - Second operand\n * @returns {{ gcd, x, y: BigInteger }}\n */\n _egcd(b) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n let a = this.value;\n b = b.value;\n\n while (b !== BigInt(0)) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: new BigInteger(xPrev),\n y: new BigInteger(yPrev),\n gcd: new BigInteger(a)\n };\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} b - Operand\n * @returns {BigInteger} gcd\n */\n gcd(b) {\n let a = this.value;\n b = b.value;\n while (b !== BigInt(0)) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return new BigInteger(a);\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value <<= x.value;\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value >>= x.value;\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value === x.value;\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value < x.value;\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value <= x.value;\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value > x.value;\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value >= x.value;\n }\n\n isZero() {\n return this.value === BigInt(0);\n }\n\n isOne() {\n return this.value === BigInt(1);\n }\n\n isNegative() {\n return this.value < BigInt(0);\n }\n\n isEven() {\n return !(this.value & BigInt(1));\n }\n\n abs() {\n const res = this.clone();\n if (this.isNegative()) {\n res.value = -res.value;\n }\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n const number = Number(this.value);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n const bit = (this.value >> BigInt(i)) & BigInt(1);\n return (bit === BigInt(0)) ? 0 : 1;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n const zero = new BigInteger(0);\n const one = new BigInteger(1);\n const negOne = new BigInteger(-1);\n\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = this.isNegative() ? negOne : zero;\n let bitlen = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(one).equal(target)) {\n bitlen++;\n }\n return bitlen;\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n const zero = new BigInteger(0);\n const negOne = new BigInteger(-1);\n\n const target = this.isNegative() ? negOne : zero;\n const eight = new BigInteger(8);\n let len = 1;\n const tmp = this.clone();\n while (!tmp.irightShift(eight).equal(target)) {\n len++;\n }\n return len;\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = this.value.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? (length - rawLength) : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n }\n}\n","import BigInteger from './native.interface';\n\nconst detectBigInt = () => typeof BigInt !== 'undefined';\n\nasync function getBigInteger() {\n if (detectBigInt()) {\n return BigInteger;\n } else {\n const { default: BigInteger } = await import('./bn.interface');\n return BigInteger;\n }\n}\n\nexport { getBigInteger };\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'p256': 'p256',\n 'P-256': 'p256',\n 'secp256r1': 'p256',\n 'prime256v1': 'p256',\n '1.2.840.10045.3.1.7': 'p256',\n '2a8648ce3d030107': 'p256',\n '2A8648CE3D030107': 'p256',\n\n /** NIST P-384 Curve */\n 'p384': 'p384',\n 'P-384': 'p384',\n 'secp384r1': 'p384',\n '1.3.132.0.34': 'p384',\n '2b81040022': 'p384',\n '2B81040022': 'p384',\n\n /** NIST P-521 Curve */\n 'p521': 'p521',\n 'P-521': 'p521',\n 'secp521r1': 'p521',\n '1.3.132.0.35': 'p521',\n '2b81040023': 'p521',\n '2B81040023': 'p521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n '1.3.132.0.10': 'secp256k1',\n '2b8104000a': 'secp256k1',\n '2B8104000A': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519',\n 'ED25519': 'ed25519',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519',\n 'Ed25519': 'ed25519',\n '1.3.6.1.4.1.11591.15.1': 'ed25519',\n '2b06010401da470f01': 'ed25519',\n '2B06010401DA470F01': 'ed25519',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519',\n 'X25519': 'curve25519',\n 'cv25519': 'curve25519',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519',\n 'Curve25519': 'curve25519',\n '1.3.6.1.4.1.3029.1.5.1': 'curve25519',\n '2b060104019755010501': 'curve25519',\n '2B060104019755010501': 'curve25519',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',\n '2b2403030208010107': 'brainpoolP256r1',\n '2B2403030208010107': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',\n '2b240303020801010b': 'brainpoolP384r1',\n '2B240303020801010B': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1',\n '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',\n '2b240303020801010d': 'brainpoolP512r1',\n '2B240303020801010D': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility\n /** @deprecated use `eddsaLegacy` instead */\n ed25519Legacy: 22,\n /** @deprecated use `eddsaLegacy` instead */\n eddsa: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n plaintext: 0,\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuer: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { getBigInteger } from './biginteger';\nimport enums from './enums';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n return bytes.subarray(2, 2 + bytelen);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const r = [];\n const e = bytes.length;\n let c = 0;\n let h;\n while (c < e) {\n h = bytes[c++].toString(16);\n while (h.length < 2) {\n h = '0' + h;\n }\n r.push('' + h);\n }\n return r.join('');\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography api, only the current version of the spec.\n * @returns {Object} The SubtleCrypto api or 'undefined'.\n */\n getWebCrypto: function() {\n return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n },\n\n /**\n * Get BigInteger class\n * It wraps the native BigInt type if it's available\n * Otherwise it relies on bn.js\n * @returns {BigInteger}\n * @async\n */\n getBigInteger,\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return require('crypto');\n },\n\n getNodeZlib: function() {\n return require('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (require('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = require('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\\-0-9]+)))$/;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha256,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * @memberof module:config\n * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9\n */\n deflateLevel: 6,\n\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.eax,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use V5 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v5Keys\n */\n v5Keys: false,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:\n * Iteration Count Byte for S2K (String to Key)\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * @memberof module:config\n * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum\n */\n checksumRequired: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * @memberof module:config\n * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored\n */\n revocationsExpire: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n\n /**\n * @memberof module:config\n * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available\n */\n minBytesForWebCrypto: 1000,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * Note: the indutny/elliptic curve library is not designed to be constant time.\n * @memberof module:config\n * @property {Boolean} useIndutnyElliptic\n */\n useIndutnyElliptic: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n } else\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n } else\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n } else\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n } else\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n } else\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n } else\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Splits a message into two parts, the body and the checksum. This is an internal function\n * @param {String} text - OpenPGP armored message part\n * @returns {Object} An object with attribute \"body\" containing the body.\n * and an attribute \"checksum\" containing the checksum.\n * @private\n */\nfunction splitChecksum(text) {\n let body = text;\n let checksum = '';\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n checksum = text.slice(lastEquals + 1).substr(0, 4);\n }\n\n return { body: body, checksum: checksum };\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input, config = defaultConfig) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n let checksum;\n let data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== 2) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === 2) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const split = splitChecksum(parts[0].slice(0, -1));\n checksum = split.checksum;\n await writer.write(split.body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n data = stream.transformPair(data, async (readable, writable) => {\n const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));\n checksumVerified.catch(() => {});\n await stream.pipe(readable, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n const checksumVerifiedString = (await checksumVerified).replace('\\n', '');\n if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {\n throw new Error('Ascii armor integrity check failed');\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n const bodyClone = stream.passiveClone(body);\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push('Hash: ' + hash + '\\n\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n result.push('=', getCheckSum(bodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n * @private\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","/**\n * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.\n * @author Artem S Vybornov \n * @license MIT\n */\nexport var AES_asm = function () {\n \"use strict\";\n\n /**\n * Galois Field stuff init flag\n */\n var ginit_done = false;\n\n /**\n * Galois Field exponentiation and logarithm tables for 3 (the generator)\n */\n var gexp3, glog3;\n\n /**\n * Init Galois Field tables\n */\n function ginit() {\n gexp3 = [],\n glog3 = [];\n\n var a = 1, c, d;\n for (c = 0; c < 255; c++) {\n gexp3[c] = a;\n\n // Multiply by three\n d = a & 0x80, a <<= 1, a &= 255;\n if (d === 0x80) a ^= 0x1b;\n a ^= gexp3[c];\n\n // Set the log table value\n glog3[gexp3[c]] = c;\n }\n gexp3[255] = gexp3[0];\n glog3[0] = 0;\n\n ginit_done = true;\n }\n\n /**\n * Galois Field multiplication\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\n function gmul(a, b) {\n var c = gexp3[(glog3[a] + glog3[b]) % 255];\n if (a === 0 || b === 0) c = 0;\n return c;\n }\n\n /**\n * Galois Field reciprocal\n * @param {number} a\n * @return {number}\n */\n function ginv(a) {\n var i = gexp3[255 - glog3[a]];\n if (a === 0) i = 0;\n return i;\n }\n\n /**\n * AES stuff init flag\n */\n var aes_init_done = false;\n\n /**\n * Encryption, Decryption, S-Box and KeyTransform tables\n *\n * @type {number[]}\n */\n var aes_sbox;\n\n /**\n * @type {number[]}\n */\n var aes_sinv;\n\n /**\n * @type {number[][]}\n */\n var aes_enc;\n\n /**\n * @type {number[][]}\n */\n var aes_dec;\n\n /**\n * Init AES tables\n */\n function aes_init() {\n if (!ginit_done) ginit();\n\n // Calculates AES S-Box value\n function _s(a) {\n var c, s, x;\n s = x = ginv(a);\n for (c = 0; c < 4; c++) {\n s = ((s << 1) | (s >>> 7)) & 255;\n x ^= s;\n }\n x ^= 99;\n return x;\n }\n\n // Tables\n aes_sbox = [],\n aes_sinv = [],\n aes_enc = [[], [], [], []],\n aes_dec = [[], [], [], []];\n\n for (var i = 0; i < 256; i++) {\n var s = _s(i);\n\n // S-Box and its inverse\n aes_sbox[i] = s;\n aes_sinv[s] = i;\n\n // Ecryption and Decryption tables\n aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);\n aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);\n // Rotate tables\n for (var t = 1; t < 4; t++) {\n aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);\n aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);\n }\n }\n\n aes_init_done = true;\n }\n\n /**\n * Asm.js module constructor.\n *\n *

\n * Heap buffer layout by offset:\n *

\n   * 0x0000   encryption key schedule\n   * 0x0400   decryption key schedule\n   * 0x0800   sbox\n   * 0x0c00   inv sbox\n   * 0x1000   encryption tables\n   * 0x2000   decryption tables\n   * 0x3000   reserved (future GCM multiplication lookup table)\n   * 0x4000   data\n   * 
\n * Don't touch anything before 0x400.\n *

\n *\n * @alias AES_asm\n * @class\n * @param foreign - ignored\n * @param buffer - heap buffer to link with\n */\n var wrapper = function (foreign, buffer) {\n // Init AES stuff for the first time\n if (!aes_init_done) aes_init();\n\n // Fill up AES tables\n var heap = new Uint32Array(buffer);\n heap.set(aes_sbox, 0x0800 >> 2);\n heap.set(aes_sinv, 0x0c00 >> 2);\n for (var i = 0; i < 4; i++) {\n heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);\n heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);\n }\n\n /**\n * Calculate AES key schedules.\n * @instance\n * @memberof AES_asm\n * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)\n * @param {number} k0 - key vector components\n * @param {number} k1 - key vector components\n * @param {number} k2 - key vector components\n * @param {number} k3 - key vector components\n * @param {number} k4 - key vector components\n * @param {number} k5 - key vector components\n * @param {number} k6 - key vector components\n * @param {number} k7 - key vector components\n */\n function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {\n var ekeys = heap.subarray(0x000, 60),\n dkeys = heap.subarray(0x100, 0x100 + 60);\n\n // Encryption key schedule\n ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);\n for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {\n var k = ekeys[i - 1];\n if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {\n k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];\n }\n if (i % ks === 0) {\n k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);\n }\n ekeys[i] = ekeys[i - ks] ^ k;\n }\n\n // Decryption key schedule\n for (var j = 0; j < i; j += 4) {\n for (var jj = 0; jj < 4; jj++) {\n var k = ekeys[i - (4 + j) + (4 - jj) % 4];\n if (j < 4 || j >= i - 4) {\n dkeys[j + jj] = k;\n } else {\n dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]\n ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]\n ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]\n ^ aes_dec[3][aes_sbox[k & 255]];\n }\n }\n }\n\n // Set rounds number\n asm.set_rounds(ks + 5);\n }\n\n // create library object with necessary properties\n var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};\n\n var asm = function (stdlib, foreign, buffer) {\n \"use asm\";\n\n var S0 = 0, S1 = 0, S2 = 0, S3 = 0,\n I0 = 0, I1 = 0, I2 = 0, I3 = 0,\n N0 = 0, N1 = 0, N2 = 0, N3 = 0,\n M0 = 0, M1 = 0, M2 = 0, M3 = 0,\n H0 = 0, H1 = 0, H2 = 0, H3 = 0,\n R = 0;\n\n var HEAP = new stdlib.Uint32Array(buffer),\n DATA = new stdlib.Uint8Array(buffer);\n\n /**\n * AES core\n * @param {number} k - precomputed key schedule offset\n * @param {number} s - precomputed sbox table offset\n * @param {number} t - precomputed round table offset\n * @param {number} r - number of inner rounds to perform\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _core(k, s, t, r, x0, x1, x2, x3) {\n k = k | 0;\n s = s | 0;\n t = t | 0;\n r = r | 0;\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t1 = 0, t2 = 0, t3 = 0,\n y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n i = 0;\n\n t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;\n\n // round 0\n x0 = x0 ^ HEAP[(k | 0) >> 2],\n x1 = x1 ^ HEAP[(k | 4) >> 2],\n x2 = x2 ^ HEAP[(k | 8) >> 2],\n x3 = x3 ^ HEAP[(k | 12) >> 2];\n\n // round 1..r\n for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {\n y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n x0 = y0, x1 = y1, x2 = y2, x3 = y3;\n }\n\n // final round\n S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],\n S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],\n S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],\n S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];\n }\n\n /**\n * ECB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n x0,\n x1,\n x2,\n x3\n );\n }\n\n /**\n * ECB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ecb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n }\n\n\n /**\n * CBC mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0 ^ x0,\n I1 ^ x1,\n I2 ^ x2,\n I3 ^ x3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n }\n\n /**\n * CBC mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cbc_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var t = 0;\n\n _core(\n 0x0400, 0x0c00, 0x2000,\n R,\n x0,\n x3,\n x2,\n x1\n );\n\n t = S1, S1 = S3, S3 = t;\n\n S0 = S0 ^ I0,\n S1 = S1 ^ I1,\n S2 = S2 ^ I2,\n S3 = S3 ^ I3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * CFB mode encryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_enc(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0 = S0 ^ x0,\n I1 = S1 = S1 ^ x1,\n I2 = S2 = S2 ^ x2,\n I3 = S3 = S3 ^ x3;\n }\n\n\n /**\n * CFB mode decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _cfb_dec(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n\n I0 = x0,\n I1 = x1,\n I2 = x2,\n I3 = x3;\n }\n\n /**\n * OFB mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ofb(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n I0,\n I1,\n I2,\n I3\n );\n\n I0 = S0,\n I1 = S1,\n I2 = S2,\n I3 = S3;\n\n S0 = S0 ^ x0,\n S1 = S1 ^ x1,\n S2 = S2 ^ x2,\n S3 = S3 ^ x3;\n }\n\n /**\n * CTR mode encryption / decryption\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _ctr(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n _core(\n 0x0000, 0x0800, 0x1000,\n R,\n N0,\n N1,\n N2,\n N3\n );\n\n N3 = (~M3 & N3) | M3 & (N3 + 1);\n N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));\n N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));\n N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));\n\n S0 = S0 ^ x0;\n S1 = S1 ^ x1;\n S2 = S2 ^ x2;\n S3 = S3 ^ x3;\n }\n\n /**\n * GCM mode MAC calculation\n * @param {number} x0 - 128-bit input block vector\n * @param {number} x1 - 128-bit input block vector\n * @param {number} x2 - 128-bit input block vector\n * @param {number} x3 - 128-bit input block vector\n */\n function _gcm_mac(x0, x1, x2, x3) {\n x0 = x0 | 0;\n x1 = x1 | 0;\n x2 = x2 | 0;\n x3 = x3 | 0;\n\n var y0 = 0, y1 = 0, y2 = 0, y3 = 0,\n z0 = 0, z1 = 0, z2 = 0, z3 = 0,\n i = 0, c = 0;\n\n x0 = x0 ^ I0,\n x1 = x1 ^ I1,\n x2 = x2 ^ I2,\n x3 = x3 ^ I3;\n\n y0 = H0 | 0,\n y1 = H1 | 0,\n y2 = H2 | 0,\n y3 = H3 | 0;\n\n for (; (i | 0) < 128; i = (i + 1) | 0) {\n if (y0 >>> 31) {\n z0 = z0 ^ x0,\n z1 = z1 ^ x1,\n z2 = z2 ^ x2,\n z3 = z3 ^ x3;\n }\n\n y0 = (y0 << 1) | (y1 >>> 31),\n y1 = (y1 << 1) | (y2 >>> 31),\n y2 = (y2 << 1) | (y3 >>> 31),\n y3 = (y3 << 1);\n\n c = x3 & 1;\n\n x3 = (x3 >>> 1) | (x2 << 31),\n x2 = (x2 >>> 1) | (x1 << 31),\n x1 = (x1 >>> 1) | (x0 << 31),\n x0 = (x0 >>> 1);\n\n if (c) x0 = x0 ^ 0xe1000000;\n }\n\n I0 = z0,\n I1 = z1,\n I2 = z2,\n I3 = z3;\n }\n\n /**\n * Set the internal rounds number.\n * @instance\n * @memberof AES_asm\n * @param {number} r - number if inner AES rounds\n */\n function set_rounds(r) {\n r = r | 0;\n R = r;\n }\n\n /**\n * Populate the internal state of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} s0 - state vector\n * @param {number} s1 - state vector\n * @param {number} s2 - state vector\n * @param {number} s3 - state vector\n */\n function set_state(s0, s1, s2, s3) {\n s0 = s0 | 0;\n s1 = s1 | 0;\n s2 = s2 | 0;\n s3 = s3 | 0;\n\n S0 = s0,\n S1 = s1,\n S2 = s2,\n S3 = s3;\n }\n\n /**\n * Populate the internal iv of the module.\n * @instance\n * @memberof AES_asm\n * @param {number} i0 - iv vector\n * @param {number} i1 - iv vector\n * @param {number} i2 - iv vector\n * @param {number} i3 - iv vector\n */\n function set_iv(i0, i1, i2, i3) {\n i0 = i0 | 0;\n i1 = i1 | 0;\n i2 = i2 | 0;\n i3 = i3 | 0;\n\n I0 = i0,\n I1 = i1,\n I2 = i2,\n I3 = i3;\n }\n\n /**\n * Set nonce for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} n0 - nonce vector\n * @param {number} n1 - nonce vector\n * @param {number} n2 - nonce vector\n * @param {number} n3 - nonce vector\n */\n function set_nonce(n0, n1, n2, n3) {\n n0 = n0 | 0;\n n1 = n1 | 0;\n n2 = n2 | 0;\n n3 = n3 | 0;\n\n N0 = n0,\n N1 = n1,\n N2 = n2,\n N3 = n3;\n }\n\n /**\n * Set counter mask for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} m0 - counter mask vector\n * @param {number} m1 - counter mask vector\n * @param {number} m2 - counter mask vector\n * @param {number} m3 - counter mask vector\n */\n function set_mask(m0, m1, m2, m3) {\n m0 = m0 | 0;\n m1 = m1 | 0;\n m2 = m2 | 0;\n m3 = m3 | 0;\n\n M0 = m0,\n M1 = m1,\n M2 = m2,\n M3 = m3;\n }\n\n /**\n * Set counter for CTR-family modes.\n * @instance\n * @memberof AES_asm\n * @param {number} c0 - counter vector\n * @param {number} c1 - counter vector\n * @param {number} c2 - counter vector\n * @param {number} c3 - counter vector\n */\n function set_counter(c0, c1, c2, c3) {\n c0 = c0 | 0;\n c1 = c1 | 0;\n c2 = c2 | 0;\n c3 = c3 | 0;\n\n N3 = (~M3 & N3) | M3 & c3,\n N2 = (~M2 & N2) | M2 & c2,\n N1 = (~M1 & N1) | M1 & c1,\n N0 = (~M0 & N0) | M0 & c0;\n }\n\n /**\n * Store the internal state vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_state(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n return 16;\n }\n\n /**\n * Store the internal iv vector into the heap.\n * @instance\n * @memberof AES_asm\n * @param {number} pos - offset where to put the data\n * @return {number} The number of bytes have been written into the heap, always 16.\n */\n function get_iv(pos) {\n pos = pos | 0;\n\n if (pos & 15) return -1;\n\n DATA[pos | 0] = I0 >>> 24,\n DATA[pos | 1] = I0 >>> 16 & 255,\n DATA[pos | 2] = I0 >>> 8 & 255,\n DATA[pos | 3] = I0 & 255,\n DATA[pos | 4] = I1 >>> 24,\n DATA[pos | 5] = I1 >>> 16 & 255,\n DATA[pos | 6] = I1 >>> 8 & 255,\n DATA[pos | 7] = I1 & 255,\n DATA[pos | 8] = I2 >>> 24,\n DATA[pos | 9] = I2 >>> 16 & 255,\n DATA[pos | 10] = I2 >>> 8 & 255,\n DATA[pos | 11] = I2 & 255,\n DATA[pos | 12] = I3 >>> 24,\n DATA[pos | 13] = I3 >>> 16 & 255,\n DATA[pos | 14] = I3 >>> 8 & 255,\n DATA[pos | 15] = I3 & 255;\n\n return 16;\n }\n\n /**\n * GCM initialization.\n * @instance\n * @memberof AES_asm\n */\n function gcm_init() {\n _ecb_enc(0, 0, 0, 0);\n H0 = S0,\n H1 = S1,\n H2 = S2,\n H3 = S3;\n }\n\n /**\n * Perform ciphering operation on the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function cipher(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _cipher_modes[mode & 7](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n DATA[pos | 0] = S0 >>> 24,\n DATA[pos | 1] = S0 >>> 16 & 255,\n DATA[pos | 2] = S0 >>> 8 & 255,\n DATA[pos | 3] = S0 & 255,\n DATA[pos | 4] = S1 >>> 24,\n DATA[pos | 5] = S1 >>> 16 & 255,\n DATA[pos | 6] = S1 >>> 8 & 255,\n DATA[pos | 7] = S1 & 255,\n DATA[pos | 8] = S2 >>> 24,\n DATA[pos | 9] = S2 >>> 16 & 255,\n DATA[pos | 10] = S2 >>> 8 & 255,\n DATA[pos | 11] = S2 & 255,\n DATA[pos | 12] = S3 >>> 24,\n DATA[pos | 13] = S3 >>> 16 & 255,\n DATA[pos | 14] = S3 >>> 8 & 255,\n DATA[pos | 15] = S3 & 255;\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * Calculates MAC of the supplied data.\n * @instance\n * @memberof AES_asm\n * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)\n * @param {number} pos - offset of the data being processed\n * @param {number} len - length of the data being processed\n * @return {number} Actual amount of data have been processed.\n */\n function mac(mode, pos, len) {\n mode = mode | 0;\n pos = pos | 0;\n len = len | 0;\n\n var ret = 0;\n\n if (pos & 15) return -1;\n\n while ((len | 0) >= 16) {\n _mac_modes[mode & 1](\n DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],\n DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],\n DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],\n DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]\n );\n\n ret = (ret + 16) | 0,\n pos = (pos + 16) | 0,\n len = (len - 16) | 0;\n }\n\n return ret | 0;\n }\n\n /**\n * AES cipher modes table (virual methods)\n */\n var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];\n\n /**\n * AES MAC modes table (virual methods)\n */\n var _mac_modes = [_cbc_enc, _gcm_mac];\n\n /**\n * Asm.js module exports\n */\n return {\n set_rounds: set_rounds,\n set_state: set_state,\n set_iv: set_iv,\n set_nonce: set_nonce,\n set_mask: set_mask,\n set_counter: set_counter,\n get_state: get_state,\n get_iv: get_iv,\n gcm_init: gcm_init,\n cipher: cipher,\n mac: mac,\n };\n }(stdlib, foreign, buffer);\n\n asm.set_key = set_key;\n\n return asm;\n };\n\n /**\n * AES enciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.ENC = {\n ECB: 0,\n CBC: 2,\n CFB: 4,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES deciphering mode constants\n * @enum {number}\n * @const\n */\n wrapper.DEC = {\n ECB: 1,\n CBC: 3,\n CFB: 5,\n OFB: 6,\n CTR: 7,\n },\n\n /**\n * AES MAC mode constants\n * @enum {number}\n * @const\n */\n wrapper.MAC = {\n CBC: 0,\n GCM: 1,\n };\n\n /**\n * Heap data offset\n * @type {number}\n * @const\n */\n wrapper.HEAP_DATA = 0x4000;\n\n return wrapper;\n}();\n","const local_atob = typeof atob === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'base64').toString('binary') : atob;\nconst local_btoa = typeof btoa === 'undefined' ? (str) => require('buffer').Buffer.from(str, 'binary').toString('base64') : btoa;\nexport function string_to_bytes(str, utf8 = false) {\n var len = str.length, bytes = new Uint8Array(utf8 ? 4 * len : len);\n for (var i = 0, j = 0; i < len; i++) {\n var c = str.charCodeAt(i);\n if (utf8 && 0xd800 <= c && c <= 0xdbff) {\n if (++i >= len)\n throw new Error('Malformed string, low surrogate expected at position ' + i);\n c = ((c ^ 0xd800) << 10) | 0x10000 | (str.charCodeAt(i) ^ 0xdc00);\n }\n else if (!utf8 && c >>> 8) {\n throw new Error('Wide characters are not allowed.');\n }\n if (!utf8 || c <= 0x7f) {\n bytes[j++] = c;\n }\n else if (c <= 0x7ff) {\n bytes[j++] = 0xc0 | (c >> 6);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else if (c <= 0xffff) {\n bytes[j++] = 0xe0 | (c >> 12);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n else {\n bytes[j++] = 0xf0 | (c >> 18);\n bytes[j++] = 0x80 | ((c >> 12) & 0x3f);\n bytes[j++] = 0x80 | ((c >> 6) & 0x3f);\n bytes[j++] = 0x80 | (c & 0x3f);\n }\n }\n return bytes.subarray(0, j);\n}\nexport function hex_to_bytes(str) {\n var len = str.length;\n if (len & 1) {\n str = '0' + str;\n len++;\n }\n var bytes = new Uint8Array(len >> 1);\n for (var i = 0; i < len; i += 2) {\n bytes[i >> 1] = parseInt(str.substr(i, 2), 16);\n }\n return bytes;\n}\nexport function base64_to_bytes(str) {\n return string_to_bytes(local_atob(str));\n}\nexport function bytes_to_string(bytes, utf8 = false) {\n var len = bytes.length, chars = new Array(len);\n for (var i = 0, j = 0; i < len; i++) {\n var b = bytes[i];\n if (!utf8 || b < 128) {\n chars[j++] = b;\n }\n else if (b >= 192 && b < 224 && i + 1 < len) {\n chars[j++] = ((b & 0x1f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 224 && b < 240 && i + 2 < len) {\n chars[j++] = ((b & 0xf) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n }\n else if (b >= 240 && b < 248 && i + 3 < len) {\n var c = ((b & 7) << 18) | ((bytes[++i] & 0x3f) << 12) | ((bytes[++i] & 0x3f) << 6) | (bytes[++i] & 0x3f);\n if (c <= 0xffff) {\n chars[j++] = c;\n }\n else {\n c ^= 0x10000;\n chars[j++] = 0xd800 | (c >> 10);\n chars[j++] = 0xdc00 | (c & 0x3ff);\n }\n }\n else {\n throw new Error('Malformed UTF8 character at byte offset ' + i);\n }\n }\n var str = '', bs = 16384;\n for (var i = 0; i < j; i += bs) {\n str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));\n }\n return str;\n}\nexport function bytes_to_hex(arr) {\n var str = '';\n for (var i = 0; i < arr.length; i++) {\n var h = (arr[i] & 0xff).toString(16);\n if (h.length < 2)\n str += '0';\n str += h;\n }\n return str;\n}\nexport function bytes_to_base64(arr) {\n return local_btoa(bytes_to_string(arr));\n}\nexport function pow2_ceil(a) {\n a -= 1;\n a |= a >>> 1;\n a |= a >>> 2;\n a |= a >>> 4;\n a |= a >>> 8;\n a |= a >>> 16;\n a += 1;\n return a;\n}\nexport function is_number(a) {\n return typeof a === 'number';\n}\nexport function is_string(a) {\n return typeof a === 'string';\n}\nexport function is_buffer(a) {\n return a instanceof ArrayBuffer;\n}\nexport function is_bytes(a) {\n return a instanceof Uint8Array;\n}\nexport function is_typed_array(a) {\n return (a instanceof Int8Array ||\n a instanceof Uint8Array ||\n a instanceof Int16Array ||\n a instanceof Uint16Array ||\n a instanceof Int32Array ||\n a instanceof Uint32Array ||\n a instanceof Float32Array ||\n a instanceof Float64Array);\n}\nexport function _heap_init(heap, heapSize) {\n const size = heap ? heap.byteLength : heapSize || 65536;\n if (size & 0xfff || size <= 0)\n throw new Error('heap size must be a positive integer and a multiple of 4096');\n heap = heap || new Uint8Array(new ArrayBuffer(size));\n return heap;\n}\nexport function _heap_write(heap, hpos, data, dpos, dlen) {\n const hlen = heap.length - hpos;\n const wlen = hlen < dlen ? hlen : dlen;\n heap.set(data.subarray(dpos, dpos + wlen), hpos);\n return wlen;\n}\nexport function joinBytes(...arg) {\n const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);\n const ret = new Uint8Array(totalLenght);\n let cursor = 0;\n for (let i = 0; i < arg.length; i++) {\n ret.set(arg[i], cursor);\n cursor += arg[i].length;\n }\n return ret;\n}\n","export class IllegalStateError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });\n }\n}\nexport class IllegalArgumentError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });\n }\n}\nexport class SecurityError extends Error {\n constructor(...args) {\n super(...args);\n Object.create(Error.prototype, { name: { value: 'SecurityError' } });\n }\n}\n","import { AES_asm } from './aes.asm';\nimport { _heap_init, _heap_write, is_bytes } from '../other/utils';\nimport { IllegalArgumentError, SecurityError } from '../other/errors';\nconst heap_pool = [];\nconst asm_pool = [];\nexport class AES {\n constructor(key, iv, padding = true, mode, heap, asm) {\n this.pos = 0;\n this.len = 0;\n this.mode = mode;\n // The AES object state\n this.pos = 0;\n this.len = 0;\n this.key = key;\n this.iv = iv;\n this.padding = padding;\n // The AES \"worker\"\n this.acquire_asm(heap, asm);\n }\n acquire_asm(heap, asm) {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);\n this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);\n this.reset(this.key, this.iv);\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n reset(key, iv) {\n const { asm } = this.acquire_asm();\n // Key\n const keylen = key.length;\n if (keylen !== 16 && keylen !== 24 && keylen !== 32)\n throw new IllegalArgumentError('illegal key size');\n const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);\n asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);\n // IV\n if (iv !== undefined) {\n if (iv.length !== 16)\n throw new IllegalArgumentError('illegal iv size');\n let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));\n }\n else {\n asm.set_iv(0, 0, 0, 0);\n }\n }\n AES_Encrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n let result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Encrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.ENC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let plen = 16 - (len % 16);\n let rlen = len;\n if (this.hasOwnProperty('padding')) {\n if (this.padding) {\n for (let p = 0; p < plen; ++p) {\n heap[pos + len + p] = plen;\n }\n len += plen;\n rlen = len;\n }\n else if (len % 16) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n }\n else {\n len += plen;\n }\n const result = new Uint8Array(rlen);\n if (len)\n asm.cipher(amode, hpos + pos, len);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n AES_Decrypt_process(data) {\n if (!is_bytes(data))\n throw new TypeError(\"data isn't of expected type\");\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let dpos = 0;\n let dlen = data.length || 0;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let plen = 0;\n let wlen = 0;\n if (this.padding) {\n plen = len + dlen - rlen || 16;\n rlen -= plen;\n }\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.pos = pos;\n this.len = len;\n return result;\n }\n AES_Decrypt_finish() {\n let { heap, asm } = this.acquire_asm();\n let amode = AES_asm.DEC[this.mode];\n let hpos = AES_asm.HEAP_DATA;\n let pos = this.pos;\n let len = this.len;\n let rlen = len;\n if (len > 0) {\n if (len % 16) {\n if (this.hasOwnProperty('padding')) {\n throw new IllegalArgumentError('data length must be a multiple of the block size');\n }\n else {\n len += 16 - (len % 16);\n }\n }\n asm.cipher(amode, hpos + pos, len);\n if (this.hasOwnProperty('padding') && this.padding) {\n let pad = heap[pos + rlen - 1];\n if (pad < 1 || pad > 16 || pad > rlen)\n throw new SecurityError('bad padding');\n let pcheck = 0;\n for (let i = pad; i > 1; i--)\n pcheck |= pad ^ heap[pos + rlen - i];\n if (pcheck)\n throw new SecurityError('bad padding');\n rlen -= pad;\n }\n }\n const result = new Uint8Array(rlen);\n if (rlen > 0) {\n result.set(heap.subarray(pos, pos + rlen));\n }\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return result;\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_ECB {\n static encrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).encrypt(data);\n }\n static decrypt(data, key, padding = false) {\n return new AES_ECB(key, padding).decrypt(data);\n }\n constructor(key, padding = false, aes) {\n this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import { AES_ECB } from '@openpgp/asmcrypto.js/dist_es8/aes/ecb';\n\n/**\n * Javascript AES implementation.\n * This is used as fallback if the native Crypto APIs are not available.\n */\nfunction aes(length) {\n const C = function(key) {\n const aesECB = new AES_ECB(key);\n\n this.encrypt = function(block) {\n return aesECB.encrypt(block);\n };\n\n this.decrypt = function(block) {\n return aesECB.decrypt(block);\n };\n };\n\n C.blockSize = C.prototype.blockSize = 16;\n C.keySize = C.prototype.keySize = length / 8;\n\n return C;\n}\n\nexport default aes;\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * @fileoverview Symmetric cryptography functions\n * @module crypto/cipher\n * @private\n */\n\nimport aes from './aes';\nimport { DES, TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TF from './twofish';\nimport BF from './blowfish';\n\n/**\n * AES-128 encryption and decryption (ID 7)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes128 = aes(128);\n/**\n * AES-128 Block Cipher (ID 8)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes192 = aes(192);\n/**\n * AES-128 Block Cipher (ID 9)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}\n * @returns {Object}\n */\nexport const aes256 = aes(256);\n// Not in OpenPGP specifications\nexport const des = DES;\n/**\n * Triple DES Block Cipher (ID 2)\n * @function\n * @param {String} key - 192-bit key\n * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}\n * @returns {Object}\n */\nexport const tripledes = TripleDES;\n/**\n * CAST-128 Block Cipher (ID 3)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}\n * @returns {Object}\n */\nexport const cast5 = CAST5;\n/**\n * Twofish Block Cipher (ID 10)\n * @function\n * @param {String} key - 256-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}\n * @returns {Object}\n */\nexport const twofish = TF;\n/**\n * Blowfish Block Cipher (ID 4)\n * @function\n * @param {String} key - 128-bit key\n * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}\n * @returns {Object}\n */\nexport const blowfish = BF;\n/**\n * Not implemented\n * @function\n * @throws {Error}\n */\nexport const idea = function() {\n throw new Error('IDEA symmetric-key algorithm not implemented');\n};\n","export var sha1_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,\n w16 = 0, w17 = 0, w18 = 0, w19 = 0,\n w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,\n w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,\n w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,\n w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,\n w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,\n w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n\n // 0\n t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 1\n t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 2\n t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 3\n t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 4\n t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 5\n t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 6\n t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 7\n t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 8\n t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 9\n t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 10\n t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 11\n t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 12\n t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 13\n t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 14\n t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 15\n t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 16\n n = w13 ^ w8 ^ w2 ^ w0;\n w16 = (n << 1) | (n >>> 31);\n t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 17\n n = w14 ^ w9 ^ w3 ^ w1;\n w17 = (n << 1) | (n >>> 31);\n t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 18\n n = w15 ^ w10 ^ w4 ^ w2;\n w18 = (n << 1) | (n >>> 31);\n t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 19\n n = w16 ^ w11 ^ w5 ^ w3;\n w19 = (n << 1) | (n >>> 31);\n t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 20\n n = w17 ^ w12 ^ w6 ^ w4;\n w20 = (n << 1) | (n >>> 31);\n t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 21\n n = w18 ^ w13 ^ w7 ^ w5;\n w21 = (n << 1) | (n >>> 31);\n t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 22\n n = w19 ^ w14 ^ w8 ^ w6;\n w22 = (n << 1) | (n >>> 31);\n t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 23\n n = w20 ^ w15 ^ w9 ^ w7;\n w23 = (n << 1) | (n >>> 31);\n t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 24\n n = w21 ^ w16 ^ w10 ^ w8;\n w24 = (n << 1) | (n >>> 31);\n t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 25\n n = w22 ^ w17 ^ w11 ^ w9;\n w25 = (n << 1) | (n >>> 31);\n t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 26\n n = w23 ^ w18 ^ w12 ^ w10;\n w26 = (n << 1) | (n >>> 31);\n t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 27\n n = w24 ^ w19 ^ w13 ^ w11;\n w27 = (n << 1) | (n >>> 31);\n t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 28\n n = w25 ^ w20 ^ w14 ^ w12;\n w28 = (n << 1) | (n >>> 31);\n t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 29\n n = w26 ^ w21 ^ w15 ^ w13;\n w29 = (n << 1) | (n >>> 31);\n t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 30\n n = w27 ^ w22 ^ w16 ^ w14;\n w30 = (n << 1) | (n >>> 31);\n t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 31\n n = w28 ^ w23 ^ w17 ^ w15;\n w31 = (n << 1) | (n >>> 31);\n t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 32\n n = w29 ^ w24 ^ w18 ^ w16;\n w32 = (n << 1) | (n >>> 31);\n t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 33\n n = w30 ^ w25 ^ w19 ^ w17;\n w33 = (n << 1) | (n >>> 31);\n t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 34\n n = w31 ^ w26 ^ w20 ^ w18;\n w34 = (n << 1) | (n >>> 31);\n t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 35\n n = w32 ^ w27 ^ w21 ^ w19;\n w35 = (n << 1) | (n >>> 31);\n t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 36\n n = w33 ^ w28 ^ w22 ^ w20;\n w36 = (n << 1) | (n >>> 31);\n t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 37\n n = w34 ^ w29 ^ w23 ^ w21;\n w37 = (n << 1) | (n >>> 31);\n t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 38\n n = w35 ^ w30 ^ w24 ^ w22;\n w38 = (n << 1) | (n >>> 31);\n t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 39\n n = w36 ^ w31 ^ w25 ^ w23;\n w39 = (n << 1) | (n >>> 31);\n t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 40\n n = w37 ^ w32 ^ w26 ^ w24;\n w40 = (n << 1) | (n >>> 31);\n t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 41\n n = w38 ^ w33 ^ w27 ^ w25;\n w41 = (n << 1) | (n >>> 31);\n t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 42\n n = w39 ^ w34 ^ w28 ^ w26;\n w42 = (n << 1) | (n >>> 31);\n t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 43\n n = w40 ^ w35 ^ w29 ^ w27;\n w43 = (n << 1) | (n >>> 31);\n t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 44\n n = w41 ^ w36 ^ w30 ^ w28;\n w44 = (n << 1) | (n >>> 31);\n t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 45\n n = w42 ^ w37 ^ w31 ^ w29;\n w45 = (n << 1) | (n >>> 31);\n t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 46\n n = w43 ^ w38 ^ w32 ^ w30;\n w46 = (n << 1) | (n >>> 31);\n t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 47\n n = w44 ^ w39 ^ w33 ^ w31;\n w47 = (n << 1) | (n >>> 31);\n t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 48\n n = w45 ^ w40 ^ w34 ^ w32;\n w48 = (n << 1) | (n >>> 31);\n t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 49\n n = w46 ^ w41 ^ w35 ^ w33;\n w49 = (n << 1) | (n >>> 31);\n t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 50\n n = w47 ^ w42 ^ w36 ^ w34;\n w50 = (n << 1) | (n >>> 31);\n t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 51\n n = w48 ^ w43 ^ w37 ^ w35;\n w51 = (n << 1) | (n >>> 31);\n t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 52\n n = w49 ^ w44 ^ w38 ^ w36;\n w52 = (n << 1) | (n >>> 31);\n t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 53\n n = w50 ^ w45 ^ w39 ^ w37;\n w53 = (n << 1) | (n >>> 31);\n t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 54\n n = w51 ^ w46 ^ w40 ^ w38;\n w54 = (n << 1) | (n >>> 31);\n t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 55\n n = w52 ^ w47 ^ w41 ^ w39;\n w55 = (n << 1) | (n >>> 31);\n t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 56\n n = w53 ^ w48 ^ w42 ^ w40;\n w56 = (n << 1) | (n >>> 31);\n t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 57\n n = w54 ^ w49 ^ w43 ^ w41;\n w57 = (n << 1) | (n >>> 31);\n t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 58\n n = w55 ^ w50 ^ w44 ^ w42;\n w58 = (n << 1) | (n >>> 31);\n t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 59\n n = w56 ^ w51 ^ w45 ^ w43;\n w59 = (n << 1) | (n >>> 31);\n t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 60\n n = w57 ^ w52 ^ w46 ^ w44;\n w60 = (n << 1) | (n >>> 31);\n t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 61\n n = w58 ^ w53 ^ w47 ^ w45;\n w61 = (n << 1) | (n >>> 31);\n t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 62\n n = w59 ^ w54 ^ w48 ^ w46;\n w62 = (n << 1) | (n >>> 31);\n t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 63\n n = w60 ^ w55 ^ w49 ^ w47;\n w63 = (n << 1) | (n >>> 31);\n t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 64\n n = w61 ^ w56 ^ w50 ^ w48;\n w64 = (n << 1) | (n >>> 31);\n t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 65\n n = w62 ^ w57 ^ w51 ^ w49;\n w65 = (n << 1) | (n >>> 31);\n t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 66\n n = w63 ^ w58 ^ w52 ^ w50;\n w66 = (n << 1) | (n >>> 31);\n t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 67\n n = w64 ^ w59 ^ w53 ^ w51;\n w67 = (n << 1) | (n >>> 31);\n t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 68\n n = w65 ^ w60 ^ w54 ^ w52;\n w68 = (n << 1) | (n >>> 31);\n t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 69\n n = w66 ^ w61 ^ w55 ^ w53;\n w69 = (n << 1) | (n >>> 31);\n t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 70\n n = w67 ^ w62 ^ w56 ^ w54;\n w70 = (n << 1) | (n >>> 31);\n t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 71\n n = w68 ^ w63 ^ w57 ^ w55;\n w71 = (n << 1) | (n >>> 31);\n t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 72\n n = w69 ^ w64 ^ w58 ^ w56;\n w72 = (n << 1) | (n >>> 31);\n t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 73\n n = w70 ^ w65 ^ w59 ^ w57;\n w73 = (n << 1) | (n >>> 31);\n t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 74\n n = w71 ^ w66 ^ w60 ^ w58;\n w74 = (n << 1) | (n >>> 31);\n t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 75\n n = w72 ^ w67 ^ w61 ^ w59;\n w75 = (n << 1) | (n >>> 31);\n t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 76\n n = w73 ^ w68 ^ w62 ^ w60;\n w76 = (n << 1) | (n >>> 31);\n t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 77\n n = w74 ^ w69 ^ w63 ^ w61;\n w77 = (n << 1) | (n >>> 31);\n t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 78\n n = w75 ^ w70 ^ w64 ^ w62;\n w78 = (n << 1) | (n >>> 31);\n t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n // 79\n n = w76 ^ w71 ^ w65 ^ w63;\n w79 = (n << 1) | (n >>> 31);\n t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;\n e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n }\n\n function reset () {\n H0 = 0x67452301;\n H1 = 0xefcdab89;\n H2 = 0x98badcfe;\n H3 = 0x10325476;\n H4 = 0xc3d2e1f0;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA1\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA1\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA1\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","import { _heap_write } from '../other/utils';\nimport { IllegalStateError } from '../other/errors';\nexport class Hash {\n constructor() {\n this.pos = 0;\n this.len = 0;\n }\n reset() {\n const { asm } = this.acquire_asm();\n this.result = null;\n this.pos = 0;\n this.len = 0;\n asm.reset();\n return this;\n }\n process(data) {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n let hpos = this.pos;\n let hlen = this.len;\n let dpos = 0;\n let dlen = data.length;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);\n hlen += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.process(hpos, hlen);\n hpos += wlen;\n hlen -= wlen;\n if (!hlen)\n hpos = 0;\n }\n this.pos = hpos;\n this.len = hlen;\n return this;\n }\n finish() {\n if (this.result !== null)\n throw new IllegalStateError('state must be reset before processing new data');\n const { asm, heap } = this.acquire_asm();\n asm.finish(this.pos, this.len, 0);\n this.result = new Uint8Array(this.HASH_SIZE);\n this.result.set(heap.subarray(0, this.HASH_SIZE));\n this.pos = 0;\n this.len = 0;\n this.release_asm();\n return this;\n }\n}\n","import { sha1_asm } from './sha1.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha1_block_size = 64;\nexport const _sha1_hash_size = 20;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha1 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha1';\n this.BLOCK_SIZE = _sha1_block_size;\n this.HASH_SIZE = _sha1_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha1().process(data).finish().result;\n }\n}\nSha1.NAME = 'sha1';\nSha1.heap_pool = [];\nSha1.asm_pool = [];\nSha1.asm_function = sha1_asm;\n","import { sha256_asm } from './sha256.asm';\nimport { Hash } from '../hash';\nimport { _heap_init } from '../../other/utils';\nexport const _sha256_block_size = 64;\nexport const _sha256_hash_size = 32;\nconst heap_pool = [];\nconst asm_pool = [];\nexport class Sha256 extends Hash {\n constructor() {\n super();\n this.NAME = 'sha256';\n this.BLOCK_SIZE = _sha256_block_size;\n this.HASH_SIZE = _sha256_hash_size;\n this.acquire_asm();\n }\n acquire_asm() {\n if (this.heap === undefined || this.asm === undefined) {\n this.heap = heap_pool.pop() || _heap_init();\n this.asm = asm_pool.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);\n this.reset();\n }\n return { heap: this.heap, asm: this.asm };\n }\n release_asm() {\n if (this.heap !== undefined && this.asm !== undefined) {\n heap_pool.push(this.heap);\n asm_pool.push(this.asm);\n }\n this.heap = undefined;\n this.asm = undefined;\n }\n static bytes(data) {\n return new Sha256().process(data).finish().result;\n }\n}\nSha256.NAME = 'sha256';\n","export var sha256_asm = function ( stdlib, foreign, buffer ) {\n \"use asm\";\n\n // SHA256 state\n var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,\n TOTAL0 = 0, TOTAL1 = 0;\n\n // HMAC state\n var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,\n O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;\n\n // I/O buffer\n var HEAP = new stdlib.Uint8Array(buffer);\n\n function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {\n w0 = w0|0;\n w1 = w1|0;\n w2 = w2|0;\n w3 = w3|0;\n w4 = w4|0;\n w5 = w5|0;\n w6 = w6|0;\n w7 = w7|0;\n w8 = w8|0;\n w9 = w9|0;\n w10 = w10|0;\n w11 = w11|0;\n w12 = w12|0;\n w13 = w13|0;\n w14 = w14|0;\n w15 = w15|0;\n\n var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;\n\n a = H0;\n b = H1;\n c = H2;\n d = H3;\n e = H4;\n f = H5;\n g = H6;\n h = H7;\n \n // 0\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 1\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 2\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 3\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 4\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 5\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 6\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 7\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 8\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 9\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 10\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 11\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 12\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 13\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 14\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 15\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 16\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 17\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 18\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 19\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 20\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 21\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 22\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 23\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 24\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 25\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 26\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 27\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 28\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 29\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 30\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 31\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 32\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 33\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 34\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 35\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 36\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 37\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 38\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 39\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 40\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 41\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 42\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 43\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 44\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 45\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 46\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 47\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 48\n w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;\n h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 49\n w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;\n g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 50\n w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;\n f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 51\n w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;\n e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 52\n w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;\n d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 53\n w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;\n c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 54\n w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;\n b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 55\n w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;\n a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n // 56\n w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;\n h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;\n d = ( d + h )|0;\n h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;\n\n // 57\n w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;\n g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;\n c = ( c + g )|0;\n g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;\n\n // 58\n w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;\n f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;\n b = ( b + f )|0;\n f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;\n\n // 59\n w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;\n e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;\n a = ( a + e )|0;\n e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;\n\n // 60\n w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;\n d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;\n h = ( h + d )|0;\n d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;\n\n // 61\n w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;\n c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;\n g = ( g + c )|0;\n c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;\n\n // 62\n w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;\n b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;\n f = ( f + b )|0;\n b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;\n\n // 63\n w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;\n a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;\n e = ( e + a )|0;\n a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;\n\n H0 = ( H0 + a )|0;\n H1 = ( H1 + b )|0;\n H2 = ( H2 + c )|0;\n H3 = ( H3 + d )|0;\n H4 = ( H4 + e )|0;\n H5 = ( H5 + f )|0;\n H6 = ( H6 + g )|0;\n H7 = ( H7 + h )|0;\n }\n\n function _core_heap ( offset ) {\n offset = offset|0;\n\n _core(\n HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],\n HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],\n HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],\n HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],\n HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],\n HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],\n HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],\n HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],\n HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],\n HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],\n HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],\n HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],\n HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],\n HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],\n HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],\n HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]\n );\n }\n\n // offset — multiple of 32\n function _state_to_heap ( output ) {\n output = output|0;\n\n HEAP[output|0] = H0>>>24;\n HEAP[output|1] = H0>>>16&255;\n HEAP[output|2] = H0>>>8&255;\n HEAP[output|3] = H0&255;\n HEAP[output|4] = H1>>>24;\n HEAP[output|5] = H1>>>16&255;\n HEAP[output|6] = H1>>>8&255;\n HEAP[output|7] = H1&255;\n HEAP[output|8] = H2>>>24;\n HEAP[output|9] = H2>>>16&255;\n HEAP[output|10] = H2>>>8&255;\n HEAP[output|11] = H2&255;\n HEAP[output|12] = H3>>>24;\n HEAP[output|13] = H3>>>16&255;\n HEAP[output|14] = H3>>>8&255;\n HEAP[output|15] = H3&255;\n HEAP[output|16] = H4>>>24;\n HEAP[output|17] = H4>>>16&255;\n HEAP[output|18] = H4>>>8&255;\n HEAP[output|19] = H4&255;\n HEAP[output|20] = H5>>>24;\n HEAP[output|21] = H5>>>16&255;\n HEAP[output|22] = H5>>>8&255;\n HEAP[output|23] = H5&255;\n HEAP[output|24] = H6>>>24;\n HEAP[output|25] = H6>>>16&255;\n HEAP[output|26] = H6>>>8&255;\n HEAP[output|27] = H6&255;\n HEAP[output|28] = H7>>>24;\n HEAP[output|29] = H7>>>16&255;\n HEAP[output|30] = H7>>>8&255;\n HEAP[output|31] = H7&255;\n }\n\n function reset () {\n H0 = 0x6a09e667;\n H1 = 0xbb67ae85;\n H2 = 0x3c6ef372;\n H3 = 0xa54ff53a;\n H4 = 0x510e527f;\n H5 = 0x9b05688c;\n H6 = 0x1f83d9ab;\n H7 = 0x5be0cd19;\n TOTAL0 = TOTAL1 = 0;\n }\n\n function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {\n h0 = h0|0;\n h1 = h1|0;\n h2 = h2|0;\n h3 = h3|0;\n h4 = h4|0;\n h5 = h5|0;\n h6 = h6|0;\n h7 = h7|0;\n total0 = total0|0;\n total1 = total1|0;\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n TOTAL0 = total0;\n TOTAL1 = total1;\n }\n\n // offset — multiple of 64\n function process ( offset, length ) {\n offset = offset|0;\n length = length|0;\n\n var hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n while ( (length|0) >= 64 ) {\n _core_heap(offset);\n\n offset = ( offset + 64 )|0;\n length = ( length - 64 )|0;\n\n hashed = ( hashed + 64 )|0;\n }\n\n TOTAL0 = ( TOTAL0 + hashed )|0;\n if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n return hashed|0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var hashed = 0,\n i = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n if ( (length|0) >= 64 ) {\n hashed = process( offset, length )|0;\n if ( (hashed|0) == -1 )\n return -1;\n\n offset = ( offset + hashed )|0;\n length = ( length - hashed )|0;\n }\n\n hashed = ( hashed + length )|0;\n TOTAL0 = ( TOTAL0 + length )|0;\n if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;\n\n HEAP[offset|length] = 0x80;\n\n if ( (length|0) >= 56 ) {\n for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )\n HEAP[offset|i] = 0x00;\n\n _core_heap(offset);\n\n length = 0;\n\n HEAP[offset|0] = 0;\n }\n\n for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )\n HEAP[offset|i] = 0;\n\n HEAP[offset|56] = TOTAL1>>>21&255;\n HEAP[offset|57] = TOTAL1>>>13&255;\n HEAP[offset|58] = TOTAL1>>>5&255;\n HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;\n HEAP[offset|60] = TOTAL0>>>21&255;\n HEAP[offset|61] = TOTAL0>>>13&255;\n HEAP[offset|62] = TOTAL0>>>5&255;\n HEAP[offset|63] = TOTAL0<<3&255;\n _core_heap(offset);\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n function hmac_reset () {\n H0 = I0;\n H1 = I1;\n H2 = I2;\n H3 = I3;\n H4 = I4;\n H5 = I5;\n H6 = I6;\n H7 = I7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function _hmac_opad () {\n H0 = O0;\n H1 = O1;\n H2 = O2;\n H3 = O3;\n H4 = O4;\n H5 = O5;\n H6 = O6;\n H7 = O7;\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {\n p0 = p0|0;\n p1 = p1|0;\n p2 = p2|0;\n p3 = p3|0;\n p4 = p4|0;\n p5 = p5|0;\n p6 = p6|0;\n p7 = p7|0;\n p8 = p8|0;\n p9 = p9|0;\n p10 = p10|0;\n p11 = p11|0;\n p12 = p12|0;\n p13 = p13|0;\n p14 = p14|0;\n p15 = p15|0;\n\n // opad\n reset();\n _core(\n p0 ^ 0x5c5c5c5c,\n p1 ^ 0x5c5c5c5c,\n p2 ^ 0x5c5c5c5c,\n p3 ^ 0x5c5c5c5c,\n p4 ^ 0x5c5c5c5c,\n p5 ^ 0x5c5c5c5c,\n p6 ^ 0x5c5c5c5c,\n p7 ^ 0x5c5c5c5c,\n p8 ^ 0x5c5c5c5c,\n p9 ^ 0x5c5c5c5c,\n p10 ^ 0x5c5c5c5c,\n p11 ^ 0x5c5c5c5c,\n p12 ^ 0x5c5c5c5c,\n p13 ^ 0x5c5c5c5c,\n p14 ^ 0x5c5c5c5c,\n p15 ^ 0x5c5c5c5c\n );\n O0 = H0;\n O1 = H1;\n O2 = H2;\n O3 = H3;\n O4 = H4;\n O5 = H5;\n O6 = H6;\n O7 = H7;\n\n // ipad\n reset();\n _core(\n p0 ^ 0x36363636,\n p1 ^ 0x36363636,\n p2 ^ 0x36363636,\n p3 ^ 0x36363636,\n p4 ^ 0x36363636,\n p5 ^ 0x36363636,\n p6 ^ 0x36363636,\n p7 ^ 0x36363636,\n p8 ^ 0x36363636,\n p9 ^ 0x36363636,\n p10 ^ 0x36363636,\n p11 ^ 0x36363636,\n p12 ^ 0x36363636,\n p13 ^ 0x36363636,\n p14 ^ 0x36363636,\n p15 ^ 0x36363636\n );\n I0 = H0;\n I1 = H1;\n I2 = H2;\n I3 = H3;\n I4 = H4;\n I5 = H5;\n I6 = H6;\n I7 = H7;\n\n TOTAL0 = 64;\n TOTAL1 = 0;\n }\n\n // offset — multiple of 64\n // output — multiple of 32\n function hmac_finish ( offset, length, output ) {\n offset = offset|0;\n length = length|0;\n output = output|0;\n\n var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n hashed = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n hashed = finish( offset, length, -1 )|0;\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n\n if ( ~output )\n _state_to_heap(output);\n\n return hashed|0;\n }\n\n // salt is assumed to be already processed\n // offset — multiple of 64\n // output — multiple of 32\n function pbkdf2_generate_block ( offset, length, block, count, output ) {\n offset = offset|0;\n length = length|0;\n block = block|0;\n count = count|0;\n output = output|0;\n\n var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;\n\n if ( offset & 63 )\n return -1;\n\n if ( ~output )\n if ( output & 31 )\n return -1;\n\n // pad block number into heap\n // FIXME probable OOB write\n HEAP[(offset+length)|0] = block>>>24;\n HEAP[(offset+length+1)|0] = block>>>16&255;\n HEAP[(offset+length+2)|0] = block>>>8&255;\n HEAP[(offset+length+3)|0] = block&255;\n\n // finish first iteration\n hmac_finish( offset, (length+4)|0, -1 )|0;\n h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;\n count = (count-1)|0;\n\n // perform the rest iterations\n while ( (count|0) > 0 ) {\n hmac_reset();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n _hmac_opad();\n _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );\n t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;\n\n h0 = h0 ^ H0;\n h1 = h1 ^ H1;\n h2 = h2 ^ H2;\n h3 = h3 ^ H3;\n h4 = h4 ^ H4;\n h5 = h5 ^ H5;\n h6 = h6 ^ H6;\n h7 = h7 ^ H7;\n\n count = (count-1)|0;\n }\n\n H0 = h0;\n H1 = h1;\n H2 = h2;\n H3 = h3;\n H4 = h4;\n H5 = h5;\n H6 = h6;\n H7 = h7;\n\n if ( ~output )\n _state_to_heap(output);\n\n return 0;\n }\n\n return {\n // SHA256\n reset: reset,\n init: init,\n process: process,\n finish: finish,\n\n // HMAC-SHA256\n hmac_reset: hmac_reset,\n hmac_init: hmac_init,\n hmac_finish: hmac_finish,\n\n // PBKDF2-HMAC-SHA256\n pbkdf2_generate_block: pbkdf2_generate_block\n }\n}\n","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n * @private\n */\n\nimport { Sha1 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha1/sha1';\nimport { Sha256 } from '@openpgp/asmcrypto.js/dist_es8/hash/sha256/sha256';\nimport sha224 from 'hash.js/lib/hash/sha/224';\nimport sha384 from 'hash.js/lib/hash/sha/384';\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport { ripemd160 } from 'hash.js/lib/hash/ripemd';\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport defaultConfig from '../../config';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction hashjsHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n }\n const hashInstance = hash();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => new Uint8Array(hashInstance.digest()));\n };\n}\n\nfunction asmcryptoHash(hash, webCryptoHash) {\n return async function(data, config = defaultConfig) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hashInstance = new hash();\n return stream.transform(data, value => {\n hashInstance.process(value);\n }, () => hashInstance.finish().result);\n } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {\n return new Uint8Array(await webCrypto.digest(webCryptoHash, data));\n } else {\n return hash.bytes(data);\n }\n };\n}\n\nconst hashFunctions = {\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),\n sha224: nodeHash('sha224') || hashjsHash(sha224),\n sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),\n sha384: nodeHash('sha384') || hashjsHash(sha384, 'SHA-384'),\n sha512: nodeHash('sha512') || hashjsHash(sha512, 'SHA-512'), // asmcrypto sha512 is huge.\n ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)\n};\n\nexport default {\n\n /** @see module:md5 */\n md5: hashFunctions.md5,\n /** @see asmCrypto */\n sha1: hashFunctions.sha1,\n /** @see hash.js */\n sha224: hashFunctions.sha224,\n /** @see asmCrypto */\n sha256: hashFunctions.sha256,\n /** @see hash.js */\n sha384: hashFunctions.sha384,\n /** @see asmCrypto */\n sha512: hashFunctions.sha512,\n /** @see hash.js */\n ripemd: hashFunctions.ripemd,\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n default:\n throw new Error('Invalid hash function.');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CFB {\n static encrypt(data, key, iv) {\n return new AES_CFB(key, iv).encrypt(data);\n }\n static decrypt(data, key, iv) {\n return new AES_CFB(key, iv).decrypt(data);\n }\n constructor(key, iv, aes) {\n this.aes = aes ? aes : new AES(key, iv, true, 'CFB');\n delete this.aes.padding;\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","import * as cipher from '.';\nimport enums from '../../enums';\n\n/**\n * Get implementation of the given cipher\n * @param {enums.symmetric} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport default function getCipher(algo) {\n const algoName = enums.read(enums.symmetric, algo);\n return cipher[algoName];\n}\n","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n * @private\n */\n\nimport { AES_CFB } from '@openpgp/asmcrypto.js/dist_es8/aes/cfb';\nimport * as stream from '@openpgp/web-stream-tools';\nimport getCipher from '../cipher/getCipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const Cipher = getCipher(algo);\n const cipherfn = new Cipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nfunction aesEncrypt(algo, key, pt, iv, config) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support\n !util.isStream(pt) &&\n pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2\n ) { // Web Crypto\n return webEncrypt(algo, key, pt, iv);\n }\n // asm.js fallback\n const cfb = new AES_CFB(key, iv);\n return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());\n}\n\nfunction aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new AES_CFB(key, iv);\n return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());\n }\n return AES_CFB.decrypt(ct, key, iv);\n}\n\nfunction xorMut(a, b) {\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nasync function webEncrypt(algo, key, pt, iv) {\n const ALGO = 'AES-CBC';\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);\n const { blockSize } = getCipher(algo);\n const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);\n const ct = new Uint8Array(await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);\n xorMut(ct, pt);\n return ct;\n}\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","import { AES } from './aes';\nimport { IllegalArgumentError } from '../other/errors';\nimport { joinBytes } from '../other/utils';\nexport class AES_CTR {\n static encrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n static decrypt(data, key, nonce) {\n return new AES_CTR(key, nonce).encrypt(data);\n }\n constructor(key, nonce, aes) {\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n delete this.aes.padding;\n this.AES_CTR_set_options(nonce);\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n AES_CTR_set_options(nonce, counter, size) {\n let { asm } = this.aes.acquire_asm();\n if (size !== undefined) {\n if (size < 8 || size > 48)\n throw new IllegalArgumentError('illegal counter size');\n let mask = Math.pow(2, size) - 1;\n asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);\n }\n else {\n size = 48;\n asm.set_mask(0, 0, 0xffff, 0xffffffff);\n }\n if (nonce !== undefined) {\n let len = nonce.length;\n if (!len || len > 16)\n throw new IllegalArgumentError('illegal nonce size');\n let view = new DataView(new ArrayBuffer(16));\n new Uint8Array(view.buffer).set(nonce);\n asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));\n }\n else {\n throw new Error('nonce is required');\n }\n if (counter !== undefined) {\n if (counter < 0 || counter >= Math.pow(2, size))\n throw new IllegalArgumentError('illegal counter value');\n asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);\n }\n }\n}\n","import { AES } from './aes';\nimport { joinBytes } from '../other/utils';\nexport class AES_CBC {\n static encrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).encrypt(data);\n }\n static decrypt(data, key, padding = true, iv) {\n return new AES_CBC(key, iv, padding).decrypt(data);\n }\n constructor(key, iv, padding = true, aes) {\n this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');\n }\n encrypt(data) {\n const r1 = this.aes.AES_Encrypt_process(data);\n const r2 = this.aes.AES_Encrypt_finish();\n return joinBytes(r1, r2);\n }\n decrypt(data) {\n const r1 = this.aes.AES_Decrypt_process(data);\n const r2 = this.aes.AES_Decrypt_finish();\n return joinBytes(r1, r2);\n }\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n * @private\n */\n\nimport { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt) {\n return AES_CBC.encrypt(pt, key, false, zeroBlock);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n * @private\n */\n\nimport { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (\n util.getWebCrypto() &&\n key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n ) {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct);\n };\n }\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n // asm.js fallback\n return async function(pt, iv) {\n return AES_CTR.encrypt(pt, key, iv);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n * @private\n */\n\nimport * as ciphers from '../cipher';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n\n let maxNtz = 0;\n let encipher;\n let decipher;\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables(cipher, key) {\n const cipherName = enums.read(enums.symmetric, cipher);\n const aes = new ciphers[cipherName](key);\n encipher = aes.encrypt.bind(aes);\n decipher = aes.decrypt.bind(aes);\n\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors';\nimport { _heap_write } from '../other/utils';\nimport { AES } from './aes';\nimport { AES_asm } from './aes.asm';\nconst _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5\nexport class AES_GCM {\n constructor(key, nonce, adata, tagSize = 16, aes) {\n this.tagSize = tagSize;\n this.gamma0 = 0;\n this.counter = 1;\n this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');\n let { asm, heap } = this.aes.acquire_asm();\n // Init GCM\n asm.gcm_init();\n // Tag size\n if (this.tagSize < 4 || this.tagSize > 16)\n throw new IllegalArgumentError('illegal tagSize value');\n // Nonce\n const noncelen = nonce.length || 0;\n const noncebuf = new Uint8Array(16);\n if (noncelen !== 12) {\n this._gcm_mac_process(nonce);\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = 0;\n heap[4] = 0;\n heap[5] = 0;\n heap[6] = 0;\n heap[7] = 0;\n heap[8] = 0;\n heap[9] = 0;\n heap[10] = 0;\n heap[11] = noncelen >>> 29;\n heap[12] = (noncelen >>> 21) & 255;\n heap[13] = (noncelen >>> 13) & 255;\n heap[14] = (noncelen >>> 5) & 255;\n heap[15] = (noncelen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_iv(0, 0, 0, 0);\n noncebuf.set(heap.subarray(0, 16));\n }\n else {\n noncebuf.set(nonce);\n noncebuf[15] = 1;\n }\n const nonceview = new DataView(noncebuf.buffer);\n this.gamma0 = nonceview.getUint32(12);\n asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);\n asm.set_mask(0, 0, 0, 0xffffffff);\n // Associated data\n if (adata !== undefined) {\n if (adata.length > _AES_GCM_data_maxLength)\n throw new IllegalArgumentError('illegal adata length');\n if (adata.length) {\n this.adata = adata;\n this._gcm_mac_process(adata);\n }\n else {\n this.adata = undefined;\n }\n }\n else {\n this.adata = undefined;\n }\n // Counter\n if (this.counter < 1 || this.counter > 0xffffffff)\n throw new RangeError('counter must be a positive 32-bit integer');\n asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);\n }\n static encrypt(cleartext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);\n }\n static decrypt(ciphertext, key, nonce, adata, tagsize) {\n return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);\n }\n encrypt(data) {\n return this.AES_GCM_encrypt(data);\n }\n decrypt(data) {\n return this.AES_GCM_decrypt(data);\n }\n AES_GCM_Encrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = (len + dlen) & -16;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > 0) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n if (wlen < len) {\n pos += wlen;\n len -= wlen;\n }\n else {\n pos = 0;\n len = 0;\n }\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Encrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let adata = this.adata;\n let pos = this.aes.pos;\n let len = this.aes.len;\n const result = new Uint8Array(len + tagSize);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);\n if (len)\n result.set(heap.subarray(pos, pos + len));\n let i = len;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n result.set(heap.subarray(0, tagSize), len);\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_Decrypt_process(data) {\n let dpos = 0;\n let dlen = data.length || 0;\n let { asm, heap } = this.aes.acquire_asm();\n let counter = this.counter;\n let tagSize = this.tagSize;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rpos = 0;\n let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;\n let tlen = len + dlen - rlen;\n let wlen = 0;\n if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)\n throw new RangeError('counter overflow');\n const result = new Uint8Array(rlen);\n while (dlen > tlen) {\n wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);\n len += wlen;\n dpos += wlen;\n dlen -= wlen;\n wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);\n wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);\n if (wlen)\n result.set(heap.subarray(pos, pos + wlen), rpos);\n counter += wlen >>> 4;\n rpos += wlen;\n pos = 0;\n len = 0;\n }\n if (dlen > 0) {\n len += _heap_write(heap, 0, data, dpos, dlen);\n }\n this.counter = counter;\n this.aes.pos = pos;\n this.aes.len = len;\n return result;\n }\n AES_GCM_Decrypt_finish() {\n let { asm, heap } = this.aes.acquire_asm();\n let tagSize = this.tagSize;\n let adata = this.adata;\n let counter = this.counter;\n let pos = this.aes.pos;\n let len = this.aes.len;\n let rlen = len - tagSize;\n if (len < tagSize)\n throw new IllegalStateError('authentication tag not found');\n const result = new Uint8Array(rlen);\n const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));\n let i = rlen;\n for (; i & 15; i++)\n heap[pos + i] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);\n asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);\n if (rlen)\n result.set(heap.subarray(pos, pos + rlen));\n const alen = adata !== undefined ? adata.length : 0;\n const clen = ((counter - 1) << 4) + len - tagSize;\n heap[0] = 0;\n heap[1] = 0;\n heap[2] = 0;\n heap[3] = alen >>> 29;\n heap[4] = alen >>> 21;\n heap[5] = (alen >>> 13) & 255;\n heap[6] = (alen >>> 5) & 255;\n heap[7] = (alen << 3) & 255;\n heap[8] = heap[9] = heap[10] = 0;\n heap[11] = clen >>> 29;\n heap[12] = (clen >>> 21) & 255;\n heap[13] = (clen >>> 13) & 255;\n heap[14] = (clen >>> 5) & 255;\n heap[15] = (clen << 3) & 255;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);\n asm.get_iv(AES_asm.HEAP_DATA);\n asm.set_counter(0, 0, 0, this.gamma0);\n asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);\n let acheck = 0;\n for (let i = 0; i < tagSize; ++i)\n acheck |= atag[i] ^ heap[i];\n if (acheck)\n throw new SecurityError('data integrity check failed');\n this.counter = 1;\n this.aes.pos = 0;\n this.aes.len = 0;\n return result;\n }\n AES_GCM_decrypt(data) {\n const result1 = this.AES_GCM_Decrypt_process(data);\n const result2 = this.AES_GCM_Decrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n AES_GCM_encrypt(data) {\n const result1 = this.AES_GCM_Encrypt_process(data);\n const result2 = this.AES_GCM_Encrypt_finish();\n const result = new Uint8Array(result1.length + result2.length);\n if (result1.length)\n result.set(result1);\n if (result2.length)\n result.set(result2, result1.length);\n return result;\n }\n _gcm_mac_process(data) {\n let { asm, heap } = this.aes.acquire_asm();\n let dpos = 0;\n let dlen = data.length || 0;\n let wlen = 0;\n while (dlen > 0) {\n wlen = _heap_write(heap, 0, data, dpos, dlen);\n dpos += wlen;\n dlen -= wlen;\n while (wlen & 15)\n heap[wlen++] = 0;\n asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);\n }\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n * @private\n */\n\nimport { AES_GCM } from '@openpgp/asmcrypto.js/dist_es8/aes/gcm';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.encrypt(pt, key, iv, adata);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (ct.length === tagLength) { // iOS does not support GCM-en/decrypting empty messages\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n }\n };\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return AES_GCM.encrypt(pt, key, iv, adata);\n },\n\n decrypt: async function(ct, iv, adata) {\n return AES_GCM.decrypt(ct, key, iv, adata);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n * @private\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","/*jshint bitwise: false*/\n\n(function(nacl) {\n'use strict';\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d;\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d, h, r;\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n d = nacl.hash(sk.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n r = nacl.hash(sm.subarray(32, smlen));\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n h = nacl.hash(sm.subarray(0, smlen));\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h;\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n h = nacl.hash(m.subarray(0, n));\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;\n if (crypto && crypto.getRandomValues) {\n // Browsers.\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n } else if (typeof require !== 'undefined') {\n // Node.js.\n crypto = require('crypto');\n if (crypto && crypto.randomBytes) {\n nacl.setPRNG(function(x, n) {\n var i, v = crypto.randomBytes(n);\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n }\n})();\n\n})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n * @private\n */\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const buf = new Uint8Array(length);\n if (nodeCrypto) {\n const bytes = nodeCrypto.randomBytes(buf.length);\n buf.set(bytes);\n } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n return buf;\n}\n\n/**\n * Create a secure random BigInteger that is greater than or equal to min and less than max.\n * @param {module:BigInteger} min - Lower bound, included\n * @param {module:BigInteger} max - Upper bound, excluded\n * @returns {Promise} Random BigInteger.\n * @async\n */\nexport async function getRandomBigInteger(min, max) {\n const BigInteger = await util.getBigInteger();\n\n if (max.lt(min)) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max.sub(min);\n const bytes = modulus.byteLength();\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = new BigInteger(await getRandomBytes(bytes + 8));\n return r.mod(modulus).add(min);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\n\n/**\n * Generate a probably prime random number\n * @param {Integer} bits - Bit length of the prime\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns BigInteger\n * @async\n */\nexport async function randomProbablePrime(bits, e, k) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n const min = one.leftShift(new BigInteger(bits - 1));\n const thirty = new BigInteger(30);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n const n = await getRandomBigInteger(min, min.leftShift(one));\n let i = n.mod(thirty).toNumber();\n\n do {\n n.iadd(new BigInteger(adds[i]));\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (n.bitLength() > bits) {\n n.imod(min.leftShift(one)).iadd(min);\n i = n.mod(thirty).toNumber();\n }\n } while (!await isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} e - Optional RSA exponent to check against the prime\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @returns {boolean}\n * @async\n */\nexport async function isProbablePrime(n, e, k) {\n if (e && !n.dec().gcd(e).isOne()) {\n return false;\n }\n if (!await divisionTest(n)) {\n return false;\n }\n if (!await fermat(n)) {\n return false;\n }\n if (!await millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param {BigInteger} n - Number to test\n * @param {BigInteger} b - Optional Fermat test base\n * @returns {boolean}\n */\nexport async function fermat(n, b) {\n const BigInteger = await util.getBigInteger();\n b = b || new BigInteger(2);\n return b.modExp(n.dec(), n).isOne();\n}\n\nexport async function divisionTest(n) {\n const BigInteger = await util.getBigInteger();\n return smallPrimes.every(m => {\n return n.mod(new BigInteger(m)) !== 0;\n });\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n];\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param {BigInteger} n - Number to test\n * @param {Integer} k - Optional number of iterations of Miller-Rabin test\n * @param {Function} rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport async function millerRabin(n, k, rand) {\n const BigInteger = await util.getBigInteger();\n const len = n.bitLength();\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n.dec(); // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!n1.getBit(s)) { s++; }\n const d = n.rightShift(new BigInteger(s));\n\n for (; k > 0; k--) {\n const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);\n\n let x = a.modExp(d, n);\n if (x.isOne() || x.equal(n1)) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = x.mul(x).mod(n);\n\n if (x.isOne()) {\n return false;\n }\n if (x.equal(n1)) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n * @private\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport async function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n * @private\n */\n\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\n/* eslint-disable no-invalid-this */\nconst RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('version').int(), // 0\n this.key('modulus').int(), // n\n this.key('publicExponent').int(), // e\n this.key('privateExponent').int(), // d\n this.key('prime1').int(), // p\n this.key('prime2').int(), // q\n this.key('exponent1').int(), // dp\n this.key('exponent2').int(), // dq\n this.key('coefficient').int() // u\n );\n}) : undefined;\n\nconst RSAPublicKey = nodeCrypto ? asn1.define('RSAPubliceKey', function () {\n this.seq().obj( // used for native NodeJS crypto\n this.key('modulus').int(), // n\n this.key('publicExponent').int() // e\n );\n}) : undefined;\n/* eslint-enable no-invalid-this */\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n const BigInteger = await util.getBigInteger();\n\n e = new BigInteger(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return {\n n: b64ToUint8Array(jwk.n),\n e: e.toUint8Array(),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n } else if (util.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {\n const opts = {\n modulusLength: bits,\n publicExponent: e.toNumber(),\n publicKeyEncoding: { type: 'pkcs1', format: 'der' },\n privateKeyEncoding: { type: 'pkcs1', format: 'der' }\n };\n const prv = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {\n if (err) {\n reject(err);\n } else {\n resolve(RSAPrivateKey.decode(der, 'der'));\n }\n });\n });\n /**\n * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.\n * @link https://tools.ietf.org/html/rfc3447#section-3.2\n * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1\n */\n return {\n n: prv.modulus.toArrayLike(Uint8Array),\n e: prv.publicExponent.toArrayLike(Uint8Array),\n d: prv.privateExponent.toArrayLike(Uint8Array),\n // switch p and q\n p: prv.prime2.toArrayLike(Uint8Array),\n q: prv.prime1.toArrayLike(Uint8Array),\n // Since p and q are switched in places, we can keep u as defined by DER\n u: prv.coefficient.toArrayLike(Uint8Array)\n };\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = await randomProbablePrime(bits - (bits >> 1), e, 40);\n p = await randomProbablePrime(bits >> 1, e, 40);\n n = p.mul(q);\n } while (n.bitLength() !== bits);\n\n const phi = p.dec().imul(q.dec());\n\n if (q.lt(p)) {\n [p, q] = [q, p];\n }\n\n return {\n n: n.toUint8Array(),\n e: e.toUint8Array(),\n d: e.modInv(phi).toUint8Array(),\n p: p.toUint8Array(),\n q: q.toUint8Array(),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: p.modInv(q).toUint8Array()\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n p = new BigInteger(p);\n q = new BigInteger(q);\n\n // expect pq = n\n if (!p.mul(q).equal(n)) {\n return false;\n }\n\n const two = new BigInteger(2);\n // expect p*u = 1 mod q\n u = new BigInteger(u);\n if (!p.mul(u).mod(q).isOne()) {\n return false;\n }\n\n e = new BigInteger(e);\n d = new BigInteger(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));\n const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r.mul(d).mul(e);\n\n const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));\n d = new BigInteger(d);\n if (m.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return m.modExp(d, n).toUint8Array('be', n.byteLength());\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPrivateKey.encode(keyObject, 'der');\n return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));\n }\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n return new Uint8Array(sign.sign(pem));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n s = new BigInteger(s);\n e = new BigInteger(e);\n if (s.gte(n)) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());\n const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1' };\n } else {\n key = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n }\n try {\n return await verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const { default: BN } = await import('bn.js');\n\n const keyObject = {\n modulus: new BN(n),\n publicExponent: new BN(e)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPublicKey.encode(keyObject, 'der');\n key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPublicKey.encode(keyObject, 'pem', {\n label: 'RSA PUBLIC KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n const BigInteger = await util.getBigInteger();\n n = new BigInteger(n);\n data = new BigInteger(emeEncode(data, n.byteLength()));\n e = new BigInteger(e);\n if (data.gte(n)) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return data.modExp(e, n).toUint8Array('be', n.byteLength());\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const { default: BN } = await import('bn.js');\n\n const pBNum = new BN(p);\n const qBNum = new BN(q);\n const dBNum = new BN(d);\n const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)\n const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)\n const keyObject = {\n version: 0,\n modulus: new BN(n),\n publicExponent: new BN(e),\n privateExponent: new BN(d),\n // switch p and q\n prime1: new BN(q),\n prime2: new BN(p),\n // switch dp and dq\n exponent1: dq,\n exponent2: dp,\n coefficient: new BN(u)\n };\n let key;\n if (typeof nodeCrypto.createPrivateKey !== 'undefined') {\n const der = RSAPrivateKey.encode(keyObject, 'der');\n key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n } else {\n const pem = RSAPrivateKey.encode(keyObject, 'pem', {\n label: 'RSA PRIVATE KEY'\n });\n key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n }\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n const BigInteger = await util.getBigInteger();\n data = new BigInteger(data);\n n = new BigInteger(n);\n e = new BigInteger(e);\n d = new BigInteger(d);\n p = new BigInteger(p);\n q = new BigInteger(q);\n u = new BigInteger(u);\n if (data.gte(n)) {\n throw new Error('Data too large.');\n }\n const dq = d.mod(q.dec()); // d mod (q-1)\n const dp = d.mod(p.dec()); // d mod (p-1)\n\n const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);\n const blinder = unblinder.modInv(n).modExp(e, n);\n data = data.mul(blinder).mod(n);\n\n\n const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p\n const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q\n const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h.mul(p).add(mp); // result < n due to relations above\n\n result = result.mul(unblinder).mod(n);\n\n\n return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const BigInteger = await util.getBigInteger();\n const pNum = new BigInteger(p);\n const qNum = new BigInteger(q);\n const dNum = new BigInteger(d);\n\n let dq = dNum.mod(qNum.dec()); // d mod (q-1)\n let dp = dNum.mod(pNum.dec()); // d mod (p-1)\n dp = dp.toUint8Array();\n dq = dq.toUint8Array();\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n * @private\n */\n\nimport util from '../../util';\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const padded = emeEncode(data, p.byteLength());\n const m = new BigInteger(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = await getRandomBigInteger(new BigInteger(1), p.dec());\n return {\n c1: g.modExp(k, p).toUint8Array(),\n c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n const BigInteger = await util.getBigInteger();\n c1 = new BigInteger(c1);\n c2 = new BigInteger(c2);\n p = new BigInteger(p);\n x = new BigInteger(x);\n\n const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);\n return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = new BigInteger(p.bitLength());\n const n1023 = new BigInteger(1023);\n if (pSize.lt(n1023)) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (!g.modExp(p.dec(), p).isOne()) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n const i = new BigInteger(1);\n const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold\n while (i.lt(threshold)) {\n res = res.mul(g).imod(p);\n if (res.isOne()) {\n return false;\n }\n i.iinc();\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1\n const rqx = p.dec().imul(r).iadd(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n * @private\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {string} String with the canonical name of the curve.\n */\n getName() {\n const hex = this.toHex();\n if (enums.curve[hex]) {\n return enums.write(enums.curve, hex);\n } else {\n throw new Error('Unknown curve object identifier.');\n }\n }\n}\n\nexport default OID;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library\n * @module crypto/public_key/elliptic/indutnyKey\n * @private\n */\n\nimport config from '../../../config';\n\nexport function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}\n\nexport function keyFromPublic(indutnyCurve, pub) {\n const keyPair = indutnyCurve.keyPair({ pub: pub });\n if (keyPair.validate().result !== true) {\n throw new Error('Invalid elliptic public key');\n }\n return keyPair;\n}\n\nexport async function getIndutnyCurve(name) {\n if (!config.useIndutnyElliptic) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n const { default: elliptic } = await import('@openpgp/elliptic');\n return new elliptic.ec(name);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n * @private\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new stream.TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { getRandomBytes } from '../../random';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport { UnsupportedError } from '../../../packet/packet';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n 'p256': 'P-256',\n 'p384': 'P-384',\n 'p521': 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,\n brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n p256: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.p256,\n web: webCurves.p256,\n payloadSize: 32,\n sharedSize: 256\n },\n p384: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.p384,\n web: webCurves.p384,\n payloadSize: 48,\n sharedSize: 384\n },\n p521: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.p521,\n web: webCurves.p521,\n payloadSize: 66,\n sharedSize: 528\n },\n secp256k1: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.secp256k1,\n payloadSize: 32\n },\n ed25519: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32\n },\n curve25519: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32\n },\n brainpoolP256r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves.brainpoolP256r1,\n payloadSize: 32\n },\n brainpoolP384r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves.brainpoolP384r1,\n payloadSize: 48\n },\n brainpoolP512r1: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves.brainpoolP512r1,\n payloadSize: 64\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName, params) {\n try {\n if (util.isArray(oidOrName) ||\n util.isUint8Array(oidOrName)) {\n // by oid byte array\n oidOrName = new OID(oidOrName);\n }\n if (oidOrName instanceof OID) {\n // by curve OID\n oidOrName = oidOrName.getName();\n }\n // by curve name or oid string\n this.name = enums.write(enums.curve, oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n params = params || curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node && curves[this.name];\n this.web = params.web && curves[this.name];\n this.payloadSize = params.payloadSize;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === 'curve25519') {\n this.type = 'curve25519';\n } else if (this.name === 'ed25519') {\n this.type = 'ed25519';\n }\n }\n\n async genKeyPair() {\n let keyPair;\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n break;\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519': {\n const privateKey = getRandomBytes(32);\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const secretKey = privateKey.slice().reverse();\n keyPair = nacl.box.keyPair.fromSecretKey(secretKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n case 'ed25519': {\n const privateKey = getRandomBytes(32);\n const keyPair = nacl.sign.keyPair.fromSeed(privateKey);\n const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);\n return { publicKey, privateKey };\n }\n }\n const indutnyCurve = await getIndutnyCurve(this.name);\n keyPair = await indutnyCurve.genKeyPair({\n entropy: util.uint8ArrayToString(getRandomBytes(32))\n });\n return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };\n }\n}\n\nasync function generate(curve) {\n const BigInteger = await util.getBigInteger();\n\n curve = new CurveWithOID(curve);\n const keyPair = await curve.genKeyPair();\n const Q = new BigInteger(keyPair.publicKey).toUint8Array();\n const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);\n return {\n oid: curve.oid,\n Q,\n secret,\n hash: curve.hash,\n cipher: curve.cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[enums.write(enums.curve, oid.toHex())].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n p256: true,\n p384: true,\n p521: true,\n secp256k1: true,\n curve25519: algo === enums.publicKey.ecdh,\n brainpoolP256r1: true,\n brainpoolP384r1: true,\n brainpoolP512r1: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === 'curve25519') {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const curve = await getIndutnyCurve(curveName);\n try {\n // Parse Q and check that it is on the curve but not at infinity\n Q = keyFromPublic(curve, Q).getPublic();\n } catch (validationErrors) {\n return false;\n }\n\n /**\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = keyFromPrivate(curve, d).getPublic();\n if (!dG.eq(Q)) {\n return false;\n }\n\n return true;\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nasync function webGenKeyPair(name) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = 0x04;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n * @private\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams } from './oid_curves';\nimport { getIndutnyCurve, keyFromPrivate, keyFromPublic } from './indutnyKey';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web': {\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n }\n case 'node': {\n const signature = await nodeSign(curve, hashAlgo, message, keyPair);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n }\n }\n }\n return ellipticSign(curve, hashed, privateKey);\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n return await webVerify(curve, hashAlgo, signature, message, publicKey);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support p521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node':\n return nodeVerify(curve, hashAlgo, signature, message, publicKey);\n }\n }\n const digest = (typeof hashAlgo === 'undefined') ? message : hashed;\n return ellipticVerify(curve, signature, digest, publicKey);\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\nasync function ellipticSign(curve, hashed, privateKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPrivate(indutnyCurve, privateKey);\n const signature = key.sign(hashed);\n return {\n r: signature.r.toArrayLike(Uint8Array),\n s: signature.s.toArrayLike(Uint8Array)\n };\n}\n\nasync function ellipticVerify(curve, signature, digest, publicKey) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const key = keyFromPublic(indutnyCurve, publicKey);\n return key.verify(digest, signature);\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, keyPair) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n const key = ECPrivateKey.encode({\n version: 1,\n parameters: curve.oid,\n privateKey: Array.from(keyPair.privateKey),\n publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }\n }, 'pem', {\n label: 'EC PRIVATE KEY'\n });\n\n return ECDSASignature.decode(sign.sign(key), 'der');\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const { default: BN } = await import('bn.js');\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n const key = SubjectPublicKeyInfo.encode({\n algorithm: {\n algorithm: [1, 2, 840, 10045, 2, 1],\n parameters: curve.oid\n },\n subjectPublicKey: { unused: 0, data: Array.from(publicKey) }\n }, 'pem', {\n label: 'PUBLIC KEY'\n });\n const signature = ECDSASignature.encode({\n r: new BN(r), s: new BN(s)\n }, 'der');\n\n try {\n return verify.verify(key, signature);\n } catch (err) {\n return false;\n }\n}\n\n// Originally written by Owen Smith https://github.com/omsmith\n// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/\n\n/* eslint-disable no-invalid-this */\n\nconst asn1 = nodeCrypto ? require('asn1.js') : undefined;\n\nconst ECDSASignature = nodeCrypto ?\n asn1.define('ECDSASignature', function() {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n );\n }) : undefined;\n\nconst ECPrivateKey = nodeCrypto ?\n asn1.define('ECPrivateKey', function() {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').explicit(0).optional().any(),\n this.key('publicKey').explicit(1).optional().bitstr()\n );\n }) : undefined;\n\nconst AlgorithmIdentifier = nodeCrypto ?\n asn1.define('AlgorithmIdentifier', function() {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional().any()\n );\n }) : undefined;\n\nconst SubjectPublicKeyInfo = nodeCrypto ?\n asn1.define('SubjectPublicKeyInfo', function() {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n );\n }) : undefined;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);\n const signature = nacl.sign.detached(hashed, secretKey);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const signature = util.concatUint8Array([r, s]);\n return nacl.sign.detached.verify(hashed, signature, publicKey.subarray(1));\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== 'ed25519') {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n * @private\n */\n\nimport sha512 from 'hash.js/lib/hash/sha/512';\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\n\nnacl.hash = bytes => new Uint8Array(sha512().update(bytes).digest());\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const seed = getRandomBytes(32);\n const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = nacl.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519: {\n return nacl.sign.detached.verify(hashed, RS, publicKey);\n }\n case enums.publicKey.ed448:\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: // unsupported\n default:\n return false;\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n * @private\n */\n\nimport * as cipher from './cipher';\nimport util from '../util';\n\n/**\n * AES key wrap\n * @function\n * @param {Uint8Array} key\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nexport function wrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const P = unpack(data);\n let A = IV;\n const R = P;\n const n = P.length / 2;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 0; j <= 5; ++j) {\n for (let i = 0; i < n; ++i) {\n t[1] = n * j + (1 + i);\n // B = A\n B[0] = A[0];\n B[1] = A[1];\n // B = A || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES(K, B)\n B = unpack(aes.encrypt(pack(B)));\n // A = MSB(64, B) ^ t\n A = B.subarray(0, 2);\n A[0] ^= t[0];\n A[1] ^= t[1];\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n return pack(A, R);\n}\n\n/**\n * AES key unwrap\n * @function\n * @param {String} key\n * @param {String} data\n * @returns {Uint8Array}\n * @throws {Error}\n */\nexport function unwrap(key, data) {\n const aes = new cipher['aes' + (key.length * 8)](key);\n const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);\n const C = unpack(data);\n let A = C.subarray(0, 2);\n const R = C.subarray(2);\n const n = C.length / 2 - 1;\n const t = new Uint32Array([0, 0]);\n let B = new Uint32Array(4);\n for (let j = 5; j >= 0; --j) {\n for (let i = n - 1; i >= 0; --i) {\n t[1] = n * j + (i + 1);\n // B = A ^ t\n B[0] = A[0] ^ t[0];\n B[1] = A[1] ^ t[1];\n // B = (A ^ t) || R[i]\n B[2] = R[2 * i];\n B[3] = R[2 * i + 1];\n // B = AES-1(B)\n B = unpack(aes.decrypt(pack(B)));\n // A = MSB(64, B)\n A = B.subarray(0, 2);\n // R[i] = LSB(64, B)\n R[2 * i] = B[2];\n R[2 * i + 1] = B[3];\n }\n }\n if (A[0] === IV[0] && A[1] === IV[1]) {\n return pack(R);\n }\n throw new Error('Key Data Integrity failed');\n}\n\nfunction createArrayBuffer(data) {\n if (util.isString(data)) {\n const { length } = data;\n const buffer = new ArrayBuffer(length);\n const view = new Uint8Array(buffer);\n for (let j = 0; j < length; ++j) {\n view[j] = data.charCodeAt(j);\n }\n return buffer;\n }\n return new Uint8Array(data).buffer;\n}\n\nfunction unpack(data) {\n const { length } = data;\n const buffer = createArrayBuffer(data);\n const view = new DataView(buffer);\n const arr = new Uint32Array(length / 4);\n for (let i = 0; i < length / 4; ++i) {\n arr[i] = view.getUint32(4 * i);\n }\n return arr;\n}\n\nfunction pack() {\n let length = 0;\n for (let k = 0; k < arguments.length; ++k) {\n length += 4 * arguments[k].length;\n }\n const buffer = new ArrayBuffer(length);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < arguments.length; ++i) {\n for (let j = 0; j < arguments[i].length; ++j) {\n view.setUint32(offset + 4 * j, arguments[i][j]);\n }\n offset += 4 * arguments[i].length;\n }\n return new Uint8Array(buffer);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { keyFromPublic, keyFromPrivate, getIndutnyCurve } from './indutnyKey';\nimport getCipher from '../../cipher/getCipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint.subarray(0, 20)\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519': {\n const d = getRandomBytes(32);\n const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);\n let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);\n publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n }\n return ellipticPublicEphemeralKey(curve, Q);\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = aesKW.wrap(Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519': {\n const secretKey = d.slice().reverse();\n const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n }\n return ellipticPrivateEphemeralKey(curve, V, d);\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipher(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(aesKW.unwrap(Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: sender\n },\n privateKey,\n curve.web.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.web.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPrivateEphemeralKey(curve, V, d) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n V = keyFromPublic(indutnyCurve, V);\n d = keyFromPrivate(indutnyCurve, d);\n const secretKey = new Uint8Array(d.getPrivate());\n const S = d.derive(V.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function ellipticPublicEphemeralKey(curve, Q) {\n const indutnyCurve = await getIndutnyCurve(curve.name);\n const v = await curve.genKeyPair();\n Q = keyFromPublic(indutnyCurve, Q);\n const V = keyFromPrivate(indutnyCurve, v.privateKey);\n const publicKey = v.publicKey;\n const S = V.derive(Q.getPublic());\n const len = indutnyCurve.curve.p.byteLength();\n const sharedKey = S.toArrayLike(Uint8Array, 'be', len);\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeSubtleCrypto = nodeCrypto && nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle;\n\nexport default async function HKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n if (webCrypto || nodeSubtleCrypto) {\n const crypto = webCrypto || nodeSubtleCrypto;\n const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n }\n\n if (nodeCrypto) {\n const hashAlgoName = enums.read(enums.hash, hashAlgo);\n // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869\n\n const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();\n // Step 1: Extract\n // PRK = HMAC-Hash(salt, IKM)\n const pseudoRandomKey = computeHMAC(salt, inputKey);\n\n const hashLen = pseudoRandomKey.length;\n\n // Step 2: Expand\n // HKDF-Expand(PRK, info, L) -> OKM\n const n = Math.ceil(outLen / hashLen);\n const outputKeyingMaterial = new Uint8Array(n * hashLen);\n\n // HMAC input buffer updated at each iteration\n const roundInput = new Uint8Array(hashLen + info.length + 1);\n // T_i and last byte are updated at each iteration, but `info` remains constant\n roundInput.set(info, hashLen);\n\n for (let i = 0; i < n; i++) {\n // T(0) = empty string (zero length)\n // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)\n roundInput[roundInput.length - 1] = i + 1;\n // t = T(i+1)\n const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));\n roundInput.set(t, 0);\n\n outputKeyingMaterial.set(t, i * hashLen);\n }\n\n return outputKeyingMaterial.subarray(0, outLen);\n }\n\n throw new Error('No HKDF implementation available');\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport getCipher from '../../cipher/getCipher';\nimport computeHKDF from '../../hkdf';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = nacl.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(32);\n const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA);\n const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = aesKW.wrap(encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n const { keySize } = getCipher(enums.symmetric.aes128);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n * @private\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const BigInteger = await util.getBigInteger();\n const one = new BigInteger(1);\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n x = new BigInteger(x);\n\n let k;\n let r;\n let s;\n let t;\n g = g.mod(p);\n x = x.mod(q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = await getRandomBigInteger(one, q); // returns in [1, q-1]\n r = g.modExp(k, p).imod(q); // (g**k mod p) mod q\n if (r.isZero()) {\n continue;\n }\n const xr = x.mul(r).imod(q);\n t = h.add(xr).imod(q); // H(m) + x*r mod q\n s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q\n if (s.isZero()) {\n continue;\n }\n break;\n }\n return {\n r: r.toUint8Array('be', q.byteLength()),\n s: s.toUint8Array('be', q.byteLength())\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n const BigInteger = await util.getBigInteger();\n const zero = new BigInteger(0);\n r = new BigInteger(r);\n s = new BigInteger(s);\n\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n\n if (r.lte(zero) || r.gte(q) ||\n s.lte(zero) || s.gte(q)) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);\n const w = s.modInv(q); // s**-1 mod q\n if (w.isZero()) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = g.mod(p);\n y = y.mod(p);\n const u1 = h.mul(w).imod(q); // H(m) * w mod q\n const u2 = r.mul(w).imod(q); // r * w mod q\n const t1 = g.modExp(u1, p); // g**u1 mod p\n const t2 = y.modExp(u2, p); // y**u2 mod p\n const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q\n return v.equal(r);\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n const BigInteger = await util.getBigInteger();\n p = new BigInteger(p);\n q = new BigInteger(q);\n g = new BigInteger(g);\n y = new BigInteger(y);\n const one = new BigInteger(1);\n // Check that 1 < g < p\n if (g.lte(one) || g.gte(p)) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (!p.dec().mod(q).isZero()) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (!g.modExp(q, p).isOne()) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = new BigInteger(q.bitLength());\n const n150 = new BigInteger(150);\n if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = new BigInteger(x);\n const two = new BigInteger(2);\n const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q\n const rqx = q.mul(r).add(x);\n if (!y.equal(g.modExp(rqx, p))) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n * @private\n */\n\nimport nacl from '@openpgp/tweetnacl/nacl-fast-light';\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa,\n /** @see tweetnacl */\n nacl: nacl\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n * @private\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read));\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { s };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read));\n return { r, s };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n let r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n r = util.leftPad(r, 32);\n let s = util.readMPI(signature.subarray(read));\n s = util.leftPad(s, 32);\n return { r, s };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n case enums.publicKey.ed25519: {\n const RS = signature.subarray(read, read + 64); read += RS.length;\n return { RS };\n }\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n // signature already padded on parsing\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal: {\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n * @private\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n * @private\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport getCipher from './cipher/getCipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { CurveWithOID } from './public_key/elliptic/oid_curves';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519: {\n if (!util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (!util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.x25519: {\n const A = bytes.subarray(read, read + 32); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const curve = new CurveWithOID(publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, curve.payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const curve = new CurveWithOID(publicParams.oid);\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, curve.payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519: {\n const seed = bytes.subarray(read, read + 32); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519: {\n const k = bytes.subarray(read, read + 32); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key.\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519: {\n const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n }\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipher(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipher(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\nexport { getCipher };\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get preferred hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n * @private\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","\n\n\nvar TYPED_OK = typeof Uint8Array !== \"undefined\" &&\n typeof Uint16Array !== \"undefined\" &&\n typeof Int32Array !== \"undefined\";\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function assign(obj /*...args obj, from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) {\n continue; \n }\n\n if (typeof source !== \"object\") {\n throw new TypeError(source + \"must be non-object\");\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n //return Object.assign(...args);\n}\n\n\n// reduce buffer size, avoiding mem copy\nexport function shrinkBuf(buf, size) {\n if (buf.length === size) {\n return buf; \n }\n if (buf.subarray) {\n return buf.subarray(0, size); \n }\n buf.length = size;\n return buf;\n}\n\n\nconst fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n let i, l, len, pos, chunk;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nconst fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (let i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\n\nexport let Buf8 = TYPED_OK ? Uint8Array : Array;\nexport let Buf16 = TYPED_OK ? Uint16Array : Array;\nexport let Buf32 = TYPED_OK ? Int32Array : Array;\nexport let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;\nexport let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;\nexport function setTyped(on) {\n if (on) {\n Buf8 = Uint8Array;\n Buf16 = Uint16Array;\n Buf32 = Int32Array;\n ({ flattenChunks, arraySet } = fnTyped);\n } else {\n Buf8 = Array;\n Buf16 = Array;\n Buf32 = Array;\n ({ flattenChunks, arraySet } = fnUntyped);\n }\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nexport const Z_NO_FLUSH = 0;\nexport const Z_PARTIAL_FLUSH = 1;\nexport const Z_SYNC_FLUSH = 2;\nexport const Z_FULL_FLUSH = 3;\nexport const Z_FINISH = 4;\nexport const Z_BLOCK = 5;\nexport const Z_TREES = 6;\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nexport const Z_OK = 0;\nexport const Z_STREAM_END = 1;\nexport const Z_NEED_DICT = 2;\nexport const Z_ERRNO = -1;\nexport const Z_STREAM_ERROR = -2;\nexport const Z_DATA_ERROR = -3;\n//export const Z_MEM_ERROR = -4;\nexport const Z_BUF_ERROR = -5;\n//export const Z_VERSION_ERROR = -6;\n\n /* compression levels */\nexport const Z_NO_COMPRESSION = 0;\nexport const Z_BEST_SPEED = 1;\nexport const Z_BEST_COMPRESSION = 9;\nexport const Z_DEFAULT_COMPRESSION = -1;\n\n\nexport const Z_FILTERED = 1;\nexport const Z_HUFFMAN_ONLY = 2;\nexport const Z_RLE = 3;\nexport const Z_FIXED = 4;\nexport const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nexport const Z_BINARY = 0;\nexport const Z_TEXT = 1;\n//export const Z_ASCII = 1; // = Z_TEXT (deprecated)\nexport const Z_UNKNOWN = 2;\n\n/* The deflate compression method */\nexport const Z_DEFLATED = 8;\n//export const Z_NULL = null // Use -1 or null inline, depending on var type\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nimport * as utils from \"../utils/common.js\";\nimport {\n Z_FIXED,\n Z_BINARY,\n Z_TEXT,\n Z_UNKNOWN\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nfunction zero(buf) {\n let len = buf.length; while (--len >= 0) {\n buf[len] = 0; \n } \n}\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nconst extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nconst extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nconst bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = w & 0xff;\n s.pending_buf[s.pending++] = w >>> 8 & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > Buf_size - length) {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> Buf_size - s.bi_valid;\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= value << s.bi_valid & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) {\n continue; \n } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) {\n return; \n }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) {\n bits--; \n }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) {\n continue; \n }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = code + bl_count[bits - 1] << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < 1 << extra_lbits[code]; n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < 1 << extra_dbits[code]; n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) {\n s.dyn_ltree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < D_CODES; n++) {\n s.dyn_dtree[n * 2]/*.Freq*/ = 0; \n }\n for (n = 0; n < BL_CODES; n++) {\n s.bl_tree[n * 2]/*.Freq*/ = 0; \n }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s) {\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n // while (len--) {\n // put_byte(s, *buf++);\n // }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n const _n2 = n * 2;\n const _m2 = m * 2;\n return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) {\n break; \n }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {\n pqdownheap(s, tree, n); \n }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) {\n s.bl_tree[curlen * 2]/*.Freq*/++; \n }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do {\n send_code(s, curlen, s.bl_tree); \n } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s) {\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = s.opt_len + 3 + 7 >>> 3;\n static_lenb = s.static_len + 3 + 7 >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) {\n opt_lenb = static_lenb; \n }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if (stored_len + 4 <= opt_lenb && buf !== -1) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n\n //#ifdef TRUNCATE_BLOCK\n // /* Try to guess if it is profitable to stop the current block here */\n // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n // /* Compute an upper bound for the compressed length */\n // out_length = s.last_lit*8;\n // in_length = s.strstart - s.block_start;\n //\n // for (dcode = 0; dcode < D_CODES; dcode++) {\n // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n // }\n // out_length >>>= 3;\n // //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n // // s->last_lit, in_length, out_length,\n // // 100L - out_length*100L/in_length));\n // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n // return true;\n // }\n // }\n //#endif\n\n return s.last_lit === s.lit_bufsize - 1;\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexport {\n _tr_init,\n _tr_stored_block,\n _tr_flush_block,\n _tr_tally,\n _tr_align\n};","\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default function adler32(adler, buf, len, pos) {\n let s1 = adler & 0xffff |0,\n s2 = adler >>> 16 & 0xffff |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = s1 + buf[pos++] |0;\n s2 = s2 + s1 |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return s1 | s2 << 16 |0;\n}\n","\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n let c;\n const table = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = makeTable();\n\n\nexport default function crc32(crc, buf, len, pos) {\n const t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return crc ^ -1; // >>> 0;\n}","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default {\n 2: \"need dictionary\", /* Z_NEED_DICT 2 */\n 1: \"stream end\", /* Z_STREAM_END 1 */\n 0: \"\", /* Z_OK 0 */\n \"-1\": \"file error\", /* Z_ERRNO (-1) */\n \"-2\": \"stream error\", /* Z_STREAM_ERROR (-2) */\n \"-3\": \"data error\", /* Z_DATA_ERROR (-3) */\n \"-4\": \"insufficient memory\", /* Z_MEM_ERROR (-4) */\n \"-5\": \"buffer error\", /* Z_BUF_ERROR (-5) */\n \"-6\": \"incompatible version\" /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport * as trees from \"./trees.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport msg from \"./messages.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_NO_FLUSH,\n Z_PARTIAL_FLUSH,\n Z_FULL_FLUSH,\n Z_FINISH,\n Z_BLOCK,\n Z_OK,\n Z_STREAM_END,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED,\n Z_HUFFMAN_ONLY,\n Z_RLE,\n Z_FIXED,\n Z_DEFAULT_STRATEGY,\n Z_UNKNOWN,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n // put_byte(s, (Byte)(b >> 8));\n // put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n //#if MIN_MATCH != 3\n // Call update_hash() MIN_MATCH-3 more times\n //#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n // if (s.high_water < s.window_size) {\n // var curr = s.strstart + s.lookahead;\n // var init = 0;\n //\n // if (s.high_water < curr) {\n // /* Previous high water mark below current data -- zero WIN_INIT\n // * bytes or up to end of window, whichever is less.\n // */\n // init = s.window_size - curr;\n // if (init > WIN_INIT)\n // init = WIN_INIT;\n // zmemzero(s->window + curr, (unsigned)init);\n // s->high_water = curr + init;\n // }\n // else if (s->high_water < (ulg)curr + WIN_INIT) {\n // /* High water mark at or above current data, but below current data\n // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n // * to end of window, whichever is less.\n // */\n // init = (ulg)curr + WIN_INIT - s->high_water;\n // if (init > s->window_size - s->high_water)\n // init = s->window_size - s->high_water;\n // zmemzero(s->window + s->high_water, (unsigned)init);\n // s->high_water += init;\n // }\n // }\n //\n // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n // \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (; ;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n // s.block_start >= s.w_size)) {\n // throw new Error(\"slide too late\");\n // }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n // if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n //#if MIN_MATCH != 3\n // Call UPDATE_HASH() MIN_MATCH-3 more times\n //#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (; ;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n let bflush; /* set if current block must be flushed */\n\n for (; ;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nclass Config {\n constructor(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n }\n};\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\nclass DeflateState {\n constructor() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n }\n}\n\nfunction deflateResetKeep(strm) {\n let s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n let old_flush, s;\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n //#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n //#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n let status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n let dictLength = dictionary.length;\n\n let s;\n let str, n;\n let wrap;\n let avail;\n let next;\n let input;\n let tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\nconst deflateInfo = 'pako deflate (from Nodeca project)';\nexport {\n deflateInit,\n deflateInit2,\n deflateReset,\n deflateResetKeep,\n deflateSetHeader,\n deflate,\n deflateEnd,\n deflateSetDictionary,\n deflateInfo\n};\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n\n\n\nimport * as utils from \"./common.js\";\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_OK = true;\nlet STR_APPLY_UIA_OK = true;\n\ntry {\n String.fromCharCode.apply(null, [ 0 ]); \n} catch (__) {\n STR_APPLY_OK = false; \n}\ntry {\n String.fromCharCode.apply(null, new Uint8Array(1)); \n} catch (__) {\n STR_APPLY_UIA_OK = false; \n}\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new utils.Buf8(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexport function string2buf (str) {\n let c, c2, m_pos, i, buf_len = 0;\n const str_len = str.length;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n const buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | c >>> 6;\n buf[i++] = 0x80 | c & 0x3f;\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | c >>> 12;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | c >>> 18;\n buf[i++] = 0x80 | c >>> 12 & 0x3f;\n buf[i++] = 0x80 | c >>> 6 & 0x3f;\n buf[i++] = 0x80 | c & 0x3f;\n }\n }\n\n return buf;\n}\n\n// Helper (used in 2 places)\nfunction _buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n let result = \"\";\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexport function buf2binstring (buf) {\n return _buf2binstring(buf, buf.length);\n}\n\n\n// Convert binary string (typed, when possible)\nexport function binstring2buf (str) {\n const buf = new utils.Buf8(str.length);\n for (let i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n}\n\n\n// convert array to string\nexport function buf2string (buf, max) {\n let i, out, c, c_len;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n // var utf16buf = new Array(len * 2);\n // try Uint16Array\n const utf16buf = new Uint16Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) {\n utf16buf[out++] = c; continue; \n }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) {\n utf16buf[out++] = 0xfffd; i += c_len - 1; continue; \n }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = c << 6 | buf[i++] & 0x3f;\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) {\n utf16buf[out++] = 0xfffd; continue; \n }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;\n utf16buf[out++] = 0xdc00 | c & 0x3ff;\n }\n }\n\n return _buf2binstring(utf16buf, out);\n}\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexport function utf8border (buf, max) {\n let pos;\n\n max = max || buf.length;\n if (max > buf.length) {\n max = buf.length; \n }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {\n pos--; \n }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) {\n return max; \n }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) {\n return max; \n }\n\n return pos + _utf8len[buf[pos]] > max ? pos : max;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class ZStream {\n constructor() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n }\n}","'use strict';\n\nimport * as zlib_deflate from \"./zlib/deflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\nimport { Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_SYNC_FLUSH,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED } from \"./zlib/constants.js\"\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\n\nclass Deflate {\n constructor(options) {\n this.options = {\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n ...(options || {})\n };\n\n const opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n }\n\n /**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize } } = this;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n /**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n /**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw new Error(deflator.msg || msg[deflator.err]); }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\nexport { Deflate, deflate, deflateRaw, gzip };\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nexport default function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let _out; /* local strm.output */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n const input = strm.input;\n const last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n const output = strm.output;\n const beg = _out - (start - strm.avail_out);\n const end = _out + (strm.avail_out - 257);\n //#ifdef INFLATE_STRICT\n const dmax = state.dmax;\n //#endif\n const wsize = state.wsize;\n const whave = state.whave;\n const wnext = state.wnext;\n const s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n const lcode = state.lencode;\n const dcode = state.distcode;\n const lmask = (1 << state.lenbits) - 1;\n const dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n } else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & (1 << op) - 1;\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = here >>> 16 & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & (1 << op) - 1;\n //#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n //#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = \"invalid distance too far back\";\n state.mode = BAD;\n break top;\n }\n\n // (!) This block is disabled in zlib defaults,\n // don't enable it for binary compatibility\n //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n // if (len <= op - whave) {\n // do {\n // output[_out++] = 0;\n // } while (--len);\n // continue top;\n // }\n // len -= op - whave;\n // do {\n // output[_out++] = 0;\n // } while (--op > whave);\n // if (op === 0) {\n // from = _out - dist;\n // do {\n // output[_out++] = output[from++];\n // } while (--len);\n // continue top;\n // }\n //#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n } else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n } else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n } else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n } else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dodist;\n } else {\n strm.msg = \"invalid distance code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];\n continue dolen;\n } else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n } else {\n strm.msg = \"invalid literal/length code\";\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);\n strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);\n state.hold = hold;\n state.bits = bits;\n return;\n}\n","\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nconst lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nconst dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nconst dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nexport default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n // var shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) {\n break; \n }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = 1 << 24 | 64 << 16 | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) {\n break; \n }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n const mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n } else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n } else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << len - drop;\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << len - 1;\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) {\n break; \n }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) {\n break; \n }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if (type === LENS && used > ENOUGH_LENS ||\n type === DISTS && used > ENOUGH_DISTS) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = root << 24 | curr << 16 | next - table_index |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = len - drop << 24 | 64 << 16 |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n}\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nimport * as utils from \"../utils/common.js\";\nimport adler32 from \"./adler32.js\";\nimport crc32 from \"./crc32.js\";\nimport inflate_fast from \"./inffast.js\";\nimport inflate_table from \"./inftrees.js\";\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nimport {\n Z_FINISH,\n Z_BLOCK,\n Z_TREES,\n Z_OK,\n Z_STREAM_END,\n Z_NEED_DICT,\n Z_STREAM_ERROR,\n Z_DATA_ERROR,\n Z_BUF_ERROR,\n Z_DEFLATED\n} from \"./constants.js\";\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\n//const MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nclass InflateState {\n constructor() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n }\n}\n\nfunction inflateResetKeep(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n let state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n let wrap;\n let state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n let ret;\n let state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n let sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n let hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary var for NEED_BITS\n\n const order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n // case MEM:\n // return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n const state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n let state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n // if (ret) {\n // state.mode = MEM;\n // return Z_MEM_ERROR;\n // }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nconst inflateInfo = 'pako inflate (from Nodeca project)';\n\nexport {\n inflateReset,\n inflateReset2,\n inflateResetKeep,\n inflateInit,\n inflateInit2,\n inflate,\n inflateEnd,\n inflateGetHeader,\n inflateSetDictionary,\n inflateInfo\n};\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nexport default class GZheader {\n constructor() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n }\n}","'use strict';\n\nimport * as zlib_inflate from \"./zlib/inflate.js\";\nimport * as utils from \"./utils/common.js\";\nimport * as strings from \"./utils/strings.js\";\nimport * as c from \"./zlib/constants.js\";\nimport msg from \"./zlib/messages.js\";\nimport ZStream from \"./zlib/zstream.js\";\nimport GZheader from \"./zlib/gzheader.js\";\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nclass Inflate {\n constructor(options) {\n this.options = {\n chunkSize: 16384,\n windowBits: 0,\n ...(options || {})\n };\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n let status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (opt.dictionary instanceof ArrayBuffer) {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n }\n /**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\n push(data, mode) {\n const { strm, options: { chunkSize, dictionary } } = this;\n let status, _mode;\n let next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n let allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (data instanceof ArrayBuffer) {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n };\n\n /**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\n onData(chunk) {\n this.chunks.push(chunk);\n };\n\n\n\n /**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\n onEnd(status) {\n // On success - join\n if (status === c.Z_OK) {\n this.result = utils.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n };\n}\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw new Error(inflator.msg || msg[inflator.err]); }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\nexport { Inflate, inflate, inflateRaw, inflate as ungzip };\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuer,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.signedHashValue = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n this.params = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false) {\n if (key.version === 5) {\n this.version = 5;\n } else {\n this.version = 4;\n }\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = [];\n this.unhashedSubpackets.forEach(data => {\n arr.push(writeSimpleLength(data.length));\n arr.push(data);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, 2);\n\n return util.concat([length, result]);\n }\n\n // V4 signature sub packets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n if (!hashed) {\n this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n mypos++;\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuer:\n // Issuer\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion === 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n default: {\n const err = new Error(`Unknown signature subpacket type ${type}`);\n if (critical) {\n throw err;\n } else {\n util.printDebug(err);\n }\n }\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, 2));\n\n let i = 2;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n constructor() {\n /** A one-octet version number. The current version is 3. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** An eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current version is 3.\n this.version = bytes[mypos++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n // An eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);\n\n const end = new Uint8Array([this.flags]);\n\n return util.concatUint8Array([start, this.issuerKeyID.write(), end]);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID)\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Deflate } from '@openpgp/pako/lib/deflate';\nimport { Inflate } from '@openpgp/pako/lib/inflate';\nimport { Z_SYNC_FLUSH, Z_FINISH } from '@openpgp/pako/lib/zlib/constants';\nimport { decode as BunzipDecode } from '@openpgp/seek-bzip';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n\n /**\n * zip/zlib compression level, between 1 and 9\n */\n this.deflateLevel = config.deflateLevel;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName];\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write(), this.deflateLevel);\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\nconst nodeZlib = util.getNodeZlib();\n\nfunction uncompressed(data) {\n return data;\n}\n\nfunction node_zlib(func, create, options = {}) {\n return function (data) {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(data => {\n return new Promise((resolve, reject) => {\n func(data, options, (err, result) => {\n if (err) return reject(err);\n resolve(result);\n });\n });\n }));\n }\n return stream.nodeToWeb(stream.webToNode(data).pipe(create(options)));\n };\n}\n\nfunction pako_zlib(constructor, options = {}) {\n return function(data) {\n const obj = new constructor(options);\n return stream.transform(data, value => {\n if (value.length) {\n obj.push(value, Z_SYNC_FLUSH);\n return obj.result;\n }\n }, () => {\n if (constructor === Deflate) {\n obj.push([], Z_FINISH);\n return obj.result;\n }\n });\n };\n}\n\nfunction bzip2(func) {\n return function(data) {\n return stream.fromAsync(async () => func(await stream.readToEnd(data)));\n };\n}\n\nconst compress_fns = nodeZlib ? {\n zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)\n} : {\n zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),\n zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)\n};\n\nconst decompress_fns = nodeZlib ? {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),\n zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n} : {\n uncompressed: uncompressed,\n zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),\n zlib: /*#__PURE__*/ pako_zlib(Inflate),\n bzip2: /*#__PURE__*/ bzip2(BunzipDecode)\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n constructor() {\n this.version = VERSION;\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n // - A one-octet version number. The only currently defined value is 1.\n if (version !== VERSION) {\n throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);\n }\n\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n return util.concat([new Uint8Array([VERSION]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await this.crypt('decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await this.crypt('encrypt', key, data);\n }\n\n /**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\n async crypt(fn, key, data) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const modeInstance = await mode(this.cipherAlgorithm, key);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const adataBuffer = new ArrayBuffer(21);\n const adataArray = new Uint8Array(adataBuffer, 0, 13);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n const iv = this.iv;\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new stream.TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)\n cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\nconst VERSION = 3;\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = 3;\n\n this.publicKeyID = new KeyID();\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version !== VERSION) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n i += this.publicKeyID.read(bytes.subarray(i));\n this.publicKeyAlgorithm = bytes[i++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);\n if (this.publicKeyAlgorithm === enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version]),\n this.publicKeyID.write(),\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n // v3 Montgomery curves have cleartext cipher algo\n if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {\n this.sessionKeyAlgorithm = sessionKeyAlgorithm;\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // add checksum\n return util.concatUint8Array([\n new Uint8Array([cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n }\n case enums.publicKey.x25519:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n return {\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n * @private\n */\n\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport { UnsupportedError } from '../packet/packet';\nimport util from '../util';\n\nclass S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = 'iterated';\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n try {\n this.type = enums.read(enums.s2k, bytes[i++]);\n } catch (err) {\n throw new UnsupportedError('Unknown S2K type.');\n }\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport S2K from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 5 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = enums.symmetric.aes256;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number. The only currently defined version is 4.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version === 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n this.s2k = new S2K();\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version === 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, key);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n } else {\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n\n const { blockSize, keySize } = crypto.getCipher(algo);\n const encryptionKey = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version === 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v5Keys ? 5 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes) {\n let pos = 0;\n // A one-octet version number (3, 4 or 5).\n this.version = bytes[pos++];\n\n if (this.version === 4 || this.version === 5) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version === 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version === 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n if (version === 5) {\n return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);\n }\n return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version === 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version === 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipher(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport S2K from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n this.s2k = new S2K();\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipher(this.symmetric).blockSize\n );\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n const cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...this.s2k.write());\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = new S2K(config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = new S2K(config);\n this.s2k.salt = crypto.random.getRandomBytes(8);\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n\n const { blockSize } = crypto.getCipher(this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = enums.aead.eax;\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } else {\n this.s2kUsage = 254;\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\nasync function produceEncryptionKey(s2k, passphrase, algorithm) {\n const { keySize } = crypto.getCipher(algorithm);\n return s2k.produceKey(passphrase, keySize);\n}\n\nexport default SecretKeyPacket;\n","\n// email-addresses.js - RFC 5322 email address parser\n// v 3.1.0\n//\n// http://tools.ietf.org/html/rfc5322\n//\n// This library does not validate email addresses.\n// emailAddresses attempts to parse addresses using the (fairly liberal)\n// grammar specified in RFC 5322.\n//\n// email-addresses returns {\n// ast: ,\n// addresses: [{\n// node: ,\n// name: ,\n// address: ,\n// local: ,\n// domain: \n// }, ...]\n// }\n//\n// emailAddresses.parseOneAddress and emailAddresses.parseAddressList\n// work as you might expect. Try it out.\n//\n// Many thanks to Dominic Sayers and his documentation on the is_email function,\n// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.\n\n(function (global) {\n\"use strict\";\n\nfunction parse5322(opts) {\n\n // tokenizing functions\n\n function inStr() { return pos < len; }\n function curTok() { return parseString[pos]; }\n function getPos() { return pos; }\n function setPos(i) { pos = i; }\n function nextTok() { pos += 1; }\n function initialize() {\n pos = 0;\n len = parseString.length;\n }\n\n // parser helper functions\n\n function o(name, value) {\n return {\n name: name,\n tokens: value || \"\",\n semantic: value || \"\",\n children: []\n };\n }\n\n function wrap(name, ast) {\n var n;\n if (ast === null) { return null; }\n n = o(name);\n n.tokens = ast.tokens;\n n.semantic = ast.semantic;\n n.children.push(ast);\n return n;\n }\n\n function add(parent, child) {\n if (child !== null) {\n parent.tokens += child.tokens;\n parent.semantic += child.semantic;\n }\n parent.children.push(child);\n return parent;\n }\n\n function compareToken(fxnCompare) {\n var tok;\n if (!inStr()) { return null; }\n tok = curTok();\n if (fxnCompare(tok)) {\n nextTok();\n return o('token', tok);\n }\n return null;\n }\n\n function literal(lit) {\n return function literalFunc() {\n return wrap('literal', compareToken(function (tok) {\n return tok === lit;\n }));\n };\n }\n\n function and() {\n var args = arguments;\n return function andFunc() {\n var i, s, result, start;\n start = getPos();\n s = o('and');\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result === null) {\n setPos(start);\n return null;\n }\n add(s, result);\n }\n return s;\n };\n }\n\n function or() {\n var args = arguments;\n return function orFunc() {\n var i, result, start;\n start = getPos();\n for (i = 0; i < args.length; i += 1) {\n result = args[i]();\n if (result !== null) {\n return result;\n }\n setPos(start);\n }\n return null;\n };\n }\n\n function opt(prod) {\n return function optFunc() {\n var result, start;\n start = getPos();\n result = prod();\n if (result !== null) {\n return result;\n }\n else {\n setPos(start);\n return o('opt');\n }\n };\n }\n\n function invis(prod) {\n return function invisFunc() {\n var result = prod();\n if (result !== null) {\n result.semantic = \"\";\n }\n return result;\n };\n }\n\n function colwsp(prod) {\n return function collapseSemanticWhitespace() {\n var result = prod();\n if (result !== null && result.semantic.length > 0) {\n result.semantic = \" \";\n }\n return result;\n };\n }\n\n function star(prod, minimum) {\n return function starFunc() {\n var s, result, count, start, min;\n start = getPos();\n s = o('star');\n count = 0;\n min = minimum === undefined ? 0 : minimum;\n while ((result = prod()) !== null) {\n count = count + 1;\n add(s, result);\n }\n if (count >= min) {\n return s;\n }\n else {\n setPos(start);\n return null;\n }\n };\n }\n\n // One expects names to get normalized like this:\n // \" First Last \" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n // \"First Last\" -> \"First Last\"\n function collapseWhitespace(s) {\n return s.replace(/([ \\t]|\\r\\n)+/g, ' ').replace(/^\\s*/, '').replace(/\\s*$/, '');\n }\n\n // UTF-8 pseudo-production (RFC 6532)\n // RFC 6532 extends RFC 5322 productions to include UTF-8\n // using the following productions:\n // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4\n // UTF8-2 = \n // UTF8-3 = \n // UTF8-4 = \n //\n // For reference, the extended RFC 5322 productions are:\n // VCHAR =/ UTF8-non-ascii\n // ctext =/ UTF8-non-ascii\n // atext =/ UTF8-non-ascii\n // qtext =/ UTF8-non-ascii\n // dtext =/ UTF8-non-ascii\n function isUTF8NonAscii(tok) {\n // In JavaScript, we just deal directly with Unicode code points,\n // so we aren't checking individual bytes for UTF-8 encoding.\n // Just check that the character is non-ascii.\n return tok.charCodeAt(0) >= 128;\n }\n\n\n // common productions (RFC 5234)\n // http://tools.ietf.org/html/rfc5234\n // B.1. Core Rules\n\n // CR = %x0D\n // ; carriage return\n function cr() { return wrap('cr', literal('\\r')()); }\n\n // CRLF = CR LF\n // ; Internet standard newline\n function crlf() { return wrap('crlf', and(cr, lf)()); }\n\n // DQUOTE = %x22\n // ; \" (Double Quote)\n function dquote() { return wrap('dquote', literal('\"')()); }\n\n // HTAB = %x09\n // ; horizontal tab\n function htab() { return wrap('htab', literal('\\t')()); }\n\n // LF = %x0A\n // ; linefeed\n function lf() { return wrap('lf', literal('\\n')()); }\n\n // SP = %x20\n function sp() { return wrap('sp', literal(' ')()); }\n\n // VCHAR = %x21-7E\n // ; visible (printing) characters\n function vchar() {\n return wrap('vchar', compareToken(function vcharFunc(tok) {\n var code = tok.charCodeAt(0);\n var accept = (0x21 <= code && code <= 0x7E);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // WSP = SP / HTAB\n // ; white space\n function wsp() { return wrap('wsp', or(sp, htab)()); }\n\n\n // email productions (RFC 5322)\n // http://tools.ietf.org/html/rfc5322\n // 3.2.1. Quoted characters\n\n // quoted-pair = (\"\\\" (VCHAR / WSP)) / obs-qp\n function quotedPair() {\n var qp = wrap('quoted-pair',\n or(\n and(literal('\\\\'), or(vchar, wsp)),\n obsQP\n )());\n if (qp === null) { return null; }\n // a quoted pair will be two characters, and the \"\\\" character\n // should be semantically \"invisible\" (RFC 5322 3.2.1)\n qp.semantic = qp.semantic[1];\n return qp;\n }\n\n // 3.2.2. Folding White Space and Comments\n\n // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS\n function fws() {\n return wrap('fws', or(\n obsFws,\n and(\n opt(and(\n star(wsp),\n invis(crlf)\n )),\n star(wsp, 1)\n )\n )());\n }\n\n // ctext = %d33-39 / ; Printable US-ASCII\n // %d42-91 / ; characters not including\n // %d93-126 / ; \"(\", \")\", or \"\\\"\n // obs-ctext\n function ctext() {\n return wrap('ctext', or(\n function ctextFunc1() {\n return compareToken(function ctextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 39) ||\n (42 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsCtext\n )());\n }\n\n // ccontent = ctext / quoted-pair / comment\n function ccontent() {\n return wrap('ccontent', or(ctext, quotedPair, comment)());\n }\n\n // comment = \"(\" *([FWS] ccontent) [FWS] \")\"\n function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }\n\n // CFWS = (1*([FWS] comment) [FWS]) / FWS\n function cfws() {\n return wrap('cfws', or(\n and(\n star(\n and(opt(fws), comment),\n 1\n ),\n opt(fws)\n ),\n fws\n )());\n }\n\n // 3.2.3. Atom\n\n //atext = ALPHA / DIGIT / ; Printable US-ASCII\n // \"!\" / \"#\" / ; characters not including\n // \"$\" / \"%\" / ; specials. Used for atoms.\n // \"&\" / \"'\" /\n // \"*\" / \"+\" /\n // \"-\" / \"/\" /\n // \"=\" / \"?\" /\n // \"^\" / \"_\" /\n // \"`\" / \"{\" /\n // \"|\" / \"}\" /\n // \"~\"\n function atext() {\n return wrap('atext', compareToken(function atextFunc(tok) {\n var accept =\n ('a' <= tok && tok <= 'z') ||\n ('A' <= tok && tok <= 'Z') ||\n ('0' <= tok && tok <= '9') ||\n (['!', '#', '$', '%', '&', '\\'', '*', '+', '-', '/',\n '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n }));\n }\n\n // atom = [CFWS] 1*atext [CFWS]\n function atom() {\n return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());\n }\n\n // dot-atom-text = 1*atext *(\".\" 1*atext)\n function dotAtomText() {\n var s, maybeText;\n s = wrap('dot-atom-text', star(atext, 1)());\n if (s === null) { return s; }\n maybeText = star(and(literal('.'), star(atext, 1)))();\n if (maybeText !== null) {\n add(s, maybeText);\n }\n return s;\n }\n\n // dot-atom = [CFWS] dot-atom-text [CFWS]\n function dotAtom() {\n return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());\n }\n\n // 3.2.4. Quoted Strings\n\n // qtext = %d33 / ; Printable US-ASCII\n // %d35-91 / ; characters not including\n // %d93-126 / ; \"\\\" or the quote character\n // obs-qtext\n function qtext() {\n return wrap('qtext', or(\n function qtextFunc1() {\n return compareToken(function qtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 === code) ||\n (35 <= code && code <= 91) ||\n (93 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsQtext\n )());\n }\n\n // qcontent = qtext / quoted-pair\n function qcontent() {\n return wrap('qcontent', or(qtext, quotedPair)());\n }\n\n // quoted-string = [CFWS]\n // DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n // [CFWS]\n function quotedString() {\n return wrap('quoted-string', and(\n invis(opt(cfws)),\n invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),\n invis(opt(cfws))\n )());\n }\n\n // 3.2.5 Miscellaneous Tokens\n\n // word = atom / quoted-string\n function word() {\n return wrap('word', or(atom, quotedString)());\n }\n\n // phrase = 1*word / obs-phrase\n function phrase() {\n return wrap('phrase', or(obsPhrase, star(word, 1))());\n }\n\n // 3.4. Address Specification\n // address = mailbox / group\n function address() {\n return wrap('address', or(mailbox, group)());\n }\n\n // mailbox = name-addr / addr-spec\n function mailbox() {\n return wrap('mailbox', or(nameAddr, addrSpec)());\n }\n\n // name-addr = [display-name] angle-addr\n function nameAddr() {\n return wrap('name-addr', and(opt(displayName), angleAddr)());\n }\n\n // angle-addr = [CFWS] \"<\" addr-spec \">\" [CFWS] /\n // obs-angle-addr\n function angleAddr() {\n return wrap('angle-addr', or(\n and(\n invis(opt(cfws)),\n literal('<'),\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n ),\n obsAngleAddr\n )());\n }\n\n // group = display-name \":\" [group-list] \";\" [CFWS]\n function group() {\n return wrap('group', and(\n displayName,\n literal(':'),\n opt(groupList),\n literal(';'),\n invis(opt(cfws))\n )());\n }\n\n // display-name = phrase\n function displayName() {\n return wrap('display-name', function phraseFixedSemantic() {\n var result = phrase();\n if (result !== null) {\n result.semantic = collapseWhitespace(result.semantic);\n }\n return result;\n }());\n }\n\n // mailbox-list = (mailbox *(\",\" mailbox)) / obs-mbox-list\n function mailboxList() {\n return wrap('mailbox-list', or(\n and(\n mailbox,\n star(and(literal(','), mailbox))\n ),\n obsMboxList\n )());\n }\n\n // address-list = (address *(\",\" address)) / obs-addr-list\n function addressList() {\n return wrap('address-list', or(\n and(\n address,\n star(and(literal(','), address))\n ),\n obsAddrList\n )());\n }\n\n // group-list = mailbox-list / CFWS / obs-group-list\n function groupList() {\n return wrap('group-list', or(\n mailboxList,\n invis(cfws),\n obsGroupList\n )());\n }\n\n // 3.4.1 Addr-Spec Specification\n\n // local-part = dot-atom / quoted-string / obs-local-part\n function localPart() {\n // note: quoted-string, dotAtom are proper subsets of obs-local-part\n // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree\n return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());\n }\n\n // dtext = %d33-90 / ; Printable US-ASCII\n // %d94-126 / ; characters not including\n // obs-dtext ; \"[\", \"]\", or \"\\\"\n function dtext() {\n return wrap('dtext', or(\n function dtextFunc1() {\n return compareToken(function dtextFunc2(tok) {\n var code = tok.charCodeAt(0);\n var accept =\n (33 <= code && code <= 90) ||\n (94 <= code && code <= 126);\n if (opts.rfc6532) {\n accept = accept || isUTF8NonAscii(tok);\n }\n return accept;\n });\n },\n obsDtext\n )()\n );\n }\n\n // domain-literal = [CFWS] \"[\" *([FWS] dtext) [FWS] \"]\" [CFWS]\n function domainLiteral() {\n return wrap('domain-literal', and(\n invis(opt(cfws)),\n literal('['),\n star(and(opt(fws), dtext)),\n opt(fws),\n literal(']'),\n invis(opt(cfws))\n )());\n }\n\n // domain = dot-atom / domain-literal / obs-domain\n function domain() {\n return wrap('domain', function domainCheckTLD() {\n var result = or(obsDomain, dotAtom, domainLiteral)();\n if (opts.rejectTLD) {\n if (result && result.semantic && result.semantic.indexOf('.') < 0) {\n return null;\n }\n }\n // strip all whitespace from domains\n if (result) {\n result.semantic = result.semantic.replace(/\\s+/g, '');\n }\n return result;\n }());\n }\n\n // addr-spec = local-part \"@\" domain\n function addrSpec() {\n return wrap('addr-spec', and(\n localPart, literal('@'), domain\n )());\n }\n\n // 3.6.2 Originator Fields\n // Below we only parse the field body, not the name of the field\n // like \"From:\", \"Sender:\", or \"Reply-To:\". Other libraries that\n // parse email headers can parse those and defer to these productions\n // for the \"RFC 5322\" part.\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // from = \"From:\" (mailbox-list / address-list) CRLF\n function fromSpec() {\n return wrap('from', or(\n mailboxList,\n addressList\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // sender = \"Sender:\" (mailbox / address) CRLF\n function senderSpec() {\n return wrap('sender', or(\n mailbox,\n address\n )());\n }\n\n // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields\n // reply-to = \"Reply-To:\" address-list CRLF\n function replyToSpec() {\n return wrap('reply-to', addressList());\n }\n\n // 4.1. Miscellaneous Obsolete Tokens\n\n // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control\n // %d11 / ; characters that do not\n // %d12 / ; include the carriage\n // %d14-31 / ; return, line feed, and\n // %d127 ; white space characters\n function obsNoWsCtl() {\n return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {\n var code = tok.charCodeAt(0);\n return ((1 <= code && code <= 8) ||\n (11 === code || 12 === code) ||\n (14 <= code && code <= 31) ||\n (127 === code));\n }));\n }\n\n // obs-ctext = obs-NO-WS-CTL\n function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }\n\n // obs-qtext = obs-NO-WS-CTL\n function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }\n\n // obs-qp = \"\\\" (%d0 / obs-NO-WS-CTL / LF / CR)\n function obsQP() {\n return opts.strict ? null : wrap('obs-qp', and(\n literal('\\\\'),\n or(literal('\\0'), obsNoWsCtl, lf, cr)\n )());\n }\n\n // obs-phrase = word *(word / \".\" / CFWS)\n function obsPhrase() {\n if (opts.strict ) return null;\n return opts.atInDisplayName ? wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), literal('@'), colwsp(cfws)))\n )()) :\n wrap('obs-phrase', and(\n word,\n star(or(word, literal('.'), colwsp(cfws)))\n )());\n }\n\n // 4.2. Obsolete Folding White Space\n\n // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908\n // obs-FWS = 1*([CRLF] WSP)\n function obsFws() {\n return opts.strict ? null : wrap('obs-FWS', star(\n and(invis(opt(crlf)), wsp),\n 1\n )());\n }\n\n // 4.4. Obsolete Addressing\n\n // obs-angle-addr = [CFWS] \"<\" obs-route addr-spec \">\" [CFWS]\n function obsAngleAddr() {\n return opts.strict ? null : wrap('obs-angle-addr', and(\n invis(opt(cfws)),\n literal('<'),\n obsRoute,\n addrSpec,\n literal('>'),\n invis(opt(cfws))\n )());\n }\n\n // obs-route = obs-domain-list \":\"\n function obsRoute() {\n return opts.strict ? null : wrap('obs-route', and(\n obsDomainList,\n literal(':')\n )());\n }\n\n // obs-domain-list = *(CFWS / \",\") \"@\" domain\n // *(\",\" [CFWS] [\"@\" domain])\n function obsDomainList() {\n return opts.strict ? null : wrap('obs-domain-list', and(\n star(or(invis(cfws), literal(','))),\n literal('@'),\n domain,\n star(and(\n literal(','),\n invis(opt(cfws)),\n opt(and(literal('@'), domain))\n ))\n )());\n }\n\n // obs-mbox-list = *([CFWS] \",\") mailbox *(\",\" [mailbox / CFWS])\n function obsMboxList() {\n return opts.strict ? null : wrap('obs-mbox-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n mailbox,\n star(and(\n literal(','),\n opt(and(\n mailbox,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-addr-list = *([CFWS] \",\") address *(\",\" [address / CFWS])\n function obsAddrList() {\n return opts.strict ? null : wrap('obs-addr-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n )),\n address,\n star(and(\n literal(','),\n opt(and(\n address,\n invis(cfws)\n ))\n ))\n )());\n }\n\n // obs-group-list = 1*([CFWS] \",\") [CFWS]\n function obsGroupList() {\n return opts.strict ? null : wrap('obs-group-list', and(\n star(and(\n invis(opt(cfws)),\n literal(',')\n ), 1),\n invis(opt(cfws))\n )());\n }\n\n // obs-local-part = word *(\".\" word)\n function obsLocalPart() {\n return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());\n }\n\n // obs-domain = atom *(\".\" atom)\n function obsDomain() {\n return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());\n }\n\n // obs-dtext = obs-NO-WS-CTL / quoted-pair\n function obsDtext() {\n return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());\n }\n\n /////////////////////////////////////////////////////\n\n // ast analysis\n\n function findNode(name, root) {\n var i, stack, node;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n return node;\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return null;\n }\n\n function findAllNodes(name, root) {\n var i, stack, node, result;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name === name) {\n result.push(node);\n }\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n return result;\n }\n\n function findAllNodesNoChildren(names, root) {\n var i, stack, node, result, namesLookup;\n if (root === null || root === undefined) { return null; }\n stack = [root];\n result = [];\n namesLookup = {};\n for (i = 0; i < names.length; i += 1) {\n namesLookup[names[i]] = true;\n }\n\n while (stack.length > 0) {\n node = stack.pop();\n if (node.name in namesLookup) {\n result.push(node);\n // don't look at children (hence findAllNodesNoChildren)\n } else {\n for (i = node.children.length - 1; i >= 0; i -= 1) {\n stack.push(node.children[i]);\n }\n }\n }\n return result;\n }\n\n function giveResult(ast) {\n var addresses, groupsAndMailboxes, i, groupOrMailbox, result;\n if (ast === null) {\n return null;\n }\n addresses = [];\n\n // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.\n groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);\n for (i = 0; i < groupsAndMailboxes.length; i += 1) {\n groupOrMailbox = groupsAndMailboxes[i];\n if (groupOrMailbox.name === 'group') {\n addresses.push(giveResultGroup(groupOrMailbox));\n } else if (groupOrMailbox.name === 'mailbox') {\n addresses.push(giveResultMailbox(groupOrMailbox));\n }\n }\n\n result = {\n ast: ast,\n addresses: addresses,\n };\n if (opts.simple) {\n result = simplifyResult(result);\n }\n if (opts.oneResult) {\n return oneResult(result);\n }\n if (opts.simple) {\n return result && result.addresses;\n } else {\n return result;\n }\n }\n\n function giveResultGroup(group) {\n var i;\n var groupName = findNode('display-name', group);\n var groupResultMailboxes = [];\n var mailboxes = findAllNodesNoChildren(['mailbox'], group);\n for (i = 0; i < mailboxes.length; i += 1) {\n groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));\n }\n return {\n node: group,\n parts: {\n name: groupName,\n },\n type: group.name, // 'group'\n name: grabSemantic(groupName),\n addresses: groupResultMailboxes,\n };\n }\n\n function giveResultMailbox(mailbox) {\n var name = findNode('display-name', mailbox);\n var aspec = findNode('addr-spec', mailbox);\n var cfws = findAllNodes('cfws', mailbox);\n var comments = findAllNodesNoChildren(['comment'], mailbox);\n\n\n var local = findNode('local-part', aspec);\n var domain = findNode('domain', aspec);\n return {\n node: mailbox,\n parts: {\n name: name,\n address: aspec,\n local: local,\n domain: domain,\n comments: cfws\n },\n type: mailbox.name, // 'mailbox'\n name: grabSemantic(name),\n address: grabSemantic(aspec),\n local: grabSemantic(local),\n domain: grabSemantic(domain),\n comments: concatComments(comments),\n groupName: grabSemantic(mailbox.groupName),\n };\n }\n\n function grabSemantic(n) {\n return n !== null && n !== undefined ? n.semantic : null;\n }\n\n function simplifyResult(result) {\n var i;\n if (result && result.addresses) {\n for (i = 0; i < result.addresses.length; i += 1) {\n delete result.addresses[i].node;\n }\n }\n return result;\n }\n\n function concatComments(comments) {\n var result = '';\n if (comments) {\n for (var i = 0; i < comments.length; i += 1) {\n result += grabSemantic(comments[i]);\n }\n }\n return result;\n }\n\n function oneResult(result) {\n if (!result) { return null; }\n if (!opts.partial && result.addresses.length > 1) { return null; }\n return result.addresses && result.addresses[0];\n }\n\n /////////////////////////////////////////////////////\n\n var parseString, pos, len, parsed, startProduction;\n\n opts = handleOpts(opts, {});\n if (opts === null) { return null; }\n\n parseString = opts.input;\n\n startProduction = {\n 'address': address,\n 'address-list': addressList,\n 'angle-addr': angleAddr,\n 'from': fromSpec,\n 'group': group,\n 'mailbox': mailbox,\n 'mailbox-list': mailboxList,\n 'reply-to': replyToSpec,\n 'sender': senderSpec,\n }[opts.startAt] || addressList;\n\n if (!opts.strict) {\n initialize();\n opts.strict = true;\n parsed = startProduction(parseString);\n if (opts.partial || !inStr()) {\n return giveResult(parsed);\n }\n opts.strict = false;\n }\n\n initialize();\n parsed = startProduction(parseString);\n if (!opts.partial && inStr()) { return null; }\n return giveResult(parsed);\n}\n\nfunction parseOneAddressSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseAddressListSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'address-list',\n }));\n}\n\nfunction parseFromSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'from',\n }));\n}\n\nfunction parseSenderSimple(opts) {\n return parse5322(handleOpts(opts, {\n oneResult: true,\n rfc6532: true,\n simple: true,\n startAt: 'sender',\n }));\n}\n\nfunction parseReplyToSimple(opts) {\n return parse5322(handleOpts(opts, {\n rfc6532: true,\n simple: true,\n startAt: 'reply-to',\n }));\n}\n\nfunction handleOpts(opts, defs) {\n function isString(str) {\n return Object.prototype.toString.call(str) === '[object String]';\n }\n\n function isObject(o) {\n return o === Object(o);\n }\n\n function isNullUndef(o) {\n return o === null || o === undefined;\n }\n\n var defaults, o;\n\n if (isString(opts)) {\n opts = { input: opts };\n } else if (!isObject(opts)) {\n return null;\n }\n\n if (!isString(opts.input)) { return null; }\n if (!defs) { return null; }\n\n defaults = {\n oneResult: false,\n partial: false,\n rejectTLD: false,\n rfc6532: false,\n simple: false,\n startAt: 'address-list',\n strict: false,\n atInDisplayName: false\n };\n\n for (o in defaults) {\n if (isNullUndef(opts[o])) {\n opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];\n }\n }\n return opts;\n}\n\nparse5322.parseOneAddress = parseOneAddressSimple;\nparse5322.parseAddressList = parseAddressListSimple;\nparse5322.parseFrom = parseFromSimple;\nparse5322.parseSender = parseSenderSimple;\nparse5322.parseReplyTo = parseReplyToSimple;\n\nif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = parse5322;\n} else {\n global.emailAddresses = parse5322;\n}\n\n}(this));\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport emailAddresses from 'email-addresses';\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n try {\n const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });\n this.comment = comments.replace(/^\\(|\\)$/g, '');\n this.name = name;\n this.email = email;\n } catch (e) {}\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n * @private\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm of a key\n * @param {Key} [key] - The key to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userID = {}, config) {\n let hashAlgo = config.preferredHashAlgorithm;\n let prefAlgo = hashAlgo;\n if (key) {\n const primaryUser = await key.getPrimaryUser(date, userID, config);\n if (primaryUser.selfCertification.preferredHashAlgorithms) {\n [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;\n hashAlgo = crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n }\n }\n switch (keyPacket.algorithm) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n prefAlgo = crypto.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);\n }\n return crypto.hash.getHashByteLength(hashAlgo) <= crypto.hash.getHashByteLength(prefAlgo) ?\n prefAlgo : hashAlgo;\n}\n\n/**\n * Returns the preferred symmetric/aead/compression algorithm for a set of keys\n * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred algorithm\n * @async\n */\nexport async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = { // these are all must-implement in rfc4880bis\n 'symmetric': enums.symmetric.aes128,\n 'aead': enums.aead.eax,\n 'compression': enums.compression.uncompressed\n }[type];\n const preferredSenderAlgo = {\n 'symmetric': config.preferredSymmetricAlgorithm,\n 'aead': config.preferredAEADAlgorithm,\n 'compression': config.preferredCompressionAlgorithm\n }[type];\n const prefPropertyName = {\n 'symmetric': 'preferredSymmetricAlgorithms',\n 'aead': 'preferredAEADAlgorithms',\n 'compression': 'preferredCompressionAlgorithms'\n }[type];\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n const recipientPrefs = primaryUser.selfCertification[prefPropertyName];\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {PrivateKey} privateKey - key to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userID, config);\n signaturePacket.rawNotations = notations;\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n await revocationSignature.verify(\n key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\n/**\n * Returns whether aead is supported by all keys in the set\n * @param {Array} keys - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {\n let supported = true;\n // TODO replace when Promise.some or Promise.any are implemented\n await Promise.all(keys.map(async function(key, i) {\n const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);\n if (!primaryUser.selfCertification.features ||\n !(primaryUser.selfCertification.features[0] & enums.features.aead)) {\n supported = false;\n }\n }));\n return supported;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc':\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function isValidSigningKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.rsaEncrypt &&\n keyAlgo !== enums.publicKey.elgamal &&\n keyAlgo !== enums.publicKey.ecdh &&\n keyAlgo !== enums.publicKey.x25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);\n}\n\nexport function isValidEncryptionKeyPacket(keyPacket, signature) {\n const keyAlgo = keyPacket.algorithm;\n return keyAlgo !== enums.publicKey.dsa &&\n keyAlgo !== enums.publicKey.rsaSign &&\n keyAlgo !== enums.publicKey.ecdsa &&\n keyAlgo !== enums.publicKey.eddsaLegacy &&\n keyAlgo !== enums.publicKey.ed25519 &&\n (!signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);\n}\n\nexport function isValidDecryptionKeyPacket(signature, config) {\n if (config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n * @private\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n * @private\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n // check for expiration time in direct signatures\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const { selfCertification } = await this.getPrimaryUser(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.isValidDecryptionKeyPacket(bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {}\n }\n }\n\n // evaluate primary key\n const primaryUser = await this.getPrimaryUser(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&\n helper.isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {\n keys.push(this);\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n const keyPacket = await helper.generateSecretSubkey(options);\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {};\n dataToSign.userID = userIDPacket;\n dataToSign.key = secretKeyPacket;\n\n const signatureProperties = {};\n signatureProperties.signatureType = enums.signature.certGeneric;\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128,\n enums.symmetric.aes192\n ], config.preferredSymmetricAlgorithm);\n if (config.aeadProtect) {\n signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.zlib,\n enums.compression.zip,\n enums.compression.uncompressed\n ], config.preferredCompressionAlgorithm);\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.aead;\n }\n if (config.v5Keys) {\n signatureProperties.features[0] |= enums.features.v5Keys;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return createKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No secret key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport KeyID from './type/keyid';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredHashAlgo, getPreferredAlgo, isAEADSupported, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);\n\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || !util.isString(algorithmName)) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.\n if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n // do not check key expiration to allow decryption of old messages\n const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {\n return;\n }\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);\n const algorithmName = enums.read(enums.symmetric, algo);\n const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?\n enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :\n undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(algo);\n return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n let symEncryptedPacket;\n if (aeadAlgorithmName) {\n symEncryptedPacket = new AEADEncryptedDataPacket();\n symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);\n } else {\n symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();\n }\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const algorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();\n pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();\n pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;\n pkESKeyPacket.sessionKey = sessionKey;\n pkESKeyPacket.sessionKeyAlgorithm = algorithm;\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n let i;\n let existingSigPacketlist;\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n if (signature) {\n existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n for (i = existingSigPacketlist.length - 1; i >= 0; i--) {\n const signaturePacket = existingSigPacketlist[i];\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n if (!signingKeys.length && i === 0) {\n onePassSig.flags = 1;\n }\n packetlist.push(onePassSig);\n }\n }\n\n await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];\n const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.signatureType = signatureType;\n onePassSig.hashAlgorithm = await getPreferredHashAlgo(primaryKey, signingKey.keyPacket, date, userIDs, config);\n onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;\n onePassSig.issuerKeyID = signingKey.getKeyID();\n if (i === signingKeys.length - 1) {\n onePassSig.flags = 1;\n }\n return onePassSig;\n })).then(onePassSignatureList => {\n onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));\n });\n\n packetlist.push(literalDataPacket);\n packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config)));\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n return armor(enums.armor.message, this.write(), null, null, null, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const userID = userIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);\n return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n let input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (streamType) {\n await stream.loadStreamsPonyfill();\n input = stream.toStream(input);\n }\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} privateKeys - private keys with decrypted secret key data for signing\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n let hashes = this.signature.packets.map(function(packet) {\n return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();\n });\n hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });\n const body = {\n hash: hashes.join(),\n text: this.text,\n data: this.signature.packets.write()\n };\n return armor(enums.armor.signed, body, undefined, undefined, undefined, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n let oneHeader = null;\n let hashAlgos = [];\n headers.forEach(function(header) {\n oneHeader = header.match(/^Hash: (.+)$/); // get header value\n if (oneHeader) {\n oneHeader = oneHeader[1].replace(/\\s/g, ''); // remove whitespace\n oneHeader = oneHeader.split(',');\n oneHeader = oneHeader.map(function(hash) {\n hash = hash.toLowerCase();\n try {\n return enums.write(enums.hash, hash);\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hash);\n }\n });\n hashAlgos = hashAlgos.concat(oneHeader);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {\n throw new Error('If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed');\n } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:\n * curve25519 (default), p256, p384, p521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key generation');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0) {\n throw new Error('UserIDs are required for key reformat');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n const streaming = message.fromStream;\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return convertStream(data, streaming, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data, message.fromStream, format);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type\n * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data, streaming, encoding = 'utf8') {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n if (streaming === 'node') {\n data = stream.webToNode(data);\n if (encoding !== 'binary') data.setEncoding(encoding);\n return data;\n }\n if (streaming === 'web' && streamType === 'ponyfill') {\n return stream.toNativeReadable(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","/**\n * web-streams-polyfill v3.0.3\n */\n/// \nconst SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})`;\n\n/// \nfunction noop() {\n return undefined;\n}\nfunction getGlobals() {\n if (typeof self !== 'undefined') {\n return self;\n }\n else if (typeof window !== 'undefined') {\n return window;\n }\n else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\nconst globals = getGlobals();\n\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nconst rethrowAssertionErrorRejection = noop;\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseResolve = Promise.resolve.bind(originalPromise);\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\nfunction newPromise(executor) {\n return new originalPromise(executor);\n}\nfunction promiseResolvedWith(value) {\n return originalPromiseResolve(value);\n}\nfunction promiseRejectedWith(reason) {\n return originalPromiseReject(reason);\n}\nfunction PerformPromiseThen(promise, onFulfilled, onRejected) {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected);\n}\nfunction uponPromise(promise, onFulfilled, onRejected) {\n PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);\n}\nfunction uponFulfillment(promise, onFulfilled) {\n uponPromise(promise, onFulfilled);\n}\nfunction uponRejection(promise, onRejected) {\n uponPromise(promise, undefined, onRejected);\n}\nfunction transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\nfunction setPromiseIsHandledToTrue(promise) {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\nconst queueMicrotask = (() => {\n const globalQueueMicrotask = globals && globals.queueMicrotask;\n if (typeof globalQueueMicrotask === 'function') {\n return globalQueueMicrotask;\n }\n const resolvedPromise = promiseResolvedWith(undefined);\n return (fn) => PerformPromiseThen(resolvedPromise, fn);\n})();\nfunction reflectCall(F, V, args) {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\nfunction promiseCall(F, V, args) {\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n }\n catch (value) {\n return promiseRejectedWith(value);\n }\n}\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nclass SimpleQueue {\n constructor() {\n this._cursor = 0;\n this._size = 0;\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n get length() {\n return this._size;\n }\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback) {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n node = node._next;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n\nfunction ReadableStreamReaderGenericInitialize(reader, stream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n }\n else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n }\n else {\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\nfunction ReadableStreamReaderGenericCancel(reader, reason) {\n const stream = reader._ownerReadableStream;\n return ReadableStreamCancel(stream, reason);\n}\nfunction ReadableStreamReaderGenericRelease(reader) {\n if (reader._ownerReadableStream._state === 'readable') {\n defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n else {\n defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n reader._ownerReadableStream._reader = undefined;\n reader._ownerReadableStream = undefined;\n}\n// Helper functions for the readers.\nfunction readerLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderClosedPromiseInitialize(reader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\nfunction defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\nfunction defaultReaderClosedPromiseInitializeAsResolved(reader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\nfunction defaultReaderClosedPromiseReject(reader, reason) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\nfunction defaultReaderClosedPromiseResetToRejected(reader, reason) {\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\nfunction defaultReaderClosedPromiseResolve(reader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nconst AbortSteps = SymbolPolyfill('[[AbortSteps]]');\nconst ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');\nconst CancelSteps = SymbolPolyfill('[[CancelSteps]]');\nconst PullSteps = SymbolPolyfill('[[PullSteps]]');\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nfunction isDictionary(x) {\n return typeof x === 'object' || typeof x === 'function';\n}\nfunction assertDictionary(obj, context) {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-callback-functions\nfunction assertFunction(x, context) {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-object\nfunction isObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\nfunction assertObject(x, context) {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\nfunction assertRequiredArgument(x, position, context) {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\nfunction assertRequiredField(x, field, context) {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nfunction convertUnrestrictedDouble(value) {\n return Number(value);\n}\nfunction censorNegativeZero(x) {\n return x === 0 ? 0 : x;\n}\nfunction integerPart(x) {\n return censorNegativeZero(MathTrunc(x));\n}\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nfunction convertUnsignedLongLongWithEnforceRange(value, context) {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n let x = Number(value);\n x = censorNegativeZero(x);\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n x = integerPart(x);\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n return x;\n}\n\nfunction assertReadableStream(x, context) {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamDefaultReader(stream) {\n return new ReadableStreamDefaultReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadRequest(stream, readRequest) {\n stream._reader._readRequests.push(readRequest);\n}\nfunction ReadableStreamFulfillReadRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readRequest = reader._readRequests.shift();\n if (done) {\n readRequest._closeSteps();\n }\n else {\n readRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadRequests(stream) {\n return stream._reader._readRequests.length;\n}\nfunction ReadableStreamHasDefaultReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamDefaultReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read() {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamDefaultReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultReaderRead(reader, readRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n }\n else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n }\n else {\n stream._readableStreamController[PullSteps](readRequest);\n }\n}\n// Helper functions for the ReadableStreamDefaultReader.\nfunction defaultReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n\n/// \nlet AsyncIteratorPrototype;\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [SymbolPolyfill.asyncIterator]() {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });\n}\n\n/// \nclass ReadableStreamAsyncIteratorImpl {\n constructor(reader, preventCancel) {\n this._ongoingPromise = undefined;\n this._isFinished = false;\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n next() {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n return(value) {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n _nextSteps() {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('iterate'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n _returnSteps(value) {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n const reader = this._reader;\n if (reader._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('finish iterating'));\n }\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\nconst ReadableStreamAsyncIteratorPrototype = {\n next() {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n return(value) {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n};\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamAsyncIterator(stream, preventCancel) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\nfunction IsReadableStreamAsyncIterator(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n return true;\n}\n// Helper functions for the ReadableStream.\nfunction streamAsyncIteratorBrandCheckException(name) {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n\n/// \n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nfunction IsFiniteNonNegativeNumber(v) {\n if (!IsNonNegativeNumber(v)) {\n return false;\n }\n if (v === Infinity) {\n return false;\n }\n return true;\n}\nfunction IsNonNegativeNumber(v) {\n if (typeof v !== 'number') {\n return false;\n }\n if (NumberIsNaN(v)) {\n return false;\n }\n if (v < 0) {\n return false;\n }\n return true;\n}\n\nfunction DequeueValue(container) {\n const pair = container._queue.shift();\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n return pair.value;\n}\nfunction EnqueueValueWithSize(container, value, size) {\n size = Number(size);\n if (!IsFiniteNonNegativeNumber(size)) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\nfunction PeekQueueValue(container) {\n const pair = container._queue.peek();\n return pair.value;\n}\nfunction ResetQueue(container) {\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n\nfunction CreateArrayFromList(elements) {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice();\n}\nfunction CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n// Not implemented correctly\nfunction TransferArrayBuffer(O) {\n return O;\n}\n// Not implemented correctly\nfunction IsDetachedBuffer(O) {\n return false;\n}\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nclass ReadableStreamBYOBRequest {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view() {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n return this._view;\n }\n respond(bytesWritten) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n if (IsDetachedBuffer(this._view.buffer)) ;\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n respondWithNewView(view) {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n if (view.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (view.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableByteStreamController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n if (this._byobRequest === null && this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, this, view);\n this._byobRequest = byobRequest;\n }\n return this._byobRequest;\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n ReadableByteStreamControllerClose(this);\n }\n enqueue(chunk) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n ReadableByteStreamControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n if (this._pendingPullIntos.length > 0) {\n const firstDescriptor = this._pendingPullIntos.peek();\n firstDescriptor.bytesFilled = 0;\n }\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableByteStream;\n if (this._queueTotalSize > 0) {\n const entry = this._queue.shift();\n this._queueTotalSize -= entry.byteLength;\n ReadableByteStreamControllerHandleQueueDrain(this);\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view);\n return;\n }\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n }\n catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n const pullIntoDescriptor = {\n buffer,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n}\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableByteStreamController.\nfunction IsReadableByteStreamController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamBYOBRequest(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n return true;\n}\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableByteStreamControllerError(controller, e);\n });\n}\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {\n let done = false;\n if (stream._state === 'closed') {\n done = true;\n }\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView, done);\n }\n else {\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);\n}\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {\n const elementSize = pullIntoDescriptor.elementSize;\n const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;\n const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n if (maxAlignedBytes > currentAlignedBytes) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n const queue = controller._queue;\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n }\n else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n return ready;\n}\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n pullIntoDescriptor.bytesFilled += size;\n}\nfunction ReadableByteStreamControllerHandleQueueDrain(controller) {\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n }\n else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller) {\n if (controller._byobRequest === null) {\n return;\n }\n controller._byobRequest._associatedReadableByteStreamController = undefined;\n controller._byobRequest._view = null;\n controller._byobRequest = null;\n}\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {\n const stream = controller._controlledReadableByteStream;\n let elementSize = 1;\n if (view.constructor !== DataView) {\n elementSize = view.constructor.BYTES_PER_ELEMENT;\n }\n const ctor = view.constructor;\n const buffer = TransferArrayBuffer(view.buffer);\n const pullIntoDescriptor = {\n buffer,\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n bytesFilled: 0,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n ReadableByteStreamControllerHandleQueueDrain(controller);\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n controller._pendingPullIntos.push(pullIntoDescriptor);\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\nfunction ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {\n if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {\n // TODO: Figure out whether we should detach the buffer or not here.\n return;\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);\n }\n pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\nfunction ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n }\n else {\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerShiftPendingPullInto(controller) {\n const descriptor = controller._pendingPullIntos.shift();\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n return descriptor;\n}\nfunction ReadableByteStreamControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return false;\n }\n if (controller._closeRequested) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableByteStreamControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n}\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\nfunction ReadableByteStreamControllerClose(controller) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n return;\n }\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled > 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n throw e;\n }\n }\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\nfunction ReadableByteStreamControllerEnqueue(controller, chunk) {\n const stream = controller._controlledReadableByteStream;\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n const buffer = chunk.buffer;\n const byteOffset = chunk.byteOffset;\n const byteLength = chunk.byteLength;\n const transferredBuffer = TransferArrayBuffer(buffer);\n if (ReadableStreamHasDefaultReader(stream)) {\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n else {\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView, false);\n }\n }\n else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n }\n else {\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\nfunction ReadableByteStreamControllerError(controller, e) {\n const stream = controller._controlledReadableByteStream;\n if (stream._state !== 'readable') {\n return;\n }\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableByteStreamControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableByteStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction ReadableByteStreamControllerRespond(controller, bytesWritten) {\n bytesWritten = Number(bytesWritten);\n if (!IsFiniteNonNegativeNumber(bytesWritten)) {\n throw new RangeError('bytesWritten must be a finite');\n }\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\nfunction ReadableByteStreamControllerRespondWithNewView(controller, view) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.byteLength !== view.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n firstDescriptor.buffer = view.buffer;\n ReadableByteStreamControllerRespondInternal(controller, view.byteLength);\n}\nfunction SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {\n controller._controlledReadableByteStream = stream;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._byobRequest = null;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._closeRequested = false;\n controller._started = false;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n controller._pendingPullIntos = new SimpleQueue();\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableByteStreamControllerError(controller, r);\n });\n}\nfunction SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {\n const controller = Object.create(ReadableByteStreamController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start(controller);\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull(controller);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel(reason);\n }\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);\n}\nfunction SetUpReadableStreamBYOBRequest(request, controller, view) {\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n// Helper functions for the ReadableStreamBYOBRequest.\nfunction byobRequestBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n// Helper functions for the ReadableByteStreamController.\nfunction byteStreamControllerBrandCheckException(name) {\n return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n\n// Abstract operations for the ReadableStream.\nfunction AcquireReadableStreamBYOBReader(stream) {\n return new ReadableStreamBYOBReader(stream);\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {\n stream._reader._readIntoRequests.push(readIntoRequest);\n}\nfunction ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {\n const reader = stream._reader;\n const readIntoRequest = reader._readIntoRequests.shift();\n if (done) {\n readIntoRequest._closeSteps(chunk);\n }\n else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\nfunction ReadableStreamGetNumReadIntoRequests(stream) {\n return stream._reader._readIntoRequests.length;\n}\nfunction ReadableStreamHasBYOBReader(stream) {\n const reader = stream._reader;\n if (reader === undefined) {\n return false;\n }\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n return true;\n}\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nclass ReadableStreamBYOBReader {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n ReadableStreamReaderGenericInitialize(this, stream);\n this._readIntoRequests = new SimpleQueue();\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason = undefined) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(view) {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n let resolvePromise;\n let rejectPromise;\n const promise = newPromise((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, readIntoRequest);\n return promise;\n }\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock() {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n if (this._ownerReadableStream === undefined) {\n return;\n }\n if (this._readIntoRequests.length > 0) {\n throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');\n }\n ReadableStreamReaderGenericRelease(this);\n }\n}\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n// Abstract operations for the readers.\nfunction IsReadableStreamBYOBReader(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {\n const stream = reader._ownerReadableStream;\n stream._disturbed = true;\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n }\n else {\n ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);\n }\n}\n// Helper functions for the ReadableStreamBYOBReader.\nfunction byobReaderBrandCheckException(name) {\n return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n\nfunction ExtractHighWaterMark(strategy, defaultHWM) {\n const { highWaterMark } = strategy;\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n return highWaterMark;\n}\nfunction ExtractSizeAlgorithm(strategy) {\n const { size } = strategy;\n if (!size) {\n return () => 1;\n }\n return size;\n}\n\nfunction convertQueuingStrategy(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n const size = init === null || init === void 0 ? void 0 : init.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\nfunction convertQueuingStrategySize(fn, context) {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n\nfunction convertUnderlyingSink(original, context) {\n assertDictionary(original, context);\n const abort = original === null || original === void 0 ? void 0 : original.abort;\n const close = original === null || original === void 0 ? void 0 : original.close;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n const write = original === null || original === void 0 ? void 0 : original.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),\n type\n };\n}\nfunction convertUnderlyingSinkAbortCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSinkCloseCallback(fn, original, context) {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\nfunction convertUnderlyingSinkStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSinkWriteCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction assertWritableStream(x, context) {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n constructor(rawUnderlyingSink = {}, rawStrategy = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n }\n else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n InitializeWritableStream(this);\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('locked');\n }\n return IsWritableStreamLocked(this);\n }\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason = undefined) {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('abort'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n return WritableStreamAbort(this, reason);\n }\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$2('close'));\n }\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamClose(this);\n }\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter() {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException$2('getWriter');\n }\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n// Abstract operations for the WritableStream.\nfunction AcquireWritableStreamDefaultWriter(stream) {\n return new WritableStreamDefaultWriter(stream);\n}\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n const controller = Object.create(WritableStreamDefaultController.prototype);\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeWritableStream(stream) {\n stream._state = 'writable';\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n stream._writer = undefined;\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined;\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\nfunction IsWritableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsWritableStreamLocked(stream) {\n if (stream._writer === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamAbort(stream, reason) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest._promise = promise;\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n return promise;\n}\nfunction WritableStreamClose(stream) {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n const promise = newPromise((resolve, reject) => {\n const closeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._closeRequest = closeRequest;\n });\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n return promise;\n}\n// WritableStream API exposed for controllers.\nfunction WritableStreamAddWriteRequest(stream) {\n const promise = newPromise((resolve, reject) => {\n const writeRequest = {\n _resolve: resolve,\n _reject: reject\n };\n stream._writeRequests.push(writeRequest);\n });\n return promise;\n}\nfunction WritableStreamDealWithRejection(stream, error) {\n const state = stream._state;\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n WritableStreamFinishErroring(stream);\n}\nfunction WritableStreamStartErroring(stream, reason) {\n const controller = stream._writableStreamController;\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\nfunction WritableStreamFinishErroring(stream) {\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(promise, () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n }, (reason) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n });\n}\nfunction WritableStreamFinishInFlightWrite(stream) {\n stream._inFlightWriteRequest._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\nfunction WritableStreamFinishInFlightWriteWithError(stream, error) {\n stream._inFlightWriteRequest._reject(error);\n stream._inFlightWriteRequest = undefined;\n WritableStreamDealWithRejection(stream, error);\n}\nfunction WritableStreamFinishInFlightClose(stream) {\n stream._inFlightCloseRequest._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n const state = stream._state;\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n stream._state = 'closed';\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n}\nfunction WritableStreamFinishInFlightCloseWithError(stream, error) {\n stream._inFlightCloseRequest._reject(error);\n stream._inFlightCloseRequest = undefined;\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream) {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamHasOperationMarkedInFlight(stream) {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n return true;\n}\nfunction WritableStreamMarkCloseRequestInFlight(stream) {\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream) {\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {\n if (stream._closeRequest !== undefined) {\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\nfunction WritableStreamUpdateBackpressure(stream, backpressure) {\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n }\n else {\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n stream._backpressure = backpressure;\n}\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nclass WritableStreamDefaultWriter {\n constructor(stream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n this._ownerWritableStream = stream;\n stream._writer = this;\n const state = stream._state;\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n }\n else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n }\n else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n }\n else {\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n return this._closedPromise;\n }\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n return this._readyPromise;\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close() {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n return WritableStreamDefaultWriterClose(this);\n }\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock() {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n const stream = this._ownerWritableStream;\n if (stream === undefined) {\n return;\n }\n WritableStreamDefaultWriterRelease(this);\n }\n write(chunk = undefined) {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n// Abstract operations for the WritableStreamDefaultWriter.\nfunction IsWritableStreamDefaultWriter(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n return true;\n}\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\nfunction WritableStreamDefaultWriterAbort(writer, reason) {\n const stream = writer._ownerWritableStream;\n return WritableStreamAbort(stream, reason);\n}\nfunction WritableStreamDefaultWriterClose(writer) {\n const stream = writer._ownerWritableStream;\n return WritableStreamClose(stream);\n}\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n return WritableStreamDefaultWriterClose(writer);\n}\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n }\n else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n }\n else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\nfunction WritableStreamDefaultWriterGetDesiredSize(writer) {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\nfunction WritableStreamDefaultWriterRelease(writer) {\n const stream = writer._ownerWritableStream;\n const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n stream._writer = undefined;\n writer._ownerWritableStream = undefined;\n}\nfunction WritableStreamDefaultWriterWrite(writer, chunk) {\n const stream = writer._ownerWritableStream;\n const controller = stream._writableStreamController;\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n const promise = WritableStreamAddWriteRequest(stream);\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n return promise;\n}\nconst closeSentinel = {};\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nclass WritableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e = undefined) {\n if (!IsWritableStreamDefaultController(this)) {\n throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n WritableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [AbortSteps](reason) {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n error: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations implementing interface required by the WritableStream.\nfunction IsWritableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(startPromise, () => {\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, r => {\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n });\n}\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let writeAlgorithm = () => promiseResolvedWith(undefined);\n let closeAlgorithm = () => promiseResolvedWith(undefined);\n let abortAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start(controller);\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write(chunk, controller);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close();\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort(reason);\n }\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller) {\n controller._writeAlgorithm = undefined;\n controller._closeAlgorithm = undefined;\n controller._abortAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\nfunction WritableStreamDefaultControllerClose(controller) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\nfunction WritableStreamDefaultControllerGetChunkSize(controller, chunk) {\n try {\n return controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\nfunction WritableStreamDefaultControllerGetDesiredSize(controller) {\n return controller._strategyHWM - controller._queueTotalSize;\n}\nfunction WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n// Abstract operations for the WritableStreamDefaultController.\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {\n const stream = controller._controlledWritableStream;\n if (!controller._started) {\n return;\n }\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n const state = stream._state;\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n if (controller._queue.length === 0) {\n return;\n }\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n }\n else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller, error) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\nfunction WritableStreamDefaultControllerProcessClose(controller) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkCloseRequestInFlight(stream);\n DequeueValue(controller);\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(sinkClosePromise, () => {\n WritableStreamFinishInFlightClose(stream);\n }, reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerProcessWrite(controller, chunk) {\n const stream = controller._controlledWritableStream;\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(sinkWritePromise, () => {\n WritableStreamFinishInFlightWrite(stream);\n const state = stream._state;\n DequeueValue(controller);\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n }, reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n });\n}\nfunction WritableStreamDefaultControllerGetBackpressure(controller) {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\nfunction WritableStreamDefaultControllerError(controller, error) {\n const stream = controller._controlledWritableStream;\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n// Helper functions for the WritableStream.\nfunction streamBrandCheckException$2(name) {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n// Helper functions for the WritableStreamDefaultWriter.\nfunction defaultWriterBrandCheckException(name) {\n return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\nfunction defaultWriterLockException(name) {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\nfunction defaultWriterClosedPromiseInitialize(writer) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\nfunction defaultWriterClosedPromiseReject(writer, reason) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\nfunction defaultWriterClosedPromiseResetToRejected(writer, reason) {\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterClosedPromiseResolve(writer) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\nfunction defaultWriterReadyPromiseInitialize(writer) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\nfunction defaultWriterReadyPromiseReject(writer, reason) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\nfunction defaultWriterReadyPromiseReset(writer) {\n defaultWriterReadyPromiseInitialize(writer);\n}\nfunction defaultWriterReadyPromiseResetToRejected(writer, reason) {\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\nfunction defaultWriterReadyPromiseResolve(writer) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n\nfunction isAbortSignal(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof value.aborted === 'boolean';\n }\n catch (_a) {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/// \nconst NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;\n\n/// \nfunction isDOMExceptionConstructor(ctor) {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n try {\n new ctor();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createDOMExceptionPolyfill() {\n // eslint-disable-next-line no-shadow\n const ctor = function DOMException(message, name) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n };\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n// eslint-disable-next-line no-redeclare\nconst DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();\n\nfunction ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n source._disturbed = true;\n let shuttingDown = false;\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n return newPromise((resolve, reject) => {\n let abortAlgorithm;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = new DOMException$1('Aborted', 'AbortError');\n const actions = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n signal.addEventListener('abort', abortAlgorithm);\n }\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done) {\n if (done) {\n resolveLoop();\n }\n else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n next(false);\n });\n }\n function pipeStep() {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(reader, {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n });\n });\n });\n }\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n }\n else {\n shutdown(true, storedError);\n }\n });\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n }\n else {\n shutdown();\n }\n });\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n }\n else {\n shutdown(true, destClosed);\n }\n }\n setPromiseIsHandledToTrue(pipeLoop());\n function waitForWritesToFinish() {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);\n }\n function isOrBecomesErrored(stream, promise, action) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n }\n else {\n uponRejection(promise, action);\n }\n }\n function isOrBecomesClosed(stream, promise, action) {\n if (stream._state === 'closed') {\n action();\n }\n else {\n uponFulfillment(promise, action);\n }\n }\n function shutdownWithAction(action, originalIsError, originalError) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n }\n else {\n doTheRest();\n }\n function doTheRest() {\n uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));\n }\n }\n function shutdown(isError, error) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n }\n else {\n finalize(isError, error);\n }\n }\n function finalize(isError, error) {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n }\n else {\n resolve(undefined);\n }\n }\n });\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nclass ReadableStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('desiredSize');\n }\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close() {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('close');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n ReadableStreamDefaultControllerClose(this);\n }\n enqueue(chunk = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('enqueue');\n }\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e = undefined) {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException$1('error');\n }\n ReadableStreamDefaultControllerError(this, e);\n }\n /** @internal */\n [CancelSteps](reason) {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n /** @internal */\n [PullSteps](readRequest) {\n const stream = this._controlledReadableStream;\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n }\n else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n readRequest._chunkSteps(chunk);\n }\n else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n}\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n// Abstract operations for the ReadableStreamDefaultController.\nfunction IsReadableStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller) {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n controller._pulling = true;\n const pullPromise = controller._pullAlgorithm();\n uponPromise(pullPromise, () => {\n controller._pulling = false;\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n }, e => {\n ReadableStreamDefaultControllerError(controller, e);\n });\n}\nfunction ReadableStreamDefaultControllerShouldCallPull(controller) {\n const stream = controller._controlledReadableStream;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n if (!controller._started) {\n return false;\n }\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n if (desiredSize > 0) {\n return true;\n }\n return false;\n}\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller) {\n controller._pullAlgorithm = undefined;\n controller._cancelAlgorithm = undefined;\n controller._strategySizeAlgorithm = undefined;\n}\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\nfunction ReadableStreamDefaultControllerClose(controller) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n controller._closeRequested = true;\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\nfunction ReadableStreamDefaultControllerEnqueue(controller, chunk) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n const stream = controller._controlledReadableStream;\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n }\n else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n }\n catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n }\n catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\nfunction ReadableStreamDefaultControllerError(controller, e) {\n const stream = controller._controlledReadableStream;\n if (stream._state !== 'readable') {\n return;\n }\n ResetQueue(controller);\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\nfunction ReadableStreamDefaultControllerGetDesiredSize(controller) {\n const state = controller._controlledReadableStream._state;\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n return controller._strategyHWM - controller._queueTotalSize;\n}\n// This is used in the implementation of TransformStream.\nfunction ReadableStreamDefaultControllerHasBackpressure(controller) {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n return true;\n}\nfunction ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {\n const state = controller._controlledReadableStream._state;\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n return false;\n}\nfunction SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {\n controller._controlledReadableStream = stream;\n controller._queue = undefined;\n controller._queueTotalSize = undefined;\n ResetQueue(controller);\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n stream._readableStreamController = controller;\n const startResult = startAlgorithm();\n uponPromise(promiseResolvedWith(startResult), () => {\n controller._started = true;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }, r => {\n ReadableStreamDefaultControllerError(controller, r);\n });\n}\nfunction SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n let startAlgorithm = () => undefined;\n let pullAlgorithm = () => promiseResolvedWith(undefined);\n let cancelAlgorithm = () => promiseResolvedWith(undefined);\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start(controller);\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull(controller);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel(reason);\n }\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n}\n// Helper functions for the ReadableStreamDefaultController.\nfunction defaultControllerBrandCheckException$1(name) {\n return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n\nfunction ReadableStreamTee(stream, cloneForBranch2) {\n const reader = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1;\n let reason2;\n let branch1;\n let branch2;\n let resolveCancelPromise;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n function pullAlgorithm() {\n if (reading) {\n return promiseResolvedWith(undefined);\n }\n reading = true;\n const readRequest = {\n _chunkSteps: value => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n reading = false;\n const value1 = value;\n const value2 = value;\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // value2 = StructuredDeserialize(StructuredSerialize(value2));\n // }\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promiseResolvedWith(undefined);\n }\n function cancel1Algorithm(reason) {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function cancel2Algorithm(reason) {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n function startAlgorithm() {\n // do nothing\n }\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n uponRejection(reader._closedPromise, (r) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n });\n return [branch1, branch2];\n}\n\nfunction convertUnderlyingDefaultOrByteSource(source, context) {\n assertDictionary(source, context);\n const original = source;\n const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;\n const cancel = original === null || original === void 0 ? void 0 : original.cancel;\n const pull = original === null || original === void 0 ? void 0 : original.pull;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const type = original === null || original === void 0 ? void 0 : original.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\nfunction convertUnderlyingSourceCancelCallback(fn, original, context) {\n assertFunction(fn, context);\n return (reason) => promiseCall(fn, original, [reason]);\n}\nfunction convertUnderlyingSourcePullCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertUnderlyingSourceStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertReadableStreamType(type, context) {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n\nfunction convertReaderOptions(options, context) {\n assertDictionary(options, context);\n const mode = options === null || options === void 0 ? void 0 : options.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\nfunction convertReadableStreamReaderMode(mode, context) {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nfunction convertIteratorOptions(options, context) {\n assertDictionary(options, context);\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n\nfunction convertPipeOptions(options, context) {\n assertDictionary(options, context);\n const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;\n const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;\n const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;\n const signal = options === null || options === void 0 ? void 0 : options.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\nfunction assertAbortSignal(signal, context) {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n\nfunction convertReadableWritablePair(pair, context) {\n assertDictionary(pair, context);\n const readable = pair === null || pair === void 0 ? void 0 : pair.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n const writable = pair === null || pair === void 0 ? void 0 : pair.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n return { readable, writable };\n}\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nclass ReadableStream {\n constructor(rawUnderlyingSource = {}, rawStrategy = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n }\n else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n InitializeReadableStream(this);\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);\n }\n else {\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);\n }\n }\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('locked');\n }\n return IsReadableStreamLocked(this);\n }\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason = undefined) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('cancel'));\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n return ReadableStreamCancel(this, reason);\n }\n getReader(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('getReader');\n }\n const options = convertReaderOptions(rawOptions, 'First parameter');\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n return AcquireReadableStreamBYOBReader(this);\n }\n pipeThrough(rawTransform, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n setPromiseIsHandledToTrue(promise);\n return transform.readable;\n }\n pipeTo(destination, rawOptions = {}) {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));\n }\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));\n }\n let options;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n }\n catch (e) {\n return promiseRejectedWith(e);\n }\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));\n }\n return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);\n }\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee() {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('tee');\n }\n const branches = ReadableStreamTee(this);\n return CreateArrayFromList(branches);\n }\n values(rawOptions = undefined) {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException$1('values');\n }\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n}\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof SymbolPolyfill.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n// Abstract operations for the ReadableStream.\n// Throws if and only if startAlgorithm throws.\nfunction CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {\n const stream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n const controller = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\nfunction InitializeReadableStream(stream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\nfunction IsReadableStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n return true;\n}\nfunction IsReadableStreamLocked(stream) {\n if (stream._reader === undefined) {\n return false;\n }\n return true;\n}\n// ReadableStream API exposed for controllers.\nfunction ReadableStreamCancel(stream, reason) {\n stream._disturbed = true;\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n ReadableStreamClose(stream);\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\nfunction ReadableStreamClose(stream) {\n stream._state = 'closed';\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseResolve(reader);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n reader._readRequests = new SimpleQueue();\n }\n}\nfunction ReadableStreamError(stream, e) {\n stream._state = 'errored';\n stream._storedError = e;\n const reader = stream._reader;\n if (reader === undefined) {\n return;\n }\n defaultReaderClosedPromiseReject(reader, e);\n if (IsReadableStreamDefaultReader(reader)) {\n reader._readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n reader._readRequests = new SimpleQueue();\n }\n else {\n reader._readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n reader._readIntoRequests = new SimpleQueue();\n }\n}\n// Helper functions for the ReadableStream.\nfunction streamBrandCheckException$1(name) {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n\nfunction convertQueuingStrategyInit(init, context) {\n assertDictionary(init, context);\n const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n\nconst byteLengthSizeFunction = function size(chunk) {\n return chunk.byteLength;\n};\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nclass ByteLengthQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size() {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the ByteLengthQueuingStrategy.\nfunction byteLengthBrandCheckException(name) {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\nfunction IsByteLengthQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nconst countSizeFunction = function size() {\n return 1;\n};\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nclass CountQueuingStrategy {\n constructor(options) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size() {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n// Helper functions for the CountQueuingStrategy.\nfunction countBrandCheckException(name) {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\nfunction IsCountQueuingStrategy(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n return true;\n}\n\nfunction convertTransformer(original, context) {\n assertDictionary(original, context);\n const flush = original === null || original === void 0 ? void 0 : original.flush;\n const readableType = original === null || original === void 0 ? void 0 : original.readableType;\n const start = original === null || original === void 0 ? void 0 : original.start;\n const transform = original === null || original === void 0 ? void 0 : original.transform;\n const writableType = original === null || original === void 0 ? void 0 : original.writableType;\n return {\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),\n writableType\n };\n}\nfunction convertTransformerFlushCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => promiseCall(fn, original, [controller]);\n}\nfunction convertTransformerStartCallback(fn, original, context) {\n assertFunction(fn, context);\n return (controller) => reflectCall(fn, original, [controller]);\n}\nfunction convertTransformerTransformCallback(fn, original, context) {\n assertFunction(fn, context);\n return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);\n}\n\n// Class TransformStream\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nclass TransformStream {\n constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n let startPromise_resolve;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n }\n else {\n startPromise_resolve(undefined);\n }\n }\n /**\n * The readable side of the transform stream.\n */\n get readable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n return this._readable;\n }\n /**\n * The writable side of the transform stream.\n */\n get writable() {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n return this._writable;\n }\n}\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\nfunction InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {\n function startAlgorithm() {\n return startPromise;\n }\n function writeAlgorithm(chunk) {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n function abortAlgorithm(reason) {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n function closeAlgorithm() {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);\n function pullAlgorithm() {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n function cancelAlgorithm(reason) {\n TransformStreamErrorWritableAndUnblockWrite(stream, reason);\n return promiseResolvedWith(undefined);\n }\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined;\n stream._backpressureChangePromise = undefined;\n stream._backpressureChangePromise_resolve = undefined;\n TransformStreamSetBackpressure(stream, true);\n stream._transformStreamController = undefined;\n}\nfunction IsTransformStream(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n return true;\n}\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream, e) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\nfunction TransformStreamErrorWritableAndUnblockWrite(stream, e) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\nfunction TransformStreamSetBackpressure(stream, backpressure) {\n // Passes also when called during construction.\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n stream._backpressure = backpressure;\n}\n// Class TransformStreamDefaultController\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nclass TransformStreamDefaultController {\n constructor() {\n throw new TypeError('Illegal constructor');\n }\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n enqueue(chunk = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason = undefined) {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n TransformStreamDefaultControllerError(this, reason);\n }\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate() {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n TransformStreamDefaultControllerTerminate(this);\n }\n}\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nif (typeof SymbolPolyfill.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n// Transform Stream Default Controller Abstract Operations\nfunction IsTransformStreamDefaultController(x) {\n if (!typeIsObject(x)) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n return true;\n}\nfunction SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n}\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {\n const controller = Object.create(TransformStreamDefaultController.prototype);\n let transformAlgorithm = (chunk) => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk);\n return promiseResolvedWith(undefined);\n }\n catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n let flushAlgorithm = () => promiseResolvedWith(undefined);\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform(chunk, controller);\n }\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush(controller);\n }\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);\n}\nfunction TransformStreamDefaultControllerClearAlgorithms(controller) {\n controller._transformAlgorithm = undefined;\n controller._flushAlgorithm = undefined;\n}\nfunction TransformStreamDefaultControllerEnqueue(controller, chunk) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n }\n catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n throw stream._readable._storedError;\n }\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n TransformStreamSetBackpressure(stream, true);\n }\n}\nfunction TransformStreamDefaultControllerError(controller, e) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\nfunction TransformStreamDefaultControllerPerformTransform(controller, chunk) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\nfunction TransformStreamDefaultControllerTerminate(controller) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n ReadableStreamDefaultControllerClose(readableController);\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n// TransformStreamDefaultSink Algorithms\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {\n const controller = stream._transformStreamController;\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {\n // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already\n // errored.\n TransformStreamError(stream, reason);\n return promiseResolvedWith(undefined);\n}\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream) {\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n const controller = stream._transformStreamController;\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n // Return a promise that is fulfilled with undefined on success.\n return transformPromiseWith(flushPromise, () => {\n if (readable._state === 'errored') {\n throw readable._storedError;\n }\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n }, r => {\n TransformStreamError(stream, r);\n throw readable._storedError;\n });\n}\n// TransformStreamDefaultSource Algorithms\nfunction TransformStreamDefaultSourcePullAlgorithm(stream) {\n // Invariant. Enforced by the promises returned by start() and pull().\n TransformStreamSetBackpressure(stream, false);\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n// Helper functions for the TransformStreamDefaultController.\nfunction defaultControllerBrandCheckException(name) {\n return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n// Helper functions for the TransformStream.\nfunction streamBrandCheckException(name) {\n return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n\nexport { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };\n//# sourceMappingURL=ponyfill.es6.mjs.map\n","/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nfunction assert(test) {\n if (!test) {\n throw new TypeError('Assertion failed');\n }\n}\n\nfunction noop() {\n return;\n}\nfunction typeIsObject(x) {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nfunction isStreamConstructor(ctor) {\n if (typeof ctor !== 'function') {\n return false;\n }\n var startCalled = false;\n try {\n new ctor({\n start: function () {\n startCalled = true;\n }\n });\n }\n catch (e) {\n // ignore\n }\n return startCalled;\n}\nfunction isReadableStream(readable) {\n if (!typeIsObject(readable)) {\n return false;\n }\n if (typeof readable.getReader !== 'function') {\n return false;\n }\n return true;\n}\nfunction isReadableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isReadableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isWritableStream(writable) {\n if (!typeIsObject(writable)) {\n return false;\n }\n if (typeof writable.getWriter !== 'function') {\n return false;\n }\n return true;\n}\nfunction isWritableStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isWritableStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction isTransformStream(transform) {\n if (!typeIsObject(transform)) {\n return false;\n }\n if (!isReadableStream(transform.readable)) {\n return false;\n }\n if (!isWritableStream(transform.writable)) {\n return false;\n }\n return true;\n}\nfunction isTransformStreamConstructor(ctor) {\n if (!isStreamConstructor(ctor)) {\n return false;\n }\n if (!isTransformStream(new ctor())) {\n return false;\n }\n return true;\n}\nfunction supportsByobReader(readable) {\n try {\n var reader = readable.getReader({ mode: 'byob' });\n reader.releaseLock();\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction supportsByteSource(ctor) {\n try {\n new ctor({ type: 'bytes' });\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n\nfunction createReadableStreamWrapper(ctor) {\n assert(isReadableStreamConstructor(ctor));\n var byteSourceSupported = supportsByteSource(ctor);\n return function (readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n type = parseReadableType(type);\n if (type === 'bytes' && !byteSourceSupported) {\n type = undefined;\n }\n if (readable.constructor === ctor) {\n if (type !== 'bytes' || supportsByobReader(readable)) {\n return readable;\n }\n }\n if (type === 'bytes') {\n var source = createWrappingReadableSource(readable, { type: type });\n return new ctor(source);\n }\n else {\n var source = createWrappingReadableSource(readable);\n return new ctor(source);\n }\n };\n}\nfunction createWrappingReadableSource(readable, _a) {\n var _b = _a === void 0 ? {} : _a, type = _b.type;\n assert(isReadableStream(readable));\n assert(readable.locked === false);\n type = parseReadableType(type);\n var source;\n if (type === 'bytes') {\n source = new WrappingReadableByteStreamSource(readable);\n }\n else {\n source = new WrappingReadableStreamDefaultSource(readable);\n }\n return source;\n}\nfunction parseReadableType(type) {\n var typeString = String(type);\n if (typeString === 'bytes') {\n return typeString;\n }\n else if (type === undefined) {\n return type;\n }\n else {\n throw new RangeError('Invalid type is specified');\n }\n}\nvar AbstractWrappingReadableStreamSource = /** @class */ (function () {\n function AbstractWrappingReadableStreamSource(underlyingStream) {\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n this._readableStreamController = undefined;\n this._pendingRead = undefined;\n this._underlyingStream = underlyingStream;\n // always keep a reader attached to detect close/error\n this._attachDefaultReader();\n }\n AbstractWrappingReadableStreamSource.prototype.start = function (controller) {\n this._readableStreamController = controller;\n };\n AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {\n assert(this._underlyingReader !== undefined);\n return this._underlyingReader.cancel(reason);\n };\n AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {\n if (this._readerMode === \"default\" /* DEFAULT */) {\n return;\n }\n this._detachReader();\n var reader = this._underlyingStream.getReader();\n this._readerMode = \"default\" /* DEFAULT */;\n this._attachReader(reader);\n };\n AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {\n var _this = this;\n assert(this._underlyingReader === undefined);\n this._underlyingReader = reader;\n var closed = this._underlyingReader.closed;\n if (!closed) {\n return;\n }\n closed\n .then(function () { return _this._finishPendingRead(); })\n .then(function () {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.close();\n }\n }, function (reason) {\n if (reader === _this._underlyingReader) {\n _this._readableStreamController.error(reason);\n }\n })\n .catch(noop);\n };\n AbstractWrappingReadableStreamSource.prototype._detachReader = function () {\n if (this._underlyingReader === undefined) {\n return;\n }\n this._underlyingReader.releaseLock();\n this._underlyingReader = undefined;\n this._readerMode = undefined;\n };\n AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {\n var _this = this;\n this._attachDefaultReader();\n // TODO Backpressure?\n var read = this._underlyingReader.read()\n .then(function (result) {\n var controller = _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n }\n else {\n controller.enqueue(result.value);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n AbstractWrappingReadableStreamSource.prototype._tryClose = function () {\n try {\n this._readableStreamController.close();\n }\n catch (_a) {\n // already errored or closed\n }\n };\n AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {\n var _this = this;\n var pendingRead;\n var finishRead = function () {\n if (_this._pendingRead === pendingRead) {\n _this._pendingRead = undefined;\n }\n };\n this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);\n };\n AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {\n var _this = this;\n if (!this._pendingRead) {\n return undefined;\n }\n var afterRead = function () { return _this._finishPendingRead(); };\n return this._pendingRead.then(afterRead, afterRead);\n };\n return AbstractWrappingReadableStreamSource;\n}());\nvar WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {\n __extends(WrappingReadableStreamDefaultSource, _super);\n function WrappingReadableStreamDefaultSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WrappingReadableStreamDefaultSource.prototype.pull = function () {\n return this._pullWithDefaultReader();\n };\n return WrappingReadableStreamDefaultSource;\n}(AbstractWrappingReadableStreamSource));\nfunction toUint8Array(view) {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\nfunction copyArrayBufferView(from, to) {\n var fromArray = toUint8Array(from);\n var toArray = toUint8Array(to);\n toArray.set(fromArray, 0);\n}\nvar WrappingReadableByteStreamSource = /** @class */ (function (_super) {\n __extends(WrappingReadableByteStreamSource, _super);\n function WrappingReadableByteStreamSource(underlyingStream) {\n var _this = this;\n var supportsByob = supportsByobReader(underlyingStream);\n _this = _super.call(this, underlyingStream) || this;\n _this._supportsByob = supportsByob;\n return _this;\n }\n Object.defineProperty(WrappingReadableByteStreamSource.prototype, \"type\", {\n get: function () {\n return 'bytes';\n },\n enumerable: false,\n configurable: true\n });\n WrappingReadableByteStreamSource.prototype._attachByobReader = function () {\n if (this._readerMode === \"byob\" /* BYOB */) {\n return;\n }\n assert(this._supportsByob);\n this._detachReader();\n var reader = this._underlyingStream.getReader({ mode: 'byob' });\n this._readerMode = \"byob\" /* BYOB */;\n this._attachReader(reader);\n };\n WrappingReadableByteStreamSource.prototype.pull = function () {\n if (this._supportsByob) {\n var byobRequest = this._readableStreamController.byobRequest;\n if (byobRequest) {\n return this._pullWithByobRequest(byobRequest);\n }\n }\n return this._pullWithDefaultReader();\n };\n WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {\n var _this = this;\n this._attachByobReader();\n // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly\n // create a separate buffer to read into, then copy that to byobRequest.view\n var buffer = new Uint8Array(byobRequest.view.byteLength);\n // TODO Backpressure?\n var read = this._underlyingReader.read(buffer)\n .then(function (result) {\n _this._readableStreamController;\n if (result.done) {\n _this._tryClose();\n byobRequest.respond(0);\n }\n else {\n copyArrayBufferView(result.value, byobRequest.view);\n byobRequest.respond(result.value.byteLength);\n }\n });\n this._setPendingRead(read);\n return read;\n };\n return WrappingReadableByteStreamSource;\n}(AbstractWrappingReadableStreamSource));\n\nfunction createWritableStreamWrapper(ctor) {\n assert(isWritableStreamConstructor(ctor));\n return function (writable) {\n if (writable.constructor === ctor) {\n return writable;\n }\n var sink = createWrappingWritableSink(writable);\n return new ctor(sink);\n };\n}\nfunction createWrappingWritableSink(writable) {\n assert(isWritableStream(writable));\n assert(writable.locked === false);\n var writer = writable.getWriter();\n return new WrappingWritableStreamSink(writer);\n}\nvar WrappingWritableStreamSink = /** @class */ (function () {\n function WrappingWritableStreamSink(underlyingWriter) {\n var _this = this;\n this._writableStreamController = undefined;\n this._pendingWrite = undefined;\n this._state = \"writable\" /* WRITABLE */;\n this._storedError = undefined;\n this._underlyingWriter = underlyingWriter;\n this._errorPromise = new Promise(function (resolve, reject) {\n _this._errorPromiseReject = reject;\n });\n this._errorPromise.catch(noop);\n }\n WrappingWritableStreamSink.prototype.start = function (controller) {\n var _this = this;\n this._writableStreamController = controller;\n this._underlyingWriter.closed\n .then(function () {\n _this._state = \"closed\" /* CLOSED */;\n })\n .catch(function (reason) { return _this._finishErroring(reason); });\n };\n WrappingWritableStreamSink.prototype.write = function (chunk) {\n var _this = this;\n var writer = this._underlyingWriter;\n // Detect past errors\n if (writer.desiredSize === null) {\n return writer.ready;\n }\n var writeRequest = writer.write(chunk);\n // Detect future errors\n writeRequest.catch(function (reason) { return _this._finishErroring(reason); });\n writer.ready.catch(function (reason) { return _this._startErroring(reason); });\n // Reject write when errored\n var write = Promise.race([writeRequest, this._errorPromise]);\n this._setPendingWrite(write);\n return write;\n };\n WrappingWritableStreamSink.prototype.close = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return this._underlyingWriter.close();\n }\n return this._finishPendingWrite().then(function () { return _this.close(); });\n };\n WrappingWritableStreamSink.prototype.abort = function (reason) {\n if (this._state === \"errored\" /* ERRORED */) {\n return undefined;\n }\n var writer = this._underlyingWriter;\n return writer.abort(reason);\n };\n WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {\n var _this = this;\n var pendingWrite;\n var finishWrite = function () {\n if (_this._pendingWrite === pendingWrite) {\n _this._pendingWrite = undefined;\n }\n };\n this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);\n };\n WrappingWritableStreamSink.prototype._finishPendingWrite = function () {\n var _this = this;\n if (this._pendingWrite === undefined) {\n return Promise.resolve();\n }\n var afterWrite = function () { return _this._finishPendingWrite(); };\n return this._pendingWrite.then(afterWrite, afterWrite);\n };\n WrappingWritableStreamSink.prototype._startErroring = function (reason) {\n var _this = this;\n if (this._state === \"writable\" /* WRITABLE */) {\n this._state = \"erroring\" /* ERRORING */;\n this._storedError = reason;\n var afterWrite = function () { return _this._finishErroring(reason); };\n if (this._pendingWrite === undefined) {\n afterWrite();\n }\n else {\n this._finishPendingWrite().then(afterWrite, afterWrite);\n }\n this._writableStreamController.error(reason);\n }\n };\n WrappingWritableStreamSink.prototype._finishErroring = function (reason) {\n if (this._state === \"writable\" /* WRITABLE */) {\n this._startErroring(reason);\n }\n if (this._state === \"erroring\" /* ERRORING */) {\n this._state = \"errored\" /* ERRORED */;\n this._errorPromiseReject(this._storedError);\n }\n };\n return WrappingWritableStreamSink;\n}());\n\nfunction createTransformStreamWrapper(ctor) {\n assert(isTransformStreamConstructor(ctor));\n return function (transform) {\n if (transform.constructor === ctor) {\n return transform;\n }\n var transformer = createWrappingTransformer(transform);\n return new ctor(transformer);\n };\n}\nfunction createWrappingTransformer(transform) {\n assert(isTransformStream(transform));\n var readable = transform.readable, writable = transform.writable;\n assert(readable.locked === false);\n assert(writable.locked === false);\n var reader = readable.getReader();\n var writer;\n try {\n writer = writable.getWriter();\n }\n catch (e) {\n reader.releaseLock(); // do not leak reader\n throw e;\n }\n return new WrappingTransformStreamTransformer(reader, writer);\n}\nvar WrappingTransformStreamTransformer = /** @class */ (function () {\n function WrappingTransformStreamTransformer(reader, writer) {\n var _this = this;\n this._transformStreamController = undefined;\n this._onRead = function (result) {\n if (result.done) {\n return;\n }\n _this._transformStreamController.enqueue(result.value);\n return _this._reader.read().then(_this._onRead);\n };\n this._onError = function (reason) {\n _this._flushReject(reason);\n _this._transformStreamController.error(reason);\n _this._reader.cancel(reason).catch(noop);\n _this._writer.abort(reason).catch(noop);\n };\n this._onTerminate = function () {\n _this._flushResolve();\n _this._transformStreamController.terminate();\n var error = new TypeError('TransformStream terminated');\n _this._writer.abort(error).catch(noop);\n };\n this._reader = reader;\n this._writer = writer;\n this._flushPromise = new Promise(function (resolve, reject) {\n _this._flushResolve = resolve;\n _this._flushReject = reject;\n });\n }\n WrappingTransformStreamTransformer.prototype.start = function (controller) {\n this._transformStreamController = controller;\n this._reader.read()\n .then(this._onRead)\n .then(this._onTerminate, this._onError);\n var readerClosed = this._reader.closed;\n if (readerClosed) {\n readerClosed\n .then(this._onTerminate, this._onError);\n }\n };\n WrappingTransformStreamTransformer.prototype.transform = function (chunk) {\n return this._writer.write(chunk);\n };\n WrappingTransformStreamTransformer.prototype.flush = function () {\n var _this = this;\n return this._writer.close()\n .then(function () { return _this._flushPromise; });\n };\n return WrappingTransformStreamTransformer;\n}());\n\nexport { createReadableStreamWrapper, createTransformStreamWrapper, createWrappingReadableSource, createWrappingTransformer, createWrappingWritableSink, createWritableStreamWrapper };\n//# sourceMappingURL=web-streams-adapter.mjs.map\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n r.strip();\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\n\n/**\n * @fileoverview\n * BigInteger implementation of basic operations\n * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)\n * @module biginteger/bn\n * @private\n */\n\n/**\n * @private\n */\nexport default class BigInteger {\n /**\n * Get a BigInteger (input must be big endian for strings and arrays)\n * @param {Number|String|Uint8Array} n - Value to convert\n * @throws {Error} on undefined input\n */\n constructor(n) {\n if (n === undefined) {\n throw new Error('Invalid BigInteger input');\n }\n\n this.value = new BN(n);\n }\n\n clone() {\n const clone = new BigInteger(null);\n this.value.copy(clone.value);\n return clone;\n }\n\n /**\n * BigInteger increment in place\n */\n iinc() {\n this.value.iadd(new BN(1));\n return this;\n }\n\n /**\n * BigInteger increment\n * @returns {BigInteger} this + 1.\n */\n inc() {\n return this.clone().iinc();\n }\n\n /**\n * BigInteger decrement in place\n */\n idec() {\n this.value.isub(new BN(1));\n return this;\n }\n\n /**\n * BigInteger decrement\n * @returns {BigInteger} this - 1.\n */\n dec() {\n return this.clone().idec();\n }\n\n\n /**\n * BigInteger addition in place\n * @param {BigInteger} x - Value to add\n */\n iadd(x) {\n this.value.iadd(x.value);\n return this;\n }\n\n /**\n * BigInteger addition\n * @param {BigInteger} x - Value to add\n * @returns {BigInteger} this + x.\n */\n add(x) {\n return this.clone().iadd(x);\n }\n\n /**\n * BigInteger subtraction in place\n * @param {BigInteger} x - Value to subtract\n */\n isub(x) {\n this.value.isub(x.value);\n return this;\n }\n\n /**\n * BigInteger subtraction\n * @param {BigInteger} x - Value to subtract\n * @returns {BigInteger} this - x.\n */\n sub(x) {\n return this.clone().isub(x);\n }\n\n /**\n * BigInteger multiplication in place\n * @param {BigInteger} x - Value to multiply\n */\n imul(x) {\n this.value.imul(x.value);\n return this;\n }\n\n /**\n * BigInteger multiplication\n * @param {BigInteger} x - Value to multiply\n * @returns {BigInteger} this * x.\n */\n mul(x) {\n return this.clone().imul(x);\n }\n\n /**\n * Compute value modulo m, in place\n * @param {BigInteger} m - Modulo\n */\n imod(m) {\n this.value = this.value.umod(m.value);\n return this;\n }\n\n /**\n * Compute value modulo m\n * @param {BigInteger} m - Modulo\n * @returns {BigInteger} this mod m.\n */\n mod(m) {\n return this.clone().imod(m);\n }\n\n /**\n * Compute modular exponentiation\n * Much faster than this.exp(e).mod(n)\n * @param {BigInteger} e - Exponent\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} this ** e mod n.\n */\n modExp(e, n) {\n // We use either Montgomery or normal reduction context\n // Montgomery requires coprime n and R (montogmery multiplier)\n // bn.js picks R as power of 2, so n must be odd\n const nred = n.isEven() ? BN.red(n.value) : BN.mont(n.value);\n const x = this.clone();\n x.value = x.value.toRed(nred).redPow(e.value).fromRed();\n return x;\n }\n\n /**\n * Compute the inverse of this value modulo n\n * Note: this and and n must be relatively prime\n * @param {BigInteger} n - Modulo\n * @returns {BigInteger} x such that this*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\n modInv(n) {\n // invm returns a wrong result if the inverse does not exist\n if (!this.gcd(n).isOne()) {\n throw new Error('Inverse does not exist');\n }\n return new BigInteger(this.value.invm(n.value));\n }\n\n /**\n * Compute greatest common divisor between this and n\n * @param {BigInteger} n - Operand\n * @returns {BigInteger} gcd\n */\n gcd(n) {\n return new BigInteger(this.value.gcd(n.value));\n }\n\n /**\n * Shift this to the left by x, in place\n * @param {BigInteger} x - Shift value\n */\n ileftShift(x) {\n this.value.ishln(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the left by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this << x.\n */\n leftShift(x) {\n return this.clone().ileftShift(x);\n }\n\n /**\n * Shift this to the right by x, in place\n * @param {BigInteger} x - Shift value\n */\n irightShift(x) {\n this.value.ishrn(x.value.toNumber());\n return this;\n }\n\n /**\n * Shift this to the right by x\n * @param {BigInteger} x - Shift value\n * @returns {BigInteger} this >> x.\n */\n rightShift(x) {\n return this.clone().irightShift(x);\n }\n\n /**\n * Whether this value is equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n equal(x) {\n return this.value.eq(x.value);\n }\n\n /**\n * Whether this value is less than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lt(x) {\n return this.value.lt(x.value);\n }\n\n /**\n * Whether this value is less than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n lte(x) {\n return this.value.lte(x.value);\n }\n\n /**\n * Whether this value is greater than x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gt(x) {\n return this.value.gt(x.value);\n }\n\n /**\n * Whether this value is greater than or equal to x\n * @param {BigInteger} x\n * @returns {Boolean}\n */\n gte(x) {\n return this.value.gte(x.value);\n }\n\n isZero() {\n return this.value.isZero();\n }\n\n isOne() {\n return this.value.eq(new BN(1));\n }\n\n isNegative() {\n return this.value.isNeg();\n }\n\n isEven() {\n return this.value.isEven();\n }\n\n abs() {\n const res = this.clone();\n res.value = res.value.abs();\n return res;\n }\n\n /**\n * Get this value as a string\n * @returns {String} this value.\n */\n toString() {\n return this.value.toString();\n }\n\n /**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\n toNumber() {\n return this.value.toNumber();\n }\n\n /**\n * Get value of i-th bit\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\n getBit(i) {\n return this.value.testn(i) ? 1 : 0;\n }\n\n /**\n * Compute bit length\n * @returns {Number} Bit length.\n */\n bitLength() {\n return this.value.bitLength();\n }\n\n /**\n * Compute byte length\n * @returns {Number} Byte length.\n */\n byteLength() {\n return this.value.byteLength();\n }\n\n /**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\n toUint8Array(endian = 'be', length) {\n return this.value.toArrayLike(Uint8Array, endian, length);\n }\n}\n","var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n","'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w) {\n var naf = [];\n var ws = 1 << (w + 1);\n var k = num.clone();\n while (k.cmpn(1) >= 0) {\n var z;\n if (k.isOdd()) {\n var mod = k.andln(ws - 1);\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n naf.push(z);\n\n // Optimization, shift by word if possible\n var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;\n for (var i = 1; i < shift; i++)\n naf.push(0);\n k.iushrn(shift);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n []\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n var m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n var m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n for (var j = 0; j < naf.length; j += doubles.step) {\n var nafW = 0;\n for (var k = j + doubles.step - 1; k >= j; k--)\n nafW = (nafW << 1) + naf[k];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (var j = 0; j < repr.length; j++) {\n var nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var k = 0; i >= 0 && naf[i] === 0; i--)\n k++;\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n for (var i = 0; i < len; i++) {\n var p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (var i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a]);\n naf[b] = getNAF(coeffs[b], wndWidth[b]);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b] /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3 /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (var j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (var i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (var j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (var j = 0; j < len; j++) {\n var z = tmp[j];\n var p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (var i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16)\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n};\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point))\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point))\n }\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate)\n }\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (var i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (var i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n // Note: this implementation is according to the original paper\n // by P. Montgomery, NOT the one by D. J. Bernstein.\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n var bytes = utils.toArray(bytes, enc);\n\n // TODO Curve448\n // Montgomery curve points must be represented in the compressed format\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (bytes.length === 33 && bytes[0] === 0x40)\n bytes = bytes.slice(1, 33).reverse(); // point must be little-endian\n if (bytes.length !== 32)\n throw new Error('Unknown point compression format');\n return this.point(bytes, 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n\n // Note: the output should always be little-endian\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n if (compact) {\n return [ 0x40 ].concat(this.getX().toArray('le', len));\n } else {\n return this.getX().toArray('be', len);\n }\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n if (this.curve.twisted) {\n // E = a * C\n var e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n var h = this.z.redSqr();\n // J = F - 2 * H\n var j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n var e = c.redAdd(d);\n // H = (c * Z1)^2\n var h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n var j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else if (options.type === 'mont')\n this.curve = new curve.mont(options);\n else throw new Error('Unknown curve type.');\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve\n });\n return curve;\n }\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'\n ]\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'\n ]\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'\n ]\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'\n ]\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650'\n ]\n});\n\n// https://tools.ietf.org/html/rfc7748#section-4.1\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9'\n ]\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n cofactor: '8',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.4\ndefineCurve('brainpoolP256r1', {\n type: 'short',\n prime: null,\n p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',\n a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',\n b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',\n n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',\n hash: hash.sha256, // or 384, or 512\n gRed: false,\n g: [\n '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',\n '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.6\ndefineCurve('brainpoolP384r1', {\n type: 'short',\n prime: null,\n p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +\n 'ACD3A729 901D1A71 87470013 3107EC53',\n a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +\n '8AA5814A 503AD4EB 04A8C7DD 22CE2826',\n b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +\n '7CB43902 95DBC994 3AB78696 FA504C11',\n n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +\n 'CF3AB6AF 6B7FC310 3B883202 E9046565',\n hash: hash.sha384, // or 512\n gRed: false,\n g: [\n '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +\n 'E8E826E03436D646AAEF87B2E247D4AF1E',\n '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +\n '280E4646217791811142820341263C5315'\n ]\n});\n\n// https://tools.ietf.org/html/rfc5639#section-3.7\ndefineCurve('brainpoolP512r1', {\n type: 'short',\n prime: null,\n p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +\n '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',\n a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +\n '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',\n b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +\n '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',\n n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +\n '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',\n hash: hash.sha512,\n gRed: false,\n g: [\n '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +\n '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',\n '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +\n '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'\n ]\n});\n\n// https://en.bitcoin.it/wiki/Secp256k1\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre\n ]\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc\n });\n};\n\n// TODO: should not validate for X25519\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // For Curve25519/Curve448 we have a specific procedure.\n // TODO Curve448\n if (this.ec.curve.type === 'mont') {\n var one = this.ec.curve.one;\n var mask = one.ushln(255 - 3).sub(one).ushln(3);\n this.priv = this.priv.or(one.ushln(255 - 1));\n this.priv = this.priv.and(mask);\n } else\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n }\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0 && (r[1] & 0x80)) {\n r = r.slice(1);\n }\n if (s[0] === 0 && (s[1] & 0x80)) {\n s = s.slice(1);\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray()\n });\n\n // Key generation for curve25519 is simpler\n if (this.curve.type === 'mont') {\n var priv = new BN(drbg.generate(32));\n return this.keyFromPrivate(priv);\n }\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n do {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n } while (true);\n};\n\nEC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {\n bitSize = bitSize || msg.byteLength() * 8;\n var delta = bitSize - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.truncateMsg = function truncateMSG(msg) {\n // Bit size is only determined correctly for Uint8Arrays and hex strings\n var bitSize;\n if (msg instanceof Uint8Array) {\n bitSize = msg.byteLength * 8;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else if (typeof msg === 'string') {\n bitSize = msg.length * 4;\n msg = this._truncateToN(new BN(msg, 16), false, bitSize);\n } else {\n msg = this._truncateToN(new BN(msg, 16));\n }\n return msg;\n}\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this.truncateMsg(msg);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8'\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; true; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n // Fallback to the old code\n var ret = this._verify(this.truncateMsg(msg), signature, key) ||\n this._verify(this._truncateToN(new BN(msg, 16)), signature, key);\n return ret;\n};\n\nEC.prototype._verify = function _verify(msg, signature, key) {\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n\n if (!this.curve._maxwellTrick) {\n var p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n var p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n if (params.hasOwnProperty('secret'))\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else {\n this._pubBytes = parseBytes(params.pub);\n if (this._pubBytes && this._pubBytes.length === 33 &&\n this._pubBytes[0] === 0x40)\n this._pubBytes = this._pubBytes.slice(1, 33);\n if (this._pubBytes && this._pubBytes.length !== 32)\n throw new Error('Unknown point compression format');\n }\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n // https://tools.ietf.org/html/rfc8032#section-5.1.5\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc, compact) {\n return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength)\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar HmacDRBG = require('hmac-drbg');\nvar rand = require('brorand');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n var curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.curve.n.toArray()\n });\n\n return this.keyFromSecret(drbg.generate(32));\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","this","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","prototype","undefined","read","async","length","value","done","readToEnd","join","result","slice","clone","then","push","write","chunk","close","abort","reason","isNode","globalThis","process","versions","NodeReadableStream","isStream","ReadableStream","isPrototypeOf","streams.ReadableStream","isUint8Array","Uint8Array","concatUint8Array","arrays","totalLength","i","Error","pos","forEach","element","set","NodeBuffer","nodeToWeb","webToNode","nodeStream","canceled","start","controller","pause","on","isBuffer","buffer","byteOffset","byteLength","enqueue","e","error","pull","resume","cancel","destroy","NodeReadable","webStream","options","_reader","streams.getReader","size","callback","doneReadingSet","WeakSet","externalBuffer","Reader","streams.isArrayStream","reader","_read","bind","_releaseLock","_cancel","streamType","streams.isStream","streams.nodeToWeb","doneReading","has","add","shift","readLine","returnVal","streams.concat","lineEndIndex","indexOf","concat","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","filter","toPonyfillReadable","toNativeReadable","WritableStream","TransformStream","loadStreamsPonyfill","ponyfill","adapter","all","createReadableStreamWrapper","toStream","toArrayStream","list","some","map","transform","transformWithCancel","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","transformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","highWaterMark","finish","output","data","result1","result2","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","Object","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","arrayStream","BigInteger","n","hex","hexByte","toString","BigInt","iinc","inc","idec","dec","iadd","x","isub","sub","imul","mul","imod","m","isNegative","mod","modExp","isZero","isOne","exp","r","lsb","rx","modInv","gcd","_egcd","b","y","xPrev","yPrev","a","q","tmp","ileftShift","leftShift","irightShift","rightShift","equal","lt","lte","gt","gte","isEven","abs","res","toNumber","number","Number","MAX_SAFE_INTEGER","getBit","bitLength","zero","one","negOne","bitlen","eight","len","toUint8Array","endian","rawLength","offset","parseInt","reverse","detectBigInt","byValue","curve","p256","secp256r1","prime256v1","p384","secp384r1","p521","secp521r1","secp256k1","ed25519Legacy","ED25519","ed25519","Ed25519","curve25519Legacy","X25519","cv25519","curve25519","Curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","eddsa","aedh","aedsa","x25519","x448","ed448","symmetric","plaintext","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","webHash","aead","eax","ocb","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuer","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","type","debugMode","env","NODE_ENV","util","isString","String","stream.isUint8Array","stream.isStream","readNumber","writeNumber","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","leftPad","padded","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","k","uint8ArrayToHex","h","c","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","s","printDebug","log","printDebugError","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","crypto","subtle","getBigInteger","default","getNodeCrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","selectUint8","isAES","cipherAlgo","enums","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","from","btoa","atob","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","deflateLevel","aeadProtect","preferredAEADAlgorithm","aeadChunkSizeByte","s2kIterationCountByte","allowUnauthenticatedMessages","allowUnauthenticatedStream","checksumRequired","minRSABits","passwordCollisionCheck","revocationsExpire","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","minBytesForWebCrypto","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","useIndutnyElliptic","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","getType","header","match","addheader","customComment","config","getCheckSum","base64.encode","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","splitChecksum","body","checksum","lastEquals","lastIndexOf","unarmor","defaultConfig","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","checksumVerified","stream.readToEnd","stream.passiveClone","stream.pipe","checksumVerifiedString","stream.isArrayStream","messageType","partIndex","partTotal","bodyClone","KeyID","toHex","equals","keyID","matchWildcard","isWildcard","isNull","static","AES_asm","gexp3","glog3","ginit_done","gmul","aes_sbox","aes_sinv","aes_enc","aes_dec","aes_init_done","aes_init","_s","ginv","d","ginit","wrapper","foreign","heap","asm","stdlib","S0","S1","S2","S3","I0","I1","I2","I3","N0","N1","N2","N3","M0","M1","M2","M3","H0","H1","H2","H3","R","HEAP","DATA","_core","x0","x1","x2","x3","t1","t2","t3","y0","y1","y2","y3","_ecb_enc","_ecb_dec","_cbc_enc","_cbc_dec","_cfb_enc","_cfb_dec","_ofb","_ctr","_gcm_mac","z0","z1","z2","z3","set_rounds","set_state","s0","s1","s2","s3","set_iv","i0","i1","i2","i3","set_nonce","n0","n1","n2","n3","set_mask","m0","m1","m2","m3","set_counter","c0","c1","c2","c3","get_state","get_iv","gcm_init","cipher","mode","ret","_cipher_modes","mac","_mac_modes","set_key","ks","k0","k1","k2","k3","k4","k5","k6","k7","ekeys","dkeys","rcon","jj","ENC","ECB","CBC","CFB","OFB","CTR","DEC","MAC","GCM","HEAP_DATA","is_bytes","_heap_init","heapSize","_heap_write","hpos","dpos","dlen","hlen","wlen","joinBytes","arg","totalLenght","reduce","sum","curr","cursor","IllegalStateError","args","IllegalArgumentError","SecurityError","heap_pool","asm_pool","AES","iv","padding","acquire_asm","pop","reset","release_asm","keylen","keyview","getUint32","ivview","AES_Encrypt_process","TypeError","amode","rpos","AES_Encrypt_finish","plen","rlen","hasOwnProperty","p","AES_Decrypt_process","AES_Decrypt_finish","pad","pcheck","AES_ECB","encrypt","decrypt","aes","C","aesECB","block","blockSize","keySize","des","keys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","left","right","looping","cbcleft","cbcleft2","cbcright","cbcright2","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","src","dst","l","f1","f2","f3","scheduleA","scheduleB","I","sBox","inn","w","ki","half","round","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","u","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","init","encryptBlock","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","_F","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","ii","dataL","dataR","parray","vector","off","_decryptBlock","kk","sha1_asm","H4","TOTAL0","TOTAL1","I4","O0","O1","O2","O3","O4","w0","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32","w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61","w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","_core_heap","_state_to_heap","h0","h1","h2","h3","h4","total0","total1","hashed","hmac_reset","_hmac_opad","hmac_init","p0","p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","hmac_finish","t0","t4","pbkdf2_generate_block","count","Hash","HASH_SIZE","Sha1","NAME","BLOCK_SIZE","asm_function","Sha256","H5","H6","H7","I5","I6","I7","O5","O6","O7","f","g","h5","h6","h7","t5","t6","t7","sha256_asm","assert","val","msg","module","create","ctor","superCtor","super_","enumerable","configurable","TempCtor","enc","hi","lo","zero2","htonl","zero8","word","inherits","ah","al","bh","bl","ch","cl","dh","dl","carry","eh","el","num","BlockHash","pending","pendingTotal","outSize","hmacStrength","_delta8","_delta32","update","utils","toArray","join32","_update","digest","_pad","_digest","rotr32","z","ch32","p32","maj32","sum32","sum32_4","sum32_5","shaCommon","s0_256","s1_256","g0_256","g1_256","common","sha256_K","SHA256","W","SHA224","T1","T2","toHex32","split32","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","SHA512","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","SHA384","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotl32","sum32_3","RIPEMD160","K","Kh","A","B","D","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","md5cycle","ff","gg","add32","cmn","md5blk","md5blks","hex_chr","rhex","webCrypto","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","hashjsHash","webCryptoHash","hashInstance","asmcryptoHash","hashFunctions","entree","state","substring","tail","md51","ripemd160","algo","getHashByteLength","AES_CFB","getCipher","algoName","knownAlgos","getCiphers","nodeAlgos","pt","cipherObj","createCipheriv","nodeEncrypt","ALGO","_key","importKey","cbc_pt","ct","xorMut","webEncrypt","cfb","aesEncrypt","cipherfn","block_size","blockc","ciphertext","encblock","decipherObj","createDecipheriv","nodeDecrypt","aesDecrypt","blockp","decblock","AES_CTR","nonce","AES_CTR_set_options","counter","mask","pow","view","AES_CBC","blockLength","rightXORMut","zeroBlock","CMAC","cbc","padding2","ivLength","tagLength","two","OMAC","cmac","en","final","EAX","omac","ctr","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","xor","OCB","encipher","decipher","maxNtz","crypt","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","xorInput","$","cipherInput","cipherName","ciphers","mask_x","mask_$","constructKeyVariables","crypted","_AES_GCM_data_maxLength","AES_GCM","tagSize","gamma0","noncelen","noncebuf","_gcm_mac_process","nonceview","RangeError","cleartext","tagsize","AES_GCM_encrypt","AES_GCM_decrypt","AES_GCM_Encrypt_process","AES_GCM_Encrypt_finish","alen","clen","AES_GCM_Decrypt_process","tlen","AES_GCM_Decrypt_finish","atag","acheck","setAAD","getAuthTag","de","setAuthTag","additionalData","gcm","nacl","gf","Float64Array","randombytes","_9","gf0","gf1","_121665","D2","X","Y","crypto_verify_32","xi","yi","vn","set25519","car25519","o","v","sel25519","pack25519","neq25519","par25519","unpack25519","Z","M","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","x32","x16","crypto_scalarmult_base","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","cleanup","arr","scalarMult","box","keyPair","fromSecretKey","sign","signedMsg","sm","smlen","crypto_sign","detached","sig","verify","crypto_sign_open","fromSeed","seed","setPRNG","self","msCrypto","getRandomValues","min","require","randomBytes","exports","getRandomBytes","getRandomBigInteger","modulus","randomProbablePrime","thirty","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","rand","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","emLen","hashPrefix","tLen","fill","EM","asn1","RSAPrivateKey","define","seq","obj","int","RSAPublicKey","hashAlgo","hashName","jwk","pNum","qNum","dNum","dq","dp","kty","qi","ext","privateToJWK","webSign","err","BN","pBNum","qBNum","dBNum","subn","createSign","keyObject","version","publicExponent","privateExponent","prime1","prime2","exponent1","exponent2","coefficient","createPrivateKey","der","format","pem","label","nodeSign","bnSign","publicToJWK","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","constants","RSA_PKCS1_PADDING","publicEncrypt","bnEncrypt","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","keyGenOpt","modulusLength","generateKey","exportKey","generateKeyPair","opts","publicKeyEncoding","privateKeyEncoding","prv","_","toArrayLike","phi","nSizeOver3","rde","pSize","n1023","threshold","rqx","OID","oid","getName","keyFromPrivate","indutnyCurve","priv","keyFromPublic","pub","validate","getIndutnyCurve","elliptic","ec","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","stream.TransformStream","lengthByte","nextPacket","UnsupportedError","params","captureStackTrace","UnparseablePacket","rawContent","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","CurveWithOID","oidOrName","webCryptoKey","namedCurve","jwkToRawPublic","webGenKeyPair","createECDH","generateKeys","getPublicKey","getPrivateKey","nodeGenKeyPair","genKeyPair","entropy","getPublic","getPrivate","validateStandardParams","Q","supportedCurves","curveName","dG","validationErrors","eq","bufX","bufY","rawPublicToJWK","crv","ECPrivateKey","parameters","unused","ECDSASignature","ellipticSign","SubjectPublicKeyInfo","algorithm","subjectPublicKey","ellipticVerify","octstr","explicit","optional","any","bitstr","AlgorithmIdentifier","objid","use","getPreferredHashAlgo","RS","wrap","IV","P","unpack","unwrap","createArrayBuffer","setUint32","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","genPrivateEphemeralKey","recipient","deriveBits","public","webPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","V","derive","ellipticPublicEphemeralKey","secret","webPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","ellipticPrivateEphemeralKey","pkcs5.encode","wrappedKey","aesKW.wrap","pkcs5.decode","aesKW.unwrap","nodeSubtleCrypto","webcrypto","HKDF","inputKey","salt","info","outLen","importedKey","hashAlgoName","computeHMAC","hmacKey","hmacMessage","createHmac","pseudoRandomKey","hashLen","outputKeyingMaterial","roundInput","HKDF_INFO","recipientA","ephemeralSecretKey","sharedSecret","ephemeralPublicKey","hkdfInput","computeHKDF","xr","u1","u2","qSize","n150","rsa","publicParams","curveSize","publicKeyParams","privateKeyParams","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","instance","followLength","checkSupportedCurve","keyAlgo","symmetricAlgo","ECDHSymkey","ecdhX","fromObject","sessionKeyParams","privateParams","algosWithNativeRepresentation","orderedParams","generate","validateParams","algoModule","prefixrandom","repeat","random","pkcs1","pkcs5","aesKW","assign","TYPED_OK","Uint16Array","Int32Array","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","fnUntyped","Buf8","Buf16","Buf32","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","STORED_BLOCK","STATIC_TREES","DYN_TREES","LENGTH_CODES","LITERALS","L_CODES","D_CODES","BL_CODES","HEAP_SIZE","MAX_BITS","Buf_size","MAX_BL_BITS","END_BLOCK","REP_3_6","REPZ_3_10","REPZ_11_138","extra_lbits","extra_dbits","extra_blbits","bl_order","static_ltree","static_dtree","_dist_code","_length_code","MAX_MATCH","base_length","base_dist","StaticTreeDesc","static_tree","extra_bits","extra_base","elems","max_length","has_stree","static_l_desc","static_d_desc","static_bl_desc","TreeDesc","dyn_tree","stat_desc","max_code","d_code","dist","put_short","pending_buf","send_bits","bi_valid","bi_buf","send_code","tree","bi_reverse","code","gen_codes","bl_count","next_code","init_block","dyn_ltree","dyn_dtree","bl_tree","opt_len","static_len","last_lit","matches","bi_windup","smaller","depth","_n2","_m2","pqdownheap","heap_len","compress_block","ltree","dtree","lc","extra","lx","d_buf","l_buf","build_tree","desc","stree","heap_max","base","xbits","overflow","gen_bitlen","scan_tree","curlen","prevlen","nextlen","max_count","min_count","send_tree","static_init_done","_tr_init","tr_static_init","l_desc","d_desc","bl_desc","_tr_stored_block","stored_len","utils.arraySet","window","copy_block","_tr_align","bi_flush","_tr_flush_block","opt_lenb","static_lenb","max_blindex","level","strm","data_type","black_mask","detect_data_type","build_bl_tree","strategy","lcodes","dcodes","blcodes","rank","send_all_trees","_tr_tally","lit_bufsize","adler32","adler","crcTable","table","makeTable","crc32","MAX_MEM_LEVEL","MIN_MATCH","MIN_LOOKAHEAD","PRESET_DICT","INIT_STATE","EXTRA_STATE","NAME_STATE","COMMENT_STATE","HCRC_STATE","BUSY_STATE","FINISH_STATE","BS_NEED_MORE","BS_BLOCK_DONE","BS_FINISH_STARTED","BS_FINISH_DONE","OS_CODE","errorCode","flush_pending","avail_out","pending_out","next_out","total_out","flush_block_only","trees._tr_flush_block","block_start","strstart","put_byte","putShortMSB","read_buf","avail_in","next_in","total_in","longest_match","cur_match","chain_length","max_chain_length","scan","best_len","prev_length","nice_match","limit","w_size","_win","wmask","w_mask","strend","scan_end1","scan_end","good_match","lookahead","match_start","fill_window","_w_size","more","window_size","hash_size","head","insert","ins_h","hash_shift","hash_mask","deflate_fast","flush","hash_head","bflush","match_length","trees._tr_tally","max_lazy_match","deflate_slow","max_insert","prev_match","match_available","Config","good_length","max_lazy","nice_length","max_chain","func","configuration_table","max_block_size","pending_buf_size","max_start","DeflateState","status","gzhead","gzindex","method","last_flush","w_bits","hash_bits","utils.Buf16","deflateReset","trees._tr_init","deflateResetKeep","lm_init","deflate","old_flush","beg","hcrc","comment","os","level_flags","bstate","deflate_huff","deflate_rle","trees._tr_align","trees._tr_stored_block","__","_utf8len","utils.Buf8","string2buf","m_pos","buf_len","str_len","ZStream","Deflate","chunkSize","windowBits","memLevel","opt","raw","gzip","ended","zlib_deflate.deflateInit2","dictionary","dict","strings.string2buf","avail","next","tmpDict","dictLength","zlib_deflate.deflateSetDictionary","_dict_set","_mode","zlib_deflate.deflate","onEnd","onData","utils.shrinkBuf","zlib_deflate.deflateEnd","utils.flattenChunks","BAD","TYPE","inflate_fast","_in","_out","hold","here","op","from_source","dmax","wsize","whave","wnext","s_window","lcode","lencode","dcode","distcode","lmask","lenbits","dmask","distbits","top","dolen","dodist","sane","MAXBITS","ENOUGH_LENS","ENOUGH_DISTS","CODES","LENS","DISTS","lbase","lext","dbase","dext","inflate_table","lens","lens_index","codes","table_index","work","incr","low","sym","root","drop","used","huff","base_index","offs","here_bits","here_op","here_val","extra_index","HEAD","FLAGS","TIME","OS","EXLEN","EXTRA","COMMENT","HCRC","DICTID","DICT","TYPEDO","STORED","COPY_","COPY","TABLE","LENLENS","CODELENS","LEN_","LEN","LENEXT","DIST","DISTEXT","MATCH","LIT","CHECK","LENGTH","DONE","zswap32","InflateState","havedict","flags","check","total","wbits","ncode","nlen","ndist","have","lendyn","distdyn","back","was","inflateReset","utils.Buf32","inflateResetKeep","inflateInit2","inflateReset2","lenfix","distfix","virgin","fixedtables","updatewindow","copy","inflate","put","last_bits","last_op","last_val","hbuf","order","inf_leave","xflags","extra_len","inflateSetDictionary","dictid","GZheader","Inflate","zlib_inflate.inflateInit2","c.Z_OK","zlib_inflate.inflateGetHeader","zlib_inflate.inflateSetDictionary","allowBufError","c.Z_FINISH","c.Z_NO_FLUSH","strings.binstring2buf","zlib_inflate.inflate","c.Z_NEED_DICT","c.Z_BUF_ERROR","c.Z_STREAM_END","c.Z_SYNC_FLUSH","zlib_inflate.inflateEnd","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","remaining","seek","n_bit","n_byte","pi","bufToHex","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","getCRC","updateCRC","updateCRCRun","mtf","Err","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","optDetail","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","CRC32","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","groups","minLen","maxLen","MAX_HUFCODE_BITS","permute","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","outputBuffer","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","multistream","bz","targetStreamCRC","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","verified","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","issuerKeyID","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","writeHashedSubPackets","toHash","stream.slice","stream.clone","writeSubPacket","humanReadable","critical","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","fromBinary","compressionFn","compress_fns","nodeZlib","node_zlib","stream.nodeToWeb","stream.webToNode","pako_zlib","deflateRaw","createDeflateRaw","createDeflate","inflateRaw","createInflateRaw","createInflate","BunzipDecode","SymEncryptedIntegrityProtectedDataPacket","encrypted","sessionKeyAlgorithm","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","AEADEncryptedDataPacket","cipherAlgorithm","aeadAlgorithm","chunkSizeByte","getAEADMode","modeInstance","tagLengthIfDecrypting","tagLengthIfEncrypting","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","latestPromise","cryptedBytes","queuedBytes","finalChunk","cryptedPromise","setInt32","desiredSize","PublicKeyEncryptedSessionKeyPacket","publicKeyID","sessionKey","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","sessionKeyData","S2K","getCount","passphrase","numBytes","rlength","prefixlen","datalen","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","produceKey","encryptionKey","generateSessionKey","associatedData","toEncrypt","PublicKeyPacket","expirationTimeV3","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","startOfSecretKeyData","unparseableKeyMaterial","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","produceEncryptionKey","cleartextWithHash","validParams","generateParams","global","parse5322","inStr","getPos","setPos","initialize","parseString","tokens","semantic","children","ast","parent","child","compareToken","fxnCompare","tok","lit","and","or","prod","invis","colwsp","star","minimum","isUTF8NonAscii","cr","crlf","lf","dquote","htab","sp","vchar","accept","rfc6532","wsp","quotedPair","obsQP","fws","obsFws","ctext","obsCtext","ccontent","cfws","atext","atom","dotAtomText","maybeText","dotAtom","qtext","obsQtext","qcontent","quotedString","address","mailbox","group","nameAddr","addrSpec","displayName","angleAddr","obsAngleAddr","groupList","obsPhrase","collapseWhitespace","mailboxList","obsMboxList","addressList","obsAddrList","obsGroupList","localPart","obsLocalPart","dtext","obsDtext","domainLiteral","domain","obsDomain","rejectTLD","obsNoWsCtl","strict","atInDisplayName","obsRoute","obsDomainList","findNode","stack","findAllNodesNoChildren","names","namesLookup","giveResult","addresses","groupsAndMailboxes","groupOrMailbox","giveResultGroup","giveResultMailbox","simplifyResult","oneResult","partial","groupName","groupResultMailboxes","mailboxes","grabSemantic","aspec","findAllNodes","comments","local","concatComments","startProduction","handleOpts","startAt","defs","isNullUndef","defaults","isObject","parseOneAddress","parseAddressList","parseFrom","parseSender","parseReplyTo","UserIDPacket","email","components","emailAddresses","otherUserID","SecretSubkeyPacket","TrustPacket","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","prefAlgo","primaryUser","getPrimaryUser","selfCertification","getPreferredCurveHashAlgo","getPreferredAlgo","userIDs","defaultAlgo","preferredSenderAlgo","prefPropertyName","senderAlgoSupport","recipientPrefs","Boolean","signingKeyPacket","signaturePacket","mergeSignatures","source","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","sanitizeKeyOptions","subkeyDefaults","isValidSigningKeyPacket","isValidEncryptionKeyPacket","isValidDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","signingKeys","isPrivate","signingKey","getSigningKey","certificate","verificationKeys","issuerKeys","getKeys","isRevoked","certifications","certification","valid","verifyCertificate","sourceUser","srcSelfSig","srcRevSig","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","sort","helper.isValidSigningKeyPacket","helper.checkKeyRequirements","helper.isValidEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","revocationCertificate","privateKeys","userSign","certify","verifyAllCertifications","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","fromSecretKeyPacket","pubSubkeyPacket","fromSecretSubkeyPacket","helper.isValidDecryptionKeyPacket","allDummies","defaultOptions","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","readPrivateKey","readKeys","armoredKeys","binaryKeys","keyIndex","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","sessionKeyObjects","decryptSessionKeys","symEncryptedPacketlist","symEncryptedPacket","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","password","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","getDecryptionKeys","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgorithmName","supported","isAEADSupported","getEncryptionKey","maybeKey","wildcard","encryptionKeyIDs","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","literalDataPacket","existingSigPacketlist","onePassSig","signingKeyID","onePassSignatureList","createSignaturePackets","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","detachedSignature","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","stream.loadStreamsPonyfill","stream.toStream","createMessage","literalDataPacketlist","CleartextMessage","newSignature","hashes","ar","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","oneHeader","createCleartextMessage","checkConfig","helper.generateSecretKey","getRevocationCertificate","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","applyRevocationCertificate","revoke","decryptKey","clonedPrivateKey","passphrases","encryptKey","signingUserIDs","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","streaming","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","signDetached","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","encoding","setEncoding","stream.toNativeReadable","object","SymbolPolyfill","iterator","description","noop","globals","typeIsObject","rethrowAssertionErrorRejection","originalPromise","originalPromiseThen","originalPromiseResolve","originalPromiseReject","newPromise","executor","promiseResolvedWith","promiseRejectedWith","PerformPromiseThen","onFulfilled","onRejected","uponPromise","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","queueMicrotask","globalQueueMicrotask","resolvedPromise","reflectCall","F","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","peek","front","ReadableStreamReaderGenericInitialize","_ownerReadableStream","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","AbortSteps","ErrorSteps","CancelSteps","PullSteps","NumberIsFinite","isFinite","MathTrunc","trunc","assertDictionary","context","assertFunction","assertObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","defaultReaderBrandCheckException","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","_disturbed","_readableStreamController","AsyncIteratorPrototype","defineProperties","toStringTag","asyncIterator","ReadableStreamAsyncIteratorImpl","_ongoingPromise","_isFinished","_preventCancel","nextSteps","_nextSteps","return","returnSteps","_returnSteps","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","IsFiniteNonNegativeNumber","IsNonNegativeNumber","DequeueValue","container","pair","_queue","_queueTotalSize","EnqueueValueWithSize","ResetQueue","CreateArrayFromList","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespond","respondWithNewView","isView","firstDescriptor","_pendingPullIntos","bytesFilled","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","_byobRequest","request","SetUpReadableStreamBYOBRequest","ReadableByteStreamControllerGetDesiredSize","_closeRequested","_controlledReadableByteStream","ReadableByteStreamControllerError","ReadableByteStreamControllerClearAlgorithms","ReadableStreamClose","ReadableByteStreamControllerClose","transferredBuffer","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableStreamHasBYOBReader","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerCallPullIfNeeded","ReadableByteStreamControllerEnqueue","_cancelAlgorithm","entry","ReadableByteStreamControllerHandleQueueDrain","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","elementSize","viewConstructor","readerType","shouldPull","_started","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","currentAlignedBytes","maxBytesToCopy","maxBytesFilled","maxAlignedBytes","totalBytesToCopyRemaining","queue","headOfQueue","bytesToCopy","destStart","destOffset","srcOffset","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","ReadableByteStreamControllerClearPendingPullIntos","ReadableStreamError","_strategyHWM","SetUpReadableByteStreamControllerFromUnderlyingSource","underlyingByteSource","startAlgorithm","pullAlgorithm","cancelAlgorithm","SetUpReadableByteStreamController","ReadableStreamAddReadIntoRequest","IsReadableStreamBYOBReader","ReadableStreamBYOBReader","byobReaderBrandCheckException","BYTES_PER_ELEMENT","emptyView","ReadableByteStreamControllerPullInto","ReadableStreamBYOBReaderRead","ExtractHighWaterMark","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException$2","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","NativeDOMException","DOMException","DOMException$1","_a","isDOMExceptionConstructor","createDOMExceptionPolyfill","ReadableStreamPipeTo","signal","shuttingDown","currentWrite","actions","shutdownWithAction","action","aborted","addEventListener","isOrBecomesErrored","shutdown","isOrBecomesClosed","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","defaultControllerBrandCheckException$1","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertReadableStreamReaderMode","convertPipeOptions","isAbortSignal","assertAbortSignal","rawUnderlyingSource","underlyingSource","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","SetUpReadableStreamDefaultControllerFromUnderlyingSource","streamBrandCheckException$1","rawOptions","convertReaderOptions","AcquireReadableStreamBYOBReader","pipeThrough","rawTransform","convertReadableWritablePair","destination","branches","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","canceled1","canceled2","cancelPromise","value1","value2","CreateReadableStream","compositeReason","cancelResult","ReadableStreamTee","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","TransformStreamError","TransformStreamDefaultSinkAbortAlgorithm","_readable","flushPromise","_flushAlgorithm","TransformStreamDefaultControllerClearAlgorithms","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamErrorWritableAndUnblockWrite","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","flushAlgorithm","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","streamBrandCheckException","IsTransformStreamDefaultController","defaultControllerBrandCheckException","readableController","TransformStreamDefaultControllerTerminate","ReadableStreamDefaultControllerHasBackpressure","extendStatics","__proto__","__extends","isStreamConstructor","startCalled","isReadableStream","isWritableStream","isTransformStream","supportsByobReader","createWrappingReadableSource","parseReadableType","WrappingReadableByteStreamSource","WrappingReadableStreamDefaultSource","typeString","AbstractWrappingReadableStreamSource","underlyingStream","_underlyingReader","_readerMode","_pendingRead","_underlyingStream","_attachDefaultReader","_detachReader","_attachReader","_this","_finishPendingRead","_pullWithDefaultReader","_tryClose","_setPendingRead","readPromise","pendingRead","finishRead","afterRead","_super","supportsByob","_supportsByob","_attachByobReader","_pullWithByobRequest","to","fromArray","createWrappingWritableSink","WrappingWritableStreamSink","underlyingWriter","_pendingWrite","_underlyingWriter","_errorPromise","_errorPromiseReject","_finishErroring","_startErroring","race","_setPendingWrite","_finishPendingWrite","writePromise","pendingWrite","finishWrite","afterWrite","createWrappingTransformer","WrappingTransformStreamTransformer","_onRead","_onError","_flushReject","_onTerminate","_flushResolve","_flushPromise","readerClosed","isReadableStreamConstructor","byteSourceSupported","supportsByteSource","isTransformStreamConstructor","isWritableStreamConstructor","sink","isBN","negative","words","red","_init","wordSize","parseHex","parseBase","cmp","_initNumber","_initArray","_parseHex","_parseBase","strip","limbLen","limbPow","imuln","_iaddn","_expand","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","out","ncarry","rword","maxJ","groupSize","groupBase","modn","idivn","toJSON","toBuffer","ArrayType","reqLength","littleEndian","andln","iushrn","_countBits","clz32","_zeroBits","zeroBits","toTwos","width","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","uor","iuand","iand","uand","iuxor","ixor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","comb10MulTo","mid","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","bl0","bh0","bl1","bh1","bl2","bh2","bl3","bh3","bl4","bh4","bl5","bh5","bl6","bh6","bl7","bh7","bl8","bh8","bl9","bh9","jumboMulTo","FFTM","mulp","mulTo","hncarry","bigMulTo","makeRBT","N","revBin","rb","rbt","rws","iws","rtws","itws","rtwdf","cos","PI","itwdf","sin","rtwdf_","itwdf_","re","ie","ro","io","guessLen13b","odd","conjugate","normalize13b","ws","convert13b","stub","ph","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","carryMask","newCarry","ishln","hint","extended","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","iabs","_ishlnsubmul","_wordDiv","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","r2","acc","egcd","yp","xp","im","isOdd","jm","_invmp","delta","cmpn","invm","bincn","ucmp","gtn","gten","ltn","lten","eqn","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","rinv","minv","ireduce","imulK","mod3","nOne","lpow","inv","wnd","currentLen","mont","nred","minAssert","minUtils","getNAF","naf","getJSF","jsf","d1","d2","m8","m14","m24","cachedProperty","computer","parseBytes","intFromLE","Rand","_rand","getByte","BaseCurve","conf","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","adjustCount","redN","_maxwellTrick","BasePoint","precomputed","point","_fixedNafMul","doubles","_getDoubles","step","repr","nafW","jpoint","mixedAdd","points","toP","_wnafMul","nafPoints","_getNAFPoints","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","comb","toJ","ja","jb","decodePoint","pointFromX","encodeCompressed","_encode","compact","getX","getY","precompute","beta","_getBeta","_hasDoubles","dbl","ShortCurve","Base","tinv","zeroA","threeA","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","Point","isRed","inf","JPoint","zOne","MontCurve","i4","a24","lambda","betas","_getEndoRoots","lambdas","basis","vec","_getEndoBasis","ntinv","prevR","aprxSqrt","len1","_endoSplit","v1","v2","ax","rhs","_endoWnafMulAdd","npoints","ncoeffs","fromJSON","pre","endoMul","JSON","obj2point","isInfinity","nx","ny","ys1","dyinv","mulAdd","jmulAdd","_precompute","negate","zinv","zinv2","ay","pz2","nz","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","dny","_zeroDbl","_threeDbl","_dbl","yyyy","yyyy8","c8","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","pz3","eqXToP","zs","xc","normalize","diffAdd","da","cb","jumlAdd","EdwardsCurve","twisted","mOneA","oneC","_mulA","_mulC","lhs","pointFromY","_extDbl","nt","_projDbl","_extAdd","_projAdd","require$$0","short","require$$1","require$$2","edwards","require$$3","ft_1","sha1_K","SHA1","require$$4","Hmac","inner","outer","sha","hmac","PresetCurve","defineCurve","cofactor","HmacDRBG","predResist","minEntropy","_reseed","reseedInterval","entropyEnc","nonceEnc","pers","persEnc","_hmac","kmac","reseed","addEnc","KeyPair","_importPrivate","privEnc","_importPublic","pubEnc","fromPublic","fromPrivate","_importDER","recoveryParam","Position","place","getLength","initial","octetLen","rmPadding","constructLength","octets","slen","toDER","backHalf","EC","nh","drbg","ns2","_truncateToN","truncOnly","truncateMsg","bkey","ns1","iter","kp","kpX","canonical","_verify","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Qprime","_secret","isPoint","_pub","_pubBytes","fromSecret","encodePoint","lastIx","encodingLength","decodeInt","privBytes","getSecret","pubBytes","_R","_S","_Rencoded","Rencoded","_Sencoded","Sencoded","encodeInt","toBytes","EDDSA","pointClass","keyFromSecret","hashInt","messagePrefix","s_","makeSignature","SG","normed","xIsOdd","require$$5"],"mappings":";6GAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxBC,cACEC,QACAC,KAAKT,GAAsB,IAAIU,SAAQ,CAACC,EAASC,KAC/CH,KAAKP,GAAsBS,EAC3BF,KAAKN,GAAqBS,CAAM,IAElCH,KAAKT,GAAoBa,OAAM,UAuCnC,SAASC,EAAcC,GACrB,OAAOA,GAASA,EAAMC,WAAaV,MAAMW,QAAQF,EACnD,CAOA,SAASG,EAAOH,GACd,IAAKD,EAAcC,GAAQ,CACzB,MAAMI,EAASJ,EAAMK,YACfC,EAAcF,EAAOE,YAK3B,OAJAF,EAAOE,YAAc,KACnBF,EAAOG,OAAOT,OAAM,eACpBQ,EAAYE,KAAKJ,EAAO,EAEnBA,EAETV,KAAKe,OAAST,CAChB,CAvDAV,EAAYoB,UAAUT,UAAY,WAIhC,YAH2BU,IAAvBjB,KAAKL,KACPK,KAAKL,GAAgB,GAEhB,CACLuB,KAAMC,gBACEnB,KAAKT,GACPS,KAAKL,KAAkBK,KAAKoB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,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAINrC,IAAK,CACHP,IAAK,EACL4C,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,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vH,EAAIw5B,GAAMwnF,UAAUmQ,GACxB,OAAOr/H,KAAKwQ,MAAMmoH,WAAWzqH,EAAGoxH,EAClC,EAEAT,GAAM79H,UAAU29H,UAAY,SAAmB13F,GAC7C,OAAOA,EAAIU,QAAQ,KAAM3nC,KAAKg+H,eAChC,EAEAa,GAAM79H,UAAUi9H,UAAY,SAAmB/2H,GAC7C,OAAOwgC,GAAMwnF,UAAUhoH,EACzB,EAEA23H,GAAM79H,UAAU08H,QAAU,SAAiBt4F,GACzC,OAAOA,aAAeplC,KAAK8+H,UAC7B,2BC1IA,IAAIt5E,EAAWxH,EAEfwH,EAAS9d,MAAQuxF,GACjBzzE,EAAS5G,KAAOu6E,GAChB3zE,EAASh1C,MAAQ4oH,GACjB5zE,EAAS+B,OAAS+xE,GAGlB9zE,EAASC,GAAKi0E,GACdl0E,EAAS7yC,MAAQ4sH"} \ No newline at end of file +{"version":3,"file":"openpgp.min.mjs","sources":["../node_modules/@openpgp/web-stream-tools/lib/writer.js","../node_modules/@openpgp/web-stream-tools/lib/util.js","../node_modules/@openpgp/web-stream-tools/lib/reader.js","../node_modules/@openpgp/web-stream-tools/lib/streams.js","../src/enums.js","../src/config/config.js","../src/util.js","../src/encoding/base64.js","../src/encoding/armor.js","../src/crypto/cipher/index.js","../src/crypto/hash/md5.js","../src/crypto/hash/index.js","../node_modules/@noble/ciphers/esm/_assert.js","../node_modules/@noble/ciphers/esm/utils.js","../node_modules/@noble/ciphers/esm/_polyval.js","../node_modules/@noble/ciphers/esm/aes.js","../src/crypto/mode/cfb.js","../src/crypto/cmac.js","../src/crypto/mode/eax.js","../src/crypto/mode/ocb.js","../src/crypto/mode/gcm.js","../src/crypto/mode/index.js","../../../src/crypto/biginteger.ts","../src/crypto/random.js","../../../src/crypto/public_key/prime.ts","../src/crypto/pkcs1.js","../src/crypto/public_key/rsa.js","../src/crypto/public_key/elgamal.js","../node_modules/@openpgp/tweetnacl/cryptoBrowser.js","../node_modules/@openpgp/tweetnacl/nacl-fast.js","../src/type/oid.js","../src/packet/packet.js","../src/crypto/public_key/elliptic/eddsa.js","../src/crypto/aes_kw.js","../src/crypto/hkdf.js","../src/crypto/public_key/elliptic/ecdh_x.js","../src/crypto/public_key/elliptic/oid_curves.js","../src/crypto/public_key/elliptic/ecdsa.js","../src/crypto/public_key/elliptic/eddsa_legacy.js","../src/crypto/pkcs5.js","../src/crypto/public_key/elliptic/ecdh.js","../src/crypto/public_key/dsa.js","../src/crypto/public_key/index.js","../src/crypto/signature.js","../src/type/ecdh_symkey.js","../src/type/kdf_params.js","../src/type/ecdh_x_symkey.js","../src/crypto/crypto.js","../src/crypto/index.js","../src/type/s2k/argon2.js","../src/type/s2k/generic.js","../src/type/s2k/index.js","../node_modules/fflate/esm/browser.js","../src/packet/literal_data.js","../src/type/keyid.js","../src/packet/signature.js","../src/packet/one_pass_signature.js","../src/packet/packetlist.js","../src/packet/compressed_data.js","../src/packet/sym_encrypted_integrity_protected_data.js","../src/packet/aead_encrypted_data.js","../src/packet/public_key_encrypted_session_key.js","../src/packet/sym_encrypted_session_key.js","../src/packet/public_key.js","../src/packet/symmetrically_encrypted_data.js","../src/packet/marker.js","../src/packet/public_subkey.js","../src/packet/user_attribute.js","../src/packet/secret_key.js","../src/packet/userid.js","../src/packet/secret_subkey.js","../src/packet/trust.js","../src/packet/padding.js","../src/signature.js","../src/key/helper.js","../src/key/user.js","../src/key/subkey.js","../src/key/key.js","../src/key/public_key.js","../src/key/private_key.js","../src/key/factory.js","../src/message.js","../src/cleartext.js","../src/openpgp.js","../node_modules/@noble/hashes/esm/_assert.js","../node_modules/@noble/hashes/esm/crypto.js","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/_md.js","../node_modules/@noble/hashes/esm/sha256.js","../node_modules/@noble/hashes/esm/hmac.js","../node_modules/@noble/curves/esm/abstract/utils.js","../node_modules/@noble/curves/esm/abstract/modular.js","../node_modules/@noble/curves/esm/abstract/curve.js","../node_modules/@noble/curves/esm/abstract/weierstrass.js","../node_modules/@noble/curves/esm/_shortw_utils.js","../node_modules/@noble/curves/esm/p256.js","../node_modules/@noble/hashes/esm/_u64.js","../node_modules/@noble/hashes/esm/sha512.js","../node_modules/@noble/curves/esm/p384.js","../node_modules/@noble/curves/esm/p521.js","../node_modules/@noble/hashes/esm/sha3.js","../node_modules/@noble/curves/esm/abstract/edwards.js","../node_modules/@noble/curves/esm/abstract/montgomery.js","../node_modules/@noble/curves/esm/ed448.js","../node_modules/@noble/curves/esm/secp256k1.js","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP256r1.ts","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP384r1.ts","../../../src/crypto/public_key/elliptic/brainpool/brainpoolP512r1.ts","../src/crypto/public_key/elliptic/noble_curves.js","../src/crypto/cipher/des.js","../src/crypto/cipher/cast5.js","../src/crypto/cipher/twofish.js","../src/crypto/cipher/blowfish.js","../src/crypto/cipher/legacy_ciphers.js","../node_modules/@noble/hashes/esm/sha1.js","../node_modules/@noble/hashes/esm/ripemd160.js","../src/crypto/hash/noble_hashes.js","../node_modules/argon2id/lib/blake2b.js","../node_modules/argon2id/lib/argon2id.js","../node_modules/argon2id/lib/setup.js","../node_modules/argon2id/index.js","../node_modules/@openpgp/seek-bzip/lib/bitreader.js","../node_modules/@openpgp/seek-bzip/lib/stream.js","../node_modules/@openpgp/seek-bzip/lib/crc32.js","../node_modules/@openpgp/seek-bzip/lib/index.js"],"sourcesContent":["const doneWritingPromise = Symbol('doneWritingPromise');\nconst doneWritingResolve = Symbol('doneWritingResolve');\nconst doneWritingReject = Symbol('doneWritingReject');\n\nconst readingIndex = Symbol('readingIndex');\n\nclass ArrayStream extends Array {\n constructor() {\n super();\n // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work\n Object.setPrototypeOf(this, ArrayStream.prototype);\n\n this[doneWritingPromise] = new Promise((resolve, reject) => {\n this[doneWritingResolve] = resolve;\n this[doneWritingReject] = reject;\n });\n this[doneWritingPromise].catch(() => {});\n }\n}\n\nArrayStream.prototype.getReader = function() {\n if (this[readingIndex] === undefined) {\n this[readingIndex] = 0;\n }\n return {\n read: async () => {\n await this[doneWritingPromise];\n if (this[readingIndex] === this.length) {\n return { value: undefined, done: true };\n }\n return { value: this[this[readingIndex]++], done: false };\n }\n };\n};\n\nArrayStream.prototype.readToEnd = async function(join) {\n await this[doneWritingPromise];\n const result = join(this.slice(this[readingIndex]));\n this.length = 0;\n return result;\n};\n\nArrayStream.prototype.clone = function() {\n const clone = new ArrayStream();\n clone[doneWritingPromise] = this[doneWritingPromise].then(() => {\n clone.push(...this);\n });\n return clone;\n};\n\n/**\n * Check whether data is an ArrayStream\n * @param {Any} input data to check\n * @returns {boolean}\n */\nfunction isArrayStream(input) {\n return input && input.getReader && Array.isArray(input);\n}\n\n/**\n * A wrapper class over the native WritableStreamDefaultWriter.\n * It also lets you \"write data to\" array streams instead of streams.\n * @class\n */\nfunction Writer(input) {\n if (!isArrayStream(input)) {\n const writer = input.getWriter();\n const releaseLock = writer.releaseLock;\n writer.releaseLock = () => {\n writer.closed.catch(function() {});\n releaseLock.call(writer);\n };\n return writer;\n }\n this.stream = input;\n}\n\n/**\n * Write a chunk of data.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.write = async function(chunk) {\n this.stream.push(chunk);\n};\n\n/**\n * Close the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.close = async function() {\n this.stream[doneWritingResolve]();\n};\n\n/**\n * Error the stream.\n * @returns {Promise}\n * @async\n */\nWriter.prototype.abort = async function(reason) {\n this.stream[doneWritingReject](reason);\n return reason;\n};\n\n/**\n * Release the writer's lock.\n * @returns {undefined}\n * @async\n */\nWriter.prototype.releaseLock = function() {};\n\nexport { ArrayStream, isArrayStream, Writer, doneWritingPromise };\n","/* eslint-disable no-prototype-builtins */\nimport { isArrayStream } from './writer.js';\nconst isNode = typeof globalThis.process === 'object' &&\n typeof globalThis.process.versions === 'object';\n\n/**\n * Check whether data is a Stream, and if so of which type\n * @param {Any} input data to check\n * @returns {'web'|'node'|'array'|'web-like'|false}\n */\nfunction isStream(input) {\n if (isArrayStream(input)) {\n return 'array';\n }\n if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {\n return 'web';\n }\n // try and detect a node native stream without having to import its class\n if (input &&\n !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&\n typeof input._read === 'function' && typeof input._readableState === 'object') {\n throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');\n }\n if (input && input.getReader) {\n return 'web-like';\n }\n return false;\n}\n\n/**\n * Check whether data is a Uint8Array\n * @param {Any} input data to check\n * @returns {Boolean}\n */\nfunction isUint8Array(input) {\n return Uint8Array.prototype.isPrototypeOf(input);\n}\n\n/**\n * Concat Uint8Arrays\n * @param {Array} Array of Uint8Arrays to concatenate\n * @returns {Uint8array} Concatenated array\n */\nfunction concatUint8Array(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!isUint8Array(arrays[i])) {\n throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach(function (element) {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n\nexport { isNode, isStream, isArrayStream, isUint8Array, concatUint8Array };\n","import { isUint8Array, isStream, isArrayStream } from './util.js';\nimport * as streams from './streams.js';\n\nconst doneReadingSet = new WeakSet();\n/**\n * The external buffer is used to store values that have been peeked or unshifted from the original stream.\n * Because of how streams are implemented, such values cannot be \"put back\" in the original stream,\n * but they need to be returned first when reading from the input again.\n */\nconst externalBuffer = Symbol('externalBuffer');\n\n/**\n * A wrapper class over the native ReadableStreamDefaultReader.\n * This additionally implements pushing back data on the stream, which\n * lets us implement peeking and a host of convenience functions.\n * It also lets you read data other than streams, such as a Uint8Array.\n * @class\n */\nfunction Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n if (isArrayStream(input)) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {};\n this._cancel = () => {};\n return;\n }\n let streamType = isStream(input);\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n this._cancel = reader.cancel.bind(reader);\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}\n\n/**\n * Read a chunk of data.\n * @returns {Promise} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }\n * @async\n */\nReader.prototype.read = async function() {\n if (this[externalBuffer] && this[externalBuffer].length) {\n const value = this[externalBuffer].shift();\n return { done: false, value };\n }\n return this._read();\n};\n\n/**\n * Allow others to read the stream.\n */\nReader.prototype.releaseLock = function() {\n if (this[externalBuffer]) {\n this.stream[externalBuffer] = this[externalBuffer];\n }\n this._releaseLock();\n};\n\n/**\n * Cancel the stream.\n */\nReader.prototype.cancel = function(reason) {\n return this._cancel(reason);\n};\n\n/**\n * Read up to and including the first \\n character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readLine = async function() {\n let buffer = [];\n let returnVal;\n while (!returnVal) {\n let { done, value } = await this.read();\n value += '';\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n const lineEndIndex = value.indexOf('\\n') + 1;\n if (lineEndIndex) {\n returnVal = streams.concat(buffer.concat(value.substr(0, lineEndIndex)));\n buffer = [];\n }\n if (lineEndIndex !== value.length) {\n buffer.push(value.substr(lineEndIndex));\n }\n }\n this.unshift(...buffer);\n return returnVal;\n};\n\n/**\n * Read a single byte/character.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readByte = async function() {\n const { done, value } = await this.read();\n if (done) return;\n const byte = value[0];\n this.unshift(streams.slice(value, 1));\n return byte;\n};\n\n/**\n * Read a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.readBytes = async function(length) {\n const buffer = [];\n let bufferLength = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) {\n if (buffer.length) return streams.concat(buffer);\n return;\n }\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= length) {\n const bufferConcat = streams.concat(buffer);\n this.unshift(streams.slice(bufferConcat, length));\n return streams.slice(bufferConcat, 0, length);\n }\n }\n};\n\n/**\n * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.\n * @returns {Promise}\n * @async\n */\nReader.prototype.peekBytes = async function(length) {\n const bytes = await this.readBytes(length);\n this.unshift(bytes);\n return bytes;\n};\n\n/**\n * Push data to the front of the stream.\n * Data must have been read in the last call to read*.\n * @param {...(Uint8Array|String|Undefined)} values\n */\nReader.prototype.unshift = function(...values) {\n if (!this[externalBuffer]) {\n this[externalBuffer] = [];\n }\n if (\n values.length === 1 && isUint8Array(values[0]) &&\n this[externalBuffer].length && values[0].length &&\n this[externalBuffer][0].byteOffset >= values[0].length\n ) {\n this[externalBuffer][0] = new Uint8Array(\n this[externalBuffer][0].buffer,\n this[externalBuffer][0].byteOffset - values[0].length,\n this[externalBuffer][0].byteLength + values[0].length\n );\n return;\n }\n this[externalBuffer].unshift(...values.filter(value => value && value.length));\n};\n\n/**\n * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nReader.prototype.readToEnd = async function(join=streams.concat) {\n const result = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await this.read();\n if (done) break;\n result.push(value);\n }\n return join(result);\n};\n\nexport { Reader, externalBuffer };\n","import { isStream, isArrayStream, isUint8Array, concatUint8Array } from './util.js';\nimport { Reader, externalBuffer } from './reader.js';\nimport { ArrayStream, Writer } from './writer.js';\n\n/**\n * Convert data to Stream\n * @param {ReadableStream|Uint8array|String} input data to convert\n * @returns {ReadableStream} Converted data\n */\nfunction toStream(input) {\n let streamType = isStream(input);\n if (streamType) {\n return input;\n }\n return new ReadableStream({\n start(controller) {\n controller.enqueue(input);\n controller.close();\n }\n });\n}\n\n/**\n * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.\n * @param {Object} input data to convert\n * @returns {ArrayStream} Converted data\n */\nfunction toArrayStream(input) {\n if (isStream(input)) {\n return input;\n }\n const stream = new ArrayStream();\n (async () => {\n const writer = getWriter(stream);\n await writer.write(input);\n await writer.close();\n })();\n return stream;\n}\n\n/**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8array|String|ReadableStream} Concatenated array\n */\nfunction concat(list) {\n if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {\n return concatStream(list);\n }\n if (list.some(stream => isArrayStream(stream))) {\n return concatArrayStream(list);\n }\n if (typeof list[0] === 'string') {\n return list.join('');\n }\n return concatUint8Array(list);\n}\n\n/**\n * Concat a list of Streams\n * @param {Array} list Array of Uint8Arrays/Strings/Streams to concatenate\n * @returns {ReadableStream} Concatenated list\n */\nfunction concatStream(list) {\n list = list.map(toStream);\n const transform = transformWithCancel(async function(reason) {\n await Promise.all(transforms.map(stream => cancel(stream, reason)));\n });\n let prev = Promise.resolve();\n const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {\n prev = prev.then(() => pipe(readable, transform.writable, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n }));\n return transform.readable;\n}\n\n/**\n * Concat a list of ArrayStreams\n * @param {Array} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate\n * @returns {ArrayStream} Concatenated streams\n */\nfunction concatArrayStream(list) {\n const result = new ArrayStream();\n let prev = Promise.resolve();\n list.forEach((stream, i) => {\n prev = prev.then(() => pipe(stream, result, {\n preventClose: i !== list.length - 1\n }));\n return prev;\n });\n return result;\n}\n\n/**\n * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {WritableStream} target\n * @param {Object} (optional) options\n * @returns {Promise} Promise indicating when piping has finished (input stream closed or errored)\n * @async\n */\nasync function pipe(input, target, {\n preventClose = false,\n preventAbort = false,\n preventCancel = false\n} = {}) {\n if (isStream(input) && !isArrayStream(input)) {\n input = toStream(input);\n try {\n if (input[externalBuffer]) {\n const writer = getWriter(target);\n for (let i = 0; i < input[externalBuffer].length; i++) {\n await writer.ready;\n await writer.write(input[externalBuffer][i]);\n }\n writer.releaseLock();\n }\n await input.pipeTo(target, {\n preventClose,\n preventAbort,\n preventCancel\n });\n } catch(e) {}\n return;\n }\n input = toArrayStream(input);\n const reader = getReader(input);\n const writer = getWriter(target);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (!preventClose) await writer.close();\n break;\n }\n await writer.write(value);\n }\n } catch (e) {\n if (!preventAbort) await writer.abort(e);\n } finally {\n reader.releaseLock();\n writer.releaseLock();\n }\n}\n\n/**\n * Pipe a readable stream through a transform stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Object} (optional) options\n * @returns {ReadableStream} transformed stream\n */\nfunction transformRaw(input, options) {\n const transformStream = new TransformStream(options);\n pipe(input, transformStream.writable);\n return transformStream.readable;\n}\n\n/**\n * Create a cancelable TransformStream.\n * @param {Function} cancel\n * @returns {TransformStream}\n */\nfunction transformWithCancel(customCancel) {\n let pulled = false;\n let cancelled = false;\n let backpressureChangePromiseResolve, backpressureChangePromiseReject;\n let outputController;\n return {\n readable: new ReadableStream({\n start(controller) {\n outputController = controller;\n },\n pull() {\n if (backpressureChangePromiseResolve) {\n backpressureChangePromiseResolve();\n } else {\n pulled = true;\n }\n },\n async cancel(reason) {\n cancelled = true;\n if (customCancel) {\n await customCancel(reason);\n }\n if (backpressureChangePromiseReject) {\n backpressureChangePromiseReject(reason);\n }\n }\n }, {highWaterMark: 0}),\n writable: new WritableStream({\n write: async function(chunk) {\n if (cancelled) {\n throw new Error('Stream is cancelled');\n }\n outputController.enqueue(chunk);\n if (!pulled) {\n await new Promise((resolve, reject) => {\n backpressureChangePromiseResolve = resolve;\n backpressureChangePromiseReject = reject;\n });\n backpressureChangePromiseResolve = null;\n backpressureChangePromiseReject = null;\n } else {\n pulled = false;\n }\n },\n close: outputController.close.bind(outputController),\n abort: outputController.error.bind(outputController)\n })\n };\n}\n\n/**\n * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} process\n * @param {Function} finish\n * @returns {ReadableStream|Uint8array|String}\n */\nfunction transform(input, process = () => undefined, finish = () => undefined) {\n if (isArrayStream(input)) {\n const output = new ArrayStream();\n (async () => {\n const writer = getWriter(output);\n try {\n const data = await readToEnd(input);\n const result1 = process(data);\n const result2 = finish();\n let result;\n if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);\n else result = result1 !== undefined ? result1 : result2;\n await writer.write(result);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return output;\n }\n if (isStream(input)) {\n return transformRaw(input, {\n async transform(value, controller) {\n try {\n const result = await process(value);\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n },\n async flush(controller) {\n try {\n const result = await finish();\n if (result !== undefined) controller.enqueue(result);\n } catch(e) {\n controller.error(e);\n }\n }\n });\n }\n const result1 = process(input);\n const result2 = finish();\n if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);\n return result1 !== undefined ? result1 : result2;\n}\n\n/**\n * Transform a stream using a helper function which is passed a readable and a writable stream.\n * This function also maintains the possibility to cancel the input stream,\n * and does so on cancelation of the output stream, despite cancelation\n * normally being impossible when the input stream is being read from.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {ReadableStream}\n */\nfunction transformPair(input, fn) {\n if (isStream(input) && !isArrayStream(input)) {\n let incomingTransformController;\n const incoming = new TransformStream({\n start(controller) {\n incomingTransformController = controller;\n }\n });\n\n const pipeDonePromise = pipe(input, incoming.writable);\n\n const outgoing = transformWithCancel(async function(reason) {\n incomingTransformController.error(reason);\n await pipeDonePromise;\n await new Promise(setTimeout);\n });\n fn(incoming.readable, outgoing.writable);\n return outgoing.readable;\n }\n input = toArrayStream(input);\n const output = new ArrayStream();\n fn(input, output);\n return output;\n}\n\n/**\n * Parse a stream using a helper function which is passed a Reader.\n * The reader additionally has a remainder() method which returns a\n * stream pointing to the remainder of input, and is linked to input\n * for cancelation.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} fn\n * @returns {Any} the return value of fn()\n */\nfunction parse(input, fn) {\n let returnValue;\n const transformed = transformPair(input, (readable, writable) => {\n const reader = getReader(readable);\n reader.remainder = () => {\n reader.releaseLock();\n pipe(readable, writable);\n return transformed;\n };\n returnValue = fn(reader);\n });\n return returnValue;\n}\n\n/**\n * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.\n * Reading either of the two returned streams will pull from the input stream.\n * The input stream will only be canceled if both of the returned streams are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Array} array containing two copies of input\n */\nfunction tee(input) {\n if (isArrayStream(input)) {\n throw new Error('ArrayStream cannot be tee()d, use clone() instead');\n }\n if (isStream(input)) {\n const teed = toStream(input).tee();\n teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];\n return teed;\n }\n return [slice(input), slice(input)];\n}\n\n/**\n * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.\n * Reading from the clone will pull from the input stream.\n * The input stream will only be canceled if both the clone and the input stream are canceled.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction clone(input) {\n if (isArrayStream(input)) {\n return input.clone();\n }\n if (isStream(input)) {\n const teed = tee(input);\n overwrite(input, teed[0]);\n return teed[1];\n }\n return slice(input);\n}\n\n/**\n * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.\n * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.\n * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.\n * If the input stream is canceled, the clone will be errored.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} cloned input\n */\nfunction passiveClone(input) {\n if (isArrayStream(input)) {\n return clone(input);\n }\n if (isStream(input)) {\n return new ReadableStream({\n start(controller) {\n const transformed = transformPair(input, async (readable, writable) => {\n const reader = getReader(readable);\n const writer = getWriter(writable);\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n try { controller.close(); } catch(e) {}\n await writer.close();\n return;\n }\n try { controller.enqueue(value); } catch(e) {}\n await writer.write(value);\n }\n } catch(e) {\n controller.error(e);\n await writer.abort(e);\n }\n });\n overwrite(input, transformed);\n }\n });\n }\n return slice(input);\n}\n\n/**\n * Modify a stream object to point to a different stream object.\n * This is used internally by clone() and passiveClone() to provide an abstraction over tee().\n * @param {ReadableStream} input\n * @param {ReadableStream} clone\n */\nfunction overwrite(input, clone) {\n // Overwrite input.getReader, input.locked, etc to point to clone\n Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {\n if (name === 'constructor') {\n return;\n }\n if (descriptor.value) {\n descriptor.value = descriptor.value.bind(clone);\n } else {\n descriptor.get = descriptor.get.bind(clone);\n }\n Object.defineProperty(input, name, descriptor);\n });\n}\n\n/**\n * Return a stream pointing to a part of the input stream.\n * @param {ReadableStream|Uint8array|String} input\n * @returns {ReadableStream|Uint8array|String} clone\n */\nfunction slice(input, begin=0, end=Infinity) {\n if (isArrayStream(input)) {\n throw new Error('Not implemented');\n }\n if (isStream(input)) {\n if (begin >= 0 && end >= 0) {\n let bytesRead = 0;\n return transformRaw(input, {\n transform(value, controller) {\n if (bytesRead < end) {\n if (bytesRead + value.length >= begin) {\n controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));\n }\n bytesRead += value.length;\n } else {\n controller.terminate();\n }\n }\n });\n }\n if (begin < 0 && (end < 0 || end === Infinity)) {\n let lastBytes = [];\n return transform(input, value => {\n if (value.length >= -begin) lastBytes = [value];\n else lastBytes.push(value);\n }, () => slice(concat(lastBytes), begin, end));\n }\n if (begin === 0 && end < 0) {\n let lastBytes;\n return transform(input, value => {\n const returnValue = lastBytes ? concat([lastBytes, value]) : value;\n if (returnValue.length >= -end) {\n lastBytes = slice(returnValue, end);\n return slice(returnValue, begin, end);\n }\n lastBytes = returnValue;\n });\n }\n console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);\n return fromAsync(async () => slice(await readToEnd(input), begin, end));\n }\n if (input[externalBuffer]) {\n input = concat(input[externalBuffer].concat([input]));\n }\n if (isUint8Array(input)) {\n return input.subarray(begin, end === Infinity ? input.length : end);\n }\n return input.slice(begin, end);\n}\n\n/**\n * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).\n * @param {ReadableStream|Uint8array|String} input\n * @param {Function} join\n * @returns {Promise} the return value of join()\n * @async\n */\nasync function readToEnd(input, join=concat) {\n if (isArrayStream(input)) {\n return input.readToEnd(join);\n }\n if (isStream(input)) {\n return getReader(input).readToEnd(join);\n }\n return input;\n}\n\n/**\n * Cancel a stream.\n * @param {ReadableStream|Uint8array|String} input\n * @param {Any} reason\n * @returns {Promise} indicates when the stream has been canceled\n * @async\n */\nasync function cancel(input, reason) {\n if (isStream(input)) {\n if (input.cancel) {\n const cancelled = await input.cancel(reason);\n // the stream is not always cancelled at this point, so we wait some more\n await new Promise(setTimeout);\n return cancelled;\n }\n if (input.destroy) {\n input.destroy(reason);\n await new Promise(setTimeout);\n return reason;\n }\n }\n}\n\n/**\n * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.\n * @param {Function} fn\n * @returns {ArrayStream}\n */\nfunction fromAsync(fn) {\n const arrayStream = new ArrayStream();\n (async () => {\n const writer = getWriter(arrayStream);\n try {\n await writer.write(await fn());\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n })();\n return arrayStream;\n}\n\n/**\n * Get a Reader\n * @param {ReadableStream|Uint8array|String} input\n * @returns {Reader}\n */\nfunction getReader(input) {\n return new Reader(input);\n}\n\n/**\n * Get a Writer\n * @param {WritableStream} input\n * @returns {Writer}\n */\nfunction getWriter(input) {\n return new Writer(input);\n}\n\n\nexport {\n ArrayStream,\n toStream,\n concatStream,\n concat,\n getReader,\n getWriter,\n pipe,\n transformRaw,\n transform,\n transformPair,\n parse,\n clone,\n passiveClone,\n slice,\n readToEnd,\n cancel,\n fromAsync\n};\n","/**\n * @module enums\n */\n\nconst byValue = Symbol('byValue');\n\nexport default {\n\n /** Maps curve names under various standards to one\n * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}\n * @enum {String}\n * @readonly\n */\n curve: {\n /** NIST P-256 Curve */\n 'nistP256': 'nistP256',\n /** @deprecated use `nistP256` instead */\n 'p256': 'nistP256',\n\n /** NIST P-384 Curve */\n 'nistP384': 'nistP384',\n /** @deprecated use `nistP384` instead */\n 'p384': 'nistP384',\n\n /** NIST P-521 Curve */\n 'nistP521': 'nistP521',\n /** @deprecated use `nistP521` instead */\n 'p521': 'nistP521',\n\n /** SECG SECP256k1 Curve */\n 'secp256k1': 'secp256k1',\n\n /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */\n 'ed25519Legacy': 'ed25519Legacy',\n /** @deprecated use `ed25519Legacy` instead */\n 'ed25519': 'ed25519Legacy',\n\n /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */\n 'curve25519Legacy': 'curve25519Legacy',\n /** @deprecated use `curve25519Legacy` instead */\n 'curve25519': 'curve25519Legacy',\n\n /** BrainpoolP256r1 Curve */\n 'brainpoolP256r1': 'brainpoolP256r1',\n\n /** BrainpoolP384r1 Curve */\n 'brainpoolP384r1': 'brainpoolP384r1',\n\n /** BrainpoolP512r1 Curve */\n 'brainpoolP512r1': 'brainpoolP512r1'\n },\n\n /** A string to key specifier type\n * @enum {Integer}\n * @readonly\n */\n s2k: {\n simple: 0,\n salted: 1,\n iterated: 3,\n argon2: 4,\n gnu: 101\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}\n * @enum {Integer}\n * @readonly\n */\n publicKey: {\n /** RSA (Encrypt or Sign) [HAC] */\n rsaEncryptSign: 1,\n /** RSA (Encrypt only) [HAC] */\n rsaEncrypt: 2,\n /** RSA (Sign only) [HAC] */\n rsaSign: 3,\n /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */\n elgamal: 16,\n /** DSA (Sign only) [FIPS186] [HAC] */\n dsa: 17,\n /** ECDH (Encrypt only) [RFC6637] */\n ecdh: 18,\n /** ECDSA (Sign only) [RFC6637] */\n ecdsa: 19,\n /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)\n * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */\n eddsaLegacy: 22,\n /** Reserved for AEDH */\n aedh: 23,\n /** Reserved for AEDSA */\n aedsa: 24,\n /** X25519 (Encrypt only) */\n x25519: 25,\n /** X448 (Encrypt only) */\n x448: 26,\n /** Ed25519 (Sign only) */\n ed25519: 27,\n /** Ed448 (Sign only) */\n ed448: 28\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}\n * @enum {Integer}\n * @readonly\n */\n symmetric: {\n /** Not implemented! */\n idea: 1,\n tripledes: 2,\n cast5: 3,\n blowfish: 4,\n aes128: 7,\n aes192: 8,\n aes256: 9,\n twofish: 10\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}\n * @enum {Integer}\n * @readonly\n */\n compression: {\n uncompressed: 0,\n /** RFC1951 */\n zip: 1,\n /** RFC1950 */\n zlib: 2,\n bzip2: 3\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}\n * @enum {Integer}\n * @readonly\n */\n hash: {\n md5: 1,\n sha1: 2,\n ripemd: 3,\n sha256: 8,\n sha384: 9,\n sha512: 10,\n sha224: 11,\n sha3_256: 12,\n sha3_512: 14\n },\n\n /** A list of hash names as accepted by webCrypto functions.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}\n * @enum {String}\n */\n webHash: {\n 'SHA-1': 2,\n 'SHA-256': 8,\n 'SHA-384': 9,\n 'SHA-512': 10\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}\n * @enum {Integer}\n * @readonly\n */\n aead: {\n eax: 1,\n ocb: 2,\n gcm: 3,\n experimentalGCM: 100 // Private algorithm\n },\n\n /** A list of packet types and numeric tags associated with them.\n * @enum {Integer}\n * @readonly\n */\n packet: {\n publicKeyEncryptedSessionKey: 1,\n signature: 2,\n symEncryptedSessionKey: 3,\n onePassSignature: 4,\n secretKey: 5,\n publicKey: 6,\n secretSubkey: 7,\n compressedData: 8,\n symmetricallyEncryptedData: 9,\n marker: 10,\n literalData: 11,\n trust: 12,\n userID: 13,\n publicSubkey: 14,\n userAttribute: 17,\n symEncryptedIntegrityProtectedData: 18,\n modificationDetectionCode: 19,\n aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1\n padding: 21\n },\n\n /** Data types in the literal packet\n * @enum {Integer}\n * @readonly\n */\n literal: {\n /** Binary data 'b' */\n binary: 'b'.charCodeAt(),\n /** Text data 't' */\n text: 't'.charCodeAt(),\n /** Utf8 data 'u' */\n utf8: 'u'.charCodeAt(),\n /** MIME message body part 'm' */\n mime: 'm'.charCodeAt()\n },\n\n\n /** One pass signature packet type\n * @enum {Integer}\n * @readonly\n */\n signature: {\n /** 0x00: Signature of a binary document. */\n binary: 0,\n /** 0x01: Signature of a canonical text document.\n *\n * Canonicalyzing the document by converting line endings. */\n text: 1,\n /** 0x02: Standalone signature.\n *\n * This signature is a signature of only its own subpacket contents.\n * It is calculated identically to a signature over a zero-lengh\n * binary document. Note that it doesn't make sense to have a V3\n * standalone signature. */\n standalone: 2,\n /** 0x10: Generic certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification does not make any particular\n * assertion as to how well the certifier has checked that the owner\n * of the key is in fact the person described by the User ID. */\n certGeneric: 16,\n /** 0x11: Persona certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has not done any verification of\n * the claim that the owner of this key is the User ID specified. */\n certPersona: 17,\n /** 0x12: Casual certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done some casual\n * verification of the claim of identity. */\n certCasual: 18,\n /** 0x13: Positive certification of a User ID and Public-Key packet.\n *\n * The issuer of this certification has done substantial\n * verification of the claim of identity.\n *\n * Most OpenPGP implementations make their \"key signatures\" as 0x10\n * certifications. Some implementations can issue 0x11-0x13\n * certifications, but few differentiate between the types. */\n certPositive: 19,\n /** 0x30: Certification revocation signature\n *\n * This signature revokes an earlier User ID certification signature\n * (signature class 0x10 through 0x13) or direct-key signature\n * (0x1F). It should be issued by the same key that issued the\n * revoked signature or an authorized revocation key. The signature\n * is computed over the same data as the certificate that it\n * revokes, and should have a later creation date than that\n * certificate. */\n certRevocation: 48,\n /** 0x18: Subkey Binding Signature\n *\n * This signature is a statement by the top-level signing key that\n * indicates that it owns the subkey. This signature is calculated\n * directly on the primary key and subkey, and not on any User ID or\n * other packets. A signature that binds a signing subkey MUST have\n * an Embedded Signature subpacket in this binding signature that\n * contains a 0x19 signature made by the signing subkey on the\n * primary key and subkey. */\n subkeyBinding: 24,\n /** 0x19: Primary Key Binding Signature\n *\n * This signature is a statement by a signing subkey, indicating\n * that it is owned by the primary key and subkey. This signature\n * is calculated the same way as a 0x18 signature: directly on the\n * primary key and subkey, and not on any User ID or other packets.\n *\n * When a signature is made over a key, the hash data starts with the\n * octet 0x99, followed by a two-octet length of the key, and then body\n * of the key packet. (Note that this is an old-style packet header for\n * a key packet with two-octet length.) A subkey binding signature\n * (type 0x18) or primary key binding signature (type 0x19) then hashes\n * the subkey using the same format as the main key (also using 0x99 as\n * the first octet). */\n keyBinding: 25,\n /** 0x1F: Signature directly on a key\n *\n * This signature is calculated directly on a key. It binds the\n * information in the Signature subpackets to the key, and is\n * appropriate to be used for subpackets that provide information\n * about the key, such as the Revocation Key subpacket. It is also\n * appropriate for statements that non-self certifiers want to make\n * about the key itself, rather than the binding between a key and a\n * name. */\n key: 31,\n /** 0x20: Key revocation signature\n *\n * The signature is calculated directly on the key being revoked. A\n * revoked key is not to be used. Only revocation signatures by the\n * key being revoked, or by an authorized revocation key, should be\n * considered valid revocation signatures.a */\n keyRevocation: 32,\n /** 0x28: Subkey revocation signature\n *\n * The signature is calculated directly on the subkey being revoked.\n * A revoked subkey is not to be used. Only revocation signatures\n * by the top-level signature key that is bound to this subkey, or\n * by an authorized revocation key, should be considered valid\n * revocation signatures.\n *\n * Key revocation signatures (types 0x20 and 0x28)\n * hash only the key being revoked. */\n subkeyRevocation: 40,\n /** 0x40: Timestamp signature.\n * This signature is only meaningful for the timestamp contained in\n * it. */\n timestamp: 64,\n /** 0x50: Third-Party Confirmation signature.\n *\n * This signature is a signature over some other OpenPGP Signature\n * packet(s). It is analogous to a notary seal on the signed data.\n * A third-party signature SHOULD include Signature Target\n * subpacket(s) to give easy identification. Note that we really do\n * mean SHOULD. There are plausible uses for this (such as a blind\n * party that only sees the signature, not the key or source\n * document) that cannot include a target subpacket. */\n thirdParty: 80\n },\n\n /** Signature subpacket type\n * @enum {Integer}\n * @readonly\n */\n signatureSubpacket: {\n signatureCreationTime: 2,\n signatureExpirationTime: 3,\n exportableCertification: 4,\n trustSignature: 5,\n regularExpression: 6,\n revocable: 7,\n keyExpirationTime: 9,\n placeholderBackwardsCompatibility: 10,\n preferredSymmetricAlgorithms: 11,\n revocationKey: 12,\n issuerKeyID: 16,\n notationData: 20,\n preferredHashAlgorithms: 21,\n preferredCompressionAlgorithms: 22,\n keyServerPreferences: 23,\n preferredKeyServer: 24,\n primaryUserID: 25,\n policyURI: 26,\n keyFlags: 27,\n signersUserID: 28,\n reasonForRevocation: 29,\n features: 30,\n signatureTarget: 31,\n embeddedSignature: 32,\n issuerFingerprint: 33,\n preferredAEADAlgorithms: 34,\n preferredCipherSuites: 39\n },\n\n /** Key flags\n * @enum {Integer}\n * @readonly\n */\n keyFlags: {\n /** 0x01 - This key may be used to certify other keys. */\n certifyKeys: 1,\n /** 0x02 - This key may be used to sign data. */\n signData: 2,\n /** 0x04 - This key may be used to encrypt communications. */\n encryptCommunication: 4,\n /** 0x08 - This key may be used to encrypt storage. */\n encryptStorage: 8,\n /** 0x10 - The private component of this key may have been split\n * by a secret-sharing mechanism. */\n splitPrivateKey: 16,\n /** 0x20 - This key may be used for authentication. */\n authentication: 32,\n /** 0x80 - The private component of this key may be in the\n * possession of more than one person. */\n sharedPrivateKey: 128\n },\n\n /** Armor type\n * @enum {Integer}\n * @readonly\n */\n armor: {\n multipartSection: 0,\n multipartLast: 1,\n signed: 2,\n message: 3,\n publicKey: 4,\n privateKey: 5,\n signature: 6\n },\n\n /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}\n * @enum {Integer}\n * @readonly\n */\n reasonForRevocation: {\n /** No reason specified (key revocations or cert revocations) */\n noReason: 0,\n /** Key is superseded (key revocations) */\n keySuperseded: 1,\n /** Key material has been compromised (key revocations) */\n keyCompromised: 2,\n /** Key is retired and no longer used (key revocations) */\n keyRetired: 3,\n /** User ID information is no longer valid (cert revocations) */\n userIDInvalid: 32\n },\n\n /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}\n * @enum {Integer}\n * @readonly\n */\n features: {\n /** 0x01 - Modification Detection (packets 18 and 19) */\n modificationDetection: 1,\n /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5\n * Symmetric-Key Encrypted Session Key Packets (packet 3) */\n aead: 2,\n /** 0x04 - Version 5 Public-Key Packet format and corresponding new\n * fingerprint format */\n v5Keys: 4,\n seipdv2: 8\n },\n\n /**\n * Asserts validity of given value and converts from string/integer to integer.\n * @param {Object} type target enum type\n * @param {String|Integer} e value to check and/or convert\n * @returns {Integer} enum value if it exists\n * @throws {Error} if the value is invalid\n */\n write: function(type, e) {\n if (typeof e === 'number') {\n e = this.read(type, e);\n }\n\n if (type[e] !== undefined) {\n return type[e];\n }\n\n throw new Error('Invalid enum value.');\n },\n\n /**\n * Converts enum integer value to the corresponding string, if it exists.\n * @param {Object} type target enum type\n * @param {Integer} e value to convert\n * @returns {String} name of enum value if it exists\n * @throws {Error} if the value is invalid\n */\n read: function(type, e) {\n if (!type[byValue]) {\n type[byValue] = [];\n Object.entries(type).forEach(([key, value]) => {\n type[byValue][value] = key;\n });\n }\n\n if (type[byValue][e] !== undefined) {\n return type[byValue][e];\n }\n\n throw new Error('Invalid enum value.');\n }\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Global configuration values.\n */\n\nimport enums from '../enums';\n\nexport default {\n /**\n * @memberof module:config\n * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}\n */\n preferredHashAlgorithm: enums.hash.sha512,\n /**\n * @memberof module:config\n * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}\n */\n preferredSymmetricAlgorithm: enums.symmetric.aes256,\n /**\n * @memberof module:config\n * @property {Integer} compression Default compression algorithm {@link module:enums.compression}\n */\n preferredCompressionAlgorithm: enums.compression.uncompressed,\n /**\n * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.\n * This option is applicable to:\n * - key generation (encryption key preferences),\n * - password-based message encryption, and\n * - private key encryption.\n * In the case of message encryption using public keys, the encryption key preferences are respected instead.\n * Note: not all OpenPGP implementations are compatible with this option.\n * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}\n * @memberof module:config\n * @property {Boolean} aeadProtect\n */\n aeadProtect: false,\n /**\n * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)\n * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,\n * this option must be set, otherwise key parsing and/or key decryption will fail.\n * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys\n * will be processed incorrectly.\n */\n parseAEADEncryptedV4KeysAsLegacy: false,\n /**\n * Default Authenticated Encryption with Additional Data (AEAD) encryption mode\n * Only has an effect when aeadProtect is set to true.\n * @memberof module:config\n * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}\n */\n preferredAEADAlgorithm: enums.aead.gcm,\n /**\n * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode\n * Only has an effect when aeadProtect is set to true.\n * Must be an integer value from 0 to 56.\n * @memberof module:config\n * @property {Integer} aeadChunkSizeByte\n */\n aeadChunkSizeByte: 12,\n /**\n * Use v6 keys.\n * Note: not all OpenPGP implementations are compatible with this option.\n * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**\n * @memberof module:config\n * @property {Boolean} v6Keys\n */\n v6Keys: false,\n /**\n * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).\n * These are non-standard entities, which in the crypto-refresh have been superseded\n * by v6 keys and v6 signatures, respectively.\n * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,\n * hence parsing them might be necessary in some cases.\n */\n enableParsingV5Entities: false,\n /**\n * S2K (String to Key) type, used for key derivation in the context of secret key encryption\n * and password-encrypted data. Weaker s2k options are not allowed.\n * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it\n * (pending standardisation).\n * @memberof module:config\n * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}\n */\n s2kType: enums.s2k.iterated,\n /**\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:\n * Iteration Count Byte for Iterated and Salted S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.\n * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).\n * @memberof module:config\n * @property {Integer} s2kIterationCountByte\n */\n s2kIterationCountByte: 224,\n /**\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:\n * Argon2 parameters for S2K (String to Key).\n * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.\n * Default settings correspond to the second recommendation from RFC9106 (\"uniformly safe option\"),\n * to ensure compatibility with memory-constrained environments.\n * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.\n * @memberof module:config\n * @property {Object} params\n * @property {Integer} params.passes - number of iterations t\n * @property {Integer} params.parallelism - degree of parallelism p\n * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.\n */\n s2kArgon2Params: {\n passes: 3,\n parallelism: 4, // lanes\n memoryExponent: 16 // 64 MiB of RAM\n },\n /**\n * Allow decryption of messages without integrity protection.\n * This is an **insecure** setting:\n * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.\n * - it enables downgrade attacks against integrity-protected messages.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedMessages\n */\n allowUnauthenticatedMessages: false,\n /**\n * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to\n * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible\n * and deferring checking their integrity until the decrypted stream has been read in full.\n *\n * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:\n * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL\n * (see https://efail.de/).\n * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.\n *\n * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.\n * @memberof module:config\n * @property {Boolean} allowUnauthenticatedStream\n */\n allowUnauthenticatedStream: false,\n /**\n * Minimum RSA key size allowed for key generation and message signing, verification and encryption.\n * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.\n * @memberof module:config\n * @property {Number} minRSABits\n */\n minRSABits: 2047,\n /**\n * Work-around for rare GPG decryption bug when encrypting with multiple passwords.\n * **Slower and slightly less secure**\n * @memberof module:config\n * @property {Boolean} passwordCollisionCheck\n */\n passwordCollisionCheck: false,\n /**\n * Allow decryption using RSA keys without `encrypt` flag.\n * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug\n * where key flags were ignored when selecting a key for encryption.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureDecryptionWithSigningKeys: false,\n /**\n * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.\n * Instead, a verification key will also be consider valid as long as it is valid at the current time.\n * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,\n * and have self-signature's creation date that does not match the primary key creation date.\n * @memberof module:config\n * @property {Boolean} allowInsecureDecryptionWithSigningKeys\n */\n allowInsecureVerificationWithReformattedKeys: false,\n /**\n * Allow using keys that do not have any key flags set.\n * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages\n * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).\n * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.\n * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.\n */\n allowMissingKeyFlags: false,\n /**\n * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).\n * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:\n * - new/incoming messages are automatically decrypted (without user interaction);\n * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).\n * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.\n * @memberof module:config\n * @property {Boolean} constantTimePKCS1Decryption\n */\n constantTimePKCS1Decryption: false,\n /**\n * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.\n * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.\n * However, the more algorithms are added, the slower the decryption procedure becomes.\n * @memberof module:config\n * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}\n */\n constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),\n /**\n * @memberof module:config\n * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error\n */\n ignoreUnsupportedPackets: true,\n /**\n * @memberof module:config\n * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error\n */\n ignoreMalformedPackets: false,\n /**\n * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only\n * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable\n * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).\n * @memberof module:config\n * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]\n */\n additionalAllowedPackets: [],\n /**\n * @memberof module:config\n * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages\n */\n showVersion: false,\n /**\n * @memberof module:config\n * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages\n */\n showComment: false,\n /**\n * @memberof module:config\n * @property {String} versionString A version string to be included in armored messages\n */\n versionString: 'OpenPGP.js VERSION',\n /**\n * @memberof module:config\n * @property {String} commentString A comment string to be included in armored messages\n */\n commentString: 'https://openpgpjs.org',\n\n /**\n * Max userID string length (used for parsing)\n * @memberof module:config\n * @property {Integer} maxUserIDLength\n */\n maxUserIDLength: 1024 * 5,\n /**\n * Contains notatations that are considered \"known\". Known notations do not trigger\n * validation error when the notation is marked as critical.\n * @memberof module:config\n * @property {Array} knownNotations\n */\n knownNotations: [],\n /**\n * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).\n * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur\n * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of\n * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.\n * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.\n */\n nonDeterministicSignaturesViaNotation: true,\n /**\n * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.\n * When false, certain standard curves will not be supported (depending on the platform).\n * @memberof module:config\n * @property {Boolean} useEllipticFallback\n */\n useEllipticFallback: true,\n /**\n * Reject insecure hash algorithms\n * @memberof module:config\n * @property {Set} rejectHashAlgorithms {@link module:enums.hash}\n */\n rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),\n /**\n * Reject insecure message hash algorithms\n * @memberof module:config\n * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash}\n */\n rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),\n /**\n * Reject insecure public key algorithms for key generation and message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey}\n */\n rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),\n /**\n * Reject non-standard curves for key generation, message encryption, signing or verification\n * @memberof module:config\n * @property {Set} rejectCurves {@link module:enums.curve}\n */\n rejectCurves: new Set([enums.curve.secp256k1])\n};\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/* eslint-disable no-console */\n\n/**\n * This object contains utility functions\n * @module util\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { createRequire } from 'module'; // Must be stripped in browser built\nimport enums from './enums';\nimport defaultConfig from './config';\n\nconst debugMode = (() => {\n try {\n return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env\n } catch (e) {}\n return false;\n})();\n\nconst util = {\n isString: function(data) {\n return typeof data === 'string' || data instanceof String;\n },\n\n nodeRequire: createRequire(import.meta.url),\n\n isArray: function(data) {\n return data instanceof Array;\n },\n\n isUint8Array: stream.isUint8Array,\n\n isStream: stream.isStream,\n\n /**\n * Load noble-curves lib on demand and return the requested curve function\n * @param {enums.publicKey} publicKeyAlgo\n * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)\n * @returns curve implementation\n * @throws on unrecognized curve, or curve not implemented by noble-curve\n */\n getNobleCurve: async (publicKeyAlgo, curveName) => {\n if (!defaultConfig.useEllipticFallback) {\n throw new Error('This curve is only supported in the full build of OpenPGP.js');\n }\n\n const { nobleCurves } = await import('./crypto/public_key/elliptic/noble_curves');\n switch (publicKeyAlgo) {\n case enums.publicKey.ecdh:\n case enums.publicKey.ecdsa: {\n const curve = nobleCurves.get(curveName);\n if (!curve) throw new Error('Unsupported curve');\n return curve;\n }\n case enums.publicKey.x448:\n return nobleCurves.get('x448');\n case enums.publicKey.ed448:\n return nobleCurves.get('ed448');\n default:\n throw new Error('Unsupported curve');\n }\n },\n\n readNumber: function (bytes) {\n let n = 0;\n for (let i = 0; i < bytes.length; i++) {\n n += (256 ** i) * bytes[bytes.length - 1 - i];\n }\n return n;\n },\n\n writeNumber: function (n, bytes) {\n const b = new Uint8Array(bytes);\n for (let i = 0; i < bytes; i++) {\n b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;\n }\n\n return b;\n },\n\n readDate: function (bytes) {\n const n = util.readNumber(bytes);\n const d = new Date(n * 1000);\n return d;\n },\n\n writeDate: function (time) {\n const numeric = Math.floor(time.getTime() / 1000);\n\n return util.writeNumber(numeric, 4);\n },\n\n normalizeDate: function (time = Date.now()) {\n return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);\n },\n\n /**\n * Read one MPI from bytes in input\n * @param {Uint8Array} bytes - Input data to parse\n * @returns {Uint8Array} Parsed MPI.\n */\n readMPI: function (bytes) {\n const bits = (bytes[0] << 8) | bytes[1];\n const bytelen = (bits + 7) >>> 3;\n // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,\n // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed\n // has not been authenticated (yet).\n // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.\n // Also, AEAD is also not affected.\n return util.readExactSubarray(bytes, 2, 2 + bytelen);\n },\n\n /**\n * Read exactly `end - start` bytes from input.\n * This is a stricter version of `.subarray`.\n * @param {Uint8Array} input - Input data to parse\n * @returns {Uint8Array} subarray of size always equal to `end - start`\n * @throws if the input array is too short.\n */\n readExactSubarray: function (input, start, end) {\n if (input.length < (end - start)) {\n throw new Error('Input array too short');\n }\n return input.subarray(start, end);\n },\n\n /**\n * Left-pad Uint8Array to length by adding 0x0 bytes\n * @param {Uint8Array} bytes - Data to pad\n * @param {Number} length - Padded length\n * @returns {Uint8Array} Padded bytes.\n */\n leftPad(bytes, length) {\n if (bytes.length > length) {\n throw new Error('Input array too long');\n }\n const padded = new Uint8Array(length);\n const offset = length - bytes.length;\n padded.set(bytes, offset);\n return padded;\n },\n\n /**\n * Convert a Uint8Array to an MPI-formatted Uint8Array.\n * @param {Uint8Array} bin - An array of 8-bit integers to convert\n * @returns {Uint8Array} MPI-formatted Uint8Array.\n */\n uint8ArrayToMPI: function (bin) {\n const bitSize = util.uint8ArrayBitLength(bin);\n if (bitSize === 0) {\n throw new Error('Zero MPI');\n }\n const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));\n const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);\n return util.concatUint8Array([prefix, stripped]);\n },\n\n /**\n * Return bit length of the input data\n * @param {Uint8Array} bin input data (big endian)\n * @returns bit length\n */\n uint8ArrayBitLength: function (bin) {\n let i; // index of leading non-zero byte\n for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;\n if (i === bin.length) {\n return 0;\n }\n const stripped = bin.subarray(i);\n return (stripped.length - 1) * 8 + util.nbits(stripped[0]);\n },\n\n /**\n * Convert a hex string to an array of 8-bit integers\n * @param {String} hex - A hex string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n hexToUint8Array: function (hex) {\n const result = new Uint8Array(hex.length >> 1);\n for (let k = 0; k < hex.length >> 1; k++) {\n result[k] = parseInt(hex.substr(k << 1, 2), 16);\n }\n return result;\n },\n\n /**\n * Convert an array of 8-bit integers to a hex string\n * @param {Uint8Array} bytes - Array of 8-bit integers to convert\n * @returns {String} Hexadecimal representation of the array.\n */\n uint8ArrayToHex: function (bytes) {\n const hexAlphabet = '0123456789abcdef';\n let s = '';\n bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });\n return s;\n },\n\n /**\n * Convert a string to an array of 8-bit integers\n * @param {String} str - String to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\n stringToUint8Array: function (str) {\n return stream.transform(str, str => {\n if (!util.isString(str)) {\n throw new Error('stringToUint8Array: Data must be in the form of a string');\n }\n\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i);\n }\n return result;\n });\n },\n\n /**\n * Convert an array of 8-bit integers to a string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @returns {String} String representation of the array.\n */\n uint8ArrayToString: function (bytes) {\n bytes = new Uint8Array(bytes);\n const result = [];\n const bs = 1 << 14;\n const j = bytes.length;\n\n for (let i = 0; i < j; i += bs) {\n result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));\n }\n return result.join('');\n },\n\n /**\n * Convert a native javascript string to a Uint8Array of utf8 bytes\n * @param {String|ReadableStream} str - The string to convert\n * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.\n */\n encodeUTF8: function (str) {\n const encoder = new TextEncoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return encoder.encode(value, { stream: !lastChunk });\n }\n return stream.transform(str, process, () => process('', true));\n },\n\n /**\n * Convert a Uint8Array of utf8 bytes to a native javascript string\n * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes\n * @returns {String|ReadableStream} A native javascript string.\n */\n decodeUTF8: function (utf8) {\n const decoder = new TextDecoder('utf-8');\n // eslint-disable-next-line no-inner-declarations\n function process(value, lastChunk = false) {\n return decoder.decode(value, { stream: !lastChunk });\n }\n return stream.transform(utf8, process, () => process(new Uint8Array(), true));\n },\n\n /**\n * Concat a list of Uint8Arrays, Strings or Streams\n * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.\n * @param {Array} Array - Of Uint8Arrays/Strings/Streams to concatenate\n * @returns {Uint8Array|String|ReadableStream} Concatenated array.\n */\n concat: stream.concat,\n\n /**\n * Concat Uint8Arrays\n * @param {Array} Array - Of Uint8Arrays to concatenate\n * @returns {Uint8Array} Concatenated array.\n */\n concatUint8Array: stream.concatUint8Array,\n\n /**\n * Check Uint8Array equality\n * @param {Uint8Array} array1 - First array\n * @param {Uint8Array} array2 - Second array\n * @returns {Boolean} Equality.\n */\n equalsUint8Array: function (array1, array2) {\n if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {\n throw new Error('Data must be in the form of a Uint8Array');\n }\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Calculates a 16bit sum of a Uint8Array by adding each character\n * codes modulus 65535\n * @param {Uint8Array} Uint8Array - To create a sum of\n * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.\n */\n writeChecksum: function (text) {\n let s = 0;\n for (let i = 0; i < text.length; i++) {\n s = (s + text[i]) & 0xFFFF;\n }\n return util.writeNumber(s, 2);\n },\n\n /**\n * Helper function to print a debug message. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebug: function (str) {\n if (debugMode) {\n console.log('[OpenPGP.js debug]', str);\n }\n },\n\n /**\n * Helper function to print a debug error. Debug\n * messages are only printed if\n * @param {String} str - String of the debug message\n */\n printDebugError: function (error) {\n if (debugMode) {\n console.error('[OpenPGP.js debug]', error);\n }\n },\n\n // returns bit length of the integer x\n nbits: function (x) {\n let r = 1;\n let t = x >>> 16;\n if (t !== 0) {\n x = t;\n r += 16;\n }\n t = x >> 8;\n if (t !== 0) {\n x = t;\n r += 8;\n }\n t = x >> 4;\n if (t !== 0) {\n x = t;\n r += 4;\n }\n t = x >> 2;\n if (t !== 0) {\n x = t;\n r += 2;\n }\n t = x >> 1;\n if (t !== 0) {\n x = t;\n r += 1;\n }\n return r;\n },\n\n /**\n * If S[1] == 0, then double(S) == (S[2..128] || 0);\n * otherwise, double(S) == (S[2..128] || 0) xor\n * (zeros(120) || 10000111).\n *\n * Both OCB and EAX (through CMAC) require this function to be constant-time.\n *\n * @param {Uint8Array} data\n */\n double: function(data) {\n const doubleVar = new Uint8Array(data.length);\n const last = data.length - 1;\n for (let i = 0; i < last; i++) {\n doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);\n }\n doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);\n return doubleVar;\n },\n\n /**\n * Shift a Uint8Array to the right by n bits\n * @param {Uint8Array} array - The array to shift\n * @param {Integer} bits - Amount of bits to shift (MUST be smaller\n * than 8)\n * @returns {String} Resulting array.\n */\n shiftRight: function (array, bits) {\n if (bits) {\n for (let i = array.length - 1; i >= 0; i--) {\n array[i] >>= bits;\n if (i > 0) {\n array[i] |= (array[i - 1] << (8 - bits));\n }\n }\n }\n return array;\n },\n\n /**\n * Get native Web Cryptography API.\n * @returns {Object} The SubtleCrypto API\n * @throws if the API is not available\n */\n getWebCrypto: function() {\n const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;\n // Fallback for Node 16, which does not expose WebCrypto as a global\n const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;\n if (!webCrypto) {\n throw new Error('The WebCrypto API is not available');\n }\n return webCrypto;\n },\n\n /**\n * Get native Node.js crypto api.\n * @returns {Object} The crypto module or 'undefined'.\n */\n getNodeCrypto: function() {\n return this.nodeRequire('crypto');\n },\n\n getNodeZlib: function() {\n return this.nodeRequire('zlib');\n },\n\n /**\n * Get native Node.js Buffer constructor. This should be used since\n * Buffer is not available under browserify.\n * @returns {Function} The Buffer constructor or 'undefined'.\n */\n getNodeBuffer: function() {\n return (this.nodeRequire('buffer') || {}).Buffer;\n },\n\n getHardwareConcurrency: function() {\n if (typeof navigator !== 'undefined') {\n return navigator.hardwareConcurrency || 1;\n }\n\n const os = this.nodeRequire('os'); // Assume we're on Node.js.\n return os.cpus().length;\n },\n\n /**\n * Test email format to ensure basic compliance:\n * - must include a single @\n * - no control or space unicode chars allowed\n * - no backslash and square brackets (as the latter can mess with the userID parsing)\n * - cannot end with a punctuation char\n * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,\n * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).\n */\n isEmailAddress: function(data) {\n if (!util.isString(data)) {\n return false;\n }\n const re = /^[^\\p{C}\\p{Z}@<>\\\\]+@[^\\p{C}\\p{Z}@<>\\\\]+[^\\p{C}\\p{Z}\\p{P}]$/u;\n return re.test(data);\n },\n\n /**\n * Normalize line endings to \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n canonicalizeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n const indices = [];\n for (let i = 0; ; i = index) {\n index = bytes.indexOf(LF, i) + 1;\n if (index) {\n if (bytes[index - 2] !== CR) indices.push(index);\n } else {\n break;\n }\n }\n if (!indices.length) {\n return bytes;\n }\n\n const normalized = new Uint8Array(bytes.length + indices.length);\n let j = 0;\n for (let i = 0; i < indices.length; i++) {\n const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);\n normalized.set(sub, j);\n j += sub.length;\n normalized[j - 1] = CR;\n normalized[j] = LF;\n j++;\n }\n normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);\n return normalized;\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Convert line endings from canonicalized to native \n * Support any encoding where CR=0x0D, LF=0x0A\n */\n nativeEOL: function(data) {\n const CR = 13;\n const LF = 10;\n let carryOverCR = false;\n\n return stream.transform(data, bytes => {\n if (carryOverCR && bytes[0] !== LF) {\n bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);\n } else {\n bytes = new Uint8Array(bytes); // Don't mutate passed bytes\n }\n\n if (bytes[bytes.length - 1] === CR) {\n carryOverCR = true;\n bytes = bytes.subarray(0, -1);\n } else {\n carryOverCR = false;\n }\n\n let index;\n let j = 0;\n for (let i = 0; i !== bytes.length; i = index) {\n index = bytes.indexOf(CR, i) + 1;\n if (!index) index = bytes.length;\n const last = index - (bytes[index] === LF ? 1 : 0);\n if (i) bytes.copyWithin(j, i, last);\n j += last - i;\n }\n return bytes.subarray(0, j);\n }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));\n },\n\n /**\n * Remove trailing spaces, carriage returns and tabs from each line\n */\n removeTrailingSpaces: function(text) {\n return text.split('\\n').map(line => {\n let i = line.length - 1;\n for (; i >= 0 && (line[i] === ' ' || line[i] === '\\t' || line[i] === '\\r'); i--);\n return line.substr(0, i + 1);\n }).join('\\n');\n },\n\n wrapError: function(message, error) {\n if (!error) {\n return new Error(message);\n }\n\n // update error message\n try {\n error.message = message + ': ' + error.message;\n } catch (e) {}\n\n return error;\n },\n\n /**\n * Map allowed packet tags to corresponding classes\n * Meant to be used to format `allowedPacket` for Packetlist.read\n * @param {Array} allowedClasses\n * @returns {Object} map from enum.packet to corresponding *Packet class\n */\n constructAllowedPackets: function(allowedClasses) {\n const map = {};\n allowedClasses.forEach(PacketClass => {\n if (!PacketClass.tag) {\n throw new Error('Invalid input: expected a packet class');\n }\n map[PacketClass.tag] = PacketClass;\n });\n return map;\n },\n\n /**\n * Return a Promise that will resolve as soon as one of the promises in input resolves\n * or will reject if all input promises all rejected\n * (similar to Promise.any, but with slightly different error handling)\n * @param {Array} promises\n * @return {Promise} Promise resolving to the result of the fastest fulfilled promise\n * or rejected with the Error of the last resolved Promise (if all promises are rejected)\n */\n anyPromise: function(promises) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let exception;\n await Promise.all(promises.map(async promise => {\n try {\n resolve(await promise);\n } catch (e) {\n exception = e;\n }\n }));\n reject(exception);\n });\n },\n\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * @param {Boolean} cond\n * @param {Uint8Array} a\n * @param {Uint8Array} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8Array: function(cond, a, b) {\n const length = Math.max(a.length, b.length);\n const result = new Uint8Array(length);\n let end = 0;\n for (let i = 0; i < result.length; i++) {\n result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));\n end += (cond & i < a.length) | ((1 - cond) & i < b.length);\n }\n return result.subarray(0, end);\n },\n /**\n * Return either `a` or `b` based on `cond`, in algorithmic constant time.\n * NB: it only supports `a, b` with values between 0-255.\n * @param {Boolean} cond\n * @param {Uint8} a\n * @param {Uint8} b\n * @returns `a` if `cond` is true, `b` otherwise\n */\n selectUint8: function(cond, a, b) {\n return (a & (256 - cond)) | (b & (255 + cond));\n },\n /**\n * @param {module:enums.symmetric} cipherAlgo\n */\n isAES: function(cipherAlgo) {\n return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;\n }\n};\n\nexport default util;\n","/* OpenPGP radix-64/base64 string encoding/decoding\n * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de\n * version 1.0, check www.haneWIN.de for the latest version\n *\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other materials\n * provided with the application or distribution.\n */\n\n/**\n * @module encoding/base64\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../util';\n\nconst Buffer = util.getNodeBuffer();\n\nlet encodeChunk;\nlet decodeChunk;\nif (Buffer) {\n encodeChunk = buf => Buffer.from(buf).toString('base64');\n decodeChunk = str => {\n const b = Buffer.from(str, 'base64');\n return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);\n };\n} else {\n encodeChunk = buf => btoa(util.uint8ArrayToString(buf));\n decodeChunk = str => util.stringToUint8Array(atob(str));\n}\n\n/**\n * Convert binary array to radix-64\n * @param {Uint8Array | ReadableStream} data - Uint8Array to convert\n * @returns {String | ReadableStream} Radix-64 version of input string.\n * @static\n */\nexport function encode(data) {\n let buf = new Uint8Array();\n return stream.transform(data, value => {\n buf = util.concatUint8Array([buf, value]);\n const r = [];\n const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).\n const lines = Math.floor(buf.length / bytesPerLine);\n const bytes = lines * bytesPerLine;\n const encoded = encodeChunk(buf.subarray(0, bytes));\n for (let i = 0; i < lines; i++) {\n r.push(encoded.substr(i * 60, 60));\n r.push('\\n');\n }\n buf = buf.subarray(bytes);\n return r.join('');\n }, () => (buf.length ? encodeChunk(buf) + '\\n' : ''));\n}\n\n/**\n * Convert radix-64 to binary array\n * @param {String | ReadableStream} data - Radix-64 string to convert\n * @returns {Uint8Array | ReadableStream} Binary array version of input string.\n * @static\n */\nexport function decode(data) {\n let buf = '';\n return stream.transform(data, value => {\n buf += value;\n\n // Count how many whitespace characters there are in buf\n let spaces = 0;\n const spacechars = [' ', '\\t', '\\r', '\\n'];\n for (let i = 0; i < spacechars.length; i++) {\n const spacechar = spacechars[i];\n for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {\n spaces++;\n }\n }\n\n // Backtrack until we have 4n non-whitespace characters\n // that we can safely base64-decode\n let length = buf.length;\n for (; length > 0 && (length - spaces) % 4 !== 0; length--) {\n if (spacechars.includes(buf[length])) spaces--;\n }\n\n const decoded = decodeChunk(buf.substr(0, length));\n buf = buf.substr(length);\n return decoded;\n }, () => decodeChunk(buf));\n}\n\n/**\n * Convert a Base-64 encoded string an array of 8-bit integer\n *\n * Note: accepts both Radix-64 and URL-safe strings\n * @param {String} base64 - Base-64 encoded string to convert\n * @returns {Uint8Array} An array of 8-bit integers.\n */\nexport function b64ToUint8Array(base64) {\n return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\n/**\n * Convert an array of 8-bit integer to a Base-64 encoded string\n * @param {Uint8Array} bytes - An array of 8-bit integers to convert\n * @param {bool} url - If true, output is URL-safe\n * @returns {String} Base-64 encoded string.\n */\nexport function uint8ArrayToB64(bytes, url) {\n let encoded = encode(bytes).replace(/[\\r\\n]/g, '');\n if (url) {\n encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');\n }\n return encoded;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport * as base64 from './base64';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Finds out which Ascii Armoring type is used. Throws error if unknown type.\n * @param {String} text - ascii armored text\n * @returns {Integer} 0 = MESSAGE PART n of m.\n * 1 = MESSAGE PART n\n * 2 = SIGNED MESSAGE\n * 3 = PGP MESSAGE\n * 4 = PUBLIC KEY BLOCK\n * 5 = PRIVATE KEY BLOCK\n * 6 = SIGNATURE\n * @private\n */\nfunction getType(text) {\n const reHeader = /^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;\n\n const header = text.match(reHeader);\n\n if (!header) {\n throw new Error('Unknown ASCII armor type');\n }\n\n // BEGIN PGP MESSAGE, PART X/Y\n // Used for multi-part messages, where the armor is split amongst Y\n // parts, and this is the Xth part out of Y.\n if (/MESSAGE, PART \\d+\\/\\d+/.test(header[1])) {\n return enums.armor.multipartSection;\n }\n // BEGIN PGP MESSAGE, PART X\n // Used for multi-part messages, where this is the Xth part of an\n // unspecified number of parts. Requires the MESSAGE-ID Armor\n // Header to be used.\n if (/MESSAGE, PART \\d+/.test(header[1])) {\n return enums.armor.multipartLast;\n }\n // BEGIN PGP SIGNED MESSAGE\n if (/SIGNED MESSAGE/.test(header[1])) {\n return enums.armor.signed;\n }\n // BEGIN PGP MESSAGE\n // Used for signed, encrypted, or compressed files.\n if (/MESSAGE/.test(header[1])) {\n return enums.armor.message;\n }\n // BEGIN PGP PUBLIC KEY BLOCK\n // Used for armoring public keys.\n if (/PUBLIC KEY BLOCK/.test(header[1])) {\n return enums.armor.publicKey;\n }\n // BEGIN PGP PRIVATE KEY BLOCK\n // Used for armoring private keys.\n if (/PRIVATE KEY BLOCK/.test(header[1])) {\n return enums.armor.privateKey;\n }\n // BEGIN PGP SIGNATURE\n // Used for detached signatures, OpenPGP/MIME signatures, and\n // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE\n // for detached signatures.\n if (/SIGNATURE/.test(header[1])) {\n return enums.armor.signature;\n }\n}\n\n/**\n * Add additional information to the armor version of an OpenPGP binary\n * packet block.\n * @author Alex\n * @version 2011-12-16\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @returns {String} The header information.\n * @private\n */\nfunction addheader(customComment, config) {\n let result = '';\n if (config.showVersion) {\n result += 'Version: ' + config.versionString + '\\n';\n }\n if (config.showComment) {\n result += 'Comment: ' + config.commentString + '\\n';\n }\n if (customComment) {\n result += 'Comment: ' + customComment + '\\n';\n }\n result += '\\n';\n return result;\n}\n\n/**\n * Calculates a checksum over the given data and returns it base64 encoded\n * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for\n * @returns {String | ReadableStream} Base64 encoded checksum.\n * @private\n */\nfunction getCheckSum(data) {\n const crc = createcrc24(data);\n return base64.encode(crc);\n}\n\n// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview\n\nconst crc_table = [\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF),\n new Array(0xFF)\n];\n\nfor (let i = 0; i <= 0xFF; i++) {\n let crc = i << 16;\n for (let j = 0; j < 8; j++) {\n crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);\n }\n crc_table[0][i] =\n ((crc & 0xFF0000) >> 16) |\n (crc & 0x00FF00) |\n ((crc & 0x0000FF) << 16);\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];\n}\nfor (let i = 0; i <= 0xFF; i++) {\n crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness\nconst isLittleEndian = (function() {\n const buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] === 0xFF;\n}());\n\n/**\n * Internal function to calculate a CRC-24 checksum over a given string (data)\n * @param {String | ReadableStream} input - Data to create a CRC-24 checksum for\n * @returns {Uint8Array | ReadableStream} The CRC-24 checksum.\n * @private\n */\nfunction createcrc24(input) {\n let crc = 0xCE04B7;\n return stream.transform(input, value => {\n const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;\n const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);\n for (let i = 0; i < len32; i++) {\n crc ^= arr32[i];\n crc =\n crc_table[0][(crc >> 24) & 0xFF] ^\n crc_table[1][(crc >> 16) & 0xFF] ^\n crc_table[2][(crc >> 8) & 0xFF] ^\n crc_table[3][(crc >> 0) & 0xFF];\n }\n for (let i = len32 * 4; i < value.length; i++) {\n crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];\n }\n }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));\n}\n\n/**\n * Verify armored headers. crypto-refresh-06, section 6.2:\n * \"An OpenPGP implementation may consider improperly formatted Armor\n * Headers to be corruption of the ASCII Armor, but SHOULD make an\n * effort to recover.\"\n * @private\n * @param {Array} headers - Armor headers\n */\nfunction verifyHeaders(headers) {\n for (let i = 0; i < headers.length; i++) {\n if (!/^([^\\s:]|[^\\s:][^:]*[^\\s:]): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));\n }\n if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {\n util.printDebugError(new Error('Unknown header: ' + headers[i]));\n }\n }\n}\n\n/**\n * Remove the (optional) checksum from an armored message.\n * @param {String} text - OpenPGP armored message\n * @returns {String} The body of the armored message.\n * @private\n */\nfunction removeChecksum(text) {\n let body = text;\n\n const lastEquals = text.lastIndexOf('=');\n\n if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum\n body = text.slice(0, lastEquals);\n }\n\n return body;\n}\n\n/**\n * Dearmor an OpenPGP armored message; verify the checksum and return\n * the encoded bytes\n * @param {String} input - OpenPGP armored message\n * @returns {Promise} An object with attribute \"text\" containing the message text,\n * an attribute \"data\" containing a stream of bytes and \"type\" for the ASCII armor type\n * @async\n * @static\n */\nexport function unarmor(input) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n try {\n const reSplit = /^-----[^-]+-----$/m;\n const reEmptyLine = /^[ \\f\\r\\t\\u00a0\\u2000-\\u200a\\u202f\\u205f\\u3000]*$/;\n\n let type;\n const headers = [];\n let lastHeaders = headers;\n let headersDone;\n let text = [];\n let textDone;\n const data = base64.decode(stream.transformPair(input, async (readable, writable) => {\n const reader = stream.getReader(readable);\n try {\n while (true) {\n let line = await reader.readLine();\n if (line === undefined) {\n throw new Error('Misformed armored text');\n }\n // remove trailing whitespace at end of lines\n line = util.removeTrailingSpaces(line.replace(/[\\r\\n]/g, ''));\n if (!type) {\n if (reSplit.test(line)) {\n type = getType(line);\n }\n } else if (!headersDone) {\n if (reSplit.test(line)) {\n reject(new Error('Mandatory blank line missing between armor headers and armor data'));\n }\n if (!reEmptyLine.test(line)) {\n lastHeaders.push(line);\n } else {\n verifyHeaders(lastHeaders);\n headersDone = true;\n if (textDone || type !== enums.armor.signed) {\n resolve({ text, data, headers, type });\n break;\n }\n }\n } else if (!textDone && type === enums.armor.signed) {\n if (!reSplit.test(line)) {\n // Reverse dash-escaping for msg\n text.push(line.replace(/^- /, ''));\n } else {\n text = text.join('\\r\\n');\n textDone = true;\n verifyHeaders(lastHeaders);\n lastHeaders = [];\n headersDone = false;\n }\n }\n }\n } catch (e) {\n reject(e);\n return;\n }\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n throw new Error('Misformed armored text');\n }\n const line = value + '';\n if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {\n await writer.write(line);\n } else {\n let remainder = await reader.readToEnd();\n if (!remainder.length) remainder = '';\n remainder = line + remainder;\n remainder = util.removeTrailingSpaces(remainder.replace(/\\r/g, ''));\n const parts = remainder.split(reSplit);\n if (parts.length === 1) {\n throw new Error('Misformed armored text');\n }\n const body = removeChecksum(parts[0].slice(0, -1));\n await writer.write(body);\n break;\n }\n }\n await writer.ready;\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n }));\n } catch (e) {\n reject(e);\n }\n }).then(async result => {\n if (stream.isArrayStream(result.data)) {\n result.data = await stream.readToEnd(result.data);\n }\n return result;\n });\n}\n\n\n/**\n * Armor an OpenPGP binary packet block\n * @param {module:enums.armor} messageType - Type of the message\n * @param {Uint8Array | ReadableStream} body - The message body to armor\n * @param {Integer} [partIndex]\n * @param {Integer} [partTotal]\n * @param {String} [customComment] - Additional comment to add to the armored string\n * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum\n * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} Armored text.\n * @static\n */\nexport function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config = defaultConfig) {\n let text;\n let hash;\n if (messageType === enums.armor.signed) {\n text = body.text;\n hash = body.hash;\n body = body.data;\n }\n // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug\n // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)\n const maybeBodyClone = emitChecksum && stream.passiveClone(body);\n\n const result = [];\n switch (messageType) {\n case enums.armor.multipartSection:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\\n');\n break;\n case enums.armor.multipartLast:\n result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\\n');\n break;\n case enums.armor.signed:\n result.push('-----BEGIN PGP SIGNED MESSAGE-----\\n');\n result.push(hash ? `Hash: ${hash}\\n\\n` : '\\n');\n result.push(text.replace(/^-/mg, '- -'));\n result.push('\\n-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n case enums.armor.message:\n result.push('-----BEGIN PGP MESSAGE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP MESSAGE-----\\n');\n break;\n case enums.armor.publicKey:\n result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PUBLIC KEY BLOCK-----\\n');\n break;\n case enums.armor.privateKey:\n result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP PRIVATE KEY BLOCK-----\\n');\n break;\n case enums.armor.signature:\n result.push('-----BEGIN PGP SIGNATURE-----\\n');\n result.push(addheader(customComment, config));\n result.push(base64.encode(body));\n maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));\n result.push('-----END PGP SIGNATURE-----\\n');\n break;\n }\n\n return util.concat(result);\n}\n","import enums from '../../enums';\n\nexport async function getLegacyCipher(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n throw new Error('Not a legacy cipher');\n case enums.symmetric.cast5:\n case enums.symmetric.blowfish:\n case enums.symmetric.twofish:\n case enums.symmetric.tripledes: {\n const { legacyCiphers } = await import('./legacy_ciphers');\n const cipher = legacyCiphers.get(algo);\n if (!cipher) {\n throw new Error('Unsupported cipher algorithm');\n }\n return cipher;\n }\n default:\n throw new Error('Unsupported cipher algorithm');\n }\n}\n\n/**\n * Get block size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherBlockSize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.aes192:\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 16;\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n case enums.symmetric.tripledes:\n return 8;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nfunction getCipherKeySize(algo) {\n switch (algo) {\n case enums.symmetric.aes128:\n case enums.symmetric.blowfish:\n case enums.symmetric.cast5:\n return 16;\n case enums.symmetric.aes192:\n case enums.symmetric.tripledes:\n return 24;\n case enums.symmetric.aes256:\n case enums.symmetric.twofish:\n return 32;\n default:\n throw new Error('Unsupported cipher');\n }\n}\n\n/**\n * Get block and key size for given cipher algo\n * @param {module:enums.symmetric} algo - alrogithm identifier\n */\nexport function getCipherParams(algo) {\n return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };\n}\n","/**\n * A fast MD5 JavaScript implementation\n * Copyright (c) 2012 Joseph Myers\n * http://www.myersdaily.org/joseph/javascript/md5-text.html\n *\n * Permission to use, copy, modify, and distribute this software\n * and its documentation for any purposes and without\n * fee is hereby granted provided that this copyright notice\n * appears in all copies.\n *\n * Of course, this soft is provided \"as is\" without express or implied\n * warranty of any kind.\n */\n\nimport util from '../../util';\n\n// MD5 Digest\nasync function md5(entree) {\n const digest = md51(util.uint8ArrayToString(entree));\n return util.hexToUint8Array(hex(digest));\n}\n\nfunction md5cycle(x, k) {\n let a = x[0];\n let b = x[1];\n let c = x[2];\n let d = x[3];\n\n a = ff(a, b, c, d, k[0], 7, -680876936);\n d = ff(d, a, b, c, k[1], 12, -389564586);\n c = ff(c, d, a, b, k[2], 17, 606105819);\n b = ff(b, c, d, a, k[3], 22, -1044525330);\n a = ff(a, b, c, d, k[4], 7, -176418897);\n d = ff(d, a, b, c, k[5], 12, 1200080426);\n c = ff(c, d, a, b, k[6], 17, -1473231341);\n b = ff(b, c, d, a, k[7], 22, -45705983);\n a = ff(a, b, c, d, k[8], 7, 1770035416);\n d = ff(d, a, b, c, k[9], 12, -1958414417);\n c = ff(c, d, a, b, k[10], 17, -42063);\n b = ff(b, c, d, a, k[11], 22, -1990404162);\n a = ff(a, b, c, d, k[12], 7, 1804603682);\n d = ff(d, a, b, c, k[13], 12, -40341101);\n c = ff(c, d, a, b, k[14], 17, -1502002290);\n b = ff(b, c, d, a, k[15], 22, 1236535329);\n\n a = gg(a, b, c, d, k[1], 5, -165796510);\n d = gg(d, a, b, c, k[6], 9, -1069501632);\n c = gg(c, d, a, b, k[11], 14, 643717713);\n b = gg(b, c, d, a, k[0], 20, -373897302);\n a = gg(a, b, c, d, k[5], 5, -701558691);\n d = gg(d, a, b, c, k[10], 9, 38016083);\n c = gg(c, d, a, b, k[15], 14, -660478335);\n b = gg(b, c, d, a, k[4], 20, -405537848);\n a = gg(a, b, c, d, k[9], 5, 568446438);\n d = gg(d, a, b, c, k[14], 9, -1019803690);\n c = gg(c, d, a, b, k[3], 14, -187363961);\n b = gg(b, c, d, a, k[8], 20, 1163531501);\n a = gg(a, b, c, d, k[13], 5, -1444681467);\n d = gg(d, a, b, c, k[2], 9, -51403784);\n c = gg(c, d, a, b, k[7], 14, 1735328473);\n b = gg(b, c, d, a, k[12], 20, -1926607734);\n\n a = hh(a, b, c, d, k[5], 4, -378558);\n d = hh(d, a, b, c, k[8], 11, -2022574463);\n c = hh(c, d, a, b, k[11], 16, 1839030562);\n b = hh(b, c, d, a, k[14], 23, -35309556);\n a = hh(a, b, c, d, k[1], 4, -1530992060);\n d = hh(d, a, b, c, k[4], 11, 1272893353);\n c = hh(c, d, a, b, k[7], 16, -155497632);\n b = hh(b, c, d, a, k[10], 23, -1094730640);\n a = hh(a, b, c, d, k[13], 4, 681279174);\n d = hh(d, a, b, c, k[0], 11, -358537222);\n c = hh(c, d, a, b, k[3], 16, -722521979);\n b = hh(b, c, d, a, k[6], 23, 76029189);\n a = hh(a, b, c, d, k[9], 4, -640364487);\n d = hh(d, a, b, c, k[12], 11, -421815835);\n c = hh(c, d, a, b, k[15], 16, 530742520);\n b = hh(b, c, d, a, k[2], 23, -995338651);\n\n a = ii(a, b, c, d, k[0], 6, -198630844);\n d = ii(d, a, b, c, k[7], 10, 1126891415);\n c = ii(c, d, a, b, k[14], 15, -1416354905);\n b = ii(b, c, d, a, k[5], 21, -57434055);\n a = ii(a, b, c, d, k[12], 6, 1700485571);\n d = ii(d, a, b, c, k[3], 10, -1894986606);\n c = ii(c, d, a, b, k[10], 15, -1051523);\n b = ii(b, c, d, a, k[1], 21, -2054922799);\n a = ii(a, b, c, d, k[8], 6, 1873313359);\n d = ii(d, a, b, c, k[15], 10, -30611744);\n c = ii(c, d, a, b, k[6], 15, -1560198380);\n b = ii(b, c, d, a, k[13], 21, 1309151649);\n a = ii(a, b, c, d, k[4], 6, -145523070);\n d = ii(d, a, b, c, k[11], 10, -1120210379);\n c = ii(c, d, a, b, k[2], 15, 718787259);\n b = ii(b, c, d, a, k[9], 21, -343485551);\n\n x[0] = add32(a, x[0]);\n x[1] = add32(b, x[1]);\n x[2] = add32(c, x[2]);\n x[3] = add32(d, x[3]);\n}\n\nfunction cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n}\n\nfunction ff(a, b, c, d, x, s, t) {\n return cmn((b & c) | ((~b) & d), a, b, x, s, t);\n}\n\nfunction gg(a, b, c, d, x, s, t) {\n return cmn((b & d) | (c & (~d)), a, b, x, s, t);\n}\n\nfunction hh(a, b, c, d, x, s, t) {\n return cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction ii(a, b, c, d, x, s, t) {\n return cmn(c ^ (b | (~d)), a, b, x, s, t);\n}\n\nfunction md51(s) {\n const n = s.length;\n const state = [1732584193, -271733879, -1732584194, 271733878];\n let i;\n for (i = 64; i <= s.length; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < s.length; i++) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i++) {\n tail[i] = 0;\n }\n }\n tail[14] = n * 8;\n md5cycle(state, tail);\n return state;\n}\n\n/* there needs to be support for Unicode here,\n * unless we pretend that we can redefine the MD-5\n * algorithm for multi-byte characters (perhaps\n * by adding every four 16-bit characters and\n * shortening the sum to 32 bits). Otherwise\n * I suggest performing MD-5 as if every character\n * was two bytes--e.g., 0040 0025 = @%--but then\n * how will an ordinary MD-5 sum be matched?\n * There is no way to standardize text to something\n * like UTF-8 before transformation; speed cost is\n * utterly prohibitive. The JavaScript standard\n * itself needs to look at this: it should start\n * providing access to strings as preformed UTF-8\n * 8-bit unsigned value arrays.\n */\nfunction md5blk(s) { /* I figured global was faster. */\n const md5blks = [];\n let i; /* Andy King said do it this way. */\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<\n 24);\n }\n return md5blks;\n}\n\nconst hex_chr = '0123456789abcdef'.split('');\n\nfunction rhex(n) {\n let s = '';\n let j = 0;\n for (; j < 4; j++) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n}\n\nfunction hex(x) {\n for (let i = 0; i < x.length; i++) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n}\n\n/* this function is much faster,\nso if possible we use it. Some IEs\nare the only ones I know of that\nneed the idiotic second function,\ngenerated by an if clause. */\n\nfunction add32(a, b) {\n return (a + b) & 0xFFFFFFFF;\n}\n\nexport default md5;\n","/**\n * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.\n * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}\n * @see {@link https://github.com/indutny/hash.js|hash.js}\n * @module crypto/hash\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport md5 from './md5';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();\n\nfunction nodeHash(type) {\n if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {\n return;\n }\n return async function (data) {\n const shasum = nodeCrypto.createHash(type);\n return stream.transform(data, value => {\n shasum.update(value);\n }, () => new Uint8Array(shasum.digest()));\n };\n}\n\nfunction nobleHash(nobleHashName, webCryptoHashName) {\n const getNobleHash = async () => {\n const { nobleHashes } = await import('./noble_hashes');\n const hash = nobleHashes.get(nobleHashName);\n if (!hash) throw new Error('Unsupported hash');\n return hash;\n };\n\n return async function(data) {\n if (stream.isArrayStream(data)) {\n data = await stream.readToEnd(data);\n }\n if (util.isStream(data)) {\n const hash = await getNobleHash();\n\n const hashInstance = hash.create();\n return stream.transform(data, value => {\n hashInstance.update(value);\n }, () => hashInstance.digest());\n } else if (webCrypto && webCryptoHashName) {\n return new Uint8Array(await webCrypto.digest(webCryptoHashName, data));\n } else {\n const hash = await getNobleHash();\n\n return hash(data);\n }\n };\n}\n\nexport default {\n\n /** @see module:md5 */\n md5: nodeHash('md5') || md5,\n sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'),\n sha224: nodeHash('sha224') || nobleHash('sha224'),\n sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'),\n sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'),\n sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'),\n ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'),\n sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'),\n sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'),\n\n /**\n * Create a hash on the specified data using the specified algorithm\n * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @param {Uint8Array} data - Data to be hashed\n * @returns {Promise} Hash value.\n */\n digest: function(algo, data) {\n switch (algo) {\n case enums.hash.md5:\n return this.md5(data);\n case enums.hash.sha1:\n return this.sha1(data);\n case enums.hash.ripemd:\n return this.ripemd(data);\n case enums.hash.sha256:\n return this.sha256(data);\n case enums.hash.sha384:\n return this.sha384(data);\n case enums.hash.sha512:\n return this.sha512(data);\n case enums.hash.sha224:\n return this.sha224(data);\n case enums.hash.sha3_256:\n return this.sha3_256(data);\n case enums.hash.sha3_512:\n return this.sha3_512(data);\n default:\n throw new Error('Unsupported hash function');\n }\n },\n\n /**\n * Returns the hash size in bytes of the specified hash algorithm type\n * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})\n * @returns {Integer} Size in bytes of the resulting hash.\n */\n getHashByteLength: function(algo) {\n switch (algo) {\n case enums.hash.md5:\n return 16;\n case enums.hash.sha1:\n case enums.hash.ripemd:\n return 20;\n case enums.hash.sha256:\n return 32;\n case enums.hash.sha384:\n return 48;\n case enums.hash.sha512:\n return 64;\n case enums.hash.sha224:\n return 28;\n case enums.hash.sha3_256:\n return 32;\n case enums.hash.sha3_512:\n return 64;\n default:\n throw new Error('Invalid hash algorithm.');\n }\n }\n};\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, copyBytes, createView, toBytes, u32 } from './utils.js';\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0, s1, s2, s3) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\nconst swapLE = (n) => (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k) {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\nconst estimateWindow = (bytes) => {\n if (bytes > 64 * 1024)\n return 8;\n if (bytes > 1024)\n return 4;\n return 2;\n};\nclass GHASH {\n // We select bits per window adaptively based on expectedLength\n constructor(key, expectedLength) {\n this.blockLen = BLOCK_SIZE;\n this.outputLen = BLOCK_SIZE;\n this.s0 = 0;\n this.s1 = 0;\n this.s2 = 0;\n this.s3 = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit)\n continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n _updateBlock(s0, s1, s2, s3) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n clean(ZEROS32); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest() {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\nclass Polyval extends GHASH {\n constructor(key, expectedLength) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(copyBytes(key));\n super(ghKey, expectedLength);\n clean(ghKey);\n }\n update(data) {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));\n clean(ZEROS32);\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\nfunction wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key, expectedLength) => hashCons(key, expectedLength);\n return hashC;\n}\nexport const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));\nexport const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));\n//# sourceMappingURL=_polyval.js.map","// prettier-ignore\nimport { bytes as abytes } from './_assert.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { clean, concatBytes, copyBytes, createView, equalBytes, isAligned32, setBigUint64, u32, u8, wrapCipher, } from './utils.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// The byte swap operation for uint32 (LE<->BE)\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n if (!isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (dst === undefined)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n if (!isAligned32(dst))\n throw new Error('unaligned dst');\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n if (!isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error('aes/pcks5: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error('aes/pcks5: wrong padding');\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error('aes/pcks5: wrong padding');\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const toClean = [xk];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n const out = getDst(ciphertext.length, dst);\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n clean(...toClean);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n if (!isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD == null ? 0 : AAD.length;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(aadLength * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * GCM: Galois/Counter Mode.\n * Modern, parallel version of CTR, with MAC.\n * Be careful: MACs can be forged.\n * Unsafe to use random nonces under the same key, due to collision chance.\n * As for nonce size, prefer 12-byte, instead of 8-byte.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(key);\n abytes(nonce);\n if (AAD !== undefined)\n abytes(AAD);\n // NIST 800-38d doesn't enforce minimum nonce length.\n // We enforce 8 bytes for compat with openssl.\n // 12 bytes are recommended. More than 12 bytes would be converted into 12.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key, 16, 24, 32);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n if (!isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n if (!equalBytes(tag, expectedTag)) {\n clean(...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.\n // If you need it larger, open an issue.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i\n (a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1); // out = A || out\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);\n }\n }\n (o32[0] = a0), (o32[1] = a1);\n }\n xk.fill(0);\n },\n};\nconst AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * For padded version, use aeskwp.\n * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),\n * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).\n */\nexport const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Second u32 of IV is used as counter for length.\n * [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)\n */\nexport const aeskwp = wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n abytes(plaintext);\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = AESKWP_IV;\n out32[1] = byteSwap(plaintext.length);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n abytes(ciphertext);\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(o32[1]) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\n// Private, unsafe low-level methods. Can change at any time.\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Modified by ProtonTech AG\n\n// Modified by Recurity Labs GmbH\n\n// modified version of https://www.hanewin.net/encrypt/PGdecode.js:\n\n/* OpenPGP encryption using RSA/AES\n * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de\n * version 2.0, check www.haneWIN.de for the latest version\n\n * This software is provided as-is, without express or implied warranty.\n * Permission to use, copy, modify, distribute or sell this software, with or\n * without fee, for any purpose and by any individual or organization, is hereby\n * granted, provided that the above copyright notice and this paragraph appear\n * in all copies. Distribution as a part of an application or binary must\n * include the above copyright notice in the documentation and/or other\n * materials provided with the application or distribution.\n */\n\n/**\n * @module crypto/mode/cfb\n */\n\nimport { cfb as nobleAesCfb, unsafe as nobleAesHelpers } from '@noble/ciphers/aes';\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport util from '../../util';\nimport enums from '../../enums';\nimport { getLegacyCipher, getCipherParams } from '../cipher';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst knownAlgos = nodeCrypto ? nodeCrypto.getCiphers() : [];\nconst nodeAlgos = {\n idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */\n tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,\n cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,\n blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,\n aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,\n aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,\n aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined\n /* twofish is not implemented in OpenSSL */\n};\n\n/**\n * CFB encryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} plaintext\n * @param {Uint8Array} iv\n * @param {Object} config - full configuration, defaults to openpgp.config\n * @returns MaybeStream\n */\nexport async function encrypt(algo, key, plaintext, iv, config) {\n const algoName = enums.read(enums.symmetric, algo);\n if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.\n return nodeEncrypt(algo, key, plaintext, iv);\n }\n if (util.isAES(algo)) {\n return aesEncrypt(algo, key, plaintext, iv, config);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n const blockc = iv.slice();\n let pt = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n pt = util.concatUint8Array([pt, chunk]);\n }\n const ciphertext = new Uint8Array(pt.length);\n let i;\n let j = 0;\n while (chunk ? pt.length >= block_size : pt.length) {\n const encblock = cipherfn.encrypt(blockc);\n for (i = 0; i < block_size; i++) {\n blockc[i] = pt[i] ^ encblock[i];\n ciphertext[j++] = blockc[i];\n }\n pt = pt.subarray(block_size);\n }\n return ciphertext.subarray(0, j);\n };\n return stream.transform(plaintext, process, process);\n}\n\n/**\n * CFB decryption\n * @param {enums.symmetric} algo - block cipher algorithm\n * @param {Uint8Array} key\n * @param {MaybeStream} ciphertext\n * @param {Uint8Array} iv\n * @returns MaybeStream\n */\nexport async function decrypt(algo, key, ciphertext, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n if (nodeCrypto && nodeAlgos[algoName]) { // Node crypto library.\n return nodeDecrypt(algo, key, ciphertext, iv);\n }\n if (util.isAES(algo)) {\n return aesDecrypt(algo, key, ciphertext, iv);\n }\n\n const LegacyCipher = await getLegacyCipher(algo);\n const cipherfn = new LegacyCipher(key);\n const block_size = cipherfn.blockSize;\n\n let blockp = iv;\n let ct = new Uint8Array();\n const process = chunk => {\n if (chunk) {\n ct = util.concatUint8Array([ct, chunk]);\n }\n const plaintext = new Uint8Array(ct.length);\n let i;\n let j = 0;\n while (chunk ? ct.length >= block_size : ct.length) {\n const decblock = cipherfn.encrypt(blockp);\n blockp = ct.subarray(0, block_size);\n for (i = 0; i < block_size; i++) {\n plaintext[j++] = blockp[i] ^ decblock[i];\n }\n ct = ct.subarray(block_size);\n }\n return plaintext.subarray(0, j);\n };\n return stream.transform(ciphertext, process, process);\n}\n\nclass WebCryptoEncryptor {\n constructor(algo, key, iv) {\n const { blockSize } = getCipherParams(algo);\n this.key = key;\n this.prevBlock = iv;\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n this.zeroBlock = new Uint8Array(this.blockSize);\n }\n\n static async isSupported(algo) {\n const { keySize } = getCipherParams(algo);\n return webCrypto.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])\n .then(() => true, () => false);\n }\n\n async _runCBC(plaintext, nonZeroIV) {\n const mode = 'AES-CBC';\n this.keyRef = this.keyRef || await webCrypto.importKey('raw', this.key, mode, false, ['encrypt']);\n const ciphertext = await webCrypto.encrypt(\n { name: mode, iv: nonZeroIV || this.zeroBlock },\n this.keyRef,\n plaintext\n );\n return new Uint8Array(ciphertext).subarray(0, plaintext.length);\n }\n\n async encryptChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const plaintext = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n const toEncrypt = util.concatUint8Array([\n this.prevBlock,\n plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block \"early\", since we only need to xor the plaintext and pass it over as prevBlock\n ]);\n\n const encryptedBlocks = await this._runCBC(toEncrypt);\n xorMut(encryptedBlocks, plaintext);\n this.prevBlock = encryptedBlocks.slice(-this.blockSize);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return encryptedBlocks;\n }\n\n this.i += added.length;\n let encryptedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n const curBlock = this.nextBlock;\n encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n this.prevBlock = encryptedBlock.slice();\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n encryptedBlock = new Uint8Array();\n }\n\n return encryptedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n this.nextBlock = this.nextBlock.subarray(0, this.i);\n const curBlock = this.nextBlock;\n const encryptedBlock = await this._runCBC(this.prevBlock);\n xorMut(encryptedBlock, curBlock);\n result = encryptedBlock.subarray(0, curBlock.length);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.keyRef = null;\n this.key = null;\n }\n\n async encrypt(plaintext) {\n // plaintext is internally padded to block length before encryption\n const encryptedWithPadding = await this._runCBC(\n util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]),\n this.iv\n );\n // drop encrypted padding\n const ct = encryptedWithPadding.subarray(0, plaintext.length);\n xorMut(ct, plaintext);\n this.clearSensitiveData();\n return ct;\n }\n}\n\nclass NobleStreamProcessor {\n constructor(forEncryption, algo, key, iv) {\n this.forEncryption = forEncryption;\n const { blockSize } = getCipherParams(algo);\n this.key = nobleAesHelpers.expandKeyLE(key);\n\n if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers\n this.prevBlock = getUint32Array(iv);\n this.nextBlock = new Uint8Array(blockSize);\n this.i = 0; // pointer inside next block\n this.blockSize = blockSize;\n }\n\n _runCFB(src) {\n const src32 = getUint32Array(src);\n const dst = new Uint8Array(src.length);\n const dst32 = getUint32Array(dst);\n for (let i = 0; i + 4 <= dst32.length; i += 4) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = nobleAesHelpers.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);\n }\n return dst;\n }\n\n async processChunk(value) {\n const missing = this.nextBlock.length - this.i;\n const added = value.subarray(0, missing);\n this.nextBlock.set(added, this.i);\n\n if ((this.i + value.length) >= (2 * this.blockSize)) {\n const leftover = (value.length - missing) % this.blockSize;\n const toProcess = util.concatUint8Array([\n this.nextBlock,\n value.subarray(missing, value.length - leftover)\n ]);\n\n const processedBlocks = this._runCFB(toProcess);\n\n // take care of leftover data\n if (leftover > 0) this.nextBlock.set(value.subarray(-leftover));\n this.i = leftover;\n\n return processedBlocks;\n }\n\n this.i += added.length;\n\n let processedBlock;\n if (this.i === this.nextBlock.length) { // block ready to be encrypted\n processedBlock = this._runCFB(this.nextBlock);\n this.i = 0;\n\n const remaining = value.subarray(added.length);\n this.nextBlock.set(remaining, this.i);\n this.i += remaining.length;\n } else {\n processedBlock = new Uint8Array();\n }\n\n return processedBlock;\n }\n\n async finish() {\n let result;\n if (this.i === 0) { // nothing more to encrypt\n result = new Uint8Array();\n } else {\n const processedBlock = this._runCFB(this.nextBlock);\n\n result = processedBlock.subarray(0, this.i);\n }\n\n this.clearSensitiveData();\n return result;\n }\n\n clearSensitiveData() {\n this.nextBlock.fill(0);\n this.prevBlock.fill(0);\n this.key.fill(0);\n }\n}\n\n\nasync function aesEncrypt(algo, key, pt, iv) {\n if (webCrypto && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys\n const cfb = new WebCryptoEncryptor(algo, key, iv);\n return util.isStream(pt) ? stream.transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);\n } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream\n const cfb = new NobleStreamProcessor(true, algo, key, iv);\n return stream.transform(pt, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).encrypt(pt);\n}\n\nasync function aesDecrypt(algo, key, ct, iv) {\n if (util.isStream(ct)) {\n const cfb = new NobleStreamProcessor(false, algo, key, iv);\n return stream.transform(ct, value => cfb.processChunk(value), () => cfb.finish());\n }\n return nobleAesCfb(key, iv).decrypt(ct);\n}\n\nfunction xorMut(a, b) {\n const aLength = Math.min(a.length, b.length);\n for (let i = 0; i < aLength; i++) {\n a[i] = a[i] ^ b[i];\n }\n}\n\nconst getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction nodeEncrypt(algo, key, pt, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const cipherObj = new nodeCrypto.createCipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(pt, value => new Uint8Array(cipherObj.update(value)));\n}\n\nfunction nodeDecrypt(algo, key, ct, iv) {\n const algoName = enums.read(enums.symmetric, algo);\n const decipherObj = new nodeCrypto.createDecipheriv(nodeAlgos[algoName], key, iv);\n return stream.transform(ct, value => new Uint8Array(decipherObj.update(value)));\n}\n","/**\n * @fileoverview This module implements AES-CMAC on top of\n * native AES-CBC using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/cmac\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n\n/**\n * This implementation of CMAC is based on the description of OMAC in\n * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that\n * document:\n *\n * We have made a small modification to the OMAC algorithm as it was\n * originally presented, changing one of its two constants.\n * Specifically, the constant 4 at line 85 was the constant 1/2 (the\n * multiplicative inverse of 2) in the original definition of OMAC [14].\n * The OMAC authors indicate that they will promulgate this modification\n * [15], which slightly simplifies implementations.\n */\n\nconst blockLength = 16;\n\n\n/**\n * xor `padding` into the end of `data`. This function implements \"the\n * operation xor→ [which] xors the shorter string into the end of longer\n * one\". Since data is always as least as long as padding, we can\n * simplify the implementation.\n * @param {Uint8Array} data\n * @param {Uint8Array} padding\n */\nfunction rightXORMut(data, padding) {\n const offset = data.length - blockLength;\n for (let i = 0; i < blockLength; i++) {\n data[i + offset] ^= padding[i];\n }\n return data;\n}\n\nfunction pad(data, padding, padding2) {\n // if |M| in {n, 2n, 3n, ...}\n if (data.length && data.length % blockLength === 0) {\n // then return M xor→ B,\n return rightXORMut(data, padding);\n }\n // else return (M || 10^(n−1−(|M| mod n))) xor→ P\n const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));\n padded.set(data);\n padded[data.length] = 0b10000000;\n return rightXORMut(padded, padding2);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\n\nexport default async function CMAC(key) {\n const cbc = await CBC(key);\n\n // L ← E_K(0^n); B ← 2L; P ← 4L\n const padding = util.double(await cbc(zeroBlock));\n const padding2 = util.double(padding);\n\n return async function(data) {\n // return CBC_K(pad(M; B, P))\n return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);\n };\n}\n\nasync function CBC(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);\n const ct = en.update(pt);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt) {\n const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);\n return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt) {\n return nobleAesCbc(key, zeroBlock, { disablePadding: true }).encrypt(pt);\n };\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-EAX en/decryption on top of\n * native AES-CTR using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/mode/eax\n */\n\nimport { ctr as nobleAesCtr } from '@noble/ciphers/aes';\nimport CMAC from '../cmac';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\n\nconst blockLength = 16;\nconst ivLength = blockLength;\nconst tagLength = blockLength;\n\nconst zero = new Uint8Array(blockLength);\nconst one = new Uint8Array(blockLength); one[blockLength - 1] = 1;\nconst two = new Uint8Array(blockLength); two[blockLength - 1] = 2;\n\nasync function OMAC(key) {\n const cmac = await CMAC(key);\n return function(t, message) {\n return cmac(util.concatUint8Array([t, message]));\n };\n}\n\nasync function CTR(key) {\n if (util.getNodeCrypto()) { // Node crypto library\n return async function(pt, iv) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);\n const ct = Buffer.concat([en.update(pt), en.final()]);\n return new Uint8Array(ct);\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const keyRef = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);\n return async function(pt, iv) {\n const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, keyRef, pt);\n return new Uint8Array(ct);\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return async function(pt, iv) {\n return nobleAesCtr(key, iv).encrypt(pt);\n };\n}\n\n\n/**\n * Class to en/decrypt using EAX mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function EAX(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('EAX mode supports only AES cipher');\n }\n\n const [\n omac,\n ctr\n ] = await Promise.all([\n OMAC(key),\n CTR(key)\n ]);\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n const [\n omacNonce,\n omacAdata\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata)\n ]);\n const ciphered = await ctr(plaintext, omacNonce);\n const omacCiphered = await omac(two, ciphered);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n return util.concatUint8Array([ciphered, tag]);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (16 bytes)\n * @param {Uint8Array} adata - Associated data to verify\n * @returns {Promise} The plaintext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');\n const ciphered = ciphertext.subarray(0, -tagLength);\n const ctTag = ciphertext.subarray(-tagLength);\n const [\n omacNonce,\n omacAdata,\n omacCiphered\n ] = await Promise.all([\n omac(zero, nonce),\n omac(one, adata),\n omac(two, ciphered)\n ]);\n const tag = omacCiphered; // Assumes that omac(*).length === tagLength.\n for (let i = 0; i < tagLength; i++) {\n tag[i] ^= omacAdata[i] ^ omacNonce[i];\n }\n if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');\n const plaintext = await ctr(ciphered, omacNonce);\n return plaintext;\n }\n };\n}\n\n\n/**\n * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.\n * @param {Uint8Array} iv - The initialization vector (16 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nEAX.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[8 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nEAX.blockLength = blockLength;\nEAX.ivLength = ivLength;\nEAX.tagLength = tagLength;\n\nexport default EAX;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 ProtonTech AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module implements AES-OCB en/decryption.\n * @module crypto/mode/ocb\n */\n\nimport { cbc as nobleAesCbc } from '@noble/ciphers/aes';\nimport { getCipherParams } from '../cipher';\nimport util from '../../util';\n\nconst blockLength = 16;\nconst ivLength = 15;\n\n// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:\n// While OCB [RFC7253] allows the authentication tag length to be of any\n// number up to 128 bits long, this document requires a fixed\n// authentication tag length of 128 bits (16 octets) for simplicity.\nconst tagLength = 16;\n\n\nfunction ntz(n) {\n let ntz = 0;\n for (let i = 1; (n & i) === 0; i <<= 1) {\n ntz++;\n }\n return ntz;\n}\n\nfunction xorMut(S, T) {\n for (let i = 0; i < S.length; i++) {\n S[i] ^= T[i];\n }\n return S;\n}\n\nfunction xor(S, T) {\n return xorMut(S.slice(), T);\n}\n\nconst zeroBlock = new Uint8Array(blockLength);\nconst one = new Uint8Array([1]);\n\n/**\n * Class to en/decrypt using OCB mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function OCB(cipher, key) {\n const { keySize } = getCipherParams(cipher);\n // sanity checks\n if (!util.isAES(cipher) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let maxNtz = 0;\n\n // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,\n // hence its execution cannot be broken up.\n // As a result, WebCrypto cannot currently be used for `encipher`.\n const aes = nobleAesCbc(key, zeroBlock, { disablePadding: true });\n const encipher = block => aes.encrypt(block);\n const decipher = block => aes.decrypt(block);\n let mask;\n\n constructKeyVariables(cipher, key);\n\n function constructKeyVariables() {\n const mask_x = encipher(zeroBlock);\n const mask_$ = util.double(mask_x);\n mask = [];\n mask[0] = util.double(mask_$);\n\n\n mask.x = mask_x;\n mask.$ = mask_$;\n }\n\n function extendKeyVariables(text, adata) {\n const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;\n for (let i = maxNtz + 1; i <= newMaxNtz; i++) {\n mask[i] = util.double(mask[i - 1]);\n }\n maxNtz = newMaxNtz;\n }\n\n function hash(adata) {\n if (!adata.length) {\n // Fast path\n return zeroBlock;\n }\n\n //\n // Consider A as a sequence of 128-bit blocks\n //\n const m = adata.length / blockLength | 0;\n\n const offset = new Uint8Array(blockLength);\n const sum = new Uint8Array(blockLength);\n for (let i = 0; i < m; i++) {\n xorMut(offset, mask[ntz(i + 1)]);\n xorMut(sum, encipher(xor(offset, adata)));\n adata = adata.subarray(blockLength);\n }\n\n //\n // Process any final partial block; compute final hash value\n //\n if (adata.length) {\n xorMut(offset, mask.x);\n\n const cipherInput = new Uint8Array(blockLength);\n cipherInput.set(adata, 0);\n cipherInput[adata.length] = 0b10000000;\n xorMut(cipherInput, offset);\n\n xorMut(sum, encipher(cipherInput));\n }\n\n return sum;\n }\n\n /**\n * Encrypt/decrypt data.\n * @param {encipher|decipher} fn - Encryption/decryption block cipher function\n * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases.\n */\n function crypt(fn, text, nonce, adata) {\n //\n // Consider P as a sequence of 128-bit blocks\n //\n const m = text.length / blockLength | 0;\n\n //\n // Key-dependent variables\n //\n extendKeyVariables(text, adata);\n\n //\n // Nonce-dependent and per-encryption variables\n //\n // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N\n // Note: We assume here that tagLength mod 16 == 0.\n const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);\n // bottom = str2num(Nonce[123..128])\n const bottom = paddedNonce[blockLength - 1] & 0b111111;\n // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))\n paddedNonce[blockLength - 1] &= 0b11000000;\n const kTop = encipher(paddedNonce);\n // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])\n const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);\n // Offset_0 = Stretch[1+bottom..128+bottom]\n const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);\n // Checksum_0 = zeros(128)\n const checksum = new Uint8Array(blockLength);\n\n const ct = new Uint8Array(text.length + tagLength);\n\n //\n // Process any whole blocks\n //\n let i;\n let pos = 0;\n for (i = 0; i < m; i++) {\n // Offset_i = Offset_{i-1} xor L_{ntz(i)}\n xorMut(offset, mask[ntz(i + 1)]);\n // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)\n // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)\n ct.set(xorMut(fn(xor(offset, text)), offset), pos);\n // Checksum_i = Checksum_{i-1} xor P_i\n xorMut(checksum, fn === encipher ? text : ct.subarray(pos));\n\n text = text.subarray(blockLength);\n pos += blockLength;\n }\n\n //\n // Process any final partial block and compute raw tag\n //\n if (text.length) {\n // Offset_* = Offset_m xor L_*\n xorMut(offset, mask.x);\n // Pad = ENCIPHER(K, Offset_*)\n const padding = encipher(offset);\n // C_* = P_* xor Pad[1..bitlen(P_*)]\n ct.set(xor(text, padding), pos);\n\n // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))\n const xorInput = new Uint8Array(blockLength);\n xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);\n xorInput[text.length] = 0b10000000;\n xorMut(checksum, xorInput);\n pos += text.length;\n }\n // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)\n const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));\n\n //\n // Assemble ciphertext\n //\n // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]\n ct.set(tag, pos);\n return ct;\n }\n\n\n return {\n /**\n * Encrypt plaintext input.\n * @param {Uint8Array} plaintext - The cleartext input to be encrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n encrypt: async function(plaintext, nonce, adata) {\n return crypt(encipher, plaintext, nonce, adata);\n },\n\n /**\n * Decrypt ciphertext input.\n * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted\n * @param {Uint8Array} nonce - The nonce (15 bytes)\n * @param {Uint8Array} adata - Associated data to sign\n * @returns {Promise} The ciphertext output.\n */\n decrypt: async function(ciphertext, nonce, adata) {\n if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');\n\n const tag = ciphertext.subarray(-tagLength);\n ciphertext = ciphertext.subarray(0, -tagLength);\n\n const crypted = crypt(decipher, ciphertext, nonce, adata);\n // if (Tag[1..TAGLEN] == T)\n if (util.equalsUint8Array(tag, crypted.subarray(-tagLength))) {\n return crypted.subarray(0, -tagLength);\n }\n throw new Error('Authentication tag mismatch');\n }\n };\n}\n\n\n/**\n * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.\n * @param {Uint8Array} iv - The initialization vector (15 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nOCB.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[7 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nOCB.blockLength = blockLength;\nOCB.ivLength = ivLength;\nOCB.tagLength = tagLength;\n\nexport default OCB;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview This module wraps native AES-GCM en/decryption for both\n * the WebCrypto api as well as node.js' crypto api.\n * @module crypto/mode/gcm\n */\n\nimport { gcm as nobleAesGcm } from '@noble/ciphers/aes';\nimport util from '../../util';\nimport enums from '../../enums';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst Buffer = util.getNodeBuffer();\n\nconst blockLength = 16;\nconst ivLength = 12; // size of the IV in bytes\nconst tagLength = 16; // size of the tag in bytes\nconst ALGO = 'AES-GCM';\n\n/**\n * Class to en/decrypt using GCM mode.\n * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use\n * @param {Uint8Array} key - The encryption key\n */\nasync function GCM(cipher, key) {\n if (cipher !== enums.symmetric.aes128 &&\n cipher !== enums.symmetric.aes192 &&\n cipher !== enums.symmetric.aes256) {\n throw new Error('GCM mode supports only AES cipher');\n }\n\n if (util.getNodeCrypto()) { // Node crypto library\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n en.setAAD(adata);\n const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);\n de.setAAD(adata);\n de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext\n const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);\n return new Uint8Array(pt);\n }\n };\n }\n\n if (util.getWebCrypto()) {\n try {\n const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);\n // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages\n const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\\/13\\.\\d(\\.\\d)* Safari/) ||\n navigator.userAgent.match(/Version\\/(13|14)\\.\\d(\\.\\d)* Mobile\\/\\S* Safari/);\n return {\n encrypt: async function(pt, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && !pt.length) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n }\n const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);\n return new Uint8Array(ct);\n },\n\n decrypt: async function(ct, iv, adata = new Uint8Array()) {\n if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n try {\n const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);\n return new Uint8Array(pt);\n } catch (e) {\n if (e.name === 'OperationError') {\n throw new Error('Authentication tag mismatch');\n }\n }\n }\n };\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n }\n\n return {\n encrypt: async function(pt, iv, adata) {\n return nobleAesGcm(key, iv, adata).encrypt(pt);\n },\n\n decrypt: async function(ct, iv, adata) {\n return nobleAesGcm(key, iv, adata).decrypt(ct);\n }\n };\n}\n\n\n/**\n * Get GCM nonce. Note: this operation is not defined by the standard.\n * A future version of the standard may define GCM mode differently,\n * hopefully under a different ID (we use Private/Experimental algorithm\n * ID 100) so that we can maintain backwards compatibility.\n * @param {Uint8Array} iv - The initialization vector (12 bytes)\n * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)\n */\nGCM.getNonce = function(iv, chunkIndex) {\n const nonce = iv.slice();\n for (let i = 0; i < chunkIndex.length; i++) {\n nonce[4 + i] ^= chunkIndex[i];\n }\n return nonce;\n};\n\nGCM.blockLength = blockLength;\nGCM.ivLength = ivLength;\nGCM.tagLength = tagLength;\n\nexport default GCM;\n","/**\n * @fileoverview Cipher modes\n * @module crypto/mode\n */\n\nimport * as cfb from './cfb';\nimport eax from './eax';\nimport ocb from './ocb';\nimport gcm from './gcm';\n\nexport default {\n /** @see module:crypto/mode/cfb */\n cfb: cfb,\n /** @see module:crypto/mode/gcm */\n gcm: gcm,\n experimentalGCM: gcm,\n /** @see module:crypto/mode/eax */\n eax: eax,\n /** @see module:crypto/mode/ocb */\n ocb: ocb\n};\n","// Operations are not constant time, but we try and limit timing leakage where we can\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport function uint8ArrayToBigInt(bytes: Uint8Array) {\n const hexAlphabet = '0123456789ABCDEF';\n let s = '';\n bytes.forEach(v => {\n s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];\n });\n return BigInt('0x0' + s);\n}\n\nexport function mod(a: bigint, m: bigint) {\n const reduced = a % m;\n return reduced < _0n ? reduced + m : reduced;\n}\n\n/**\n * Compute modular exponentiation using square and multiply\n * @param {BigInt} a - Base\n * @param {BigInt} e - Exponent\n * @param {BigInt} n - Modulo\n * @returns {BigInt} b ** e mod n.\n */\nexport function modExp(b: bigint, e: bigint, n: bigint) {\n if (n === _0n) throw Error('Modulo cannot be zero');\n if (n === _1n) return BigInt(0);\n if (e < _0n) throw Error('Unsopported negative exponent');\n\n let exp = e;\n let x = b;\n\n x %= n;\n let r = BigInt(1);\n while (exp > _0n) {\n const lsb = exp & _1n;\n exp >>= _1n; // e / 2\n // Always compute multiplication step, to reduce timing leakage\n const rx = (r * x) % n;\n // Update r only if lsb is 1 (odd exponent)\n r = lsb ? rx : r;\n x = (x * x) % n; // Square\n }\n return r;\n}\n\n\nfunction abs(x: bigint) {\n return x >= _0n ? x : -x;\n}\n\n/**\n * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)\n * Given a and b, compute (x, y) such that ax + by = gdc(a, b).\n * Negative numbers are also supported.\n * @param {BigInt} a - First operand\n * @param {BigInt} b - Second operand\n * @returns {{ gcd, x, y: bigint }}\n */\nfunction _egcd(aInput: bigint, bInput: bigint) {\n let x = BigInt(0);\n let y = BigInt(1);\n let xPrev = BigInt(1);\n let yPrev = BigInt(0);\n\n // Deal with negative numbers: run algo over absolute values,\n // and \"move\" the sign to the returned x and/or y.\n // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers\n let a = abs(aInput);\n let b = abs(bInput);\n const aNegated = aInput < _0n;\n const bNegated = bInput < _0n;\n\n while (b !== _0n) {\n const q = a / b;\n let tmp = x;\n x = xPrev - q * x;\n xPrev = tmp;\n\n tmp = y;\n y = yPrev - q * y;\n yPrev = tmp;\n\n tmp = b;\n b = a % b;\n a = tmp;\n }\n\n return {\n x: aNegated ? -xPrev : xPrev,\n y: bNegated ? -yPrev : yPrev,\n gcd: a\n };\n}\n\n/**\n * Compute the inverse of `a` modulo `n`\n * Note: `a` and and `n` must be relatively prime\n * @param {BigInt} a\n * @param {BigInt} n - Modulo\n * @returns {BigInt} x such that a*x = 1 mod n\n * @throws {Error} if the inverse does not exist\n */\nexport function modInv(a: bigint, n: bigint) {\n const { gcd, x } = _egcd(a, n);\n if (gcd !== _1n) {\n throw new Error('Inverse does not exist');\n }\n return mod(x + n, n);\n}\n\n/**\n * Compute greatest common divisor between this and n\n * @param {BigInt} aInput - Operand\n * @param {BigInt} bInput - Operand\n * @returns {BigInt} gcd\n */\nexport function gcd(aInput: bigint, bInput: bigint) {\n let a = aInput;\n let b = bInput;\n while (b !== _0n) {\n const tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\n/**\n * Get this value as an exact Number (max 53 bits)\n * Fails if this value is too large\n * @returns {Number}\n */\nexport function bigIntToNumber(x: bigint) {\n const number = Number(x);\n if (number > Number.MAX_SAFE_INTEGER) {\n // We throw and error to conform with the bn.js implementation\n throw new Error('Number can only safely store up to 53 bits');\n }\n return number;\n}\n\n/**\n * Get value of i-th bit\n * @param {BigInt} x\n * @param {Number} i - Bit index\n * @returns {Number} Bit value.\n */\nexport function getBit(x:bigint, i: number) {\n const bit = (x >> BigInt(i)) & _1n;\n return bit === _0n ? 0 : 1;\n}\n\n/**\n * Compute bit length\n */\nexport function bitLength(x: bigint) {\n // -1n >> -1n is -1n\n // 1n >> 1n is 0n\n const target = x < _0n ? BigInt(-1) : _0n;\n let bitlen = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _1n) !== target) {\n bitlen++;\n }\n return bitlen;\n}\n\n/**\n * Compute byte length\n */\nexport function byteLength(x: bigint) {\n const target = x < _0n ? BigInt(-1) : _0n;\n const _8n = BigInt(8);\n let len = 1;\n let tmp = x;\n // eslint-disable-next-line no-cond-assign\n while ((tmp >>= _8n) !== target) {\n len++;\n }\n return len;\n}\n\n/**\n * Get Uint8Array representation of this number\n * @param {String} endian - Endianess of output array (defaults to 'be')\n * @param {Number} length - Of output array\n * @returns {Uint8Array}\n */\nexport function bigIntToUint8Array(x: bigint, endian = 'be', length: number) {\n // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)\n // this is faster than shift+mod iterations\n let hex = x.toString(16);\n if (hex.length % 2 === 1) {\n hex = '0' + hex;\n }\n\n const rawLength = hex.length / 2;\n const bytes = new Uint8Array(length || rawLength);\n // parse hex\n const offset = length ? length - rawLength : 0;\n let i = 0;\n while (i < rawLength) {\n bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);\n i++;\n }\n\n if (endian !== 'be') {\n bytes.reverse();\n }\n\n return bytes;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js\n * @module crypto/random\n */\nimport { byteLength, mod, uint8ArrayToBigInt } from './biginteger';\nimport util from '../util';\n\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Retrieve secure random byte array of the specified length\n * @param {Integer} length - Length in bytes to generate\n * @returns {Uint8Array} Random byte array.\n */\nexport function getRandomBytes(length) {\n const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto?.webcrypto;\n if (webcrypto?.getRandomValues) {\n const buf = new Uint8Array(length);\n return webcrypto.getRandomValues(buf);\n } else {\n throw new Error('No secure random number generator available.');\n }\n}\n\n/**\n * Create a secure random BigInt that is greater than or equal to min and less than max.\n * @param {bigint} min - Lower bound, included\n * @param {bigint} max - Upper bound, excluded\n * @returns {bigint} Random BigInt.\n * @async\n */\nexport function getRandomBigInteger(min, max) {\n if (max < min) {\n throw new Error('Illegal parameter value: max <= min');\n }\n\n const modulus = max - min;\n const bytes = byteLength(modulus);\n\n // Using a while loop is necessary to avoid bias introduced by the mod operation.\n // However, we request 64 extra random bits so that the bias is negligible.\n // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));\n return mod(r, modulus) + min;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Algorithms for probabilistic random prime generation\n * @module crypto/public_key/prime\n */\nimport { bigIntToNumber, bitLength, gcd, getBit, mod, modExp } from '../biginteger';\nimport { getRandomBigInteger } from '../random';\n\nconst _1n = BigInt(1);\n\n/**\n * Generate a probably prime random number\n * @param bits - Bit length of the prime\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function randomProbablePrime(bits: number, e: bigint, k: number) {\n const _30n = BigInt(30);\n const min = _1n << BigInt(bits - 1);\n /*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */\n const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];\n\n let n = getRandomBigInteger(min, min << _1n);\n let i = bigIntToNumber(mod(n, _30n));\n\n do {\n n += BigInt(adds[i]);\n i = (i + adds[i]) % adds.length;\n // If reached the maximum, go back to the minimum.\n if (bitLength(n) > bits) {\n n = mod(n, min << _1n); n += min;\n i = bigIntToNumber(mod(n, _30n));\n }\n } while (!isProbablePrime(n, e, k));\n return n;\n}\n\n/**\n * Probabilistic primality testing\n * @param n - Number to test\n * @param e - Optional RSA exponent to check against the prime\n * @param k - Optional number of iterations of Miller-Rabin test\n */\nexport function isProbablePrime(n: bigint, e: bigint, k: number) {\n if (e && gcd(n - _1n, e) !== _1n) {\n return false;\n }\n if (!divisionTest(n)) {\n return false;\n }\n if (!fermat(n)) {\n return false;\n }\n if (!millerRabin(n, k)) {\n return false;\n }\n // TODO implement the Lucas test\n // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n return true;\n}\n\n/**\n * Tests whether n is probably prime or not using Fermat's test with b = 2.\n * Fails if b^(n-1) mod n != 1.\n * @param n - Number to test\n * @param b - Optional Fermat test base\n */\nexport function fermat(n: bigint, b = BigInt(2)) {\n return modExp(b, n - _1n, n) === _1n;\n}\n\nexport function divisionTest(n: bigint) {\n const _0n = BigInt(0);\n return smallPrimes.every(m => mod(n, m) !== _0n);\n}\n\n// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c\nconst smallPrimes = [\n 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,\n 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,\n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,\n 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,\n 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,\n 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,\n 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,\n 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,\n 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,\n 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,\n 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,\n 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,\n 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,\n 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,\n 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,\n 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,\n 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,\n 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,\n 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,\n 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,\n 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,\n 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,\n 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,\n 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,\n 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,\n 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,\n 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,\n 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,\n 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,\n 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,\n 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,\n 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,\n 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,\n 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,\n 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,\n 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,\n 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,\n 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,\n 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,\n 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,\n 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,\n 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,\n 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,\n 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,\n 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,\n 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,\n 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,\n 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,\n 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,\n 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,\n 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,\n 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\n 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,\n 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,\n 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,\n 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,\n 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,\n 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,\n 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,\n 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,\n 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,\n 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,\n 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,\n 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,\n 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,\n 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,\n 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,\n 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,\n 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,\n 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,\n 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,\n 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,\n 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,\n 4957, 4967, 4969, 4973, 4987, 4993, 4999\n].map(n => BigInt(n));\n\n\n// Miller-Rabin - Miller Rabin algorithm for primality test\n// Copyright Fedor Indutny, 2014.\n//\n// This software is licensed under the MIT License.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin\n\n// Sample syntax for Fixed-Base Miller-Rabin:\n// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))\n\n/**\n * Tests whether n is probably prime or not using the Miller-Rabin test.\n * See HAC Remark 4.28.\n * @param n - Number to test\n * @param k - Optional number of iterations of Miller-Rabin test\n * @param rand - Optional function to generate potential witnesses\n * @returns {boolean}\n * @async\n */\nexport function millerRabin(n: bigint, k: number, rand?: () => bigint) {\n const len = bitLength(n);\n\n if (!k) {\n k = Math.max(1, (len / 48) | 0);\n }\n\n const n1 = n - _1n; // n - 1\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n let s = 0;\n while (!getBit(n1, s)) { s++; }\n const d = n >> BigInt(s);\n\n for (; k > 0; k--) {\n const a = rand ? rand() : getRandomBigInteger(BigInt(2), n1);\n\n let x = modExp(a, d, n);\n if (x === _1n || x === n1) {\n continue;\n }\n\n let i;\n for (i = 1; i < s; i++) {\n x = mod(x * x, n);\n\n if (x === _1n) {\n return false;\n }\n if (x === n1) {\n break;\n }\n }\n\n if (i === s) {\n return false;\n }\n }\n\n return true;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function\n * @see module:crypto/public_key/rsa\n * @see module:crypto/public_key/elliptic/ecdh\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs1\n */\n\nimport { getRandomBytes } from './random';\nimport hash from './hash';\nimport util from '../util';\n\n/**\n * ASN1 object identifiers for hashes\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}\n */\nconst hash_headers = [];\nhash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,\n 0x10];\nhash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];\nhash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];\nhash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,\n 0x04, 0x20];\nhash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,\n 0x04, 0x30];\nhash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,\n 0x00, 0x04, 0x40];\nhash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,\n 0x00, 0x04, 0x1C];\n\n/**\n * Create padding with secure random data\n * @private\n * @param {Integer} length - Length of the padding in bytes\n * @returns {Uint8Array} Random padding.\n */\nfunction getPKCS1Padding(length) {\n const result = new Uint8Array(length);\n let count = 0;\n while (count < length) {\n const randomBytes = getRandomBytes(length - count);\n for (let i = 0; i < randomBytes.length; i++) {\n if (randomBytes[i] !== 0) {\n result[count++] = randomBytes[i];\n }\n }\n }\n return result;\n}\n\n/**\n * Create a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}\n * @param {Uint8Array} message - Message to be encoded\n * @param {Integer} keyLength - The length in octets of the key modulus\n * @returns {Uint8Array} EME-PKCS1 padded message.\n */\nexport function emeEncode(message, keyLength) {\n const mLength = message.length;\n // length checking\n if (mLength > keyLength - 11) {\n throw new Error('Message too long');\n }\n // Generate an octet string PS of length k - mLen - 3 consisting of\n // pseudo-randomly generated nonzero octets\n const PS = getPKCS1Padding(keyLength - mLength - 3);\n // Concatenate PS, the message M, and other padding to form an\n // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.\n const encoded = new Uint8Array(keyLength);\n // 0x00 byte\n encoded[1] = 2;\n encoded.set(PS, 2);\n // 0x00 bytes\n encoded.set(message, keyLength - mLength);\n return encoded;\n}\n\n/**\n * Decode a EME-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}\n * @param {Uint8Array} encoded - Encoded message bytes\n * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)\n * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)\n * @throws {Error} on decoding failure, unless `randomPayload` is provided\n */\nexport function emeDecode(encoded, randomPayload) {\n // encoded format: 0x00 0x02 0x00 \n let offset = 2;\n let separatorNotFound = 1;\n for (let j = offset; j < encoded.length; j++) {\n separatorNotFound &= encoded[j] !== 0;\n offset += separatorNotFound;\n }\n\n const psLen = offset - 2;\n const payload = encoded.subarray(offset + 1); // discard the 0x00 separator\n const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;\n\n if (randomPayload) {\n return util.selectUint8Array(isValidPadding, payload, randomPayload);\n }\n\n if (isValidPadding) {\n return payload;\n }\n\n throw new Error('Decryption error');\n}\n\n/**\n * Create a EMSA-PKCS1-v1_5 padded message\n * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}\n * @param {Integer} algo - Hash algorithm type used\n * @param {Uint8Array} hashed - Message to be encoded\n * @param {Integer} emLen - Intended length in octets of the encoded message\n * @returns {Uint8Array} Encoded message.\n */\nexport function emsaEncode(algo, hashed, emLen) {\n let i;\n if (hashed.length !== hash.getHashByteLength(algo)) {\n throw new Error('Invalid hash length');\n }\n // produce an ASN.1 DER value for the hash function used.\n // Let T be the full hash prefix\n const hashPrefix = new Uint8Array(hash_headers[algo].length);\n for (i = 0; i < hash_headers[algo].length; i++) {\n hashPrefix[i] = hash_headers[algo][i];\n }\n // and let tLen be the length in octets prefix and hashed data\n const tLen = hashPrefix.length + hashed.length;\n if (emLen < tLen + 11) {\n throw new Error('Intended encoded message length too short');\n }\n // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF\n // The length of PS will be at least 8 octets\n const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);\n\n // Concatenate PS, the hash prefix, hashed data, and other padding to form the\n // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed\n const EM = new Uint8Array(emLen);\n EM[1] = 0x01;\n EM.set(PS, 2);\n EM.set(hashPrefix, emLen - tLen);\n EM.set(hashed, emLen - hashed.length);\n return EM;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview RSA implementation\n * @module crypto/public_key/rsa\n */\nimport { randomProbablePrime } from './prime';\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../encoding/base64';\nimport { emsaEncode, emeEncode, emeDecode } from '../pkcs1';\nimport enums from '../../enums';\nimport { bigIntToNumber, bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\nimport hash from '../hash';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\nconst _1n = BigInt(1);\n\n/** Create signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Promise} RSA Signature.\n * @async\n */\nexport async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {\n if (hash.getHashByteLength(hashAlgo) >= n.length) {\n // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error\n // e.g. if a 512-bit RSA key is used with a SHA-512 digest.\n // The size limit is actually slightly different but here we only care about throwing\n // on common key sizes.\n throw new Error('Digest size cannot exceed key modulus size');\n }\n\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeSign(hashAlgo, data, n, e, d, p, q, u);\n }\n }\n return bnSign(hashAlgo, n, d, hashed);\n}\n\n/**\n * Verify signature\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} s - Signature\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} hashed - Hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(hashAlgo, data, s, n, e, hashed) {\n if (data && !util.isStream(data)) {\n if (util.getWebCrypto()) {\n try {\n return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);\n } catch (err) {\n util.printDebugError(err);\n }\n } else if (util.getNodeCrypto()) {\n return nodeVerify(hashAlgo, data, s, n, e);\n }\n }\n return bnVerify(hashAlgo, s, n, e, hashed);\n}\n\n/**\n * Encrypt message\n * @param {Uint8Array} data - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @returns {Promise} RSA Ciphertext.\n * @async\n */\nexport async function encrypt(data, n, e) {\n if (util.getNodeCrypto()) {\n return nodeEncrypt(data, n, e);\n }\n return bnEncrypt(data, n, e);\n}\n\n/**\n * Decrypt RSA message\n * @param {Uint8Array} m - Message\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA private coefficient\n * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} RSA Plaintext.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(data, n, e, d, p, q, u, randomPayload) {\n // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,\n // and we want to avoid checking the error type to decide if the random payload\n // should indeed be returned.\n if (util.getNodeCrypto() && !randomPayload) {\n try {\n return await nodeDecrypt(data, n, e, d, p, q, u);\n } catch (err) {\n util.printDebugError(err);\n }\n }\n return bnDecrypt(data, n, e, d, p, q, u, randomPayload);\n}\n\n/**\n * Generate a new random private key B bits long with public exponent E.\n *\n * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using\n * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.\n * @see module:crypto/public_key/prime\n * @param {Integer} bits - RSA bit length\n * @param {Integer} e - RSA public exponent\n * @returns {{n, e, d,\n * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,\n * RSA private prime p, RSA private prime q, u = p ** -1 mod q\n * @async\n */\nexport async function generate(bits, e) {\n e = BigInt(e);\n\n // Native RSA keygen using Web Crypto\n if (util.getWebCrypto()) {\n const keyGenOpt = {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits, // the specified keysize in bits\n publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent\n hash: {\n name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'\n }\n };\n const keyPair = await webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);\n\n // export the generated keys as JsonWebKey (JWK)\n // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33\n const jwk = await webCrypto.exportKey('jwk', keyPair.privateKey);\n // map JWK parameters to corresponding OpenPGP names\n return jwkToPrivate(jwk, e);\n } else if (util.getNodeCrypto()) {\n const opts = {\n modulusLength: bits,\n publicExponent: bigIntToNumber(e),\n publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },\n privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }\n };\n const jwk = await new Promise((resolve, reject) => {\n nodeCrypto.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {\n if (err) {\n reject(err);\n } else {\n resolve(jwkPrivateKey);\n }\n });\n });\n return jwkToPrivate(jwk, e);\n }\n\n // RSA keygen fallback using 40 iterations of the Miller-Rabin test\n // See https://stackoverflow.com/a/6330138 for justification\n // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST\n let p;\n let q;\n let n;\n do {\n q = randomProbablePrime(bits - (bits >> 1), e, 40);\n p = randomProbablePrime(bits >> 1, e, 40);\n n = p * q;\n } while (bitLength(n) !== bits);\n\n const phi = (p - _1n) * (q - _1n);\n\n if (q < p) {\n [p, q] = [q, p];\n }\n\n return {\n n: bigIntToUint8Array(n),\n e: bigIntToUint8Array(e),\n d: bigIntToUint8Array(modInv(e, phi)),\n p: bigIntToUint8Array(p),\n q: bigIntToUint8Array(q),\n // dp: d.mod(p.subn(1)),\n // dq: d.mod(q.subn(1)),\n u: bigIntToUint8Array(modInv(p, q))\n };\n}\n\n/**\n * Validate RSA parameters\n * @param {Uint8Array} n - RSA public modulus\n * @param {Uint8Array} e - RSA public exponent\n * @param {Uint8Array} d - RSA private exponent\n * @param {Uint8Array} p - RSA private prime p\n * @param {Uint8Array} q - RSA private prime q\n * @param {Uint8Array} u - RSA inverse of p w.r.t. q\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(n, e, d, p, q, u) {\n n = uint8ArrayToBigInt(n);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n\n // expect pq = n\n if ((p * q) !== n) {\n return false;\n }\n\n const _2n = BigInt(2);\n // expect p*u = 1 mod q\n u = uint8ArrayToBigInt(u);\n if (mod(p * u, q) !== BigInt(1)) {\n return false;\n }\n\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n /**\n * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)\n * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]\n * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]\n *\n * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)\n */\n const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));\n const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q\n const rde = r * d * e;\n\n const areInverses = mod(rde, p - _1n) === r && mod(rde, q - _1n) === r;\n if (!areInverses) {\n return false;\n }\n\n return true;\n}\n\nasync function bnSign(hashAlgo, n, d, hashed) {\n n = uint8ArrayToBigInt(n);\n const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));\n d = uint8ArrayToBigInt(d);\n return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));\n}\n\nasync function webSign(hashName, data, n, e, d, p, q, u) {\n /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.\n * We swap them in privateToJWK, so it usually works out, but nevertheless,\n * not all OpenPGP keys are compatible with this requirement.\n * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still\n * does if the underlying Web Crypto does so (though the tested implementations\n * don't do so).\n */\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n };\n const key = await webCrypto.importKey('jwk', jwk, algo, false, ['sign']);\n return new Uint8Array(await webCrypto.sign('RSASSA-PKCS1-v1_5', key, data));\n}\n\nasync function nodeSign(hashAlgo, data, n, e, d, p, q, u) {\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(data);\n sign.end();\n\n const jwk = await privateToJWK(n, e, d, p, q, u);\n return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));\n}\n\nasync function bnVerify(hashAlgo, s, n, e, hashed) {\n n = uint8ArrayToBigInt(n);\n s = uint8ArrayToBigInt(s);\n e = uint8ArrayToBigInt(e);\n if (s >= n) {\n throw new Error('Signature size cannot exceed modulus size');\n }\n const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));\n const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));\n return util.equalsUint8Array(EM1, EM2);\n}\n\nasync function webVerify(hashName, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = await webCrypto.importKey('jwk', jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName }\n }, false, ['verify']);\n return webCrypto.verify('RSASSA-PKCS1-v1_5', key, s, data);\n}\n\nasync function nodeVerify(hashAlgo, data, s, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1' };\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(data);\n verify.end();\n\n try {\n return verify.verify(key, s);\n } catch (err) {\n return false;\n }\n}\n\nasync function nodeEncrypt(data, n, e) {\n const jwk = publicToJWK(n, e);\n const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n return new Uint8Array(nodeCrypto.publicEncrypt(key, data));\n}\n\nasync function bnEncrypt(data, n, e) {\n n = uint8ArrayToBigInt(n);\n data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));\n e = uint8ArrayToBigInt(e);\n if (data >= n) {\n throw new Error('Message size cannot exceed modulus size');\n }\n return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));\n}\n\nasync function nodeDecrypt(data, n, e, d, p, q, u) {\n const jwk = await privateToJWK(n, e, d, p, q, u);\n const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };\n\n try {\n return new Uint8Array(nodeCrypto.privateDecrypt(key, data));\n } catch (err) {\n throw new Error('Decryption error');\n }\n}\n\nasync function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {\n data = uint8ArrayToBigInt(data);\n n = uint8ArrayToBigInt(n);\n e = uint8ArrayToBigInt(e);\n d = uint8ArrayToBigInt(d);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n u = uint8ArrayToBigInt(u);\n if (data >= n) {\n throw new Error('Data too large.');\n }\n const dq = mod(d, q - _1n); // d mod (q-1)\n const dp = mod(d, p - _1n); // d mod (p-1)\n\n const unblinder = getRandomBigInteger(BigInt(2), n);\n const blinder = modExp(modInv(unblinder, n), e, n);\n data = mod(data * blinder, n);\n\n const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p\n const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q\n const h = mod(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)\n\n let result = h * p + mp; // result < n due to relations above\n\n result = mod(result * unblinder, n);\n\n return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);\n}\n\n/** Convert Openpgp private key params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n * @param {Uint8Array} d\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} u\n */\nasync function privateToJWK(n, e, d, p, q, u) {\n const pNum = uint8ArrayToBigInt(p);\n const qNum = uint8ArrayToBigInt(q);\n const dNum = uint8ArrayToBigInt(d);\n\n let dq = mod(dNum, qNum - _1n); // d mod (q-1)\n let dp = mod(dNum, pNum - _1n); // d mod (p-1)\n dp = bigIntToUint8Array(dp);\n dq = bigIntToUint8Array(dq);\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n d: uint8ArrayToB64(d, true),\n // switch p and q\n p: uint8ArrayToB64(q, true),\n q: uint8ArrayToB64(p, true),\n // switch dp and dq\n dp: uint8ArrayToB64(dq, true),\n dq: uint8ArrayToB64(dp, true),\n qi: uint8ArrayToB64(u, true),\n ext: true\n };\n}\n\n/** Convert Openpgp key public params to jwk key according to\n * @link https://tools.ietf.org/html/rfc7517\n * @param {String} hashAlgo\n * @param {Uint8Array} n\n * @param {Uint8Array} e\n */\nfunction publicToJWK(n, e) {\n return {\n kty: 'RSA',\n n: uint8ArrayToB64(n, true),\n e: uint8ArrayToB64(e, true),\n ext: true\n };\n}\n\n/** Convert JWK private key to OpenPGP private key params */\nfunction jwkToPrivate(jwk, e) {\n return {\n n: b64ToUint8Array(jwk.n),\n e: bigIntToUint8Array(e),\n d: b64ToUint8Array(jwk.d),\n // switch p and q\n p: b64ToUint8Array(jwk.q),\n q: b64ToUint8Array(jwk.p),\n // Since p and q are switched in places, u is the inverse of jwk.q\n u: b64ToUint8Array(jwk.qi)\n };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview ElGamal implementation\n * @module crypto/public_key/elgamal\n */\nimport { getRandomBigInteger } from '../random';\nimport { emeEncode, emeDecode } from '../pkcs1';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\nconst _1n = BigInt(1);\n\n/**\n * ElGamal Encryption function\n * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)\n * @param {Uint8Array} data - To be padded and encrypted\n * @param {Uint8Array} p\n * @param {Uint8Array} g\n * @param {Uint8Array} y\n * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}\n * @async\n */\nexport async function encrypt(data, p, g, y) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n const padded = emeEncode(data, byteLength(p));\n const m = uint8ArrayToBigInt(padded);\n\n // OpenPGP uses a \"special\" version of ElGamal where g is generator of the full group Z/pZ*\n // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]\n const k = getRandomBigInteger(_1n, p - _1n);\n return {\n c1: bigIntToUint8Array(modExp(g, k, p)),\n c2: bigIntToUint8Array(mod(modExp(y, k, p) * m, p))\n };\n}\n\n/**\n * ElGamal Encryption function\n * @param {Uint8Array} c1\n * @param {Uint8Array} c2\n * @param {Uint8Array} p\n * @param {Uint8Array} x\n * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing\n * (needed for constant-time processing)\n * @returns {Promise} Unpadded message.\n * @throws {Error} on decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function decrypt(c1, c2, p, x, randomPayload) {\n c1 = uint8ArrayToBigInt(c1);\n c2 = uint8ArrayToBigInt(c2);\n p = uint8ArrayToBigInt(p);\n x = uint8ArrayToBigInt(x);\n\n const padded = mod(modInv(modExp(c1, x, p), p) * c2, p);\n return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);\n}\n\n/**\n * Validate ElGamal parameters\n * @param {Uint8Array} p - ElGamal prime\n * @param {Uint8Array} g - ElGamal group generator\n * @param {Uint8Array} y - ElGamal public key\n * @param {Uint8Array} x - ElGamal private exponent\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, g, y, x) {\n p = uint8ArrayToBigInt(p);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n // Expect p-1 to be large\n const pSize = BigInt(bitLength(p));\n const _1023n = BigInt(1023);\n if (pSize < _1023n) {\n return false;\n }\n\n /**\n * g should have order p-1\n * Check that g ** (p-1) = 1 mod p\n */\n if (modExp(g, p - _1n, p) !== _1n) {\n return false;\n }\n\n /**\n * Since p-1 is not prime, g might have a smaller order that divides p-1\n * We want to make sure that the order is large enough to hinder a small subgroup attack\n *\n * We just check g**i != 1 for all i up to a threshold\n */\n let res = g;\n let i = BigInt(1);\n const _2n = BigInt(2);\n const threshold = _2n << BigInt(17); // we want order > threshold\n while (i < threshold) {\n res = mod(res * g, p);\n if (res === _1n) {\n return false;\n }\n i++;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{r(p-1) + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const r = getRandomBigInteger(_2n << (pSize - _1n), _2n << pSize); // draw r of same size as p-1\n const rqx = (p - _1n) * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","// declare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import { crypto } from './crypto.js';\n\n'use strict';\nconst nacl = {};\nexport default nacl;\n\n// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n//\n// Implementation derived from TweetNaCl version 20140427.\n// See for details: http://tweetnacl.cr.yp.to/\n\nvar gf = function(init) {\n var i, r = new Float64Array(16);\n if (init) for (i = 0; i < init.length; i++) r[i] = init[i];\n return r;\n};\n\n// Pluggable, initialized in high-level API below.\nvar randombytes = function(/* x, n */) { throw new Error('no PRNG'); };\n\nvar _9 = new Uint8Array(32); _9[0] = 9;\n\nvar gf0 = gf(),\n gf1 = gf([1]),\n _121665 = gf([0xdb41, 1]),\n D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),\n D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),\n X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),\n Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),\n I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\nfunction ts64(x, i, h, l) {\n x[i] = (h >> 24) & 0xff;\n x[i+1] = (h >> 16) & 0xff;\n x[i+2] = (h >> 8) & 0xff;\n x[i+3] = h & 0xff;\n x[i+4] = (l >> 24) & 0xff;\n x[i+5] = (l >> 16) & 0xff;\n x[i+6] = (l >> 8) & 0xff;\n x[i+7] = l & 0xff;\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i,d = 0;\n for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x,xi,y,yi,32);\n}\n\nfunction set25519(r, a) {\n var i;\n for (i = 0; i < 16; i++) r[i] = a[i]|0;\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for (i = 0; i < 16; i++) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c-1 + 37 * (c-1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b-1);\n for (var i = 0; i < 16; i++) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for (i = 0; i < 16; i++) t[i] = n[i];\n car25519(t);\n car25519(t);\n car25519(t);\n for (j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);\n b = (m[15]>>16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1-b);\n }\n for (i = 0; i < 16; i++) {\n o[2*i] = t[i] & 0xff;\n o[2*i+1] = t[i]>>8;\n }\n}\n\nfunction neq25519(a, b) {\n var c = new Uint8Array(32), d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction par25519(a) {\n var d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);\n o[15] &= 0x7fff;\n}\n\nfunction A(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];\n}\n\nfunction Z(o, a, b) {\n for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 253; a >= 0; a--) {\n S(c, c);\n if(a !== 2 && a !== 4) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for (a = 0; a < 16; a++) c[a] = i[a];\n for (a = 250; a >= 0; a--) {\n S(c, c);\n if(a !== 1) M(c, c, i);\n }\n for (a = 0; a < 16; a++) o[a] = c[a];\n}\n\nfunction crypto_scalarmult(q, n, p) {\n var z = new Uint8Array(32);\n var x = new Float64Array(80), r, i;\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n for (i = 0; i < 31; i++) z[i] = n[i];\n z[31]=(n[31]&127)|64;\n z[0]&=248;\n unpack25519(x,p);\n for (i = 0; i < 16; i++) {\n b[i]=x[i];\n d[i]=a[i]=c[i]=0;\n }\n a[0]=d[0]=1;\n for (i=254; i>=0; --i) {\n r=(z[i>>>3]>>>(i&7))&1;\n sel25519(a,b,r);\n sel25519(c,d,r);\n A(e,a,c);\n Z(a,a,c);\n A(c,b,d);\n Z(b,b,d);\n S(d,e);\n S(f,a);\n M(a,c,a);\n M(c,b,e);\n A(e,a,c);\n Z(a,a,c);\n S(b,a);\n Z(c,d,f);\n M(a,c,_121665);\n A(a,a,d);\n M(c,c,a);\n M(a,d,f);\n M(d,b,x);\n S(b,e);\n sel25519(a,b,r);\n sel25519(c,d,r);\n }\n for (i = 0; i < 16; i++) {\n x[i+16]=a[i];\n x[i+32]=c[i];\n x[i+48]=b[i];\n x[i+64]=d[i];\n }\n var x32 = x.subarray(32);\n var x16 = x.subarray(16);\n inv25519(x32,x32);\n M(x16,x16,x32);\n pack25519(q,x16);\n return 0;\n}\n\nfunction crypto_scalarmult_base(q, n) {\n return crypto_scalarmult(q, n, _9);\n}\n\nfunction crypto_box_keypair(y, x) {\n randombytes(x, 32);\n return crypto_scalarmult_base(y, x);\n}\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction crypto_hashblocks_hl(hh, hl, m, n) {\n var wh = new Int32Array(16), wl = new Int32Array(16),\n bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,\n bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,\n th, tl, i, j, h, l, a, b, c, d;\n\n var ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n var pos = 0;\n while (n >= 128) {\n for (i = 0; i < 16; i++) {\n j = 8 * i + pos;\n wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];\n wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];\n }\n for (i = 0; i < 80; i++) {\n bh0 = ah0;\n bh1 = ah1;\n bh2 = ah2;\n bh3 = ah3;\n bh4 = ah4;\n bh5 = ah5;\n bh6 = ah6;\n bh7 = ah7;\n\n bl0 = al0;\n bl1 = al1;\n bl2 = al2;\n bl3 = al3;\n bl4 = al4;\n bl5 = al5;\n bl6 = al6;\n bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));\n l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i*2];\n l = K[i*2+1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i%16];\n l = wl[i%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));\n l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i%16 === 15) {\n for (j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j+9)%16];\n l = wl[(j+9)%16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j+1)%16];\n tl = wl[(j+1)%16];\n h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j+14)%16];\n tl = wl[(j+14)%16];\n h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n n -= 128;\n }\n\n return n;\n}\n\nfunction crypto_hash(out, m, n) {\n var hh = new Int32Array(8),\n hl = new Int32Array(8),\n x = new Uint8Array(256),\n i, b = n;\n\n hh[0] = 0x6a09e667;\n hh[1] = 0xbb67ae85;\n hh[2] = 0x3c6ef372;\n hh[3] = 0xa54ff53a;\n hh[4] = 0x510e527f;\n hh[5] = 0x9b05688c;\n hh[6] = 0x1f83d9ab;\n hh[7] = 0x5be0cd19;\n\n hl[0] = 0xf3bcc908;\n hl[1] = 0x84caa73b;\n hl[2] = 0xfe94f82b;\n hl[3] = 0x5f1d36f1;\n hl[4] = 0xade682d1;\n hl[5] = 0x2b3e6c1f;\n hl[6] = 0xfb41bd6b;\n hl[7] = 0x137e2179;\n\n crypto_hashblocks_hl(hh, hl, m, n);\n n %= 128;\n\n for (i = 0; i < n; i++) x[i] = m[b-n+i];\n x[n] = 128;\n\n n = 256-128*(n<112?1:0);\n x[n-9] = 0;\n ts64(x, n-8, (b / 0x20000000) | 0, b << 3);\n crypto_hashblocks_hl(hh, hl, x, n);\n\n for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);\n\n return 0;\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n var i;\n for (i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (i = 255; i >= 0; --i) {\n b = (s[(i/8)|0] >> (i&7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction crypto_sign_keypair(pk, sk, seeded) {\n var d = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n if (!seeded) randombytes(sk, 32);\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for (i = 0; i < 32; i++) sk[i+32] = pk[i];\n return 0;\n}\n\nvar L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) x[j] -= carry * L[j];\n for (i = 0; i < 32; i++) {\n x[i+1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64), i;\n for (i = 0; i < 64; i++) x[i] = r[i];\n for (i = 0; i < 64; i++) r[i] = 0;\n modL(r, x);\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n crypto_hash(d, sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for (i = 0; i < n; i++) sm[64 + i] = m[i];\n for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];\n\n crypto_hash(r, sm.subarray(32), n+32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for (i = 32; i < 64; i++) sm[i] = sk[i];\n crypto_hash(h, sm, n + 64);\n reduce(h);\n\n for (i = 0; i < 64; i++) x[i] = 0;\n for (i = 0; i < 32; i++) x[i] = r[i];\n for (i = 0; i < 32; i++) {\n for (j = 0; j < 32; j++) {\n x[i+j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) M(r[0], r[0], I);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if (neq25519(chk, num)) return -1;\n\n if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i;\n var t = new Uint8Array(32), h = new Uint8Array(64);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n if (n < 64) return -1;\n\n if (unpackneg(q, pk)) return -1;\n\n for (i = 0; i < n; i++) m[i] = sm[i];\n for (i = 0; i < 32; i++) m[i+32] = pk[i];\n crypto_hash(h, m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if (crypto_verify_32(sm, 0, t, 0)) {\n for (i = 0; i < n; i++) m[i] = 0;\n return -1;\n }\n\n for (i = 0; i < n; i++) m[i] = sm[i + 64];\n return n;\n}\n\nvar crypto_scalarmult_BYTES = 32,\n crypto_scalarmult_SCALARBYTES = 32,\n crypto_box_PUBLICKEYBYTES = 32,\n crypto_box_SECRETKEYBYTES = 32,\n crypto_sign_BYTES = 64,\n crypto_sign_PUBLICKEYBYTES = 32,\n crypto_sign_SECRETKEYBYTES = 64,\n crypto_sign_SEEDBYTES = 32;\n\nfunction checkArrayTypes() {\n for (var i = 0; i < arguments.length; i++) {\n if (!(arguments[i] instanceof Uint8Array))\n throw new TypeError('unexpected type, use Uint8Array');\n }\n}\n\nfunction cleanup(arr) {\n for (var i = 0; i < arr.length; i++) arr[i] = 0;\n}\n\nnacl.scalarMult = function(n, p) {\n checkArrayTypes(n, p);\n if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');\n if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');\n var q = new Uint8Array(crypto_scalarmult_BYTES);\n crypto_scalarmult(q, n, p);\n return q;\n};\n\nnacl.box = {};\n\nnacl.box.keyPair = function() {\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);\n crypto_box_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.box.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_box_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);\n crypto_scalarmult_base(pk, secretKey);\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign = function(msg, secretKey) {\n checkArrayTypes(msg, secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);\n crypto_sign(signedMsg, msg, msg.length, secretKey);\n return signedMsg;\n};\n\nnacl.sign.detached = function(msg, secretKey) {\n var signedMsg = nacl.sign(msg, secretKey);\n var sig = new Uint8Array(crypto_sign_BYTES);\n for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];\n return sig;\n};\n\nnacl.sign.detached.verify = function(msg, sig, publicKey) {\n checkArrayTypes(msg, sig, publicKey);\n if (sig.length !== crypto_sign_BYTES)\n throw new Error('bad signature size');\n if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)\n throw new Error('bad public key size');\n var sm = new Uint8Array(crypto_sign_BYTES + msg.length);\n var m = new Uint8Array(crypto_sign_BYTES + msg.length);\n var i;\n for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];\n for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nnacl.sign.keyPair = function() {\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.sign.keyPair.fromSecretKey = function(secretKey) {\n checkArrayTypes(secretKey);\n if (secretKey.length !== crypto_sign_SECRETKEYBYTES)\n throw new Error('bad secret key size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];\n return {publicKey: pk, secretKey: new Uint8Array(secretKey)};\n};\n\nnacl.sign.keyPair.fromSeed = function(seed) {\n checkArrayTypes(seed);\n if (seed.length !== crypto_sign_SEEDBYTES)\n throw new Error('bad seed size');\n var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);\n var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);\n for (var i = 0; i < 32; i++) sk[i] = seed[i];\n crypto_sign_keypair(pk, sk, true);\n return {publicKey: pk, secretKey: sk};\n};\n\nnacl.setPRNG = function(fn) {\n randombytes = fn;\n};\n\n(function() {\n // Initialize PRNG if environment provides CSPRNG.\n // If not, methods calling randombytes will throw.\n if (crypto && crypto.getRandomValues) {\n // Browsers and Node v16+\n var QUOTA = 65536;\n nacl.setPRNG(function(x, n) {\n var i, v = new Uint8Array(n);\n for (i = 0; i < n; i += QUOTA) {\n crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));\n }\n for (i = 0; i < n; i++) x[i] = v[i];\n cleanup(v);\n });\n }\n})();\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Wrapper to an OID value\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:\n * The sequence of octets in the third column is the result of applying\n * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier\n * with subsequent truncation. The truncation removes the two fields of\n * encoded Object Identifier. The first omitted field is one octet\n * representing the Object Identifier tag, and the second omitted field\n * is the length of the Object Identifier body. For example, the\n * complete ASN.1 DER encoding for the NIST P-256 curve OID is \"06 08 2A\n * 86 48 CE 3D 03 01 07\", from which the first entry in the table above\n * is constructed by omitting the first two octets. Only the truncated\n * sequence of octets is the valid representation of a curve OID.\n * @module type/oid\n */\n\nimport util from '../util';\nimport enums from '../enums';\n\nconst knownOIDs = {\n '2a8648ce3d030107': enums.curve.nistP256,\n '2b81040022': enums.curve.nistP384,\n '2b81040023': enums.curve.nistP521,\n '2b8104000a': enums.curve.secp256k1,\n '2b06010401da470f01': enums.curve.ed25519Legacy,\n '2b060104019755010501': enums.curve.curve25519Legacy,\n '2b2403030208010107': enums.curve.brainpoolP256r1,\n '2b240303020801010b': enums.curve.brainpoolP384r1,\n '2b240303020801010d': enums.curve.brainpoolP512r1\n};\n\nclass OID {\n constructor(oid) {\n if (oid instanceof OID) {\n this.oid = oid.oid;\n } else if (util.isArray(oid) ||\n util.isUint8Array(oid)) {\n oid = new Uint8Array(oid);\n if (oid[0] === 0x06) { // DER encoded oid byte array\n if (oid[1] !== oid.length - 2) {\n throw new Error('Length mismatch in DER encoded oid');\n }\n oid = oid.subarray(2);\n }\n this.oid = oid;\n } else {\n this.oid = '';\n }\n }\n\n /**\n * Method to read an OID object\n * @param {Uint8Array} input - Where to read the OID from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length >= 1) {\n const length = input[0];\n if (input.length >= 1 + length) {\n this.oid = input.subarray(1, 1 + length);\n return 1 + this.oid.length;\n }\n }\n throw new Error('Invalid oid');\n }\n\n /**\n * Serialize an OID object\n * @returns {Uint8Array} Array with the serialized value the OID.\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);\n }\n\n /**\n * Serialize an OID object as a hex string\n * @returns {string} String with the hex value of the OID.\n */\n toHex() {\n return util.uint8ArrayToHex(this.oid);\n }\n\n /**\n * If a known curve object identifier, return the canonical name of the curve\n * @returns {enums.curve} String with the canonical name of the curve\n * @throws if unknown\n */\n getName() {\n const name = knownOIDs[this.toHex()];\n if (!name) {\n throw new Error('Unknown curve object identifier.');\n }\n\n return name;\n }\n}\n\nexport default OID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Functions for reading and writing packets\n * @module packet/packet\n */\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\nexport function readSimpleLength(bytes) {\n let len = 0;\n let offset;\n const type = bytes[0];\n\n\n if (type < 192) {\n [len] = bytes;\n offset = 1;\n } else if (type < 255) {\n len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;\n offset = 2;\n } else if (type === 255) {\n len = util.readNumber(bytes.subarray(1, 1 + 4));\n offset = 5;\n }\n\n return {\n len: len,\n offset: offset\n };\n}\n\n/**\n * Encodes a given integer of length to the openpgp length specifier to a\n * string\n *\n * @param {Integer} length - The length to encode\n * @returns {Uint8Array} String with openpgp length representation.\n */\nexport function writeSimpleLength(length) {\n if (length < 192) {\n return new Uint8Array([length]);\n } else if (length > 191 && length < 8384) {\n /*\n * let a = (total data packet length) - 192 let bc = two octet\n * representation of a let d = b + 192\n */\n return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);\n }\n return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);\n}\n\nexport function writePartialLength(power) {\n if (power < 0 || power > 30) {\n throw new Error('Partial Length power must be between 1 and 30');\n }\n return new Uint8Array([224 + power]);\n}\n\nexport function writeTag(tag_type) {\n /* we're only generating v4 packet headers here */\n return new Uint8Array([0xC0 | tag_type]);\n}\n\n/**\n * Writes a packet header version 4 with the given tag_type and length to a\n * string\n *\n * @param {Integer} tag_type - Tag type\n * @param {Integer} length - Length of the payload\n * @returns {String} String of the header.\n */\nexport function writeHeader(tag_type, length) {\n /* we're only generating v4 packet headers here */\n return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);\n}\n\n/**\n * Whether the packet type supports partial lengths per RFC4880\n * @param {Integer} tag - Tag type\n * @returns {Boolean} String of the header.\n */\nexport function supportsStreaming(tag) {\n return [\n enums.packet.literalData,\n enums.packet.compressedData,\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n ].includes(tag);\n}\n\n/**\n * Generic static Packet Parser function\n *\n * @param {Uint8Array | ReadableStream} input - Input stream as string\n * @param {Function} callback - Function to call with the parsed packet\n * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.\n */\nexport async function readPackets(input, callback) {\n const reader = stream.getReader(input);\n let writer;\n let callbackReturned;\n try {\n const peekedBytes = await reader.peekBytes(2);\n // some sanity checks\n if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {\n throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');\n }\n const headerByte = await reader.readByte();\n let tag = -1;\n let format = -1;\n let packetLength;\n\n format = 0; // 0 = old format; 1 = new format\n if ((headerByte & 0x40) !== 0) {\n format = 1;\n }\n\n let packetLengthType;\n if (format) {\n // new format header\n tag = headerByte & 0x3F; // bit 5-0\n } else {\n // old format header\n tag = (headerByte & 0x3F) >> 2; // bit 5-2\n packetLengthType = headerByte & 0x03; // bit 1-0\n }\n\n const packetSupportsStreaming = supportsStreaming(tag);\n let packet = null;\n if (packetSupportsStreaming) {\n if (util.isStream(input) === 'array') {\n const arrayStream = new stream.ArrayStream();\n writer = stream.getWriter(arrayStream);\n packet = arrayStream;\n } else {\n const transform = new TransformStream();\n writer = stream.getWriter(transform.writable);\n packet = transform.readable;\n }\n // eslint-disable-next-line callback-return\n callbackReturned = callback({ tag, packet });\n } else {\n packet = [];\n }\n\n let wasPartialLength;\n do {\n if (!format) {\n // 4.2.1. Old Format Packet Lengths\n switch (packetLengthType) {\n case 0:\n // The packet has a one-octet length. The header is 2 octets\n // long.\n packetLength = await reader.readByte();\n break;\n case 1:\n // The packet has a two-octet length. The header is 3 octets\n // long.\n packetLength = (await reader.readByte() << 8) | await reader.readByte();\n break;\n case 2:\n // The packet has a four-octet length. The header is 5\n // octets long.\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n break;\n default:\n // 3 - The packet is of indeterminate length. The header is 1\n // octet long, and the implementation must determine how long\n // the packet is. If the packet is in a file, this means that\n // the packet extends until the end of the file. In general,\n // an implementation SHOULD NOT use indeterminate-length\n // packets except where the end of the data will be clear\n // from the context, and even then it is better to use a\n // definite length, or a new format header. The new format\n // headers described below have a mechanism for precisely\n // encoding data of indeterminate length.\n packetLength = Infinity;\n break;\n }\n } else { // 4.2.2. New Format Packet Lengths\n // 4.2.2.1. One-Octet Lengths\n const lengthByte = await reader.readByte();\n wasPartialLength = false;\n if (lengthByte < 192) {\n packetLength = lengthByte;\n // 4.2.2.2. Two-Octet Lengths\n } else if (lengthByte >= 192 && lengthByte < 224) {\n packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;\n // 4.2.2.4. Partial Body Lengths\n } else if (lengthByte > 223 && lengthByte < 255) {\n packetLength = 1 << (lengthByte & 0x1F);\n wasPartialLength = true;\n if (!packetSupportsStreaming) {\n throw new TypeError('This packet type does not support partial lengths.');\n }\n // 4.2.2.3. Five-Octet Lengths\n } else {\n packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<\n 8) | await reader.readByte();\n }\n }\n if (packetLength > 0) {\n let bytesRead = 0;\n while (true) {\n if (writer) await writer.ready;\n const { done, value } = await reader.read();\n if (done) {\n if (packetLength === Infinity) break;\n throw new Error('Unexpected end of packet');\n }\n const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);\n if (writer) await writer.write(chunk);\n else packet.push(chunk);\n bytesRead += value.length;\n if (bytesRead >= packetLength) {\n reader.unshift(value.subarray(packetLength - bytesRead + value.length));\n break;\n }\n }\n }\n } while (wasPartialLength);\n\n // If this was not a packet that \"supports streaming\", we peek to check\n // whether it is the last packet in the message. We peek 2 bytes instead\n // of 1 because the beginning of this function also peeks 2 bytes, and we\n // want to cut a `subarray` of the correct length into `web-stream-tools`'\n // `externalBuffer` as a tiny optimization here.\n //\n // If it *was* a streaming packet (i.e. the data packets), we peek at the\n // entire remainder of the stream, in order to forward errors in the\n // remainder of the stream to the packet data. (Note that this means we\n // read/peek at all signature packets before closing the literal data\n // packet, for example.) This forwards MDC errors to the literal data\n // stream, for example, so that they don't get lost / forgotten on\n // decryptedMessage.packets.stream, which we never look at.\n //\n // An example of what we do when stream-parsing a message containing\n // [ one-pass signature packet, literal data packet, signature packet ]:\n // 1. Read the one-pass signature packet\n // 2. Peek 2 bytes of the literal data packet\n // 3. Parse the one-pass signature packet\n //\n // 4. Read the literal data packet, simultaneously stream-parsing it\n // 5. Peek until the end of the message\n // 6. Finish parsing the literal data packet\n //\n // 7. Read the signature packet again (we already peeked at it in step 5)\n // 8. Peek at the end of the stream again (`peekBytes` returns undefined)\n // 9. Parse the signature packet\n //\n // Note that this means that if there's an error in the very end of the\n // stream, such as an MDC error, we throw in step 5 instead of in step 8\n // (or never), which is the point of this exercise.\n const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);\n if (writer) {\n await writer.ready;\n await writer.close();\n } else {\n packet = util.concatUint8Array(packet);\n // eslint-disable-next-line callback-return\n await callback({ tag, packet });\n }\n return !nextPacket || !nextPacket.length;\n } catch (e) {\n if (writer) {\n await writer.abort(e);\n return true;\n } else {\n throw e;\n }\n } finally {\n if (writer) {\n await callbackReturned;\n }\n reader.releaseLock();\n }\n}\n\nexport class UnsupportedError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnsupportedError';\n }\n}\n\n// unknown packet types are handled differently depending on the packet criticality\nexport class UnknownPacketError extends UnsupportedError {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UnsupportedError);\n }\n\n this.name = 'UnknownPacketError';\n }\n}\n\nexport class UnparseablePacket {\n constructor(tag, rawContent) {\n this.tag = tag;\n this.rawContent = rawContent;\n }\n\n write() {\n return this.rawContent;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP\n * @module crypto/public_key/elliptic/eddsa\n */\n\nimport ed25519 from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { getRandomBytes } from '../../random';\nimport { b64ToUint8Array, uint8ArrayToB64 } from '../../../encoding/base64';\n\n\n/**\n * Generate (non-legacy) EdDSA key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n A: new Uint8Array(b64ToUint8Array(publicKey.x)),\n seed: b64ToUint8Array(privateKey.d, true)\n };\n } catch (err) {\n if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux\n throw err;\n }\n const seed = getRandomBytes(getPayloadSize(algo));\n const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);\n return { A, seed };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const seed = ed448.utils.randomPrivateKey();\n const A = ed448.getPublicKey(seed);\n return { A, seed };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\n/**\n * Sign a message using the provided key\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * RS: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(algo, hashAlgo, message, publicKey, privateKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = privateKeyToJWK(algo, publicKey, privateKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);\n\n const signature = new Uint8Array(\n await webCrypto.sign('Ed25519', key, hashed)\n );\n\n return { RS: signature };\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n const secretKey = util.concatUint8Array([privateKey, publicKey]);\n const signature = ed25519.sign.detached(hashed, secretKey);\n return { RS: signature };\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n const signature = ed448.sign(hashed, privateKey);\n return { RS: signature };\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{ RS: Uint8Array }} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(algo, hashAlgo, { RS }, m, publicKey, hashed) {\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo(algo))) {\n // Enforce digest sizes:\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n switch (algo) {\n case enums.publicKey.ed25519:\n try {\n const webCrypto = util.getWebCrypto();\n const jwk = publicKeyToJWK(algo, publicKey);\n const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);\n const verified = await webCrypto.verify('Ed25519', key, RS, hashed);\n return verified;\n } catch (err) {\n if (err.name !== 'NotSupportedError') {\n throw err;\n }\n return ed25519.sign.detached.verify(hashed, RS, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n return ed448.verify(RS, hashed, publicKey);\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n/**\n * Validate (non-legacy) EdDSA parameters\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} A - EdDSA public point\n * @param {Uint8Array} seed - EdDSA secret seed\n * @param {Uint8Array} oid - (legacy only) EdDSA OID\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(algo, A, seed) {\n switch (algo) {\n case enums.publicKey.ed25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented\n */\n const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n\n case enums.publicKey.ed448: {\n const ed448 = await util.getNobleCurve(enums.publicKey.ed448);\n\n const publicKey = ed448.getPublicKey(seed);\n return util.equalsUint8Array(A, publicKey);\n }\n default:\n return false;\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return 32;\n\n case enums.publicKey.ed448:\n return 57;\n\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n}\n\nexport function getPreferredHashAlgo(algo) {\n switch (algo) {\n case enums.publicKey.ed25519:\n return enums.hash.sha256;\n case enums.publicKey.ed448:\n return enums.hash.sha512;\n default:\n throw new Error('Unknown EdDSA algo');\n }\n}\n\nconst publicKeyToJWK = (algo, publicKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = {\n kty: 'OKP',\n crv: 'Ed25519',\n x: uint8ArrayToB64(publicKey, true),\n ext: true\n };\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n\nconst privateKeyToJWK = (algo, publicKey, privateKey) => {\n switch (algo) {\n case enums.publicKey.ed25519: {\n const jwk = publicKeyToJWK(algo, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n }\n default:\n throw new Error('Unsupported EdDSA algorithm');\n }\n};\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions\n * @see module:crypto/public_key/elliptic/ecdh\n * @module crypto/aes_kw\n */\n\nimport { aeskw as nobleAesKW } from '@noble/ciphers/aes';\nimport { getCipherParams } from './cipher';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n/**\n * AES key wrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} dataToWrap\n * @returns {Uint8Array} wrapped key\n */\nexport async function wrap(algo, key, dataToWrap) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n try {\n const wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);\n // Import data as HMAC key, as it has no key length requirements\n const keyToWrap = await webCrypto.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n const wrapped = await webCrypto.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });\n return new Uint8Array(wrapped);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n }\n\n return nobleAesKW(key).encrypt(dataToWrap);\n}\n\n/**\n * AES key unwrap\n * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo\n * @param {Uint8Array} key - wrapping key\n * @param {Uint8Array} wrappedData\n * @returns {Uint8Array} unwrapped data\n */\nexport async function unwrap(algo, key, wrappedData) {\n const { keySize } = getCipherParams(algo);\n // sanity checks, since WebCrypto does not use the `algo` input\n if (!util.isAES(algo) || key.length !== keySize) {\n throw new Error('Unexpected algorithm or key size');\n }\n\n let wrappingKey;\n try {\n wrappingKey = await webCrypto.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);\n } catch (err) {\n // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support\n if (err.name !== 'NotSupportedError' &&\n !(key.length === 24 && err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support operation: ' + err.message);\n return nobleAesKW(key).decrypt(wrappedData);\n }\n\n try {\n const unwrapped = await webCrypto.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);\n return new Uint8Array(await webCrypto.exportKey('raw', unwrapped));\n } catch (err) {\n if (err.name === 'OperationError') {\n throw new Error('Key Data Integrity failed');\n }\n throw err;\n }\n}\n","/**\n * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.\n * @module crypto/hkdf\n */\n\nimport enums from '../enums';\nimport util from '../util';\n\nconst webCrypto = util.getWebCrypto();\n\nexport default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {\n const hash = enums.read(enums.webHash, hashAlgo);\n if (!hash) throw new Error('Hash algo not supported with HKDF');\n\n const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);\n const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);\n return new Uint8Array(bits);\n}\n","/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport x25519 from '@openpgp/tweetnacl';\nimport * as aesKW from '../../aes_kw';\nimport { getRandomBytes } from '../../random';\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport computeHKDF from '../../hkdf';\nimport { getCipherParams } from '../../cipher';\n\nconst HKDF_INFO = {\n x25519: util.encodeUTF8('OpenPGP X25519'),\n x448: util.encodeUTF8('OpenPGP X448')\n};\n\n/**\n * Generate ECDH key for Montgomery curves\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}\n */\nexport async function generate(algo) {\n switch (algo) {\n case enums.publicKey.x25519: {\n // k stays in little-endian, unlike legacy ECDH over curve25519\n const k = getRandomBytes(32);\n const { publicKey: A } = x25519.box.keyPair.fromSecretKey(k);\n return { A, k };\n }\n\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const k = x448.utils.randomPrivateKey();\n const A = x448.getPublicKey(k);\n return { A, k };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n* Validate ECDH parameters\n* @param {module:enums.publicKey} algo - Algorithm identifier\n* @param {Uint8Array} A - ECDH public point\n* @param {Uint8Array} k - ECDH secret scalar\n* @returns {Promise} Whether params are valid.\n* @async\n*/\nexport async function validateParams(algo, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const { publicKey } = x25519.box.keyPair.fromSecretKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n /**\n * Derive public point A' from private key\n * and expect A == A'\n */\n const publicKey = x448.getPublicKey(k);\n return util.equalsUint8Array(A, publicKey);\n }\n\n default:\n return false;\n }\n}\n\n/**\n * Wrap and encrypt a session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} data - session key data to be encrypted\n * @param {Uint8Array} recipientA - Recipient public key (K_B)\n * @returns {Promise<{\n * ephemeralPublicKey: Uint8Array,\n * wrappedKey: Uint8Array\n * }>} ephemeral public key (K_A) and encrypted key\n * @async\n */\nexport async function encrypt(algo, data, recipientA) {\n const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n recipientA,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n const wrappedKey = await aesKW.wrap(cipherAlgo, encryptionKey, data);\n return { ephemeralPublicKey, wrappedKey };\n }\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Decrypt and unwrap the session key\n *\n * @param {module:enums.publicKey} algo - Algorithm identifier\n * @param {Uint8Array} ephemeralPublicKey - (K_A)\n * @param {Uint8Array} wrappedKey,\n * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF\n * @param {Uint8Array} k - Recipient secret key (b)\n * @returns {Promise} decrypted session key data\n * @async\n */\nexport async function decrypt(algo, ephemeralPublicKey, wrappedKey, A, k) {\n const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);\n const hkdfInput = util.concatUint8Array([\n ephemeralPublicKey,\n A,\n sharedSecret\n ]);\n switch (algo) {\n case enums.publicKey.x25519: {\n const cipherAlgo = enums.symmetric.aes128;\n const { keySize } = getCipherParams(cipherAlgo);\n const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n case enums.publicKey.x448: {\n const cipherAlgo = enums.symmetric.aes256;\n const { keySize } = getCipherParams(enums.symmetric.aes256);\n const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);\n return aesKW.unwrap(cipherAlgo, encryptionKey, wrappedKey);\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport function getPayloadSize(algo) {\n switch (algo) {\n case enums.publicKey.x25519:\n return 32;\n\n case enums.publicKey.x448:\n return 56;\n\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * Generate shared secret and ephemeral public key for encryption\n * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret\n * @async\n */\nexport async function generateEphemeralEncryptionMaterial(algo, recipientA) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo));\n const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const { publicKey: ephemeralPublicKey } = x25519.box.keyPair.fromSecretKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const ephemeralSecretKey = x448.utils.randomPrivateKey();\n const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);\n assertNonZeroArray(sharedSecret);\n const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey);\n return { ephemeralPublicKey, sharedSecret };\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\nexport async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {\n switch (algo) {\n case enums.publicKey.x25519: {\n const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n case enums.publicKey.x448: {\n const x448 = await util.getNobleCurve(enums.publicKey.x448);\n const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);\n assertNonZeroArray(sharedSecret);\n return sharedSecret;\n }\n default:\n throw new Error('Unsupported ECDH algorithm');\n }\n}\n\n/**\n * x25519 and x448 produce an all-zero value when given as input a point with small order.\n * This does not lead to a security issue in the context of ECDH, but it is still unexpected,\n * hence we throw.\n * @param {Uint8Array} sharedSecret\n */\nfunction assertNonZeroArray(sharedSecret) {\n let acc = 0;\n for (let i = 0; i < sharedSecret.length; i++) {\n acc |= sharedSecret[i];\n }\n if (acc === 0) {\n throw new Error('Unexpected low order point');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Wrapper of an instance of an Elliptic Curve\n * @module crypto/public_key/elliptic/curve\n */\nimport nacl from '@openpgp/tweetnacl';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { uint8ArrayToB64, b64ToUint8Array } from '../../../encoding/base64';\nimport OID from '../../../type/oid';\nimport { UnsupportedError } from '../../../packet/packet';\nimport { generate as eddsaGenerate } from './eddsa';\nimport { generate as ecdhXGenerate } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\nconst webCurves = {\n [enums.curve.nistP256]: 'P-256',\n [enums.curve.nistP384]: 'P-384',\n [enums.curve.nistP521]: 'P-521'\n};\nconst knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];\nconst nodeCurves = nodeCrypto ? {\n [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,\n [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,\n [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,\n [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,\n [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,\n [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,\n [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,\n [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,\n [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined\n} : {};\n\nconst curves = {\n [enums.curve.nistP256]: {\n oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.nistP256],\n web: webCurves[enums.curve.nistP256],\n payloadSize: 32,\n sharedSize: 256,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP384]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.nistP384],\n web: webCurves[enums.curve.nistP384],\n payloadSize: 48,\n sharedSize: 384,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.nistP521]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.nistP521],\n web: webCurves[enums.curve.nistP521],\n payloadSize: 66,\n sharedSize: 528,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.secp256k1]: {\n oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.secp256k1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.ed25519Legacy]: {\n oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],\n keyType: enums.publicKey.eddsaLegacy,\n hash: enums.hash.sha512,\n node: false, // nodeCurves.ed25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.curve25519Legacy]: {\n oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],\n keyType: enums.publicKey.ecdh,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: false, // nodeCurves.curve25519 TODO\n payloadSize: 32,\n wireFormatLeadingByte: 0x40\n },\n [enums.curve.brainpoolP256r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha256,\n cipher: enums.symmetric.aes128,\n node: nodeCurves[enums.curve.brainpoolP256r1],\n payloadSize: 32,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP384r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha384,\n cipher: enums.symmetric.aes192,\n node: nodeCurves[enums.curve.brainpoolP384r1],\n payloadSize: 48,\n wireFormatLeadingByte: 0x04\n },\n [enums.curve.brainpoolP512r1]: {\n oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],\n keyType: enums.publicKey.ecdsa,\n hash: enums.hash.sha512,\n cipher: enums.symmetric.aes256,\n node: nodeCurves[enums.curve.brainpoolP512r1],\n payloadSize: 64,\n wireFormatLeadingByte: 0x04\n }\n};\n\nclass CurveWithOID {\n constructor(oidOrName) {\n try {\n this.name = oidOrName instanceof OID ?\n oidOrName.getName() :\n enums.write(enums.curve,oidOrName);\n } catch (err) {\n throw new UnsupportedError('Unknown curve');\n }\n const params = curves[this.name];\n\n this.keyType = params.keyType;\n\n this.oid = params.oid;\n this.hash = params.hash;\n this.cipher = params.cipher;\n this.node = params.node;\n this.web = params.web;\n this.payloadSize = params.payloadSize;\n this.sharedSize = params.sharedSize;\n this.wireFormatLeadingByte = params.wireFormatLeadingByte;\n if (this.web && util.getWebCrypto()) {\n this.type = 'web';\n } else if (this.node && util.getNodeCrypto()) {\n this.type = 'node';\n } else if (this.name === enums.curve.curve25519Legacy) {\n this.type = 'curve25519Legacy';\n } else if (this.name === enums.curve.ed25519Legacy) {\n this.type = 'ed25519Legacy';\n }\n }\n\n async genKeyPair() {\n switch (this.type) {\n case 'web':\n try {\n return await webGenKeyPair(this.name, this.wireFormatLeadingByte);\n } catch (err) {\n util.printDebugError('Browser did not support generating ec key ' + err.message);\n return jsGenKeyPair(this.name);\n }\n case 'node':\n return nodeGenKeyPair(this.name);\n case 'curve25519Legacy': {\n // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3\n const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);\n const privateKey = k.slice().reverse();\n privateKey[0] = (privateKey[0] & 127) | 64;\n privateKey[31] &= 248;\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n case 'ed25519Legacy': {\n const { seed: privateKey, A } = await eddsaGenerate(enums.publicKey.ed25519);\n const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);\n return { publicKey, privateKey };\n }\n default:\n return jsGenKeyPair(this.name);\n }\n }\n}\n\nasync function generate(curveName) {\n const curve = new CurveWithOID(curveName);\n const { oid, hash, cipher } = curve;\n const keyPair = await curve.genKeyPair();\n return {\n oid,\n Q: keyPair.publicKey,\n secret: util.leftPad(keyPair.privateKey, curve.payloadSize),\n hash,\n cipher\n };\n}\n\n/**\n * Get preferred hash algo to use with the given curve\n * @param {module:type/oid} oid - curve oid\n * @returns {enums.hash} hash algorithm\n */\nfunction getPreferredHashAlgo(oid) {\n return curves[oid.getName()].hash;\n}\n\n/**\n * Validate ECDH and ECDSA parameters\n * Not suitable for EdDSA (different secret key format)\n * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves\n * @param {module:type/oid} oid - EC object identifier\n * @param {Uint8Array} Q - EC public point\n * @param {Uint8Array} d - EC secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nasync function validateStandardParams(algo, oid, Q, d) {\n const supportedCurves = {\n [enums.curve.nistP256]: true,\n [enums.curve.nistP384]: true,\n [enums.curve.nistP521]: true,\n [enums.curve.secp256k1]: true,\n [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,\n [enums.curve.brainpoolP256r1]: true,\n [enums.curve.brainpoolP384r1]: true,\n [enums.curve.brainpoolP512r1]: true\n };\n\n // Check whether the given curve is supported\n const curveName = oid.getName();\n if (!supportedCurves[curveName]) {\n return false;\n }\n\n if (curveName === enums.curve.curve25519Legacy) {\n d = d.slice().reverse();\n // Re-derive public point Q'\n const { publicKey } = nacl.box.keyPair.fromSecretKey(d);\n\n Q = new Uint8Array(Q);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n /*\n * Re-derive public point Q' = dG from private key\n * Expect Q == Q'\n */\n const dG = nobleCurve.getPublicKey(d, false);\n if (!util.equalsUint8Array(dG, Q)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Check whether the public point has a valid encoding.\n * NB: this function does not check e.g. whether the point belongs to the curve.\n */\nfunction checkPublicPointEnconding(curve, V) {\n const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;\n\n const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;\n\n if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {\n throw new Error('Invalid point encoding');\n }\n}\n\nexport {\n CurveWithOID, curves, webCurves, nodeCurves, generate, getPreferredHashAlgo, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding\n};\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\nasync function jsGenKeyPair(name) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves\n const privateKey = nobleCurve.utils.randomPrivateKey();\n const publicKey = nobleCurve.getPublicKey(privateKey, false);\n return { publicKey, privateKey };\n}\n\nasync function webGenKeyPair(name, wireFormatLeadingByte) {\n // Note: keys generated with ECDSA and ECDH are structurally equivalent\n const webCryptoKey = await webCrypto.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);\n\n const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);\n const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);\n\n return {\n publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),\n privateKey: b64ToUint8Array(privateKey.d, true)\n };\n}\n\nasync function nodeGenKeyPair(name) {\n // Note: ECDSA and ECDH key generation is structurally equivalent\n const ecdh = nodeCrypto.createECDH(nodeCurves[name]);\n await ecdh.generateKeys();\n return {\n publicKey: new Uint8Array(ecdh.getPublicKey()),\n privateKey: new Uint8Array(ecdh.getPrivateKey())\n };\n}\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * @param {JsonWebKey} jwk - key for conversion\n *\n * @returns {Uint8Array} Raw public key.\n */\nfunction jwkToRawPublic(jwk, wireFormatLeadingByte) {\n const bufX = b64ToUint8Array(jwk.x);\n const bufY = b64ToUint8Array(jwk.y);\n const publicKey = new Uint8Array(bufX.length + bufY.length + 1);\n publicKey[0] = wireFormatLeadingByte;\n publicKey.set(bufX, 1);\n publicKey.set(bufY, bufX.length + 1);\n return publicKey;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n *\n * @returns {JsonWebKey} Public key in jwk format.\n */\nfunction rawPublicToJWK(payloadSize, name, publicKey) {\n const len = payloadSize;\n const bufX = publicKey.slice(1, len + 1);\n const bufY = publicKey.slice(len + 1, len * 2 + 1);\n // https://www.rfc-editor.org/rfc/rfc7518.txt\n const jwk = {\n kty: 'EC',\n crv: name,\n x: uint8ArrayToB64(bufX, true),\n y: uint8ArrayToB64(bufY, true),\n ext: true\n };\n return jwk;\n}\n\n/**\n * @param {Integer} payloadSize - ec payload size\n * @param {String} name - curve name\n * @param {Uint8Array} publicKey - public key\n * @param {Uint8Array} privateKey - private key\n *\n * @returns {JsonWebKey} Private key in jwk format.\n */\nfunction privateToJWK(payloadSize, name, publicKey, privateKey) {\n const jwk = rawPublicToJWK(payloadSize, name, publicKey);\n jwk.d = uint8ArrayToB64(privateKey, true);\n return jwk;\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs\n * @module crypto/public_key/elliptic/ecdsa\n */\n\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { getRandomBytes } from '../../random';\nimport hash from '../../hash';\nimport { CurveWithOID, webCurves, privateToJWK, rawPublicToJWK, validateStandardParams, nodeCurves, checkPublicPointEnconding } from './oid_curves';\nimport { bigIntToUint8Array } from '../../biginteger';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Sign a message using the provided key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (message && !util.isStream(message)) {\n const keyPair = { publicKey, privateKey };\n switch (curve.type) {\n case 'web':\n // If browser doesn't support a curve, we'll catch it\n try {\n // Need to await to make sure browser succeeds\n return await webSign(curve, hashAlgo, message, keyPair);\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunaley Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support signing: ' + err.message);\n }\n break;\n case 'node':\n return nodeSign(curve, hashAlgo, message, privateKey);\n }\n }\n\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });\n return {\n r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),\n s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)\n };\n}\n\n/**\n * Verifies if a signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify\n * @param {Uint8Array} message - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, signature, message, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n // See https://github.com/openpgpjs/openpgpjs/pull/948.\n // NB: the impact was more likely limited to Brainpool curves, since thanks\n // to WebCrypto availability, NIST curve should not have been affected.\n // Similarly, secp256k1 should have been used rarely enough.\n // However, we implement the fix for all curves, since it's only needed in case of\n // verification failure, which is unexpected, hence a minor slowdown is acceptable.\n const tryFallbackVerificationForOldBug = async () => (\n hashed[0] === 0 ?\n jsVerify(curve, signature, hashed.subarray(1), publicKey) :\n false\n );\n\n if (message && !util.isStream(message)) {\n switch (curve.type) {\n case 'web':\n try {\n // Need to await to make sure browser succeeds\n const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n } catch (err) {\n // We do not fallback if the error is related to key integrity\n // Unfortunately Safari does not support nistP521 and throws a DataError when using it\n // So we need to always fallback for that curve\n if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {\n throw err;\n }\n util.printDebugError('Browser did not support verifying: ' + err.message);\n }\n break;\n case 'node': {\n const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n }\n }\n }\n\n const verified = await jsVerify(curve, signature, hashed, publicKey);\n return verified || tryFallbackVerificationForOldBug();\n}\n\n/**\n * Validate ECDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDSA public point\n * @param {Uint8Array} d - ECDSA secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n const curve = new CurveWithOID(oid);\n // Reject curves x25519 and ed25519\n if (curve.keyType !== enums.publicKey.ecdsa) {\n return false;\n }\n\n // To speed up the validation, we try to use node- or webcrypto when available\n // and sign + verify a random message\n switch (curve.type) {\n case 'web':\n case 'node': {\n const message = getRandomBytes(8);\n const hashAlgo = enums.hash.sha256;\n const hashed = await hash.digest(hashAlgo, message);\n try {\n const signature = await sign(oid, hashAlgo, message, Q, d, hashed);\n // eslint-disable-next-line @typescript-eslint/return-await\n return await verify(oid, hashAlgo, signature, message, Q, hashed);\n } catch (err) {\n return false;\n }\n }\n default:\n return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Fallback javascript implementation of ECDSA verification.\n * To be used if no native implementation is available for the given curve/operation.\n */\nasync function jsVerify(curve, signature, hashed, publicKey) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);\n // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch\n return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });\n}\n\nasync function webSign(curve, hashAlgo, message, keyPair) {\n const len = curve.payloadSize;\n const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['sign']\n );\n\n const signature = new Uint8Array(await webCrypto.sign(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n message\n ));\n\n return {\n r: signature.slice(0, len),\n s: signature.slice(len, len << 1)\n };\n}\n\nasync function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);\n const key = await webCrypto.importKey(\n 'jwk',\n jwk,\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, curve.hash) }\n },\n false,\n ['verify']\n );\n\n const signature = util.concatUint8Array([r, s]).buffer;\n\n return webCrypto.verify(\n {\n 'name': 'ECDSA',\n 'namedCurve': webCurves[curve.name],\n 'hash': { name: enums.read(enums.webHash, hashAlgo) }\n },\n key,\n signature,\n message\n );\n}\n\nasync function nodeSign(curve, hashAlgo, message, privateKey) {\n // JWT encoding cannot be used for now, as Brainpool curves are not supported\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n privateKey: nodeBuffer.from(privateKey)\n });\n\n const sign = nodeCrypto.createSign(enums.read(enums.hash, hashAlgo));\n sign.write(message);\n sign.end();\n\n const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));\n const len = curve.payloadSize;\n\n return {\n r: signature.subarray(0, len),\n s: signature.subarray(len, len << 1)\n };\n}\n\nasync function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {\n const ecKeyUtils = util.nodeRequire('eckey-utils');\n const nodeBuffer = util.getNodeBuffer();\n const { publicKey: derPublicKey } = ecKeyUtils.generateDer({\n curveName: nodeCurves[curve.name],\n publicKey: nodeBuffer.from(publicKey)\n });\n\n const verify = nodeCrypto.createVerify(enums.read(enums.hash, hashAlgo));\n verify.write(message);\n verify.end();\n\n const signature = util.concatUint8Array([r, s]);\n\n try {\n return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);\n } catch (err) {\n return false;\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2018 Proton Technologies AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.\n * This key type has been deprecated by the crypto-refresh RFC.\n * @module crypto/public_key/elliptic/eddsa_legacy\n */\n\nimport nacl from '@openpgp/tweetnacl';\nimport util from '../../../util';\nimport enums from '../../../enums';\nimport hash from '../../hash';\nimport { CurveWithOID, checkPublicPointEnconding } from './oid_curves';\nimport { sign as eddsaSign, verify as eddsaVerify } from './eddsa';\n\n/**\n * Sign a message using the provided legacy EdDSA key\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)\n * @param {Uint8Array} message - Message to sign\n * @param {Uint8Array} publicKey - Public key\n * @param {Uint8Array} privateKey - Private key used to sign the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Promise<{\n * r: Uint8Array,\n * s: Uint8Array\n * }>} Signature of the message\n * @async\n */\nexport async function sign(oid, hashAlgo, message, publicKey, privateKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const { RS: signature } = await eddsaSign(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);\n // EdDSA signature params are returned in little-endian format\n return {\n r: signature.subarray(0, 32),\n s: signature.subarray(32)\n };\n}\n\n/**\n * Verifies if a legacy EdDSA signature is valid for a message\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature\n * @param {{r: Uint8Array,\n s: Uint8Array}} signature Signature to verify the message\n * @param {Uint8Array} m - Message to verify\n * @param {Uint8Array} publicKey - Public key used to verify the message\n * @param {Uint8Array} hashed - The hashed message\n * @returns {Boolean}\n * @async\n */\nexport async function verify(oid, hashAlgo, { r, s }, m, publicKey, hashed) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, publicKey);\n if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {\n // Enforce digest sizes, since the constraint was already present in RFC4880bis:\n // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2\n // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n throw new Error('Hash algorithm too weak for EdDSA.');\n }\n const RS = util.concatUint8Array([r, s]);\n return eddsaVerify(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);\n}\n/**\n * Validate legacy EdDSA parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - EdDSA public point\n * @param {Uint8Array} k - EdDSA secret seed\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, k) {\n // Check whether the given curve is supported\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n return false;\n }\n\n /**\n * Derive public point Q' = dG from private key\n * and expect Q == Q'\n */\n const { publicKey } = nacl.sign.keyPair.fromSeed(k);\n const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix\n return util.equalsUint8Array(Q, dG);\n\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport util from '../util';\n\n/**\n * @fileoverview Functions to add and remove PKCS5 padding\n * @see PublicKeyEncryptedSessionKeyPacket\n * @module crypto/pkcs5\n * @private\n */\n\n/**\n * Add pkcs5 padding to a message\n * @param {Uint8Array} message - message to pad\n * @returns {Uint8Array} Padded message.\n */\nexport function encode(message) {\n const c = 8 - (message.length % 8);\n const padded = new Uint8Array(message.length + c).fill(c);\n padded.set(message);\n return padded;\n}\n\n/**\n * Remove pkcs5 padding from a message\n * @param {Uint8Array} message - message to remove padding from\n * @returns {Uint8Array} Message without padding.\n */\nexport function decode(message) {\n const len = message.length;\n if (len > 0) {\n const c = message[len - 1];\n if (c >= 1) {\n const provided = message.subarray(len - c);\n const computed = new Uint8Array(c).fill(c);\n if (util.equalsUint8Array(provided, computed)) {\n return message.subarray(0, len - c);\n }\n }\n }\n throw new Error('Invalid padding');\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview Key encryption and decryption for RFC 6637 ECDH\n * @module crypto/public_key/elliptic/ecdh\n */\n\nimport { CurveWithOID, jwkToRawPublic, rawPublicToJWK, privateToJWK, validateStandardParams, checkPublicPointEnconding } from './oid_curves';\nimport * as aesKW from '../../aes_kw';\nimport hash from '../../hash';\nimport enums from '../../../enums';\nimport util from '../../../util';\nimport { b64ToUint8Array } from '../../../encoding/base64';\nimport * as pkcs5 from '../../pkcs5';\nimport { getCipherParams } from '../../cipher';\nimport { generateEphemeralEncryptionMaterial as ecdhXGenerateEphemeralEncryptionMaterial, recomputeSharedSecret as ecdhXRecomputeSharedSecret } from './ecdh_x';\n\nconst webCrypto = util.getWebCrypto();\nconst nodeCrypto = util.getNodeCrypto();\n\n/**\n * Validate ECDH parameters\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {Uint8Array} Q - ECDH public point\n * @param {Uint8Array} d - ECDH secret scalar\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(oid, Q, d) {\n return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);\n}\n\n// Build Param for ECDH algorithm (RFC 6637)\nfunction buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {\n return util.concatUint8Array([\n oid.write(),\n new Uint8Array([public_algo]),\n kdfParams.write(),\n util.stringToUint8Array('Anonymous Sender '),\n fingerprint\n ]);\n}\n\n// Key Derivation Function (RFC 6637)\nasync function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {\n // Note: X is little endian for Curve25519, big-endian for all others.\n // This is not ideal, but the RFC's are unclear\n // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B\n let i;\n if (stripLeading) {\n // Work around old go crypto bug\n for (i = 0; i < X.length && X[i] === 0; i++);\n X = X.subarray(i);\n }\n if (stripTrailing) {\n // Work around old OpenPGP.js bug\n for (i = X.length - 1; i >= 0 && X[i] === 0; i--);\n X = X.subarray(0, i + 1);\n }\n const digest = await hash.digest(hashAlgo, util.concatUint8Array([\n new Uint8Array([0, 0, 0, 1]),\n X,\n param\n ]));\n return digest.subarray(0, length);\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPublicEphemeralKey(curve, Q) {\n switch (curve.type) {\n case 'curve25519Legacy': {\n const { sharedSecret: sharedKey, ephemeralPublicKey } = await ecdhXGenerateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));\n const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);\n return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPublicEphemeralKey(curve, Q);\n } catch (err) {\n util.printDebugError(err);\n return jsPublicEphemeralKey(curve, Q);\n }\n }\n break;\n case 'node':\n return nodePublicEphemeralKey(curve, Q);\n default:\n return jsPublicEphemeralKey(curve, Q);\n\n }\n}\n\n/**\n * Encrypt and wrap a session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} data - Unpadded session key data\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}\n * @async\n */\nexport async function encrypt(oid, kdfParams, data, Q, fingerprint) {\n const m = pkcs5.encode(data);\n\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);\n const wrappedKey = await aesKW.wrap(kdfParams.cipher, Z, m);\n return { publicKey, wrappedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function genPrivateEphemeralKey(curve, V, Q, d) {\n if (d.length !== curve.payloadSize) {\n const privateKey = new Uint8Array(curve.payloadSize);\n privateKey.set(d, curve.payloadSize - d.length);\n d = privateKey;\n }\n switch (curve.type) {\n case 'curve25519Legacy': {\n const secretKey = d.slice().reverse();\n const sharedKey = await ecdhXRecomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);\n return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below\n }\n case 'web':\n if (curve.web && util.getWebCrypto()) {\n try {\n return await webPrivateEphemeralKey(curve, V, Q, d);\n } catch (err) {\n util.printDebugError(err);\n return jsPrivateEphemeralKey(curve, V, d);\n }\n }\n break;\n case 'node':\n return nodePrivateEphemeralKey(curve, V, d);\n default:\n return jsPrivateEphemeralKey(curve, V, d);\n }\n}\n\n/**\n * Decrypt and unwrap the value derived from session key\n *\n * @param {module:type/oid} oid - Elliptic curve object identifier\n * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} C - Encrypted and wrapped value derived from session key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version\n * @returns {Promise} Value derived from session key.\n * @async\n */\nexport async function decrypt(oid, kdfParams, V, C, Q, d, fingerprint) {\n const curve = new CurveWithOID(oid);\n checkPublicPointEnconding(curve, Q);\n checkPublicPointEnconding(curve, V);\n const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);\n const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);\n const { keySize } = getCipherParams(kdfParams.cipher);\n let err;\n for (let i = 0; i < 3; i++) {\n try {\n // Work around old go crypto bug and old OpenPGP.js bug, respectively.\n const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);\n return pkcs5.decode(await aesKW.unwrap(kdfParams.cipher, Z, C));\n } catch (e) {\n err = e;\n }\n }\n throw err;\n}\n\nasync function jsPrivateEphemeralKey(curve, V, d) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { secretKey: d, sharedKey };\n}\n\nasync function jsPublicEphemeralKey(curve, Q) {\n const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);\n const { publicKey: V, privateKey: v } = await curve.genKeyPair();\n\n // The output includes parity byte\n const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);\n const sharedKey = sharedSecretWithParity.subarray(1);\n return { publicKey: V, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} Q - Recipient public key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPrivateEphemeralKey(curve, V, Q, d) {\n const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);\n let privateKey = webCrypto.importKey(\n 'jwk',\n recipient,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);\n let sender = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n []\n );\n [privateKey, sender] = await Promise.all([privateKey, sender]);\n let S = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: sender\n },\n privateKey,\n curve.sharedSize\n );\n let secret = webCrypto.exportKey(\n 'jwk',\n privateKey\n );\n [S, secret] = await Promise.all([S, secret]);\n const sharedKey = new Uint8Array(S);\n const secretKey = b64ToUint8Array(secret.d, true);\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using webCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function webPublicEphemeralKey(curve, Q) {\n const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);\n let keyPair = webCrypto.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n true,\n ['deriveKey', 'deriveBits']\n );\n let recipient = webCrypto.importKey(\n 'jwk',\n jwk,\n {\n name: 'ECDH',\n namedCurve: curve.web\n },\n false,\n []\n );\n [keyPair, recipient] = await Promise.all([keyPair, recipient]);\n let s = webCrypto.deriveBits(\n {\n name: 'ECDH',\n namedCurve: curve.web,\n public: recipient\n },\n keyPair.privateKey,\n curve.sharedSize\n );\n let p = webCrypto.exportKey(\n 'jwk',\n keyPair.publicKey\n );\n [s, p] = await Promise.all([s, p]);\n const sharedKey = new Uint8Array(s);\n const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));\n return { publicKey, sharedKey };\n}\n\n/**\n * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} V - Public part of ephemeral key\n * @param {Uint8Array} d - Recipient private key\n * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePrivateEphemeralKey(curve, V, d) {\n const recipient = nodeCrypto.createECDH(curve.node);\n recipient.setPrivateKey(d);\n const sharedKey = new Uint8Array(recipient.computeSecret(V));\n const secretKey = new Uint8Array(recipient.getPrivateKey());\n return { secretKey, sharedKey };\n}\n\n/**\n * Generate ECDHE ephemeral key and secret from public key using nodeCrypto\n *\n * @param {CurveWithOID} curve - Elliptic curve object\n * @param {Uint8Array} Q - Recipient public key\n * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}\n * @async\n */\nasync function nodePublicEphemeralKey(curve, Q) {\n const sender = nodeCrypto.createECDH(curve.node);\n sender.generateKeys();\n const sharedKey = new Uint8Array(sender.computeSecret(Q));\n const publicKey = new Uint8Array(sender.getPublicKey());\n return { publicKey, sharedKey };\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @fileoverview A Digital signature algorithm implementation\n * @module crypto/public_key/dsa\n */\nimport { getRandomBigInteger } from '../random';\nimport util from '../../util';\nimport { isProbablePrime } from './prime';\nimport { bigIntToUint8Array, bitLength, byteLength, mod, modExp, modInv, uint8ArrayToBigInt } from '../biginteger';\n\n/*\n TODO regarding the hash function, read:\n https://tools.ietf.org/html/rfc4880#section-13.6\n https://tools.ietf.org/html/rfc4880#section-14\n*/\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\n/**\n * DSA Sign function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} x\n * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}\n * @async\n */\nexport async function sign(hashAlgo, hashed, g, p, q, x) {\n const _0n = BigInt(0);\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n x = uint8ArrayToBigInt(x);\n\n let k;\n let r;\n let s;\n let t;\n g = mod(g, p);\n x = mod(x, q);\n // If the output size of the chosen hash is larger than the number of\n // bits of q, the hash result is truncated to fit by taking the number\n // of leftmost bits equal to the number of bits of q. This (possibly\n // truncated) hash function result is treated as a number and used\n // directly in the DSA signature algorithm.\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n // FIPS-186-4, section 4.6:\n // The values of r and s shall be checked to determine if r = 0 or s = 0.\n // If either r = 0 or s = 0, a new value of k shall be generated, and the\n // signature shall be recalculated. It is extremely unlikely that r = 0\n // or s = 0 if signatures are generated properly.\n while (true) {\n // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n k = getRandomBigInteger(_1n, q); // returns in [1, q-1]\n r = mod(modExp(g, k, p), q); // (g**k mod p) mod q\n if (r === _0n) {\n continue;\n }\n const xr = mod(x * r, q);\n t = mod(h + xr, q); // H(m) + x*r mod q\n s = mod(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q\n if (s === _0n) {\n continue;\n }\n break;\n }\n return {\n r: bigIntToUint8Array(r, 'be', byteLength(p)),\n s: bigIntToUint8Array(s, 'be', byteLength(p))\n };\n}\n\n/**\n * DSA Verify function\n * @param {Integer} hashAlgo\n * @param {Uint8Array} r\n * @param {Uint8Array} s\n * @param {Uint8Array} hashed\n * @param {Uint8Array} g\n * @param {Uint8Array} p\n * @param {Uint8Array} q\n * @param {Uint8Array} y\n * @returns {boolean}\n * @async\n */\nexport async function verify(hashAlgo, r, s, hashed, g, p, q, y) {\n r = uint8ArrayToBigInt(r);\n s = uint8ArrayToBigInt(s);\n\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n\n if (r <= _0n || r >= q ||\n s <= _0n || s >= q) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n const h = mod(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);\n const w = modInv(s, q); // s**-1 mod q\n if (w === _0n) {\n util.printDebug('invalid DSA Signature');\n return false;\n }\n\n g = mod(g, p);\n y = mod(y, p);\n const u1 = mod(h * w, q); // H(m) * w mod q\n const u2 = mod(r * w, q); // r * w mod q\n const t1 = modExp(g, u1, p); // g**u1 mod p\n const t2 = modExp(y, u2, p); // y**u2 mod p\n const v = mod(mod(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q\n return v === r;\n}\n\n/**\n * Validate DSA parameters\n * @param {Uint8Array} p - DSA prime\n * @param {Uint8Array} q - DSA group order\n * @param {Uint8Array} g - DSA sub-group generator\n * @param {Uint8Array} y - DSA public key\n * @param {Uint8Array} x - DSA private key\n * @returns {Promise} Whether params are valid.\n * @async\n */\nexport async function validateParams(p, q, g, y, x) {\n p = uint8ArrayToBigInt(p);\n q = uint8ArrayToBigInt(q);\n g = uint8ArrayToBigInt(g);\n y = uint8ArrayToBigInt(y);\n // Check that 1 < g < p\n if (g <= _1n || g >= p) {\n return false;\n }\n\n /**\n * Check that subgroup order q divides p-1\n */\n if (mod(p - _1n, q) !== _0n) {\n return false;\n }\n\n /**\n * g has order q\n * Check that g ** q = 1 mod p\n */\n if (modExp(g, q, p) !== _1n) {\n return false;\n }\n\n /**\n * Check q is large and probably prime (we mainly want to avoid small factors)\n */\n const qSize = BigInt(bitLength(q));\n const _150n = BigInt(150);\n if (qSize < _150n || !isProbablePrime(q, null, 32)) {\n return false;\n }\n\n /**\n * Re-derive public key y' = g ** x mod p\n * Expect y == y'\n *\n * Blinded exponentiation computes g**{rq + x} to compare to y\n */\n x = uint8ArrayToBigInt(x);\n const _2n = BigInt(2);\n const r = getRandomBigInteger(_2n << (qSize - _1n), _2n << qSize); // draw r of same size as q\n const rqx = q * r + x;\n if (y !== modExp(g, rqx, p)) {\n return false;\n }\n\n return true;\n}\n","/**\n * @fileoverview Asymmetric cryptography functions\n * @module crypto/public_key\n */\n\nimport * as rsa from './rsa';\nimport * as elgamal from './elgamal';\nimport * as elliptic from './elliptic';\nimport * as dsa from './dsa';\n\nexport default {\n /** @see module:crypto/public_key/rsa */\n rsa: rsa,\n /** @see module:crypto/public_key/elgamal */\n elgamal: elgamal,\n /** @see module:crypto/public_key/elliptic */\n elliptic: elliptic,\n /** @see module:crypto/public_key/dsa */\n dsa: dsa\n};\n","/**\n * @fileoverview Provides functions for asymmetric signing and signature verification\n * @module crypto/signature\n */\n\nimport publicKey from './public_key';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Parse signature in binary form to get the parameters.\n * The returned values are only padded for EdDSA, since in the other cases their expected length\n * depends on the key params, hence we delegate the padding to the signature verification function.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Uint8Array} signature - Data for which the signature was created\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport function parseSignatureParams(algo, signature) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA signatures:\n // - MPI of RSA signature value m**d mod n.\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n // The signature needs to be the same length as the public key modulo n.\n // We pad s on signature verification, where we have access to n.\n return { read, signatureParams: { s } };\n }\n // Algorithm-Specific Fields for DSA or ECDSA signatures:\n // - MPI of DSA or ECDSA value r.\n // - MPI of DSA or ECDSA value s.\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n {\n // If the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for legacy EdDSA signatures:\n // - MPI of an EC point r.\n // - EdDSA value s, in MPI, in the little endian representation\n case enums.publicKey.eddsaLegacy: {\n // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature\n // verification: if the signature payload sizes are unexpected, we will throw on verification,\n // where we also have access to the OID curve from the key.\n const r = util.readMPI(signature.subarray(read)); read += r.length + 2;\n const s = util.readMPI(signature.subarray(read)); read += s.length + 2;\n return { read, signatureParams: { r, s } };\n }\n // Algorithm-Specific Fields for Ed25519 signatures:\n // - 64 octets of the native signature\n // Algorithm-Specific Fields for Ed448 signatures:\n // - 114 octets of the native signature\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo);\n const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length;\n return { read, signatureParams: { RS } };\n }\n\n default:\n throw new UnsupportedError('Unknown signature algorithm.');\n }\n}\n\n/**\n * Verifies the signature provided for data using specified algorithms and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} signature - Named algorithm-specific signature parameters\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Data for which the signature was created\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} True if signature is valid.\n * @async\n */\nexport async function verify(algo, hashAlgo, signature, publicParams, data, hashed) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto\n return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);\n }\n case enums.publicKey.dsa: {\n const { g, p, q, y } = publicParams;\n const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers\n return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);\n }\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // padding needed for webcrypto\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicParams;\n const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:\n // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9\n const r = util.leftPad(signature.r, curveSize);\n const s = util.leftPad(signature.s, curveSize);\n return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n\n/**\n * Creates a signature on data using specified algorithms and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}\n * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}\n * for public key and hash algorithms.\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {module:enums.hash} hashAlgo - Hash algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters\n * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters\n * @param {Uint8Array} data - Data to be signed\n * @param {Uint8Array} hashed - The hashed data\n * @returns {Promise} Signature Object containing named signature parameters.\n * @async\n */\nexport async function sign(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {\n if (!publicKeyParams || !privateKeyParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);\n return { s };\n }\n case enums.publicKey.dsa: {\n const { g, p, q } = publicKeyParams;\n const { x } = privateKeyParams;\n return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);\n }\n case enums.publicKey.elgamal:\n throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');\n case enums.publicKey.ecdsa: {\n const { oid, Q } = publicKeyParams;\n const { d } = privateKeyParams;\n return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);\n }\n case enums.publicKey.eddsaLegacy: {\n const { oid, Q } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicKeyParams;\n const { seed } = privateKeyParams;\n return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);\n }\n default:\n throw new Error('Unknown signature algorithm.');\n }\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Encoded symmetric key for ECDH (incl. legacy x25519)\n *\n * @module type/ecdh_symkey\n */\n\nimport util from '../util';\n\nclass ECDHSymmetricKey {\n constructor(data) {\n if (data) {\n this.data = data;\n }\n }\n\n /**\n * Read an ECDHSymmetricKey from an Uint8Array:\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n if (bytes.length >= 1) {\n const length = bytes[0];\n if (bytes.length >= 1 + length) {\n this.data = bytes.subarray(1, 1 + length);\n return 1 + this.data.length;\n }\n }\n throw new Error('Invalid symmetric key');\n }\n\n /**\n * Write an ECDHSymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);\n }\n}\n\nexport default ECDHSymmetricKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { UnsupportedError } from '../packet/packet';\n\n/**\n * Implementation of type KDF parameters\n *\n * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:\n * A key derivation function (KDF) is necessary to implement the EC\n * encryption. The Concatenation Key Derivation Function (Approved\n * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is\n * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.\n * @module type/kdf_params\n * @private\n */\n\nclass KDFParams {\n /**\n * @param {enums.hash} hash - Hash algorithm\n * @param {enums.symmetric} cipher - Symmetric algorithm\n */\n constructor(data) {\n if (data) {\n const { hash, cipher } = data;\n this.hash = hash;\n this.cipher = cipher;\n } else {\n this.hash = null;\n this.cipher = null;\n }\n }\n\n /**\n * Read KDFParams from an Uint8Array\n * @param {Uint8Array} input - Where to read the KDFParams from\n * @returns {Number} Number of read bytes.\n */\n read(input) {\n if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {\n throw new UnsupportedError('Cannot read KDFParams');\n }\n this.hash = input[2];\n this.cipher = input[3];\n return 4;\n }\n\n /**\n * Write KDFParams to an Uint8Array\n * @returns {Uint8Array} Array with the KDFParams value\n */\n write() {\n return new Uint8Array([3, 1, this.hash, this.cipher]);\n }\n}\n\nexport default KDFParams;\n","/**\n * Encoded symmetric key for x25519 and x448\n * The payload format varies for v3 and v6 PKESK:\n * the former includes an algorithm byte preceeding the encrypted session key.\n *\n * @module type/x25519x448_symkey\n */\n\nimport util from '../util';\n\nclass ECDHXSymmetricKey {\n static fromObject({ wrappedKey, algorithm }) {\n const instance = new ECDHXSymmetricKey();\n instance.wrappedKey = wrappedKey;\n instance.algorithm = algorithm;\n return instance;\n }\n\n /**\n * - 1 octect for the length `l`\n * - `l` octects of encoded session key data (with optional leading algorithm byte)\n * @param {Uint8Array} bytes\n * @returns {Number} Number of read bytes.\n */\n read(bytes) {\n let read = 0;\n let followLength = bytes[read++];\n this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even\n followLength -= followLength % 2;\n this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength;\n }\n\n /**\n * Write an MontgomerySymmetricKey as an Uint8Array\n * @returns {Uint8Array} Serialised data\n */\n write() {\n return util.concatUint8Array([\n this.algorithm ?\n new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :\n new Uint8Array([this.wrappedKey.length]),\n this.wrappedKey\n ]);\n }\n}\n\nexport default ECDHXSymmetricKey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n// The GPG4Browsers crypto interface\n\n/**\n * @fileoverview Provides functions for asymmetric encryption and decryption as\n * well as key generation and parameter handling for all public-key cryptosystems.\n * @module crypto/crypto\n */\n\nimport publicKey from './public_key';\nimport mode from './mode';\nimport { getRandomBytes } from './random';\nimport { getCipherParams } from './cipher';\nimport ECDHSymkey from '../type/ecdh_symkey';\nimport KDFParams from '../type/kdf_params';\nimport enums from '../enums';\nimport util from '../util';\nimport OID from '../type/oid';\nimport { UnsupportedError } from '../packet/packet';\nimport ECDHXSymmetricKey from '../type/ecdh_x_symkey';\n\n/**\n * Encrypts data using specified algorithm and public key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.\n * @param {module:enums.publicKey} keyAlgo - Public key algorithm\n * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Uint8Array} data - Session key data to be encrypted\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @returns {Promise} Encrypted session key parameters.\n * @async\n */\nexport async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const { n, e } = publicParams;\n const c = await publicKey.rsa.encrypt(data, n, e);\n return { c };\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n return publicKey.elgamal.encrypt(data, p, g, y);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicParams;\n const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(\n oid, kdfParams, data, Q, fingerprint);\n return { V, C: new ECDHSymkey(C) };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n if (symmetricAlgo && !util.isAES(symmetricAlgo)) {\n // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276\n throw new Error('X25519 and X448 keys can only encrypt AES session keys');\n }\n const { A } = publicParams;\n const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(\n keyAlgo, data, A);\n const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });\n return { ephemeralPublicKey, C };\n }\n default:\n return [];\n }\n}\n\n/**\n * Decrypts data using specified algorithm and private key parameters.\n * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}\n * @param {module:enums.publicKey} algo - Public key algorithm\n * @param {Object} publicKeyParams - Algorithm-specific public key parameters\n * @param {Object} privateKeyParams - Algorithm-specific private key parameters\n * @param {Object} sessionKeyParams - Encrypted session key parameters\n * @param {Uint8Array} fingerprint - Recipient fingerprint\n * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing\n * (needed for constant-time processing in RSA and ElGamal)\n * @returns {Promise} Decrypted data.\n * @throws {Error} on sensitive decryption error, unless `randomPayload` is given\n * @async\n */\nexport async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {\n switch (algo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt: {\n const { c } = sessionKeyParams;\n const { n, e } = publicKeyParams;\n const { d, p, q, u } = privateKeyParams;\n return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);\n }\n case enums.publicKey.elgamal: {\n const { c1, c2 } = sessionKeyParams;\n const p = publicKeyParams.p;\n const x = privateKeyParams.x;\n return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);\n }\n case enums.publicKey.ecdh: {\n const { oid, Q, kdfParams } = publicKeyParams;\n const { d } = privateKeyParams;\n const { V, C } = sessionKeyParams;\n return publicKey.elliptic.ecdh.decrypt(\n oid, kdfParams, V, C.data, Q, d, fingerprint);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicKeyParams;\n const { k } = privateKeyParams;\n const { ephemeralPublicKey, C } = sessionKeyParams;\n if (C.algorithm !== null && !util.isAES(C.algorithm)) {\n throw new Error('AES session key expected');\n }\n return publicKey.elliptic.ecdhX.decrypt(\n algo, ephemeralPublicKey, C.wrappedKey, A, k);\n }\n default:\n throw new Error('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse public key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.\n */\nexport function parsePublicKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;\n const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;\n return { read, publicParams: { n, e } };\n }\n case enums.publicKey.dsa: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, q, g, y } };\n }\n case enums.publicKey.elgamal: {\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;\n const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;\n return { read, publicParams: { p, g, y } };\n }\n case enums.publicKey.ecdsa: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.eddsaLegacy: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n if (oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n Q = util.leftPad(Q, 33);\n return { read: read, publicParams: { oid, Q } };\n }\n case enums.publicKey.ecdh: {\n const oid = new OID(); read += oid.read(bytes);\n checkSupportedCurve(oid);\n const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;\n const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));\n return { read: read, publicParams: { oid, Q, kdfParams } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length;\n return { read, publicParams: { A } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Parse private key material in binary form to get the key parameters\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @param {Object} publicParams - (ECC only) public params, needed to format some private params\n * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.\n */\nexport function parsePrivateKeyParams(algo, bytes, publicParams) {\n let read = 0;\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;\n const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;\n const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;\n return { read, privateParams: { d, p, q, u } };\n }\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal: {\n const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;\n return { read, privateParams: { x } };\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;\n d = util.leftPad(d, payloadSize);\n return { read, privateParams: { d } };\n }\n case enums.publicKey.eddsaLegacy: {\n const payloadSize = getCurvePayloadSize(algo, publicParams.oid);\n if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {\n throw new Error('Unexpected OID for eddsaLegacy');\n }\n let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;\n seed = util.leftPad(seed, payloadSize);\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const payloadSize = getCurvePayloadSize(algo);\n const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length;\n return { read, privateParams: { seed } };\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const payloadSize = getCurvePayloadSize(algo);\n const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length;\n return { read, privateParams: { k } };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/** Returns the types comprising the encrypted session key of an algorithm\n * @param {module:enums.publicKey} algo - The key algorithm\n * @param {Uint8Array} bytes - The key material to parse\n * @returns {Object} The session key parameters referenced by name.\n */\nexport function parseEncSessionKeyParams(algo, bytes) {\n let read = 0;\n switch (algo) {\n // Algorithm-Specific Fields for RSA encrypted session keys:\n // - MPI of RSA encrypted value m**e mod n.\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign: {\n const c = util.readMPI(bytes.subarray(read));\n return { c };\n }\n\n // Algorithm-Specific Fields for Elgamal encrypted session keys:\n // - MPI of Elgamal value g**k mod p\n // - MPI of Elgamal value m * y**k mod p\n case enums.publicKey.elgamal: {\n const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;\n const c2 = util.readMPI(bytes.subarray(read));\n return { c1, c2 };\n }\n // Algorithm-Specific Fields for ECDH encrypted session keys:\n // - MPI containing the ephemeral key used to establish the shared secret\n // - ECDH Symmetric Key\n case enums.publicKey.ecdh: {\n const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;\n const C = new ECDHSymkey(); C.read(bytes.subarray(read));\n return { V, C };\n }\n // Algorithm-Specific Fields for X25519 or X448 encrypted session keys:\n // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).\n // - A one-octet size of the following fields.\n // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).\n // - The encrypted session key.\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const pointSize = getCurvePayloadSize(algo);\n const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length;\n const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));\n return { ephemeralPublicKey, C };\n }\n default:\n throw new UnsupportedError('Unknown public key encryption algorithm.');\n }\n}\n\n/**\n * Convert params to MPI and serializes them in the proper order\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} params - The key parameters indexed by name\n * @returns {Uint8Array} The array containing the MPIs.\n */\nexport function serializeParams(algo, params) {\n // Some algorithms do not rely on MPIs to store the binary params\n const algosWithNativeRepresentation = new Set([\n enums.publicKey.ed25519,\n enums.publicKey.x25519,\n enums.publicKey.ed448,\n enums.publicKey.x448\n ]);\n const orderedParams = Object.keys(params).map(name => {\n const param = params[name];\n if (!util.isUint8Array(param)) return param.write();\n return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);\n });\n return util.concatUint8Array(orderedParams);\n}\n\n/**\n * Generate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Integer} bits - Bit length for RSA keys\n * @param {module:type/oid} oid - Object identifier for ECC keys\n * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.\n * @async\n */\nexport function generateParams(algo, bits, oid) {\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({\n privateParams: { d, p, q, u },\n publicParams: { n, e }\n }));\n case enums.publicKey.ecdsa:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { d: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({\n privateParams: { seed: secret },\n publicParams: { oid: new OID(oid), Q }\n }));\n case enums.publicKey.ecdh:\n return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({\n privateParams: { d: secret },\n publicParams: {\n oid: new OID(oid),\n Q,\n kdfParams: new KDFParams({ hash, cipher })\n }\n }));\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({\n privateParams: { seed },\n publicParams: { A }\n }));\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({\n privateParams: { k },\n publicParams: { A }\n }));\n case enums.publicKey.dsa:\n case enums.publicKey.elgamal:\n throw new Error('Unsupported algorithm for key generation.');\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Validate algorithm-specific key parameters\n * @param {module:enums.publicKey} algo - The public key algorithm\n * @param {Object} publicParams - Algorithm-specific public key parameters\n * @param {Object} privateParams - Algorithm-specific private key parameters\n * @returns {Promise} Whether the parameters are valid.\n * @async\n */\nexport async function validateParams(algo, publicParams, privateParams) {\n if (!publicParams || !privateParams) {\n throw new Error('Missing key parameters');\n }\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign: {\n const { n, e } = publicParams;\n const { d, p, q, u } = privateParams;\n return publicKey.rsa.validateParams(n, e, d, p, q, u);\n }\n case enums.publicKey.dsa: {\n const { p, q, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.dsa.validateParams(p, q, g, y, x);\n }\n case enums.publicKey.elgamal: {\n const { p, g, y } = publicParams;\n const { x } = privateParams;\n return publicKey.elgamal.validateParams(p, g, y, x);\n }\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh: {\n const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];\n const { oid, Q } = publicParams;\n const { d } = privateParams;\n return algoModule.validateParams(oid, Q, d);\n }\n case enums.publicKey.eddsaLegacy: {\n const { Q, oid } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);\n }\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448: {\n const { A } = publicParams;\n const { seed } = privateParams;\n return publicKey.elliptic.eddsa.validateParams(algo, A, seed);\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const { A } = publicParams;\n const { k } = privateParams;\n return publicKey.elliptic.ecdhX.validateParams(algo, A, k);\n }\n default:\n throw new Error('Unknown public key algorithm.');\n }\n}\n\n/**\n * Generates a random byte prefix for the specified algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.\n * @async\n */\nexport async function getPrefixRandom(algo) {\n const { blockSize } = getCipherParams(algo);\n const prefixrandom = await getRandomBytes(blockSize);\n const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);\n return util.concat([prefixrandom, repeat]);\n}\n\n/**\n * Generating a session key for the specified symmetric algorithm\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} algo - Symmetric encryption algorithm\n * @returns {Uint8Array} Random bytes as a string to be used as a key.\n */\nexport function generateSessionKey(algo) {\n const { keySize } = getCipherParams(algo);\n return getRandomBytes(keySize);\n}\n\n/**\n * Get implementation of the given AEAD mode\n * @param {enums.aead} algo\n * @returns {Object}\n * @throws {Error} on invalid algo\n */\nexport function getAEADMode(algo) {\n const algoName = enums.read(enums.aead, algo);\n return mode[algoName];\n}\n\n/**\n * Check whether the given curve OID is supported\n * @param {module:type/oid} oid - EC object identifier\n * @throws {UnsupportedError} if curve is not supported\n */\nfunction checkSupportedCurve(oid) {\n try {\n oid.getName();\n } catch (e) {\n throw new UnsupportedError('Unknown curve OID');\n }\n}\n\n/**\n * Get encoded secret size for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getCurvePayloadSize(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.ecdh:\n case enums.publicKey.eddsaLegacy:\n return new publicKey.elliptic.CurveWithOID(oid).payloadSize;\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPayloadSize(algo);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return publicKey.elliptic.ecdhX.getPayloadSize(algo);\n default:\n throw new Error('Unknown elliptic algo');\n }\n}\n\n/**\n * Get preferred signing hash algo for a given elliptic algo\n * @param {module:enums.publicKey} algo - alrogithm identifier\n * @param {module:type/oid} [oid] - curve OID if needed by algo\n */\nexport function getPreferredCurveHashAlgo(algo, oid) {\n switch (algo) {\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return publicKey.elliptic.getPreferredHashAlgo(oid);\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);\n default:\n throw new Error('Unknown elliptic signing algo');\n }\n}\n\n\nexport { getCipherParams };\n","/**\n * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js\n * @see module:crypto/crypto\n * @see module:crypto/signature\n * @see module:crypto/public_key\n * @see module:crypto/cipher\n * @see module:crypto/random\n * @see module:crypto/hash\n * @module crypto\n */\n\nimport * as cipher from './cipher';\nimport hash from './hash';\nimport mode from './mode';\nimport publicKey from './public_key';\nimport * as signature from './signature';\nimport * as random from './random';\nimport * as pkcs1 from './pkcs1';\nimport * as pkcs5 from './pkcs5';\nimport * as crypto from './crypto';\nimport * as aesKW from './aes_kw';\n\n// TODO move cfb and gcm to cipher\nconst mod = {\n /** @see module:crypto/cipher */\n cipher: cipher,\n /** @see module:crypto/hash */\n hash: hash,\n /** @see module:crypto/mode */\n mode: mode,\n /** @see module:crypto/public_key */\n publicKey: publicKey,\n /** @see module:crypto/signature */\n signature: signature,\n /** @see module:crypto/random */\n random: random,\n /** @see module:crypto/pkcs1 */\n pkcs1: pkcs1,\n /** @see module:crypto/pkcs5 */\n pkcs5: pkcs5,\n /** @see module:crypto/aes_kw */\n aesKW: aesKW\n};\n\nObject.assign(mod, crypto);\n\nexport default mod;\n","import defaultConfig from '../../config';\nimport enums from '../../enums';\nimport util from '../../util';\nimport crypto from '../../crypto';\n\nconst ARGON2_TYPE = 0x02; // id\nconst ARGON2_VERSION = 0x13;\nconst ARGON2_SALT_SIZE = 16;\n\nexport class Argon2OutOfMemoryError extends Error {\n constructor(...params) {\n super(...params);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Argon2OutOfMemoryError);\n }\n\n this.name = 'Argon2OutOfMemoryError';\n }\n}\n\n// cache argon wasm module\nlet loadArgonWasmModule;\nlet argon2Promise;\n// reload wasm module above this treshold, to deallocated used memory\nconst ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;\n\nclass Argon2S2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n const { passes, parallelism, memoryExponent } = config.s2kArgon2Params;\n\n this.type = 'argon2';\n /**\n * 16 bytes of salt\n * @type {Uint8Array}\n */\n this.salt = null;\n /**\n * number of passes\n * @type {Integer}\n */\n this.t = passes;\n /**\n * degree of parallelism (lanes)\n * @type {Integer}\n */\n this.p = parallelism;\n /**\n * exponent indicating memory size\n * @type {Integer}\n */\n this.encodedM = memoryExponent;\n }\n\n generateSalt() {\n this.salt = crypto.random.getRandomBytes(ARGON2_SALT_SIZE);\n }\n\n /**\n * Parsing function for argon2 string-to-key specifier.\n * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n\n this.salt = bytes.subarray(i, i + 16);\n i += 16;\n\n this.t = bytes[i++];\n this.p = bytes[i++];\n this.encodedM = bytes[i++]; // memory size exponent, one-octect\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n const arr = [\n new Uint8Array([enums.write(enums.s2k, this.type)]),\n this.salt,\n new Uint8Array([this.t, this.p, this.encodedM])\n ];\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to `keySize`\n * @throws {Argon2OutOfMemoryError|Errors}\n * @async\n */\n async produceKey(passphrase, keySize) {\n const decodedM = 2 << (this.encodedM - 1);\n\n try {\n // on first load, the argon2 lib is imported and the WASM module is initialized.\n // the two steps need to be atomic to avoid race conditions causing multiple wasm modules\n // being loaded when `argon2Promise` is not initialized.\n loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;\n argon2Promise = argon2Promise || loadArgonWasmModule();\n\n // important to keep local ref to argon2 in case the module is reloaded by another instance\n const argon2 = await argon2Promise;\n\n const passwordBytes = util.encodeUTF8(passphrase);\n const hash = argon2({\n version: ARGON2_VERSION,\n type: ARGON2_TYPE,\n password: passwordBytes,\n salt: this.salt,\n tagLength: keySize,\n memorySize: decodedM,\n parallelism: this.p,\n passes: this.t\n });\n\n // a lot of memory was used, reload to deallocate\n if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {\n // it will be awaited if needed at the next `produceKey` invocation\n argon2Promise = loadArgonWasmModule();\n argon2Promise.catch(() => {});\n }\n return hash;\n } catch (e) {\n if (e.message && (\n e.message.includes('Unable to grow instance memory') || // Chrome\n e.message.includes('failed to grow memory') || // Firefox\n e.message.includes('WebAssembly.Memory.grow') || // Safari\n e.message.includes('Out of memory') // Safari iOS\n )) {\n throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');\n } else {\n throw e;\n }\n }\n }\n}\n\nexport default Argon2S2K;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * Implementation of the String-to-key specifier\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:\n * String-to-key (S2K) specifiers are used to convert passphrase strings\n * into symmetric-key encryption/decryption keys. They are used in two\n * places, currently: to encrypt the secret part of private keys in the\n * private keyring, and to convert passphrases to encryption keys for\n * symmetrically encrypted messages.\n * @module type/s2k\n */\n\nimport defaultConfig from '../../config';\nimport crypto from '../../crypto';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\nimport util from '../../util';\n\nclass GenericS2K {\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(s2kType, config = defaultConfig) {\n /**\n * Hash function identifier, or 0 for gnu-dummy keys\n * @type {module:enums.hash | 0}\n */\n this.algorithm = enums.hash.sha256;\n /**\n * enums.s2k identifier or 'gnu-dummy'\n * @type {String}\n */\n this.type = enums.read(enums.s2k, s2kType);\n /** @type {Integer} */\n this.c = config.s2kIterationCountByte;\n /** Eight bytes of salt in a binary string.\n * @type {Uint8Array}\n */\n this.salt = null;\n }\n\n generateSalt() {\n switch (this.type) {\n case 'salted':\n case 'iterated':\n this.salt = crypto.random.getRandomBytes(8);\n }\n }\n\n getCount() {\n // Exponent bias, defined in RFC4880\n const expbias = 6;\n\n return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);\n }\n\n /**\n * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).\n * @param {Uint8Array} bytes - Payload of string-to-key specifier\n * @returns {Integer} Actual length of the object.\n */\n read(bytes) {\n let i = 0;\n this.algorithm = bytes[i++];\n\n switch (this.type) {\n case 'simple':\n break;\n\n case 'salted':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n break;\n\n case 'iterated':\n this.salt = bytes.subarray(i, i + 8);\n i += 8;\n\n // Octet 10: count, a one-octet, coded value\n this.c = bytes[i++];\n break;\n\n case 'gnu':\n if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {\n i += 3; // GNU\n const gnuExtType = 1000 + bytes[i++];\n if (gnuExtType === 1001) {\n this.type = 'gnu-dummy';\n // GnuPG extension mode 1001 -- don't write secret key at all\n } else {\n throw new UnsupportedError('Unknown s2k gnu protection mode.');\n }\n } else {\n throw new UnsupportedError('Unknown s2k type.');\n }\n break;\n\n default:\n throw new UnsupportedError('Unknown s2k type.'); // unreachable\n }\n\n return i;\n }\n\n /**\n * Serializes s2k information\n * @returns {Uint8Array} Binary representation of s2k.\n */\n write() {\n if (this.type === 'gnu-dummy') {\n return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);\n }\n const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];\n\n switch (this.type) {\n case 'simple':\n break;\n case 'salted':\n arr.push(this.salt);\n break;\n case 'iterated':\n arr.push(this.salt);\n arr.push(new Uint8Array([this.c]));\n break;\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Produces a key using the specified passphrase and the defined\n * hashAlgorithm\n * @param {String} passphrase - Passphrase containing user input\n * @returns {Promise} Produced key with a length corresponding to.\n * hashAlgorithm hash length\n * @async\n */\n async produceKey(passphrase, numBytes) {\n passphrase = util.encodeUTF8(passphrase);\n\n const arr = [];\n let rlength = 0;\n\n let prefixlen = 0;\n while (rlength < numBytes) {\n let toHash;\n switch (this.type) {\n case 'simple':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);\n break;\n case 'salted':\n toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);\n break;\n case 'iterated': {\n const data = util.concatUint8Array([this.salt, passphrase]);\n let datalen = data.length;\n const count = Math.max(this.getCount(), datalen);\n toHash = new Uint8Array(prefixlen + count);\n toHash.set(data, prefixlen);\n for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {\n toHash.copyWithin(pos, prefixlen, pos);\n }\n break;\n }\n case 'gnu':\n throw new Error('GNU s2k type not supported.');\n default:\n throw new Error('Unknown s2k type.');\n }\n const result = await crypto.hash.digest(this.algorithm, toHash);\n arr.push(result);\n rlength += result.length;\n prefixlen++;\n }\n\n return util.concatUint8Array(arr).subarray(0, numBytes);\n }\n}\n\nexport default GenericS2K;\n","import defaultConfig from '../../config';\nimport Argon2S2K, { Argon2OutOfMemoryError } from './argon2';\nimport GenericS2K from './generic';\nimport enums from '../../enums';\nimport { UnsupportedError } from '../../packet/packet';\n\nconst allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);\n\n/**\n * Instantiate a new S2K instance of the given type\n * @param {module:enums.s2k} type\n * @oaram {Object} [config]\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromType(type, config = defaultConfig) {\n switch (type) {\n case enums.s2k.argon2:\n return new Argon2S2K(config);\n case enums.s2k.iterated:\n case enums.s2k.gnu:\n case enums.s2k.salted:\n case enums.s2k.simple:\n return new GenericS2K(type, config);\n default:\n throw new UnsupportedError('Unsupported S2K type');\n }\n}\n\n/**\n * Instantiate a new S2K instance based on the config settings\n * @oaram {Object} config\n * @returns {Object} New s2k object\n * @throws {Error} for unknown or unsupported types\n */\nexport function newS2KFromConfig(config) {\n const { s2kType } = config;\n\n if (!allowedS2KTypesForEncryption.has(s2kType)) {\n throw new Error('The provided `config.s2kType` value is not allowed');\n }\n\n return newS2KFromType(s2kType, config);\n}\n\nexport { Argon2OutOfMemoryError };\n","// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n ], { type: 'text/javascript' }))));\n w.onmessage = function (e) {\n var d = e.data, ed = d.$e$;\n if (ed) {\n var err = new Error(ed[0]);\n err['code'] = ed[1];\n err.stack = ed[2];\n cb(err, null);\n }\n else\n cb(null, d);\n };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\n// see fleb note\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new u32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return [b, r];\n};\nvar _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 0; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >>> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);\n n.set(v.subarray(s, e));\n return n;\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n ,\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, buf, st) {\n // source length\n var sl = dat.length;\n if (!sl || (st && st.f && !st.l))\n return buf || new u8(0);\n // have to estimate size\n var noBuf = !buf || st;\n // no state\n var noSt = !st || st.i;\n if (!st)\n st = {};\n // Assumes roughly 33% compression ratio average\n if (!buf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (noBuf)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >>> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17;\n if (noBuf)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (noBuf)\n cbuf(bt + 131072);\n var end = bt + add;\n for (; bt < end; bt += 4) {\n buf[bt] = buf[bt - dt];\n buf[bt + 1] = buf[bt + 1 - dt];\n buf[bt + 2] = buf[bt + 2 - dt];\n buf[bt + 3] = buf[bt + 3 - dt];\n }\n bt = end;\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n return bt == buf.length ? buf : slc(buf, 0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >>> 8;\n d[o + 2] |= v >>> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return [et, 0];\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return [v, 1];\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return [new u8(tr), mbt];\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return [cl.subarray(0, cli), s];\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >>> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];\n var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];\n var _c = lc(dlt), lclt = _c[0], nlc = _c[1];\n var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n lcfreq[lclt[i] & 31]++;\n for (var i = 0; i < lcdt.length; ++i)\n lcfreq[lcdt[i] & 31]++;\n var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);\n if (flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n if (syms[i] > 255) {\n var len = (syms[i] >>> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];\n var dst = syms[i] & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, lst) {\n var s = dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var pos = 0;\n if (!lvl || s < 8) {\n for (var i = 0; i <= s; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[pos >> 3] = lst;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n }\n else {\n var opt = deo[lvl - 1];\n var n = opt >>> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = new u16(32768), head = new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new u32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx bitpos\n var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;\n for (; i < s; ++i) {\n // hash value\n // deopt when i > s - 3 - at end, deopt acceptable\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && rem > 423) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = (i - dif + j + 32768) & 32767;\n var pti = prev[ti];\n var cd = (ti - pti + 32768) & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += (imod - pimod + 32768) & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one Uint32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n // this is the easiest way to avoid needing to maintain state\n if (!lst && pos & 7)\n pos = wfblk(w, pos + 1, et);\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Alder32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return [fnStr, td];\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n var _a;\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];\n ch[id] = wcln(fns[m], fnStr, td_1);\n }\n var td = mrg({}, ch[id][1]);\n return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };\nvar bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zlv]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get u8\nvar gu8 = function (o) { return o && o.size && new u8(o.size); };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) { return strm.push(ev.data[0], ev.data[1]); };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n w.postMessage([d, t = f], [d.buffer]);\n };\n strm.terminate = function () { w.terminate(); };\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += d[10] | (d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);\n};\n// zlib valid\nvar zlv = function (d) {\n if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if (d[1] & 32)\n err(6, 'invalid zlib data: preset dictionaries not supported');\n};\nfunction AsyncCmpStrm(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n// zlib footer: -4 to -0 is Adler32\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (!cb && typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, !f), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.d = final;\n this.p(chunk, final || false);\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n /**\n * Creates an inflation stream\n * @param cb The callback to call whenever data is inflated\n */\n function Inflate(cb) {\n this.s = {};\n this.p = new u8(0);\n this.ondata = cb;\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n var l = this.p.length;\n var n = new u8(l + c.length);\n n.set(this.p), n.set(c, l), this.p = n;\n };\n Inflate.prototype.c = function (final) {\n this.d = this.s.i = final || false;\n var bts = this.s.b;\n var dt = inflt(this.p, this.o, this.s);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous inflation stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncInflate(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, 0, function () {\n var strm = new Inflate();\n onmessage = astrm(strm);\n }, 7);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);\n}\n/**\n * Expands DEFLATE data with no wrapper\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function inflateSync(data, out) {\n return inflt(data, out);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n this.c.p(c);\n this.l += c.length;\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n /**\n * Creates a GUNZIP stream\n * @param cb The callback to call whenever data is inflated\n */\n function Gunzip(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n var s = this.p.length > 3 ? gzs(this.p) : 4;\n if (s >= this.p.length && !final)\n return;\n this.p = this.p.subarray(s), this.v = 0;\n }\n if (final) {\n if (this.p.length < 8)\n err(6, 'invalid gzip data');\n this.p = this.p.subarray(0, -8);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous GUNZIP stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncGunzip(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, 0, function () {\n var strm = new Gunzip();\n onmessage = astrm(strm);\n }, 9);\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);\n}\n/**\n * Expands GZIP data\n * @param data The data to decompress\n * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.\n * @returns The decompressed version of the data\n */\nexport function gunzipSync(data, out) {\n return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n this.c.p(c);\n var raw = dopt(c, this.o, this.v && 2, f && 4, !f);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n /**\n * Creates a Zlib decompression stream\n * @param cb The callback to call whenever data is inflated\n */\n function Unzlib(cb) {\n this.v = 1;\n Inflate.call(this, cb);\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 2 && !final)\n return;\n this.p = this.p.subarray(2), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous Zlib decompression stream\n * @param cb The callback to call whenever data is deflated\n */\n function AsyncUnzlib(cb) {\n this.ondata = cb;\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, 0, function () {\n var strm = new Unzlib();\n onmessage = astrm(strm);\n }, 11);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);\n}\n/**\n * Expands Zlib data\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function unzlibSync(data, out) {\n return inflt((zlv(data), data.subarray(2, -4)), out);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n /**\n * Creates a decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function Decompress(cb) {\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n var _this_1 = this;\n var cb = function () { _this_1.ondata.apply(_this_1, arguments); };\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(cb)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(cb)\n : new this.Z(cb);\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous decompression stream\n * @param cb The callback to call whenever data is decompressed\n */\n function AsyncDecompress(cb) {\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, out) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, out)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, out)\n : unzlibSync(data, out);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (val instanceof u8)\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return [r, slc(d, i - 1)];\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), ch = _a[0], np = _a[1];\n if (final) {\n if (np.length)\n err(8);\n this.p = null;\n }\n else\n this.p = np;\n this.ondata(ch, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td)\n return td.decode(dat);\n else {\n var _a = dutf8(dat), out = _a[0], ext = _a[1];\n if (ext.length)\n err(8);\n return out;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);\n var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];\n};\n// read zip64 extra field\nvar z64e = function (d, b) {\n for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))\n ;\n return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this_1 = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this_1 = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this_1.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this_1.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this_1.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this_1.ondata(err, dat, final);\n _this_1.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this_1 = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this_1.d & 1))\n return;\n _this_1.u.splice(-1, 1);\n _this_1.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (data, final) {\n this.ondata(null, data, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this_1 = this;\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (data, final) {\n try {\n this.i.push(data, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this_1 = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this_1.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this_1.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (data, final) {\n if (this.i.terminate)\n data = slc(data, 0);\n this.i.push(data, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this_1 = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var _a;\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n if (sc_1 == 4294967295) {\n _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];\n }\n else if (dd)\n sc_1 = -1;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this_1.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this_1.k[0] == chks_3 && _this_1.c)\n _this_1.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n if (sc < 320000) {\n try {\n cbl(null, inflateSync(infl, new u8(su)));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = o == 4294967295 || c == 65535;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the Literal Data Packet (Tag 11)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:\n * A Literal Data packet contains the body of a message; data that is not to be\n * further interpreted.\n */\nclass LiteralDataPacket {\n static get tag() {\n return enums.packet.literalData;\n }\n\n /**\n * @param {Date} date - The creation date of the literal package\n */\n constructor(date = new Date()) {\n this.format = enums.literal.utf8; // default format for literal data packets\n this.date = util.normalizeDate(date);\n this.text = null; // textual data representation\n this.data = null; // literal data representation\n this.filename = '';\n }\n\n /**\n * Set the packet data to a javascript native string, end of line\n * will be normalized to \\r\\n and by default text is converted to UTF8\n * @param {String | ReadableStream} text - Any native javascript string\n * @param {enums.literal} [format] - The format of the string of bytes\n */\n setText(text, format = enums.literal.utf8) {\n this.format = format;\n this.text = text;\n this.data = null;\n }\n\n /**\n * Returns literal data packets as native JavaScript string\n * with normalized end of line to \\n\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {String | ReadableStream} Literal data as text.\n */\n getText(clone = false) {\n if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read\n this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));\n }\n return this.text;\n }\n\n /**\n * Set the packet data to value represented by the provided string of bytes.\n * @param {Uint8Array | ReadableStream} bytes - The string of bytes\n * @param {enums.literal} format - The format of the string of bytes\n */\n setBytes(bytes, format) {\n this.format = format;\n this.data = bytes;\n this.text = null;\n }\n\n\n /**\n * Get the byte sequence representing the literal packet data\n * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again\n * @returns {Uint8Array | ReadableStream} A sequence of bytes.\n */\n getBytes(clone = false) {\n if (this.data === null) {\n // encode UTF8 and normalize EOL to \\r\\n\n this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));\n }\n if (clone) {\n return stream.passiveClone(this.data);\n }\n return this.data;\n }\n\n\n /**\n * Sets the filename of the literal packet data\n * @param {String} filename - Any native javascript string\n */\n setFilename(filename) {\n this.filename = filename;\n }\n\n\n /**\n * Get the filename of the literal packet data\n * @returns {String} Filename.\n */\n getFilename() {\n return this.filename;\n }\n\n /**\n * Parsing function for a literal data packet (tag 11).\n *\n * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet\n * @returns {Promise} Object representation.\n * @async\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n // - A one-octet field that describes how the data is formatted.\n const format = await reader.readByte(); // enums.literal\n\n const filename_len = await reader.readByte();\n this.filename = util.decodeUTF8(await reader.readBytes(filename_len));\n\n this.date = util.readDate(await reader.readBytes(4));\n\n let data = reader.remainder();\n if (stream.isArrayStream(data)) data = await stream.readToEnd(data);\n this.setBytes(data, format);\n });\n }\n\n /**\n * Creates a Uint8Array representation of the packet, excluding the data\n *\n * @returns {Uint8Array} Uint8Array representation of the packet.\n */\n writeHeader() {\n const filename = util.encodeUTF8(this.filename);\n const filename_length = new Uint8Array([filename.length]);\n\n const format = new Uint8Array([this.format]);\n const date = util.writeDate(this.date);\n\n return util.concatUint8Array([format, filename_length, filename, date]);\n }\n\n /**\n * Creates a Uint8Array representation of the packet\n *\n * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet.\n */\n write() {\n const header = this.writeHeader();\n const data = this.getBytes();\n\n return util.concat([header, data]);\n }\n}\n\nexport default LiteralDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n/**\n * @module type/keyid\n */\n\nimport util from '../util';\n\n/**\n * Implementation of type key id\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:\n * A Key ID is an eight-octet scalar that identifies a key.\n * Implementations SHOULD NOT assume that Key IDs are unique. The\n * section \"Enhanced Key Formats\" below describes how Key IDs are\n * formed.\n */\nclass KeyID {\n constructor() {\n this.bytes = '';\n }\n\n /**\n * Parsing method for a key id\n * @param {Uint8Array} bytes - Input to read the key id from\n */\n read(bytes) {\n this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));\n return this.bytes.length;\n }\n\n /**\n * Serializes the Key ID\n * @returns {Uint8Array} Key ID as a Uint8Array.\n */\n write() {\n return util.stringToUint8Array(this.bytes);\n }\n\n /**\n * Returns the Key ID represented as a hexadecimal string\n * @returns {String} Key ID as a hexadecimal string.\n */\n toHex() {\n return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));\n }\n\n /**\n * Checks equality of Key ID's\n * @param {KeyID} keyID\n * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard\n */\n equals(keyID, matchWildcard = false) {\n return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;\n }\n\n /**\n * Checks to see if the Key ID is unset\n * @returns {Boolean} True if the Key ID is null.\n */\n isNull() {\n return this.bytes === '';\n }\n\n /**\n * Checks to see if the Key ID is a \"wildcard\" Key ID (all zeros)\n * @returns {Boolean} True if this is a wildcard Key ID.\n */\n isWildcard() {\n return /^0+$/.test(this.toHex());\n }\n\n static mapToHex(keyID) {\n return keyID.toHex();\n }\n\n static fromID(hex) {\n const keyID = new KeyID();\n keyID.read(util.hexToUint8Array(hex));\n return keyID;\n }\n\n static wildcard() {\n const keyID = new KeyID();\n keyID.read(new Uint8Array(8));\n return keyID;\n }\n}\n\nexport default KeyID;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { readSimpleLength, UnsupportedError, writeSimpleLength } from './packet';\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.\nconst verified = Symbol('verified');\n\n// A salt notation is used to randomize signatures.\n// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks\n// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).\n// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.\n// some chosen-prefix attacks.\n// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.\nconst SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';\n\n// GPG puts the Issuer and Signature subpackets in the unhashed area.\n// Tampering with those invalidates the signature, so we still trust them and parse them.\n// All other unhashed subpackets are ignored.\nconst allowedUnhashedSubpackets = new Set([\n enums.signatureSubpacket.issuerKeyID,\n enums.signatureSubpacket.issuerFingerprint,\n enums.signatureSubpacket.embeddedSignature\n]);\n\n/**\n * Implementation of the Signature Packet (Tag 2)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:\n * A Signature packet describes a binding between some public key and\n * some data. The most common signatures are a signature of a file or a\n * block of text, and a signature that is a certification of a User ID.\n */\nclass SignaturePacket {\n static get tag() {\n return enums.packet.signature;\n }\n\n constructor() {\n this.version = null;\n /** @type {enums.signature} */\n this.signatureType = null;\n /** @type {enums.hash} */\n this.hashAlgorithm = null;\n /** @type {enums.publicKey} */\n this.publicKeyAlgorithm = null;\n\n this.signatureData = null;\n this.unhashedSubpackets = [];\n this.unknownSubpackets = [];\n this.signedHashValue = null;\n this.salt = null;\n\n this.created = null;\n this.signatureExpirationTime = null;\n this.signatureNeverExpires = true;\n this.exportable = null;\n this.trustLevel = null;\n this.trustAmount = null;\n this.regularExpression = null;\n this.revocable = null;\n this.keyExpirationTime = null;\n this.keyNeverExpires = null;\n this.preferredSymmetricAlgorithms = null;\n this.revocationKeyClass = null;\n this.revocationKeyAlgorithm = null;\n this.revocationKeyFingerprint = null;\n this.issuerKeyID = new KeyID();\n this.rawNotations = [];\n this.notations = {};\n this.preferredHashAlgorithms = null;\n this.preferredCompressionAlgorithms = null;\n this.keyServerPreferences = null;\n this.preferredKeyServer = null;\n this.isPrimaryUserID = null;\n this.policyURI = null;\n this.keyFlags = null;\n this.signersUserID = null;\n this.reasonForRevocationFlag = null;\n this.reasonForRevocationString = null;\n this.features = null;\n this.signatureTargetPublicKeyAlgorithm = null;\n this.signatureTargetHashAlgorithm = null;\n this.signatureTargetHash = null;\n this.embeddedSignature = null;\n this.issuerKeyVersion = null;\n this.issuerFingerprint = null;\n this.preferredAEADAlgorithms = null;\n this.preferredCipherSuites = null;\n\n this.revoked = null;\n this[verified] = null;\n }\n\n /**\n * parsing function for a signature packet (tag 2).\n * @param {String} bytes - Payload of a tag 2 packet\n * @returns {SignaturePacket} Object representation.\n */\n read(bytes, config = defaultConfig) {\n let i = 0;\n this.version = bytes[i++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);\n }\n\n this.signatureType = bytes[i++];\n this.publicKeyAlgorithm = bytes[i++];\n this.hashAlgorithm = bytes[i++];\n\n // hashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), true);\n if (!this.created) {\n throw new Error('Missing signature creation time subpacket.');\n }\n\n // A V4 signature hashes the packet body\n // starting from its first field, the version number, through the end\n // of the hashed subpacket data. Thus, the fields hashed are the\n // signature version, the signature type, the public-key algorithm, the\n // hash algorithm, the hashed subpacket length, and the hashed\n // subpacket body.\n this.signatureData = bytes.subarray(0, i);\n\n // unhashed subpackets\n i += this.readSubPackets(bytes.subarray(i, bytes.length), false);\n\n // Two-octet field holding left 16 bits of signed hash value.\n this.signedHashValue = bytes.subarray(i, i + 2);\n i += 2;\n\n // Only for v6 signatures, a variable-length field containing:\n if (this.version === 6) {\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[i++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(i, i + saltLength);\n i += saltLength;\n }\n\n const signatureMaterial = bytes.subarray(i, bytes.length);\n const { read, signatureParams } = crypto.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);\n if (read < signatureMaterial.length) {\n throw new Error('Error reading MPIs');\n }\n this.params = signatureParams;\n }\n\n /**\n * @returns {Uint8Array | ReadableStream}\n */\n writeParams() {\n if (this.params instanceof Promise) {\n return stream.fromAsync(\n async () => crypto.serializeParams(this.publicKeyAlgorithm, await this.params)\n );\n }\n return crypto.serializeParams(this.publicKeyAlgorithm, this.params);\n }\n\n write() {\n const arr = [];\n arr.push(this.signatureData);\n arr.push(this.writeUnhashedSubPackets());\n arr.push(this.signedHashValue);\n if (this.version === 6) {\n arr.push(new Uint8Array([this.salt.length]));\n arr.push(this.salt);\n }\n arr.push(this.writeParams());\n return util.concat(arr);\n }\n\n /**\n * Signs provided data. This needs to be done prior to serialization.\n * @param {SecretKeyPacket} key - Private key used to sign the message.\n * @param {Object} data - Contains packets to be signed.\n * @param {Date} [date] - The signature creation time.\n * @param {Boolean} [detached] - Whether to create a detached signature\n * @throws {Error} if signing failed\n * @async\n */\n async sign(key, data, date = new Date(), detached = false, config) {\n this.version = key.version;\n\n this.created = util.normalizeDate(date);\n this.issuerKeyVersion = key.version;\n this.issuerFingerprint = key.getFingerprintBytes();\n this.issuerKeyID = key.getKeyID();\n\n const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];\n\n // add randomness to the signature\n if (this.version === 6) {\n const saltLength = saltLengthForHash(this.hashAlgorithm);\n if (this.salt === null) {\n this.salt = crypto.random.getRandomBytes(saltLength);\n } else if (saltLength !== this.salt.length) {\n throw new Error('Provided salt does not have the required length');\n }\n } else if (config.nonDeterministicSignaturesViaNotation) {\n const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));\n // since re-signing the same object is not supported, it's not expected to have multiple salt notations,\n // but we guard against it as a sanity check\n if (saltNotations.length === 0) {\n const saltValue = crypto.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm));\n this.rawNotations.push({\n name: SALT_NOTATION_NAME,\n value: saltValue,\n humanReadable: false,\n critical: false\n });\n } else {\n throw new Error('Unexpected existing salt notation');\n }\n }\n\n // Add hashed subpackets\n arr.push(this.writeHashedSubPackets());\n\n // Remove unhashed subpackets, in case some allowed unhashed\n // subpackets existed, in order not to duplicate them (in both\n // the hashed and unhashed subpackets) when re-signing.\n this.unhashedSubpackets = [];\n\n this.signatureData = util.concat(arr);\n\n const toHash = this.toHash(this.signatureType, data, detached);\n const hash = await this.hash(this.signatureType, data, toHash, detached);\n\n this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);\n const signed = async () => crypto.signature.sign(\n this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)\n );\n if (util.isStream(hash)) {\n this.params = signed();\n } else {\n this.params = await signed();\n\n // Store the fact that this signature is valid, e.g. for when we call `await\n // getLatestValidSignature(this.revocationSignatures, key, data)` later.\n // Note that this only holds up if the key and data passed to verify are the\n // same as the ones passed to sign.\n this[verified] = true;\n }\n }\n\n /**\n * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeHashedSubPackets() {\n const sub = enums.signatureSubpacket;\n const arr = [];\n let bytes;\n if (this.created === null) {\n throw new Error('Missing signature creation time');\n }\n arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));\n if (this.signatureExpirationTime !== null) {\n arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));\n }\n if (this.exportable !== null) {\n arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));\n }\n if (this.trustLevel !== null) {\n bytes = new Uint8Array([this.trustLevel, this.trustAmount]);\n arr.push(writeSubPacket(sub.trustSignature, true, bytes));\n }\n if (this.regularExpression !== null) {\n arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));\n }\n if (this.revocable !== null) {\n arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));\n }\n if (this.keyExpirationTime !== null) {\n arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));\n }\n if (this.preferredSymmetricAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));\n arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));\n }\n if (this.revocationKeyClass !== null) {\n bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);\n bytes = util.concat([bytes, this.revocationKeyFingerprint]);\n arr.push(writeSubPacket(sub.revocationKey, false, bytes));\n }\n if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {\n // If the version of [the] key is greater than 4, this subpacket\n // MUST NOT be included in the signature.\n arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write()));\n }\n this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {\n bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];\n const encodedName = util.encodeUTF8(name);\n // 2 octets of name length\n bytes.push(util.writeNumber(encodedName.length, 2));\n // 2 octets of value length\n bytes.push(util.writeNumber(value.length, 2));\n bytes.push(encodedName);\n bytes.push(value);\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.notationData, critical, bytes));\n });\n if (this.preferredHashAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));\n arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));\n }\n if (this.preferredCompressionAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));\n arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));\n }\n if (this.keyServerPreferences !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));\n arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));\n }\n if (this.preferredKeyServer !== null) {\n arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));\n }\n if (this.isPrimaryUserID !== null) {\n arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));\n }\n if (this.policyURI !== null) {\n arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));\n }\n if (this.keyFlags !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));\n arr.push(writeSubPacket(sub.keyFlags, true, bytes));\n }\n if (this.signersUserID !== null) {\n arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));\n }\n if (this.reasonForRevocationFlag !== null) {\n bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);\n arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));\n }\n if (this.features !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));\n arr.push(writeSubPacket(sub.features, false, bytes));\n }\n if (this.signatureTargetPublicKeyAlgorithm !== null) {\n bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];\n bytes.push(util.stringToUint8Array(this.signatureTargetHash));\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.signatureTarget, true, bytes));\n }\n if (this.embeddedSignature !== null) {\n arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));\n }\n if (this.issuerFingerprint !== null) {\n bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];\n bytes = util.concat(bytes);\n arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));\n }\n if (this.preferredAEADAlgorithms !== null) {\n bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));\n arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));\n }\n if (this.preferredCipherSuites !== null) {\n bytes = new Uint8Array([].concat(...this.preferredCipherSuites));\n arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));\n }\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n /**\n * Creates an Uint8Array containing the unhashed subpackets\n * @returns {Uint8Array} Subpacket data.\n */\n writeUnhashedSubPackets() {\n const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {\n return writeSubPacket(type, critical, body);\n });\n\n const result = util.concat(arr);\n const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);\n\n return util.concat([length, result]);\n }\n\n // Signature subpackets\n readSubPacket(bytes, hashed = true) {\n let mypos = 0;\n\n // The leftmost bit denotes a \"critical\" packet\n const critical = !!(bytes[mypos] & 0x80);\n const type = bytes[mypos] & 0x7F;\n\n mypos++;\n\n if (!hashed) {\n this.unhashedSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n if (!allowedUnhashedSubpackets.has(type)) {\n return;\n }\n }\n\n // subpacket type\n switch (type) {\n case enums.signatureSubpacket.signatureCreationTime:\n // Signature Creation Time\n this.created = util.readDate(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.signatureExpirationTime: {\n // Signature Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.signatureNeverExpires = seconds === 0;\n this.signatureExpirationTime = seconds;\n\n break;\n }\n case enums.signatureSubpacket.exportableCertification:\n // Exportable Certification\n this.exportable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.trustSignature:\n // Trust Signature\n this.trustLevel = bytes[mypos++];\n this.trustAmount = bytes[mypos++];\n break;\n case enums.signatureSubpacket.regularExpression:\n // Regular Expression\n this.regularExpression = bytes[mypos];\n break;\n case enums.signatureSubpacket.revocable:\n // Revocable\n this.revocable = bytes[mypos++] === 1;\n break;\n case enums.signatureSubpacket.keyExpirationTime: {\n // Key Expiration Time in seconds\n const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));\n\n this.keyExpirationTime = seconds;\n this.keyNeverExpires = seconds === 0;\n\n break;\n }\n case enums.signatureSubpacket.preferredSymmetricAlgorithms:\n // Preferred Symmetric Algorithms\n this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.revocationKey:\n // Revocation Key\n // (1 octet of class, 1 octet of public-key algorithm ID, 20\n // octets of\n // fingerprint)\n this.revocationKeyClass = bytes[mypos++];\n this.revocationKeyAlgorithm = bytes[mypos++];\n this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);\n break;\n\n case enums.signatureSubpacket.issuerKeyID:\n // Issuer\n if (this.version === 4) {\n this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));\n } else if (hashed) {\n // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,\n // since the Issuer Fingerprint subpacket is to be used instead.\n // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.\n // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,\n // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)\n // issuerFingerprint.\n // If the packet is hashed, then we reject the signature, to avoid verifying data different from\n // what was parsed.\n throw new Error('Unexpected Issuer Key ID subpacket');\n }\n break;\n\n case enums.signatureSubpacket.notationData: {\n // Notation Data\n const humanReadable = !!(bytes[mypos] & 0x80);\n\n // We extract key/value tuple from the byte stream.\n mypos += 4;\n const m = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n const n = util.readNumber(bytes.subarray(mypos, mypos + 2));\n mypos += 2;\n\n const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));\n const value = bytes.subarray(mypos + m, mypos + m + n);\n\n this.rawNotations.push({ name, humanReadable, value, critical });\n\n if (humanReadable) {\n this.notations[name] = util.decodeUTF8(value);\n }\n break;\n }\n case enums.signatureSubpacket.preferredHashAlgorithms:\n // Preferred Hash Algorithms\n this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCompressionAlgorithms:\n // Preferred Compression Algorithms\n this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.keyServerPreferences:\n // Key Server Preferences\n this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredKeyServer:\n // Preferred Key Server\n this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.primaryUserID:\n // Primary User ID\n this.isPrimaryUserID = bytes[mypos++] !== 0;\n break;\n case enums.signatureSubpacket.policyURI:\n // Policy URI\n this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.keyFlags:\n // Key Flags\n this.keyFlags = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signersUserID:\n // Signer's User ID\n this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.reasonForRevocation:\n // Reason for Revocation\n this.reasonForRevocationFlag = bytes[mypos++];\n this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.features:\n // Features\n this.features = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.signatureTarget: {\n // Signature Target\n // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)\n this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];\n this.signatureTargetHashAlgorithm = bytes[mypos++];\n\n const len = crypto.getHashByteLength(this.signatureTargetHashAlgorithm);\n\n this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));\n break;\n }\n case enums.signatureSubpacket.embeddedSignature:\n // Embedded Signature\n this.embeddedSignature = new SignaturePacket();\n this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));\n break;\n case enums.signatureSubpacket.issuerFingerprint:\n // Issuer Fingerprint\n this.issuerKeyVersion = bytes[mypos++];\n this.issuerFingerprint = bytes.subarray(mypos, bytes.length);\n if (this.issuerKeyVersion >= 5) {\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));\n }\n break;\n case enums.signatureSubpacket.preferredAEADAlgorithms:\n // Preferred AEAD Algorithms\n this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];\n break;\n case enums.signatureSubpacket.preferredCipherSuites:\n // Preferred AEAD Cipher Suites\n this.preferredCipherSuites = [];\n for (let i = mypos; i < bytes.length; i += 2) {\n this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);\n }\n break;\n default:\n this.unknownSubpackets.push({\n type,\n critical,\n body: bytes.subarray(mypos, bytes.length)\n });\n break;\n }\n }\n\n readSubPackets(bytes, trusted = true, config) {\n const subpacketLengthBytes = this.version === 6 ? 4 : 2;\n\n // Two-octet scalar octet count for following subpacket data.\n const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));\n\n let i = subpacketLengthBytes;\n\n // subpacket data set (zero or more subpackets)\n while (i < 2 + subpacketLength) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);\n\n i += len.len;\n }\n\n return i;\n }\n\n // Produces data to produce signature on\n toSign(type, data) {\n const t = enums.signature;\n\n switch (type) {\n case t.binary:\n if (data.text !== null) {\n return util.encodeUTF8(data.getText(true));\n }\n return data.getBytes(true);\n\n case t.text: {\n const bytes = data.getBytes(true);\n // normalize EOL to \\r\\n\n return util.canonicalizeEOL(bytes);\n }\n case t.standalone:\n return new Uint8Array(0);\n\n case t.certGeneric:\n case t.certPersona:\n case t.certCasual:\n case t.certPositive:\n case t.certRevocation: {\n let packet;\n let tag;\n\n if (data.userID) {\n tag = 0xB4;\n packet = data.userID;\n } else if (data.userAttribute) {\n tag = 0xD1;\n packet = data.userAttribute;\n } else {\n throw new Error('Either a userID or userAttribute packet needs to be ' +\n 'supplied for certification.');\n }\n\n const bytes = packet.write();\n\n return util.concat([this.toSign(t.key, data),\n new Uint8Array([tag]),\n util.writeNumber(bytes.length, 4),\n bytes]);\n }\n case t.subkeyBinding:\n case t.subkeyRevocation:\n case t.keyBinding:\n return util.concat([this.toSign(t.key, data), this.toSign(t.key, {\n key: data.bind\n })]);\n\n case t.key:\n if (data.key === undefined) {\n throw new Error('Key packet is required for this signature.');\n }\n return data.key.writeForHash(this.version);\n\n case t.keyRevocation:\n return this.toSign(t.key, data);\n case t.timestamp:\n return new Uint8Array(0);\n case t.thirdParty:\n throw new Error('Not implemented');\n default:\n throw new Error('Unknown signature type.');\n }\n }\n\n calculateTrailer(data, detached) {\n let length = 0;\n return stream.transform(stream.clone(this.signatureData), value => {\n length += value.length;\n }, () => {\n const arr = [];\n if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {\n if (detached) {\n arr.push(new Uint8Array(6));\n } else {\n arr.push(data.writeHeader());\n }\n }\n arr.push(new Uint8Array([this.version, 0xFF]));\n if (this.version === 5) {\n arr.push(new Uint8Array(4));\n }\n arr.push(util.writeNumber(length, 4));\n // For v5, this should really be writeNumber(length, 8) rather than the\n // hardcoded 4 zero bytes above\n return util.concat(arr);\n });\n }\n\n toHash(signatureType, data, detached = false) {\n const bytes = this.toSign(signatureType, data);\n\n return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);\n }\n\n async hash(signatureType, data, toHash, detached = false) {\n if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {\n // avoid hashing unexpected salt size\n throw new Error('Signature salt does not have the expected length');\n }\n\n if (!toHash) toHash = this.toHash(signatureType, data, detached);\n return crypto.hash.digest(this.hashAlgorithm, toHash);\n }\n\n /**\n * verifies the signature packet. Note: not all signature types are implemented\n * @param {PublicSubkeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature\n * @param {module:enums.signature} signatureType - Expected signature type\n * @param {Uint8Array|Object} data - Data which on the signature applies\n * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration\n * @param {Boolean} [detached] - Whether to verify a detached signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if signature validation failed\n * @async\n */\n async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {\n if (!this.issuerKeyID.equals(key.getKeyID())) {\n throw new Error('Signature was not issued by the given public key');\n }\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');\n }\n\n const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;\n // Cryptographic validity is cached after one successful verification.\n // However, for message signatures, we always re-verify, since the passed `data` can change\n const skipVerify = this[verified] && !isMessageSignature;\n if (!skipVerify) {\n let toHash;\n let hash;\n if (this.hashed) {\n hash = await this.hashed;\n } else {\n toHash = this.toHash(signatureType, data, detached);\n hash = await this.hash(signatureType, data, toHash);\n }\n hash = await stream.readToEnd(hash);\n if (this.signedHashValue[0] !== hash[0] ||\n this.signedHashValue[1] !== hash[1]) {\n throw new Error('Signed digest did not match');\n }\n\n this.params = await this.params;\n\n this[verified] = await crypto.signature.verify(\n this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,\n toHash, hash\n );\n\n if (!this[verified]) {\n throw new Error('Signature verification failed');\n }\n }\n\n const normDate = util.normalizeDate(date);\n if (normDate && this.created > normDate) {\n throw new Error('Signature creation time is in the future');\n }\n if (normDate && normDate >= this.getExpirationTime()) {\n throw new Error('Signature is expired');\n }\n if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {\n throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&\n [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {\n throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());\n }\n this.unknownSubpackets.forEach(({ type, critical }) => {\n if (critical) {\n throw new Error(`Unknown critical signature subpacket type ${type}`);\n }\n });\n this.rawNotations.forEach(({ name, critical }) => {\n if (critical && (config.knownNotations.indexOf(name) < 0)) {\n throw new Error(`Unknown critical notation: ${name}`);\n }\n });\n if (this.revocationKeyClass !== null) {\n throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');\n }\n }\n\n /**\n * Verifies signature expiration date\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @returns {Boolean} True if expired.\n */\n isExpired(date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n return !(this.created <= normDate && normDate < this.getExpirationTime());\n }\n return false;\n }\n\n /**\n * Returns the expiration time of the signature or Infinity if signature does not expire\n * @returns {Date | Infinity} Expiration time.\n */\n getExpirationTime() {\n return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);\n }\n}\n\nexport default SignaturePacket;\n\n/**\n * Creates a Uint8Array representation of a sub signature packet\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}\n * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}\n * @param {Integer} type - Subpacket signature type.\n * @param {Boolean} critical - Whether the subpacket should be critical.\n * @param {String} data - Data to be included\n * @returns {Uint8Array} The signature subpacket.\n * @private\n */\nfunction writeSubPacket(type, critical, data) {\n const arr = [];\n arr.push(writeSimpleLength(data.length + 1));\n arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));\n arr.push(data);\n return util.concat(arr);\n}\n\n/**\n * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.\n * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}\n * @param {enums.hash} hashAlgorithm - Hash algorithm.\n * @returns {Integer} Salt length.\n * @private\n */\nfunction saltLengthForHash(hashAlgorithm) {\n switch (hashAlgorithm) {\n case enums.hash.sha256: return 16;\n case enums.hash.sha384: return 24;\n case enums.hash.sha512: return 32;\n case enums.hash.sha224: return 16;\n case enums.hash.sha3_256: return 16;\n case enums.hash.sha3_512: return 32;\n default: throw new Error('Unsupported hash function');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport SignaturePacket from './signature';\nimport KeyID from '../type/keyid';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the One-Pass Signature Packets (Tag 4)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:\n * The One-Pass Signature packet precedes the signed data and contains\n * enough information to allow the receiver to begin calculating any\n * hashes needed to verify the signature. It allows the Signature\n * packet to be placed at the end of the message, so that the signer\n * can compute the entire signed message in one pass.\n */\nclass OnePassSignaturePacket {\n static get tag() {\n return enums.packet.onePassSignature;\n }\n\n static fromSignaturePacket(signaturePacket, isLast) {\n const onePassSig = new OnePassSignaturePacket();\n onePassSig.version = signaturePacket.version === 6 ? 6 : 3;\n onePassSig.signatureType = signaturePacket.signatureType;\n onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;\n onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;\n onePassSig.issuerKeyID = signaturePacket.issuerKeyID;\n onePassSig.salt = signaturePacket.salt; // v6 only\n onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only\n\n onePassSig.flags = isLast ? 1 : 0;\n return onePassSig;\n }\n\n constructor() {\n /** A one-octet version number. The current versions are 3 and 6. */\n this.version = null;\n /**\n * A one-octet signature type.\n * Signature types are described in\n * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.\n * @type {enums.signature}\n\n */\n this.signatureType = null;\n /**\n * A one-octet number describing the hash algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}\n * @type {enums.hash}\n */\n this.hashAlgorithm = null;\n /**\n * A one-octet number describing the public-key algorithm used.\n * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}\n * @type {enums.publicKey}\n */\n this.publicKeyAlgorithm = null;\n /** Only for v6, a variable-length field containing the salt. */\n this.salt = null;\n /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */\n this.issuerKeyID = null;\n /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */\n this.issuerFingerprint = null;\n /**\n * A one-octet number holding a flag showing whether the signature is nested.\n * A zero value indicates that the next packet is another One-Pass Signature packet\n * that describes another signature to be applied to the same message data.\n */\n this.flags = null;\n }\n\n /**\n * parsing function for a one-pass signature packet (tag 4).\n * @param {Uint8Array} bytes - Payload of a tag 4 packet\n * @returns {OnePassSignaturePacket} Object representation.\n */\n read(bytes) {\n let mypos = 0;\n // A one-octet version number. The current versions are 3 or 6.\n this.version = bytes[mypos++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);\n }\n\n // A one-octet signature type. Signature types are described in\n // Section 5.2.1.\n this.signatureType = bytes[mypos++];\n\n // A one-octet number describing the hash algorithm used.\n this.hashAlgorithm = bytes[mypos++];\n\n // A one-octet number describing the public-key algorithm used.\n this.publicKeyAlgorithm = bytes[mypos++];\n\n if (this.version === 6) {\n // Only for v6 signatures, a variable-length field containing:\n\n // A one-octet salt size. The value MUST match the value defined\n // for the hash algorithm as specified in Table 23 (Hash algorithm registry).\n // To allow parsing unknown hash algos, we only check the expected salt length when verifying.\n const saltLength = bytes[mypos++];\n\n // The salt; a random value value of the specified size.\n this.salt = bytes.subarray(mypos, mypos + saltLength);\n mypos += saltLength;\n\n // Only for v6 packets, 32 octets of the fingerprint of the signing key.\n this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);\n mypos += 32;\n this.issuerKeyID = new KeyID();\n // For v6 the Key ID is the high-order 64 bits of the fingerprint.\n this.issuerKeyID.read(this.issuerFingerprint);\n } else {\n // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.\n this.issuerKeyID = new KeyID();\n this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));\n mypos += 8;\n }\n\n // A one-octet number holding a flag showing whether the signature\n // is nested. A zero value indicates that the next packet is\n // another One-Pass Signature packet that describes another\n // signature to be applied to the same message data.\n this.flags = bytes[mypos++];\n return this;\n }\n\n /**\n * creates a string representation of a one-pass signature packet\n * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.\n */\n write() {\n const arr = [new Uint8Array([\n this.version,\n this.signatureType,\n this.hashAlgorithm,\n this.publicKeyAlgorithm\n ])];\n if (this.version === 6) {\n arr.push(\n new Uint8Array([this.salt.length]),\n this.salt,\n this.issuerFingerprint\n );\n } else {\n arr.push(this.issuerKeyID.write());\n }\n arr.push(new Uint8Array([this.flags]));\n return util.concatUint8Array(arr);\n }\n\n calculateTrailer(...args) {\n return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));\n }\n\n async verify() {\n const correspondingSig = await this.correspondingSig;\n if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {\n throw new Error('Corresponding signature packet missing');\n }\n if (\n correspondingSig.signatureType !== this.signatureType ||\n correspondingSig.hashAlgorithm !== this.hashAlgorithm ||\n correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||\n !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||\n (this.version === 3 && correspondingSig.version === 6) ||\n (this.version === 6 && correspondingSig.version !== 6) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||\n (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))\n ) {\n throw new Error('Corresponding signature packet does not match one-pass signature packet');\n }\n correspondingSig.hashed = this.hashed;\n return correspondingSig.verify.apply(correspondingSig, arguments);\n }\n}\n\nOnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;\nOnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;\nOnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;\n\nexport default OnePassSignaturePacket;\n","import * as stream from '@openpgp/web-stream-tools';\nimport {\n readPackets, supportsStreaming,\n writeTag, writeHeader,\n writePartialLength, writeSimpleLength,\n UnparseablePacket,\n UnsupportedError,\n UnknownPacketError\n} from './packet';\nimport util from '../util';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * Instantiate a new packet given its tag\n * @function newPacketFromTag\n * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @returns {Object} New packet object with type based on tag\n * @throws {Error|UnsupportedError} for disallowed or unknown packets\n */\nexport function newPacketFromTag(tag, allowedPackets) {\n if (!allowedPackets[tag]) {\n // distinguish between disallowed packets and unknown ones\n let packetType;\n try {\n packetType = enums.read(enums.packet, tag);\n } catch (e) {\n throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);\n }\n throw new Error(`Packet not allowed in this context: ${packetType}`);\n }\n return new allowedPackets[tag]();\n}\n\n/**\n * This class represents a list of openpgp packets.\n * Take care when iterating over it - the packets themselves\n * are stored as numerical indices.\n * @extends Array\n */\nclass PacketList extends Array {\n /**\n * Parses the given binary data and returns a list of packets.\n * Equivalent to calling `read` on an empty PacketList instance.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @returns {PacketList} parsed list of packets\n * @throws on parsing errors\n * @async\n */\n static async fromBinary(bytes, allowedPackets, config = defaultConfig) {\n const packets = new PacketList();\n await packets.read(bytes, allowedPackets, config);\n return packets;\n }\n\n /**\n * Reads a stream of binary data and interprets it as a list of packets.\n * @param {Uint8Array | ReadableStream} bytes - binary data to parse\n * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class\n * @param {Object} [config] - full configuration, defaults to openpgp.config\n * @throws on parsing errors\n * @async\n */\n async read(bytes, allowedPackets, config = defaultConfig) {\n if (config.additionalAllowedPackets.length) {\n allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config.additionalAllowedPackets) };\n }\n this.stream = stream.transformPair(bytes, async (readable, writable) => {\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n await writer.ready;\n const done = await readPackets(readable, async parsed => {\n try {\n if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {\n // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:\n // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145\n // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10\n // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21\n return;\n }\n const packet = newPacketFromTag(parsed.tag, allowedPackets);\n packet.packets = new PacketList();\n packet.fromStream = util.isStream(parsed.packet);\n await packet.read(parsed.packet, config);\n await writer.write(packet);\n } catch (e) {\n // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,\n // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.\n // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.\n if (e instanceof UnknownPacketError) {\n if (parsed.tag <= 39) {\n await writer.abort(e);\n } else {\n return;\n }\n }\n\n const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;\n const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);\n if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {\n // The packets that support streaming are the ones that contain message data.\n // Those are also the ones we want to be more strict about and throw on parse errors\n // (since we likely cannot process the message without these packets anyway).\n await writer.abort(e);\n } else {\n const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);\n await writer.write(unparsedPacket);\n }\n util.printDebugError(e);\n }\n });\n if (done) {\n await writer.ready;\n await writer.close();\n return;\n }\n }\n } catch (e) {\n await writer.abort(e);\n }\n });\n\n // Wait until first few packets have been read\n const reader = stream.getReader(this.stream);\n while (true) {\n const { done, value } = await reader.read();\n if (!done) {\n this.push(value);\n } else {\n this.stream = null;\n }\n if (done || supportsStreaming(value.constructor.tag)) {\n break;\n }\n }\n reader.releaseLock();\n }\n\n /**\n * Creates a binary representation of openpgp objects contained within the\n * class instance.\n * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.\n */\n write() {\n const arr = [];\n\n for (let i = 0; i < this.length; i++) {\n const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;\n const packetbytes = this[i].write();\n if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {\n let buffer = [];\n let bufferLength = 0;\n const minLength = 512;\n arr.push(writeTag(tag));\n arr.push(stream.transform(packetbytes, value => {\n buffer.push(value);\n bufferLength += value.length;\n if (bufferLength >= minLength) {\n const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);\n const chunkSize = 2 ** powerOf2;\n const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));\n buffer = [bufferConcat.subarray(1 + chunkSize)];\n bufferLength = buffer[0].length;\n return bufferConcat.subarray(0, 1 + chunkSize);\n }\n }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));\n } else {\n if (util.isStream(packetbytes)) {\n let length = 0;\n arr.push(stream.transform(stream.clone(packetbytes), value => {\n length += value.length;\n }, () => writeHeader(tag, length)));\n } else {\n arr.push(writeHeader(tag, packetbytes.length));\n }\n arr.push(packetbytes);\n }\n }\n\n return util.concat(arr);\n }\n\n /**\n * Creates a new PacketList with all packets matching the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {PacketList}\n */\n filterByTag(...tags) {\n const filtered = new PacketList();\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(this[i].constructor.tag))) {\n filtered.push(this[i]);\n }\n }\n\n return filtered;\n }\n\n /**\n * Traverses packet list and returns first packet with matching tag\n * @param {module:enums.packet} tag - The packet tag\n * @returns {Packet|undefined}\n */\n findPacket(tag) {\n return this.find(packet => packet.constructor.tag === tag);\n }\n\n /**\n * Find indices of packets with the given tag(s)\n * @param {...module:enums.packet} tags - packet tags to look for\n * @returns {Integer[]} packet indices\n */\n indexOfTag(...tags) {\n const tagIndex = [];\n const that = this;\n\n const handle = tag => packetType => tag === packetType;\n\n for (let i = 0; i < this.length; i++) {\n if (tags.some(handle(that[i].constructor.tag))) {\n tagIndex.push(i);\n }\n }\n return tagIndex;\n }\n}\n\nexport default PacketList;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { Inflate, Deflate, Zlib, Unzlib } from 'fflate';\nimport * as stream from '@openpgp/web-stream-tools';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A Compressed Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Compressed Data Packet (Tag 8)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:\n * The Compressed Data packet contains compressed data. Typically,\n * this packet is found as the contents of an encrypted packet, or following\n * a Signature or One-Pass Signature packet, and contains a literal data packet.\n */\nclass CompressedDataPacket {\n static get tag() {\n return enums.packet.compressedData;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n /**\n * List of packets\n * @type {PacketList}\n */\n this.packets = null;\n /**\n * Compression algorithm\n * @type {enums.compression}\n */\n this.algorithm = config.preferredCompressionAlgorithm;\n\n /**\n * Compressed packet data\n * @type {Uint8Array | ReadableStream}\n */\n this.compressed = null;\n }\n\n /**\n * Parsing function for the packet.\n * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async read(bytes, config = defaultConfig) {\n await stream.parse(bytes, async reader => {\n\n // One octet that gives the algorithm used to compress the packet.\n this.algorithm = await reader.readByte();\n\n // Compressed data, which makes up the remainder of the packet.\n this.compressed = reader.remainder();\n\n await this.decompress(config);\n });\n }\n\n\n /**\n * Return the compressed packet.\n * @returns {Uint8Array | ReadableStream} Binary compressed packet.\n */\n write() {\n if (this.compressed === null) {\n this.compress();\n }\n\n return util.concat([new Uint8Array([this.algorithm]), this.compressed]);\n }\n\n\n /**\n * Decompression method for decompressing the compressed data\n * read by read_packet\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async decompress(config = defaultConfig) {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async\n if (!decompressionFn) {\n throw new Error(`${compressionName} decompression not supported`);\n }\n\n this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets, config);\n }\n\n /**\n * Compress the packet data (member decompressedData)\n */\n compress() {\n const compressionName = enums.read(enums.compression, this.algorithm);\n const compressionFn = compress_fns[compressionName];\n if (!compressionFn) {\n throw new Error(`${compressionName} compression not supported`);\n }\n\n this.compressed = compressionFn(this.packets.write());\n }\n}\n\nexport default CompressedDataPacket;\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n/**\n * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.\n * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator\n * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor\n * @returns {ReadableStream} compressed or decompressed data\n */\nfunction zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {\n return data => {\n if (!util.isStream(data) || stream.isArrayStream(data)) {\n return stream.fromAsync(() => stream.readToEnd(data).then(inputData => {\n return new Promise((resolve, reject) => {\n const zlibStream = new ZlibStreamedConstructor();\n zlibStream.ondata = processedData => {\n resolve(processedData);\n };\n try {\n zlibStream.push(inputData, true); // only one chunk to push\n } catch (err) {\n reject(err);\n }\n });\n }));\n }\n\n // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)\n if (compressionStreamInstantiator) {\n try {\n const compressorOrDecompressor = compressionStreamInstantiator();\n return data.pipeThrough(compressorOrDecompressor);\n } catch (err) {\n // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate.\n if (err.name !== 'TypeError') {\n throw err;\n }\n }\n }\n\n // JS fallback\n const inputReader = data.getReader();\n const zlibStream = new ZlibStreamedConstructor();\n\n return new ReadableStream({\n async start(controller) {\n zlibStream.ondata = async (value, isLast) => {\n controller.enqueue(value);\n if (isLast) {\n controller.close();\n }\n };\n\n while (true) {\n const { done, value } = await inputReader.read();\n if (done) {\n zlibStream.push(new Uint8Array(), true);\n return;\n } else if (value.length) {\n zlibStream.push(value);\n }\n }\n }\n });\n };\n}\n\nfunction bzip2Decompress() {\n return async function(data) {\n const { decode: bunzipDecode } = await import('@openpgp/seek-bzip');\n return stream.fromAsync(async () => bunzipDecode(await stream.readToEnd(data)));\n };\n}\n\n/**\n * Get Compression Stream API instatiators if the constructors are implemented.\n * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported\n * (supported formats cannot be determined in advance).\n * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat\n * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}\n */\nconst getCompressionStreamInstantiators = compressionFormat => ({\n compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),\n decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))\n});\n\nconst compress_fns = {\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)\n};\n\nconst decompress_fns = {\n uncompressed: data => data,\n zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),\n zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),\n bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import\n};\n\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\nimport { UnsupportedError } from './packet';\n\n// A SEIP packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:\n * The Symmetrically Encrypted Integrity Protected Data packet is\n * a variant of the Symmetrically Encrypted Data packet. It is a new feature\n * created for OpenPGP that addresses the problem of detecting a modification to\n * encrypted data. It is used in combination with a Modification Detection Code\n * packet.\n */\nclass SymEncryptedIntegrityProtectedDataPacket {\n static get tag() {\n return enums.packet.symEncryptedIntegrityProtectedData;\n }\n\n static fromObject({ version, aeadAlgorithm }) {\n if (version !== 1 && version !== 2) {\n throw new Error('Unsupported SEIPD version');\n }\n\n const seip = new SymEncryptedIntegrityProtectedDataPacket();\n seip.version = version;\n if (version === 2) {\n seip.aeadAlgorithm = aeadAlgorithm;\n }\n\n return seip;\n }\n\n constructor() {\n this.version = null;\n\n // The following 4 fields are for V2 only.\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = null;\n this.chunkSizeByte = null;\n this.salt = null;\n\n this.encrypted = null;\n this.packets = null;\n }\n\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n this.version = await reader.readByte();\n // - A one-octet version number with value 1 or 2.\n if (this.version !== 1 && this.version !== 2) {\n throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);\n }\n\n if (this.version === 2) {\n // - A one-octet cipher algorithm.\n this.cipherAlgorithm = await reader.readByte();\n // - A one-octet AEAD algorithm.\n this.aeadAlgorithm = await reader.readByte();\n // - A one-octet chunk size.\n this.chunkSizeByte = await reader.readByte();\n // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.\n this.salt = await reader.readBytes(32);\n }\n\n // For V1:\n // - Encrypted data, the output of the selected symmetric-key cipher\n // operating in Cipher Feedback mode with shift amount equal to the\n // block size of the cipher (CFB-n where n is the block size).\n // For V2:\n // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.\n // - A final, summary authentication tag for the AEAD mode.\n this.encrypted = reader.remainder();\n });\n }\n\n write() {\n if (this.version === 2) {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);\n }\n return util.concat([new Uint8Array([this.version]), this.encrypted]);\n }\n\n /**\n * Encrypt the payload in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on encryption failure\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n const { blockSize, keySize } = crypto.getCipherParams(sessionKeyAlgorithm);\n if (key.length !== keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let bytes = this.packets.write();\n if (stream.isArrayStream(bytes)) bytes = await stream.readToEnd(bytes);\n\n if (this.version === 2) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n this.salt = crypto.random.getRandomBytes(32);\n this.chunkSizeByte = config.aeadChunkSizeByte;\n this.encrypted = await runAEAD(this, 'encrypt', key, bytes);\n } else {\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet\n\n const tohash = util.concat([prefix, bytes, mdc]);\n const hash = await crypto.hash.sha1(stream.passiveClone(tohash));\n const plaintext = util.concat([tohash, hash]);\n\n this.encrypted = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);\n }\n return true;\n }\n\n /**\n * Decrypts the encrypted data contained in the packet.\n * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} on decryption failure\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // We check that the session key size matches the one expected by the symmetric algorithm.\n // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,\n // but we want to ensure that the input key isn't e.g. too short.\n // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,\n // which is instead included in the SEIPDv2 data.\n if (key.length !== crypto.getCipherParams(sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n\n let encrypted = stream.clone(this.encrypted);\n if (stream.isArrayStream(encrypted)) encrypted = await stream.readToEnd(encrypted);\n\n let packetbytes;\n if (this.version === 2) {\n if (this.cipherAlgorithm !== sessionKeyAlgorithm) {\n // sanity check\n throw new Error('Unexpected session key algorithm');\n }\n packetbytes = await runAEAD(this, 'decrypt', key, encrypted);\n } else {\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));\n\n // there must be a modification detection code packet as the\n // last packet and everything gets hashed except the hash itself\n const realHash = stream.slice(stream.passiveClone(decrypted), -20);\n const tohash = stream.slice(decrypted, 0, -20);\n const verifyHash = Promise.all([\n stream.readToEnd(await crypto.hash.sha1(stream.passiveClone(tohash))),\n stream.readToEnd(realHash)\n ]).then(([hash, mdc]) => {\n if (!util.equalsUint8Array(hash, mdc)) {\n throw new Error('Modification detected.');\n }\n return new Uint8Array();\n });\n const bytes = stream.slice(tohash, blockSize + 2); // Remove random prefix\n packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet\n packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);\n if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {\n packetbytes = await stream.readToEnd(packetbytes);\n }\n }\n\n this.packets = await PacketList.fromBinary(packetbytes, allowedPackets, config);\n return true;\n }\n}\n\nexport default SymEncryptedIntegrityProtectedDataPacket;\n\n/**\n * En/decrypt the payload.\n * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt\n * @param {Uint8Array} key - The session key used to en/decrypt the payload\n * @param {Uint8Array | ReadableStream} data - The data to en/decrypt\n * @returns {Promise>}\n * @async\n */\nexport async function runAEAD(packet, fn, key, data) {\n const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;\n const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)\n if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type');\n\n const mode = crypto.getAEADMode(packet.aeadAlgorithm);\n const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;\n const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;\n const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))\n const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;\n const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);\n const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);\n const adataTagArray = new Uint8Array(adataBuffer);\n const adataView = new DataView(adataBuffer);\n const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);\n adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);\n let chunkIndex = 0;\n let latestPromise = Promise.resolve();\n let cryptedBytes = 0;\n let queuedBytes = 0;\n let iv;\n let ivView;\n if (isSEIPDv2) {\n const { keySize } = crypto.getCipherParams(packet.cipherAlgorithm);\n const { ivLength } = mode;\n const info = new Uint8Array(adataBuffer, 0, 5);\n const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);\n key = derived.subarray(0, keySize);\n iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.\n iv.fill(0, iv.length - 8);\n ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n } else { // AEADEncryptedDataPacket\n iv = packet.iv;\n // ivView is unused in this case\n }\n const modeInstance = await mode(packet.cipherAlgorithm, key);\n return stream.transformPair(data, async (readable, writable) => {\n if (util.isStream(readable) !== 'array') {\n const buffer = new TransformStream({}, {\n highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),\n size: array => array.length\n });\n stream.pipe(buffer.readable, writable);\n writable = buffer.writable;\n }\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n while (true) {\n let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();\n const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);\n chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);\n let cryptedPromise;\n let done;\n let nonce;\n if (isSEIPDv2) { // SEIPD V2\n nonce = iv;\n } else { // AEADEncryptedDataPacket\n nonce = iv.slice();\n for (let i = 0; i < 8; i++) {\n nonce[iv.length - 8 + i] ^= chunkIndexArray[i];\n }\n }\n if (!chunkIndex || chunk.length) {\n reader.unshift(finalChunk);\n cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);\n cryptedPromise.catch(() => {});\n queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;\n } else {\n // After the last chunk, we either encrypt a final, empty\n // data chunk to get the final authentication tag or\n // validate that final authentication tag.\n adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...)\n cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);\n cryptedPromise.catch(() => {});\n queuedBytes += tagLengthIfEncrypting;\n done = true;\n }\n cryptedBytes += chunk.length - tagLengthIfDecrypting;\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {\n await writer.ready;\n await writer.write(crypted);\n queuedBytes -= crypted.length;\n }).catch(err => writer.abort(err));\n if (done || queuedBytes > writer.desiredSize) {\n await latestPromise; // Respect backpressure\n }\n if (!done) {\n if (isSEIPDv2) { // SEIPD V2\n ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...)\n } else { // AEADEncryptedDataPacket\n adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)\n }\n } else {\n await writer.close();\n break;\n }\n }\n } catch (e) {\n await writer.ready.catch(() => {});\n await writer.abort(e);\n }\n });\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError } from './packet';\nimport { runAEAD } from './sym_encrypted_integrity_protected_data';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// An AEAD-encrypted Data packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\nconst VERSION = 1; // A one-octet version number of the data packet.\n\n/**\n * Implementation of the Symmetrically Encrypted Authenticated Encryption with\n * Additional Data (AEAD) Protected Data Packet\n *\n * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:\n * AEAD Protected Data Packet\n */\nclass AEADEncryptedDataPacket {\n static get tag() {\n return enums.packet.aeadEncryptedData;\n }\n\n constructor() {\n this.version = VERSION;\n /** @type {enums.symmetric} */\n this.cipherAlgorithm = null;\n /** @type {enums.aead} */\n this.aeadAlgorithm = enums.aead.eax;\n this.chunkSizeByte = null;\n this.iv = null;\n this.encrypted = null;\n this.packets = null;\n }\n\n /**\n * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @param {Uint8Array | ReadableStream} bytes\n * @throws {Error} on parsing failure\n */\n async read(bytes) {\n await stream.parse(bytes, async reader => {\n const version = await reader.readByte();\n if (version !== VERSION) { // The only currently defined value is 1.\n throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);\n }\n this.cipherAlgorithm = await reader.readByte();\n this.aeadAlgorithm = await reader.readByte();\n this.chunkSizeByte = await reader.readByte();\n\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = await reader.readBytes(mode.ivLength);\n this.encrypted = reader.remainder();\n });\n }\n\n /**\n * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)\n * @returns {Uint8Array | ReadableStream} The encrypted payload.\n */\n write() {\n return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);\n }\n\n /**\n * Decrypt the encrypted payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.packets = await PacketList.fromBinary(\n await runAEAD(this, 'decrypt', key, stream.clone(this.encrypted)),\n allowedPackets,\n config\n );\n }\n\n /**\n * Encrypt the packet payload.\n * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm\n * @param {Uint8Array} key - The session key used to encrypt the payload\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n this.cipherAlgorithm = sessionKeyAlgorithm;\n\n const { ivLength } = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(ivLength); // generate new random IV\n this.chunkSizeByte = config.aeadChunkSizeByte;\n const data = this.packets.write();\n this.encrypted = await runAEAD(this, 'encrypt', key, data);\n }\n}\n\nexport default AEADEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Public-Key Encrypted Session Key Packets (Tag 1)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:\n * A Public-Key Encrypted Session Key packet holds the session key\n * used to encrypt a message. Zero or more Public-Key Encrypted Session Key\n * packets and/or Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data Packet, which holds an encrypted message. The\n * message is encrypted with the session key, and the session key is itself\n * encrypted and stored in the Encrypted Session Key packet(s). The\n * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted\n * Session Key packet for each OpenPGP key to which the message is encrypted.\n * The recipient of the message finds a session key that is encrypted to their\n * public key, decrypts the session key, and then uses the session key to\n * decrypt the message.\n */\nclass PublicKeyEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.publicKeyEncryptedSessionKey;\n }\n\n constructor() {\n this.version = null;\n\n // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`\n this.publicKeyID = new KeyID();\n\n // For version 6:\n this.publicKeyVersion = null;\n this.publicKeyFingerprint = null;\n\n // For all versions:\n this.publicKeyAlgorithm = null;\n\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n\n /** @type {Object} */\n this.encrypted = {};\n }\n\n static fromObject({\n version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm\n }) {\n const pkesk = new PublicKeyEncryptedSessionKeyPacket();\n\n if (version !== 3 && version !== 6) {\n throw new Error('Unsupported PKESK version');\n }\n\n pkesk.version = version;\n\n if (version === 6) {\n pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;\n pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();\n }\n\n pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();\n pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;\n pkesk.sessionKey = sessionKey;\n pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;\n\n return pkesk;\n }\n\n /**\n * Parsing function for a publickey encrypted session key packet (tag 1).\n *\n * @param {Uint8Array} bytes - Payload of a tag 1 packet\n */\n read(bytes) {\n let offset = 0;\n this.version = bytes[offset++];\n if (this.version !== 3 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);\n }\n if (this.version === 6) {\n // A one-octet size of the following two fields:\n // - A one octet key version number.\n // - The fingerprint of the public key or subkey to which the session key is encrypted.\n // The size may also be zero.\n const versionAndFingerprintLength = bytes[offset++];\n if (versionAndFingerprintLength) {\n this.publicKeyVersion = bytes[offset++];\n const fingerprintLength = versionAndFingerprintLength - 1;\n this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength;\n if (this.publicKeyVersion >= 5) {\n // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint);\n } else {\n // For v4 The Key ID is the low-order 64 bits of the fingerprint.\n this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));\n }\n } else {\n // The size may also be zero, and the key version and\n // fingerprint omitted for an \"anonymous recipient\"\n this.publicKeyID = KeyID.wildcard();\n }\n } else {\n offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));\n }\n this.publicKeyAlgorithm = bytes[offset++];\n this.encrypted = crypto.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));\n if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {\n if (this.version === 3) {\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);\n } else if (this.encrypted.C.algorithm !== null) {\n throw new Error('Unexpected cleartext symmetric algorithm');\n }\n }\n }\n\n /**\n * Create a binary representation of a tag 1 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const arr = [\n new Uint8Array([this.version])\n ];\n\n if (this.version === 6) {\n if (this.publicKeyFingerprint !== null) {\n arr.push(new Uint8Array([\n this.publicKeyFingerprint.length + 1,\n this.publicKeyVersion]\n ));\n arr.push(this.publicKeyFingerprint);\n } else {\n arr.push(new Uint8Array([0]));\n }\n } else {\n arr.push(this.publicKeyID.write());\n }\n\n arr.push(\n new Uint8Array([this.publicKeyAlgorithm]),\n crypto.serializeParams(this.publicKeyAlgorithm, this.encrypted)\n );\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Encrypt session key packet\n * @param {PublicKeyPacket} key - Public key\n * @throws {Error} if encryption failed\n * @async\n */\n async encrypt(key) {\n const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);\n // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a\n // v6 PKESK packet, as it is included in the v2 SEIPD packet.\n const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);\n this.encrypted = await crypto.publicKeyEncrypt(\n algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);\n }\n\n /**\n * Decrypts the session key (only for public key encrypted session key packets (tag 1)\n * @param {SecretKeyPacket} key - decrypted private key\n * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.\n * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }\n * @throws {Error} if decryption failed, unless `randomSessionKey` is given\n * @async\n */\n async decrypt(key, randomSessionKey) {\n // check that session key algo matches the secret key algo\n if (this.publicKeyAlgorithm !== key.algorithm) {\n throw new Error('Decryption error');\n }\n\n const randomPayload = randomSessionKey ?\n encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :\n null;\n const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();\n const decryptedData = await crypto.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);\n\n const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);\n\n if (this.version === 3) {\n // v3 Montgomery curves have cleartext cipher algo\n const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;\n this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;\n\n if (sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n }\n this.sessionKey = sessionKey;\n }\n}\n\nexport default PublicKeyEncryptedSessionKeyPacket;\n\n\nfunction encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n // add checksum\n return util.concatUint8Array([\n new Uint8Array(version === 6 ? [] : [cipherAlgo]),\n sessionKeyData,\n util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))\n ]);\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return sessionKeyData;\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n\n\nfunction decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {\n switch (keyAlgo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh: {\n // verify checksum in constant time\n const result = decryptedData.subarray(0, decryptedData.length - 2);\n const checksum = decryptedData.subarray(decryptedData.length - 2);\n const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));\n const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];\n const decryptedSessionKey = version === 6 ?\n { sessionKeyAlgorithm: null, sessionKey: result } :\n { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };\n if (randomSessionKey) {\n // We must not leak info about the validity of the decrypted checksum or cipher algo.\n // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.\n const isValidPayload = isValidChecksum &\n decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &\n decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;\n return {\n sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),\n sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(\n isValidPayload,\n decryptedSessionKey.sessionKeyAlgorithm,\n randomSessionKey.sessionKeyAlgorithm\n )\n };\n } else {\n const isValidPayload = isValidChecksum && (\n version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));\n if (isValidPayload) {\n return decryptedSessionKey;\n } else {\n throw new Error('Decryption error');\n }\n }\n }\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n return {\n sessionKeyAlgorithm: null,\n sessionKey: decryptedData\n };\n default:\n throw new Error('Unsupported public key algorithm');\n }\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport computeHKDF from '../crypto/hkdf';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Symmetric-Key Encrypted Session Key Packets (Tag 3)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:\n * The Symmetric-Key Encrypted Session Key packet holds the\n * symmetric-key encryption of a session key used to encrypt a message.\n * Zero or more Public-Key Encrypted Session Key packets and/or\n * Symmetric-Key Encrypted Session Key packets may precede a\n * Symmetrically Encrypted Data packet that holds an encrypted message.\n * The message is encrypted with a session key, and the session key is\n * itself encrypted and stored in the Encrypted Session Key packet or\n * the Symmetric-Key Encrypted Session Key packet.\n */\nclass SymEncryptedSessionKeyPacket {\n static get tag() {\n return enums.packet.symEncryptedSessionKey;\n }\n\n /**\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(config = defaultConfig) {\n this.version = config.aeadProtect ? 6 : 4;\n this.sessionKey = null;\n /**\n * Algorithm to encrypt the session key with\n * @type {enums.symmetric}\n */\n this.sessionKeyEncryptionAlgorithm = null;\n /**\n * Algorithm to encrypt the message with\n * @type {enums.symmetric}\n */\n this.sessionKeyAlgorithm = null;\n /**\n * AEAD mode to encrypt the session key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);\n this.encrypted = null;\n this.s2k = null;\n this.iv = null;\n }\n\n /**\n * Parsing function for a symmetric encrypted session key packet (tag 3).\n *\n * @param {Uint8Array} bytes - Payload of a tag 3 packet\n */\n read(bytes) {\n let offset = 0;\n\n // A one-octet version number with value 4, 5 or 6.\n this.version = bytes[offset++];\n if (this.version !== 4 && this.version !== 5 && this.version !== 6) {\n throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);\n }\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following 5 fields.\n offset++;\n }\n\n // A one-octet number describing the symmetric algorithm used.\n const algo = bytes[offset++];\n\n if (this.version >= 5) {\n // A one-octet AEAD algorithm.\n this.aeadAlgorithm = bytes[offset++];\n\n if (this.version === 6) {\n // A one-octet scalar octet count of the following field.\n offset++;\n }\n }\n\n // A string-to-key (S2K) specifier, length as defined above.\n const s2kType = bytes[offset++];\n this.s2k = newS2KFromType(s2kType);\n offset += this.s2k.read(bytes.subarray(offset, bytes.length));\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n\n // A starting initialization vector of size specified by the AEAD\n // algorithm.\n this.iv = bytes.subarray(offset, offset += mode.ivLength);\n }\n\n // The encrypted session key itself, which is decrypted with the\n // string-to-key object. This is optional in version 4.\n if (this.version >= 5 || offset < bytes.length) {\n this.encrypted = bytes.subarray(offset, bytes.length);\n this.sessionKeyEncryptionAlgorithm = algo;\n } else {\n this.sessionKeyAlgorithm = algo;\n }\n }\n\n /**\n * Create a binary representation of a tag 3 packet\n *\n * @returns {Uint8Array} The Uint8Array representation.\n */\n write() {\n const algo = this.encrypted === null ?\n this.sessionKeyAlgorithm :\n this.sessionKeyEncryptionAlgorithm;\n\n let bytes;\n\n const s2k = this.s2k.write();\n if (this.version === 6) {\n const s2kLen = s2k.length;\n const fieldsLen = 3 + s2kLen + this.iv.length;\n bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);\n } else if (this.version === 5) {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);\n } else {\n bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);\n\n if (this.encrypted !== null) {\n bytes = util.concatUint8Array([bytes, this.encrypted]);\n }\n }\n\n return bytes;\n }\n\n /**\n * Decrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);\n } else if (this.encrypted !== null) {\n const decrypted = await crypto.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));\n\n this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);\n this.sessionKey = decrypted.subarray(1, decrypted.length);\n if (this.sessionKey.length !== crypto.getCipherParams(this.sessionKeyAlgorithm).keySize) {\n throw new Error('Unexpected session key size');\n }\n } else {\n // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo\n this.sessionKey = key;\n }\n }\n\n /**\n * Encrypts the session key with the given passphrase\n * @param {String} passphrase - The passphrase in string form\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n const algo = this.sessionKeyEncryptionAlgorithm !== null ?\n this.sessionKeyEncryptionAlgorithm :\n this.sessionKeyAlgorithm;\n\n this.sessionKeyEncryptionAlgorithm = algo;\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n\n const { blockSize, keySize } = crypto.getCipherParams(algo);\n const key = await this.s2k.produceKey(passphrase, keySize);\n\n if (this.sessionKey === null) {\n this.sessionKey = crypto.generateSessionKey(this.sessionKeyAlgorithm);\n }\n\n if (this.version >= 5) {\n const mode = crypto.getAEADMode(this.aeadAlgorithm);\n this.iv = crypto.random.getRandomBytes(mode.ivLength); // generate new random IV\n const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);\n const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;\n const modeInstance = await mode(algo, encryptionKey);\n this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);\n } else {\n const toEncrypt = util.concatUint8Array([\n new Uint8Array([this.sessionKeyAlgorithm]),\n this.sessionKey\n ]);\n this.encrypted = await crypto.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config);\n }\n }\n}\n\nexport default SymEncryptedSessionKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport KeyID from '../type/keyid';\nimport defaultConfig from '../config';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Key Material Packet (Tag 5,6,7,14)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:\n * A key material packet contains all the information about a public or\n * private key. There are four variants of this packet type, and two\n * major versions.\n *\n * A Public-Key packet starts a series of packets that forms an OpenPGP\n * key (sometimes called an OpenPGP certificate).\n */\nclass PublicKeyPacket {\n static get tag() {\n return enums.packet.publicKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n /**\n * Packet version\n * @type {Integer}\n */\n this.version = config.v6Keys ? 6 : 4;\n /**\n * Key creation date.\n * @type {Date}\n */\n this.created = util.normalizeDate(date);\n /**\n * Public key algorithm.\n * @type {enums.publicKey}\n */\n this.algorithm = null;\n /**\n * Algorithm specific public params\n * @type {Object}\n */\n this.publicParams = null;\n /**\n * Time until expiration in days (V3 only)\n * @type {Integer}\n */\n this.expirationTimeV3 = 0;\n /**\n * Fingerprint bytes\n * @type {Uint8Array}\n */\n this.fingerprint = null;\n /**\n * KeyID\n * @type {module:type/keyid~KeyID}\n */\n this.keyID = null;\n }\n\n /**\n * Create a PublicKeyPacket from a SecretKeyPacket\n * @param {SecretKeyPacket} secretKeyPacket - key packet to convert\n * @returns {PublicKeyPacket} public key packet\n * @static\n */\n static fromSecretKeyPacket(secretKeyPacket) {\n const keyPacket = new PublicKeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n\n /**\n * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}\n * @param {Uint8Array} bytes - Input array to read the packet from\n * @returns {Object} This object with attributes set by the parser\n * @async\n */\n async read(bytes, config = defaultConfig) {\n let pos = 0;\n // A one-octet version number (4, 5 or 6).\n this.version = bytes[pos++];\n if (this.version === 5 && !config.enableParsingV5Entities) {\n throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');\n }\n\n if (this.version === 4 || this.version === 5 || this.version === 6) {\n // - A four-octet number denoting the time that the key was created.\n this.created = util.readDate(bytes.subarray(pos, pos + 4));\n pos += 4;\n\n // - A one-octet number denoting the public-key algorithm of this key.\n this.algorithm = bytes[pos++];\n\n if (this.version >= 5) {\n // - A four-octet scalar octet count for the following key material.\n pos += 4;\n }\n\n // - A series of values comprising the key material.\n const { read, publicParams } = crypto.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (\n this.version === 6 &&\n publicParams.oid && (\n publicParams.oid.getName() === enums.curve.curve25519Legacy ||\n publicParams.oid.getName() === enums.curve.ed25519Legacy\n )\n ) {\n throw new Error('Legacy curve25519 cannot be used with v6 keys');\n }\n this.publicParams = publicParams;\n pos += read;\n\n // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor\n await this.computeFingerprintAndKeyID();\n return pos;\n }\n throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);\n }\n\n /**\n * Creates an OpenPGP public key packet for the given key.\n * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.\n */\n write() {\n const arr = [];\n // Version\n arr.push(new Uint8Array([this.version]));\n arr.push(util.writeDate(this.created));\n // A one-octet number denoting the public-key algorithm of this key\n arr.push(new Uint8Array([this.algorithm]));\n\n const params = crypto.serializeParams(this.algorithm, this.publicParams);\n if (this.version >= 5) {\n // A four-octet scalar octet count for the following key material\n arr.push(util.writeNumber(params.length, 4));\n }\n // Algorithm-specific params\n arr.push(params);\n return util.concatUint8Array(arr);\n }\n\n /**\n * Write packet in order to be hashed; either for a signature or a fingerprint\n * @param {Integer} version - target version of signature or key\n */\n writeForHash(version) {\n const bytes = this.writePublicKey();\n\n const versionOctet = 0x95 + version;\n const lengthOctets = version >= 5 ? 4 : 2;\n return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form. Returns null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return null;\n }\n\n /**\n * Returns the creation time of the key\n * @returns {Date}\n */\n getCreationTime() {\n return this.created;\n }\n\n /**\n * Return the key ID of the key\n * @returns {module:type/keyid~KeyID} The 8-byte key ID\n */\n getKeyID() {\n return this.keyID;\n }\n\n /**\n * Computes and set the key ID and fingerprint of the key\n * @async\n */\n async computeFingerprintAndKeyID() {\n await this.computeFingerprint();\n this.keyID = new KeyID();\n\n if (this.version >= 5) {\n this.keyID.read(this.fingerprint.subarray(0, 8));\n } else if (this.version === 4) {\n this.keyID.read(this.fingerprint.subarray(12, 20));\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Computes and set the fingerprint of the key\n */\n async computeFingerprint() {\n const toHash = this.writeForHash(this.version);\n\n if (this.version >= 5) {\n this.fingerprint = await crypto.hash.sha256(toHash);\n } else if (this.version === 4) {\n this.fingerprint = await crypto.hash.sha1(toHash);\n } else {\n throw new Error('Unsupported key version');\n }\n }\n\n /**\n * Returns the fingerprint of the key, as an array of bytes\n * @returns {Uint8Array} A Uint8Array containing the fingerprint\n */\n getFingerprintBytes() {\n return this.fingerprint;\n }\n\n /**\n * Calculates and returns the fingerprint of the key, as a string\n * @returns {String} A string containing the fingerprint in lowercase hex\n */\n getFingerprint() {\n return util.uint8ArrayToHex(this.getFingerprintBytes());\n }\n\n /**\n * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint\n * @returns {Boolean} Whether the two keys have the same version and public key data.\n */\n hasSameFingerprintAs(other) {\n return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());\n }\n\n /**\n * Returns algorithm information\n * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.\n */\n getAlgorithmInfo() {\n const result = {};\n result.algorithm = enums.read(enums.publicKey, this.algorithm);\n // RSA, DSA or ElGamal public modulo\n const modulo = this.publicParams.n || this.publicParams.p;\n if (modulo) {\n result.bits = util.uint8ArrayBitLength(modulo);\n } else if (this.publicParams.oid) {\n result.curve = this.publicParams.oid.getName();\n }\n return result;\n }\n}\n\n/**\n * Alias of read()\n * @see PublicKeyPacket#read\n */\nPublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;\n\n/**\n * Alias of write()\n * @see PublicKeyPacket#write\n */\nPublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;\n\nexport default PublicKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nimport LiteralDataPacket from './literal_data';\nimport CompressedDataPacket from './compressed_data';\nimport OnePassSignaturePacket from './one_pass_signature';\nimport SignaturePacket from './signature';\nimport PacketList from './packetlist';\n\n// A SE packet can contain the following packet types\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n\n/**\n * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:\n * The Symmetrically Encrypted Data packet contains data encrypted with a\n * symmetric-key algorithm. When it has been decrypted, it contains other\n * packets (usually a literal data packet or compressed data packet, but in\n * theory other Symmetrically Encrypted Data packets or sequences of packets\n * that form whole OpenPGP messages).\n */\nclass SymmetricallyEncryptedDataPacket {\n static get tag() {\n return enums.packet.symmetricallyEncryptedData;\n }\n\n constructor() {\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Decrypted packets contained within.\n * @type {PacketList}\n */\n this.packets = null;\n }\n\n read(bytes) {\n this.encrypted = bytes;\n }\n\n write() {\n return this.encrypted;\n }\n\n /**\n * Decrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n\n * @throws {Error} if decryption was not successful\n * @async\n */\n async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error\n if (!config.allowUnauthenticatedMessages) {\n throw new Error('Message is not authenticated.');\n }\n\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n const encrypted = await stream.readToEnd(stream.clone(this.encrypted));\n const decrypted = await crypto.mode.cfb.decrypt(sessionKeyAlgorithm, key,\n encrypted.subarray(blockSize + 2),\n encrypted.subarray(2, blockSize + 2)\n );\n\n this.packets = await PacketList.fromBinary(decrypted, allowedPackets, config);\n }\n\n /**\n * Encrypt the symmetrically-encrypted packet data\n * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.\n * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use\n * @param {Uint8Array} key - The key of cipher blocksize length to be used\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {\n const data = this.packets.write();\n const { blockSize } = crypto.getCipherParams(sessionKeyAlgorithm);\n\n const prefix = await crypto.getPrefixRandom(sessionKeyAlgorithm);\n const FRE = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);\n const ciphertext = await crypto.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);\n this.encrypted = util.concat([FRE, ciphertext]);\n }\n}\n\nexport default SymmetricallyEncryptedDataPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\n\n/**\n * Implementation of the strange \"Marker packet\" (Tag 10)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:\n * An experimental version of PGP used this packet as the Literal\n * packet, but no released version of PGP generated Literal packets with this\n * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as\n * the Marker packet.\n *\n * The body of this packet consists of:\n * The three octets 0x50, 0x47, 0x50 (which spell \"PGP\" in UTF-8).\n *\n * Such a packet MUST be ignored when received. It may be placed at the\n * beginning of a message that uses features not available in PGP\n * version 2.6 in order to cause that version to report that newer\n * software is necessary to process the message.\n */\nclass MarkerPacket {\n static get tag() {\n return enums.packet.marker;\n }\n\n /**\n * Parsing function for a marker data packet (tag 10).\n * @param {Uint8Array} bytes - Payload of a tag 10 packet\n * @returns {Boolean} whether the packet payload contains \"PGP\"\n */\n read(bytes) {\n if (bytes[0] === 0x50 && // P\n bytes[1] === 0x47 && // G\n bytes[2] === 0x50) { // P\n return true;\n }\n return false;\n }\n\n write() {\n return new Uint8Array([0x50, 0x47, 0x50]);\n }\n}\n\nexport default MarkerPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport enums from '../enums';\n\n/**\n * A Public-Subkey packet (tag 14) has exactly the same format as a\n * Public-Key packet, but denotes a subkey. One or more subkeys may be\n * associated with a top-level key. By convention, the top-level key\n * provides signature services, and the subkeys provide encryption\n * services.\n * @extends PublicKeyPacket\n */\nclass PublicSubkeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.publicSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(date, config) {\n super(date, config);\n }\n\n /**\n * Create a PublicSubkeyPacket from a SecretSubkeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert\n * @returns {SecretSubkeyPacket} public key packet\n * @static\n */\n static fromSecretSubkeyPacket(secretSubkeyPacket) {\n const keyPacket = new PublicSubkeyPacket();\n const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;\n keyPacket.version = version;\n keyPacket.created = created;\n keyPacket.algorithm = algorithm;\n keyPacket.publicParams = publicParams;\n keyPacket.keyID = keyID;\n keyPacket.fingerprint = fingerprint;\n return keyPacket;\n }\n}\n\nexport default PublicSubkeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { readSimpleLength, writeSimpleLength } from './packet';\nimport enums from '../enums';\nimport util from '../util';\n\n/**\n * Implementation of the User Attribute Packet (Tag 17)\n *\n * The User Attribute packet is a variation of the User ID packet. It\n * is capable of storing more types of data than the User ID packet,\n * which is limited to text. Like the User ID packet, a User Attribute\n * packet may be certified by the key owner (\"self-signed\") or any other\n * key owner who cares to certify it. Except as noted, a User Attribute\n * packet may be used anywhere that a User ID packet may be used.\n *\n * While User Attribute packets are not a required part of the OpenPGP\n * standard, implementations SHOULD provide at least enough\n * compatibility to properly handle a certification signature on the\n * User Attribute packet. A simple way to do this is by treating the\n * User Attribute packet as a User ID packet with opaque contents, but\n * an implementation may use any method desired.\n */\nclass UserAttributePacket {\n static get tag() {\n return enums.packet.userAttribute;\n }\n\n constructor() {\n this.attributes = [];\n }\n\n /**\n * parsing function for a user attribute packet (tag 17).\n * @param {Uint8Array} input - Payload of a tag 17 packet\n */\n read(bytes) {\n let i = 0;\n while (i < bytes.length) {\n const len = readSimpleLength(bytes.subarray(i, bytes.length));\n i += len.offset;\n\n this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));\n i += len.len;\n }\n }\n\n /**\n * Creates a binary representation of the user attribute packet\n * @returns {Uint8Array} String representation.\n */\n write() {\n const arr = [];\n for (let i = 0; i < this.attributes.length; i++) {\n arr.push(writeSimpleLength(this.attributes[i].length));\n arr.push(util.stringToUint8Array(this.attributes[i]));\n }\n return util.concatUint8Array(arr);\n }\n\n /**\n * Compare for equality\n * @param {UserAttributePacket} usrAttr\n * @returns {Boolean} True if equal.\n */\n equals(usrAttr) {\n if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {\n return false;\n }\n return this.attributes.every(function(attr, index) {\n return attr === usrAttr.attributes[index];\n });\n }\n}\n\nexport default UserAttributePacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport PublicKeyPacket from './public_key';\nimport { newS2KFromConfig, newS2KFromType } from '../type/s2k';\nimport crypto from '../crypto';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { UnsupportedError, writeTag } from './packet';\nimport computeHKDF from '../crypto/hkdf';\n\n/**\n * A Secret-Key packet contains all the information that is found in a\n * Public-Key packet, including the public-key material, but also\n * includes the secret-key material after all the public-key fields.\n * @extends PublicKeyPacket\n */\nclass SecretKeyPacket extends PublicKeyPacket {\n static get tag() {\n return enums.packet.secretKey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n /**\n * Secret-key data\n */\n this.keyMaterial = null;\n /**\n * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n /**\n * S2K usage\n * @type {enums.symmetric}\n */\n this.s2kUsage = 0;\n /**\n * S2K object\n * @type {type/s2k}\n */\n this.s2k = null;\n /**\n * Symmetric algorithm to encrypt the key with\n * @type {enums.symmetric}\n */\n this.symmetric = null;\n /**\n * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)\n * @type {enums.aead}\n */\n this.aead = null;\n /**\n * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis\n * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).\n * This value is only relevant to know how to decrypt the key:\n * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.\n * @type {Boolean}\n * @private\n */\n this.isLegacyAEAD = null;\n /**\n * Decrypted private parameters, referenced by name\n * @type {Object}\n */\n this.privateParams = null;\n /**\n * `true` for keys whose integrity is already confirmed, based on\n * the AEAD encryption mechanism\n * @type {Boolean}\n * @private\n */\n this.usedModernAEAD = null;\n }\n\n // 5.5.3. Secret-Key Packet Formats\n\n /**\n * Internal parser for private keys as specified in\n * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}\n * @param {Uint8Array} bytes - Input string to read the packet from\n * @async\n */\n async read(bytes, config = defaultConfig) {\n // - A Public-Key or Public-Subkey packet, as described above.\n let i = await this.readPublicKey(bytes, config);\n const startOfSecretKeyData = i;\n\n // - One octet indicating string-to-key usage conventions. Zero\n // indicates that the secret-key data is not encrypted. 255 or 254\n // indicates that a string-to-key specifier is being given. Any\n // other value is a symmetric-key encryption algorithm identifier.\n this.s2kUsage = bytes[i++];\n\n // - Only for a version 5 packet, a one-octet scalar octet count of\n // the next 4 optional fields.\n if (this.version === 5) {\n i++;\n }\n\n // - Only for a version 6 packet where the secret key material is\n // encrypted (that is, where the previous octet is not zero), a one-\n // octet scalar octet count of the cumulative length of all the\n // following optional string-to-key parameter fields.\n if (this.version === 6 && this.s2kUsage) {\n i++;\n }\n\n try {\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one-octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n this.symmetric = bytes[i++];\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n this.aead = bytes[i++];\n }\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n i++;\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n const s2kType = bytes[i++];\n this.s2k = newS2KFromType(s2kType);\n i += this.s2k.read(bytes.subarray(i, bytes.length));\n\n if (this.s2k.type === 'gnu-dummy') {\n return;\n }\n } else if (this.s2kUsage) {\n this.symmetric = this.s2kUsage;\n }\n\n\n if (this.s2kUsage) {\n // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).\n // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).\n // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always\n // fail if the key was parsed according to the wrong format, since the keys are processed differently.\n // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.\n this.isLegacyAEAD = this.s2kUsage === 253 && (\n this.version === 5 || (this.version === 4 && config.parseAEADEncryptedV4KeysAsLegacy));\n // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)\n // of the same length as the cipher's block size.\n // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the\n // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.\n // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero\n if (this.s2kUsage !== 253 || this.isLegacyAEAD) {\n this.iv = bytes.subarray(\n i,\n i + crypto.getCipherParams(this.symmetric).blockSize\n );\n this.usedModernAEAD = false;\n } else {\n // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),\n // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which\n // is used as the nonce for the AEAD algorithm.\n this.iv = bytes.subarray(\n i,\n i + crypto.getAEADMode(this.aead).ivLength\n );\n // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.\n this.usedModernAEAD = true;\n }\n\n i += this.iv.length;\n }\n } catch (e) {\n // if the s2k is unsupported, we still want to support encrypting and verifying with the given key\n if (!this.s2kUsage) throw e; // always throw for decrypted keys\n this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);\n this.isEncrypted = true;\n }\n\n // - Only for a version 5 packet, a four-octet scalar octet count for\n // the following key material.\n if (this.version === 5) {\n i += 4;\n }\n\n // - Plain or encrypted multiprecision integers comprising the secret\n // key data. These algorithm-specific fields are as described\n // below.\n this.keyMaterial = bytes.subarray(i);\n this.isEncrypted = !!this.s2kUsage;\n\n if (!this.isEncrypted) {\n let cleartext;\n if (this.version === 6) {\n cleartext = this.keyMaterial;\n } else {\n cleartext = this.keyMaterial.subarray(0, -2);\n if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {\n throw new Error('Key checksum mismatch');\n }\n }\n try {\n const { read, privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n if (read < cleartext.length) {\n throw new Error('Error reading MPIs');\n }\n this.privateParams = privateParams;\n } catch (err) {\n if (err instanceof UnsupportedError) throw err;\n // avoid throwing potentially sensitive errors\n throw new Error('Error reading MPIs');\n }\n }\n }\n\n /**\n * Creates an OpenPGP key packet for the given key.\n * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.\n */\n write() {\n const serializedPublicKey = this.writePublicKey();\n if (this.unparseableKeyMaterial) {\n return util.concatUint8Array([\n serializedPublicKey,\n this.unparseableKeyMaterial\n ]);\n }\n\n const arr = [serializedPublicKey];\n arr.push(new Uint8Array([this.s2kUsage]));\n\n const optionalFieldsArr = [];\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // one- octet symmetric encryption algorithm.\n if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {\n optionalFieldsArr.push(this.symmetric);\n\n // - [Optional] If string-to-key usage octet was 253, a one-octet\n // AEAD algorithm.\n if (this.s2kUsage === 253) {\n optionalFieldsArr.push(this.aead);\n }\n\n const s2k = this.s2k.write();\n\n // - [Optional] Only for a version 6 packet, and if string-to-key usage\n // octet was 255, 254, or 253, an one-octet count of the following field.\n if (this.version === 6) {\n optionalFieldsArr.push(s2k.length);\n }\n\n // - [Optional] If string-to-key usage octet was 255, 254, or 253, a\n // string-to-key specifier. The length of the string-to-key\n // specifier is implied by its type, as described above.\n optionalFieldsArr.push(...s2k);\n }\n\n // - [Optional] If secret data is encrypted (string-to-key usage octet\n // not zero), an Initial Vector (IV) of the same length as the\n // cipher's block size.\n if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {\n optionalFieldsArr.push(...this.iv);\n }\n\n if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {\n arr.push(new Uint8Array([optionalFieldsArr.length]));\n }\n arr.push(new Uint8Array(optionalFieldsArr));\n\n if (!this.isDummy()) {\n if (!this.s2kUsage) {\n this.keyMaterial = crypto.serializeParams(this.algorithm, this.privateParams);\n }\n\n if (this.version === 5) {\n arr.push(util.writeNumber(this.keyMaterial.length, 4));\n }\n arr.push(this.keyMaterial);\n\n if (!this.s2kUsage && this.version !== 6) {\n arr.push(util.writeChecksum(this.keyMaterial));\n }\n }\n\n return util.concatUint8Array(arr);\n }\n\n /**\n * Check whether secret-key data is available in decrypted form.\n * Returns false for gnu-dummy keys and null for public keys.\n * @returns {Boolean|null}\n */\n isDecrypted() {\n return this.isEncrypted === false;\n }\n\n /**\n * Check whether the key includes secret key material.\n * Some secret keys do not include it, and can thus only be used\n * for public-key operations (encryption and verification).\n * Such keys are:\n * - GNU-dummy keys, where the secret material has been stripped away\n * - encrypted keys with unsupported S2K or cipher\n */\n isMissingSecretKeyMaterial() {\n return this.unparseableKeyMaterial !== undefined || this.isDummy();\n }\n\n /**\n * Check whether this is a gnu-dummy key\n * @returns {Boolean}\n */\n isDummy() {\n return !!(this.s2k && this.s2k.type === 'gnu-dummy');\n }\n\n /**\n * Remove private key material, converting the key to a dummy one.\n * The resulting key cannot be used for signing/decrypting but can still verify signatures.\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n makeDummy(config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n if (this.isDecrypted()) {\n this.clearPrivateParams();\n }\n delete this.unparseableKeyMaterial;\n this.isEncrypted = null;\n this.keyMaterial = null;\n this.s2k = newS2KFromType(enums.s2k.gnu, config);\n this.s2k.algorithm = 0;\n this.s2k.c = 0;\n this.s2k.type = 'gnu-dummy';\n this.s2kUsage = 254;\n this.symmetric = enums.symmetric.aes256;\n this.isLegacyAEAD = null;\n this.usedModernAEAD = null;\n }\n\n /**\n * Encrypt the payload. By default, we use aes256 and iterated, salted string\n * to key specifier. If the key is in a decrypted state (isEncrypted === false)\n * and the passphrase is empty or undefined, the key will be set as not encrypted.\n * This can be used to remove passphrase protection after calling decrypt().\n * @param {String} passphrase\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if encryption was not successful\n * @async\n */\n async encrypt(passphrase, config = defaultConfig) {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key packet is already encrypted');\n }\n\n if (!passphrase) {\n throw new Error('A non-empty passphrase is required for key encryption.');\n }\n\n this.s2k = newS2KFromConfig(config);\n this.s2k.generateSalt();\n const cleartext = crypto.serializeParams(this.algorithm, this.privateParams);\n this.symmetric = enums.symmetric.aes256;\n\n const { blockSize } = crypto.getCipherParams(this.symmetric);\n\n if (config.aeadProtect) {\n this.s2kUsage = 253;\n this.aead = config.preferredAEADAlgorithm;\n const mode = crypto.getAEADMode(this.aead);\n this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.\n this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material\n\n const serializedPacketTag = writeTag(this.constructor.tag);\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n\n const modeInstance = await mode(this.symmetric, key);\n this.iv = this.isLegacyAEAD ? crypto.random.getRandomBytes(blockSize) : crypto.random.getRandomBytes(mode.ivLength);\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n\n this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);\n } else {\n this.s2kUsage = 254;\n this.usedModernAEAD = false;\n const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric);\n this.iv = crypto.random.getRandomBytes(blockSize);\n this.keyMaterial = await crypto.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([\n cleartext,\n await crypto.hash.sha1(cleartext, config)\n ]), this.iv, config);\n }\n }\n\n /**\n * Decrypts the private key params which are needed to use the key.\n * Successful decryption does not imply key integrity, call validate() to confirm that.\n * {@link SecretKeyPacket.isDecrypted} should be false, as\n * otherwise calls to this function will throw an error.\n * @param {String} passphrase - The passphrase for this private key as string\n * @throws {Error} if the key is already decrypted, or if decryption was not successful\n * @async\n */\n async decrypt(passphrase) {\n if (this.isDummy()) {\n return false;\n }\n\n if (this.unparseableKeyMaterial) {\n throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');\n }\n\n if (this.isDecrypted()) {\n throw new Error('Key packet is already decrypted.');\n }\n\n let key;\n const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only\n if (this.s2kUsage === 254 || this.s2kUsage === 253) {\n key = await produceEncryptionKey(\n this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD);\n } else if (this.s2kUsage === 255) {\n throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');\n } else {\n throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');\n }\n\n let cleartext;\n if (this.s2kUsage === 253) {\n const mode = crypto.getAEADMode(this.aead);\n const modeInstance = await mode(this.symmetric, key);\n try {\n const associateData = this.isLegacyAEAD ?\n new Uint8Array() :\n util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);\n cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);\n } catch (err) {\n if (err.message === 'Authentication tag mismatch') {\n throw new Error('Incorrect key passphrase: ' + err.message);\n }\n throw err;\n }\n } else {\n const cleartextWithHash = await crypto.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);\n\n cleartext = cleartextWithHash.subarray(0, -20);\n const hash = await crypto.hash.sha1(cleartext);\n\n if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {\n throw new Error('Incorrect key passphrase');\n }\n }\n\n try {\n const { privateParams } = crypto.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);\n this.privateParams = privateParams;\n } catch (err) {\n throw new Error('Error reading MPIs');\n }\n this.isEncrypted = false;\n this.keyMaterial = null;\n this.s2kUsage = 0;\n this.aead = null;\n this.symmetric = null;\n this.isLegacyAEAD = null;\n }\n\n /**\n * Checks that the key parameters are consistent\n * @throws {Error} if validation was not successful\n * @async\n */\n async validate() {\n if (this.isDummy()) {\n return;\n }\n\n if (!this.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n\n if (this.usedModernAEAD) {\n // key integrity confirmed by successful AEAD decryption\n return;\n }\n\n let validParams;\n try {\n // this can throw if some parameters are undefined\n validParams = await crypto.validateParams(this.algorithm, this.publicParams, this.privateParams);\n } catch (_) {\n validParams = false;\n }\n if (!validParams) {\n throw new Error('Key is invalid');\n }\n }\n\n async generate(bits, curve) {\n // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.\n // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.\n if (this.version === 6 && (\n (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||\n this.algorithm === enums.publicKey.eddsaLegacy\n )) {\n throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);\n }\n const { privateParams, publicParams } = await crypto.generateParams(this.algorithm, bits, curve);\n this.privateParams = privateParams;\n this.publicParams = publicParams;\n this.isEncrypted = false;\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n if (this.isMissingSecretKeyMaterial()) {\n return;\n }\n\n Object.keys(this.privateParams).forEach(name => {\n const param = this.privateParams[name];\n param.fill(0);\n delete this.privateParams[name];\n });\n this.privateParams = null;\n this.isEncrypted = true;\n }\n}\n\n/**\n * Derive encryption key\n * @param {Number} keyVersion - key derivation differs for v5 keys\n * @param {module:type/s2k} s2k\n * @param {String} passphrase\n * @param {module:enums.symmetric} cipherAlgo\n * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)\n * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)\n * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)\n * @returns encryption key\n */\nasync function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) {\n if (s2k.type === 'argon2' && !aeadMode) {\n throw new Error('Using Argon2 S2K without AEAD is not allowed');\n }\n if (s2k.type === 'simple' && keyVersion === 6) {\n throw new Error('Using Simple S2K with version 6 keys is not allowed');\n }\n const { keySize } = crypto.getCipherParams(cipherAlgo);\n const derivedKey = await s2k.produceKey(passphrase, keySize);\n if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {\n return derivedKey;\n }\n const info = util.concatUint8Array([\n serializedPacketTag,\n new Uint8Array([keyVersion, cipherAlgo, aeadMode])\n ]);\n return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);\n}\n\nexport default SecretKeyPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\n\n/**\n * Implementation of the User ID Packet (Tag 13)\n *\n * A User ID packet consists of UTF-8 text that is intended to represent\n * the name and email address of the key holder. By convention, it\n * includes an RFC 2822 [RFC2822] mail name-addr, but there are no\n * restrictions on its content. The packet length in the header\n * specifies the length of the User ID.\n */\nclass UserIDPacket {\n static get tag() {\n return enums.packet.userID;\n }\n\n constructor() {\n /** A string containing the user id. Usually in the form\n * John Doe \n * @type {String}\n */\n this.userID = '';\n\n this.name = '';\n this.email = '';\n this.comment = '';\n }\n\n /**\n * Create UserIDPacket instance from object\n * @param {Object} userID - Object specifying userID name, email and comment\n * @returns {UserIDPacket}\n * @static\n */\n static fromObject(userID) {\n if (util.isString(userID) ||\n (userID.name && !util.isString(userID.name)) ||\n (userID.email && !util.isEmailAddress(userID.email)) ||\n (userID.comment && !util.isString(userID.comment))) {\n throw new Error('Invalid user ID format');\n }\n const packet = new UserIDPacket();\n Object.assign(packet, userID);\n const components = [];\n if (packet.name) components.push(packet.name);\n if (packet.comment) components.push(`(${packet.comment})`);\n if (packet.email) components.push(`<${packet.email}>`);\n packet.userID = components.join(' ');\n return packet;\n }\n\n /**\n * Parsing function for a user id packet (tag 13).\n * @param {Uint8Array} input - Payload of a tag 13 packet\n */\n read(bytes, config = defaultConfig) {\n const userID = util.decodeUTF8(bytes);\n if (userID.length > config.maxUserIDLength) {\n throw new Error('User ID string is too long');\n }\n\n /**\n * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,\n * as well comments placed between the name (if present) and the bracketed email address:\n * - name (comment) \n * - email\n * In the first case, the `email` is the only required part, and it must contain the `@` symbol.\n * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,\n * since they interfere with `comment` parsing.\n */\n const re = /^(?[^()]+\\s+)?(?\\([^()]+\\)\\s+)?(?<\\S+@\\S+>)$/;\n const matches = re.exec(userID);\n if (matches !== null) {\n const { name, comment, email } = matches.groups;\n this.comment = comment?.replace(/^\\(|\\)|\\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace\n this.name = name?.trim() || '';\n this.email = email.substring(1, email.length - 1); // remove brackets\n } else if (/^[^\\s@]+@[^\\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace\n this.email = userID;\n }\n\n this.userID = userID;\n }\n\n /**\n * Creates a binary representation of the user id packet\n * @returns {Uint8Array} Binary representation.\n */\n write() {\n return util.encodeUTF8(this.userID);\n }\n\n equals(otherUserID) {\n return otherUserID && otherUserID.userID === this.userID;\n }\n}\n\nexport default UserIDPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport SecretKeyPacket from './secret_key';\nimport enums from '../enums';\nimport defaultConfig from '../config';\n\n/**\n * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret\n * Key packet and has exactly the same format.\n * @extends SecretKeyPacket\n */\nclass SecretSubkeyPacket extends SecretKeyPacket {\n static get tag() {\n return enums.packet.secretSubkey;\n }\n\n /**\n * @param {Date} [date] - Creation date\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n constructor(date = new Date(), config = defaultConfig) {\n super(date, config);\n }\n}\n\nexport default SecretSubkeyPacket;\n","import enums from '../enums';\nimport { UnsupportedError } from './packet';\n\n/**\n * Implementation of the Trust Packet (Tag 12)\n *\n * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:\n * The Trust packet is used only within keyrings and is not normally\n * exported. Trust packets contain data that record the user's\n * specifications of which key holders are trustworthy introducers,\n * along with other information that implementing software uses for\n * trust information. The format of Trust packets is defined by a given\n * implementation.\n *\n * Trust packets SHOULD NOT be emitted to output streams that are\n * transferred to other users, and they SHOULD be ignored on any input\n * other than local keyring files.\n */\nclass TrustPacket {\n static get tag() {\n return enums.packet.trust;\n }\n\n /**\n * Parsing function for a trust packet (tag 12).\n * Currently not implemented as we ignore trust packets\n */\n read() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n\n write() {\n throw new UnsupportedError('Trust packets are not supported');\n }\n}\n\nexport default TrustPacket;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2022 Proton AG\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport crypto from '../crypto';\nimport enums from '../enums';\n\n/**\n * Implementation of the Padding Packet\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:\n * Padding Packet\n */\nclass PaddingPacket {\n static get tag() {\n return enums.packet.padding;\n }\n\n constructor() {\n this.padding = null;\n }\n\n /**\n * Read a padding packet\n * @param {Uint8Array | ReadableStream} bytes\n */\n read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars\n // Padding packets are ignored, so this function is never called.\n }\n\n /**\n * Write the padding packet\n * @returns {Uint8Array} The padding packet.\n */\n write() {\n return this.padding;\n }\n\n /**\n * Create random padding.\n * @param {Number} length - The length of padding to be generated.\n * @throws {Error} if padding generation was not successful\n * @async\n */\n async createPadding(length) {\n this.padding = await crypto.random.getRandomBytes(length);\n }\n}\n\nexport default PaddingPacket;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport { PacketList, SignaturePacket } from './packet';\nimport enums from './enums';\nimport util from './util';\nimport defaultConfig from './config';\n\n// A Signature can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP signature.\n */\nexport class Signature {\n /**\n * @param {PacketList} packetlist - The signature packets\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns binary encoded signature\n * @returns {ReadableStream} Binary signature.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns an array of KeyIDs of all of the issuers who created this signature\n * @returns {Array} The Key IDs of the signing keys\n */\n getSigningKeyIDs() {\n return this.packets.map(packet => packet.issuerKeyID);\n }\n}\n\n/**\n * reads an (optionally armored) OpenPGP signature and returns a signature object\n * @param {Object} options\n * @param {String} [options.armoredSignature] - Armored signature to be parsed\n * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New signature object.\n * @async\n * @static\n */\nexport async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredSignature || binarySignature;\n if (!input) {\n throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');\n }\n if (armoredSignature && !util.isString(armoredSignature)) {\n throw new Error('readSignature: options.armoredSignature must be a string');\n }\n if (binarySignature && !util.isUint8Array(binarySignature)) {\n throw new Error('readSignature: options.binarySignature must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredSignature) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.signature) {\n throw new Error('Armored text not of type signature');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedPackets, config);\n return new Signature(packetlist);\n}\n","/**\n * @fileoverview Provides helpers methods for key module\n * @module key/helper\n */\n\nimport {\n SecretKeyPacket,\n SecretSubkeyPacket,\n SignaturePacket\n} from '../packet';\nimport enums from '../enums';\nimport crypto from '../crypto';\nimport util from '../util';\nimport defaultConfig from '../config';\n\nexport async function generateSecretSubkey(options, config) {\n const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);\n secretSubkeyPacket.packets = null;\n secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretSubkeyPacket.generate(options.rsaBits, options.curve);\n await secretSubkeyPacket.computeFingerprintAndKeyID();\n return secretSubkeyPacket;\n}\n\nexport async function generateSecretKey(options, config) {\n const secretKeyPacket = new SecretKeyPacket(options.date, config);\n secretKeyPacket.packets = null;\n secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);\n await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);\n await secretKeyPacket.computeFingerprintAndKeyID();\n return secretKeyPacket;\n}\n\n/**\n * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.\n * @param {Array} signatures - List of signatures\n * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature\n * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,\n * `enums.signatures.certGeneric` should be given regardless of the actual trust level)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - full configuration\n * @returns {Promise} The latest valid signature.\n * @async\n */\nexport async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {\n let latestValid;\n let exception;\n for (let i = signatures.length - 1; i >= 0; i--) {\n try {\n if (\n (!latestValid || signatures[i].created >= latestValid.created)\n ) {\n await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);\n latestValid = signatures[i];\n }\n } catch (e) {\n exception = e;\n }\n }\n if (!latestValid) {\n throw util.wrapError(\n `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`\n .replace('certGeneric ', 'self-')\n .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),\n exception);\n }\n return latestValid;\n}\n\nexport function isDataExpired(keyPacket, signature, date = new Date()) {\n const normDate = util.normalizeDate(date);\n if (normDate !== null) {\n const expirationTime = getKeyExpirationTime(keyPacket, signature);\n return !(keyPacket.created <= normDate && normDate < expirationTime);\n }\n return false;\n}\n\n/**\n * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}\n * @param {SecretSubkeyPacket} subkey - Subkey key packet\n * @param {SecretKeyPacket} primaryKey - Primary key packet\n * @param {Object} options\n * @param {Object} config - Full configuration\n */\nexport async function createBindingSignature(subkey, primaryKey, options, config) {\n const dataToSign = {};\n dataToSign.key = primaryKey;\n dataToSign.bind = subkey;\n const signatureProperties = { signatureType: enums.signature.subkeyBinding };\n if (options.sign) {\n signatureProperties.keyFlags = [enums.keyFlags.signData];\n signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {\n signatureType: enums.signature.keyBinding\n }, options.date, undefined, undefined, undefined, config);\n } else {\n signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);\n return subkeySignaturePacket;\n}\n\n/**\n * Returns the preferred signature hash algorithm for a set of keys.\n * @param {Array} [targetKeys] - The keys to get preferences from\n * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from\n * @param {Object} config - full configuration\n * @returns {Promise}\n * @async\n */\nexport async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {\n /**\n * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the\n * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).\n * if no keys are available, `preferredSenderAlgo` is returned.\n * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).\n */\n const defaultAlgo = enums.hash.sha256; // MUST implement\n const preferredSenderAlgo = config.preferredHashAlgorithm;\n\n const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {\n const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);\n const targetPrefs = selfCertification.preferredHashAlgorithms;\n return targetPrefs;\n }));\n const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys\n for (const supportedAlgos of supportedAlgosPerTarget) {\n for (const hashAlgo of supportedAlgos) {\n try {\n // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on\n const supportedAlgo = enums.write(enums.hash, hashAlgo);\n supportedAlgosMap.set(\n supportedAlgo,\n supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1\n );\n } catch {}\n }\n }\n const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;\n const getStrongestSupportedHashAlgo = () => {\n if (supportedAlgosMap.size === 0) {\n return defaultAlgo;\n }\n const sortedHashAlgos = Array.from(supportedAlgosMap.keys())\n .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))\n .sort((algoA, algoB) => crypto.hash.getHashByteLength(algoA) - crypto.hash.getHashByteLength(algoB));\n const strongestHashAlgo = sortedHashAlgos[0];\n // defaultAlgo is always implicilty supported, and might be stronger than the rest\n return crypto.hash.getHashByteLength(strongestHashAlgo) >= crypto.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;\n };\n\n const eccAlgos = new Set([\n enums.publicKey.ecdsa,\n enums.publicKey.eddsaLegacy,\n enums.publicKey.ed25519,\n enums.publicKey.ed448\n ]);\n\n if (eccAlgos.has(signingKeyPacket.algorithm)) {\n // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:\n // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5\n // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3\n // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4\n // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4\n // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;\n // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve\n // preferred algo, even if not supported by all targets.\n const preferredCurveAlgo = crypto.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);\n\n const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);\n const preferredSenderAlgoStrongerThanCurveAlgo = crypto.hash.getHashByteLength(preferredSenderAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo);\n\n if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {\n return preferredSenderAlgo;\n } else {\n const strongestSupportedAlgo = getStrongestSupportedHashAlgo();\n return crypto.hash.getHashByteLength(strongestSupportedAlgo) >= crypto.hash.getHashByteLength(preferredCurveAlgo) ?\n strongestSupportedAlgo :\n preferredCurveAlgo;\n }\n }\n\n // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,\n // since it was manually set by the sender.\n return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();\n}\n\n/**\n * Returns the preferred compression algorithm for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Preferred compression algorithm\n * @async\n */\nexport async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const defaultAlgo = enums.compression.uncompressed;\n const preferredSenderAlgo = config.preferredCompressionAlgorithm;\n\n // if preferredSenderAlgo appears in the prefs of all recipients, we pick it\n // otherwise we use the default algo\n // if no keys are available, preferredSenderAlgo is returned\n const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {\n const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config);\n const recipientPrefs = selfCertification.preferredCompressionAlgorithms;\n return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;\n }));\n return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;\n}\n\n/**\n * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys\n * @param {Array} [keys] - Set of keys\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Array} [userIDs] - User IDs\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred\n * @async\n */\nexport async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config)));\n const withAEAD = keys.length ?\n selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :\n config.aeadProtect;\n\n if (withAEAD) {\n const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };\n const desiredCipherSuites = [\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: config.preferredAEADAlgorithm },\n { symmetricAlgo: config.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },\n { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config.preferredAEADAlgorithm }\n ];\n for (const desiredCipherSuite of desiredCipherSuites) {\n if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(\n cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo\n ))) {\n return desiredCipherSuite;\n }\n }\n return defaultCipherSuite;\n }\n const defaultSymAlgo = enums.symmetric.aes128;\n const desiredSymAlgo = config.preferredSymmetricAlgorithm;\n return {\n symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?\n desiredSymAlgo :\n defaultSymAlgo,\n aeadAlgo: undefined\n };\n}\n\n/**\n * Create signature packet\n * @param {Object} dataToSign - Contains packets to be signed\n * @param {Array} recipientKeys - keys to get preferences from\n * @param {SecretKeyPacket|\n * SecretSubkeyPacket} signingKeyPacket secret key packet for signing\n * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Object} [userID] - User ID\n * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [detached] - Whether to create a detached signature packet\n * @param {Object} config - full configuration\n * @returns {Promise} Signature packet.\n */\nexport async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {\n if (signingKeyPacket.isDummy()) {\n throw new Error('Cannot sign with a gnu-dummy key.');\n }\n if (!signingKeyPacket.isDecrypted()) {\n throw new Error('Signing key is not decrypted.');\n }\n const signaturePacket = new SignaturePacket();\n Object.assign(signaturePacket, signatureProperties);\n signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;\n signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);\n signaturePacket.rawNotations = [...notations];\n await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);\n return signaturePacket;\n}\n\n/**\n * Merges signatures from source[attr] to dest[attr]\n * @param {Object} source\n * @param {Object} dest\n * @param {String} attr\n * @param {Date} [date] - date to use for signature expiration check, instead of the current time\n * @param {Function} [checkFn] - signature only merged if true\n */\nexport async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {\n source = source[attr];\n if (source) {\n if (!dest[attr].length) {\n dest[attr] = source;\n } else {\n await Promise.all(source.map(async function(sourceSig) {\n if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&\n !dest[attr].some(function(destSig) {\n return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());\n })) {\n dest[attr].push(sourceSig);\n }\n }));\n }\n }\n}\n\n/**\n * Checks if a given certificate or binding signature is revoked\n * @param {SecretKeyPacket|\n * PublicKeyPacket} primaryKey The primary key packet\n * @param {Object} dataToVerify - The data to check\n * @param {Array} revocations - The revocation signatures to check\n * @param {SignaturePacket} signature - The certificate or signature to check\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the signature revokes the data.\n * @async\n */\nexport async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {\n key = key || primaryKey;\n const revocationKeyIDs = [];\n await Promise.all(revocations.map(async function(revocationSignature) {\n try {\n if (\n // Note: a third-party revocation signature could legitimately revoke a\n // self-signature if the signature has an authorized revocation key.\n // However, we don't support passing authorized revocation keys, nor\n // verifying such revocation signatures. Instead, we indicate an error\n // when parsing a key with an authorized revocation key, and ignore\n // third-party revocation signatures here. (It could also be revoking a\n // third-party key certification, which should only affect\n // `verifyAllCertifications`.)\n !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)\n ) {\n const isHardRevocation = ![\n enums.reasonForRevocation.keyRetired,\n enums.reasonForRevocation.keySuperseded,\n enums.reasonForRevocation.userIDInvalid\n ].includes(revocationSignature.reasonForRevocationFlag);\n\n await revocationSignature.verify(\n key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config\n );\n\n // TODO get an identifier of the revoked object instead\n revocationKeyIDs.push(revocationSignature.issuerKeyID);\n }\n } catch (e) {}\n }));\n // TODO further verify that this is the signature that should be revoked\n if (signature) {\n signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :\n signature.revoked || false;\n return signature.revoked;\n }\n return revocationKeyIDs.length > 0;\n}\n\n/**\n * Returns key expiration time based on the given certification signature.\n * The expiration time of the signature is ignored.\n * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check\n * @param {SignaturePacket} signature - signature to process\n * @returns {Date|Infinity} expiration time or infinity if the key does not expire\n */\nexport function getKeyExpirationTime(keyPacket, signature) {\n let expirationTime;\n // check V4 expiration time\n if (signature.keyNeverExpires === false) {\n expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;\n }\n return expirationTime ? new Date(expirationTime) : Infinity;\n}\n\nexport function sanitizeKeyOptions(options, subkeyDefaults = {}) {\n options.type = options.type || subkeyDefaults.type;\n options.curve = options.curve || subkeyDefaults.curve;\n options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;\n options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n options.sign = options.sign || false;\n\n switch (options.type) {\n case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`\n try {\n options.curve = enums.write(enums.curve, options.curve);\n } catch (e) {\n throw new Error('Unknown curve');\n }\n if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||\n options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now\n options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;\n }\n if (options.sign) {\n options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;\n } else {\n options.algorithm = enums.publicKey.ecdh;\n }\n break;\n case 'curve25519':\n options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;\n break;\n case 'curve448':\n options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;\n break;\n case 'rsa':\n options.algorithm = enums.publicKey.rsaEncryptSign;\n break;\n default:\n throw new Error(`Unsupported key type ${options.type}`);\n }\n return options;\n}\n\nexport function validateSigningKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ed25519:\n case enums.publicKey.ed448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateEncryptionKeyPacket(keyPacket, signature, config) {\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448:\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n default:\n return false;\n }\n}\n\nexport function validateDecryptionKeyPacket(keyPacket, signature, config) {\n if (!signature.keyFlags && !config.allowMissingKeyFlags) {\n throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');\n }\n\n switch (keyPacket.algorithm) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.elgamal:\n case enums.publicKey.ecdh:\n case enums.publicKey.x25519:\n case enums.publicKey.x448: {\n const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;\n if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {\n // This is only relevant for RSA keys, all other signing algorithms cannot decrypt\n return true;\n }\n\n return !signature.keyFlags ||\n (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||\n (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check key against blacklisted algorithms and minimum strength requirements.\n * @param {SecretKeyPacket|PublicKeyPacket|\n * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket\n * @param {Config} config\n * @throws {Error} if the key packet does not meet the requirements\n */\nexport function checkKeyRequirements(keyPacket, config) {\n const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);\n const algoInfo = keyPacket.getAlgorithmInfo();\n if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {\n throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);\n }\n switch (keyAlgo) {\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.rsaEncrypt:\n if (algoInfo.bits < config.minRSABits) {\n throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);\n }\n break;\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n case enums.publicKey.ecdh:\n if (config.rejectCurves.has(algoInfo.curve)) {\n throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);\n }\n break;\n default:\n break;\n }\n}\n","/**\n * @module key/User\n */\n\nimport enums from '../enums';\nimport util from '../util';\nimport { PacketList } from '../packet';\nimport { mergeSignatures, isDataRevoked, createSignaturePacket } from './helper';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents an user ID or attribute packet and the relevant signatures.\n * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info\n * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with\n */\nclass User {\n constructor(userPacket, mainKey) {\n this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;\n this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;\n this.selfCertifications = [];\n this.otherCertifications = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured user data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.userID || this.userAttribute);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.selfCertifications);\n packetlist.push(...this.otherCertifications);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @returns {User}\n */\n clone() {\n const user = new User(this.userID || this.userAttribute, this.mainKey);\n user.selfCertifications = [...this.selfCertifications];\n user.otherCertifications = [...this.otherCertifications];\n user.revocationSignatures = [...this.revocationSignatures];\n return user;\n }\n\n /**\n * Generate third-party certifications over this user and its primary key\n * @param {Array} signingKeys - Decrypted private keys for signing\n * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} New user with new certifications.\n * @async\n */\n async certify(signingKeys, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {\n if (!privateKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n if (privateKey.hasSameFingerprintAs(primaryKey)) {\n throw new Error(\"The user's own key can only be used for self-certifications\");\n }\n const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);\n return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {\n // Most OpenPGP implementations use generic certification (0x10)\n signatureType: enums.signature.certGeneric,\n keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]\n }, date, undefined, undefined, undefined, config);\n }));\n await user.update(this, date, config);\n return user;\n }\n\n /**\n * Checks if a given certificate of the user is revoked\n * @param {SignaturePacket} certificate - The certificate to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(certificate, keyPacket, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return isDataRevoked(primaryKey, enums.signature.certRevocation, {\n key: primaryKey,\n userID: this.userID,\n userAttribute: this.userAttribute\n }, this.revocationSignatures, certificate, keyPacket, date, config);\n }\n\n /**\n * Verifies the user certificate.\n * @param {SignaturePacket} certificate - A certificate of this user\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate\n * @throws if the user certificate is invalid.\n * @async\n */\n async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const { issuerKeyID } = certificate;\n const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);\n if (issuerKeys.length === 0) {\n return null;\n }\n await Promise.all(issuerKeys.map(async key => {\n const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);\n if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {\n throw new Error('User certificate is revoked');\n }\n try {\n await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('User certificate is invalid', e);\n }\n }));\n return true;\n }\n\n /**\n * Verifies all user certificates\n * @param {Array} verificationKeys - Array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllCertifications(verificationKeys, date = new Date(), config) {\n const that = this;\n const certifications = this.selfCertifications.concat(this.otherCertifications);\n return Promise.all(certifications.map(async certification => ({\n keyID: certification.issuerKeyID,\n valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)\n })));\n }\n\n /**\n * Verify User. Checks for existence of self signatures, revocation signatures\n * and validity of self signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} config - Full configuration\n * @returns {Promise} Status of user.\n * @throws {Error} if there are no valid self signatures.\n * @async\n */\n async verify(date = new Date(), config) {\n if (!this.selfCertifications.length) {\n throw new Error('No self-certifications found');\n }\n const that = this;\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // TODO replace when Promise.some or Promise.any are implemented\n let exception;\n for (let i = this.selfCertifications.length - 1; i >= 0; i--) {\n try {\n const selfCertification = this.selfCertifications[i];\n if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {\n throw new Error('Self-certification is revoked');\n }\n try {\n await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Self-certification is invalid', e);\n }\n return true;\n } catch (e) {\n exception = e;\n }\n }\n throw exception;\n }\n\n /**\n * Update user with new components from specified user\n * @param {User} sourceUser - Source user to merge\n * @param {Date} date - Date to verify the validity of signatures\n * @param {Object} config - Full configuration\n * @returns {Promise}\n * @async\n */\n async update(sourceUser, date, config) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n // self signatures\n await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {\n try {\n await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // other signatures\n await mergeSignatures(sourceUser, this, 'otherCertifications', date);\n // revocation signatures\n await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {\n return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the user\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New user with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = {\n userID: this.userID,\n userAttribute: this.userAttribute,\n key: primaryKey\n };\n const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);\n user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.certRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await user.update(this);\n return user;\n }\n}\n\nexport default User;\n","/**\n * @module key/Subkey\n */\n\nimport enums from '../enums';\nimport * as helper from './helper';\nimport { PacketList } from '../packet';\nimport defaultConfig from '../config';\n\n/**\n * Class that represents a subkey packet and the relevant signatures.\n * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID\n * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint\n * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs\n * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo\n * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime\n * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted\n */\nclass Subkey {\n /**\n * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey\n * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey\n */\n constructor(subkeyPacket, mainKey) {\n this.keyPacket = subkeyPacket;\n this.bindingSignatures = [];\n this.revocationSignatures = [];\n this.mainKey = mainKey;\n }\n\n /**\n * Transforms structured subkey data to packetlist\n * @returns {PacketList}\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.bindingSignatures);\n return packetlist;\n }\n\n /**\n * Shallow clone\n * @return {Subkey}\n */\n clone() {\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.bindingSignatures = [...this.bindingSignatures];\n subkey.revocationSignatures = [...this.revocationSignatures];\n return subkey;\n }\n\n /**\n * Checks if a binding signature of a subkey is revoked\n * @param {SignaturePacket} signature - The binding signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the binding signature is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n return helper.isDataRevoked(\n primaryKey, enums.signature.subkeyRevocation, {\n key: primaryKey,\n bind: this.keyPacket\n }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify subkey. Checks for revocation signatures, expiration time\n * and valid binding signature.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @throws {Error} if the subkey is invalid.\n * @async\n */\n async verify(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n // check subkey binding signatures\n const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n // check binding signature is not revoked\n if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {\n throw new Error('Subkey is revoked');\n }\n // check for expiration time\n if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {\n throw new Error('Subkey is expired');\n }\n return bindingSignature;\n }\n\n /**\n * Returns the expiration time of the subkey or Infinity if key does not expire.\n * Returns null if the subkey is invalid.\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n const dataToVerify = { key: primaryKey, bind: this.keyPacket };\n let bindingSignature;\n try {\n bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n } catch (e) {\n return null;\n }\n const keyExpiry = helper.getKeyExpirationTime(this.keyPacket, bindingSignature);\n const sigExpiry = bindingSignature.getExpirationTime();\n return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;\n }\n\n /**\n * Update subkey with new components from specified subkey\n * @param {Subkey} subkey - Source subkey to merge\n * @param {Date} [date] - Date to verify validity of signatures\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if update failed\n * @async\n */\n async update(subkey, date = new Date(), config = defaultConfig) {\n const primaryKey = this.mainKey.keyPacket;\n if (!this.hasSameFingerprintAs(subkey)) {\n throw new Error('Subkey update method: fingerprints of subkeys not equal');\n }\n // key packet\n if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&\n subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {\n this.keyPacket = subkey.keyPacket;\n }\n // update missing binding signatures\n const that = this;\n const dataToVerify = { key: primaryKey, bind: that.keyPacket };\n await helper.mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {\n for (let i = 0; i < that.bindingSignatures.length; i++) {\n if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {\n if (srcBindSig.created > that.bindingSignatures[i].created) {\n that.bindingSignatures[i] = srcBindSig;\n }\n return false;\n }\n }\n try {\n await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);\n return true;\n } catch (e) {\n return false;\n }\n });\n // revocation signatures\n await helper.mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {\n return helper.isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);\n });\n }\n\n /**\n * Revokes the subkey\n * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New subkey with revocation signature.\n * @async\n */\n async revoke(\n primaryKey,\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n const dataToSign = { key: primaryKey, bind: this.keyPacket };\n const subkey = new Subkey(this.keyPacket, this.mainKey);\n subkey.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], primaryKey, {\n signatureType: enums.signature.subkeyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, false, config));\n await subkey.update(this);\n return subkey;\n }\n\n hasSameFingerprintAs(other) {\n return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {\n Subkey.prototype[name] =\n function() {\n return this.keyPacket[name]();\n };\n});\n\nexport default Subkey;\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from '../encoding/armor';\nimport {\n PacketList,\n SignaturePacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport util from '../util';\nimport User from './user';\nimport Subkey from './subkey';\nimport * as helper from './helper';\nimport { UnparseablePacket } from '../packet/packet';\n\n// A key revocation certificate can contain the following packets\nconst allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\nconst mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);\nconst keyPacketTags = new Set([\n enums.packet.publicKey, enums.packet.privateKey,\n enums.packet.publicSubkey, enums.packet.privateSubkey\n]);\n\n/**\n * Abstract class that represents an OpenPGP key. Must contain a primary key.\n * Can contain additional subkeys, signatures, user ids, user attributes.\n * @borrows PublicKeyPacket#getKeyID as Key#getKeyID\n * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint\n * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs\n * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo\n * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime\n */\nclass Key {\n /**\n * Transforms packetlist to structured key data\n * @param {PacketList} packetlist - The packets that form a key\n * @param {Set} disallowedPackets - disallowed packet tags\n */\n packetListToStructure(packetlist, disallowedPackets = new Set()) {\n let user;\n let primaryKeyID;\n let subkey;\n let ignoreUntil;\n\n for (const packet of packetlist) {\n\n if (packet instanceof UnparseablePacket) {\n const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);\n if (isUnparseableKeyPacket && !ignoreUntil) {\n // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must\n // discard all non-key packets that follow, until another (sub)key packet is found.\n if (mainKeyPacketTags.has(packet.tag)) {\n ignoreUntil = mainKeyPacketTags;\n } else {\n ignoreUntil = keyPacketTags;\n }\n }\n continue;\n }\n\n const tag = packet.constructor.tag;\n if (ignoreUntil) {\n if (!ignoreUntil.has(tag)) continue;\n ignoreUntil = null;\n }\n if (disallowedPackets.has(tag)) {\n throw new Error(`Unexpected packet type: ${tag}`);\n }\n switch (tag) {\n case enums.packet.publicKey:\n case enums.packet.secretKey:\n if (this.keyPacket) {\n throw new Error('Key block contains multiple keys');\n }\n this.keyPacket = packet;\n primaryKeyID = this.getKeyID();\n if (!primaryKeyID) {\n throw new Error('Missing Key ID');\n }\n break;\n case enums.packet.userID:\n case enums.packet.userAttribute:\n user = new User(packet, this);\n this.users.push(user);\n break;\n case enums.packet.publicSubkey:\n case enums.packet.secretSubkey:\n user = null;\n subkey = new Subkey(packet, this);\n this.subkeys.push(subkey);\n break;\n case enums.packet.signature:\n switch (packet.signatureType) {\n case enums.signature.certGeneric:\n case enums.signature.certPersona:\n case enums.signature.certCasual:\n case enums.signature.certPositive:\n if (!user) {\n util.printDebug('Dropping certification signatures without preceding user packet');\n continue;\n }\n if (packet.issuerKeyID.equals(primaryKeyID)) {\n user.selfCertifications.push(packet);\n } else {\n user.otherCertifications.push(packet);\n }\n break;\n case enums.signature.certRevocation:\n if (user) {\n user.revocationSignatures.push(packet);\n } else {\n this.directSignatures.push(packet);\n }\n break;\n case enums.signature.key:\n this.directSignatures.push(packet);\n break;\n case enums.signature.subkeyBinding:\n if (!subkey) {\n util.printDebug('Dropping subkey binding signature without preceding subkey packet');\n continue;\n }\n subkey.bindingSignatures.push(packet);\n break;\n case enums.signature.keyRevocation:\n this.revocationSignatures.push(packet);\n break;\n case enums.signature.subkeyRevocation:\n if (!subkey) {\n util.printDebug('Dropping subkey revocation signature without preceding subkey packet');\n continue;\n }\n subkey.revocationSignatures.push(packet);\n break;\n }\n break;\n }\n }\n }\n\n /**\n * Transforms structured key data to packetlist\n * @returns {PacketList} The packets that form a key.\n */\n toPacketList() {\n const packetlist = new PacketList();\n packetlist.push(this.keyPacket);\n packetlist.push(...this.revocationSignatures);\n packetlist.push(...this.directSignatures);\n this.users.map(user => packetlist.push(...user.toPacketList()));\n this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));\n return packetlist;\n }\n\n /**\n * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.\n * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.\n * @returns {Promise} Clone of the key.\n */\n clone(clonePrivateParams = false) {\n const key = new this.constructor(this.toPacketList());\n if (clonePrivateParams) {\n key.getKeys().forEach(k => {\n // shallow clone the key packets\n k.keyPacket = Object.create(\n Object.getPrototypeOf(k.keyPacket),\n Object.getOwnPropertyDescriptors(k.keyPacket)\n );\n if (!k.keyPacket.isDecrypted()) return;\n // deep clone the private params, which are cleared during encryption\n const privateParams = {};\n Object.keys(k.keyPacket.privateParams).forEach(name => {\n privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);\n });\n k.keyPacket.privateParams = privateParams;\n });\n }\n return key;\n }\n\n /**\n * Returns an array containing all public or private subkeys matching keyID;\n * If no keyID is given, returns all subkeys.\n * @param {type/keyID} [keyID] - key ID to look for\n * @returns {Array} array of subkeys\n */\n getSubkeys(keyID = null) {\n const subkeys = this.subkeys.filter(subkey => (\n !keyID || subkey.getKeyID().equals(keyID, true)\n ));\n return subkeys;\n }\n\n /**\n * Returns an array containing all public or private keys matching keyID.\n * If no keyID is given, returns all keys, starting with the primary key.\n * @param {type/keyid~KeyID} [keyID] - key ID to look for\n * @returns {Array} array of keys\n */\n getKeys(keyID = null) {\n const keys = [];\n if (!keyID || this.getKeyID().equals(keyID, true)) {\n keys.push(this);\n }\n return keys.concat(this.getSubkeys(keyID));\n }\n\n /**\n * Returns key IDs of all keys\n * @returns {Array}\n */\n getKeyIDs() {\n return this.getKeys().map(key => key.getKeyID());\n }\n\n /**\n * Returns userIDs\n * @returns {Array} Array of userIDs.\n */\n getUserIDs() {\n return this.users.map(user => {\n return user.userID ? user.userID.userID : null;\n }).filter(userID => userID !== null);\n }\n\n /**\n * Returns binary encoded key\n * @returns {Uint8Array} Binary key.\n */\n write() {\n return this.toPacketList().write();\n }\n\n /**\n * Returns last created key or key by given keyID that is available for signing and verification\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} signing key\n * @throws if no valid signing key was found\n * @async\n */\n async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(\n subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config\n );\n if (!helper.validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n continue;\n }\n if (!bindingSignature.embeddedSignature) {\n throw new Error('Missing embedded signature');\n }\n // verify embedded signature\n await helper.getLatestValidSignature(\n [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config\n );\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateSigningKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Returns last created key or key by given keyID that is available for encryption or decryption\n * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve\n * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date\n * @param {Object} [userID] - filter keys for the given user ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} encryption key\n * @throws if no valid encryption key was found\n * @async\n */\n async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n await this.verifyPrimaryKey(date, userID, config);\n const primaryKey = this.keyPacket;\n try {\n helper.checkKeyRequirements(primaryKey, config);\n } catch (err) {\n throw util.wrapError('Could not verify primary key', err);\n }\n // V4: by convention subkeys are preferred for encryption service\n const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);\n let exception;\n for (const subkey of subkeys) {\n if (!keyID || subkey.getKeyID().equals(keyID)) {\n try {\n await subkey.verify(date, config);\n const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config)) {\n helper.checkKeyRequirements(subkey.keyPacket, config);\n return subkey;\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n try {\n // if no valid subkey for encryption, evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&\n helper.validateEncryptionKeyPacket(primaryKey, selfCertification, config)) {\n helper.checkKeyRequirements(primaryKey, config);\n return this;\n }\n } catch (e) {\n exception = e;\n }\n throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);\n }\n\n /**\n * Checks if a signature on a key is revoked\n * @param {SignaturePacket} signature - The signature to verify\n * @param {PublicSubkeyPacket|\n * SecretSubkeyPacket|\n * PublicKeyPacket|\n * SecretKeyPacket} key, optional The key to verify the signature\n * @param {Date} [date] - Use the given date for verification, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} True if the certificate is revoked.\n * @async\n */\n async isRevoked(signature, key, date = new Date(), config = defaultConfig) {\n return helper.isDataRevoked(\n this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config\n );\n }\n\n /**\n * Verify primary key. Checks for revocation signatures, expiration time\n * and valid self signature. Throws if the primary key is invalid.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} If key verification failed\n * @async\n */\n async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n // check for key revocation signatures\n if (await this.isRevoked(null, null, date, config)) {\n throw new Error('Primary key is revoked');\n }\n // check for valid, unrevoked, unexpired self signature\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n // check for expiration time in binding signatures\n if (helper.isDataExpired(primaryKey, selfCertification, date)) {\n throw new Error('Primary key is expired');\n }\n if (primaryKey.version !== 6) {\n // check for expiration time in direct signatures (for V6 keys, the above already did so)\n const directSignature = await helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key\n\n if (directSignature && helper.isDataExpired(primaryKey, directSignature, date)) {\n throw new Error('Primary key is expired');\n }\n }\n }\n\n /**\n * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.\n * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.\n * @param {Object} [userID] - User ID to consider instead of the primary user\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise}\n * @async\n */\n async getExpirationTime(userID, config = defaultConfig) {\n let primaryKeyExpiry;\n try {\n const selfCertification = await this.getPrimarySelfSignature(null, userID, config);\n const selfSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, selfCertification);\n const selfSigExpiry = selfCertification.getExpirationTime();\n const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.\n await helper.getLatestValidSignature(\n this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config\n ).catch(() => {});\n if (directSignature) {\n const directSigKeyExpiry = helper.getKeyExpirationTime(this.keyPacket, directSignature);\n // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,\n // causing a discountinous validy period for the key\n primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);\n } else {\n primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;\n }\n } catch (e) {\n primaryKeyExpiry = null;\n }\n\n return util.normalizeDate(primaryKeyExpiry);\n }\n\n\n /**\n * For V4 keys, returns the self-signature of the primary user.\n * For V5 keys, returns the latest valid direct-key self-signature.\n * This self-signature is to be used to check the key expiration,\n * algorithm preferences, and so on.\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} The primary self-signature\n * @async\n */\n async getPrimarySelfSignature(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n if (primaryKey.version === 6) {\n return helper.getLatestValidSignature(\n this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config\n );\n }\n const { selfCertification } = await this.getPrimaryUser(date, userID, config);\n return selfCertification;\n }\n\n /**\n * Returns primary user and most significant (latest valid) self signature\n * - if multiple primary users exist, returns the one with the latest self signature\n * - otherwise, returns the user with the latest self signature\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * user: User,\n * selfCertification: SignaturePacket\n * }>} The primary user and the self signature\n * @async\n */\n async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const users = [];\n let exception;\n for (let i = 0; i < this.users.length; i++) {\n try {\n const user = this.users[i];\n if (!user.userID) {\n continue;\n }\n if (\n (userID.name !== undefined && user.userID.name !== userID.name) ||\n (userID.email !== undefined && user.userID.email !== userID.email) ||\n (userID.comment !== undefined && user.userID.comment !== userID.comment)\n ) {\n throw new Error('Could not find user that matches that user ID');\n }\n const dataToVerify = { userID: user.userID, key: primaryKey };\n const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);\n users.push({ index: i, user, selfCertification });\n } catch (e) {\n exception = e;\n }\n }\n if (!users.length) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('Could not find primary user');\n }\n await Promise.all(users.map(async function (a) {\n return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config);\n }));\n // sort by primary user flag and signature creation time\n const primaryUser = users.sort(function(a, b) {\n const A = a.selfCertification;\n const B = b.selfCertification;\n return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;\n }).pop();\n const { user, selfCertification: cert } = primaryUser;\n if (cert.revoked || await user.isRevoked(cert, null, date, config)) {\n throw new Error('Primary user is revoked');\n }\n return primaryUser;\n }\n\n /**\n * Update key with new components from specified key with same key ID:\n * users, subkeys, certificates are merged into the destination key,\n * duplicates and expired signatures are ignored.\n *\n * If the source key is a private key and the destination key is public,\n * a private key is returned.\n * @param {Key} sourceKey - Source key to merge\n * @param {Date} [date] - Date to verify validity of signatures and keys\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} updated key\n * @async\n */\n async update(sourceKey, date = new Date(), config = defaultConfig) {\n if (!this.hasSameFingerprintAs(sourceKey)) {\n throw new Error('Primary key fingerprints must be equal to update the key');\n }\n if (!this.isPrivate() && sourceKey.isPrivate()) {\n // check for equal subkey packets\n const equal = (this.subkeys.length === sourceKey.subkeys.length) &&\n (this.subkeys.every(destSubkey => {\n return sourceKey.subkeys.some(srcSubkey => {\n return destSubkey.hasSameFingerprintAs(srcSubkey);\n });\n }));\n if (!equal) {\n throw new Error('Cannot update public key with private key if subkeys mismatch');\n }\n\n return sourceKey.update(this, config);\n }\n // from here on, either:\n // - destination key is private, source key is public\n // - the keys are of the same type\n // hence we don't need to convert the destination key type\n const updatedKey = this.clone();\n // revocation signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {\n return helper.isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);\n });\n // direct signatures\n await helper.mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);\n // update users\n await Promise.all(sourceKey.users.map(async srcUser => {\n // multiple users with the same ID/attribute are not explicitly disallowed by the spec\n // hence we support them, just in case\n const usersToUpdate = updatedKey.users.filter(dstUser => (\n (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||\n (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))\n ));\n if (usersToUpdate.length > 0) {\n await Promise.all(\n usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))\n );\n } else {\n const newUser = srcUser.clone();\n newUser.mainKey = updatedKey;\n updatedKey.users.push(newUser);\n }\n }));\n // update subkeys\n await Promise.all(sourceKey.subkeys.map(async srcSubkey => {\n // multiple subkeys with same fingerprint might be preset\n const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (\n dstSubkey.hasSameFingerprintAs(srcSubkey)\n ));\n if (subkeysToUpdate.length > 0) {\n await Promise.all(\n subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))\n );\n } else {\n const newSubkey = srcSubkey.clone();\n newSubkey.mainKey = updatedKey;\n updatedKey.subkeys.push(newSubkey);\n }\n }));\n\n return updatedKey;\n }\n\n /**\n * Get revocation certificate from a revoked key.\n * (To get a revocation certificate for an unrevoked key, call revoke() first.)\n * @param {Date} date - Use the given date instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Armored revocation certificate.\n * @async\n */\n async getRevocationCertificate(date = new Date(), config = defaultConfig) {\n const dataToVerify = { key: this.keyPacket };\n const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);\n const packetlist = new PacketList();\n packetlist.push(revocationSignature);\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config);\n }\n\n /**\n * Applies a revocation certificate to a key\n * This adds the first signature packet in the armored text to the key,\n * if it is a valid revocation signature.\n * @param {String} revocationCertificate - armored revocation certificate\n * @param {Date} [date] - Date to verify the certificate\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Revoked key.\n * @async\n */\n async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {\n const input = await unarmor(revocationCertificate, config);\n const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);\n const revocationSignature = packetlist.findPacket(enums.packet.signature);\n if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {\n throw new Error('Could not find revocation signature packet');\n }\n if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {\n throw new Error('Revocation signature does not match key');\n }\n try {\n await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);\n } catch (e) {\n throw util.wrapError('Could not verify revocation signature', e);\n }\n const key = this.clone();\n key.revocationSignatures.push(revocationSignature);\n return key;\n }\n\n /**\n * Signs primary user of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {\n const { index, user } = await this.getPrimaryUser(date, userID, config);\n const userSign = await user.certify(privateKeys, date, config);\n const key = this.clone();\n key.users[index] = userSign;\n return key;\n }\n\n /**\n * Signs all users of key\n * @param {Array} privateKeys - decrypted private keys for signing\n * @param {Date} [date] - Use the given date for signing, instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} Key with new certificate signature.\n * @async\n */\n async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {\n const key = this.clone();\n key.users = await Promise.all(this.users.map(function(user) {\n return user.certify(privateKeys, date, config);\n }));\n return key;\n }\n\n /**\n * Verifies primary user of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [userID] - User ID to get instead of the primary user, if it exists\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const { user } = await this.getPrimaryUser(date, userID, config);\n const results = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n return results;\n }\n\n /**\n * Verifies all users of key\n * - if no arguments are given, verifies the self certificates;\n * - otherwise, verifies all certificates signed with given keys.\n * @param {Array} [verificationKeys] - array of keys to verify certificate signatures\n * @param {Date} [date] - Use the given date for verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} List of userID, signer's keyID and validity of signature.\n * Signature validity is null if the verification keys do not correspond to the certificate.\n * @async\n */\n async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const results = [];\n await Promise.all(this.users.map(async user => {\n const signatures = verificationKeys ?\n await user.verifyAllCertifications(verificationKeys, date, config) :\n [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];\n\n results.push(...signatures.map(\n signature => ({\n userID: user.userID ? user.userID.userID : null,\n userAttribute: user.userAttribute,\n keyID: signature.keyID,\n valid: signature.valid\n }))\n );\n }));\n return results;\n }\n}\n\n['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {\n Key.prototype[name] =\n Subkey.prototype[name];\n});\n\nexport default Key;\n","// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor } from '../encoding/armor';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport Key from './key';\n\n/**\n * Class that represents an OpenPGP Public Key\n */\nclass PublicKey extends Key {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.keyPacket = null;\n this.revocationSignatures = [];\n this.directSignatures = [];\n this.users = [];\n this.subkeys = [];\n if (packetlist) {\n this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing public-key packet');\n }\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {false}\n */\n isPrivate() {\n return false;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n return this;\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n}\n\nexport default PublicKey;\n\n","import PublicKey from './public_key';\nimport { armor } from '../encoding/armor';\nimport {\n PacketList,\n PublicKeyPacket,\n PublicSubkeyPacket\n} from '../packet';\nimport defaultConfig from '../config';\nimport enums from '../enums';\nimport * as helper from './helper';\n\n/**\n * Class that represents an OpenPGP Private key\n */\nclass PrivateKey extends PublicKey {\n /**\n * @param {PacketList} packetlist - The packets that form this key\n */\n constructor(packetlist) {\n super();\n this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));\n if (!this.keyPacket) {\n throw new Error('Invalid key: missing private-key packet');\n }\n }\n\n /**\n * Returns true if this is a private key\n * @returns {Boolean}\n */\n isPrivate() {\n return true;\n }\n\n /**\n * Returns key as public key (shallow copy)\n * @returns {PublicKey} New public Key\n */\n toPublic() {\n const packetlist = new PacketList();\n const keyPackets = this.toPacketList();\n for (const keyPacket of keyPackets) {\n switch (keyPacket.constructor.tag) {\n case enums.packet.secretKey: {\n const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);\n packetlist.push(pubKeyPacket);\n break;\n }\n case enums.packet.secretSubkey: {\n const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);\n packetlist.push(pubSubkeyPacket);\n break;\n }\n default:\n packetlist.push(keyPacket);\n }\n }\n return new PublicKey(packetlist);\n }\n\n /**\n * Returns ASCII armored text of key\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.\n const emitChecksum = this.keyPacket.version !== 6;\n return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config);\n }\n\n /**\n * Returns all keys that are available for decryption, matching the keyID when given\n * This is useful to retrieve keys for session key decryption\n * @param {module:type/keyid~KeyID} keyID, optional\n * @param {Date} date, optional\n * @param {String} userID, optional\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} Array of decryption keys.\n * @throws {Error} if no decryption key is found\n * @async\n */\n async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {\n const primaryKey = this.keyPacket;\n const keys = [];\n let exception = null;\n for (let i = 0; i < this.subkeys.length; i++) {\n if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {\n if (this.subkeys[i].keyPacket.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n continue;\n }\n\n try {\n const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };\n const bindingSignature = await helper.getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);\n if (helper.validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config)) {\n keys.push(this.subkeys[i]);\n }\n } catch (e) {\n exception = e;\n }\n }\n }\n\n // evaluate primary key\n const selfCertification = await this.getPrimarySelfSignature(date, userID, config);\n if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && helper.validateDecryptionKeyPacket(primaryKey, selfCertification, config)) {\n if (primaryKey.isDummy()) {\n exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');\n } else {\n keys.push(this);\n }\n }\n\n if (keys.length === 0) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw exception || new Error('No decryption key packets found');\n }\n\n return keys;\n }\n\n /**\n * Returns true if the primary key or any subkey is decrypted.\n * A dummy key is considered encrypted.\n */\n isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }\n\n /**\n * Check whether the private and public primary key parameters correspond\n * Together with verification of binding signatures, this guarantees key integrity\n * In case of gnu-dummy primary key, it is enough to validate any signing subkeys\n * otherwise all encryption subkeys are validated\n * If only gnu-dummy keys are found, we cannot properly validate so we throw an error\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @throws {Error} if validation was not successful and the key cannot be trusted\n * @async\n */\n async validate(config = defaultConfig) {\n if (!this.isPrivate()) {\n throw new Error('Cannot validate a public key');\n }\n\n let signingKeyPacket;\n if (!this.keyPacket.isDummy()) {\n signingKeyPacket = this.keyPacket;\n } else {\n /**\n * It is enough to validate any signing keys\n * since its binding signatures are also checked\n */\n const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });\n // This could again be a dummy key\n if (signingKey && !signingKey.keyPacket.isDummy()) {\n signingKeyPacket = signingKey.keyPacket;\n }\n }\n\n if (signingKeyPacket) {\n return signingKeyPacket.validate();\n } else {\n const keys = this.getKeys();\n const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);\n if (allDummies) {\n throw new Error('Cannot validate an all-gnu-dummy key');\n }\n\n return Promise.all(keys.map(async key => key.keyPacket.validate()));\n }\n }\n\n /**\n * Clear private key parameters\n */\n clearPrivateParams() {\n this.getKeys().forEach(({ keyPacket }) => {\n if (keyPacket.isDecrypted()) {\n keyPacket.clearPrivateParams();\n }\n });\n }\n\n /**\n * Revokes the key\n * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation\n * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation\n * @param {Date} date - optional, override the creationtime of the revocation signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New key with revocation signature.\n * @async\n */\n async revoke(\n {\n flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,\n string: reasonForRevocationString = ''\n } = {},\n date = new Date(),\n config = defaultConfig\n ) {\n if (!this.isPrivate()) {\n throw new Error('Need private key for revoking');\n }\n const dataToSign = { key: this.keyPacket };\n const key = this.clone();\n key.revocationSignatures.push(await helper.createSignaturePacket(dataToSign, [], this.keyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),\n reasonForRevocationString\n }, date, undefined, undefined, undefined, config));\n return key;\n }\n\n\n /**\n * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.\n * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.\n * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.\n * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).\n * Note: Curve448 and Curve25519 are not widely supported yet.\n * @param {String} options.curve (optional) Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date (optional) Override the creation date of the key and the key signatures\n * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false\n * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise}\n * @async\n */\n async addSubkey(options = {}) {\n const config = { ...defaultConfig, ...options.config };\n if (options.passphrase) {\n throw new Error('Subkey could not be encrypted here, please encrypt whole key');\n }\n if (options.rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);\n }\n const secretKeyPacket = this.keyPacket;\n if (secretKeyPacket.isDummy()) {\n throw new Error('Cannot add subkey to gnu-dummy primary key');\n }\n if (!secretKeyPacket.isDecrypted()) {\n throw new Error('Key is not decrypted');\n }\n const defaultOptions = secretKeyPacket.getAlgorithmInfo();\n defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);\n defaultOptions.rsaBits = defaultOptions.bits || 4096;\n defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';\n options = helper.sanitizeKeyOptions(options, defaultOptions);\n // Every subkey for a v4 primary key MUST be a v4 subkey.\n // Every subkey for a v6 primary key MUST be a v6 subkey.\n // For v5 keys, since we dropped generation support, a v4 subkey is added.\n // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.\n const keyPacket = await helper.generateSecretSubkey(options, { ...config, v6Keys: this.keyPacket.version === 6 });\n helper.checkKeyRequirements(keyPacket, config);\n const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options, config);\n const packetList = this.toPacketList();\n packetList.push(keyPacket, bindingSignature);\n return new PrivateKey(packetList);\n }\n}\n\nfunction getDefaultSubkeyType(algoName) {\n const algo = enums.write(enums.publicKey, algoName);\n // NB: no encryption-only algos, since they cannot be in primary keys\n switch (algo) {\n case enums.publicKey.rsaEncrypt:\n case enums.publicKey.rsaEncryptSign:\n case enums.publicKey.rsaSign:\n case enums.publicKey.dsa:\n return 'rsa';\n case enums.publicKey.ecdsa:\n case enums.publicKey.eddsaLegacy:\n return 'ecc';\n case enums.publicKey.ed25519:\n return 'curve25519';\n case enums.publicKey.ed448:\n return 'curve448';\n default:\n throw new Error('Unsupported algorithm');\n }\n}\n\nexport default PrivateKey;\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2015-2016 Decentral\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport {\n PacketList,\n UserIDPacket,\n SignaturePacket,\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserAttributePacket\n} from '../packet';\nimport PrivateKey from './private_key';\nimport PublicKey from './public_key';\nimport * as helper from './helper';\nimport enums from '../enums';\nimport util from '../util';\nimport defaultConfig from '../config';\nimport { unarmor } from '../encoding/armor';\n\n// A Key can contain the following packets\nconst allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([\n PublicKeyPacket,\n PublicSubkeyPacket,\n SecretKeyPacket,\n SecretSubkeyPacket,\n UserIDPacket,\n UserAttributePacket,\n SignaturePacket\n]);\n\n/**\n * Creates a PublicKey or PrivateKey depending on the packetlist in input\n * @param {PacketList} - packets to parse\n * @return {Key} parsed key\n * @throws if no key packet was found\n */\nfunction createKey(packetlist) {\n for (const packet of packetlist) {\n switch (packet.constructor.tag) {\n case enums.packet.secretKey:\n return new PrivateKey(packetlist);\n case enums.packet.publicKey:\n return new PublicKey(packetlist);\n }\n }\n throw new Error('No key packet found');\n}\n\n\n/**\n * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).\n * @param {String} options.curve Elliptic curve for ECC keys\n * @param {Integer} options.rsaBits Number of bits for RSA keys\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Creation date of the key and the key signatures\n * @param {Object} config - Full configuration\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function generate(options, config) {\n options.sign = true; // primary key is always a signing key\n options = helper.sanitizeKeyOptions(options);\n options.subkeys = options.subkeys.map((subkey, index) => helper.sanitizeKeyOptions(options.subkeys[index], options));\n let promises = [helper.generateSecretKey(options, config)];\n promises = promises.concat(options.subkeys.map(options => helper.generateSecretSubkey(options, config)));\n const packets = await Promise.all(promises);\n\n const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n}\n\n/**\n * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.\n * @param {PrivateKey} options.privateKey The private key to reformat\n * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' }\n * @param {String} options.passphrase Passphrase used to encrypt the resulting private key\n * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires\n * @param {Date} options.date Override the creation date of the key signatures\n * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]\n * @param {Object} config - Full configuration\n *\n * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}\n * @async\n * @static\n * @private\n */\nexport async function reformat(options, config) {\n options = sanitize(options);\n const { privateKey } = options;\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot reformat a public key');\n }\n\n if (privateKey.keyPacket.isDummy()) {\n throw new Error('Cannot reformat a gnu-dummy primary key');\n }\n\n const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());\n if (!isDecrypted) {\n throw new Error('Key is not decrypted');\n }\n\n const secretKeyPacket = privateKey.keyPacket;\n\n if (!options.subkeys) {\n options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {\n const secretSubkeyPacket = subkey.keyPacket;\n const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };\n const bindingSignature = await (\n helper.getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)\n ).catch(() => ({}));\n return {\n sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)\n };\n }));\n }\n\n const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);\n if (options.subkeys.length !== secretSubkeyPackets.length) {\n throw new Error('Number of subkey options does not match number of subkeys');\n }\n\n options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));\n\n const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);\n const revocationCertificate = await key.getRevocationCertificate(options.date, config);\n key.revocationSignatures = [];\n return { key, revocationCertificate };\n\n function sanitize(options, subkeyDefaults = {}) {\n options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;\n options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;\n options.date = options.date || subkeyDefaults.date;\n\n return options;\n }\n}\n\n/**\n * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection\n * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.\n * @param {SecretKeyPacket} secretKeyPacket\n * @param {SecretSubkeyPacket} secretSubkeyPackets\n * @param {Object} options\n * @param {Object} config - Full configuration\n * @returns {PrivateKey}\n */\nasync function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {\n // set passphrase protection\n if (options.passphrase) {\n await secretKeyPacket.encrypt(options.passphrase, config);\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n await secretSubkeyPacket.encrypt(subkeyPassphrase, config);\n }\n }));\n\n const packetlist = new PacketList();\n packetlist.push(secretKeyPacket);\n\n function createPreferredAlgos(algos, preferredAlgo) {\n return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];\n }\n\n function getKeySignatureProperties() {\n const signatureProperties = {};\n signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];\n const symmetricAlgorithms = createPreferredAlgos([\n // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)\n enums.symmetric.aes256,\n enums.symmetric.aes128\n ], config.preferredSymmetricAlgorithm);\n signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;\n if (config.aeadProtect) {\n const aeadAlgorithms = createPreferredAlgos([\n enums.aead.gcm,\n enums.aead.eax,\n enums.aead.ocb\n ], config.preferredAEADAlgorithm);\n signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {\n return symmetricAlgorithms.map(symmetricAlgorithm => {\n return [symmetricAlgorithm, aeadAlgorithm];\n });\n });\n }\n signatureProperties.preferredHashAlgorithms = createPreferredAlgos([\n // prefer fast asm.js implementations (SHA-256)\n enums.hash.sha256,\n enums.hash.sha512,\n enums.hash.sha3_256,\n enums.hash.sha3_512\n ], config.preferredHashAlgorithm);\n signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([\n enums.compression.uncompressed,\n enums.compression.zlib,\n enums.compression.zip\n ], config.preferredCompressionAlgorithm);\n // integrity protection always enabled\n signatureProperties.features = [0];\n signatureProperties.features[0] |= enums.features.modificationDetection;\n if (config.aeadProtect) {\n signatureProperties.features[0] |= enums.features.seipdv2;\n }\n if (options.keyExpirationTime > 0) {\n signatureProperties.keyExpirationTime = options.keyExpirationTime;\n signatureProperties.keyNeverExpires = false;\n }\n return signatureProperties;\n }\n\n if (secretKeyPacket.version === 6) { // add direct key signature with key prefs\n const dataToSign = {\n key: secretKeyPacket\n };\n\n const signatureProperties = getKeySignatureProperties();\n signatureProperties.signatureType = enums.signature.key;\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n packetlist.push(signaturePacket);\n }\n\n await Promise.all(options.userIDs.map(async function(userID, index) {\n const userIDPacket = UserIDPacket.fromObject(userID);\n const dataToSign = {\n userID: userIDPacket,\n key: secretKeyPacket\n };\n const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};\n signatureProperties.signatureType = enums.signature.certPositive;\n if (index === 0) {\n signatureProperties.isPrimaryUserID = true;\n }\n\n const signaturePacket = await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);\n\n return { userIDPacket, signaturePacket };\n })).then(list => {\n list.forEach(({ userIDPacket, signaturePacket }) => {\n packetlist.push(userIDPacket);\n packetlist.push(signaturePacket);\n });\n });\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyOptions = options.subkeys[index];\n const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);\n return { secretSubkeyPacket, subkeySignaturePacket };\n })).then(packets => {\n packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {\n packetlist.push(secretSubkeyPacket);\n packetlist.push(subkeySignaturePacket);\n });\n });\n\n // Add revocation signature packet for creating a revocation certificate.\n // This packet should be removed before returning the key.\n const dataToSign = { key: secretKeyPacket };\n packetlist.push(await helper.createSignaturePacket(dataToSign, [], secretKeyPacket, {\n signatureType: enums.signature.keyRevocation,\n reasonForRevocationFlag: enums.reasonForRevocation.noReason,\n reasonForRevocationString: ''\n }, options.date, undefined, undefined, undefined, config));\n\n if (options.passphrase) {\n secretKeyPacket.clearPrivateParams();\n }\n\n await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {\n const subkeyPassphrase = options.subkeys[index].passphrase;\n if (subkeyPassphrase) {\n secretSubkeyPacket.clearPrivateParams();\n }\n }));\n\n return new PrivateKey(packetlist);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key and returns a key object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);\n return createKey(firstKeyPacketList);\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object\n * @param {Object} options\n * @param {String} [options.armoredKey] - Armored key to be parsed\n * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Key object.\n * @async\n * @static\n */\nexport async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!armoredKey && !binaryKey) {\n throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');\n }\n if (armoredKey && !util.isString(armoredKey)) {\n throw new Error('readPrivateKey: options.armoredKey must be a string');\n }\n if (binaryKey && !util.isUint8Array(binaryKey)) {\n throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n let input;\n if (armoredKey) {\n const { type, data } = await unarmor(armoredKey, config);\n if (!(type === enums.armor.privateKey)) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n } else {\n input = binaryKey;\n }\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n return new PrivateKey(firstPrivateKeyList);\n }\n throw new Error('No secret key packet found');\n}\n\n/**\n * Reads an (optionally armored) OpenPGP key block and returns a list of key objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readKeys: options.binaryKeys must be a Uint8Array');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n if (keyIndex.length === 0) {\n throw new Error('No key packet found');\n }\n for (let i = 0; i < keyIndex.length; i++) {\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = createKey(oneKeyList);\n keys.push(newKey);\n }\n return keys;\n}\n\n/**\n * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects\n * @param {Object} options\n * @param {String} [options.armoredKeys] - Armored keys to be parsed\n * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Key objects.\n * @async\n * @static\n */\nexport async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {\n config = { ...defaultConfig, ...config };\n let input = armoredKeys || binaryKeys;\n if (!input) {\n throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');\n }\n if (armoredKeys && !util.isString(armoredKeys)) {\n throw new Error('readPrivateKeys: options.armoredKeys must be a string');\n }\n if (binaryKeys && !util.isUint8Array(binaryKeys)) {\n throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');\n }\n if (armoredKeys) {\n const { type, data } = await unarmor(armoredKeys, config);\n if (type !== enums.armor.privateKey) {\n throw new Error('Armored text not of type private key');\n }\n input = data;\n }\n const keys = [];\n const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);\n const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);\n for (let i = 0; i < keyIndex.length; i++) {\n if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {\n continue;\n }\n const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);\n const newKey = new PrivateKey(oneKeyList);\n keys.push(newKey);\n }\n if (keys.length === 0) {\n throw new Error('No secret key packet found');\n }\n return keys;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { armor, unarmor } from './encoding/armor';\nimport { Argon2OutOfMemoryError } from './type/s2k';\nimport defaultConfig from './config';\nimport crypto from './crypto';\nimport enums from './enums';\nimport util from './util';\nimport { Signature } from './signature';\nimport { getPreferredCipherSuite, createSignaturePacket } from './key';\nimport {\n PacketList,\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n} from './packet';\n\n// A Message can contain the following packets\nconst allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([\n LiteralDataPacket,\n CompressedDataPacket,\n AEADEncryptedDataPacket,\n SymEncryptedIntegrityProtectedDataPacket,\n SymmetricallyEncryptedDataPacket,\n PublicKeyEncryptedSessionKeyPacket,\n SymEncryptedSessionKeyPacket,\n OnePassSignaturePacket,\n SignaturePacket\n]);\n// A SKESK packet can contain the following packets\nconst allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);\n// A detached signature can contain the following packets\nconst allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP message.\n * Can be an encrypted message, signed message, compressed message or literal message\n * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}\n */\nexport class Message {\n /**\n * @param {PacketList} packetlist - The packets that form this message\n */\n constructor(packetlist) {\n this.packets = packetlist || new PacketList();\n }\n\n /**\n * Returns the key IDs of the keys to which the session key is encrypted\n * @returns {Array} Array of keyID objects.\n */\n getEncryptionKeyIDs() {\n const keyIDs = [];\n const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n pkESKeyPacketlist.forEach(function(packet) {\n keyIDs.push(packet.publicKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Returns the key IDs of the keys that signed the message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const msg = this.unwrapCompressed();\n // search for one pass signatures\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);\n if (onePassSigList.length > 0) {\n return onePassSigList.map(packet => packet.issuerKeyID);\n }\n // if nothing found look for signature packets\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n return signatureList.map(packet => packet.issuerKeyID);\n }\n\n /**\n * Decrypt the message. Either a private key, a session key, or a password must be specified.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Date} [date] - Use the given date for key verification instead of the current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with decrypted content.\n * @async\n */\n async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {\n const symEncryptedPacketlist = this.packets.filterByTag(\n enums.packet.symmetricallyEncryptedData,\n enums.packet.symEncryptedIntegrityProtectedData,\n enums.packet.aeadEncryptedData\n );\n\n if (symEncryptedPacketlist.length === 0) {\n throw new Error('No encrypted data found');\n }\n\n const symEncryptedPacket = symEncryptedPacketlist[0];\n const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;\n\n const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config);\n\n let exception = null;\n const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {\n if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {\n throw new Error('Invalid session key for decryption.');\n }\n\n try {\n const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.decrypt(algo, data, config);\n } catch (e) {\n util.printDebugError(e);\n exception = e;\n }\n }));\n // We don't await stream.cancel here because it only returns when the other copy is canceled too.\n stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.\n symEncryptedPacket.encrypted = null;\n await decryptedPromise;\n\n if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {\n throw exception || new Error('Decryption failed.');\n }\n\n const resultMsg = new Message(symEncryptedPacket.packets);\n symEncryptedPacket.packets = new PacketList(); // remove packets after decryption\n\n return resultMsg;\n }\n\n /**\n * Decrypt encrypted session keys either with private keys or passwords.\n * @param {Array} [decryptionKeys] - Private keys with decrypted secret data\n * @param {Array} [passwords] - Passwords used to decrypt\n * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)\n * @param {Date} [date] - Use the given date for key verification, instead of current time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise>} array of object with potential sessionKey, algorithm pairs\n * @async\n */\n async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config = defaultConfig) {\n let decryptedSessionKeyPackets = [];\n\n let exception;\n if (passwords) {\n const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);\n if (skeskPackets.length === 0) {\n throw new Error('No symmetrically encrypted session key packet found.');\n }\n await Promise.all(passwords.map(async function(password, i) {\n let packets;\n if (i) {\n packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);\n } else {\n packets = skeskPackets;\n }\n await Promise.all(packets.map(async function(skeskPacket) {\n try {\n await skeskPacket.decrypt(password);\n decryptedSessionKeyPackets.push(skeskPacket);\n } catch (err) {\n util.printDebugError(err);\n if (err instanceof Argon2OutOfMemoryError) {\n exception = err;\n }\n }\n }));\n }));\n } else if (decryptionKeys) {\n const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);\n if (pkeskPackets.length === 0) {\n throw new Error('No public key encrypted session key packet found.');\n }\n await Promise.all(pkeskPackets.map(async function(pkeskPacket) {\n await Promise.all(decryptionKeys.map(async function(decryptionKey) {\n let decryptionKeyPackets;\n try {\n // do not check key expiration to allow decryption of old messages\n decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);\n } catch (err) {\n exception = err;\n return;\n }\n\n let algos = [\n enums.symmetric.aes256, // Old OpenPGP.js default fallback\n enums.symmetric.aes128, // RFC4880bis fallback\n enums.symmetric.tripledes, // RFC4880 fallback\n enums.symmetric.cast5 // Golang OpenPGP fallback\n ];\n try {\n const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config); // TODO: Pass userID from somewhere.\n if (selfCertification.preferredSymmetricAlgorithms) {\n algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);\n }\n } catch (e) {}\n\n await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {\n if (!decryptionKeyPacket.isDecrypted()) {\n throw new Error('Decryption key is not decrypted.');\n }\n\n // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.\n const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||\n pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal\n );\n\n if (doConstantTimeDecryption) {\n // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,\n // either with the successfully decrypted session key, or with a randomly generated one.\n // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on\n // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:\n // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the\n // randomly generated keys of the remaining key types.\n // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly\n // generated session keys.\n // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.\n\n const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times\n await Promise.all((\n expectedSymmetricAlgorithm ?\n [expectedSymmetricAlgorithm] :\n Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)\n ).map(async sessionKeyAlgorithm => {\n const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();\n pkeskPacketCopy.read(serialisedPKESK);\n const randomSessionKey = {\n sessionKeyAlgorithm,\n sessionKey: crypto.generateSessionKey(sessionKeyAlgorithm)\n };\n try {\n await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);\n decryptedSessionKeyPackets.push(pkeskPacketCopy);\n } catch (err) {\n // `decrypt` can still throw some non-security-sensitive errors\n util.printDebugError(err);\n exception = err;\n }\n }));\n\n } else {\n try {\n await pkeskPacket.decrypt(decryptionKeyPacket);\n const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;\n if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {\n throw new Error('A non-preferred symmetric algorithm was used.');\n }\n decryptedSessionKeyPackets.push(pkeskPacket);\n } catch (err) {\n util.printDebugError(err);\n exception = err;\n }\n }\n }));\n }));\n stream.cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.\n pkeskPacket.encrypted = null;\n }));\n } else {\n throw new Error('No key or password specified.');\n }\n\n if (decryptedSessionKeyPackets.length > 0) {\n // Return only unique session keys\n if (decryptedSessionKeyPackets.length > 1) {\n const seen = new Set();\n decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {\n const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);\n if (seen.has(k)) {\n return false;\n }\n seen.add(k);\n return true;\n });\n }\n\n return decryptedSessionKeyPackets.map(packet => ({\n data: packet.sessionKey,\n algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)\n }));\n }\n throw exception || new Error('Session key decryption failed.');\n }\n\n /**\n * Get literal data that is the body of the message\n * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.\n */\n getLiteralData() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getBytes()) || null;\n }\n\n /**\n * Get filename from literal data packet\n * @returns {(String|null)} Filename of literal data packet as string.\n */\n getFilename() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n return (literal && literal.getFilename()) || null;\n }\n\n /**\n * Get literal data as text\n * @returns {(String|null)} Literal body of the message interpreted as text.\n */\n getText() {\n const msg = this.unwrapCompressed();\n const literal = msg.packets.findPacket(enums.packet.literalData);\n if (literal) {\n return literal.getText();\n }\n return null;\n }\n\n /**\n * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.\n * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for\n * @param {Date} [date] - Date to select algorithm preferences at\n * @param {Array} [userIDs] - User IDs to select algorithm preferences for\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.\n * @async\n */\n static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config);\n const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);\n const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;\n\n await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()\n .catch(() => null) // ignore key strength requirements\n .then(maybeKey => {\n if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&\n !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted\n throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');\n }\n })\n ));\n\n const sessionKeyData = crypto.generateSessionKey(symmetricAlgo);\n return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };\n }\n\n /**\n * Encrypt the message either with public keys, passwords, or both at once.\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - Password(s) for message encryption\n * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]\n * @param {Date} [date] - Override the creation date of the literal package\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n if (sessionKey) {\n if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {\n throw new Error('Invalid session key for encryption.');\n }\n } else if (encryptionKeys && encryptionKeys.length) {\n sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);\n } else if (passwords && passwords.length) {\n sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);\n } else {\n throw new Error('No keys, passwords, or session key provided.');\n }\n\n const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;\n\n const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);\n\n const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({\n version: aeadAlgorithmName ? 2 : 1,\n aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null\n });\n symEncryptedPacket.packets = this.packets;\n\n const algorithm = enums.write(enums.symmetric, algorithmName);\n await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);\n\n msg.packets.push(symEncryptedPacket);\n symEncryptedPacket.packets = new PacketList(); // remove packets after encryption\n return msg;\n }\n\n /**\n * Encrypt a session key either with public keys, passwords, or both at once.\n * @param {Uint8Array} sessionKey - session key for encryption\n * @param {String} algorithmName - session key algorithm\n * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {Array} [encryptionKeys] - Public key(s) for message encryption\n * @param {Array} [passwords] - For message encryption\n * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs\n * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [date] - Override the date\n * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with encrypted content.\n * @async\n */\n static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {\n const packetlist = new PacketList();\n const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);\n const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);\n\n if (encryptionKeys) {\n const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {\n const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);\n\n const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({\n version: aeadAlgorithm ? 6 : 3,\n encryptionKeyPacket: encryptionKey.keyPacket,\n anonymousRecipient: wildcard,\n sessionKey,\n sessionKeyAlgorithm: symmetricAlgorithm\n });\n\n await pkESKeyPacket.encrypt(encryptionKey.keyPacket);\n delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption\n return pkESKeyPacket;\n }));\n packetlist.push(...results);\n }\n if (passwords) {\n const testDecrypt = async function(keyPacket, password) {\n try {\n await keyPacket.decrypt(password);\n return 1;\n } catch (e) {\n return 0;\n }\n };\n\n const sum = (accumulator, currentValue) => accumulator + currentValue;\n\n const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {\n const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);\n symEncryptedSessionKeyPacket.sessionKey = sessionKey;\n symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;\n if (aeadAlgorithm) {\n symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;\n }\n await symEncryptedSessionKeyPacket.encrypt(password, config);\n\n if (config.passwordCollisionCheck) {\n const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));\n if (results.reduce(sum) !== 1) {\n return encryptPassword(sessionKey, algorithm, password);\n }\n }\n\n delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption\n return symEncryptedSessionKeyPacket;\n };\n\n const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));\n packetlist.push(...results);\n }\n\n return new Message(packetlist);\n }\n\n /**\n * Sign the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to add to the message\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New message with signed content.\n * @async\n */\n async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const packetlist = new PacketList();\n\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n\n const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config); // this returns the existing signature packets as well\n const onePassSignaturePackets = signaturePackets.map(\n (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))\n .reverse(); // innermost OPS refers to the first signature packet\n\n packetlist.push(...onePassSignaturePackets);\n packetlist.push(literalDataPacket);\n packetlist.push(...signaturePackets);\n\n return new Message(packetlist);\n }\n\n /**\n * Compresses the message (the literal and -if signed- signature data packets of the message)\n * @param {module:enums.compression} algo - compression algorithm\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Message} New message with compressed content.\n */\n compress(algo, config = defaultConfig) {\n if (algo === enums.compression.uncompressed) {\n return this;\n }\n\n const compressed = new CompressedDataPacket(config);\n compressed.algorithm = algo;\n compressed.packets = this.packets;\n\n const packetList = new PacketList();\n packetList.push(compressed);\n\n return new Message(packetList);\n }\n\n /**\n * Create a detached signature for the message (the literal data packet of the message)\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creation time of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New detached signature of message content.\n * @async\n */\n async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = this.packets.findPacket(enums.packet.literalData);\n if (!literalDataPacket) {\n throw new Error('No literal data packet to sign.');\n }\n return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config));\n }\n\n /**\n * Verify message signatures\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signatures.\n * @async\n */\n async verify(verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n if (stream.isArrayStream(msg.packets.stream)) {\n msg.packets.push(...await stream.readToEnd(msg.packets.stream, _ => _ || []));\n }\n const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();\n const signatureList = msg.packets.filterByTag(enums.packet.signature);\n if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !stream.isArrayStream(msg.packets.stream)) {\n await Promise.all(onePassSigList.map(async onePassSig => {\n onePassSig.correspondingSig = new Promise((resolve, reject) => {\n onePassSig.correspondingSigResolve = resolve;\n onePassSig.correspondingSigReject = reject;\n });\n onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);\n onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));\n onePassSig.hashed.catch(() => {});\n }));\n msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {\n const reader = stream.getReader(readable);\n const writer = stream.getWriter(writable);\n try {\n for (let i = 0; i < onePassSigList.length; i++) {\n const { value: signature } = await reader.read();\n onePassSigList[i].correspondingSigResolve(signature);\n }\n await reader.readToEnd();\n await writer.ready;\n await writer.close();\n } catch (e) {\n onePassSigList.forEach(onePassSig => {\n onePassSig.correspondingSigReject(e);\n });\n await writer.abort(e);\n }\n });\n return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);\n }\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);\n }\n\n /**\n * Verify detached message signature\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Signature} signature\n * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {\n const msg = this.unwrapCompressed();\n const literalDataList = msg.packets.filterByTag(enums.packet.literalData);\n if (literalDataList.length !== 1) {\n throw new Error('Can only verify message with one literal data packet.');\n }\n const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);\n }\n\n /**\n * Unwrap compressed message\n * @returns {Message} Message Content of compressed message.\n */\n unwrapCompressed() {\n const compressed = this.packets.filterByTag(enums.packet.compressedData);\n if (compressed.length) {\n return new Message(compressed[0].packets);\n }\n return this;\n }\n\n /**\n * Append signature to unencrypted message object\n * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n */\n async appendSignature(detachedSignature, config = defaultConfig) {\n await this.packets.read(\n util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,\n allowedDetachedSignaturePackets,\n config\n );\n }\n\n /**\n * Returns binary encoded message\n * @returns {ReadableStream} Binary message.\n */\n write() {\n return this.packets.write();\n }\n\n /**\n * Returns ASCII armored text of message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n const trailingPacket = this.packets[this.packets.length - 1];\n // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?\n trailingPacket.version !== 2 :\n this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);\n return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config);\n }\n}\n\n/**\n * Create signature packets for the message\n * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign\n * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing\n * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature to append\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [date] - Override the creationtime of the signature\n * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures\n * @param {Boolean} [detached] - Whether to create detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} List of signature packets.\n * @async\n * @private\n */\nexport async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config = defaultConfig) {\n const packetlist = new PacketList();\n\n // If data packet was created from Uint8Array, use binary, otherwise use text\n const signatureType = literalDataPacket.text === null ?\n enums.signature.binary : enums.signature.text;\n\n await Promise.all(signingKeys.map(async (primaryKey, i) => {\n const signingUserID = signingUserIDs[i];\n if (!primaryKey.isPrivate()) {\n throw new Error('Need private key for signing');\n }\n const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config);\n return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config);\n })).then(signatureList => {\n packetlist.push(...signatureList);\n });\n\n if (signature) {\n const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);\n packetlist.push(...existingSigPacketlist);\n }\n return packetlist;\n}\n\n/**\n * Create object containing signer's keyID and validity of signature\n * @param {SignaturePacket} signature - Signature packet\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} [date] - Check signature validity with respect to the given date\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise<{\n * keyID: module:type/keyid~KeyID,\n * signature: Promise,\n * verified: Promise\n * }>} signer's keyID and validity of signature\n * @async\n * @private\n */\nasync function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n let primaryKey;\n let unverifiedSigningKey;\n\n for (const key of verificationKeys) {\n const issuerKeys = key.getKeys(signature.issuerKeyID);\n if (issuerKeys.length > 0) {\n primaryKey = key;\n unverifiedSigningKey = issuerKeys[0];\n break;\n }\n }\n\n const isOnePassSignature = signature instanceof OnePassSignaturePacket;\n const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;\n\n const verifiedSig = {\n keyID: signature.issuerKeyID,\n verified: (async () => {\n if (!unverifiedSigningKey) {\n throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);\n }\n\n await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);\n const signaturePacket = await signaturePacketPromise;\n if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {\n throw new Error('Key is newer than the signature');\n }\n // We pass the signature creation time to check whether the key was expired at the time of signing.\n // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before\n try {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);\n } catch (e) {\n // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,\n // making the key invalid at the time of signing.\n // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.\n // Note: we do not support the edge case of a key that was reformatted and it has expired.\n if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {\n await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);\n } else {\n throw e;\n }\n }\n return true;\n })(),\n signature: (async () => {\n const signaturePacket = await signaturePacketPromise;\n const packetlist = new PacketList();\n signaturePacket && packetlist.push(signaturePacket);\n return new Signature(packetlist);\n })()\n };\n\n // Mark potential promise rejections as \"handled\". This is needed because in\n // some cases, we reject them before the user has a reasonable chance to\n // handle them (e.g. `await readToEnd(result.data); await result.verified` and\n // the data stream errors).\n verifiedSig.signature.catch(() => {});\n verifiedSig.verified.catch(() => {});\n\n return verifiedSig;\n}\n\n/**\n * Create list of objects containing signer's keyID and validity of signature\n * @param {Array} signatureList - Array of signature packets\n * @param {Array} literalDataList - Array of literal data packets\n * @param {Array} verificationKeys - Array of public keys to verify signatures\n * @param {Date} date - Verify the signature against the given date,\n * i.e. check signature creation time < date < expiration time\n * @param {Boolean} [detached] - Whether to verify detached signature packets\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)\n * @async\n * @private\n */\nexport async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {\n return Promise.all(signatureList.filter(function(signature) {\n return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));\n }).map(async function(signature) {\n return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);\n }));\n}\n\n/**\n * Reads an (optionally armored) OpenPGP message and returns a Message object\n * @param {Object} options\n * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed\n * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n let input = armoredMessage || binaryMessage;\n if (!input) {\n throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');\n }\n if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {\n throw new Error('readMessage: options.armoredMessage must be a string or stream');\n }\n if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {\n throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n if (armoredMessage) {\n const { type, data } = await unarmor(input, config);\n if (type !== enums.armor.message) {\n throw new Error('Armored text not of type message');\n }\n input = data;\n }\n const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);\n const message = new Message(packetlist);\n message.fromStream = streamType;\n return message;\n}\n\n/**\n * Creates new message object from text or binary data.\n * @param {Object} options\n * @param {String | ReadableStream} [options.text] - The text message contents\n * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents\n * @param {String} [options.filename=\"\"] - Name of the file (if any)\n * @param {Date} [options.date=current date] - Date of the message, or modification date of the file\n * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type\n * @returns {Promise} New message object.\n * @async\n * @static\n */\nexport async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {\n const input = text !== undefined ? text : binary;\n if (input === undefined) {\n throw new Error('createMessage: must pass options object containing `text` or `binary`');\n }\n if (text && !util.isString(text) && !util.isStream(text)) {\n throw new Error('createMessage: options.text must be a string or stream');\n }\n if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {\n throw new Error('createMessage: options.binary must be a Uint8Array or stream');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const streamType = util.isStream(input);\n const literalDataPacket = new LiteralDataPacket(date);\n if (text !== undefined) {\n literalDataPacket.setText(input, enums.write(enums.literal, format));\n } else {\n literalDataPacket.setBytes(input, enums.write(enums.literal, format));\n }\n if (filename !== undefined) {\n literalDataPacket.setFilename(filename);\n }\n const literalDataPacketlist = new PacketList();\n literalDataPacketlist.push(literalDataPacket);\n const message = new Message(literalDataPacketlist);\n message.fromStream = streamType;\n return message;\n}\n","// GPG4Browsers - An OpenPGP implementation in javascript\n// Copyright (C) 2011 Recurity Labs GmbH\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport { armor, unarmor } from './encoding/armor';\nimport enums from './enums';\nimport util from './util';\nimport { PacketList, LiteralDataPacket, SignaturePacket } from './packet';\nimport { Signature } from './signature';\nimport { createVerificationObjects, createSignaturePackets } from './message';\nimport defaultConfig from './config';\n\n// A Cleartext message can contain the following packets\nconst allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);\n\n/**\n * Class that represents an OpenPGP cleartext signed message.\n * See {@link https://tools.ietf.org/html/rfc4880#section-7}\n */\nexport class CleartextMessage {\n /**\n * @param {String} text - The cleartext of the signed message\n * @param {Signature} signature - The detached signature or an empty signature for unsigned messages\n */\n constructor(text, signature) {\n // remove trailing whitespace and normalize EOL to canonical form \n this.text = util.removeTrailingSpaces(text).replace(/\\r?\\n/g, '\\r\\n');\n if (signature && !(signature instanceof Signature)) {\n throw new Error('Invalid signature input');\n }\n this.signature = signature || new Signature(new PacketList());\n }\n\n /**\n * Returns the key IDs of the keys that signed the cleartext message\n * @returns {Array} Array of keyID objects.\n */\n getSigningKeyIDs() {\n const keyIDs = [];\n const signatureList = this.signature.packets;\n signatureList.forEach(function(packet) {\n keyIDs.push(packet.issuerKeyID);\n });\n return keyIDs;\n }\n\n /**\n * Sign the cleartext message\n * @param {Array} signingKeys - private keys with decrypted secret key data for signing\n * @param {Array} recipientKeys - recipient keys to get the signing preferences from\n * @param {Signature} [signature] - Any existing detached signature\n * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]\n * @param {Date} [date] - The creation time of the signature that should be created\n * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]\n * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from\n * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise} New cleartext message with signed content.\n * @async\n */\n async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config = defaultConfig) {\n const literalDataPacket = new LiteralDataPacket();\n literalDataPacket.setText(this.text);\n const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config));\n return new CleartextMessage(this.text, newSignature);\n }\n\n /**\n * Verify signatures of cleartext signed message\n * @param {Array} keys - Array of keys to verify signatures\n * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {Promise,\n * verified: Promise\n * }>>} List of signer's keyID and validity of signature.\n * @async\n */\n verify(keys, date = new Date(), config = defaultConfig) {\n const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets\n const literalDataPacket = new LiteralDataPacket();\n // we assume that cleartext signature is generated based on UTF8 cleartext\n literalDataPacket.setText(this.text);\n return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);\n }\n\n /**\n * Get cleartext\n * @returns {String} Cleartext of message.\n */\n getText() {\n // normalize end of line to \\n\n return this.text.replace(/\\r\\n/g, '\\n');\n }\n\n /**\n * Returns ASCII armored text of cleartext signed message\n * @param {Object} [config] - Full configuration, defaults to openpgp.config\n * @returns {String | ReadableStream} ASCII armor.\n */\n armor(config = defaultConfig) {\n // emit header and checksum if one of the signatures has a version not 6\n const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);\n const hash = emitHeaderAndChecksum ?\n Array.from(new Set(this.signature.packets.map(\n packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()\n ))).join() :\n null;\n\n const body = {\n hash,\n text: this.text,\n data: this.signature.packets.write()\n };\n\n // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.\n return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config);\n }\n}\n\n/**\n * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object\n * @param {Object} options\n * @param {String} options.cleartextMessage - Text to be parsed\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} New cleartext message object.\n * @async\n * @static\n */\nexport async function readCleartextMessage({ cleartextMessage, config, ...rest }) {\n config = { ...defaultConfig, ...config };\n if (!cleartextMessage) {\n throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');\n }\n if (!util.isString(cleartextMessage)) {\n throw new Error('readCleartextMessage: options.cleartextMessage must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n const input = await unarmor(cleartextMessage);\n if (input.type !== enums.armor.signed) {\n throw new Error('No cleartext signed message.');\n }\n const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config);\n verifyHeaders(input.headers, packetlist);\n const signature = new Signature(packetlist);\n return new CleartextMessage(input.text, signature);\n}\n\n/**\n * Compare hash algorithm specified in the armor header with signatures\n * @param {Array} headers - Armor headers\n * @param {PacketList} packetlist - The packetlist with signature packets\n * @private\n */\nfunction verifyHeaders(headers, packetlist) {\n const checkHashAlgos = function(hashAlgos) {\n const check = packet => algo => packet.hashAlgorithm === algo;\n\n for (let i = 0; i < packetlist.length; i++) {\n if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {\n return false;\n }\n }\n return true;\n };\n\n const hashAlgos = [];\n headers.forEach(header => {\n const hashHeader = header.match(/^Hash: (.+)$/); // get header value\n if (hashHeader) {\n const parsedHashIDs = hashHeader[1]\n .replace(/\\s/g, '') // remove whitespace\n .split(',')\n .map(hashName => {\n try {\n return enums.write(enums.hash, hashName.toLowerCase());\n } catch (e) {\n throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());\n }\n });\n hashAlgos.push(...parsedHashIDs);\n } else {\n throw new Error('Only \"Hash\" header allowed in cleartext signed message');\n }\n });\n\n if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {\n throw new Error('Hash algorithm mismatch in armor header and signature');\n }\n}\n\n/**\n * Creates a new CleartextMessage object from text\n * @param {Object} options\n * @param {String} options.text\n * @static\n * @async\n */\nexport async function createCleartextMessage({ text, ...rest }) {\n if (!text) {\n throw new Error('createCleartextMessage: must pass options object containing `text`');\n }\n if (!util.isString(text)) {\n throw new Error('createCleartextMessage: options.text must be a string');\n }\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n return new CleartextMessage(text);\n}\n","// OpenPGP.js - An OpenPGP implementation in javascript\n// Copyright (C) 2016 Tankred Hase\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3.0 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport * as stream from '@openpgp/web-stream-tools';\nimport { Message } from './message';\nimport { CleartextMessage } from './cleartext';\nimport { generate, reformat, getPreferredCompressionAlgo } from './key';\nimport defaultConfig from './config';\nimport util from './util';\nimport { checkKeyRequirements } from './key/helper';\n\n\n//////////////////////\n// //\n// Key handling //\n// //\n//////////////////////\n\n\n/**\n * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.\n * By default, primary and subkeys will be of same type.\n * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.\n * @param {Object} options\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).\n * Note: Curve448 and Curve25519 (new format) are not widely supported yet.\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys\n * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:\n * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,\n * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1\n * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`\n * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n if (!type && !curve) {\n type = config.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)\n curve = 'curve25519Legacy'; // unused with type != 'ecc'\n } else {\n type = type || 'ecc';\n curve = curve || 'curve25519Legacy';\n }\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && !config.v6Keys) {\n throw new Error('UserIDs are required for V4 keys');\n }\n if (type === 'rsa' && rsaBits < config.minRSABits) {\n throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);\n }\n\n const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };\n\n try {\n const { key, revocationCertificate } = await generate(options, config);\n key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));\n\n return {\n privateKey: formatObject(key, format, config),\n publicKey: formatObject(key.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error generating keypair', err);\n }\n}\n\n/**\n * Reformats signature packets for a key and rewraps key object.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - Private key to reformat\n * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`\n * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.\n * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires\n * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended\n * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The generated key object in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }\n * @async\n * @static\n */\nexport async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n userIDs = toArray(userIDs);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {\n throw new Error('UserIDs are required for V4 keys');\n }\n const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };\n\n try {\n const { key: reformattedKey, revocationCertificate } = await reformat(options, config);\n\n return {\n privateKey: formatObject(reformattedKey, format, config),\n publicKey: formatObject(reformattedKey.toPublic(), format, config),\n revocationCertificate\n };\n } catch (err) {\n throw util.wrapError('Error reformatting keypair', err);\n }\n}\n\n/**\n * Revokes a key. Requires either a private key or a revocation certificate.\n * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.\n * @param {Object} options\n * @param {Key} options.key - Public or private key to revoke\n * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with\n * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation\n * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation\n * @param {String} [options.reasonForRevocation.string=\"\"] - String explaining the reason for revocation\n * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The revoked key in the form:\n * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or\n * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise\n * @async\n * @static\n */\nexport async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const revokedKey = revocationCertificate ?\n await key.applyRevocationCertificate(revocationCertificate, date, config) :\n await key.revoke(reasonForRevocation, date, config);\n\n return revokedKey.isPrivate() ? {\n privateKey: formatObject(revokedKey, format, config),\n publicKey: formatObject(revokedKey.toPublic(), format, config)\n } : {\n privateKey: null,\n publicKey: formatObject(revokedKey, format, config)\n };\n } catch (err) {\n throw util.wrapError('Error revoking key', err);\n }\n}\n\n/**\n * Unlock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to decrypt\n * @param {String|Array} options.passphrase - The user's passphrase(s)\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The unlocked key object.\n * @async\n */\nexport async function decryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot decrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];\n\n try {\n await Promise.all(clonedPrivateKey.getKeys().map(key => (\n // try to decrypt each key with any of the given passphrases\n util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))\n )));\n\n await clonedPrivateKey.validate(config);\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error decrypting private key', err);\n }\n}\n\n/**\n * Lock a private key with the given passphrase.\n * This method does not change the original key.\n * @param {Object} options\n * @param {PrivateKey} options.privateKey - The private key to encrypt\n * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} The locked key object.\n * @async\n */\nexport async function encryptKey({ privateKey, passphrase, config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!privateKey.isPrivate()) {\n throw new Error('Cannot encrypt a public key');\n }\n const clonedPrivateKey = privateKey.clone(true);\n\n const keys = clonedPrivateKey.getKeys();\n const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);\n if (passphrases.length !== keys.length) {\n throw new Error('Invalid number of passphrases given for key encryption');\n }\n\n try {\n await Promise.all(keys.map(async (key, i) => {\n const { keyPacket } = key;\n await keyPacket.encrypt(passphrases[i], config);\n keyPacket.clearPrivateParams();\n }));\n return clonedPrivateKey;\n } catch (err) {\n clonedPrivateKey.clearPrivateParams();\n throw util.wrapError('Error encrypting private key', err);\n }\n}\n\n\n///////////////////////////////////////////\n// //\n// Message encryption and decryption //\n// //\n///////////////////////////////////////////\n\n\n/**\n * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`\n * must be specified. If signing keys are specified, those will be used to sign the message.\n * @param {Object} options\n * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message\n * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed\n * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message\n * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Signature} [options.signature] - A detached signature to add to the encrypted message\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`\n * @param {Date} [options.date=current date] - Override the creation date of the message signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords);\n signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations);\n if (rest.detached) {\n throw new Error(\"The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.\");\n }\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (!signingKeys) {\n signingKeys = [];\n }\n\n try {\n if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified\n message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config);\n }\n message = message.compress(\n await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config),\n config\n );\n message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n if (format === 'object') return message;\n // serialize data\n const armor = format === 'armored';\n const data = armor ? message.armor(config) : message.write();\n return await convertStream(data);\n } catch (err) {\n throw util.wrapError('Error encrypting message', err);\n }\n}\n\n/**\n * Decrypts a message with the user's private key, a session key or a password.\n * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).\n * @param {Object} options\n * @param {Message} options.message - The message object with the encrypted data\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the message\n * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }\n * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing decrypted and verified message in the form:\n *\n * {\n * data: MaybeStream, (if format was 'utf8', the default)\n * data: MaybeStream, (if format was 'binary')\n * filename: String,\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);\n if (!verificationKeys) {\n verificationKeys = [];\n }\n\n const result = {};\n result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);\n result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();\n result.filename = decrypted.getFilename();\n linkStreams(result, message);\n if (expectSigned) {\n if (verificationKeys.length === 0) {\n throw new Error('Verification keys are required to verify message signatures');\n }\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error decrypting message', err);\n }\n}\n\n\n//////////////////////////////////////////\n// //\n// Message signing and verification //\n// //\n//////////////////////////////////////////\n\n\n/**\n * Signs a message.\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed\n * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext\n * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from\n * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message\n * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature\n * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]\n * @param {Date} [options.date=current date] - Override the creation date of the signature\n * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`\n * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`\n * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); checkOutputMessageFormat(format);\n signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations);\n\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');\n if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');\n if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');\n\n if (!signingKeys || signingKeys.length === 0) {\n throw new Error('No signing keys provided');\n }\n\n try {\n let signature;\n if (detached) {\n signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n } else {\n signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config);\n }\n if (format === 'object') return signature;\n\n const armor = format === 'armored';\n signature = armor ? signature.armor(config) : signature.write();\n if (detached) {\n signature = stream.transformPair(message.packets.write(), async (readable, writable) => {\n await Promise.all([\n stream.pipe(signature, writable),\n stream.readToEnd(readable).catch(() => {})\n ]);\n });\n }\n return await convertStream(signature);\n } catch (err) {\n throw util.wrapError('Error signing message', err);\n }\n}\n\n/**\n * Verifies signatures of cleartext signed message\n * @param {Object} options\n * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures\n * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures\n * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys\n * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.\n * @param {Signature} [options.signature] - Detached signature for verification\n * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Object containing verified message in the form:\n *\n * {\n * data: MaybeStream, (if `message` was a CleartextMessage)\n * data: MaybeStream, (if `message` was a Message)\n * signatures: [\n * {\n * keyID: module:type/keyid~KeyID,\n * verified: Promise,\n * signature: Promise\n * }, ...\n * ]\n * }\n *\n * where `signatures` contains a separate entry for each signature packet found in the input message.\n * @async\n * @static\n */\nexport async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if (message instanceof CleartextMessage && format === 'binary') throw new Error(\"Can't return cleartext message data as binary\");\n if (message instanceof CleartextMessage && signature) throw new Error(\"Can't verify detached cleartext signature\");\n\n try {\n const result = {};\n if (signature) {\n result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);\n } else {\n result.signatures = await message.verify(verificationKeys, date, config);\n }\n result.data = format === 'binary' ? message.getLiteralData() : message.getText();\n if (message.fromStream && !signature) linkStreams(result, message);\n if (expectSigned) {\n if (result.signatures.length === 0) {\n throw new Error('Message is not signed');\n }\n result.data = stream.concat([\n result.data,\n stream.fromAsync(async () => {\n await util.anyPromise(result.signatures.map(sig => sig.verified));\n })\n ]);\n }\n result.data = await convertStream(result.data);\n return result;\n } catch (err) {\n throw util.wrapError('Error verifying signed message', err);\n }\n}\n\n\n///////////////////////////////////////////////\n// //\n// Session key encryption and decryption //\n// //\n///////////////////////////////////////////////\n\n/**\n * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.\n * @param {Object} options\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}\n * @param {Date} [options.date=current date] - Date to select algorithm preferences at\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.\n * @async\n * @static\n */\nexport async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error generating session key', err);\n }\n}\n\n/**\n * Encrypt a symmetric session key with public keys, passwords, or both at once.\n * At least one of `encryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)\n * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'\n * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'\n * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key\n * @param {String|String[]} [options.passwords] - Passwords for the message\n * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value\n * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs\n * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]\n * @param {Date} [options.date=current date] - Override the date\n * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).\n * @async\n * @static\n */\nexport async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);\n encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs);\n if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {\n throw new Error('No encryption keys or passwords provided.');\n }\n\n try {\n const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);\n return formatObject(message, format, config);\n } catch (err) {\n throw util.wrapError('Error encrypting session key', err);\n }\n}\n\n/**\n * Decrypt symmetric session keys using private keys or passwords (not both).\n * One of `decryptionKeys` or `passwords` must be specified.\n * @param {Object} options\n * @param {Message} options.message - A message object containing the encrypted session key packets\n * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data\n * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key\n * @param {Date} [options.date] - Date to use for key verification instead of the current time\n * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}\n * @returns {Promise} Array of decrypted session key, algorithm pairs in the form:\n * { data:Uint8Array, algorithm:String }\n * @throws if no session key could be found or decrypted\n * @async\n * @static\n */\nexport async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {\n config = { ...defaultConfig, ...config }; checkConfig(config);\n checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords);\n if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');\n const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);\n\n try {\n const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config);\n return sessionKeys;\n } catch (err) {\n throw util.wrapError('Error decrypting session keys', err);\n }\n}\n\n\n//////////////////////////\n// //\n// Helper functions //\n// //\n//////////////////////////\n\n\n/**\n * Input validation\n * @private\n */\nfunction checkString(data, name) {\n if (!util.isString(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type String');\n }\n}\nfunction checkBinary(data, name) {\n if (!util.isUint8Array(data)) {\n throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');\n }\n}\nfunction checkMessage(message) {\n if (!(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message');\n }\n}\nfunction checkCleartextOrMessage(message) {\n if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {\n throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');\n }\n}\nfunction checkOutputMessageFormat(format) {\n if (format !== 'armored' && format !== 'binary' && format !== 'object') {\n throw new Error(`Unsupported format ${format}`);\n }\n}\nconst defaultConfigPropsCount = Object.keys(defaultConfig).length;\nfunction checkConfig(config) {\n const inputConfigProps = Object.keys(config);\n if (inputConfigProps.length !== defaultConfigPropsCount) {\n for (const inputProp of inputConfigProps) {\n if (defaultConfig[inputProp] === undefined) {\n throw new Error(`Unknown config property: ${inputProp}`);\n }\n }\n }\n}\n\n/**\n * Normalize parameter to an array if it is not undefined.\n * @param {Object} param - the parameter to be normalized\n * @returns {Array|undefined} The resulting array or undefined.\n * @private\n */\nfunction toArray(param) {\n if (param && !util.isArray(param)) {\n param = [param];\n }\n return param;\n}\n\n/**\n * Convert data to or from Stream\n * @param {Object} data - the data to convert\n * @returns {Promise} The data in the respective format.\n * @async\n * @private\n */\nasync function convertStream(data) {\n const streamType = util.isStream(data);\n if (streamType === 'array') {\n return stream.readToEnd(data);\n }\n return data;\n}\n\n/**\n * Link result.data to the message stream for cancellation.\n * Also, forward errors in the message to result.data.\n * @param {Object} result - the data to convert\n * @param {Message} message - message object\n * @returns {Object}\n * @private\n */\nfunction linkStreams(result, message) {\n result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {\n await stream.pipe(result.data, writable, {\n preventClose: true\n });\n const writer = stream.getWriter(writable);\n try {\n // Forward errors in the message stream to result.data.\n await stream.readToEnd(readable, _ => _);\n await writer.close();\n } catch (e) {\n await writer.abort(e);\n }\n });\n}\n\n/**\n * Convert the object to the given format\n * @param {Key|Message} object\n * @param {'armored'|'binary'|'object'} format\n * @param {Object} config - Full configuration\n * @returns {String|Uint8Array|Object}\n */\nfunction formatObject(object, format, config) {\n switch (format) {\n case 'object':\n return object;\n case 'armored':\n return object.armor(config);\n case 'binary':\n return object.write();\n default:\n throw new Error(`Unsupported format ${format}`);\n }\n}\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\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// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n}, sha256);\nexport const secp256r1 = p256;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha384 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp384r1 aka p384\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');\nconst Fp = Field(P);\nconst CURVE_A = Fp.create(BigInt('-3'));\n// prettier-ignore\nconst CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n// prettier-ignore\nexport const p384 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\n // Curve order, total count of valid points in the field.\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n // Base (generator) point (x, y)\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n h: BigInt(1),\n lowS: false,\n}, sha384);\nexport const secp384r1 = p384;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-12')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p384.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n// NIST secp521r1 aka p521\n// Note that it's 521, which differs from 512 of its hash function.\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521\n// Field over which we'll do calculations.\n// prettier-ignore\nconst P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst Fp = Field(P);\nconst CURVE = {\n a: Fp.create(BigInt('-3')),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Fp,\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n h: BigInt(1),\n};\n// prettier-ignore\nexport const p521 = createCurve({\n a: CURVE.a, // Equation params: a, b\n b: CURVE.b,\n Fp, // Field: 2n**521n - 1n\n // Curve order, total count of valid points in the field\n n: CURVE.n,\n Gx: CURVE.Gx, // Base point (x, y) aka generator point\n Gy: CURVE.Gy,\n h: CURVE.h,\n lowS: false,\n allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\nexport const secp521r1 = p521;\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: CURVE.a,\n B: CURVE.b,\n Z: Fp.create(BigInt('-4')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=p521.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { shake256 } from '@noble/hashes/sha3';\nimport { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xof } from './abstract/hash-to-curve.js';\nimport { Field, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * Edwards448 (not Ed448-Goldilocks) curve with following addons:\n * - X448 ECDH\n * - Decaf cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2\n */\nconst shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));\nconst shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));\nconst ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');\n// prettier-ignore\nconst _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);\n// prettier-ignore\nconst _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);\n// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.\n// Used for efficient square root calculation.\n// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]\nfunction ed448_pow_Pminus3div4(x) {\n const P = ed448P;\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b222 = (pow2(b220, _2n, P) * b2) % P;\n const b223 = (pow2(b222, _1n, P) * x) % P;\n return (pow2(b223, _223n, P) * b222) % P;\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most\n // significant bit of the last byte to 1.\n bytes[0] &= 252; // 0b11111100\n // and the most significant bit of the last byte to 1.\n bytes[55] |= 128; // 0b10000000\n // NOTE: is is NOOP for 56 bytes scalars (X25519/X448)\n bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)\n return bytes;\n}\n// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.\n// Uses algo from RFC8032 5.1.3.\nfunction uvRatio(u, v) {\n const P = ed448P;\n // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3\n // To compute the square root of (u/v), the first step is to compute the\n // candidate root x = (u/v)^((p+1)/4). This can be done using the\n // following trick, to use a single modular powering for both the\n // inversion of v and the square root:\n // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)\n const u2v = mod(u * u * v, P); // u²v\n const u3v = mod(u2v * u, P); // u³v\n const u5v3 = mod(u3v * u2v * v, P); // u⁵v³\n const root = ed448_pow_Pminus3div4(u5v3);\n const x = mod(u3v * root, P);\n // Verify that root is exists\n const x2 = mod(x * x, P); // x²\n // If vx² = u, the recovered x-coordinate is x. Otherwise, no\n // square root exists, and the decoding fails.\n return { isValid: mod(x2 * v, P) === u, value: x };\n}\nconst Fp = Field(ed448P, 456, true);\nconst ED448_DEF = {\n // Param: a\n a: BigInt(1),\n // -39081. Negative number is P - number\n d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'),\n // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n\n Fp,\n // Subgroup order: how many points curve has;\n // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n\n n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n nBitLength: 456,\n // Cofactor\n h: BigInt(4),\n // Base point (x, y) aka generator point\n Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'),\n Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'),\n // SHAKE256(dom4(phflag,context)||x, 114)\n hash: shake256_114,\n randomBytes,\n adjustScalarBytes,\n // dom4\n domain: (data, ctx, phflag) => {\n if (ctx.length > 255)\n throw new Error(`Context is too big: ${ctx.length}`);\n return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n },\n uvRatio,\n};\nexport const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF);\n// NOTE: there is no ed448ctx, since ed448 supports ctx by default\nexport const ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 });\nexport const x448 = /* @__PURE__ */ (() => montgomery({\n a: BigInt(156326),\n // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys\n montgomeryBits: 448,\n nByteLength: 56,\n P: ed448P,\n Gu: BigInt(5),\n powPminus2: (x) => {\n const P = ed448P;\n const Pminus3div4 = ed448_pow_Pminus3div4(x);\n const Pminus3 = pow2(Pminus3div4, BigInt(2), P);\n return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts edwards448 public key to x448 public key. Uses formula:\n * * `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * * `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n * @example\n * const aPub = ed448.getPublicKey(utils.randomPrivateKey());\n * x448.getSharedSecret(edwardsToMontgomery(aPub), edwardsToMontgomery(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed448.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((y - _1n) * Fp.inv(y + _1n)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version\n// Hash To Curve Elligator2 Map\nconst ELL2_C1 = (Fp.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic\nconst ELL2_J = BigInt(156326);\nfunction map_to_curve_elligator2_curve448(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1\n tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0\n let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1\n let x1n = Fp.neg(ELL2_J); // 5. x1n = -J\n let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2\n tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd\n tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3\n let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)\n y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)\n let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd\n let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u\n y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)\n tv2 = Fp.sqr(y1); // 20. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2\n let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)\n return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)\n}\nfunction map_to_curve_elligator2_edwards448(u) {\n let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)\n let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2\n let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2\n let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2\n let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2\n let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2\n let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2\n let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2\n xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2\n xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd\n xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn\n xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4\n tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2\n tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2\n let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2\n let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2\n tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4\n let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2\n tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn\n let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4\n let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2\n yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4\n yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2\n tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2\n tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2\n tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd\n tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2\n tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1\n let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1\n tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2\n yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4\n tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd\n let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0\n xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)\n xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)\n yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)\n yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)\n const inv = Fp.invertBatch([xEd, yEd]); // batch division\n return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {\n DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',\n encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 224,\n expand: 'xof',\n hash: shake256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertDcfPoint(other) {\n if (!(other instanceof DcfPoint))\n throw new Error('DecafPoint expected');\n}\n// 1-d\nconst ONE_MINUS_D = BigInt('39082');\n// 1-2d\nconst ONE_MINUS_TWO_D = BigInt('78163');\n// √(-d)\nconst SQRT_MINUS_D = BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');\n// 1 / √(-d)\nconst INVSQRT_MINUS_D = BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_448B = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes448ToNumberLE = (bytes) => ed448.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_448B);\n// Computes Elligator map for Decaf\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\nfunction calcElligatorDecafMap(r0) {\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const r = mod(-(r0 * r0)); // 1\n const u0 = mod(d * (r - _1n)); // 2\n const u1 = mod((u0 + _1n) * (u0 - r)); // 3\n const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4\n let v_prime = v; // 5\n if (!was_square)\n v_prime = mod(r0 * v);\n let sgn = _1n; // 6\n if (!was_square)\n sgn = mod(-_1n);\n const s = mod(v_prime * (r + _1n)); // 7\n let s_abs = s;\n if (isNegativeLE(s, P))\n s_abs = mod(-s);\n const s2 = s * s;\n const W0 = mod(s_abs * _2n); // 8\n const W1 = mod(s2 + _1n); // 9\n const W2 = mod(s2 - _1n); // 10\n const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11\n return new ed448.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed448/ExtendedPoint has 4 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Decaf was created to solve this.\n * Decaf point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass DcfPoint {\n // Private property to discourage combining ExtendedPoint + DecafPoint\n // Always use Decaf encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new DcfPoint(ed448.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 112-byte hash function like shake256 and converts it to `DecafPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-element-derivation-2\n * @param hex 112-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('decafHash', hex, 112);\n const r1 = bytes448ToNumberLE(hex.slice(0, 56));\n const R1 = calcElligatorDecafMap(r1);\n const r2 = bytes448ToNumberLE(hex.slice(56, 112));\n const R2 = calcElligatorDecafMap(r2);\n return new DcfPoint(R1.add(R2));\n }\n /**\n * Converts decaf-encoded string to decaf point.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-decode-2\n * @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('decafHex', hex, 56);\n const { d } = ed448.CURVE;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const emsg = 'DecafPoint.fromHex: the hex is not valid encoding of DecafPoint';\n const s = bytes448ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 2. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 56), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s); // 1\n const u1 = mod(_1n + s2); // 2\n const u1sq = mod(u1 * u1);\n const u2 = mod(u1sq - _4n * d * s2); // 3\n const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4\n let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5\n if (isNegativeLE(u3, P))\n u3 = mod(-u3);\n const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6\n const y = mod((_1n - s2) * invsqrt * u1); // 7\n const t = mod(x * y); // 8\n if (!isValid)\n throw new Error(emsg);\n return new DcfPoint(new ed448.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes decaf point to Uint8Array.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-encode-2\n */\n toRawBytes() {\n let { ex: x, ey: _y, ez: z, et: t } = this.ep;\n const P = ed448.CURVE.Fp.ORDER;\n const mod = ed448.CURVE.Fp.create;\n const u1 = mod(mod(x + t) * mod(x - t)); // 1\n const x2 = mod(x * x);\n const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2\n let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3\n if (isNegativeLE(ratio, P))\n ratio = mod(-ratio);\n const u2 = mod(INVSQRT_MINUS_D * ratio * z - t); // 4\n let s = mod(ONE_MINUS_D * invsqrt * x * u2); // 5\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 56);\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448-07#name-equals-2\n equals(other) {\n assertDcfPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed448.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2)\n return mod(X1 * Y2) === mod(Y1 * X2);\n }\n add(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertDcfPoint(other);\n return new DcfPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new DcfPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new DcfPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new DcfPoint(this.ep.double());\n }\n negate() {\n return new DcfPoint(this.ep.negate());\n }\n}\nexport const DecafPoint = /* @__PURE__ */ (() => {\n // decaf448 base point is ed448 base x 2\n // https://github.com/dalek-cryptography/curve25519-dalek/blob/59837c6ecff02b77b9d5ff84dbc239d0cf33ef90/vendor/ristretto.sage#L699\n if (!DcfPoint.BASE)\n DcfPoint.BASE = new DcfPoint(ed448.ExtendedPoint.BASE).multiply(_2n);\n if (!DcfPoint.ZERO)\n DcfPoint.ZERO = new DcfPoint(ed448.ExtendedPoint.ZERO);\n return DcfPoint;\n})();\n// Hashing to decaf448. https://www.rfc-editor.org/rfc/rfc9380#appendix-C\nexport const hashToDecaf448 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xof(msg, DST, 112, 224, shake256);\n const P = DcfPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_decaf448 = hashToDecaf448; // legacy\n//# sourceMappingURL=ed448.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));\nconst CURVE_A = Fp.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));\nconst CURVE_B = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');\n\n// prettier-ignore\nexport const brainpoolP256r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),\n Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),\n h: BigInt(1),\n lowS: false\n} as const, sha256);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha384 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));\nconst CURVE_A = Fp.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));\nconst CURVE_B = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');\n\n// prettier-ignore\nexport const brainpoolP384r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),\n Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),\n h: BigInt(1),\n lowS: false\n} as const, sha384);\n","import { createCurve } from '@noble/curves/_shortw_utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { Field } from '@noble/curves/abstract/modular';\n\n// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7\n\n// eslint-disable-next-line new-cap\nconst Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));\nconst CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));\nconst CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');\n\n// prettier-ignore\nexport const brainpoolP512r1 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp,\n // Curve order (q), total count of valid points in the field\n n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),\n Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),\n h: BigInt(1),\n lowS: false\n} as const, sha512);\n","/**\n * This file is needed to dynamic import the noble-curves.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { p256 as nistP256 } from '@noble/curves/p256';\nimport { p384 as nistP384 } from '@noble/curves/p384';\nimport { p521 as nistP521 } from '@noble/curves/p521';\nimport { x448, ed448 } from '@noble/curves/ed448';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { brainpoolP256r1 } from './brainpool/brainpoolP256r1';\nimport { brainpoolP384r1 } from './brainpool/brainpoolP384r1';\nimport { brainpoolP512r1 } from './brainpool/brainpoolP512r1';\n\nexport const nobleCurves = new Map(Object.entries({\n nistP256,\n nistP384,\n nistP521,\n brainpoolP256r1,\n brainpoolP384r1,\n brainpoolP512r1,\n secp256k1,\n x448,\n ed448\n}));\n\n","//Paul Tero, July 2001\n//http://www.tero.co.uk/des/\n//\n//Optimised for performance with large blocks by Michael Hayworth, November 2001\n//http://www.netdealing.com\n//\n// Modified by Recurity Labs GmbH\n\n//THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n//SUCH DAMAGE.\n\n//des\n//this takes the key, the message, and whether to encrypt or decrypt\n\nfunction des(keys, message, encrypt, mode, iv, padding) {\n //declaring this locally speeds things up a bit\n const spfunction1 = [\n 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,\n 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,\n 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,\n 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,\n 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,\n 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004\n ];\n const spfunction2 = [\n -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,\n -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,\n -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,\n -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,\n -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,\n 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,\n -0x7fef7fe0, 0x108000\n ];\n const spfunction3 = [\n 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,\n 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,\n 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,\n 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,\n 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,\n 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200\n ];\n const spfunction4 = [\n 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,\n 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,\n 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,\n 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,\n 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080\n ];\n const spfunction5 = [\n 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,\n 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,\n 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,\n 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,\n 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,\n 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,\n 0x40080000, 0x2080100, 0x40000100\n ];\n const spfunction6 = [\n 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,\n 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,\n 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,\n 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,\n 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,\n 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010\n ];\n const spfunction7 = [\n 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,\n 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,\n 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,\n 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,\n 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,\n 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002\n ];\n const spfunction8 = [\n 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,\n 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,\n 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,\n 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,\n 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,\n 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000\n ];\n\n //create the 16 or 48 subkeys we will need\n let m = 0;\n let i;\n let j;\n let temp;\n let right1;\n let right2;\n let left;\n let right;\n let looping;\n let cbcleft;\n let cbcleft2;\n let cbcright;\n let cbcright2;\n let endloop;\n let loopinc;\n let len = message.length;\n\n //set up the loops for single and triple des\n const iterations = keys.length === 32 ? 3 : 9; //single or triple des\n if (iterations === 3) {\n looping = encrypt ? [0, 32, 2] : [30, -2, -2];\n } else {\n looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];\n }\n\n //pad the message depending on the padding parameter\n //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (encrypt) {\n message = desAddPadding(message, padding);\n len = message.length;\n }\n\n //store the result here\n let result = new Uint8Array(len);\n let k = 0;\n\n if (mode === 1) { //CBC mode\n cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];\n m = 0;\n }\n\n //loop through each 64 bit chunk of the message\n while (m < len) {\n left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n left ^= cbcleft;\n right ^= cbcright;\n } else {\n cbcleft2 = cbcleft;\n cbcright2 = cbcright;\n cbcleft = left;\n cbcright = right;\n }\n }\n\n //first each 64 but chunk of the message must be permuted according to IP\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n //do this either 1 or 3 times for each chunk of the message\n for (j = 0; j < iterations; j += 3) {\n endloop = looping[j + 1];\n loopinc = looping[j + 2];\n //now go through and perform the encryption or decryption\n for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency\n right1 = right ^ keys[i];\n right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n //the result is attained by passing these bytes through the S selection functions\n temp = left;\n left = right;\n right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>\n 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &\n 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);\n }\n temp = left;\n left = right;\n right = temp; //unreverse left and right\n } //for either 1 or 3 iterations\n\n //move then each one bit to the right\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n //now perform IP-1, which is IP in the opposite direction\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= temp;\n right ^= (temp << 2);\n temp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= temp;\n left ^= (temp << 16);\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n\n //for Cipher Block Chaining mode, xor the message with the previous result\n if (mode === 1) {\n if (encrypt) {\n cbcleft = left;\n cbcright = right;\n } else {\n left ^= cbcleft2;\n right ^= cbcright2;\n }\n }\n\n result[k++] = (left >>> 24);\n result[k++] = ((left >>> 16) & 0xff);\n result[k++] = ((left >>> 8) & 0xff);\n result[k++] = (left & 0xff);\n result[k++] = (right >>> 24);\n result[k++] = ((right >>> 16) & 0xff);\n result[k++] = ((right >>> 8) & 0xff);\n result[k++] = (right & 0xff);\n } //for every 8 characters, or 64 bits in the message\n\n //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt\n if (!encrypt) {\n result = desRemovePadding(result, padding);\n }\n\n return result;\n} //end of des\n\n\n//desCreateKeys\n//this takes as input a 64 bit key (even though only 56 bits are used)\n//as an array of 2 integers, and returns 16 48 bit keys\n\nfunction desCreateKeys(key) {\n //declaring this locally speeds things up a bit\n const pc2bytes0 = [\n 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,\n 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204\n ];\n const pc2bytes1 = [\n 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,\n 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101\n ];\n const pc2bytes2 = [\n 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,\n 0x1000000, 0x1000008, 0x1000800, 0x1000808\n ];\n const pc2bytes3 = [\n 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,\n 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000\n ];\n const pc2bytes4 = [\n 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,\n 0x41000, 0x1010, 0x41010\n ];\n const pc2bytes5 = [\n 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,\n 0x2000000, 0x2000400, 0x2000020, 0x2000420\n ];\n const pc2bytes6 = [\n 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,\n 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002\n ];\n const pc2bytes7 = [\n 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,\n 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800\n ];\n const pc2bytes8 = [\n 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,\n 0x2000002, 0x2040002, 0x2000002, 0x2040002\n ];\n const pc2bytes9 = [\n 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,\n 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408\n ];\n const pc2bytes10 = [\n 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,\n 0x102000, 0x102020, 0x102000, 0x102020\n ];\n const pc2bytes11 = [\n 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,\n 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200\n ];\n const pc2bytes12 = [\n 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,\n 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010\n ];\n const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];\n\n //how many iterations (1 for des, 3 for triple des)\n const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n //stores the return keys\n const keys = new Array(32 * iterations);\n //now define the left shifts which need to be done\n const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n //other variables\n let lefttemp;\n let righttemp;\n let m = 0;\n let n = 0;\n let temp;\n\n for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations\n let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];\n\n temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= temp;\n left ^= (temp << 4);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= temp;\n left ^= (temp << 2);\n temp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= temp;\n right ^= (temp << -16);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n temp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= temp;\n right ^= (temp << 8);\n temp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= temp;\n left ^= (temp << 1);\n\n //the right side needs to be shifted and to get the last four bits of the left side\n temp = (left << 8) | ((right >>> 20) & 0x000000f0);\n //left needs to be put upside down\n left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);\n right = temp;\n\n //now go through and perform these shifts on the left and right keys\n for (let i = 0; i < shifts.length; i++) {\n //shift the keys either one or two bits to the left\n if (shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n //now apply PC-2, in such a way that E is easier when encrypting or decrypting\n //this conversion will look like PC-2 except only the last 6 bits of each byte are used\n //rather than 48 consecutive bits and the order of lines will be according to\n //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7\n lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(\n left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &\n 0xf];\n righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |\n pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf];\n temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;\n keys[n++] = lefttemp ^ temp;\n keys[n++] = righttemp ^ (temp << 16);\n }\n } //for each iterations\n //return the keys we've created\n return keys;\n} //end of desCreateKeys\n\n\nfunction desAddPadding(message, padding) {\n const padLength = 8 - (message.length % 8);\n\n let pad;\n if (padding === 2 && (padLength < 8)) { //pad the message with spaces\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { //PKCS7 padding\n pad = padLength;\n } else if (!padding && (padLength < 8)) { //pad the message out with null bytes\n pad = 0;\n } else if (padLength === 8) {\n return message;\n } else {\n throw new Error('des: invalid padding');\n }\n\n const paddedMessage = new Uint8Array(message.length + padLength);\n for (let i = 0; i < message.length; i++) {\n paddedMessage[i] = message[i];\n }\n for (let j = 0; j < padLength; j++) {\n paddedMessage[message.length + j] = pad;\n }\n\n return paddedMessage;\n}\n\nfunction desRemovePadding(message, padding) {\n let padLength = null;\n let pad;\n if (padding === 2) { // space padded\n pad = ' '.charCodeAt(0);\n } else if (padding === 1) { // PKCS7\n padLength = message[message.length - 1];\n } else if (!padding) { // null padding\n pad = 0;\n } else {\n throw new Error('des: invalid padding');\n }\n\n if (!padLength) {\n padLength = 1;\n while (message[message.length - padLength] === pad) {\n padLength++;\n }\n padLength--;\n }\n\n return message.subarray(0, message.length - padLength);\n}\n\n// added by Recurity Labs\n\nexport function TripleDES(key) {\n this.key = [];\n\n for (let i = 0; i < 3; i++) {\n this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));\n }\n\n this.encrypt = function(block) {\n return des(\n desCreateKeys(this.key[2]),\n des(\n desCreateKeys(this.key[1]),\n des(\n desCreateKeys(this.key[0]),\n block, true, 0, null, null\n ),\n false, 0, null, null\n ), true, 0, null, null\n );\n };\n}\n\nTripleDES.keySize = TripleDES.prototype.keySize = 24;\nTripleDES.blockSize = TripleDES.prototype.blockSize = 8;\n\n// This is \"original\" DES\n\nexport function DES(key) {\n this.key = key;\n\n this.encrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, true, 0, null, padding);\n };\n\n this.decrypt = function(block, padding) {\n const keys = desCreateKeys(this.key);\n return des(keys, block, false, 0, null, padding);\n };\n}\n","// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2010 pjacobs@xeekr.com . All rights reserved.\n\n// Modified by Recurity Labs GmbH\n\n// fixed/modified by Herbert Hanewinkel, www.haneWIN.de\n// check www.haneWIN.de for the latest version\n\n// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.\n// CAST-128 is a common OpenPGP cipher.\n\n\n// CAST5 constructor\n\nfunction OpenPGPSymEncCAST5() {\n this.BlockSize = 8;\n this.KeySize = 16;\n\n this.setKey = function(key) {\n this.masking = new Array(16);\n this.rotate = new Array(16);\n\n this.reset();\n\n if (key.length === this.KeySize) {\n this.keySchedule(key);\n } else {\n throw new Error('CAST-128: keys must be 16 bytes');\n }\n return true;\n };\n\n this.reset = function() {\n for (let i = 0; i < 16; i++) {\n this.masking[i] = 0;\n this.rotate[i] = 0;\n }\n };\n\n this.getBlockSize = function() {\n return this.BlockSize;\n };\n\n this.encrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >>> 16) & 255;\n dst[i + 6] = (l >>> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n\n this.decrypt = function(src) {\n const dst = new Array(src.length);\n\n for (let i = 0; i < src.length; i += 8) {\n let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];\n let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];\n let t;\n\n t = r;\n r = l ^ f1(r, this.masking[15], this.rotate[15]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[14], this.rotate[14]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[13], this.rotate[13]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[12], this.rotate[12]);\n l = t;\n\n t = r;\n r = l ^ f3(r, this.masking[11], this.rotate[11]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[10], this.rotate[10]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[9], this.rotate[9]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[8], this.rotate[8]);\n l = t;\n\n t = r;\n r = l ^ f2(r, this.masking[7], this.rotate[7]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[6], this.rotate[6]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[5], this.rotate[5]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[4], this.rotate[4]);\n l = t;\n\n t = r;\n r = l ^ f1(r, this.masking[3], this.rotate[3]);\n l = t;\n t = r;\n r = l ^ f3(r, this.masking[2], this.rotate[2]);\n l = t;\n t = r;\n r = l ^ f2(r, this.masking[1], this.rotate[1]);\n l = t;\n t = r;\n r = l ^ f1(r, this.masking[0], this.rotate[0]);\n l = t;\n\n dst[i] = (r >>> 24) & 255;\n dst[i + 1] = (r >>> 16) & 255;\n dst[i + 2] = (r >>> 8) & 255;\n dst[i + 3] = r & 255;\n dst[i + 4] = (l >>> 24) & 255;\n dst[i + 5] = (l >> 16) & 255;\n dst[i + 6] = (l >> 8) & 255;\n dst[i + 7] = l & 255;\n }\n\n return dst;\n };\n const scheduleA = new Array(4);\n\n scheduleA[0] = new Array(4);\n scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];\n scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n scheduleA[1] = new Array(4);\n scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n scheduleA[2] = new Array(4);\n scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];\n scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];\n scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];\n scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];\n\n\n scheduleA[3] = new Array(4);\n scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];\n scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];\n scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];\n scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];\n\n const scheduleB = new Array(4);\n\n scheduleB[0] = new Array(4);\n scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];\n scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];\n scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];\n scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];\n\n scheduleB[1] = new Array(4);\n scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];\n scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];\n scheduleB[1][2] = [7, 6, 8, 9, 3];\n scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];\n\n\n scheduleB[2] = new Array(4);\n scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];\n scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];\n scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];\n scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];\n\n\n scheduleB[3] = new Array(4);\n scheduleB[3][0] = [8, 9, 7, 6, 3];\n scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];\n scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];\n scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];\n\n // changed 'in' to 'inn' (in javascript 'in' is a reserved word)\n this.keySchedule = function(inn) {\n const t = new Array(8);\n const k = new Array(32);\n\n let j;\n\n for (let i = 0; i < 4; i++) {\n j = i * 4;\n t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];\n }\n\n const x = [6, 7, 4, 5];\n let ki = 0;\n let w;\n\n for (let half = 0; half < 2; half++) {\n for (let round = 0; round < 4; round++) {\n for (j = 0; j < 4; j++) {\n const a = scheduleA[round][j];\n w = t[a[1]];\n\n w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];\n w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];\n w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];\n w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];\n w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];\n t[a[0]] = w;\n }\n\n for (j = 0; j < 4; j++) {\n const b = scheduleB[round][j];\n w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];\n\n w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];\n w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];\n w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];\n w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];\n k[ki] = w;\n ki++;\n }\n }\n }\n\n for (let i = 0; i < 16; i++) {\n this.masking[i] = k[i];\n this.rotate[i] = k[16 + i] & 0x1f;\n }\n };\n\n // These are the three 'f' functions. See RFC 2144, section 2.2.\n\n function f1(d, m, r) {\n const t = m + d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];\n }\n\n function f2(d, m, r) {\n const t = m ^ d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];\n }\n\n function f3(d, m, r) {\n const t = m - d;\n const I = (t << r) | (t >>> (32 - r));\n return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];\n }\n\n const sBox = new Array(8);\n sBox[0] = [\n 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,\n 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,\n 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,\n 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,\n 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,\n 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,\n 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,\n 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,\n 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,\n 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,\n 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,\n 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,\n 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,\n 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,\n 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,\n 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,\n 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,\n 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,\n 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,\n 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,\n 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,\n 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,\n 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,\n 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,\n 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,\n 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,\n 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,\n 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,\n 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,\n 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,\n 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,\n 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf\n ];\n\n sBox[1] = [\n 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,\n 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,\n 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,\n 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,\n 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,\n 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,\n 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,\n 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,\n 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,\n 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,\n 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,\n 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,\n 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,\n 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,\n 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,\n 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,\n 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,\n 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,\n 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,\n 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,\n 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,\n 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,\n 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,\n 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,\n 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,\n 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,\n 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,\n 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,\n 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,\n 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,\n 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,\n 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1\n ];\n\n sBox[2] = [\n 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,\n 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,\n 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,\n 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,\n 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,\n 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,\n 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,\n 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,\n 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,\n 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,\n 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,\n 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,\n 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,\n 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,\n 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,\n 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,\n 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,\n 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,\n 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,\n 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,\n 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,\n 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,\n 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,\n 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,\n 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,\n 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,\n 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,\n 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,\n 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,\n 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,\n 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,\n 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783\n ];\n\n sBox[3] = [\n 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,\n 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,\n 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,\n 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,\n 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,\n 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,\n 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,\n 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,\n 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,\n 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,\n 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,\n 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,\n 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,\n 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,\n 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,\n 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,\n 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,\n 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,\n 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,\n 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,\n 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,\n 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,\n 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,\n 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,\n 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,\n 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,\n 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,\n 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,\n 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,\n 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,\n 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,\n 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2\n ];\n\n sBox[4] = [\n 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,\n 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,\n 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,\n 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,\n 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,\n 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,\n 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,\n 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,\n 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,\n 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,\n 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,\n 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,\n 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,\n 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,\n 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,\n 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,\n 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,\n 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,\n 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,\n 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,\n 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,\n 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,\n 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,\n 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,\n 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,\n 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,\n 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,\n 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,\n 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,\n 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,\n 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,\n 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4\n ];\n\n sBox[5] = [\n 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,\n 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,\n 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,\n 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,\n 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,\n 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,\n 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,\n 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,\n 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,\n 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,\n 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,\n 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,\n 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,\n 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,\n 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,\n 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,\n 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,\n 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,\n 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,\n 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,\n 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,\n 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,\n 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,\n 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,\n 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,\n 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,\n 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,\n 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,\n 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,\n 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,\n 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,\n 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f\n ];\n\n sBox[6] = [\n 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,\n 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,\n 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,\n 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,\n 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,\n 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,\n 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,\n 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,\n 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,\n 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,\n 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,\n 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,\n 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,\n 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,\n 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,\n 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,\n 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,\n 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,\n 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,\n 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,\n 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,\n 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,\n 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,\n 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,\n 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,\n 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,\n 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,\n 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,\n 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,\n 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,\n 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,\n 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3\n ];\n\n sBox[7] = [\n 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,\n 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,\n 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,\n 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,\n 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,\n 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,\n 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,\n 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,\n 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,\n 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,\n 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,\n 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,\n 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,\n 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,\n 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,\n 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,\n 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,\n 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,\n 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,\n 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,\n 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,\n 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,\n 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,\n 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,\n 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,\n 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,\n 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,\n 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,\n 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,\n 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,\n 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,\n 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e\n ];\n}\n\nfunction CAST5(key) {\n this.cast5 = new OpenPGPSymEncCAST5();\n this.cast5.setKey(key);\n\n this.encrypt = function(block) {\n return this.cast5.encrypt(block);\n };\n}\n\nCAST5.blockSize = CAST5.prototype.blockSize = 8;\nCAST5.keySize = CAST5.prototype.keySize = 16;\n\nexport default CAST5;\n","/* eslint-disable no-mixed-operators, no-fallthrough */\n\n\n/* Modified by Recurity Labs GmbH\n *\n * Cipher.js\n * A block-cipher algorithm implementation on JavaScript\n * See Cipher.readme.txt for further information.\n *\n * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]\n * This script file is distributed under the LGPL\n *\n * ACKNOWLEDGMENT\n *\n * The main subroutines are written by Michiel van Everdingen.\n *\n * Michiel van Everdingen\n * http://home.versatel.nl/MAvanEverdingen/index.html\n *\n * All rights for these routines are reserved to Michiel van Everdingen.\n *\n */\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//Math\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst MAXINT = 0xFFFFFFFF;\n\nfunction rotw(w, n) {\n return (w << n | w >>> (32 - n)) & MAXINT;\n}\n\nfunction getW(a, i) {\n return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;\n}\n\nfunction setW(a, i, w) {\n a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);\n}\n\nfunction getB(x, n) {\n return (x >>> (n * 8)) & 0xFF;\n}\n\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Twofish\n// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction createTwofish() {\n //\n let keyBytes = null;\n let dataBytes = null;\n let dataOffset = -1;\n // var dataLength = -1;\n // var idx2 = -1;\n //\n\n let tfsKey = [];\n let tfsM = [\n [],\n [],\n [],\n []\n ];\n\n function tfsInit(key) {\n keyBytes = key;\n let i;\n let a;\n let b;\n let c;\n let d;\n const meKey = [];\n const moKey = [];\n const inKey = [];\n let kLen;\n const sKey = [];\n let f01;\n let f5b;\n let fef;\n\n const q0 = [\n [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],\n [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]\n ];\n const q1 = [\n [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],\n [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]\n ];\n const q2 = [\n [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],\n [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]\n ];\n const q3 = [\n [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],\n [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]\n ];\n const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];\n const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];\n const q = [\n [],\n []\n ];\n const m = [\n [],\n [],\n [],\n []\n ];\n\n function ffm5b(x) {\n return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];\n }\n\n function ffmEf(x) {\n return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];\n }\n\n function mdsRem(p, q) {\n let i;\n let t;\n let u;\n for (i = 0; i < 8; i++) {\n t = q >>> 24;\n q = ((q << 8) & MAXINT) | p >>> 24;\n p = (p << 8) & MAXINT;\n u = t << 1;\n if (t & 128) {\n u ^= 333;\n }\n q ^= t ^ (u << 16);\n u ^= t >>> 1;\n if (t & 1) {\n u ^= 166;\n }\n q ^= u << 24 | u << 8;\n }\n return q;\n }\n\n function qp(n, x) {\n const a = x >> 4;\n const b = x & 15;\n const c = q0[n][a ^ b];\n const d = q1[n][ror4[b] ^ ashx[a]];\n return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];\n }\n\n function hFun(x, key) {\n let a = getB(x, 0);\n let b = getB(x, 1);\n let c = getB(x, 2);\n let d = getB(x, 3);\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(key[3], 0);\n b = q[0][b] ^ getB(key[3], 1);\n c = q[0][c] ^ getB(key[3], 2);\n d = q[1][d] ^ getB(key[3], 3);\n case 3:\n a = q[1][a] ^ getB(key[2], 0);\n b = q[1][b] ^ getB(key[2], 1);\n c = q[0][c] ^ getB(key[2], 2);\n d = q[0][d] ^ getB(key[2], 3);\n case 2:\n a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);\n b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);\n c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);\n d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);\n }\n return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];\n }\n\n keyBytes = keyBytes.slice(0, 32);\n i = keyBytes.length;\n while (i !== 16 && i !== 24 && i !== 32) {\n keyBytes[i++] = 0;\n }\n\n for (i = 0; i < keyBytes.length; i += 4) {\n inKey[i >> 2] = getW(keyBytes, i);\n }\n for (i = 0; i < 256; i++) {\n q[0][i] = qp(0, i);\n q[1][i] = qp(1, i);\n }\n for (i = 0; i < 256; i++) {\n f01 = q[1][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);\n m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);\n f01 = q[0][i];\n f5b = ffm5b(f01);\n fef = ffmEf(f01);\n m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);\n m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);\n }\n\n kLen = inKey.length / 2;\n for (i = 0; i < kLen; i++) {\n a = inKey[i + i];\n meKey[i] = a;\n b = inKey[i + i + 1];\n moKey[i] = b;\n sKey[kLen - i - 1] = mdsRem(a, b);\n }\n for (i = 0; i < 40; i += 2) {\n a = 0x1010101 * i;\n b = a + 0x1010101;\n a = hFun(a, meKey);\n b = rotw(hFun(b, moKey), 8);\n tfsKey[i] = (a + b) & MAXINT;\n tfsKey[i + 1] = rotw(a + 2 * b, 9);\n }\n for (i = 0; i < 256; i++) {\n a = b = c = d = i;\n switch (kLen) {\n case 4:\n a = q[1][a] ^ getB(sKey[3], 0);\n b = q[0][b] ^ getB(sKey[3], 1);\n c = q[0][c] ^ getB(sKey[3], 2);\n d = q[1][d] ^ getB(sKey[3], 3);\n case 3:\n a = q[1][a] ^ getB(sKey[2], 0);\n b = q[1][b] ^ getB(sKey[2], 1);\n c = q[0][c] ^ getB(sKey[2], 2);\n d = q[0][d] ^ getB(sKey[2], 3);\n case 2:\n tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];\n tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];\n tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];\n tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];\n }\n }\n }\n\n function tfsG0(x) {\n return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];\n }\n\n function tfsG1(x) {\n return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];\n }\n\n function tfsFrnd(r, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);\n blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);\n blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;\n }\n\n function tfsIrnd(i, blk) {\n let a = tfsG0(blk[0]);\n let b = tfsG1(blk[1]);\n blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;\n blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);\n a = tfsG0(blk[2]);\n b = tfsG1(blk[3]);\n blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;\n blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);\n }\n\n function tfsClose() {\n tfsKey = [];\n tfsM = [\n [],\n [],\n [],\n []\n ];\n }\n\n function tfsEncrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[1],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[2],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];\n for (let j = 0; j < 8; j++) {\n tfsFrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);\n dataOffset += 16;\n return dataBytes;\n }\n\n function tfsDecrypt(data, offset) {\n dataBytes = data;\n dataOffset = offset;\n const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],\n getW(dataBytes, dataOffset + 4) ^ tfsKey[5],\n getW(dataBytes, dataOffset + 8) ^ tfsKey[6],\n getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];\n for (let j = 7; j >= 0; j--) {\n tfsIrnd(j, blk);\n }\n setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);\n setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);\n setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);\n setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);\n dataOffset += 16;\n }\n\n // added by Recurity Labs\n\n function tfsFinal() {\n return dataBytes;\n }\n\n return {\n name: 'twofish',\n blocksize: 128 / 8,\n open: tfsInit,\n close: tfsClose,\n encrypt: tfsEncrypt,\n decrypt: tfsDecrypt,\n // added by Recurity Labs\n finalize: tfsFinal\n };\n}\n\n// added by Recurity Labs\n\nfunction TF(key) {\n this.tf = createTwofish();\n this.tf.open(Array.from(key), 0);\n\n this.encrypt = function(block) {\n return this.tf.encrypt(Array.from(block), 0);\n };\n}\n\nTF.keySize = TF.prototype.keySize = 32;\nTF.blockSize = TF.prototype.blockSize = 16;\n\nexport default TF;\n","/* Modified by Recurity Labs GmbH\n *\n * Originally written by nklein software (nklein.com)\n */\n\n/*\n * Javascript implementation based on Bruce Schneier's reference implementation.\n *\n *\n * The constructor doesn't do much of anything. It's just here\n * so we can start defining properties and methods and such.\n */\nfunction Blowfish() {}\n\n/*\n * Declare the block size so that protocols know what size\n * Initialization Vector (IV) they will need.\n */\nBlowfish.prototype.BLOCKSIZE = 8;\n\n/*\n * These are the default SBOXES.\n */\nBlowfish.prototype.SBOXES = [\n [\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,\n 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,\n 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,\n 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,\n 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,\n 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,\n 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,\n 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,\n 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,\n 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,\n 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,\n 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,\n 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,\n 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,\n 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,\n 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,\n 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,\n 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,\n 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,\n 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,\n 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,\n 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a\n ],\n [\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,\n 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,\n 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,\n 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,\n 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,\n 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,\n 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,\n 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,\n 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,\n 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,\n 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,\n 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,\n 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,\n 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,\n 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,\n 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,\n 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,\n 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,\n 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,\n 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,\n 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,\n 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7\n ],\n [\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,\n 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,\n 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,\n 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,\n 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,\n 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,\n 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,\n 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,\n 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,\n 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,\n 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,\n 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,\n 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,\n 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,\n 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,\n 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,\n 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,\n 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,\n 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,\n 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,\n 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,\n 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0\n ],\n [\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,\n 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,\n 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,\n 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,\n 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,\n 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,\n 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,\n 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,\n 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,\n 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,\n 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,\n 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,\n 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,\n 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,\n 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,\n 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,\n 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,\n 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,\n 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,\n 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,\n 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,\n 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6\n ]\n];\n\n//*\n//* This is the default PARRAY\n//*\nBlowfish.prototype.PARRAY = [\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,\n 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b\n];\n\n//*\n//* This is the number of rounds the cipher will go\n//*\nBlowfish.prototype.NN = 16;\n\n//*\n//* This function is needed to get rid of problems\n//* with the high-bit getting set. If we don't do\n//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not\n//* equal to ( bb & 0x00FFFFFFFF ) even when they\n//* agree bit-for-bit for the first 32 bits.\n//*\nBlowfish.prototype._clean = function(xx) {\n if (xx < 0) {\n const yy = xx & 0x7FFFFFFF;\n xx = yy + 0x80000000;\n }\n return xx;\n};\n\n//*\n//* This is the mixing function that uses the sboxes\n//*\nBlowfish.prototype._F = function(xx) {\n let yy;\n\n const dd = xx & 0x00FF;\n xx >>>= 8;\n const cc = xx & 0x00FF;\n xx >>>= 8;\n const bb = xx & 0x00FF;\n xx >>>= 8;\n const aa = xx & 0x00FF;\n\n yy = this.sboxes[0][aa] + this.sboxes[1][bb];\n yy ^= this.sboxes[2][cc];\n yy += this.sboxes[3][dd];\n\n return yy;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and does NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._encryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = 0; ii < this.NN; ++ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[this.NN + 0];\n dataR ^= this.parray[this.NN + 1];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a vector of numbers and turns them\n//* into long words so that they can be processed by the\n//* real algorithm.\n//*\n//* Maybe I should make the real algorithm above take a vector\n//* instead. That will involve more looping, but it won't require\n//* the F() method to deconstruct the vector.\n//*\nBlowfish.prototype.encryptBlock = function(vector) {\n let ii;\n const vals = [0, 0];\n const off = this.BLOCKSIZE / 2;\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);\n vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);\n }\n\n this._encryptBlock(vals);\n\n const ret = [];\n for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {\n ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);\n ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);\n // vals[ 0 ] = ( vals[ 0 ] >>> 8 );\n // vals[ 1 ] = ( vals[ 1 ] >>> 8 );\n }\n\n return ret;\n};\n\n//*\n//* This method takes an array with two values, left and right\n//* and undoes NN rounds of Blowfish on them.\n//*\nBlowfish.prototype._decryptBlock = function(vals) {\n let dataL = vals[0];\n let dataR = vals[1];\n\n let ii;\n\n for (ii = this.NN + 1; ii > 1; --ii) {\n dataL ^= this.parray[ii];\n dataR = this._F(dataL) ^ dataR;\n\n const tmp = dataL;\n dataL = dataR;\n dataR = tmp;\n }\n\n dataL ^= this.parray[1];\n dataR ^= this.parray[0];\n\n vals[0] = this._clean(dataR);\n vals[1] = this._clean(dataL);\n};\n\n//*\n//* This method takes a key array and initializes the\n//* sboxes and parray for this encryption.\n//*\nBlowfish.prototype.init = function(key) {\n let ii;\n let jj = 0;\n\n this.parray = [];\n for (ii = 0; ii < this.NN + 2; ++ii) {\n let data = 0x00000000;\n for (let kk = 0; kk < 4; ++kk) {\n data = (data << 8) | (key[jj] & 0x00FF);\n if (++jj >= key.length) {\n jj = 0;\n }\n }\n this.parray[ii] = this.PARRAY[ii] ^ data;\n }\n\n this.sboxes = [];\n for (ii = 0; ii < 4; ++ii) {\n this.sboxes[ii] = [];\n for (jj = 0; jj < 256; ++jj) {\n this.sboxes[ii][jj] = this.SBOXES[ii][jj];\n }\n }\n\n const vals = [0x00000000, 0x00000000];\n\n for (ii = 0; ii < this.NN + 2; ii += 2) {\n this._encryptBlock(vals);\n this.parray[ii + 0] = vals[0];\n this.parray[ii + 1] = vals[1];\n }\n\n for (ii = 0; ii < 4; ++ii) {\n for (jj = 0; jj < 256; jj += 2) {\n this._encryptBlock(vals);\n this.sboxes[ii][jj + 0] = vals[0];\n this.sboxes[ii][jj + 1] = vals[1];\n }\n }\n};\n\n// added by Recurity Labs\nfunction BF(key) {\n this.bf = new Blowfish();\n this.bf.init(key);\n\n this.encrypt = function(block) {\n return this.bf.encryptBlock(block);\n };\n}\n\nBF.keySize = BF.prototype.keySize = 16;\nBF.blockSize = BF.prototype.blockSize = 8;\n\nexport default BF;\n","/**\n * This file is needed to dynamic import the legacy ciphers.\n * Separate dynamic imports are not convenient as they result in multiple chunks.\n */\n\nimport { TripleDES } from './des';\nimport CAST5 from './cast5';\nimport TwoFish from './twofish';\nimport BlowFish from './blowfish';\nimport enums from '../../enums';\n\nexport const legacyCiphers = new Map([\n [enums.symmetric.tripledes, TripleDES],\n [enums.symmetric.cast5, CAST5],\n [enums.symmetric.blowfish, BlowFish],\n [enums.symmetric.twofish, TwoFish]\n]);\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms.\n// Initial state\nconst SHA1_IV = /* @__PURE__ */ new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA1 extends HashMD {\n constructor() {\n super(64, 20, 8, false);\n this.A = SHA1_IV[0] | 0;\n this.B = SHA1_IV[1] | 0;\n this.C = SHA1_IV[2] | 0;\n this.D = SHA1_IV[3] | 0;\n this.E = SHA1_IV[4] | 0;\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n SHA1_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * SHA1 (RFC 3174) hash function.\n * It was cryptographically broken: prefer newer algorithms.\n * @param message - data that would be hashed\n */\nexport const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());\n//# sourceMappingURL=sha1.js.map","import { HashMD } from './_md.js';\nimport { rotl, wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n R_BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.js.map","/**\n * This file is needed to dynamic import the noble-hashes.\n * Separate dynamic imports are not convenient as they result in too many chunks,\n * which share a lot of code anyway.\n */\n\nimport { sha1 } from '@noble/hashes/sha1';\nimport { sha224, sha256 } from '@noble/hashes/sha256';\nimport { sha384, sha512 } from '@noble/hashes/sha512';\nimport { sha3_256, sha3_512 } from '@noble/hashes/sha3';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\n\nexport const nobleHashes = new Map(Object.entries({\n sha1,\n sha224,\n sha256,\n sha384,\n sha512,\n sha3_256,\n sha3_512,\n ripemd160\n}));\n","// Adapted from the reference implementation in RFC7693\n// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes\n\n// Uint64 values are represented using two Uint32s, stored as little endian\n// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays\n// need to be manually handled\n\n// 64-bit unsigned addition (little endian, in place)\n// Sets a[i,i+1] += b[j,j+1]\n// `a` and `b` must be Uint32Array(2)\nfunction ADD64 (a, i, b, j) {\n a[i] += b[j];\n a[i+1] += b[j+1] + (a[i] < b[j]); // add carry\n}\n\n// Increment 64-bit little-endian unsigned value by `c` (in place)\n// `a` must be Uint32Array(2)\nfunction INC64 (a, c) {\n a[0] += c;\n a[1] += (a[0] < c);\n}\n\n// G Mixing function\n// The ROTRs are inlined for speed\nfunction G (v, m, a, b, c, d, ix, iy) {\n ADD64(v, a, v, b) // v[a,a+1] += v[b,b+1]\n ADD64(v, a, m, ix) // v[a, a+1] += x ... x0\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits\n let xor0 = v[d] ^ v[a]\n let xor1 = v[d + 1] ^ v[a + 1]\n v[d] = xor1\n v[d + 1] = xor0\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor0 >>> 24) ^ (xor1 << 8)\n v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)\n\n ADD64(v, a, v, b)\n ADD64(v, a, m, iy)\n\n // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits\n xor0 = v[d] ^ v[a]\n xor1 = v[d + 1] ^ v[a + 1]\n v[d] = (xor0 >>> 16) ^ (xor1 << 16)\n v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)\n\n ADD64(v, c, v, d)\n\n // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits\n xor0 = v[b] ^ v[c]\n xor1 = v[b + 1] ^ v[c + 1]\n v[b] = (xor1 >>> 31) ^ (xor0 << 1)\n v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)\n}\n\n// Initialization Vector\nconst BLAKE2B_IV32 = new Uint32Array([\n 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,\n 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,\n 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,\n 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19\n])\n\n// These are offsets into a Uint64 buffer.\n// Multiply them all by 2 to make them offsets into a Uint32 buffer\nconst SIGMA = new Uint8Array([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3\n].map(x => x * 2))\n\n// Compression function. 'last' flag indicates last block.\n// Note: we're representing 16 uint64s as 32 uint32s\nfunction compress(S, last) {\n const v = new Uint32Array(32)\n const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32)\n\n // init work variables\n for (let i = 0; i < 16; i++) {\n v[i] = S.h[i]\n v[i + 16] = BLAKE2B_IV32[i]\n }\n\n // low 64 bits of offset\n v[24] ^= S.t0[0]\n v[25] ^= S.t0[1]\n // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1\n\n // if last block\n const f0 = last ? 0xFFFFFFFF : 0;\n v[28] ^= f0;\n v[29] ^= f0;\n\n // twelve rounds of mixing\n for (let i = 0; i < 12; i++) {\n // ROUND(r)\n const i16 = i << 4;\n G(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1])\n G(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3])\n G(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5])\n G(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7])\n G(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9])\n G(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11])\n G(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13])\n G(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15])\n }\n\n for (let i = 0; i < 16; i++) {\n S.h[i] ^= v[i] ^ v[i + 16]\n }\n}\n\n// Creates a BLAKE2b hashing context\n// Requires an output length between 1 and 64 bytes\n// Takes an optional Uint8Array key\nclass Blake2b {\n constructor(outlen, key, salt, personal) {\n const params = new Uint8Array(64)\n // 0: outlen, keylen, fanout, depth\n // 4: leaf length, sequential mode\n // 8: node offset\n // 12: node offset\n // 16: node depth, inner length, rfu\n // 20: rfu\n // 24: rfu\n // 28: rfu\n // 32: salt\n // 36: salt\n // 40: salt\n // 44: salt\n // 48: personal\n // 52: personal\n // 56: personal\n // 60: personal\n\n // init internal state\n this.S = {\n b: new Uint8Array(BLOCKBYTES),\n h: new Uint32Array(OUTBYTES_MAX / 4),\n t0: new Uint32Array(2), // input counter `t`, lower 64-bits only\n c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`\n outlen // output length in bytes\n }\n\n // init parameter block\n params[0] = outlen\n if (key) params[1] = key.length\n params[2] = 1 // fanout\n params[3] = 1 // depth\n if (salt) params.set(salt, 32)\n if (personal) params.set(personal, 48)\n const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];\n }\n\n // key the hash, if applicable\n if (key) {\n const block = new Uint8Array(BLOCKBYTES)\n block.set(key)\n this.update(block)\n }\n }\n\n // Updates a BLAKE2b streaming hash\n // Requires Uint8Array (byte array)\n update(input) {\n if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')\n // for (let i = 0; i < input.length; i++) {\n // if (this.S.c === BLOCKBYTES) { // buffer full\n // INC64(this.S.t0, this.S.c) // add counters\n // compress(this.S, false)\n // this.S.c = 0 // empty buffer\n // }\n // this.S.b[this.S.c++] = input[i]\n // }\n let i = 0\n while(i < input.length) {\n if (this.S.c === BLOCKBYTES) { // buffer full\n INC64(this.S.t0, this.S.c) // add counters\n compress(this.S, false)\n this.S.c = 0 // empty buffer\n }\n let left = BLOCKBYTES - this.S.c\n this.S.b.set(input.subarray(i, i + left), this.S.c) // end index can be out of bounds\n const fill = Math.min(left, input.length - i)\n this.S.c += fill\n i += fill\n }\n return this\n }\n\n /**\n * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one\n * @param {Uint8Array} [prealloc] - optional preallocated buffer\n * @returns {ArrayBuffer} message digest\n */\n digest(prealloc) {\n INC64(this.S.t0, this.S.c) // mark last block offset\n\n // final block, padded\n this.S.b.fill(0, this.S.c);\n this.S.c = BLOCKBYTES;\n compress(this.S, true)\n\n const out = prealloc || new Uint8Array(this.S.outlen);\n for (let i = 0; i < this.S.outlen; i++) {\n // must be loaded individually since default Uint32 endianness is platform dependant\n out[i] = this.S.h[i >> 2] >> (8 * (i & 3))\n }\n this.S.h = null; // prevent calling `update` after `digest`\n return out.buffer;\n }\n}\n\n\nexport default function createHash(outlen, key, salt, personal) {\n if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)\n if (key) {\n if (!(key instanceof Uint8Array)) throw new Error('key must be Uint8Array or Buffer')\n if (key.length > KEYBYTES_MAX) throw new Error(`key size must be at most ${KEYBYTES_MAX} (given: ${key.length})`)\n }\n if (salt) {\n if (!(salt instanceof Uint8Array)) throw new Error('salt must be Uint8Array or Buffer')\n if (salt.length !== SALTBYTES) throw new Error(`salt must be exactly ${SALTBYTES} (given: ${salt.length}`)\n }\n if (personal) {\n if (!(personal instanceof Uint8Array)) throw new Error('personal must be Uint8Array or Buffer')\n if (personal.length !== PERSONALBYTES) throw new Error(`salt must be exactly ${PERSONALBYTES} (given: ${personal.length}`)\n }\n\n return new Blake2b(outlen, key, salt, personal)\n}\n\nconst OUTBYTES_MAX = 64;\nconst KEYBYTES_MAX = 64;\nconst SALTBYTES = 16;\nconst PERSONALBYTES = 16;\nconst BLOCKBYTES = 128;\n\n","import blake2b from \"./blake2b.js\"\nconst TYPE = 2; // Argon2id\nconst VERSION = 0x13;\nconst TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;\nconst SALTBYTES_MIN = 8;\nconst passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst passwordBYTES_MIN = 8;\nconst MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;\nconst ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)\nconst SECRETBYTES_MAX = 32; // key (optional)\n\nconst ARGON2_BLOCK_SIZE = 1024;\nconst ARGON2_PREHASH_DIGEST_LENGTH = 64;\n\nconst isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;\n\n// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])\nfunction LE32(buf, n, i) {\n buf[i+0] = n;\n buf[i+1] = n >> 8;\n buf[i+2] = n >> 16;\n buf[i+3] = n >> 24;\n return buf;\n}\n\n/**\n * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])\n * @param {Uint8Array} buf\n * @param {Number} n\n * @param {Number} i\n */\nfunction LE64(buf, n, i) {\n if (n > Number.MAX_SAFE_INTEGER) throw new Error(\"LE64: large numbers unsupported\");\n // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations\n // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)\n // so we manually extract each byte\n let remainder = n;\n for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER\n buf[offset] = remainder; // implicit & 0xff\n remainder = (remainder - buf[offset]) / 256;\n }\n return buf;\n}\n\n/**\n * Variable-Length Hash Function H'\n * @param {Number} outlen - T\n * @param {Uint8Array} X - value to hash\n * @param {Uint8Array} res - output buffer, of length `outlength` or larger\n */\nfunction H_(outlen, X, res) {\n const V = new Uint8Array(64); // no need to keep around all V_i\n\n const V1_in = new Uint8Array(4 + X.length);\n LE32(V1_in, outlen, 0);\n V1_in.set(X, 4);\n if (outlen <= 64) {\n // H'^T(A) = H^T(LE32(T)||A)\n blake2b(outlen).update(V1_in).digest(res);\n return res\n }\n\n const r = Math.ceil(outlen / 32) - 2;\n\n // Let V_i be a 64-byte block and W_i be its first 32 bytes.\n // V_1 = H^(64)(LE32(T)||A)\n // V_2 = H^(64)(V_1)\n // ...\n // V_r = H^(64)(V_{r-1})\n // V_{r+1} = H^(T-32*r)(V_{r})\n // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}\n for (let i = 0; i < r; i++) {\n blake2b(64).update(i === 0 ? V1_in : V).digest(V);\n // store W_i in result buffer already\n res.set(V.subarray(0, 32), i*32)\n }\n // V_{r+1}\n const V_r1 = new Uint8Array(blake2b(outlen - 32*r).update(V).digest());\n res.set(V_r1, r*32);\n\n return res;\n}\n\n// compute buf = xs ^ ys\nfunction XOR(wasmContext, buf, xs, ys) {\n wasmContext.fn.XOR(\n buf.byteOffset,\n xs.byteOffset,\n ys.byteOffset,\n );\n return buf\n}\n\n/**\n * @param {Uint8Array} X (read-only)\n * @param {Uint8Array} Y (read-only)\n * @param {Uint8Array} R - output buffer\n * @returns\n */\nfunction G(wasmContext, X, Y, R) {\n wasmContext.fn.G(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\nfunction G2(wasmContext, X, Y, R) {\n wasmContext.fn.G2(\n X.byteOffset,\n Y.byteOffset,\n R.byteOffset,\n wasmContext.refs.gZ.byteOffset\n );\n return R;\n}\n\n// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.\nfunction* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {\n // For each segment, we do the following. First, we compute the value Z as:\n // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )\n wasmContext.refs.prngTmp.fill(0);\n const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);\n LE64(Z, pass, 0);\n LE64(Z, lane, 8);\n LE64(Z, slice, 16);\n LE64(Z, m_, 24);\n LE64(Z, totalPasses, 32);\n LE64(Z, TYPE, 40);\n\n // Then we compute q/(128*SL) 1024-byte values\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),\n // ...,\n // G( ZERO(1024),\n // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),\n for(let i = 1; i <= segmentLength; i++) {\n // tmp.set(Z); // no need to re-copy\n LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed\n const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );\n\n // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2\n // NB: the first generated pair must be used for the first block of the segment, and so on.\n // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.\n for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {\n yield g2.subarray(k, k+8);\n }\n }\n return [];\n}\n\nfunction validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {\n const assertLength = (name, value, min, max) => {\n if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }\n }\n\n if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');\n assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);\n assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);\n assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);\n assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);\n // optional fields\n ad && assertLength('associated data', ad, 0, ADBYTES_MAX);\n secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);\n\n return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };\n}\n\nconst KB = 1024;\nconst WASM_PAGE_SIZE = 64 * KB;\n\nexport default function argon2id(params, { memory, instance: wasmInstance }) {\n if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system\n\n const ctx = validateParams({ type: TYPE, version: VERSION, ...params });\n\n const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;\n const wasmRefs = {};\n const wasmFn = {};\n wasmFn.G = wasmG;\n wasmFn.G2 = wasmG2;\n wasmFn.XOR = wasmXOR;\n\n // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.\n const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));\n const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references\n if (memory.buffer.byteLength < requiredMemory) {\n const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE)\n // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.\n // Otherwise, the operation fails, and the original memory can still be used.\n memory.grow(missing)\n }\n\n let offset = 0;\n // Init wasm memory needed in other functions\n wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;\n wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;\n wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;\n wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;\n // Init wasm memory needed locally\n const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;\n const wasmContext = { fn: wasmFn, refs: wasmRefs };\n const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;\n const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);\n const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);\n\n // 1. Establish H_0\n const H0 = getH0(ctx);\n\n // 2. Allocate the memory as m' 1024-byte blocks\n // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.\n const q = m_ / ctx.lanes;\n const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));\n const initBlock = (i, j) => {\n B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);\n return B[i][j];\n }\n\n for (let i = 0; i < ctx.lanes; i++) {\n // const LEi = LE0; // since p = 1 for us\n const tmp = new Uint8Array(H0.length + 8);\n // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p\n // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))\n tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));\n // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p\n // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))\n LE32(tmp, 1, H0.length);\n H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));\n }\n\n // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2\n // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes\n // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.\n const SL = 4; // vertical slices\n const segmentLength = q / SL;\n for (let pass = 0; pass < ctx.passes; pass++) {\n // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel\n for (let sl = 0; sl < SL; sl++) {\n const isDataIndependent = pass === 0 && sl <= 1;\n for (let i = 0; i < ctx.lanes; i++) { // lane\n // On the first slice of the first pass, blocks 0 and 1 are already filled\n let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;\n // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)\n const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;\n for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {\n const j = sl * segmentLength + segmentOffset;\n const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]\n\n // we can assume the PRNG is never done\n const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength)\n const l = lz[0]; const z = lz[1];\n // for (let i = 0; i < p; i++ )\n // B[i][j] = G(B[i][j-1], B[l][z])\n // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.\n if (pass === 0) initBlock(i, j);\n G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);\n\n // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one\n if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j])\n }\n }\n }\n }\n\n // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:\n // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]\n const C = B[0][q-1];\n for(let i = 1; i < ctx.lanes; i++) {\n XOR(wasmContext, C, C, B[i][q-1])\n }\n\n const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));\n // clear memory since the module might be cached\n allocatedMemory.fill(0) // clear sensitive contents\n memory.grow(0) // allow deallocation\n // 8. The output tag is computed as H'^T(C).\n return tag;\n\n}\n\nfunction getH0(ctx) {\n const H = blake2b(ARGON2_PREHASH_DIGEST_LENGTH);\n const ZERO32 = new Uint8Array(4);\n const params = new Uint8Array(24);\n LE32(params, ctx.lanes, 0);\n LE32(params, ctx.tagLength, 4);\n LE32(params, ctx.memorySize, 8);\n LE32(params, ctx.passes, 12);\n LE32(params, ctx.version, 16);\n LE32(params, ctx.type, 20);\n\n const toHash = [params];\n if (ctx.password) {\n toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0))\n toHash.push(ctx.password)\n } else {\n toHash.push(ZERO32) // context.password.length\n }\n\n if (ctx.salt) {\n toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0))\n toHash.push(ctx.salt)\n } else {\n toHash.push(ZERO32) // context.salt.length\n }\n\n if (ctx.secret) {\n toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0))\n toHash.push(ctx.secret)\n // todo clear secret?\n } else {\n toHash.push(ZERO32) // context.secret.length\n }\n\n if (ctx.ad) {\n toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0))\n toHash.push(ctx.ad)\n } else {\n toHash.push(ZERO32) // context.ad.length\n }\n H.update(concatArrays(toHash))\n\n const outputBuffer = H.digest();\n return new Uint8Array(outputBuffer);\n}\n\nfunction concatArrays(arrays) {\n if (arrays.length === 1) return arrays[0];\n\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n if (!(arrays[i] instanceof Uint8Array)) {\n throw new Error('concatArrays: Data must be in the form of a Uint8Array');\n }\n\n totalLength += arrays[i].length;\n }\n\n const result = new Uint8Array(totalLength);\n let pos = 0;\n arrays.forEach((element) => {\n result.set(element, pos);\n pos += element.length;\n });\n\n return result;\n}\n","import argon2id from \"./argon2id.js\";\n\nlet isSIMDSupported;\nasync function wasmLoader(memory, getSIMD, getNonSIMD) {\n const importObject = { env: { memory } };\n if (isSIMDSupported === undefined) {\n try {\n const loaded = await getSIMD(importObject);\n isSIMDSupported = true;\n return loaded;\n } catch(e) {\n isSIMDSupported = false;\n }\n }\n\n const loader = isSIMDSupported ? getSIMD : getNonSIMD;\n return loader(importObject);\n}\n\nexport default async function setupWasm(getSIMD, getNonSIMD) {\n const memory = new WebAssembly.Memory({\n // in pages of 64KiB each\n // these values need to be compatible with those declared when building in `build-wasm`\n initial: 1040, // 65MB\n maximum: 65536, // 4GB\n });\n const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);\n\n /**\n * Argon2id hash function\n * @callback computeHash\n * @param {Object} params\n * @param {Uint8Array} params.password - password\n * @param {Uint8Array} params.salt - salt\n * @param {Integer} params.parallelism\n * @param {Integer} params.passes\n * @param {Integer} params.memorySize - in kibibytes\n * @param {Integer} params.tagLength - output tag length\n * @param {Uint8Array} [params.ad] - associated data (optional)\n * @param {Uint8Array} [params.secret] - secret data (optional)\n * @return {Uint8Array} argon2id hash\n */\n const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });\n\n return computeHash;\n}\n","import setupWasm from './lib/setup.js';\nimport wasmSIMD from './dist/simd.wasm';\nimport wasmNonSIMD from './dist/no-simd.wasm';\n\nconst loadWasm = async () => setupWasm(\n (instanceObject) => wasmSIMD(instanceObject),\n (instanceObject) => wasmNonSIMD(instanceObject),\n);\n\nexport default loadWasm;\n","/*\nnode-bzip - a pure-javascript Node.JS module for decoding bzip2 data\n\nCopyright (C) 2012 Eli Skeggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];\n\n// offset in bytes\nvar BitReader = function(stream) {\n this.stream = stream;\n this.bitOffset = 0;\n this.curByte = 0;\n this.hasByte = false;\n};\n\nBitReader.prototype._ensureByte = function() {\n if (!this.hasByte) {\n this.curByte = this.stream.readByte();\n this.hasByte = true;\n }\n};\n\n// reads bits from the buffer\nBitReader.prototype.read = function(bits) {\n var result = 0;\n while (bits > 0) {\n this._ensureByte();\n var remaining = 8 - this.bitOffset;\n // if we're in a byte\n if (bits >= remaining) {\n result <<= remaining;\n result |= BITMASK[remaining] & this.curByte;\n this.hasByte = false;\n this.bitOffset = 0;\n bits -= remaining;\n } else {\n result <<= bits;\n var shift = remaining - bits;\n result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;\n this.bitOffset += bits;\n bits = 0;\n }\n }\n return result;\n};\n\n// seek to an arbitrary point in the buffer (expressed in bits)\nBitReader.prototype.seek = function(pos) {\n var n_bit = pos % 8;\n var n_byte = (pos - n_bit) / 8;\n this.bitOffset = n_bit;\n this.stream.seek(n_byte);\n this.hasByte = false;\n};\n\n// reads 6 bytes worth of data using the read method\nBitReader.prototype.pi = function() {\n var buf = new Uint8Array(6), i;\n for (i = 0; i < buf.length; i++) {\n buf[i] = this.read(8);\n }\n return bufToHex(buf);\n};\n\nfunction bufToHex(buf) {\n return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');\n}\n\nmodule.exports = BitReader;\n","/* very simple input/output stream interface */\nvar Stream = function() {\n};\n\n// input streams //////////////\n/** Returns the next byte, or -1 for EOF. */\nStream.prototype.readByte = function() {\n throw new Error(\"abstract method readByte() not implemented\");\n};\n/** Attempts to fill the buffer; returns number of bytes read, or\n * -1 for EOF. */\nStream.prototype.read = function(buffer, bufOffset, length) {\n var bytesRead = 0;\n while (bytesRead < length) {\n var c = this.readByte();\n if (c < 0) { // EOF\n return (bytesRead===0) ? -1 : bytesRead;\n }\n buffer[bufOffset++] = c;\n bytesRead++;\n }\n return bytesRead;\n};\nStream.prototype.seek = function(new_pos) {\n throw new Error(\"abstract method seek() not implemented\");\n};\n\n// output streams ///////////\nStream.prototype.writeByte = function(_byte) {\n throw new Error(\"abstract method readByte() not implemented\");\n};\nStream.prototype.write = function(buffer, bufOffset, length) {\n var i;\n for (i=0; i>> 0; // return an unsigned value\n };\n\n /**\n * Update the CRC with a single byte\n * @param value The value to update the CRC with\n */\n this.updateCRC = function(value) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n };\n\n /**\n * Update the CRC with a sequence of identical bytes\n * @param value The value to update the CRC with\n * @param count The number of bytes\n */\n this.updateCRCRun = function(value, count) {\n while (count-- > 0) {\n crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];\n }\n };\n };\n return CRC32;\n})();\n","/*\nseek-bzip - a pure-javascript module for seeking within bzip2 data\n\nCopyright (C) 2013 C. Scott Ananian\nCopyright (C) 2012 Eli Skeggs\nCopyright (C) 2011 Kevin Kwok\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, see\nhttp://www.gnu.org/licenses/lgpl-2.1.html\n\nAdapted from node-bzip, copyright 2012 Eli Skeggs.\nAdapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).\n\nBased on micro-bunzip by Rob Landley (rob@landley.net).\n\nBased on bzip2 decompression code by Julian R Seward (jseward@acm.org),\nwhich also acknowledges contributions by Mike Burrows, David Wheeler,\nPeter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,\nRobert Sedgewick, and Jon L. Bentley.\n*/\n\nvar BitReader = require('./bitreader');\nvar Stream = require('./stream');\nvar CRC32 = require('./crc32');\n\nvar MAX_HUFCODE_BITS = 20;\nvar MAX_SYMBOLS = 258;\nvar SYMBOL_RUNA = 0;\nvar SYMBOL_RUNB = 1;\nvar MIN_GROUPS = 2;\nvar MAX_GROUPS = 6;\nvar GROUP_SIZE = 50;\n\nvar WHOLEPI = \"314159265359\";\nvar SQRTPI = \"177245385090\";\n\nvar mtf = function(array, index) {\n var src = array[index], i;\n for (i = index; i > 0; i--) {\n array[i] = array[i-1];\n }\n array[0] = src;\n return src;\n};\n\nvar Err = {\n OK: 0,\n LAST_BLOCK: -1,\n NOT_BZIP_DATA: -2,\n UNEXPECTED_INPUT_EOF: -3,\n UNEXPECTED_OUTPUT_EOF: -4,\n DATA_ERROR: -5,\n OUT_OF_MEMORY: -6,\n OBSOLETE_INPUT: -7,\n END_OF_BLOCK: -8\n};\nvar ErrorMessages = {};\nErrorMessages[Err.LAST_BLOCK] = \"Bad file checksum\";\nErrorMessages[Err.NOT_BZIP_DATA] = \"Not bzip data\";\nErrorMessages[Err.UNEXPECTED_INPUT_EOF] = \"Unexpected input EOF\";\nErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = \"Unexpected output EOF\";\nErrorMessages[Err.DATA_ERROR] = \"Data error\";\nErrorMessages[Err.OUT_OF_MEMORY] = \"Out of memory\";\nErrorMessages[Err.OBSOLETE_INPUT] = \"Obsolete (pre 0.9.5) bzip format not supported.\";\n\nvar _throw = function(status, optDetail) {\n var msg = ErrorMessages[status] || 'unknown error';\n if (optDetail) { msg += ': '+optDetail; }\n var e = new TypeError(msg);\n e.errorCode = status;\n throw e;\n};\n\nvar Bunzip = function(inputStream, outputStream) {\n this.writePos = this.writeCurrent = this.writeCount = 0;\n\n this._start_bunzip(inputStream, outputStream);\n};\nBunzip.prototype._init_block = function() {\n var moreBlocks = this._get_next_block();\n if ( !moreBlocks ) {\n this.writeCount = -1;\n return false; /* no more blocks */\n }\n this.blockCRC = new CRC32();\n return true;\n};\n/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */\nBunzip.prototype._start_bunzip = function(inputStream, outputStream) {\n /* Ensure that file starts with \"BZh['1'-'9'].\" */\n var buf = new Uint8Array(4);\n if (inputStream.read(buf, 0, 4) !== 4 ||\n String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')\n _throw(Err.NOT_BZIP_DATA, 'bad magic');\n\n var level = buf[3] - 0x30;\n if (level < 1 || level > 9)\n _throw(Err.NOT_BZIP_DATA, 'level out of range');\n\n this.reader = new BitReader(inputStream);\n\n /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of\n uncompressed data. Allocate intermediate buffer for block. */\n this.dbufSize = 100000 * level;\n this.nextoutput = 0;\n this.outputStream = outputStream;\n this.streamCRC = 0;\n};\nBunzip.prototype._get_next_block = function() {\n var i, j, k;\n var reader = this.reader;\n // this is get_next_block() function from micro-bunzip:\n /* Read in header signature and CRC, then validate signature.\n (last block signature means CRC is for whole file, return now) */\n var h = reader.pi();\n if (h === SQRTPI) { // last block\n return false; /* no more blocks */\n }\n if (h !== WHOLEPI)\n _throw(Err.NOT_BZIP_DATA);\n this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)\n this.streamCRC = (this.targetBlockCRC ^\n ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;\n /* We can add support for blockRandomised if anybody complains. There was\n some code for this in busybox 1.0.0-pre3, but nobody ever noticed that\n it didn't actually work. */\n if (reader.read(1))\n _throw(Err.OBSOLETE_INPUT);\n var origPointer = reader.read(24);\n if (origPointer > this.dbufSize)\n _throw(Err.DATA_ERROR, 'initial position out of bounds');\n /* mapping table: if some byte values are never used (encoding things\n like ascii text), the compression code removes the gaps to have fewer\n symbols to deal with, and writes a sparse bitfield indicating which\n values were present. We make a translation table to convert the symbols\n back to the corresponding bytes. */\n var t = reader.read(16);\n var symToByte = new Uint8Array(256), symTotal = 0;\n for (i = 0; i < 16; i++) {\n if (t & (1 << (0xF - i))) {\n var o = i * 16;\n k = reader.read(16);\n for (j = 0; j < 16; j++)\n if (k & (1 << (0xF - j)))\n symToByte[symTotal++] = o + j;\n }\n }\n\n /* How many different huffman coding groups does this block use? */\n var groupCount = reader.read(3);\n if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)\n _throw(Err.DATA_ERROR);\n /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding\n group. Read in the group selector list, which is stored as MTF encoded\n bit runs. (MTF=Move To Front, as each value is used it's moved to the\n start of the list.) */\n var nSelectors = reader.read(15);\n if (nSelectors === 0)\n _throw(Err.DATA_ERROR);\n\n var mtfSymbol = new Uint8Array(256);\n for (i = 0; i < groupCount; i++)\n mtfSymbol[i] = i;\n\n var selectors = new Uint8Array(nSelectors); // was 32768...\n\n for (i = 0; i < nSelectors; i++) {\n /* Get next value */\n for (j = 0; reader.read(1); j++)\n if (j >= groupCount) _throw(Err.DATA_ERROR);\n /* Decode MTF to get the next selector */\n selectors[i] = mtf(mtfSymbol, j);\n }\n\n /* Read the huffman coding tables for each group, which code for symTotal\n literal symbols, plus two run symbols (RUNA, RUNB) */\n var symCount = symTotal + 2;\n var groups = [], hufGroup;\n for (j = 0; j < groupCount; j++) {\n var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);\n /* Read huffman code lengths for each symbol. They're stored in\n a way similar to mtf; record a starting value for the first symbol,\n and an offset from the previous value for everys symbol after that. */\n t = reader.read(5); // lengths\n for (i = 0; i < symCount; i++) {\n for (;;) {\n if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);\n /* If first bit is 0, stop. Else second bit indicates whether\n to increment or decrement the value. */\n if(!reader.read(1))\n break;\n if(!reader.read(1))\n t++;\n else\n t--;\n }\n length[i] = t;\n }\n\n /* Find largest and smallest lengths in this group */\n var minLen, maxLen;\n minLen = maxLen = length[0];\n for (i = 1; i < symCount; i++) {\n if (length[i] > maxLen)\n maxLen = length[i];\n else if (length[i] < minLen)\n minLen = length[i];\n }\n\n /* Calculate permute[], base[], and limit[] tables from length[].\n *\n * permute[] is the lookup table for converting huffman coded symbols\n * into decoded symbols. base[] is the amount to subtract from the\n * value of a huffman symbol of a given length when using permute[].\n *\n * limit[] indicates the largest numerical value a symbol with a given\n * number of bits can have. This is how the huffman codes can vary in\n * length: each code with a value>limit[length] needs another bit.\n */\n hufGroup = {};\n groups.push(hufGroup);\n hufGroup.permute = new Uint16Array(MAX_SYMBOLS);\n hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);\n hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);\n hufGroup.minLen = minLen;\n hufGroup.maxLen = maxLen;\n /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */\n var pp = 0;\n for (i = minLen; i <= maxLen; i++) {\n temp[i] = hufGroup.limit[i] = 0;\n for (t = 0; t < symCount; t++)\n if (length[t] === i)\n hufGroup.permute[pp++] = t;\n }\n /* Count symbols coded for at each bit length */\n for (i = 0; i < symCount; i++)\n temp[length[i]]++;\n /* Calculate limit[] (the largest symbol-coding value at each bit\n * length, which is (previous limit<<1)+symbols at this level), and\n * base[] (number of symbols to ignore at each bit length, which is\n * limit minus the cumulative count of symbols coded for already). */\n pp = t = 0;\n for (i = minLen; i < maxLen; i++) {\n pp += temp[i];\n /* We read the largest possible symbol size and then unget bits\n after determining how many we need, and those extra bits could\n be set to anything. (They're noise from future symbols.) At\n each level we're really only interested in the first few bits,\n so here we set all the trailing to-be-ignored bits to 1 so they\n don't affect the value>limit[length] comparison. */\n hufGroup.limit[i] = pp - 1;\n pp <<= 1;\n t += temp[i];\n hufGroup.base[i + 1] = pp - t;\n }\n hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */\n hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;\n hufGroup.base[minLen] = 0;\n }\n /* We've finished reading and digesting the block header. Now read this\n block's huffman coded symbols from the file and undo the huffman coding\n and run length encoding, saving the result into dbuf[dbufCount++]=uc */\n\n /* Initialize symbol occurrence counters and symbol Move To Front table */\n var byteCount = new Uint32Array(256);\n for (i = 0; i < 256; i++)\n mtfSymbol[i] = i;\n /* Loop through compressed symbols. */\n var runPos = 0, dbufCount = 0, selector = 0, uc;\n var dbuf = this.dbuf = new Uint32Array(this.dbufSize);\n symCount = 0;\n for (;;) {\n /* Determine which huffman coding group to use. */\n if (!(symCount--)) {\n symCount = GROUP_SIZE - 1;\n if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }\n hufGroup = groups[selectors[selector++]];\n }\n /* Read next huffman-coded symbol. */\n i = hufGroup.minLen;\n j = reader.read(i);\n for (;;i++) {\n if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }\n if (j <= hufGroup.limit[i])\n break;\n j = (j << 1) | reader.read(1);\n }\n /* Huffman decode value to get nextSym (with bounds checking) */\n j -= hufGroup.base[i];\n if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }\n var nextSym = hufGroup.permute[j];\n /* We have now decoded the symbol, which indicates either a new literal\n byte, or a repeated run of the most recent literal byte. First,\n check if nextSym indicates a repeated run, and if so loop collecting\n how many times to repeat the last literal. */\n if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {\n /* If this is the start of a new run, zero out counter */\n if (!runPos){\n runPos = 1;\n t = 0;\n }\n /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at\n each bit position, add 1 or 2 instead. For example,\n 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.\n You can make any bit pattern that way using 1 less symbol than\n the basic or 0/1 method (except all bits 0, which would use no\n symbols, but a run of length 0 doesn't mean anything in this\n context). Thus space is saved. */\n if (nextSym === SYMBOL_RUNA)\n t += runPos;\n else\n t += 2 * runPos;\n runPos <<= 1;\n continue;\n }\n /* When we hit the first non-run symbol after a run, we now know\n how many times to repeat the last literal, so append that many\n copies to our buffer of decoded symbols (dbuf) now. (The last\n literal used is the one at the head of the mtfSymbol array.) */\n if (runPos){\n runPos = 0;\n if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }\n uc = symToByte[mtfSymbol[0]];\n byteCount[uc] += t;\n while (t--)\n dbuf[dbufCount++] = uc;\n }\n /* Is this the terminating symbol? */\n if (nextSym > symTotal)\n break;\n /* At this point, nextSym indicates a new literal character. Subtract\n one to get the position in the MTF array at which this literal is\n currently to be found. (Note that the result can't be -1 or 0,\n because 0 and 1 are RUNA and RUNB. But another instance of the\n first symbol in the mtf array, position 0, would have been handled\n as part of a run above. Therefore 1 unused mtf position minus\n 2 non-literal nextSym values equals -1.) */\n if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }\n i = nextSym - 1;\n uc = mtf(mtfSymbol, i);\n uc = symToByte[uc];\n /* We have our literal byte. Save it into dbuf. */\n byteCount[uc]++;\n dbuf[dbufCount++] = uc;\n }\n /* At this point, we've read all the huffman-coded symbols (and repeated\n runs) for this block from the input stream, and decoded them into the\n intermediate buffer. There are dbufCount many decoded bytes in dbuf[].\n Now undo the Burrows-Wheeler transform on dbuf.\n See http://dogma.net/markn/articles/bwt/bwt.htm\n */\n if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }\n /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */\n j = 0;\n for (i = 0; i < 256; i++) {\n k = j + byteCount[i];\n byteCount[i] = j;\n j = k;\n }\n /* Figure out what order dbuf would be in if we sorted it. */\n for (i = 0; i < dbufCount; i++) {\n uc = dbuf[i] & 0xff;\n dbuf[byteCount[uc]] |= (i << 8);\n byteCount[uc]++;\n }\n /* Decode first byte by hand to initialize \"previous\" byte. Note that it\n doesn't get output, and if the first three characters are identical\n it doesn't qualify as a run (hence writeRunCountdown=5). */\n var pos = 0, current = 0, run = 0;\n if (dbufCount) {\n pos = dbuf[origPointer];\n current = (pos & 0xff);\n pos >>= 8;\n run = -1;\n }\n this.writePos = pos;\n this.writeCurrent = current;\n this.writeCount = dbufCount;\n this.writeRun = run;\n\n return true; /* more blocks to come */\n};\n/* Undo burrows-wheeler transform on intermediate buffer to produce output.\n If start_bunzip was initialized with out_fd=-1, then up to len bytes of\n data are written to outbuf. Return value is number of bytes written or\n error (all errors are negative numbers). If out_fd!=-1, outbuf and len\n are ignored, data is written to out_fd and return is RETVAL_OK or error.\n*/\nBunzip.prototype._read_bunzip = function(outputBuffer, len) {\n var copies, previous, outbyte;\n /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully\n decoded, which results in this returning RETVAL_LAST_BLOCK, also\n equal to -1... Confusing, I'm returning 0 here to indicate no\n bytes written into the buffer */\n if (this.writeCount < 0) { return 0; }\n\n var gotcount = 0;\n var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;\n var dbufCount = this.writeCount, outputsize = this.outputsize;\n var run = this.writeRun;\n\n while (dbufCount) {\n dbufCount--;\n previous = current;\n pos = dbuf[pos];\n current = pos & 0xff;\n pos >>= 8;\n if (run++ === 3){\n copies = current;\n outbyte = previous;\n current = -1;\n } else {\n copies = 1;\n outbyte = current;\n }\n this.blockCRC.updateCRCRun(outbyte, copies);\n while (copies--) {\n this.outputStream.writeByte(outbyte);\n this.nextoutput++;\n }\n if (current != previous)\n run = 0;\n }\n this.writeCount = dbufCount;\n // check CRC\n if (this.blockCRC.getCRC() !== this.targetBlockCRC) {\n _throw(Err.DATA_ERROR, \"Bad block CRC \"+\n \"(got \"+this.blockCRC.getCRC().toString(16)+\n \" expected \"+this.targetBlockCRC.toString(16)+\")\");\n }\n return this.nextoutput;\n};\n\nvar coerceInputStream = function(input) {\n if ('readByte' in input) { return input; }\n var inputStream = new Stream();\n inputStream.pos = 0;\n inputStream.readByte = function() { return input[this.pos++]; };\n inputStream.seek = function(pos) { this.pos = pos; };\n inputStream.eof = function() { return this.pos >= input.length; };\n return inputStream;\n};\nvar coerceOutputStream = function(output) {\n var outputStream = new Stream();\n var resizeOk = true;\n if (output) {\n if (typeof(output)==='number') {\n outputStream.buffer = new Uint8Array(output);\n resizeOk = false;\n } else if ('writeByte' in output) {\n return output;\n } else {\n outputStream.buffer = output;\n resizeOk = false;\n }\n } else {\n outputStream.buffer = new Uint8Array(16384);\n }\n outputStream.pos = 0;\n outputStream.writeByte = function(_byte) {\n if (resizeOk && this.pos >= this.buffer.length) {\n var newBuffer = new Uint8Array(this.buffer.length*2);\n newBuffer.set(this.buffer);\n this.buffer = newBuffer;\n }\n this.buffer[this.pos++] = _byte;\n };\n outputStream.getBuffer = function() {\n // trim buffer\n if (this.pos !== this.buffer.length) {\n if (!resizeOk)\n throw new TypeError('outputsize does not match decoded input');\n var newBuffer = new Uint8Array(this.pos);\n newBuffer.set(this.buffer.subarray(0, this.pos));\n this.buffer = newBuffer;\n }\n return this.buffer;\n };\n outputStream._coerced = true;\n return outputStream;\n};\n\n/* Static helper functions */\n// 'input' can be a stream or a buffer\n// 'output' can be a stream or a buffer or a number (buffer size)\nconst decode = function(input, output, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n\n var bz = new Bunzip(inputStream, outputStream);\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n if (bz._init_block()) {\n bz._read_bunzip();\n } else {\n var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)\n if (targetStreamCRC !== bz.streamCRC) {\n _throw(Err.DATA_ERROR, \"Bad stream CRC \"+\n \"(got \"+bz.streamCRC.toString(16)+\n \" expected \"+targetStreamCRC.toString(16)+\")\");\n }\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n } else break;\n }\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\nconst decodeBlock = function(input, pos, output) {\n // make a stream from a buffer, if necessary\n var inputStream = coerceInputStream(input);\n var outputStream = coerceOutputStream(output);\n var bz = new Bunzip(inputStream, outputStream);\n bz.reader.seek(pos);\n /* Fill the decode buffer for the block */\n var moreBlocks = bz._get_next_block();\n if (moreBlocks) {\n /* Init the CRC for writing */\n bz.blockCRC = new CRC32();\n\n /* Zero this so the current byte from before the seek is not written */\n bz.writeCopies = 0;\n\n /* Decompress the block and write to stdout */\n bz._read_bunzip();\n // XXX keep writing?\n }\n if ('getBuffer' in outputStream)\n return outputStream.getBuffer();\n};\n/* Reads bzip2 file from stream or buffer `input`, and invoke\n * `callback(position, size)` once for each bzip2 block,\n * where position gives the starting position (in *bits*)\n * and size gives uncompressed size of the block (in *bytes*). */\nconst table = function(input, callback, multistream) {\n // make a stream from a buffer, if necessary\n var inputStream = new Stream();\n inputStream.delegate = coerceInputStream(input);\n inputStream.pos = 0;\n inputStream.readByte = function() {\n this.pos++;\n return this.delegate.readByte();\n };\n if (inputStream.delegate.eof) {\n inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);\n }\n var outputStream = new Stream();\n outputStream.pos = 0;\n outputStream.writeByte = function() { this.pos++; };\n\n var bz = new Bunzip(inputStream, outputStream);\n var blockSize = bz.dbufSize;\n while (true) {\n if ('eof' in inputStream && inputStream.eof()) break;\n\n var position = inputStream.pos*8 + bz.reader.bitOffset;\n if (bz.reader.hasByte) { position -= 8; }\n\n if (bz._init_block()) {\n var start = outputStream.pos;\n bz._read_bunzip();\n callback(position, outputStream.pos - start);\n } else {\n var crc = bz.reader.read(32); // (but we ignore the crc)\n if (multistream &&\n 'eof' in inputStream &&\n !inputStream.eof()) {\n // note that start_bunzip will also resync the bit reader to next byte\n bz._start_bunzip(inputStream, outputStream);\n console.assert(bz.dbufSize === blockSize,\n \"shouldn't change block size within multistream file\");\n } else break;\n }\n }\n};\n\nmodule.exports = {\n Bunzip,\n Stream,\n Err,\n decode,\n decodeBlock,\n table\n};\n"],"names":["doneWritingPromise","Symbol","doneWritingResolve","doneWritingReject","readingIndex","ArrayStream","Array","constructor","super","Object","setPrototypeOf","this","prototype","Promise","resolve","reject","catch","isArrayStream","input","getReader","isArray","Writer","writer","getWriter","releaseLock","closed","call","stream","isStream","globalThis","ReadableStream","isPrototypeOf","_read","_readableState","Error","isUint8Array","Uint8Array","concatUint8Array","arrays","length","totalLength","i","result","pos","forEach","element","set","undefined","read","async","value","done","readToEnd","join","slice","clone","then","push","write","chunk","close","abort","reason","process","versions","doneReadingSet","WeakSet","externalBuffer","Reader","reader","bind","_releaseLock","_cancel","cancel","doneReading","has","add","e","toStream","start","controller","enqueue","toArrayStream","concat","list","some","map","transform","transformWithCancel","all","transforms","prev","transformPair","readable","writable","pipe","preventClose","concatStream","concatArrayStream","target","preventAbort","preventCancel","ready","pipeTo","transformRaw","options","transformStream","TransformStream","customCancel","backpressureChangePromiseResolve","backpressureChangePromiseReject","outputController","pulled","cancelled","pull","highWaterMark","WritableStream","error","finish","output","data","result1","result2","flush","fn","incomingTransformController","incoming","pipeDonePromise","outgoing","setTimeout","parse","returnValue","transformed","remainder","teed","tee","overwrite","passiveClone","entries","getOwnPropertyDescriptors","name","descriptor","get","defineProperty","begin","end","Infinity","bytesRead","Math","max","terminate","lastBytes","console","warn","fromAsync","subarray","destroy","arrayStream","shift","readLine","returnVal","buffer","streams.concat","lineEndIndex","indexOf","substr","unshift","readByte","byte","streams.slice","readBytes","bufferLength","bufferConcat","peekBytes","bytes","values","byteOffset","byteLength","filter","byValue","enums","curve","nistP256","p256","nistP384","p384","nistP521","p521","secp256k1","ed25519Legacy","ed25519","curve25519Legacy","curve25519","brainpoolP256r1","brainpoolP384r1","brainpoolP512r1","s2k","simple","salted","iterated","argon2","gnu","publicKey","rsaEncryptSign","rsaEncrypt","rsaSign","elgamal","dsa","ecdh","ecdsa","eddsaLegacy","aedh","aedsa","x25519","x448","ed448","symmetric","idea","tripledes","cast5","blowfish","aes128","aes192","aes256","twofish","compression","uncompressed","zip","zlib","bzip2","hash","md5","sha1","ripemd","sha256","sha384","sha512","sha224","sha3_256","sha3_512","webHash","aead","eax","ocb","gcm","experimentalGCM","packet","publicKeyEncryptedSessionKey","signature","symEncryptedSessionKey","onePassSignature","secretKey","secretSubkey","compressedData","symmetricallyEncryptedData","marker","literalData","trust","userID","publicSubkey","userAttribute","symEncryptedIntegrityProtectedData","modificationDetectionCode","aeadEncryptedData","padding","literal","binary","text","utf8","mime","standalone","certGeneric","certPersona","certCasual","certPositive","certRevocation","subkeyBinding","keyBinding","key","keyRevocation","subkeyRevocation","timestamp","thirdParty","signatureSubpacket","signatureCreationTime","signatureExpirationTime","exportableCertification","trustSignature","regularExpression","revocable","keyExpirationTime","placeholderBackwardsCompatibility","preferredSymmetricAlgorithms","revocationKey","issuerKeyID","notationData","preferredHashAlgorithms","preferredCompressionAlgorithms","keyServerPreferences","preferredKeyServer","primaryUserID","policyURI","keyFlags","signersUserID","reasonForRevocation","features","signatureTarget","embeddedSignature","issuerFingerprint","preferredAEADAlgorithms","preferredCipherSuites","certifyKeys","signData","encryptCommunication","encryptStorage","splitPrivateKey","authentication","sharedPrivateKey","armor","multipartSection","multipartLast","signed","message","privateKey","noReason","keySuperseded","keyCompromised","keyRetired","userIDInvalid","modificationDetection","v5Keys","seipdv2","type","config","preferredHashAlgorithm","preferredSymmetricAlgorithm","preferredCompressionAlgorithm","aeadProtect","parseAEADEncryptedV4KeysAsLegacy","preferredAEADAlgorithm","aeadChunkSizeByte","v6Keys","enableParsingV5Entities","s2kType","s2kIterationCountByte","s2kArgon2Params","passes","parallelism","memoryExponent","allowUnauthenticatedMessages","allowUnauthenticatedStream","minRSABits","passwordCollisionCheck","allowInsecureDecryptionWithSigningKeys","allowInsecureVerificationWithReformattedKeys","allowMissingKeyFlags","constantTimePKCS1Decryption","constantTimePKCS1DecryptionSupportedSymmetricAlgorithms","Set","ignoreUnsupportedPackets","ignoreMalformedPackets","additionalAllowedPackets","showVersion","showComment","versionString","commentString","maxUserIDLength","knownNotations","nonDeterministicSignaturesViaNotation","useEllipticFallback","rejectHashAlgorithms","rejectMessageHashAlgorithms","rejectPublicKeyAlgorithms","rejectCurves","debugMode","env","NODE_ENV","util","isString","String","nodeRequire","stream.isUint8Array","stream.isStream","getNobleCurve","publicKeyAlgo","curveName","defaultConfig","nobleCurves","noble_curves","readNumber","n","writeNumber","b","readDate","Date","writeDate","time","numeric","floor","getTime","normalizeDate","now","readMPI","bytelen","readExactSubarray","leftPad","padded","offset","uint8ArrayToMPI","bin","bitSize","uint8ArrayBitLength","stripped","ceil","prefix","nbits","hexToUint8Array","hex","k","parseInt","uint8ArrayToHex","hexAlphabet","s","v","stringToUint8Array","str","stream.transform","charCodeAt","uint8ArrayToString","bs","j","fromCharCode","apply","encodeUTF8","encoder","TextEncoder","lastChunk","encode","decodeUTF8","decoder","TextDecoder","decode","stream.concat","stream.concatUint8Array","equalsUint8Array","array1","array2","writeChecksum","printDebug","log","printDebugError","x","r","t","double","doubleVar","last","shiftRight","array","bits","getWebCrypto","webCrypto","crypto","subtle","getNodeCrypto","webcrypto","getNodeZlib","getNodeBuffer","Buffer","getHardwareConcurrency","navigator","hardwareConcurrency","cpus","isEmailAddress","test","canonicalizeEOL","carryOverCR","index","indices","normalized","sub","nativeEOL","copyWithin","removeTrailingSpaces","split","line","wrapError","constructAllowedPackets","allowedClasses","PacketClass","tag","anyPromise","promises","exception","promise","selectUint8Array","cond","a","selectUint8","isAES","cipherAlgo","encodeChunk","decodeChunk","buf","lines","encoded","spaces","spacechars","spacechar","includes","decoded","b64ToUint8Array","base64","replace","uint8ArrayToB64","url","getType","header","match","addheader","customComment","getCheckSum","crc","len32","isLittleEndian","arr32","Uint32Array","crc_table","createcrc24","base64.encode","from","toString","btoa","atob","ArrayBuffer","DataView","setInt16","Int16Array","verifyHeaders","headers","removeChecksum","body","lastEquals","lastIndexOf","unarmor","reSplit","reEmptyLine","headersDone","textDone","lastHeaders","base64.decode","stream.transformPair","stream.getReader","stream.getWriter","parts","stream.isArrayStream","stream.readToEnd","messageType","partIndex","partTotal","emitChecksum","maybeBodyClone","stream.passiveClone","getLegacyCipher","algo","legacyCiphers","legacy_ciphers","cipher","getCipherBlockSize","getCipherKeySize","getCipherParams","keySize","blockSize","md5cycle","c","d","ff","gg","hh","ii","add32","cmn","q","md5blk","md5blks","hex_chr","rhex","nodeCrypto","nodeCryptoHashes","getHashes","nodeHash","shasum","createHash","update","digest","nobleHash","nobleHashName","webCryptoHashName","getNobleHash","nobleHashes","noble_hashes","hashInstance","create","hash$1","entree","state","substring","tail","md51","getHashByteLength","isBytes","lengths","exists","instance","checkFinished","destroyed","finished","out","min","outputLen","u8","arr","u32","createView","toBytes","utf8ToBytes","copyBytes","equalBytes","diff","wrapCipher","params","assign","setBigUint64","view","isLE","_32n","BigInt","_u32_max","wh","Number","wl","setUint32","isAligned32","clean","fill","BLOCK_SIZE","ZEROS16","ZEROS32","swapLE","GHASH","expectedLength","blockLen","s0","s1","s2","s3","abytes","kView","k0","getUint32","k1","k2","k3","doubles","W","estimateWindow","windows","windowSize","items","w","d0","d1","d2","d3","_updateBlock","o0","o1","o2","o3","mask","num","bytePos","bitPos","bit","e0","e1","e2","e3","aexists","b32","blocks","left","elm","digestInto","aoutput","o32","res","Polyval","ghKey","reverse","hiBit","carry","_toGHASHKey","wrapConstructorWithKey","hashCons","hashC","msg","tmp","ghash","EMPTY_BLOCK","POLY","mul2","mul","sbox","box","invSbox","_","rotr32_8","rotl32_8","byteSwap","word","genTtable","T0","T1","T2","T3","T01","T23","sbox2","Uint16Array","idx","tableEncoding","tableDecoding","xPowers","p","expandKeyLE","len","toClean","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","apply0123","encrypt","rounds","t0","t1","t2","t3","decrypt","getDst","dst","ctrCounter","nonce","src","srcLen","ctr","c32","src32","dst32","ctr32","ctrPos","ctrNum","nonceLength","processCtr","plaintext","ciphertext","cbc","iv","opts","pcks5","disablePadding","o","_out","outLen","remaining","validateBlockEncrypt","_iv","n32","tmp32","paddingByte","padPCKS","validateBlockDecrypt","ps0","ps1","ps2","ps3","lastByte","validatePCKS","cfb","processCfb","isEncrypt","next32","tagLength","AAD","_computeTag","authKey","tagMask","aadLength","h","computeTag","deriveKeys","counter","nonceLen","g","passedTag","isBytes32","encryptBlock","block","decryptBlock","AESW","kek","a0","a1","chunks","AESKW_IV","aeskw","sum","pad","concatBytes","unsafe","knownAlgos","getCiphers","nodeAlgos","WebCryptoEncryptor","prevBlock","nextBlock","zeroBlock","isSupported","importKey","_runCBC","nonZeroIV","mode","keyRef","encryptChunk","missing","added","leftover","toEncrypt","encryptedBlocks","xorMut","encryptedBlock","curBlock","clearSensitiveData","ct","NobleStreamProcessor","forEncryption","nobleAesHelpers","getUint32Array","_runCFB","processChunk","toProcess","processedBlocks","processedBlock","aLength","algoName","decipherObj","createDecipheriv","nodeDecrypt","nobleAesCfb","aesDecrypt","cipherfn","block_size","blockp","decblock","pt","cipherObj","createCipheriv","nodeEncrypt","aesEncrypt","blockc","encblock","blockLength","rightXORMut","CMAC","CBC","padding2","err","nobleAesCbc","ivLength","zero","one","two","OMAC","cmac","CTR","en","final","nobleAesCtr","EAX","omac","adata","omacNonce","omacAdata","ciphered","ctTag","omacCiphered","getNonce","chunkIndex","ntz","S","T","xor","OCB","maxNtz","aes","encipher","decipher","crypt","m","newMaxNtz","extendKeyVariables","paddedNonce","bottom","kTop","stretched","checksum","xorInput","$","cipherInput","mask_x","mask_$","constructKeyVariables","crypted","ALGO","GCM","setAAD","getAuthTag","de","setAuthTag","_key","webcryptoEmptyMessagesUnsupported","userAgent","nobleAesGcm","additionalData","_0n","_1n","uint8ArrayToBigInt","mod","reduced","modExp","exp","lsb","abs","modInv","gcd","aInput","bInput","y","xPrev","yPrev","aNegated","bNegated","_egcd","bigIntToNumber","number","MAX_SAFE_INTEGER","getBit","bitLength","bitlen","_8n","bigIntToUint8Array","endian","rawLength","getRandomBytes","getRandomValues","getRandomBigInteger","modulus","randomProbablePrime","_30n","adds","isProbablePrime","smallPrimes","every","divisionTest","fermat","n1","millerRabin","hash_headers","emeEncode","keyLength","mLength","PS","count","randomBytes","getPKCS1Padding","emeDecode","randomPayload","separatorNotFound","psLen","payload","isValidPadding","emsaEncode","hashed","emLen","hashPrefix","tLen","EM","privateToJWK","u","pNum","qNum","dNum","dq","dp","kty","qi","ext","publicToJWK","jwkToPrivate","jwk","format","constants","RSA_PKCS1_PADDING","privateDecrypt","unblinder","blinder","mp","mq","bnDecrypt","publicEncrypt","bnEncrypt","keyGenOpt","modulusLength","publicExponent","keyPair","generateKey","exportKey","publicKeyEncoding","privateKeyEncoding","generateKeyPair","jwkPrivateKey","phi","hashAlgo","hashName","sign","webSign","createSign","nodeSign","bnSign","_2n","rde","verify","webVerify","createVerify","nodeVerify","EM1","EM2","bnVerify","c1","c2","pSize","threshold","nacl","gf","init","Float64Array","randombytes","_9","gf0","gf1","_121665","D","D2","X","Y","I","ts64","l","crypto_verify_32","xi","yi","vn","set25519","car25519","sel25519","pack25519","neq25519","par25519","unpack25519","A","Z","M","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","inv25519","crypto_scalarmult","z","f","x32","x16","crypto_scalarmult_base","K","crypto_hashblocks_hl","hl","bh0","bh1","bh2","bh3","bh4","bh5","bh6","bh7","bl0","bl1","bl2","bl3","bl4","bl5","bl6","bl7","th","tl","Int32Array","ah0","ah1","ah2","ah3","ah4","ah5","ah6","ah7","al0","al1","al2","al3","al4","al5","al6","al7","crypto_hash","cswap","pack","tx","ty","zi","scalarmult","scalarbase","crypto_sign_keypair","pk","sk","seeded","L","modL","reduce","unpackneg","chk","den","den2","den4","den6","pow2523","crypto_sign_BYTES","checkArrayTypes","arguments","TypeError","scalarMult","crypto_box_keypair","fromSecretKey","signedMsg","sm","smlen","crypto_sign","detached","sig","crypto_sign_open","fromSeed","seed","setPRNG","cleanup","knownOIDs","OID","oid","toHex","getName","readSimpleLength","writeSimpleLength","writePartialLength","power","writeTag","tag_type","writeHeader","supportsStreaming","readPackets","callback","callbackReturned","peekedBytes","headerByte","packetLength","packetLengthType","packetSupportsStreaming","wasPartialLength","stream.ArrayStream","lengthByte","nextPacket","UnsupportedError","captureStackTrace","UnknownPacketError","UnparseablePacket","rawContent","generate","webCryptoKey","getPayloadSize","utils","randomPrivateKey","getPublicKey","getPreferredHashAlgo","privateKeyToJWK","RS","publicKeyToJWK","crv","wrap","dataToWrap","wrappingKey","keyToWrap","wrapped","wrapKey","nobleAesKW","unwrap","wrappedData","unwrapped","unwrapKey","computeHKDF","inputKey","salt","info","importedKey","deriveBits","HKDF_INFO","generateEphemeralEncryptionMaterial","recipientA","ephemeralSecretKey","sharedSecret","assertNonZeroArray","ephemeralPublicKey","getSharedSecret","recomputeSharedSecret","acc","wrappedKey","hkdfInput","aesKW.unwrap","encryptionKey","aesKW.wrap","webCurves","knownCurves","getCurves","nodeCurves","curves","keyType","node","web","payloadSize","sharedSize","wireFormatLeadingByte","CurveWithOID","oidOrName","genKeyPair","namedCurve","jwkToRawPublic","webGenKeyPair","jsGenKeyPair","createECDH","generateKeys","getPrivateKey","nodeGenKeyPair","ecdhXGenerate","eddsaGenerate","validateStandardParams","Q","supportedCurves","dG","checkPublicPointEnconding","V","pointSize","nobleCurve","bufX","bufY","rawPublicToJWK","ecKeyUtils","nodeBuffer","derPrivateKey","generateDer","dsaEncoding","lowS","tryFallbackVerificationForOldBug","jsVerify","verified","derPublicKey","eddsaSign","eddsaVerify","provided","computed","buildEcdhParam","public_algo","kdfParams","fingerprint","kdf","param","stripLeading","stripTrailing","genPublicEphemeralKey","sharedKey","ecdhXGenerateEphemeralEncryptionMaterial","recipient","public","webPublicEphemeralKey","jsPublicEphemeralKey","sender","computeSecret","nodePublicEphemeralKey","genPrivateEphemeralKey","ecdhXRecomputeSharedSecret","secret","webPrivateEphemeralKey","jsPrivateEphemeralKey","setPrivateKey","nodePrivateEphemeralKey","C","pkcs5.decode","pkcs5.encode","xr","qSize","u1","u2","rsa","elliptic","signatureParams","rsSize","eddsa","publicKeyParams","privateKeyParams","publicParams","curveSize","ECDHSymmetricKey","KDFParams","ECDHXSymmetricKey","fromObject","algorithm","followLength","checkSupportedCurve","getCurvePayloadSize","ecdhX","privateParams","prefixrandom","repeat","ECDHSymkey","sessionKeyParams","keyAlgo","symmetricAlgo","algosWithNativeRepresentation","orderedParams","keys","validateParams","algoModule","random","pkcs1","pkcs5","aesKW","Argon2OutOfMemoryError","loadArgonWasmModule","argon2Promise","Argon2S2K","encodedM","generateSalt","produceKey","passphrase","decodedM","index$1","default","version","password","memorySize","GenericS2K","getCount","numBytes","rlength","prefixlen","toHash","datalen","allowedS2KTypesForEncryption","newS2KFromType","newS2KFromConfig","u16","fleb","fdeb","clim","freb","eb","_a","fl","revfl","_b","fd","revfd","rev","hMap","cd","mb","co","le","rvb","sv","r_1","flt","fdt","flm","flrm","fdm","fdrm","bits16","shft","slc","BYTES_PER_ELEMENT","ec","ind","nt","code","wbits","wbits16","hTree","et","sort","i0","i1","i2","maxSym","tr","mbt","ln","dt","lft","cst","i2_1","i2_2","i2_3","lc","cl","cli","cln","cls","clen","cf","wfblk","dat","wblk","syms","lf","df","li","bl","dlt","mlb","ddt","mdb","_c","lclt","nlc","_d","lcdt","ndc","lcfreq","_e","lct","mlcb","nlcc","lm","ll","dm","dl","flen","ftlen","dtlen","llm","lcts","it","clct","deo","dopt","opt","pre","post","st","lvl","plvl","lst","msk_1","head","bs1_1","bs2_1","hsh","lc_1","wi","hv","imod","pimod","rem","ch_1","dif","maxn","maxd","ml","nl","mmd","md","ti","lin","din","dflt","level","mem","Deflate","cb","ondata","Inflate","bts","sl","noBuf","noSt","cbuf","nbuf","bt","lbt","dbt","tbts","hLit","hcLen","ldt","clt","clb","clbmsk","clm","lt","lms","dms","lpos","sym","dsym","inflt","Zlib","raw","lv","zlh","wbytes","Unzlib","td","LiteralDataPacket","date","filename","setText","getText","getBytes","setBytes","setFilename","getFilename","stream.parse","filename_len","filename_length","KeyID","equals","keyID","matchWildcard","isWildcard","isNull","mapToHex","fromID","wildcard","SALT_NOTATION_NAME","allowedUnhashedSubpackets","SignaturePacket","signatureType","hashAlgorithm","publicKeyAlgorithm","signatureData","unhashedSubpackets","unknownSubpackets","signedHashValue","created","signatureNeverExpires","exportable","trustLevel","trustAmount","keyNeverExpires","revocationKeyClass","revocationKeyAlgorithm","revocationKeyFingerprint","rawNotations","notations","isPrimaryUserID","reasonForRevocationFlag","reasonForRevocationString","signatureTargetPublicKeyAlgorithm","signatureTargetHashAlgorithm","signatureTargetHash","issuerKeyVersion","revoked","readSubPackets","saltLength","signatureMaterial","parseSignatureParams","writeParams","stream.fromAsync","serializeParams","writeUnhashedSubPackets","getFingerprintBytes","getKeyID","saltLengthForHash","saltValue","humanReadable","critical","writeHashedSubPackets","stream.slice","stream.clone","writeSubPacket","encodedName","readSubPacket","mypos","seconds","trusted","subpacketLengthBytes","subpacketLength","toSign","writeForHash","calculateTrailer","isMessageSignature","normDate","getExpirationTime","toUpperCase","isExpired","OnePassSignaturePacket","fromSignaturePacket","signaturePacket","isLast","onePassSig","flags","args","correspondingSig","newPacketFromTag","allowedPackets","packetType","PacketList","fromBinary","packets","parsed","fromStream","throwUnsupportedError","throwMalformedError","unparsedPacket","packetbytes","minLength","powerOf2","LN2","chunkSize","filterByTag","tags","filtered","handle","findPacket","find","indexOfTag","tagIndex","that","CompressedDataPacket","compressed","decompress","compress","compressionName","decompressionFn","decompress_fns","compressionFn","compress_fns","compressionStreamInstantiator","ZlibStreamedConstructor","inputData","zlibStream","processedData","compressorOrDecompressor","pipeThrough","inputReader","bzip2Decompress","bunzipDecode","getCompressionStreamInstantiators","compressionFormat","compressor","CompressionStream","decompressor","DecompressionStream","SymEncryptedIntegrityProtectedDataPacket","aeadAlgorithm","seip","cipherAlgorithm","chunkSizeByte","encrypted","sessionKeyAlgorithm","runAEAD","getPrefixRandom","mdc","tohash","decrypted","realHash","verifyHash","isSEIPDv2","isAEADP","getAEADMode","tagLengthIfDecrypting","tagLengthIfEncrypting","chunkIndexSizeIfAEADEP","adataBuffer","adataArray","adataTagArray","adataView","chunkIndexArray","ivView","latestPromise","cryptedBytes","queuedBytes","derived","modeInstance","size","stream.pipe","finalChunk","cryptedPromise","setInt32","desiredSize","AEADEncryptedDataPacket","PublicKeyEncryptedSessionKeyPacket","publicKeyID","publicKeyVersion","publicKeyFingerprint","sessionKey","encryptionKeyPacket","anonymousRecipient","pkesk","versionAndFingerprintLength","fingerprintLength","parseEncSessionKeyParams","encodeSessionKey","publicKeyEncrypt","randomSessionKey","decryptedData","publicKeyDecrypt","computedChecksum","isValidChecksum","decryptedSessionKey","isValidPayload","decodeSessionKey","hasEncryptedAlgo","sessionKeyData","SymEncryptedSessionKeyPacket","sessionKeyEncryptionAlgorithm","s2kLen","fieldsLen","generateSessionKey","PublicKeyPacket","expirationTimeV3","fromSecretKeyPacket","secretKeyPacket","keyPacket","parsePublicKeyParams","computeFingerprintAndKeyID","writePublicKey","versionOctet","lengthOctets","isDecrypted","getCreationTime","computeFingerprint","getFingerprint","hasSameFingerprintAs","other","getAlgorithmInfo","modulo","readPublicKey","SymmetricallyEncryptedDataPacket","FRE","MarkerPacket","PublicSubkeyPacket","fromSecretSubkeyPacket","secretSubkeyPacket","UserAttributePacket","attributes","usrAttr","attr","SecretKeyPacket","keyMaterial","isEncrypted","s2kUsage","isLegacyAEAD","usedModernAEAD","startOfSecretKeyData","unparseableKeyMaterial","cleartext","parsePrivateKeyParams","serializedPublicKey","optionalFieldsArr","isDummy","isMissingSecretKeyMaterial","makeDummy","clearPrivateParams","serializedPacketTag","produceEncryptionKey","associateData","cleartextWithHash","validate","validParams","generateParams","keyVersion","aeadMode","derivedKey","UserIDPacket","email","comment","components","matches","exec","groups","trim","otherUserID","SecretSubkeyPacket","TrustPacket","PaddingPacket","createPadding","Signature","packetlist","getSigningKeyIDs","readSignature","armoredSignature","binarySignature","rest","unknownOptions","generateSecretSubkey","rsaBits","generateSecretKey","getLatestValidSignature","signatures","dataToVerify","latestValid","$1","$2","toLowerCase","isDataExpired","expirationTime","getKeyExpirationTime","createBindingSignature","subkey","primaryKey","dataToSign","signatureProperties","createSignaturePacket","recipientKeys","signingKeyPacket","recipientUserIDs","targetKeys","targetUserIDs","defaultAlgo","preferredSenderAlgo","supportedAlgosPerTarget","getPrimarySelfSignature","supportedAlgosMap","Map","supportedAlgos","supportedAlgo","isSupportedHashAlgo","getStrongestSupportedHashAlgo","strongestHashAlgo","algoA","algoB","preferredCurveAlgo","getPreferredCurveHashAlgo","preferredSenderAlgoIsSupported","preferredSenderAlgoStrongerThanCurveAlgo","strongestSupportedAlgo","mergeSignatures","source","dest","checkFn","sourceSig","destSig","isDataRevoked","revocations","revocationKeyIDs","revocationSignature","isHardRevocation","sanitizeKeyOptions","subkeyDefaults","validateSigningKeyPacket","validateEncryptionKeyPacket","validateDecryptionKeyPacket","checkKeyRequirements","algoInfo","User","userPacket","mainKey","selfCertifications","otherCertifications","revocationSignatures","toPacketList","user","certify","signingKeys","isPrivate","signingKey","getSigningKey","isRevoked","certificate","verifyCertificate","verificationKeys","issuerKeys","getKeys","verifyAllCertifications","certifications","certification","valid","selfCertification","sourceUser","srcSelfSig","srcRevSig","revoke","flag","string","Subkey","subkeyPacket","bindingSignatures","helper.isDataRevoked","bindingSignature","helper.getLatestValidSignature","helper.isDataExpired","keyExpiry","helper.getKeyExpirationTime","sigExpiry","helper.mergeSignatures","srcBindSig","helper.createSignaturePacket","allowedRevocationPackets","mainKeyPacketTags","keyPacketTags","privateSubkey","Key","packetListToStructure","disallowedPackets","primaryKeyID","ignoreUntil","users","subkeys","directSignatures","clonePrivateParams","getPrototypeOf","getSubkeys","getKeyIDs","getUserIDs","verifyPrimaryKey","helper.checkKeyRequirements","helper.validateSigningKeyPacket","getEncryptionKey","helper.validateEncryptionKeyPacket","directSignature","primaryKeyExpiry","selfSigKeyExpiry","selfSigExpiry","directSigKeyExpiry","getPrimaryUser","primaryUser","B","pop","cert","sourceKey","destSubkey","srcSubkey","updatedKey","usersToUpdate","dstUser","srcUser","userToUpdate","newUser","subkeysToUpdate","dstSubkey","subkeyToUpdate","newSubkey","getRevocationCertificate","applyRevocationCertificate","revocationCertificate","signPrimaryUser","privateKeys","userSign","signAllUsers","verifyPrimaryUser","verifyAllUsers","results","PublicKey","toPublic","PrivateKey","keyPackets","pubKeyPacket","pubSubkeyPacket","getDecryptionKeys","helper.validateDecryptionKeyPacket","Boolean","addSubkey","defaultOptions","getDefaultSubkeyType","helper.sanitizeKeyOptions","helper.generateSecretSubkey","helper.createBindingSignature","packetList","allowedKeyPackets","createKey","wrapKeyObject","secretSubkeyPackets","subkeyPassphrase","createPreferredAlgos","algos","preferredAlgo","getKeySignatureProperties","symmetricAlgorithms","aeadAlgorithms","flatMap","symmetricAlgorithm","userIDs","userIDPacket","subkeyOptions","subkeySignaturePacket","readKey","armoredKey","binaryKey","keyIndex","readPrivateKey","firstPrivateKeyList","readKeys","armoredKeys","binaryKeys","newKey","readPrivateKeys","oneKeyList","allowedMessagePackets","allowedSymSessionKeyPackets","allowedDetachedSignaturePackets","Message","getEncryptionKeyIDs","keyIDs","unwrapCompressed","onePassSigList","decryptionKeys","passwords","sessionKeys","symEncryptedPacketlist","symEncryptedPacket","expectedSymmetricAlgorithm","sessionKeyObjects","decryptSessionKeys","decryptedPromise","algorithmName","stream.cancel","resultMsg","decryptedSessionKeyPackets","skeskPackets","skeskPacket","pkeskPackets","pkeskPacket","decryptionKey","decryptionKeyPackets","decryptionKeyPacket","serialisedPKESK","pkeskPacketCopy","seen","item","getLiteralData","encryptionKeys","aeadAlgo","selfSigs","selfSig","defaultCipherSuite","desiredCipherSuites","desiredCipherSuite","cipherSuite","defaultSymAlgo","desiredSymAlgo","getPreferredCipherSuite","symmetricAlgoName","aeadAlgoName","maybeKey","encryptionKeyIDs","aeadAlgorithmName","encryptSessionKey","pkESKeyPacket","testDecrypt","accumulator","currentValue","encryptPassword","symEncryptedSessionKeyPacket","pwd","signingKeyIDs","signingUserIDs","literalDataPacket","signaturePackets","createSignaturePackets","onePassSignaturePackets","signDetached","recipientKeyIDs","literalDataList","signatureList","correspondingSigResolve","correspondingSigReject","createVerificationObjects","verifyDetached","appendSignature","detachedSignature","trailingPacket","signingUserID","existingSigPacketlist","unverifiedSigningKey","signaturePacketPromise","verifiedSig","createVerificationObject","readMessage","armoredMessage","binaryMessage","streamType","createMessage","literalDataPacketlist","CleartextMessage","newSignature","emitHeaderAndChecksum","readCleartextMessage","cleartextMessage","checkHashAlgos","hashAlgos","check","hashHeader","parsedHashIDs","createCleartextMessage","checkConfig","toArray","helper.generateSecretKey","formatObject","reformatKey","reformattedKey","sanitize","reformat","revokeKey","revokedKey","decryptKey","clonedPrivateKey","passphrases","encryptKey","encryptionUserIDs","signatureNotations","checkMessage","checkOutputMessageFormat","publicKeys","senderAlgoSupport","recipientPrefs","getPreferredCompressionAlgo","convertStream","expectSigned","linkStreams","checkCleartextOrMessage","checkBinary","checkString","defaultConfigPropsCount","inputConfigProps","inputProp","object","isSafeInteger","rotr","rotl","byteSwap32","Hash","_cloneInto","wrapConstructor","bytesLength","Chi","Maj","HashMD","padOffset","take","dataView","roundClean","oview","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","E","F","G","H","W15","W2","SHA224","HMAC","assertHash","iHash","oHash","assertExists","assertBytes","hmac","abool","title","hexes","padStart","bytesToHex","numberToHexUnpadded","hexToNumber","asciis","_0","_A","_F","_f","asciiToBase16","char","hexToBytes","al","ai","hi","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","isPosBig","inRange","aInRange","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reset","reseed","gen","pred","validatorFns","bigint","val","function","boolean","stringOrUint8Array","field","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","memoized","WeakMap","arg","_3n","_4n","_5n","pow","pow2","invert","FpSqrt","P","p1div4","root","eql","sqr","nv","ONE","legendreC","Q1div2","neg","ZERO","ge","tonelliShanks","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","freeze","MASK","is0","isOdd","lhs","rhs","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","constTimeNegate","condition","negate","validateW","unsafeLadder","precomputeWindow","points","base","window","precomputes","BASE","maxNumber","shiftBy","offset1","offset2","cond1","cond2","wNAFCached","comp","setWindowSize","delete","pippenger","scalars","buckets","lastBits","scalar","resI","sumI","validateBasic","Gx","Gy","validateSigVerOpts","prehash","b2n","h2b","ut","DER","Err","_tlv","dataLen","ut.numberToHexUnpadded","lenLen","first","lengthBytes","_int","toSig","int","tlv","ut.abytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","clearCofactor","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","mod.Field","point","_isCompressed","toAffine","ut.concatBytes","weierstrassEquation","x2","x3","normPrivateKeyToScalar","N","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","ut.aInRange","assertPrjPoint","Point","toAffineMemo","iz","px","py","pz","ax","ay","zz","assertValidMemo","right","fromAffine","normalizeZ","toInv","fromHex","assertValidity","fromPrivateKey","multiply","msm","_setWindowSize","wnaf","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","subtract","multiplyUnsafe","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","cofactor","toRawBytes","isCompressed","_bits","ProjectivePoint","isWithinCurveOrder","ut.inRange","weierstrass","curveDef","bits2int","bits2int_modN","validateOpts","compressedLen","uncompressedLen","modN","CURVE_ORDER","invN","mod.invert","cat","y2","sqrtError","suffix","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","slcNum","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","R","ir","hasHighS","normalizeS","toDERRawBytes","ut.hexToBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","mod.getMinHashLength","fieldLen","minLen","mod.mapHashToField","precompute","isProbPub","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","extraEntropy","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","privateA","publicB","privKey","ut.createHmacDrbg","drbg","sg","_sig","derError","is","getHash","msgs","createCurve","defHash","U32_MASK64","fromBig","Ah","Al","rotlSH","rotlSL","rotlBH","rotlBL","u64","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","SHA384","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_7n","_256n","_0x71n","round","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","Keccak","enableXOF","posOut","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","keccakP","writeInto","bufferOut","xofInto","xof","shake256","wrapXOFConstructorWithOpts","dkLen","genShake","VERIFY_DEFAULT","zip215","twistedEdwards","adjustScalarBytes","domain","uvRatio","mapToCurve","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","isSmallOrder","normed","ut.bytesToNumberLE","isXOdd","isLastByteOdd","getExtendedPublicKey","ut.numberToBytesLE","modN_LE","pointBytes","hashDomainToScalar","context","verifyOpts","SB","ExtendedPoint","montgomery","montgomeryBits","powPminus2","Gu","montgomeryBytes","swap","x_2","x_3","dummy","a24","encodeUCoordinate","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","shake256_114","ed448P","_11n","_22n","_44n","_88n","_223n","ed448_pow_Pminus3div4","b22","b44","b88","b176","b220","b222","b223","ED448_DEF","u2v","u3v","u5v3","secp256k1P","secp256k1N","divNearest","_6n","_23n","a2","POW_2_128","des","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","temp","right1","right2","looping","endloop","loopinc","iterations","padLength","paddedMessage","desAddPadding","desRemovePadding","desCreateKeys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","shifts","lefttemp","righttemp","TripleDES","OpenPGPSymEncCAST5","BlockSize","KeySize","setKey","masking","rotate","keySchedule","getBlockSize","f1","f2","f3","scheduleA","scheduleB","sBox","inn","ki","half","CAST5","MAXINT","rotw","getW","setW","splice","getB","TF","tf","keyBytes","dataBytes","dataOffset","tfsKey","tfsM","tfsG0","tfsG1","tfsFrnd","blk","tfsIrnd","blocksize","open","meKey","moKey","inKey","kLen","sKey","f01","f5b","fef","q0","q1","q2","q3","ror4","ashx","ffm5b","ffmEf","mdsRem","qp","hFun","finalize","createTwofish","Blowfish","BF","bf","BLOCKSIZE","SBOXES","PARRAY","NN","_clean","xx","yy","dd","cc","bb","aa","sboxes","_encryptBlock","vals","dataL","dataR","parray","vector","off","ret","_decryptBlock","jj","kk","BlowFish","TwoFish","SHA1_IV","SHA1_W","SHA1","Rho","Id","Pi","idxL","idxR","shiftsL","shiftsR","Kl","Kr","group","R_BUF","RIPEMD160","h0","h1","h2","h3","h4","ar","br","cr","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","ripemd160","ADD64","INC64","ix","iy","xor0","xor1","BLAKE2B_IV32","SIGMA","f0","i16","Blake2b","outlen","personal","BLOCKBYTES","OUTBYTES_MAX","params32","prealloc","TYPE","VERSION","TAGBYTES_MAX","TAGBYTES_MIN","SALTBYTES_MAX","SALTBYTES_MIN","passwordBYTES_MAX","passwordBYTES_MIN","MEMBYTES_MAX","ADBYTES_MAX","SECRETBYTES_MAX","ARGON2_BLOCK_SIZE","ARGON2_PREHASH_DIGEST_LENGTH","LE32","LE64","H_","V1_in","blake2b","V_r1","XOR","wasmContext","xs","ys","refs","gZ","G2","makePRNG","pass","lane","m_","totalPasses","segmentLength","segmentOffset","prngTmp","g2","ZERO1024","prngR","KB","WASM_PAGE_SIZE","argon2id","memory","wasmInstance","ad","assertLength","lanes","wasmG","wasmG2","wasmXOR","getLZ","wasmLZ","exports","wasmRefs","wasmFn","requiredMemory","grow","lz","newBlock","blockMemory","allocatedMemory","H0","ZERO32","concatArrays","outputBuffer","getH0","initBlock","isDataIndependent","PRNG","J1J2","next","isSIMDSupported","setupWasm","getSIMD","getNonSIMD","WebAssembly","Memory","initial","maximum","wasmModule","importObject","loaded","wasmLoader","instanceObject","BITMASK","BitReader","bitOffset","curByte","hasByte","_ensureByte","seek","n_bit","n_byte","pi","bufToHex","bitreader","Stream","bufOffset","new_pos","writeByte","_byte","crc32Lookup","crc32","getCRC","updateCRC","updateCRCRun","require$$0","require$$1","CRC32","require$$2","mtf","OK","LAST_BLOCK","NOT_BZIP_DATA","UNEXPECTED_INPUT_EOF","UNEXPECTED_OUTPUT_EOF","DATA_ERROR","OUT_OF_MEMORY","OBSOLETE_INPUT","END_OF_BLOCK","ErrorMessages","_throw","status","optDetail","errorCode","Bunzip","inputStream","outputStream","writePos","writeCurrent","writeCount","_start_bunzip","_init_block","_get_next_block","blockCRC","dbufSize","nextoutput","streamCRC","targetBlockCRC","origPointer","symToByte","symTotal","groupCount","nSelectors","mtfSymbol","selectors","hufGroup","symCount","maxLen","MAX_HUFCODE_BITS","permute","limit","pp","MAX_VALUE","byteCount","uc","runPos","dbufCount","selector","dbuf","GROUP_SIZE","nextSym","current","run","writeRun","_read_bunzip","copies","previous","outbyte","outputsize","coerceInputStream","eof","coerceOutputStream","resizeOk","newBuffer","getBuffer","_coerced","lib","multistream","bz","targetStreamCRC","decodeBlock","writeCopies","table","delegate","position","assert"],"mappings":";wZAAA,MAAMA,EAAqBC,OAAO,sBAC5BC,EAAqBD,OAAO,sBAC5BE,EAAoBF,OAAO,qBAE3BG,EAAeH,OAAO,gBAE5B,MAAMI,UAAoBC,MACxB,WAAAC,GACEC,QAEAC,OAAOC,eAAeC,KAAMN,EAAYO,WAExCD,KAAKX,GAAsB,IAAIa,SAAQ,CAACC,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Gt+F,OAAOrB,KAAK,KACrB0/F,KACA,QAASpD,IACRA,EAAY6C,MAKV,MAHLQ,EAAGhD,cAAcL,EAAaC,GAC9B/1F,QAAQ05F,OAAOP,EAAG5C,WAAan8E,EAChB,sDAEvB,CACA,CACA","x_google_ignoreList":[0,1,2,3,12,13,14,15,28,29,52,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,114,115,117,118,119,120,121,122,123,124]} \ No newline at end of file diff --git a/app/node_modules/openpgp/dist/openpgp.mjs b/app/node_modules/openpgp/dist/openpgp.mjs index 960e15cf4..4690044da 100644 --- a/app/node_modules/openpgp/dist/openpgp.mjs +++ b/app/node_modules/openpgp/dist/openpgp.mjs @@ -1,6 +1,21 @@ -/*! OpenPGP.js v5.11.2 - 2024-06-19 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +/*! OpenPGP.js v6.0.0 - 2024-11-04 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + const doneWritingPromise = Symbol('doneWritingPromise'); const doneWritingResolve = Symbol('doneWritingResolve'); const doneWritingReject = Symbol('doneWritingReject'); @@ -10,6 +25,9 @@ const readingIndex = Symbol('readingIndex'); class ArrayStream extends Array { constructor() { super(); + // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work + Object.setPrototypeOf(this, ArrayStream.prototype); + this[doneWritingPromise] = new Promise((resolve, reject) => { this[doneWritingResolve] = resolve; this[doneWritingReject] = reject; @@ -110,15 +128,14 @@ Writer.prototype.abort = async function(reason) { */ Writer.prototype.releaseLock = function() {}; -const isNode = typeof globalThis.process === 'object' && +/* eslint-disable no-prototype-builtins */ +typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; -const NodeReadableStream = isNode && void('stream').Readable; - /** * Check whether data is a Stream, and if so of which type * @param {Any} input data to check - * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false} + * @returns {'web'|'node'|'array'|'web-like'|false} */ function isStream(input) { if (isArrayStream(input)) { @@ -127,11 +144,11 @@ function isStream(input) { if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) { return 'web'; } - if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) { - return 'ponyfill'; - } - if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) { - return 'node'; + // try and detect a node native stream without having to import its class + if (input && + !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) && + typeof input._read === 'function' && typeof input._readableState === 'object') { + throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`'); } if (input && input.getReader) { return 'web-like'; @@ -175,99 +192,12 @@ function concatUint8Array(arrays) { return result; } -const NodeBuffer = isNode && void('buffer').Buffer; -const NodeReadableStream$1 = isNode && void('stream').Readable; - +const doneReadingSet = new WeakSet(); /** - * Web / node stream conversion functions - * From https://github.com/gwicke/node-web-streams + * The external buffer is used to store values that have been peeked or unshifted from the original stream. + * Because of how streams are implemented, such values cannot be "put back" in the original stream, + * but they need to be returned first when reading from the input again. */ - -let nodeToWeb; -let webToNode; - -if (NodeReadableStream$1) { - - /** - * Convert a Node Readable Stream to a Web ReadableStream - * @param {Readable} nodeStream - * @returns {ReadableStream} - */ - nodeToWeb = function(nodeStream) { - let canceled = false; - return new ReadableStream({ - start(controller) { - nodeStream.pause(); - nodeStream.on('data', chunk => { - if (canceled) { - return; - } - if (NodeBuffer.isBuffer(chunk)) { - chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - controller.enqueue(chunk); - nodeStream.pause(); - }); - nodeStream.on('end', () => { - if (canceled) { - return; - } - controller.close(); - }); - nodeStream.on('error', e => controller.error(e)); - }, - pull() { - nodeStream.resume(); - }, - cancel(reason) { - canceled = true; - nodeStream.destroy(reason); - } - }); - }; - - - class NodeReadable extends NodeReadableStream$1 { - constructor(webStream, options) { - super(options); - this._reader = getReader(webStream); - } - - async _read(size) { - try { - while (true) { - const { done, value } = await this._reader.read(); - if (done) { - this.push(null); - break; - } - if (!this.push(value)) { - break; - } - } - } catch (e) { - this.destroy(e); - } - } - - async _destroy(error, callback) { - this._reader.cancel(error).then(callback, callback); - } - } - - /** - * Convert a Web ReadableStream to a Node Readable Stream - * @param {ReadableStream} webStream - * @param {Object} options - * @returns {Readable} - */ - webToNode = function(webStream, options) { - return new NodeReadable(webStream, options); - }; - -} - -const doneReadingSet = new WeakSet(); const externalBuffer = Symbol('externalBuffer'); /** @@ -286,13 +216,10 @@ function Reader(input) { const reader = input.getReader(); this._read = reader.read.bind(reader); this._releaseLock = () => {}; - this._cancel = async () => {}; + this._cancel = () => {}; return; } let streamType = isStream(input); - if (streamType === 'node') { - input = nodeToWeb(input); - } if (streamType) { const reader = input.getReader(); this._read = reader.read.bind(reader); @@ -399,6 +326,7 @@ Reader.prototype.readByte = async function() { Reader.prototype.readBytes = async function(length) { const buffer = []; let bufferLength = 0; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) { @@ -458,6 +386,7 @@ Reader.prototype.unshift = function(...values) { */ Reader.prototype.readToEnd = async function(join=concat) { const result = []; + // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await this.read(); if (done) break; @@ -466,32 +395,6 @@ Reader.prototype.readToEnd = async function(join=concat) { return join(result); }; -let { ReadableStream, WritableStream, TransformStream } = globalThis; - -let toPonyfillReadable, toNativeReadable; - -async function loadStreamsPonyfill() { - if (TransformStream) { - return; - } - - const [ponyfill, adapter] = await Promise.all([ - Promise.resolve().then(function () { return ponyfill_es6; }), - Promise.resolve().then(function () { return webStreamsAdapter; }) - ]); - - ({ ReadableStream, WritableStream, TransformStream } = ponyfill); - - const { createReadableStreamWrapper } = adapter; - - if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) { - toPonyfillReadable = createReadableStreamWrapper(ReadableStream); - toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream); - } -} - -const NodeBuffer$1 = isNode && void('buffer').Buffer; - /** * Convert data to Stream * @param {ReadableStream|Uint8array|String} input data to convert @@ -499,12 +402,6 @@ const NodeBuffer$1 = isNode && void('buffer').Buffer; */ function toStream(input) { let streamType = isStream(input); - if (streamType === 'node') { - return nodeToWeb(input); - } - if (streamType === 'web' && toPonyfillReadable) { - return toPonyfillReadable(input); - } if (streamType) { return input; } @@ -517,7 +414,7 @@ function toStream(input) { } /** - * Convert data to ArrayStream + * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream. * @param {Object} input data to convert * @returns {ArrayStream} Converted data */ @@ -550,9 +447,6 @@ function concat(list) { if (typeof list[0] === 'string') { return list.join(''); } - if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) { - return NodeBuffer$1.concat(list); - } return concatUint8Array(list); } @@ -593,24 +487,6 @@ function concatArrayStream(list) { return result; } -/** - * Get a Reader - * @param {ReadableStream|Uint8array|String} input - * @returns {Reader} - */ -function getReader(input) { - return new Reader(input); -} - -/** - * Get a Writer - * @param {WritableStream} input - * @returns {Writer} - */ -function getWriter(input) { - return new Writer(input); -} - /** * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream. * @param {ReadableStream|Uint8array|String} input @@ -647,6 +523,7 @@ async function pipe(input, target, { const reader = getReader(input); const writer = getWriter(target); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -898,6 +775,7 @@ function passiveClone(input) { const reader = getReader(readable); const writer = getWriter(writable); try { + // eslint-disable-next-line no-constant-condition while (true) { await writer.ready; const { done, value } = await reader.read(); @@ -981,9 +859,8 @@ function slice(input, begin=0, end=Infinity) { if (returnValue.length >= -end) { lastBytes = slice(returnValue, end); return slice(returnValue, begin, end); - } else { - lastBytes = returnValue; } + lastBytes = returnValue; }); } console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`); @@ -992,9 +869,8 @@ function slice(input, begin=0, end=Infinity) { if (input[externalBuffer]) { input = concat(input[externalBuffer].concat([input])); } - if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) { - if (end === Infinity) end = input.length; - return input.subarray(begin, end); + if (isUint8Array(input)) { + return input.subarray(begin, end === Infinity ? input.length : end); } return input.slice(begin, end); } @@ -1026,7 +902,10 @@ async function readToEnd(input, join=concat) { async function cancel(input, reason) { if (isStream(input)) { if (input.cancel) { - return input.cancel(reason); + const cancelled = await input.cancel(reason); + // the stream is not always cancelled at this point, so we wait some more + await new Promise(setTimeout); + return cancelled; } if (input.destroy) { input.destroy(reason); @@ -1055,636 +934,152 @@ function fromAsync(fn) { return arrayStream; } -/* eslint-disable new-cap */ +/** + * Get a Reader + * @param {ReadableStream|Uint8array|String} input + * @returns {Reader} + */ +function getReader(input) { + return new Reader(input); +} /** - * @fileoverview - * BigInteger implementation of basic operations - * that wraps the native BigInt library. - * Operations are not constant time, - * but we try and limit timing leakage where we can - * @module biginteger/native - * @private + * Get a Writer + * @param {WritableStream} input + * @returns {Writer} */ +function getWriter(input) { + return new Writer(input); +} /** - * @private + * @module enums */ -class BigInteger { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on null or undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); - } - if (n instanceof Uint8Array) { - const bytes = n; - const hex = new Array(bytes.length); - for (let i = 0; i < bytes.length; i++) { - const hexByte = bytes[i].toString(16); - hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte; - } - this.value = BigInt('0x0' + hex.join('')); - } else { - this.value = BigInt(n); - } - } +const byValue = Symbol('byValue'); - clone() { - return new BigInteger(this.value); - } +var enums = { - /** - * BigInteger increment in place + /** Maps curve names under various standards to one + * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} + * @enum {String} + * @readonly */ - iinc() { - this.value++; - return this; - } + curve: { + /** NIST P-256 Curve */ + 'nistP256': 'nistP256', + /** @deprecated use `nistP256` instead */ + 'p256': 'nistP256', - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } + /** NIST P-384 Curve */ + 'nistP384': 'nistP384', + /** @deprecated use `nistP384` instead */ + 'p384': 'nistP384', - /** - * BigInteger decrement in place - */ - idec() { - this.value--; - return this; - } + /** NIST P-521 Curve */ + 'nistP521': 'nistP521', + /** @deprecated use `nistP521` instead */ + 'p521': 'nistP521', - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + /** SECG SECP256k1 Curve */ + 'secp256k1': 'secp256k1', - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value += x.value; - return this; - } + /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ + 'ed25519Legacy': 'ed25519Legacy', + /** @deprecated use `ed25519Legacy` instead */ + 'ed25519': 'ed25519Legacy', - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ + 'curve25519Legacy': 'curve25519Legacy', + /** @deprecated use `curve25519Legacy` instead */ + 'curve25519': 'curve25519Legacy', - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value -= x.value; - return this; - } + /** BrainpoolP256r1 Curve */ + 'brainpoolP256r1': 'brainpoolP256r1', - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } + /** BrainpoolP384r1 Curve */ + 'brainpoolP384r1': 'brainpoolP384r1', - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value *= x.value; - return this; - } + /** BrainpoolP512r1 Curve */ + 'brainpoolP512r1': 'brainpoolP512r1' + }, - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. + /** A string to key specifier type + * @enum {Integer} + * @readonly */ - mul(x) { - return this.clone().imul(x); - } + s2k: { + simple: 0, + salted: 1, + iterated: 3, + argon2: 4, + gnu: 101 + }, - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo + /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} + * @enum {Integer} + * @readonly */ - imod(m) { - this.value %= m.value; - if (this.isNegative()) { - this.iadd(m); - } - return this; - } + publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ + rsaEncryptSign: 1, + /** RSA (Encrypt only) [HAC] */ + rsaEncrypt: 2, + /** RSA (Sign only) [HAC] */ + rsaSign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ + elgamal: 16, + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsaLegacy: 22, + /** Reserved for AEDH */ + aedh: 23, + /** Reserved for AEDSA */ + aedsa: 24, + /** X25519 (Encrypt only) */ + x25519: 25, + /** X448 (Encrypt only) */ + x448: 26, + /** Ed25519 (Sign only) */ + ed25519: 27, + /** Ed448 (Sign only) */ + ed448: 28 + }, - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + * @enum {Integer} + * @readonly */ - mod(m) { - return this.clone().imod(m); - } + symmetric: { + /** Not implemented! */ + idea: 1, + tripledes: 2, + cast5: 3, + blowfish: 4, + aes128: 7, + aes192: 8, + aes256: 9, + twofish: 10 + }, - /** - * Compute modular exponentiation using square and multiply - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. + /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + * @enum {Integer} + * @readonly */ - modExp(e, n) { - if (n.isZero()) throw Error('Modulo cannot be zero'); - if (n.isOne()) return new BigInteger(0); - if (e.isNegative()) throw Error('Unsopported negative exponent'); - - let exp = e.value; - let x = this.value; - - x %= n.value; - let r = BigInt(1); - while (exp > BigInt(0)) { - const lsb = exp & BigInt(1); - exp >>= BigInt(1); // e / 2 - // Always compute multiplication step, to reduce timing leakage - const rx = (r * x) % n.value; - // Update r only if lsb is 1 (odd exponent) - r = lsb ? rx : r; - x = (x * x) % n.value; // Square - } - return new BigInteger(r); - } - - - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - const { gcd, x } = this._egcd(n); - if (!gcd.isOne()) { - throw new Error('Inverse does not exist'); - } - return x.add(n).mod(n); - } - - /** - * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) - * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b) - * @param {BigInteger} b - Second operand - * @returns {{ gcd, x, y: BigInteger }} - */ - _egcd(b) { - let x = BigInt(0); - let y = BigInt(1); - let xPrev = BigInt(1); - let yPrev = BigInt(0); - - let a = this.value; - b = b.value; - - while (b !== BigInt(0)) { - const q = a / b; - let tmp = x; - x = xPrev - q * x; - xPrev = tmp; - - tmp = y; - y = yPrev - q * y; - yPrev = tmp; - - tmp = b; - b = a % b; - a = tmp; - } - - return { - x: new BigInteger(xPrev), - y: new BigInteger(yPrev), - gcd: new BigInteger(a) - }; - } - - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} b - Operand - * @returns {BigInteger} gcd - */ - gcd(b) { - let a = this.value; - b = b.value; - while (b !== BigInt(0)) { - const tmp = b; - b = a % b; - a = tmp; - } - return new BigInteger(a); - } - - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value <<= x.value; - return this; - } - - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); - } - - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value >>= x.value; - return this; - } - - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); - } - - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value === x.value; - } - - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value < x.value; - } - - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value <= x.value; - } - - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value > x.value; - } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value >= x.value; - } - - isZero() { - return this.value === BigInt(0); - } - - isOne() { - return this.value === BigInt(1); - } - - isNegative() { - return this.value < BigInt(0); - } - - isEven() { - return !(this.value & BigInt(1)); - } - - abs() { - const res = this.clone(); - if (this.isNegative()) { - res.value = -res.value; - } - return res; - } - - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); - } - - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - const number = Number(this.value); - if (number > Number.MAX_SAFE_INTEGER) { - // We throw and error to conform with the bn.js implementation - throw new Error('Number can only safely store up to 53 bits'); - } - return number; - } - - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - const bit = (this.value >> BigInt(i)) & BigInt(1); - return (bit === BigInt(0)) ? 0 : 1; - } - - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - const zero = new BigInteger(0); - const one = new BigInteger(1); - const negOne = new BigInteger(-1); - - // -1n >> -1n is -1n - // 1n >> 1n is 0n - const target = this.isNegative() ? negOne : zero; - let bitlen = 1; - const tmp = this.clone(); - while (!tmp.irightShift(one).equal(target)) { - bitlen++; - } - return bitlen; - } - - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - const zero = new BigInteger(0); - const negOne = new BigInteger(-1); - - const target = this.isNegative() ? negOne : zero; - const eight = new BigInteger(8); - let len = 1; - const tmp = this.clone(); - while (!tmp.irightShift(eight).equal(target)) { - len++; - } - return len; - } - - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) - // this is faster than shift+mod iterations - let hex = this.value.toString(16); - if (hex.length % 2 === 1) { - hex = '0' + hex; - } - - const rawLength = hex.length / 2; - const bytes = new Uint8Array(length || rawLength); - // parse hex - const offset = length ? (length - rawLength) : 0; - let i = 0; - while (i < rawLength) { - bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); - i++; - } - - if (endian !== 'be') { - bytes.reverse(); - } - - return bytes; - } -} - -const detectBigInt = () => typeof BigInt !== 'undefined'; - -async function getBigInteger() { - if (detectBigInt()) { - return BigInteger; - } else { - const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; }); - return BigInteger; - } -} - -/** - * @module enums - */ - -const byValue = Symbol('byValue'); - -var enums = { - - /** Maps curve names under various standards to one - * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki} - * @enum {String} - * @readonly - */ - curve: { - /** NIST P-256 Curve */ - 'p256': 'p256', - 'P-256': 'p256', - 'secp256r1': 'p256', - 'prime256v1': 'p256', - '1.2.840.10045.3.1.7': 'p256', - '2a8648ce3d030107': 'p256', - '2A8648CE3D030107': 'p256', - - /** NIST P-384 Curve */ - 'p384': 'p384', - 'P-384': 'p384', - 'secp384r1': 'p384', - '1.3.132.0.34': 'p384', - '2b81040022': 'p384', - '2B81040022': 'p384', - - /** NIST P-521 Curve */ - 'p521': 'p521', - 'P-521': 'p521', - 'secp521r1': 'p521', - '1.3.132.0.35': 'p521', - '2b81040023': 'p521', - '2B81040023': 'p521', - - /** SECG SECP256k1 Curve */ - 'secp256k1': 'secp256k1', - '1.3.132.0.10': 'secp256k1', - '2b8104000a': 'secp256k1', - '2B8104000A': 'secp256k1', - - /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */ - 'ed25519Legacy': 'ed25519', - 'ED25519': 'ed25519', - /** @deprecated use `ed25519Legacy` instead */ - 'ed25519': 'ed25519', - 'Ed25519': 'ed25519', - '1.3.6.1.4.1.11591.15.1': 'ed25519', - '2b06010401da470f01': 'ed25519', - '2B06010401DA470F01': 'ed25519', - - /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */ - 'curve25519Legacy': 'curve25519', - 'X25519': 'curve25519', - 'cv25519': 'curve25519', - /** @deprecated use `curve25519Legacy` instead */ - 'curve25519': 'curve25519', - 'Curve25519': 'curve25519', - '1.3.6.1.4.1.3029.1.5.1': 'curve25519', - '2b060104019755010501': 'curve25519', - '2B060104019755010501': 'curve25519', - - /** BrainpoolP256r1 Curve */ - 'brainpoolP256r1': 'brainpoolP256r1', - '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1', - '2b2403030208010107': 'brainpoolP256r1', - '2B2403030208010107': 'brainpoolP256r1', - - /** BrainpoolP384r1 Curve */ - 'brainpoolP384r1': 'brainpoolP384r1', - '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1', - '2b240303020801010b': 'brainpoolP384r1', - '2B240303020801010B': 'brainpoolP384r1', - - /** BrainpoolP512r1 Curve */ - 'brainpoolP512r1': 'brainpoolP512r1', - '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1', - '2b240303020801010d': 'brainpoolP512r1', - '2B240303020801010D': 'brainpoolP512r1' - }, - - /** A string to key specifier type - * @enum {Integer} - * @readonly - */ - s2k: { - simple: 0, - salted: 1, - iterated: 3, - gnu: 101 - }, - - /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1} - * @enum {Integer} - * @readonly - */ - publicKey: { - /** RSA (Encrypt or Sign) [HAC] */ - rsaEncryptSign: 1, - /** RSA (Encrypt only) [HAC] */ - rsaEncrypt: 2, - /** RSA (Sign only) [HAC] */ - rsaSign: 3, - /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ - elgamal: 16, - /** DSA (Sign only) [FIPS186] [HAC] */ - dsa: 17, - /** ECDH (Encrypt only) [RFC6637] */ - ecdh: 18, - /** ECDSA (Sign only) [RFC6637] */ - ecdsa: 19, - /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below) - * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ - eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility - /** @deprecated use `eddsaLegacy` instead */ - ed25519Legacy: 22, - /** @deprecated use `eddsaLegacy` instead */ - eddsa: 22, - /** Reserved for AEDH */ - aedh: 23, - /** Reserved for AEDSA */ - aedsa: 24, - /** X25519 (Encrypt only) */ - x25519: 25, - /** X448 (Encrypt only) */ - x448: 26, - /** Ed25519 (Sign only) */ - ed25519: 27, - /** Ed448 (Sign only) */ - ed448: 28 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - * @enum {Integer} - * @readonly - */ - symmetric: { - plaintext: 0, - /** Not implemented! */ - idea: 1, - tripledes: 2, - cast5: 3, - blowfish: 4, - aes128: 7, - aes192: 8, - aes256: 9, - twofish: 10 - }, - - /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - * @enum {Integer} - * @readonly - */ - compression: { - uncompressed: 0, - /** RFC1951 */ - zip: 1, - /** RFC1950 */ - zlib: 2, - bzip2: 3 - }, + compression: { + uncompressed: 0, + /** RFC1951 */ + zip: 1, + /** RFC1950 */ + zlib: 2, + bzip2: 3 + }, /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} * @enum {Integer} @@ -1697,7 +1092,9 @@ var enums = { sha256: 8, sha384: 9, sha512: 10, - sha224: 11 + sha224: 11, + sha3_256: 12, + sha3_512: 14 }, /** A list of hash names as accepted by webCrypto functions. @@ -1718,6 +1115,7 @@ var enums = { aead: { eax: 1, ocb: 2, + gcm: 3, experimentalGCM: 100 // Private algorithm }, @@ -1743,7 +1141,8 @@ var enums = { userAttribute: 17, symEncryptedIntegrityProtectedData: 18, modificationDetectionCode: 19, - aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1 + padding: 21 }, /** Data types in the literal packet @@ -1899,7 +1298,7 @@ var enums = { placeholderBackwardsCompatibility: 10, preferredSymmetricAlgorithms: 11, revocationKey: 12, - issuer: 16, + issuerKeyID: 16, notationData: 20, preferredHashAlgorithms: 21, preferredCompressionAlgorithms: 22, @@ -1914,7 +1313,8 @@ var enums = { signatureTarget: 31, embeddedSignature: 32, issuerFingerprint: 33, - preferredAEADAlgorithms: 34 + preferredAEADAlgorithms: 34, + preferredCipherSuites: 39 }, /** Key flags @@ -1983,7 +1383,8 @@ var enums = { aead: 2, /** 0x04 - Version 5 Public-Key Packet format and corresponding new * fingerprint format */ - v5Keys: 4 + v5Keys: 4, + seipdv2: 8 }, /** @@ -2029,9 +1430,328 @@ var enums = { }; // GPG4Browsers - An OpenPGP implementation in javascript - -const debugMode = (() => { - try { +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +var config = { + /** + * @memberof module:config + * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} + */ + preferredHashAlgorithm: enums.hash.sha512, + /** + * @memberof module:config + * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} + */ + preferredSymmetricAlgorithm: enums.symmetric.aes256, + /** + * @memberof module:config + * @property {Integer} compression Default compression algorithm {@link module:enums.compression} + */ + preferredCompressionAlgorithm: enums.compression.uncompressed, + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * This option is applicable to: + * - key generation (encryption key preferences), + * - password-based message encryption, and + * - private key encryption. + * In the case of message encryption using public keys, the encryption key preferences are respected instead. + * Note: not all OpenPGP implementations are compatible with this option. + * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10} + * @memberof module:config + * @property {Boolean} aeadProtect + */ + aeadProtect: false, + /** + * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`) + * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`, + * this option must be set, otherwise key parsing and/or key decryption will fail. + * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys + * will be processed incorrectly. + */ + parseAEADEncryptedV4KeysAsLegacy: false, + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aeadProtect is set to true. + * @memberof module:config + * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} + */ + preferredAEADAlgorithm: enums.aead.gcm, + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aeadProtect is set to true. + * Must be an integer value from 0 to 56. + * @memberof module:config + * @property {Integer} aeadChunkSizeByte + */ + aeadChunkSizeByte: 12, + /** + * Use v6 keys. + * Note: not all OpenPGP implementations are compatible with this option. + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + * @memberof module:config + * @property {Boolean} v6Keys + */ + v6Keys: false, + /** + * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet). + * These are non-standard entities, which in the crypto-refresh have been superseded + * by v6 keys and v6 signatures, respectively. + * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries, + * hence parsing them might be necessary in some cases. + */ + enableParsingV5Entities: false, + /** + * S2K (String to Key) type, used for key derivation in the context of secret key encryption + * and password-encrypted data. Weaker s2k options are not allowed. + * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it + * (pending standardisation). + * @memberof module:config + * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k} + */ + s2kType: enums.s2k.iterated, + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}: + * Iteration Count Byte for Iterated and Salted S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`. + * Note: this is the exponent value, not the final number of iterations (refer to specs for more details). + * @memberof module:config + * @property {Integer} s2kIterationCountByte + */ + s2kIterationCountByte: 224, + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}: + * Argon2 parameters for S2K (String to Key). + * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`. + * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"), + * to ensure compatibility with memory-constrained environments. + * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4. + * @memberof module:config + * @property {Object} params + * @property {Integer} params.passes - number of iterations t + * @property {Integer} params.parallelism - degree of parallelism p + * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes. + */ + s2kArgon2Params: { + passes: 3, + parallelism: 4, // lanes + memoryExponent: 16 // 64 MiB of RAM + }, + /** + * Allow decryption of messages without integrity protection. + * This is an **insecure** setting: + * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. + * - it enables downgrade attacks against integrity-protected messages. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedMessages + */ + allowUnauthenticatedMessages: false, + /** + * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to + * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible + * and deferring checking their integrity until the decrypted stream has been read in full. + * + * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity: + * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL + * (see https://efail.de/). + * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data. + * + * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed. + * @memberof module:config + * @property {Boolean} allowUnauthenticatedStream + */ + allowUnauthenticatedStream: false, + /** + * Minimum RSA key size allowed for key generation and message signing, verification and encryption. + * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. + * @memberof module:config + * @property {Number} minRSABits + */ + minRSABits: 2047, + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + * @memberof module:config + * @property {Boolean} passwordCollisionCheck + */ + passwordCollisionCheck: false, + /** + * Allow decryption using RSA keys without `encrypt` flag. + * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug + * where key flags were ignored when selecting a key for encryption. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureDecryptionWithSigningKeys: false, + /** + * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. + * Instead, a verification key will also be consider valid as long as it is valid at the current time. + * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, + * and have self-signature's creation date that does not match the primary key creation date. + * @memberof module:config + * @property {Boolean} allowInsecureDecryptionWithSigningKeys + */ + allowInsecureVerificationWithReformattedKeys: false, + /** + * Allow using keys that do not have any key flags set. + * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages + * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29). + * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation. + * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm. + */ + allowMissingKeyFlags: false, + /** + * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). + * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: + * - new/incoming messages are automatically decrypted (without user interaction); + * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). + * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. + * @memberof module:config + * @property {Boolean} constantTimePKCS1Decryption + */ + constantTimePKCS1Decryption: false, + /** + * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. + * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. + * However, the more algorithms are added, the slower the decryption procedure becomes. + * @memberof module:config + * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} + */ + constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), + /** + * @memberof module:config + * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error + */ + ignoreUnsupportedPackets: true, + /** + * @memberof module:config + * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error + */ + ignoreMalformedPackets: false, + /** + * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only + * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable + * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). + * @memberof module:config + * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] + */ + additionalAllowedPackets: [], + /** + * @memberof module:config + * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages + */ + showVersion: false, + /** + * @memberof module:config + * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages + */ + showComment: false, + /** + * @memberof module:config + * @property {String} versionString A version string to be included in armored messages + */ + versionString: 'OpenPGP.js 6.0.0', + /** + * @memberof module:config + * @property {String} commentString A comment string to be included in armored messages + */ + commentString: 'https://openpgpjs.org', + + /** + * Max userID string length (used for parsing) + * @memberof module:config + * @property {Integer} maxUserIDLength + */ + maxUserIDLength: 1024 * 5, + /** + * Contains notatations that are considered "known". Known notations do not trigger + * validation error when the notation is marked as critical. + * @memberof module:config + * @property {Array} knownNotations + */ + knownNotations: [], + /** + * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design). + * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur + * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of + * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks. + * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases. + */ + nonDeterministicSignaturesViaNotation: true, + /** + * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API. + * When false, certain standard curves will not be supported (depending on the platform). + * @memberof module:config + * @property {Boolean} useEllipticFallback + */ + useEllipticFallback: true, + /** + * Reject insecure hash algorithms + * @memberof module:config + * @property {Set} rejectHashAlgorithms {@link module:enums.hash} + */ + rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), + /** + * Reject insecure message hash algorithms + * @memberof module:config + * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} + */ + rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), + /** + * Reject insecure public key algorithms for key generation and message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} + */ + rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), + /** + * Reject non-standard curves for key generation, message encryption, signing or verification + * @memberof module:config + * @property {Set} rejectCurves {@link module:enums.curve} + */ + rejectCurves: new Set([enums.curve.secp256k1]) +}; + +/** + * @fileoverview This object contains global configuration values. + * @see module:config/config + * @module config + */ + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +const createRequire = () => () => {}; // Must be stripped in browser built + +const debugMode = (() => { + try { return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env } catch (e) {} return false; @@ -2042,6 +1762,8 @@ const util = { return typeof data === 'string' || data instanceof String; }, + nodeRequire: createRequire(), + isArray: function(data) { return data instanceof Array; }, @@ -2050,6 +1772,35 @@ const util = { isStream: isStream, + /** + * Load noble-curves lib on demand and return the requested curve function + * @param {enums.publicKey} publicKeyAlgo + * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA) + * @returns curve implementation + * @throws on unrecognized curve, or curve not implemented by noble-curve + */ + getNobleCurve: async (publicKeyAlgo, curveName) => { + if (!config.useEllipticFallback) { + throw new Error('This curve is only supported in the full build of OpenPGP.js'); + } + + const { nobleCurves } = await Promise.resolve().then(function () { return noble_curves; }); + switch (publicKeyAlgo) { + case enums.publicKey.ecdh: + case enums.publicKey.ecdsa: { + const curve = nobleCurves.get(curveName); + if (!curve) throw new Error('Unsupported curve'); + return curve; + } + case enums.publicKey.x448: + return nobleCurves.get('x448'); + case enums.publicKey.ed448: + return nobleCurves.get('ed448'); + default: + throw new Error('Unsupported curve'); + } + }, + readNumber: function (bytes) { let n = 0; for (let i = 0; i < bytes.length; i++) { @@ -2091,7 +1842,26 @@ const util = { readMPI: function (bytes) { const bits = (bytes[0] << 8) | bytes[1]; const bytelen = (bits + 7) >>> 3; - return bytes.subarray(2, 2 + bytelen); + // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures, + // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed + // has not been authenticated (yet). + // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues. + // Also, AEAD is also not affected. + return util.readExactSubarray(bytes, 2, 2 + bytelen); + }, + + /** + * Read exactly `end - start` bytes from input. + * This is a stricter version of `.subarray`. + * @param {Uint8Array} input - Input data to parse + * @returns {Uint8Array} subarray of size always equal to `end - start` + * @throws if the input array is too short. + */ + readExactSubarray: function (input, start, end) { + if (input.length < (end - start)) { + throw new Error('Input array too short'); + } + return input.subarray(start, end); }, /** @@ -2101,6 +1871,9 @@ const util = { * @returns {Uint8Array} Padded bytes. */ leftPad(bytes, length) { + if (bytes.length > length) { + throw new Error('Input array too long'); + } const padded = new Uint8Array(length); const offset = length - bytes.length; padded.set(bytes, offset); @@ -2156,18 +1929,10 @@ const util = { * @returns {String} Hexadecimal representation of the array. */ uint8ArrayToHex: function (bytes) { - const r = []; - const e = bytes.length; - let c = 0; - let h; - while (c < e) { - h = bytes[c++].toString(16); - while (h.length < 2) { - h = '0' + h; - } - r.push('' + h); - } - return r.join(''); + const hexAlphabet = '0123456789abcdef'; + let s = ''; + bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; }); + return s; }, /** @@ -2378,32 +2143,30 @@ const util = { }, /** - * Get native Web Cryptography api, only the current version of the spec. - * @returns {Object} The SubtleCrypto api or 'undefined'. + * Get native Web Cryptography API. + * @returns {Object} The SubtleCrypto API + * @throws if the API is not available */ getWebCrypto: function() { - return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; + // Fallback for Node 16, which does not expose WebCrypto as a global + const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle; + if (!webCrypto) { + throw new Error('The WebCrypto API is not available'); + } + return webCrypto; }, - /** - * Get BigInteger class - * It wraps the native BigInt type if it's available - * Otherwise it relies on bn.js - * @returns {BigInteger} - * @async - */ - getBigInteger, - /** * Get native Node.js crypto api. * @returns {Object} The crypto module or 'undefined'. */ getNodeCrypto: function() { - return void('crypto'); + return this.nodeRequire('crypto'); }, getNodeZlib: function() { - return void('zlib'); + return this.nodeRequire('zlib'); }, /** @@ -2412,7 +2175,7 @@ const util = { * @returns {Function} The Buffer constructor or 'undefined'. */ getNodeBuffer: function() { - return ({}).Buffer; + return (this.nodeRequire('buffer') || {}).Buffer; }, getHardwareConcurrency: function() { @@ -2420,15 +2183,24 @@ const util = { return navigator.hardwareConcurrency || 1; } - const os = void('os'); // Assume we're on Node.js. + const os = this.nodeRequire('os'); // Assume we're on Node.js. return os.cpus().length; }, - isEmailAddress: function(data) { + /** + * Test email format to ensure basic compliance: + * - must include a single @ + * - no control or space unicode chars allowed + * - no backslash and square brackets (as the latter can mess with the userID parsing) + * - cannot end with a punctuation char + * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation, + * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)). + */ + isEmailAddress: function(data) { if (!util.isString(data)) { return false; } - const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/; + const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u; return re.test(data); }, @@ -2631,14 +2403,15 @@ const util = { * provided with the application or distribution. */ -const Buffer = util.getNodeBuffer(); + +const Buffer$2 = util.getNodeBuffer(); let encodeChunk; let decodeChunk; -if (Buffer) { - encodeChunk = buf => Buffer.from(buf).toString('base64'); +if (Buffer$2) { + encodeChunk = buf => Buffer$2.from(buf).toString('base64'); decodeChunk = str => { - const b = Buffer.from(str, 'base64'); + const b = Buffer$2.from(str, 'base64'); return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); }; } else { @@ -2652,7 +2425,7 @@ if (Buffer) { * @returns {String | ReadableStream} Radix-64 version of input string. * @static */ -function encode(data) { +function encode$1(data) { let buf = new Uint8Array(); return transform(data, value => { buf = util.concatUint8Array([buf, value]); @@ -2676,7 +2449,7 @@ function encode(data) { * @returns {Uint8Array | ReadableStream} Binary array version of input string. * @static */ -function decode(data) { +function decode$2(data) { let buf = ''; return transform(data, value => { buf += value; @@ -2712,7 +2485,7 @@ function decode(data) { * @returns {Uint8Array} An array of 8-bit integers. */ function b64ToUint8Array(base64) { - return decode(base64.replace(/-/g, '+').replace(/_/g, '/')); + return decode$2(base64.replace(/-/g, '+').replace(/_/g, '/')); } /** @@ -2722,254 +2495,30 @@ function b64ToUint8Array(base64) { * @returns {String} Base-64 encoded string. */ function uint8ArrayToB64(bytes, url) { - let encoded = encode(bytes).replace(/[\r\n]/g, ''); - if (url) { + let encoded = encode$1(bytes).replace(/[\r\n]/g, ''); + { encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, ''); } return encoded; } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -var config = { - /** - * @memberof module:config - * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash} - */ - preferredHashAlgorithm: enums.hash.sha256, - /** - * @memberof module:config - * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric} - */ - preferredSymmetricAlgorithm: enums.symmetric.aes256, - /** - * @memberof module:config - * @property {Integer} compression Default compression algorithm {@link module:enums.compression} - */ - preferredCompressionAlgorithm: enums.compression.uncompressed, - /** - * @memberof module:config - * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9 - */ - deflateLevel: 6, - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07} - * @memberof module:config - * @property {Boolean} aeadProtect - */ - aeadProtect: false, - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aeadProtect is set to true. - * @memberof module:config - * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead} - */ - preferredAEADAlgorithm: enums.aead.eax, - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aeadProtect is set to true. - * Must be an integer value from 0 to 56. - * @memberof module:config - * @property {Integer} aeadChunkSizeByte - */ - aeadChunkSizeByte: 12, - /** - * Use V5 keys. - * Note: not all OpenPGP implementations are compatible with this option. - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - * @memberof module:config - * @property {Boolean} v5Keys - */ - v5Keys: false, - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - * @memberof module:config - * @property {Integer} s2kIterationCountByte - */ - s2kIterationCountByte: 224, - /** - * Allow decryption of messages without integrity protection. - * This is an **insecure** setting: - * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe. - * - it enables downgrade attacks against integrity-protected messages. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedMessages - */ - allowUnauthenticatedMessages: false, - /** - * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to - * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible - * and deferring checking their integrity until the decrypted stream has been read in full. - * - * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user. - * @memberof module:config - * @property {Boolean} allowUnauthenticatedStream - */ - allowUnauthenticatedStream: false, - /** - * @memberof module:config - * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum - */ - checksumRequired: false, - /** - * Minimum RSA key size allowed for key generation and message signing, verification and encryption. - * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones. - * @memberof module:config - * @property {Number} minRSABits - */ - minRSABits: 2047, - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - * @memberof module:config - * @property {Boolean} passwordCollisionCheck - */ - passwordCollisionCheck: false, - /** - * @memberof module:config - * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored - */ - revocationsExpire: false, - /** - * Allow decryption using RSA keys without `encrypt` flag. - * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug - * where key flags were ignored when selecting a key for encryption. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureDecryptionWithSigningKeys: false, - /** - * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined. - * Instead, a verification key will also be consider valid as long as it is valid at the current time. - * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted, - * and have self-signature's creation date that does not match the primary key creation date. - * @memberof module:config - * @property {Boolean} allowInsecureDecryptionWithSigningKeys - */ - allowInsecureVerificationWithReformattedKeys: false, - - /** - * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716). - * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply: - * - new/incoming messages are automatically decrypted (without user interaction); - * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely). - * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`. - * @memberof module:config - * @property {Boolean} constantTimePKCS1Decryption - */ - constantTimePKCS1Decryption: false, - /** - * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled. - * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail. - * However, the more algorithms are added, the slower the decryption procedure becomes. - * @memberof module:config - * @property {Set} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric} - */ - constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]), - - /** - * @memberof module:config - * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available - */ - minBytesForWebCrypto: 1000, - /** - * @memberof module:config - * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error - */ - ignoreUnsupportedPackets: true, - /** - * @memberof module:config - * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error - */ - ignoreMalformedPackets: false, - /** - * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only - * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable - * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message). - * @memberof module:config - * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket] - */ - additionalAllowedPackets: [], - /** - * @memberof module:config - * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages - */ - showVersion: false, - /** - * @memberof module:config - * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages - */ - showComment: false, - /** - * @memberof module:config - * @property {String} versionString A version string to be included in armored messages - */ - versionString: 'OpenPGP.js 5.11.2', - /** - * @memberof module:config - * @property {String} commentString A comment string to be included in armored messages - */ - commentString: 'https://openpgpjs.org', - - /** - * Max userID string length (used for parsing) - * @memberof module:config - * @property {Integer} maxUserIDLength - */ - maxUserIDLength: 1024 * 5, - /** - * Contains notatations that are considered "known". Known notations do not trigger - * validation error when the notation is marked as critical. - * @memberof module:config - * @property {Array} knownNotations - */ - knownNotations: [], - /** - * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API. - * When false, certain standard curves will not be supported (depending on the platform). - * Note: the indutny/elliptic curve library is not designed to be constant time. - * @memberof module:config - * @property {Boolean} useIndutnyElliptic - */ - useIndutnyElliptic: true, - /** - * Reject insecure hash algorithms - * @memberof module:config - * @property {Set} rejectHashAlgorithms {@link module:enums.hash} - */ - rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]), - /** - * Reject insecure message hash algorithms - * @memberof module:config - * @property {Set} rejectMessageHashAlgorithms {@link module:enums.hash} - */ - rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]), - /** - * Reject insecure public key algorithms for key generation and message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectPublicKeyAlgorithms {@link module:enums.publicKey} - */ - rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]), - /** - * Reject non-standard curves for key generation, message encryption, signing or verification - * @memberof module:config - * @property {Set} rejectCurves {@link module:enums.curve} - */ - rejectCurves: new Set([enums.curve.secp256k1]) -}; - -/** - * @fileoverview This object contains global configuration values. - * @see module:config/config - * @module config - */ - -// GPG4Browsers - An OpenPGP implementation in javascript /** * Finds out which Ascii Armoring type is used. Throws error if unknown type. @@ -2997,33 +2546,33 @@ function getType(text) { // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipartSection; - } else + } // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipartLast; - } else + } // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; - } else + } // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; - } else + } // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.publicKey; - } else + } // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.privateKey; - } else + } // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE @@ -3057,7 +2606,6 @@ function addheader(customComment, config) { return result; } - /** * Calculates a checksum over the given data and returns it base64 encoded * @param {String | ReadableStream} data - Data to create a CRC-24 checksum for @@ -3066,7 +2614,7 @@ function addheader(customComment, config) { */ function getCheckSum(data) { const crc = createcrc24(data); - return encode(crc); + return encode$1(crc); } // https://create.stephan-brumme.com/crc32/#slicing-by-8-overview @@ -3099,7 +2647,7 @@ for (let i = 0; i <= 0xFF; i++) { } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness -const isLittleEndian = (function() { +const isLittleEndian$1 = (function() { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */); // Int16Array uses the platform's endianness. @@ -3115,7 +2663,7 @@ const isLittleEndian = (function() { function createcrc24(input) { let crc = 0xCE04B7; return transform(input, value => { - const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0; + const len32 = isLittleEndian$1 ? Math.floor(value.length / 4) : 0; const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32); for (let i = 0; i < len32; i++) { crc ^= arr32[i]; @@ -3139,7 +2687,7 @@ function createcrc24(input) { * @private * @param {Array} headers - Armor headers */ -function verifyHeaders(headers) { +function verifyHeaders$1(headers) { for (let i = 0; i < headers.length; i++) { if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) { util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i])); @@ -3151,24 +2699,21 @@ function verifyHeaders(headers) { } /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param {String} text - OpenPGP armored message part - * @returns {Object} An object with attribute "body" containing the body. - * and an attribute "checksum" containing the checksum. + * Remove the (optional) checksum from an armored message. + * @param {String} text - OpenPGP armored message + * @returns {String} The body of the armored message. * @private */ -function splitChecksum(text) { +function removeChecksum(text) { let body = text; - let checksum = ''; const lastEquals = text.lastIndexOf('='); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); - checksum = text.slice(lastEquals + 1).substr(0, 4); } - return { body: body, checksum: checksum }; + return body; } /** @@ -3180,7 +2725,7 @@ function splitChecksum(text) { * @async * @static */ -function unarmor(input, config$1 = config) { +function unarmor(input) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { @@ -3193,8 +2738,7 @@ function unarmor(input, config$1 = config) { let headersDone; let text = []; let textDone; - let checksum; - let data = decode(transformPair(input, async (readable, writable) => { + const data = decode$2(transformPair(input, async (readable, writable) => { const reader = getReader(readable); try { while (true) { @@ -3215,21 +2759,21 @@ function unarmor(input, config$1 = config) { if (!reEmptyLine.test(line)) { lastHeaders.push(line); } else { - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); headersDone = true; - if (textDone || type !== 2) { + if (textDone || type !== enums.armor.signed) { resolve({ text, data, headers, type }); break; } } - } else if (!textDone && type === 2) { + } else if (!textDone && type === enums.armor.signed) { if (!reSplit.test(line)) { // Reverse dash-escaping for msg text.push(line.replace(/^- /, '')); } else { text = text.join('\r\n'); textDone = true; - verifyHeaders(lastHeaders); + verifyHeaders$1(lastHeaders); lastHeaders = []; headersDone = false; } @@ -3259,9 +2803,8 @@ function unarmor(input, config$1 = config) { if (parts.length === 1) { throw new Error('Misformed armored text'); } - const split = splitChecksum(parts[0].slice(0, -1)); - checksum = split.checksum; - await writer.write(split.body); + const body = removeChecksum(parts[0].slice(0, -1)); + await writer.write(body); break; } } @@ -3271,24 +2814,6 @@ function unarmor(input, config$1 = config) { await writer.abort(e); } })); - data = transformPair(data, async (readable, writable) => { - const checksumVerified = readToEnd(getCheckSum(passiveClone(readable))); - checksumVerified.catch(() => {}); - await pipe(readable, writable, { - preventClose: true - }); - const writer = getWriter(writable); - try { - const checksumVerifiedString = (await checksumVerified).replace('\n', ''); - if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) { - throw new Error('Ascii armor integrity check failed'); - } - await writer.ready; - await writer.close(); - } catch (e) { - await writer.abort(e); - } - }); } catch (e) { reject(e); } @@ -3308,10 +2833,13 @@ function unarmor(input, config$1 = config) { * @param {Integer} [partIndex] * @param {Integer} [partTotal] * @param {String} [customComment] - Additional comment to add to the armored string + * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum + * (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks) + * @param {Object} [config] - Full configuration, defaults to openpgp.config * @returns {String | ReadableStream} Armored text. * @static */ -function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) { +function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) { let text; let hash; if (messageType === enums.armor.signed) { @@ -3319,59 +2847,62 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 hash = body.hash; body = body.data; } - const bodyClone = passiveClone(body); + // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug + // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071) + const maybeBodyClone = emitChecksum && passiveClone(body); + const result = []; switch (messageType) { case enums.armor.multipartSection: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n'); break; case enums.armor.multipartLast: result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n'); break; case enums.armor.signed: result.push('-----BEGIN PGP SIGNED MESSAGE-----\n'); - result.push('Hash: ' + hash + '\n\n'); + result.push(hash ? `Hash: ${hash}\n\n` : '\n'); result.push(text.replace(/^-/mg, '- -')); result.push('\n-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; case enums.armor.message: result.push('-----BEGIN PGP MESSAGE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP MESSAGE-----\n'); break; case enums.armor.publicKey: result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PUBLIC KEY BLOCK-----\n'); break; case enums.armor.privateKey: result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP PRIVATE KEY BLOCK-----\n'); break; case enums.armor.signature: result.push('-----BEGIN PGP SIGNATURE-----\n'); result.push(addheader(customComment, config$1)); - result.push(encode(body)); - result.push('=', getCheckSum(bodyClone)); + result.push(encode$1(body)); + maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone)); result.push('-----END PGP SIGNATURE-----\n'); break; } @@ -3379,40689 +2910,25656 @@ function armor(messageType, body, partIndex, partTotal, customComment, config$1 return util.concat(result); } -// GPG4Browsers - An OpenPGP implementation in javascript +async function getLegacyCipher(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + throw new Error('Not a legacy cipher'); + case enums.symmetric.cast5: + case enums.symmetric.blowfish: + case enums.symmetric.twofish: + case enums.symmetric.tripledes: { + const { legacyCiphers } = await Promise.resolve().then(function () { return legacy_ciphers; }); + const cipher = legacyCiphers.get(algo); + if (!cipher) { + throw new Error('Unsupported cipher algorithm'); + } + return cipher; + } + default: + throw new Error('Unsupported cipher algorithm'); + } +} /** - * Implementation of type key id - * - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. + * Get block size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -class KeyID { - constructor() { - this.bytes = ''; - } - - /** - * Parsing method for a key id - * @param {Uint8Array} bytes - Input to read the key id from - */ - read(bytes) { - this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); - return this.bytes.length; - } - - /** - * Serializes the Key ID - * @returns {Uint8Array} Key ID as a Uint8Array. - */ - write() { - return util.stringToUint8Array(this.bytes); - } - - /** - * Returns the Key ID represented as a hexadecimal string - * @returns {String} Key ID as a hexadecimal string. - */ - toHex() { - return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); - } - - /** - * Checks equality of Key ID's - * @param {KeyID} keyID - * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard - */ - equals(keyID, matchWildcard = false) { - return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; - } - - /** - * Checks to see if the Key ID is unset - * @returns {Boolean} True if the Key ID is null. - */ - isNull() { - return this.bytes === ''; - } - - /** - * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) - * @returns {Boolean} True if this is a wildcard Key ID. - */ - isWildcard() { - return /^0+$/.test(this.toHex()); - } - - static mapToHex(keyID) { - return keyID.toHex(); - } - - static fromID(hex) { - const keyID = new KeyID(); - keyID.read(util.hexToUint8Array(hex)); - return keyID; +function getCipherBlockSize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.aes192: + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 16; + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + case enums.symmetric.tripledes: + return 8; + default: + throw new Error('Unsupported cipher'); } +} - static wildcard() { - const keyID = new KeyID(); - keyID.read(new Uint8Array(8)); - return keyID; +/** + * Get key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier + */ +function getCipherKeySize(algo) { + switch (algo) { + case enums.symmetric.aes128: + case enums.symmetric.blowfish: + case enums.symmetric.cast5: + return 16; + case enums.symmetric.aes192: + case enums.symmetric.tripledes: + return 24; + case enums.symmetric.aes256: + case enums.symmetric.twofish: + return 32; + default: + throw new Error('Unsupported cipher'); } } /** - * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. - * @author Artem S Vybornov - * @license MIT + * Get block and key size for given cipher algo + * @param {module:enums.symmetric} algo - alrogithm identifier */ -var AES_asm = function () { - - /** - * Galois Field stuff init flag - */ - var ginit_done = false; +function getCipherParams(algo) { + return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) }; +} - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; +var cipher = /*#__PURE__*/Object.freeze({ + __proto__: null, + getCipherParams: getCipherParams, + getLegacyCipher: getLegacyCipher +}); - /** - * Init Galois Field tables - */ - function ginit() { - gexp3 = [], - glog3 = []; +/** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ - var a = 1, c, d; - for (c = 0; c < 255; c++) { - gexp3[c] = a; - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if (d === 0x80) a ^= 0x1b; - a ^= gexp3[c]; +// MD5 Digest +async function md5(entree) { + const digest = md51(util.uint8ArrayToString(entree)); + return util.hexToUint8Array(hex(digest)); +} - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; +function md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; - ginit_done = true; - } + a = ff(a, b, c, d, k[0], 7, -680876936); + d = ff(d, a, b, c, k[1], 12, -389564586); + c = ff(c, d, a, b, k[2], 17, 606105819); + b = ff(b, c, d, a, k[3], 22, -1044525330); + a = ff(a, b, c, d, k[4], 7, -176418897); + d = ff(d, a, b, c, k[5], 12, 1200080426); + c = ff(c, d, a, b, k[6], 17, -1473231341); + b = ff(b, c, d, a, k[7], 22, -45705983); + a = ff(a, b, c, d, k[8], 7, 1770035416); + d = ff(d, a, b, c, k[9], 12, -1958414417); + c = ff(c, d, a, b, k[10], 17, -42063); + b = ff(b, c, d, a, k[11], 22, -1990404162); + a = ff(a, b, c, d, k[12], 7, 1804603682); + d = ff(d, a, b, c, k[13], 12, -40341101); + c = ff(c, d, a, b, k[14], 17, -1502002290); + b = ff(b, c, d, a, k[15], 22, 1236535329); - /** - * Galois Field multiplication - * @param {number} a - * @param {number} b - * @return {number} - */ - function gmul(a, b) { - var c = gexp3[(glog3[a] + glog3[b]) % 255]; - if (a === 0 || b === 0) c = 0; - return c; - } + a = gg(a, b, c, d, k[1], 5, -165796510); + d = gg(d, a, b, c, k[6], 9, -1069501632); + c = gg(c, d, a, b, k[11], 14, 643717713); + b = gg(b, c, d, a, k[0], 20, -373897302); + a = gg(a, b, c, d, k[5], 5, -701558691); + d = gg(d, a, b, c, k[10], 9, 38016083); + c = gg(c, d, a, b, k[15], 14, -660478335); + b = gg(b, c, d, a, k[4], 20, -405537848); + a = gg(a, b, c, d, k[9], 5, 568446438); + d = gg(d, a, b, c, k[14], 9, -1019803690); + c = gg(c, d, a, b, k[3], 14, -187363961); + b = gg(b, c, d, a, k[8], 20, 1163531501); + a = gg(a, b, c, d, k[13], 5, -1444681467); + d = gg(d, a, b, c, k[2], 9, -51403784); + c = gg(c, d, a, b, k[7], 14, 1735328473); + b = gg(b, c, d, a, k[12], 20, -1926607734); - /** - * Galois Field reciprocal - * @param {number} a - * @return {number} - */ - function ginv(a) { - var i = gexp3[255 - glog3[a]]; - if (a === 0) i = 0; - return i; - } + a = hh(a, b, c, d, k[5], 4, -378558); + d = hh(d, a, b, c, k[8], 11, -2022574463); + c = hh(c, d, a, b, k[11], 16, 1839030562); + b = hh(b, c, d, a, k[14], 23, -35309556); + a = hh(a, b, c, d, k[1], 4, -1530992060); + d = hh(d, a, b, c, k[4], 11, 1272893353); + c = hh(c, d, a, b, k[7], 16, -155497632); + b = hh(b, c, d, a, k[10], 23, -1094730640); + a = hh(a, b, c, d, k[13], 4, 681279174); + d = hh(d, a, b, c, k[0], 11, -358537222); + c = hh(c, d, a, b, k[3], 16, -722521979); + b = hh(b, c, d, a, k[6], 23, 76029189); + a = hh(a, b, c, d, k[9], 4, -640364487); + d = hh(d, a, b, c, k[12], 11, -421815835); + c = hh(c, d, a, b, k[15], 16, 530742520); + b = hh(b, c, d, a, k[2], 23, -995338651); - /** - * AES stuff init flag - */ - var aes_init_done = false; + a = ii(a, b, c, d, k[0], 6, -198630844); + d = ii(d, a, b, c, k[7], 10, 1126891415); + c = ii(c, d, a, b, k[14], 15, -1416354905); + b = ii(b, c, d, a, k[5], 21, -57434055); + a = ii(a, b, c, d, k[12], 6, 1700485571); + d = ii(d, a, b, c, k[3], 10, -1894986606); + c = ii(c, d, a, b, k[10], 15, -1051523); + b = ii(b, c, d, a, k[1], 21, -2054922799); + a = ii(a, b, c, d, k[8], 6, 1873313359); + d = ii(d, a, b, c, k[15], 10, -30611744); + c = ii(c, d, a, b, k[6], 15, -1560198380); + b = ii(b, c, d, a, k[13], 21, 1309151649); + a = ii(a, b, c, d, k[4], 6, -145523070); + d = ii(d, a, b, c, k[11], 10, -1120210379); + c = ii(c, d, a, b, k[2], 15, 718787259); + b = ii(b, c, d, a, k[9], 21, -343485551); - /** - * Encryption, Decryption, S-Box and KeyTransform tables - * - * @type {number[]} - */ - var aes_sbox; + x[0] = add32(a, x[0]); + x[1] = add32(b, x[1]); + x[2] = add32(c, x[2]); + x[3] = add32(d, x[3]); +} - /** - * @type {number[]} - */ - var aes_sinv; +function cmn(q, a, b, x, s, t) { + a = add32(add32(a, q), add32(x, t)); + return add32((a << s) | (a >>> (32 - s)), b); +} - /** - * @type {number[][]} - */ - var aes_enc; +function ff(a, b, c, d, x, s, t) { + return cmn((b & c) | ((~b) & d), a, b, x, s, t); +} - /** - * @type {number[][]} - */ - var aes_dec; +function gg(a, b, c, d, x, s, t) { + return cmn((b & d) | (c & (~d)), a, b, x, s, t); +} - /** - * Init AES tables - */ - function aes_init() { - if (!ginit_done) ginit(); +function hh(a, b, c, d, x, s, t) { + return cmn(b ^ c ^ d, a, b, x, s, t); +} - // Calculates AES S-Box value - function _s(a) { - var c, s, x; - s = x = ginv(a); - for (c = 0; c < 4; c++) { - s = ((s << 1) | (s >>> 7)) & 255; - x ^= s; - } - x ^= 99; - return x; - } - - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [[], [], [], []], - aes_dec = [[], [], [], []]; - - for (var i = 0; i < 256; i++) { - var s = _s(i); - - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; - - // Ecryption and Decryption tables - aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s); - aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i); - // Rotate tables - for (var t = 1; t < 4; t++) { - aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24); - aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24); - } - } +function ii(a, b, c, d, x, s, t) { + return cmn(c ^ (b | (~d)), a, b, x, s, t); +} - aes_init_done = true; +function md51(s) { + const n = s.length; + const state = [1732584193, -271733879, -1732584194, 271733878]; + let i; + for (i = 64; i <= s.length; i += 64) { + md5cycle(state, md5blk(s.substring(i - 64, i))); } - - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-   * 0x0000   encryption key schedule
-   * 0x0400   decryption key schedule
-   * 0x0800   sbox
-   * 0x0c00   inv sbox
-   * 0x1000   encryption tables
-   * 0x2000   decryption tables
-   * 0x3000   reserved (future GCM multiplication lookup table)
-   * 0x4000   data
-   * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param foreign - ignored - * @param buffer - heap buffer to link with - */ - var wrapper = function (foreign, buffer) { - // Init AES stuff for the first time - if (!aes_init_done) aes_init(); - - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set(aes_sbox, 0x0800 >> 2); - heap.set(aes_sinv, 0x0c00 >> 2); - for (var i = 0; i < 4; i++) { - heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2); - heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2); + s = s.substring(i - 64); + const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (i = 0; i < s.length; i++) { + tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); + } + tail[i >> 2] |= 0x80 << ((i % 4) << 3); + if (i > 55) { + md5cycle(state, tail); + for (i = 0; i < 16; i++) { + tail[i] = 0; } + } + tail[14] = n * 8; + md5cycle(state, tail); + return state; +} - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {number} k0 - key vector components - * @param {number} k1 - key vector components - * @param {number} k2 - key vector components - * @param {number} k3 - key vector components - * @param {number} k4 - key vector components - * @param {number} k5 - key vector components - * @param {number} k6 - key vector components - * @param {number} k7 - key vector components - */ - function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { - var ekeys = heap.subarray(0x000, 60), - dkeys = heap.subarray(0x100, 0x100 + 60); - - // Encryption key schedule - ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); - for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { - var k = ekeys[i - 1]; - if ((i % ks === 0) || (ks === 8 && i % ks === 4)) { - k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; - } - if (i % ks === 0) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0); - } - ekeys[i] = ekeys[i - ks] ^ k; - } - - // Decryption key schedule - for (var j = 0; j < i; j += 4) { - for (var jj = 0; jj < 4; jj++) { - var k = ekeys[i - (4 + j) + (4 - jj) % 4]; - if (j < 4 || j >= i - 4) { - dkeys[j + jj] = k; - } else { - dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] - ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] - ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] - ^ aes_dec[3][aes_sbox[k & 255]]; - } - } - } - - // Set rounds number - asm.set_rounds(ks + 5); - } - - // create library object with necessary properties - var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array}; - - var asm = function (stdlib, foreign, buffer) { - "use asm"; - - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); - - /** - * AES core - * @param {number} k - precomputed key schedule offset - * @param {number} s - precomputed sbox table offset - * @param {number} t - precomputed round table offset - * @param {number} r - number of inner rounds to perform - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _core(k, s, t, r, x0, x1, x2, x3) { - k = k | 0; - s = s | 0; - t = t | 0; - r = r | 0; - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k | 0) >> 2], - x1 = x1 ^ HEAP[(k | 4) >> 2], - x2 = x2 ^ HEAP[(k | 8) >> 2], - x3 = x3 ^ HEAP[(k | 12) >> 2]; - - // round 1..r - for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) { - y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } - - // final round - S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], - S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], - S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], - S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2]; - } - - /** - * ECB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } - - /** - * ECB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ecb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - } - - - /** - * CBC mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } - - /** - * CBC mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cbc_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * CFB mode encryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_enc(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } - - - /** - * CFB mode decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _cfb_dec(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * OFB mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ofb(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * CTR mode encryption / decryption - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _ctr(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); - - N3 = (~M3 & N3) | M3 & (N3 + 1); - N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0)); - N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0)); - N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0)); - - S0 = S0 ^ x0; - S1 = S1 ^ x1; - S2 = S2 ^ x2; - S3 = S3 ^ x3; - } - - /** - * GCM mode MAC calculation - * @param {number} x0 - 128-bit input block vector - * @param {number} x1 - 128-bit input block vector - * @param {number} x2 - 128-bit input block vector - * @param {number} x3 - 128-bit input block vector - */ - function _gcm_mac(x0, x1, x2, x3) { - x0 = x0 | 0; - x1 = x1 | 0; - x2 = x2 | 0; - x3 = x3 | 0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0 | 0, - y1 = H1 | 0, - y2 = H2 | 0, - y3 = H3 | 0; - - for (; (i | 0) < 128; i = (i + 1) | 0) { - if (y0 >>> 31) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } - - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); - - c = x3 & 1; - - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); - - if (c) x0 = x0 ^ 0xe1000000; - } - - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } - - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {number} r - number if inner AES rounds - */ - function set_rounds(r) { - r = r | 0; - R = r; - } - - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {number} s0 - state vector - * @param {number} s1 - state vector - * @param {number} s2 - state vector - * @param {number} s3 - state vector - */ - function set_state(s0, s1, s2, s3) { - s0 = s0 | 0; - s1 = s1 | 0; - s2 = s2 | 0; - s3 = s3 | 0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } - - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {number} i0 - iv vector - * @param {number} i1 - iv vector - * @param {number} i2 - iv vector - * @param {number} i3 - iv vector - */ - function set_iv(i0, i1, i2, i3) { - i0 = i0 | 0; - i1 = i1 | 0; - i2 = i2 | 0; - i3 = i3 | 0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } - - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} n0 - nonce vector - * @param {number} n1 - nonce vector - * @param {number} n2 - nonce vector - * @param {number} n3 - nonce vector - */ - function set_nonce(n0, n1, n2, n3) { - n0 = n0 | 0; - n1 = n1 | 0; - n2 = n2 | 0; - n3 = n3 | 0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } - - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} m0 - counter mask vector - * @param {number} m1 - counter mask vector - * @param {number} m2 - counter mask vector - * @param {number} m3 - counter mask vector - */ - function set_mask(m0, m1, m2, m3) { - m0 = m0 | 0; - m1 = m1 | 0; - m2 = m2 | 0; - m3 = m3 | 0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } - - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {number} c0 - counter vector - * @param {number} c1 - counter vector - * @param {number} c2 - counter vector - * @param {number} c3 - counter vector - */ - function set_counter(c0, c1, c2, c3) { - c0 = c0 | 0; - c1 = c1 | 0; - c2 = c2 | 0; - c3 = c3 | 0; - - N3 = (~M3 & N3) | M3 & c3, - N2 = (~M2 & N2) | M2 & c2, - N1 = (~M1 & N1) | M1 & c1, - N0 = (~M0 & N0) | M0 & c0; - } - - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_state(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - return 16; - } - - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {number} pos - offset where to put the data - * @return {number} The number of bytes have been written into the heap, always 16. - */ - function get_iv(pos) { - pos = pos | 0; - - if (pos & 15) return -1; - - DATA[pos | 0] = I0 >>> 24, - DATA[pos | 1] = I0 >>> 16 & 255, - DATA[pos | 2] = I0 >>> 8 & 255, - DATA[pos | 3] = I0 & 255, - DATA[pos | 4] = I1 >>> 24, - DATA[pos | 5] = I1 >>> 16 & 255, - DATA[pos | 6] = I1 >>> 8 & 255, - DATA[pos | 7] = I1 & 255, - DATA[pos | 8] = I2 >>> 24, - DATA[pos | 9] = I2 >>> 16 & 255, - DATA[pos | 10] = I2 >>> 8 & 255, - DATA[pos | 11] = I2 & 255, - DATA[pos | 12] = I3 >>> 24, - DATA[pos | 13] = I3 >>> 16 & 255, - DATA[pos | 14] = I3 >>> 8 & 255, - DATA[pos | 15] = I3 & 255; - - return 16; - } - - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init() { - _ecb_enc(0, 0, 0, 0); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } - - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function cipher(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; - - var ret = 0; +/* there needs to be support for Unicode here, + * unless we pretend that we can redefine the MD-5 + * algorithm for multi-byte characters (perhaps + * by adding every four 16-bit characters and + * shortening the sum to 32 bits). Otherwise + * I suggest performing MD-5 as if every character + * was two bytes--e.g., 0040 0025 = @%--but then + * how will an ordinary MD-5 sum be matched? + * There is no way to standardize text to something + * like UTF-8 before transformation; speed cost is + * utterly prohibitive. The JavaScript standard + * itself needs to look at this: it should start + * providing access to strings as preformed UTF-8 + * 8-bit unsigned value arrays. + */ +function md5blk(s) { /* I figured global was faster. */ + const md5blks = []; + let i; /* Andy King said do it this way. */ + for (i = 0; i < 64; i += 4) { + md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << + 24); + } + return md5blks; +} - if (pos & 15) return -1; +const hex_chr = '0123456789abcdef'.split(''); - while ((len | 0) >= 16) { - _cipher_modes[mode & 7]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); +function rhex(n) { + let s = ''; + let j = 0; + for (; j < 4; j++) { + s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; + } + return s; +} - DATA[pos | 0] = S0 >>> 24, - DATA[pos | 1] = S0 >>> 16 & 255, - DATA[pos | 2] = S0 >>> 8 & 255, - DATA[pos | 3] = S0 & 255, - DATA[pos | 4] = S1 >>> 24, - DATA[pos | 5] = S1 >>> 16 & 255, - DATA[pos | 6] = S1 >>> 8 & 255, - DATA[pos | 7] = S1 & 255, - DATA[pos | 8] = S2 >>> 24, - DATA[pos | 9] = S2 >>> 16 & 255, - DATA[pos | 10] = S2 >>> 8 & 255, - DATA[pos | 11] = S2 & 255, - DATA[pos | 12] = S3 >>> 24, - DATA[pos | 13] = S3 >>> 16 & 255, - DATA[pos | 14] = S3 >>> 8 & 255, - DATA[pos | 15] = S3 & 255; - - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } +function hex(x) { + for (let i = 0; i < x.length; i++) { + x[i] = rhex(x[i]); + } + return x.join(''); +} - return ret | 0; - } +/* this function is much faster, +so if possible we use it. Some IEs +are the only ones I know of that +need the idiotic second function, +generated by an if clause. */ - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {number} pos - offset of the data being processed - * @param {number} len - length of the data being processed - * @return {number} Actual amount of data have been processed. - */ - function mac(mode, pos, len) { - mode = mode | 0; - pos = pos | 0; - len = len | 0; +function add32(a, b) { + return (a + b) & 0xFFFFFFFF; +} - var ret = 0; +/** + * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. + * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} + * @see {@link https://github.com/indutny/hash.js|hash.js} + * @module crypto/hash + */ - if (pos & 15) return -1; - while ((len | 0) >= 16) { - _mac_modes[mode & 1]( - DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], - DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], - DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], - DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15] - ); +const webCrypto$a = util.getWebCrypto(); +const nodeCrypto$9 = util.getNodeCrypto(); +const nodeCryptoHashes = nodeCrypto$9 && nodeCrypto$9.getHashes(); - ret = (ret + 16) | 0, - pos = (pos + 16) | 0, - len = (len - 16) | 0; - } +function nodeHash(type) { + if (!nodeCrypto$9 || !nodeCryptoHashes.includes(type)) { + return; + } + return async function (data) { + const shasum = nodeCrypto$9.createHash(type); + return transform(data, value => { + shasum.update(value); + }, () => new Uint8Array(shasum.digest())); + }; +} - return ret | 0; - } +function nobleHash(nobleHashName, webCryptoHashName) { + const getNobleHash = async () => { + const { nobleHashes } = await Promise.resolve().then(function () { return noble_hashes; }); + const hash = nobleHashes.get(nobleHashName); + if (!hash) throw new Error('Unsupported hash'); + return hash; + }; - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; + return async function(data) { + if (isArrayStream(data)) { + data = await readToEnd(data); + } + if (util.isStream(data)) { + const hash = await getNobleHash(); - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [_cbc_enc, _gcm_mac]; + const hashInstance = hash.create(); + return transform(data, value => { + hashInstance.update(value); + }, () => hashInstance.digest()); + } else if (webCrypto$a && webCryptoHashName) { + return new Uint8Array(await webCrypto$a.digest(webCryptoHashName, data)); + } else { + const hash = await getNobleHash(); - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter: set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac, - }; - }(stdlib, foreign, buffer); + return hash(data); + } + }; +} - asm.set_key = set_key; +var hash$1 = { - return asm; - }; + /** @see module:md5 */ + md5: nodeHash('md5') || md5, + sha1: nodeHash('sha1') || nobleHash('sha1', 'SHA-1'), + sha224: nodeHash('sha224') || nobleHash('sha224'), + sha256: nodeHash('sha256') || nobleHash('sha256', 'SHA-256'), + sha384: nodeHash('sha384') || nobleHash('sha384', 'SHA-384'), + sha512: nodeHash('sha512') || nobleHash('sha512', 'SHA-512'), + ripemd: nodeHash('ripemd160') || nobleHash('ripemd160'), + sha3_256: nodeHash('sha3-256') || nobleHash('sha3_256'), + sha3_512: nodeHash('sha3-512') || nobleHash('sha3_512'), /** - * AES enciphering mode constants - * @enum {number} - * @const + * Create a hash on the specified data using the specified algorithm + * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param {Uint8Array} data - Data to be hashed + * @returns {Promise} Hash value. */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7, + digest: function(algo, data) { + switch (algo) { + case enums.hash.md5: + return this.md5(data); + case enums.hash.sha1: + return this.sha1(data); + case enums.hash.ripemd: + return this.ripemd(data); + case enums.hash.sha256: + return this.sha256(data); + case enums.hash.sha384: + return this.sha384(data); + case enums.hash.sha512: + return this.sha512(data); + case enums.hash.sha224: + return this.sha224(data); + case enums.hash.sha3_256: + return this.sha3_256(data); + case enums.hash.sha3_512: + return this.sha3_512(data); + default: + throw new Error('Unsupported hash function'); + } }, - /** - * AES deciphering mode constants - * @enum {number} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7, - }, - - /** - * AES MAC mode constants - * @enum {number} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1, - }; - /** - * Heap data offset - * @type {number} - * @const + * Returns the hash size in bytes of the specified hash algorithm type + * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns {Integer} Size in bytes of the resulting hash. */ - wrapper.HEAP_DATA = 0x4000; - - return wrapper; -}(); - -function is_bytes(a) { - return a instanceof Uint8Array; -} -function _heap_init(heap, heapSize) { - const size = heap ? heap.byteLength : heapSize || 65536; - if (size & 0xfff || size <= 0) - throw new Error('heap size must be a positive integer and a multiple of 4096'); - heap = heap || new Uint8Array(new ArrayBuffer(size)); - return heap; -} -function _heap_write(heap, hpos, data, dpos, dlen) { - const hlen = heap.length - hpos; - const wlen = hlen < dlen ? hlen : dlen; - heap.set(data.subarray(dpos, dpos + wlen), hpos); - return wlen; -} -function joinBytes(...arg) { - const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0); - const ret = new Uint8Array(totalLenght); - let cursor = 0; - for (let i = 0; i < arg.length; i++) { - ret.set(arg[i], cursor); - cursor += arg[i].length; - } - return ret; -} - -class IllegalStateError extends Error { - constructor(...args) { - super(...args); + getHashByteLength: function(algo) { + switch (algo) { + case enums.hash.md5: + return 16; + case enums.hash.sha1: + case enums.hash.ripemd: + return 20; + case enums.hash.sha256: + return 32; + case enums.hash.sha384: + return 48; + case enums.hash.sha512: + return 64; + case enums.hash.sha224: + return 28; + case enums.hash.sha3_256: + return 32; + case enums.hash.sha3_512: + return 64; + default: + throw new Error('Invalid hash algorithm.'); } + } +}; + +function isBytes$2(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); } -class IllegalArgumentError extends Error { - constructor(...args) { - super(...args); - } +function bytes$1(b, ...lengths) { + if (!isBytes$2(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); } -class SecurityError extends Error { - constructor(...args) { - super(...args); +function output$1(out, instance) { + bytes$1(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } -const heap_pool = []; -const asm_pool = []; -class AES { - constructor(key, iv, padding = true, mode, heap, asm) { - this.pos = 0; - this.len = 0; - this.mode = mode; - // The AES object state - this.pos = 0; - this.len = 0; - this.key = key; - this.iv = iv; - this.padding = padding; - // The AES "worker" - this.acquire_asm(heap, asm); - } - acquire_asm(heap, asm) { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA); - this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer); - this.reset(this.key, this.iv); - } - return { heap: this.heap, asm: this.asm }; +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +// Cast array to different type +const u8$1 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32$2 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// big-endian hardware is rare. Just in case someone still decides to run ciphers: +// early-throw an error because we don't support BE yet. +const isLE$1 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE$1) + throw new Error('Non little-endian hardware is not supported'); +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$2(str) { + if (typeof str !== 'string') + throw new Error(`string expected, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes$1(data) { + if (typeof data === 'string') + data = utf8ToBytes$2(data); + else if (isBytes$2(data)) + data = copyBytes(data); + else + throw new Error(`Uint8Array expected, got ${typeof data}`); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes$1(a); + sum += a.length; } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool.push(this.heap); - asm_pool.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - reset(key, iv) { - const { asm } = this.acquire_asm(); - // Key - const keylen = key.length; - if (keylen !== 16 && keylen !== 24 && keylen !== 32) - throw new IllegalArgumentError('illegal key size'); - const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); - asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0); - // IV - if (iv !== undefined) { - if (iv.length !== 16) - throw new IllegalArgumentError('illegal iv size'); - let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); - asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); - } - else { - asm.set_iv(0, 0, 0, 0); - } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; } - AES_Encrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - let result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes$1(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +const wrapCipher = (params, c) => { + Object.assign(c, params); + return c; +}; +// Polyfill for Safari 14 +function setBigUint64$1(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = 0; + const l = 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Is byte array aligned to 4 byte offset (u32)? +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +// copy bytes to new u8a (aligned). Because Buffer.slice is broken. +function copyBytes(bytes) { + return Uint8Array.from(bytes); +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +// GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. +// Implemented in terms of GHash with conversion function for keys +// GCM GHASH from NIST SP800-38d, SIV from RFC 8452. +// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf +// GHASH modulo: x^128 + x^7 + x^2 + x + 1 +// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 +const BLOCK_SIZE$1 = 16; +// TODO: rewrite +// temporary padding buffer +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = u32$2(ZEROS16); +const POLY$1 = 0xe1; // v = 2*v % POLY +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor) +const mul2$1 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +/** + * `mulX_POLYVAL(ByteReverse(H))` from spec + * @param k mutated in place + */ +function _toGHASHKey(k) { + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +class GHASH { + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + this.blockLen = BLOCK_SIZE$1; + this.outputLen = BLOCK_SIZE$1; + this.s0 = 0; + this.s1 = 0; + this.s2 = 0; + this.s3 = 0; + this.finished = false; + key = toBytes$1(key); + bytes$1(key, 16); + const kView = createView$1(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3); + } + items.push({ s0, s1, s2, s3 }); } } - this.pos = pos; - this.len = len; - return result; - } - AES_Encrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.ENC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let plen = 16 - (len % 16); - let rlen = len; - if (this.hasOwnProperty('padding')) { - if (this.padding) { - for (let p = 0; p < plen; ++p) { - heap[pos + len + p] = plen; + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3); + w += 1; } - len += plen; - rlen = len; - } - else if (len % 16) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); } } - else { - len += plen; + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + const left = data.length % BLOCK_SIZE$1; + for (let i = 0; i < blocks; i++) { + this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); + clean(ZEROS32); // clean tmp buffer } - const result = new Uint8Array(rlen); - if (len) - asm.cipher(amode, hpos + pos, len); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } - AES_Decrypt_process(data) { - if (!is_bytes(data)) - throw new TypeError("data isn't of expected type"); - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let dpos = 0; - let dlen = data.length || 0; - let rpos = 0; - let rlen = (len + dlen) & -16; - let plen = 0; - let wlen = 0; - if (this.padding) { - plen = len + dlen - rlen || 16; - rlen -= plen; + return this; + } + destroy() { + const { t } = this; + // clean precompute table + for (const elm of t) { + (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0); + } + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out; + } + digest() { + const res = new Uint8Array(BLOCK_SIZE$1); + this.digestInto(res); + this.destroy(); + return res; + } +} +class Polyval extends GHASH { + constructor(key, expectedLength) { + key = toBytes$1(key); + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + data = toBytes$1(data); + exists$1(this); + const b32 = u32$2(data); + const left = data.length % BLOCK_SIZE$1; + const blocks = Math.floor(data.length / BLOCK_SIZE$1); + for (let i = 0; i < blocks; i++) { + this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1)); + this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); + clean(ZEROS32); } - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; + return this; + } + digestInto(out) { + exists$1(this); + output$1(out, this); + this.finished = true; + // tmp ugly hack + const { s0, s1, s2, s3 } = this; + const o32 = u32$2(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + return out.reverse(); + } +} +function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes$1(msg)).digest(); + const tmp = hashCons(new Uint8Array(16), 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key, expectedLength) => hashCons(key, expectedLength); + return hashC; +} +const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); +wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); + +// prettier-ignore +/* +AES (Advanced Encryption Standard) aka Rijndael block cipher. + +Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: +1. **S-box**, table substitution +2. **Shift rows**, cyclic shift left of all rows of data array +3. **Mix columns**, multiplying every column by fixed polynomial +4. **Add round key**, round_key xor i-th column of array + +Resources: +- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf +- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf +*/ +const BLOCK_SIZE = 16; +const BLOCK_SIZE32 = 4; +const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// TODO: remove multiplication, binary ops only +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Montgomery ladder + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + box[0] = 0x63; // first elm + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); +// Inverted S-box +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// Rotate u32 by 8 +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// The byte swap operation for uint32 (LE<->BE) +const byteSwap$1 = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +function expandKeyLE(key) { + bytes$1(key); + const len = key.length; + if (![16, 24, 32].includes(len)) + throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); + const { sbox2 } = tableEncoding; + const toClean = []; + if (!isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = u32$2(key); + const Nk = k32.length; + const subByte = (n) => applySbox(sbox2, n, n, n, n); + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; +} +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Inverse key by chunks of 4 (rounds) + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt$6(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]); + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3); + } + // Last round + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function getDst(len, dst) { + if (dst === undefined) + return new Uint8Array(len); + bytes$1(dst); + if (dst.length < len) + throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); + if (!isAligned32(dst)) + throw new Error('unaligned dst'); + return dst; +} +// TODO: investigate merging with ctr32 +function ctrCounter(xk, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const ctr = nonce; + const c32 = u32$2(ctr); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + // Full 128 bit counter with wrap around + let carry = 1; + for (let i = ctr.length - 1; i >= 0; i--) { + carry = (carry + (ctr[i] & 0xff)) | 0; + ctr[i] = carry & 0xff; + carry >>>= 8; + } + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than block) + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +function ctr32(xk, isLE, nonce, src, dst) { + bytes$1(nonce, BLOCK_SIZE); + bytes$1(src); + dst = getDst(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32$2(ctr); + const view = createView$1(ctr); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3]); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ s0; + dst32[i + 1] = src32[i + 1] ^ s1; + dst32[i + 2] = src32[i + 2] ^ s2; + dst32[i + 3] = src32[i + 3] ^ s3; + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt$6(xk, c32[0], c32[1], c32[2], c32[3])); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + const buf = u8$1(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + return dst; +} +/** + * CTR: counter mode. Creates stream cipher. + * Requires good IV. Parallelizable. OK, but no MAC. + */ +const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) { + bytes$1(key); + bytes$1(nonce, BLOCK_SIZE); + function processCtr(buf, dst) { + bytes$1(buf); + if (dst !== undefined) { + bytes$1(dst); + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + bytes$1(data); + if (data.length % BLOCK_SIZE !== 0) { + throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`); + } +} +function validateBlockEncrypt(plaintext, pcks5, dst) { + bytes$1(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pcks5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (!isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32$2(plaintext); + if (pcks5) { + let left = BLOCK_SIZE - remaining; + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + const out = getDst(outLen, dst); + const o = u32$2(out); + return { b, o, out }; +} +function validatePCKS(data, pcks5) { + if (!pcks5) + return data; + const len = data.length; + if (!len) + throw new Error('aes/pcks5: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + if (lastByte <= 0 || lastByte > 16) + throw new Error('aes/pcks5: wrong padding'); + const out = data.subarray(0, -lastByte); + for (let i = 0; i < lastByte; i++) + if (data[len - i - 1] !== lastByte) + throw new Error('aes/pcks5: wrong padding'); + return out; +} +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32$2(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * CBC: Cipher-Block-Chaining. Key is previous round’s block. + * Fragile: needs proper padding. Unauthenticated: needs MAC. + */ +const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) { + bytes$1(key); + bytes$1(iv, 16); + const pcks5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); } - else { - pos = 0; - len = 0; + if (pcks5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]); + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3); + } + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32$2(_iv); + const out = getDst(ciphertext.length, dst); + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32$2(ciphertext); + const o = u32$2(out); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$6(xk, s0, s1, s2, s3); + (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3); } + clean(...toClean); + return validatePCKS(out, pcks5); + }, + }; +}); +/** + * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + */ +const cfb$1 = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) { + bytes$1(key); + bytes$1(iv, 16); + function processCfb(src, isEncrypt, dst) { + bytes$1(src); + const srcLen = src.length; + dst = getDst(srcLen, dst); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + if (!isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32$2(src); + const dst32 = u32$2(dst); + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32$2(_iv); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$6(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + ({ s0, s1, s2, s3 } = encrypt$6(xk, s0, s1, s2, s3)); + const buf = u8$1(new Uint32Array([s0, s1, s2, s3])); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD == null ? 0 : AAD.length; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + h.update(data); + const num = new Uint8Array(16); + const view = createView$1(num); + if (AAD) + setBigUint64$1(view, 0, BigInt(aadLength * 8), isLE); + setBigUint64$1(view, 8, BigInt(data.length * 8), isLE); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} +/** + * GCM: Galois/Counter Mode. + * Modern, parallel version of CTR, with MAC. + * Be careful: MACs can be forged. + * Unsafe to use random nonces under the same key, due to collision chance. + * As for nonce size, prefer 12-byte, instead of 8-byte. + */ +const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) { + bytes$1(key); + bytes$1(nonce); + if (AAD !== undefined) + bytes$1(AAD); + // NIST 800-38d doesn't enforce minimum nonce length. + // We enforce 8 bytes for compat with openssl. + // 12 bytes are recommended. More than 12 bytes would be converted into 12. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); } - this.pos = pos; - this.len = len; - return result; - } - AES_Decrypt_finish() { - let { heap, asm } = this.acquire_asm(); - let amode = AES_asm.DEC[this.mode]; - let hpos = AES_asm.HEAP_DATA; - let pos = this.pos; - let len = this.len; - let rlen = len; - if (len > 0) { - if (len % 16) { - if (this.hasOwnProperty('padding')) { - throw new IllegalArgumentError('data length must be a multiple of the block size'); - } - else { - len += 16 - (len % 16); + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView$1(nonceLen); + setBigUint64$1(view, 8, BigInt(nonce.length * 8), false); + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + bytes$1(plaintext); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + if (ciphertext.length < tagLength) + throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + if (!equalBytes$1(tag, passedTag)) + throw new Error('aes/gcm: invalid ghash tag'); + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; +}); +function isBytes32(a) { + return (a != null && + typeof a === 'object' && + (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')); +} +function encryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = encrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +function decryptBlock(xk, block) { + bytes$1(block, 16); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32$2(block); + let { s0, s1, s2, s3 } = decrypt$6(xk, b32[0], b32[1], b32[2], b32[3]); + (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3); + return block; +} +/** + * AES-W (base for AESKW/AESKWP). + * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf), + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/). + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints. + // If you need it larger, open an issue. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i + (a0 = s0), (a1 = s1 ^ byteSwap$1(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3); } } - asm.cipher(amode, hpos + pos, len); - if (this.hasOwnProperty('padding') && this.padding) { - let pad = heap[pos + rlen - 1]; - if (pad < 1 || pad > 16 || pad > rlen) - throw new SecurityError('bad padding'); - let pcheck = 0; - for (let i = pad; i > 1; i--) - pcheck |= pad ^ heap[pos + rlen - i]; - if (pcheck) - throw new SecurityError('bad padding'); - rlen -= pad; - } + (o32[0] = a0), (o32[1] = a1); // out = A || out } - const result = new Uint8Array(rlen); - if (rlen > 0) { - result.set(heap.subarray(pos, pos + rlen)); + xk.fill(0); + }, + decrypt(kek, out) { + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32$2(out); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap$1(ctr); + const { s0, s1, s2, s3 } = decrypt$6(xk, a0, a1, o32[pos], o32[pos + 1]); + (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3); + } + } + (o32[0] = a0), (o32[1] = a1); } - this.pos = 0; - this.len = 0; - this.release_asm(); - return result; - } -} + xk.fill(0); + }, +}; +const AESKW_IV = new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * For padded version, use aeskwp. + * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/), + * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf). + */ +const aeskw = wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + bytes$1(plaintext); + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes$2(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + bytes$1(ciphertext); + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes$1(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, +})); +// Private, unsafe low-level methods. Can change at any time. +const unsafe = { + expandKeyLE, + expandKeyDecLE, + encrypt: encrypt$6, + decrypt: decrypt$6, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, +}; -class AES_ECB { - static encrypt(data, key, padding = false) { - return new AES_ECB(key, padding).encrypt(data); - } - static decrypt(data, key, padding = false) { - return new AES_ECB(key, padding).decrypt(data); - } - constructor(key, padding = false, aes) { - this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); +// Modified by ProtonTech AG + + +const webCrypto$9 = util.getWebCrypto(); +const nodeCrypto$8 = util.getNodeCrypto(); + +const knownAlgos = nodeCrypto$8 ? nodeCrypto$8.getCiphers() : []; +const nodeAlgos = { + idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ + tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, + cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, + blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, + aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, + aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, + aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined + /* twofish is not implemented in OpenSSL */ +}; + +/** + * CFB encryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} plaintext + * @param {Uint8Array} iv + * @param {Object} config - full configuration, defaults to openpgp.config + * @returns MaybeStream + */ +async function encrypt$5(algo, key, plaintext, iv, config) { + const algoName = enums.read(enums.symmetric, algo); + if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. + return nodeEncrypt$1(algo, key, plaintext, iv); + } + if (util.isAES(algo)) { + return aesEncrypt(algo, key, plaintext, iv); + } + + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; + + const blockc = iv.slice(); + let pt = new Uint8Array(); + const process = chunk => { + if (chunk) { + pt = util.concatUint8Array([pt, chunk]); } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); + const ciphertext = new Uint8Array(pt.length); + let i; + let j = 0; + while (chunk ? pt.length >= block_size : pt.length) { + const encblock = cipherfn.encrypt(blockc); + for (i = 0; i < block_size; i++) { + blockc[i] = pt[i] ^ encblock[i]; + ciphertext[j++] = blockc[i]; + } + pt = pt.subarray(block_size); } + return ciphertext.subarray(0, j); + }; + return transform(plaintext, process, process); } /** - * Javascript AES implementation. - * This is used as fallback if the native Crypto APIs are not available. + * CFB decryption + * @param {enums.symmetric} algo - block cipher algorithm + * @param {Uint8Array} key + * @param {MaybeStream} ciphertext + * @param {Uint8Array} iv + * @returns MaybeStream */ -function aes(length) { - const C = function(key) { - const aesECB = new AES_ECB(key); +async function decrypt$5(algo, key, ciphertext, iv) { + const algoName = enums.read(enums.symmetric, algo); + if (nodeCrypto$8 && nodeAlgos[algoName]) { // Node crypto library. + return nodeDecrypt$1(algo, key, ciphertext, iv); + } + if (util.isAES(algo)) { + return aesDecrypt(algo, key, ciphertext, iv); + } - this.encrypt = function(block) { - return aesECB.encrypt(block); - }; + const LegacyCipher = await getLegacyCipher(algo); + const cipherfn = new LegacyCipher(key); + const block_size = cipherfn.blockSize; - this.decrypt = function(block) { - return aesECB.decrypt(block); - }; + let blockp = iv; + let ct = new Uint8Array(); + const process = chunk => { + if (chunk) { + ct = util.concatUint8Array([ct, chunk]); + } + const plaintext = new Uint8Array(ct.length); + let i; + let j = 0; + while (chunk ? ct.length >= block_size : ct.length) { + const decblock = cipherfn.encrypt(blockp); + blockp = ct.subarray(0, block_size); + for (i = 0; i < block_size; i++) { + plaintext[j++] = blockp[i] ^ decblock[i]; + } + ct = ct.subarray(block_size); + } + return plaintext.subarray(0, j); }; + return transform(ciphertext, process, process); +} - C.blockSize = C.prototype.blockSize = 16; - C.keySize = C.prototype.keySize = length / 8; +class WebCryptoEncryptor { + constructor(algo, key, iv) { + const { blockSize } = getCipherParams(algo); + this.key = key; + this.prevBlock = iv; + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + this.zeroBlock = new Uint8Array(this.blockSize); + } - return C; -} + static async isSupported(algo) { + const { keySize } = getCipherParams(algo); + return webCrypto$9.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt']) + .then(() => true, () => false); + } -//Paul Tero, July 2001 -//http://www.tero.co.uk/des/ -// -//Optimised for performance with large blocks by Michael Hayworth, November 2001 -//http://www.netdealing.com -// -// Modified by Recurity Labs GmbH + async _runCBC(plaintext, nonZeroIV) { + const mode = 'AES-CBC'; + this.keyRef = this.keyRef || await webCrypto$9.importKey('raw', this.key, mode, false, ['encrypt']); + const ciphertext = await webCrypto$9.encrypt( + { name: mode, iv: nonZeroIV || this.zeroBlock }, + this.keyRef, + plaintext + ); + return new Uint8Array(ciphertext).subarray(0, plaintext.length); + } + + async encryptChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const plaintext = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); + const toEncrypt = util.concatUint8Array([ + this.prevBlock, + plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock + ]); -//THIS SOFTWARE IS PROVIDED "AS IS" AND -//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -//SUCH DAMAGE. + const encryptedBlocks = await this._runCBC(toEncrypt); + xorMut$1(encryptedBlocks, plaintext); + this.prevBlock = encryptedBlocks.slice(-this.blockSize); -//des -//this takes the key, the message, and whether to encrypt or decrypt + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; -function des(keys, message, encrypt, mode, iv, padding) { - //declaring this locally speeds things up a bit - const spfunction1 = [ - 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, - 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, - 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, - 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, - 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, - 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 - ]; - const spfunction2 = [ - -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, - -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, - -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, - -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, - -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, - 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, - -0x7fef7fe0, 0x108000 - ]; - const spfunction3 = [ - 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, - 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, - 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, - 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, - 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, - 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 - ]; - const spfunction4 = [ - 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, - 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, - 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, - 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, - 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 - ]; - const spfunction5 = [ - 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, - 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, - 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, - 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, - 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, - 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, - 0x40080000, 0x2080100, 0x40000100 - ]; - const spfunction6 = [ - 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, - 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, - 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, - 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, - 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, - 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 - ]; - const spfunction7 = [ - 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, - 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, - 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, - 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, - 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, - 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 - ]; - const spfunction8 = [ - 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, - 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, - 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, - 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, - 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, - 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 - ]; + return encryptedBlocks; + } - //create the 16 or 48 subkeys we will need - let m = 0; - let i; - let j; - let temp; - let right1; - let right2; - let left; - let right; - let looping; - let cbcleft; - let cbcleft2; - let cbcright; - let cbcright2; - let endloop; - let loopinc; - let len = message.length; + this.i += added.length; + let encryptedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + const curBlock = this.nextBlock; + encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + this.prevBlock = encryptedBlock.slice(); + this.i = 0; - //set up the loops for single and triple des - const iterations = keys.length === 32 ? 3 : 9; //single or triple des - if (iterations === 3) { - looping = encrypt ? [0, 32, 2] : [30, -2, -2]; - } else { - looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + encryptedBlock = new Uint8Array(); + } + + return encryptedBlock; } - //pad the message depending on the padding parameter - //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt - if (encrypt) { - message = desAddPadding(message, padding); - len = message.length; + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + this.nextBlock = this.nextBlock.subarray(0, this.i); + const curBlock = this.nextBlock; + const encryptedBlock = await this._runCBC(this.prevBlock); + xorMut$1(encryptedBlock, curBlock); + result = encryptedBlock.subarray(0, curBlock.length); + } + + this.clearSensitiveData(); + return result; } - //store the result here - let result = new Uint8Array(len); - let k = 0; + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.keyRef = null; + this.key = null; + } - if (mode === 1) { //CBC mode - cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++]; - m = 0; + async encrypt(plaintext) { + // plaintext is internally padded to block length before encryption + const encryptedWithPadding = await this._runCBC( + util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), + this.iv + ); + // drop encrypted padding + const ct = encryptedWithPadding.subarray(0, plaintext.length); + xorMut$1(ct, plaintext); + this.clearSensitiveData(); + return ct; } +} - //loop through each 64 bit chunk of the message - while (m < len) { - left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; +class NobleStreamProcessor { + constructor(forEncryption, algo, key, iv) { + this.forEncryption = forEncryption; + const { blockSize } = getCipherParams(algo); + this.key = unsafe.expandKeyLE(key); - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - left ^= cbcleft; - right ^= cbcright; - } else { - cbcleft2 = cbcleft; - cbcright2 = cbcright; - cbcleft = left; - cbcright = right; - } + if (iv.byteOffset % 4 !== 0) iv = iv.slice(); // aligned arrays required by noble-ciphers + this.prevBlock = getUint32Array(iv); + this.nextBlock = new Uint8Array(blockSize); + this.i = 0; // pointer inside next block + this.blockSize = blockSize; + } + + _runCFB(src) { + const src32 = getUint32Array(src); + const dst = new Uint8Array(src.length); + const dst32 = getUint32Array(dst); + for (let i = 0; i + 4 <= dst32.length; i += 4) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4); } + return dst; + } - //first each 64 but chunk of the message must be permuted according to IP - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); + async processChunk(value) { + const missing = this.nextBlock.length - this.i; + const added = value.subarray(0, missing); + this.nextBlock.set(added, this.i); - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); + if ((this.i + value.length) >= (2 * this.blockSize)) { + const leftover = (value.length - missing) % this.blockSize; + const toProcess = util.concatUint8Array([ + this.nextBlock, + value.subarray(missing, value.length - leftover) + ]); - //do this either 1 or 3 times for each chunk of the message - for (j = 0; j < iterations; j += 3) { - endloop = looping[j + 1]; - loopinc = looping[j + 2]; - //now go through and perform the encryption or decryption - for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency - right1 = right ^ keys[i]; - right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - //the result is attained by passing these bytes through the S selection functions - temp = left; - left = right; - right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> - 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & - 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); - } - temp = left; - left = right; - right = temp; //unreverse left and right - } //for either 1 or 3 iterations + const processedBlocks = this._runCFB(toProcess); - //move then each one bit to the right - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); + // take care of leftover data + if (leftover > 0) this.nextBlock.set(value.subarray(-leftover)); + this.i = leftover; - //now perform IP-1, which is IP in the opposite direction - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((right >>> 2) ^ left) & 0x33333333; - left ^= temp; - right ^= (temp << 2); - temp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= temp; - left ^= (temp << 16); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); + return processedBlocks; + } - //for Cipher Block Chaining mode, xor the message with the previous result - if (mode === 1) { - if (encrypt) { - cbcleft = left; - cbcright = right; - } else { - left ^= cbcleft2; - right ^= cbcright2; - } + this.i += added.length; + + let processedBlock; + if (this.i === this.nextBlock.length) { // block ready to be encrypted + processedBlock = this._runCFB(this.nextBlock); + this.i = 0; + + const remaining = value.subarray(added.length); + this.nextBlock.set(remaining, this.i); + this.i += remaining.length; + } else { + processedBlock = new Uint8Array(); } - result[k++] = (left >>> 24); - result[k++] = ((left >>> 16) & 0xff); - result[k++] = ((left >>> 8) & 0xff); - result[k++] = (left & 0xff); - result[k++] = (right >>> 24); - result[k++] = ((right >>> 16) & 0xff); - result[k++] = ((right >>> 8) & 0xff); - result[k++] = (right & 0xff); - } //for every 8 characters, or 64 bits in the message + return processedBlock; + } - //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt - if (!encrypt) { - result = desRemovePadding(result, padding); + async finish() { + let result; + if (this.i === 0) { // nothing more to encrypt + result = new Uint8Array(); + } else { + const processedBlock = this._runCFB(this.nextBlock); + + result = processedBlock.subarray(0, this.i); + } + + this.clearSensitiveData(); + return result; } - return result; -} //end of des + clearSensitiveData() { + this.nextBlock.fill(0); + this.prevBlock.fill(0); + this.key.fill(0); + } +} -//desCreateKeys -//this takes as input a 64 bit key (even though only 56 bits are used) -//as an array of 2 integers, and returns 16 48 bit keys +async function aesEncrypt(algo, key, pt, iv) { + if (webCrypto$9 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys + const cfb = new WebCryptoEncryptor(algo, key, iv); + return util.isStream(pt) ? transform(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt); + } else if (util.isStream(pt)) { // async callbacks are not accepted by stream.transform unless the input is a stream + const cfb = new NobleStreamProcessor(true, algo, key, iv); + return transform(pt, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).encrypt(pt); +} -function desCreateKeys(key) { - //declaring this locally speeds things up a bit - const pc2bytes0 = [ - 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, - 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 - ]; - const pc2bytes1 = [ - 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, - 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 - ]; - const pc2bytes2 = [ - 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, - 0x1000000, 0x1000008, 0x1000800, 0x1000808 - ]; - const pc2bytes3 = [ - 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, - 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 - ]; - const pc2bytes4 = [ - 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, - 0x41000, 0x1010, 0x41010 - ]; - const pc2bytes5 = [ - 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, - 0x2000000, 0x2000400, 0x2000020, 0x2000420 - ]; - const pc2bytes6 = [ - 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, - 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 - ]; - const pc2bytes7 = [ - 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, - 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 - ]; - const pc2bytes8 = [ - 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, - 0x2000002, 0x2040002, 0x2000002, 0x2040002 - ]; - const pc2bytes9 = [ - 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, - 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 - ]; - const pc2bytes10 = [ - 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, - 0x102000, 0x102020, 0x102000, 0x102020 - ]; - const pc2bytes11 = [ - 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, - 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 - ]; - const pc2bytes12 = [ - 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, - 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 - ]; - const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; +async function aesDecrypt(algo, key, ct, iv) { + if (util.isStream(ct)) { + const cfb = new NobleStreamProcessor(false, algo, key, iv); + return transform(ct, value => cfb.processChunk(value), () => cfb.finish()); + } + return cfb$1(key, iv).decrypt(ct); +} - //how many iterations (1 for des, 3 for triple des) - const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - //stores the return keys - const keys = new Array(32 * iterations); - //now define the left shifts which need to be done - const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - //other variables - let lefttemp; - let righttemp; - let m = 0; - let n = 0; - let temp; +function xorMut$1(a, b) { + const aLength = Math.min(a.length, b.length); + for (let i = 0; i < aLength; i++) { + a[i] = a[i] ^ b[i]; + } +} - for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations - let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; +const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= temp; - left ^= (temp << 4); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 2) ^ right) & 0x33333333; - right ^= temp; - left ^= (temp << 2); - temp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= temp; - right ^= (temp << -16); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); - temp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= temp; - right ^= (temp << 8); - temp = ((left >>> 1) ^ right) & 0x55555555; - right ^= temp; - left ^= (temp << 1); +function nodeEncrypt$1(algo, key, pt, iv) { + const algoName = enums.read(enums.symmetric, algo); + const cipherObj = new nodeCrypto$8.createCipheriv(nodeAlgos[algoName], key, iv); + return transform(pt, value => new Uint8Array(cipherObj.update(value))); +} - //the right side needs to be shifted and to get the last four bits of the left side - temp = (left << 8) | ((right >>> 20) & 0x000000f0); - //left needs to be put upside down - left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); - right = temp; +function nodeDecrypt$1(algo, key, ct, iv) { + const algoName = enums.read(enums.symmetric, algo); + const decipherObj = new nodeCrypto$8.createDecipheriv(nodeAlgos[algoName], key, iv); + return transform(ct, value => new Uint8Array(decipherObj.update(value))); +} - //now go through and perform these shifts on the left and right keys - for (let i = 0; i < shifts.length; i++) { - //shift the keys either one or two bits to the left - if (shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; +var cfb = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$5, + encrypt: encrypt$5 +}); - //now apply PC-2, in such a way that E is easier when encrypting or decrypting - //this conversion will look like PC-2 except only the last 6 bits of each byte are used - //rather than 48 consecutive bits and the order of lines will be according to - //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 - lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( - left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & - 0xf]; - righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | - pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]; - temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; - keys[n++] = lefttemp ^ temp; - keys[n++] = righttemp ^ (temp << 16); - } - } //for each iterations - //return the keys we've created - return keys; -} //end of desCreateKeys +/** + * @fileoverview This module implements AES-CMAC on top of + * native AES-CBC using either the WebCrypto API or Node.js' crypto API. + * @module crypto/cmac + */ -function desAddPadding(message, padding) { - const padLength = 8 - (message.length % 8); +const webCrypto$8 = util.getWebCrypto(); +const nodeCrypto$7 = util.getNodeCrypto(); - let pad; - if (padding === 2 && (padLength < 8)) { //pad the message with spaces - pad = ' '.charCodeAt(0); - } else if (padding === 1) { //PKCS7 padding - pad = padLength; - } else if (!padding && (padLength < 8)) { //pad the message out with null bytes - pad = 0; - } else if (padLength === 8) { - return message; - } else { - throw new Error('des: invalid padding'); - } - const paddedMessage = new Uint8Array(message.length + padLength); - for (let i = 0; i < message.length; i++) { - paddedMessage[i] = message[i]; - } - for (let j = 0; j < padLength; j++) { - paddedMessage[message.length + j] = pad; - } +/** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ - return paddedMessage; -} +const blockLength$3 = 16; -function desRemovePadding(message, padding) { - let padLength = null; - let pad; - if (padding === 2) { // space padded - pad = ' '.charCodeAt(0); - } else if (padding === 1) { // PKCS7 - padLength = message[message.length - 1]; - } else if (!padding) { // null padding - pad = 0; - } else { - throw new Error('des: invalid padding'); - } - if (!padLength) { - padLength = 1; - while (message[message.length - padLength] === pad) { - padLength++; - } - padLength--; +/** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param {Uint8Array} data + * @param {Uint8Array} padding + */ +function rightXORMut(data, padding) { + const offset = data.length - blockLength$3; + for (let i = 0; i < blockLength$3; i++) { + data[i + offset] ^= padding[i]; } + return data; +} - return message.subarray(0, message.length - padLength); +function pad(data, padding, padding2) { + // if |M| in {n, 2n, 3n, ...} + if (data.length && data.length % blockLength$3 === 0) { + // then return M xor→ B, + return rightXORMut(data, padding); + } + // else return (M || 10^(n−1−(|M| mod n))) xor→ P + const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3))); + padded.set(data); + padded[data.length] = 0b10000000; + return rightXORMut(padded, padding2); } -// added by Recurity Labs +const zeroBlock$1 = new Uint8Array(blockLength$3); -function TripleDES(key) { - this.key = []; +async function CMAC(key) { + const cbc = await CBC(key); - for (let i = 0; i < 3; i++) { - this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); - } + // L ← E_K(0^n); B ← 2L; P ← 4L + const padding = util.double(await cbc(zeroBlock$1)); + const padding2 = util.double(padding); - this.encrypt = function(block) { - return des( - desCreateKeys(this.key[2]), - des( - desCreateKeys(this.key[1]), - des( - desCreateKeys(this.key[0]), - block, true, 0, null, null - ), - false, 0, null, null - ), true, 0, null, null - ); + return async function(data) { + // return CBC_K(pad(M; B, P)) + return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3); }; } -TripleDES.keySize = TripleDES.prototype.keySize = 24; -TripleDES.blockSize = TripleDES.prototype.blockSize = 8; - -// This is "original" DES - -function DES(key) { - this.key = key; +async function CBC(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt) { + const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1); + const ct = en.update(pt); + return new Uint8Array(ct); + }; + } - this.encrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, true, 0, null, padding); - }; + if (util.getWebCrypto()) { + try { + key = await webCrypto$8.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); + return async function(pt) { + const ct = await webCrypto$8.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt); + return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - this.decrypt = function(block, padding) { - const keys = desCreateKeys(this.key); - return des(keys, block, false, 0, null, padding); + return async function(pt) { + return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt); }; } -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Copyright 2010 pjacobs@xeekr.com . All rights reserved. - -// Modified by Recurity Labs GmbH +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// fixed/modified by Herbert Hanewinkel, www.haneWIN.de -// check www.haneWIN.de for the latest version -// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. -// CAST-128 is a common OpenPGP cipher. +const webCrypto$7 = util.getWebCrypto(); +const nodeCrypto$6 = util.getNodeCrypto(); +const Buffer$1 = util.getNodeBuffer(); -// CAST5 constructor +const blockLength$2 = 16; +const ivLength$2 = blockLength$2; +const tagLength$2 = blockLength$2; -function OpenPGPSymEncCAST5() { - this.BlockSize = 8; - this.KeySize = 16; +const zero = new Uint8Array(blockLength$2); +const one$1 = new Uint8Array(blockLength$2); one$1[blockLength$2 - 1] = 1; +const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2; - this.setKey = function(key) { - this.masking = new Array(16); - this.rotate = new Array(16); +async function OMAC(key) { + const cmac = await CMAC(key); + return function(t, message) { + return cmac(util.concatUint8Array([t, message])); + }; +} - this.reset(); +async function CTR(key) { + if (util.getNodeCrypto()) { // Node crypto library + return async function(pt, iv) { + const en = new nodeCrypto$6.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); + const ct = Buffer$1.concat([en.update(pt), en.final()]); + return new Uint8Array(ct); + }; + } - if (key.length === this.KeySize) { - this.keySchedule(key); - } else { - throw new Error('CAST-128: keys must be 16 bytes'); + if (util.getWebCrypto()) { + try { + const keyRef = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); + return async function(pt, iv) { + const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt); + return new Uint8Array(ct); + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); } - return true; + } + + return async function(pt, iv) { + return ctr(key, iv).encrypt(pt); }; +} - this.reset = function() { - for (let i = 0; i < 16; i++) { - this.masking[i] = 0; - this.rotate[i] = 0; + +/** + * Class to en/decrypt using EAX mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function EAX(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('EAX mode supports only AES cipher'); + } + + const [ + omac, + ctr + ] = await Promise.all([ + OMAC(key), + CTR(key) + ]); + + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + const [ + omacNonce, + omacAdata + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata) + ]); + const ciphered = await ctr(plaintext, omacNonce); + const omacCiphered = await omac(two, ciphered); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + return util.concatUint8Array([ciphered, tag]); + }, + + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (16 bytes) + * @param {Uint8Array} adata - Associated data to verify + * @returns {Promise} The plaintext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$2) throw new Error('Invalid EAX ciphertext'); + const ciphered = ciphertext.subarray(0, -tagLength$2); + const ctTag = ciphertext.subarray(-tagLength$2); + const [ + omacNonce, + omacAdata, + omacCiphered + ] = await Promise.all([ + omac(zero, nonce), + omac(one$1, adata), + omac(two, ciphered) + ]); + const tag = omacCiphered; // Assumes that omac(*).length === tagLength. + for (let i = 0; i < tagLength$2; i++) { + tag[i] ^= omacAdata[i] ^ omacNonce[i]; + } + if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); + const plaintext = await ctr(ciphered, omacNonce); + return plaintext; } }; +} - this.getBlockSize = function() { - return this.BlockSize; - }; - this.encrypt = function(src) { - const dst = new Array(src.length); +/** + * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. + * @param {Uint8Array} iv - The initialization vector (16 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +EAX.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[8 + i] ^= chunkIndex[i]; + } + return nonce; +}; - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; +EAX.blockLength = blockLength$2; +EAX.ivLength = ivLength$2; +EAX.tagLength = tagLength$2; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 ProtonTech AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; +const blockLength$1 = 16; +const ivLength$1 = 15; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; +// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: +// While OCB [RFC7253] allows the authentication tag length to be of any +// number up to 128 bits long, this document requires a fixed +// authentication tag length of 128 bits (16 octets) for simplicity. +const tagLength$1 = 16; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >>> 16) & 255; - dst[i + 6] = (l >>> 8) & 255; - dst[i + 7] = l & 255; - } - return dst; - }; +function ntz(n) { + let ntz = 0; + for (let i = 1; (n & i) === 0; i <<= 1) { + ntz++; + } + return ntz; +} - this.decrypt = function(src) { - const dst = new Array(src.length); +function xorMut(S, T) { + for (let i = 0; i < S.length; i++) { + S[i] ^= T[i]; + } + return S; +} - for (let i = 0; i < src.length; i += 8) { - let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; - let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; - let t; +function xor(S, T) { + return xorMut(S.slice(), T); +} - t = r; - r = l ^ f1(r, this.masking[15], this.rotate[15]); - l = t; - t = r; - r = l ^ f3(r, this.masking[14], this.rotate[14]); - l = t; - t = r; - r = l ^ f2(r, this.masking[13], this.rotate[13]); - l = t; - t = r; - r = l ^ f1(r, this.masking[12], this.rotate[12]); - l = t; +const zeroBlock = new Uint8Array(blockLength$1); +const one = new Uint8Array([1]); - t = r; - r = l ^ f3(r, this.masking[11], this.rotate[11]); - l = t; - t = r; - r = l ^ f2(r, this.masking[10], this.rotate[10]); - l = t; - t = r; - r = l ^ f1(r, this.masking[9], this.rotate[9]); - l = t; - t = r; - r = l ^ f3(r, this.masking[8], this.rotate[8]); - l = t; +/** + * Class to en/decrypt using OCB mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function OCB(cipher, key) { + const { keySize } = getCipherParams(cipher); + // sanity checks + if (!util.isAES(cipher) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - t = r; - r = l ^ f2(r, this.masking[7], this.rotate[7]); - l = t; - t = r; - r = l ^ f1(r, this.masking[6], this.rotate[6]); - l = t; - t = r; - r = l ^ f3(r, this.masking[5], this.rotate[5]); - l = t; - t = r; - r = l ^ f2(r, this.masking[4], this.rotate[4]); - l = t; + let maxNtz = 0; - t = r; - r = l ^ f1(r, this.masking[3], this.rotate[3]); - l = t; - t = r; - r = l ^ f3(r, this.masking[2], this.rotate[2]); - l = t; - t = r; - r = l ^ f2(r, this.masking[1], this.rotate[1]); - l = t; - t = r; - r = l ^ f1(r, this.masking[0], this.rotate[0]); - l = t; + // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls, + // hence its execution cannot be broken up. + // As a result, WebCrypto cannot currently be used for `encipher`. + const aes = cbc(key, zeroBlock, { disablePadding: true }); + const encipher = block => aes.encrypt(block); + const decipher = block => aes.decrypt(block); + let mask; - dst[i] = (r >>> 24) & 255; - dst[i + 1] = (r >>> 16) & 255; - dst[i + 2] = (r >>> 8) & 255; - dst[i + 3] = r & 255; - dst[i + 4] = (l >>> 24) & 255; - dst[i + 5] = (l >> 16) & 255; - dst[i + 6] = (l >> 8) & 255; - dst[i + 7] = l & 255; - } + constructKeyVariables(); - return dst; - }; - const scheduleA = new Array(4); + function constructKeyVariables() { + const mask_x = encipher(zeroBlock); + const mask_$ = util.double(mask_x); + mask = []; + mask[0] = util.double(mask_$); - scheduleA[0] = new Array(4); - scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; - scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - scheduleA[1] = new Array(4); - scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + mask.x = mask_x; + mask.$ = mask_$; + } - scheduleA[2] = new Array(4); - scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; - scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; - scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; - scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; + function extendKeyVariables(text, adata) { + const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1; + for (let i = maxNtz + 1; i <= newMaxNtz; i++) { + mask[i] = util.double(mask[i - 1]); + } + maxNtz = newMaxNtz; + } + function hash(adata) { + if (!adata.length) { + // Fast path + return zeroBlock; + } - scheduleA[3] = new Array(4); - scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; - scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; - scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; - scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; + // + // Consider A as a sequence of 128-bit blocks + // + const m = adata.length / blockLength$1 | 0; - const scheduleB = new Array(4); + const offset = new Uint8Array(blockLength$1); + const sum = new Uint8Array(blockLength$1); + for (let i = 0; i < m; i++) { + xorMut(offset, mask[ntz(i + 1)]); + xorMut(sum, encipher(xor(offset, adata))); + adata = adata.subarray(blockLength$1); + } - scheduleB[0] = new Array(4); - scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; - scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; - scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; - scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; + // + // Process any final partial block; compute final hash value + // + if (adata.length) { + xorMut(offset, mask.x); - scheduleB[1] = new Array(4); - scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; - scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; - scheduleB[1][2] = [7, 6, 8, 9, 3]; - scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; + const cipherInput = new Uint8Array(blockLength$1); + cipherInput.set(adata, 0); + cipherInput[adata.length] = 0b10000000; + xorMut(cipherInput, offset); + xorMut(sum, encipher(cipherInput)); + } - scheduleB[2] = new Array(4); - scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; - scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; - scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; - scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; + return sum; + } + + /** + * Encrypt/decrypt data. + * @param {encipher|decipher} fn - Encryption/decryption block cipher function + * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. + */ + function crypt(fn, text, nonce, adata) { + // + // Consider P as a sequence of 128-bit blocks + // + const m = text.length / blockLength$1 | 0; + // + // Key-dependent variables + // + extendKeyVariables(text, adata); - scheduleB[3] = new Array(4); - scheduleB[3][0] = [8, 9, 7, 6, 3]; - scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; - scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; - scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; + // + // Nonce-dependent and per-encryption variables + // + // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + // Note: We assume here that tagLength mod 16 == 0. + const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]); + // bottom = str2num(Nonce[123..128]) + const bottom = paddedNonce[blockLength$1 - 1] & 0b111111; + // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + paddedNonce[blockLength$1 - 1] &= 0b11000000; + const kTop = encipher(paddedNonce); + // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); + // Offset_0 = Stretch[1+bottom..128+bottom] + const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); + // Checksum_0 = zeros(128) + const checksum = new Uint8Array(blockLength$1); - // changed 'in' to 'inn' (in javascript 'in' is a reserved word) - this.keySchedule = function(inn) { - const t = new Array(8); - const k = new Array(32); + const ct = new Uint8Array(text.length + tagLength$1); - let j; + // + // Process any whole blocks + // + let i; + let pos = 0; + for (i = 0; i < m; i++) { + // Offset_i = Offset_{i-1} xor L_{ntz(i)} + xorMut(offset, mask[ntz(i + 1)]); + // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + ct.set(xorMut(fn(xor(offset, text)), offset), pos); + // Checksum_i = Checksum_{i-1} xor P_i + xorMut(checksum, fn === encipher ? text : ct.subarray(pos)); - for (let i = 0; i < 4; i++) { - j = i * 4; - t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + text = text.subarray(blockLength$1); + pos += blockLength$1; } - const x = [6, 7, 4, 5]; - let ki = 0; - let w; + // + // Process any final partial block and compute raw tag + // + if (text.length) { + // Offset_* = Offset_m xor L_* + xorMut(offset, mask.x); + // Pad = ENCIPHER(K, Offset_*) + const padding = encipher(offset); + // C_* = P_* xor Pad[1..bitlen(P_*)] + ct.set(xor(text, padding), pos); - for (let half = 0; half < 2; half++) { - for (let round = 0; round < 4; round++) { - for (j = 0; j < 4; j++) { - const a = scheduleA[round][j]; - w = t[a[1]]; + // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) + const xorInput = new Uint8Array(blockLength$1); + xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); + xorInput[text.length] = 0b10000000; + xorMut(checksum, xorInput); + pos += text.length; + } + // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata)); - w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; - w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; - w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; - w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; - w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; - t[a[0]] = w; - } + // + // Assemble ciphertext + // + // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] + ct.set(tag, pos); + return ct; + } - for (j = 0; j < 4; j++) { - const b = scheduleB[round][j]; - w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; - w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; - w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; - w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; - k[ki] = w; - ki++; - } - } - } + return { + /** + * Encrypt plaintext input. + * @param {Uint8Array} plaintext - The cleartext input to be encrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + encrypt: async function(plaintext, nonce, adata) { + return crypt(encipher, plaintext, nonce, adata); + }, - for (let i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; + /** + * Decrypt ciphertext input. + * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted + * @param {Uint8Array} nonce - The nonce (15 bytes) + * @param {Uint8Array} adata - Associated data to sign + * @returns {Promise} The ciphertext output. + */ + decrypt: async function(ciphertext, nonce, adata) { + if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); + + const tag = ciphertext.subarray(-tagLength$1); + ciphertext = ciphertext.subarray(0, -tagLength$1); + + const crypted = crypt(decipher, ciphertext, nonce, adata); + // if (Tag[1..TAGLEN] == T) + if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { + return crypted.subarray(0, -tagLength$1); + } + throw new Error('Authentication tag mismatch'); } }; +} - // These are the three 'f' functions. See RFC 2144, section 2.2. - function f1(d, m, r) { - const t = m + d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; +/** + * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. + * @param {Uint8Array} iv - The initialization vector (15 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +OCB.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[7 + i] ^= chunkIndex[i]; } + return nonce; +}; - function f2(d, m, r) { - const t = m ^ d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; - } +OCB.blockLength = blockLength$1; +OCB.ivLength = ivLength$1; +OCB.tagLength = tagLength$1; - function f3(d, m, r) { - const t = m - d; - const I = (t << r) | (t >>> (32 - r)); - return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const webCrypto$6 = util.getWebCrypto(); +const nodeCrypto$5 = util.getNodeCrypto(); +const Buffer = util.getNodeBuffer(); + +const blockLength = 16; +const ivLength = 12; // size of the IV in bytes +const tagLength = 16; // size of the tag in bytes +const ALGO = 'AES-GCM'; + +/** + * Class to en/decrypt using GCM mode. + * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use + * @param {Uint8Array} key - The encryption key + */ +async function GCM(cipher, key) { + if (cipher !== enums.symmetric.aes128 && + cipher !== enums.symmetric.aes192 && + cipher !== enums.symmetric.aes256) { + throw new Error('GCM mode supports only AES cipher'); } - const sBox = new Array(8); - sBox[0] = [ - 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, - 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, - 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, - 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, - 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, - 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, - 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, - 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, - 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, - 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, - 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, - 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, - 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, - 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, - 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, - 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, - 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, - 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, - 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, - 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, - 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, - 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, - 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, - 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, - 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, - 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, - 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, - 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, - 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, - 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, - 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, - 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf - ]; + if (util.getNodeCrypto()) { // Node crypto library + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + const en = new nodeCrypto$5.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + en.setAAD(adata); + const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext + return new Uint8Array(ct); + }, - sBox[1] = [ - 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, - 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, - 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, - 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, - 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, - 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, - 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, - 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, - 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, - 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, - 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, - 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, - 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, - 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, - 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, - 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, - 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, - 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, - 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, - 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, - 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, - 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, - 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, - 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, - 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, - 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, - 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, - 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, - 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, - 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, - 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, - 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + const de = new nodeCrypto$5.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); + de.setAAD(adata); + de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext + const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]); + return new Uint8Array(pt); + } + }; + } - sBox[2] = [ - 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, - 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, - 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, - 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, - 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, - 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, - 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, - 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, - 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, - 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, - 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, - 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, - 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, - 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, - 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, - 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, - 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, - 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, - 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, - 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, - 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, - 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, - 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, - 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, - 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, - 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, - 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, - 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, - 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, - 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, - 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, - 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 - ]; + if (util.getWebCrypto()) { + try { + const _key = await webCrypto$6.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); + // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages + const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) || + navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/); + return { + encrypt: async function(pt, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && !pt.length) { + return gcm(key, iv, adata).encrypt(pt); + } + const ct = await webCrypto$6.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt); + return new Uint8Array(ct); + }, - sBox[3] = [ - 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, - 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, - 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, - 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, - 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, - 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, - 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, - 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, - 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, - 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, - 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, - 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, - 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, - 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, - 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, - 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, - 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, - 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, - 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, - 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, - 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, - 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, - 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, - 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, - 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, - 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, - 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, - 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, - 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, - 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, - 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, - 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 - ]; + decrypt: async function(ct, iv, adata = new Uint8Array()) { + if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) { + return gcm(key, iv, adata).decrypt(ct); + } + try { + const pt = await webCrypto$6.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct); + return new Uint8Array(pt); + } catch (e) { + if (e.name === 'OperationError') { + throw new Error('Authentication tag mismatch'); + } + } + } + }; + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support operation: ' + err.message); + } + } - sBox[4] = [ - 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, - 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, - 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, - 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, - 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, - 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, - 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, - 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, - 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, - 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, - 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, - 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, - 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, - 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, - 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, - 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, - 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, - 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, - 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, - 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, - 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, - 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, - 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, - 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, - 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, - 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, - 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, - 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, - 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, - 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, - 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, - 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 - ]; + return { + encrypt: async function(pt, iv, adata) { + return gcm(key, iv, adata).encrypt(pt); + }, - sBox[5] = [ - 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, - 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, - 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, - 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, - 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, - 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, - 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, - 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, - 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, - 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, - 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, - 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, - 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, - 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, - 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, - 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, - 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, - 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, - 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, - 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, - 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, - 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, - 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, - 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, - 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, - 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, - 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, - 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, - 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, - 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, - 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, - 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f - ]; + decrypt: async function(ct, iv, adata) { + return gcm(key, iv, adata).decrypt(ct); + } + }; +} - sBox[6] = [ - 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, - 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, - 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, - 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, - 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, - 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, - 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, - 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, - 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, - 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, - 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, - 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, - 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, - 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, - 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, - 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, - 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, - 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, - 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, - 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, - 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, - 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, - 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, - 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, - 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, - 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, - 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, - 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, - 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, - 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, - 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, - 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 - ]; - - sBox[7] = [ - 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, - 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, - 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, - 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, - 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, - 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, - 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, - 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, - 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, - 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, - 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, - 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, - 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, - 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, - 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, - 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, - 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, - 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, - 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, - 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, - 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, - 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, - 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, - 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, - 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, - 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, - 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, - 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, - 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, - 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, - 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, - 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e - ]; -} - -function CAST5(key) { - this.cast5 = new OpenPGPSymEncCAST5(); - this.cast5.setKey(key); - - this.encrypt = function(block) { - return this.cast5.encrypt(block); - }; -} -CAST5.blockSize = CAST5.prototype.blockSize = 8; -CAST5.keySize = CAST5.prototype.keySize = 16; - -/* eslint-disable no-mixed-operators, no-fallthrough */ +/** + * Get GCM nonce. Note: this operation is not defined by the standard. + * A future version of the standard may define GCM mode differently, + * hopefully under a different ID (we use Private/Experimental algorithm + * ID 100) so that we can maintain backwards compatibility. + * @param {Uint8Array} iv - The initialization vector (12 bytes) + * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) + */ +GCM.getNonce = function(iv, chunkIndex) { + const nonce = iv.slice(); + for (let i = 0; i < chunkIndex.length; i++) { + nonce[4 + i] ^= chunkIndex[i]; + } + return nonce; +}; +GCM.blockLength = blockLength; +GCM.ivLength = ivLength; +GCM.tagLength = tagLength; -/* Modified by Recurity Labs GmbH - * - * Cipher.js - * A block-cipher algorithm implementation on JavaScript - * See Cipher.readme.txt for further information. - * - * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] - * This script file is distributed under the LGPL - * - * ACKNOWLEDGMENT - * - * The main subroutines are written by Michiel van Everdingen. - * - * Michiel van Everdingen - * http://home.versatel.nl/MAvanEverdingen/index.html - * - * All rights for these routines are reserved to Michiel van Everdingen. - * +/** + * @fileoverview Cipher modes + * @module crypto/mode */ -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//Math -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -const MAXINT = 0xFFFFFFFF; +var mode = { + /** @see module:crypto/mode/cfb */ + cfb: cfb, + /** @see module:crypto/mode/gcm */ + gcm: GCM, + experimentalGCM: GCM, + /** @see module:crypto/mode/eax */ + eax: EAX, + /** @see module:crypto/mode/ocb */ + ocb: OCB +}; -function rotw(w, n) { - return (w << n | w >>> (32 - n)) & MAXINT; +// Operations are not constant time, but we try and limit timing leakage where we can +const _0n$8 = BigInt(0); +const _1n$d = BigInt(1); +function uint8ArrayToBigInt(bytes) { + const hexAlphabet = '0123456789ABCDEF'; + let s = ''; + bytes.forEach(v => { + s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; + }); + return BigInt('0x0' + s); +} +function mod$2(a, m) { + const reduced = a % m; + return reduced < _0n$8 ? reduced + m : reduced; +} +/** + * Compute modular exponentiation using square and multiply + * @param {BigInt} a - Base + * @param {BigInt} e - Exponent + * @param {BigInt} n - Modulo + * @returns {BigInt} b ** e mod n. + */ +function modExp(b, e, n) { + if (n === _0n$8) + throw Error('Modulo cannot be zero'); + if (n === _1n$d) + return BigInt(0); + if (e < _0n$8) + throw Error('Unsopported negative exponent'); + let exp = e; + let x = b; + x %= n; + let r = BigInt(1); + while (exp > _0n$8) { + const lsb = exp & _1n$d; + exp >>= _1n$d; // e / 2 + // Always compute multiplication step, to reduce timing leakage + const rx = (r * x) % n; + // Update r only if lsb is 1 (odd exponent) + r = lsb ? rx : r; + x = (x * x) % n; // Square + } + return r; } - -function getW(a, i) { - return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +function abs(x) { + return x >= _0n$8 ? x : -x; } - -function setW(a, i, w) { - a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +/** + * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf) + * Given a and b, compute (x, y) such that ax + by = gdc(a, b). + * Negative numbers are also supported. + * @param {BigInt} a - First operand + * @param {BigInt} b - Second operand + * @returns {{ gcd, x, y: bigint }} + */ +function _egcd(aInput, bInput) { + let x = BigInt(0); + let y = BigInt(1); + let xPrev = BigInt(1); + let yPrev = BigInt(0); + // Deal with negative numbers: run algo over absolute values, + // and "move" the sign to the returned x and/or y. + // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers + let a = abs(aInput); + let b = abs(bInput); + const aNegated = aInput < _0n$8; + const bNegated = bInput < _0n$8; + while (b !== _0n$8) { + const q = a / b; + let tmp = x; + x = xPrev - q * x; + xPrev = tmp; + tmp = y; + y = yPrev - q * y; + yPrev = tmp; + tmp = b; + b = a % b; + a = tmp; + } + return { + x: aNegated ? -xPrev : xPrev, + y: bNegated ? -yPrev : yPrev, + gcd: a + }; +} +/** + * Compute the inverse of `a` modulo `n` + * Note: `a` and and `n` must be relatively prime + * @param {BigInt} a + * @param {BigInt} n - Modulo + * @returns {BigInt} x such that a*x = 1 mod n + * @throws {Error} if the inverse does not exist + */ +function modInv(a, n) { + const { gcd, x } = _egcd(a, n); + if (gcd !== _1n$d) { + throw new Error('Inverse does not exist'); + } + return mod$2(x + n, n); +} +/** + * Compute greatest common divisor between this and n + * @param {BigInt} aInput - Operand + * @param {BigInt} bInput - Operand + * @returns {BigInt} gcd + */ +function gcd(aInput, bInput) { + let a = aInput; + let b = bInput; + while (b !== _0n$8) { + const tmp = b; + b = a % b; + a = tmp; + } + return a; +} +/** + * Get this value as an exact Number (max 53 bits) + * Fails if this value is too large + * @returns {Number} + */ +function bigIntToNumber(x) { + const number = Number(x); + if (number > Number.MAX_SAFE_INTEGER) { + // We throw and error to conform with the bn.js implementation + throw new Error('Number can only safely store up to 53 bits'); + } + return number; +} +/** + * Get value of i-th bit + * @param {BigInt} x + * @param {Number} i - Bit index + * @returns {Number} Bit value. + */ +function getBit(x, i) { + const bit = (x >> BigInt(i)) & _1n$d; + return bit === _0n$8 ? 0 : 1; +} +/** + * Compute bit length + */ +function bitLength(x) { + // -1n >> -1n is -1n + // 1n >> 1n is 0n + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + let bitlen = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _1n$d) !== target) { + bitlen++; + } + return bitlen; +} +/** + * Compute byte length + */ +function byteLength(x) { + const target = x < _0n$8 ? BigInt(-1) : _0n$8; + const _8n = BigInt(8); + let len = 1; + let tmp = x; + // eslint-disable-next-line no-cond-assign + while ((tmp >>= _8n) !== target) { + len++; + } + return len; +} +/** + * Get Uint8Array representation of this number + * @param {String} endian - Endianess of output array (defaults to 'be') + * @param {Number} length - Of output array + * @returns {Uint8Array} + */ +function bigIntToUint8Array(x, endian = 'be', length) { + // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/) + // this is faster than shift+mod iterations + let hex = x.toString(16); + if (hex.length % 2 === 1) { + hex = '0' + hex; + } + const rawLength = hex.length / 2; + const bytes = new Uint8Array(length || rawLength); + // parse hex + const offset = length ? length - rawLength : 0; + let i = 0; + while (i < rawLength) { + bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + i++; + } + if (endian !== 'be') { + bytes.reverse(); + } + return bytes; } -function getB(x, n) { - return (x >>> (n * 8)) & 0xFF; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +const nodeCrypto$4 = util.getNodeCrypto(); + +/** + * Retrieve secure random byte array of the specified length + * @param {Integer} length - Length in bytes to generate + * @returns {Uint8Array} Random byte array. + */ +function getRandomBytes(length) { + const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$4?.webcrypto; + if (webcrypto?.getRandomValues) { + const buf = new Uint8Array(length); + return webcrypto.getRandomValues(buf); + } else { + throw new Error('No secure random number generator available.'); + } } -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Twofish -// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/** + * Create a secure random BigInt that is greater than or equal to min and less than max. + * @param {bigint} min - Lower bound, included + * @param {bigint} max - Upper bound, excluded + * @returns {bigint} Random BigInt. + * @async + */ +function getRandomBigInteger(min, max) { + if (max < min) { + throw new Error('Illegal parameter value: max <= min'); + } -function createTwofish() { - // - let keyBytes = null; - let dataBytes = null; - let dataOffset = -1; - // var dataLength = -1; - // var idx2 = -1; - // + const modulus = max - min; + const bytes = byteLength(modulus); - let tfsKey = []; - let tfsM = [ - [], - [], - [], - [] - ]; + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8)); + return mod$2(r, modulus) + min; +} - function tfsInit(key) { - keyBytes = key; - let i; - let a; - let b; - let c; - let d; - const meKey = []; - const moKey = []; - const inKey = []; - let kLen; - const sKey = []; - let f01; - let f5b; - let fef; +var random = /*#__PURE__*/Object.freeze({ + __proto__: null, + getRandomBigInteger: getRandomBigInteger, + getRandomBytes: getRandomBytes +}); - const q0 = [ - [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], - [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] - ]; - const q1 = [ - [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], - [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] - ]; - const q2 = [ - [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], - [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] - ]; - const q3 = [ - [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], - [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] - ]; - const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; - const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; - const q = [ - [], - [] - ]; - const m = [ - [], - [], - [], - [] - ]; - - function ffm5b(x) { - return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +/** + * @fileoverview Algorithms for probabilistic random prime generation + * @module crypto/public_key/prime + */ +const _1n$c = BigInt(1); +/** + * Generate a probably prime random number + * @param bits - Bit length of the prime + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function randomProbablePrime(bits, e, k) { + const _30n = BigInt(30); + const min = _1n$c << BigInt(bits - 1); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 + * the next possible prime is mod 30: + * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 + */ + const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; + let n = getRandomBigInteger(min, min << _1n$c); + let i = bigIntToNumber(mod$2(n, _30n)); + do { + n += BigInt(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (bitLength(n) > bits) { + n = mod$2(n, min << _1n$c); + n += min; + i = bigIntToNumber(mod$2(n, _30n)); + } + } while (!isProbablePrime(n, e, k)); + return n; +} +/** + * Probabilistic primality testing + * @param n - Number to test + * @param e - Optional RSA exponent to check against the prime + * @param k - Optional number of iterations of Miller-Rabin test + */ +function isProbablePrime(n, e, k) { + if (e && gcd(n - _1n$c, e) !== _1n$c) { + return false; } - - function ffmEf(x) { - return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + if (!divisionTest(n)) { + return false; } - - function mdsRem(p, q) { - let i; - let t; - let u; - for (i = 0; i < 8; i++) { - t = q >>> 24; - q = ((q << 8) & MAXINT) | p >>> 24; - p = (p << 8) & MAXINT; - u = t << 1; - if (t & 128) { - u ^= 333; + if (!fermat(n)) { + return false; + } + if (!millerRabin(n, k)) { + return false; + } + // TODO implement the Lucas test + // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + return true; +} +/** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n != 1. + * @param n - Number to test + * @param b - Optional Fermat test base + */ +function fermat(n, b = BigInt(2)) { + return modExp(b, n - _1n$c, n) === _1n$c; +} +function divisionTest(n) { + const _0n = BigInt(0); + return smallPrimes.every(m => mod$2(n, m) !== _0n); +} +// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c +const smallPrimes = [ + 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, + 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, + 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, + 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, + 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, + 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, + 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, + 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, + 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, + 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, + 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, + 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, + 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, + 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, + 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, + 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, + 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, + 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, + 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, + 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, + 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, + 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, + 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, + 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, + 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, + 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, + 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, + 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, + 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, + 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, + 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, + 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, + 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, + 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, + 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, + 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, + 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, + 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, + 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, + 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, + 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, + 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, + 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, + 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, + 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, + 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, + 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, + 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, + 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, + 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, + 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, + 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, + 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, + 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, + 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, + 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, + 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, + 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, + 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, + 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, + 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, + 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, + 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, + 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, + 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, + 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, + 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, + 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, + 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, + 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, + 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, + 4957, 4967, 4969, 4973, 4987, 4993, 4999 +].map(n => BigInt(n)); +// Miller-Rabin - Miller Rabin algorithm for primality test +// Copyright Fedor Indutny, 2014. +// +// This software is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin +// Sample syntax for Fixed-Base Miller-Rabin: +// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) +/** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n - Number to test + * @param k - Optional number of iterations of Miller-Rabin test + * @param rand - Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ +function millerRabin(n, k, rand) { + const len = bitLength(n); + if (!k) { + k = Math.max(1, (len / 48) | 0); + } + const n1 = n - _1n$c; // n - 1 + // Find d and s, (n - 1) = (2 ^ s) * d; + let s = 0; + while (!getBit(n1, s)) { + s++; + } + const d = n >> BigInt(s); + for (; k > 0; k--) { + const a = getRandomBigInteger(BigInt(2), n1); + let x = modExp(a, d, n); + if (x === _1n$c || x === n1) { + continue; } - q ^= t ^ (u << 16); - u ^= t >>> 1; - if (t & 1) { - u ^= 166; + let i; + for (i = 1; i < s; i++) { + x = mod$2(x * x, n); + if (x === _1n$c) { + return false; + } + if (x === n1) { + break; + } + } + if (i === s) { + return false; } - q ^= u << 24 | u << 8; - } - return q; - } - - function qp(n, x) { - const a = x >> 4; - const b = x & 15; - const c = q0[n][a ^ b]; - const d = q1[n][ror4[b] ^ ashx[a]]; - return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; } + return true; +} - function hFun(x, key) { - let a = getB(x, 0); - let b = getB(x, 1); - let c = getB(x, 2); - let d = getB(x, 3); - switch (kLen) { - case 4: - a = q[1][a] ^ getB(key[3], 0); - b = q[0][b] ^ getB(key[3], 1); - c = q[0][c] ^ getB(key[3], 2); - d = q[1][d] ^ getB(key[3], 3); - case 3: - a = q[1][a] ^ getB(key[2], 0); - b = q[1][b] ^ getB(key[2], 1); - c = q[0][c] ^ getB(key[2], 2); - d = q[0][d] ^ getB(key[2], 3); - case 2: - a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); - b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); - c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); - d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); - } - return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - keyBytes = keyBytes.slice(0, 32); - i = keyBytes.length; - while (i !== 16 && i !== 24 && i !== 32) { - keyBytes[i++] = 0; - } - for (i = 0; i < keyBytes.length; i += 4) { - inKey[i >> 2] = getW(keyBytes, i); - } - for (i = 0; i < 256; i++) { - q[0][i] = qp(0, i); - q[1][i] = qp(1, i); - } - for (i = 0; i < 256; i++) { - f01 = q[1][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - f01 = q[0][i]; - f5b = ffm5b(f01); - fef = ffmEf(f01); - m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } +/** + * ASN1 object identifiers for hashes + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} + */ +const hash_headers = []; +hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, + 0x10]; +hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; +hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; +hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, + 0x04, 0x20]; +hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x30]; +hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40]; +hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C]; - kLen = inKey.length / 2; - for (i = 0; i < kLen; i++) { - a = inKey[i + i]; - meKey[i] = a; - b = inKey[i + i + 1]; - moKey[i] = b; - sKey[kLen - i - 1] = mdsRem(a, b); - } - for (i = 0; i < 40; i += 2) { - a = 0x1010101 * i; - b = a + 0x1010101; - a = hFun(a, meKey); - b = rotw(hFun(b, moKey), 8); - tfsKey[i] = (a + b) & MAXINT; - tfsKey[i + 1] = rotw(a + 2 * b, 9); - } - for (i = 0; i < 256; i++) { - a = b = c = d = i; - switch (kLen) { - case 4: - a = q[1][a] ^ getB(sKey[3], 0); - b = q[0][b] ^ getB(sKey[3], 1); - c = q[0][c] ^ getB(sKey[3], 2); - d = q[1][d] ^ getB(sKey[3], 3); - case 3: - a = q[1][a] ^ getB(sKey[2], 0); - b = q[1][b] ^ getB(sKey[2], 1); - c = q[0][c] ^ getB(sKey[2], 2); - d = q[0][d] ^ getB(sKey[2], 3); - case 2: - tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; - tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; - tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; - tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; +/** + * Create padding with secure random data + * @private + * @param {Integer} length - Length of the padding in bytes + * @returns {Uint8Array} Random padding. + */ +function getPKCS1Padding(length) { + const result = new Uint8Array(length); + let count = 0; + while (count < length) { + const randomBytes = getRandomBytes(length - count); + for (let i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result[count++] = randomBytes[i]; } } } + return result; +} - function tfsG0(x) { - return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; - } - - function tfsG1(x) { - return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; - } - - function tfsFrnd(r, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); - blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); - blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; +/** + * Create a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} + * @param {Uint8Array} message - Message to be encoded + * @param {Integer} keyLength - The length in octets of the key modulus + * @returns {Uint8Array} EME-PKCS1 padded message. + */ +function emeEncode(message, keyLength) { + const mLength = message.length; + // length checking + if (mLength > keyLength - 11) { + throw new Error('Message too long'); } + // Generate an octet string PS of length k - mLen - 3 consisting of + // pseudo-randomly generated nonzero octets + const PS = getPKCS1Padding(keyLength - mLength - 3); + // Concatenate PS, the message M, and other padding to form an + // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. + const encoded = new Uint8Array(keyLength); + // 0x00 byte + encoded[1] = 2; + encoded.set(PS, 2); + // 0x00 bytes + encoded.set(message, keyLength - mLength); + return encoded; +} - function tfsIrnd(i, blk) { - let a = tfsG0(blk[0]); - let b = tfsG1(blk[1]); - blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; - blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); - a = tfsG0(blk[2]); - b = tfsG1(blk[3]); - blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; - blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); +/** + * Decode a EME-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} + * @param {Uint8Array} encoded - Encoded message bytes + * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) + * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) + * @throws {Error} on decoding failure, unless `randomPayload` is provided + */ +function emeDecode(encoded, randomPayload) { + // encoded format: 0x00 0x02 0x00 + let offset = 2; + let separatorNotFound = 1; + for (let j = offset; j < encoded.length; j++) { + separatorNotFound &= encoded[j] !== 0; + offset += separatorNotFound; } - function tfsClose() { - tfsKey = []; - tfsM = [ - [], - [], - [], - [] - ]; - } + const psLen = offset - 2; + const payload = encoded.subarray(offset + 1); // discard the 0x00 separator + const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - function tfsEncrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], - getW(dataBytes, dataOffset + 4) ^ tfsKey[1], - getW(dataBytes, dataOffset + 8) ^ tfsKey[2], - getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; - for (let j = 0; j < 8; j++) { - tfsFrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); - dataOffset += 16; - return dataBytes; + if (randomPayload) { + return util.selectUint8Array(isValidPadding, payload, randomPayload); } - function tfsDecrypt(data, offset) { - dataBytes = data; - dataOffset = offset; - const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], - getW(dataBytes, dataOffset + 4) ^ tfsKey[5], - getW(dataBytes, dataOffset + 8) ^ tfsKey[6], - getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; - for (let j = 7; j >= 0; j--) { - tfsIrnd(j, blk); - } - setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); - setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); - setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); - setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); - dataOffset += 16; + if (isValidPadding) { + return payload; } - // added by Recurity Labs + throw new Error('Decryption error'); +} - function tfsFinal() { - return dataBytes; +/** + * Create a EMSA-PKCS1-v1_5 padded message + * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} + * @param {Integer} algo - Hash algorithm type used + * @param {Uint8Array} hashed - Message to be encoded + * @param {Integer} emLen - Intended length in octets of the encoded message + * @returns {Uint8Array} Encoded message. + */ +function emsaEncode(algo, hashed, emLen) { + let i; + if (hashed.length !== hash$1.getHashByteLength(algo)) { + throw new Error('Invalid hash length'); + } + // produce an ASN.1 DER value for the hash function used. + // Let T be the full hash prefix + const hashPrefix = new Uint8Array(hash_headers[algo].length); + for (i = 0; i < hash_headers[algo].length; i++) { + hashPrefix[i] = hash_headers[algo][i]; + } + // and let tLen be the length in octets prefix and hashed data + const tLen = hashPrefix.length + hashed.length; + if (emLen < tLen + 11) { + throw new Error('Intended encoded message length too short'); } + // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF + // The length of PS will be at least 8 octets + const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - return { - name: 'twofish', - blocksize: 128 / 8, - open: tfsInit, - close: tfsClose, - encrypt: tfsEncrypt, - decrypt: tfsDecrypt, - // added by Recurity Labs - finalize: tfsFinal - }; + // Concatenate PS, the hash prefix, hashed data, and other padding to form the + // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed + const EM = new Uint8Array(emLen); + EM[1] = 0x01; + EM.set(PS, 2); + EM.set(hashPrefix, emLen - tLen); + EM.set(hashed, emLen - hashed.length); + return EM; } -// added by Recurity Labs +var pkcs1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + emeDecode: emeDecode, + emeEncode: emeEncode, + emsaEncode: emsaEncode +}); -function TF(key) { - this.tf = createTwofish(); - this.tf.open(Array.from(key), 0); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - this.encrypt = function(block) { - return this.tf.encrypt(Array.from(block), 0); - }; -} -TF.keySize = TF.prototype.keySize = 32; -TF.blockSize = TF.prototype.blockSize = 16; +const webCrypto$5 = util.getWebCrypto(); +const nodeCrypto$3 = util.getNodeCrypto(); +const _1n$b = BigInt(1); -/* Modified by Recurity Labs GmbH - * - * Originally written by nklein software (nklein.com) +/** Create signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} hashed - Hashed message + * @returns {Promise} RSA Signature. + * @async */ +async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) { + if (hash$1.getHashByteLength(hashAlgo) >= n.length) { + // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error + // e.g. if a 512-bit RSA key is used with a SHA-512 digest. + // The size limit is actually slightly different but here we only care about throwing + // on common key sizes. + throw new Error('Digest size cannot exceed key modulus size'); + } -/* - * Javascript implementation based on Bruce Schneier's reference implementation. - * - * - * The constructor doesn't do much of anything. It's just here - * so we can start defining properties and methods and such. - */ -function Blowfish() {} + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeSign$1(hashAlgo, data, n, e, d, p, q, u); + } + } + return bnSign(hashAlgo, n, d, hashed); +} -/* - * Declare the block size so that protocols know what size - * Initialization Vector (IV) they will need. +/** + * Verify signature + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Uint8Array} data - Message + * @param {Uint8Array} s - Signature + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} hashed - Hashed message + * @returns {Boolean} + * @async */ -Blowfish.prototype.BLOCKSIZE = 8; +async function verify$6(hashAlgo, data, s, n, e, hashed) { + if (data && !util.isStream(data)) { + if (util.getWebCrypto()) { + try { + return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e); + } catch (err) { + util.printDebugError(err); + } + } else if (util.getNodeCrypto()) { + return nodeVerify$1(hashAlgo, data, s, n, e); + } + } + return bnVerify(hashAlgo, s, n, e, hashed); +} -/* - * These are the default SBOXES. +/** + * Encrypt message + * @param {Uint8Array} data - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @returns {Promise} RSA Ciphertext. + * @async */ -Blowfish.prototype.SBOXES = [ - [ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, - 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, - 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, - 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, - 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, - 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, - 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, - 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, - 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, - 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, - 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, - 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, - 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, - 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, - 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, - 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, - 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, - 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, - 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, - 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, - 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, - 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a - ], - [ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, - 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, - 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, - 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, - 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, - 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, - 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, - 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, - 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, - 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, - 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, - 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, - 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, - 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, - 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, - 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, - 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, - 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, - 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, - 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, - 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, - 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 - ], - [ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, - 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, - 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, - 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, - 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, - 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, - 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, - 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, - 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, - 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, - 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, - 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, - 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, - 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, - 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, - 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, - 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, - 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, - 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, - 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, - 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, - 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 - ], - [ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, - 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, - 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, - 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, - 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, - 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, - 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, - 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, - 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, - 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, - 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, - 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, - 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, - 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, - 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, - 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, - 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, - 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, - 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, - 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, - 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, - 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 - ] -]; - -//* -//* This is the default PARRAY -//* -Blowfish.prototype.PARRAY = [ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, - 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b -]; - -//* -//* This is the number of rounds the cipher will go -//* -Blowfish.prototype.NN = 16; - -//* -//* This function is needed to get rid of problems -//* with the high-bit getting set. If we don't do -//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not -//* equal to ( bb & 0x00FFFFFFFF ) even when they -//* agree bit-for-bit for the first 32 bits. -//* -Blowfish.prototype._clean = function(xx) { - if (xx < 0) { - const yy = xx & 0x7FFFFFFF; - xx = yy + 0x80000000; +async function encrypt$4(data, n, e) { + if (util.getNodeCrypto()) { + return nodeEncrypt(data, n, e); } - return xx; -}; - -//* -//* This is the mixing function that uses the sboxes -//* -Blowfish.prototype._F = function(xx) { - let yy; + return bnEncrypt(data, n, e); +} - const dd = xx & 0x00FF; - xx >>>= 8; - const cc = xx & 0x00FF; - xx >>>= 8; - const bb = xx & 0x00FF; - xx >>>= 8; - const aa = xx & 0x00FF; +/** + * Decrypt RSA message + * @param {Uint8Array} m - Message + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA private coefficient + * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} RSA Plaintext. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$4(data, n, e, d, p, q, u, randomPayload) { + // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, + // and we want to avoid checking the error type to decide if the random payload + // should indeed be returned. + if (util.getNodeCrypto() && !randomPayload) { + try { + return await nodeDecrypt(data, n, e, d, p, q, u); + } catch (err) { + util.printDebugError(err); + } + } + return bnDecrypt(data, n, e, d, p, q, u, randomPayload); +} - yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy ^= this.sboxes[2][cc]; - yy += this.sboxes[3][dd]; +/** + * Generate a new random private key B bits long with public exponent E. + * + * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param {Integer} bits - RSA bit length + * @param {Integer} e - RSA public exponent + * @returns {{n, e, d, + * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = p ** -1 mod q + * @async + */ +async function generate$4(bits, e) { + e = BigInt(e); - return yy; -}; + // Native RSA keygen using Web Crypto + if (util.getWebCrypto()) { + const keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, // the specified keysize in bits + publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); -//* -//* This method takes an array with two values, left and right -//* and does NN rounds of Blowfish on them. -//* -Blowfish.prototype._encryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); + // map JWK parameters to corresponding OpenPGP names + return jwkToPrivate(jwk, e); + } else if (util.getNodeCrypto()) { + const opts = { + modulusLength: bits, + publicExponent: bigIntToNumber(e), + publicKeyEncoding: { type: 'pkcs1', format: 'jwk' }, + privateKeyEncoding: { type: 'pkcs1', format: 'jwk' } + }; + const jwk = await new Promise((resolve, reject) => { + nodeCrypto$3.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => { + if (err) { + reject(err); + } else { + resolve(jwkPrivateKey); + } + }); + }); + return jwkToPrivate(jwk, e); + } - let ii; + // RSA keygen fallback using 40 iterations of the Miller-Rabin test + // See https://stackoverflow.com/a/6330138 for justification + // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST + let p; + let q; + let n; + do { + q = randomProbablePrime(bits - (bits >> 1), e, 40); + p = randomProbablePrime(bits >> 1, e, 40); + n = p * q; + } while (bitLength(n) !== bits); - for (ii = 0; ii < this.NN; ++ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; + const phi = (p - _1n$b) * (q - _1n$b); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + if (q < p) { + [p, q] = [q, p]; } - dataL ^= this.parray[this.NN + 0]; - dataR ^= this.parray[this.NN + 1]; + return { + n: bigIntToUint8Array(n), + e: bigIntToUint8Array(e), + d: bigIntToUint8Array(modInv(e, phi)), + p: bigIntToUint8Array(p), + q: bigIntToUint8Array(q), + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: bigIntToUint8Array(modInv(p, q)) + }; +} - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; +/** + * Validate RSA parameters + * @param {Uint8Array} n - RSA public modulus + * @param {Uint8Array} e - RSA public exponent + * @param {Uint8Array} d - RSA private exponent + * @param {Uint8Array} p - RSA private prime p + * @param {Uint8Array} q - RSA private prime q + * @param {Uint8Array} u - RSA inverse of p w.r.t. q + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$9(n, e, d, p, q, u) { + n = uint8ArrayToBigInt(n); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); -//* -//* This method takes a vector of numbers and turns them -//* into long words so that they can be processed by the -//* real algorithm. -//* -//* Maybe I should make the real algorithm above take a vector -//* instead. That will involve more looping, but it won't require -//* the F() method to deconstruct the vector. -//* -Blowfish.prototype.encryptBlock = function(vector) { - let ii; - const vals = [0, 0]; - const off = this.BLOCKSIZE / 2; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); - vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); + // expect pq = n + if ((p * q) !== n) { + return false; } - this._encryptBlock(vals); + const _2n = BigInt(2); + // expect p*u = 1 mod q + u = uint8ArrayToBigInt(u); + if (mod$2(p * u, q) !== BigInt(1)) { + return false; + } - const ret = []; - for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { - ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); - ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); - // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); - // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + /** + * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) + * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] + * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] + * + * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) + */ + const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3)); + const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q + const rde = r * d * e; + + const areInverses = mod$2(rde, p - _1n$b) === r && mod$2(rde, q - _1n$b) === r; + if (!areInverses) { + return false; } - return ret; -}; + return true; +} -//* -//* This method takes an array with two values, left and right -//* and undoes NN rounds of Blowfish on them. -//* -Blowfish.prototype._decryptBlock = function(vals) { - let dataL = vals[0]; - let dataR = vals[1]; +async function bnSign(hashAlgo, n, d, hashed) { + n = uint8ArrayToBigInt(n); + const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n))); + d = uint8ArrayToBigInt(d); + return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n)); +} - let ii; +async function webSign$1(hashName, data, n, e, d, p, q, u) { + /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. + * We swap them in privateToJWK, so it usually works out, but nevertheless, + * not all OpenPGP keys are compatible with this requirement. + * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still + * does if the underlying Web Crypto does so (though the tested implementations + * don't do so). + */ + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }; + const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); + return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); +} - for (ii = this.NN + 1; ii > 1; --ii) { - dataL ^= this.parray[ii]; - dataR = this._F(dataL) ^ dataR; +async function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) { + const sign = nodeCrypto$3.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(data); + sign.end(); - const tmp = dataL; - dataL = dataR; - dataR = tmp; + const jwk = await privateToJWK$1(n, e, d, p, q, u); + return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' })); +} + +async function bnVerify(hashAlgo, s, n, e, hashed) { + n = uint8ArrayToBigInt(n); + s = uint8ArrayToBigInt(s); + e = uint8ArrayToBigInt(e); + if (s >= n) { + throw new Error('Signature size cannot exceed modulus size'); } + const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n)); + const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n)); + return util.equalsUint8Array(EM1, EM2); +} - dataL ^= this.parray[1]; - dataR ^= this.parray[0]; +async function webVerify$1(hashName, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = await webCrypto$5.importKey('jwk', jwk, { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: hashName } + }, false, ['verify']); + return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); +} - vals[0] = this._clean(dataR); - vals[1] = this._clean(dataL); -}; +async function nodeVerify$1(hashAlgo, data, s, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1' }; -//* -//* This method takes a key array and initializes the -//* sboxes and parray for this encryption. -//* -Blowfish.prototype.init = function(key) { - let ii; - let jj = 0; + const verify = nodeCrypto$3.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(data); + verify.end(); - this.parray = []; - for (ii = 0; ii < this.NN + 2; ++ii) { - let data = 0x00000000; - for (let kk = 0; kk < 4; ++kk) { - data = (data << 8) | (key[jj] & 0x00FF); - if (++jj >= key.length) { - jj = 0; - } - } - this.parray[ii] = this.PARRAY[ii] ^ data; + try { + return verify.verify(key, s); + } catch (err) { + return false; } +} - this.sboxes = []; - for (ii = 0; ii < 4; ++ii) { - this.sboxes[ii] = []; - for (jj = 0; jj < 256; ++jj) { - this.sboxes[ii][jj] = this.SBOXES[ii][jj]; - } +async function nodeEncrypt(data, n, e) { + const jwk = publicToJWK(n, e); + const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; + + return new Uint8Array(nodeCrypto$3.publicEncrypt(key, data)); +} + +async function bnEncrypt(data, n, e) { + n = uint8ArrayToBigInt(n); + data = uint8ArrayToBigInt(emeEncode(data, byteLength(n))); + e = uint8ArrayToBigInt(e); + if (data >= n) { + throw new Error('Message size cannot exceed modulus size'); } + return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n)); +} - const vals = [0x00000000, 0x00000000]; +async function nodeDecrypt(data, n, e, d, p, q, u) { + const jwk = await privateToJWK$1(n, e, d, p, q, u); + const key = { key: jwk, format: 'jwk' , type: 'pkcs1', padding: nodeCrypto$3.constants.RSA_PKCS1_PADDING }; - for (ii = 0; ii < this.NN + 2; ii += 2) { - this._encryptBlock(vals); - this.parray[ii + 0] = vals[0]; - this.parray[ii + 1] = vals[1]; + try { + return new Uint8Array(nodeCrypto$3.privateDecrypt(key, data)); + } catch (err) { + throw new Error('Decryption error'); } +} - for (ii = 0; ii < 4; ++ii) { - for (jj = 0; jj < 256; jj += 2) { - this._encryptBlock(vals); - this.sboxes[ii][jj + 0] = vals[0]; - this.sboxes[ii][jj + 1] = vals[1]; - } +async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { + data = uint8ArrayToBigInt(data); + n = uint8ArrayToBigInt(n); + e = uint8ArrayToBigInt(e); + d = uint8ArrayToBigInt(d); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + u = uint8ArrayToBigInt(u); + if (data >= n) { + throw new Error('Data too large.'); } -}; + const dq = mod$2(d, q - _1n$b); // d mod (q-1) + const dp = mod$2(d, p - _1n$b); // d mod (p-1) -// added by Recurity Labs -function BF(key) { - this.bf = new Blowfish(); - this.bf.init(key); + const unblinder = getRandomBigInteger(BigInt(2), n); + const blinder = modExp(modInv(unblinder, n), e, n); + data = mod$2(data * blinder, n); - this.encrypt = function(block) { - return this.bf.encryptBlock(block); - }; -} + const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p + const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q + const h = mod$2(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q) -BF.keySize = BF.prototype.keySize = 16; -BF.blockSize = BF.prototype.blockSize = 8; + let result = h * p + mp; // result < n due to relations above -/** - * @fileoverview Symmetric cryptography functions - * @module crypto/cipher - * @private + result = mod$2(result * unblinder, n); + + return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload); +} + +/** Convert Openpgp private key params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e + * @param {Uint8Array} d + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} u */ +async function privateToJWK$1(n, e, d, p, q, u) { + const pNum = uint8ArrayToBigInt(p); + const qNum = uint8ArrayToBigInt(q); + const dNum = uint8ArrayToBigInt(d); -/** - * AES-128 encryption and decryption (ID 7) - * @function - * @param {String} key - 128-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} + let dq = mod$2(dNum, qNum - _1n$b); // d mod (q-1) + let dp = mod$2(dNum, pNum - _1n$b); // d mod (p-1) + dp = bigIntToUint8Array(dp); + dq = bigIntToUint8Array(dq); + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + d: uint8ArrayToB64(d), + // switch p and q + p: uint8ArrayToB64(q), + q: uint8ArrayToB64(p), + // switch dp and dq + dp: uint8ArrayToB64(dq), + dq: uint8ArrayToB64(dp), + qi: uint8ArrayToB64(u), + ext: true + }; +} + +/** Convert Openpgp key public params to jwk key according to + * @link https://tools.ietf.org/html/rfc7517 + * @param {String} hashAlgo + * @param {Uint8Array} n + * @param {Uint8Array} e */ -const aes128 = aes(128); -/** - * AES-128 Block Cipher (ID 8) - * @function - * @param {String} key - 192-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes192 = aes(192); -/** - * AES-128 Block Cipher (ID 9) - * @function - * @param {String} key - 256-bit key - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197} - * @returns {Object} - */ -const aes256 = aes(256); -// Not in OpenPGP specifications -const des$1 = DES; -/** - * Triple DES Block Cipher (ID 2) - * @function - * @param {String} key - 192-bit key - * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67} - * @returns {Object} - */ -const tripledes = TripleDES; -/** - * CAST-128 Block Cipher (ID 3) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm} - * @returns {Object} - */ -const cast5 = CAST5; -/** - * Twofish Block Cipher (ID 10) - * @function - * @param {String} key - 256-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH} - * @returns {Object} - */ -const twofish = TF; -/** - * Blowfish Block Cipher (ID 4) - * @function - * @param {String} key - 128-bit key - * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH} - * @returns {Object} - */ -const blowfish = BF; -/** - * Not implemented - * @function - * @throws {Error} - */ -const idea = function() { - throw new Error('IDEA symmetric-key algorithm not implemented'); -}; +function publicToJWK(n, e) { + return { + kty: 'RSA', + n: uint8ArrayToB64(n), + e: uint8ArrayToB64(e), + ext: true + }; +} -var cipher = /*#__PURE__*/Object.freeze({ +/** Convert JWK private key to OpenPGP private key params */ +function jwkToPrivate(jwk, e) { + return { + n: b64ToUint8Array(jwk.n), + e: bigIntToUint8Array(e), + d: b64ToUint8Array(jwk.d), + // switch p and q + p: b64ToUint8Array(jwk.q), + q: b64ToUint8Array(jwk.p), + // Since p and q are switched in places, u is the inverse of jwk.q + u: b64ToUint8Array(jwk.qi) + }; +} + +var rsa = /*#__PURE__*/Object.freeze({ __proto__: null, - aes128: aes128, - aes192: aes192, - aes256: aes256, - des: des$1, - tripledes: tripledes, - cast5: cast5, - twofish: twofish, - blowfish: blowfish, - idea: idea + decrypt: decrypt$4, + encrypt: encrypt$4, + generate: generate$4, + sign: sign$6, + validateParams: validateParams$9, + verify: verify$6 }); -var sha1_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0, - w16 = 0, w17 = 0, w18 = 0, w19 = 0, - w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0, - w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0, - w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0, - w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0, - w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0, - w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - - // 0 - t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 1 - t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 2 - t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 3 - t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 4 - t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 5 - t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 6 - t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 7 - t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 8 - t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 9 - t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 10 - t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 11 - t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 12 - t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 13 - t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 14 - t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 15 - t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 16 - n = w13 ^ w8 ^ w2 ^ w0; - w16 = (n << 1) | (n >>> 31); - t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 17 - n = w14 ^ w9 ^ w3 ^ w1; - w17 = (n << 1) | (n >>> 31); - t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 18 - n = w15 ^ w10 ^ w4 ^ w2; - w18 = (n << 1) | (n >>> 31); - t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 19 - n = w16 ^ w11 ^ w5 ^ w3; - w19 = (n << 1) | (n >>> 31); - t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 20 - n = w17 ^ w12 ^ w6 ^ w4; - w20 = (n << 1) | (n >>> 31); - t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 21 - n = w18 ^ w13 ^ w7 ^ w5; - w21 = (n << 1) | (n >>> 31); - t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 22 - n = w19 ^ w14 ^ w8 ^ w6; - w22 = (n << 1) | (n >>> 31); - t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 23 - n = w20 ^ w15 ^ w9 ^ w7; - w23 = (n << 1) | (n >>> 31); - t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 24 - n = w21 ^ w16 ^ w10 ^ w8; - w24 = (n << 1) | (n >>> 31); - t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 25 - n = w22 ^ w17 ^ w11 ^ w9; - w25 = (n << 1) | (n >>> 31); - t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 26 - n = w23 ^ w18 ^ w12 ^ w10; - w26 = (n << 1) | (n >>> 31); - t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 27 - n = w24 ^ w19 ^ w13 ^ w11; - w27 = (n << 1) | (n >>> 31); - t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 28 - n = w25 ^ w20 ^ w14 ^ w12; - w28 = (n << 1) | (n >>> 31); - t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 29 - n = w26 ^ w21 ^ w15 ^ w13; - w29 = (n << 1) | (n >>> 31); - t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 30 - n = w27 ^ w22 ^ w16 ^ w14; - w30 = (n << 1) | (n >>> 31); - t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 31 - n = w28 ^ w23 ^ w17 ^ w15; - w31 = (n << 1) | (n >>> 31); - t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 32 - n = w29 ^ w24 ^ w18 ^ w16; - w32 = (n << 1) | (n >>> 31); - t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 33 - n = w30 ^ w25 ^ w19 ^ w17; - w33 = (n << 1) | (n >>> 31); - t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 34 - n = w31 ^ w26 ^ w20 ^ w18; - w34 = (n << 1) | (n >>> 31); - t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 35 - n = w32 ^ w27 ^ w21 ^ w19; - w35 = (n << 1) | (n >>> 31); - t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 36 - n = w33 ^ w28 ^ w22 ^ w20; - w36 = (n << 1) | (n >>> 31); - t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 37 - n = w34 ^ w29 ^ w23 ^ w21; - w37 = (n << 1) | (n >>> 31); - t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 38 - n = w35 ^ w30 ^ w24 ^ w22; - w38 = (n << 1) | (n >>> 31); - t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 39 - n = w36 ^ w31 ^ w25 ^ w23; - w39 = (n << 1) | (n >>> 31); - t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 40 - n = w37 ^ w32 ^ w26 ^ w24; - w40 = (n << 1) | (n >>> 31); - t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 41 - n = w38 ^ w33 ^ w27 ^ w25; - w41 = (n << 1) | (n >>> 31); - t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 42 - n = w39 ^ w34 ^ w28 ^ w26; - w42 = (n << 1) | (n >>> 31); - t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 43 - n = w40 ^ w35 ^ w29 ^ w27; - w43 = (n << 1) | (n >>> 31); - t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 44 - n = w41 ^ w36 ^ w30 ^ w28; - w44 = (n << 1) | (n >>> 31); - t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 45 - n = w42 ^ w37 ^ w31 ^ w29; - w45 = (n << 1) | (n >>> 31); - t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 46 - n = w43 ^ w38 ^ w32 ^ w30; - w46 = (n << 1) | (n >>> 31); - t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 47 - n = w44 ^ w39 ^ w33 ^ w31; - w47 = (n << 1) | (n >>> 31); - t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 48 - n = w45 ^ w40 ^ w34 ^ w32; - w48 = (n << 1) | (n >>> 31); - t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 49 - n = w46 ^ w41 ^ w35 ^ w33; - w49 = (n << 1) | (n >>> 31); - t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 50 - n = w47 ^ w42 ^ w36 ^ w34; - w50 = (n << 1) | (n >>> 31); - t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 51 - n = w48 ^ w43 ^ w37 ^ w35; - w51 = (n << 1) | (n >>> 31); - t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 52 - n = w49 ^ w44 ^ w38 ^ w36; - w52 = (n << 1) | (n >>> 31); - t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 53 - n = w50 ^ w45 ^ w39 ^ w37; - w53 = (n << 1) | (n >>> 31); - t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 54 - n = w51 ^ w46 ^ w40 ^ w38; - w54 = (n << 1) | (n >>> 31); - t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 55 - n = w52 ^ w47 ^ w41 ^ w39; - w55 = (n << 1) | (n >>> 31); - t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 56 - n = w53 ^ w48 ^ w42 ^ w40; - w56 = (n << 1) | (n >>> 31); - t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 57 - n = w54 ^ w49 ^ w43 ^ w41; - w57 = (n << 1) | (n >>> 31); - t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 58 - n = w55 ^ w50 ^ w44 ^ w42; - w58 = (n << 1) | (n >>> 31); - t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 59 - n = w56 ^ w51 ^ w45 ^ w43; - w59 = (n << 1) | (n >>> 31); - t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 60 - n = w57 ^ w52 ^ w46 ^ w44; - w60 = (n << 1) | (n >>> 31); - t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 61 - n = w58 ^ w53 ^ w47 ^ w45; - w61 = (n << 1) | (n >>> 31); - t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 62 - n = w59 ^ w54 ^ w48 ^ w46; - w62 = (n << 1) | (n >>> 31); - t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 63 - n = w60 ^ w55 ^ w49 ^ w47; - w63 = (n << 1) | (n >>> 31); - t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 64 - n = w61 ^ w56 ^ w50 ^ w48; - w64 = (n << 1) | (n >>> 31); - t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 65 - n = w62 ^ w57 ^ w51 ^ w49; - w65 = (n << 1) | (n >>> 31); - t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 66 - n = w63 ^ w58 ^ w52 ^ w50; - w66 = (n << 1) | (n >>> 31); - t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 67 - n = w64 ^ w59 ^ w53 ^ w51; - w67 = (n << 1) | (n >>> 31); - t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 68 - n = w65 ^ w60 ^ w54 ^ w52; - w68 = (n << 1) | (n >>> 31); - t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 69 - n = w66 ^ w61 ^ w55 ^ w53; - w69 = (n << 1) | (n >>> 31); - t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 70 - n = w67 ^ w62 ^ w56 ^ w54; - w70 = (n << 1) | (n >>> 31); - t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 71 - n = w68 ^ w63 ^ w57 ^ w55; - w71 = (n << 1) | (n >>> 31); - t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 72 - n = w69 ^ w64 ^ w58 ^ w56; - w72 = (n << 1) | (n >>> 31); - t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 73 - n = w70 ^ w65 ^ w59 ^ w57; - w73 = (n << 1) | (n >>> 31); - t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 74 - n = w71 ^ w66 ^ w60 ^ w58; - w74 = (n << 1) | (n >>> 31); - t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 75 - n = w72 ^ w67 ^ w61 ^ w59; - w75 = (n << 1) | (n >>> 31); - t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 76 - n = w73 ^ w68 ^ w62 ^ w60; - w76 = (n << 1) | (n >>> 31); - t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 77 - n = w74 ^ w69 ^ w63 ^ w61; - w77 = (n << 1) | (n >>> 31); - t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 78 - n = w75 ^ w70 ^ w64 ^ w62; - w78 = (n << 1) | (n >>> 31); - t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - // 79 - n = w76 ^ w71 ^ w65 ^ w63; - w79 = (n << 1) | (n >>> 31); - t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0; - e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } - - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - } - - function reset () { - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } - - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if ( offset & 63 ) - return -1; - if ( ~output ) - if ( output & 31 ) - return -1; +const _1n$a = BigInt(1); - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; +/** + * ElGamal Encryption function + * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) + * @param {Uint8Array} data - To be padded and encrypted + * @param {Uint8Array} p + * @param {Uint8Array} g + * @param {Uint8Array} y + * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} + * @async + */ +async function encrypt$3(data, p, g, y) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } + const padded = emeEncode(data, byteLength(p)); + const m = uint8ArrayToBigInt(padded); - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0; + // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* + // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] + const k = getRandomBigInteger(_1n$a, p - _1n$a); + return { + c1: bigIntToUint8Array(modExp(g, k, p)), + c2: bigIntToUint8Array(mod$2(modExp(y, k, p) * m, p)) + }; +} - HEAP[offset|length] = 0x80; +/** + * ElGamal Encryption function + * @param {Uint8Array} c1 + * @param {Uint8Array} c2 + * @param {Uint8Array} p + * @param {Uint8Array} x + * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing + * (needed for constant-time processing) + * @returns {Promise} Unpadded message. + * @throws {Error} on decryption error, unless `randomPayload` is given + * @async + */ +async function decrypt$3(c1, c2, p, x, randomPayload) { + c1 = uint8ArrayToBigInt(c1); + c2 = uint8ArrayToBigInt(c2); + p = uint8ArrayToBigInt(p); + x = uint8ArrayToBigInt(x); - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - _core_heap(offset); + const padded = mod$2(modInv(modExp(c1, x, p), p) * c2, p); + return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload); +} - length = 0; +/** + * Validate ElGamal parameters + * @param {Uint8Array} p - ElGamal prime + * @param {Uint8Array} g - ElGamal group generator + * @param {Uint8Array} y - ElGamal public key + * @param {Uint8Array} x - ElGamal private exponent + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$8(p, g, y, x) { + p = uint8ArrayToBigInt(p); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - HEAP[offset|0] = 0; - } + // Check that 1 < g < p + if (g <= _1n$a || g >= p) { + return false; + } - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; + // Expect p-1 to be large + const pSize = BigInt(bitLength(p)); + const _1023n = BigInt(1023); + if (pSize < _1023n) { + return false; + } - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; + /** + * g should have order p-1 + * Check that g ** (p-1) = 1 mod p + */ + if (modExp(g, p - _1n$a, p) !== _1n$a) { + return false; + } - TOTAL0 = 64; - TOTAL1 = 0; + /** + * Since p-1 is not prime, g might have a smaller order that divides p-1 + * We want to make sure that the order is large enough to hinder a small subgroup attack + * + * We just check g**i != 1 for all i up to a threshold + */ + let res = g; + let i = BigInt(1); + const _2n = BigInt(2); + const threshold = _2n << BigInt(17); // we want order > threshold + while (i < threshold) { + res = mod$2(res * g, p); + if (res === _1n$a) { + return false; } + i++; + } - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{r(p-1) + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const r = getRandomBigInteger(_2n << (pSize - _1n$a), _2n << pSize); // draw r of same size as p-1 + const rqx = (p - _1n$a) * r + x; + if (y !== modExp(g, rqx, p)) { + return false; + } - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); + return true; +} - if ( ~output ) - _state_to_heap(output); +var elgamal = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$3, + encrypt: encrypt$3, + validateParams: validateParams$8 +}); - return hashed|0; - } +// declare const globalThis: Record | undefined; +const crypto$3 = + typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; +const nacl = {}; - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ - if ( offset & 63 ) - return -1; +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; - if ( ~output ) - if ( output & 31 ) - return -1; +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; +var _9 = new Uint8Array(32); _9[0] = 9; - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4; - count = (count-1)|0; +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} - _hmac_opad(); - _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4; +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} - count = (count-1)|0; - } +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} - if ( ~output ) - _state_to_heap(output); +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} - return 0; +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} - return { - // SHA1 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA1 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA1 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} -class Hash { - constructor() { - this.pos = 0; - this.len = 0; - } - reset() { - const { asm } = this.acquire_asm(); - this.result = null; - this.pos = 0; - this.len = 0; - asm.reset(); - return this; - } - process(data) { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - let hpos = this.pos; - let hlen = this.len; - let dpos = 0; - let dlen = data.length; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.process(hpos, hlen); - hpos += wlen; - hlen -= wlen; - if (!hlen) - hpos = 0; - } - this.pos = hpos; - this.len = hlen; - return this; - } - finish() { - if (this.result !== null) - throw new IllegalStateError('state must be reset before processing new data'); - const { asm, heap } = this.acquire_asm(); - asm.finish(this.pos, this.len, 0); - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set(heap.subarray(0, this.HASH_SIZE)); - this.pos = 0; - this.len = 0; - this.release_asm(); - return this; - } +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; } -const _sha1_block_size = 64; -const _sha1_hash_size = 20; -const heap_pool$1 = []; -const asm_pool$1 = []; -class Sha1 extends Hash { - constructor() { - super(); - this.NAME = 'sha1'; - this.BLOCK_SIZE = _sha1_block_size; - this.HASH_SIZE = _sha1_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$1.pop() || _heap_init(); - this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$1.push(this.heap); - asm_pool$1.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha1().process(data).finish().result; - } -} -Sha1.NAME = 'sha1'; -Sha1.heap_pool = []; -Sha1.asm_pool = []; -Sha1.asm_function = sha1_asm; - -var sha256_asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; - - // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; - - // I/O buffer - var HEAP = new stdlib.Uint8Array(buffer); - - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; - - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; - - a = H0; - b = H1; - c = H2; - d = H3; - e = H4; - f = H5; - g = H6; - h = H7; - - // 0 - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 1 - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 2 - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 3 - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 4 - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 5 - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 6 - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 7 - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 8 - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 9 - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 10 - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 11 - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 12 - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 13 - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 14 - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 15 - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 16 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 17 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 18 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 19 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 20 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 21 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 22 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 23 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 24 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 25 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 26 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 27 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 28 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 29 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 30 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 31 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 32 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 33 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 34 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 35 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 36 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 37 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 38 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 39 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 40 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 41 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 42 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 43 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 44 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 45 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 46 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 47 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 48 - w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 49 - w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 50 - w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 51 - w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 52 - w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 53 - w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 54 - w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 55 - w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - // 56 - w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - d = ( d + h )|0; - h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0; - - // 57 - w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0; - c = ( c + g )|0; - g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0; - - // 58 - w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0; - b = ( b + f )|0; - f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0; - - // 59 - w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0; - a = ( a + e )|0; - e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0; - - // 60 - w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0; - h = ( h + d )|0; - d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0; - - // 61 - w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0; - g = ( g + c )|0; - c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0; - - // 62 - w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0; - f = ( f + b )|0; - b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0; - - // 63 - w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0; - e = ( e + a )|0; - a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; - - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; - } - - function _core_heap ( offset ) { - offset = offset|0; - - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); - } +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} - // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; - - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; - } - - function reset () { - H0 = 0x6a09e667; - H1 = 0xbb67ae85; - H2 = 0x3c6ef372; - H3 = 0xa54ff53a; - H4 = 0x510e527f; - H5 = 0x9b05688c; - H6 = 0x1f83d9ab; - H7 = 0x5be0cd19; - TOTAL0 = TOTAL1 = 0; - } - - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - TOTAL0 = total0; - TOTAL1 = total1; - } - - // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; - - var hashed = 0; - - if ( offset & 63 ) - return -1; - - while ( (length|0) >= 64 ) { - _core_heap(offset); - - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; - - hashed = ( hashed + 64 )|0; - } +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} - return hashed|0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var hashed = 0, - i = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; - - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; - } - - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; - - HEAP[offset|length] = 0x80; - - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); - - length = 0; - - HEAP[offset|0] = 0; - } - - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; - _core_heap(offset); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - function hmac_reset () { - H0 = I0; - H1 = I1; - H2 = I2; - H3 = I3; - H4 = I4; - H5 = I5; - H6 = I6; - H7 = I7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function _hmac_opad () { - H0 = O0; - H1 = O1; - H2 = O2; - H3 = O3; - H4 = O4; - H5 = O5; - H6 = O6; - H7 = O7; - TOTAL0 = 64; - TOTAL1 = 0; - } - - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; - - // opad - reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); - O0 = H0; - O1 = H1; - O2 = H2; - O3 = H3; - O4 = H4; - O5 = H5; - O6 = H6; - O7 = H7; - - // ipad - reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); - I0 = H0; - I1 = H1; - I2 = H2; - I3 = H3; - I4 = H4; - I5 = H5; - I6 = H6; - I7 = H7; - - TOTAL0 = 64; - TOTAL1 = 0; - } - - // offset — multiple of 64 - // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; - - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - hashed = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - hashed = finish( offset, length, -1 )|0; - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - - if ( ~output ) - _state_to_heap(output); - - return hashed|0; - } - - // salt is assumed to be already processed - // offset — multiple of 64 - // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; - - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; - - if ( offset & 63 ) - return -1; - - if ( ~output ) - if ( output & 31 ) - return -1; - - // pad block number into heap - // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; - - // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; - h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; - - // perform the rest iterations - while ( (count|0) > 0 ) { - hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); - t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; - - h0 = h0 ^ H0; - h1 = h1 ^ H1; - h2 = h2 ^ H2; - h3 = h3 ^ H3; - h4 = h4 ^ H4; - h5 = h5 ^ H5; - h6 = h6 ^ H6; - h7 = h7 ^ H7; - - count = (count-1)|0; - } - - H0 = h0; - H1 = h1; - H2 = h2; - H3 = h3; - H4 = h4; - H5 = h5; - H6 = h6; - H7 = h7; - - if ( ~output ) - _state_to_heap(output); - - return 0; - } - - return { - // SHA256 - reset: reset, - init: init, - process: process, - finish: finish, - - // HMAC-SHA256 - hmac_reset: hmac_reset, - hmac_init: hmac_init, - hmac_finish: hmac_finish, - - // PBKDF2-HMAC-SHA256 - pbkdf2_generate_block: pbkdf2_generate_block - } -}; - -const _sha256_block_size = 64; -const _sha256_hash_size = 32; -const heap_pool$2 = []; -const asm_pool$2 = []; -class Sha256 extends Hash { - constructor() { - super(); - this.NAME = 'sha256'; - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; - this.acquire_asm(); - } - acquire_asm() { - if (this.heap === undefined || this.asm === undefined) { - this.heap = heap_pool$2.pop() || _heap_init(); - this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer); - this.reset(); - } - return { heap: this.heap, asm: this.asm }; - } - release_asm() { - if (this.heap !== undefined && this.asm !== undefined) { - heap_pool$2.push(this.heap); - asm_pool$2.push(this.asm); - } - this.heap = undefined; - this.asm = undefined; - } - static bytes(data) { - return new Sha256().process(data).finish().result; - } -} -Sha256.NAME = 'sha256'; - -var minimalisticAssert = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var inherits_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; -} -}); - -var inherits_1 = inherits_browser; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -var toArray_1 = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -var htonl_1 = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -var toHex32_1 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -var zero2_1 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -var zero8_1 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -var join32_1 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -var split32_1 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -var rotr32_1 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -var rotl32_1 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -var sum32_1 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -var sum32_3_1 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -var sum32_4_1 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -var sum32_5_1 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -var sum64_1 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -var sum64_lo_1 = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -var sum64_5_lo_1 = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -var rotr64_hi_1 = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var rotr64_lo_1 = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var shr64_lo_1 = shr64_lo; - -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -var common = { - BlockHash: BlockHash_1 -}; - -var rotr32$1 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -var ft_1_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -var ch32_1 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -var maj32_1 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; - -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; - -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; - -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); -} -var g0_256_1 = g0_256; - -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); -} -var g1_256_1 = g1_256; - -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; - -var sum32$1 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$1 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; - -var BlockHash$1 = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$1); -var _256 = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - _256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, _256); -var _224 = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - -var rotr64_hi$1 = utils.rotr64_hi; -var rotr64_lo$1 = utils.rotr64_lo; -var shr64_hi$1 = utils.shr64_hi; -var shr64_lo$1 = utils.shr64_lo; -var sum64$1 = utils.sum64; -var sum64_hi$1 = utils.sum64_hi; -var sum64_lo$1 = utils.sum64_lo; -var sum64_4_hi$1 = utils.sum64_4_hi; -var sum64_4_lo$1 = utils.sum64_4_lo; -var sum64_5_hi$1 = utils.sum64_5_hi; -var sum64_5_lo$1 = utils.sum64_5_lo; - -var BlockHash$2 = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash$2); -var _512 = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - minimalisticAssert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); // 34 - var c2_hi = rotr64_hi$1(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); // 34 - var c2_lo = rotr64_lo$1(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); // 61 - var c2_hi = shr64_hi$1(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); // 61 - var c2_lo = shr64_lo$1(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - _512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, _512); -var _384 = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -var rotl32$1 = utils.rotl32; -var sum32$2 = utils.sum32; -var sum32_3$1 = utils.sum32_3; -var sum32_4$2 = utils.sum32_4; -var BlockHash$3 = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash$3.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash$3); -var ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32$2( - rotl32$1( - sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32$1(C, 10); - C = B; - B = T; - T = sum32$2( - rotl32$1( - sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$1(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -var ripemd = { - ripemd160: ripemd160 -}; - -/** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. - */ - -// MD5 Digest -async function md5(entree) { - const digest = md51(util.uint8ArrayToString(entree)); - return util.hexToUint8Array(hex(digest)); -} - -function md5cycle(x, k) { - let a = x[0]; - let b = x[1]; - let c = x[2]; - let d = x[3]; - - a = ff(a, b, c, d, k[0], 7, -680876936); - d = ff(d, a, b, c, k[1], 12, -389564586); - c = ff(c, d, a, b, k[2], 17, 606105819); - b = ff(b, c, d, a, k[3], 22, -1044525330); - a = ff(a, b, c, d, k[4], 7, -176418897); - d = ff(d, a, b, c, k[5], 12, 1200080426); - c = ff(c, d, a, b, k[6], 17, -1473231341); - b = ff(b, c, d, a, k[7], 22, -45705983); - a = ff(a, b, c, d, k[8], 7, 1770035416); - d = ff(d, a, b, c, k[9], 12, -1958414417); - c = ff(c, d, a, b, k[10], 17, -42063); - b = ff(b, c, d, a, k[11], 22, -1990404162); - a = ff(a, b, c, d, k[12], 7, 1804603682); - d = ff(d, a, b, c, k[13], 12, -40341101); - c = ff(c, d, a, b, k[14], 17, -1502002290); - b = ff(b, c, d, a, k[15], 22, 1236535329); - - a = gg(a, b, c, d, k[1], 5, -165796510); - d = gg(d, a, b, c, k[6], 9, -1069501632); - c = gg(c, d, a, b, k[11], 14, 643717713); - b = gg(b, c, d, a, k[0], 20, -373897302); - a = gg(a, b, c, d, k[5], 5, -701558691); - d = gg(d, a, b, c, k[10], 9, 38016083); - c = gg(c, d, a, b, k[15], 14, -660478335); - b = gg(b, c, d, a, k[4], 20, -405537848); - a = gg(a, b, c, d, k[9], 5, 568446438); - d = gg(d, a, b, c, k[14], 9, -1019803690); - c = gg(c, d, a, b, k[3], 14, -187363961); - b = gg(b, c, d, a, k[8], 20, 1163531501); - a = gg(a, b, c, d, k[13], 5, -1444681467); - d = gg(d, a, b, c, k[2], 9, -51403784); - c = gg(c, d, a, b, k[7], 14, 1735328473); - b = gg(b, c, d, a, k[12], 20, -1926607734); - - a = hh(a, b, c, d, k[5], 4, -378558); - d = hh(d, a, b, c, k[8], 11, -2022574463); - c = hh(c, d, a, b, k[11], 16, 1839030562); - b = hh(b, c, d, a, k[14], 23, -35309556); - a = hh(a, b, c, d, k[1], 4, -1530992060); - d = hh(d, a, b, c, k[4], 11, 1272893353); - c = hh(c, d, a, b, k[7], 16, -155497632); - b = hh(b, c, d, a, k[10], 23, -1094730640); - a = hh(a, b, c, d, k[13], 4, 681279174); - d = hh(d, a, b, c, k[0], 11, -358537222); - c = hh(c, d, a, b, k[3], 16, -722521979); - b = hh(b, c, d, a, k[6], 23, 76029189); - a = hh(a, b, c, d, k[9], 4, -640364487); - d = hh(d, a, b, c, k[12], 11, -421815835); - c = hh(c, d, a, b, k[15], 16, 530742520); - b = hh(b, c, d, a, k[2], 23, -995338651); - - a = ii(a, b, c, d, k[0], 6, -198630844); - d = ii(d, a, b, c, k[7], 10, 1126891415); - c = ii(c, d, a, b, k[14], 15, -1416354905); - b = ii(b, c, d, a, k[5], 21, -57434055); - a = ii(a, b, c, d, k[12], 6, 1700485571); - d = ii(d, a, b, c, k[3], 10, -1894986606); - c = ii(c, d, a, b, k[10], 15, -1051523); - b = ii(b, c, d, a, k[1], 21, -2054922799); - a = ii(a, b, c, d, k[8], 6, 1873313359); - d = ii(d, a, b, c, k[15], 10, -30611744); - c = ii(c, d, a, b, k[6], 15, -1560198380); - b = ii(b, c, d, a, k[13], 21, 1309151649); - a = ii(a, b, c, d, k[4], 6, -145523070); - d = ii(d, a, b, c, k[11], 10, -1120210379); - c = ii(c, d, a, b, k[2], 15, 718787259); - b = ii(b, c, d, a, k[9], 21, -343485551); - - x[0] = add32(a, x[0]); - x[1] = add32(b, x[1]); - x[2] = add32(c, x[2]); - x[3] = add32(d, x[3]); -} - -function cmn(q, a, b, x, s, t) { - a = add32(add32(a, q), add32(x, t)); - return add32((a << s) | (a >>> (32 - s)), b); -} - -function ff(a, b, c, d, x, s, t) { - return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} - -function gg(a, b, c, d, x, s, t) { - return cmn((b & d) | (c & (~d)), a, b, x, s, t); -} - -function hh(a, b, c, d, x, s, t) { - return cmn(b ^ c ^ d, a, b, x, s, t); -} - -function ii(a, b, c, d, x, s, t) { - return cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -function md51(s) { - const n = s.length; - const state = [1732584193, -271733879, -1732584194, 271733878]; - let i; - for (i = 64; i <= s.length; i += 64) { - md5cycle(state, md5blk(s.substring(i - 64, i))); - } - s = s.substring(i - 64); - const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (i = 0; i < s.length; i++) { - tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); - } - tail[i >> 2] |= 0x80 << ((i % 4) << 3); - if (i > 55) { - md5cycle(state, tail); - for (i = 0; i < 16; i++) { - tail[i] = 0; - } - } - tail[14] = n * 8; - md5cycle(state, tail); - return state; -} - -/* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ -function md5blk(s) { /* I figured global was faster. */ - const md5blks = []; - let i; /* Andy King said do it this way. */ - for (i = 0; i < 64; i += 4) { - md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << - 24); - } - return md5blks; -} - -const hex_chr = '0123456789abcdef'.split(''); - -function rhex(n) { - let s = ''; - let j = 0; - for (; j < 4; j++) { - s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; - } - return s; -} - -function hex(x) { - for (let i = 0; i < x.length; i++) { - x[i] = rhex(x[i]); - } - return x.join(''); -} - -/* this function is much faster, -so if possible we use it. Some IEs -are the only ones I know of that -need the idiotic second function, -generated by an if clause. */ - -function add32(a, b) { - return (a + b) & 0xFFFFFFFF; -} - -/** - * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries. - * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto} - * @see {@link https://github.com/indutny/hash.js|hash.js} - * @module crypto/hash - * @private - */ - -const webCrypto = util.getWebCrypto(); -const nodeCrypto = util.getNodeCrypto(); -const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes(); - -function nodeHash(type) { - if (!nodeCrypto || !nodeCryptoHashes.includes(type)) { - return; - } - return async function (data) { - const shasum = nodeCrypto.createHash(type); - return transform(data, value => { - shasum.update(value); - }, () => new Uint8Array(shasum.digest())); - }; -} - -function hashjsHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } - const hashInstance = hash(); - return transform(data, value => { - hashInstance.update(value); - }, () => new Uint8Array(hashInstance.digest())); - }; -} - -function asmcryptoHash(hash, webCryptoHash) { - return async function(data, config$1 = config) { - if (isArrayStream(data)) { - data = await readToEnd(data); - } - if (util.isStream(data)) { - const hashInstance = new hash(); - return transform(data, value => { - hashInstance.process(value); - }, () => hashInstance.finish().result); - } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) { - return new Uint8Array(await webCrypto.digest(webCryptoHash, data)); - } else { - return hash.bytes(data); - } - }; -} - -const hashFunctions = { - md5: nodeHash('md5') || md5, - sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'), - sha224: nodeHash('sha224') || hashjsHash(_224), - sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'), - sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'), - sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge. - ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160) -}; - -var hash = { - - /** @see module:md5 */ - md5: hashFunctions.md5, - /** @see asmCrypto */ - sha1: hashFunctions.sha1, - /** @see hash.js */ - sha224: hashFunctions.sha224, - /** @see asmCrypto */ - sha256: hashFunctions.sha256, - /** @see hash.js */ - sha384: hashFunctions.sha384, - /** @see asmCrypto */ - sha512: hashFunctions.sha512, - /** @see hash.js */ - ripemd: hashFunctions.ripemd, - - /** - * Create a hash on the specified data using the specified algorithm - * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {Uint8Array} data - Data to be hashed - * @returns {Promise} Hash value. - */ - digest: function(algo, data) { - switch (algo) { - case enums.hash.md5: - return this.md5(data); - case enums.hash.sha1: - return this.sha1(data); - case enums.hash.ripemd: - return this.ripemd(data); - case enums.hash.sha256: - return this.sha256(data); - case enums.hash.sha384: - return this.sha384(data); - case enums.hash.sha512: - return this.sha512(data); - case enums.hash.sha224: - return this.sha224(data); - default: - throw new Error('Invalid hash function.'); - } - }, - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns {Integer} Size in bytes of the resulting hash. - */ - getHashByteLength: function(algo) { - switch (algo) { - case enums.hash.md5: - return 16; - case enums.hash.sha1: - case enums.hash.ripemd: - return 20; - case enums.hash.sha256: - return 32; - case enums.hash.sha384: - return 48; - case enums.hash.sha512: - return 64; - case enums.hash.sha224: - return 28; - default: - throw new Error('Invalid hash algorithm.'); - } - } -}; - -class AES_CFB { - static encrypt(data, key, iv) { - return new AES_CFB(key, iv).encrypt(data); - } - static decrypt(data, key, iv) { - return new AES_CFB(key, iv).decrypt(data); - } - constructor(key, iv, aes) { - this.aes = aes ? aes : new AES(key, iv, true, 'CFB'); - delete this.aes.padding; - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * Get implementation of the given cipher - * @param {enums.symmetric} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getCipher(algo) { - const algoName = enums.read(enums.symmetric, algo); - return cipher[algoName]; -} - -// Modified by ProtonTech AG - -const webCrypto$1 = util.getWebCrypto(); -const nodeCrypto$1 = util.getNodeCrypto(); - -const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : []; -const nodeAlgos = { - idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */ - tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined, - cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined, - blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined, - aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined, - aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined, - aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined - /* twofish is not implemented in OpenSSL */ -}; - -/** - * CFB encryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} plaintext - * @param {Uint8Array} iv - * @param {Object} config - full configuration, defaults to openpgp.config - * @returns MaybeStream - */ -async function encrypt(algo, key, plaintext, iv, config) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeEncrypt(algo, key, plaintext, iv); - } - if (util.isAES(algo)) { - return aesEncrypt(algo, key, plaintext, iv, config); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - const blockc = iv.slice(); - let pt = new Uint8Array(); - const process = chunk => { - if (chunk) { - pt = util.concatUint8Array([pt, chunk]); - } - const ciphertext = new Uint8Array(pt.length); - let i; - let j = 0; - while (chunk ? pt.length >= block_size : pt.length) { - const encblock = cipherfn.encrypt(blockc); - for (i = 0; i < block_size; i++) { - blockc[i] = pt[i] ^ encblock[i]; - ciphertext[j++] = blockc[i]; - } - pt = pt.subarray(block_size); - } - return ciphertext.subarray(0, j); - }; - return transform(plaintext, process, process); -} - -/** - * CFB decryption - * @param {enums.symmetric} algo - block cipher algorithm - * @param {Uint8Array} key - * @param {MaybeStream} ciphertext - * @param {Uint8Array} iv - * @returns MaybeStream - */ -async function decrypt(algo, key, ciphertext, iv) { - const algoName = enums.read(enums.symmetric, algo); - if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library. - return nodeDecrypt(algo, key, ciphertext, iv); - } - if (util.isAES(algo)) { - return aesDecrypt(algo, key, ciphertext, iv); - } - - const Cipher = getCipher(algo); - const cipherfn = new Cipher(key); - const block_size = cipherfn.blockSize; - - let blockp = iv; - let ct = new Uint8Array(); - const process = chunk => { - if (chunk) { - ct = util.concatUint8Array([ct, chunk]); - } - const plaintext = new Uint8Array(ct.length); - let i; - let j = 0; - while (chunk ? ct.length >= block_size : ct.length) { - const decblock = cipherfn.encrypt(blockp); - blockp = ct.subarray(0, block_size); - for (i = 0; i < block_size; i++) { - plaintext[j++] = blockp[i] ^ decblock[i]; - } - ct = ct.subarray(block_size); - } - return plaintext.subarray(0, j); - }; - return transform(ciphertext, process, process); -} - -function aesEncrypt(algo, key, pt, iv, config) { - if ( - util.getWebCrypto() && - key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support - !util.isStream(pt) && - pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2 - ) { // Web Crypto - return webEncrypt(algo, key, pt, iv); - } - // asm.js fallback - const cfb = new AES_CFB(key, iv); - return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish()); -} - -function aesDecrypt(algo, key, ct, iv) { - if (util.isStream(ct)) { - const cfb = new AES_CFB(key, iv); - return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish()); - } - return AES_CFB.decrypt(ct, key, iv); -} - -function xorMut(a, b) { - for (let i = 0; i < a.length; i++) { - a[i] = a[i] ^ b[i]; - } -} - -async function webEncrypt(algo, key, pt, iv) { - const ALGO = 'AES-CBC'; - const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']); - const { blockSize } = getCipher(algo); - const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]); - const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length); - xorMut(ct, pt); - return ct; -} - -function nodeEncrypt(algo, key, pt, iv) { - const algoName = enums.read(enums.symmetric, algo); - const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv); - return transform(pt, value => new Uint8Array(cipherObj.update(value))); -} - -function nodeDecrypt(algo, key, ct, iv) { - const algoName = enums.read(enums.symmetric, algo); - const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv); - return transform(ct, value => new Uint8Array(decipherObj.update(value))); -} - -var cfb = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt, - decrypt: decrypt -}); - -class AES_CTR { - static encrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - static decrypt(data, key, nonce) { - return new AES_CTR(key, nonce).encrypt(data); - } - constructor(key, nonce, aes) { - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - delete this.aes.padding; - this.AES_CTR_set_options(nonce); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - AES_CTR_set_options(nonce, counter, size) { - let { asm } = this.aes.acquire_asm(); - if (size !== undefined) { - if (size < 8 || size > 48) - throw new IllegalArgumentError('illegal counter size'); - let mask = Math.pow(2, size) - 1; - asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0); - } - else { - size = 48; - asm.set_mask(0, 0, 0xffff, 0xffffffff); - } - if (nonce !== undefined) { - let len = nonce.length; - if (!len || len > 16) - throw new IllegalArgumentError('illegal nonce size'); - let view = new DataView(new ArrayBuffer(16)); - new Uint8Array(view.buffer).set(nonce); - asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); - } - else { - throw new Error('nonce is required'); - } - if (counter !== undefined) { - if (counter < 0 || counter >= Math.pow(2, size)) - throw new IllegalArgumentError('illegal counter value'); - asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0); - } - } -} - -class AES_CBC { - static encrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).encrypt(data); - } - static decrypt(data, key, padding = true, iv) { - return new AES_CBC(key, iv, padding).decrypt(data); - } - constructor(key, iv, padding = true, aes) { - this.aes = aes ? aes : new AES(key, iv, padding, 'CBC'); - } - encrypt(data) { - const r1 = this.aes.AES_Encrypt_process(data); - const r2 = this.aes.AES_Encrypt_finish(); - return joinBytes(r1, r2); - } - decrypt(data) { - const r1 = this.aes.AES_Decrypt_process(data); - const r2 = this.aes.AES_Decrypt_finish(); - return joinBytes(r1, r2); - } -} - -/** - * @fileoverview This module implements AES-CMAC on top of - * native AES-CBC using either the WebCrypto API or Node.js' crypto API. - * @module crypto/cmac - * @private - */ - -const webCrypto$2 = util.getWebCrypto(); -const nodeCrypto$2 = util.getNodeCrypto(); - - -/** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - -const blockLength = 16; - - -/** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param {Uint8Array} data - * @param {Uint8Array} padding - */ -function rightXORMut(data, padding) { - const offset = data.length - blockLength; - for (let i = 0; i < blockLength; i++) { - data[i + offset] ^= padding[i]; - } - return data; -} - -function pad(data, padding, padding2) { - // if |M| in {n, 2n, 3n, ...} - if (data.length && data.length % blockLength === 0) { - // then return M xor→ B, - return rightXORMut(data, padding); - } - // else return (M || 10^(n−1−(|M| mod n))) xor→ P - const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength))); - padded.set(data); - padded[data.length] = 0b10000000; - return rightXORMut(padded, padding2); -} - -const zeroBlock = new Uint8Array(blockLength); - -async function CMAC(key) { - const cbc = await CBC(key); - - // L ← E_K(0^n); B ← 2L; P ← 4L - const padding = util.double(await cbc(zeroBlock)); - const padding2 = util.double(padding); - - return async function(data) { - // return CBC_K(pad(M; B, P)) - return (await cbc(pad(data, padding, padding2))).subarray(-blockLength); - }; -} - -async function CBC(key) { - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']); - return async function(pt) { - const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt); - return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt) { - const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock); - const ct = en.update(pt); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt) { - return AES_CBC.encrypt(pt, key, false, zeroBlock); - }; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$3 = util.getWebCrypto(); -const nodeCrypto$3 = util.getNodeCrypto(); -const Buffer$1 = util.getNodeBuffer(); - - -const blockLength$1 = 16; -const ivLength = blockLength$1; -const tagLength = blockLength$1; - -const zero = new Uint8Array(blockLength$1); -const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1; -const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2; - -async function OMAC(key) { - const cmac = await CMAC(key); - return function(t, message) { - return cmac(util.concatUint8Array([t, message])); - }; -} - -async function CTR(key) { - if ( - util.getWebCrypto() && - key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - ) { - key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']); - return async function(pt, iv) { - const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt); - return new Uint8Array(ct); - }; - } - if (util.getNodeCrypto()) { // Node crypto library - return async function(pt, iv) { - const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv); - const ct = Buffer$1.concat([en.update(pt), en.final()]); - return new Uint8Array(ct); - }; - } - // asm.js fallback - return async function(pt, iv) { - return AES_CTR.encrypt(pt, key, iv); - }; -} - - -/** - * Class to en/decrypt using EAX mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function EAX(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('EAX mode supports only AES cipher'); - } - - const [ - omac, - ctr - ] = await Promise.all([ - OMAC(key), - CTR(key) - ]); - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - const [ - omacNonce, - omacAdata - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata) - ]); - const ciphered = await ctr(plaintext, omacNonce); - const omacCiphered = await omac(two, ciphered); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - return util.concatUint8Array([ciphered, tag]); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (16 bytes) - * @param {Uint8Array} adata - Associated data to verify - * @returns {Promise} The plaintext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext'); - const ciphered = ciphertext.subarray(0, -tagLength); - const ctTag = ciphertext.subarray(-tagLength); - const [ - omacNonce, - omacAdata, - omacCiphered - ] = await Promise.all([ - omac(zero, nonce), - omac(one, adata), - omac(two, ciphered) - ]); - const tag = omacCiphered; // Assumes that omac(*).length === tagLength. - for (let i = 0; i < tagLength; i++) { - tag[i] ^= omacAdata[i] ^ omacNonce[i]; - } - if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch'); - const plaintext = await ctr(ciphered, omacNonce); - return plaintext; - } - }; -} - - -/** - * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}. - * @param {Uint8Array} iv - The initialization vector (16 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -EAX.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[8 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -EAX.blockLength = blockLength$1; -EAX.ivLength = ivLength; -EAX.tagLength = tagLength; - -// OpenPGP.js - An OpenPGP implementation in javascript - -const blockLength$2 = 16; -const ivLength$1 = 15; - -// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2: -// While OCB [RFC7253] allows the authentication tag length to be of any -// number up to 128 bits long, this document requires a fixed -// authentication tag length of 128 bits (16 octets) for simplicity. -const tagLength$1 = 16; - - -function ntz(n) { - let ntz = 0; - for (let i = 1; (n & i) === 0; i <<= 1) { - ntz++; - } - return ntz; -} - -function xorMut$1(S, T) { - for (let i = 0; i < S.length; i++) { - S[i] ^= T[i]; - } - return S; -} - -function xor(S, T) { - return xorMut$1(S.slice(), T); -} - -const zeroBlock$1 = new Uint8Array(blockLength$2); -const one$1 = new Uint8Array([1]); - -/** - * Class to en/decrypt using OCB mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function OCB(cipher$1, key) { - - let maxNtz = 0; - let encipher; - let decipher; - let mask; - - constructKeyVariables(cipher$1, key); - - function constructKeyVariables(cipher$1, key) { - const cipherName = enums.read(enums.symmetric, cipher$1); - const aes = new cipher[cipherName](key); - encipher = aes.encrypt.bind(aes); - decipher = aes.decrypt.bind(aes); - - const mask_x = encipher(zeroBlock$1); - const mask_$ = util.double(mask_x); - mask = []; - mask[0] = util.double(mask_$); - - - mask.x = mask_x; - mask.$ = mask_$; - } - - function extendKeyVariables(text, adata) { - const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1; - for (let i = maxNtz + 1; i <= newMaxNtz; i++) { - mask[i] = util.double(mask[i - 1]); - } - maxNtz = newMaxNtz; - } - - function hash(adata) { - if (!adata.length) { - // Fast path - return zeroBlock$1; - } - - // - // Consider A as a sequence of 128-bit blocks - // - const m = adata.length / blockLength$2 | 0; - - const offset = new Uint8Array(blockLength$2); - const sum = new Uint8Array(blockLength$2); - for (let i = 0; i < m; i++) { - xorMut$1(offset, mask[ntz(i + 1)]); - xorMut$1(sum, encipher(xor(offset, adata))); - adata = adata.subarray(blockLength$2); - } - - // - // Process any final partial block; compute final hash value - // - if (adata.length) { - xorMut$1(offset, mask.x); - - const cipherInput = new Uint8Array(blockLength$2); - cipherInput.set(adata, 0); - cipherInput[adata.length] = 0b10000000; - xorMut$1(cipherInput, offset); - - xorMut$1(sum, encipher(cipherInput)); - } - - return sum; - } - - /** - * Encrypt/decrypt data. - * @param {encipher|decipher} fn - Encryption/decryption block cipher function - * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext or plaintext output, with tag appended in both cases. - */ - function crypt(fn, text, nonce, adata) { - // - // Consider P as a sequence of 128-bit blocks - // - const m = text.length / blockLength$2 | 0; - - // - // Key-dependent variables - // - extendKeyVariables(text, adata); - - // - // Nonce-dependent and per-encryption variables - // - // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N - // Note: We assume here that tagLength mod 16 == 0. - const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]); - // bottom = str2num(Nonce[123..128]) - const bottom = paddedNonce[blockLength$2 - 1] & 0b111111; - // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) - paddedNonce[blockLength$2 - 1] &= 0b11000000; - const kTop = encipher(paddedNonce); - // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) - const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]); - // Offset_0 = Stretch[1+bottom..128+bottom] - const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1); - // Checksum_0 = zeros(128) - const checksum = new Uint8Array(blockLength$2); - - const ct = new Uint8Array(text.length + tagLength$1); - - // - // Process any whole blocks - // - let i; - let pos = 0; - for (i = 0; i < m; i++) { - // Offset_i = Offset_{i-1} xor L_{ntz(i)} - xorMut$1(offset, mask[ntz(i + 1)]); - // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) - // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) - ct.set(xorMut$1(fn(xor(offset, text)), offset), pos); - // Checksum_i = Checksum_{i-1} xor P_i - xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos)); - - text = text.subarray(blockLength$2); - pos += blockLength$2; - } - - // - // Process any final partial block and compute raw tag - // - if (text.length) { - // Offset_* = Offset_m xor L_* - xorMut$1(offset, mask.x); - // Pad = ENCIPHER(K, Offset_*) - const padding = encipher(offset); - // C_* = P_* xor Pad[1..bitlen(P_*)] - ct.set(xor(text, padding), pos); - - // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - const xorInput = new Uint8Array(blockLength$2); - xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0); - xorInput[text.length] = 0b10000000; - xorMut$1(checksum, xorInput); - pos += text.length; - } - // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) - const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata)); - - // - // Assemble ciphertext - // - // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN] - ct.set(tag, pos); - return ct; - } - - - return { - /** - * Encrypt plaintext input. - * @param {Uint8Array} plaintext - The cleartext input to be encrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - encrypt: async function(plaintext, nonce, adata) { - return crypt(encipher, plaintext, nonce, adata); - }, - - /** - * Decrypt ciphertext input. - * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted - * @param {Uint8Array} nonce - The nonce (15 bytes) - * @param {Uint8Array} adata - Associated data to sign - * @returns {Promise} The ciphertext output. - */ - decrypt: async function(ciphertext, nonce, adata) { - if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext'); - - const tag = ciphertext.subarray(-tagLength$1); - ciphertext = ciphertext.subarray(0, -tagLength$1); - - const crypted = crypt(decipher, ciphertext, nonce, adata); - // if (Tag[1..TAGLEN] == T) - if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) { - return crypted.subarray(0, -tagLength$1); - } - throw new Error('Authentication tag mismatch'); - } - }; -} - - -/** - * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}. - * @param {Uint8Array} iv - The initialization vector (15 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -OCB.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[7 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -OCB.blockLength = blockLength$2; -OCB.ivLength = ivLength$1; -OCB.tagLength = tagLength$1; - -const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 -class AES_GCM { - constructor(key, nonce, adata, tagSize = 16, aes) { - this.tagSize = tagSize; - this.gamma0 = 0; - this.counter = 1; - this.aes = aes ? aes : new AES(key, undefined, false, 'CTR'); - let { asm, heap } = this.aes.acquire_asm(); - // Init GCM - asm.gcm_init(); - // Tag size - if (this.tagSize < 4 || this.tagSize > 16) - throw new IllegalArgumentError('illegal tagSize value'); - // Nonce - const noncelen = nonce.length || 0; - const noncebuf = new Uint8Array(16); - if (noncelen !== 12) { - this._gcm_mac_process(nonce); - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = 0; - heap[4] = 0; - heap[5] = 0; - heap[6] = 0; - heap[7] = 0; - heap[8] = 0; - heap[9] = 0; - heap[10] = 0; - heap[11] = noncelen >>> 29; - heap[12] = (noncelen >>> 21) & 255; - heap[13] = (noncelen >>> 13) & 255; - heap[14] = (noncelen >>> 5) & 255; - heap[15] = (noncelen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_iv(0, 0, 0, 0); - noncebuf.set(heap.subarray(0, 16)); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; - } - const nonceview = new DataView(noncebuf.buffer); - this.gamma0 = nonceview.getUint32(12); - asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); - asm.set_mask(0, 0, 0, 0xffffffff); - // Associated data - if (adata !== undefined) { - if (adata.length > _AES_GCM_data_maxLength) - throw new IllegalArgumentError('illegal adata length'); - if (adata.length) { - this.adata = adata; - this._gcm_mac_process(adata); - } - else { - this.adata = undefined; - } - } - else { - this.adata = undefined; - } - // Counter - if (this.counter < 1 || this.counter > 0xffffffff) - throw new RangeError('counter must be a positive 32-bit integer'); - asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0); - } - static encrypt(cleartext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext); - } - static decrypt(ciphertext, key, nonce, adata, tagsize) { - return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext); - } - encrypt(data) { - return this.AES_GCM_encrypt(data); - } - decrypt(data) { - return this.AES_GCM_decrypt(data); - } - AES_GCM_Encrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = (len + dlen) & -16; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > 0) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len); - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - if (wlen < len) { - pos += wlen; - len -= wlen; - } - else { - pos = 0; - len = 0; - } - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Encrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let adata = this.adata; - let pos = this.aes.pos; - let len = this.aes.len; - const result = new Uint8Array(len + tagSize); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16); - if (len) - result.set(heap.subarray(pos, pos + len)); - let i = len; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - result.set(heap.subarray(0, tagSize), len); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_Decrypt_process(data) { - let dpos = 0; - let dlen = data.length || 0; - let { asm, heap } = this.aes.acquire_asm(); - let counter = this.counter; - let tagSize = this.tagSize; - let pos = this.aes.pos; - let len = this.aes.len; - let rpos = 0; - let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0; - let tlen = len + dlen - rlen; - let wlen = 0; - if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength) - throw new RangeError('counter overflow'); - const result = new Uint8Array(rlen); - while (dlen > tlen) { - wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen); - len += wlen; - dpos += wlen; - dlen -= wlen; - wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen); - wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen); - if (wlen) - result.set(heap.subarray(pos, pos + wlen), rpos); - counter += wlen >>> 4; - rpos += wlen; - pos = 0; - len = 0; - } - if (dlen > 0) { - len += _heap_write(heap, 0, data, dpos, dlen); - } - this.counter = counter; - this.aes.pos = pos; - this.aes.len = len; - return result; - } - AES_GCM_Decrypt_finish() { - let { asm, heap } = this.aes.acquire_asm(); - let tagSize = this.tagSize; - let adata = this.adata; - let counter = this.counter; - let pos = this.aes.pos; - let len = this.aes.len; - let rlen = len - tagSize; - if (len < tagSize) - throw new IllegalStateError('authentication tag not found'); - const result = new Uint8Array(rlen); - const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); - let i = rlen; - for (; i & 15; i++) - heap[pos + i] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i); - asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i); - if (rlen) - result.set(heap.subarray(pos, pos + rlen)); - const alen = adata !== undefined ? adata.length : 0; - const clen = ((counter - 1) << 4) + len - tagSize; - heap[0] = 0; - heap[1] = 0; - heap[2] = 0; - heap[3] = alen >>> 29; - heap[4] = alen >>> 21; - heap[5] = (alen >>> 13) & 255; - heap[6] = (alen >>> 5) & 255; - heap[7] = (alen << 3) & 255; - heap[8] = heap[9] = heap[10] = 0; - heap[11] = clen >>> 29; - heap[12] = (clen >>> 21) & 255; - heap[13] = (clen >>> 13) & 255; - heap[14] = (clen >>> 5) & 255; - heap[15] = (clen << 3) & 255; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16); - asm.get_iv(AES_asm.HEAP_DATA); - asm.set_counter(0, 0, 0, this.gamma0); - asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16); - let acheck = 0; - for (let i = 0; i < tagSize; ++i) - acheck |= atag[i] ^ heap[i]; - if (acheck) - throw new SecurityError('data integrity check failed'); - this.counter = 1; - this.aes.pos = 0; - this.aes.len = 0; - return result; - } - AES_GCM_decrypt(data) { - const result1 = this.AES_GCM_Decrypt_process(data); - const result2 = this.AES_GCM_Decrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - AES_GCM_encrypt(data) { - const result1 = this.AES_GCM_Encrypt_process(data); - const result2 = this.AES_GCM_Encrypt_finish(); - const result = new Uint8Array(result1.length + result2.length); - if (result1.length) - result.set(result1); - if (result2.length) - result.set(result2, result1.length); - return result; - } - _gcm_mac_process(data) { - let { asm, heap } = this.aes.acquire_asm(); - let dpos = 0; - let dlen = data.length || 0; - let wlen = 0; - while (dlen > 0) { - wlen = _heap_write(heap, 0, data, dpos, dlen); - dpos += wlen; - dlen -= wlen; - while (wlen & 15) - heap[wlen++] = 0; - asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$4 = util.getWebCrypto(); -const nodeCrypto$4 = util.getNodeCrypto(); -const Buffer$2 = util.getNodeBuffer(); - -const blockLength$3 = 16; -const ivLength$2 = 12; // size of the IV in bytes -const tagLength$2 = 16; // size of the tag in bytes -const ALGO = 'AES-GCM'; - -/** - * Class to en/decrypt using GCM mode. - * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use - * @param {Uint8Array} key - The encryption key - */ -async function GCM(cipher, key) { - if (cipher !== enums.symmetric.aes128 && - cipher !== enums.symmetric.aes192 && - cipher !== enums.symmetric.aes256) { - throw new Error('GCM mode supports only AES cipher'); - } - - if (util.getNodeCrypto()) { // Node crypto library - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - en.setAAD(adata); - const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv); - de.setAAD(adata); - de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext - const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]); - return new Uint8Array(pt); - } - }; - } - - if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support - const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']); - - return { - encrypt: async function(pt, iv, adata = new Uint8Array()) { - if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.encrypt(pt, key, iv, adata); - } - const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt); - return new Uint8Array(ct); - }, - - decrypt: async function(ct, iv, adata = new Uint8Array()) { - if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages - return AES_GCM.decrypt(ct, key, iv, adata); - } - const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct); - return new Uint8Array(pt); - } - }; - } - - return { - encrypt: async function(pt, iv, adata) { - return AES_GCM.encrypt(pt, key, iv, adata); - }, - - decrypt: async function(ct, iv, adata) { - return AES_GCM.decrypt(ct, key, iv, adata); - } - }; -} - - -/** - * Get GCM nonce. Note: this operation is not defined by the standard. - * A future version of the standard may define GCM mode differently, - * hopefully under a different ID (we use Private/Experimental algorithm - * ID 100) so that we can maintain backwards compatibility. - * @param {Uint8Array} iv - The initialization vector (12 bytes) - * @param {Uint8Array} chunkIndex - The chunk index (8 bytes) - */ -GCM.getNonce = function(iv, chunkIndex) { - const nonce = iv.slice(); - for (let i = 0; i < chunkIndex.length; i++) { - nonce[4 + i] ^= chunkIndex[i]; - } - return nonce; -}; - -GCM.blockLength = blockLength$3; -GCM.ivLength = ivLength$2; -GCM.tagLength = tagLength$2; - -/** - * @fileoverview Cipher modes - * @module crypto/mode - * @private - */ - -var mode = { - /** @see module:crypto/mode/cfb */ - cfb: cfb, - /** @see module:crypto/mode/gcm */ - gcm: GCM, - experimentalGCM: GCM, - /** @see module:crypto/mode/eax */ - eax: EAX, - /** @see module:crypto/mode/ocb */ - ocb: OCB -}; - -var naclFastLight = createCommonjsModule(function (module) { -/*jshint bitwise: false*/ - -(function(nacl) { - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d; - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d, h, r; - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - d = nacl.hash(sk.subarray(0, 32)); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - r = nacl.hash(sm.subarray(32, smlen)); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - h = nacl.hash(sm.subarray(0, smlen)); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i; - var t = new Uint8Array(32), h; - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - h = nacl.hash(m.subarray(0, n)); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - return n; -} - -var crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32; - -function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError('unexpected type, use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.box = {}; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof commonjsRequire !== 'undefined') { - // Node.js. - crypto = void('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(module.exports ? module.exports : (self.nacl = self.nacl || {})); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const nodeCrypto$5 = util.getNodeCrypto(); - -/** - * Retrieve secure random byte array of the specified length - * @param {Integer} length - Length in bytes to generate - * @returns {Uint8Array} Random byte array. - */ -function getRandomBytes(length) { - const buf = new Uint8Array(length); - if (nodeCrypto$5) { - const bytes = nodeCrypto$5.randomBytes(buf.length); - buf.set(bytes); - } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) { - crypto.getRandomValues(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; -} - -/** - * Create a secure random BigInteger that is greater than or equal to min and less than max. - * @param {module:BigInteger} min - Lower bound, included - * @param {module:BigInteger} max - Upper bound, excluded - * @returns {Promise} Random BigInteger. - * @async - */ -async function getRandomBigInteger(min, max) { - const BigInteger = await util.getBigInteger(); - - if (max.lt(min)) { - throw new Error('Illegal parameter value: max <= min'); - } - - const modulus = max.sub(min); - const bytes = modulus.byteLength(); - - // Using a while loop is necessary to avoid bias introduced by the mod operation. - // However, we request 64 extra random bits so that the bias is negligible. - // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - const r = new BigInteger(await getRandomBytes(bytes + 8)); - return r.mod(modulus).add(min); -} - -var random = /*#__PURE__*/Object.freeze({ - __proto__: null, - getRandomBytes: getRandomBytes, - getRandomBigInteger: getRandomBigInteger -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Generate a probably prime random number - * @param {Integer} bits - Bit length of the prime - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns BigInteger - * @async - */ -async function randomProbablePrime(bits, e, k) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - const min = one.leftShift(new BigInteger(bits - 1)); - const thirty = new BigInteger(30); - /* - * We can avoid any multiples of 3 and 5 by looking at n mod 30 - * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 - * the next possible prime is mod 30: - * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 - */ - const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; - - const n = await getRandomBigInteger(min, min.leftShift(one)); - let i = n.mod(thirty).toNumber(); - - do { - n.iadd(new BigInteger(adds[i])); - i = (i + adds[i]) % adds.length; - // If reached the maximum, go back to the minimum. - if (n.bitLength() > bits) { - n.imod(min.leftShift(one)).iadd(min); - i = n.mod(thirty).toNumber(); - } - } while (!await isProbablePrime(n, e, k)); - return n; -} - -/** - * Probabilistic primality testing - * @param {BigInteger} n - Number to test - * @param {BigInteger} e - Optional RSA exponent to check against the prime - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @returns {boolean} - * @async - */ -async function isProbablePrime(n, e, k) { - if (e && !n.dec().gcd(e).isOne()) { - return false; - } - if (!await divisionTest(n)) { - return false; - } - if (!await fermat(n)) { - return false; - } - if (!await millerRabin(n, k)) { - return false; - } - // TODO implement the Lucas test - // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - return true; -} - -/** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n != 1. - * @param {BigInteger} n - Number to test - * @param {BigInteger} b - Optional Fermat test base - * @returns {boolean} - */ -async function fermat(n, b) { - const BigInteger = await util.getBigInteger(); - b = b || new BigInteger(2); - return b.modExp(n.dec(), n).isOne(); -} - -async function divisionTest(n) { - const BigInteger = await util.getBigInteger(); - return smallPrimes.every(m => { - return n.mod(new BigInteger(m)) !== 0; - }); -} - -// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c -const smallPrimes = [ - 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, - 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, - 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, - 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, - 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, - 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, - 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, - 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, - 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, - 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, - 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, - 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, - 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, - 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, - 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, - 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, - 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, - 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, - 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, - 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, - 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, - 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, - 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, - 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, - 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, - 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, - 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, - 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, - 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, - 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, - 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, - 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, - 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, - 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, - 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, - 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, - 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, - 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, - 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, - 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, - 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, - 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, - 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, - 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, - 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, - 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, - 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, - 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, - 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, - 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, - 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, - 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, - 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, - 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, - 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, - 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, - 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, - 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, - 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, - 4957, 4967, 4969, 4973, 4987, 4993, 4999 -]; - - -// Miller-Rabin - Miller Rabin algorithm for primality test -// Copyright Fedor Indutny, 2014. -// -// This software is licensed under the MIT License. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin - -// Sample syntax for Fixed-Base Miller-Rabin: -// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) - -/** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param {BigInteger} n - Number to test - * @param {Integer} k - Optional number of iterations of Miller-Rabin test - * @param {Function} rand - Optional function to generate potential witnesses - * @returns {boolean} - * @async - */ -async function millerRabin(n, k, rand) { - const BigInteger = await util.getBigInteger(); - const len = n.bitLength(); - - if (!k) { - k = Math.max(1, (len / 48) | 0); - } - - const n1 = n.dec(); // n - 1 - - // Find d and s, (n - 1) = (2 ^ s) * d; - let s = 0; - while (!n1.getBit(s)) { s++; } - const d = n.rightShift(new BigInteger(s)); - - for (; k > 0; k--) { - const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1); - - let x = a.modExp(d, n); - if (x.isOne() || x.equal(n1)) { - continue; - } - - let i; - for (i = 1; i < s; i++) { - x = x.mul(x).mod(n); - - if (x.isOne()) { - return false; - } - if (x.equal(n1)) { - break; - } - } - - if (i === s) { - return false; - } - } - - return true; -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ASN1 object identifiers for hashes - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2} - */ -const hash_headers = []; -hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, - 0x10]; -hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; -hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; -hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, - 0x04, 0x20]; -hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, - 0x04, 0x30]; -hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, - 0x00, 0x04, 0x40]; -hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, - 0x00, 0x04, 0x1C]; - -/** - * Create padding with secure random data - * @private - * @param {Integer} length - Length of the padding in bytes - * @returns {Uint8Array} Random padding. - */ -function getPKCS1Padding(length) { - const result = new Uint8Array(length); - let count = 0; - while (count < length) { - const randomBytes = getRandomBytes(length - count); - for (let i = 0; i < randomBytes.length; i++) { - if (randomBytes[i] !== 0) { - result[count++] = randomBytes[i]; - } - } - } - return result; -} - -/** - * Create a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1} - * @param {Uint8Array} message - Message to be encoded - * @param {Integer} keyLength - The length in octets of the key modulus - * @returns {Uint8Array} EME-PKCS1 padded message. - */ -function emeEncode(message, keyLength) { - const mLength = message.length; - // length checking - if (mLength > keyLength - 11) { - throw new Error('Message too long'); - } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - const PS = getPKCS1Padding(keyLength - mLength - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - const encoded = new Uint8Array(keyLength); - // 0x00 byte - encoded[1] = 2; - encoded.set(PS, 2); - // 0x00 bytes - encoded.set(message, keyLength - mLength); - return encoded; -} - -/** - * Decode a EME-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2} - * @param {Uint8Array} encoded - Encoded message bytes - * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing) - * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given) - * @throws {Error} on decoding failure, unless `randomPayload` is provided - */ -function emeDecode(encoded, randomPayload) { - // encoded format: 0x00 0x02 0x00 - let offset = 2; - let separatorNotFound = 1; - for (let j = offset; j < encoded.length; j++) { - separatorNotFound &= encoded[j] !== 0; - offset += separatorNotFound; - } - - const psLen = offset - 2; - const payload = encoded.subarray(offset + 1); // discard the 0x00 separator - const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound; - - if (randomPayload) { - return util.selectUint8Array(isValidPadding, payload, randomPayload); - } - - if (isValidPadding) { - return payload; - } - - throw new Error('Decryption error'); -} - -/** - * Create a EMSA-PKCS1-v1_5 padded message - * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3} - * @param {Integer} algo - Hash algorithm type used - * @param {Uint8Array} hashed - Message to be encoded - * @param {Integer} emLen - Intended length in octets of the encoded message - * @returns {Uint8Array} Encoded message. - */ -async function emsaEncode(algo, hashed, emLen) { - let i; - if (hashed.length !== hash.getHashByteLength(algo)) { - throw new Error('Invalid hash length'); - } - // produce an ASN.1 DER value for the hash function used. - // Let T be the full hash prefix - const hashPrefix = new Uint8Array(hash_headers[algo].length); - for (i = 0; i < hash_headers[algo].length; i++) { - hashPrefix[i] = hash_headers[algo][i]; - } - // and let tLen be the length in octets prefix and hashed data - const tLen = hashPrefix.length + hashed.length; - if (emLen < tLen + 11) { - throw new Error('Intended encoded message length too short'); - } - // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF - // The length of PS will be at least 8 octets - const PS = new Uint8Array(emLen - tLen - 3).fill(0xff); - - // Concatenate PS, the hash prefix, hashed data, and other padding to form the - // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed - const EM = new Uint8Array(emLen); - EM[1] = 0x01; - EM.set(PS, 2); - EM.set(hashPrefix, emLen - tLen); - EM.set(hashed, emLen - hashed.length); - return EM; -} - -var pkcs1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - emeEncode: emeEncode, - emeDecode: emeDecode, - emsaEncode: emsaEncode -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -const webCrypto$5 = util.getWebCrypto(); -const nodeCrypto$6 = util.getNodeCrypto(); -const asn1 = nodeCrypto$6 ? void('asn1.js') : undefined; - -/* eslint-disable no-invalid-this */ -const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('version').int(), // 0 - this.key('modulus').int(), // n - this.key('publicExponent').int(), // e - this.key('privateExponent').int(), // d - this.key('prime1').int(), // p - this.key('prime2').int(), // q - this.key('exponent1').int(), // dp - this.key('exponent2').int(), // dq - this.key('coefficient').int() // u - ); -}) : undefined; - -const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () { - this.seq().obj( // used for native NodeJS crypto - this.key('modulus').int(), // n - this.key('publicExponent').int() // e - ); -}) : undefined; -/* eslint-enable no-invalid-this */ - -/** Create signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} hashed - Hashed message - * @returns {Promise} RSA Signature. - * @async - */ -async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeSign(hashAlgo, data, n, e, d, p, q, u); - } - } - return bnSign(hashAlgo, n, d, hashed); -} - -/** - * Verify signature - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Uint8Array} data - Message - * @param {Uint8Array} s - Signature - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} hashed - Hashed message - * @returns {Boolean} - * @async - */ -async function verify(hashAlgo, data, s, n, e, hashed) { - if (data && !util.isStream(data)) { - if (util.getWebCrypto()) { - try { - return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e); - } catch (err) { - util.printDebugError(err); - } - } else if (util.getNodeCrypto()) { - return nodeVerify(hashAlgo, data, s, n, e); - } - } - return bnVerify(hashAlgo, s, n, e, hashed); -} - -/** - * Encrypt message - * @param {Uint8Array} data - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @returns {Promise} RSA Ciphertext. - * @async - */ -async function encrypt$1(data, n, e) { - if (util.getNodeCrypto()) { - return nodeEncrypt$1(data, n, e); - } - return bnEncrypt(data, n, e); -} - -/** - * Decrypt RSA message - * @param {Uint8Array} m - Message - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA private coefficient - * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} RSA Plaintext. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$1(data, n, e, d, p, q, u, randomPayload) { - // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption, - // and we want to avoid checking the error type to decide if the random payload - // should indeed be returned. - if (util.getNodeCrypto() && !randomPayload) { - try { - return await nodeDecrypt$1(data, n, e, d, p, q, u); - } catch (err) { - util.printDebugError(err); - } - } - return bnDecrypt(data, n, e, d, p, q, u, randomPayload); -} - -/** - * Generate a new random private key B bits long with public exponent E. - * - * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param {Integer} bits - RSA bit length - * @param {Integer} e - RSA public exponent - * @returns {{n, e, d, - * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = p ** -1 mod q - * @async - */ -async function generate(bits, e) { - const BigInteger = await util.getBigInteger(); - - e = new BigInteger(e); - - // Native RSA keygen using Web Crypto - if (util.getWebCrypto()) { - const keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, // the specified keysize in bits - publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']); - - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey); - // map JWK parameters to corresponding OpenPGP names - return { - n: b64ToUint8Array(jwk.n), - e: e.toUint8Array(), - d: b64ToUint8Array(jwk.d), - // switch p and q - p: b64ToUint8Array(jwk.q), - q: b64ToUint8Array(jwk.p), - // Since p and q are switched in places, u is the inverse of jwk.q - u: b64ToUint8Array(jwk.qi) - }; - } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) { - const opts = { - modulusLength: bits, - publicExponent: e.toNumber(), - publicKeyEncoding: { type: 'pkcs1', format: 'der' }, - privateKeyEncoding: { type: 'pkcs1', format: 'der' } - }; - const prv = await new Promise((resolve, reject) => { - nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => { - if (err) { - reject(err); - } else { - resolve(RSAPrivateKey.decode(der, 'der')); - } - }); - }); - /** - * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`. - * @link https://tools.ietf.org/html/rfc3447#section-3.2 - * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1 - */ - return { - n: prv.modulus.toArrayLike(Uint8Array), - e: prv.publicExponent.toArrayLike(Uint8Array), - d: prv.privateExponent.toArrayLike(Uint8Array), - // switch p and q - p: prv.prime2.toArrayLike(Uint8Array), - q: prv.prime1.toArrayLike(Uint8Array), - // Since p and q are switched in places, we can keep u as defined by DER - u: prv.coefficient.toArrayLike(Uint8Array) - }; - } - - // RSA keygen fallback using 40 iterations of the Miller-Rabin test - // See https://stackoverflow.com/a/6330138 for justification - // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST - let p; - let q; - let n; - do { - q = await randomProbablePrime(bits - (bits >> 1), e, 40); - p = await randomProbablePrime(bits >> 1, e, 40); - n = p.mul(q); - } while (n.bitLength() !== bits); - - const phi = p.dec().imul(q.dec()); - - if (q.lt(p)) { - [p, q] = [q, p]; - } - - return { - n: n.toUint8Array(), - e: e.toUint8Array(), - d: e.modInv(phi).toUint8Array(), - p: p.toUint8Array(), - q: q.toUint8Array(), - // dp: d.mod(p.subn(1)), - // dq: d.mod(q.subn(1)), - u: p.modInv(q).toUint8Array() - }; -} - -/** - * Validate RSA parameters - * @param {Uint8Array} n - RSA public modulus - * @param {Uint8Array} e - RSA public exponent - * @param {Uint8Array} d - RSA private exponent - * @param {Uint8Array} p - RSA private prime p - * @param {Uint8Array} q - RSA private prime q - * @param {Uint8Array} u - RSA inverse of p w.r.t. q - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - p = new BigInteger(p); - q = new BigInteger(q); - - // expect pq = n - if (!p.mul(q).equal(n)) { - return false; - } - - const two = new BigInteger(2); - // expect p*u = 1 mod q - u = new BigInteger(u); - if (!p.mul(u).mod(q).isOne()) { - return false; - } - - e = new BigInteger(e); - d = new BigInteger(d); - /** - * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1) - * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)] - * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)] - * - * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1) - */ - const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3)); - const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q - const rde = r.mul(d).mul(e); - - const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r); - if (!areInverses) { - return false; - } - - return true; -} - -async function bnSign(hashAlgo, n, d, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength())); - d = new BigInteger(d); - if (m.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return m.modExp(d, n).toUint8Array('be', n.byteLength()); -} - -async function webSign(hashName, data, n, e, d, p, q, u) { - /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q. - * We swap them in privateToJWK, so it usually works out, but nevertheless, - * not all OpenPGP keys are compatible with this requirement. - * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still - * does if the underlying Web Crypto does so (though the tested implementations - * don't do so). - */ - const jwk = await privateToJWK(n, e, d, p, q, u); - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }; - const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']); - return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data)); -} - -async function nodeSign(hashAlgo, data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(data); - sign.end(); - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPrivateKey.encode(keyObject, 'der'); - return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' })); - } - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - return new Uint8Array(sign.sign(pem)); -} - -async function bnVerify(hashAlgo, s, n, e, hashed) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - s = new BigInteger(s); - e = new BigInteger(e); - if (s.gte(n)) { - throw new Error('Signature size cannot exceed modulus size'); - } - const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength()); - const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength()); - return util.equalsUint8Array(EM1, EM2); -} - -async function webVerify(hashName, data, s, n, e) { - const jwk = publicToJWK(n, e); - const key = await webCrypto$5.importKey('jwk', jwk, { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: hashName } - }, false, ['verify']); - return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data); -} - -async function nodeVerify(hashAlgo, data, s, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(data); - verify.end(); - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1' }; - } else { - key = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - } - try { - return await verify.verify(key, s); - } catch (err) { - return false; - } -} - -async function nodeEncrypt$1(data, n, e) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const keyObject = { - modulus: new BN(n), - publicExponent: new BN(e) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPublicKey.encode(keyObject, 'der'); - key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPublicKey.encode(keyObject, 'pem', { - label: 'RSA PUBLIC KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data)); -} - -async function bnEncrypt(data, n, e) { - const BigInteger = await util.getBigInteger(); - n = new BigInteger(n); - data = new BigInteger(emeEncode(data, n.byteLength())); - e = new BigInteger(e); - if (data.gte(n)) { - throw new Error('Message size cannot exceed modulus size'); - } - return data.modExp(e, n).toUint8Array('be', n.byteLength()); -} - -async function nodeDecrypt$1(data, n, e, d, p, q, u) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const pBNum = new BN(p); - const qBNum = new BN(q); - const dBNum = new BN(d); - const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1) - const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1) - const keyObject = { - version: 0, - modulus: new BN(n), - publicExponent: new BN(e), - privateExponent: new BN(d), - // switch p and q - prime1: new BN(q), - prime2: new BN(p), - // switch dp and dq - exponent1: dq, - exponent2: dp, - coefficient: new BN(u) - }; - let key; - if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { - const der = RSAPrivateKey.encode(keyObject, 'der'); - key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } else { - const pem = RSAPrivateKey.encode(keyObject, 'pem', { - label: 'RSA PRIVATE KEY' - }); - key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING }; - } - try { - return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data)); - } catch (err) { - throw new Error('Decryption error'); - } -} - -async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) { - const BigInteger = await util.getBigInteger(); - data = new BigInteger(data); - n = new BigInteger(n); - e = new BigInteger(e); - d = new BigInteger(d); - p = new BigInteger(p); - q = new BigInteger(q); - u = new BigInteger(u); - if (data.gte(n)) { - throw new Error('Data too large.'); - } - const dq = d.mod(q.dec()); // d mod (q-1) - const dp = d.mod(p.dec()); // d mod (p-1) - - const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n); - const blinder = unblinder.modInv(n).modExp(e, n); - data = data.mul(blinder).mod(n); - - - const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p - const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q - const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q) - - let result = h.mul(p).add(mp); // result < n due to relations above - - result = result.mul(unblinder).mod(n); - - - return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload); -} - -/** Convert Openpgp private key params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - * @param {Uint8Array} d - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} u - */ -async function privateToJWK(n, e, d, p, q, u) { - const BigInteger = await util.getBigInteger(); - const pNum = new BigInteger(p); - const qNum = new BigInteger(q); - const dNum = new BigInteger(d); - - let dq = dNum.mod(qNum.dec()); // d mod (q-1) - let dp = dNum.mod(pNum.dec()); // d mod (p-1) - dp = dp.toUint8Array(); - dq = dq.toUint8Array(); - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - d: uint8ArrayToB64(d, true), - // switch p and q - p: uint8ArrayToB64(q, true), - q: uint8ArrayToB64(p, true), - // switch dp and dq - dp: uint8ArrayToB64(dq, true), - dq: uint8ArrayToB64(dp, true), - qi: uint8ArrayToB64(u, true), - ext: true - }; -} - -/** Convert Openpgp key public params to jwk key according to - * @link https://tools.ietf.org/html/rfc7517 - * @param {String} hashAlgo - * @param {Uint8Array} n - * @param {Uint8Array} e - */ -function publicToJWK(n, e) { - return { - kty: 'RSA', - n: uint8ArrayToB64(n, true), - e: uint8ArrayToB64(e, true), - ext: true - }; -} - -var rsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign, - verify: verify, - encrypt: encrypt$1, - decrypt: decrypt$1, - generate: generate, - validateParams: validateParams -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * ElGamal Encryption function - * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA) - * @param {Uint8Array} data - To be padded and encrypted - * @param {Uint8Array} p - * @param {Uint8Array} g - * @param {Uint8Array} y - * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>} - * @async - */ -async function encrypt$2(data, p, g, y) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const padded = emeEncode(data, p.byteLength()); - const m = new BigInteger(padded); - - // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ* - // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2] - const k = await getRandomBigInteger(new BigInteger(1), p.dec()); - return { - c1: g.modExp(k, p).toUint8Array(), - c2: y.modExp(k, p).imul(m).imod(p).toUint8Array() - }; -} - -/** - * ElGamal Encryption function - * @param {Uint8Array} c1 - * @param {Uint8Array} c2 - * @param {Uint8Array} p - * @param {Uint8Array} x - * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing - * (needed for constant-time processing) - * @returns {Promise} Unpadded message. - * @throws {Error} on decryption error, unless `randomPayload` is given - * @async - */ -async function decrypt$2(c1, c2, p, x, randomPayload) { - const BigInteger = await util.getBigInteger(); - c1 = new BigInteger(c1); - c2 = new BigInteger(c2); - p = new BigInteger(p); - x = new BigInteger(x); - - const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p); - return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload); -} - -/** - * Validate ElGamal parameters - * @param {Uint8Array} p - ElGamal prime - * @param {Uint8Array} g - ElGamal group generator - * @param {Uint8Array} y - ElGamal public key - * @param {Uint8Array} x - ElGamal private exponent - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$1(p, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - g = new BigInteger(g); - y = new BigInteger(y); - - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - // Expect p-1 to be large - const pSize = new BigInteger(p.bitLength()); - const n1023 = new BigInteger(1023); - if (pSize.lt(n1023)) { - return false; - } - - /** - * g should have order p-1 - * Check that g ** (p-1) = 1 mod p - */ - if (!g.modExp(p.dec(), p).isOne()) { - return false; - } - - /** - * Since p-1 is not prime, g might have a smaller order that divides p-1 - * We want to make sure that the order is large enough to hinder a small subgroup attack - * - * We just check g**i != 1 for all i up to a threshold - */ - let res = g; - const i = new BigInteger(1); - const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold - while (i.lt(threshold)) { - res = res.mul(g).imod(p); - if (res.isOne()) { - return false; - } - i.iinc(); - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{r(p-1) + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1 - const rqx = p.dec().imul(r).iadd(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var elgamal = /*#__PURE__*/Object.freeze({ - __proto__: null, - encrypt: encrypt$2, - decrypt: decrypt$2, - validateParams: validateParams$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class OID { - constructor(oid) { - if (oid instanceof OID) { - this.oid = oid.oid; - } else if (util.isArray(oid) || - util.isUint8Array(oid)) { - oid = new Uint8Array(oid); - if (oid[0] === 0x06) { // DER encoded oid byte array - if (oid[1] !== oid.length - 2) { - throw new Error('Length mismatch in DER encoded oid'); - } - oid = oid.subarray(2); - } - this.oid = oid; - } else { - this.oid = ''; - } - } - - /** - * Method to read an OID object - * @param {Uint8Array} input - Where to read the OID from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length >= 1) { - const length = input[0]; - if (input.length >= 1 + length) { - this.oid = input.subarray(1, 1 + length); - return 1 + this.oid.length; - } - } - throw new Error('Invalid oid'); - } - - /** - * Serialize an OID object - * @returns {Uint8Array} Array with the serialized value the OID. - */ - write() { - return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); - } - - /** - * Serialize an OID object as a hex string - * @returns {string} String with the hex value of the OID. - */ - toHex() { - return util.uint8ArrayToHex(this.oid); - } - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns {string} String with the canonical name of the curve. - */ - getName() { - const hex = this.toHex(); - if (enums.curve[hex]) { - return enums.write(enums.curve, hex); - } else { - throw new Error('Unknown curve object identifier.'); - } - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -function keyFromPrivate(indutnyCurve, priv) { - const keyPair = indutnyCurve.keyPair({ priv: priv }); - return keyPair; -} - -function keyFromPublic(indutnyCurve, pub) { - const keyPair = indutnyCurve.keyPair({ pub: pub }); - if (keyPair.validate().result !== true) { - throw new Error('Invalid elliptic public key'); - } - return keyPair; -} - -async function getIndutnyCurve(name) { - if (!config.useIndutnyElliptic) { - throw new Error('This curve is only supported in the full build of OpenPGP.js'); - } - const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; }); - return new elliptic.ec(name); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -function readSimpleLength(bytes) { - let len = 0; - let offset; - const type = bytes[0]; - - - if (type < 192) { - [len] = bytes; - offset = 1; - } else if (type < 255) { - len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; - offset = 2; - } else if (type === 255) { - len = util.readNumber(bytes.subarray(1, 1 + 4)); - offset = 5; - } - - return { - len: len, - offset: offset - }; -} - -/** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * - * @param {Integer} length - The length to encode - * @returns {Uint8Array} String with openpgp length representation. - */ -function writeSimpleLength(length) { - if (length < 192) { - return new Uint8Array([length]); - } else if (length > 191 && length < 8384) { - /* - * let a = (total data packet length) - 192 let bc = two octet - * representation of a let d = b + 192 - */ - return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); - } - return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); -} - -function writePartialLength(power) { - if (power < 0 || power > 30) { - throw new Error('Partial Length power must be between 1 and 30'); - } - return new Uint8Array([224 + power]); -} - -function writeTag(tag_type) { - /* we're only generating v4 packet headers here */ - return new Uint8Array([0xC0 | tag_type]); -} - -/** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * - * @param {Integer} tag_type - Tag type - * @param {Integer} length - Length of the payload - * @returns {String} String of the header. - */ -function writeHeader(tag_type, length) { - /* we're only generating v4 packet headers here */ - return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); -} - -/** - * Whether the packet type supports partial lengths per RFC4880 - * @param {Integer} tag - Tag type - * @returns {Boolean} String of the header. - */ -function supportsStreaming(tag) { - return [ - enums.packet.literalData, - enums.packet.compressedData, - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ].includes(tag); -} - -/** - * Generic static Packet Parser function - * - * @param {Uint8Array | ReadableStream} input - Input stream as string - * @param {Function} callback - Function to call with the parsed packet - * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. - */ -async function readPackets(input, callback) { - const reader = getReader(input); - let writer; - let callbackReturned; - try { - const peekedBytes = await reader.peekBytes(2); - // some sanity checks - if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { - throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); - } - const headerByte = await reader.readByte(); - let tag = -1; - let format = -1; - let packetLength; - - format = 0; // 0 = old format; 1 = new format - if ((headerByte & 0x40) !== 0) { - format = 1; - } - - let packetLengthType; - if (format) { - // new format header - tag = headerByte & 0x3F; // bit 5-0 - } else { - // old format header - tag = (headerByte & 0x3F) >> 2; // bit 5-2 - packetLengthType = headerByte & 0x03; // bit 1-0 - } - - const packetSupportsStreaming = supportsStreaming(tag); - let packet = null; - if (packetSupportsStreaming) { - if (util.isStream(input) === 'array') { - const arrayStream = new ArrayStream(); - writer = getWriter(arrayStream); - packet = arrayStream; - } else { - const transform = new TransformStream(); - writer = getWriter(transform.writable); - packet = transform.readable; - } - // eslint-disable-next-line callback-return - callbackReturned = callback({ tag, packet }); - } else { - packet = []; - } - - let wasPartialLength; - do { - if (!format) { - // 4.2.1. Old Format Packet Lengths - switch (packetLengthType) { - case 0: - // The packet has a one-octet length. The header is 2 octets - // long. - packetLength = await reader.readByte(); - break; - case 1: - // The packet has a two-octet length. The header is 3 octets - // long. - packetLength = (await reader.readByte() << 8) | await reader.readByte(); - break; - case 2: - // The packet has a four-octet length. The header is 5 - // octets long. - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - break; - default: - // 3 - The packet is of indeterminate length. The header is 1 - // octet long, and the implementation must determine how long - // the packet is. If the packet is in a file, this means that - // the packet extends until the end of the file. In general, - // an implementation SHOULD NOT use indeterminate-length - // packets except where the end of the data will be clear - // from the context, and even then it is better to use a - // definite length, or a new format header. The new format - // headers described below have a mechanism for precisely - // encoding data of indeterminate length. - packetLength = Infinity; - break; - } - } else { // 4.2.2. New Format Packet Lengths - // 4.2.2.1. One-Octet Lengths - const lengthByte = await reader.readByte(); - wasPartialLength = false; - if (lengthByte < 192) { - packetLength = lengthByte; - // 4.2.2.2. Two-Octet Lengths - } else if (lengthByte >= 192 && lengthByte < 224) { - packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; - // 4.2.2.4. Partial Body Lengths - } else if (lengthByte > 223 && lengthByte < 255) { - packetLength = 1 << (lengthByte & 0x1F); - wasPartialLength = true; - if (!packetSupportsStreaming) { - throw new TypeError('This packet type does not support partial lengths.'); - } - // 4.2.2.3. Five-Octet Lengths - } else { - packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << - 8) | await reader.readByte(); - } - } - if (packetLength > 0) { - let bytesRead = 0; - while (true) { - if (writer) await writer.ready; - const { done, value } = await reader.read(); - if (done) { - if (packetLength === Infinity) break; - throw new Error('Unexpected end of packet'); - } - const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); - if (writer) await writer.write(chunk); - else packet.push(chunk); - bytesRead += value.length; - if (bytesRead >= packetLength) { - reader.unshift(value.subarray(packetLength - bytesRead + value.length)); - break; - } - } - } - } while (wasPartialLength); - - // If this was not a packet that "supports streaming", we peek to check - // whether it is the last packet in the message. We peek 2 bytes instead - // of 1 because the beginning of this function also peeks 2 bytes, and we - // want to cut a `subarray` of the correct length into `web-stream-tools`' - // `externalBuffer` as a tiny optimization here. - // - // If it *was* a streaming packet (i.e. the data packets), we peek at the - // entire remainder of the stream, in order to forward errors in the - // remainder of the stream to the packet data. (Note that this means we - // read/peek at all signature packets before closing the literal data - // packet, for example.) This forwards MDC errors to the literal data - // stream, for example, so that they don't get lost / forgotten on - // decryptedMessage.packets.stream, which we never look at. - // - // An example of what we do when stream-parsing a message containing - // [ one-pass signature packet, literal data packet, signature packet ]: - // 1. Read the one-pass signature packet - // 2. Peek 2 bytes of the literal data packet - // 3. Parse the one-pass signature packet - // - // 4. Read the literal data packet, simultaneously stream-parsing it - // 5. Peek until the end of the message - // 6. Finish parsing the literal data packet - // - // 7. Read the signature packet again (we already peeked at it in step 5) - // 8. Peek at the end of the stream again (`peekBytes` returns undefined) - // 9. Parse the signature packet - // - // Note that this means that if there's an error in the very end of the - // stream, such as an MDC error, we throw in step 5 instead of in step 8 - // (or never), which is the point of this exercise. - const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); - if (writer) { - await writer.ready; - await writer.close(); - } else { - packet = util.concatUint8Array(packet); - // eslint-disable-next-line callback-return - await callback({ tag, packet }); - } - return !nextPacket || !nextPacket.length; - } catch (e) { - if (writer) { - await writer.abort(e); - return true; - } else { - throw e; - } - } finally { - if (writer) { - await callbackReturned; - } - reader.releaseLock(); - } -} - -class UnsupportedError extends Error { - constructor(...params) { - super(...params); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, UnsupportedError); - } - - this.name = 'UnsupportedError'; - } -} - -class UnparseablePacket { - constructor(tag, rawContent) { - this.tag = tag; - this.rawContent = rawContent; - } - - write() { - return this.rawContent; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$6 = util.getWebCrypto(); -const nodeCrypto$7 = util.getNodeCrypto(); - -const webCurves = { - 'p256': 'P-256', - 'p384': 'P-384', - 'p521': 'P-521' -}; -const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : []; -const nodeCurves = nodeCrypto$7 ? { - secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, - p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, - p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, - p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, - ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined, - curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined, - brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, - brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, - brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined -} : {}; - -const curves = { - p256: { - oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.p256, - web: webCurves.p256, - payloadSize: 32, - sharedSize: 256 - }, - p384: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.p384, - web: webCurves.p384, - payloadSize: 48, - sharedSize: 384 - }, - p521: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.p521, - web: webCurves.p521, - payloadSize: 66, - sharedSize: 528 - }, - secp256k1: { - oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1, - payloadSize: 32 - }, - ed25519: { - oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], - keyType: enums.publicKey.eddsaLegacy, - hash: enums.hash.sha512, - node: false, // nodeCurves.ed25519 TODO - payloadSize: 32 - }, - curve25519: { - oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], - keyType: enums.publicKey.ecdh, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: false, // nodeCurves.curve25519 TODO - payloadSize: 32 - }, - brainpoolP256r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha256, - cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1, - payloadSize: 32 - }, - brainpoolP384r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha384, - cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1, - payloadSize: 48 - }, - brainpoolP512r1: { - oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], - keyType: enums.publicKey.ecdsa, - hash: enums.hash.sha512, - cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1, - payloadSize: 64 - } -}; - -class CurveWithOID { - constructor(oidOrName, params) { - try { - if (util.isArray(oidOrName) || - util.isUint8Array(oidOrName)) { - // by oid byte array - oidOrName = new OID(oidOrName); - } - if (oidOrName instanceof OID) { - // by curve OID - oidOrName = oidOrName.getName(); - } - // by curve name or oid string - this.name = enums.write(enums.curve, oidOrName); - } catch (err) { - throw new UnsupportedError('Unknown curve'); - } - params = params || curves[this.name]; - - this.keyType = params.keyType; - - this.oid = params.oid; - this.hash = params.hash; - this.cipher = params.cipher; - this.node = params.node && curves[this.name]; - this.web = params.web && curves[this.name]; - this.payloadSize = params.payloadSize; - if (this.web && util.getWebCrypto()) { - this.type = 'web'; - } else if (this.node && util.getNodeCrypto()) { - this.type = 'node'; - } else if (this.name === 'curve25519') { - this.type = 'curve25519'; - } else if (this.name === 'ed25519') { - this.type = 'ed25519'; - } - } - - async genKeyPair() { - let keyPair; - switch (this.type) { - case 'web': - try { - return await webGenKeyPair(this.name); - } catch (err) { - util.printDebugError('Browser did not support generating ec key ' + err.message); - break; - } - case 'node': - return nodeGenKeyPair(this.name); - case 'curve25519': { - const privateKey = getRandomBytes(32); - privateKey[0] = (privateKey[0] & 127) | 64; - privateKey[31] &= 248; - const secretKey = privateKey.slice().reverse(); - keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - case 'ed25519': { - const privateKey = getRandomBytes(32); - const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey); - const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); - return { publicKey, privateKey }; - } - } - const indutnyCurve = await getIndutnyCurve(this.name); - keyPair = await indutnyCurve.genKeyPair({ - entropy: util.uint8ArrayToString(getRandomBytes(32)) - }); - return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) }; - } -} - -async function generate$1(curve) { - const BigInteger = await util.getBigInteger(); - - curve = new CurveWithOID(curve); - const keyPair = await curve.genKeyPair(); - const Q = new BigInteger(keyPair.publicKey).toUint8Array(); - const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize); - return { - oid: curve.oid, - Q, - secret, - hash: curve.hash, - cipher: curve.cipher - }; -} - -/** - * Get preferred hash algo to use with the given curve - * @param {module:type/oid} oid - curve oid - * @returns {enums.hash} hash algorithm - */ -function getPreferredHashAlgo(oid) { - return curves[enums.write(enums.curve, oid.toHex())].hash; -} - -/** - * Validate ECDH and ECDSA parameters - * Not suitable for EdDSA (different secret key format) - * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves - * @param {module:type/oid} oid - EC object identifier - * @param {Uint8Array} Q - EC public point - * @param {Uint8Array} d - EC secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateStandardParams(algo, oid, Q, d) { - const supportedCurves = { - p256: true, - p384: true, - p521: true, - secp256k1: true, - curve25519: algo === enums.publicKey.ecdh, - brainpoolP256r1: true, - brainpoolP384r1: true, - brainpoolP512r1: true - }; - - // Check whether the given curve is supported - const curveName = oid.getName(); - if (!supportedCurves[curveName]) { - return false; - } - - if (curveName === 'curve25519') { - d = d.slice().reverse(); - // Re-derive public point Q' - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d); - - Q = new Uint8Array(Q); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - if (!util.equalsUint8Array(dG, Q)) { - return false; - } - - return true; - } - - const curve = await getIndutnyCurve(curveName); - try { - // Parse Q and check that it is on the curve but not at infinity - Q = keyFromPublic(curve, Q).getPublic(); - } catch (validationErrors) { - return false; - } - - /** - * Re-derive public point Q' = dG from private key - * Expect Q == Q' - */ - const dG = keyFromPrivate(curve, d).getPublic(); - if (!dG.eq(Q)) { - return false; - } - - return true; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -async function webGenKeyPair(name) { - // Note: keys generated with ECDSA and ECDH are structurally equivalent - const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - - const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey); - const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey); - - return { - publicKey: jwkToRawPublic(publicKey), - privateKey: b64ToUint8Array(privateKey.d) - }; -} - -async function nodeGenKeyPair(name) { - // Note: ECDSA and ECDH key generation is structurally equivalent - const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]); - await ecdh.generateKeys(); - return { - publicKey: new Uint8Array(ecdh.getPublicKey()), - privateKey: new Uint8Array(ecdh.getPrivateKey()) - }; -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -/** - * @param {JsonWebKey} jwk - key for conversion - * - * @returns {Uint8Array} Raw public key. - */ -function jwkToRawPublic(jwk) { - const bufX = b64ToUint8Array(jwk.x); - const bufY = b64ToUint8Array(jwk.y); - const publicKey = new Uint8Array(bufX.length + bufY.length + 1); - publicKey[0] = 0x04; - publicKey.set(bufX, 1); - publicKey.set(bufY, bufX.length + 1); - return publicKey; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * - * @returns {JsonWebKey} Public key in jwk format. - */ -function rawPublicToJWK(payloadSize, name, publicKey) { - const len = payloadSize; - const bufX = publicKey.slice(1, len + 1); - const bufY = publicKey.slice(len + 1, len * 2 + 1); - // https://www.rfc-editor.org/rfc/rfc7518.txt - const jwk = { - kty: 'EC', - crv: name, - x: uint8ArrayToB64(bufX, true), - y: uint8ArrayToB64(bufY, true), - ext: true - }; - return jwk; -} - -/** - * @param {Integer} payloadSize - ec payload size - * @param {String} name - curve name - * @param {Uint8Array} publicKey - public key - * @param {Uint8Array} privateKey - private key - * - * @returns {JsonWebKey} Private key in jwk format. - */ -function privateToJWK$1(payloadSize, name, publicKey, privateKey) { - const jwk = rawPublicToJWK(payloadSize, name, publicKey); - jwk.d = uint8ArrayToB64(privateKey, true); - return jwk; -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$7 = util.getWebCrypto(); -const nodeCrypto$8 = util.getNodeCrypto(); - -/** - * Sign a message using the provided key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - const keyPair = { publicKey, privateKey }; - switch (curve.type) { - case 'web': { - // If browser doesn't support a curve, we'll catch it - try { - // Need to await to make sure browser succeeds - return await webSign$1(curve, hashAlgo, message, keyPair); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunaley Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support signing: ' + err.message); - } - break; - } - case 'node': { - const signature = await nodeSign$1(curve, hashAlgo, message, keyPair); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; - } - } - } - return ellipticSign(curve, hashed, privateKey); -} - -/** - * Verifies if a signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify - * @param {Uint8Array} message - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) { - const curve = new CurveWithOID(oid); - if (message && !util.isStream(message)) { - switch (curve.type) { - case 'web': - try { - // Need to await to make sure browser succeeds - return await webVerify$1(curve, hashAlgo, signature, message, publicKey); - } catch (err) { - // We do not fallback if the error is related to key integrity - // Unfortunately Safari does not support p521 and throws a DataError when using it - // So we need to always fallback for that curve - if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) { - throw err; - } - util.printDebugError('Browser did not support verifying: ' + err.message); - } - break; - case 'node': - return nodeVerify$1(curve, hashAlgo, signature, message, publicKey); - } - } - const digest = (typeof hashAlgo === 'undefined') ? message : hashed; - return ellipticVerify(curve, signature, digest, publicKey); -} - -/** - * Validate ECDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDSA public point - * @param {Uint8Array} d - ECDSA secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$2(oid, Q, d) { - const curve = new CurveWithOID(oid); - // Reject curves x25519 and ed25519 - if (curve.keyType !== enums.publicKey.ecdsa) { - return false; - } - - // To speed up the validation, we try to use node- or webcrypto when available - // and sign + verify a random message - switch (curve.type) { - case 'web': - case 'node': { - const message = getRandomBytes(8); - const hashAlgo = enums.hash.sha256; - const hashed = await hash.digest(hashAlgo, message); - try { - const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed); - return await verify$1(oid, hashAlgo, signature, message, Q, hashed); - } catch (err) { - return false; - } - } - default: - return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); - } -} - - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - -async function ellipticSign(curve, hashed, privateKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPrivate(indutnyCurve, privateKey); - const signature = key.sign(hashed); - return { - r: signature.r.toArrayLike(Uint8Array), - s: signature.s.toArrayLike(Uint8Array) - }; -} - -async function ellipticVerify(curve, signature, digest, publicKey) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const key = keyFromPublic(indutnyCurve, publicKey); - return key.verify(digest, signature); -} - -async function webSign$1(curve, hashAlgo, message, keyPair) { - const len = curve.payloadSize; - const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['sign'] - ); - - const signature = new Uint8Array(await webCrypto$7.sign( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - message - )); - - return { - r: signature.slice(0, len), - s: signature.slice(len, len << 1) - }; -} - -async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); - const key = await webCrypto$7.importKey( - 'jwk', - jwk, - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, curve.hash) } - }, - false, - ['verify'] - ); - - const signature = util.concatUint8Array([r, s]).buffer; - - return webCrypto$7.verify( - { - 'name': 'ECDSA', - 'namedCurve': webCurves[curve.name], - 'hash': { name: enums.read(enums.webHash, hashAlgo) } - }, - key, - signature, - message - ); -} - -async function nodeSign$1(curve, hashAlgo, message, keyPair) { - const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo)); - sign.write(message); - sign.end(); - const key = ECPrivateKey.encode({ - version: 1, - parameters: curve.oid, - privateKey: Array.from(keyPair.privateKey), - publicKey: { unused: 0, data: Array.from(keyPair.publicKey) } - }, 'pem', { - label: 'EC PRIVATE KEY' - }); - - return ECDSASignature.decode(sign.sign(key), 'der'); -} - -async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) { - const { default: BN } = await Promise.resolve().then(function () { return bn$1; }); - - const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo)); - verify.write(message); - verify.end(); - const key = SubjectPublicKeyInfo.encode({ - algorithm: { - algorithm: [1, 2, 840, 10045, 2, 1], - parameters: curve.oid - }, - subjectPublicKey: { unused: 0, data: Array.from(publicKey) } - }, 'pem', { - label: 'PUBLIC KEY' - }); - const signature = ECDSASignature.encode({ - r: new BN(r), s: new BN(s) - }, 'der'); - - try { - return verify.verify(key, signature); - } catch (err) { - return false; - } -} - -// Originally written by Owen Smith https://github.com/omsmith -// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ - -/* eslint-disable no-invalid-this */ - -const asn1$1 = nodeCrypto$8 ? void('asn1.js') : undefined; - -const ECDSASignature = nodeCrypto$8 ? - asn1$1.define('ECDSASignature', function() { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ); - }) : undefined; - -const ECPrivateKey = nodeCrypto$8 ? - asn1$1.define('ECPrivateKey', function() { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().any(), - this.key('publicKey').explicit(1).optional().bitstr() - ); - }) : undefined; - -const AlgorithmIdentifier = nodeCrypto$8 ? - asn1$1.define('AlgorithmIdentifier', function() { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional().any() - ); - }) : undefined; - -const SubjectPublicKeyInfo = nodeCrypto$8 ? - asn1$1.define('SubjectPublicKeyInfo', function() { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ); - }) : undefined; - -var ecdsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$1, - verify: verify$1, - validateParams: validateParams$2 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Sign a message using the provided legacy EdDSA key - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * r: Uint8Array, - * s: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - // EdDSA signature params are returned in little-endian format - return { - r: signature.subarray(0, 32), - s: signature.subarray(32) - }; -} - -/** - * Verifies if a legacy EdDSA signature is valid for a message - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{r: Uint8Array, - s: Uint8Array}} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - const signature = util.concatUint8Array([r, s]); - return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1)); -} -/** - * Validate legacy EdDSA parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - EdDSA public point - * @param {Uint8Array} k - EdDSA secret seed - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$3(oid, Q, k) { - // Check whether the given curve is supported - if (oid.getName() !== 'ed25519') { - return false; - } - - /** - * Derive public point Q' = dG from private key - * and expect Q == Q' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k); - const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix - return util.equalsUint8Array(Q, dG); - -} - -var eddsa_legacy = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$2, - verify: verify$2, - validateParams: validateParams$3 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest()); - -/** - * Generate (non-legacy) EdDSA key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} - */ -async function generate$2(algo) { - switch (algo) { - case enums.publicKey.ed25519: { - const seed = getRandomBytes(32); - const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed); - return { A, seed }; - } - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} - -/** - * Sign a message using the provided key - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) - * @param {Uint8Array} message - Message to sign - * @param {Uint8Array} publicKey - Public key - * @param {Uint8Array} privateKey - Private key used to sign the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Promise<{ - * RS: Uint8Array - * }>} Signature of the message - * @async - */ -async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - const secretKey = util.concatUint8Array([privateKey, publicKey]); - const signature = naclFastLight.sign.detached(hashed, secretKey); - return { RS: signature }; - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } - -} - -/** - * Verifies if a signature is valid for a message - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature - * @param {{ RS: Uint8Array }} signature Signature to verify the message - * @param {Uint8Array} m - Message to verify - * @param {Uint8Array} publicKey - Public key used to verify the message - * @param {Uint8Array} hashed - The hashed message - * @returns {Boolean} - * @async - */ -async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) { - if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) { - throw new Error('Hash algorithm too weak for EdDSA.'); - } - switch (algo) { - case enums.publicKey.ed25519: { - return naclFastLight.sign.detached.verify(hashed, RS, publicKey); - } - case enums.publicKey.ed448: - default: - throw new Error('Unsupported EdDSA algorithm'); - } -} -/** - * Validate (non-legacy) EdDSA parameters - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} A - EdDSA public point - * @param {Uint8Array} seed - EdDSA secret seed - * @param {Uint8Array} oid - (legacy only) EdDSA OID - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$4(algo, A, seed) { - switch (algo) { - case enums.publicKey.ed25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed); - return util.equalsUint8Array(A, publicKey); - } - - case enums.publicKey.ed448: // unsupported - default: - return false; - } -} - -function getPreferredHashAlgo$1(algo) { - switch (algo) { - case enums.publicKey.ed25519: - return enums.hash.sha256; - default: - throw new Error('Unknown EdDSA algo'); - } -} - -var eddsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$2, - sign: sign$3, - verify: verify$3, - validateParams: validateParams$4, - getPreferredHashAlgo: getPreferredHashAlgo$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * AES key wrap - * @function - * @param {Uint8Array} key - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -function wrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const P = unpack(data); - let A = IV; - const R = P; - const n = P.length / 2; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 0; j <= 5; ++j) { - for (let i = 0; i < n; ++i) { - t[1] = n * j + (1 + i); - // B = A - B[0] = A[0]; - B[1] = A[1]; - // B = A || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES(K, B) - B = unpack(aes.encrypt(pack(B))); - // A = MSB(64, B) ^ t - A = B.subarray(0, 2); - A[0] ^= t[0]; - A[1] ^= t[1]; - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - return pack(A, R); -} - -/** - * AES key unwrap - * @function - * @param {String} key - * @param {String} data - * @returns {Uint8Array} - * @throws {Error} - */ -function unwrap(key, data) { - const aes = new cipher['aes' + (key.length * 8)](key); - const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); - const C = unpack(data); - let A = C.subarray(0, 2); - const R = C.subarray(2); - const n = C.length / 2 - 1; - const t = new Uint32Array([0, 0]); - let B = new Uint32Array(4); - for (let j = 5; j >= 0; --j) { - for (let i = n - 1; i >= 0; --i) { - t[1] = n * j + (i + 1); - // B = A ^ t - B[0] = A[0] ^ t[0]; - B[1] = A[1] ^ t[1]; - // B = (A ^ t) || R[i] - B[2] = R[2 * i]; - B[3] = R[2 * i + 1]; - // B = AES-1(B) - B = unpack(aes.decrypt(pack(B))); - // A = MSB(64, B) - A = B.subarray(0, 2); - // R[i] = LSB(64, B) - R[2 * i] = B[2]; - R[2 * i + 1] = B[3]; - } - } - if (A[0] === IV[0] && A[1] === IV[1]) { - return pack(R); - } - throw new Error('Key Data Integrity failed'); -} - -function createArrayBuffer(data) { - if (util.isString(data)) { - const { length } = data; - const buffer = new ArrayBuffer(length); - const view = new Uint8Array(buffer); - for (let j = 0; j < length; ++j) { - view[j] = data.charCodeAt(j); - } - return buffer; - } - return new Uint8Array(data).buffer; -} - -function unpack(data) { - const { length } = data; - const buffer = createArrayBuffer(data); - const view = new DataView(buffer); - const arr = new Uint32Array(length / 4); - for (let i = 0; i < length / 4; ++i) { - arr[i] = view.getUint32(4 * i); - } - return arr; -} - -function pack() { - let length = 0; - for (let k = 0; k < arguments.length; ++k) { - length += 4 * arguments[k].length; - } - const buffer = new ArrayBuffer(length); - const view = new DataView(buffer); - let offset = 0; - for (let i = 0; i < arguments.length; ++i) { - for (let j = 0; j < arguments[i].length; ++j) { - view.setUint32(offset + 4 * j, arguments[i][j]); - } - offset += 4 * arguments[i].length; - } - return new Uint8Array(buffer); -} - -var aesKW = /*#__PURE__*/Object.freeze({ - __proto__: null, - wrap: wrap, - unwrap: unwrap -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * @fileoverview Functions to add and remove PKCS5 padding - * @see PublicKeyEncryptedSessionKeyPacket - * @module crypto/pkcs5 - * @private - */ - -/** - * Add pkcs5 padding to a message - * @param {Uint8Array} message - message to pad - * @returns {Uint8Array} Padded message. - */ -function encode$1(message) { - const c = 8 - (message.length % 8); - const padded = new Uint8Array(message.length + c).fill(c); - padded.set(message); - return padded; -} - -/** - * Remove pkcs5 padding from a message - * @param {Uint8Array} message - message to remove padding from - * @returns {Uint8Array} Message without padding. - */ -function decode$1(message) { - const len = message.length; - if (len > 0) { - const c = message[len - 1]; - if (c >= 1) { - const provided = message.subarray(len - c); - const computed = new Uint8Array(c).fill(c); - if (util.equalsUint8Array(provided, computed)) { - return message.subarray(0, len - c); - } - } - } - throw new Error('Invalid padding'); -} - -var pkcs5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - encode: encode$1, - decode: decode$1 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -const webCrypto$8 = util.getWebCrypto(); -const nodeCrypto$9 = util.getNodeCrypto(); - -/** - * Validate ECDH parameters - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {Uint8Array} Q - ECDH public point - * @param {Uint8Array} d - ECDH secret scalar - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$5(oid, Q, d) { - return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); -} - -// Build Param for ECDH algorithm (RFC 6637) -function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { - return util.concatUint8Array([ - oid.write(), - new Uint8Array([public_algo]), - kdfParams.write(), - util.stringToUint8Array('Anonymous Sender '), - fingerprint.subarray(0, 20) - ]); -} - -// Key Derivation Function (RFC 6637) -async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { - // Note: X is little endian for Curve25519, big-endian for all others. - // This is not ideal, but the RFC's are unclear - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - let i; - if (stripLeading) { - // Work around old go crypto bug - for (i = 0; i < X.length && X[i] === 0; i++); - X = X.subarray(i); - } - if (stripTrailing) { - // Work around old OpenPGP.js bug - for (i = X.length - 1; i >= 0 && X[i] === 0; i--); - X = X.subarray(0, i + 1); - } - const digest = await hash.digest(hashAlgo, util.concatUint8Array([ - new Uint8Array([0, 0, 0, 1]), - X, - param - ])); - return digest.subarray(0, length); -} - -/** - * Generate ECDHE ephemeral key and secret from public key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPublicEphemeralKey(curve, Q) { - switch (curve.type) { - case 'curve25519': { - const d = getRandomBytes(32); - const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d); - let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey); - publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); - return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPublicEphemeralKey(curve, Q); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePublicEphemeralKey(curve, Q); - } - return ellipticPublicEphemeralKey(curve, Q); -} - -/** - * Encrypt and wrap a session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} data - Unpadded session key data - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} - * @async - */ -async function encrypt$3(oid, kdfParams, data, Q, fingerprint) { - const m = encode$1(data); - - const curve = new CurveWithOID(oid); - const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); - const wrappedKey = wrap(Z, m); - return { publicKey, wrappedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function genPrivateEphemeralKey(curve, V, Q, d) { - if (d.length !== curve.payloadSize) { - const privateKey = new Uint8Array(curve.payloadSize); - privateKey.set(d, curve.payloadSize - d.length); - d = privateKey; - } - switch (curve.type) { - case 'curve25519': { - const secretKey = d.slice().reverse(); - const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1)); - return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below - } - case 'web': - if (curve.web && util.getWebCrypto()) { - try { - return await webPrivateEphemeralKey(curve, V, Q, d); - } catch (err) { - util.printDebugError(err); - } - } - break; - case 'node': - return nodePrivateEphemeralKey(curve, V, d); - } - return ellipticPrivateEphemeralKey(curve, V, d); -} - -/** - * Decrypt and unwrap the value derived from session key - * - * @param {module:type/oid} oid - Elliptic curve object identifier - * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} C - Encrypted and wrapped value derived from session key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Value derived from session key. - * @async - */ -async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) { - const curve = new CurveWithOID(oid); - const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); - const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); - const { keySize } = getCipher(kdfParams.cipher); - let err; - for (let i = 0; i < 3; i++) { - try { - // Work around old go crypto bug and old OpenPGP.js bug, respectively. - const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); - return decode$1(unwrap(Z, C)); - } catch (e) { - err = e; - } - } - throw err; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} Q - Recipient public key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPrivateEphemeralKey(curve, V, Q, d) { - const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d); - let privateKey = webCrypto$8.importKey( - 'jwk', - recipient, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V); - let sender = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - [] - ); - [privateKey, sender] = await Promise.all([privateKey, sender]); - let S = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: sender - }, - privateKey, - curve.web.sharedSize - ); - let secret = webCrypto$8.exportKey( - 'jwk', - privateKey - ); - [S, secret] = await Promise.all([S, secret]); - const sharedKey = new Uint8Array(S); - const secretKey = b64ToUint8Array(secret.d); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using webCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function webPublicEphemeralKey(curve, Q) { - const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q); - let keyPair = webCrypto$8.generateKey( - { - name: 'ECDH', - namedCurve: curve.web.web - }, - true, - ['deriveKey', 'deriveBits'] - ); - let recipient = webCrypto$8.importKey( - 'jwk', - jwk, - { - name: 'ECDH', - namedCurve: curve.web.web - }, - false, - [] - ); - [keyPair, recipient] = await Promise.all([keyPair, recipient]); - let s = webCrypto$8.deriveBits( - { - name: 'ECDH', - namedCurve: curve.web.web, - public: recipient - }, - keyPair.privateKey, - curve.web.sharedSize - ); - let p = webCrypto$8.exportKey( - 'jwk', - keyPair.publicKey - ); - [s, p] = await Promise.all([s, p]); - const sharedKey = new Uint8Array(s); - const publicKey = new Uint8Array(jwkToRawPublic(p)); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPrivateEphemeralKey(curve, V, d) { - const indutnyCurve = await getIndutnyCurve(curve.name); - V = keyFromPublic(indutnyCurve, V); - d = keyFromPrivate(indutnyCurve, d); - const secretKey = new Uint8Array(d.getPrivate()); - const S = d.derive(V.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function ellipticPublicEphemeralKey(curve, Q) { - const indutnyCurve = await getIndutnyCurve(curve.name); - const v = await curve.genKeyPair(); - Q = keyFromPublic(indutnyCurve, Q); - const V = keyFromPrivate(indutnyCurve, v.privateKey); - const publicKey = v.publicKey; - const S = V.derive(Q.getPublic()); - const len = indutnyCurve.curve.p.byteLength(); - const sharedKey = S.toArrayLike(Uint8Array, 'be', len); - return { publicKey, sharedKey }; -} - -/** - * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} V - Public part of ephemeral key - * @param {Uint8Array} d - Recipient private key - * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePrivateEphemeralKey(curve, V, d) { - const recipient = nodeCrypto$9.createECDH(curve.node.node); - recipient.setPrivateKey(d); - const sharedKey = new Uint8Array(recipient.computeSecret(V)); - const secretKey = new Uint8Array(recipient.getPrivateKey()); - return { secretKey, sharedKey }; -} - -/** - * Generate ECDHE ephemeral key and secret from public key using nodeCrypto - * - * @param {CurveWithOID} curve - Elliptic curve object - * @param {Uint8Array} Q - Recipient public key - * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} - * @async - */ -async function nodePublicEphemeralKey(curve, Q) { - const sender = nodeCrypto$9.createECDH(curve.node.node); - sender.generateKeys(); - const sharedKey = new Uint8Array(sender.computeSecret(Q)); - const publicKey = new Uint8Array(sender.getPublicKey()); - return { publicKey, sharedKey }; -} - -var ecdh = /*#__PURE__*/Object.freeze({ - __proto__: null, - validateParams: validateParams$5, - encrypt: encrypt$3, - decrypt: decrypt$3 -}); - -/** - * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. - * @module crypto/hkdf - * @private - */ - -const webCrypto$9 = util.getWebCrypto(); -const nodeCrypto$a = util.getNodeCrypto(); -const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle; - -async function HKDF(hashAlgo, inputKey, salt, info, outLen) { - const hash = enums.read(enums.webHash, hashAlgo); - if (!hash) throw new Error('Hash algo not supported with HKDF'); - - if (webCrypto$9 || nodeSubtleCrypto) { - const crypto = webCrypto$9 || nodeSubtleCrypto; - const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); - const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); - return new Uint8Array(bits); - } - - if (nodeCrypto$a) { - const hashAlgoName = enums.read(enums.hash, hashAlgo); - // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869 - - const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest(); - // Step 1: Extract - // PRK = HMAC-Hash(salt, IKM) - const pseudoRandomKey = computeHMAC(salt, inputKey); - - const hashLen = pseudoRandomKey.length; - - // Step 2: Expand - // HKDF-Expand(PRK, info, L) -> OKM - const n = Math.ceil(outLen / hashLen); - const outputKeyingMaterial = new Uint8Array(n * hashLen); - - // HMAC input buffer updated at each iteration - const roundInput = new Uint8Array(hashLen + info.length + 1); - // T_i and last byte are updated at each iteration, but `info` remains constant - roundInput.set(info, hashLen); - - for (let i = 0; i < n; i++) { - // T(0) = empty string (zero length) - // T(i) = HMAC-Hash(PRK, T(i-1) | info | i) - roundInput[roundInput.length - 1] = i + 1; - // t = T(i+1) - const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen)); - roundInput.set(t, 0); - - outputKeyingMaterial.set(t, i * hashLen); - } - - return outputKeyingMaterial.subarray(0, outLen); - } - - throw new Error('No HKDF implementation available'); -} - -/** - * @fileoverview Key encryption and decryption for RFC 6637 ECDH - * @module crypto/public_key/elliptic/ecdh - * @private - */ - -const HKDF_INFO = { - x25519: util.encodeUTF8('OpenPGP X25519') -}; - -/** - * Generate ECDH key for Montgomery curves - * @param {module:enums.publicKey} algo - Algorithm identifier - * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} - */ -async function generate$3(algo) { - switch (algo) { - case enums.publicKey.x25519: { - // k stays in little-endian, unlike legacy ECDH over curve25519 - const k = getRandomBytes(32); - const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k); - return { A, k }; - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** -* Validate ECDH parameters -* @param {module:enums.publicKey} algo - Algorithm identifier -* @param {Uint8Array} A - ECDH public point -* @param {Uint8Array} k - ECDH secret scalar -* @returns {Promise} Whether params are valid. -* @async -*/ -async function validateParams$6(algo, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - /** - * Derive public point A' from private key - * and expect A == A' - */ - const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k); - return util.equalsUint8Array(A, publicKey); - } - - default: - return false; - } -} - -/** - * Wrap and encrypt a session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} data - session key data to be encrypted - * @param {Uint8Array} recipientA - Recipient public key (K_B) - * @returns {Promise<{ - * ephemeralPublicKey: Uint8Array, - * wrappedKey: Uint8Array - * }>} ephemeral public key (K_A) and encrypted key - * @async - */ -async function encrypt$4(algo, data, recipientA) { - switch (algo) { - case enums.publicKey.x25519: { - const ephemeralSecretKey = getRandomBytes(32); - const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA); - const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - recipientA, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - const wrappedKey = wrap(encryptionKey, data); - return { ephemeralPublicKey, wrappedKey }; - } - - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -/** - * Decrypt and unwrap the session key - * - * @param {module:enums.publicKey} algo - Algorithm identifier - * @param {Uint8Array} ephemeralPublicKey - (K_A) - * @param {Uint8Array} wrappedKey, - * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF - * @param {Uint8Array} k - Recipient secret key (b) - * @returns {Promise} decrypted session key data - * @async - */ -async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) { - switch (algo) { - case enums.publicKey.x25519: { - const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey); - const hkdfInput = util.concatUint8Array([ - ephemeralPublicKey, - A, - sharedSecret - ]); - const { keySize } = getCipher(enums.symmetric.aes128); - const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); - return unwrap(encryptionKey, wrappedKey); - } - default: - throw new Error('Unsupported ECDH algorithm'); - } -} - -var ecdh_x = /*#__PURE__*/Object.freeze({ - __proto__: null, - generate: generate$3, - validateParams: validateParams$6, - encrypt: encrypt$4, - decrypt: decrypt$4 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -var elliptic = /*#__PURE__*/Object.freeze({ - __proto__: null, - CurveWithOID: CurveWithOID, - ecdh: ecdh, - ecdhX: ecdh_x, - ecdsa: ecdsa, - eddsaLegacy: eddsa_legacy, - eddsa: eddsa, - generate: generate$1, - getPreferredHashAlgo: getPreferredHashAlgo -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - -/* - TODO regarding the hash function, read: - https://tools.ietf.org/html/rfc4880#section-13.6 - https://tools.ietf.org/html/rfc4880#section-14 -*/ - -/** - * DSA Sign function - * @param {Integer} hashAlgo - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} x - * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} - * @async - */ -async function sign$4(hashAlgo, hashed, g, p, q, x) { - const BigInteger = await util.getBigInteger(); - const one = new BigInteger(1); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - x = new BigInteger(x); - - let k; - let r; - let s; - let t; - g = g.mod(p); - x = x.mod(q); - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - while (true) { - // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - k = await getRandomBigInteger(one, q); // returns in [1, q-1] - r = g.modExp(k, p).imod(q); // (g**k mod p) mod q - if (r.isZero()) { - continue; - } - const xr = x.mul(r).imod(q); - t = h.add(xr).imod(q); // H(m) + x*r mod q - s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q - if (s.isZero()) { - continue; - } - break; - } - return { - r: r.toUint8Array('be', q.byteLength()), - s: s.toUint8Array('be', q.byteLength()) - }; -} - -/** - * DSA Verify function - * @param {Integer} hashAlgo - * @param {Uint8Array} r - * @param {Uint8Array} s - * @param {Uint8Array} hashed - * @param {Uint8Array} g - * @param {Uint8Array} p - * @param {Uint8Array} q - * @param {Uint8Array} y - * @returns {boolean} - * @async - */ -async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) { - const BigInteger = await util.getBigInteger(); - const zero = new BigInteger(0); - r = new BigInteger(r); - s = new BigInteger(s); - - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - - if (r.lte(zero) || r.gte(q) || - s.lte(zero) || s.gte(q)) { - util.printDebug('invalid DSA Signature'); - return false; - } - const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q); - const w = s.modInv(q); // s**-1 mod q - if (w.isZero()) { - util.printDebug('invalid DSA Signature'); - return false; - } - - g = g.mod(p); - y = y.mod(p); - const u1 = h.mul(w).imod(q); // H(m) * w mod q - const u2 = r.mul(w).imod(q); // r * w mod q - const t1 = g.modExp(u1, p); // g**u1 mod p - const t2 = y.modExp(u2, p); // y**u2 mod p - const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q - return v.equal(r); -} - -/** - * Validate DSA parameters - * @param {Uint8Array} p - DSA prime - * @param {Uint8Array} q - DSA group order - * @param {Uint8Array} g - DSA sub-group generator - * @param {Uint8Array} y - DSA public key - * @param {Uint8Array} x - DSA private key - * @returns {Promise} Whether params are valid. - * @async - */ -async function validateParams$7(p, q, g, y, x) { - const BigInteger = await util.getBigInteger(); - p = new BigInteger(p); - q = new BigInteger(q); - g = new BigInteger(g); - y = new BigInteger(y); - const one = new BigInteger(1); - // Check that 1 < g < p - if (g.lte(one) || g.gte(p)) { - return false; - } - - /** - * Check that subgroup order q divides p-1 - */ - if (!p.dec().mod(q).isZero()) { - return false; - } - - /** - * g has order q - * Check that g ** q = 1 mod p - */ - if (!g.modExp(q, p).isOne()) { - return false; - } - - /** - * Check q is large and probably prime (we mainly want to avoid small factors) - */ - const qSize = new BigInteger(q.bitLength()); - const n150 = new BigInteger(150); - if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) { - return false; - } - - /** - * Re-derive public key y' = g ** x mod p - * Expect y == y' - * - * Blinded exponentiation computes g**{rq + x} to compare to y - */ - x = new BigInteger(x); - const two = new BigInteger(2); - const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q - const rqx = q.mul(r).add(x); - if (!y.equal(g.modExp(rqx, p))) { - return false; - } - - return true; -} - -var dsa = /*#__PURE__*/Object.freeze({ - __proto__: null, - sign: sign$4, - verify: verify$4, - validateParams: validateParams$7 -}); - -/** - * @fileoverview Asymmetric cryptography functions - * @module crypto/public_key - * @private - */ - -var publicKey = { - /** @see module:crypto/public_key/rsa */ - rsa: rsa, - /** @see module:crypto/public_key/elgamal */ - elgamal: elgamal, - /** @see module:crypto/public_key/elliptic */ - elliptic: elliptic, - /** @see module:crypto/public_key/dsa */ - dsa: dsa, - /** @see tweetnacl */ - nacl: naclFastLight -}; - -/** - * @fileoverview Provides functions for asymmetric signing and signature verification - * @module crypto/signature - * @private - */ - -/** - * Parse signature in binary form to get the parameters. - * The returned values are only padded for EdDSA, since in the other cases their expected length - * depends on the key params, hence we delegate the padding to the signature verification function. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Uint8Array} signature - Data for which the signature was created - * @returns {Promise} True if signature is valid. - * @async - */ -function parseSignatureParams(algo, signature) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA signatures: - // - MPI of RSA signature value m**d mod n. - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const s = util.readMPI(signature.subarray(read)); - // The signature needs to be the same length as the public key modulo n. - // We pad s on signature verification, where we have access to n. - return { s }; - } - // Algorithm-Specific Fields for DSA or ECDSA signatures: - // - MPI of DSA or ECDSA value r. - // - MPI of DSA or ECDSA value s. - case enums.publicKey.dsa: - case enums.publicKey.ecdsa: - { - const r = util.readMPI(signature.subarray(read)); read += r.length + 2; - const s = util.readMPI(signature.subarray(read)); - return { r, s }; - } - // Algorithm-Specific Fields for legacy EdDSA signatures: - // - MPI of an EC point r. - // - EdDSA value s, in MPI, in the little endian representation - case enums.publicKey.eddsaLegacy: { - // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values: - // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 - let r = util.readMPI(signature.subarray(read)); read += r.length + 2; - r = util.leftPad(r, 32); - let s = util.readMPI(signature.subarray(read)); - s = util.leftPad(s, 32); - return { r, s }; - } - // Algorithm-Specific Fields for Ed25519 signatures: - // - 64 octets of the native signature - case enums.publicKey.ed25519: { - const RS = signature.subarray(read, read + 64); read += RS.length; - return { RS }; - } - default: - throw new UnsupportedError('Unknown signature algorithm.'); - } -} - -/** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} signature - Named algorithm-specific signature parameters - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Data for which the signature was created - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} True if signature is valid. - * @async - */ -async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto - return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); - } - case enums.publicKey.dsa: { - const { g, p, q, y } = publicParams; - const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers - return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicParams; - const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; - // padding needed for webcrypto - const r = util.leftPad(signature.r, curveSize); - const s = util.leftPad(signature.s, curveSize); - return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicParams; - // signature already padded on parsing - return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -/** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {module:enums.hash} hashAlgo - Hash algorithm - * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters - * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters - * @param {Uint8Array} data - Data to be signed - * @param {Uint8Array} hashed - The hashed data - * @returns {Promise} Signature Object containing named signature parameters. - * @async - */ -async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { - if (!publicKeyParams || !privateKeyParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaSign: { - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); - return { s }; - } - case enums.publicKey.dsa: { - const { g, p, q } = publicKeyParams; - const { x } = privateKeyParams; - return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); - } - case enums.publicKey.elgamal: { - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - } - case enums.publicKey.ecdsa: { - const { oid, Q } = publicKeyParams; - const { d } = privateKeyParams; - return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); - } - case enums.publicKey.eddsaLegacy: { - const { oid, Q } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); - } - case enums.publicKey.ed25519: { - const { A } = publicKeyParams; - const { seed } = privateKeyParams; - return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); - } - default: - throw new Error('Unknown signature algorithm.'); - } -} - -var signature = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseSignatureParams: parseSignatureParams, - verify: verify$5, - sign: sign$5 -}); - -// OpenPGP.js - An OpenPGP implementation in javascript - -class ECDHSymmetricKey { - constructor(data) { - if (data) { - this.data = data; - } - } - - /** - * Read an ECDHSymmetricKey from an Uint8Array: - * - 1 octect for the length `l` - * - `l` octects of encoded session key data - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - if (bytes.length >= 1) { - const length = bytes[0]; - if (bytes.length >= 1 + length) { - this.data = bytes.subarray(1, 1 + length); - return 1 + this.data.length; - } - } - throw new Error('Invalid symmetric key'); - } - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -/** - * Implementation of type KDF parameters - * - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - * @module type/kdf_params - * @private - */ - -class KDFParams { - /** - * @param {enums.hash} hash - Hash algorithm - * @param {enums.symmetric} cipher - Symmetric algorithm - */ - constructor(data) { - if (data) { - const { hash, cipher } = data; - this.hash = hash; - this.cipher = cipher; - } else { - this.hash = null; - this.cipher = null; - } - } - - /** - * Read KDFParams from an Uint8Array - * @param {Uint8Array} input - Where to read the KDFParams from - * @returns {Number} Number of read bytes. - */ - read(input) { - if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { - throw new UnsupportedError('Cannot read KDFParams'); - } - this.hash = input[2]; - this.cipher = input[3]; - return 4; - } - - /** - * Write KDFParams to an Uint8Array - * @returns {Uint8Array} Array with the KDFParams value - */ - write() { - return new Uint8Array([3, 1, this.hash, this.cipher]); - } -} - -/** - * Encoded symmetric key for x25519 and x448 - * The payload format varies for v3 and v6 PKESK: - * the former includes an algorithm byte preceeding the encrypted session key. - * - * @module type/x25519x448_symkey - */ - -class ECDHXSymmetricKey { - static fromObject({ wrappedKey, algorithm }) { - const instance = new ECDHXSymmetricKey(); - instance.wrappedKey = wrappedKey; - instance.algorithm = algorithm; - return instance; - } - - /** - * - 1 octect for the length `l` - * - `l` octects of encoded session key data (with optional leading algorithm byte) - * @param {Uint8Array} bytes - * @returns {Number} Number of read bytes. - */ - read(bytes) { - let read = 0; - let followLength = bytes[read++]; - this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even - followLength -= followLength % 2; - this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength; - } - - /** - * Write an MontgomerySymmetricKey as an Uint8Array - * @returns {Uint8Array} Serialised data - */ - write() { - return util.concatUint8Array([ - this.algorithm ? - new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : - new Uint8Array([this.wrappedKey.length]), - this.wrappedKey - ]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param {module:enums.publicKey} keyAlgo - Public key algorithm - * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Uint8Array} data - Session key data to be encrypted - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @returns {Promise} Encrypted session key parameters. - * @async - */ -async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const { n, e } = publicParams; - const c = await publicKey.rsa.encrypt(data, n, e); - return { c }; - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - return publicKey.elgamal.encrypt(data, p, g, y); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicParams; - const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( - oid, kdfParams, data, Q, fingerprint); - return { V, C: new ECDHSymmetricKey(C) }; - } - case enums.publicKey.x25519: { - if (!util.isAES(symmetricAlgo)) { - // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 - throw new Error('X25519 keys can only encrypt AES session keys'); - } - const { A } = publicParams; - const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( - keyAlgo, data, A); - const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); - return { ephemeralPublicKey, C }; - } - default: - return []; - } -} - -/** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} - * @param {module:enums.publicKey} algo - Public key algorithm - * @param {Object} publicKeyParams - Algorithm-specific public key parameters - * @param {Object} privateKeyParams - Algorithm-specific private key parameters - * @param {Object} sessionKeyParams - Encrypted session key parameters - * @param {Uint8Array} fingerprint - Recipient fingerprint - * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing - * (needed for constant-time processing in RSA and ElGamal) - * @returns {Promise} Decrypted data. - * @throws {Error} on sensitive decryption error, unless `randomPayload` is given - * @async - */ -async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { - switch (algo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaEncrypt: { - const { c } = sessionKeyParams; - const { n, e } = publicKeyParams; - const { d, p, q, u } = privateKeyParams; - return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); - } - case enums.publicKey.elgamal: { - const { c1, c2 } = sessionKeyParams; - const p = publicKeyParams.p; - const x = privateKeyParams.x; - return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); - } - case enums.publicKey.ecdh: { - const { oid, Q, kdfParams } = publicKeyParams; - const { d } = privateKeyParams; - const { V, C } = sessionKeyParams; - return publicKey.elliptic.ecdh.decrypt( - oid, kdfParams, V, C.data, Q, d, fingerprint); - } - case enums.publicKey.x25519: { - const { A } = publicKeyParams; - const { k } = privateKeyParams; - const { ephemeralPublicKey, C } = sessionKeyParams; - if (!util.isAES(C.algorithm)) { - throw new Error('AES session key expected'); - } - return publicKey.elliptic.ecdhX.decrypt( - algo, ephemeralPublicKey, C.wrappedKey, A, k); - } - default: - throw new Error('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse public key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. - */ -function parsePublicKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; - const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; - return { read, publicParams: { n, e } }; - } - case enums.publicKey.dsa: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, q, g, y } }; - } - case enums.publicKey.elgamal: { - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; - const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; - return { read, publicParams: { p, g, y } }; - } - case enums.publicKey.ecdsa: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.eddsaLegacy: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - Q = util.leftPad(Q, 33); - return { read: read, publicParams: { oid, Q } }; - } - case enums.publicKey.ecdh: { - const oid = new OID(); read += oid.read(bytes); - checkSupportedCurve(oid); - const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; - const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); - return { read: read, publicParams: { oid, Q, kdfParams } }; - } - case enums.publicKey.ed25519: - case enums.publicKey.x25519: { - const A = bytes.subarray(read, read + 32); read += A.length; - return { read, publicParams: { A } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Parse private key material in binary form to get the key parameters - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @param {Object} publicParams - (ECC only) public params, needed to format some private params - * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. - */ -function parsePrivateKeyParams(algo, bytes, publicParams) { - let read = 0; - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; - const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; - const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; - return { read, privateParams: { d, p, q, u } }; - } - case enums.publicKey.dsa: - case enums.publicKey.elgamal: { - const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; - return { read, privateParams: { x } }; - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const curve = new CurveWithOID(publicParams.oid); - let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; - d = util.leftPad(d, curve.payloadSize); - return { read, privateParams: { d } }; - } - case enums.publicKey.eddsaLegacy: { - const curve = new CurveWithOID(publicParams.oid); - let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; - seed = util.leftPad(seed, curve.payloadSize); - return { read, privateParams: { seed } }; - } - case enums.publicKey.ed25519: { - const seed = bytes.subarray(read, read + 32); read += seed.length; - return { read, privateParams: { seed } }; - } - case enums.publicKey.x25519: { - const k = bytes.subarray(read, read + 32); read += k.length; - return { read, privateParams: { k } }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** Returns the types comprising the encrypted session key of an algorithm - * @param {module:enums.publicKey} algo - The key algorithm - * @param {Uint8Array} bytes - The key material to parse - * @returns {Object} The session key parameters referenced by name. - */ -function parseEncSessionKeyParams(algo, bytes) { - let read = 0; - switch (algo) { - // Algorithm-Specific Fields for RSA encrypted session keys: - // - MPI of RSA encrypted value m**e mod n. - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: { - const c = util.readMPI(bytes.subarray(read)); - return { c }; - } - - // Algorithm-Specific Fields for Elgamal encrypted session keys: - // - MPI of Elgamal value g**k mod p - // - MPI of Elgamal value m * y**k mod p - case enums.publicKey.elgamal: { - const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; - const c2 = util.readMPI(bytes.subarray(read)); - return { c1, c2 }; - } - // Algorithm-Specific Fields for ECDH encrypted session keys: - // - MPI containing the ephemeral key used to establish the shared secret - // - ECDH Symmetric Key - case enums.publicKey.ecdh: { - const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; - const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); - return { V, C }; - } - // Algorithm-Specific Fields for X25519 encrypted session keys: - // - 32 octets representing an ephemeral X25519 public key. - // - A one-octet size of the following fields. - // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). - // - The encrypted session key. - case enums.publicKey.x25519: { - const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length; - const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); - return { ephemeralPublicKey, C }; - } - default: - throw new UnsupportedError('Unknown public key encryption algorithm.'); - } -} - -/** - * Convert params to MPI and serializes them in the proper order - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} params - The key parameters indexed by name - * @returns {Uint8Array} The array containing the MPIs. - */ -function serializeParams(algo, params) { - // Some algorithms do not rely on MPIs to store the binary params - const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]); - const orderedParams = Object.keys(params).map(name => { - const param = params[name]; - if (!util.isUint8Array(param)) return param.write(); - return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); - }); - return util.concatUint8Array(orderedParams); -} - -/** - * Generate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Integer} bits - Bit length for RSA keys - * @param {module:type/oid} oid - Object identifier for ECC keys - * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. - * @async - */ -function generateParams(algo, bits, oid) { - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ - privateParams: { d, p, q, u }, - publicParams: { n, e } - })); - } - case enums.publicKey.ecdsa: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { d: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ - privateParams: { seed: secret }, - publicParams: { oid: new OID(oid), Q } - })); - case enums.publicKey.ecdh: - return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ - privateParams: { d: secret }, - publicParams: { - oid: new OID(oid), - Q, - kdfParams: new KDFParams({ hash, cipher }) - } - })); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ - privateParams: { seed }, - publicParams: { A } - })); - case enums.publicKey.x25519: - return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ - privateParams: { k }, - publicParams: { A } - })); - case enums.publicKey.dsa: - case enums.publicKey.elgamal: - throw new Error('Unsupported algorithm for key generation.'); - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Validate algorithm-specific key parameters - * @param {module:enums.publicKey} algo - The public key algorithm - * @param {Object} publicParams - Algorithm-specific public key parameters - * @param {Object} privateParams - Algorithm-specific private key parameters - * @returns {Promise} Whether the parameters are valid. - * @async - */ -async function validateParams$8(algo, publicParams, privateParams) { - if (!publicParams || !privateParams) { - throw new Error('Missing key parameters'); - } - switch (algo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: { - const { n, e } = publicParams; - const { d, p, q, u } = privateParams; - return publicKey.rsa.validateParams(n, e, d, p, q, u); - } - case enums.publicKey.dsa: { - const { p, q, g, y } = publicParams; - const { x } = privateParams; - return publicKey.dsa.validateParams(p, q, g, y, x); - } - case enums.publicKey.elgamal: { - const { p, g, y } = publicParams; - const { x } = privateParams; - return publicKey.elgamal.validateParams(p, g, y, x); - } - case enums.publicKey.ecdsa: - case enums.publicKey.ecdh: { - const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; - const { oid, Q } = publicParams; - const { d } = privateParams; - return algoModule.validateParams(oid, Q, d); - } - case enums.publicKey.eddsaLegacy: { - const { Q, oid } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); - } - case enums.publicKey.ed25519: { - const { A } = publicParams; - const { seed } = privateParams; - return publicKey.elliptic.eddsa.validateParams(algo, A, seed); - } - case enums.publicKey.x25519: { - const { A } = publicParams; - const { k } = privateParams; - return publicKey.elliptic.ecdhX.validateParams(algo, A, k); - } - default: - throw new Error('Unknown public key algorithm.'); - } -} - -/** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - * @async - */ -async function getPrefixRandom(algo) { - const { blockSize } = getCipher(algo); - const prefixrandom = await getRandomBytes(blockSize); - const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - return util.concat([prefixrandom, repeat]); -} - -/** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} algo - Symmetric encryption algorithm - * @returns {Uint8Array} Random bytes as a string to be used as a key. - */ -function generateSessionKey(algo) { - const { keySize } = getCipher(algo); - return getRandomBytes(keySize); -} - -/** - * Get implementation of the given AEAD mode - * @param {enums.aead} algo - * @returns {Object} - * @throws {Error} on invalid algo - */ -function getAEADMode(algo) { - const algoName = enums.read(enums.aead, algo); - return mode[algoName]; -} - -/** - * Check whether the given curve OID is supported - * @param {module:type/oid} oid - EC object identifier - * @throws {UnsupportedError} if curve is not supported - */ -function checkSupportedCurve(oid) { - try { - oid.getName(); - } catch (e) { - throw new UnsupportedError('Unknown curve OID'); - } -} - -/** - * Get preferred hash algo for a given elliptic algo - * @param {module:enums.publicKey} algo - alrogithm identifier - * @param {module:type/oid} [oid] - curve OID if needed by algo - */ -function getPreferredCurveHashAlgo(algo, oid) { - switch (algo) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - return publicKey.elliptic.getPreferredHashAlgo(oid); - case enums.publicKey.ed25519: - return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); - default: - throw new Error('Unknown elliptic signing algo'); - } -} - -var crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - publicKeyEncrypt: publicKeyEncrypt, - publicKeyDecrypt: publicKeyDecrypt, - parsePublicKeyParams: parsePublicKeyParams, - parsePrivateKeyParams: parsePrivateKeyParams, - parseEncSessionKeyParams: parseEncSessionKeyParams, - serializeParams: serializeParams, - generateParams: generateParams, - validateParams: validateParams$8, - getPrefixRandom: getPrefixRandom, - generateSessionKey: generateSessionKey, - getAEADMode: getAEADMode, - getCipher: getCipher, - getPreferredCurveHashAlgo: getPreferredCurveHashAlgo -}); - -/** - * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash - * @module crypto - * @private - */ - -// TODO move cfb and gcm to cipher -const mod = { - /** @see module:crypto/cipher */ - cipher: cipher, - /** @see module:crypto/hash */ - hash: hash, - /** @see module:crypto/mode */ - mode: mode, - /** @see module:crypto/public_key */ - publicKey: publicKey, - /** @see module:crypto/signature */ - signature: signature, - /** @see module:crypto/random */ - random: random, - /** @see module:crypto/pkcs1 */ - pkcs1: pkcs1, - /** @see module:crypto/pkcs5 */ - pkcs5: pkcs5, - /** @see module:crypto/aes_kw */ - aesKW: aesKW -}; - -Object.assign(mod, crypto$1); - -var TYPED_OK = typeof Uint8Array !== "undefined" && - typeof Uint16Array !== "undefined" && - typeof Int32Array !== "undefined"; - - -// reduce buffer size, avoiding mem copy -function shrinkBuf(buf, size) { - if (buf.length === size) { - return buf; - } - if (buf.subarray) { - return buf.subarray(0, size); - } - buf.length = size; - return buf; -} - - -const fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - let i, l, len, pos, chunk; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - const result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -const fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (let i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// - -let Buf8 = TYPED_OK ? Uint8Array : Array; -let Buf16 = TYPED_OK ? Uint16Array : Array; -let Buf32 = TYPED_OK ? Int32Array : Array; -let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks; -let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -/* Allowed flush values; see deflate() and inflate() below for details */ -const Z_NO_FLUSH = 0; -const Z_PARTIAL_FLUSH = 1; -const Z_SYNC_FLUSH = 2; -const Z_FULL_FLUSH = 3; -const Z_FINISH = 4; -const Z_BLOCK = 5; -const Z_TREES = 6; - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -const Z_OK = 0; -const Z_STREAM_END = 1; -const Z_NEED_DICT = 2; -const Z_STREAM_ERROR = -2; -const Z_DATA_ERROR = -3; -//export const Z_MEM_ERROR = -4; -const Z_BUF_ERROR = -5; -const Z_DEFAULT_COMPRESSION = -1; - - -const Z_FILTERED = 1; -const Z_HUFFMAN_ONLY = 2; -const Z_RLE = 3; -const Z_FIXED = 4; -const Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -const Z_BINARY = 0; -const Z_TEXT = 1; -//export const Z_ASCII = 1; // = Z_TEXT (deprecated) -const Z_UNKNOWN = 2; - -/* The deflate compression method */ -const Z_DEFLATED = 8; -//export const Z_NULL = null // Use -1 or null inline, depending on var type - -/*============================================================================*/ - - -function zero$1(buf) { - let len = buf.length; while (--len >= 0) { - buf[len] = 0; - } -} - -// From zutil.h - -const STORED_BLOCK = 0; -const STATIC_TREES = 1; -const DYN_TREES = 2; -/* The three kinds of block type */ - -const MIN_MATCH = 3; -const MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -const LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -const LITERALS = 256; -/* number of literal bytes 0..255 */ - -const L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -const D_CODES = 30; -/* number of distance codes */ - -const BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -const HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -const MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -const Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -const MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -const END_BLOCK = 256; -/* end of block literal code */ - -const REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -const REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -const REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -const extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -const extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -const extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -const bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -const static_ltree = new Array((L_CODES + 2) * 2); -zero$1(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -const static_dtree = new Array(D_CODES * 2); -zero$1(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -const _dist_code = new Array(DIST_CODE_LEN); -zero$1(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero$1(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -const base_length = new Array(LENGTH_CODES); -zero$1(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -const base_dist = new Array(D_CODES); -zero$1(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -let static_l_desc; -let static_d_desc; -let static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = w & 0xff; - s.pending_buf[s.pending++] = w >>> 8 & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > Buf_size - length) { - s.bi_buf |= value << s.bi_valid & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> Buf_size - s.bi_valid; - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= value << s.bi_valid & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - let res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const max_code = desc.max_code; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const extra = desc.stat_desc.extra_bits; - const base = desc.stat_desc.extra_base; - const max_length = desc.stat_desc.max_length; - let h; /* heap index */ - let n, m; /* iterate over the tree elements */ - let bits; /* bit length */ - let xbits; /* extra bits */ - let f; /* frequency */ - let overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { - continue; - } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { - return; - } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { - bits--; - } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { - continue; - } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - let code = 0; /* running code value */ - let bits; /* bit index */ - let n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = code + bl_count[bits - 1] << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < 1 << extra_lbits[code]; n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < 1 << extra_dbits[code]; n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - let n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { - s.dyn_ltree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < D_CODES; n++) { - s.dyn_dtree[n * 2]/*.Freq*/ = 0; - } - for (n = 0; n < BL_CODES; n++) { - s.bl_tree[n * 2]/*.Freq*/ = 0; - } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) { - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } - // while (len--) { - // put_byte(s, *buf++); - // } - arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - const _n2 = n * 2; - const _m2 = m * 2; - return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]; -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - const v = s.heap[k]; - let j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { - break; - } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - let dist; /* distance of matched string */ - let lc; /* match length or unmatched char (if dist == 0) */ - let lx = 0; /* running index in l_buf */ - let code; /* the code to send */ - let extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - const tree = desc.dyn_tree; - const stree = desc.stat_desc.static_tree; - const has_stree = desc.stat_desc.has_stree; - const elems = desc.stat_desc.elems; - let n, m; /* iterate over heap elements */ - let max_code = -1; /* largest code with non zero frequency */ - let node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) { - pqdownheap(s, tree, n); - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { - s.bl_tree[curlen * 2]/*.Freq*/++; - } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - let n; /* iterates over all tree elements */ - let prevlen = -1; /* last emitted length */ - let curlen; /* length of current code */ - - let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - let count = 0; /* repeat count of the current code */ - let max_count = 7; /* max repeat count */ - let min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { - send_code(s, curlen, s.bl_tree); - } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - let max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - let rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - let black_mask = 0xf3ffc07f; - let n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -let static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) { - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - let max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = s.opt_len + 3 + 7 >>> 3; - static_lenb = s.static_len + 3 + 7 >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { - opt_lenb = static_lenb; - } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if (stored_len + 4 <= opt_lenb && buf !== -1) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - - //#ifdef TRUNCATE_BLOCK - // /* Try to guess if it is profitable to stop the current block here */ - // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { - // /* Compute an upper bound for the compressed length */ - // out_length = s.last_lit*8; - // in_length = s.strstart - s.block_start; - // - // for (dcode = 0; dcode < D_CODES; dcode++) { - // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); - // } - // out_length >>>= 3; - // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - // // s->last_lit, in_length, out_length, - // // 100L - out_length*100L/in_length)); - // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { - // return true; - // } - // } - //#endif - - return s.last_lit === s.lit_bufsize - 1; - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function adler32(adler, buf, len, pos) { - let s1 = adler & 0xffff |0, - s2 = adler >>> 16 & 0xffff |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = s1 + buf[pos++] |0; - s2 = s2 + s1 |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return s1 | s2 << 16 |0; -} - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - let c; - const table = []; - - for (let n = 0; n < 256; n++) { - c = n; - for (let k = 0; k < 8; k++) { - c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -const crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - const t = crcTable, - end = pos + len; - - crc ^= -1; - - for (let i = pos; i < end; i++) { - crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return crc ^ -1; // >>> 0; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var msg = { - 2: "need dictionary", /* Z_NEED_DICT 2 */ - 1: "stream end", /* Z_STREAM_END 1 */ - 0: "", /* Z_OK 0 */ - "-1": "file error", /* Z_ERRNO (-1) */ - "-2": "stream error", /* Z_STREAM_ERROR (-2) */ - "-3": "data error", /* Z_DATA_ERROR (-3) */ - "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */ - "-5": "buffer error", /* Z_BUF_ERROR (-5) */ - "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */ -}; - -/*============================================================================*/ - - -const MAX_MEM_LEVEL = 9; - - -const LENGTH_CODES$1 = 29; -/* number of length codes, not counting the special END_BLOCK code */ -const LITERALS$1 = 256; -/* number of literal bytes 0..255 */ -const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; -/* number of Literal or Length codes, including the END_BLOCK code */ -const D_CODES$1 = 30; -/* number of distance codes */ -const BL_CODES$1 = 19; -/* number of codes used to transfer the bit lengths */ -const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; -/* maximum heap size */ -const MAX_BITS$1 = 15; -/* All codes must not exceed MAX_BITS bits */ - -const MIN_MATCH$1 = 3; -const MAX_MATCH$1 = 258; -const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); - -const PRESET_DICT = 0x20; - -const INIT_STATE = 42; -const EXTRA_STATE = 69; -const NAME_STATE = 73; -const COMMENT_STATE = 91; -const HCRC_STATE = 103; -const BUSY_STATE = 113; -const FINISH_STATE = 666; - -const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -const BS_BLOCK_DONE = 2; /* block flush performed */ -const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - const s = strm.state; - - //_tr_flush_bits(s); - let len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { - // put_byte(s, (Byte)(b >> 8)); - // put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - let len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - let chain_length = s.max_chain_length; /* max hash chain length */ - let scan = s.strstart; /* current string */ - let match; /* matched string */ - let len; /* length of current match */ - let best_len = s.prev_length; /* best match length so far */ - let nice_match = s.nice_match; /* stop if match long enough */ - const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - const _win = s.window; // shortcut - - const wmask = s.w_mask; - const prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - const strend = s.strstart + MAX_MATCH$1; - let scan_end1 = _win[scan + best_len - 1]; - let scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH$1 - (strend - scan); - scan = strend - MAX_MATCH$1; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - const _w_size = s.w_size; - let p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH$1) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; - //#if MIN_MATCH != 3 - // Call update_hash() MIN_MATCH-3 more times - //#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH$1) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ - // if (s.high_water < s.window_size) { - // var curr = s.strstart + s.lookahead; - // var init = 0; - // - // if (s.high_water < curr) { - // /* Previous high water mark below current data -- zero WIN_INIT - // * bytes or up to end of window, whichever is less. - // */ - // init = s.window_size - curr; - // if (init > WIN_INIT) - // init = WIN_INIT; - // zmemzero(s->window + curr, (unsigned)init); - // s->high_water = curr + init; - // } - // else if (s->high_water < (ulg)curr + WIN_INIT) { - // /* High water mark at or above current data, but below current data - // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up - // * to end of window, whichever is less. - // */ - // init = (ulg)curr + WIN_INIT - s->high_water; - // if (init > s->window_size - s->high_water) - // init = s->window_size - s->high_water; - // zmemzero(s->window + s->high_water, (unsigned)init); - // s->high_water += init; - // } - // } - // - // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, - // "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - let max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (; ;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); - // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || - // s.block_start >= s.w_size)) { - // throw new Error("slide too late"); - // } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); - // if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - const max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - let hash_head; /* head of the hash chain */ - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH$1) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - - //#if MIN_MATCH != 3 - // Call UPDATE_HASH() MIN_MATCH-3 more times - //#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - let hash_head; /* head of hash chain */ - let bflush; /* set if current block must be flushed */ - - let max_insert; - - /* Process the input block. */ - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH$1) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH$1 - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH$1 - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH$1; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH$1 - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - let bflush; /* set if current block must be flushed */ - let prev; /* byte at distance one to match */ - let scan, strend; /* scan goes up to strend for length of run */ - - const _win = s.window; - - for (; ;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH$1) { - fill_window(s); - if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH$1; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH$1 - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH$1) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - let bflush; /* set if current block must be flushed */ - - for (; ;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = _tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -class Config { - constructor(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; - } -} -const configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - s.ins_h = 0; -} - -class DeflateState { - constructor() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); - this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); - this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); - zero$2(this.dyn_ltree); - zero$2(this.dyn_dtree); - zero$2(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new Buf16(MAX_BITS$1 + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ - zero$2(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; - zero$2(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ - } -} - -function deflateResetKeep(strm) { - let s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - _tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - const ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - let wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - const s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); - s.window = new Buf8(s.w_size * 2); - s.head = new Buf16(s.hash_size); - s.prev = new Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - - -function deflate(strm, flush) { - let old_flush, s; - let beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - let level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - - //#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } - //#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - _tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - _tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero$2(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - let status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - let dictLength = dictionary.length; - - let s; - let str, n; - let wrap; - let avail; - let next; - let input; - let tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero$2(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new Buf8(s.w_size); - arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH$1) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH$1 - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH$1 - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH$1 - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - -// String encode/decode helpers - -try { - String.fromCharCode.apply(null, [ 0 ]); -} catch (__) { -} -try { - String.fromCharCode.apply(null, new Uint8Array(1)); -} catch (__) { -} - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -const _utf8len = new Buf8(256); -for (let q = 0; q < 256; q++) { - _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - -// convert string to array (typed, when possible) -function string2buf (str) { - let c, c2, m_pos, i, buf_len = 0; - const str_len = str.length; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - const buf = new Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | c >>> 6; - buf[i++] = 0x80 | c & 0x3f; - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | c >>> 12; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } else { - /* four bytes */ - buf[i++] = 0xf0 | c >>> 18; - buf[i++] = 0x80 | c >>> 12 & 0x3f; - buf[i++] = 0x80 | c >>> 6 & 0x3f; - buf[i++] = 0x80 | c & 0x3f; - } - } - - return buf; -} - - -// Convert binary string (typed, when possible) -function binstring2buf (str) { - const buf = new Buf8(str.length); - for (let i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class ZStream { - constructor() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; - } -} - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ - -class Deflate { - constructor(options) { - this.options = { - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - ...(options || {}) - }; - - const opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - let dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } - } - - /** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize } } = this; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = string2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - /** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - /** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -const BAD = 30; /* got a data error -- remain here until reset */ -const TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -function inflate_fast(strm, start) { - let _in; /* local strm.input */ - let _out; /* local strm.output */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - let hold; /* local strm.hold */ - let bits; /* local strm.bits */ - let here; /* retrieved table entry */ - let op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - let len; /* match length, unused bytes */ - let dist; /* match distance */ - let from; /* where to copy match from */ - let from_source; - - - - /* copy state to local variables */ - const state = strm.state; - //here = state.here; - _in = strm.next_in; - const input = strm.input; - const last = _in + (strm.avail_in - 5); - _out = strm.next_out; - const output = strm.output; - const beg = _out - (start - strm.avail_out); - const end = _out + (strm.avail_out - 257); - //#ifdef INFLATE_STRICT - const dmax = state.dmax; - //#endif - const wsize = state.wsize; - const whave = state.whave; - const wnext = state.wnext; - const s_window = state.window; - hold = state.hold; - bits = state.bits; - const lcode = state.lencode; - const dcode = state.distcode; - const lmask = (1 << state.lenbits) - 1; - const dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & (1 << op) - 1; - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = here >>> 16 & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & (1 << op) - 1; - //#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - //#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = "invalid distance too far back"; - state.mode = BAD; - break top; - } - - // (!) This block is disabled in zlib defaults, - // don't enable it for binary compatibility - //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR - // if (len <= op - whave) { - // do { - // output[_out++] = 0; - // } while (--len); - // continue top; - // } - // len -= op - whave; - // do { - // output[_out++] = 0; - // } while (--op > whave); - // if (op === 0) { - // from = _out - dist; - // do { - // output[_out++] = output[from++]; - // } while (--len); - // continue top; - // } - //#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dodist; - } else { - strm.msg = "invalid distance code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)]; - continue dolen; - } else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } else { - strm.msg = "invalid literal/length code"; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); - strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); - state.hold = hold; - state.bits = bits; - return; -} - -const MAXBITS = 15; -const ENOUGH_LENS = 852; -const ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -const CODES = 0; -const LENS = 1; -const DISTS = 2; - -const lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -const lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -const dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -const dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { - const bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - let len = 0; /* a code's length in bits */ - let sym = 0; /* index of code symbols */ - let min = 0, max = 0; /* minimum and maximum code lengths */ - let root = 0; /* number of index bits for root table */ - let curr = 0; /* number of index bits for current table */ - let drop = 0; /* code bits to drop for sub-table */ - let left = 0; /* number of prefix codes available */ - let used = 0; /* code entries in table used */ - let huff = 0; /* Huffman code */ - let incr; /* for incrementing code, index */ - let fill; /* index for replicating entries */ - let low; /* low bits for current root entry */ - let next; /* next available space in table */ - let base = null; /* base value table to use */ - let base_index = 0; - // var shoextra; /* extra bits table to use */ - let end; /* use base and extra for symbol > end */ - const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - let extra = null; - let extra_index = 0; - - let here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { - break; - } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = 1 << 24 | 64 << 16 | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { - break; - } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - const mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << len - drop; - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << len - 1; - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { - break; - } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { - break; - } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if (type === LENS && used > ENOUGH_LENS || - type === DISTS && used > ENOUGH_DISTS) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = root << 24 | curr << 16 | next - table_index |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = len - drop << 24 | 64 << 16 |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -} - -const CODES$1 = 0; -const LENS$1 = 1; -const DISTS$1 = 2; - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -const HEAD = 1; /* i: waiting for magic header */ -const FLAGS = 2; /* i: waiting for method and flags (gzip) */ -const TIME = 3; /* i: waiting for modification time (gzip) */ -const OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -const EXLEN = 5; /* i: waiting for extra length (gzip) */ -const EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -const NAME = 7; /* i: waiting for end of file name (gzip) */ -const COMMENT = 8; /* i: waiting for end of comment (gzip) */ -const HCRC = 9; /* i: waiting for header crc (gzip) */ -const DICTID = 10; /* i: waiting for dictionary check value */ -const DICT = 11; /* waiting for inflateSetDictionary() call */ -const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ -const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -const STORED = 14; /* i: waiting for stored size (length and complement) */ -const COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -const COPY = 16; /* i/o: waiting for input or output to copy stored block */ -const TABLE = 17; /* i: waiting for dynamic block table lengths */ -const LENLENS = 18; /* i: waiting for code length code lengths */ -const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -const LEN_ = 20; /* i: same as LEN below, but only first time in */ -const LEN = 21; /* i: waiting for length/lit/eob code */ -const LENEXT = 22; /* i: waiting for length extra bits */ -const DIST = 23; /* i: waiting for distance code */ -const DISTEXT = 24; /* i: waiting for distance extra bits */ -const MATCH = 25; /* o: waiting for output space to copy string */ -const LIT = 26; /* o: waiting for output space to write literal */ -const CHECK = 27; /* i: waiting for 32-bit check value */ -const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -const DONE = 29; /* finished check, done -- remain here until reset */ -const BAD$1 = 30; /* got a data error -- remain here until reset */ -//const MEM = 31; /* got an inflate() memory error -- remain here until reset */ -const SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -const ENOUGH_LENS$1 = 852; -const ENOUGH_DISTS$1 = 592; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -class InflateState { - constructor() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new Buf16(320); /* temporary storage for code lengths */ - this.work = new Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ - } -} - -function inflateResetKeep(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); - state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - let state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - let wrap; - let state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - let ret; - let state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -let virgin = true; - -let lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - let sym; - - lenfix = new Buf32(512); - distfix = new Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - let dist; - const state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - let state; - let input, output; // input/output buffers - let next; /* next input INDEX */ - let put; /* next output INDEX */ - let have, left; /* available input and output */ - let hold; /* bit buffer */ - let bits; /* bits in bit buffer */ - let _in, _out; /* save starting available input and output */ - let copy; /* number of stored or match bytes to copy */ - let from; /* where to copy match bytes from */ - let from_source; - let here = 0; /* current decoding table entry */ - let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - let len; /* length to copy for repeats, bits to drop */ - let ret; /* return code */ - let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ - let opts; - - let n; // temporary var for NEED_BITS - - const order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD$1; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD$1; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE$1; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD$1; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD$1; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE$1; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE$1; - /* falls through */ - case TYPE$1: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD$1; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD$1; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE$1; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD$1; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD$1; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD$1) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD$1; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD$1; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD$1; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE$1) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE$1; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD$1; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD$1; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD$1; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD$1; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD$1: - ret = Z_DATA_ERROR; - break inf_leave; - // case MEM: - // return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE$1 ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - const state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - let state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - const dictLength = dictionary.length; - - let state; - let dictid; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - updatewindow(strm, dictionary, dictLength, dictLength); - // if (ret) { - // state.mode = MEM; - // return Z_MEM_ERROR; - // } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -class GZheader { - constructor() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; - } -} - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overridden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = void('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -class Inflate { - constructor(options) { - this.options = { - chunkSize: 16384, - windowBits: 0, - ...(options || {}) - }; - - const opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - let status = inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - inflateGetHeader(this.strm, this.header); - - // Setup dictionary - if (opt.dictionary) { - // Convert data if needed - if (typeof opt.dictionary === 'string') { - opt.dictionary = string2buf(opt.dictionary); - } else if (opt.dictionary instanceof ArrayBuffer) { - opt.dictionary = new Uint8Array(opt.dictionary); - } - if (opt.raw) { //In raw mode we need to set the dictionary early - status = inflateSetDictionary(this.strm, opt.dictionary); - if (status !== Z_OK) { - throw new Error(msg[status]); - } - } - } - } - /** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ - push(data, mode) { - const { strm, options: { chunkSize, dictionary } } = this; - let status, _mode; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - let allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = binstring2buf(data); - } else if (data instanceof ArrayBuffer) { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = inflate(strm, Z_NO_FLUSH); /* no bad return value */ - - if (status === Z_NEED_DICT && dictionary) { - status = inflateSetDictionary(this.strm, dictionary); - } - - if (status === Z_BUF_ERROR && allowBufError === true) { - status = Z_OK; - allowBufError = false; - } - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - this.onData(shrinkBuf(strm.output, strm.next_out)); - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - if (status === Z_STREAM_END) { - _mode = Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; - }; - - /** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): output data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ - onData(chunk) { - this.chunks.push(chunk); - }; - - - - /** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ - onEnd(status) { - // On success - join - if (status === Z_OK) { - this.result = flattenChunks(this.chunks); - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; - }; -} - -/* -node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - -Copyright (C) 2012 Eli Skeggs - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - -var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; - -// offset in bytes -var BitReader = function(stream) { - this.stream = stream; - this.bitOffset = 0; - this.curByte = 0; - this.hasByte = false; -}; - -BitReader.prototype._ensureByte = function() { - if (!this.hasByte) { - this.curByte = this.stream.readByte(); - this.hasByte = true; - } -}; - -// reads bits from the buffer -BitReader.prototype.read = function(bits) { - var result = 0; - while (bits > 0) { - this._ensureByte(); - var remaining = 8 - this.bitOffset; - // if we're in a byte - if (bits >= remaining) { - result <<= remaining; - result |= BITMASK[remaining] & this.curByte; - this.hasByte = false; - this.bitOffset = 0; - bits -= remaining; - } else { - result <<= bits; - var shift = remaining - bits; - result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; - this.bitOffset += bits; - bits = 0; - } - } - return result; -}; - -// seek to an arbitrary point in the buffer (expressed in bits) -BitReader.prototype.seek = function(pos) { - var n_bit = pos % 8; - var n_byte = (pos - n_bit) / 8; - this.bitOffset = n_bit; - this.stream.seek(n_byte); - this.hasByte = false; -}; - -// reads 6 bytes worth of data using the read method -BitReader.prototype.pi = function() { - var buf = new Uint8Array(6), i; - for (i = 0; i < buf.length; i++) { - buf[i] = this.read(8); - } - return bufToHex(buf); -}; - -function bufToHex(buf) { - return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); -} - -var bitreader = BitReader; - -/* very simple input/output stream interface */ -var Stream = function() { -}; - -// input streams ////////////// -/** Returns the next byte, or -1 for EOF. */ -Stream.prototype.readByte = function() { - throw new Error("abstract method readByte() not implemented"); -}; -/** Attempts to fill the buffer; returns number of bytes read, or - * -1 for EOF. */ -Stream.prototype.read = function(buffer, bufOffset, length) { - var bytesRead = 0; - while (bytesRead < length) { - var c = this.readByte(); - if (c < 0) { // EOF - return (bytesRead===0) ? -1 : bytesRead; - } - buffer[bufOffset++] = c; - bytesRead++; - } - return bytesRead; -}; -Stream.prototype.seek = function(new_pos) { - throw new Error("abstract method seek() not implemented"); -}; - -// output streams /////////// -Stream.prototype.writeByte = function(_byte) { - throw new Error("abstract method readByte() not implemented"); -}; -Stream.prototype.write = function(buffer, bufOffset, length) { - var i; - for (i=0; i>> 0; // return an unsigned value - }; - - /** - * Update the CRC with a single byte - * @param value The value to update the CRC with - */ - this.updateCRC = function(value) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - }; - - /** - * Update the CRC with a sequence of identical bytes - * @param value The value to update the CRC with - * @param count The number of bytes - */ - this.updateCRCRun = function(value, count) { - while (count-- > 0) { - crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; - } - }; - }; - return CRC32; -})(); - -/* -seek-bzip - a pure-javascript module for seeking within bzip2 data - -Copyright (C) 2013 C. Scott Ananian -Copyright (C) 2012 Eli Skeggs -Copyright (C) 2011 Kevin Kwok - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, see -http://www.gnu.org/licenses/lgpl-2.1.html - -Adapted from node-bzip, copyright 2012 Eli Skeggs. -Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). - -Based on micro-bunzip by Rob Landley (rob@landley.net). - -Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), -which also acknowledges contributions by Mike Burrows, David Wheeler, -Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, -Robert Sedgewick, and Jon L. Bentley. -*/ - - - - - -var MAX_HUFCODE_BITS = 20; -var MAX_SYMBOLS = 258; -var SYMBOL_RUNA = 0; -var SYMBOL_RUNB = 1; -var MIN_GROUPS = 2; -var MAX_GROUPS = 6; -var GROUP_SIZE = 50; - -var WHOLEPI = "314159265359"; -var SQRTPI = "177245385090"; - -var mtf = function(array, index) { - var src = array[index], i; - for (i = index; i > 0; i--) { - array[i] = array[i-1]; - } - array[0] = src; - return src; -}; - -var Err = { - OK: 0, - LAST_BLOCK: -1, - NOT_BZIP_DATA: -2, - UNEXPECTED_INPUT_EOF: -3, - UNEXPECTED_OUTPUT_EOF: -4, - DATA_ERROR: -5, - OUT_OF_MEMORY: -6, - OBSOLETE_INPUT: -7, - END_OF_BLOCK: -8 -}; -var ErrorMessages = {}; -ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; -ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; -ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; -ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; -ErrorMessages[Err.DATA_ERROR] = "Data error"; -ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; -ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - -var _throw = function(status, optDetail) { - var msg = ErrorMessages[status] || 'unknown error'; - if (optDetail) { msg += ': '+optDetail; } - var e = new TypeError(msg); - e.errorCode = status; - throw e; -}; - -var Bunzip = function(inputStream, outputStream) { - this.writePos = this.writeCurrent = this.writeCount = 0; - - this._start_bunzip(inputStream, outputStream); -}; -Bunzip.prototype._init_block = function() { - var moreBlocks = this._get_next_block(); - if ( !moreBlocks ) { - this.writeCount = -1; - return false; /* no more blocks */ - } - this.blockCRC = new crc32$1(); - return true; -}; -/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ -Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { - /* Ensure that file starts with "BZh['1'-'9']." */ - var buf = new Uint8Array(4); - if (inputStream.read(buf, 0, 4) !== 4 || - String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') - _throw(Err.NOT_BZIP_DATA, 'bad magic'); - - var level = buf[3] - 0x30; - if (level < 1 || level > 9) - _throw(Err.NOT_BZIP_DATA, 'level out of range'); - - this.reader = new bitreader(inputStream); - - /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of - uncompressed data. Allocate intermediate buffer for block. */ - this.dbufSize = 100000 * level; - this.nextoutput = 0; - this.outputStream = outputStream; - this.streamCRC = 0; -}; -Bunzip.prototype._get_next_block = function() { - var i, j, k; - var reader = this.reader; - // this is get_next_block() function from micro-bunzip: - /* Read in header signature and CRC, then validate signature. - (last block signature means CRC is for whole file, return now) */ - var h = reader.pi(); - if (h === SQRTPI) { // last block - return false; /* no more blocks */ - } - if (h !== WHOLEPI) - _throw(Err.NOT_BZIP_DATA); - this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) - this.streamCRC = (this.targetBlockCRC ^ - ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; - /* We can add support for blockRandomised if anybody complains. There was - some code for this in busybox 1.0.0-pre3, but nobody ever noticed that - it didn't actually work. */ - if (reader.read(1)) - _throw(Err.OBSOLETE_INPUT); - var origPointer = reader.read(24); - if (origPointer > this.dbufSize) - _throw(Err.DATA_ERROR, 'initial position out of bounds'); - /* mapping table: if some byte values are never used (encoding things - like ascii text), the compression code removes the gaps to have fewer - symbols to deal with, and writes a sparse bitfield indicating which - values were present. We make a translation table to convert the symbols - back to the corresponding bytes. */ - var t = reader.read(16); - var symToByte = new Uint8Array(256), symTotal = 0; - for (i = 0; i < 16; i++) { - if (t & (1 << (0xF - i))) { - var o = i * 16; - k = reader.read(16); - for (j = 0; j < 16; j++) - if (k & (1 << (0xF - j))) - symToByte[symTotal++] = o + j; - } - } - - /* How many different huffman coding groups does this block use? */ - var groupCount = reader.read(3); - if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) - _throw(Err.DATA_ERROR); - /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding - group. Read in the group selector list, which is stored as MTF encoded - bit runs. (MTF=Move To Front, as each value is used it's moved to the - start of the list.) */ - var nSelectors = reader.read(15); - if (nSelectors === 0) - _throw(Err.DATA_ERROR); - - var mtfSymbol = new Uint8Array(256); - for (i = 0; i < groupCount; i++) - mtfSymbol[i] = i; - - var selectors = new Uint8Array(nSelectors); // was 32768... - - for (i = 0; i < nSelectors; i++) { - /* Get next value */ - for (j = 0; reader.read(1); j++) - if (j >= groupCount) _throw(Err.DATA_ERROR); - /* Decode MTF to get the next selector */ - selectors[i] = mtf(mtfSymbol, j); - } - - /* Read the huffman coding tables for each group, which code for symTotal - literal symbols, plus two run symbols (RUNA, RUNB) */ - var symCount = symTotal + 2; - var groups = [], hufGroup; - for (j = 0; j < groupCount; j++) { - var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); - /* Read huffman code lengths for each symbol. They're stored in - a way similar to mtf; record a starting value for the first symbol, - and an offset from the previous value for everys symbol after that. */ - t = reader.read(5); // lengths - for (i = 0; i < symCount; i++) { - for (;;) { - if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); - /* If first bit is 0, stop. Else second bit indicates whether - to increment or decrement the value. */ - if(!reader.read(1)) - break; - if(!reader.read(1)) - t++; - else - t--; - } - length[i] = t; - } - - /* Find largest and smallest lengths in this group */ - var minLen, maxLen; - minLen = maxLen = length[0]; - for (i = 1; i < symCount; i++) { - if (length[i] > maxLen) - maxLen = length[i]; - else if (length[i] < minLen) - minLen = length[i]; - } - - /* Calculate permute[], base[], and limit[] tables from length[]. - * - * permute[] is the lookup table for converting huffman coded symbols - * into decoded symbols. base[] is the amount to subtract from the - * value of a huffman symbol of a given length when using permute[]. - * - * limit[] indicates the largest numerical value a symbol with a given - * number of bits can have. This is how the huffman codes can vary in - * length: each code with a value>limit[length] needs another bit. - */ - hufGroup = {}; - groups.push(hufGroup); - hufGroup.permute = new Uint16Array(MAX_SYMBOLS); - hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); - hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); - hufGroup.minLen = minLen; - hufGroup.maxLen = maxLen; - /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ - var pp = 0; - for (i = minLen; i <= maxLen; i++) { - temp[i] = hufGroup.limit[i] = 0; - for (t = 0; t < symCount; t++) - if (length[t] === i) - hufGroup.permute[pp++] = t; - } - /* Count symbols coded for at each bit length */ - for (i = 0; i < symCount; i++) - temp[length[i]]++; - /* Calculate limit[] (the largest symbol-coding value at each bit - * length, which is (previous limit<<1)+symbols at this level), and - * base[] (number of symbols to ignore at each bit length, which is - * limit minus the cumulative count of symbols coded for already). */ - pp = t = 0; - for (i = minLen; i < maxLen; i++) { - pp += temp[i]; - /* We read the largest possible symbol size and then unget bits - after determining how many we need, and those extra bits could - be set to anything. (They're noise from future symbols.) At - each level we're really only interested in the first few bits, - so here we set all the trailing to-be-ignored bits to 1 so they - don't affect the value>limit[length] comparison. */ - hufGroup.limit[i] = pp - 1; - pp <<= 1; - t += temp[i]; - hufGroup.base[i + 1] = pp - t; - } - hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ - hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; - hufGroup.base[minLen] = 0; - } - /* We've finished reading and digesting the block header. Now read this - block's huffman coded symbols from the file and undo the huffman coding - and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - - /* Initialize symbol occurrence counters and symbol Move To Front table */ - var byteCount = new Uint32Array(256); - for (i = 0; i < 256; i++) - mtfSymbol[i] = i; - /* Loop through compressed symbols. */ - var runPos = 0, dbufCount = 0, selector = 0, uc; - var dbuf = this.dbuf = new Uint32Array(this.dbufSize); - symCount = 0; - for (;;) { - /* Determine which huffman coding group to use. */ - if (!(symCount--)) { - symCount = GROUP_SIZE - 1; - if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } - hufGroup = groups[selectors[selector++]]; - } - /* Read next huffman-coded symbol. */ - i = hufGroup.minLen; - j = reader.read(i); - for (;;i++) { - if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } - if (j <= hufGroup.limit[i]) - break; - j = (j << 1) | reader.read(1); - } - /* Huffman decode value to get nextSym (with bounds checking) */ - j -= hufGroup.base[i]; - if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } - var nextSym = hufGroup.permute[j]; - /* We have now decoded the symbol, which indicates either a new literal - byte, or a repeated run of the most recent literal byte. First, - check if nextSym indicates a repeated run, and if so loop collecting - how many times to repeat the last literal. */ - if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { - /* If this is the start of a new run, zero out counter */ - if (!runPos){ - runPos = 1; - t = 0; - } - /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at - each bit position, add 1 or 2 instead. For example, - 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. - You can make any bit pattern that way using 1 less symbol than - the basic or 0/1 method (except all bits 0, which would use no - symbols, but a run of length 0 doesn't mean anything in this - context). Thus space is saved. */ - if (nextSym === SYMBOL_RUNA) - t += runPos; - else - t += 2 * runPos; - runPos <<= 1; - continue; - } - /* When we hit the first non-run symbol after a run, we now know - how many times to repeat the last literal, so append that many - copies to our buffer of decoded symbols (dbuf) now. (The last - literal used is the one at the head of the mtfSymbol array.) */ - if (runPos){ - runPos = 0; - if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } - uc = symToByte[mtfSymbol[0]]; - byteCount[uc] += t; - while (t--) - dbuf[dbufCount++] = uc; - } - /* Is this the terminating symbol? */ - if (nextSym > symTotal) - break; - /* At this point, nextSym indicates a new literal character. Subtract - one to get the position in the MTF array at which this literal is - currently to be found. (Note that the result can't be -1 or 0, - because 0 and 1 are RUNA and RUNB. But another instance of the - first symbol in the mtf array, position 0, would have been handled - as part of a run above. Therefore 1 unused mtf position minus - 2 non-literal nextSym values equals -1.) */ - if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } - i = nextSym - 1; - uc = mtf(mtfSymbol, i); - uc = symToByte[uc]; - /* We have our literal byte. Save it into dbuf. */ - byteCount[uc]++; - dbuf[dbufCount++] = uc; - } - /* At this point, we've read all the huffman-coded symbols (and repeated - runs) for this block from the input stream, and decoded them into the - intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. - Now undo the Burrows-Wheeler transform on dbuf. - See http://dogma.net/markn/articles/bwt/bwt.htm - */ - if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } - /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ - j = 0; - for (i = 0; i < 256; i++) { - k = j + byteCount[i]; - byteCount[i] = j; - j = k; - } - /* Figure out what order dbuf would be in if we sorted it. */ - for (i = 0; i < dbufCount; i++) { - uc = dbuf[i] & 0xff; - dbuf[byteCount[uc]] |= (i << 8); - byteCount[uc]++; - } - /* Decode first byte by hand to initialize "previous" byte. Note that it - doesn't get output, and if the first three characters are identical - it doesn't qualify as a run (hence writeRunCountdown=5). */ - var pos = 0, current = 0, run = 0; - if (dbufCount) { - pos = dbuf[origPointer]; - current = (pos & 0xff); - pos >>= 8; - run = -1; - } - this.writePos = pos; - this.writeCurrent = current; - this.writeCount = dbufCount; - this.writeRun = run; - - return true; /* more blocks to come */ -}; -/* Undo burrows-wheeler transform on intermediate buffer to produce output. - If start_bunzip was initialized with out_fd=-1, then up to len bytes of - data are written to outbuf. Return value is number of bytes written or - error (all errors are negative numbers). If out_fd!=-1, outbuf and len - are ignored, data is written to out_fd and return is RETVAL_OK or error. -*/ -Bunzip.prototype._read_bunzip = function(outputBuffer, len) { - var copies, previous, outbyte; - /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully - decoded, which results in this returning RETVAL_LAST_BLOCK, also - equal to -1... Confusing, I'm returning 0 here to indicate no - bytes written into the buffer */ - if (this.writeCount < 0) { return 0; } - var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; - var dbufCount = this.writeCount; this.outputsize; - var run = this.writeRun; - - while (dbufCount) { - dbufCount--; - previous = current; - pos = dbuf[pos]; - current = pos & 0xff; - pos >>= 8; - if (run++ === 3){ - copies = current; - outbyte = previous; - current = -1; - } else { - copies = 1; - outbyte = current; - } - this.blockCRC.updateCRCRun(outbyte, copies); - while (copies--) { - this.outputStream.writeByte(outbyte); - this.nextoutput++; - } - if (current != previous) - run = 0; - } - this.writeCount = dbufCount; - // check CRC - if (this.blockCRC.getCRC() !== this.targetBlockCRC) { - _throw(Err.DATA_ERROR, "Bad block CRC "+ - "(got "+this.blockCRC.getCRC().toString(16)+ - " expected "+this.targetBlockCRC.toString(16)+")"); - } - return this.nextoutput; -}; - -var coerceInputStream = function(input) { - if ('readByte' in input) { return input; } - var inputStream = new stream(); - inputStream.pos = 0; - inputStream.readByte = function() { return input[this.pos++]; }; - inputStream.seek = function(pos) { this.pos = pos; }; - inputStream.eof = function() { return this.pos >= input.length; }; - return inputStream; -}; -var coerceOutputStream = function(output) { - var outputStream = new stream(); - var resizeOk = true; - if (output) { - if (typeof(output)==='number') { - outputStream.buffer = new Uint8Array(output); - resizeOk = false; - } else if ('writeByte' in output) { - return output; - } else { - outputStream.buffer = output; - resizeOk = false; - } - } else { - outputStream.buffer = new Uint8Array(16384); - } - outputStream.pos = 0; - outputStream.writeByte = function(_byte) { - if (resizeOk && this.pos >= this.buffer.length) { - var newBuffer = new Uint8Array(this.buffer.length*2); - newBuffer.set(this.buffer); - this.buffer = newBuffer; - } - this.buffer[this.pos++] = _byte; - }; - outputStream.getBuffer = function() { - // trim buffer - if (this.pos !== this.buffer.length) { - if (!resizeOk) - throw new TypeError('outputsize does not match decoded input'); - var newBuffer = new Uint8Array(this.pos); - newBuffer.set(this.buffer.subarray(0, this.pos)); - this.buffer = newBuffer; - } - return this.buffer; - }; - outputStream._coerced = true; - return outputStream; -}; - -/* Static helper functions */ -// 'input' can be a stream or a buffer -// 'output' can be a stream or a buffer or a number (buffer size) -const decode$2 = function(input, output, multistream) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - - var bz = new Bunzip(inputStream, outputStream); - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - if (bz._init_block()) { - bz._read_bunzip(); - } else { - var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) - if (targetStreamCRC !== bz.streamCRC) { - _throw(Err.DATA_ERROR, "Bad stream CRC "+ - "(got "+bz.streamCRC.toString(16)+ - " expected "+targetStreamCRC.toString(16)+")"); - } - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - } else break; - } - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -const decodeBlock = function(input, pos, output) { - // make a stream from a buffer, if necessary - var inputStream = coerceInputStream(input); - var outputStream = coerceOutputStream(output); - var bz = new Bunzip(inputStream, outputStream); - bz.reader.seek(pos); - /* Fill the decode buffer for the block */ - var moreBlocks = bz._get_next_block(); - if (moreBlocks) { - /* Init the CRC for writing */ - bz.blockCRC = new crc32$1(); - - /* Zero this so the current byte from before the seek is not written */ - bz.writeCopies = 0; - - /* Decompress the block and write to stdout */ - bz._read_bunzip(); - // XXX keep writing? - } - if ('getBuffer' in outputStream) - return outputStream.getBuffer(); -}; -/* Reads bzip2 file from stream or buffer `input`, and invoke - * `callback(position, size)` once for each bzip2 block, - * where position gives the starting position (in *bits*) - * and size gives uncompressed size of the block (in *bytes*). */ -const table = function(input, callback, multistream) { - // make a stream from a buffer, if necessary - var inputStream = new stream(); - inputStream.delegate = coerceInputStream(input); - inputStream.pos = 0; - inputStream.readByte = function() { - this.pos++; - return this.delegate.readByte(); - }; - if (inputStream.delegate.eof) { - inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); - } - var outputStream = new stream(); - outputStream.pos = 0; - outputStream.writeByte = function() { this.pos++; }; - - var bz = new Bunzip(inputStream, outputStream); - var blockSize = bz.dbufSize; - while (true) { - if ('eof' in inputStream && inputStream.eof()) break; - - var position = inputStream.pos*8 + bz.reader.bitOffset; - if (bz.reader.hasByte) { position -= 8; } - - if (bz._init_block()) { - var start = outputStream.pos; - bz._read_bunzip(); - callback(position, outputStream.pos - start); - } else { - bz.reader.read(32); // (but we ignore the crc) - if (multistream && - 'eof' in inputStream && - !inputStream.eof()) { - // note that start_bunzip will also resync the bit reader to next byte - bz._start_bunzip(inputStream, outputStream); - console.assert(bz.dbufSize === blockSize, - "shouldn't change block size within multistream file"); - } else break; - } - } -}; - -var lib = { - Bunzip, - Stream: stream, - Err, - decode: decode$2, - decodeBlock, - table -}; -var lib_4 = lib.decode; - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the Literal Data Packet (Tag 11) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - */ -class LiteralDataPacket { - static get tag() { - return enums.packet.literalData; - } - - /** - * @param {Date} date - The creation date of the literal package - */ - constructor(date = new Date()) { - this.format = enums.literal.utf8; // default format for literal data packets - this.date = util.normalizeDate(date); - this.text = null; // textual data representation - this.data = null; // literal data representation - this.filename = ''; - } - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param {String | ReadableStream} text - Any native javascript string - * @param {enums.literal} [format] - The format of the string of bytes - */ - setText(text, format = enums.literal.utf8) { - this.format = format; - this.text = text; - this.data = null; - } - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {String | ReadableStream} Literal data as text. - */ - getText(clone = false) { - if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read - this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); - } - return this.text; - } - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param {Uint8Array | ReadableStream} bytes - The string of bytes - * @param {enums.literal} format - The format of the string of bytes - */ - setBytes(bytes, format) { - this.format = format; - this.data = bytes; - this.text = null; - } - - - /** - * Get the byte sequence representing the literal packet data - * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again - * @returns {Uint8Array | ReadableStream} A sequence of bytes. - */ - getBytes(clone = false) { - if (this.data === null) { - // encode UTF8 and normalize EOL to \r\n - this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); - } - if (clone) { - return passiveClone(this.data); - } - return this.data; - } - - - /** - * Sets the filename of the literal packet data - * @param {String} filename - Any native javascript string - */ - setFilename(filename) { - this.filename = filename; - } - - - /** - * Get the filename of the literal packet data - * @returns {String} Filename. - */ - getFilename() { - return this.filename; - } - - /** - * Parsing function for a literal data packet (tag 11). - * - * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet - * @returns {Promise} Object representation. - * @async - */ - async read(bytes) { - await parse(bytes, async reader => { - // - A one-octet field that describes how the data is formatted. - const format = await reader.readByte(); // enums.literal - - const filename_len = await reader.readByte(); - this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - - this.date = util.readDate(await reader.readBytes(4)); - - let data = reader.remainder(); - if (isArrayStream(data)) data = await readToEnd(data); - this.setBytes(data, format); - }); - } - - /** - * Creates a Uint8Array representation of the packet, excluding the data - * - * @returns {Uint8Array} Uint8Array representation of the packet. - */ - writeHeader() { - const filename = util.encodeUTF8(this.filename); - const filename_length = new Uint8Array([filename.length]); - - const format = new Uint8Array([this.format]); - const date = util.writeDate(this.date); - - return util.concatUint8Array([format, filename_length, filename, date]); - } - - /** - * Creates a Uint8Array representation of the packet - * - * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. - */ - write() { - const header = this.writeHeader(); - const data = this.getBytes(); - - return util.concat([header, data]); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. -const verified = Symbol('verified'); - -// GPG puts the Issuer and Signature subpackets in the unhashed area. -// Tampering with those invalidates the signature, so we still trust them and parse them. -// All other unhashed subpackets are ignored. -const allowedUnhashedSubpackets = new Set([ - enums.signatureSubpacket.issuer, - enums.signatureSubpacket.issuerFingerprint, - enums.signatureSubpacket.embeddedSignature -]); - -/** - * Implementation of the Signature Packet (Tag 2) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - */ -class SignaturePacket { - static get tag() { - return enums.packet.signature; - } - - constructor() { - this.version = null; - /** @type {enums.signature} */ - this.signatureType = null; - /** @type {enums.hash} */ - this.hashAlgorithm = null; - /** @type {enums.publicKey} */ - this.publicKeyAlgorithm = null; - - this.signatureData = null; - this.unhashedSubpackets = []; - this.signedHashValue = null; - - this.created = null; - this.signatureExpirationTime = null; - this.signatureNeverExpires = true; - this.exportable = null; - this.trustLevel = null; - this.trustAmount = null; - this.regularExpression = null; - this.revocable = null; - this.keyExpirationTime = null; - this.keyNeverExpires = null; - this.preferredSymmetricAlgorithms = null; - this.revocationKeyClass = null; - this.revocationKeyAlgorithm = null; - this.revocationKeyFingerprint = null; - this.issuerKeyID = new KeyID(); - this.rawNotations = []; - this.notations = {}; - this.preferredHashAlgorithms = null; - this.preferredCompressionAlgorithms = null; - this.keyServerPreferences = null; - this.preferredKeyServer = null; - this.isPrimaryUserID = null; - this.policyURI = null; - this.keyFlags = null; - this.signersUserID = null; - this.reasonForRevocationFlag = null; - this.reasonForRevocationString = null; - this.features = null; - this.signatureTargetPublicKeyAlgorithm = null; - this.signatureTargetHashAlgorithm = null; - this.signatureTargetHash = null; - this.embeddedSignature = null; - this.issuerKeyVersion = null; - this.issuerFingerprint = null; - this.preferredAEADAlgorithms = null; - - this.revoked = null; - this[verified] = null; - } - - /** - * parsing function for a signature packet (tag 2). - * @param {String} bytes - Payload of a tag 2 packet - * @returns {SignaturePacket} Object representation. - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); - } - - this.signatureType = bytes[i++]; - this.publicKeyAlgorithm = bytes[i++]; - this.hashAlgorithm = bytes[i++]; - - // hashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), true); - if (!this.created) { - throw new Error('Missing signature creation time subpacket.'); - } - - // A V4 signature hashes the packet body - // starting from its first field, the version number, through the end - // of the hashed subpacket data. Thus, the fields hashed are the - // signature version, the signature type, the public-key algorithm, the - // hash algorithm, the hashed subpacket length, and the hashed - // subpacket body. - this.signatureData = bytes.subarray(0, i); - - // unhashed subpackets - i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - - // Two-octet field holding left 16 bits of signed hash value. - this.signedHashValue = bytes.subarray(i, i + 2); - i += 2; - - this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length)); - } - - /** - * @returns {Uint8Array | ReadableStream} - */ - writeParams() { - if (this.params instanceof Promise) { - return fromAsync( - async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params) - ); - } - return mod.serializeParams(this.publicKeyAlgorithm, this.params); - } - - write() { - const arr = []; - arr.push(this.signatureData); - arr.push(this.writeUnhashedSubPackets()); - arr.push(this.signedHashValue); - arr.push(this.writeParams()); - return util.concat(arr); - } - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param {SecretKeyPacket} key - Private key used to sign the message. - * @param {Object} data - Contains packets to be signed. - * @param {Date} [date] - The signature creation time. - * @param {Boolean} [detached] - Whether to create a detached signature - * @throws {Error} if signing failed - * @async - */ - async sign(key, data, date = new Date(), detached = false) { - if (key.version === 5) { - this.version = 5; - } else { - this.version = 4; - } - const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; - - this.created = util.normalizeDate(date); - this.issuerKeyVersion = key.version; - this.issuerFingerprint = key.getFingerprintBytes(); - this.issuerKeyID = key.getKeyID(); - - // Add hashed subpackets - arr.push(this.writeHashedSubPackets()); - - // Remove unhashed subpackets, in case some allowed unhashed - // subpackets existed, in order not to duplicate them (in both - // the hashed and unhashed subpackets) when re-signing. - this.unhashedSubpackets = []; - - this.signatureData = util.concat(arr); - - const toHash = this.toHash(this.signatureType, data, detached); - const hash = await this.hash(this.signatureType, data, toHash, detached); - - this.signedHashValue = slice(clone(hash), 0, 2); - const signed = async () => mod.signature.sign( - this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) - ); - if (util.isStream(hash)) { - this.params = signed(); - } else { - this.params = await signed(); - - // Store the fact that this signature is valid, e.g. for when we call `await - // getLatestValidSignature(this.revocationSignatures, key, data)` later. - // Note that this only holds up if the key and data passed to verify are the - // same as the ones passed to sign. - this[verified] = true; - } - } - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeHashedSubPackets() { - const sub = enums.signatureSubpacket; - const arr = []; - let bytes; - if (this.created === null) { - throw new Error('Missing signature creation time'); - } - arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); - if (this.signatureExpirationTime !== null) { - arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); - } - if (this.exportable !== null) { - arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); - } - if (this.trustLevel !== null) { - bytes = new Uint8Array([this.trustLevel, this.trustAmount]); - arr.push(writeSubPacket(sub.trustSignature, true, bytes)); - } - if (this.regularExpression !== null) { - arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); - } - if (this.revocable !== null) { - arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); - } - if (this.keyExpirationTime !== null) { - arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); - } - if (this.preferredSymmetricAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); - arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); - } - if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); - bytes = util.concat([bytes, this.revocationKeyFingerprint]); - arr.push(writeSubPacket(sub.revocationKey, false, bytes)); - } - if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) { - // If the version of [the] key is greater than 4, this subpacket - // MUST NOT be included in the signature. - arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write())); - } - this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { - bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; - const encodedName = util.encodeUTF8(name); - // 2 octets of name length - bytes.push(util.writeNumber(encodedName.length, 2)); - // 2 octets of value length - bytes.push(util.writeNumber(value.length, 2)); - bytes.push(encodedName); - bytes.push(value); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.notationData, critical, bytes)); - }); - if (this.preferredHashAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); - arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); - } - if (this.preferredCompressionAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); - arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); - } - if (this.keyServerPreferences !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); - arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); - } - if (this.preferredKeyServer !== null) { - arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); - } - if (this.isPrimaryUserID !== null) { - arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); - } - if (this.policyURI !== null) { - arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); - } - if (this.keyFlags !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); - arr.push(writeSubPacket(sub.keyFlags, true, bytes)); - } - if (this.signersUserID !== null) { - arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); - } - if (this.reasonForRevocationFlag !== null) { - bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); - arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); - } - if (this.features !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); - arr.push(writeSubPacket(sub.features, false, bytes)); - } - if (this.signatureTargetPublicKeyAlgorithm !== null) { - bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(util.stringToUint8Array(this.signatureTargetHash)); - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); - } - if (this.embeddedSignature !== null) { - arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); - } - if (this.issuerFingerprint !== null) { - bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; - bytes = util.concat(bytes); - arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes)); - } - if (this.preferredAEADAlgorithms !== null) { - bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); - arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); - } - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - /** - * Creates an Uint8Array containing the unhashed subpackets - * @returns {Uint8Array} Subpacket data. - */ - writeUnhashedSubPackets() { - const arr = []; - this.unhashedSubpackets.forEach(data => { - arr.push(writeSimpleLength(data.length)); - arr.push(data); - }); - - const result = util.concat(arr); - const length = util.writeNumber(result.length, 2); - - return util.concat([length, result]); - } - - // V4 signature sub packets - readSubPacket(bytes, hashed = true) { - let mypos = 0; - - // The leftmost bit denotes a "critical" packet - const critical = !!(bytes[mypos] & 0x80); - const type = bytes[mypos] & 0x7F; - - if (!hashed) { - this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length)); - if (!allowedUnhashedSubpackets.has(type)) { - return; - } - } - - mypos++; - - // subpacket type - switch (type) { - case enums.signatureSubpacket.signatureCreationTime: - // Signature Creation Time - this.created = util.readDate(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.signatureExpirationTime: { - // Signature Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.signatureNeverExpires = seconds === 0; - this.signatureExpirationTime = seconds; - - break; - } - case enums.signatureSubpacket.exportableCertification: - // Exportable Certification - this.exportable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.trustSignature: - // Trust Signature - this.trustLevel = bytes[mypos++]; - this.trustAmount = bytes[mypos++]; - break; - case enums.signatureSubpacket.regularExpression: - // Regular Expression - this.regularExpression = bytes[mypos]; - break; - case enums.signatureSubpacket.revocable: - // Revocable - this.revocable = bytes[mypos++] === 1; - break; - case enums.signatureSubpacket.keyExpirationTime: { - // Key Expiration Time in seconds - const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); - - this.keyExpirationTime = seconds; - this.keyNeverExpires = seconds === 0; - - break; - } - case enums.signatureSubpacket.preferredSymmetricAlgorithms: - // Preferred Symmetric Algorithms - this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.revocationKey: - // Revocation Key - // (1 octet of class, 1 octet of public-key algorithm ID, 20 - // octets of - // fingerprint) - this.revocationKeyClass = bytes[mypos++]; - this.revocationKeyAlgorithm = bytes[mypos++]; - this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); - break; - - case enums.signatureSubpacket.issuer: - // Issuer - this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); - break; - - case enums.signatureSubpacket.notationData: { - // Notation Data - const humanReadable = !!(bytes[mypos] & 0x80); - - // We extract key/value tuple from the byte stream. - mypos += 4; - const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); - mypos += 2; - - const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); - const value = bytes.subarray(mypos + m, mypos + m + n); - - this.rawNotations.push({ name, humanReadable, value, critical }); - - if (humanReadable) { - this.notations[name] = util.decodeUTF8(value); - } - break; - } - case enums.signatureSubpacket.preferredHashAlgorithms: - // Preferred Hash Algorithms - this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredCompressionAlgorithms: - // Preferred Compression Algorithms - this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.keyServerPreferences: - // Key Server Preferences - this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.preferredKeyServer: - // Preferred Key Server - this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.primaryUserID: - // Primary User ID - this.isPrimaryUserID = bytes[mypos++] !== 0; - break; - case enums.signatureSubpacket.policyURI: - // Policy URI - this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.keyFlags: - // Key Flags - this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signersUserID: - // Signer's User ID - this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.reasonForRevocation: - // Reason for Revocation - this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.features: - // Features - this.features = [...bytes.subarray(mypos, bytes.length)]; - break; - case enums.signatureSubpacket.signatureTarget: { - // Signature Target - // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) - this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; - this.signatureTargetHashAlgorithm = bytes[mypos++]; - - const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm); - - this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); - break; - } - case enums.signatureSubpacket.embeddedSignature: - // Embedded Signature - this.embeddedSignature = new SignaturePacket(); - this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); - break; - case enums.signatureSubpacket.issuerFingerprint: - // Issuer Fingerprint - this.issuerKeyVersion = bytes[mypos++]; - this.issuerFingerprint = bytes.subarray(mypos, bytes.length); - if (this.issuerKeyVersion === 5) { - this.issuerKeyID.read(this.issuerFingerprint); - } else { - this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); - } - break; - case enums.signatureSubpacket.preferredAEADAlgorithms: - // Preferred AEAD Algorithms - this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; - break; - default: { - const err = new Error(`Unknown signature subpacket type ${type}`); - if (critical) { - throw err; - } else { - util.printDebug(err); - } - } - } - } - - readSubPackets(bytes, trusted = true, config) { - // Two-octet scalar octet count for following subpacket data. - const subpacketLength = util.readNumber(bytes.subarray(0, 2)); - - let i = 2; - - // subpacket data set (zero or more subpackets) - while (i < 2 + subpacketLength) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); - - i += len.len; - } - - return i; - } - - // Produces data to produce signature on - toSign(type, data) { - const t = enums.signature; - - switch (type) { - case t.binary: - if (data.text !== null) { - return util.encodeUTF8(data.getText(true)); - } - return data.getBytes(true); - - case t.text: { - const bytes = data.getBytes(true); - // normalize EOL to \r\n - return util.canonicalizeEOL(bytes); - } - case t.standalone: - return new Uint8Array(0); - - case t.certGeneric: - case t.certPersona: - case t.certCasual: - case t.certPositive: - case t.certRevocation: { - let packet; - let tag; - - if (data.userID) { - tag = 0xB4; - packet = data.userID; - } else if (data.userAttribute) { - tag = 0xD1; - packet = data.userAttribute; - } else { - throw new Error('Either a userID or userAttribute packet needs to be ' + - 'supplied for certification.'); - } - - const bytes = packet.write(); - - return util.concat([this.toSign(t.key, data), - new Uint8Array([tag]), - util.writeNumber(bytes.length, 4), - bytes]); - } - case t.subkeyBinding: - case t.subkeyRevocation: - case t.keyBinding: - return util.concat([this.toSign(t.key, data), this.toSign(t.key, { - key: data.bind - })]); - - case t.key: - if (data.key === undefined) { - throw new Error('Key packet is required for this signature.'); - } - return data.key.writeForHash(this.version); - - case t.keyRevocation: - return this.toSign(t.key, data); - case t.timestamp: - return new Uint8Array(0); - case t.thirdParty: - throw new Error('Not implemented'); - default: - throw new Error('Unknown signature type.'); - } - } - - calculateTrailer(data, detached) { - let length = 0; - return transform(clone(this.signatureData), value => { - length += value.length; - }, () => { - const arr = []; - if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { - if (detached) { - arr.push(new Uint8Array(6)); - } else { - arr.push(data.writeHeader()); - } - } - arr.push(new Uint8Array([this.version, 0xFF])); - if (this.version === 5) { - arr.push(new Uint8Array(4)); - } - arr.push(util.writeNumber(length, 4)); - // For v5, this should really be writeNumber(length, 8) rather than the - // hardcoded 4 zero bytes above - return util.concat(arr); - }); - } - - toHash(signatureType, data, detached = false) { - const bytes = this.toSign(signatureType, data); - - return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]); - } - - async hash(signatureType, data, toHash, detached = false) { - if (!toHash) toHash = this.toHash(signatureType, data, detached); - return mod.hash.digest(this.hashAlgorithm, toHash); - } - - /** - * verifies the signature packet. Note: not all signature types are implemented - * @param {PublicSubkeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature - * @param {module:enums.signature} signatureType - Expected signature type - * @param {Uint8Array|Object} data - Data which on the signature applies - * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration - * @param {Boolean} [detached] - Whether to verify a detached signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if signature validation failed - * @async - */ - async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { - if (!this.issuerKeyID.equals(key.getKeyID())) { - throw new Error('Signature was not issued by the given public key'); - } - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); - } - - const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; - // Cryptographic validity is cached after one successful verification. - // However, for message signatures, we always re-verify, since the passed `data` can change - const skipVerify = this[verified] && !isMessageSignature; - if (!skipVerify) { - let toHash; - let hash; - if (this.hashed) { - hash = await this.hashed; - } else { - toHash = this.toHash(signatureType, data, detached); - hash = await this.hash(signatureType, data, toHash); - } - hash = await readToEnd(hash); - if (this.signedHashValue[0] !== hash[0] || - this.signedHashValue[1] !== hash[1]) { - throw new Error('Signed digest did not match'); - } - - this.params = await this.params; - - this[verified] = await mod.signature.verify( - this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, - toHash, hash - ); - - if (!this[verified]) { - throw new Error('Signature verification failed'); - } - } - - const normDate = util.normalizeDate(date); - if (normDate && this.created > normDate) { - throw new Error('Signature creation time is in the future'); - } - if (normDate && normDate >= this.getExpirationTime()) { - throw new Error('Signature is expired'); - } - if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { - throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && - [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { - throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); - } - this.rawNotations.forEach(({ name, critical }) => { - if (critical && (config$1.knownNotations.indexOf(name) < 0)) { - throw new Error(`Unknown critical notation: ${name}`); - } - }); - if (this.revocationKeyClass !== null) { - throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); - } - } - - /** - * Verifies signature expiration date - * @param {Date} [date] - Use the given date for verification instead of the current time - * @returns {Boolean} True if expired. - */ - isExpired(date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - return !(this.created <= normDate && normDate < this.getExpirationTime()); - } - return false; - } - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns {Date | Infinity} Expiration time. - */ - getExpirationTime() { - return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); - } -} - -/** - * Creates a Uint8Array representation of a sub signature packet - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} - * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} - * @param {Integer} type - Subpacket signature type. - * @param {Boolean} critical - Whether the subpacket should be critical. - * @param {String} data - Data to be included - * @returns {Uint8Array} The signature subpacket. - * @private - */ -function writeSubPacket(type, critical, data) { - const arr = []; - arr.push(writeSimpleLength(data.length + 1)); - arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); - arr.push(data); - return util.concat(arr); -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -const VERSION = 3; - -/** - * Implementation of the One-Pass Signature Packets (Tag 4) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ -class OnePassSignaturePacket { - static get tag() { - return enums.packet.onePassSignature; - } - - constructor() { - /** A one-octet version number. The current version is 3. */ - this.version = null; - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - * @type {enums.signature} - - */ - this.signatureType = null; - /** - * A one-octet number describing the hash algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} - * @type {enums.hash} - */ - this.hashAlgorithm = null; - /** - * A one-octet number describing the public-key algorithm used. - * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} - * @type {enums.publicKey} - */ - this.publicKeyAlgorithm = null; - /** An eight-octet number holding the Key ID of the signing key. */ - this.issuerKeyID = null; - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - this.flags = null; - } - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param {Uint8Array} bytes - Payload of a tag 4 packet - * @returns {OnePassSignaturePacket} Object representation. - */ - read(bytes) { - let mypos = 0; - // A one-octet version number. The current version is 3. - this.version = bytes[mypos++]; - if (this.version !== VERSION) { - throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); - } - - // A one-octet signature type. Signature types are described in - // Section 5.2.1. - this.signatureType = bytes[mypos++]; - - // A one-octet number describing the hash algorithm used. - this.hashAlgorithm = bytes[mypos++]; - - // A one-octet number describing the public-key algorithm used. - this.publicKeyAlgorithm = bytes[mypos++]; - - // An eight-octet number holding the Key ID of the signing key. - this.issuerKeyID = new KeyID(); - this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); - mypos += 8; - - // A one-octet number holding a flag showing whether the signature - // is nested. A zero value indicates that the next packet is - // another One-Pass Signature packet that describes another - // signature to be applied to the same message data. - this.flags = bytes[mypos++]; - return this; - } - - /** - * creates a string representation of a one-pass signature packet - * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. - */ - write() { - const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]); - - const end = new Uint8Array([this.flags]); - - return util.concatUint8Array([start, this.issuerKeyID.write(), end]); - } - - calculateTrailer(...args) { - return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); - } - - async verify() { - const correspondingSig = await this.correspondingSig; - if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { - throw new Error('Corresponding signature packet missing'); - } - if ( - correspondingSig.signatureType !== this.signatureType || - correspondingSig.hashAlgorithm !== this.hashAlgorithm || - correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || - !correspondingSig.issuerKeyID.equals(this.issuerKeyID) - ) { - throw new Error('Corresponding signature packet does not match one-pass signature packet'); - } - correspondingSig.hashed = this.hashed; - return correspondingSig.verify.apply(correspondingSig, arguments); - } -} - -OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; -OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; -OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; - -/** - * Instantiate a new packet given its tag - * @function newPacketFromTag - * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @returns {Object} New packet object with type based on tag - * @throws {Error|UnsupportedError} for disallowed or unknown packets - */ -function newPacketFromTag(tag, allowedPackets) { - if (!allowedPackets[tag]) { - // distinguish between disallowed packets and unknown ones - let packetType; - try { - packetType = enums.read(enums.packet, tag); - } catch (e) { - throw new UnsupportedError(`Unknown packet type with tag: ${tag}`); - } - throw new Error(`Packet not allowed in this context: ${packetType}`); - } - return new allowedPackets[tag](); -} - -/** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - * @extends Array - */ -class PacketList extends Array { - /** - * Parses the given binary data and returns a list of packets. - * Equivalent to calling `read` on an empty PacketList instance. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @returns {PacketList} parsed list of packets - * @throws on parsing errors - * @async - */ - static async fromBinary(bytes, allowedPackets, config$1 = config) { - const packets = new PacketList(); - await packets.read(bytes, allowedPackets, config$1); - return packets; - } - - /** - * Reads a stream of binary data and interprets it as a list of packets. - * @param {Uint8Array | ReadableStream} bytes - binary data to parse - * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class - * @param {Object} [config] - full configuration, defaults to openpgp.config - * @throws on parsing errors - * @async - */ - async read(bytes, allowedPackets, config$1 = config) { - if (config$1.additionalAllowedPackets.length) { - allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; - } - this.stream = transformPair(bytes, async (readable, writable) => { - const writer = getWriter(writable); - try { - while (true) { - await writer.ready; - const done = await readPackets(readable, async parsed => { - try { - if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) { - // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: - // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 - // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 - return; - } - const packet = newPacketFromTag(parsed.tag, allowedPackets); - packet.packets = new PacketList(); - packet.fromStream = util.isStream(parsed.packet); - await packet.read(parsed.packet, config$1); - await writer.write(packet); - } catch (e) { - const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; - const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); - if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { - // The packets that support streaming are the ones that contain message data. - // Those are also the ones we want to be more strict about and throw on parse errors - // (since we likely cannot process the message without these packets anyway). - await writer.abort(e); - } else { - const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); - await writer.write(unparsedPacket); - } - util.printDebugError(e); - } - }); - if (done) { - await writer.ready; - await writer.close(); - return; - } - } - } catch (e) { - await writer.abort(e); - } - }); - - // Wait until first few packets have been read - const reader = getReader(this.stream); - while (true) { - const { done, value } = await reader.read(); - if (!done) { - this.push(value); - } else { - this.stream = null; - } - if (done || supportsStreaming(value.constructor.tag)) { - break; - } - } - reader.releaseLock(); - } - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. - */ - write() { - const arr = []; - - for (let i = 0; i < this.length; i++) { - const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; - const packetbytes = this[i].write(); - if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { - let buffer = []; - let bufferLength = 0; - const minLength = 512; - arr.push(writeTag(tag)); - arr.push(transform(packetbytes, value => { - buffer.push(value); - bufferLength += value.length; - if (bufferLength >= minLength) { - const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); - const chunkSize = 2 ** powerOf2; - const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); - buffer = [bufferConcat.subarray(1 + chunkSize)]; - bufferLength = buffer[0].length; - return bufferConcat.subarray(0, 1 + chunkSize); - } - }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); - } else { - if (util.isStream(packetbytes)) { - let length = 0; - arr.push(transform(clone(packetbytes), value => { - length += value.length; - }, () => writeHeader(tag, length))); - } else { - arr.push(writeHeader(tag, packetbytes.length)); - } - arr.push(packetbytes); - } - } - - return util.concat(arr); - } - - /** - * Creates a new PacketList with all packets matching the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {PacketList} - */ - filterByTag(...tags) { - const filtered = new PacketList(); - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(this[i].constructor.tag))) { - filtered.push(this[i]); - } - } - - return filtered; - } - - /** - * Traverses packet list and returns first packet with matching tag - * @param {module:enums.packet} tag - The packet tag - * @returns {Packet|undefined} - */ - findPacket(tag) { - return this.find(packet => packet.constructor.tag === tag); - } - - /** - * Find indices of packets with the given tag(s) - * @param {...module:enums.packet} tags - packet tags to look for - * @returns {Integer[]} packet indices - */ - indexOfTag(...tags) { - const tagIndex = []; - const that = this; - - const handle = tag => packetType => tag === packetType; - - for (let i = 0; i < this.length; i++) { - if (tags.some(handle(that[i].constructor.tag))) { - tagIndex.push(i); - } - } - return tagIndex; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A Compressed Data packet can contain the following packet types -const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -/** - * Implementation of the Compressed Data Packet (Tag 8) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ -class CompressedDataPacket { - static get tag() { - return enums.packet.compressedData; - } - - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * List of packets - * @type {PacketList} - */ - this.packets = null; - /** - * Compression algorithm - * @type {enums.compression} - */ - this.algorithm = config$1.preferredCompressionAlgorithm; - - /** - * Compressed packet data - * @type {Uint8Array | ReadableStream} - */ - this.compressed = null; - - /** - * zip/zlib compression level, between 1 and 9 - */ - this.deflateLevel = config$1.deflateLevel; - } - - /** - * Parsing function for the packet. - * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async read(bytes, config$1 = config) { - await parse(bytes, async reader => { - - // One octet that gives the algorithm used to compress the packet. - this.algorithm = await reader.readByte(); - - // Compressed data, which makes up the remainder of the packet. - this.compressed = reader.remainder(); - - await this.decompress(config$1); - }); - } - - - /** - * Return the compressed packet. - * @returns {Uint8Array | ReadableStream} Binary compressed packet. - */ - write() { - if (this.compressed === null) { - this.compress(); - } - - return util.concat([new Uint8Array([this.algorithm]), this.compressed]); - } - - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - async decompress(config$1 = config) { - const compressionName = enums.read(enums.compression, this.algorithm); - const decompressionFn = decompress_fns[compressionName]; - if (!decompressionFn) { - throw new Error(`${compressionName} decompression not supported`); - } - - this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1); - } - - /** - * Compress the packet data (member decompressedData) - */ - compress() { - const compressionName = enums.read(enums.compression, this.algorithm); - const compressionFn = compress_fns[compressionName]; - if (!compressionFn) { - throw new Error(`${compressionName} compression not supported`); - } - - this.compressed = compressionFn(this.packets.write(), this.deflateLevel); - } -} - -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// - - -const nodeZlib = util.getNodeZlib(); - -function uncompressed(data) { - return data; -} - -function node_zlib(func, create, options = {}) { - return function (data) { - if (!util.isStream(data) || isArrayStream(data)) { - return fromAsync(() => readToEnd(data).then(data => { - return new Promise((resolve, reject) => { - func(data, options, (err, result) => { - if (err) return reject(err); - resolve(result); - }); - }); - })); - } - return nodeToWeb(webToNode(data).pipe(create(options))); - }; -} - -function pako_zlib(constructor, options = {}) { - return function(data) { - const obj = new constructor(options); - return transform(data, value => { - if (value.length) { - obj.push(value, Z_SYNC_FLUSH); - return obj.result; - } - }, () => { - if (constructor === Deflate) { - obj.push([], Z_FINISH); - return obj.result; - } - }); - }; -} - -function bzip2(func) { - return function(data) { - return fromAsync(async () => func(await readToEnd(data))); - }; -} - -const compress_fns = nodeZlib ? { - zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed) -} : { - zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed), - zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed) -}; - -const decompress_fns = nodeZlib ? { - uncompressed: uncompressed, - zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw), - zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -} : { - uncompressed: uncompressed, - zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }), - zlib: /*#__PURE__*/ pako_zlib(Inflate), - bzip2: /*#__PURE__*/ bzip2(lib_4) -}; - -// GPG4Browsers - An OpenPGP implementation in javascript - -// A SEIP packet can contain the following packet types -const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$1 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ -class SymEncryptedIntegrityProtectedDataPacket { - static get tag() { - return enums.packet.symEncryptedIntegrityProtectedData; - } - - constructor() { - this.version = VERSION$1; - this.encrypted = null; - this.packets = null; - } - - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - // - A one-octet version number. The only currently defined value is 1. - if (version !== VERSION$1) { - throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`); - } - - // - Encrypted data, the output of the selected symmetric-key cipher - // operating in Cipher Feedback mode with shift amount equal to the - // block size of the cipher (CFB-n where n is the block size). - this.encrypted = reader.remainder(); - }); - } - - write() { - return util.concat([new Uint8Array([VERSION$1]), this.encrypted]); - } - - /** - * Encrypt the payload in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on encryption failure - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - - let bytes = this.packets.write(); - if (isArrayStream(bytes)) bytes = await readToEnd(bytes); - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - - const tohash = util.concat([prefix, bytes, mdc]); - const hash = await mod.hash.sha1(passiveClone(tohash)); - const plaintext = util.concat([tohash, hash]); - - this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); - return true; - } - - /** - * Decrypts the encrypted data contained in the packet. - * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} on decryption failure - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - let encrypted = clone(this.encrypted); - if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); - - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - const realHash = slice(passiveClone(decrypted), -20); - const tohash = slice(decrypted, 0, -20); - const verifyHash = Promise.all([ - readToEnd(await mod.hash.sha1(passiveClone(tohash))), - readToEnd(realHash) - ]).then(([hash, mdc]) => { - if (!util.equalsUint8Array(hash, mdc)) { - throw new Error('Modification detected.'); - } - return new Uint8Array(); - }); - const bytes = slice(tohash, blockSize + 2); // Remove random prefix - let packetbytes = slice(bytes, 0, -2); // Remove MDC packet - packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); - if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { - packetbytes = await readToEnd(packetbytes); - } - this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1); - return true; - } -} - -// OpenPGP.js - An OpenPGP implementation in javascript - -// An AEAD-encrypted Data packet can contain the following packet types -const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); - -const VERSION$2 = 1; // A one-octet version number of the data packet. - -/** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ -class AEADEncryptedDataPacket { - static get tag() { - return enums.packet.aeadEncryptedData; - } - - constructor() { - this.version = VERSION$2; - /** @type {enums.symmetric} */ - this.cipherAlgorithm = null; - /** @type {enums.aead} */ - this.aeadAlgorithm = enums.aead.eax; - this.chunkSizeByte = null; - this.iv = null; - this.encrypted = null; - this.packets = null; - } - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param {Uint8Array | ReadableStream} bytes - * @throws {Error} on parsing failure - */ - async read(bytes) { - await parse(bytes, async reader => { - const version = await reader.readByte(); - if (version !== VERSION$2) { // The only currently defined value is 1. - throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); - } - this.cipherAlgorithm = await reader.readByte(); - this.aeadAlgorithm = await reader.readByte(); - this.chunkSizeByte = await reader.readByte(); - - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = await reader.readBytes(mode.ivLength); - this.encrypted = reader.remainder(); - }); - } - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns {Uint8Array | ReadableStream} The encrypted payload. - */ - write() { - return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); - } - - /** - * Decrypt the encrypted payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.packets = await PacketList.fromBinary( - await this.crypt('decrypt', key, clone(this.encrypted)), - allowedPackets$2, - config$1 - ); - } - - /** - * Encrypt the packet payload. - * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm - * @param {Uint8Array} key - The session key used to encrypt the payload - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - this.cipherAlgorithm = sessionKeyAlgorithm; - - const { ivLength } = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV - this.chunkSizeByte = config$1.aeadChunkSizeByte; - const data = this.packets.write(); - this.encrypted = await this.crypt('encrypt', key, data); - } - - /** - * En/decrypt the payload. - * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt - * @param {Uint8Array} key - The session key used to en/decrypt the payload - * @param {Uint8Array | ReadableStream} data - The data to en/decrypt - * @returns {Promise>} - * @async - */ - async crypt(fn, key, data) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const modeInstance = await mode(this.cipherAlgorithm, key); - const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; - const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; - const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) - const adataBuffer = new ArrayBuffer(21); - const adataArray = new Uint8Array(adataBuffer, 0, 13); - const adataTagArray = new Uint8Array(adataBuffer); - const adataView = new DataView(adataBuffer); - const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); - adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0); - let chunkIndex = 0; - let latestPromise = Promise.resolve(); - let cryptedBytes = 0; - let queuedBytes = 0; - const iv = this.iv; - return transformPair(data, async (readable, writable) => { - if (util.isStream(readable) !== 'array') { - const buffer = new TransformStream({}, { - highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6), - size: array => array.length - }); - pipe(buffer.readable, writable); - writable = buffer.writable; - } - const reader = getReader(readable); - const writer = getWriter(writable); - try { - while (true) { - let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); - const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); - chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); - let cryptedPromise; - let done; - if (!chunkIndex || chunk.length) { - reader.unshift(finalChunk); - cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray); - queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; - } else { - // After the last chunk, we either encrypt a final, empty - // data chunk to get the final authentication tag or - // validate that final authentication tag. - adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...) - cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray); - queuedBytes += tagLengthIfEncrypting; - done = true; - } - cryptedBytes += chunk.length - tagLengthIfDecrypting; - // eslint-disable-next-line no-loop-func - latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { - await writer.ready; - await writer.write(crypted); - queuedBytes -= crypted.length; - }).catch(err => writer.abort(err)); - if (done || queuedBytes > writer.desiredSize) { - await latestPromise; // Respect backpressure - } - if (!done) { - adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) - } else { - await writer.close(); - break; - } - } - } catch (e) { - await writer.abort(e); - } - }); - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; -const VERSION$3 = 3; + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; -/** - * Public-Key Encrypted Session Key Packets (Tag 1) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ -class PublicKeyEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.publicKeyEncryptedSessionKey; - } + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - constructor() { - this.version = 3; + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - this.publicKeyID = new KeyID(); - this.publicKeyAlgorithm = null; + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - this.sessionKey = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = null; + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} - /** @type {Object} */ - this.encrypted = {}; - } +function S(o, a) { + M(o, a, a); +} - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * - * @param {Uint8Array} bytes - Payload of a tag 1 packet - */ - read(bytes) { - let i = 0; - this.version = bytes[i++]; - if (this.version !== VERSION$3) { - throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); - } - i += this.publicKeyID.read(bytes.subarray(i)); - this.publicKeyAlgorithm = bytes[i++]; - this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version); - if (this.publicKeyAlgorithm === enums.publicKey.x25519) { - this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); - } +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - /** - * Create a binary representation of a tag 1 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const arr = [ - new Uint8Array([this.version]), - this.publicKeyID.write(), - new Uint8Array([this.publicKeyAlgorithm]), - mod.serializeParams(this.publicKeyAlgorithm, this.encrypted) - ]; - - return util.concatUint8Array(arr); +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - /** - * Encrypt session key packet - * @param {PublicKeyPacket} key - Public key - * @throws {Error} if encryption failed - * @async - */ - async encrypt(key) { - const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); - const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey); - this.encrypted = await mod.publicKeyEncrypt( - algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes()); +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; } - - /** - * Decrypts the session key (only for public key encrypted session key packets (tag 1) - * @param {SecretKeyPacket} key - decrypted private key - * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. - * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } - * @throws {Error} if decryption failed, unless `randomSessionKey` is given - * @async - */ - async decrypt(key, randomSessionKey) { - // check that session key algo matches the secret key algo - if (this.publicKeyAlgorithm !== key.algorithm) { - throw new Error('Decryption error'); - } - - const randomPayload = randomSessionKey ? - encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : - null; - const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload); - - const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); - - // v3 Montgomery curves have cleartext cipher algo - if (this.publicKeyAlgorithm !== enums.publicKey.x25519) { - this.sessionKeyAlgorithm = sessionKeyAlgorithm; - } - this.sessionKey = sessionKey; + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; } +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} -function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // add checksum - return util.concatUint8Array([ - new Uint8Array([cipherAlgo]), - sessionKeyData, - util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) - ]); - } - case enums.publicKey.x25519: - return sessionKeyData; - default: - throw new Error('Unsupported public key algorithm'); - } +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); } +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; -function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { - switch (keyAlgo) { - case enums.publicKey.rsaEncrypt: - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.elgamal: - case enums.publicKey.ecdh: { - // verify checksum in constant time - const result = decryptedData.subarray(0, decryptedData.length - 2); - const checksum = decryptedData.subarray(decryptedData.length - 2); - const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); - const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; - const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; - if (randomSessionKey) { - // We must not leak info about the validity of the decrypted checksum or cipher algo. - // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. - const isValidPayload = isValidChecksum & - decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & - decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; - return { - sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), - sessionKeyAlgorithm: util.selectUint8( - isValidPayload, - decryptedSessionKey.sessionKeyAlgorithm, - randomSessionKey.sessionKeyAlgorithm - ) - }; - } else { - const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm); - if (isValidPayload) { - return decryptedSessionKey; - } else { - throw new Error('Decryption error'); - } - } +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } - case enums.publicKey.x25519: - return { - sessionKey: decryptedData - }; - default: - throw new Error('Unsupported public key algorithm'); - } -} + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; -// GPG4Browsers - An OpenPGP implementation in javascript - -class S2K { - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - /** - * Hash function identifier, or 0 for gnu-dummy keys - * @type {module:enums.hash | 0} - */ - this.algorithm = enums.hash.sha256; - /** - * enums.s2k identifier or 'gnu-dummy' - * @type {String} - */ - this.type = 'iterated'; - /** @type {Integer} */ - this.c = config$1.s2kIterationCountByte; - /** Eight bytes of salt in a binary string. - * @type {Uint8Array} - */ - this.salt = null; - } + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; - getCount() { - // Exponent bias, defined in RFC4880 - const expbias = 6; + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param {Uint8Array} bytes - Payload of string-to-key specifier - * @returns {Integer} Actual length of the object. - */ - read(bytes) { - let i = 0; - try { - this.type = enums.read(enums.s2k, bytes[i++]); - } catch (err) { - throw new UnsupportedError('Unknown S2K type.'); - } - this.algorithm = bytes[i++]; + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - switch (this.type) { - case 'simple': - break; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - case 'salted': - this.salt = bytes.subarray(i, i + 8); - i += 8; - break; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - case 'iterated': - this.salt = bytes.subarray(i, i + 8); - i += 8; + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); - // Octet 10: count, a one-octet, coded value - this.c = bytes[i++]; - break; + // add + h = bh3; + l = bl3; - case 'gnu': - if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { - i += 3; // GNU - const gnuExtType = 1000 + bytes[i++]; - if (gnuExtType === 1001) { - this.type = 'gnu-dummy'; - // GnuPG extension mode 1001 -- don't write secret key at all - } else { - throw new UnsupportedError('Unknown s2k gnu protection mode.'); - } - } else { - throw new UnsupportedError('Unknown s2k type.'); - } - break; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - default: - throw new UnsupportedError('Unknown s2k type.'); // unreachable - } + h = th; + l = tl; - return i; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Serializes s2k information - * @returns {Uint8Array} Binary representation of s2k. - */ - write() { - if (this.type === 'gnu-dummy') { - return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); - } - const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - switch (this.type) { - case 'simple': - break; - case 'salted': - arr.push(this.salt); - break; - case 'iterated': - arr.push(this.salt); - arr.push(new Uint8Array([this.c])); - break; - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); - } + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - return util.concatUint8Array(arr); - } + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param {String} passphrase - Passphrase containing user input - * @returns {Promise} Produced key with a length corresponding to. - * hashAlgorithm hash length - * @async - */ - async produceKey(passphrase, numBytes) { - passphrase = util.encodeUTF8(passphrase); + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - const arr = []; - let rlength = 0; + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - let prefixlen = 0; - while (rlength < numBytes) { - let toHash; - switch (this.type) { - case 'simple': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); - break; - case 'salted': - toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); - break; - case 'iterated': { - const data = util.concatUint8Array([this.salt, passphrase]); - let datalen = data.length; - const count = Math.max(this.getCount(), datalen); - toHash = new Uint8Array(prefixlen + count); - toHash.set(data, prefixlen); - for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { - toHash.copyWithin(pos, prefixlen, pos); - } - break; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); } - case 'gnu': - throw new Error('GNU s2k type not supported.'); - default: - throw new Error('Unknown s2k type.'); } - const result = await mod.hash.digest(this.algorithm, toHash); - arr.push(result); - rlength += result.length; - prefixlen++; } - return util.concatUint8Array(arr).subarray(0, numBytes); - } -} + // add + h = ah0; + l = al0; -// GPG4Browsers - An OpenPGP implementation in javascript + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -/** - * Symmetric-Key Encrypted Session Key Packets (Tag 3) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: - * The Symmetric-Key Encrypted Session Key packet holds the - * symmetric-key encryption of a session key used to encrypt a message. - * Zero or more Public-Key Encrypted Session Key packets and/or - * Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data packet that holds an encrypted message. - * The message is encrypted with a session key, and the session key is - * itself encrypted and stored in the Encrypted Session Key packet or - * the Symmetric-Key Encrypted Session Key packet. - */ -class SymEncryptedSessionKeyPacket { - static get tag() { - return enums.packet.symEncryptedSessionKey; - } + h = hh[0]; + l = hl[0]; - /** - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(config$1 = config) { - this.version = config$1.aeadProtect ? 5 : 4; - this.sessionKey = null; - /** - * Algorithm to encrypt the session key with - * @type {enums.symmetric} - */ - this.sessionKeyEncryptionAlgorithm = null; - /** - * Algorithm to encrypt the message with - * @type {enums.symmetric} - */ - this.sessionKeyAlgorithm = enums.symmetric.aes256; - /** - * AEAD mode to encrypt the session key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); - this.encrypted = null; - this.s2k = null; - this.iv = null; - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * - * @param {Uint8Array} bytes - Payload of a tag 3 packet - */ - read(bytes) { - let offset = 0; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // A one-octet version number. The only currently defined version is 4. - this.version = bytes[offset++]; - if (this.version !== 4 && this.version !== 5) { - throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); - } + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - // A one-octet number describing the symmetric algorithm used. - const algo = bytes[offset++]; + h = ah1; + l = al1; - if (this.version === 5) { - // A one-octet AEAD algorithm. - this.aeadAlgorithm = bytes[offset++]; - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - // A string-to-key (S2K) specifier, length as defined above. - this.s2k = new S2K(); - offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + h = hh[1]; + l = hl[1]; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // A starting initialization vector of size specified by the AEAD - // algorithm. - this.iv = bytes.subarray(offset, offset += mode.ivLength); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - // The encrypted session key itself, which is decrypted with the - // string-to-key object. This is optional in version 4. - if (this.version === 5 || offset < bytes.length) { - this.encrypted = bytes.subarray(offset, bytes.length); - this.sessionKeyEncryptionAlgorithm = algo; - } else { - this.sessionKeyAlgorithm = algo; - } - } + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - /** - * Create a binary representation of a tag 3 packet - * - * @returns {Uint8Array} The Uint8Array representation. - */ - write() { - const algo = this.encrypted === null ? - this.sessionKeyAlgorithm : - this.sessionKeyEncryptionAlgorithm; + h = ah2; + l = al2; - let bytes; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this.version === 5) { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]); - } else { - bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]); + h = hh[2]; + l = hl[2]; - if (this.encrypted !== null) { - bytes = util.concatUint8Array([bytes, this.encrypted]); - } - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return bytes; - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - /** - * Decrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(passphrase) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - const { blockSize, keySize } = mod.getCipher(algo); - const key = await this.s2k.produceKey(passphrase, keySize); + h = ah3; + l = al3; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, key); - this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); - } else if (this.encrypted !== null) { - const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1, decrypted.length); - } else { - this.sessionKey = key; - } - } + h = hh[3]; + l = hl[3]; - /** - * Encrypts the session key with the given passphrase - * @param {String} passphrase - The passphrase in string form - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - const algo = this.sessionKeyEncryptionAlgorithm !== null ? - this.sessionKeyEncryptionAlgorithm : - this.sessionKeyAlgorithm; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - this.sessionKeyEncryptionAlgorithm = algo; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - const { blockSize, keySize } = mod.getCipher(algo); - const encryptionKey = await this.s2k.produceKey(passphrase, keySize); + h = ah4; + l = al4; - if (this.sessionKey === null) { - this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (this.version === 5) { - const mode = mod.getAEADMode(this.aeadAlgorithm); - this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV - const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); - const modeInstance = await mode(algo, encryptionKey); - this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData); - } else { - const toEncrypt = util.concatUint8Array([ - new Uint8Array([this.sessionKeyAlgorithm]), - this.sessionKey - ]); - this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1); - } + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; } + + return n; } -// GPG4Browsers - An OpenPGP implementation in javascript +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; -/** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ -class PublicKeyPacket { - static get tag() { - return enums.packet.publicKey; - } + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - /** - * Packet version - * @type {Integer} - */ - this.version = config$1.v5Keys ? 5 : 4; - /** - * Key creation date. - * @type {Date} - */ - this.created = util.normalizeDate(date); - /** - * Public key algorithm. - * @type {enums.publicKey} - */ - this.algorithm = null; - /** - * Algorithm specific public params - * @type {Object} - */ - this.publicParams = null; - /** - * Time until expiration in days (V3 only) - * @type {Integer} - */ - this.expirationTimeV3 = 0; - /** - * Fingerprint bytes - * @type {Uint8Array} - */ - this.fingerprint = null; - /** - * KeyID - * @type {module:type/keyid~KeyID} - */ - this.keyID = null; - } + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add$1(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - /** - * Create a PublicKeyPacket from a SecretKeyPacket - * @param {SecretKeyPacket} secretKeyPacket - key packet to convert - * @returns {PublicKeyPacket} public key packet - * @static - */ - static fromSecretKeyPacket(secretKeyPacket) { - const keyPacket = new PublicKeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); } +} - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * @param {Uint8Array} bytes - Input array to read the packet from - * @returns {Object} This object with attributes set by the parser - * @async - */ - async read(bytes) { - let pos = 0; - // A one-octet version number (3, 4 or 5). - this.version = bytes[pos++]; +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} - if (this.version === 4 || this.version === 5) { - // - A four-octet number denoting the time that the key was created. - this.created = util.readDate(bytes.subarray(pos, pos + 4)); - pos += 4; +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add$1(q, p); + add$1(p, p); + cswap(p, q, b); + } +} - // - A one-octet number denoting the public-key algorithm of this key. - this.algorithm = bytes[pos++]; +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} - if (this.version === 5) { - // - A four-octet scalar octet count for the following key material. - pos += 4; - } +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - // - A series of values comprising the key material. - const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); - this.publicParams = publicParams; - pos += read; + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor - await this.computeFingerprintAndKeyID(); - return pos; - } - throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); - } + scalarbase(p, d); + pack(pk, p); - /** - * Creates an OpenPGP public key packet for the given key. - * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. - */ - write() { - const arr = []; - // Version - arr.push(new Uint8Array([this.version])); - arr.push(util.writeDate(this.created)); - // A one-octet number denoting the public-key algorithm of this key - arr.push(new Uint8Array([this.algorithm])); + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} - const params = mod.serializeParams(this.algorithm, this.publicParams); - if (this.version === 5) { - // A four-octet scalar octet count for the following key material - arr.push(util.writeNumber(params.length, 4)); +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; } - // Algorithm-specific params - arr.push(params); - return util.concatUint8Array(arr); + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; } +} - /** - * Write packet in order to be hashed; either for a signature or a fingerprint - * @param {Integer} version - target version of signature or key - */ - writeForHash(version) { - const bytes = this.writePublicKey(); +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} - if (version === 5) { - return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]); - } - return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]); - } +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return null; - } + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - /** - * Returns the creation time of the key - * @returns {Date} - */ - getCreationTime() { - return this.created; - } + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - /** - * Return the key ID of the key - * @returns {module:type/keyid~KeyID} The 8-byte key ID - */ - getKeyID() { - return this.keyID; - } + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - /** - * Computes and set the key ID and fingerprint of the key - * @async - */ - async computeFingerprintAndKeyID() { - await this.computeFingerprint(); - this.keyID = new KeyID(); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - if (this.version === 5) { - this.keyID.read(this.fingerprint.subarray(0, 8)); - } else if (this.version === 4) { - this.keyID.read(this.fingerprint.subarray(12, 20)); - } else { - throw new Error('Unsupported key version'); + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; } } - /** - * Computes and set the fingerprint of the key - */ - async computeFingerprint() { - const toHash = this.writeForHash(this.version); + modL(sm.subarray(32), x); + return smlen; +} - if (this.version === 5) { - this.fingerprint = await mod.hash.sha256(toHash); - } else if (this.version === 4) { - this.fingerprint = await mod.hash.sha1(toHash); - } else { - throw new Error('Unsupported key version'); - } - } +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - /** - * Returns the fingerprint of the key, as an array of bytes - * @returns {Uint8Array} A Uint8Array containing the fingerprint - */ - getFingerprintBytes() { - return this.fingerprint; - } + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - /** - * Calculates and returns the fingerprint of the key, as a string - * @returns {String} A string containing the fingerprint in lowercase hex - */ - getFingerprint() { - return util.uint8ArrayToHex(this.getFingerprintBytes()); - } + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns {Boolean} Whether the two keys have the same version and public key data. - */ - hasSameFingerprintAs(other) { - return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - /** - * Returns algorithm information - * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. - */ - getAlgorithmInfo() { - const result = {}; - result.algorithm = enums.read(enums.publicKey, this.algorithm); - // RSA, DSA or ElGamal public modulo - const modulo = this.publicParams.n || this.publicParams.p; - if (modulo) { - result.bits = util.uint8ArrayBitLength(modulo); - } else if (this.publicParams.oid) { - result.curve = this.publicParams.oid.getName(); - } - return result; - } + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; } -/** - * Alias of read() - * @see PublicKeyPacket#read - */ -PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; -/** - * Alias of write() - * @see PublicKeyPacket#write - */ -PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + if (n < 64) return -1; -// GPG4Browsers - An OpenPGP implementation in javascript + if (unpackneg(q, pk)) return -1; -// A SE packet can contain the following packet types -const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - OnePassSignaturePacket, - SignaturePacket -]); + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); -/** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ -class SymmetricallyEncryptedDataPacket { - static get tag() { - return enums.packet.symmetricallyEncryptedData; - } + scalarbase(q, sm.subarray(32)); + add$1(p, q); + pack(t, p); - constructor() { - /** - * Encrypted secret-key data - */ - this.encrypted = null; - /** - * Decrypted packets contained within. - * @type {PacketList} - */ - this.packets = null; + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; } - read(bytes) { - this.encrypted = bytes; - } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} - write() { - return this.encrypted; +var crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32; + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); } +} - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} - * @throws {Error} if decryption was not successful - * @async - */ - async decrypt(sessionKeyAlgorithm, key, config$1 = config) { - // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error - if (!config$1.allowUnauthenticatedMessages) { - throw new Error('Message is not authenticated.'); - } +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); - const encrypted = await readToEnd(clone(this.encrypted)); - const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, - encrypted.subarray(blockSize + 2), - encrypted.subarray(2, blockSize + 2) - ); +nacl.box = {}; - this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1); - } +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use - * @param {Uint8Array} key - The key of cipher blocksize length to be used - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(sessionKeyAlgorithm, key, config$1 = config) { - const data = this.packets.write(); - const { blockSize } = mod.getCipher(sessionKeyAlgorithm); +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; - const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm); - const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); - const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); - this.encrypted = util.concat([FRE, ciphertext]); - } -} +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; -// GPG4Browsers - An OpenPGP implementation in javascript +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; -/** - * Implementation of the strange "Marker packet" (Tag 10) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * - * The body of this packet consists of: - * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). - * - * Such a packet MUST be ignored when received. It may be placed at the - * beginning of a message that uses features not available in PGP - * version 2.6 in order to cause that version to report that newer - * software is necessary to process the message. - */ -class MarkerPacket { - static get tag() { - return enums.packet.marker; +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + if (crypto$3 && crypto$3.getRandomValues) { + // Browsers and Node v16+ + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto$3.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); } +})(); - /** - * Parsing function for a marker data packet (tag 10). - * @param {Uint8Array} bytes - Payload of a tag 10 packet - * @returns {Boolean} whether the packet payload contains "PGP" - */ - read(bytes) { - if (bytes[0] === 0x50 && // P - bytes[1] === 0x47 && // G - bytes[2] === 0x50) { // P - return true; - } - return false; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - write() { - return new Uint8Array([0x50, 0x47, 0x50]); - } -} -// GPG4Browsers - An OpenPGP implementation in javascript +const knownOIDs = { + '2a8648ce3d030107': enums.curve.nistP256, + '2b81040022': enums.curve.nistP384, + '2b81040023': enums.curve.nistP521, + '2b8104000a': enums.curve.secp256k1, + '2b06010401da470f01': enums.curve.ed25519Legacy, + '2b060104019755010501': enums.curve.curve25519Legacy, + '2b2403030208010107': enums.curve.brainpoolP256r1, + '2b240303020801010b': enums.curve.brainpoolP384r1, + '2b240303020801010d': enums.curve.brainpoolP512r1 +}; -/** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - * @extends PublicKeyPacket - */ -class PublicSubkeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.publicSubkey; +class OID { + constructor(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (util.isArray(oid) || + util.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { // DER encoded oid byte array + if (oid[1] !== oid.length - 2) { + throw new Error('Length mismatch in DER encoded oid'); + } + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; + } } /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config + * Method to read an OID object + * @param {Uint8Array} input - Where to read the OID from + * @returns {Number} Number of read bytes. */ - // eslint-disable-next-line no-useless-constructor - constructor(date, config) { - super(date, config); + read(input) { + if (input.length >= 1) { + const length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } + } + throw new Error('Invalid oid'); } /** - * Create a PublicSubkeyPacket from a SecretSubkeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert - * @returns {SecretSubkeyPacket} public key packet - * @static + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID. */ - static fromSecretSubkeyPacket(secretSubkeyPacket) { - const keyPacket = new PublicSubkeyPacket(); - const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; - keyPacket.version = version; - keyPacket.created = created; - keyPacket.algorithm = algorithm; - keyPacket.publicParams = publicParams; - keyPacket.keyID = keyID; - keyPacket.fingerprint = fingerprint; - return keyPacket; - } -} - -// GPG4Browsers - An OpenPGP implementation in javascript - -/** - * Implementation of the User Attribute Packet (Tag 17) - * - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ -class UserAttributePacket { - static get tag() { - return enums.packet.userAttribute; - } - - constructor() { - this.attributes = []; + write() { + return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); } /** - * parsing function for a user attribute packet (tag 17). - * @param {Uint8Array} input - Payload of a tag 17 packet + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID. */ - read(bytes) { - let i = 0; - while (i < bytes.length) { - const len = readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); - i += len.len; - } + toHex() { + return util.uint8ArrayToHex(this.oid); } /** - * Creates a binary representation of the user attribute packet - * @returns {Uint8Array} String representation. + * If a known curve object identifier, return the canonical name of the curve + * @returns {enums.curve} String with the canonical name of the curve + * @throws if unknown */ - write() { - const arr = []; - for (let i = 0; i < this.attributes.length; i++) { - arr.push(writeSimpleLength(this.attributes[i].length)); - arr.push(util.stringToUint8Array(this.attributes[i])); + getName() { + const name = knownOIDs[this.toHex()]; + if (!name) { + throw new Error('Unknown curve object identifier.'); } - return util.concatUint8Array(arr); - } - /** - * Compare for equality - * @param {UserAttributePacket} usrAttr - * @returns {Boolean} True if equal. - */ - equals(usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { - return false; - } - return this.attributes.every(function(attr, index) { - return attr === usrAttr.attributes[index]; - }); + return name; } } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - * @extends PublicKeyPacket - */ -class SecretKeyPacket extends PublicKeyPacket { - static get tag() { - return enums.packet.secretKey; - } - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - /** - * Secret-key data - */ - this.keyMaterial = null; - /** - * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - this.isEncrypted = null; - /** - * S2K usage - * @type {enums.symmetric} - */ - this.s2kUsage = 0; - /** - * S2K object - * @type {type/s2k} - */ - this.s2k = null; - /** - * Symmetric algorithm to encrypt the key with - * @type {enums.symmetric} - */ - this.symmetric = null; - /** - * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) - * @type {enums.aead} - */ - this.aead = null; - /** - * Decrypted private parameters, referenced by name - * @type {Object} - */ - this.privateParams = null; - } +function readSimpleLength(bytes) { + let len = 0; + let offset; + const type = bytes[0]; - // 5.5.3. Secret-Key Packet Formats - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param {Uint8Array} bytes - Input string to read the packet from - * @async - */ - async read(bytes) { - // - A Public-Key or Public-Subkey packet, as described above. - let i = await this.readPublicKey(bytes); - const startOfSecretKeyData = i; + if (type < 192) { + [len] = bytes; + offset = 1; + } else if (type < 255) { + len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192; + offset = 2; + } else if (type === 255) { + len = util.readNumber(bytes.subarray(1, 1 + 4)); + offset = 5; + } - // - One octet indicating string-to-key usage conventions. Zero - // indicates that the secret-key data is not encrypted. 255 or 254 - // indicates that a string-to-key specifier is being given. Any - // other value is a symmetric-key encryption algorithm identifier. - this.s2kUsage = bytes[i++]; + return { + len: len, + offset: offset + }; +} - // - Only for a version 5 packet, a one-octet scalar octet count of - // the next 4 optional fields. - if (this.version === 5) { - i++; - } +/** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * + * @param {Integer} length - The length to encode + * @returns {Uint8Array} String with openpgp length representation. + */ +function writeSimpleLength(length) { + if (length < 192) { + return new Uint8Array([length]); + } else if (length > 191 && length < 8384) { + /* + * let a = (total data packet length) - 192 let bc = two octet + * representation of a let d = b + 192 + */ + return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]); + } + return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]); +} - try { - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one-octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - this.symmetric = bytes[i++]; +function writePartialLength(power) { + if (power < 0 || power > 30) { + throw new Error('Partial Length power must be between 1 and 30'); + } + return new Uint8Array([224 + power]); +} - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - this.aead = bytes[i++]; - } +function writeTag(tag_type) { + /* we're only generating v4 packet headers here */ + return new Uint8Array([0xC0 | tag_type]); +} - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - this.s2k = new S2K(); - i += this.s2k.read(bytes.subarray(i, bytes.length)); +/** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * + * @param {Integer} tag_type - Tag type + * @param {Integer} length - Length of the payload + * @returns {String} String of the header. + */ +function writeHeader(tag_type, length) { + /* we're only generating v4 packet headers here */ + return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]); +} - if (this.s2k.type === 'gnu-dummy') { - return; - } - } else if (this.s2kUsage) { - this.symmetric = this.s2kUsage; - } +/** + * Whether the packet type supports partial lengths per RFC4880 + * @param {Integer} tag - Tag type + * @returns {Boolean} String of the header. + */ +function supportsStreaming(tag) { + return [ + enums.packet.literalData, + enums.packet.compressedData, + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ].includes(tag); +} - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage) { - this.iv = bytes.subarray( - i, - i + mod.getCipher(this.symmetric).blockSize - ); +/** + * Generic static Packet Parser function + * + * @param {Uint8Array | ReadableStream} input - Input stream as string + * @param {Function} callback - Function to call with the parsed packet + * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise. + */ +async function readPackets(input, callback) { + const reader = getReader(input); + let writer; + let callbackReturned; + try { + const peekedBytes = await reader.peekBytes(2); + // some sanity checks + if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) { + throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.'); + } + const headerByte = await reader.readByte(); + let tag = -1; + let format = -1; + let packetLength; - i += this.iv.length; - } - } catch (e) { - // if the s2k is unsupported, we still want to support encrypting and verifying with the given key - if (!this.s2kUsage) throw e; // always throw for decrypted keys - this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); - this.isEncrypted = true; + format = 0; // 0 = old format; 1 = new format + if ((headerByte & 0x40) !== 0) { + format = 1; } - // - Only for a version 5 packet, a four-octet scalar octet count for - // the following key material. - if (this.version === 5) { - i += 4; + let packetLengthType; + if (format) { + // new format header + tag = headerByte & 0x3F; // bit 5-0 + } else { + // old format header + tag = (headerByte & 0x3F) >> 2; // bit 5-2 + packetLengthType = headerByte & 0x03; // bit 1-0 } - // - Plain or encrypted multiprecision integers comprising the secret - // key data. These algorithm-specific fields are as described - // below. - this.keyMaterial = bytes.subarray(i); - this.isEncrypted = !!this.s2kUsage; + const packetSupportsStreaming = supportsStreaming(tag); + let packet = null; + if (packetSupportsStreaming) { + if (util.isStream(input) === 'array') { + const arrayStream = new ArrayStream(); + writer = getWriter(arrayStream); + packet = arrayStream; + } else { + const transform = new TransformStream(); + writer = getWriter(transform.writable); + packet = transform.readable; + } + // eslint-disable-next-line callback-return + callbackReturned = callback({ tag, packet }); + } else { + packet = []; + } - if (!this.isEncrypted) { - const cleartext = this.keyMaterial.subarray(0, -2); - if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { - throw new Error('Key checksum mismatch'); + let wasPartialLength; + do { + if (!format) { + // 4.2.1. Old Format Packet Lengths + switch (packetLengthType) { + case 0: + // The packet has a one-octet length. The header is 2 octets + // long. + packetLength = await reader.readByte(); + break; + case 1: + // The packet has a two-octet length. The header is 3 octets + // long. + packetLength = (await reader.readByte() << 8) | await reader.readByte(); + break; + case 2: + // The packet has a four-octet length. The header is 5 + // octets long. + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + break; + default: + // 3 - The packet is of indeterminate length. The header is 1 + // octet long, and the implementation must determine how long + // the packet is. If the packet is in a file, this means that + // the packet extends until the end of the file. In general, + // an implementation SHOULD NOT use indeterminate-length + // packets except where the end of the data will be clear + // from the context, and even then it is better to use a + // definite length, or a new format header. The new format + // headers described below have a mechanism for precisely + // encoding data of indeterminate length. + packetLength = Infinity; + break; + } + } else { // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + const lengthByte = await reader.readByte(); + wasPartialLength = false; + if (lengthByte < 192) { + packetLength = lengthByte; + // 4.2.2.2. Two-Octet Lengths + } else if (lengthByte >= 192 && lengthByte < 224) { + packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192; + // 4.2.2.4. Partial Body Lengths + } else if (lengthByte > 223 && lengthByte < 255) { + packetLength = 1 << (lengthByte & 0x1F); + wasPartialLength = true; + if (!packetSupportsStreaming) { + throw new TypeError('This packet type does not support partial lengths.'); + } + // 4.2.2.3. Five-Octet Lengths + } else { + packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() << + 8) | await reader.readByte(); + } } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - if (err instanceof UnsupportedError) throw err; - // avoid throwing potentially sensitive errors - throw new Error('Error reading MPIs'); + if (packetLength > 0) { + let bytesRead = 0; + while (true) { + if (writer) await writer.ready; + const { done, value } = await reader.read(); + if (done) { + if (packetLength === Infinity) break; + throw new Error('Unexpected end of packet'); + } + const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead); + if (writer) await writer.write(chunk); + else packet.push(chunk); + bytesRead += value.length; + if (bytesRead >= packetLength) { + reader.unshift(value.subarray(packetLength - bytesRead + value.length)); + break; + } + } } + } while (wasPartialLength); + + // If this was not a packet that "supports streaming", we peek to check + // whether it is the last packet in the message. We peek 2 bytes instead + // of 1 because the beginning of this function also peeks 2 bytes, and we + // want to cut a `subarray` of the correct length into `web-stream-tools`' + // `externalBuffer` as a tiny optimization here. + // + // If it *was* a streaming packet (i.e. the data packets), we peek at the + // entire remainder of the stream, in order to forward errors in the + // remainder of the stream to the packet data. (Note that this means we + // read/peek at all signature packets before closing the literal data + // packet, for example.) This forwards MDC errors to the literal data + // stream, for example, so that they don't get lost / forgotten on + // decryptedMessage.packets.stream, which we never look at. + // + // An example of what we do when stream-parsing a message containing + // [ one-pass signature packet, literal data packet, signature packet ]: + // 1. Read the one-pass signature packet + // 2. Peek 2 bytes of the literal data packet + // 3. Parse the one-pass signature packet + // + // 4. Read the literal data packet, simultaneously stream-parsing it + // 5. Peek until the end of the message + // 6. Finish parsing the literal data packet + // + // 7. Read the signature packet again (we already peeked at it in step 5) + // 8. Peek at the end of the stream again (`peekBytes` returns undefined) + // 9. Parse the signature packet + // + // Note that this means that if there's an error in the very end of the + // stream, such as an MDC error, we throw in step 5 instead of in step 8 + // (or never), which is the point of this exercise. + const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2); + if (writer) { + await writer.ready; + await writer.close(); + } else { + packet = util.concatUint8Array(packet); + // eslint-disable-next-line callback-return + await callback({ tag, packet }); } - } - - /** - * Creates an OpenPGP key packet for the given key. - * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. - */ - write() { - const serializedPublicKey = this.writePublicKey(); - if (this.unparseableKeyMaterial) { - return util.concatUint8Array([ - serializedPublicKey, - this.unparseableKeyMaterial - ]); + return !nextPacket || !nextPacket.length; + } catch (e) { + if (writer) { + await writer.abort(e); + return true; + } else { + throw e; } - - const arr = [serializedPublicKey]; - arr.push(new Uint8Array([this.s2kUsage])); - - const optionalFieldsArr = []; - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // one- octet symmetric encryption algorithm. - if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { - optionalFieldsArr.push(this.symmetric); - - // - [Optional] If string-to-key usage octet was 253, a one-octet - // AEAD algorithm. - if (this.s2kUsage === 253) { - optionalFieldsArr.push(this.aead); - } - - // - [Optional] If string-to-key usage octet was 255, 254, or 253, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - optionalFieldsArr.push(...this.s2k.write()); + } finally { + if (writer) { + await callbackReturned; } + reader.releaseLock(); + } +} - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { - optionalFieldsArr.push(...this.iv); - } +class UnsupportedError extends Error { + constructor(...params) { + super(...params); - if (this.version === 5) { - arr.push(new Uint8Array([optionalFieldsArr.length])); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - arr.push(new Uint8Array(optionalFieldsArr)); - if (!this.isDummy()) { - if (!this.s2kUsage) { - this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams); - } + this.name = 'UnsupportedError'; + } +} - if (this.version === 5) { - arr.push(util.writeNumber(this.keyMaterial.length, 4)); - } - arr.push(this.keyMaterial); +// unknown packet types are handled differently depending on the packet criticality +class UnknownPacketError extends UnsupportedError { + constructor(...params) { + super(...params); - if (!this.s2kUsage) { - arr.push(util.writeChecksum(this.keyMaterial)); - } + if (Error.captureStackTrace) { + Error.captureStackTrace(this, UnsupportedError); } - return util.concatUint8Array(arr); - } - - /** - * Check whether secret-key data is available in decrypted form. - * Returns false for gnu-dummy keys and null for public keys. - * @returns {Boolean|null} - */ - isDecrypted() { - return this.isEncrypted === false; + this.name = 'UnknownPacketError'; } +} - /** - * Check whether the key includes secret key material. - * Some secret keys do not include it, and can thus only be used - * for public-key operations (encryption and verification). - * Such keys are: - * - GNU-dummy keys, where the secret material has been stripped away - * - encrypted keys with unsupported S2K or cipher - */ - isMissingSecretKeyMaterial() { - return this.unparseableKeyMaterial !== undefined || this.isDummy(); +class UnparseablePacket { + constructor(tag, rawContent) { + this.tag = tag; + this.rawContent = rawContent; } - /** - * Check whether this is a gnu-dummy key - * @returns {Boolean} - */ - isDummy() { - return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + write() { + return this.rawContent; } +} - /** - * Remove private key material, converting the key to a dummy one. - * The resulting key cannot be used for signing/decrypting but can still verify signatures. - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - makeDummy(config$1 = config) { - if (this.isDummy()) { - return; - } - if (this.isDecrypted()) { - this.clearPrivateParams(); - } - delete this.unparseableKeyMaterial; - this.isEncrypted = null; - this.keyMaterial = null; - this.s2k = new S2K(config$1); - this.s2k.algorithm = 0; - this.s2k.c = 0; - this.s2k.type = 'gnu-dummy'; - this.s2kUsage = 254; - this.symmetric = enums.symmetric.aes256; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param {String} passphrase - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if encryption was not successful - * @async - */ - async encrypt(passphrase, config$1 = config) { - if (this.isDummy()) { - return; - } - if (!this.isDecrypted()) { - throw new Error('Key packet is already encrypted'); - } - if (!passphrase) { - throw new Error('A non-empty passphrase is required for key encryption.'); - } +/** + * Generate (non-legacy) EdDSA key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>} + */ +async function generate$3(algo) { + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify']); - this.s2k = new S2K(config$1); - this.s2k.salt = mod.random.getRandomBytes(8); - const cleartext = mod.serializeParams(this.algorithm, this.privateParams); - this.symmetric = enums.symmetric.aes256; - const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); + const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey); - const { blockSize } = mod.getCipher(this.symmetric); - this.iv = mod.random.getRandomBytes(blockSize); + return { + A: new Uint8Array(b64ToUint8Array(publicKey.x)), + seed: b64ToUint8Array(privateKey.d, true) + }; + } catch (err) { + if (err.name !== 'NotSupportedError' && err.name !== 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux + throw err; + } + const seed = getRandomBytes(getPayloadSize$1(algo)); + const { publicKey: A } = nacl.sign.keyPair.fromSeed(seed); + return { A, seed }; + } - if (config$1.aeadProtect) { - this.s2kUsage = 253; - this.aead = enums.aead.eax; - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); - this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array()); - } else { - this.s2kUsage = 254; - this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ - cleartext, - await mod.hash.sha1(cleartext, config$1) - ]), this.iv, config$1); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const seed = ed448.utils.randomPrivateKey(); + const A = ed448.getPublicKey(seed); + return { A, seed }; } + default: + throw new Error('Unsupported EdDSA algorithm'); } +} - /** - * Decrypts the private key params which are needed to use the key. - * Successful decryption does not imply key integrity, call validate() to confirm that. - * {@link SecretKeyPacket.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param {String} passphrase - The passphrase for this private key as string - * @throws {Error} if the key is already decrypted, or if decryption was not successful - * @async - */ - async decrypt(passphrase) { - if (this.isDummy()) { - return false; - } +/** + * Sign a message using the provided key + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * RS: Uint8Array + * }>} Signature of the message + * @async + */ +async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: + try { + const webCrypto = util.getWebCrypto(); + const jwk = privateKeyToJWK(algo, publicKey, privateKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']); - if (this.unparseableKeyMaterial) { - throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); - } + const signature = new Uint8Array( + await webCrypto.sign('Ed25519', key, hashed) + ); - if (this.isDecrypted()) { - throw new Error('Key packet is already decrypted.'); - } + return { RS: signature }; + } catch (err) { + if (err.name !== 'NotSupportedError') { + throw err; + } + const secretKey = util.concatUint8Array([privateKey, publicKey]); + const signature = nacl.sign.detached(hashed, secretKey); + return { RS: signature }; + } - let key; - if (this.s2kUsage === 254 || this.s2kUsage === 253) { - key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric); - } else if (this.s2kUsage === 255) { - throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); - } else { - throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + const signature = ed448.sign(hashed, privateKey); + return { RS: signature }; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } - let cleartext; - if (this.s2kUsage === 253) { - const mode = mod.getAEADMode(this.aead); - const modeInstance = await mode(this.symmetric, key); +} + +/** + * Verifies if a signature is valid for a message + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{ RS: Uint8Array }} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async + */ +async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) { + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(getPreferredHashAlgo$2(algo))) { + // Enforce digest sizes: + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + throw new Error('Hash algorithm too weak for EdDSA.'); + } + switch (algo) { + case enums.publicKey.ed25519: try { - cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array()); + const webCrypto = util.getWebCrypto(); + const jwk = publicKeyToJWK(algo, publicKey); + const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']); + const verified = await webCrypto.verify('Ed25519', key, RS, hashed); + return verified; } catch (err) { - if (err.message === 'Authentication tag mismatch') { - throw new Error('Incorrect key passphrase: ' + err.message); + if (err.name !== 'NotSupportedError') { + throw err; } - throw err; + return nacl.sign.detached.verify(hashed, RS, publicKey); } - } else { - const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); - - cleartext = cleartextWithHash.subarray(0, -20); - const hash = await mod.hash.sha1(cleartext); - - if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { - throw new Error('Incorrect key passphrase'); - } - } - try { - const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); - this.privateParams = privateParams; - } catch (err) { - throw new Error('Error reading MPIs'); + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); + return ed448.verify(RS, hashed, publicKey); } - this.isEncrypted = false; - this.keyMaterial = null; - this.s2kUsage = 0; + default: + throw new Error('Unsupported EdDSA algorithm'); } - - /** - * Checks that the key parameters are consistent - * @throws {Error} if validation was not successful - * @async - */ - async validate() { - if (this.isDummy()) { - return; +} +/** + * Validate (non-legacy) EdDSA parameters + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} A - EdDSA public point + * @param {Uint8Array} seed - EdDSA secret seed + * @param {Uint8Array} oid - (legacy only) EdDSA OID + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$7(algo, A, seed) { + switch (algo) { + case enums.publicKey.ed25519: { + /** + * Derive public point A' from private key + * and expect A == A' + * TODO: move to sign-verify using WebCrypto (same as ECDSA) when curve is more widely implemented + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(seed); + return util.equalsUint8Array(A, publicKey); } - if (!this.isDecrypted()) { - throw new Error('Key is not decrypted'); - } + case enums.publicKey.ed448: { + const ed448 = await util.getNobleCurve(enums.publicKey.ed448); - let validParams; - try { - // this can throw if some parameters are undefined - validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams); - } catch (_) { - validParams = false; - } - if (!validParams) { - throw new Error('Key is invalid'); + const publicKey = ed448.getPublicKey(seed); + return util.equalsUint8Array(A, publicKey); } + default: + return false; } +} - async generate(bits, curve) { - const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve); - this.privateParams = privateParams; - this.publicParams = publicParams; - this.isEncrypted = false; - } +function getPayloadSize$1(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return 32; - /** - * Clear private key parameters - */ - clearPrivateParams() { - if (this.isMissingSecretKeyMaterial()) { - return; - } + case enums.publicKey.ed448: + return 57; - Object.keys(this.privateParams).forEach(name => { - const param = this.privateParams[name]; - param.fill(0); - delete this.privateParams[name]; - }); - this.privateParams = null; - this.isEncrypted = true; + default: + throw new Error('Unsupported EdDSA algorithm'); } } -async function produceEncryptionKey(s2k, passphrase, algorithm) { - const { keySize } = mod.getCipher(algorithm); - return s2k.produceKey(passphrase, keySize); +function getPreferredHashAlgo$2(algo) { + switch (algo) { + case enums.publicKey.ed25519: + return enums.hash.sha256; + case enums.publicKey.ed448: + return enums.hash.sha512; + default: + throw new Error('Unknown EdDSA algo'); + } } -var emailAddresses = createCommonjsModule(function (module) { -// email-addresses.js - RFC 5322 email address parser -// v 3.1.0 -// -// http://tools.ietf.org/html/rfc5322 -// -// This library does not validate email addresses. -// emailAddresses attempts to parse addresses using the (fairly liberal) -// grammar specified in RFC 5322. -// -// email-addresses returns { -// ast: , -// addresses: [{ -// node: , -// name: , -// address: , -// local: , -// domain: -// }, ...] -// } -// -// emailAddresses.parseOneAddress and emailAddresses.parseAddressList -// work as you might expect. Try it out. -// -// Many thanks to Dominic Sayers and his documentation on the is_email function, -// http://code.google.com/p/isemail/ , which helped greatly in writing this parser. - -(function (global) { - -function parse5322(opts) { - - // tokenizing functions - - function inStr() { return pos < len; } - function curTok() { return parseString[pos]; } - function getPos() { return pos; } - function setPos(i) { pos = i; } - function nextTok() { pos += 1; } - function initialize() { - pos = 0; - len = parseString.length; - } - - // parser helper functions - - function o(name, value) { - return { - name: name, - tokens: value || "", - semantic: value || "", - children: [] - }; - } - - function wrap(name, ast) { - var n; - if (ast === null) { return null; } - n = o(name); - n.tokens = ast.tokens; - n.semantic = ast.semantic; - n.children.push(ast); - return n; - } - - function add(parent, child) { - if (child !== null) { - parent.tokens += child.tokens; - parent.semantic += child.semantic; - } - parent.children.push(child); - return parent; +const publicKeyToJWK = (algo, publicKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: uint8ArrayToB64(publicKey), + ext: true + }; + return jwk; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; - function compareToken(fxnCompare) { - var tok; - if (!inStr()) { return null; } - tok = curTok(); - if (fxnCompare(tok)) { - nextTok(); - return o('token', tok); - } - return null; +const privateKeyToJWK = (algo, publicKey, privateKey) => { + switch (algo) { + case enums.publicKey.ed25519: { + const jwk = publicKeyToJWK(algo, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } + default: + throw new Error('Unsupported EdDSA algorithm'); + } +}; - function literal(lit) { - return function literalFunc() { - return wrap('literal', compareToken(function (tok) { - return tok === lit; - })); - }; - } +var eddsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + generate: generate$3, + getPayloadSize: getPayloadSize$1, + getPreferredHashAlgo: getPreferredHashAlgo$2, + sign: sign$5, + validateParams: validateParams$7, + verify: verify$5 +}); - function and() { - var args = arguments; - return function andFunc() { - var i, s, result, start; - start = getPos(); - s = o('and'); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result === null) { - setPos(start); - return null; - } - add(s, result); - } - return s; - }; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function or() { - var args = arguments; - return function orFunc() { - var i, result, start; - start = getPos(); - for (i = 0; i < args.length; i += 1) { - result = args[i](); - if (result !== null) { - return result; - } - setPos(start); - } - return null; - }; - } - function opt(prod) { - return function optFunc() { - var result, start; - start = getPos(); - result = prod(); - if (result !== null) { - return result; - } - else { - setPos(start); - return o('opt'); - } - }; - } +const webCrypto$4 = util.getWebCrypto(); +/** + * AES key wrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} dataToWrap + * @returns {Uint8Array} wrapped key + */ +async function wrap(algo, key, dataToWrap) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - function invis(prod) { - return function invisFunc() { - var result = prod(); - if (result !== null) { - result.semantic = ""; - } - return result; - }; + try { + const wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']); + // Import data as HMAC key, as it has no key length requirements + const keyToWrap = await webCrypto$4.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + const wrapped = await webCrypto$4.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' }); + return new Uint8Array(wrapped); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + } - function colwsp(prod) { - return function collapseSemanticWhitespace() { - var result = prod(); - if (result !== null && result.semantic.length > 0) { - result.semantic = " "; - } - return result; - }; - } + return aeskw(key).encrypt(dataToWrap); +} - function star(prod, minimum) { - return function starFunc() { - var s, result, count, start, min; - start = getPos(); - s = o('star'); - count = 0; - min = minimum === undefined ? 0 : minimum; - while ((result = prod()) !== null) { - count = count + 1; - add(s, result); - } - if (count >= min) { - return s; - } - else { - setPos(start); - return null; - } - }; - } +/** + * AES key unwrap + * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo + * @param {Uint8Array} key - wrapping key + * @param {Uint8Array} wrappedData + * @returns {Uint8Array} unwrapped data + */ +async function unwrap(algo, key, wrappedData) { + const { keySize } = getCipherParams(algo); + // sanity checks, since WebCrypto does not use the `algo` input + if (!util.isAES(algo) || key.length !== keySize) { + throw new Error('Unexpected algorithm or key size'); + } - // One expects names to get normalized like this: - // " First Last " -> "First Last" - // "First Last" -> "First Last" - // "First Last" -> "First Last" - function collapseWhitespace(s) { - return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, ''); + let wrappingKey; + try { + wrappingKey = await webCrypto$4.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']); + } catch (err) { + // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support + if (err.name !== 'NotSupportedError' && + !(key.length === 24 && err.name === 'OperationError')) { + throw err; } + util.printDebugError('Browser did not support operation: ' + err.message); + return aeskw(key).decrypt(wrappedData); + } - // UTF-8 pseudo-production (RFC 6532) - // RFC 6532 extends RFC 5322 productions to include UTF-8 - // using the following productions: - // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - // UTF8-2 = - // UTF8-3 = - // UTF8-4 = - // - // For reference, the extended RFC 5322 productions are: - // VCHAR =/ UTF8-non-ascii - // ctext =/ UTF8-non-ascii - // atext =/ UTF8-non-ascii - // qtext =/ UTF8-non-ascii - // dtext =/ UTF8-non-ascii - function isUTF8NonAscii(tok) { - // In JavaScript, we just deal directly with Unicode code points, - // so we aren't checking individual bytes for UTF-8 encoding. - // Just check that the character is non-ascii. - return tok.charCodeAt(0) >= 128; - } - - - // common productions (RFC 5234) - // http://tools.ietf.org/html/rfc5234 - // B.1. Core Rules - - // CR = %x0D - // ; carriage return - function cr() { return wrap('cr', literal('\r')()); } - - // CRLF = CR LF - // ; Internet standard newline - function crlf() { return wrap('crlf', and(cr, lf)()); } - - // DQUOTE = %x22 - // ; " (Double Quote) - function dquote() { return wrap('dquote', literal('"')()); } - - // HTAB = %x09 - // ; horizontal tab - function htab() { return wrap('htab', literal('\t')()); } - - // LF = %x0A - // ; linefeed - function lf() { return wrap('lf', literal('\n')()); } - - // SP = %x20 - function sp() { return wrap('sp', literal(' ')()); } - - // VCHAR = %x21-7E - // ; visible (printing) characters - function vchar() { - return wrap('vchar', compareToken(function vcharFunc(tok) { - var code = tok.charCodeAt(0); - var accept = (0x21 <= code && code <= 0x7E); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); + try { + const unwrapped = await webCrypto$4.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + return new Uint8Array(await webCrypto$4.exportKey('raw', unwrapped)); + } catch (err) { + if (err.name === 'OperationError') { + throw new Error('Key Data Integrity failed'); } + throw err; + } +} - // WSP = SP / HTAB - // ; white space - function wsp() { return wrap('wsp', or(sp, htab)()); } - - - // email productions (RFC 5322) - // http://tools.ietf.org/html/rfc5322 - // 3.2.1. Quoted characters - - // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp - function quotedPair() { - var qp = wrap('quoted-pair', - or( - and(literal('\\'), or(vchar, wsp)), - obsQP - )()); - if (qp === null) { return null; } - // a quoted pair will be two characters, and the "\" character - // should be semantically "invisible" (RFC 5322 3.2.1) - qp.semantic = qp.semantic[1]; - return qp; - } - - // 3.2.2. Folding White Space and Comments - - // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS - function fws() { - return wrap('fws', or( - obsFws, - and( - opt(and( - star(wsp), - invis(crlf) - )), - star(wsp, 1) - ) - )()); - } - - // ctext = %d33-39 / ; Printable US-ASCII - // %d42-91 / ; characters not including - // %d93-126 / ; "(", ")", or "\" - // obs-ctext - function ctext() { - return wrap('ctext', or( - function ctextFunc1() { - return compareToken(function ctextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 39) || - (42 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsCtext - )()); - } - - // ccontent = ctext / quoted-pair / comment - function ccontent() { - return wrap('ccontent', or(ctext, quotedPair, comment)()); - } - - // comment = "(" *([FWS] ccontent) [FWS] ")" - function comment() { - return wrap('comment', and( - literal('('), - star(and(opt(fws), ccontent)), - opt(fws), - literal(')') - )()); - } - - // CFWS = (1*([FWS] comment) [FWS]) / FWS - function cfws() { - return wrap('cfws', or( - and( - star( - and(opt(fws), comment), - 1 - ), - opt(fws) - ), - fws - )()); - } - - // 3.2.3. Atom - - //atext = ALPHA / DIGIT / ; Printable US-ASCII - // "!" / "#" / ; characters not including - // "$" / "%" / ; specials. Used for atoms. - // "&" / "'" / - // "*" / "+" / - // "-" / "/" / - // "=" / "?" / - // "^" / "_" / - // "`" / "{" / - // "|" / "}" / - // "~" - function atext() { - return wrap('atext', compareToken(function atextFunc(tok) { - var accept = - ('a' <= tok && tok <= 'z') || - ('A' <= tok && tok <= 'Z') || - ('0' <= tok && tok <= '9') || - (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', - '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - })); - } +var aesKW = /*#__PURE__*/Object.freeze({ + __proto__: null, + unwrap: unwrap, + wrap: wrap +}); - // atom = [CFWS] 1*atext [CFWS] - function atom() { - return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))()); - } +/** + * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API. + * @module crypto/hkdf + */ - // dot-atom-text = 1*atext *("." 1*atext) - function dotAtomText() { - var s, maybeText; - s = wrap('dot-atom-text', star(atext, 1)()); - if (s === null) { return s; } - maybeText = star(and(literal('.'), star(atext, 1)))(); - if (maybeText !== null) { - add(s, maybeText); - } - return s; - } - - // dot-atom = [CFWS] dot-atom-text [CFWS] - function dotAtom() { - return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))()); - } - - // 3.2.4. Quoted Strings - - // qtext = %d33 / ; Printable US-ASCII - // %d35-91 / ; characters not including - // %d93-126 / ; "\" or the quote character - // obs-qtext - function qtext() { - return wrap('qtext', or( - function qtextFunc1() { - return compareToken(function qtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 === code) || - (35 <= code && code <= 91) || - (93 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsQtext - )()); - } - // qcontent = qtext / quoted-pair - function qcontent() { - return wrap('qcontent', or(qtext, quotedPair)()); - } +const webCrypto$3 = util.getWebCrypto(); - // quoted-string = [CFWS] - // DQUOTE *([FWS] qcontent) [FWS] DQUOTE - // [CFWS] - function quotedString() { - return wrap('quoted-string', and( - invis(opt(cfws)), - invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), - invis(opt(cfws)) - )()); - } +async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) { + const hash = enums.read(enums.webHash, hashAlgo); + if (!hash) throw new Error('Hash algo not supported with HKDF'); - // 3.2.5 Miscellaneous Tokens + const importedKey = await webCrypto$3.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']); + const bits = await webCrypto$3.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8); + return new Uint8Array(bits); +} - // word = atom / quoted-string - function word() { - return wrap('word', or(atom, quotedString)()); - } +/** + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @module crypto/public_key/elliptic/ecdh + */ - // phrase = 1*word / obs-phrase - function phrase() { - return wrap('phrase', or(obsPhrase, star(word, 1))()); - } - // 3.4. Address Specification - // address = mailbox / group - function address() { - return wrap('address', or(mailbox, group)()); - } +const HKDF_INFO = { + x25519: util.encodeUTF8('OpenPGP X25519'), + x448: util.encodeUTF8('OpenPGP X448') +}; - // mailbox = name-addr / addr-spec - function mailbox() { - return wrap('mailbox', or(nameAddr, addrSpec)()); +/** + * Generate ECDH key for Montgomery curves + * @param {module:enums.publicKey} algo - Algorithm identifier + * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>} + */ +async function generate$2(algo) { + switch (algo) { + case enums.publicKey.x25519: { + // k stays in little-endian, unlike legacy ECDH over curve25519 + const k = getRandomBytes(32); + const { publicKey: A } = nacl.box.keyPair.fromSecretKey(k); + return { A, k }; } - // name-addr = [display-name] angle-addr - function nameAddr() { - return wrap('name-addr', and(opt(displayName), angleAddr)()); + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const k = x448.utils.randomPrivateKey(); + const A = x448.getPublicKey(k); + return { A, k }; } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / - // obs-angle-addr - function angleAddr() { - return wrap('angle-addr', or( - and( - invis(opt(cfws)), - literal('<'), - addrSpec, - literal('>'), - invis(opt(cfws)) - ), - obsAngleAddr - )()); +/** +* Validate ECDH parameters +* @param {module:enums.publicKey} algo - Algorithm identifier +* @param {Uint8Array} A - ECDH public point +* @param {Uint8Array} k - ECDH secret scalar +* @returns {Promise} Whether params are valid. +* @async +*/ +async function validateParams$6(algo, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + /** + * Derive public point A' from private key + * and expect A == A' + */ + const { publicKey } = nacl.box.keyPair.fromSecretKey(k); + return util.equalsUint8Array(A, publicKey); } - - // group = display-name ":" [group-list] ";" [CFWS] - function group() { - return wrap('group', and( - displayName, - literal(':'), - opt(groupList), - literal(';'), - invis(opt(cfws)) - )()); + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + /** + * Derive public point A' from private key + * and expect A == A' + */ + const publicKey = x448.getPublicKey(k); + return util.equalsUint8Array(A, publicKey); } - // display-name = phrase - function displayName() { - return wrap('display-name', function phraseFixedSemantic() { - var result = phrase(); - if (result !== null) { - result.semantic = collapseWhitespace(result.semantic); - } - return result; - }()); - } - - // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list - function mailboxList() { - return wrap('mailbox-list', or( - and( - mailbox, - star(and(literal(','), mailbox)) - ), - obsMboxList - )()); - } - - // address-list = (address *("," address)) / obs-addr-list - function addressList() { - return wrap('address-list', or( - and( - address, - star(and(literal(','), address)) - ), - obsAddrList - )()); - } - - // group-list = mailbox-list / CFWS / obs-group-list - function groupList() { - return wrap('group-list', or( - mailboxList, - invis(cfws), - obsGroupList - )()); - } - - // 3.4.1 Addr-Spec Specification - - // local-part = dot-atom / quoted-string / obs-local-part - function localPart() { - // note: quoted-string, dotAtom are proper subsets of obs-local-part - // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree - return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)()); - } - - // dtext = %d33-90 / ; Printable US-ASCII - // %d94-126 / ; characters not including - // obs-dtext ; "[", "]", or "\" - function dtext() { - return wrap('dtext', or( - function dtextFunc1() { - return compareToken(function dtextFunc2(tok) { - var code = tok.charCodeAt(0); - var accept = - (33 <= code && code <= 90) || - (94 <= code && code <= 126); - if (opts.rfc6532) { - accept = accept || isUTF8NonAscii(tok); - } - return accept; - }); - }, - obsDtext - )() - ); - } + default: + return false; + } +} - // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - function domainLiteral() { - return wrap('domain-literal', and( - invis(opt(cfws)), - literal('['), - star(and(opt(fws), dtext)), - opt(fws), - literal(']'), - invis(opt(cfws)) - )()); - } - - // domain = dot-atom / domain-literal / obs-domain - function domain() { - return wrap('domain', function domainCheckTLD() { - var result = or(obsDomain, dotAtom, domainLiteral)(); - if (opts.rejectTLD) { - if (result && result.semantic && result.semantic.indexOf('.') < 0) { - return null; - } - } - // strip all whitespace from domains - if (result) { - result.semantic = result.semantic.replace(/\s+/g, ''); - } - return result; - }()); - } - - // addr-spec = local-part "@" domain - function addrSpec() { - return wrap('addr-spec', and( - localPart, literal('@'), domain - )()); - } - - // 3.6.2 Originator Fields - // Below we only parse the field body, not the name of the field - // like "From:", "Sender:", or "Reply-To:". Other libraries that - // parse email headers can parse those and defer to these productions - // for the "RFC 5322" part. - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // from = "From:" (mailbox-list / address-list) CRLF - function fromSpec() { - return wrap('from', or( - mailboxList, - addressList - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // sender = "Sender:" (mailbox / address) CRLF - function senderSpec() { - return wrap('sender', or( - mailbox, - address - )()); - } - - // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields - // reply-to = "Reply-To:" address-list CRLF - function replyToSpec() { - return wrap('reply-to', addressList()); - } - - // 4.1. Miscellaneous Obsolete Tokens - - // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control - // %d11 / ; characters that do not - // %d12 / ; include the carriage - // %d14-31 / ; return, line feed, and - // %d127 ; white space characters - function obsNoWsCtl() { - return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) { - var code = tok.charCodeAt(0); - return ((1 <= code && code <= 8) || - (11 === code || 12 === code) || - (14 <= code && code <= 31) || - (127 === code)); - })); +/** + * Wrap and encrypt a session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} data - session key data to be encrypted + * @param {Uint8Array} recipientA - Recipient public key (K_B) + * @returns {Promise<{ + * ephemeralPublicKey: Uint8Array, + * wrappedKey: Uint8Array + * }>} ephemeral public key (K_A) and encrypted key + * @async + */ +async function encrypt$2(algo, data, recipientA) { + const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + recipientA, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; } - - // obs-ctext = obs-NO-WS-CTL - function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); } - - // obs-qtext = obs-NO-WS-CTL - function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); } - - // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR) - function obsQP() { - return opts.strict ? null : wrap('obs-qp', and( - literal('\\'), - or(literal('\0'), obsNoWsCtl, lf, cr) - )()); - } - - // obs-phrase = word *(word / "." / CFWS) - function obsPhrase() { - if (opts.strict ) return null; - return opts.atInDisplayName ? wrap('obs-phrase', and( - word, - star(or(word, literal('.'), literal('@'), colwsp(cfws))) - )()) : - wrap('obs-phrase', and( - word, - star(or(word, literal('.'), colwsp(cfws))) - )()); - } - - // 4.2. Obsolete Folding White Space - - // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908 - // obs-FWS = 1*([CRLF] WSP) - function obsFws() { - return opts.strict ? null : wrap('obs-FWS', star( - and(invis(opt(crlf)), wsp), - 1 - )()); - } - - // 4.4. Obsolete Addressing - - // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] - function obsAngleAddr() { - return opts.strict ? null : wrap('obs-angle-addr', and( - invis(opt(cfws)), - literal('<'), - obsRoute, - addrSpec, - literal('>'), - invis(opt(cfws)) - )()); - } - - // obs-route = obs-domain-list ":" - function obsRoute() { - return opts.strict ? null : wrap('obs-route', and( - obsDomainList, - literal(':') - )()); - } - - // obs-domain-list = *(CFWS / ",") "@" domain - // *("," [CFWS] ["@" domain]) - function obsDomainList() { - return opts.strict ? null : wrap('obs-domain-list', and( - star(or(invis(cfws), literal(','))), - literal('@'), - domain, - star(and( - literal(','), - invis(opt(cfws)), - opt(and(literal('@'), domain)) - )) - )()); - } - - // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) - function obsMboxList() { - return opts.strict ? null : wrap('obs-mbox-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - mailbox, - star(and( - literal(','), - opt(and( - mailbox, - invis(cfws) - )) - )) - )()); - } - - // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) - function obsAddrList() { - return opts.strict ? null : wrap('obs-addr-list', and( - star(and( - invis(opt(cfws)), - literal(',') - )), - address, - star(and( - literal(','), - opt(and( - address, - invis(cfws) - )) - )) - )()); - } - - // obs-group-list = 1*([CFWS] ",") [CFWS] - function obsGroupList() { - return opts.strict ? null : wrap('obs-group-list', and( - star(and( - invis(opt(cfws)), - literal(',') - ), 1), - invis(opt(cfws)) - )()); - } - - // obs-local-part = word *("." word) - function obsLocalPart() { - return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))()); - } - - // obs-domain = atom *("." atom) - function obsDomain() { - return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))()); - } - - // obs-dtext = obs-NO-WS-CTL / quoted-pair - function obsDtext() { - return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)()); - } - - ///////////////////////////////////////////////////// - - // ast analysis - - function findNode(name, root) { - var i, stack, node; - if (root === null || root === undefined) { return null; } - stack = [root]; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - return node; - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return null; - } - - function findAllNodes(name, root) { - var i, stack, node, result; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - while (stack.length > 0) { - node = stack.pop(); - if (node.name === name) { - result.push(node); - } - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - return result; + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + const wrappedKey = await wrap(cipherAlgo, encryptionKey, data); + return { ephemeralPublicKey, wrappedKey }; } - function findAllNodesNoChildren(names, root) { - var i, stack, node, result, namesLookup; - if (root === null || root === undefined) { return null; } - stack = [root]; - result = []; - namesLookup = {}; - for (i = 0; i < names.length; i += 1) { - namesLookup[names[i]] = true; - } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - while (stack.length > 0) { - node = stack.pop(); - if (node.name in namesLookup) { - result.push(node); - // don't look at children (hence findAllNodesNoChildren) - } else { - for (i = node.children.length - 1; i >= 0; i -= 1) { - stack.push(node.children[i]); - } - } - } - return result; +/** + * Decrypt and unwrap the session key + * + * @param {module:enums.publicKey} algo - Algorithm identifier + * @param {Uint8Array} ephemeralPublicKey - (K_A) + * @param {Uint8Array} wrappedKey, + * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF + * @param {Uint8Array} k - Recipient secret key (b) + * @returns {Promise} decrypted session key data + * @async + */ +async function decrypt$2(algo, ephemeralPublicKey, wrappedKey, A, k) { + const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k); + const hkdfInput = util.concatUint8Array([ + ephemeralPublicKey, + A, + sharedSecret + ]); + switch (algo) { + case enums.publicKey.x25519: { + const cipherAlgo = enums.symmetric.aes128; + const { keySize } = getCipherParams(cipherAlgo); + const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); } - - function giveResult(ast) { - var addresses, groupsAndMailboxes, i, groupOrMailbox, result; - if (ast === null) { - return null; - } - addresses = []; - - // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'. - groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast); - for (i = 0; i < groupsAndMailboxes.length; i += 1) { - groupOrMailbox = groupsAndMailboxes[i]; - if (groupOrMailbox.name === 'group') { - addresses.push(giveResultGroup(groupOrMailbox)); - } else if (groupOrMailbox.name === 'mailbox') { - addresses.push(giveResultMailbox(groupOrMailbox)); - } - } - - result = { - ast: ast, - addresses: addresses, - }; - if (opts.simple) { - result = simplifyResult(result); - } - if (opts.oneResult) { - return oneResult(result); - } - if (opts.simple) { - return result && result.addresses; - } else { - return result; - } + case enums.publicKey.x448: { + const cipherAlgo = enums.symmetric.aes256; + const { keySize } = getCipherParams(enums.symmetric.aes256); + const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize); + return unwrap(cipherAlgo, encryptionKey, wrappedKey); } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - function giveResultGroup(group) { - var i; - var groupName = findNode('display-name', group); - var groupResultMailboxes = []; - var mailboxes = findAllNodesNoChildren(['mailbox'], group); - for (i = 0; i < mailboxes.length; i += 1) { - groupResultMailboxes.push(giveResultMailbox(mailboxes[i])); - } - return { - node: group, - parts: { - name: groupName, - }, - type: group.name, // 'group' - name: grabSemantic(groupName), - addresses: groupResultMailboxes, - }; - } +function getPayloadSize(algo) { + switch (algo) { + case enums.publicKey.x25519: + return 32; - function giveResultMailbox(mailbox) { - var name = findNode('display-name', mailbox); - var aspec = findNode('addr-spec', mailbox); - var cfws = findAllNodes('cfws', mailbox); - var comments = findAllNodesNoChildren(['comment'], mailbox); + case enums.publicKey.x448: + return 56; + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - var local = findNode('local-part', aspec); - var domain = findNode('domain', aspec); - return { - node: mailbox, - parts: { - name: name, - address: aspec, - local: local, - domain: domain, - comments: cfws - }, - type: mailbox.name, // 'mailbox' - name: grabSemantic(name), - address: grabSemantic(aspec), - local: grabSemantic(local), - domain: grabSemantic(domain), - comments: concatComments(comments), - groupName: grabSemantic(mailbox.groupName), - }; +/** + * Generate shared secret and ephemeral public key for encryption + * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret + * @async + */ +async function generateEphemeralEncryptionMaterial(algo, recipientA) { + switch (algo) { + case enums.publicKey.x25519: { + const ephemeralSecretKey = getRandomBytes(getPayloadSize(algo)); + const sharedSecret = nacl.scalarMult(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const { publicKey: ephemeralPublicKey } = nacl.box.keyPair.fromSecretKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; + } + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const ephemeralSecretKey = x448.utils.randomPrivateKey(); + const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA); + assertNonZeroArray(sharedSecret); + const ephemeralPublicKey = x448.getPublicKey(ephemeralSecretKey); + return { ephemeralPublicKey, sharedSecret }; } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - function grabSemantic(n) { - return n !== null && n !== undefined ? n.semantic : null; +async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) { + switch (algo) { + case enums.publicKey.x25519: { + const sharedSecret = nacl.scalarMult(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; } - - function simplifyResult(result) { - var i; - if (result && result.addresses) { - for (i = 0; i < result.addresses.length; i += 1) { - delete result.addresses[i].node; - } - } - return result; + case enums.publicKey.x448: { + const x448 = await util.getNobleCurve(enums.publicKey.x448); + const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey); + assertNonZeroArray(sharedSecret); + return sharedSecret; } + default: + throw new Error('Unsupported ECDH algorithm'); + } +} - function concatComments(comments) { - var result = ''; - if (comments) { - for (var i = 0; i < comments.length; i += 1) { - result += grabSemantic(comments[i]); - } - } - return result; - } +/** + * x25519 and x448 produce an all-zero value when given as input a point with small order. + * This does not lead to a security issue in the context of ECDH, but it is still unexpected, + * hence we throw. + * @param {Uint8Array} sharedSecret + */ +function assertNonZeroArray(sharedSecret) { + let acc = 0; + for (let i = 0; i < sharedSecret.length; i++) { + acc |= sharedSecret[i]; + } + if (acc === 0) { + throw new Error('Unexpected low order point'); + } +} - function oneResult(result) { - if (!result) { return null; } - if (!opts.partial && result.addresses.length > 1) { return null; } - return result.addresses && result.addresses[0]; - } +var ecdh_x = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$2, + encrypt: encrypt$2, + generate: generate$2, + generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial, + getPayloadSize: getPayloadSize, + recomputeSharedSecret: recomputeSharedSecret, + validateParams: validateParams$6 +}); - ///////////////////////////////////////////////////// +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - var parseString, pos, len, parsed, startProduction; - opts = handleOpts(opts, {}); - if (opts === null) { return null; } +const webCrypto$2 = util.getWebCrypto(); +const nodeCrypto$2 = util.getNodeCrypto(); - parseString = opts.input; +const webCurves = { + [enums.curve.nistP256]: 'P-256', + [enums.curve.nistP384]: 'P-384', + [enums.curve.nistP521]: 'P-521' +}; +const knownCurves = nodeCrypto$2 ? nodeCrypto$2.getCurves() : []; +const nodeCurves = nodeCrypto$2 ? { + [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined, + [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined, + [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined, + [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined, + [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined, + [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined, + [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined, + [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined, + [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined +} : {}; - startProduction = { - 'address': address, - 'address-list': addressList, - 'angle-addr': angleAddr, - 'from': fromSpec, - 'group': group, - 'mailbox': mailbox, - 'mailbox-list': mailboxList, - 'reply-to': replyToSpec, - 'sender': senderSpec, - }[opts.startAt] || addressList; +const curves = { + [enums.curve.nistP256]: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.nistP256], + web: webCurves[enums.curve.nistP256], + payloadSize: 32, + sharedSize: 256, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP384]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.nistP384], + web: webCurves[enums.curve.nistP384], + payloadSize: 48, + sharedSize: 384, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.nistP521]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.nistP521], + web: webCurves[enums.curve.nistP521], + payloadSize: 66, + sharedSize: 528, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.secp256k1]: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.secp256k1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.ed25519Legacy]: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: enums.publicKey.eddsaLegacy, + hash: enums.hash.sha512, + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.curve25519Legacy]: { + oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: enums.publicKey.ecdh, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32, + wireFormatLeadingByte: 0x40 + }, + [enums.curve.brainpoolP256r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha256, + cipher: enums.symmetric.aes128, + node: nodeCurves[enums.curve.brainpoolP256r1], + payloadSize: 32, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP384r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha384, + cipher: enums.symmetric.aes192, + node: nodeCurves[enums.curve.brainpoolP384r1], + payloadSize: 48, + wireFormatLeadingByte: 0x04 + }, + [enums.curve.brainpoolP512r1]: { + oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], + keyType: enums.publicKey.ecdsa, + hash: enums.hash.sha512, + cipher: enums.symmetric.aes256, + node: nodeCurves[enums.curve.brainpoolP512r1], + payloadSize: 64, + wireFormatLeadingByte: 0x04 + } +}; - if (!opts.strict) { - initialize(); - opts.strict = true; - parsed = startProduction(parseString); - if (opts.partial || !inStr()) { - return giveResult(parsed); - } - opts.strict = false; +class CurveWithOID { + constructor(oidOrName) { + try { + this.name = oidOrName instanceof OID ? + oidOrName.getName() : + enums.write(enums.curve,oidOrName); + } catch (err) { + throw new UnsupportedError('Unknown curve'); } + const params = curves[this.name]; - initialize(); - parsed = startProduction(parseString); - if (!opts.partial && inStr()) { return null; } - return giveResult(parsed); -} - -function parseOneAddressSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} + this.keyType = params.keyType; -function parseAddressListSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'address-list', - })); -} + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node; + this.web = params.web; + this.payloadSize = params.payloadSize; + this.sharedSize = params.sharedSize; + this.wireFormatLeadingByte = params.wireFormatLeadingByte; + if (this.web && util.getWebCrypto()) { + this.type = 'web'; + } else if (this.node && util.getNodeCrypto()) { + this.type = 'node'; + } else if (this.name === enums.curve.curve25519Legacy) { + this.type = 'curve25519Legacy'; + } else if (this.name === enums.curve.ed25519Legacy) { + this.type = 'ed25519Legacy'; + } + } -function parseFromSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'from', - })); + async genKeyPair() { + switch (this.type) { + case 'web': + try { + return await webGenKeyPair(this.name, this.wireFormatLeadingByte); + } catch (err) { + util.printDebugError('Browser did not support generating ec key ' + err.message); + return jsGenKeyPair(this.name); + } + case 'node': + return nodeGenKeyPair(this.name); + case 'curve25519Legacy': { + // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3 + const { k, A } = await generate$2(enums.publicKey.x25519); + const privateKey = k.slice().reverse(); + privateKey[0] = (privateKey[0] & 127) | 64; + privateKey[31] &= 248; + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + case 'ed25519Legacy': { + const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519); + const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]); + return { publicKey, privateKey }; + } + default: + return jsGenKeyPair(this.name); + } + } } -function parseSenderSimple(opts) { - return parse5322(handleOpts(opts, { - oneResult: true, - rfc6532: true, - simple: true, - startAt: 'sender', - })); +async function generate$1(curveName) { + const curve = new CurveWithOID(curveName); + const { oid, hash, cipher } = curve; + const keyPair = await curve.genKeyPair(); + return { + oid, + Q: keyPair.publicKey, + secret: util.leftPad(keyPair.privateKey, curve.payloadSize), + hash, + cipher + }; } -function parseReplyToSimple(opts) { - return parse5322(handleOpts(opts, { - rfc6532: true, - simple: true, - startAt: 'reply-to', - })); +/** + * Get preferred hash algo to use with the given curve + * @param {module:type/oid} oid - curve oid + * @returns {enums.hash} hash algorithm + */ +function getPreferredHashAlgo$1(oid) { + return curves[oid.getName()].hash; } -function handleOpts(opts, defs) { - function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; - } - - function isObject(o) { - return o === Object(o); - } +/** + * Validate ECDH and ECDSA parameters + * Not suitable for EdDSA (different secret key format) + * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves + * @param {module:type/oid} oid - EC object identifier + * @param {Uint8Array} Q - EC public point + * @param {Uint8Array} d - EC secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateStandardParams(algo, oid, Q, d) { + const supportedCurves = { + [enums.curve.nistP256]: true, + [enums.curve.nistP384]: true, + [enums.curve.nistP521]: true, + [enums.curve.secp256k1]: true, + [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh, + [enums.curve.brainpoolP256r1]: true, + [enums.curve.brainpoolP384r1]: true, + [enums.curve.brainpoolP512r1]: true + }; - function isNullUndef(o) { - return o === null || o === undefined; - } + // Check whether the given curve is supported + const curveName = oid.getName(); + if (!supportedCurves[curveName]) { + return false; + } - var defaults, o; + if (curveName === enums.curve.curve25519Legacy) { + d = d.slice().reverse(); + // Re-derive public point Q' + const { publicKey } = nacl.box.keyPair.fromSecretKey(d); - if (isString(opts)) { - opts = { input: opts }; - } else if (!isObject(opts)) { - return null; + Q = new Uint8Array(Q); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + if (!util.equalsUint8Array(dG, Q)) { + return false; } - if (!isString(opts.input)) { return null; } - if (!defs) { return null; } - - defaults = { - oneResult: false, - partial: false, - rejectTLD: false, - rfc6532: false, - simple: false, - startAt: 'address-list', - strict: false, - atInDisplayName: false - }; - - for (o in defaults) { - if (isNullUndef(opts[o])) { - opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o]; - } - } - return opts; -} + return true; + } -parse5322.parseOneAddress = parseOneAddressSimple; -parse5322.parseAddressList = parseAddressListSimple; -parse5322.parseFrom = parseFromSimple; -parse5322.parseSender = parseSenderSimple; -parse5322.parseReplyTo = parseReplyToSimple; + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + /* + * Re-derive public point Q' = dG from private key + * Expect Q == Q' + */ + const dG = nobleCurve.getPublicKey(d, false); + if (!util.equalsUint8Array(dG, Q)) { + return false; + } -{ - module.exports = parse5322; + return true; } -}()); -}); - -// GPG4Browsers - An OpenPGP implementation in javascript - /** - * Implementation of the User ID Packet (Tag 13) - * - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. + * Check whether the public point has a valid encoding. + * NB: this function does not check e.g. whether the point belongs to the curve. */ -class UserIDPacket { - static get tag() { - return enums.packet.userID; - } +function checkPublicPointEnconding(curve, V) { + const { payloadSize, wireFormatLeadingByte, name: curveName } = curve; - constructor() { - /** A string containing the user id. Usually in the form - * John Doe - * @type {String} - */ - this.userID = ''; + const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2; - this.name = ''; - this.email = ''; - this.comment = ''; + if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) { + throw new Error('Invalid point encoding'); } +} - /** - * Create UserIDPacket instance from object - * @param {Object} userID - Object specifying userID name, email and comment - * @returns {UserIDPacket} - * @static - */ - static fromObject(userID) { - if (util.isString(userID) || - (userID.name && !util.isString(userID.name)) || - (userID.email && !util.isEmailAddress(userID.email)) || - (userID.comment && !util.isString(userID.comment))) { - throw new Error('Invalid user ID format'); - } - const packet = new UserIDPacket(); - Object.assign(packet, userID); - const components = []; - if (packet.name) components.push(packet.name); - if (packet.comment) components.push(`(${packet.comment})`); - if (packet.email) components.push(`<${packet.email}>`); - packet.userID = components.join(' '); - return packet; - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// +async function jsGenKeyPair(name) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves + const privateKey = nobleCurve.utils.randomPrivateKey(); + const publicKey = nobleCurve.getPublicKey(privateKey, false); + return { publicKey, privateKey }; +} - /** - * Parsing function for a user id packet (tag 13). - * @param {Uint8Array} input - Payload of a tag 13 packet - */ - read(bytes, config$1 = config) { - const userID = util.decodeUTF8(bytes); - if (userID.length > config$1.maxUserIDLength) { - throw new Error('User ID string is too long'); - } - try { - const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true }); - this.comment = comments.replace(/^\(|\)$/g, ''); - this.name = name; - this.email = email; - } catch (e) {} - this.userID = userID; - } +async function webGenKeyPair(name, wireFormatLeadingByte) { + // Note: keys generated with ECDSA and ECDH are structurally equivalent + const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']); - /** - * Creates a binary representation of the user id packet - * @returns {Uint8Array} Binary representation. - */ - write() { - return util.encodeUTF8(this.userID); - } + const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey); + const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey); - equals(otherUserID) { - return otherUserID && otherUserID.userID === this.userID; - } + return { + publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte), + privateKey: b64ToUint8Array(privateKey.d) + }; } -// GPG4Browsers - An OpenPGP implementation in javascript +async function nodeGenKeyPair(name) { + // Note: ECDSA and ECDH key generation is structurally equivalent + const ecdh = nodeCrypto$2.createECDH(nodeCurves[name]); + await ecdh.generateKeys(); + return { + publicKey: new Uint8Array(ecdh.getPublicKey()), + privateKey: new Uint8Array(ecdh.getPrivateKey()) + }; +} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// /** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - * @extends SecretKeyPacket + * @param {JsonWebKey} jwk - key for conversion + * + * @returns {Uint8Array} Raw public key. */ -class SecretSubkeyPacket extends SecretKeyPacket { - static get tag() { - return enums.packet.secretSubkey; - } - - /** - * @param {Date} [date] - Creation date - * @param {Object} [config] - Full configuration, defaults to openpgp.config - */ - constructor(date = new Date(), config$1 = config) { - super(date, config$1); - } +function jwkToRawPublic(jwk, wireFormatLeadingByte) { + const bufX = b64ToUint8Array(jwk.x); + const bufY = b64ToUint8Array(jwk.y); + const publicKey = new Uint8Array(bufX.length + bufY.length + 1); + publicKey[0] = wireFormatLeadingByte; + publicKey.set(bufX, 1); + publicKey.set(bufY, bufX.length + 1); + return publicKey; } /** - * Implementation of the Trust Packet (Tag 12) - * - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key * - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. + * @returns {JsonWebKey} Public key in jwk format. */ -class TrustPacket { - static get tag() { - return enums.packet.trust; - } - - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - */ - read() { - throw new UnsupportedError('Trust packets are not supported'); - } +function rawPublicToJWK(payloadSize, name, publicKey) { + const len = payloadSize; + const bufX = publicKey.slice(1, len + 1); + const bufY = publicKey.slice(len + 1, len * 2 + 1); + // https://www.rfc-editor.org/rfc/rfc7518.txt + const jwk = { + kty: 'EC', + crv: name, + x: uint8ArrayToB64(bufX), + y: uint8ArrayToB64(bufY), + ext: true + }; + return jwk; +} - write() { - throw new UnsupportedError('Trust packets are not supported'); - } +/** + * @param {Integer} payloadSize - ec payload size + * @param {String} name - curve name + * @param {Uint8Array} publicKey - public key + * @param {Uint8Array} privateKey - private key + * + * @returns {JsonWebKey} Private key in jwk format. + */ +function privateToJWK(payloadSize, name, publicKey, privateKey) { + const jwk = rawPublicToJWK(payloadSize, name, publicKey); + jwk.d = uint8ArrayToB64(privateKey); + return jwk; } -// GPG4Browsers - An OpenPGP implementation in javascript +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// A Signature can contain the following packets -const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + +const webCrypto$1 = util.getWebCrypto(); +const nodeCrypto$1 = util.getNodeCrypto(); /** - * Class that represents an OpenPGP signature. + * Sign a message using the provided key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async */ -class Signature { - /** - * @param {PacketList} packetlist - The signature packets - */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); - } - - /** - * Returns binary encoded signature - * @returns {ReadableStream} Binary signature. - */ - write() { - return this.packets.write(); - } - - /** - * Returns ASCII armored text of signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1); +async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (message && !util.isStream(message)) { + const keyPair = { publicKey, privateKey }; + switch (curve.type) { + case 'web': + // If browser doesn't support a curve, we'll catch it + try { + // Need to await to make sure browser succeeds + return await webSign(curve, hashAlgo, message, keyPair); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunaley Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support signing: ' + err.message); + } + break; + case 'node': + return nodeSign(curve, hashAlgo, message, privateKey); + } } - /** - * Returns an array of KeyIDs of all of the issuers who created this signature - * @returns {Array} The Key IDs of the signing keys - */ - getSigningKeyIDs() { - return this.packets.map(packet => packet.issuerKeyID); - } + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + const signature = nobleCurve.sign(hashed, privateKey, { lowS: false }); + return { + r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize), + s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize) + }; } /** - * reads an (optionally armored) OpenPGP signature and returns a signature object - * @param {Object} options - * @param {String} [options.armoredSignature] - Armored signature to be parsed - * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New signature object. + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} message - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} * @async - * @static */ -async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredSignature || binarySignature; - if (!input) { - throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); - } - if (armoredSignature && !util.isString(armoredSignature)) { - throw new Error('readSignature: options.armoredSignature must be a string'); - } - if (binarySignature && !util.isUint8Array(binarySignature)) { - throw new Error('readSignature: options.binarySignature must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + // See https://github.com/openpgpjs/openpgpjs/pull/948. + // NB: the impact was more likely limited to Brainpool curves, since thanks + // to WebCrypto availability, NIST curve should not have been affected. + // Similarly, secp256k1 should have been used rarely enough. + // However, we implement the fix for all curves, since it's only needed in case of + // verification failure, which is unexpected, hence a minor slowdown is acceptable. + const tryFallbackVerificationForOldBug = async () => ( + hashed[0] === 0 ? + jsVerify(curve, signature, hashed.subarray(1), publicKey) : + false + ); - if (armoredSignature) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.signature) { - throw new Error('Armored text not of type signature'); + if (message && !util.isStream(message)) { + switch (curve.type) { + case 'web': + try { + // Need to await to make sure browser succeeds + const verified = await webVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } catch (err) { + // We do not fallback if the error is related to key integrity + // Unfortunately Safari does not support nistP521 and throws a DataError when using it + // So we need to always fallback for that curve + if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) { + throw err; + } + util.printDebugError('Browser did not support verifying: ' + err.message); + } + break; + case 'node': { + const verified = await nodeVerify(curve, hashAlgo, signature, message, publicKey); + return verified || tryFallbackVerificationForOldBug(); + } } - input = data; } - const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1); - return new Signature(packetlist); -} - -/** - * @fileoverview Provides helpers methods for key module - * @module key/helper - * @private - */ - -async function generateSecretSubkey(options, config) { - const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); - secretSubkeyPacket.packets = null; - secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretSubkeyPacket.generate(options.rsaBits, options.curve); - await secretSubkeyPacket.computeFingerprintAndKeyID(); - return secretSubkeyPacket; -} -async function generateSecretKey(options, config) { - const secretKeyPacket = new SecretKeyPacket(options.date, config); - secretKeyPacket.packets = null; - secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); - await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); - await secretKeyPacket.computeFingerprintAndKeyID(); - return secretKeyPacket; + const verified = await jsVerify(curve, signature, hashed, publicKey); + return verified || tryFallbackVerificationForOldBug(); } /** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param {Array} signatures - List of signatures - * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - full configuration - * @returns {Promise} The latest valid signature. + * Validate ECDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDSA public point + * @param {Uint8Array} d - ECDSA secret scalar + * @returns {Promise} Whether params are valid. * @async */ -async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { - let latestValid; - let exception; - for (let i = signatures.length - 1; i >= 0; i--) { - try { - if ( - (!latestValid || signatures[i].created >= latestValid.created) - ) { - await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); - latestValid = signatures[i]; +async function validateParams$5(oid, Q, d) { + const curve = new CurveWithOID(oid); + // Reject curves x25519 and ed25519 + if (curve.keyType !== enums.publicKey.ecdsa) { + return false; + } + + // To speed up the validation, we try to use node- or webcrypto when available + // and sign + verify a random message + switch (curve.type) { + case 'web': + case 'node': { + const message = getRandomBytes(8); + const hashAlgo = enums.hash.sha256; + const hashed = await hash$1.digest(hashAlgo, message); + try { + const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed); + // eslint-disable-next-line @typescript-eslint/return-await + return await verify$4(oid, hashAlgo, signature, message, Q, hashed); + } catch (err) { + return false; } - } catch (e) { - exception = e; } + default: + return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d); } - if (!latestValid) { - throw util.wrapError( - `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` - .replace('certGeneric ', 'self-') - .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), - exception); - } - return latestValid; } -function isDataExpired(keyPacket, signature, date = new Date()) { - const normDate = util.normalizeDate(date); - if (normDate !== null) { - const expirationTime = getKeyExpirationTime(keyPacket, signature); - return !(keyPacket.created <= normDate && normDate < expirationTime); - } - return false; -} + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// /** - * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} - * @param {SecretSubkeyPacket} subkey - Subkey key packet - * @param {SecretKeyPacket} primaryKey - Primary key packet - * @param {Object} options - * @param {Object} config - Full configuration + * Fallback javascript implementation of ECDSA verification. + * To be used if no native implementation is available for the given curve/operation. */ -async function createBindingSignature(subkey, primaryKey, options, config) { - const dataToSign = {}; - dataToSign.key = primaryKey; - dataToSign.bind = subkey; - const signatureProperties = { signatureType: enums.signature.subkeyBinding }; - if (options.sign) { - signatureProperties.keyFlags = [enums.keyFlags.signData]; - signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, { - signatureType: enums.signature.keyBinding - }, options.date, undefined, undefined, undefined, config); - } else { - signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; - } - const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); - return subkeySignaturePacket; +async function jsVerify(curve, signature, hashed, publicKey) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name); + // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch + return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false }); } -/** - * Returns the preferred signature hash algorithm of a key - * @param {Key} [key] - The key to get preferences from - * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} config - full configuration - * @returns {Promise} - * @async - */ -async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) { - let hashAlgo = config.preferredHashAlgorithm; - let prefAlgo = hashAlgo; - if (key) { - const primaryUser = await key.getPrimaryUser(date, userID, config); - if (primaryUser.selfCertification.preferredHashAlgorithms) { - [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms; - hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; - } - } - switch (keyPacket.algorithm) { - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ed25519: - prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid); +async function webSign(curve, hashAlgo, message, keyPair) { + const len = curve.payloadSize; + const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['sign'] + ); + + const signature = new Uint8Array(await webCrypto$1.sign( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + message + )); + + return { + r: signature.slice(0, len), + s: signature.slice(len, len << 1) + }; +} + +async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey); + const key = await webCrypto$1.importKey( + 'jwk', + jwk, + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, curve.hash) } + }, + false, + ['verify'] + ); + + const signature = util.concatUint8Array([r, s]).buffer; + + return webCrypto$1.verify( + { + 'name': 'ECDSA', + 'namedCurve': webCurves[curve.name], + 'hash': { name: enums.read(enums.webHash, hashAlgo) } + }, + key, + signature, + message + ); +} + +async function nodeSign(curve, hashAlgo, message, privateKey) { + // JWT encoding cannot be used for now, as Brainpool curves are not supported + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + privateKey: nodeBuffer.from(privateKey) + }); + + const sign = nodeCrypto$1.createSign(enums.read(enums.hash, hashAlgo)); + sign.write(message); + sign.end(); + + const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' })); + const len = curve.payloadSize; + + return { + r: signature.subarray(0, len), + s: signature.subarray(len, len << 1) + }; +} + +async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) { + const ecKeyUtils = util.nodeRequire('eckey-utils'); + const nodeBuffer = util.getNodeBuffer(); + const { publicKey: derPublicKey } = ecKeyUtils.generateDer({ + curveName: nodeCurves[curve.name], + publicKey: nodeBuffer.from(publicKey) + }); + + const verify = nodeCrypto$1.createVerify(enums.read(enums.hash, hashAlgo)); + verify.write(message); + verify.end(); + + const signature = util.concatUint8Array([r, s]); + + try { + return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature); + } catch (err) { + return false; } - return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ? - prefAlgo : hashAlgo; } -/** - * Returns the preferred symmetric/aead/compression algorithm for a set of keys - * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return - * @param {Array} [keys] - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Preferred algorithm - * @async - */ -async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) { - const defaultAlgo = { // these are all must-implement in rfc4880bis - 'symmetric': enums.symmetric.aes128, - 'aead': enums.aead.eax, - 'compression': enums.compression.uncompressed - }[type]; - const preferredSenderAlgo = { - 'symmetric': config$1.preferredSymmetricAlgorithm, - 'aead': config$1.preferredAEADAlgorithm, - 'compression': config$1.preferredCompressionAlgorithm - }[type]; - const prefPropertyName = { - 'symmetric': 'preferredSymmetricAlgorithms', - 'aead': 'preferredAEADAlgorithms', - 'compression': 'preferredCompressionAlgorithms' - }[type]; +var ecdsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$4, + validateParams: validateParams$5, + verify: verify$4 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // if preferredSenderAlgo appears in the prefs of all recipients, we pick it - // otherwise we use the default algo - // if no keys are available, preferredSenderAlgo is returned - const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - const recipientPrefs = primaryUser.selfCertification[prefPropertyName]; - return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; - })); - return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; -} /** - * Create signature packet - * @param {Object} dataToSign - Contains packets to be signed - * @param {PrivateKey} privateKey - key to get preferences from - * @param {SecretKeyPacket| - * SecretSubkeyPacket} signingKeyPacket secret key packet for signing - * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing - * @param {Date} [date] - Override the creationtime of the signature - * @param {Object} [userID] - User ID - * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [detached] - Whether to create a detached signature packet - * @param {Object} config - full configuration - * @returns {Promise} Signature packet. + * Sign a message using the provided legacy EdDSA key + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger) + * @param {Uint8Array} message - Message to sign + * @param {Uint8Array} publicKey - Public key + * @param {Uint8Array} privateKey - Private key used to sign the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Promise<{ + * r: Uint8Array, + * s: Uint8Array + * }>} Signature of the message + * @async */ -async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) { - if (signingKeyPacket.isDummy()) { - throw new Error('Cannot sign with a gnu-dummy key.'); - } - if (!signingKeyPacket.isDecrypted()) { - throw new Error('Signing key is not decrypted.'); +async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); } - const signaturePacket = new SignaturePacket(); - Object.assign(signaturePacket, signatureProperties); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config); - signaturePacket.rawNotations = notations; - await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached); - return signaturePacket; + const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed); + // EdDSA signature params are returned in little-endian format + return { + r: signature.subarray(0, 32), + s: signature.subarray(32) + }; } /** - * Merges signatures from source[attr] to dest[attr] - * @param {Object} source - * @param {Object} dest - * @param {String} attr - * @param {Date} [date] - date to use for signature expiration check, instead of the current time - * @param {Function} [checkFn] - signature only merged if true + * Verifies if a legacy EdDSA signature is valid for a message + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m - Message to verify + * @param {Uint8Array} publicKey - Public key used to verify the message + * @param {Uint8Array} hashed - The hashed message + * @returns {Boolean} + * @async */ -async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { - source = source[attr]; - if (source) { - if (!dest[attr].length) { - dest[attr] = source; - } else { - await Promise.all(source.map(async function(sourceSig) { - if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && - !dest[attr].some(function(destSig) { - return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); - })) { - dest[attr].push(sourceSig); - } - })); - } +async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, publicKey); + if (hash$1.getHashByteLength(hashAlgo) < hash$1.getHashByteLength(enums.hash.sha256)) { + // Enforce digest sizes, since the constraint was already present in RFC4880bis: + // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2 + // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + throw new Error('Hash algorithm too weak for EdDSA.'); } + const RS = util.concatUint8Array([r, s]); + return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed); } - /** - * Checks if a given certificate or binding signature is revoked - * @param {SecretKeyPacket| - * PublicKeyPacket} primaryKey The primary key packet - * @param {Object} dataToVerify - The data to check - * @param {Array} revocations - The revocation signatures to check - * @param {SignaturePacket} signature - The certificate or signature to check - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the signature revokes the data. + * Validate legacy EdDSA parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - EdDSA public point + * @param {Uint8Array} k - EdDSA secret seed + * @returns {Promise} Whether params are valid. * @async */ -async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { - key = key || primaryKey; - const revocationKeyIDs = []; - await Promise.all(revocations.map(async function(revocationSignature) { - try { - if ( - // Note: a third-party revocation signature could legitimately revoke a - // self-signature if the signature has an authorized revocation key. - // However, we don't support passing authorized revocation keys, nor - // verifying such revocation signatures. Instead, we indicate an error - // when parsing a key with an authorized revocation key, and ignore - // third-party revocation signatures here. (It could also be revoking a - // third-party key certification, which should only affect - // `verifyAllCertifications`.) - !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) - ) { - await revocationSignature.verify( - key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config - ); - - // TODO get an identifier of the revoked object instead - revocationKeyIDs.push(revocationSignature.issuerKeyID); - } - } catch (e) {} - })); - // TODO further verify that this is the signature that should be revoked - if (signature) { - signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : - signature.revoked || false; - return signature.revoked; +async function validateParams$4(oid, Q, k) { + // Check whether the given curve is supported + if (oid.getName() !== enums.curve.ed25519Legacy) { + return false; } - return revocationKeyIDs.length > 0; + + /** + * Derive public point Q' = dG from private key + * and expect Q == Q' + */ + const { publicKey } = nacl.sign.keyPair.fromSeed(k); + const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix + return util.equalsUint8Array(Q, dG); + } +var eddsa_legacy = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$3, + validateParams: validateParams$4, + verify: verify$3 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + /** - * Returns key expiration time based on the given certification signature. - * The expiration time of the signature is ignored. - * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check - * @param {SignaturePacket} signature - signature to process - * @returns {Date|Infinity} expiration time or infinity if the key does not expire + * @fileoverview Functions to add and remove PKCS5 padding + * @see PublicKeyEncryptedSessionKeyPacket + * @module crypto/pkcs5 + * @private */ -function getKeyExpirationTime(keyPacket, signature) { - let expirationTime; - // check V4 expiration time - if (signature.keyNeverExpires === false) { - expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; - } - return expirationTime ? new Date(expirationTime) : Infinity; + +/** + * Add pkcs5 padding to a message + * @param {Uint8Array} message - message to pad + * @returns {Uint8Array} Padded message. + */ +function encode(message) { + const c = 8 - (message.length % 8); + const padded = new Uint8Array(message.length + c).fill(c); + padded.set(message); + return padded; } /** - * Returns whether aead is supported by all keys in the set - * @param {Array} keys - Set of keys - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Array} [userIDs] - User IDs - * @param {Object} config - full configuration - * @returns {Promise} - * @async + * Remove pkcs5 padding from a message + * @param {Uint8Array} message - message to remove padding from + * @returns {Uint8Array} Message without padding. */ -async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) { - let supported = true; - // TODO replace when Promise.some or Promise.any are implemented - await Promise.all(keys.map(async function(key, i) { - const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1); - if (!primaryUser.selfCertification.features || - !(primaryUser.selfCertification.features[0] & enums.features.aead)) { - supported = false; +function decode$1(message) { + const len = message.length; + if (len > 0) { + const c = message[len - 1]; + if (c >= 1) { + const provided = message.subarray(len - c); + const computed = new Uint8Array(c).fill(c); + if (util.equalsUint8Array(provided, computed)) { + return message.subarray(0, len - c); + } } - })); - return supported; + } + throw new Error('Invalid padding'); } -function sanitizeKeyOptions(options, subkeyDefaults = {}) { - options.type = options.type || subkeyDefaults.type; - options.curve = options.curve || subkeyDefaults.curve; - options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; - options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; +var pkcs5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: decode$1, + encode: encode +}); - options.sign = options.sign || false; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - switch (options.type) { - case 'ecc': - try { - options.curve = enums.write(enums.curve, options.curve); - } catch (e) { - throw new Error('Unknown curve'); - } - if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) { - options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; - } - if (options.sign) { - options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; - } else { - options.algorithm = enums.publicKey.ecdh; - } - break; - case 'rsa': - options.algorithm = enums.publicKey.rsaEncryptSign; - break; - default: - throw new Error(`Unsupported key type ${options.type}`); - } - return options; + +const webCrypto = util.getWebCrypto(); +const nodeCrypto = util.getNodeCrypto(); + +/** + * Validate ECDH parameters + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {Uint8Array} Q - ECDH public point + * @param {Uint8Array} d - ECDH secret scalar + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$3(oid, Q, d) { + return validateStandardParams(enums.publicKey.ecdh, oid, Q, d); } -function isValidSigningKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.rsaEncrypt && - keyAlgo !== enums.publicKey.elgamal && - keyAlgo !== enums.publicKey.ecdh && - keyAlgo !== enums.publicKey.x25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.signData) !== 0); -} - -function isValidEncryptionKeyPacket(keyPacket, signature) { - const keyAlgo = keyPacket.algorithm; - return keyAlgo !== enums.publicKey.dsa && - keyAlgo !== enums.publicKey.rsaSign && - keyAlgo !== enums.publicKey.ecdsa && - keyAlgo !== enums.publicKey.eddsaLegacy && - keyAlgo !== enums.publicKey.ed25519 && - (!signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0); +// Build Param for ECDH algorithm (RFC 6637) +function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) { + return util.concatUint8Array([ + oid.write(), + new Uint8Array([public_algo]), + kdfParams.write(), + util.stringToUint8Array('Anonymous Sender '), + fingerprint + ]); } -function isValidDecryptionKeyPacket(signature, config) { - if (config.allowInsecureDecryptionWithSigningKeys) { - // This is only relevant for RSA keys, all other signing algorithms cannot decrypt - return true; +// Key Derivation Function (RFC 6637) +async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) { + // Note: X is little endian for Curve25519, big-endian for all others. + // This is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + let i; + if (stripLeading) { + // Work around old go crypto bug + for (i = 0; i < X.length && X[i] === 0; i++); + X = X.subarray(i); } - - return !signature.keyFlags || - (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || - (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + if (stripTrailing) { + // Work around old OpenPGP.js bug + for (i = X.length - 1; i >= 0 && X[i] === 0; i--); + X = X.subarray(0, i + 1); + } + const digest = await hash$1.digest(hashAlgo, util.concatUint8Array([ + new Uint8Array([0, 0, 0, 1]), + X, + param + ])); + return digest.subarray(0, length); } /** - * Check key against blacklisted algorithms and minimum strength requirements. - * @param {SecretKeyPacket|PublicKeyPacket| - * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket - * @param {Config} config - * @throws {Error} if the key packet does not meet the requirements + * Generate ECDHE ephemeral key and secret from public key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async */ -function checkKeyRequirements(keyPacket, config) { - const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); - const algoInfo = keyPacket.getAlgorithmInfo(); - if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { - throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); - } - switch (keyAlgo) { - case enums.publicKey.rsaEncryptSign: - case enums.publicKey.rsaSign: - case enums.publicKey.rsaEncrypt: - if (algoInfo.bits < config.minRSABits) { - throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); - } - break; - case enums.publicKey.ecdsa: - case enums.publicKey.eddsaLegacy: - case enums.publicKey.ecdh: - if (config.rejectCurves.has(algoInfo.curve)) { - throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); +async function genPublicEphemeralKey(curve, Q) { + switch (curve.type) { + case 'curve25519Legacy': { + const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1)); + const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]); + return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below + } + case 'web': + if (curve.web && util.getWebCrypto()) { + try { + return await webPublicEphemeralKey(curve, Q); + } catch (err) { + util.printDebugError(err); + return jsPublicEphemeralKey(curve, Q); + } } break; + case 'node': + return nodePublicEphemeralKey(curve, Q); + default: + return jsPublicEphemeralKey(curve, Q); + } } /** - * @module key/User - * @private - */ - -/** - * Class that represents an user ID or attribute packet and the relevant signatures. - * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info - * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} data - Unpadded session key data + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>} + * @async */ -class User { - constructor(userPacket, mainKey) { - this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; - this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; - this.selfCertifications = []; - this.otherCertifications = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } - - /** - * Transforms structured user data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.userID || this.userAttribute); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.selfCertifications); - packetlist.push(...this.otherCertifications); - return packetlist; - } - - /** - * Shallow clone - * @returns {User} - */ - clone() { - const user = new User(this.userID || this.userAttribute, this.mainKey); - user.selfCertifications = [...this.selfCertifications]; - user.otherCertifications = [...this.otherCertifications]; - user.revocationSignatures = [...this.revocationSignatures]; - return user; - } - - /** - * Generate third-party certifications over this user and its primary key - * @param {Array} signingKeys - Decrypted private keys for signing - * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} New user with new certifications. - * @async - */ - async certify(signingKeys, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { - if (!privateKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - if (privateKey.hasSameFingerprintAs(primaryKey)) { - throw new Error("The user's own key can only be used for self-certifications"); - } - const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); - return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, { - // Most OpenPGP implementations use generic certification (0x10) - signatureType: enums.signature.certGeneric, - keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] - }, date, undefined, undefined, undefined, config); - })); - await user.update(this, date, config); - return user; - } - - /** - * Checks if a given certificate of the user is revoked - * @param {SignaturePacket} certificate - The certificate to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} True if the certificate is revoked. - * @async - */ - async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked(primaryKey, enums.signature.certRevocation, { - key: primaryKey, - userID: this.userID, - userAttribute: this.userAttribute - }, this.revocationSignatures, certificate, keyPacket, date, config$1); - } - - /** - * Verifies the user certificate. - * @param {SignaturePacket} certificate - A certificate of this user - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate - * @throws if the user certificate is invalid. - * @async - */ - async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const { issuerKeyID } = certificate; - const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); - if (issuerKeys.length === 0) { - return null; - } - await Promise.all(issuerKeys.map(async key => { - const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); - if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { - throw new Error('User certificate is revoked'); - } - try { - await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('User certificate is invalid', e); - } - })); - return true; - } +async function encrypt$1(oid, kdfParams, data, Q, fingerprint) { + const m = encode(data); - /** - * Verifies all user certificates - * @param {Array} verificationKeys - Array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllCertifications(verificationKeys, date = new Date(), config) { - const that = this; - const certifications = this.selfCertifications.concat(this.otherCertifications); - return Promise.all(certifications.map(async certification => ({ - keyID: certification.issuerKeyID, - valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) - }))); - } + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param); + const wrappedKey = await wrap(kdfParams.cipher, Z, m); + return { publicKey, wrappedKey }; +} - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} config - Full configuration - * @returns {Promise} Status of user. - * @throws {Error} if there are no valid self signatures. - * @async - */ - async verify(date = new Date(), config) { - if (!this.selfCertifications.length) { - throw new Error('No self-certifications found'); +/** + * Generate ECDHE secret from private key and public part of ephemeral key + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; + } + switch (curve.type) { + case 'curve25519Legacy': { + const secretKey = d.slice().reverse(); + const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey); + return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } - const that = this; - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // TODO replace when Promise.some or Promise.any are implemented - let exception; - for (let i = this.selfCertifications.length - 1; i >= 0; i--) { - try { - const selfCertification = this.selfCertifications[i]; - if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { - throw new Error('Self-certification is revoked'); - } + case 'web': + if (curve.web && util.getWebCrypto()) { try { - await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); - } catch (e) { - throw util.wrapError('Self-certification is invalid', e); + return await webPrivateEphemeralKey(curve, V, Q, d); + } catch (err) { + util.printDebugError(err); + return jsPrivateEphemeralKey(curve, V, d); } - return true; - } catch (e) { - exception = e; } - } - throw exception; + break; + case 'node': + return nodePrivateEphemeralKey(curve, V, d); + default: + return jsPrivateEphemeralKey(curve, V, d); } +} - /** - * Update user with new components from specified user - * @param {User} sourceUser - Source user to merge - * @param {Date} date - Date to verify the validity of signatures - * @param {Object} config - Full configuration - * @returns {Promise} - * @async - */ - async update(sourceUser, date, config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - // self signatures - await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { - try { - await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); - return true; - } catch (e) { - return false; - } - }); - // other signatures - await mergeSignatures(sourceUser, this, 'otherCertifications', date); - // revocation signatures - await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); - }); +/** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid - Elliptic curve object identifier + * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} C - Encrypted and wrapped value derived from session key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version + * @returns {Promise} Value derived from session key. + * @async + */ +async function decrypt$1(oid, kdfParams, V, C, Q, d, fingerprint) { + const curve = new CurveWithOID(oid); + checkPublicPointEnconding(curve, Q); + checkPublicPointEnconding(curve, V); + const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d); + const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint); + const { keySize } = getCipherParams(kdfParams.cipher); + let err; + for (let i = 0; i < 3; i++) { + try { + // Work around old go crypto bug and old OpenPGP.js bug, respectively. + const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2); + return decode$1(await unwrap(kdfParams.cipher, Z, C)); + } catch (e) { + err = e; + } } + throw err; +} - /** - * Revokes the user - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New user with revocation signature. - * @async - */ - async revoke( - primaryKey, +async function jsPrivateEphemeralKey(curve, V, d) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V); + const sharedKey = sharedSecretWithParity.subarray(1); + return { secretKey: d, sharedKey }; +} + +async function jsPublicEphemeralKey(curve, Q) { + const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name); + const { publicKey: V, privateKey: v } = await curve.genKeyPair(); + + // The output includes parity byte + const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q); + const sharedKey = sharedSecretWithParity.subarray(1); + return { publicKey: V, sharedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} Q - Recipient public key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPrivateEphemeralKey(curve, V, Q, d) { + const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d); + let privateKey = webCrypto.importKey( + 'jwk', + recipient, { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { - userID: this.userID, - userAttribute: this.userAttribute, - key: primaryKey - }; - const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); - user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.certRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await user.update(this); - return user; - } + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V); + let sender = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + [] + ); + [privateKey, sender] = await Promise.all([privateKey, sender]); + let S = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: sender + }, + privateKey, + curve.sharedSize + ); + let secret = webCrypto.exportKey( + 'jwk', + privateKey + ); + [S, secret] = await Promise.all([S, secret]); + const sharedKey = new Uint8Array(S); + const secretKey = b64ToUint8Array(secret.d); + return { secretKey, sharedKey }; +} + +/** + * Generate ECDHE ephemeral key and secret from public key using webCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function webPublicEphemeralKey(curve, Q) { + const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q); + let keyPair = webCrypto.generateKey( + { + name: 'ECDH', + namedCurve: curve.web + }, + true, + ['deriveKey', 'deriveBits'] + ); + let recipient = webCrypto.importKey( + 'jwk', + jwk, + { + name: 'ECDH', + namedCurve: curve.web + }, + false, + [] + ); + [keyPair, recipient] = await Promise.all([keyPair, recipient]); + let s = webCrypto.deriveBits( + { + name: 'ECDH', + namedCurve: curve.web, + public: recipient + }, + keyPair.privateKey, + curve.sharedSize + ); + let p = webCrypto.exportKey( + 'jwk', + keyPair.publicKey + ); + [s, p] = await Promise.all([s, p]); + const sharedKey = new Uint8Array(s); + const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte)); + return { publicKey, sharedKey }; +} + +/** + * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} V - Public part of ephemeral key + * @param {Uint8Array} d - Recipient private key + * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePrivateEphemeralKey(curve, V, d) { + const recipient = nodeCrypto.createECDH(curve.node); + recipient.setPrivateKey(d); + const sharedKey = new Uint8Array(recipient.computeSecret(V)); + const secretKey = new Uint8Array(recipient.getPrivateKey()); + return { secretKey, sharedKey }; +} + +/** + * Generate ECDHE ephemeral key and secret from public key using nodeCrypto + * + * @param {CurveWithOID} curve - Elliptic curve object + * @param {Uint8Array} Q - Recipient public key + * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>} + * @async + */ +async function nodePublicEphemeralKey(curve, Q) { + const sender = nodeCrypto.createECDH(curve.node); + sender.generateKeys(); + const sharedKey = new Uint8Array(sender.computeSecret(Q)); + const publicKey = new Uint8Array(sender.getPublicKey()); + return { publicKey, sharedKey }; } +var ecdh = /*#__PURE__*/Object.freeze({ + __proto__: null, + decrypt: decrypt$1, + encrypt: encrypt$1, + validateParams: validateParams$3 +}); + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +var elliptic = /*#__PURE__*/Object.freeze({ + __proto__: null, + CurveWithOID: CurveWithOID, + ecdh: ecdh, + ecdhX: ecdh_x, + ecdsa: ecdsa, + eddsa: eddsa, + eddsaLegacy: eddsa_legacy, + generate: generate$1, + getPreferredHashAlgo: getPreferredHashAlgo$1 +}); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 +*/ + +const _0n$7 = BigInt(0); +const _1n$9 = BigInt(1); + /** - * @module key/Subkey - * @private + * DSA Sign function + * @param {Integer} hashAlgo + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} x + * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>} + * @async */ +async function sign$2(hashAlgo, hashed, g, p, q, x) { + const _0n = BigInt(0); + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + x = uint8ArrayToBigInt(x); + + let k; + let r; + let s; + let t; + g = mod$2(g, p); + x = mod$2(x, q); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + while (true) { + // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + k = getRandomBigInteger(_1n$9, q); // returns in [1, q-1] + r = mod$2(modExp(g, k, p), q); // (g**k mod p) mod q + if (r === _0n) { + continue; + } + const xr = mod$2(x * r, q); + t = mod$2(h + xr, q); // H(m) + x*r mod q + s = mod$2(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q + if (s === _0n) { + continue; + } + break; + } + return { + r: bigIntToUint8Array(r, 'be', byteLength(p)), + s: bigIntToUint8Array(s, 'be', byteLength(p)) + }; +} /** - * Class that represents a subkey packet and the relevant signatures. - * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID - * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint - * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs - * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo - * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime - * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + * DSA Verify function + * @param {Integer} hashAlgo + * @param {Uint8Array} r + * @param {Uint8Array} s + * @param {Uint8Array} hashed + * @param {Uint8Array} g + * @param {Uint8Array} p + * @param {Uint8Array} q + * @param {Uint8Array} y + * @returns {boolean} + * @async */ -class Subkey { - /** - * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey - * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey - */ - constructor(subkeyPacket, mainKey) { - this.keyPacket = subkeyPacket; - this.bindingSignatures = []; - this.revocationSignatures = []; - this.mainKey = mainKey; - } +async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) { + r = uint8ArrayToBigInt(r); + s = uint8ArrayToBigInt(s); - /** - * Transforms structured subkey data to packetlist - * @returns {PacketList} - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.bindingSignatures); - return packetlist; - } + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); - /** - * Shallow clone - * @return {Subkey} - */ - clone() { - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.bindingSignatures = [...this.bindingSignatures]; - subkey.revocationSignatures = [...this.revocationSignatures]; - return subkey; + if (r <= _0n$7 || r >= q || + s <= _0n$7 || s >= q) { + util.printDebug('invalid DSA Signature'); + return false; } - - /** - * Checks if a binding signature of a subkey is revoked - * @param {SignaturePacket} signature - The binding signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the binding signature is revoked. - * @async - */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - return isDataRevoked( - primaryKey, enums.signature.subkeyRevocation, { - key: primaryKey, - bind: this.keyPacket - }, this.revocationSignatures, signature, key, date, config$1 - ); + const h = mod$2(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q); + const w = modInv(s, q); // s**-1 mod q + if (w === _0n$7) { + util.printDebug('invalid DSA Signature'); + return false; } - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @throws {Error} if the subkey is invalid. - * @async - */ - async verify(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - // check subkey binding signatures - const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - // check binding signature is not revoked - if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { - throw new Error('Subkey is revoked'); - } - // check for expiration time - if (isDataExpired(this.keyPacket, bindingSignature, date)) { - throw new Error('Subkey is expired'); - } - return bindingSignature; + g = mod$2(g, p); + y = mod$2(y, p); + const u1 = mod$2(h * w, q); // H(m) * w mod q + const u2 = mod$2(r * w, q); // r * w mod q + const t1 = modExp(g, u1, p); // g**u1 mod p + const t2 = modExp(y, u2, p); // y**u2 mod p + const v = mod$2(mod$2(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q + return v === r; +} + +/** + * Validate DSA parameters + * @param {Uint8Array} p - DSA prime + * @param {Uint8Array} q - DSA group order + * @param {Uint8Array} g - DSA sub-group generator + * @param {Uint8Array} y - DSA public key + * @param {Uint8Array} x - DSA private key + * @returns {Promise} Whether params are valid. + * @async + */ +async function validateParams$2(p, q, g, y, x) { + p = uint8ArrayToBigInt(p); + q = uint8ArrayToBigInt(q); + g = uint8ArrayToBigInt(g); + y = uint8ArrayToBigInt(y); + // Check that 1 < g < p + if (g <= _1n$9 || g >= p) { + return false; } /** - * Returns the expiration time of the subkey or Infinity if key does not expire. - * Returns null if the subkey is invalid. - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async + * Check that subgroup order q divides p-1 */ - async getExpirationTime(date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - const dataToVerify = { key: primaryKey, bind: this.keyPacket }; - let bindingSignature; - try { - bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - } catch (e) { - return null; - } - const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); - const sigExpiry = bindingSignature.getExpirationTime(); - return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; + if (mod$2(p - _1n$9, q) !== _0n$7) { + return false; } /** - * Update subkey with new components from specified subkey - * @param {Subkey} subkey - Source subkey to merge - * @param {Date} [date] - Date to verify validity of signatures - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if update failed - * @async - */ - async update(subkey, date = new Date(), config$1 = config) { - const primaryKey = this.mainKey.keyPacket; - if (!this.hasSameFingerprintAs(subkey)) { - throw new Error('Subkey update method: fingerprints of subkeys not equal'); - } - // key packet - if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && - subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { - this.keyPacket = subkey.keyPacket; - } - // update missing binding signatures - const that = this; - const dataToVerify = { key: primaryKey, bind: that.keyPacket }; - await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { - for (let i = 0; i < that.bindingSignatures.length; i++) { - if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { - if (srcBindSig.created > that.bindingSignatures[i].created) { - that.bindingSignatures[i] = srcBindSig; - } - return false; - } - } - try { - await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); - return true; - } catch (e) { - return false; - } - }); - // revocation signatures - await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { - return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); - }); + * g has order q + * Check that g ** q = 1 mod p + */ + if (modExp(g, q, p) !== _1n$9) { + return false; } /** - * Revokes the subkey - * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New subkey with revocation signature. - * @async + * Check q is large and probably prime (we mainly want to avoid small factors) */ - async revoke( - primaryKey, - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - const dataToSign = { key: primaryKey, bind: this.keyPacket }; - const subkey = new Subkey(this.keyPacket, this.mainKey); - subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, { - signatureType: enums.signature.subkeyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, false, config$1)); - await subkey.update(this); - return subkey; + const qSize = BigInt(bitLength(q)); + const _150n = BigInt(150); + if (qSize < _150n || !isProbablePrime(q, null, 32)) { + return false; } - hasSameFingerprintAs(other) { - return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + /** + * Re-derive public key y' = g ** x mod p + * Expect y == y' + * + * Blinded exponentiation computes g**{rq + x} to compare to y + */ + x = uint8ArrayToBigInt(x); + const _2n = BigInt(2); + const r = getRandomBigInteger(_2n << (qSize - _1n$9), _2n << qSize); // draw r of same size as q + const rqx = q * r + x; + if (y !== modExp(g, rqx, p)) { + return false; } + + return true; } -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { - Subkey.prototype[name] = - function() { - return this.keyPacket[name](); - }; +var dsa = /*#__PURE__*/Object.freeze({ + __proto__: null, + sign: sign$2, + validateParams: validateParams$2, + verify: verify$2 }); -// GPG4Browsers - An OpenPGP implementation in javascript - -// A key revocation certificate can contain the following packets -const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); -const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); -const keyPacketTags = new Set([ - enums.packet.publicKey, enums.packet.privateKey, - enums.packet.publicSubkey, enums.packet.privateSubkey -]); - /** - * Abstract class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. - * @borrows PublicKeyPacket#getKeyID as Key#getKeyID - * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint - * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs - * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo - * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + * @fileoverview Asymmetric cryptography functions + * @module crypto/public_key */ -class Key { - /** - * Transforms packetlist to structured key data - * @param {PacketList} packetlist - The packets that form a key - * @param {Set} disallowedPackets - disallowed packet tags - */ - packetListToStructure(packetlist, disallowedPackets = new Set()) { - let user; - let primaryKeyID; - let subkey; - let ignoreUntil; - for (const packet of packetlist) { - if (packet instanceof UnparseablePacket) { - const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); - if (isUnparseableKeyPacket && !ignoreUntil) { - // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must - // discard all non-key packets that follow, until another (sub)key packet is found. - if (mainKeyPacketTags.has(packet.tag)) { - ignoreUntil = mainKeyPacketTags; - } else { - ignoreUntil = keyPacketTags; - } - } - continue; - } +var publicKey = { + /** @see module:crypto/public_key/rsa */ + rsa: rsa, + /** @see module:crypto/public_key/elgamal */ + elgamal: elgamal, + /** @see module:crypto/public_key/elliptic */ + elliptic: elliptic, + /** @see module:crypto/public_key/dsa */ + dsa: dsa +}; - const tag = packet.constructor.tag; - if (ignoreUntil) { - if (!ignoreUntil.has(tag)) continue; - ignoreUntil = null; - } - if (disallowedPackets.has(tag)) { - throw new Error(`Unexpected packet type: ${tag}`); - } - switch (tag) { - case enums.packet.publicKey: - case enums.packet.secretKey: - if (this.keyPacket) { - throw new Error('Key block contains multiple keys'); - } - this.keyPacket = packet; - primaryKeyID = this.getKeyID(); - if (!primaryKeyID) { - throw new Error('Missing Key ID'); - } - break; - case enums.packet.userID: - case enums.packet.userAttribute: - user = new User(packet, this); - this.users.push(user); - break; - case enums.packet.publicSubkey: - case enums.packet.secretSubkey: - user = null; - subkey = new Subkey(packet, this); - this.subkeys.push(subkey); - break; - case enums.packet.signature: - switch (packet.signatureType) { - case enums.signature.certGeneric: - case enums.signature.certPersona: - case enums.signature.certCasual: - case enums.signature.certPositive: - if (!user) { - util.printDebug('Dropping certification signatures without preceding user packet'); - continue; - } - if (packet.issuerKeyID.equals(primaryKeyID)) { - user.selfCertifications.push(packet); - } else { - user.otherCertifications.push(packet); - } - break; - case enums.signature.certRevocation: - if (user) { - user.revocationSignatures.push(packet); - } else { - this.directSignatures.push(packet); - } - break; - case enums.signature.key: - this.directSignatures.push(packet); - break; - case enums.signature.subkeyBinding: - if (!subkey) { - util.printDebug('Dropping subkey binding signature without preceding subkey packet'); - continue; - } - subkey.bindingSignatures.push(packet); - break; - case enums.signature.keyRevocation: - this.revocationSignatures.push(packet); - break; - case enums.signature.subkeyRevocation: - if (!subkey) { - util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); - continue; - } - subkey.revocationSignatures.push(packet); - break; - } - break; - } - } - } +/** + * @fileoverview Provides functions for asymmetric signing and signature verification + * @module crypto/signature + */ - /** - * Transforms structured key data to packetlist - * @returns {PacketList} The packets that form a key. - */ - toPacketList() { - const packetlist = new PacketList(); - packetlist.push(this.keyPacket); - packetlist.push(...this.revocationSignatures); - packetlist.push(...this.directSignatures); - this.users.map(user => packetlist.push(...user.toPacketList())); - this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); - return packetlist; - } - /** - * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. - * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. - * @returns {Promise} Clone of the key. - */ - clone(clonePrivateParams = false) { - const key = new this.constructor(this.toPacketList()); - if (clonePrivateParams) { - key.getKeys().forEach(k => { - // shallow clone the key packets - k.keyPacket = Object.create( - Object.getPrototypeOf(k.keyPacket), - Object.getOwnPropertyDescriptors(k.keyPacket) - ); - if (!k.keyPacket.isDecrypted()) return; - // deep clone the private params, which are cleared during encryption - const privateParams = {}; - Object.keys(k.keyPacket.privateParams).forEach(name => { - privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); - }); - k.keyPacket.privateParams = privateParams; - }); +/** + * Parse signature in binary form to get the parameters. + * The returned values are only padded for EdDSA, since in the other cases their expected length + * depends on the key params, hence we delegate the padding to the signature verification function. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Uint8Array} signature - Data for which the signature was created + * @returns {Promise} True if signature is valid. + * @async + */ +function parseSignatureParams(algo, signature) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA signatures: + // - MPI of RSA signature value m**d mod n. + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + // The signature needs to be the same length as the public key modulo n. + // We pad s on signature verification, where we have access to n. + return { read, signatureParams: { s } }; + } + // Algorithm-Specific Fields for DSA or ECDSA signatures: + // - MPI of DSA or ECDSA value r. + // - MPI of DSA or ECDSA value s. + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + { + // If the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for legacy EdDSA signatures: + // - MPI of an EC point r. + // - EdDSA value s, in MPI, in the little endian representation + case enums.publicKey.eddsaLegacy: { + // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature + // verification: if the signature payload sizes are unexpected, we will throw on verification, + // where we also have access to the OID curve from the key. + const r = util.readMPI(signature.subarray(read)); read += r.length + 2; + const s = util.readMPI(signature.subarray(read)); read += s.length + 2; + return { read, signatureParams: { r, s } }; + } + // Algorithm-Specific Fields for Ed25519 signatures: + // - 64 octets of the native signature + // Algorithm-Specific Fields for Ed448 signatures: + // - 114 octets of the native signature + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const rsSize = 2 * publicKey.elliptic.eddsa.getPayloadSize(algo); + const RS = util.readExactSubarray(signature, read, read + rsSize); read += RS.length; + return { read, signatureParams: { RS } }; } - return key; - } - /** - * Returns an array containing all public or private subkeys matching keyID; - * If no keyID is given, returns all subkeys. - * @param {type/keyID} [keyID] - key ID to look for - * @returns {Array} array of subkeys - */ - getSubkeys(keyID = null) { - const subkeys = this.subkeys.filter(subkey => ( - !keyID || subkey.getKeyID().equals(keyID, true) - )); - return subkeys; + default: + throw new UnsupportedError('Unknown signature algorithm.'); } +} - /** - * Returns an array containing all public or private keys matching keyID. - * If no keyID is given, returns all keys, starting with the primary key. - * @param {type/keyid~KeyID} [keyID] - key ID to look for - * @returns {Array} array of keys - */ - getKeys(keyID = null) { - const keys = []; - if (!keyID || this.getKeyID().equals(keyID, true)) { - keys.push(this); +/** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} signature - Named algorithm-specific signature parameters + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Data for which the signature was created + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} True if signature is valid. + * @async + */ +async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto + return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed); } - return keys.concat(this.getSubkeys(keyID)); + case enums.publicKey.dsa: { + const { g, p, q, y } = publicParams; + const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers + return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y); + } + case enums.publicKey.ecdsa: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // padding needed for webcrypto + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicParams; + const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize; + // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values: + // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9 + const r = util.leftPad(signature.r, curveSize); + const s = util.leftPad(signature.s, curveSize); + return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, { r, s }, data, Q, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); } +} - /** - * Returns key IDs of all keys - * @returns {Array} - */ - getKeyIDs() { - return this.getKeys().map(key => key.getKeyID()); +/** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {module:enums.hash} hashAlgo - Hash algorithm + * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters + * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters + * @param {Uint8Array} data - Data to be signed + * @param {Uint8Array} hashed - The hashed data + * @returns {Promise} Signature Object containing named signature parameters. + * @async + */ +async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) { + if (!publicKeyParams || !privateKeyParams) { + throw new Error('Missing key parameters'); } - - /** - * Returns userIDs - * @returns {Array} Array of userIDs. - */ - getUserIDs() { - return this.users.map(user => { - return user.userID ? user.userID.userID : null; - }).filter(userID => userID !== null); + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaSign: { + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed); + return { s }; + } + case enums.publicKey.dsa: { + const { g, p, q } = publicKeyParams; + const { x } = privateKeyParams; + return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x); + } + case enums.publicKey.elgamal: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + case enums.publicKey.ecdsa: { + const { oid, Q } = publicKeyParams; + const { d } = privateKeyParams; + return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed); + } + case enums.publicKey.eddsaLegacy: { + const { oid, Q } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicKeyParams; + const { seed } = privateKeyParams; + return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed); + } + default: + throw new Error('Unknown signature algorithm.'); } +} - /** - * Returns binary encoded key - * @returns {Uint8Array} Binary key. - */ - write() { - return this.toPacketList().write(); - } +var signature = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseSignatureParams: parseSignatureParams, + sign: sign$1, + verify: verify$1 +}); - /** - * Returns last created key or key by given keyID that is available for signing and verification - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} signing key - * @throws if no valid signing key was found - * @async - */ - async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature( - subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 - ); - if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) { - continue; - } - if (!bindingSignature.embeddedSignature) { - throw new Error('Missing embedded signature'); - } - // verify embedded signature - await getLatestValidSignature( - [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 - ); - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } catch (e) { - exception = e; - } - } - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - try { - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) { - checkKeyRequirements(primaryKey, config$1); - return this; - } - } catch (e) { - exception = e; + +class ECDHSymmetricKey { + constructor(data) { + if (data) { + this.data = data; } - throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); } /** - * Returns last created key or key by given keyID that is available for encryption or decryption - * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve - * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date - * @param {Object} [userID] - filter keys for the given user ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} encryption key - * @throws if no valid encryption key was found - * @async + * Read an ECDHSymmetricKey from an Uint8Array: + * - 1 octect for the length `l` + * - `l` octects of encoded session key data + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. */ - async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { - await this.verifyPrimaryKey(date, userID, config$1); - const primaryKey = this.keyPacket; - // V4: by convention subkeys are preferred for encryption service - const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); - let exception; - for (const subkey of subkeys) { - if (!keyID || subkey.getKeyID().equals(keyID)) { - try { - await subkey.verify(date, config$1); - const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; - const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) { - checkKeyRequirements(subkey.keyPacket, config$1); - return subkey; - } - } catch (e) { - exception = e; - } - } - } - - try { - // if no valid subkey for encryption, evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID)) && - isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) { - checkKeyRequirements(primaryKey, config$1); - return this; + read(bytes) { + if (bytes.length >= 1) { + const length = bytes[0]; + if (bytes.length >= 1 + length) { + this.data = bytes.subarray(1, 1 + length); + return 1 + this.data.length; } - } catch (e) { - exception = e; } - throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + throw new Error('Invalid symmetric key'); } /** - * Checks if a signature on a key is revoked - * @param {SignaturePacket} signature - The signature to verify - * @param {PublicSubkeyPacket| - * SecretSubkeyPacket| - * PublicKeyPacket| - * SecretKeyPacket} key, optional The key to verify the signature - * @param {Date} [date] - Use the given date for verification, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} True if the certificate is revoked. - * @async + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data */ - async isRevoked(signature, key, date = new Date(), config$1 = config) { - return isDataRevoked( - this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 - ); + write() { + return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]); } +} - /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature. Throws if the primary key is invalid. - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} If key verification failed - * @async - */ - async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - // check for key revocation signatures - if (await this.isRevoked(null, null, date, config$1)) { - throw new Error('Primary key is revoked'); - } - // check for valid, unrevoked, unexpired self signature - const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); - // check for expiration time in binding signatures - if (isDataExpired(primaryKey, selfCertification, date)) { - throw new Error('Primary key is expired'); - } - // check for expiration time in direct signatures - const directSignature = await getLatestValidSignature( - this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 - ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (directSignature && isDataExpired(primaryKey, directSignature, date)) { - throw new Error('Primary key is expired'); - } - } +/** + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @module type/kdf_params + * @private + */ + +class KDFParams { /** - * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. - * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. - * @param {Object} [userID] - User ID to consider instead of the primary user - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} - * @async + * @param {enums.hash} hash - Hash algorithm + * @param {enums.symmetric} cipher - Symmetric algorithm */ - async getExpirationTime(userID, config$1 = config) { - let primaryKeyExpiry; - try { - const { selfCertification } = await this.getPrimaryUser(null, userID, config$1); - const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); - const selfSigExpiry = selfCertification.getExpirationTime(); - const directSignature = await getLatestValidSignature( - this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 - ).catch(() => {}); - if (directSignature) { - const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); - // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, - // causing a discountinous validy period for the key - primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); - } else { - primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; - } - } catch (e) { - primaryKeyExpiry = null; + constructor(data) { + if (data) { + const { hash, cipher } = data; + this.hash = hash; + this.cipher = cipher; + } else { + this.hash = null; + this.cipher = null; } - - return util.normalizeDate(primaryKeyExpiry); } - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * user: User, - * selfCertification: SignaturePacket - * }>} The primary user and the self signature - * @async + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input - Where to read the KDFParams from + * @returns {Number} Number of read bytes. */ - async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const users = []; - let exception; - for (let i = 0; i < this.users.length; i++) { - try { - const user = this.users[i]; - if (!user.userID) { - continue; - } - if ( - (userID.name !== undefined && user.userID.name !== userID.name) || - (userID.email !== undefined && user.userID.email !== userID.email) || - (userID.comment !== undefined && user.userID.comment !== userID.comment) - ) { - throw new Error('Could not find user that matches that user ID'); - } - const dataToVerify = { userID: user.userID, key: primaryKey }; - const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); - users.push({ index: i, user, selfCertification }); - } catch (e) { - exception = e; - } - } - if (!users.length) { - throw exception || new Error('Could not find primary user'); - } - await Promise.all(users.map(async function (a) { - return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); - })); - // sort by primary user flag and signature creation time - const primaryUser = users.sort(function(a, b) { - const A = a.selfCertification; - const B = b.selfCertification; - return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; - }).pop(); - const { user, selfCertification: cert } = primaryUser; - if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { - throw new Error('Primary user is revoked'); + read(input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new UnsupportedError('Cannot read KDFParams'); } - return primaryUser; + this.hash = input[2]; + this.cipher = input[3]; + return 4; } /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * - * If the source key is a private key and the destination key is public, - * a private key is returned. - * @param {Key} sourceKey - Source key to merge - * @param {Date} [date] - Date to verify validity of signatures and keys - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} updated key - * @async + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value */ - async update(sourceKey, date = new Date(), config$1 = config) { - if (!this.hasSameFingerprintAs(sourceKey)) { - throw new Error('Primary key fingerprints must be equal to update the key'); - } - if (!this.isPrivate() && sourceKey.isPrivate()) { - // check for equal subkey packets - const equal = (this.subkeys.length === sourceKey.subkeys.length) && - (this.subkeys.every(destSubkey => { - return sourceKey.subkeys.some(srcSubkey => { - return destSubkey.hasSameFingerprintAs(srcSubkey); - }); - })); - if (!equal) { - throw new Error('Cannot update public key with private key if subkeys mismatch'); - } + write() { + return new Uint8Array([3, 1, this.hash, this.cipher]); + } +} - return sourceKey.update(this, config$1); - } - // from here on, either: - // - destination key is private, source key is public - // - the keys are of the same type - // hence we don't need to convert the destination key type - const updatedKey = this.clone(); - // revocation signatures - await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { - return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); - }); - // direct signatures - await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); - // update users - await Promise.all(sourceKey.users.map(async srcUser => { - // multiple users with the same ID/attribute are not explicitly disallowed by the spec - // hence we support them, just in case - const usersToUpdate = updatedKey.users.filter(dstUser => ( - (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || - (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) - )); - if (usersToUpdate.length > 0) { - await Promise.all( - usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) - ); - } else { - const newUser = srcUser.clone(); - newUser.mainKey = updatedKey; - updatedKey.users.push(newUser); - } - })); - // update subkeys - await Promise.all(sourceKey.subkeys.map(async srcSubkey => { - // multiple subkeys with same fingerprint might be preset - const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( - dstSubkey.hasSameFingerprintAs(srcSubkey) - )); - if (subkeysToUpdate.length > 0) { - await Promise.all( - subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) - ); - } else { - const newSubkey = srcSubkey.clone(); - newSubkey.mainKey = updatedKey; - updatedKey.subkeys.push(newSubkey); - } - })); +/** + * Encoded symmetric key for x25519 and x448 + * The payload format varies for v3 and v6 PKESK: + * the former includes an algorithm byte preceeding the encrypted session key. + * + * @module type/x25519x448_symkey + */ - return updatedKey; + +class ECDHXSymmetricKey { + static fromObject({ wrappedKey, algorithm }) { + const instance = new ECDHXSymmetricKey(); + instance.wrappedKey = wrappedKey; + instance.algorithm = algorithm; + return instance; } /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @param {Date} date - Use the given date instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Armored revocation certificate. - * @async + * - 1 octect for the length `l` + * - `l` octects of encoded session key data (with optional leading algorithm byte) + * @param {Uint8Array} bytes + * @returns {Number} Number of read bytes. */ - async getRevocationCertificate(date = new Date(), config$1 = config) { - const dataToVerify = { key: this.keyPacket }; - const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); - const packetlist = new PacketList(); - packetlist.push(revocationSignature); - return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate'); + read(bytes) { + let read = 0; + let followLength = bytes[read++]; + this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even + followLength -= followLength % 2; + this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength); read += followLength; } /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param {String} revocationCertificate - armored revocation certificate - * @param {Date} [date] - Date to verify the certificate - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Revoked key. - * @async + * Write an MontgomerySymmetricKey as an Uint8Array + * @returns {Uint8Array} Serialised data */ - async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { - const input = await unarmor(revocationCertificate, config$1); - const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); - const revocationSignature = packetlist.findPacket(enums.packet.signature); - if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { - throw new Error('Could not find revocation signature packet'); + write() { + return util.concatUint8Array([ + this.algorithm ? + new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) : + new Uint8Array([this.wrappedKey.length]), + this.wrappedKey + ]); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} keyAlgo - Public key algorithm + * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only) + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Uint8Array} data - Session key data to be encrypted + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @returns {Promise} Encrypted session key parameters. + * @async + */ +async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const { n, e } = publicParams; + const c = await publicKey.rsa.encrypt(data, n, e); + return { c }; } - if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { - throw new Error('Revocation signature does not match key'); + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + return publicKey.elgamal.encrypt(data, p, g, y); } - try { - await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); - } catch (e) { - throw util.wrapError('Could not verify revocation signature', e); + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicParams; + const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt( + oid, kdfParams, data, Q, fingerprint); + return { V, C: new ECDHSymmetricKey(C) }; } - const key = this.clone(); - key.revocationSignatures.push(revocationSignature); - return key; + case enums.publicKey.x25519: + case enums.publicKey.x448: { + if (symmetricAlgo && !util.isAES(symmetricAlgo)) { + // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276 + throw new Error('X25519 and X448 keys can only encrypt AES session keys'); + } + const { A } = publicParams; + const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt( + keyAlgo, data, A); + const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey }); + return { ephemeralPublicKey, C }; + } + default: + return []; } +} - /** - * Signs primary user of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signPrimaryUser(privateKeys, date, userID, config$1 = config) { - const { index, user } = await this.getPrimaryUser(date, userID, config$1); - const userSign = await user.certify(privateKeys, date, config$1); - const key = this.clone(); - key.users[index] = userSign; - return key; +/** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3} + * @param {module:enums.publicKey} algo - Public key algorithm + * @param {Object} publicKeyParams - Algorithm-specific public key parameters + * @param {Object} privateKeyParams - Algorithm-specific private key parameters + * @param {Object} sessionKeyParams - Encrypted session key parameters + * @param {Uint8Array} fingerprint - Recipient fingerprint + * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing + * (needed for constant-time processing in RSA and ElGamal) + * @returns {Promise} Decrypted data. + * @throws {Error} on sensitive decryption error, unless `randomPayload` is given + * @async + */ +async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) { + switch (algo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: { + const { c } = sessionKeyParams; + const { n, e } = publicKeyParams; + const { d, p, q, u } = privateKeyParams; + return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload); + } + case enums.publicKey.elgamal: { + const { c1, c2 } = sessionKeyParams; + const p = publicKeyParams.p; + const x = privateKeyParams.x; + return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload); + } + case enums.publicKey.ecdh: { + const { oid, Q, kdfParams } = publicKeyParams; + const { d } = privateKeyParams; + const { V, C } = sessionKeyParams; + return publicKey.elliptic.ecdh.decrypt( + oid, kdfParams, V, C.data, Q, d, fingerprint); + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicKeyParams; + const { k } = privateKeyParams; + const { ephemeralPublicKey, C } = sessionKeyParams; + if (C.algorithm !== null && !util.isAES(C.algorithm)) { + throw new Error('AES session key expected'); + } + return publicKey.elliptic.ecdhX.decrypt( + algo, ephemeralPublicKey, C.wrappedKey, A, k); + } + default: + throw new Error('Unknown public key encryption algorithm.'); + } +} + +/** + * Parse public key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name. + */ +function parsePublicKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const n = util.readMPI(bytes.subarray(read)); read += n.length + 2; + const e = util.readMPI(bytes.subarray(read)); read += e.length + 2; + return { read, publicParams: { n, e } }; + } + case enums.publicKey.dsa: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, q, g, y } }; + } + case enums.publicKey.elgamal: { + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const g = util.readMPI(bytes.subarray(read)); read += g.length + 2; + const y = util.readMPI(bytes.subarray(read)); read += y.length + 2; + return { read, publicParams: { p, g, y } }; + } + case enums.publicKey.ecdsa: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.eddsaLegacy: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + if (oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + Q = util.leftPad(Q, 33); + return { read: read, publicParams: { oid, Q } }; + } + case enums.publicKey.ecdh: { + const oid = new OID(); read += oid.read(bytes); + checkSupportedCurve(oid); + const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2; + const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read)); + return { read: read, publicParams: { oid, Q, kdfParams } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo)); read += A.length; + return { read, publicParams: { A } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); + } +} + +/** + * Parse private key material in binary form to get the key parameters + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @param {Object} publicParams - (ECC only) public params, needed to format some private params + * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name. + */ +function parsePrivateKeyParams(algo, bytes, publicParams) { + let read = 0; + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + const p = util.readMPI(bytes.subarray(read)); read += p.length + 2; + const q = util.readMPI(bytes.subarray(read)); read += q.length + 2; + const u = util.readMPI(bytes.subarray(read)); read += u.length + 2; + return { read, privateParams: { d, p, q, u } }; + } + case enums.publicKey.dsa: + case enums.publicKey.elgamal: { + const x = util.readMPI(bytes.subarray(read)); read += x.length + 2; + return { read, privateParams: { x } }; + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + let d = util.readMPI(bytes.subarray(read)); read += d.length + 2; + d = util.leftPad(d, payloadSize); + return { read, privateParams: { d } }; + } + case enums.publicKey.eddsaLegacy: { + const payloadSize = getCurvePayloadSize(algo, publicParams.oid); + if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) { + throw new Error('Unexpected OID for eddsaLegacy'); + } + let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2; + seed = util.leftPad(seed, payloadSize); + return { read, privateParams: { seed } }; + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const payloadSize = getCurvePayloadSize(algo); + const seed = util.readExactSubarray(bytes, read, read + payloadSize); read += seed.length; + return { read, privateParams: { seed } }; + } + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const payloadSize = getCurvePayloadSize(algo); + const k = util.readExactSubarray(bytes, read, read + payloadSize); read += k.length; + return { read, privateParams: { k } }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } +} - /** - * Signs all users of key - * @param {Array} privateKeys - decrypted private keys for signing - * @param {Date} [date] - Use the given date for signing, instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} Key with new certificate signature. - * @async - */ - async signAllUsers(privateKeys, date = new Date(), config$1 = config) { - const key = this.clone(); - key.users = await Promise.all(this.users.map(function(user) { - return user.certify(privateKeys, date, config$1); - })); - return key; - } +/** Returns the types comprising the encrypted session key of an algorithm + * @param {module:enums.publicKey} algo - The key algorithm + * @param {Uint8Array} bytes - The key material to parse + * @returns {Object} The session key parameters referenced by name. + */ +function parseEncSessionKeyParams(algo, bytes) { + let read = 0; + switch (algo) { + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: { + const c = util.readMPI(bytes.subarray(read)); + return { c }; + } - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [userID] - User ID to get instead of the primary user, if it exists - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { - const primaryKey = this.keyPacket; - const { user } = await this.getPrimaryUser(date, userID, config$1); - const results = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - return results; + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case enums.publicKey.elgamal: { + const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2; + const c2 = util.readMPI(bytes.subarray(read)); + return { c1, c2 }; + } + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case enums.publicKey.ecdh: { + const V = util.readMPI(bytes.subarray(read)); read += V.length + 2; + const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read)); + return { V, C }; + } + // Algorithm-Specific Fields for X25519 or X448 encrypted session keys: + // - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448). + // - A one-octet size of the following fields. + // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet). + // - The encrypted session key. + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const pointSize = getCurvePayloadSize(algo); + const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize); read += ephemeralPublicKey.length; + const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read)); + return { ephemeralPublicKey, C }; + } + default: + throw new UnsupportedError('Unknown public key encryption algorithm.'); } +} - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param {Array} [verificationKeys] - array of keys to verify certificate signatures - * @param {Date} [date] - Use the given date for verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} List of userID, signer's keyID and validity of signature. - * Signature validity is null if the verification keys do not correspond to the certificate. - * @async - */ - async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { - const primaryKey = this.keyPacket; - const results = []; - await Promise.all(this.users.map(async user => { - const signatures = verificationKeys ? - await user.verifyAllCertifications(verificationKeys, date, config$1) : - [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; +/** + * Convert params to MPI and serializes them in the proper order + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} params - The key parameters indexed by name + * @returns {Uint8Array} The array containing the MPIs. + */ +function serializeParams(algo, params) { + // Some algorithms do not rely on MPIs to store the binary params + const algosWithNativeRepresentation = new Set([ + enums.publicKey.ed25519, + enums.publicKey.x25519, + enums.publicKey.ed448, + enums.publicKey.x448 + ]); + const orderedParams = Object.keys(params).map(name => { + const param = params[name]; + if (!util.isUint8Array(param)) return param.write(); + return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param); + }); + return util.concatUint8Array(orderedParams); +} - results.push(...signatures.map( - signature => ({ - userID: user.userID ? user.userID.userID : null, - userAttribute: user.userAttribute, - keyID: signature.keyID, - valid: signature.valid - })) - ); - })); - return results; +/** + * Generate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Integer} bits - Bit length for RSA keys + * @param {module:type/oid} oid - Object identifier for ECC keys + * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name. + * @async + */ +function generateParams(algo, bits, oid) { + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({ + privateParams: { d, p, q, u }, + publicParams: { n, e } + })); + case enums.publicKey.ecdsa: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { d: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({ + privateParams: { seed: secret }, + publicParams: { oid: new OID(oid), Q } + })); + case enums.publicKey.ecdh: + return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({ + privateParams: { d: secret }, + publicParams: { + oid: new OID(oid), + Q, + kdfParams: new KDFParams({ hash, cipher }) + } + })); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({ + privateParams: { seed }, + publicParams: { A } + })); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({ + privateParams: { k }, + publicParams: { A } + })); + case enums.publicKey.dsa: + case enums.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + default: + throw new Error('Unknown public key algorithm.'); } } -['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { - Key.prototype[name] = - Subkey.prototype[name]; -}); - -// This library is free software; you can redistribute it and/or - /** - * Class that represents an OpenPGP Public Key + * Validate algorithm-specific key parameters + * @param {module:enums.publicKey} algo - The public key algorithm + * @param {Object} publicParams - Algorithm-specific public key parameters + * @param {Object} privateParams - Algorithm-specific private key parameters + * @returns {Promise} Whether the parameters are valid. + * @async */ -class PublicKey extends Key { - /** - * @param {PacketList} packetlist - The packets that form this key - */ - constructor(packetlist) { - super(); - this.keyPacket = null; - this.revocationSignatures = []; - this.directSignatures = []; - this.users = []; - this.subkeys = []; - if (packetlist) { - this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing public-key packet'); - } +async function validateParams$1(algo, publicParams, privateParams) { + if (!publicParams || !privateParams) { + throw new Error('Missing key parameters'); + } + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: { + const { n, e } = publicParams; + const { d, p, q, u } = privateParams; + return publicKey.rsa.validateParams(n, e, d, p, q, u); + } + case enums.publicKey.dsa: { + const { p, q, g, y } = publicParams; + const { x } = privateParams; + return publicKey.dsa.validateParams(p, q, g, y, x); + } + case enums.publicKey.elgamal: { + const { p, g, y } = publicParams; + const { x } = privateParams; + return publicKey.elgamal.validateParams(p, g, y, x); + } + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: { + const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)]; + const { oid, Q } = publicParams; + const { d } = privateParams; + return algoModule.validateParams(oid, Q, d); + } + case enums.publicKey.eddsaLegacy: { + const { Q, oid } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed); + } + case enums.publicKey.ed25519: + case enums.publicKey.ed448: { + const { A } = publicParams; + const { seed } = privateParams; + return publicKey.elliptic.eddsa.validateParams(algo, A, seed); } - } - - /** - * Returns true if this is a private key - * @returns {false} - */ - isPrivate() { - return false; - } - - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - return this; - } - - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const { A } = publicParams; + const { k } = privateParams; + return publicKey.elliptic.ecdhX.validateParams(algo, A, k); + } + default: + throw new Error('Unknown public key algorithm.'); } } /** - * Class that represents an OpenPGP Private key + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Promise} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + * @async */ -class PrivateKey extends PublicKey { - /** - * @param {PacketList} packetlist - The packets that form this key +async function getPrefixRandom(algo) { + const { blockSize } = getCipherParams(algo); + const prefixrandom = await getRandomBytes(blockSize); + const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + return util.concat([prefixrandom, repeat]); +} + +/** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo - Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key. */ - constructor(packetlist) { - super(); - this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); - if (!this.keyPacket) { - throw new Error('Invalid key: missing private-key packet'); - } - } +function generateSessionKey$1(algo) { + const { keySize } = getCipherParams(algo); + return getRandomBytes(keySize); +} - /** - * Returns true if this is a private key - * @returns {Boolean} - */ - isPrivate() { - return true; - } +/** + * Get implementation of the given AEAD mode + * @param {enums.aead} algo + * @returns {Object} + * @throws {Error} on invalid algo + */ +function getAEADMode(algo) { + const algoName = enums.read(enums.aead, algo); + return mode[algoName]; +} - /** - * Returns key as public key (shallow copy) - * @returns {PublicKey} New public Key - */ - toPublic() { - const packetlist = new PacketList(); - const keyPackets = this.toPacketList(); - for (const keyPacket of keyPackets) { - switch (keyPacket.constructor.tag) { - case enums.packet.secretKey: { - const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); - packetlist.push(pubKeyPacket); - break; - } - case enums.packet.secretSubkey: { - const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); - packetlist.push(pubSubkeyPacket); - break; - } - default: - packetlist.push(keyPacket); - } - } - return new PublicKey(packetlist); +/** + * Check whether the given curve OID is supported + * @param {module:type/oid} oid - EC object identifier + * @throws {UnsupportedError} if curve is not supported + */ +function checkSupportedCurve(oid) { + try { + oid.getName(); + } catch (e) { + throw new UnsupportedError('Unknown curve OID'); } +} - /** - * Returns ASCII armored text of key - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1); +/** + * Get encoded secret size for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getCurvePayloadSize(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.ecdh: + case enums.publicKey.eddsaLegacy: + return new publicKey.elliptic.CurveWithOID(oid).payloadSize; + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPayloadSize(algo); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return publicKey.elliptic.ecdhX.getPayloadSize(algo); + default: + throw new Error('Unknown elliptic algo'); } +} - /** - * Returns all keys that are available for decryption, matching the keyID when given - * This is useful to retrieve keys for session key decryption - * @param {module:type/keyid~KeyID} keyID, optional - * @param {Date} date, optional - * @param {String} userID, optional - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} Array of decryption keys. - * @async - */ - async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { - const primaryKey = this.keyPacket; - const keys = []; - for (let i = 0; i < this.subkeys.length; i++) { - if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { - try { - const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; - const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); - if (isValidDecryptionKeyPacket(bindingSignature, config$1)) { - keys.push(this.subkeys[i]); - } - } catch (e) {} - } - } - - // evaluate primary key - const primaryUser = await this.getPrimaryUser(date, userID, config$1); - if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && - isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) { - keys.push(this); - } - - return keys; +/** + * Get preferred signing hash algo for a given elliptic algo + * @param {module:enums.publicKey} algo - alrogithm identifier + * @param {module:type/oid} [oid] - curve OID if needed by algo + */ +function getPreferredCurveHashAlgo(algo, oid) { + switch (algo) { + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return publicKey.elliptic.getPreferredHashAlgo(oid); + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo); + default: + throw new Error('Unknown elliptic signing algo'); } +} - /** - * Returns true if the primary key or any subkey is decrypted. - * A dummy key is considered encrypted. - */ - isDecrypted() { - return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); - } +var crypto$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + generateParams: generateParams, + generateSessionKey: generateSessionKey$1, + getAEADMode: getAEADMode, + getCipherParams: getCipherParams, + getCurvePayloadSize: getCurvePayloadSize, + getPreferredCurveHashAlgo: getPreferredCurveHashAlgo, + getPrefixRandom: getPrefixRandom, + parseEncSessionKeyParams: parseEncSessionKeyParams, + parsePrivateKeyParams: parsePrivateKeyParams, + parsePublicKeyParams: parsePublicKeyParams, + publicKeyDecrypt: publicKeyDecrypt, + publicKeyEncrypt: publicKeyEncrypt, + serializeParams: serializeParams, + validateParams: validateParams$1 +}); - /** - * Check whether the private and public primary key parameters correspond - * Together with verification of binding signatures, this guarantees key integrity - * In case of gnu-dummy primary key, it is enough to validate any signing subkeys - * otherwise all encryption subkeys are validated - * If only gnu-dummy keys are found, we cannot properly validate so we throw an error - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @throws {Error} if validation was not successful and the key cannot be trusted - * @async - */ - async validate(config$1 = config) { - if (!this.isPrivate()) { - throw new Error('Cannot validate a public key'); - } +/** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ - let signingKeyPacket; - if (!this.keyPacket.isDummy()) { - signingKeyPacket = this.keyPacket; - } else { - /** - * It is enough to validate any signing keys - * since its binding signatures are also checked - */ - const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); - // This could again be a dummy key - if (signingKey && !signingKey.keyPacket.isDummy()) { - signingKeyPacket = signingKey.keyPacket; - } - } - if (signingKeyPacket) { - return signingKeyPacket.validate(); - } else { - const keys = this.getKeys(); - const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); - if (allDummies) { - throw new Error('Cannot validate an all-gnu-dummy key'); - } +// TODO move cfb and gcm to cipher +const mod$1 = { + /** @see module:crypto/cipher */ + cipher: cipher, + /** @see module:crypto/hash */ + hash: hash$1, + /** @see module:crypto/mode */ + mode: mode, + /** @see module:crypto/public_key */ + publicKey: publicKey, + /** @see module:crypto/signature */ + signature: signature, + /** @see module:crypto/random */ + random: random, + /** @see module:crypto/pkcs1 */ + pkcs1: pkcs1, + /** @see module:crypto/pkcs5 */ + pkcs5: pkcs5, + /** @see module:crypto/aes_kw */ + aesKW: aesKW +}; - return Promise.all(keys.map(async key => key.keyPacket.validate())); +Object.assign(mod$1, crypto$2); + +const ARGON2_TYPE = 0x02; // id +const ARGON2_VERSION = 0x13; +const ARGON2_SALT_SIZE = 16; + +class Argon2OutOfMemoryError extends Error { + constructor(...params) { + super(...params); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Argon2OutOfMemoryError); } - } - /** - * Clear private key parameters - */ - clearPrivateParams() { - this.getKeys().forEach(({ keyPacket }) => { - if (keyPacket.isDecrypted()) { - keyPacket.clearPrivateParams(); - } - }); + this.name = 'Argon2OutOfMemoryError'; } +} +// cache argon wasm module +let loadArgonWasmModule; +let argon2Promise; +// reload wasm module above this treshold, to deallocated used memory +const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; + +class Argon2S2K { /** - * Revokes the key - * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation - * @param {Date} date - optional, override the creationtime of the revocation signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New key with revocation signature. - * @async - */ - async revoke( - { - flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, - string: reasonForRevocationString = '' - } = {}, - date = new Date(), - config$1 = config - ) { - if (!this.isPrivate()) { - throw new Error('Need private key for revoking'); - } - const dataToSign = { key: this.keyPacket }; - const key = this.clone(); - key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), - reasonForRevocationString - }, date, undefined, undefined, undefined, config$1)); - return key; + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params; + + this.type = 'argon2'; + /** + * 16 bytes of salt + * @type {Uint8Array} + */ + this.salt = null; + /** + * number of passes + * @type {Integer} + */ + this.t = passes; + /** + * degree of parallelism (lanes) + * @type {Integer} + */ + this.p = parallelism; + /** + * exponent indicating memory size + * @type {Integer} + */ + this.encodedM = memoryExponent; } + generateSalt() { + this.salt = mod$1.random.getRandomBytes(ARGON2_SALT_SIZE); + } /** - * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. - * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. - * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA - * @param {String} options.curve (optional) Elliptic curve for ECC keys - * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date (optional) Override the creation date of the key and the key signatures - * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false - * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} - * @async - */ - async addSubkey(options = {}) { - const config$1 = { ...config, ...options.config }; - if (options.passphrase) { - throw new Error('Subkey could not be encrypted here, please encrypt whole key'); - } - if (options.rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); - } - const secretKeyPacket = this.keyPacket; - if (secretKeyPacket.isDummy()) { - throw new Error('Cannot add subkey to gnu-dummy primary key'); - } - if (!secretKeyPacket.isDecrypted()) { - throw new Error('Key is not decrypted'); - } - const defaultOptions = secretKeyPacket.getAlgorithmInfo(); - defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA - defaultOptions.rsaBits = defaultOptions.bits || 4096; - defaultOptions.curve = defaultOptions.curve || 'curve25519'; - options = sanitizeKeyOptions(options, defaultOptions); - const keyPacket = await generateSecretSubkey(options); - checkKeyRequirements(keyPacket, config$1); - const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); - const packetList = this.toPacketList(); - packetList.push(keyPacket, bindingSignature); - return new PrivateKey(packetList); - } -} + * Parsing function for argon2 string-to-key specifier. + * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; -// OpenPGP.js - An OpenPGP implementation in javascript + this.salt = bytes.subarray(i, i + 16); + i += 16; -// A Key can contain the following packets -const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ - PublicKeyPacket, - PublicSubkeyPacket, - SecretKeyPacket, - SecretSubkeyPacket, - UserIDPacket, - UserAttributePacket, - SignaturePacket -]); + this.t = bytes[i++]; + this.p = bytes[i++]; + this.encodedM = bytes[i++]; // memory size exponent, one-octect -/** - * Creates a PublicKey or PrivateKey depending on the packetlist in input - * @param {PacketList} - packets to parse - * @return {Key} parsed key - * @throws if no key packet was found - */ -function createKey(packetlist) { - for (const packet of packetlist) { - switch (packet.constructor.tag) { - case enums.packet.secretKey: - return new PrivateKey(packetlist); - case enums.packet.publicKey: - return new PublicKey(packetlist); - } + return i; } - throw new Error('No key packet found'); -} + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + const arr = [ + new Uint8Array([enums.write(enums.s2k, this.type)]), + this.salt, + new Uint8Array([this.t, this.p, this.encodedM]) + ]; -/** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * By default, primary and subkeys will be of same type. - * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA - * @param {String} options.curve Elliptic curve for ECC keys - * @param {Integer} options.rsaBits Number of bits for RSA keys - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Creation date of the key and the key signatures - * @param {Object} config - Full configuration - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ -async function generate$4(options, config) { - options.sign = true; // primary key is always a signing key - options = sanitizeKeyOptions(options); - options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); - let promises = [generateSecretKey(options, config)]; - promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); - const packets = await Promise.all(promises); + return util.concatUint8Array(arr); + } - const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; -} + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to `keySize` + * @throws {Argon2OutOfMemoryError|Errors} + * @async + */ + async produceKey(passphrase, keySize) { + const decodedM = 2 << (this.encodedM - 1); -/** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param {PrivateKey} options.privateKey The private key to reformat - * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } - * @param {String} options.passphrase Passphrase used to encrypt the resulting private key - * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires - * @param {Date} options.date Override the creation date of the key signatures - * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * @param {Object} config - Full configuration - * - * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} - * @async - * @static - * @private - */ -async function reformat(options, config) { - options = sanitize(options); - const { privateKey } = options; + try { + // on first load, the argon2 lib is imported and the WASM module is initialized. + // the two steps need to be atomic to avoid race conditions causing multiple wasm modules + // being loaded when `argon2Promise` is not initialized. + loadArgonWasmModule = loadArgonWasmModule || (await Promise.resolve().then(function () { return index$1; })).default; + argon2Promise = argon2Promise || loadArgonWasmModule(); + + // important to keep local ref to argon2 in case the module is reloaded by another instance + const argon2 = await argon2Promise; + + const passwordBytes = util.encodeUTF8(passphrase); + const hash = argon2({ + version: ARGON2_VERSION, + type: ARGON2_TYPE, + password: passwordBytes, + salt: this.salt, + tagLength: keySize, + memorySize: decodedM, + parallelism: this.p, + passes: this.t + }); - if (!privateKey.isPrivate()) { - throw new Error('Cannot reformat a public key'); + // a lot of memory was used, reload to deallocate + if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); + } + return hash; + } catch (e) { + if (e.message && ( + e.message.includes('Unable to grow instance memory') || // Chrome + e.message.includes('failed to grow memory') || // Firefox + e.message.includes('WebAssembly.Memory.grow') || // Safari + e.message.includes('Out of memory') // Safari iOS + )) { + throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2'); + } else { + throw e; + } + } } +} - if (privateKey.keyPacket.isDummy()) { - throw new Error('Cannot reformat a gnu-dummy primary key'); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +class GenericS2K { + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(s2kType, config$1 = config) { + /** + * Hash function identifier, or 0 for gnu-dummy keys + * @type {module:enums.hash | 0} + */ + this.algorithm = enums.hash.sha256; + /** + * enums.s2k identifier or 'gnu-dummy' + * @type {String} + */ + this.type = enums.read(enums.s2k, s2kType); + /** @type {Integer} */ + this.c = config$1.s2kIterationCountByte; + /** Eight bytes of salt in a binary string. + * @type {Uint8Array} + */ + this.salt = null; } - const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); - if (!isDecrypted) { - throw new Error('Key is not decrypted'); + generateSalt() { + switch (this.type) { + case 'salted': + case 'iterated': + this.salt = mod$1.random.getRandomBytes(8); + } } - const secretKeyPacket = privateKey.keyPacket; + getCount() { + // Exponent bias, defined in RFC4880 + const expbias = 6; - if (!options.subkeys) { - options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { - const secretSubkeyPacket = subkey.keyPacket; - const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; - const bindingSignature = await ( - getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) - ).catch(() => ({})); - return { - sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) - }; - })); + return (16 + (this.c & 15)) << ((this.c >> 4) + expbias); } - const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); - if (options.subkeys.length !== secretSubkeyPackets.length) { - throw new Error('Number of subkey options does not match number of subkeys'); - } + /** + * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param {Uint8Array} bytes - Payload of string-to-key specifier + * @returns {Integer} Actual length of the object. + */ + read(bytes) { + let i = 0; + this.algorithm = bytes[i++]; - options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); + switch (this.type) { + case 'simple': + break; - const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); - const revocationCertificate = await key.getRevocationCertificate(options.date, config); - key.revocationSignatures = []; - return { key, revocationCertificate }; + case 'salted': + this.salt = bytes.subarray(i, i + 8); + i += 8; + break; - function sanitize(options, subkeyDefaults = {}) { - options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; - options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; - options.date = options.date || subkeyDefaults.date; + case 'iterated': + this.salt = bytes.subarray(i, i + 8); + i += 8; - return options; - } -} + // Octet 10: count, a one-octet, coded value + this.c = bytes[i++]; + break; -/** - * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection - * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. - * @param {SecretKeyPacket} secretKeyPacket - * @param {SecretSubkeyPacket} secretSubkeyPackets - * @param {Object} options - * @param {Object} config - Full configuration - * @returns {PrivateKey} - */ -async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { - // set passphrase protection - if (options.passphrase) { - await secretKeyPacket.encrypt(options.passphrase, config); - } + case 'gnu': + if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') { + i += 3; // GNU + const gnuExtType = 1000 + bytes[i++]; + if (gnuExtType === 1001) { + this.type = 'gnu-dummy'; + // GnuPG extension mode 1001 -- don't write secret key at all + } else { + throw new UnsupportedError('Unknown s2k gnu protection mode.'); + } + } else { + throw new UnsupportedError('Unknown s2k type.'); + } + break; - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - await secretSubkeyPacket.encrypt(subkeyPassphrase, config); + default: + throw new UnsupportedError('Unknown s2k type.'); // unreachable } - })); - const packetlist = new PacketList(); - packetlist.push(secretKeyPacket); + return i; + } - await Promise.all(options.userIDs.map(async function(userID, index) { - function createPreferredAlgos(algos, preferredAlgo) { - return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + /** + * Serializes s2k information + * @returns {Uint8Array} Binary representation of s2k. + */ + write() { + if (this.type === 'gnu-dummy') { + return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]); } + const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])]; - const userIDPacket = UserIDPacket.fromObject(userID); - const dataToSign = {}; - dataToSign.userID = userIDPacket; - dataToSign.key = secretKeyPacket; - - const signatureProperties = {}; - signatureProperties.signatureType = enums.signature.certGeneric; - signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; - signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([ - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) - enums.symmetric.aes256, - enums.symmetric.aes128, - enums.symmetric.aes192 - ], config.preferredSymmetricAlgorithm); - if (config.aeadProtect) { - signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([ - enums.aead.eax, - enums.aead.ocb - ], config.preferredAEADAlgorithm); - } - signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ - // prefer fast asm.js implementations (SHA-256) - enums.hash.sha256, - enums.hash.sha512 - ], config.preferredHashAlgorithm); - signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ - enums.compression.zlib, - enums.compression.zip, - enums.compression.uncompressed - ], config.preferredCompressionAlgorithm); - if (index === 0) { - signatureProperties.isPrimaryUserID = true; - } - // integrity protection always enabled - signatureProperties.features = [0]; - signatureProperties.features[0] |= enums.features.modificationDetection; - if (config.aeadProtect) { - signatureProperties.features[0] |= enums.features.aead; - } - if (config.v5Keys) { - signatureProperties.features[0] |= enums.features.v5Keys; - } - if (options.keyExpirationTime > 0) { - signatureProperties.keyExpirationTime = options.keyExpirationTime; - signatureProperties.keyNeverExpires = false; + switch (this.type) { + case 'simple': + break; + case 'salted': + arr.push(this.salt); + break; + case 'iterated': + arr.push(this.salt); + arr.push(new Uint8Array([this.c])); + break; + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); } - const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + return util.concatUint8Array(arr); + } - return { userIDPacket, signaturePacket }; - })).then(list => { - list.forEach(({ userIDPacket, signaturePacket }) => { - packetlist.push(userIDPacket); - packetlist.push(signaturePacket); - }); - }); + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param {String} passphrase - Passphrase containing user input + * @returns {Promise} Produced key with a length corresponding to. + * hashAlgorithm hash length + * @async + */ + async produceKey(passphrase, numBytes) { + passphrase = util.encodeUTF8(passphrase); - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyOptions = options.subkeys[index]; - const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); - return { secretSubkeyPacket, subkeySignaturePacket }; - })).then(packets => { - packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { - packetlist.push(secretSubkeyPacket); - packetlist.push(subkeySignaturePacket); - }); - }); + const arr = []; + let rlength = 0; - // Add revocation signature packet for creating a revocation certificate. - // This packet should be removed before returning the key. - const dataToSign = { key: secretKeyPacket }; - packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, { - signatureType: enums.signature.keyRevocation, - reasonForRevocationFlag: enums.reasonForRevocation.noReason, - reasonForRevocationString: '' - }, options.date, undefined, undefined, undefined, config)); + let prefixlen = 0; + while (rlength < numBytes) { + let toHash; + switch (this.type) { + case 'simple': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]); + break; + case 'salted': + toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]); + break; + case 'iterated': { + const data = util.concatUint8Array([this.salt, passphrase]); + let datalen = data.length; + const count = Math.max(this.getCount(), datalen); + toHash = new Uint8Array(prefixlen + count); + toHash.set(data, prefixlen); + for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) { + toHash.copyWithin(pos, prefixlen, pos); + } + break; + } + case 'gnu': + throw new Error('GNU s2k type not supported.'); + default: + throw new Error('Unknown s2k type.'); + } + const result = await mod$1.hash.digest(this.algorithm, toHash); + arr.push(result); + rlength += result.length; + prefixlen++; + } - if (options.passphrase) { - secretKeyPacket.clearPrivateParams(); + return util.concatUint8Array(arr).subarray(0, numBytes); } +} - await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { - const subkeyPassphrase = options.subkeys[index].passphrase; - if (subkeyPassphrase) { - secretSubkeyPacket.clearPrivateParams(); +const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]); + +/** + * Instantiate a new S2K instance of the given type + * @param {module:enums.s2k} type + * @oaram {Object} [config] + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromType(type, config$1 = config) { + switch (type) { + case enums.s2k.argon2: + return new Argon2S2K(config$1); + case enums.s2k.iterated: + case enums.s2k.gnu: + case enums.s2k.salted: + case enums.s2k.simple: + return new GenericS2K(type, config$1); + default: + throw new UnsupportedError('Unsupported S2K type'); + } +} + +/** + * Instantiate a new S2K instance based on the config settings + * @oaram {Object} config + * @returns {Object} New s2k object + * @throws {Error} for unknown or unsupported types + */ +function newS2KFromConfig(config) { + const { s2kType } = config; + + if (!allowedS2KTypesForEncryption.has(s2kType)) { + throw new Error('The provided `config.s2kType` value is not allowed'); + } + + return newS2KFromType(s2kType, config); +} + +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, u32$1 = Uint32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +// see fleb note +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new u32$1(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return [b, r]; +}; +var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >>> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32$1 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, buf, st) { + // source length + var sl = dat.length; + if (!sl || (st && st.f && !st.l)) + return buf || new u8(0); + // have to estimate size + var noBuf = !buf || st; + // no state + var noSt = !st || st.i; + if (!st) + st = {}; + // Assumes roughly 33% compression ratio average + if (!buf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (noBuf) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >>> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17; + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >>> 8; + d[o + 2] |= v >>> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return [et, 0]; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return [v, 1]; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return [new u8(tr), mbt]; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return [cl.subarray(0, cli), s]; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >>> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; + var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; + var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; + var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + lcfreq[lclt[i] & 31]++; + for (var i = 0; i < lcdt.length; ++i) + lcfreq[lcdt[i] & 31]++; + var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); + if (flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + if (syms[i] > 255) { + var len = (syms[i] >>> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; + var dst = syms[i] & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new u32$1([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, lst) { + var s = dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var pos = 0; + if (!lvl || s < 8) { + for (var i = 0; i <= s; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[pos >> 3] = lst; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } } - })); - - return new PrivateKey(packetlist); -} - + else { + var opt = deo[lvl - 1]; + var n = opt >>> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = new u16(32768), head = new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new u32$1(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx bitpos + var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; + for (; i < s; ++i) { + // hash value + // deopt when i > s - 3 - at end, deopt acceptable + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && rem > 423) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = (i - dif + j + 32768) & 32767; + var pti = prev[ti]; + var cd = (ti - pti + 32768) & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += (imod - pimod + 32768) & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one Uint32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + // this is the easiest way to avoid needing to maintain state + if (!lst && pos & 7) + pos = wfblk(w, pos + 1, et); + } + return slc(o, 0, pre + shft(pos) + post); +}; +// Alder32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); + } + }; +}; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st); +}; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1); +}; +// zlib footer: -4 to -0 is Adler32 /** - * Reads an (optionally armored) OpenPGP key and returns a key object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static + * Streaming DEFLATE compression */ -async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { - throw new Error('Armored text not of type key'); +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (!cb && typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return createKey(packetlist); -} - + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, !f), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.d = final; + this.p(chunk, final || false); + }; + return Deflate; +}()); /** - * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object - * @param {Object} options - * @param {String} [options.armoredKey] - Armored key to be parsed - * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Key object. - * @async - * @static + * Streaming DEFLATE decompression */ -async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!armoredKey && !binaryKey) { - throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); - } - if (armoredKey && !util.isString(armoredKey)) { - throw new Error('readPrivateKey: options.armoredKey must be a string'); - } - if (binaryKey && !util.isUint8Array(binaryKey)) { - throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - let input; - if (armoredKey) { - const { type, data } = await unarmor(armoredKey, config$1); - if (!(type === enums.armor.privateKey)) { - throw new Error('Armored text not of type private key'); - } - input = data; - } else { - input = binaryKey; - } - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - return new PrivateKey(packetlist); -} - +var Inflate = /*#__PURE__*/ (function () { + /** + * Creates an inflation stream + * @param cb The callback to call whenever data is inflated + */ + function Inflate(cb) { + this.s = {}; + this.p = new u8(0); + this.ondata = cb; + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + var l = this.p.length; + var n = new u8(l + c.length); + n.set(this.p), n.set(c, l), this.p = n; + }; + Inflate.prototype.c = function (final) { + this.d = this.s.i = final || false; + var bts = this.s.b; + var dt = inflt(this.p, this.o, this.s); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); /** - * Reads an (optionally armored) OpenPGP key block and returns a list of key objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static + * Streaming Zlib compression */ -async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { - throw new Error('Armored text not of type key'); +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = createKey(oneKeyList); - keys.push(newKey); - } - return keys; -} - + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + this.c.p(c); + var raw = dopt(c, this.o, this.v && 2, f && 4, !f); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + return Zlib; +}()); /** - * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects - * @param {Object} options - * @param {String} [options.armoredKeys] - Armored keys to be parsed - * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Key objects. - * @async - * @static + * Streaming Zlib decompression */ -async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { - config$1 = { ...config, ...config$1 }; - let input = armoredKeys || binaryKeys; - if (!input) { - throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); - } - if (armoredKeys && !util.isString(armoredKeys)) { - throw new Error('readPrivateKeys: options.armoredKeys must be a string'); - } - if (binaryKeys && !util.isUint8Array(binaryKeys)) { - throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); - } - if (armoredKeys) { - const { type, data } = await unarmor(armoredKeys, config$1); - if (type !== enums.armor.privateKey) { - throw new Error('Armored text not of type private key'); +var Unzlib = /*#__PURE__*/ (function () { + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + function Unzlib(cb) { + this.v = 1; + Inflate.call(this, cb); } - input = data; - } - const keys = []; - const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); - const keyIndex = packetlist.indexOfTag(enums.packet.secretKey); - if (keyIndex.length === 0) { - throw new Error('No secret key packet found'); - } - for (let i = 0; i < keyIndex.length; i++) { - const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); - const newKey = new PrivateKey(oneKeyList); - keys.push(newKey); - } - return keys; + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 2 && !final) + return; + this.p = this.p.subarray(2), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; } +catch (e) { } // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -// A Message can contain the following packets -const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ - LiteralDataPacket, - CompressedDataPacket, - AEADEncryptedDataPacket, - SymEncryptedIntegrityProtectedDataPacket, - SymmetricallyEncryptedDataPacket, - PublicKeyEncryptedSessionKeyPacket, - SymEncryptedSessionKeyPacket, - OnePassSignaturePacket, - SignaturePacket -]); -// A SKESK packet can contain the following packets -const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); -// A detached signature can contain the following packets -const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); /** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + * Implementation of the Literal Data Packet (Tag 11) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. */ -class Message { +class LiteralDataPacket { + static get tag() { + return enums.packet.literalData; + } + /** - * @param {PacketList} packetlist - The packets that form this message + * @param {Date} date - The creation date of the literal package */ - constructor(packetlist) { - this.packets = packetlist || new PacketList(); + constructor(date = new Date()) { + this.format = enums.literal.utf8; // default format for literal data packets + this.date = util.normalizeDate(date); + this.text = null; // textual data representation + this.data = null; // literal data representation + this.filename = ''; } /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns {Array} Array of keyID objects. - */ - getEncryptionKeyIDs() { - const keyIDs = []; - const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - pkESKeyPacketlist.forEach(function(packet) { - keyIDs.push(packet.publicKeyID); - }); - return keyIDs; + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param {String | ReadableStream} text - Any native javascript string + * @param {enums.literal} [format] - The format of the string of bytes + */ + setText(text, format = enums.literal.utf8) { + this.format = format; + this.text = text; + this.data = null; } /** - * Returns the key IDs of the keys that signed the message - * @returns {Array} Array of keyID objects. + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {String | ReadableStream} Literal data as text. */ - getSigningKeyIDs() { - const msg = this.unwrapCompressed(); - // search for one pass signatures - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); - if (onePassSigList.length > 0) { - return onePassSigList.map(packet => packet.issuerKeyID); + getText(clone = false) { + if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read + this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone))); } - // if nothing found look for signature packets - const signatureList = msg.packets.filterByTag(enums.packet.signature); - return signatureList.map(packet => packet.issuerKeyID); + return this.text; } /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Date} [date] - Use the given date for key verification instead of the current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with decrypted content. - * @async + * Set the packet data to value represented by the provided string of bytes. + * @param {Uint8Array | ReadableStream} bytes - The string of bytes + * @param {enums.literal} format - The format of the string of bytes */ - async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { - const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1); + setBytes(bytes, format) { + this.format = format; + this.data = bytes; + this.text = null; + } - const symEncryptedPacketlist = this.packets.filterByTag( - enums.packet.symmetricallyEncryptedData, - enums.packet.symEncryptedIntegrityProtectedData, - enums.packet.aeadEncryptedData - ); - if (symEncryptedPacketlist.length === 0) { - throw new Error('No encrypted data found'); + /** + * Get the byte sequence representing the literal packet data + * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again + * @returns {Uint8Array | ReadableStream} A sequence of bytes. + */ + getBytes(clone = false) { + if (this.data === null) { + // encode UTF8 and normalize EOL to \r\n + this.data = util.canonicalizeEOL(util.encodeUTF8(this.text)); } + if (clone) { + return passiveClone(this.data); + } + return this.data; + } - const symEncryptedPacket = symEncryptedPacketlist[0]; - let exception = null; - const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { - if (!util.isUint8Array(data) || !util.isString(algorithmName)) { - throw new Error('Invalid session key for decryption.'); - } - - try { - const algo = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.decrypt(algo, data, config$1); - } catch (e) { - util.printDebugError(e); - exception = e; - } - })); - // We don't await stream.cancel here because it only returns when the other copy is canceled too. - cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. - symEncryptedPacket.encrypted = null; - await decryptedPromise; - if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { - throw exception || new Error('Decryption failed.'); - } + /** + * Sets the filename of the literal packet data + * @param {String} filename - Any native javascript string + */ + setFilename(filename) { + this.filename = filename; + } - const resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - return resultMsg; + /** + * Get the filename of the literal packet data + * @returns {String} Filename. + */ + getFilename() { + return this.filename; } /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param {Array} [decryptionKeys] - Private keys with decrypted secret data - * @param {Array} [passwords] - Passwords used to decrypt - * @param {Date} [date] - Use the given date for key verification, instead of current time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * Parsing function for a literal data packet (tag 11). + * + * @param {Uint8Array | ReadableStream} input - Payload of a tag 11 packet + * @returns {Promise} Object representation. * @async */ - async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) { - let decryptedSessionKeyPackets = []; + async read(bytes) { + await parse(bytes, async reader => { + // - A one-octet field that describes how the data is formatted. + const format = await reader.readByte(); // enums.literal - let exception; - if (passwords) { - const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); - if (skeskPackets.length === 0) { - throw new Error('No symmetrically encrypted session key packet found.'); - } - await Promise.all(passwords.map(async function(password, i) { - let packets; - if (i) { - packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); - } else { - packets = skeskPackets; - } - await Promise.all(packets.map(async function(skeskPacket) { - try { - await skeskPacket.decrypt(password); - decryptedSessionKeyPackets.push(skeskPacket); - } catch (err) { - util.printDebugError(err); - } - })); - })); - } else if (decryptionKeys) { - const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); - if (pkeskPackets.length === 0) { - throw new Error('No public key encrypted session key packet found.'); - } - await Promise.all(pkeskPackets.map(async function(pkeskPacket) { - await Promise.all(decryptionKeys.map(async function(decryptionKey) { - let algos = [ - enums.symmetric.aes256, // Old OpenPGP.js default fallback - enums.symmetric.aes128, // RFC4880bis fallback - enums.symmetric.tripledes, // RFC4880 fallback - enums.symmetric.cast5 // Golang OpenPGP fallback - ]; - try { - const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere. - if (primaryUser.selfCertification.preferredSymmetricAlgorithms) { - algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms); - } - } catch (e) {} + const filename_len = await reader.readByte(); + this.filename = util.decodeUTF8(await reader.readBytes(filename_len)); - // do not check key expiration to allow decryption of old messages - const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); - await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { - if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) { - return; - } - if (!decryptionKeyPacket.isDecrypted()) { - throw new Error('Decryption key is not decrypted.'); - } + this.date = util.readDate(await reader.readBytes(4)); - // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. - const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || - pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal - ); + let data = reader.remainder(); + if (isArrayStream(data)) data = await readToEnd(data); + this.setBytes(data, format); + }); + } - if (doConstantTimeDecryption) { - // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, - // either with the successfully decrypted session key, or with a randomly generated one. - // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on - // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: - // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the - // randomly generated keys of the remaining key types. - // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly - // generated session keys. - // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. + /** + * Creates a Uint8Array representation of the packet, excluding the data + * + * @returns {Uint8Array} Uint8Array representation of the packet. + */ + writeHeader() { + const filename = util.encodeUTF8(this.filename); + const filename_length = new Uint8Array([filename.length]); - const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times - await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => { - const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); - pkeskPacketCopy.read(serialisedPKESK); - const randomSessionKey = { - sessionKeyAlgorithm, - sessionKey: mod.generateSessionKey(sessionKeyAlgorithm) - }; - try { - await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); - decryptedSessionKeyPackets.push(pkeskPacketCopy); - } catch (err) { - // `decrypt` can still throw some non-security-sensitive errors - util.printDebugError(err); - exception = err; - } - })); + const format = new Uint8Array([this.format]); + const date = util.writeDate(this.date); - } else { - try { - await pkeskPacket.decrypt(decryptionKeyPacket); - if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) { - throw new Error('A non-preferred symmetric algorithm was used.'); - } - decryptedSessionKeyPackets.push(pkeskPacket); - } catch (err) { - util.printDebugError(err); - exception = err; - } - } - })); - })); - cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. - pkeskPacket.encrypted = null; - })); - } else { - throw new Error('No key or password specified.'); - } + return util.concatUint8Array([format, filename_length, filename, date]); + } - if (decryptedSessionKeyPackets.length > 0) { - // Return only unique session keys - if (decryptedSessionKeyPackets.length > 1) { - const seen = new Set(); - decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { - const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); - if (seen.has(k)) { - return false; - } - seen.add(k); - return true; - }); - } + /** + * Creates a Uint8Array representation of the packet + * + * @returns {Uint8Array | ReadableStream} Uint8Array representation of the packet. + */ + write() { + const header = this.writeHeader(); + const data = this.getBytes(); + + return util.concat([header, data]); + } +} - return decryptedSessionKeyPackets.map(packet => ({ - data: packet.sessionKey, - algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm) - })); - } - throw exception || new Error('Session key decryption failed.'); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ +class KeyID { + constructor() { + this.bytes = ''; } /** - * Get literal data that is the body of the message - * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + * Parsing method for a key id + * @param {Uint8Array} bytes - Input to read the key id from */ - getLiteralData() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getBytes()) || null; + read(bytes) { + this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8)); + return this.bytes.length; } /** - * Get filename from literal data packet - * @returns {(String|null)} Filename of literal data packet as string. + * Serializes the Key ID + * @returns {Uint8Array} Key ID as a Uint8Array. */ - getFilename() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - return (literal && literal.getFilename()) || null; + write() { + return util.stringToUint8Array(this.bytes); } /** - * Get literal data as text - * @returns {(String|null)} Literal body of the message interpreted as text. + * Returns the Key ID represented as a hexadecimal string + * @returns {String} Key ID as a hexadecimal string. */ - getText() { - const msg = this.unwrapCompressed(); - const literal = msg.packets.findPacket(enums.packet.literalData); - if (literal) { - return literal.getText(); - } - return null; + toHex() { + return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes)); } /** - * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. - * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for - * @param {Date} [date] - Date to select algorithm preferences at - * @param {Array} [userIDs] - User IDs to select algorithm preferences for - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. - * @async + * Checks equality of Key ID's + * @param {KeyID} keyID + * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard */ - static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { - const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1); - const algorithmName = enums.read(enums.symmetric, algo); - const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ? - enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) : - undefined; - - await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() - .catch(() => null) // ignore key strength requirements - .then(maybeKey => { - if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) { - throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); - } - }) - )); + equals(keyID, matchWildcard = false) { + return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes; + } - const sessionKeyData = mod.generateSessionKey(algo); - return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName }; + /** + * Checks to see if the Key ID is unset + * @returns {Boolean} True if the Key ID is null. + */ + isNull() { + return this.bytes === ''; } /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - Password(s) for message encryption - * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] - * @param {Date} [date] - Override the creation date of the literal package - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async + * Checks to see if the Key ID is a "wildcard" Key ID (all zeros) + * @returns {Boolean} True if this is a wildcard Key ID. */ - async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - if (sessionKey) { - if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { - throw new Error('Invalid session key for encryption.'); - } - } else if (encryptionKeys && encryptionKeys.length) { - sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); - } else if (passwords && passwords.length) { - sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); - } else { - throw new Error('No keys, passwords, or session key provided.'); - } + isWildcard() { + return /^0+$/.test(this.toHex()); + } - const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; + static mapToHex(keyID) { + return keyID.toHex(); + } - const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); + static fromID(hex) { + const keyID = new KeyID(); + keyID.read(util.hexToUint8Array(hex)); + return keyID; + } - let symEncryptedPacket; - if (aeadAlgorithmName) { - symEncryptedPacket = new AEADEncryptedDataPacket(); - symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName); - } else { - symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket(); - } - symEncryptedPacket.packets = this.packets; + static wildcard() { + const keyID = new KeyID(); + keyID.read(new Uint8Array(8)); + return keyID; + } +} - const algorithm = enums.write(enums.symmetric, algorithmName); - await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new PacketList(); // remove packets after encryption - return msg; + +// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification. +const verified = Symbol('verified'); + +// A salt notation is used to randomize signatures. +// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks +// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170). +// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g. +// some chosen-prefix attacks. +// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt. +const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org'; + +// GPG puts the Issuer and Signature subpackets in the unhashed area. +// Tampering with those invalidates the signature, so we still trust them and parse them. +// All other unhashed subpackets are ignored. +const allowedUnhashedSubpackets = new Set([ + enums.signatureSubpacket.issuerKeyID, + enums.signatureSubpacket.issuerFingerprint, + enums.signatureSubpacket.embeddedSignature +]); + +/** + * Implementation of the Signature Packet (Tag 2) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + */ +class SignaturePacket { + static get tag() { + return enums.packet.signature; + } + + constructor() { + this.version = null; + /** @type {enums.signature} */ + this.signatureType = null; + /** @type {enums.hash} */ + this.hashAlgorithm = null; + /** @type {enums.publicKey} */ + this.publicKeyAlgorithm = null; + + this.signatureData = null; + this.unhashedSubpackets = []; + this.unknownSubpackets = []; + this.signedHashValue = null; + this.salt = null; + + this.created = null; + this.signatureExpirationTime = null; + this.signatureNeverExpires = true; + this.exportable = null; + this.trustLevel = null; + this.trustAmount = null; + this.regularExpression = null; + this.revocable = null; + this.keyExpirationTime = null; + this.keyNeverExpires = null; + this.preferredSymmetricAlgorithms = null; + this.revocationKeyClass = null; + this.revocationKeyAlgorithm = null; + this.revocationKeyFingerprint = null; + this.issuerKeyID = new KeyID(); + this.rawNotations = []; + this.notations = {}; + this.preferredHashAlgorithms = null; + this.preferredCompressionAlgorithms = null; + this.keyServerPreferences = null; + this.preferredKeyServer = null; + this.isPrimaryUserID = null; + this.policyURI = null; + this.keyFlags = null; + this.signersUserID = null; + this.reasonForRevocationFlag = null; + this.reasonForRevocationString = null; + this.features = null; + this.signatureTargetPublicKeyAlgorithm = null; + this.signatureTargetHashAlgorithm = null; + this.signatureTargetHash = null; + this.embeddedSignature = null; + this.issuerKeyVersion = null; + this.issuerFingerprint = null; + this.preferredAEADAlgorithms = null; + this.preferredCipherSuites = null; + + this.revoked = null; + this[verified] = null; } /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param {Uint8Array} sessionKey - session key for encryption - * @param {String} algorithmName - session key algorithm - * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {Array} [encryptionKeys] - Public key(s) for message encryption - * @param {Array} [passwords] - For message encryption - * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs - * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [date] - Override the date - * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with encrypted content. - * @async + * parsing function for a signature packet (tag 2). + * @param {String} bytes - Payload of a tag 2 packet + * @returns {SignaturePacket} Object representation. */ - static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { - const packetlist = new PacketList(); - const algorithm = enums.write(enums.symmetric, algorithmName); - const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); + read(bytes, config$1 = config) { + let i = 0; + this.version = bytes[i++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); + } - if (encryptionKeys) { - const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { - const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket(); - pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = algorithm; - await pkESKeyPacket.encrypt(encryptionKey.keyPacket); - delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption - return pkESKeyPacket; - })); - packetlist.push(...results); + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`); } - if (passwords) { - const testDecrypt = async function(keyPacket, password) { - try { - await keyPacket.decrypt(password); - return 1; - } catch (e) { - return 0; - } - }; - const sum = (accumulator, currentValue) => accumulator + currentValue; + this.signatureType = bytes[i++]; + this.publicKeyAlgorithm = bytes[i++]; + this.hashAlgorithm = bytes[i++]; - const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { - const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); - symEncryptedSessionKeyPacket.sessionKey = sessionKey; - symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; - if (aeadAlgorithm) { - symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; - } - await symEncryptedSessionKeyPacket.encrypt(password, config$1); + // hashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), true); + if (!this.created) { + throw new Error('Missing signature creation time subpacket.'); + } - if (config$1.passwordCollisionCheck) { - const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); - if (results.reduce(sum) !== 1) { - return encryptPassword(sessionKey, algorithm, password); - } - } + // A V4 signature hashes the packet body + // starting from its first field, the version number, through the end + // of the hashed subpacket data. Thus, the fields hashed are the + // signature version, the signature type, the public-key algorithm, the + // hash algorithm, the hashed subpacket length, and the hashed + // subpacket body. + this.signatureData = bytes.subarray(0, i); - delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption - return symEncryptedSessionKeyPacket; - }; + // unhashed subpackets + i += this.readSubPackets(bytes.subarray(i, bytes.length), false); - const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd))); - packetlist.push(...results); + // Two-octet field holding left 16 bits of signed hash value. + this.signedHashValue = bytes.subarray(i, i + 2); + i += 2; + + // Only for v6 signatures, a variable-length field containing: + if (this.version === 6) { + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[i++]; + + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(i, i + saltLength); + i += saltLength; } - return new Message(packetlist); + const signatureMaterial = bytes.subarray(i, bytes.length); + const { read, signatureParams } = mod$1.signature.parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial); + if (read < signatureMaterial.length) { + throw new Error('Error reading MPIs'); + } + this.params = signatureParams; } /** - * Sign the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to add to the message - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New message with signed content. - * @async + * @returns {Uint8Array | ReadableStream} */ - async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const packetlist = new PacketList(); + writeParams() { + if (this.params instanceof Promise) { + return fromAsync( + async () => mod$1.serializeParams(this.publicKeyAlgorithm, await this.params) + ); + } + return mod$1.serializeParams(this.publicKeyAlgorithm, this.params); + } - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); + write() { + const arr = []; + arr.push(this.signatureData); + arr.push(this.writeUnhashedSubPackets()); + arr.push(this.signedHashValue); + if (this.version === 6) { + arr.push(new Uint8Array([this.salt.length])); + arr.push(this.salt); } + arr.push(this.writeParams()); + return util.concat(arr); + } - let i; - let existingSigPacketlist; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; + /** + * Signs provided data. This needs to be done prior to serialization. + * @param {SecretKeyPacket} key - Private key used to sign the message. + * @param {Object} data - Contains packets to be signed. + * @param {Date} [date] - The signature creation time. + * @param {Boolean} [detached] - Whether to create a detached signature + * @throws {Error} if signing failed + * @async + */ + async sign(key, data, date = new Date(), detached = false, config) { + this.version = key.version; - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - const signaturePacket = existingSigPacketlist[i]; - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signaturePacket.signatureType; - onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; - onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; - onePassSig.issuerKeyID = signaturePacket.issuerKeyID; - if (!signingKeys.length && i === 0) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); - } - } + this.created = util.normalizeDate(date); + this.issuerKeyVersion = key.version; + this.issuerFingerprint = key.getFingerprintBytes(); + this.issuerKeyID = key.getKeyID(); - await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) { - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); - } - const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i]; - const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1); - const onePassSig = new OnePassSignaturePacket(); - onePassSig.signatureType = signatureType; - onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1); - onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm; - onePassSig.issuerKeyID = signingKey.getKeyID(); - if (i === signingKeys.length - 1) { - onePassSig.flags = 1; + const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])]; + + // add randomness to the signature + if (this.version === 6) { + const saltLength = saltLengthForHash(this.hashAlgorithm); + if (this.salt === null) { + this.salt = mod$1.random.getRandomBytes(saltLength); + } else if (saltLength !== this.salt.length) { + throw new Error('Provided salt does not have the required length'); + } + } else if (config.nonDeterministicSignaturesViaNotation) { + const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME)); + // since re-signing the same object is not supported, it's not expected to have multiple salt notations, + // but we guard against it as a sanity check + if (saltNotations.length === 0) { + const saltValue = mod$1.random.getRandomBytes(saltLengthForHash(this.hashAlgorithm)); + this.rawNotations.push({ + name: SALT_NOTATION_NAME, + value: saltValue, + humanReadable: false, + critical: false + }); + } else { + throw new Error('Unexpected existing salt notation'); } - return onePassSig; - })).then(onePassSignatureList => { - onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig)); - }); + } - packetlist.push(literalDataPacket); - packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1))); + // Add hashed subpackets + arr.push(this.writeHashedSubPackets()); - return new Message(packetlist); - } + // Remove unhashed subpackets, in case some allowed unhashed + // subpackets existed, in order not to duplicate them (in both + // the hashed and unhashed subpackets) when re-signing. + this.unhashedSubpackets = []; - /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param {module:enums.compression} algo - compression algorithm - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Message} New message with compressed content. - */ - compress(algo, config$1 = config) { - if (algo === enums.compression.uncompressed) { - return this; - } + this.signatureData = util.concat(arr); - const compressed = new CompressedDataPacket(config$1); - compressed.algorithm = algo; - compressed.packets = this.packets; + const toHash = this.toHash(this.signatureType, data, detached); + const hash = await this.hash(this.signatureType, data, toHash, detached); - const packetList = new PacketList(); - packetList.push(compressed); + this.signedHashValue = slice(clone(hash), 0, 2); + const signed = async () => mod$1.signature.sign( + this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash) + ); + if (util.isStream(hash)) { + this.params = signed(); + } else { + this.params = await signed(); - return new Message(packetList); + // Store the fact that this signature is valid, e.g. for when we call `await + // getLatestValidSignature(this.revocationSignatures, key, data)` later. + // Note that this only holds up if the key and data passed to verify are the + // same as the ones passed to sign. + this[verified] = true; + } } /** - * Create a detached signature for the message (the literal data packet of the message) - * @param {Array} signingKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creation time of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New detached signature of message content. - * @async + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns {Uint8Array} Subpacket data. */ - async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = this.packets.findPacket(enums.packet.literalData); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); + writeHashedSubPackets() { + const sub = enums.signatureSubpacket; + const arr = []; + let bytes; + if (this.created === null) { + throw new Error('Missing signature creation time'); + } + arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created))); + if (this.signatureExpirationTime !== null) { + arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4))); + } + if (this.exportable !== null) { + arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0]))); + } + if (this.trustLevel !== null) { + bytes = new Uint8Array([this.trustLevel, this.trustAmount]); + arr.push(writeSubPacket(sub.trustSignature, true, bytes)); + } + if (this.regularExpression !== null) { + arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression)); + } + if (this.revocable !== null) { + arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0]))); + } + if (this.keyExpirationTime !== null) { + arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4))); + } + if (this.preferredSymmetricAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms)); + arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes)); + } + if (this.revocationKeyClass !== null) { + bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); + bytes = util.concat([bytes, this.revocationKeyFingerprint]); + arr.push(writeSubPacket(sub.revocationKey, false, bytes)); + } + if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) { + // If the version of [the] key is greater than 4, this subpacket + // MUST NOT be included in the signature. + arr.push(writeSubPacket(sub.issuerKeyID, true, this.issuerKeyID.write())); + } + this.rawNotations.forEach(({ name, value, humanReadable, critical }) => { + bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])]; + const encodedName = util.encodeUTF8(name); + // 2 octets of name length + bytes.push(util.writeNumber(encodedName.length, 2)); + // 2 octets of value length + bytes.push(util.writeNumber(value.length, 2)); + bytes.push(encodedName); + bytes.push(value); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.notationData, critical, bytes)); + }); + if (this.preferredHashAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms)); + arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes)); + } + if (this.preferredCompressionAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms)); + arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes)); + } + if (this.keyServerPreferences !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences)); + arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes)); + } + if (this.preferredKeyServer !== null) { + arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer))); + } + if (this.isPrimaryUserID !== null) { + arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); + } + if (this.policyURI !== null) { + arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI))); + } + if (this.keyFlags !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags)); + arr.push(writeSubPacket(sub.keyFlags, true, bytes)); + } + if (this.signersUserID !== null) { + arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID))); + } + if (this.reasonForRevocationFlag !== null) { + bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes)); + } + if (this.features !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features)); + arr.push(writeSubPacket(sub.features, false, bytes)); + } + if (this.signatureTargetPublicKeyAlgorithm !== null) { + bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; + bytes.push(util.stringToUint8Array(this.signatureTargetHash)); + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.signatureTarget, true, bytes)); + } + if (this.embeddedSignature !== null) { + arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write())); } - return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - } - - /** - * Verify message signatures - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signatures. - * @async - */ - async verify(verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); + if (this.issuerFingerprint !== null) { + bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint]; + bytes = util.concat(bytes); + arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes)); } - if (isArrayStream(msg.packets.stream)) { - msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + if (this.preferredAEADAlgorithms !== null) { + bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms)); + arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes)); } - const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); - const signatureList = msg.packets.filterByTag(enums.packet.signature); - if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { - await Promise.all(onePassSigList.map(async onePassSig => { - onePassSig.correspondingSig = new Promise((resolve, reject) => { - onePassSig.correspondingSigResolve = resolve; - onePassSig.correspondingSigReject = reject; - }); - onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); - onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); - onePassSig.hashed.catch(() => {}); - })); - msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { - const reader = getReader(readable); - const writer = getWriter(writable); - try { - for (let i = 0; i < onePassSigList.length; i++) { - const { value: signature } = await reader.read(); - onePassSigList[i].correspondingSigResolve(signature); - } - await reader.readToEnd(); - await writer.ready; - await writer.close(); - } catch (e) { - onePassSigList.forEach(onePassSig => { - onePassSig.correspondingSigReject(e); - }); - await writer.abort(e); - } - }); - return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + if (this.preferredCipherSuites !== null) { + bytes = new Uint8Array([].concat(...this.preferredCipherSuites)); + arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes)); } - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); - } - /** - * Verify detached message signature - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Signature} signature - * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { - const msg = this.unwrapCompressed(); - const literalDataList = msg.packets.filterByTag(enums.packet.literalData); - if (literalDataList.length !== 1) { - throw new Error('Can only verify message with one literal data packet.'); - } - const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); - } + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); - /** - * Unwrap compressed message - * @returns {Message} Message Content of compressed message. - */ - unwrapCompressed() { - const compressed = this.packets.filterByTag(enums.packet.compressedData); - if (compressed.length) { - return new Message(compressed[0].packets); - } - return this; + return util.concat([length, result]); } /** - * Append signature to unencrypted message object - * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature - * @param {Object} [config] - Full configuration, defaults to openpgp.config + * Creates an Uint8Array containing the unhashed subpackets + * @returns {Uint8Array} Subpacket data. */ - async appendSignature(detachedSignature, config$1 = config) { - await this.packets.read( - util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, - allowedDetachedSignaturePackets, - config$1 - ); - } + writeUnhashedSubPackets() { + const arr = this.unhashedSubpackets.map(({ type, critical, body }) => { + return writeSubPacket(type, critical, body); + }); - /** - * Returns binary encoded message - * @returns {ReadableStream} Binary message. - */ - write() { - return this.packets.write(); - } + const result = util.concat(arr); + const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2); - /** - * Returns ASCII armored text of message - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {ReadableStream} ASCII armor. - */ - armor(config$1 = config) { - return armor(enums.armor.message, this.write(), null, null, null, config$1); + return util.concat([length, result]); } -} -/** - * Create signature packets for the message - * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign - * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature to append - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [date] - Override the creationtime of the signature - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Boolean} [detached] - Whether to create detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} List of signature packets. - * @async - * @private - */ -async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) { - const packetlist = new PacketList(); + // Signature subpackets + readSubPacket(bytes, hashed = true) { + let mypos = 0; - // If data packet was created from Uint8Array, use binary, otherwise use text - const signatureType = literalDataPacket.text === null ? - enums.signature.binary : enums.signature.text; + // The leftmost bit denotes a "critical" packet + const critical = !!(bytes[mypos] & 0x80); + const type = bytes[mypos] & 0x7F; - await Promise.all(signingKeys.map(async (primaryKey, i) => { - const userID = userIDs[i]; - if (!primaryKey.isPrivate()) { - throw new Error('Need private key for signing'); + mypos++; + + if (!hashed) { + this.unhashedSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + if (!allowedUnhashedSubpackets.has(type)) { + return; + } } - const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1); - return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1); - })).then(signatureList => { - packetlist.push(...signatureList); - }); - if (signature) { - const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); - packetlist.push(...existingSigPacketlist); - } - return packetlist; -} + // subpacket type + switch (type) { + case enums.signatureSubpacket.signatureCreationTime: + // Signature Creation Time + this.created = util.readDate(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.signatureExpirationTime: { + // Signature Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); -/** - * Create object containing signer's keyID and validity of signature - * @param {SignaturePacket} signature - Signature packet - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} [date] - Check signature validity with respect to the given date - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise<{ - * keyID: module:type/keyid~KeyID, - * signature: Promise, - * verified: Promise - * }>} signer's keyID and validity of signature - * @async - * @private - */ -async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - let primaryKey; - let unverifiedSigningKey; + this.signatureNeverExpires = seconds === 0; + this.signatureExpirationTime = seconds; - for (const key of verificationKeys) { - const issuerKeys = key.getKeys(signature.issuerKeyID); - if (issuerKeys.length > 0) { - primaryKey = key; - unverifiedSigningKey = issuerKeys[0]; - break; - } - } + break; + } + case enums.signatureSubpacket.exportableCertification: + // Exportable Certification + this.exportable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.trustSignature: + // Trust Signature + this.trustLevel = bytes[mypos++]; + this.trustAmount = bytes[mypos++]; + break; + case enums.signatureSubpacket.regularExpression: + // Regular Expression + this.regularExpression = bytes[mypos]; + break; + case enums.signatureSubpacket.revocable: + // Revocable + this.revocable = bytes[mypos++] === 1; + break; + case enums.signatureSubpacket.keyExpirationTime: { + // Key Expiration Time in seconds + const seconds = util.readNumber(bytes.subarray(mypos, bytes.length)); + + this.keyExpirationTime = seconds; + this.keyNeverExpires = seconds === 0; + + break; + } + case enums.signatureSubpacket.preferredSymmetricAlgorithms: + // Preferred Symmetric Algorithms + this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.revocationKey: + // Revocation Key + // (1 octet of class, 1 octet of public-key algorithm ID, 20 + // octets of + // fingerprint) + this.revocationKeyClass = bytes[mypos++]; + this.revocationKeyAlgorithm = bytes[mypos++]; + this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20); + break; + + case enums.signatureSubpacket.issuerKeyID: + // Issuer + if (this.version === 4) { + this.issuerKeyID.read(bytes.subarray(mypos, bytes.length)); + } else if (hashed) { + // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature, + // since the Issuer Fingerprint subpacket is to be used instead. + // The `issuerKeyID` value will be set when reading the issuerFingerprint packet. + // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it, + // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed) + // issuerFingerprint. + // If the packet is hashed, then we reject the signature, to avoid verifying data different from + // what was parsed. + throw new Error('Unexpected Issuer Key ID subpacket'); + } + break; + + case enums.signatureSubpacket.notationData: { + // Notation Data + const humanReadable = !!(bytes[mypos] & 0x80); + + // We extract key/value tuple from the byte stream. + mypos += 4; + const m = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; + const n = util.readNumber(bytes.subarray(mypos, mypos + 2)); + mypos += 2; - const isOnePassSignature = signature instanceof OnePassSignaturePacket; - const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; + const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m)); + const value = bytes.subarray(mypos + m, mypos + m + n); - const verifiedSig = { - keyID: signature.issuerKeyID, - verified: (async () => { - if (!unverifiedSigningKey) { - throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + this.rawNotations.push({ name, humanReadable, value, critical }); + + if (humanReadable) { + this.notations[name] = util.decodeUTF8(value); + } + break; } + case enums.signatureSubpacket.preferredHashAlgorithms: + // Preferred Hash Algorithms + this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCompressionAlgorithms: + // Preferred Compression Algorithms + this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.keyServerPreferences: + // Key Server Preferences + this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredKeyServer: + // Preferred Key Server + this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.primaryUserID: + // Primary User ID + this.isPrimaryUserID = bytes[mypos++] !== 0; + break; + case enums.signatureSubpacket.policyURI: + // Policy URI + this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.keyFlags: + // Key Flags + this.keyFlags = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signersUserID: + // Signer's User ID + this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.reasonForRevocation: + // Reason for Revocation + this.reasonForRevocationFlag = bytes[mypos++]; + this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.features: + // Features + this.features = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.signatureTarget: { + // Signature Target + // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; + this.signatureTargetHashAlgorithm = bytes[mypos++]; - await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); - const signaturePacket = await signaturePacketPromise; - if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { - throw new Error('Key is newer than the signature'); + const len = mod$1.getHashByteLength(this.signatureTargetHashAlgorithm); + + this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len)); + break; } - // We pass the signature creation time to check whether the key was expired at the time of signing. - // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before - try { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); - } catch (e) { - // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, - // making the key invalid at the time of signing. - // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. - // Note: we do not support the edge case of a key that was reformatted and it has expired. - if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { - await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + case enums.signatureSubpacket.embeddedSignature: + // Embedded Signature + this.embeddedSignature = new SignaturePacket(); + this.embeddedSignature.read(bytes.subarray(mypos, bytes.length)); + break; + case enums.signatureSubpacket.issuerFingerprint: + // Issuer Fingerprint + this.issuerKeyVersion = bytes[mypos++]; + this.issuerFingerprint = bytes.subarray(mypos, bytes.length); + if (this.issuerKeyVersion >= 5) { + this.issuerKeyID.read(this.issuerFingerprint); } else { - throw e; + this.issuerKeyID.read(this.issuerFingerprint.subarray(-8)); } - } - return true; - })(), - signature: (async () => { - const signaturePacket = await signaturePacketPromise; - const packetlist = new PacketList(); - signaturePacket && packetlist.push(signaturePacket); - return new Signature(packetlist); - })() - }; + break; + case enums.signatureSubpacket.preferredAEADAlgorithms: + // Preferred AEAD Algorithms + this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)]; + break; + case enums.signatureSubpacket.preferredCipherSuites: + // Preferred AEAD Cipher Suites + this.preferredCipherSuites = []; + for (let i = mypos; i < bytes.length; i += 2) { + this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]); + } + break; + default: + this.unknownSubpackets.push({ + type, + critical, + body: bytes.subarray(mypos, bytes.length) + }); + break; + } + } - // Mark potential promise rejections as "handled". This is needed because in - // some cases, we reject them before the user has a reasonable chance to - // handle them (e.g. `await readToEnd(result.data); await result.verified` and - // the data stream errors). - verifiedSig.signature.catch(() => {}); - verifiedSig.verified.catch(() => {}); + readSubPackets(bytes, trusted = true, config) { + const subpacketLengthBytes = this.version === 6 ? 4 : 2; - return verifiedSig; -} + // Two-octet scalar octet count for following subpacket data. + const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes)); -/** - * Create list of objects containing signer's keyID and validity of signature - * @param {Array} signatureList - Array of signature packets - * @param {Array} literalDataList - Array of literal data packets - * @param {Array} verificationKeys - Array of public keys to verify signatures - * @param {Date} date - Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time - * @param {Boolean} [detached] - Whether to verify detached signature packets - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) - * @async - * @private - */ -async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { - return Promise.all(signatureList.filter(function(signature) { - return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); - }).map(async function(signature) { - return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); - })); -} + let i = subpacketLengthBytes; -/** - * Reads an (optionally armored) OpenPGP message and returns a Message object - * @param {Object} options - * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed - * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New message object. - * @async - * @static - */ -async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - let input = armoredMessage || binaryMessage; - if (!input) { - throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); - } - if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { - throw new Error('readMessage: options.armoredMessage must be a string or stream'); - } - if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { - throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // subpacket data set (zero or more subpackets) + while (i < 2 + subpacketLength) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - if (armoredMessage) { - const { type, data } = await unarmor(input, config$1); - if (type !== enums.armor.message) { - throw new Error('Armored text not of type message'); + this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config); + + i += len.len; } - input = data; - } - const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); - const message = new Message(packetlist); - message.fromStream = streamType; - return message; -} -/** - * Creates new message object from text or binary data. - * @param {Object} options - * @param {String | ReadableStream} [options.text] - The text message contents - * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents - * @param {String} [options.filename=""] - Name of the file (if any) - * @param {Date} [options.date=current date] - Date of the message, or modification date of the file - * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type - * @returns {Promise} New message object. - * @async - * @static - */ -async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { - let input = text !== undefined ? text : binary; - if (input === undefined) { - throw new Error('createMessage: must pass options object containing `text` or `binary`'); - } - if (text && !util.isString(text) && !util.isStream(text)) { - throw new Error('createMessage: options.text must be a string or stream'); - } - if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { - throw new Error('createMessage: options.binary must be a Uint8Array or stream'); + return i; } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - const streamType = util.isStream(input); - if (streamType) { - await loadStreamsPonyfill(); - input = toStream(input); - } - const literalDataPacket = new LiteralDataPacket(date); - if (text !== undefined) { - literalDataPacket.setText(input, enums.write(enums.literal, format)); - } else { - literalDataPacket.setBytes(input, enums.write(enums.literal, format)); - } - if (filename !== undefined) { - literalDataPacket.setFilename(filename); - } - const literalDataPacketlist = new PacketList(); - literalDataPacketlist.push(literalDataPacket); - const message = new Message(literalDataPacketlist); - message.fromStream = streamType; - return message; -} + // Produces data to produce signature on + toSign(type, data) { + const t = enums.signature; + + switch (type) { + case t.binary: + if (data.text !== null) { + return util.encodeUTF8(data.getText(true)); + } + return data.getBytes(true); + + case t.text: { + const bytes = data.getBytes(true); + // normalize EOL to \r\n + return util.canonicalizeEOL(bytes); + } + case t.standalone: + return new Uint8Array(0); + + case t.certGeneric: + case t.certPersona: + case t.certCasual: + case t.certPositive: + case t.certRevocation: { + let packet; + let tag; + + if (data.userID) { + tag = 0xB4; + packet = data.userID; + } else if (data.userAttribute) { + tag = 0xD1; + packet = data.userAttribute; + } else { + throw new Error('Either a userID or userAttribute packet needs to be ' + + 'supplied for certification.'); + } + + const bytes = packet.write(); -// GPG4Browsers - An OpenPGP implementation in javascript + return util.concat([this.toSign(t.key, data), + new Uint8Array([tag]), + util.writeNumber(bytes.length, 4), + bytes]); + } + case t.subkeyBinding: + case t.subkeyRevocation: + case t.keyBinding: + return util.concat([this.toSign(t.key, data), this.toSign(t.key, { + key: data.bind + })]); -// A Cleartext message can contain the following packets -const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + case t.key: + if (data.key === undefined) { + throw new Error('Key packet is required for this signature.'); + } + return data.key.writeForHash(this.version); -/** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} - */ -class CleartextMessage { - /** - * @param {String} text - The cleartext of the signed message - * @param {Signature} signature - The detached signature or an empty signature for unsigned messages - */ - constructor(text, signature) { - // remove trailing whitespace and normalize EOL to canonical form - this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); - if (signature && !(signature instanceof Signature)) { - throw new Error('Invalid signature input'); + case t.keyRevocation: + return this.toSign(t.key, data); + case t.timestamp: + return new Uint8Array(0); + case t.thirdParty: + throw new Error('Not implemented'); + default: + throw new Error('Unknown signature type.'); } - this.signature = signature || new Signature(new PacketList()); } - /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns {Array} Array of keyID objects. - */ - getSigningKeyIDs() { - const keyIDs = []; - const signatureList = this.signature.packets; - signatureList.forEach(function(packet) { - keyIDs.push(packet.issuerKeyID); + calculateTrailer(data, detached) { + let length = 0; + return transform(clone(this.signatureData), value => { + length += value.length; + }, () => { + const arr = []; + if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) { + if (detached) { + arr.push(new Uint8Array(6)); + } else { + arr.push(data.writeHeader()); + } + } + arr.push(new Uint8Array([this.version, 0xFF])); + if (this.version === 5) { + arr.push(new Uint8Array(4)); + } + arr.push(util.writeNumber(length, 4)); + // For v5, this should really be writeNumber(length, 8) rather than the + // hardcoded 4 zero bytes above + return util.concat(arr); }); - return keyIDs; } - /** - * Sign the cleartext message - * @param {Array} privateKeys - private keys with decrypted secret key data for signing - * @param {Signature} [signature] - Any existing detached signature - * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] - * @param {Date} [date] - The creation time of the signature that should be created - * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise} New cleartext message with signed content. - * @async - */ - async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { - const literalDataPacket = new LiteralDataPacket(); - literalDataPacket.setText(this.text); - const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1)); - return new CleartextMessage(this.text, newSignature); - } + toHash(signatureType, data, detached = false) { + const bytes = this.toSign(signatureType, data); - /** - * Verify signatures of cleartext signed message - * @param {Array} keys - Array of keys to verify signatures - * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {Promise, - * verified: Promise - * }>>} List of signer's keyID and validity of signature. - * @async - */ - verify(keys, date = new Date(), config$1 = config) { - const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets - const literalDataPacket = new LiteralDataPacket(); - // we assume that cleartext signature is generated based on UTF8 cleartext - literalDataPacket.setText(this.text); - return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]); } - /** - * Get cleartext - * @returns {String} Cleartext of message. - */ - getText() { - // normalize end of line to \n - return this.text.replace(/\r\n/g, '\n'); + async hash(signatureType, data, toHash, detached = false) { + if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) { + // avoid hashing unexpected salt size + throw new Error('Signature salt does not have the expected length'); + } + + if (!toHash) toHash = this.toHash(signatureType, data, detached); + return mod$1.hash.digest(this.hashAlgorithm, toHash); } /** - * Returns ASCII armored text of cleartext signed message + * verifies the signature packet. Note: not all signature types are implemented + * @param {PublicSubkeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature + * @param {module:enums.signature} signatureType - Expected signature type + * @param {Uint8Array|Object} data - Data which on the signature applies + * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration + * @param {Boolean} [detached] - Whether to verify a detached signature * @param {Object} [config] - Full configuration, defaults to openpgp.config - * @returns {String | ReadableStream} ASCII armor. + * @throws {Error} if signature validation failed + * @async */ - armor(config$1 = config) { - let hashes = this.signature.packets.map(function(packet) { - return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase(); - }); - hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; }); - const body = { - hash: hashes.join(), - text: this.text, - data: this.signature.packets.write() - }; - return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1); - } -} + async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) { + if (!this.issuerKeyID.equals(key.getKeyID())) { + throw new Error('Signature was not issued by the given public key'); + } + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.'); + } -/** - * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param {Object} options - * @param {String} options.cleartextMessage - Text to be parsed - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} New cleartext message object. - * @async - * @static - */ -async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; - if (!cleartextMessage) { - throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); - } - if (!util.isString(cleartextMessage)) { - throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text; + // Cryptographic validity is cached after one successful verification. + // However, for message signatures, we always re-verify, since the passed `data` can change + const skipVerify = this[verified] && !isMessageSignature; + if (!skipVerify) { + let toHash; + let hash; + if (this.hashed) { + hash = await this.hashed; + } else { + toHash = this.toHash(signatureType, data, detached); + hash = await this.hash(signatureType, data, toHash); + } + hash = await readToEnd(hash); + if (this.signedHashValue[0] !== hash[0] || + this.signedHashValue[1] !== hash[1]) { + throw new Error('Signed digest did not match'); + } - const input = await unarmor(cleartextMessage); - if (input.type !== enums.armor.signed) { - throw new Error('No cleartext signed message.'); - } - const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1); - verifyHeaders$1(input.headers, packetlist); - const signature = new Signature(packetlist); - return new CleartextMessage(input.text, signature); -} + this.params = await this.params; -/** - * Compare hash algorithm specified in the armor header with signatures - * @param {Array} headers - Armor headers - * @param {PacketList} packetlist - The packetlist with signature packets - * @private - */ -function verifyHeaders$1(headers, packetlist) { - const checkHashAlgos = function(hashAlgos) { - const check = packet => algo => packet.hashAlgorithm === algo; + this[verified] = await mod$1.signature.verify( + this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, + toHash, hash + ); - for (let i = 0; i < packetlist.length; i++) { - if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { - return false; + if (!this[verified]) { + throw new Error('Signature verification failed'); } } - return true; - }; - let oneHeader = null; - let hashAlgos = []; - headers.forEach(function(header) { - oneHeader = header.match(/^Hash: (.+)$/); // get header value - if (oneHeader) { - oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace - oneHeader = oneHeader.split(','); - oneHeader = oneHeader.map(function(hash) { - hash = hash.toLowerCase(); - try { - return enums.write(enums.hash, hash); - } catch (e) { - throw new Error('Unknown hash algorithm in armor header: ' + hash); - } - }); - hashAlgos = hashAlgos.concat(oneHeader); - } else { - throw new Error('Only "Hash" header allowed in cleartext signed message'); + const normDate = util.normalizeDate(date); + if (normDate && this.created > normDate) { + throw new Error('Signature creation time is in the future'); + } + if (normDate && normDate >= this.getExpirationTime()) { + throw new Error('Signature is expired'); + } + if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) { + throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) && + [enums.signature.binary, enums.signature.text].includes(this.signatureType)) { + throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase()); + } + this.unknownSubpackets.forEach(({ type, critical }) => { + if (critical) { + throw new Error(`Unknown critical signature subpacket type ${type}`); + } + }); + this.rawNotations.forEach(({ name, critical }) => { + if (critical && (config$1.knownNotations.indexOf(name) < 0)) { + throw new Error(`Unknown critical notation: ${name}`); + } + }); + if (this.revocationKeyClass !== null) { + throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.'); + } + } + + /** + * Verifies signature expiration date + * @param {Date} [date] - Use the given date for verification instead of the current time + * @returns {Boolean} True if expired. + */ + isExpired(date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + return !(this.created <= normDate && normDate < this.getExpirationTime()); } - }); + return false; + } - if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { - throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { - throw new Error('Hash algorithm mismatch in armor header and signature'); + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns {Date | Infinity} Expiration time. + */ + getExpirationTime() { + return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000); } } /** - * Creates a new CleartextMessage object from text - * @param {Object} options - * @param {String} options.text - * @static - * @async + * Creates a Uint8Array representation of a sub signature packet + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} + * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} + * @param {Integer} type - Subpacket signature type. + * @param {Boolean} critical - Whether the subpacket should be critical. + * @param {String} data - Data to be included + * @returns {Uint8Array} The signature subpacket. + * @private */ -async function createCleartextMessage({ text, ...rest }) { - if (!text) { - throw new Error('createCleartextMessage: must pass options object containing `text`'); - } - if (!util.isString(text)) { - throw new Error('createCleartextMessage: options.text must be a string'); - } - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - return new CleartextMessage(text); +function writeSubPacket(type, critical, data) { + const arr = []; + arr.push(writeSimpleLength(data.length + 1)); + arr.push(new Uint8Array([(critical ? 0x80 : 0) | type])); + arr.push(data); + return util.concat(arr); } -// OpenPGP.js - An OpenPGP implementation in javascript - - -////////////////////// -// // -// Key handling // -// // -////////////////////// - - /** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type. - * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. - * @param {Object} options - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys - * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys: - * curve25519 (default), p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 - * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` - * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static + * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh. + * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5} + * @param {enums.hash} hashAlgorithm - Hash algorithm. + * @returns {Integer} Salt length. + * @private */ -async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key generation'); +function saltLengthForHash(hashAlgorithm) { + switch (hashAlgorithm) { + case enums.hash.sha256: return 16; + case enums.hash.sha384: return 24; + case enums.hash.sha512: return 32; + case enums.hash.sha224: return 16; + case enums.hash.sha3_256: return 16; + case enums.hash.sha3_512: return 32; + default: throw new Error('Unsupported hash function'); } - if (type === 'rsa' && rsaBits < config$1.minRSABits) { - throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); - } - - const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; +} - try { - const { key, revocationCertificate } = await generate$4(options, config$1); - key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return { - privateKey: formatObject(key, format, config$1), - publicKey: formatObject(key.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error generating keypair', err); - } -} /** - * Reformats signature packets for a key and rewraps key object. - * @param {Object} options - * @param {PrivateKey} options.privateKey - Private key to reformat - * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` - * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. - * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires - * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended - * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The generated key object in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } - * @async - * @static + * Implementation of the One-Pass Signature Packets (Tag 4) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. */ -async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - userIDs = toArray$1(userIDs); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +class OnePassSignaturePacket { + static get tag() { + return enums.packet.onePassSignature; + } + + static fromSignaturePacket(signaturePacket, isLast) { + const onePassSig = new OnePassSignaturePacket(); + onePassSig.version = signaturePacket.version === 6 ? 6 : 3; + onePassSig.signatureType = signaturePacket.signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.issuerKeyID = signaturePacket.issuerKeyID; + onePassSig.salt = signaturePacket.salt; // v6 only + onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only - if (userIDs.length === 0) { - throw new Error('UserIDs are required for key reformat'); + onePassSig.flags = isLast ? 1 : 0; + return onePassSig; } - const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - try { - const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); + constructor() { + /** A one-octet version number. The current versions are 3 and 6. */ + this.version = null; + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + * @type {enums.signature} - return { - privateKey: formatObject(reformattedKey, format, config$1), - publicKey: formatObject(reformattedKey.toPublic(), format, config$1), - revocationCertificate - }; - } catch (err) { - throw util.wrapError('Error reformatting keypair', err); + */ + this.signatureType = null; + /** + * A one-octet number describing the hash algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4} + * @type {enums.hash} + */ + this.hashAlgorithm = null; + /** + * A one-octet number describing the public-key algorithm used. + * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1} + * @type {enums.publicKey} + */ + this.publicKeyAlgorithm = null; + /** Only for v6, a variable-length field containing the salt. */ + this.salt = null; + /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */ + this.issuerKeyID = null; + /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */ + this.issuerFingerprint = null; + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + this.flags = null; } -} -/** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. - * @param {Object} options - * @param {Key} options.key - Public or private key to revoke - * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with - * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation - * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation - * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature - * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The revoked key in the form: - * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or - * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise - * @async - * @static - */ -async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + /** + * parsing function for a one-pass signature packet (tag 4). + * @param {Uint8Array} bytes - Payload of a tag 4 packet + * @returns {OnePassSignaturePacket} Object representation. + */ + read(bytes) { + let mypos = 0; + // A one-octet version number. The current versions are 3 or 6. + this.version = bytes[mypos++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`); + } - try { - const revokedKey = revocationCertificate ? - await key.applyRevocationCertificate(revocationCertificate, date, config$1) : - await key.revoke(reasonForRevocation, date, config$1); + // A one-octet signature type. Signature types are described in + // Section 5.2.1. + this.signatureType = bytes[mypos++]; - return revokedKey.isPrivate() ? { - privateKey: formatObject(revokedKey, format, config$1), - publicKey: formatObject(revokedKey.toPublic(), format, config$1) - } : { - privateKey: null, - publicKey: formatObject(revokedKey, format, config$1) - }; - } catch (err) { - throw util.wrapError('Error revoking key', err); - } -} + // A one-octet number describing the hash algorithm used. + this.hashAlgorithm = bytes[mypos++]; -/** - * Unlock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to decrypt - * @param {String|Array} options.passphrase - The user's passphrase(s) - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The unlocked key object. - * @async - */ -async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // A one-octet number describing the public-key algorithm used. + this.publicKeyAlgorithm = bytes[mypos++]; - if (!privateKey.isPrivate()) { - throw new Error('Cannot decrypt a public key'); - } - const clonedPrivateKey = privateKey.clone(true); - const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; + if (this.version === 6) { + // Only for v6 signatures, a variable-length field containing: - try { - await Promise.all(clonedPrivateKey.getKeys().map(key => ( - // try to decrypt each key with any of the given passphrases - util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) - ))); + // A one-octet salt size. The value MUST match the value defined + // for the hash algorithm as specified in Table 23 (Hash algorithm registry). + // To allow parsing unknown hash algos, we only check the expected salt length when verifying. + const saltLength = bytes[mypos++]; - await clonedPrivateKey.validate(config$1); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error decrypting private key', err); - } -} + // The salt; a random value value of the specified size. + this.salt = bytes.subarray(mypos, mypos + saltLength); + mypos += saltLength; -/** - * Lock a private key with the given passphrase. - * This method does not change the original key. - * @param {Object} options - * @param {PrivateKey} options.privateKey - The private key to encrypt - * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} The locked key object. - * @async - */ -async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + // Only for v6 packets, 32 octets of the fingerprint of the signing key. + this.issuerFingerprint = bytes.subarray(mypos, mypos + 32); + mypos += 32; + this.issuerKeyID = new KeyID(); + // For v6 the Key ID is the high-order 64 bits of the fingerprint. + this.issuerKeyID.read(this.issuerFingerprint); + } else { + // Only for v3 packets, an eight-octet number holding the Key ID of the signing key. + this.issuerKeyID = new KeyID(); + this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8)); + mypos += 8; + } - if (!privateKey.isPrivate()) { - throw new Error('Cannot encrypt a public key'); + // A one-octet number holding a flag showing whether the signature + // is nested. A zero value indicates that the next packet is + // another One-Pass Signature packet that describes another + // signature to be applied to the same message data. + this.flags = bytes[mypos++]; + return this; } - const clonedPrivateKey = privateKey.clone(true); - const keys = clonedPrivateKey.getKeys(); - const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); - if (passphrases.length !== keys.length) { - throw new Error('Invalid number of passphrases given for key encryption'); + /** + * creates a string representation of a one-pass signature packet + * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet. + */ + write() { + const arr = [new Uint8Array([ + this.version, + this.signatureType, + this.hashAlgorithm, + this.publicKeyAlgorithm + ])]; + if (this.version === 6) { + arr.push( + new Uint8Array([this.salt.length]), + this.salt, + this.issuerFingerprint + ); + } else { + arr.push(this.issuerKeyID.write()); + } + arr.push(new Uint8Array([this.flags])); + return util.concatUint8Array(arr); } - try { - await Promise.all(keys.map(async (key, i) => { - const { keyPacket } = key; - await keyPacket.encrypt(passphrases[i], config$1); - keyPacket.clearPrivateParams(); - })); - return clonedPrivateKey; - } catch (err) { - clonedPrivateKey.clearPrivateParams(); - throw util.wrapError('Error encrypting private key', err); + calculateTrailer(...args) { + return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args)); } -} + async verify() { + const correspondingSig = await this.correspondingSig; + if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) { + throw new Error('Corresponding signature packet missing'); + } + if ( + correspondingSig.signatureType !== this.signatureType || + correspondingSig.hashAlgorithm !== this.hashAlgorithm || + correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || + !correspondingSig.issuerKeyID.equals(this.issuerKeyID) || + (this.version === 3 && correspondingSig.version === 6) || + (this.version === 6 && correspondingSig.version !== 6) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) || + (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt)) + ) { + throw new Error('Corresponding signature packet does not match one-pass signature packet'); + } + correspondingSig.hashed = this.hashed; + return correspondingSig.verify.apply(correspondingSig, arguments); + } +} -/////////////////////////////////////////// -// // -// Message encryption and decryption // -// // -/////////////////////////////////////////// - +OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash; +OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash; +OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign; /** - * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` - * must be specified. If signing keys are specified, those will be used to sign the message. - * @param {Object} options - * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message - * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed - * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message - * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Signature} [options.signature] - A detached signature to add to the encrypted message - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` - * @param {Date} [options.date=current date] - Override the creation date of the message signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static + * Instantiate a new packet given its tag + * @function newPacketFromTag + * @param {module:enums.packet} tag - Property value from {@link module:enums.packet} + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @returns {Object} New packet object with type based on tag + * @throws {Error|UnsupportedError} for disallowed or unknown packets */ -async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords); - signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations); - if (rest.detached) { - throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); - } - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - - if (!signingKeys) { - signingKeys = []; - } - const streaming = message.fromStream; - try { - if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified - message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); +function newPacketFromTag(tag, allowedPackets) { + if (!allowedPackets[tag]) { + // distinguish between disallowed packets and unknown ones + let packetType; + try { + packetType = enums.read(enums.packet, tag); + } catch (e) { + throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`); } - message = message.compress( - await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1), - config$1 - ); - message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - if (format === 'object') return message; - // serialize data - const armor = format === 'armored'; - const data = armor ? message.armor(config$1) : message.write(); - return convertStream(data, streaming, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error encrypting message', err); + throw new Error(`Packet not allowed in this context: ${packetType}`); } + return new allowedPackets[tag](); } /** - * Decrypts a message with the user's private key, a session key or a password. - * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). - * @param {Object} options - * @param {Message} options.message - The message object with the encrypted data - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key - * @param {String|String[]} [options.passwords] - Passwords to decrypt the message - * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } - * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: MaybeStream, (if format was 'utf8', the default) - * data: MaybeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } - * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + * @extends Array */ -async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +class PacketList extends Array { + /** + * Parses the given binary data and returns a list of packets. + * Equivalent to calling `read` on an empty PacketList instance. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @returns {PacketList} parsed list of packets + * @throws on parsing errors + * @async + */ + static async fromBinary(bytes, allowedPackets, config$1 = config) { + const packets = new PacketList(); + await packets.read(bytes, allowedPackets, config$1); + return packets; + } - try { - const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); - if (!verificationKeys) { - verificationKeys = []; + /** + * Reads a stream of binary data and interprets it as a list of packets. + * @param {Uint8Array | ReadableStream} bytes - binary data to parse + * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class + * @param {Object} [config] - full configuration, defaults to openpgp.config + * @throws on parsing errors + * @async + */ + async read(bytes, allowedPackets, config$1 = config) { + if (config$1.additionalAllowedPackets.length) { + allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) }; } + this.stream = transformPair(bytes, async (readable, writable) => { + const writer = getWriter(writable); + try { + while (true) { + await writer.ready; + const done = await readPackets(readable, async parsed => { + try { + if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) { + // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed: + // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145 + // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10 + // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21 + return; + } + const packet = newPacketFromTag(parsed.tag, allowedPackets); + packet.packets = new PacketList(); + packet.fromStream = util.isStream(parsed.packet); + await packet.read(parsed.packet, config$1); + await writer.write(packet); + } catch (e) { + // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence, + // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored. + // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical. + if (e instanceof UnknownPacketError) { + if (parsed.tag <= 39) { + await writer.abort(e); + } else { + return; + } + } - const result = {}; - result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); - result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); - result.filename = decrypted.getFilename(); - linkStreams(result, message); - if (expectSigned) { - if (verificationKeys.length === 0) { - throw new Error('Verification keys are required to verify message signatures'); + const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError; + const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError); + if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) { + // The packets that support streaming are the ones that contain message data. + // Those are also the ones we want to be more strict about and throw on parse errors + // (since we likely cannot process the message without these packets anyway). + await writer.abort(e); + } else { + const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet); + await writer.write(unparsedPacket); + } + util.printDebugError(e); + } + }); + if (done) { + await writer.ready; + await writer.close(); + return; + } + } + } catch (e) { + await writer.abort(e); } - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); + }); + + // Wait until first few packets have been read + const reader = getReader(this.stream); + while (true) { + const { done, value } = await reader.read(); + if (!done) { + this.push(value); + } else { + this.stream = null; + } + if (done || supportsStreaming(value.constructor.tag)) { + break; } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error decrypting message', err); + reader.releaseLock(); } -} + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns {Uint8Array} A Uint8Array containing valid openpgp packets. + */ + write() { + const arr = []; -////////////////////////////////////////// -// // -// Message signing and verification // -// // -////////////////////////////////////////// + for (let i = 0; i < this.length; i++) { + const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag; + const packetbytes = this[i].write(); + if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) { + let buffer = []; + let bufferLength = 0; + const minLength = 512; + arr.push(writeTag(tag)); + arr.push(transform(packetbytes, value => { + buffer.push(value); + bufferLength += value.length; + if (bufferLength >= minLength) { + const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30); + const chunkSize = 2 ** powerOf2; + const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer)); + buffer = [bufferConcat.subarray(1 + chunkSize)]; + bufferLength = buffer[0].length; + return bufferConcat.subarray(0, 1 + chunkSize); + } + }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer)))); + } else { + if (util.isStream(packetbytes)) { + let length = 0; + arr.push(transform(clone(packetbytes), value => { + length += value.length; + }, () => writeHeader(tag, length))); + } else { + arr.push(writeHeader(tag, packetbytes.length)); + } + arr.push(packetbytes); + } + } + return util.concat(arr); + } -/** - * Signs a message. - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed - * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext - * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message - * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature - * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] - * @param {Date} [options.date=current date] - Override the creation date of the signature - * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` - * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static - */ -async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); checkOutputMessageFormat(format); - signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations); + /** + * Creates a new PacketList with all packets matching the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {PacketList} + */ + filterByTag(...tags) { + const filtered = new PacketList(); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); - if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + const handle = tag => packetType => tag === packetType; - if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); - if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(this[i].constructor.tag))) { + filtered.push(this[i]); + } + } - if (!signingKeys || signingKeys.length === 0) { - throw new Error('No signing keys provided'); + return filtered; } - try { - let signature; - if (detached) { - signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } else { - signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1); - } - if (format === 'object') return signature; + /** + * Traverses packet list and returns first packet with matching tag + * @param {module:enums.packet} tag - The packet tag + * @returns {Packet|undefined} + */ + findPacket(tag) { + return this.find(packet => packet.constructor.tag === tag); + } - const armor = format === 'armored'; - signature = armor ? signature.armor(config$1) : signature.write(); - if (detached) { - signature = transformPair(message.packets.write(), async (readable, writable) => { - await Promise.all([ - pipe(signature, writable), - readToEnd(readable).catch(() => {}) - ]); - }); + /** + * Find indices of packets with the given tag(s) + * @param {...module:enums.packet} tags - packet tags to look for + * @returns {Integer[]} packet indices + */ + indexOfTag(...tags) { + const tagIndex = []; + const that = this; + + const handle = tag => packetType => tag === packetType; + + for (let i = 0; i < this.length; i++) { + if (tags.some(handle(that[i].constructor.tag))) { + tagIndex.push(i); + } } - return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary'); - } catch (err) { - throw util.wrapError('Error signing message', err); + return tagIndex; } } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A Compressed Data packet can contain the following packet types +const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + /** - * Verifies signatures of cleartext signed message - * @param {Object} options - * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures - * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures - * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys - * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - * @param {Signature} [options.signature] - Detached signature for verification - * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: MaybeStream, (if `message` was a CleartextMessage) - * data: MaybeStream, (if `message` was a Message) - * signatures: [ - * { - * keyID: module:type/keyid~KeyID, - * verified: Promise, - * signature: Promise - * }, ... - * ] - * } + * Implementation of the Compressed Data Packet (Tag 8) * - * where `signatures` contains a separate entry for each signature packet found in the input message. - * @async - * @static + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. */ -async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +class CompressedDataPacket { + static get tag() { + return enums.packet.compressedData; + } - if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); - if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + /** + * List of packets + * @type {PacketList} + */ + this.packets = null; + /** + * Compression algorithm + * @type {enums.compression} + */ + this.algorithm = config$1.preferredCompressionAlgorithm; - try { - const result = {}; - if (signature) { - result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); - } else { - result.signatures = await message.verify(verificationKeys, date, config$1); - } - result.data = format === 'binary' ? message.getLiteralData() : message.getText(); - if (message.fromStream && !signature) linkStreams(result, message); - if (expectSigned) { - if (result.signatures.length === 0) { - throw new Error('Message is not signed'); - } - result.data = concat([ - result.data, - fromAsync(async () => { - await util.anyPromise(result.signatures.map(sig => sig.verified)); - }) - ]); + /** + * Compressed packet data + * @type {Uint8Array | ReadableStream} + */ + this.compressed = null; + } + + /** + * Parsing function for the packet. + * @param {Uint8Array | ReadableStream} bytes - Payload of a tag 8 packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async read(bytes, config$1 = config) { + await parse(bytes, async reader => { + + // One octet that gives the algorithm used to compress the packet. + this.algorithm = await reader.readByte(); + + // Compressed data, which makes up the remainder of the packet. + this.compressed = reader.remainder(); + + await this.decompress(config$1); + }); + } + + + /** + * Return the compressed packet. + * @returns {Uint8Array | ReadableStream} Binary compressed packet. + */ + write() { + if (this.compressed === null) { + this.compress(); } - result.data = await convertStream(result.data, message.fromStream, format); - return result; - } catch (err) { - throw util.wrapError('Error verifying signed message', err); + + return util.concat([new Uint8Array([this.algorithm]), this.compressed]); } -} -/////////////////////////////////////////////// -// // -// Session key encryption and decryption // -// // -/////////////////////////////////////////////// + /** + * Decompression method for decompressing the compressed data + * read by read_packet + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async decompress(config$1 = config) { + const compressionName = enums.read(enums.compression, this.algorithm); + const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async + if (!decompressionFn) { + throw new Error(`${compressionName} decompression not supported`); + } -/** - * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. - * @param {Object} options - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} - * @param {Date} [options.date=current date] - Date to select algorithm preferences at - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. - * @async - * @static - */ -async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + this.packets = await PacketList.fromBinary(await decompressionFn(this.compressed), allowedPackets$5, config$1); + } - try { - const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error generating session key', err); + /** + * Compress the packet data (member decompressedData) + */ + compress() { + const compressionName = enums.read(enums.compression, this.algorithm); + const compressionFn = compress_fns[compressionName]; + if (!compressionFn) { + throw new Error(`${compressionName} compression not supported`); + } + + this.compressed = compressionFn(this.packets.write()); } } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + /** - * Encrypt a symmetric session key with public keys, passwords, or both at once. - * At least one of `encryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) - * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' - * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key - * @param {String|String[]} [options.passwords] - Passwords for the message - * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value - * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs - * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] - * @param {Date} [options.date=current date] - Override the date - * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). - * @async - * @static + * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise. + * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator + * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor + * @returns {ReadableStream} compressed or decompressed data */ -async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); - encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); - if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) { + return data => { + if (!util.isStream(data) || isArrayStream(data)) { + return fromAsync(() => readToEnd(data).then(inputData => { + return new Promise((resolve, reject) => { + const zlibStream = new ZlibStreamedConstructor(); + zlibStream.ondata = processedData => { + resolve(processedData); + }; + try { + zlibStream.push(inputData, true); // only one chunk to push + } catch (err) { + reject(err); + } + }); + })); + } - if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { - throw new Error('No encryption keys or passwords provided.'); - } + // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) + if (compressionStreamInstantiator) { + try { + const compressorOrDecompressor = compressionStreamInstantiator(); + return data.pipeThrough(compressorOrDecompressor); + } catch (err) { + // If format is unsupported in Compression/DecompressionStream, then a TypeError in thrown, and we fallback to fflate. + if (err.name !== 'TypeError') { + throw err; + } + } + } - try { - const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); - return formatObject(message, format, config$1); - } catch (err) { - throw util.wrapError('Error encrypting session key', err); - } + // JS fallback + const inputReader = data.getReader(); + const zlibStream = new ZlibStreamedConstructor(); + + return new ReadableStream({ + async start(controller) { + zlibStream.ondata = async (value, isLast) => { + controller.enqueue(value); + if (isLast) { + controller.close(); + } + }; + + while (true) { + const { done, value } = await inputReader.read(); + if (done) { + zlibStream.push(new Uint8Array(), true); + return; + } else if (value.length) { + zlibStream.push(value); + } + } + } + }); + }; +} + +function bzip2Decompress() { + return async function(data) { + const { decode: bunzipDecode } = await Promise.resolve().then(function () { return index; }); + return fromAsync(async () => bunzipDecode(await readToEnd(data))); + }; } /** - * Decrypt symmetric session keys using private keys or passwords (not both). - * One of `decryptionKeys` or `passwords` must be specified. - * @param {Object} options - * @param {Message} options.message - A message object containing the encrypted session key packets - * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data - * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key - * @param {Date} [options.date] - Date to use for key verification instead of the current time - * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} - * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: - * { data:Uint8Array, algorithm:String } - * @throws if no session key could be found or decrypted - * @async - * @static + * Get Compression Stream API instatiators if the constructors are implemented. + * NB: the return instatiator functions will throw when called if the provided `compressionFormat` is not supported + * (supported formats cannot be determined in advance). + * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat + * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }} */ -async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { - config$1 = { ...config, ...config$1 }; checkConfig(config$1); - checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); - if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); - const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); +const getCompressionStreamInstantiators = compressionFormat => ({ + compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)), + decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat)) +}); - try { - const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1); - return sessionKeys; - } catch (err) { - throw util.wrapError('Error decrypting session keys', err); - } -} +const compress_fns = { + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib) +}; +const decompress_fns = { + uncompressed: data => data, + zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate), + zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib), + bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import +}; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -////////////////////////// -// // -// Helper functions // -// // -////////////////////////// +// A SEIP packet can contain the following packet types +const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); /** - * Input validation - * @private + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. */ -function checkString(data, name) { - if (!util.isString(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type String'); +class SymEncryptedIntegrityProtectedDataPacket { + static get tag() { + return enums.packet.symEncryptedIntegrityProtectedData; } -} -function checkBinary(data, name) { - if (!util.isUint8Array(data)) { - throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array'); + + static fromObject({ version, aeadAlgorithm }) { + if (version !== 1 && version !== 2) { + throw new Error('Unsupported SEIPD version'); + } + + const seip = new SymEncryptedIntegrityProtectedDataPacket(); + seip.version = version; + if (version === 2) { + seip.aeadAlgorithm = aeadAlgorithm; + } + + return seip; } -} -function checkMessage(message) { - if (!(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message'); + + constructor() { + this.version = null; + + // The following 4 fields are for V2 only. + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = null; + this.chunkSizeByte = null; + this.salt = null; + + this.encrypted = null; + this.packets = null; } -} -function checkCleartextOrMessage(message) { - if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { - throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); + + async read(bytes) { + await parse(bytes, async reader => { + this.version = await reader.readByte(); + // - A one-octet version number with value 1 or 2. + if (this.version !== 1 && this.version !== 2) { + throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`); + } + + if (this.version === 2) { + // - A one-octet cipher algorithm. + this.cipherAlgorithm = await reader.readByte(); + // - A one-octet AEAD algorithm. + this.aeadAlgorithm = await reader.readByte(); + // - A one-octet chunk size. + this.chunkSizeByte = await reader.readByte(); + // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique. + this.salt = await reader.readBytes(32); + } + + // For V1: + // - Encrypted data, the output of the selected symmetric-key cipher + // operating in Cipher Feedback mode with shift amount equal to the + // block size of the cipher (CFB-n where n is the block size). + // For V2: + // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode. + // - A final, summary authentication tag for the AEAD mode. + this.encrypted = reader.remainder(); + }); } -} -function checkOutputMessageFormat(format) { - if (format !== 'armored' && format !== 'binary' && format !== 'object') { - throw new Error(`Unsupported format ${format}`); + + write() { + if (this.version === 2) { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]); + } + return util.concat([new Uint8Array([this.version]), this.encrypted]); + } + + /** + * Encrypt the payload in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on encryption failure + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + const { blockSize, keySize } = mod$1.getCipherParams(sessionKeyAlgorithm); + if (key.length !== keySize) { + throw new Error('Unexpected session key size'); + } + + let bytes = this.packets.write(); + if (isArrayStream(bytes)) bytes = await readToEnd(bytes); + + if (this.version === 2) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + this.salt = mod$1.random.getRandomBytes(32); + this.chunkSizeByte = config$1.aeadChunkSizeByte; + this.encrypted = await runAEAD(this, 'encrypt', key, bytes); + } else { + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet + + const tohash = util.concat([prefix, bytes, mdc]); + const hash = await mod$1.hash.sha1(passiveClone(tohash)); + const plaintext = util.concat([tohash, hash]); + + this.encrypted = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1); + } + return true; } -} -const defaultConfigPropsCount = Object.keys(config).length; -function checkConfig(config$1) { - const inputConfigProps = Object.keys(config$1); - if (inputConfigProps.length !== defaultConfigPropsCount) { - for (const inputProp of inputConfigProps) { - if (config[inputProp] === undefined) { - throw new Error(`Unknown config property: ${inputProp}`); + + /** + * Decrypts the encrypted data contained in the packet. + * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} on decryption failure + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // We check that the session key size matches the one expected by the symmetric algorithm. + // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size, + // but we want to ensure that the input key isn't e.g. too short. + // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm, + // which is instead included in the SEIPDv2 data. + if (key.length !== mod$1.getCipherParams(sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + + let encrypted = clone(this.encrypted); + if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted); + + let packetbytes; + if (this.version === 2) { + if (this.cipherAlgorithm !== sessionKeyAlgorithm) { + // sanity check + throw new Error('Unexpected session key algorithm'); + } + packetbytes = await runAEAD(this, 'decrypt', key, encrypted); + } else { + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize)); + + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + const realHash = slice(passiveClone(decrypted), -20); + const tohash = slice(decrypted, 0, -20); + const verifyHash = Promise.all([ + readToEnd(await mod$1.hash.sha1(passiveClone(tohash))), + readToEnd(realHash) + ]).then(([hash, mdc]) => { + if (!util.equalsUint8Array(hash, mdc)) { + throw new Error('Modification detected.'); + } + return new Uint8Array(); + }); + const bytes = slice(tohash, blockSize + 2); // Remove random prefix + packetbytes = slice(bytes, 0, -2); // Remove MDC packet + packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]); + if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) { + packetbytes = await readToEnd(packetbytes); } } - } -} -/** - * Normalize parameter to an array if it is not undefined. - * @param {Object} param - the parameter to be normalized - * @returns {Array|undefined} The resulting array or undefined. - * @private - */ -function toArray$1(param) { - if (param && !util.isArray(param)) { - param = [param]; + this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1); + return true; } - return param; } /** - * Convert data to or from Stream - * @param {Object} data - the data to convert - * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type - * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams - * @returns {Promise} The data in the respective format. + * En/decrypt the payload. + * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt + * @param {Uint8Array} key - The session key used to en/decrypt the payload + * @param {Uint8Array | ReadableStream} data - The data to en/decrypt + * @returns {Promise>} * @async - * @private - */ -async function convertStream(data, streaming, encoding = 'utf8') { - const streamType = util.isStream(data); - if (streamType === 'array') { - return readToEnd(data); - } - if (streaming === 'node') { - data = webToNode(data); - if (encoding !== 'binary') data.setEncoding(encoding); - return data; - } - if (streaming === 'web' && streamType === 'ponyfill') { - return toNativeReadable(data); - } - return data; -} - -/** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param {Object} result - the data to convert - * @param {Message} message - message object - * @returns {Object} - * @private */ -function linkStreams(result, message) { - result.data = transformPair(message.packets.stream, async (readable, writable) => { - await pipe(result.data, writable, { - preventClose: true - }); +async function runAEAD(packet, fn, key, data) { + const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2; + const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import) + if (!isSEIPDv2 && !isAEADP) throw new Error('Unexpected packet type'); + + const mode = mod$1.getAEADMode(packet.aeadAlgorithm); + const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0; + const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0; + const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6)) + const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0; + const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP); + const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP); + const adataTagArray = new Uint8Array(adataBuffer); + const adataView = new DataView(adataBuffer); + const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8); + adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0); + let chunkIndex = 0; + let latestPromise = Promise.resolve(); + let cryptedBytes = 0; + let queuedBytes = 0; + let iv; + let ivView; + if (isSEIPDv2) { + const { keySize } = mod$1.getCipherParams(packet.cipherAlgorithm); + const { ivLength } = mode; + const info = new Uint8Array(adataBuffer, 0, 5); + const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength); + key = derived.subarray(0, keySize); + iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. + iv.fill(0, iv.length - 8); + ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + } else { // AEADEncryptedDataPacket + iv = packet.iv; + // ivView is unused in this case + } + const modeInstance = await mode(packet.cipherAlgorithm, key); + return transformPair(data, async (readable, writable) => { + if (util.isStream(readable) !== 'array') { + const buffer = new TransformStream({}, { + highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6), + size: array => array.length + }); + pipe(buffer.readable, writable); + writable = buffer.writable; + } + const reader = getReader(readable); const writer = getWriter(writable); try { - // Forward errors in the message stream to result.data. - await readToEnd(readable, _ => _); - await writer.close(); + while (true) { + let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array(); + const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting); + chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting); + let cryptedPromise; + let done; + let nonce; + if (isSEIPDv2) { // SEIPD V2 + nonce = iv; + } else { // AEADEncryptedDataPacket + nonce = iv.slice(); + for (let i = 0; i < 8; i++) { + nonce[iv.length - 8 + i] ^= chunkIndexArray[i]; + } + } + if (!chunkIndex || chunk.length) { + reader.unshift(finalChunk); + cryptedPromise = modeInstance[fn](chunk, nonce, adataArray); + cryptedPromise.catch(() => {}); + queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting; + } else { + // After the last chunk, we either encrypt a final, empty + // data chunk to get the final authentication tag or + // validate that final authentication tag. + adataView.setInt32(5 + chunkIndexSizeIfAEADEP + 4, cryptedBytes); // Should be setInt64(5 + chunkIndexSizeIfAEADEP, ...) + cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray); + cryptedPromise.catch(() => {}); + queuedBytes += tagLengthIfEncrypting; + done = true; + } + cryptedBytes += chunk.length - tagLengthIfDecrypting; + // eslint-disable-next-line @typescript-eslint/no-loop-func + latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => { + await writer.ready; + await writer.write(crypted); + queuedBytes -= crypted.length; + }).catch(err => writer.abort(err)); + if (done || queuedBytes > writer.desiredSize) { + await latestPromise; // Respect backpressure + } + if (!done) { + if (isSEIPDv2) { // SEIPD V2 + ivView.setInt32(iv.length - 4, ++chunkIndex); // Should be setInt64(iv.length - 8, ...) + } else { // AEADEncryptedDataPacket + adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...) + } + } else { + await writer.close(); + break; + } + } } catch (e) { + await writer.ready.catch(() => {}); await writer.abort(e); } }); } -/** - * Convert the object to the given format - * @param {Key|Message} object - * @param {'armored'|'binary'|'object'} format - * @param {Object} config - Full configuration - * @returns {String|Uint8Array|Object} - */ -function formatObject(object, format, config) { - switch (format) { - case 'object': - return object; - case 'armored': - return object.armor(config); - case 'binary': - return object.write(); - default: - throw new Error(`Unsupported format ${format}`); - } -} - -/** - * web-streams-polyfill v3.0.3 - */ -/// -const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? - Symbol : - description => `Symbol(${description})`; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -/// -function noop() { - return undefined; -} -function getGlobals() { - if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else if (typeof global !== 'undefined') { - return global; - } - return undefined; -} -const globals = getGlobals(); -function typeIsObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -const rethrowAssertionErrorRejection = noop; +// An AEAD-encrypted Data packet can contain the following packet types +const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); -const originalPromise = Promise; -const originalPromiseThen = Promise.prototype.then; -const originalPromiseResolve = Promise.resolve.bind(originalPromise); -const originalPromiseReject = Promise.reject.bind(originalPromise); -function newPromise(executor) { - return new originalPromise(executor); -} -function promiseResolvedWith(value) { - return originalPromiseResolve(value); -} -function promiseRejectedWith(reason) { - return originalPromiseReject(reason); -} -function PerformPromiseThen(promise, onFulfilled, onRejected) { - // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an - // approximation. - return originalPromiseThen.call(promise, onFulfilled, onRejected); -} -function uponPromise(promise, onFulfilled, onRejected) { - PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); -} -function uponFulfillment(promise, onFulfilled) { - uponPromise(promise, onFulfilled); -} -function uponRejection(promise, onRejected) { - uponPromise(promise, undefined, onRejected); -} -function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { - return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); -} -function setPromiseIsHandledToTrue(promise) { - PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); -} -const queueMicrotask = (() => { - const globalQueueMicrotask = globals && globals.queueMicrotask; - if (typeof globalQueueMicrotask === 'function') { - return globalQueueMicrotask; - } - const resolvedPromise = promiseResolvedWith(undefined); - return (fn) => PerformPromiseThen(resolvedPromise, fn); -})(); -function reflectCall(F, V, args) { - if (typeof F !== 'function') { - throw new TypeError('Argument is not a function'); - } - return Function.prototype.apply.call(F, V, args); -} -function promiseCall(F, V, args) { - try { - return promiseResolvedWith(reflectCall(F, V, args)); - } - catch (value) { - return promiseRejectedWith(value); - } -} +const VERSION$1 = 1; // A one-octet version number of the data packet. -// Original from Chromium -// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js -const QUEUE_MAX_ARRAY_SIZE = 16384; /** - * Simple queue structure. + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet * - * Avoids scalability issues with using a packed array directly by using - * multiple arrays in a linked list and keeping the array size bounded. + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet */ -class SimpleQueue { - constructor() { - this._cursor = 0; - this._size = 0; - // _front and _back are always defined. - this._front = { - _elements: [], - _next: undefined - }; - this._back = this._front; - // The cursor is used to avoid calling Array.shift(). - // It contains the index of the front element of the array inside the - // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). - this._cursor = 0; - // When there is only one node, size === elements.length - cursor. - this._size = 0; - } - get length() { - return this._size; - } - // For exception safety, this method is structured in order: - // 1. Read state - // 2. Calculate required state mutations - // 3. Perform state mutations - push(element) { - const oldBack = this._back; - let newBack = oldBack; - if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { - newBack = { - _elements: [], - _next: undefined - }; - } - // push() is the mutation most likely to throw an exception, so it - // goes first. - oldBack._elements.push(element); - if (newBack !== oldBack) { - this._back = newBack; - oldBack._next = newBack; - } - ++this._size; - } - // Like push(), shift() follows the read -> calculate -> mutate pattern for - // exception safety. - shift() { // must not be called on an empty queue - const oldFront = this._front; - let newFront = oldFront; - const oldCursor = this._cursor; - let newCursor = oldCursor + 1; - const elements = oldFront._elements; - const element = elements[oldCursor]; - if (newCursor === QUEUE_MAX_ARRAY_SIZE) { - newFront = oldFront._next; - newCursor = 0; - } - // No mutations before this point. - --this._size; - this._cursor = newCursor; - if (oldFront !== newFront) { - this._front = newFront; - } - // Permit shifted element to be garbage collected. - elements[oldCursor] = undefined; - return element; - } - // The tricky thing about forEach() is that it can be called - // re-entrantly. The queue may be mutated inside the callback. It is easy to - // see that push() within the callback has no negative effects since the end - // of the queue is checked for on every iteration. If shift() is called - // repeatedly within the callback then the next iteration may return an - // element that has been removed. In this case the callback will be called - // with undefined values until we either "catch up" with elements that still - // exist or reach the back of the queue. - forEach(callback) { - let i = this._cursor; - let node = this._front; - let elements = node._elements; - while (i !== elements.length || node._next !== undefined) { - if (i === elements.length) { - node = node._next; - elements = node._elements; - i = 0; - if (elements.length === 0) { - break; - } - } - callback(elements[i]); - ++i; - } - } - // Return the element that would be returned if shift() was called now, - // without modifying the queue. - peek() { // must not be called on an empty queue - const front = this._front; - const cursor = this._cursor; - return front._elements[cursor]; - } -} +class AEADEncryptedDataPacket { + static get tag() { + return enums.packet.aeadEncryptedData; + } -function ReadableStreamReaderGenericInitialize(reader, stream) { - reader._ownerReadableStream = stream; - stream._reader = reader; - if (stream._state === 'readable') { - defaultReaderClosedPromiseInitialize(reader); - } - else if (stream._state === 'closed') { - defaultReaderClosedPromiseInitializeAsResolved(reader); - } - else { - defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); - } -} -// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state -// check. -function ReadableStreamReaderGenericCancel(reader, reason) { - const stream = reader._ownerReadableStream; - return ReadableStreamCancel(stream, reason); -} -function ReadableStreamReaderGenericRelease(reader) { - if (reader._ownerReadableStream._state === 'readable') { - defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - else { - defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); - } - reader._ownerReadableStream._reader = undefined; - reader._ownerReadableStream = undefined; -} -// Helper functions for the readers. -function readerLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released reader'); -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderClosedPromiseInitialize(reader) { - reader._closedPromise = newPromise((resolve, reject) => { - reader._closedPromise_resolve = resolve; - reader._closedPromise_reject = reject; + constructor() { + this.version = VERSION$1; + /** @type {enums.symmetric} */ + this.cipherAlgorithm = null; + /** @type {enums.aead} */ + this.aeadAlgorithm = enums.aead.eax; + this.chunkSizeByte = null; + this.iv = null; + this.encrypted = null; + this.packets = null; + } + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param {Uint8Array | ReadableStream} bytes + * @throws {Error} on parsing failure + */ + async read(bytes) { + await parse(bytes, async reader => { + const version = await reader.readByte(); + if (version !== VERSION$1) { // The only currently defined value is 1. + throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`); + } + this.cipherAlgorithm = await reader.readByte(); + this.aeadAlgorithm = await reader.readByte(); + this.chunkSizeByte = await reader.readByte(); + + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = await reader.readBytes(mode.ivLength); + this.encrypted = reader.remainder(); }); + } + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns {Uint8Array | ReadableStream} The encrypted payload. + */ + write() { + return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]); + } + + /** + * Decrypt the encrypted payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.packets = await PacketList.fromBinary( + await runAEAD(this, 'decrypt', key, clone(this.encrypted)), + allowedPackets$3, + config$1 + ); + } + + /** + * Encrypt the packet payload. + * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm + * @param {Uint8Array} key - The session key used to encrypt the payload + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + this.cipherAlgorithm = sessionKeyAlgorithm; + + const { ivLength } = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(ivLength); // generate new random IV + this.chunkSizeByte = config$1.aeadChunkSizeByte; + const data = this.packets.write(); + this.encrypted = await runAEAD(this, 'encrypt', key, data); + } } -function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseReject(reader, reason); -} -function defaultReaderClosedPromiseInitializeAsResolved(reader) { - defaultReaderClosedPromiseInitialize(reader); - defaultReaderClosedPromiseResolve(reader); -} -function defaultReaderClosedPromiseReject(reader, reason) { - if (reader._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(reader._closedPromise); - reader._closedPromise_reject(reason); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -function defaultReaderClosedPromiseResetToRejected(reader, reason) { - defaultReaderClosedPromiseInitializeAsRejected(reader, reason); -} -function defaultReaderClosedPromiseResolve(reader) { - if (reader._closedPromise_resolve === undefined) { - return; - } - reader._closedPromise_resolve(undefined); - reader._closedPromise_resolve = undefined; - reader._closedPromise_reject = undefined; -} -const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); -const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); -const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); -const PullSteps = SymbolPolyfill('[[PullSteps]]'); +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill -const NumberIsFinite = Number.isFinite || function (x) { - return typeof x === 'number' && isFinite(x); -}; +/** + * Public-Key Encrypted Session Key Packets (Tag 1) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ +class PublicKeyEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.publicKeyEncryptedSessionKey; + } -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill -const MathTrunc = Math.trunc || function (v) { - return v < 0 ? Math.ceil(v) : Math.floor(v); -}; + constructor() { + this.version = null; -// https://heycam.github.io/webidl/#idl-dictionaries -function isDictionary(x) { - return typeof x === 'object' || typeof x === 'function'; -} -function assertDictionary(obj, context) { - if (obj !== undefined && !isDictionary(obj)) { - throw new TypeError(`${context} is not an object.`); - } -} -// https://heycam.github.io/webidl/#idl-callback-functions -function assertFunction(x, context) { - if (typeof x !== 'function') { - throw new TypeError(`${context} is not a function.`); - } -} -// https://heycam.github.io/webidl/#idl-object -function isObject(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; -} -function assertObject(x, context) { - if (!isObject(x)) { - throw new TypeError(`${context} is not an object.`); - } -} -function assertRequiredArgument(x, position, context) { - if (x === undefined) { - throw new TypeError(`Parameter ${position} is required in '${context}'.`); - } -} -function assertRequiredField(x, field, context) { - if (x === undefined) { - throw new TypeError(`${field} is required in '${context}'.`); - } -} -// https://heycam.github.io/webidl/#idl-unrestricted-double -function convertUnrestrictedDouble(value) { - return Number(value); -} -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} -function integerPart(x) { - return censorNegativeZero(MathTrunc(x)); -} -// https://heycam.github.io/webidl/#idl-unsigned-long-long -function convertUnsignedLongLongWithEnforceRange(value, context) { - const lowerBound = 0; - const upperBound = Number.MAX_SAFE_INTEGER; - let x = Number(value); - x = censorNegativeZero(x); - if (!NumberIsFinite(x)) { - throw new TypeError(`${context} is not a finite number`); - } - x = integerPart(x); - if (x < lowerBound || x > upperBound) { - throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); - } - if (!NumberIsFinite(x) || x === 0) { - return 0; - } - // TODO Use BigInt if supported? - // let xBigInt = BigInt(integerPart(x)); - // xBigInt = BigInt.asUintN(64, xBigInt); - // return Number(xBigInt); - return x; -} + // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()` + this.publicKeyID = new KeyID(); -function assertReadableStream(x, context) { - if (!IsReadableStream(x)) { - throw new TypeError(`${context} is not a ReadableStream.`); - } -} + // For version 6: + this.publicKeyVersion = null; + this.publicKeyFingerprint = null; -// Abstract operations for the ReadableStream. -function AcquireReadableStreamDefaultReader(stream) { - return new ReadableStreamDefaultReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadRequest(stream, readRequest) { - stream._reader._readRequests.push(readRequest); -} -function ReadableStreamFulfillReadRequest(stream, chunk, done) { - const reader = stream._reader; - const readRequest = reader._readRequests.shift(); - if (done) { - readRequest._closeSteps(); - } - else { - readRequest._chunkSteps(chunk); - } -} -function ReadableStreamGetNumReadRequests(stream) { - return stream._reader._readRequests.length; -} -function ReadableStreamHasDefaultReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; - } - if (!IsReadableStreamDefaultReader(reader)) { - return false; - } - return true; -} -/** - * A default reader vended by a {@link ReadableStream}. - * - * @public - */ -class ReadableStreamDefaultReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readRequests = new SimpleQueue(); - } + // For all versions: + this.publicKeyAlgorithm = null; + + this.sessionKey = null; /** - * Returns a promise that will be fulfilled when the stream becomes closed, - * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - get closed() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('closed')); - } - return this._closedPromise; + this.sessionKeyAlgorithm = null; + + /** @type {Object} */ + this.encrypted = {}; + } + + static fromObject({ + version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm + }) { + const pkesk = new PublicKeyEncryptedSessionKeyPacket(); + + if (version !== 3 && version !== 6) { + throw new Error('Unsupported PKESK version'); } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); + + pkesk.version = version; + + if (version === 6) { + pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version; + pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes(); } - /** - * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. - */ - read() { - if (!IsReadableStreamDefaultReader(this)) { - return promiseRejectedWith(defaultReaderBrandCheckException('read')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: () => resolvePromise({ value: undefined, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamDefaultReaderRead(this, readRequest); - return promise; + + pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID(); + pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkesk.sessionKey = sessionKey; + pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm; + + return pkesk; + } + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * + * @param {Uint8Array} bytes - Payload of a tag 1 packet + */ + read(bytes) { + let offset = 0; + this.version = bytes[offset++]; + if (this.version !== 3 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`); } - /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. - */ - releaseLock() { - if (!IsReadableStreamDefaultReader(this)) { - throw defaultReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); + if (this.version === 6) { + // A one-octet size of the following two fields: + // - A one octet key version number. + // - The fingerprint of the public key or subkey to which the session key is encrypted. + // The size may also be zero. + const versionAndFingerprintLength = bytes[offset++]; + if (versionAndFingerprintLength) { + this.publicKeyVersion = bytes[offset++]; + const fingerprintLength = versionAndFingerprintLength - 1; + this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength); offset += fingerprintLength; + if (this.publicKeyVersion >= 5) { + // For v5/6 the Key ID is the high-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint); + } else { + // For v4 The Key ID is the low-order 64 bits of the fingerprint. + this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8)); } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamDefaultReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamDefaultReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { - return false; - } - return true; -} -function ReadableStreamDefaultReaderRead(reader, readRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'closed') { - readRequest._closeSteps(); - } - else if (stream._state === 'errored') { - readRequest._errorSteps(stream._storedError); + } else { + // The size may also be zero, and the key version and + // fingerprint omitted for an "anonymous recipient" + this.publicKeyID = KeyID.wildcard(); + } + } else { + offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8)); } - else { - stream._readableStreamController[PullSteps](readRequest); + this.publicKeyAlgorithm = bytes[offset++]; + this.encrypted = mod$1.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset)); + if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) { + if (this.version === 3) { + this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm); + } else if (this.encrypted.C.algorithm !== null) { + throw new Error('Unexpected cleartext symmetric algorithm'); + } } -} -// Helper functions for the ReadableStreamDefaultReader. -function defaultReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); -} + } -/// -let AsyncIteratorPrototype; -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - // We're running inside a ES2018+ environment, but we're compiling to an older syntax. - // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. - AsyncIteratorPrototype = { - // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) - // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator - [SymbolPolyfill.asyncIterator]() { - return this; - } - }; - Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); -} - -/// -class ReadableStreamAsyncIteratorImpl { - constructor(reader, preventCancel) { - this._ongoingPromise = undefined; - this._isFinished = false; - this._reader = reader; - this._preventCancel = preventCancel; - } - next() { - const nextSteps = () => this._nextSteps(); - this._ongoingPromise = this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : - nextSteps(); - return this._ongoingPromise; - } - return(value) { - const returnSteps = () => this._returnSteps(value); - return this._ongoingPromise ? - transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : - returnSteps(); - } - _nextSteps() { - if (this._isFinished) { - return Promise.resolve({ value: undefined, done: true }); - } - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('iterate')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readRequest = { - _chunkSteps: chunk => { - this._ongoingPromise = undefined; - // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. - // FIXME Is this a bug in the specification, or in the test? - queueMicrotask(() => resolvePromise({ value: chunk, done: false })); - }, - _closeSteps: () => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - resolvePromise({ value: undefined, done: true }); - }, - _errorSteps: reason => { - this._ongoingPromise = undefined; - this._isFinished = true; - ReadableStreamReaderGenericRelease(reader); - rejectPromise(reason); - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promise; - } - _returnSteps(value) { - if (this._isFinished) { - return Promise.resolve({ value, done: true }); - } - this._isFinished = true; - const reader = this._reader; - if (reader._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('finish iterating')); - } - if (!this._preventCancel) { - const result = ReadableStreamReaderGenericCancel(reader, value); - ReadableStreamReaderGenericRelease(reader); - return transformPromiseWith(result, () => ({ value, done: true })); - } - ReadableStreamReaderGenericRelease(reader); - return promiseResolvedWith({ value, done: true }); - } -} -const ReadableStreamAsyncIteratorPrototype = { - next() { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); - } - return this._asyncIteratorImpl.next(); - }, - return(value) { - if (!IsReadableStreamAsyncIterator(this)) { - return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); - } - return this._asyncIteratorImpl.return(value); + /** + * Create a binary representation of a tag 1 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const arr = [ + new Uint8Array([this.version]) + ]; + + if (this.version === 6) { + if (this.publicKeyFingerprint !== null) { + arr.push(new Uint8Array([ + this.publicKeyFingerprint.length + 1, + this.publicKeyVersion] + )); + arr.push(this.publicKeyFingerprint); + } else { + arr.push(new Uint8Array([0])); + } + } else { + arr.push(this.publicKeyID.write()); } -}; -if (AsyncIteratorPrototype !== undefined) { - Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); -} -// Abstract operations for the ReadableStream. -function AcquireReadableStreamAsyncIterator(stream, preventCancel) { - const reader = AcquireReadableStreamDefaultReader(stream); - const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); - const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); - iterator._asyncIteratorImpl = impl; - return iterator; -} -function IsReadableStreamAsyncIterator(x) { - if (!typeIsObject(x)) { - return false; + + arr.push( + new Uint8Array([this.publicKeyAlgorithm]), + mod$1.serializeParams(this.publicKeyAlgorithm, this.encrypted) + ); + + return util.concatUint8Array(arr); + } + + /** + * Encrypt session key packet + * @param {PublicKeyPacket} key - Public key + * @throws {Error} if encryption failed + * @async + */ + async encrypt(key) { + const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm); + // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a + // v6 PKESK packet, as it is included in the v2 SEIPD packet. + const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey); + this.encrypted = await mod$1.publicKeyEncrypt( + algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint); + } + + /** + * Decrypts the session key (only for public key encrypted session key packets (tag 1) + * @param {SecretKeyPacket} key - decrypted private key + * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size. + * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric } + * @throws {Error} if decryption failed, unless `randomSessionKey` is given + * @async + */ + async decrypt(key, randomSessionKey) { + // check that session key algo matches the secret key algo + if (this.publicKeyAlgorithm !== key.algorithm) { + throw new Error('Decryption error'); } - if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { - return false; + + const randomPayload = randomSessionKey ? + encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) : + null; + const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes(); + const decryptedData = await mod$1.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload); + + const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey); + + if (this.version === 3) { + // v3 Montgomery curves have cleartext cipher algo + const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448; + this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm; + + if (sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } } - return true; -} -// Helper functions for the ReadableStream. -function streamAsyncIteratorBrandCheckException(name) { - return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + this.sessionKey = sessionKey; + } } -/// -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill -const NumberIsNaN = Number.isNaN || function (x) { - // eslint-disable-next-line no-self-compare - return x !== x; -}; -function IsFiniteNonNegativeNumber(v) { - if (!IsNonNegativeNumber(v)) { - return false; - } - if (v === Infinity) { - return false; - } - return true; +function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + // add checksum + return util.concatUint8Array([ + new Uint8Array(version === 6 ? [] : [cipherAlgo]), + sessionKeyData, + util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8)) + ]); + case enums.publicKey.x25519: + case enums.publicKey.x448: + return sessionKeyData; + default: + throw new Error('Unsupported public key algorithm'); + } } -function IsNonNegativeNumber(v) { - if (typeof v !== 'number') { - return false; - } - if (NumberIsNaN(v)) { - return false; - } - if (v < 0) { - return false; + + +function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) { + switch (keyAlgo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: { + // verify checksum in constant time + const result = decryptedData.subarray(0, decryptedData.length - 2); + const checksum = decryptedData.subarray(decryptedData.length - 2); + const computedChecksum = util.writeChecksum(result.subarray(result.length % 8)); + const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1]; + const decryptedSessionKey = version === 6 ? + { sessionKeyAlgorithm: null, sessionKey: result } : + { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) }; + if (randomSessionKey) { + // We must not leak info about the validity of the decrypted checksum or cipher algo. + // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data. + const isValidPayload = isValidChecksum & + decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm & + decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length; + return { + sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey), + sessionKeyAlgorithm: version === 6 ? null : util.selectUint8( + isValidPayload, + decryptedSessionKey.sessionKeyAlgorithm, + randomSessionKey.sessionKeyAlgorithm + ) + }; + } else { + const isValidPayload = isValidChecksum && ( + version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm)); + if (isValidPayload) { + return decryptedSessionKey; + } else { + throw new Error('Decryption error'); + } + } } - return true; + case enums.publicKey.x25519: + case enums.publicKey.x448: + return { + sessionKeyAlgorithm: null, + sessionKey: decryptedData + }; + default: + throw new Error('Unsupported public key algorithm'); + } } -function DequeueValue(container) { - const pair = container._queue.shift(); - container._queueTotalSize -= pair.size; - if (container._queueTotalSize < 0) { - container._queueTotalSize = 0; - } - return pair.value; -} -function EnqueueValueWithSize(container, value, size) { - size = Number(size); - if (!IsFiniteNonNegativeNumber(size)) { - throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); - } - container._queue.push({ value, size }); - container._queueTotalSize += size; -} -function PeekQueueValue(container) { - const pair = container._queue.peek(); - return pair.value; -} -function ResetQueue(container) { - container._queue = new SimpleQueue(); - container._queueTotalSize = 0; -} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function CreateArrayFromList(elements) { - // We use arrays to represent lists, so this is basically a no-op. - // Do a slice though just in case we happen to depend on the unique-ness. - return elements.slice(); -} -function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { - new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); -} -// Not implemented correctly -function TransferArrayBuffer(O) { - return O; -} -// Not implemented correctly -function IsDetachedBuffer(O) { - return false; -} /** - * A pull-into request in a {@link ReadableByteStreamController}. - * - * @public - */ -class ReadableStreamBYOBRequest { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. - */ - get view() { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('view'); - } - return this._view; - } - respond(bytesWritten) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respond'); - } - assertRequiredArgument(bytesWritten, 1, 'respond'); - bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - if (IsDetachedBuffer(this._view.buffer)) ; - ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); - } - respondWithNewView(view) { - if (!IsReadableStreamBYOBRequest(this)) { - throw byobRequestBrandCheckException('respondWithNewView'); - } - assertRequiredArgument(view, 1, 'respondWithNewView'); - if (!ArrayBuffer.isView(view)) { - throw new TypeError('You can only respond with array buffer views'); - } - if (view.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (view.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._associatedReadableByteStreamController === undefined) { - throw new TypeError('This BYOB request has been invalidated'); - } - ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); - } -} -Object.defineProperties(ReadableStreamBYOBRequest.prototype, { - respond: { enumerable: true }, - respondWithNewView: { enumerable: true }, - view: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBRequest', - configurable: true - }); -} -/** - * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * Symmetric-Key Encrypted Session Key Packets (Tag 3) * - * @public + * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}: + * The Symmetric-Key Encrypted Session Key packet holds the + * symmetric-key encryption of a session key used to encrypt a message. + * Zero or more Public-Key Encrypted Session Key packets and/or + * Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data packet that holds an encrypted message. + * The message is encrypted with a session key, and the session key is + * itself encrypted and stored in the Encrypted Session Key packet or + * the Symmetric-Key Encrypted Session Key packet. */ -class ReadableByteStreamController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the current BYOB pull request, or `null` if there isn't one. - */ - get byobRequest() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('byobRequest'); - } - if (this._byobRequest === null && this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); - const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); - SetUpReadableStreamBYOBRequest(byobRequest, this, view); - this._byobRequest = byobRequest; - } - return this._byobRequest; - } +class SymEncryptedSessionKeyPacket { + static get tag() { + return enums.packet.symEncryptedSessionKey; + } + + /** + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(config$1 = config) { + this.version = config$1.aeadProtect ? 6 : 4; + this.sessionKey = null; /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + * Algorithm to encrypt the session key with + * @type {enums.symmetric} */ - get desiredSize() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('desiredSize'); - } - return ReadableByteStreamControllerGetDesiredSize(this); - } + this.sessionKeyEncryptionAlgorithm = null; /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. + * Algorithm to encrypt the message with + * @type {enums.symmetric} */ - close() { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('close'); - } - if (this._closeRequested) { - throw new TypeError('The stream has already been closed; do not close it again!'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); - } - ReadableByteStreamControllerClose(this); - } - enqueue(chunk) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('enqueue'); - } - assertRequiredArgument(chunk, 1, 'enqueue'); - if (!ArrayBuffer.isView(chunk)) { - throw new TypeError('chunk must be an array buffer view'); - } - if (chunk.byteLength === 0) { - throw new TypeError('chunk must have non-zero byteLength'); - } - if (chunk.buffer.byteLength === 0) { - throw new TypeError(`chunk's buffer must have non-zero byteLength`); - } - if (this._closeRequested) { - throw new TypeError('stream is closed or draining'); - } - const state = this._controlledReadableByteStream._state; - if (state !== 'readable') { - throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); - } - ReadableByteStreamControllerEnqueue(this, chunk); - } + this.sessionKeyAlgorithm = null; /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + * AEAD mode to encrypt the session key with (if AEAD protection is enabled) + * @type {enums.aead} */ - error(e = undefined) { - if (!IsReadableByteStreamController(this)) { - throw byteStreamControllerBrandCheckException('error'); - } - ReadableByteStreamControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - if (this._pendingPullIntos.length > 0) { - const firstDescriptor = this._pendingPullIntos.peek(); - firstDescriptor.bytesFilled = 0; - } - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableByteStreamControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableByteStream; - if (this._queueTotalSize > 0) { - const entry = this._queue.shift(); - this._queueTotalSize -= entry.byteLength; - ReadableByteStreamControllerHandleQueueDrain(this); - const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); - readRequest._chunkSteps(view); - return; - } - const autoAllocateChunkSize = this._autoAllocateChunkSize; - if (autoAllocateChunkSize !== undefined) { - let buffer; - try { - buffer = new ArrayBuffer(autoAllocateChunkSize); - } - catch (bufferE) { - readRequest._errorSteps(bufferE); - return; - } - const pullIntoDescriptor = { - buffer, - byteOffset: 0, - byteLength: autoAllocateChunkSize, - bytesFilled: 0, - elementSize: 1, - viewConstructor: Uint8Array, - readerType: 'default' - }; - this._pendingPullIntos.push(pullIntoDescriptor); - } - ReadableStreamAddReadRequest(stream, readRequest); - ReadableByteStreamControllerCallPullIfNeeded(this); - } -} -Object.defineProperties(ReadableByteStreamController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - byobRequest: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableByteStreamController', - configurable: true - }); -} -// Abstract operations for the ReadableByteStreamController. -function IsReadableByteStreamController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { - return false; - } - return true; -} -function IsReadableStreamBYOBRequest(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { - return false; - } - return true; -} -function ReadableByteStreamControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); - if (!shouldPull) { - return; - } - if (controller._pulling) { - controller._pullAgain = true; - return; - } - controller._pulling = true; - // TODO: Test controller argument - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableByteStreamControllerCallPullIfNeeded(controller); - } - }, e => { - ReadableByteStreamControllerError(controller, e); - }); -} -function ReadableByteStreamControllerClearPendingPullIntos(controller) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - controller._pendingPullIntos = new SimpleQueue(); -} -function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { - let done = false; - if (stream._state === 'closed') { - done = true; - } - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - if (pullIntoDescriptor.readerType === 'default') { - ReadableStreamFulfillReadRequest(stream, filledView, done); - } - else { - ReadableStreamFulfillReadIntoRequest(stream, filledView, done); - } -} -function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { - const bytesFilled = pullIntoDescriptor.bytesFilled; - const elementSize = pullIntoDescriptor.elementSize; - return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); -} -function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { - controller._queue.push({ buffer, byteOffset, byteLength }); - controller._queueTotalSize += byteLength; -} -function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { - const elementSize = pullIntoDescriptor.elementSize; - const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; - const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); - const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; - const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; - let totalBytesToCopyRemaining = maxBytesToCopy; - let ready = false; - if (maxAlignedBytes > currentAlignedBytes) { - totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; - ready = true; - } - const queue = controller._queue; - while (totalBytesToCopyRemaining > 0) { - const headOfQueue = queue.peek(); - const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); - const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); - if (headOfQueue.byteLength === bytesToCopy) { - queue.shift(); - } - else { - headOfQueue.byteOffset += bytesToCopy; - headOfQueue.byteLength -= bytesToCopy; - } - controller._queueTotalSize -= bytesToCopy; - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); - totalBytesToCopyRemaining -= bytesToCopy; - } - return ready; -} -function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - pullIntoDescriptor.bytesFilled += size; -} -function ReadableByteStreamControllerHandleQueueDrain(controller) { - if (controller._queueTotalSize === 0 && controller._closeRequested) { - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(controller._controlledReadableByteStream); - } - else { - ReadableByteStreamControllerCallPullIfNeeded(controller); - } -} -function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { - if (controller._byobRequest === null) { - return; - } - controller._byobRequest._associatedReadableByteStreamController = undefined; - controller._byobRequest._view = null; - controller._byobRequest = null; -} -function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { - while (controller._pendingPullIntos.length > 0) { - if (controller._queueTotalSize === 0) { - return; - } - const pullIntoDescriptor = controller._pendingPullIntos.peek(); - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { - const stream = controller._controlledReadableByteStream; - let elementSize = 1; - if (view.constructor !== DataView) { - elementSize = view.constructor.BYTES_PER_ELEMENT; - } - const ctor = view.constructor; - const buffer = TransferArrayBuffer(view.buffer); - const pullIntoDescriptor = { - buffer, - byteOffset: view.byteOffset, - byteLength: view.byteLength, - bytesFilled: 0, - elementSize, - viewConstructor: ctor, - readerType: 'byob' - }; - if (controller._pendingPullIntos.length > 0) { - controller._pendingPullIntos.push(pullIntoDescriptor); - // No ReadableByteStreamControllerCallPullIfNeeded() call since: - // - No change happens on desiredSize - // - The source has already been notified of that there's at least 1 pending read(view) - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - return; - } - if (stream._state === 'closed') { - const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); - readIntoRequest._closeSteps(emptyView); - return; - } - if (controller._queueTotalSize > 0) { - if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { - const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); - ReadableByteStreamControllerHandleQueueDrain(controller); - readIntoRequest._chunkSteps(filledView); - return; - } - if (controller._closeRequested) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - readIntoRequest._errorSteps(e); - return; - } - } - controller._pendingPullIntos.push(pullIntoDescriptor); - ReadableStreamAddReadIntoRequest(stream, readIntoRequest); - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { - firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); - const stream = controller._controlledReadableByteStream; - if (ReadableStreamHasBYOBReader(stream)) { - while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { - const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); - ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); - } - } -} -function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { - if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { - throw new RangeError('bytesWritten out of range'); - } - ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); - if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { - // TODO: Figure out whether we should detach the buffer or not here. - return; - } - ReadableByteStreamControllerShiftPendingPullInto(controller); - const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; - if (remainderSize > 0) { - const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; - const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); - ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); - } - pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); - pullIntoDescriptor.bytesFilled -= remainderSize; - ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); -} -function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { - const firstDescriptor = controller._pendingPullIntos.peek(); - const state = controller._controlledReadableByteStream._state; - if (state === 'closed') { - if (bytesWritten !== 0) { - throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); - } - ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); - } - else { - ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); - } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerShiftPendingPullInto(controller) { - const descriptor = controller._pendingPullIntos.shift(); - ReadableByteStreamControllerInvalidateBYOBRequest(controller); - return descriptor; -} -function ReadableByteStreamControllerShouldCallPull(controller) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return false; - } - if (controller._closeRequested) { - return false; - } - if (!controller._started) { - return false; - } - if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; - } - if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { - return true; - } - const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; + this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm); + this.encrypted = null; + this.s2k = null; + this.iv = null; + } + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * + * @param {Uint8Array} bytes - Payload of a tag 3 packet + */ + read(bytes) { + let offset = 0; + + // A one-octet version number with value 4, 5 or 6. + this.version = bytes[offset++]; + if (this.version !== 4 && this.version !== 5 && this.version !== 6) { + throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`); } - return false; -} -function ReadableByteStreamControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; -} -// A client of ReadableByteStreamController may use these functions directly to bypass state check. -function ReadableByteStreamControllerClose(controller) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + + if (this.version === 6) { + // A one-octet scalar octet count of the following 5 fields. + offset++; } - if (controller._queueTotalSize > 0) { - controller._closeRequested = true; - return; + + // A one-octet number describing the symmetric algorithm used. + const algo = bytes[offset++]; + + if (this.version >= 5) { + // A one-octet AEAD algorithm. + this.aeadAlgorithm = bytes[offset++]; + + if (this.version === 6) { + // A one-octet scalar octet count of the following field. + offset++; + } } - if (controller._pendingPullIntos.length > 0) { - const firstPendingPullInto = controller._pendingPullIntos.peek(); - if (firstPendingPullInto.bytesFilled > 0) { - const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); - ReadableByteStreamControllerError(controller, e); - throw e; - } + + // A string-to-key (S2K) specifier, length as defined above. + const s2kType = bytes[offset++]; + this.s2k = newS2KFromType(s2kType); + offset += this.s2k.read(bytes.subarray(offset, bytes.length)); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + + // A starting initialization vector of size specified by the AEAD + // algorithm. + this.iv = bytes.subarray(offset, offset += mode.ivLength); } - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamClose(stream); -} -function ReadableByteStreamControllerEnqueue(controller, chunk) { - const stream = controller._controlledReadableByteStream; - if (controller._closeRequested || stream._state !== 'readable') { - return; + + // The encrypted session key itself, which is decrypted with the + // string-to-key object. This is optional in version 4. + if (this.version >= 5 || offset < bytes.length) { + this.encrypted = bytes.subarray(offset, bytes.length); + this.sessionKeyEncryptionAlgorithm = algo; + } else { + this.sessionKeyAlgorithm = algo; } - const buffer = chunk.buffer; - const byteOffset = chunk.byteOffset; - const byteLength = chunk.byteLength; - const transferredBuffer = TransferArrayBuffer(buffer); - if (ReadableStreamHasDefaultReader(stream)) { - if (ReadableStreamGetNumReadRequests(stream) === 0) { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - } - else { - const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); - ReadableStreamFulfillReadRequest(stream, transferredView, false); - } + } + + /** + * Create a binary representation of a tag 3 packet + * + * @returns {Uint8Array} The Uint8Array representation. + */ + write() { + const algo = this.encrypted === null ? + this.sessionKeyAlgorithm : + this.sessionKeyEncryptionAlgorithm; + + let bytes; + + const s2k = this.s2k.write(); + if (this.version === 6) { + const s2kLen = s2k.length; + const fieldsLen = 3 + s2kLen + this.iv.length; + bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]); + } else if (this.version === 5) { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]); + } else { + bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]); + + if (this.encrypted !== null) { + bytes = util.concatUint8Array([bytes, this.encrypted]); + } } - else if (ReadableStreamHasBYOBReader(stream)) { - // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); - ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + + return bytes; + } + + /** + * Decrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(passphrase) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata); + } else if (this.encrypted !== null) { + const decrypted = await mod$1.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize)); + + this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]); + this.sessionKey = decrypted.subarray(1, decrypted.length); + if (this.sessionKey.length !== mod$1.getCipherParams(this.sessionKeyAlgorithm).keySize) { + throw new Error('Unexpected session key size'); + } + } else { + // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo + this.sessionKey = key; } - else { - ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + + /** + * Encrypts the session key with the given passphrase + * @param {String} passphrase - The passphrase in string form + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + const algo = this.sessionKeyEncryptionAlgorithm !== null ? + this.sessionKeyEncryptionAlgorithm : + this.sessionKeyAlgorithm; + + this.sessionKeyEncryptionAlgorithm = algo; + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + + const { blockSize, keySize } = mod$1.getCipherParams(algo); + const key = await this.s2k.produceKey(passphrase, keySize); + + if (this.sessionKey === null) { + this.sessionKey = mod$1.generateSessionKey(this.sessionKeyAlgorithm); } - ReadableByteStreamControllerCallPullIfNeeded(controller); -} -function ReadableByteStreamControllerError(controller, e) { - const stream = controller._controlledReadableByteStream; - if (stream._state !== 'readable') { - return; + + if (this.version >= 5) { + const mode = mod$1.getAEADMode(this.aeadAlgorithm); + this.iv = mod$1.random.getRandomBytes(mode.ivLength); // generate new random IV + const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]); + const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key; + const modeInstance = await mode(algo, encryptionKey); + this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata); + } else { + const toEncrypt = util.concatUint8Array([ + new Uint8Array([this.sessionKeyAlgorithm]), + this.sessionKey + ]); + this.encrypted = await mod$1.mode.cfb.encrypt(algo, key, toEncrypt, new Uint8Array(blockSize), config$1); } - ReadableByteStreamControllerClearPendingPullIntos(controller); - ResetQueue(controller); - ReadableByteStreamControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); -} -function ReadableByteStreamControllerGetDesiredSize(controller) { - const state = controller._controlledReadableByteStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; - } - return controller._strategyHWM - controller._queueTotalSize; -} -function ReadableByteStreamControllerRespond(controller, bytesWritten) { - bytesWritten = Number(bytesWritten); - if (!IsFiniteNonNegativeNumber(bytesWritten)) { - throw new RangeError('bytesWritten must be a finite'); - } - ReadableByteStreamControllerRespondInternal(controller, bytesWritten); -} -function ReadableByteStreamControllerRespondWithNewView(controller, view) { - const firstDescriptor = controller._pendingPullIntos.peek(); - if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { - throw new RangeError('The region specified by view does not match byobRequest'); - } - if (firstDescriptor.byteLength !== view.byteLength) { - throw new RangeError('The buffer of view has different capacity than byobRequest'); - } - firstDescriptor.buffer = view.buffer; - ReadableByteStreamControllerRespondInternal(controller, view.byteLength); -} -function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { - controller._controlledReadableByteStream = stream; - controller._pullAgain = false; - controller._pulling = false; - controller._byobRequest = null; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._closeRequested = false; - controller._started = false; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - controller._autoAllocateChunkSize = autoAllocateChunkSize; - controller._pendingPullIntos = new SimpleQueue(); - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableByteStreamControllerCallPullIfNeeded(controller); - }, r => { - ReadableByteStreamControllerError(controller, r); - }); + } } -function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { - const controller = Object.create(ReadableByteStreamController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingByteSource.start !== undefined) { - startAlgorithm = () => underlyingByteSource.start(controller); - } - if (underlyingByteSource.pull !== undefined) { - pullAlgorithm = () => underlyingByteSource.pull(controller); - } - if (underlyingByteSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ +class PublicKeyPacket { + static get tag() { + return enums.packet.publicKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + /** + * Packet version + * @type {Integer} + */ + this.version = config$1.v6Keys ? 6 : 4; + /** + * Key creation date. + * @type {Date} + */ + this.created = util.normalizeDate(date); + /** + * Public key algorithm. + * @type {enums.publicKey} + */ + this.algorithm = null; + /** + * Algorithm specific public params + * @type {Object} + */ + this.publicParams = null; + /** + * Time until expiration in days (V3 only) + * @type {Integer} + */ + this.expirationTimeV3 = 0; + /** + * Fingerprint bytes + * @type {Uint8Array} + */ + this.fingerprint = null; + /** + * KeyID + * @type {module:type/keyid~KeyID} + */ + this.keyID = null; + } + + /** + * Create a PublicKeyPacket from a SecretKeyPacket + * @param {SecretKeyPacket} secretKeyPacket - key packet to convert + * @returns {PublicKeyPacket} public key packet + * @static + */ + static fromSecretKeyPacket(secretKeyPacket) { + const keyPacket = new PublicKeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * @param {Uint8Array} bytes - Input array to read the packet from + * @returns {Object} This object with attributes set by the parser + * @async + */ + async read(bytes, config$1 = config) { + let pos = 0; + // A one-octet version number (4, 5 or 6). + this.version = bytes[pos++]; + if (this.version === 5 && !config$1.enableParsingV5Entities) { + throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed'); } - const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; - if (autoAllocateChunkSize === 0) { - throw new TypeError('autoAllocateChunkSize must be greater than 0'); + + if (this.version === 4 || this.version === 5 || this.version === 6) { + // - A four-octet number denoting the time that the key was created. + this.created = util.readDate(bytes.subarray(pos, pos + 4)); + pos += 4; + + // - A one-octet number denoting the public-key algorithm of this key. + this.algorithm = bytes[pos++]; + + if (this.version >= 5) { + // - A four-octet scalar octet count for the following key material. + pos += 4; + } + + // - A series of values comprising the key material. + const { read, publicParams } = mod$1.parsePublicKeyParams(this.algorithm, bytes.subarray(pos)); + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if ( + this.version === 6 && + publicParams.oid && ( + publicParams.oid.getName() === enums.curve.curve25519Legacy || + publicParams.oid.getName() === enums.curve.ed25519Legacy + ) + ) { + throw new Error('Legacy curve25519 cannot be used with v6 keys'); + } + this.publicParams = publicParams; + pos += read; + + // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor + await this.computeFingerprintAndKeyID(); + return pos; } - SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); -} -function SetUpReadableStreamBYOBRequest(request, controller, view) { - request._associatedReadableByteStreamController = controller; - request._view = view; -} -// Helper functions for the ReadableStreamBYOBRequest. -function byobRequestBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); -} -// Helper functions for the ReadableByteStreamController. -function byteStreamControllerBrandCheckException(name) { - return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); -} + throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`); + } -// Abstract operations for the ReadableStream. -function AcquireReadableStreamBYOBReader(stream) { - return new ReadableStreamBYOBReader(stream); -} -// ReadableStream API exposed for controllers. -function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { - stream._reader._readIntoRequests.push(readIntoRequest); -} -function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { - const reader = stream._reader; - const readIntoRequest = reader._readIntoRequests.shift(); - if (done) { - readIntoRequest._closeSteps(chunk); + /** + * Creates an OpenPGP public key packet for the given key. + * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet. + */ + write() { + const arr = []; + // Version + arr.push(new Uint8Array([this.version])); + arr.push(util.writeDate(this.created)); + // A one-octet number denoting the public-key algorithm of this key + arr.push(new Uint8Array([this.algorithm])); + + const params = mod$1.serializeParams(this.algorithm, this.publicParams); + if (this.version >= 5) { + // A four-octet scalar octet count for the following key material + arr.push(util.writeNumber(params.length, 4)); } - else { - readIntoRequest._chunkSteps(chunk); + // Algorithm-specific params + arr.push(params); + return util.concatUint8Array(arr); + } + + /** + * Write packet in order to be hashed; either for a signature or a fingerprint + * @param {Integer} version - target version of signature or key + */ + writeForHash(version) { + const bytes = this.writePublicKey(); + + const versionOctet = 0x95 + version; + const lengthOctets = version >= 5 ? 4 : 2; + return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]); + } + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return null; + } + + /** + * Returns the creation time of the key + * @returns {Date} + */ + getCreationTime() { + return this.created; + } + + /** + * Return the key ID of the key + * @returns {module:type/keyid~KeyID} The 8-byte key ID + */ + getKeyID() { + return this.keyID; + } + + /** + * Computes and set the key ID and fingerprint of the key + * @async + */ + async computeFingerprintAndKeyID() { + await this.computeFingerprint(); + this.keyID = new KeyID(); + + if (this.version >= 5) { + this.keyID.read(this.fingerprint.subarray(0, 8)); + } else if (this.version === 4) { + this.keyID.read(this.fingerprint.subarray(12, 20)); + } else { + throw new Error('Unsupported key version'); } -} -function ReadableStreamGetNumReadIntoRequests(stream) { - return stream._reader._readIntoRequests.length; -} -function ReadableStreamHasBYOBReader(stream) { - const reader = stream._reader; - if (reader === undefined) { - return false; + } + + /** + * Computes and set the fingerprint of the key + */ + async computeFingerprint() { + const toHash = this.writeForHash(this.version); + + if (this.version >= 5) { + this.fingerprint = await mod$1.hash.sha256(toHash); + } else if (this.version === 4) { + this.fingerprint = await mod$1.hash.sha1(toHash); + } else { + throw new Error('Unsupported key version'); } - if (!IsReadableStreamBYOBReader(reader)) { - return false; + } + + /** + * Returns the fingerprint of the key, as an array of bytes + * @returns {Uint8Array} A Uint8Array containing the fingerprint + */ + getFingerprintBytes() { + return this.fingerprint; + } + + /** + * Calculates and returns the fingerprint of the key, as a string + * @returns {String} A string containing the fingerprint in lowercase hex + */ + getFingerprint() { + return util.uint8ArrayToHex(this.getFingerprintBytes()); + } + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns {Boolean} Whether the two keys have the same version and public key data. + */ + hasSameFingerprintAs(other) { + return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey()); + } + + /** + * Returns algorithm information + * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}. + */ + getAlgorithmInfo() { + const result = {}; + result.algorithm = enums.read(enums.publicKey, this.algorithm); + // RSA, DSA or ElGamal public modulo + const modulo = this.publicParams.n || this.publicParams.p; + if (modulo) { + result.bits = util.uint8ArrayBitLength(modulo); + } else if (this.publicParams.oid) { + result.curve = this.publicParams.oid.getName(); } - return true; + return result; + } } + +/** + * Alias of read() + * @see PublicKeyPacket#read + */ +PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read; + +/** + * Alias of write() + * @see PublicKeyPacket#write + */ +PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +// A SE packet can contain the following packet types +const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + OnePassSignaturePacket, + SignaturePacket +]); + /** - * A BYOB reader vended by a {@link ReadableStream}. + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) * - * @public - */ -class ReadableStreamBYOBReader { - constructor(stream) { - assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); - assertReadableStream(stream, 'First parameter'); - if (IsReadableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive reading by another reader'); - } - if (!IsReadableByteStreamController(stream._readableStreamController)) { - throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + - 'source'); - } - ReadableStreamReaderGenericInitialize(this, stream); - this._readIntoRequests = new SimpleQueue(); - } - /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the reader's lock is released before the stream finishes closing. - */ - get closed() { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('closed')); - } - return this._closedPromise; - } - /** - * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. - */ - cancel(reason = undefined) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('cancel')); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('cancel')); - } - return ReadableStreamReaderGenericCancel(this, reason); - } + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ +class SymmetricallyEncryptedDataPacket { + static get tag() { + return enums.packet.symmetricallyEncryptedData; + } + + constructor() { /** - * Attempts to reads bytes into view, and returns a promise resolved with the result. - * - * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + * Encrypted secret-key data */ - read(view) { - if (!IsReadableStreamBYOBReader(this)) { - return promiseRejectedWith(byobReaderBrandCheckException('read')); - } - if (!ArrayBuffer.isView(view)) { - return promiseRejectedWith(new TypeError('view must be an array buffer view')); - } - if (view.byteLength === 0) { - return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); - } - if (view.buffer.byteLength === 0) { - return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); - } - if (this._ownerReadableStream === undefined) { - return promiseRejectedWith(readerLockException('read from')); - } - let resolvePromise; - let rejectPromise; - const promise = newPromise((resolve, reject) => { - resolvePromise = resolve; - rejectPromise = reject; - }); - const readIntoRequest = { - _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), - _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), - _errorSteps: e => rejectPromise(e) - }; - ReadableStreamBYOBReaderRead(this, view, readIntoRequest); - return promise; - } + this.encrypted = null; /** - * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. - * If the associated stream is errored when the lock is released, the reader will appear errored in the same way - * from now on; otherwise, the reader will appear closed. - * - * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by - * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to - * do so will throw a `TypeError` and leave the reader locked to the stream. + * Decrypted packets contained within. + * @type {PacketList} */ - releaseLock() { - if (!IsReadableStreamBYOBReader(this)) { - throw byobReaderBrandCheckException('releaseLock'); - } - if (this._ownerReadableStream === undefined) { - return; - } - if (this._readIntoRequests.length > 0) { - throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); - } - ReadableStreamReaderGenericRelease(this); - } -} -Object.defineProperties(ReadableStreamBYOBReader.prototype, { - cancel: { enumerable: true }, - read: { enumerable: true }, - releaseLock: { enumerable: true }, - closed: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamBYOBReader', - configurable: true - }); -} -// Abstract operations for the readers. -function IsReadableStreamBYOBReader(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { - return false; + this.packets = null; + } + + read(bytes) { + this.encrypted = bytes; + } + + write() { + return this.encrypted; + } + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + + * @throws {Error} if decryption was not successful + * @async + */ + async decrypt(sessionKeyAlgorithm, key, config$1 = config) { + // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error + if (!config$1.allowUnauthenticatedMessages) { + throw new Error('Message is not authenticated.'); } - return true; + + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + const encrypted = await readToEnd(clone(this.encrypted)); + const decrypted = await mod$1.mode.cfb.decrypt(sessionKeyAlgorithm, key, + encrypted.subarray(blockSize + 2), + encrypted.subarray(2, blockSize + 2) + ); + + this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1); + } + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use + * @param {Uint8Array} key - The key of cipher blocksize length to be used + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(sessionKeyAlgorithm, key, config$1 = config) { + const data = this.packets.write(); + const { blockSize } = mod$1.getCipherParams(sessionKeyAlgorithm); + + const prefix = await mod$1.getPrefixRandom(sessionKeyAlgorithm); + const FRE = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1); + const ciphertext = await mod$1.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1); + this.encrypted = util.concat([FRE, ciphertext]); + } } -function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { - const stream = reader._ownerReadableStream; - stream._disturbed = true; - if (stream._state === 'errored') { - readIntoRequest._errorSteps(stream._storedError); - } - else { - ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the strange "Marker packet" (Tag 10) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * + * The body of this packet consists of: + * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + * + * Such a packet MUST be ignored when received. It may be placed at the + * beginning of a message that uses features not available in PGP + * version 2.6 in order to cause that version to report that newer + * software is necessary to process the message. + */ +class MarkerPacket { + static get tag() { + return enums.packet.marker; + } + + /** + * Parsing function for a marker data packet (tag 10). + * @param {Uint8Array} bytes - Payload of a tag 10 packet + * @returns {Boolean} whether the packet payload contains "PGP" + */ + read(bytes) { + if (bytes[0] === 0x50 && // P + bytes[1] === 0x47 && // G + bytes[2] === 0x50) { // P + return true; } + return false; + } + + write() { + return new Uint8Array([0x50, 0x47, 0x50]); + } } -// Helper functions for the ReadableStreamBYOBReader. -function byobReaderBrandCheckException(name) { - return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); -} -function ExtractHighWaterMark(strategy, defaultHWM) { - const { highWaterMark } = strategy; - if (highWaterMark === undefined) { - return defaultHWM; - } - if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { - throw new RangeError('Invalid highWaterMark'); - } - return highWaterMark; -} -function ExtractSizeAlgorithm(strategy) { - const { size } = strategy; - if (!size) { - return () => 1; - } - return size; -} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + * @extends PublicKeyPacket + */ +class PublicSubkeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.publicSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(date, config) { + super(date, config); + } -function convertQueuingStrategy(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - const size = init === null || init === void 0 ? void 0 : init.size; - return { - highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), - size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) - }; -} -function convertQueuingStrategySize(fn, context) { - assertFunction(fn, context); - return chunk => convertUnrestrictedDouble(fn(chunk)); + /** + * Create a PublicSubkeyPacket from a SecretSubkeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert + * @returns {SecretSubkeyPacket} public key packet + * @static + */ + static fromSecretSubkeyPacket(secretSubkeyPacket) { + const keyPacket = new PublicSubkeyPacket(); + const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket; + keyPacket.version = version; + keyPacket.created = created; + keyPacket.algorithm = algorithm; + keyPacket.publicParams = publicParams; + keyPacket.keyID = keyID; + keyPacket.fingerprint = fingerprint; + return keyPacket; + } } -function convertUnderlyingSink(original, context) { - assertDictionary(original, context); - const abort = original === null || original === void 0 ? void 0 : original.abort; - const close = original === null || original === void 0 ? void 0 : original.close; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - const write = original === null || original === void 0 ? void 0 : original.write; - return { - abort: abort === undefined ? - undefined : - convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), - close: close === undefined ? - undefined : - convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), - start: start === undefined ? - undefined : - convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), - write: write === undefined ? - undefined : - convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), - type - }; -} -function convertUnderlyingSinkAbortCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSinkCloseCallback(fn, original, context) { - assertFunction(fn, context); - return () => promiseCall(fn, original, []); -} -function convertUnderlyingSinkStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertUnderlyingSinkWriteCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); -} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function assertWritableStream(x, context) { - if (!IsWritableStream(x)) { - throw new TypeError(`${context} is not a WritableStream.`); - } -} /** - * A writable stream represents a destination for data, into which you can write. + * Implementation of the User Attribute Packet (Tag 17) + * + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. * - * @public + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. */ -class WritableStream$1 { - constructor(rawUnderlyingSink = {}, rawStrategy = {}) { - if (rawUnderlyingSink === undefined) { - rawUnderlyingSink = null; - } - else { - assertObject(rawUnderlyingSink, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); - InitializeWritableStream(this); - const type = underlyingSink.type; - if (type !== undefined) { - throw new RangeError('Invalid type is specified'); - } - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); +class UserAttributePacket { + static get tag() { + return enums.packet.userAttribute; + } + + constructor() { + this.attributes = []; + } + + /** + * parsing function for a user attribute packet (tag 17). + * @param {Uint8Array} input - Payload of a tag 17 packet + */ + read(bytes) { + let i = 0; + while (i < bytes.length) { + const len = readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len))); + i += len.len; } - /** - * Returns whether or not the writable stream is locked to a writer. - */ - get locked() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('locked'); - } - return IsWritableStreamLocked(this); + } + + /** + * Creates a binary representation of the user attribute packet + * @returns {Uint8Array} String representation. + */ + write() { + const arr = []; + for (let i = 0; i < this.attributes.length; i++) { + arr.push(writeSimpleLength(this.attributes[i].length)); + arr.push(util.stringToUint8Array(this.attributes[i])); + } + return util.concatUint8Array(arr); + } + + /** + * Compare for equality + * @param {UserAttributePacket} usrAttr + * @returns {Boolean} True if equal. + */ + equals(usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) { + return false; } + return this.attributes.every(function(attr, index) { + return attr === usrAttr.attributes[index]; + }); + } +} + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + * @extends PublicKeyPacket + */ +class SecretKeyPacket extends PublicKeyPacket { + static get tag() { + return enums.packet.secretKey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); /** - * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be - * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort - * mechanism of the underlying sink. - * - * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled - * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel - * the stream) if the stream is currently locked. + * Secret-key data */ - abort(reason = undefined) { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('abort')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); - } - return WritableStreamAbort(this, reason); - } + this.keyMaterial = null; /** - * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its - * close behavior. During this time any further attempts to write will fail (without erroring the stream). - * - * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream - * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with - * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. */ - close() { - if (!IsWritableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$2('close')); - } - if (IsWritableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); - } - if (WritableStreamCloseQueuedOrInFlight(this)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamClose(this); - } + this.isEncrypted = null; /** - * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream - * is locked, no other writer can be acquired until this one is released. - * - * This functionality is especially useful for creating abstractions that desire the ability to write to a stream - * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at - * the same time, which would cause the resulting written data to be unpredictable and probably useless. + * S2K usage + * @type {enums.symmetric} */ - getWriter() { - if (!IsWritableStream(this)) { - throw streamBrandCheckException$2('getWriter'); - } - return AcquireWritableStreamDefaultWriter(this); - } -} -Object.defineProperties(WritableStream$1.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - getWriter: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStream', - configurable: true - }); -} -// Abstract operations for the WritableStream. -function AcquireWritableStreamDefaultWriter(stream) { - return new WritableStreamDefaultWriter(stream); -} -// Throws if and only if startAlgorithm throws. -function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(WritableStream$1.prototype); - InitializeWritableStream(stream); - const controller = Object.create(WritableStreamDefaultController.prototype); - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeWritableStream(stream) { - stream._state = 'writable'; - // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is - // 'erroring' or 'errored'. May be set to an undefined value. - stream._storedError = undefined; - stream._writer = undefined; - // Initialize to undefined first because the constructor of the controller checks this - // variable to validate the caller. - stream._writableStreamController = undefined; - // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data - // producer without waiting for the queued writes to finish. - stream._writeRequests = new SimpleQueue(); - // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents - // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. - stream._inFlightWriteRequest = undefined; - // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer - // has been detached. - stream._closeRequest = undefined; - // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it - // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. - stream._inFlightCloseRequest = undefined; - // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. - stream._pendingAbortRequest = undefined; - // The backpressure signal set by the controller. - stream._backpressure = false; -} -function IsWritableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { - return false; - } - return true; -} -function IsWritableStreamLocked(stream) { - if (stream._writer === undefined) { - return false; - } - return true; -} -function WritableStreamAbort(stream, reason) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseResolvedWith(undefined); - } - if (stream._pendingAbortRequest !== undefined) { - return stream._pendingAbortRequest._promise; - } - let wasAlreadyErroring = false; - if (state === 'erroring') { - wasAlreadyErroring = true; - // reason will not be used, so don't keep a reference to it. - reason = undefined; - } - const promise = newPromise((resolve, reject) => { - stream._pendingAbortRequest = { - _promise: undefined, - _resolve: resolve, - _reject: reject, - _reason: reason, - _wasAlreadyErroring: wasAlreadyErroring - }; - }); - stream._pendingAbortRequest._promise = promise; - if (!wasAlreadyErroring) { - WritableStreamStartErroring(stream, reason); - } - return promise; -} -function WritableStreamClose(stream) { - const state = stream._state; - if (state === 'closed' || state === 'errored') { - return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); - } - const promise = newPromise((resolve, reject) => { - const closeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._closeRequest = closeRequest; - }); - const writer = stream._writer; - if (writer !== undefined && stream._backpressure && state === 'writable') { - defaultWriterReadyPromiseResolve(writer); - } - WritableStreamDefaultControllerClose(stream._writableStreamController); - return promise; -} -// WritableStream API exposed for controllers. -function WritableStreamAddWriteRequest(stream) { - const promise = newPromise((resolve, reject) => { - const writeRequest = { - _resolve: resolve, - _reject: reject - }; - stream._writeRequests.push(writeRequest); - }); - return promise; -} -function WritableStreamDealWithRejection(stream, error) { - const state = stream._state; - if (state === 'writable') { - WritableStreamStartErroring(stream, error); - return; - } - WritableStreamFinishErroring(stream); -} -function WritableStreamStartErroring(stream, reason) { - const controller = stream._writableStreamController; - stream._state = 'erroring'; - stream._storedError = reason; - const writer = stream._writer; - if (writer !== undefined) { - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); - } - if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { - WritableStreamFinishErroring(stream); - } -} -function WritableStreamFinishErroring(stream) { - stream._state = 'errored'; - stream._writableStreamController[ErrorSteps](); - const storedError = stream._storedError; - stream._writeRequests.forEach(writeRequest => { - writeRequest._reject(storedError); - }); - stream._writeRequests = new SimpleQueue(); - if (stream._pendingAbortRequest === undefined) { - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const abortRequest = stream._pendingAbortRequest; - stream._pendingAbortRequest = undefined; - if (abortRequest._wasAlreadyErroring) { - abortRequest._reject(storedError); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - return; - } - const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); - uponPromise(promise, () => { - abortRequest._resolve(); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }, (reason) => { - abortRequest._reject(reason); - WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - }); -} -function WritableStreamFinishInFlightWrite(stream) { - stream._inFlightWriteRequest._resolve(undefined); - stream._inFlightWriteRequest = undefined; -} -function WritableStreamFinishInFlightWriteWithError(stream, error) { - stream._inFlightWriteRequest._reject(error); - stream._inFlightWriteRequest = undefined; - WritableStreamDealWithRejection(stream, error); -} -function WritableStreamFinishInFlightClose(stream) { - stream._inFlightCloseRequest._resolve(undefined); - stream._inFlightCloseRequest = undefined; - const state = stream._state; - if (state === 'erroring') { - // The error was too late to do anything, so it is ignored. - stream._storedError = undefined; - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._resolve(); - stream._pendingAbortRequest = undefined; - } - } - stream._state = 'closed'; - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseResolve(writer); - } -} -function WritableStreamFinishInFlightCloseWithError(stream, error) { - stream._inFlightCloseRequest._reject(error); - stream._inFlightCloseRequest = undefined; - // Never execute sink abort() after sink close(). - if (stream._pendingAbortRequest !== undefined) { - stream._pendingAbortRequest._reject(error); - stream._pendingAbortRequest = undefined; - } - WritableStreamDealWithRejection(stream, error); -} -// TODO(ricea): Fix alphabetical order. -function WritableStreamCloseQueuedOrInFlight(stream) { - if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamHasOperationMarkedInFlight(stream) { - if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { - return false; - } - return true; -} -function WritableStreamMarkCloseRequestInFlight(stream) { - stream._inFlightCloseRequest = stream._closeRequest; - stream._closeRequest = undefined; -} -function WritableStreamMarkFirstWriteRequestInFlight(stream) { - stream._inFlightWriteRequest = stream._writeRequests.shift(); -} -function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { - if (stream._closeRequest !== undefined) { - stream._closeRequest._reject(stream._storedError); - stream._closeRequest = undefined; - } - const writer = stream._writer; - if (writer !== undefined) { - defaultWriterClosedPromiseReject(writer, stream._storedError); - } -} -function WritableStreamUpdateBackpressure(stream, backpressure) { - const writer = stream._writer; - if (writer !== undefined && backpressure !== stream._backpressure) { - if (backpressure) { - defaultWriterReadyPromiseReset(writer); - } - else { - defaultWriterReadyPromiseResolve(writer); - } - } - stream._backpressure = backpressure; -} -/** - * A default writer vended by a {@link WritableStream}. - * - * @public - */ -class WritableStreamDefaultWriter { - constructor(stream) { - assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); - assertWritableStream(stream, 'First parameter'); - if (IsWritableStreamLocked(stream)) { - throw new TypeError('This stream has already been locked for exclusive writing by another writer'); - } - this._ownerWritableStream = stream; - stream._writer = this; - const state = stream._state; - if (state === 'writable') { - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { - defaultWriterReadyPromiseInitialize(this); - } - else { - defaultWriterReadyPromiseInitializeAsResolved(this); - } - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'erroring') { - defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); - defaultWriterClosedPromiseInitialize(this); - } - else if (state === 'closed') { - defaultWriterReadyPromiseInitializeAsResolved(this); - defaultWriterClosedPromiseInitializeAsResolved(this); - } - else { - const storedError = stream._storedError; - defaultWriterReadyPromiseInitializeAsRejected(this, storedError); - defaultWriterClosedPromiseInitializeAsRejected(this, storedError); - } - } + this.s2kUsage = 0; /** - * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or - * the writer’s lock is released before the stream finishes closing. + * S2K object + * @type {type/s2k} */ - get closed() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('closed')); - } - return this._closedPromise; - } + this.s2k = null; /** - * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. - * A producer can use this information to determine the right amount of data to write. - * - * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort - * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when - * the writer’s lock is released. + * Symmetric algorithm to encrypt the key with + * @type {enums.symmetric} */ - get desiredSize() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('desiredSize'); - } - if (this._ownerWritableStream === undefined) { - throw defaultWriterLockException('desiredSize'); - } - return WritableStreamDefaultWriterGetDesiredSize(this); - } + this.symmetric = null; /** - * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions - * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips - * back to zero or below, the getter will return a new promise that stays pending until the next transition. - * - * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become - * rejected. + * AEAD algorithm to encrypt the key with (if AEAD protection is enabled) + * @type {enums.aead} */ - get ready() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('ready')); - } - return this._readyPromise; - } + this.aead = null; /** - * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis + * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older). + * This value is only relevant to know how to decrypt the key: + * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism. + * @type {Boolean} + * @private */ - abort(reason = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('abort')); - } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('abort')); - } - return WritableStreamDefaultWriterAbort(this, reason); - } + this.isLegacyAEAD = null; /** - * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + * Decrypted private parameters, referenced by name + * @type {Object} */ - close() { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('close')); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return promiseRejectedWith(defaultWriterLockException('close')); - } - if (WritableStreamCloseQueuedOrInFlight(stream)) { - return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); - } - return WritableStreamDefaultWriterClose(this); - } + this.privateParams = null; /** - * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. - * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from - * now on; otherwise, the writer will appear closed. - * - * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the - * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). - * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents - * other producers from writing in an interleaved manner. + * `true` for keys whose integrity is already confirmed, based on + * the AEAD encryption mechanism + * @type {Boolean} + * @private */ - releaseLock() { - if (!IsWritableStreamDefaultWriter(this)) { - throw defaultWriterBrandCheckException('releaseLock'); - } - const stream = this._ownerWritableStream; - if (stream === undefined) { - return; - } - WritableStreamDefaultWriterRelease(this); + this.usedModernAEAD = null; + } + + // 5.5.3. Secret-Key Packet Formats + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param {Uint8Array} bytes - Input string to read the packet from + * @async + */ + async read(bytes, config$1 = config) { + // - A Public-Key or Public-Subkey packet, as described above. + let i = await this.readPublicKey(bytes, config$1); + const startOfSecretKeyData = i; + + // - One octet indicating string-to-key usage conventions. Zero + // indicates that the secret-key data is not encrypted. 255 or 254 + // indicates that a string-to-key specifier is being given. Any + // other value is a symmetric-key encryption algorithm identifier. + this.s2kUsage = bytes[i++]; + + // - Only for a version 5 packet, a one-octet scalar octet count of + // the next 4 optional fields. + if (this.version === 5) { + i++; + } + + // - Only for a version 6 packet where the secret key material is + // encrypted (that is, where the previous octet is not zero), a one- + // octet scalar octet count of the cumulative length of all the + // following optional string-to-key parameter fields. + if (this.version === 6 && this.s2kUsage) { + i++; } - write(chunk = undefined) { - if (!IsWritableStreamDefaultWriter(this)) { - return promiseRejectedWith(defaultWriterBrandCheckException('write')); + + try { + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one-octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + this.symmetric = bytes[i++]; + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + this.aead = bytes[i++]; } - if (this._ownerWritableStream === undefined) { - return promiseRejectedWith(defaultWriterLockException('write to')); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + i++; } - return WritableStreamDefaultWriterWrite(this, chunk); - } -} -Object.defineProperties(WritableStreamDefaultWriter.prototype, { - abort: { enumerable: true }, - close: { enumerable: true }, - releaseLock: { enumerable: true }, - write: { enumerable: true }, - closed: { enumerable: true }, - desiredSize: { enumerable: true }, - ready: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultWriter', - configurable: true - }); -} -// Abstract operations for the WritableStreamDefaultWriter. -function IsWritableStreamDefaultWriter(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { - return false; - } - return true; -} -// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. -function WritableStreamDefaultWriterAbort(writer, reason) { - const stream = writer._ownerWritableStream; - return WritableStreamAbort(stream, reason); -} -function WritableStreamDefaultWriterClose(writer) { - const stream = writer._ownerWritableStream; - return WritableStreamClose(stream); -} -function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseResolvedWith(undefined); - } - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - return WritableStreamDefaultWriterClose(writer); -} -function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { - if (writer._closedPromiseState === 'pending') { - defaultWriterClosedPromiseReject(writer, error); - } - else { - defaultWriterClosedPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { - if (writer._readyPromiseState === 'pending') { - defaultWriterReadyPromiseReject(writer, error); - } - else { - defaultWriterReadyPromiseResetToRejected(writer, error); - } -} -function WritableStreamDefaultWriterGetDesiredSize(writer) { - const stream = writer._ownerWritableStream; - const state = stream._state; - if (state === 'errored' || state === 'erroring') { - return null; - } - if (state === 'closed') { - return 0; - } - return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); -} -function WritableStreamDefaultWriterRelease(writer) { - const stream = writer._ownerWritableStream; - const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); - WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); - // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not - // rejected until afterwards. This means that simply testing state will not work. - WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); - stream._writer = undefined; - writer._ownerWritableStream = undefined; -} -function WritableStreamDefaultWriterWrite(writer, chunk) { - const stream = writer._ownerWritableStream; - const controller = stream._writableStreamController; - const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); - if (stream !== writer._ownerWritableStream) { - return promiseRejectedWith(defaultWriterLockException('write to')); - } - const state = stream._state; - if (state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { - return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); - } - if (state === 'erroring') { - return promiseRejectedWith(stream._storedError); - } - const promise = WritableStreamAddWriteRequest(stream); - WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); - return promise; -} -const closeSentinel = {}; -/** - * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. - * - * @public - */ -class WritableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. - * - * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying - * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the - * normal lifecycle of interactions with the underlying sink. - */ - error(e = undefined) { - if (!IsWritableStreamDefaultController(this)) { - throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + const s2kType = bytes[i++]; + this.s2k = newS2KFromType(s2kType); + i += this.s2k.read(bytes.subarray(i, bytes.length)); + + if (this.s2k.type === 'gnu-dummy') { + return; } - const state = this._controlledWritableStream._state; - if (state !== 'writable') { - // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so - // just treat it as a no-op. - return; + } else if (this.s2kUsage) { + this.symmetric = this.s2kUsage; + } + + + if (this.s2kUsage) { + // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5). + // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format). + // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always + // fail if the key was parsed according to the wrong format, since the keys are processed differently. + // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag. + this.isLegacyAEAD = this.s2kUsage === 253 && ( + this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy)); + // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV) + // of the same length as the cipher's block size. + // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the + // cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm. + // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero + if (this.s2kUsage !== 253 || this.isLegacyAEAD) { + this.iv = bytes.subarray( + i, + i + mod$1.getCipherParams(this.symmetric).blockSize + ); + this.usedModernAEAD = false; + } else { + // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted), + // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which + // is used as the nonce for the AEAD algorithm. + this.iv = bytes.subarray( + i, + i + mod$1.getAEADMode(this.aead).ivLength + ); + // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation. + this.usedModernAEAD = true; } - WritableStreamDefaultControllerError(this, e); - } - /** @internal */ - [AbortSteps](reason) { - const result = this._abortAlgorithm(reason); - WritableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [ErrorSteps]() { - ResetQueue(this); - } -} -Object.defineProperties(WritableStreamDefaultController.prototype, { - error: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'WritableStreamDefaultController', - configurable: true - }); -} -// Abstract operations implementing interface required by the WritableStream. -function IsWritableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { - return false; - } - return true; -} -function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledWritableStream = stream; - stream._writableStreamController = controller; - // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._writeAlgorithm = writeAlgorithm; - controller._closeAlgorithm = closeAlgorithm; - controller._abortAlgorithm = abortAlgorithm; - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - const startResult = startAlgorithm(); - const startPromise = promiseResolvedWith(startResult); - uponPromise(startPromise, () => { - controller._started = true; - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, r => { - controller._started = true; - WritableStreamDealWithRejection(stream, r); - }); -} -function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { - const controller = Object.create(WritableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let writeAlgorithm = () => promiseResolvedWith(undefined); - let closeAlgorithm = () => promiseResolvedWith(undefined); - let abortAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSink.start !== undefined) { - startAlgorithm = () => underlyingSink.start(controller); - } - if (underlyingSink.write !== undefined) { - writeAlgorithm = chunk => underlyingSink.write(chunk, controller); - } - if (underlyingSink.close !== undefined) { - closeAlgorithm = () => underlyingSink.close(); - } - if (underlyingSink.abort !== undefined) { - abortAlgorithm = reason => underlyingSink.abort(reason); - } - SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); -} -// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. -function WritableStreamDefaultControllerClearAlgorithms(controller) { - controller._writeAlgorithm = undefined; - controller._closeAlgorithm = undefined; - controller._abortAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -function WritableStreamDefaultControllerClose(controller) { - EnqueueValueWithSize(controller, closeSentinel, 0); - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { - try { - return controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); - return 1; - } -} -function WritableStreamDefaultControllerGetDesiredSize(controller) { - return controller._strategyHWM - controller._queueTotalSize; -} -function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); - return; - } - const stream = controller._controlledWritableStream; - if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); - } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); -} -// Abstract operations for the WritableStreamDefaultController. -function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { - const stream = controller._controlledWritableStream; - if (!controller._started) { - return; - } - if (stream._inFlightWriteRequest !== undefined) { - return; - } - const state = stream._state; - if (state === 'erroring') { - WritableStreamFinishErroring(stream); - return; - } - if (controller._queue.length === 0) { - return; - } - const value = PeekQueueValue(controller); - if (value === closeSentinel) { - WritableStreamDefaultControllerProcessClose(controller); - } - else { - WritableStreamDefaultControllerProcessWrite(controller, value); + + i += this.iv.length; + } + } catch (e) { + // if the s2k is unsupported, we still want to support encrypting and verifying with the given key + if (!this.s2kUsage) throw e; // always throw for decrypted keys + this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData); + this.isEncrypted = true; } -} -function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { - if (controller._controlledWritableStream._state === 'writable') { - WritableStreamDefaultControllerError(controller, error); + + // - Only for a version 5 packet, a four-octet scalar octet count for + // the following key material. + if (this.version === 5) { + i += 4; } -} -function WritableStreamDefaultControllerProcessClose(controller) { - const stream = controller._controlledWritableStream; - WritableStreamMarkCloseRequestInFlight(stream); - DequeueValue(controller); - const sinkClosePromise = controller._closeAlgorithm(); - WritableStreamDefaultControllerClearAlgorithms(controller); - uponPromise(sinkClosePromise, () => { - WritableStreamFinishInFlightClose(stream); - }, reason => { - WritableStreamFinishInFlightCloseWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerProcessWrite(controller, chunk) { - const stream = controller._controlledWritableStream; - WritableStreamMarkFirstWriteRequestInFlight(stream); - const sinkWritePromise = controller._writeAlgorithm(chunk); - uponPromise(sinkWritePromise, () => { - WritableStreamFinishInFlightWrite(stream); - const state = stream._state; - DequeueValue(controller); - if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { - const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); - WritableStreamUpdateBackpressure(stream, backpressure); + + // - Plain or encrypted multiprecision integers comprising the secret + // key data. These algorithm-specific fields are as described + // below. + this.keyMaterial = bytes.subarray(i); + this.isEncrypted = !!this.s2kUsage; + + if (!this.isEncrypted) { + let cleartext; + if (this.version === 6) { + cleartext = this.keyMaterial; + } else { + cleartext = this.keyMaterial.subarray(0, -2); + if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) { + throw new Error('Key checksum mismatch'); } - WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); - }, reason => { - if (stream._state === 'writable') { - WritableStreamDefaultControllerClearAlgorithms(controller); + } + try { + const { read, privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + if (read < cleartext.length) { + throw new Error('Error reading MPIs'); } - WritableStreamFinishInFlightWriteWithError(stream, reason); - }); -} -function WritableStreamDefaultControllerGetBackpressure(controller) { - const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); - return desiredSize <= 0; -} -// A client of WritableStreamDefaultController may use these functions directly to bypass state check. -function WritableStreamDefaultControllerError(controller, error) { - const stream = controller._controlledWritableStream; - WritableStreamDefaultControllerClearAlgorithms(controller); - WritableStreamStartErroring(stream, error); -} -// Helper functions for the WritableStream. -function streamBrandCheckException$2(name) { - return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); -} -// Helper functions for the WritableStreamDefaultWriter. -function defaultWriterBrandCheckException(name) { - return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); -} -function defaultWriterLockException(name) { - return new TypeError('Cannot ' + name + ' a stream using a released writer'); -} -function defaultWriterClosedPromiseInitialize(writer) { - writer._closedPromise = newPromise((resolve, reject) => { - writer._closedPromise_resolve = resolve; - writer._closedPromise_reject = reject; - writer._closedPromiseState = 'pending'; - }); -} -function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseReject(writer, reason); -} -function defaultWriterClosedPromiseInitializeAsResolved(writer) { - defaultWriterClosedPromiseInitialize(writer); - defaultWriterClosedPromiseResolve(writer); -} -function defaultWriterClosedPromiseReject(writer, reason) { - if (writer._closedPromise_reject === undefined) { - return; - } - setPromiseIsHandledToTrue(writer._closedPromise); - writer._closedPromise_reject(reason); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'rejected'; -} -function defaultWriterClosedPromiseResetToRejected(writer, reason) { - defaultWriterClosedPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterClosedPromiseResolve(writer) { - if (writer._closedPromise_resolve === undefined) { - return; - } - writer._closedPromise_resolve(undefined); - writer._closedPromise_resolve = undefined; - writer._closedPromise_reject = undefined; - writer._closedPromiseState = 'resolved'; -} -function defaultWriterReadyPromiseInitialize(writer) { - writer._readyPromise = newPromise((resolve, reject) => { - writer._readyPromise_resolve = resolve; - writer._readyPromise_reject = reject; - }); - writer._readyPromiseState = 'pending'; -} -function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseReject(writer, reason); -} -function defaultWriterReadyPromiseInitializeAsResolved(writer) { - defaultWriterReadyPromiseInitialize(writer); - defaultWriterReadyPromiseResolve(writer); -} -function defaultWriterReadyPromiseReject(writer, reason) { - if (writer._readyPromise_reject === undefined) { - return; + this.privateParams = privateParams; + } catch (err) { + if (err instanceof UnsupportedError) throw err; + // avoid throwing potentially sensitive errors + throw new Error('Error reading MPIs'); + } } - setPromiseIsHandledToTrue(writer._readyPromise); - writer._readyPromise_reject(reason); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'rejected'; -} -function defaultWriterReadyPromiseReset(writer) { - defaultWriterReadyPromiseInitialize(writer); -} -function defaultWriterReadyPromiseResetToRejected(writer, reason) { - defaultWriterReadyPromiseInitializeAsRejected(writer, reason); -} -function defaultWriterReadyPromiseResolve(writer) { - if (writer._readyPromise_resolve === undefined) { - return; + } + + /** + * Creates an OpenPGP key packet for the given key. + * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet. + */ + write() { + const serializedPublicKey = this.writePublicKey(); + if (this.unparseableKeyMaterial) { + return util.concatUint8Array([ + serializedPublicKey, + this.unparseableKeyMaterial + ]); } - writer._readyPromise_resolve(undefined); - writer._readyPromise_resolve = undefined; - writer._readyPromise_reject = undefined; - writer._readyPromiseState = 'fulfilled'; -} -function isAbortSignal(value) { - if (typeof value !== 'object' || value === null) { - return false; + const arr = [serializedPublicKey]; + arr.push(new Uint8Array([this.s2kUsage])); + + const optionalFieldsArr = []; + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // one- octet symmetric encryption algorithm. + if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) { + optionalFieldsArr.push(this.symmetric); + + // - [Optional] If string-to-key usage octet was 253, a one-octet + // AEAD algorithm. + if (this.s2kUsage === 253) { + optionalFieldsArr.push(this.aead); + } + + const s2k = this.s2k.write(); + + // - [Optional] Only for a version 6 packet, and if string-to-key usage + // octet was 255, 254, or 253, an one-octet count of the following field. + if (this.version === 6) { + optionalFieldsArr.push(s2k.length); + } + + // - [Optional] If string-to-key usage octet was 255, 254, or 253, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + optionalFieldsArr.push(...s2k); } - try { - return typeof value.aborted === 'boolean'; + + // - [Optional] If secret data is encrypted (string-to-key usage octet + // not zero), an Initial Vector (IV) of the same length as the + // cipher's block size. + if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') { + optionalFieldsArr.push(...this.iv); } - catch (_a) { - // AbortSignal.prototype.aborted throws if its brand check fails - return false; + + if (this.version === 5 || (this.version === 6 && this.s2kUsage)) { + arr.push(new Uint8Array([optionalFieldsArr.length])); } -} + arr.push(new Uint8Array(optionalFieldsArr)); -/// -const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined; + if (!this.isDummy()) { + if (!this.s2kUsage) { + this.keyMaterial = mod$1.serializeParams(this.algorithm, this.privateParams); + } -/// -function isDOMExceptionConstructor(ctor) { - if (!(typeof ctor === 'function' || typeof ctor === 'object')) { - return false; + if (this.version === 5) { + arr.push(util.writeNumber(this.keyMaterial.length, 4)); + } + arr.push(this.keyMaterial); + + if (!this.s2kUsage && this.version !== 6) { + arr.push(util.writeChecksum(this.keyMaterial)); + } } - try { - new ctor(); - return true; + + return util.concatUint8Array(arr); + } + + /** + * Check whether secret-key data is available in decrypted form. + * Returns false for gnu-dummy keys and null for public keys. + * @returns {Boolean|null} + */ + isDecrypted() { + return this.isEncrypted === false; + } + + /** + * Check whether the key includes secret key material. + * Some secret keys do not include it, and can thus only be used + * for public-key operations (encryption and verification). + * Such keys are: + * - GNU-dummy keys, where the secret material has been stripped away + * - encrypted keys with unsupported S2K or cipher + */ + isMissingSecretKeyMaterial() { + return this.unparseableKeyMaterial !== undefined || this.isDummy(); + } + + /** + * Check whether this is a gnu-dummy key + * @returns {Boolean} + */ + isDummy() { + return !!(this.s2k && this.s2k.type === 'gnu-dummy'); + } + + /** + * Remove private key material, converting the key to a dummy one. + * The resulting key cannot be used for signing/decrypting but can still verify signatures. + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + makeDummy(config$1 = config) { + if (this.isDummy()) { + return; } - catch (_a) { - return false; + if (this.isDecrypted()) { + this.clearPrivateParams(); } -} -function createDOMExceptionPolyfill() { - // eslint-disable-next-line no-shadow - const ctor = function DOMException(message, name) { - this.message = message || ''; - this.name = name || 'Error'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - }; - ctor.prototype = Object.create(Error.prototype); - Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); - return ctor; -} -// eslint-disable-next-line no-redeclare -const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); - -function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { - const reader = AcquireReadableStreamDefaultReader(source); - const writer = AcquireWritableStreamDefaultWriter(dest); - source._disturbed = true; - let shuttingDown = false; - // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. - let currentWrite = promiseResolvedWith(undefined); - return newPromise((resolve, reject) => { - let abortAlgorithm; - if (signal !== undefined) { - abortAlgorithm = () => { - const error = new DOMException$1('Aborted', 'AbortError'); - const actions = []; - if (!preventAbort) { - actions.push(() => { - if (dest._state === 'writable') { - return WritableStreamAbort(dest, error); - } - return promiseResolvedWith(undefined); - }); - } - if (!preventCancel) { - actions.push(() => { - if (source._state === 'readable') { - return ReadableStreamCancel(source, error); - } - return promiseResolvedWith(undefined); - }); - } - shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); - }; - if (signal.aborted) { - abortAlgorithm(); - return; - } - signal.addEventListener('abort', abortAlgorithm); - } - // Using reader and writer, read all chunks from this and write them to dest - // - Backpressure must be enforced - // - Shutdown must stop all activity - function pipeLoop() { - return newPromise((resolveLoop, rejectLoop) => { - function next(done) { - if (done) { - resolveLoop(); - } - else { - // Use `PerformPromiseThen` instead of `uponPromise` to avoid - // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers - PerformPromiseThen(pipeStep(), next, rejectLoop); - } - } - next(false); - }); - } - function pipeStep() { - if (shuttingDown) { - return promiseResolvedWith(true); - } - return PerformPromiseThen(writer._readyPromise, () => { - return newPromise((resolveRead, rejectRead) => { - ReadableStreamDefaultReaderRead(reader, { - _chunkSteps: chunk => { - currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); - resolveRead(false); - }, - _closeSteps: () => resolveRead(true), - _errorSteps: rejectRead - }); - }); - }); - } - // Errors must be propagated forward - isOrBecomesErrored(source, reader._closedPromise, storedError => { - if (!preventAbort) { - shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Errors must be propagated backward - isOrBecomesErrored(dest, writer._closedPromise, storedError => { - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); - } - else { - shutdown(true, storedError); - } - }); - // Closing must be propagated forward - isOrBecomesClosed(source, reader._closedPromise, () => { - if (!preventClose) { - shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); - } - else { - shutdown(); - } - }); - // Closing must be propagated backward - if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { - const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); - if (!preventCancel) { - shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); - } - else { - shutdown(true, destClosed); - } - } - setPromiseIsHandledToTrue(pipeLoop()); - function waitForWritesToFinish() { - // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait - // for that too. - const oldCurrentWrite = currentWrite; - return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); - } - function isOrBecomesErrored(stream, promise, action) { - if (stream._state === 'errored') { - action(stream._storedError); - } - else { - uponRejection(promise, action); - } - } - function isOrBecomesClosed(stream, promise, action) { - if (stream._state === 'closed') { - action(); - } - else { - uponFulfillment(promise, action); - } - } - function shutdownWithAction(action, originalIsError, originalError) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), doTheRest); - } - else { - doTheRest(); - } - function doTheRest() { - uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); - } - } - function shutdown(isError, error) { - if (shuttingDown) { - return; - } - shuttingDown = true; - if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { - uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); - } - else { - finalize(isError, error); - } - } - function finalize(isError, error) { - WritableStreamDefaultWriterRelease(writer); - ReadableStreamReaderGenericRelease(reader); - if (signal !== undefined) { - signal.removeEventListener('abort', abortAlgorithm); - } - if (isError) { - reject(error); - } - else { - resolve(undefined); - } - } - }); -} + delete this.unparseableKeyMaterial; + this.isEncrypted = null; + this.keyMaterial = null; + this.s2k = newS2KFromType(enums.s2k.gnu, config$1); + this.s2k.algorithm = 0; + this.s2k.c = 0; + this.s2k.type = 'gnu-dummy'; + this.s2kUsage = 254; + this.symmetric = enums.symmetric.aes256; + this.isLegacyAEAD = null; + this.usedModernAEAD = null; + } -/** - * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. - * - * @public - */ -class ReadableStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is - * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. - */ - get desiredSize() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('desiredSize'); - } - return ReadableStreamDefaultControllerGetDesiredSize(this); + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param {String} passphrase + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if encryption was not successful + * @async + */ + async encrypt(passphrase, config$1 = config) { + if (this.isDummy()) { + return; } - /** - * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from - * the stream, but once those are read, the stream will become closed. - */ - close() { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('close'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits close'); - } - ReadableStreamDefaultControllerClose(this); + + if (!this.isDecrypted()) { + throw new Error('Key packet is already encrypted'); } - enqueue(chunk = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('enqueue'); - } - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { - throw new TypeError('The stream is not in a state that permits enqueue'); - } - return ReadableStreamDefaultControllerEnqueue(this, chunk); + + if (!passphrase) { + throw new Error('A non-empty passphrase is required for key encryption.'); } - /** - * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. - */ - error(e = undefined) { - if (!IsReadableStreamDefaultController(this)) { - throw defaultControllerBrandCheckException$1('error'); - } - ReadableStreamDefaultControllerError(this, e); - } - /** @internal */ - [CancelSteps](reason) { - ResetQueue(this); - const result = this._cancelAlgorithm(reason); - ReadableStreamDefaultControllerClearAlgorithms(this); - return result; - } - /** @internal */ - [PullSteps](readRequest) { - const stream = this._controlledReadableStream; - if (this._queue.length > 0) { - const chunk = DequeueValue(this); - if (this._closeRequested && this._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(this); - ReadableStreamClose(stream); - } - else { - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } - readRequest._chunkSteps(chunk); - } - else { - ReadableStreamAddReadRequest(stream, readRequest); - ReadableStreamDefaultControllerCallPullIfNeeded(this); - } + + this.s2k = newS2KFromConfig(config$1); + this.s2k.generateSalt(); + const cleartext = mod$1.serializeParams(this.algorithm, this.privateParams); + this.symmetric = enums.symmetric.aes256; + + const { blockSize } = mod$1.getCipherParams(this.symmetric); + + if (config$1.aeadProtect) { + this.s2kUsage = 253; + this.aead = config$1.preferredAEADAlgorithm; + const mode = mod$1.getAEADMode(this.aead); + this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead. + this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material + + const serializedPacketTag = writeTag(this.constructor.tag); + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + + const modeInstance = await mode(this.symmetric, key); + this.iv = this.isLegacyAEAD ? mod$1.random.getRandomBytes(blockSize) : mod$1.random.getRandomBytes(mode.ivLength); + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + + this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData); + } else { + this.s2kUsage = 254; + this.usedModernAEAD = false; + const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric); + this.iv = mod$1.random.getRandomBytes(blockSize); + this.keyMaterial = await mod$1.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([ + cleartext, + await mod$1.hash.sha1(cleartext, config$1) + ]), this.iv, config$1); } -} -Object.defineProperties(ReadableStreamDefaultController.prototype, { - close: { enumerable: true }, - enqueue: { enumerable: true }, - error: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStreamDefaultController', - configurable: true - }); -} -// Abstract operations for the ReadableStreamDefaultController. -function IsReadableStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; + } + + /** + * Decrypts the private key params which are needed to use the key. + * Successful decryption does not imply key integrity, call validate() to confirm that. + * {@link SecretKeyPacket.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param {String} passphrase - The passphrase for this private key as string + * @throws {Error} if the key is already decrypted, or if decryption was not successful + * @async + */ + async decrypt(passphrase) { + if (this.isDummy()) { + return false; } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { - return false; + + if (this.unparseableKeyMaterial) { + throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo'); } - return true; -} -function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { - const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); - if (!shouldPull) { - return; + + if (this.isDecrypted()) { + throw new Error('Key packet is already decrypted.'); } - if (controller._pulling) { - controller._pullAgain = true; - return; + + let key; + const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only + if (this.s2kUsage === 254 || this.s2kUsage === 253) { + key = await produceEncryptionKey( + this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD); + } else if (this.s2kUsage === 255) { + throw new Error('Encrypted private key is authenticated using an insecure two-byte hash'); + } else { + throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5'); } - controller._pulling = true; - const pullPromise = controller._pullAlgorithm(); - uponPromise(pullPromise, () => { - controller._pulling = false; - if (controller._pullAgain) { - controller._pullAgain = false; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); + + let cleartext; + if (this.s2kUsage === 253) { + const mode = mod$1.getAEADMode(this.aead); + const modeInstance = await mode(this.symmetric, key); + try { + const associateData = this.isLegacyAEAD ? + new Uint8Array() : + util.concatUint8Array([serializedPacketTag, this.writePublicKey()]); + cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData); + } catch (err) { + if (err.message === 'Authentication tag mismatch') { + throw new Error('Incorrect key passphrase: ' + err.message); } - }, e => { - ReadableStreamDefaultControllerError(controller, e); - }); -} -function ReadableStreamDefaultControllerShouldCallPull(controller) { - const stream = controller._controlledReadableStream; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return false; - } - if (!controller._started) { - return false; + throw err; + } + } else { + const cleartextWithHash = await mod$1.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv); + + cleartext = cleartextWithHash.subarray(0, -20); + const hash = await mod$1.hash.sha1(cleartext); + + if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) { + throw new Error('Incorrect key passphrase'); + } } - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - return true; + + try { + const { privateParams } = mod$1.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams); + this.privateParams = privateParams; + } catch (err) { + throw new Error('Error reading MPIs'); } - const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); - if (desiredSize > 0) { - return true; + this.isEncrypted = false; + this.keyMaterial = null; + this.s2kUsage = 0; + this.aead = null; + this.symmetric = null; + this.isLegacyAEAD = null; + } + + /** + * Checks that the key parameters are consistent + * @throws {Error} if validation was not successful + * @async + */ + async validate() { + if (this.isDummy()) { + return; } - return false; -} -function ReadableStreamDefaultControllerClearAlgorithms(controller) { - controller._pullAlgorithm = undefined; - controller._cancelAlgorithm = undefined; - controller._strategySizeAlgorithm = undefined; -} -// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. -function ReadableStreamDefaultControllerClose(controller) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; + + if (!this.isDecrypted()) { + throw new Error('Key is not decrypted'); } - const stream = controller._controlledReadableStream; - controller._closeRequested = true; - if (controller._queue.length === 0) { - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamClose(stream); + + if (this.usedModernAEAD) { + // key integrity confirmed by successful AEAD decryption + return; } -} -function ReadableStreamDefaultControllerEnqueue(controller, chunk) { - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { - return; + + let validParams; + try { + // this can throw if some parameters are undefined + validParams = await mod$1.validateParams(this.algorithm, this.publicParams, this.privateParams); + } catch (_) { + validParams = false; } - const stream = controller._controlledReadableStream; - if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { - ReadableStreamFulfillReadRequest(stream, chunk, false); + if (!validParams) { + throw new Error('Key is invalid'); } - else { - let chunkSize; - try { - chunkSize = controller._strategySizeAlgorithm(chunk); - } - catch (chunkSizeE) { - ReadableStreamDefaultControllerError(controller, chunkSizeE); - throw chunkSizeE; - } - try { - EnqueueValueWithSize(controller, chunk, chunkSize); - } - catch (enqueueE) { - ReadableStreamDefaultControllerError(controller, enqueueE); - throw enqueueE; - } + } + + async generate(bits, curve) { + // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures. + // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs. + if (this.version === 6 && ( + (this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) || + this.algorithm === enums.publicKey.eddsaLegacy + )) { + throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`); + } + const { privateParams, publicParams } = await mod$1.generateParams(this.algorithm, bits, curve); + this.privateParams = privateParams; + this.publicParams = publicParams; + this.isEncrypted = false; + } + + /** + * Clear private key parameters + */ + clearPrivateParams() { + if (this.isMissingSecretKeyMaterial()) { + return; } - ReadableStreamDefaultControllerCallPullIfNeeded(controller); + + Object.keys(this.privateParams).forEach(name => { + const param = this.privateParams[name]; + param.fill(0); + delete this.privateParams[name]; + }); + this.privateParams = null; + this.isEncrypted = true; + } } -function ReadableStreamDefaultControllerError(controller, e) { - const stream = controller._controlledReadableStream; - if (stream._state !== 'readable') { - return; - } - ResetQueue(controller); - ReadableStreamDefaultControllerClearAlgorithms(controller); - ReadableStreamError(stream, e); + +/** + * Derive encryption key + * @param {Number} keyVersion - key derivation differs for v5 keys + * @param {module:type/s2k} s2k + * @param {String} passphrase + * @param {module:enums.symmetric} cipherAlgo + * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5) + * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5) + * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only) + * @returns encryption key + */ +async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD) { + if (s2k.type === 'argon2' && !aeadMode) { + throw new Error('Using Argon2 S2K without AEAD is not allowed'); + } + if (s2k.type === 'simple' && keyVersion === 6) { + throw new Error('Using Simple S2K with version 6 keys is not allowed'); + } + const { keySize } = mod$1.getCipherParams(cipherAlgo); + const derivedKey = await s2k.produceKey(passphrase, keySize); + if (!aeadMode || keyVersion === 5 || isLegacyAEAD) { + return derivedKey; + } + const info = util.concatUint8Array([ + serializedPacketTag, + new Uint8Array([keyVersion, cipherAlgo, aeadMode]) + ]); + return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize); } -function ReadableStreamDefaultControllerGetDesiredSize(controller) { - const state = controller._controlledReadableStream._state; - if (state === 'errored') { - return null; - } - if (state === 'closed') { - return 0; + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the User ID Packet (Tag 13) + * + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ +class UserIDPacket { + static get tag() { + return enums.packet.userID; + } + + constructor() { + /** A string containing the user id. Usually in the form + * John Doe + * @type {String} + */ + this.userID = ''; + + this.name = ''; + this.email = ''; + this.comment = ''; + } + + /** + * Create UserIDPacket instance from object + * @param {Object} userID - Object specifying userID name, email and comment + * @returns {UserIDPacket} + * @static + */ + static fromObject(userID) { + if (util.isString(userID) || + (userID.name && !util.isString(userID.name)) || + (userID.email && !util.isEmailAddress(userID.email)) || + (userID.comment && !util.isString(userID.comment))) { + throw new Error('Invalid user ID format'); } - return controller._strategyHWM - controller._queueTotalSize; -} -// This is used in the implementation of TransformStream. -function ReadableStreamDefaultControllerHasBackpressure(controller) { - if (ReadableStreamDefaultControllerShouldCallPull(controller)) { - return false; + const packet = new UserIDPacket(); + Object.assign(packet, userID); + const components = []; + if (packet.name) components.push(packet.name); + if (packet.comment) components.push(`(${packet.comment})`); + if (packet.email) components.push(`<${packet.email}>`); + packet.userID = components.join(' '); + return packet; + } + + /** + * Parsing function for a user id packet (tag 13). + * @param {Uint8Array} input - Payload of a tag 13 packet + */ + read(bytes, config$1 = config) { + const userID = util.decodeUTF8(bytes); + if (userID.length > config$1.maxUserIDLength) { + throw new Error('User ID string is too long'); } - return true; -} -function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { - const state = controller._controlledReadableStream._state; - if (!controller._closeRequested && state === 'readable') { - return true; + + /** + * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1, + * as well comments placed between the name (if present) and the bracketed email address: + * - name (comment) + * - email + * In the first case, the `email` is the only required part, and it must contain the `@` symbol. + * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`, + * since they interfere with `comment` parsing. + */ + const re = /^(?[^()]+\s+)?(?\([^()]+\)\s+)?(?<\S+@\S+>)$/; + const matches = re.exec(userID); + if (matches !== null) { + const { name, comment, email } = matches.groups; + this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace + this.name = name?.trim() || ''; + this.email = email.substring(1, email.length - 1); // remove brackets + } else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace + this.email = userID; } - return false; + + this.userID = userID; + } + + /** + * Creates a binary representation of the user id packet + * @returns {Uint8Array} Binary representation. + */ + write() { + return util.encodeUTF8(this.userID); + } + + equals(otherUserID) { + return otherUserID && otherUserID.userID === this.userID; + } } -function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { - controller._controlledReadableStream = stream; - controller._queue = undefined; - controller._queueTotalSize = undefined; - ResetQueue(controller); - controller._started = false; - controller._closeRequested = false; - controller._pullAgain = false; - controller._pulling = false; - controller._strategySizeAlgorithm = sizeAlgorithm; - controller._strategyHWM = highWaterMark; - controller._pullAlgorithm = pullAlgorithm; - controller._cancelAlgorithm = cancelAlgorithm; - stream._readableStreamController = controller; - const startResult = startAlgorithm(); - uponPromise(promiseResolvedWith(startResult), () => { - controller._started = true; - ReadableStreamDefaultControllerCallPullIfNeeded(controller); - }, r => { - ReadableStreamDefaultControllerError(controller, r); - }); + +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + * @extends SecretKeyPacket + */ +class SecretSubkeyPacket extends SecretKeyPacket { + static get tag() { + return enums.packet.secretSubkey; + } + + /** + * @param {Date} [date] - Creation date + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + constructor(date = new Date(), config$1 = config) { + super(date, config$1); + } } -function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { - const controller = Object.create(ReadableStreamDefaultController.prototype); - let startAlgorithm = () => undefined; - let pullAlgorithm = () => promiseResolvedWith(undefined); - let cancelAlgorithm = () => promiseResolvedWith(undefined); - if (underlyingSource.start !== undefined) { - startAlgorithm = () => underlyingSource.start(controller); - } - if (underlyingSource.pull !== undefined) { - pullAlgorithm = () => underlyingSource.pull(controller); - } - if (underlyingSource.cancel !== undefined) { - cancelAlgorithm = reason => underlyingSource.cancel(reason); - } - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); -} -// Helper functions for the ReadableStreamDefaultController. -function defaultControllerBrandCheckException$1(name) { - return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); -} - -function ReadableStreamTee(stream, cloneForBranch2) { - const reader = AcquireReadableStreamDefaultReader(stream); - let reading = false; - let canceled1 = false; - let canceled2 = false; - let reason1; - let reason2; - let branch1; - let branch2; - let resolveCancelPromise; - const cancelPromise = newPromise(resolve => { - resolveCancelPromise = resolve; - }); - function pullAlgorithm() { - if (reading) { - return promiseResolvedWith(undefined); - } - reading = true; - const readRequest = { - _chunkSteps: value => { - // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using - // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let - // successful synchronously-available reads get ahead of asynchronously-available errors. - queueMicrotask(() => { - reading = false; - const value1 = value; - const value2 = value; - // There is no way to access the cloning code right now in the reference implementation. - // If we add one then we'll need an implementation for serializable objects. - // if (!canceled2 && cloneForBranch2) { - // value2 = StructuredDeserialize(StructuredSerialize(value2)); - // } - if (!canceled1) { - ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1); - } - if (!canceled2) { - ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2); - } - }); - }, - _closeSteps: () => { - reading = false; - if (!canceled1) { - ReadableStreamDefaultControllerClose(branch1._readableStreamController); - } - if (!canceled2) { - ReadableStreamDefaultControllerClose(branch2._readableStreamController); - } - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }, - _errorSteps: () => { - reading = false; - } - }; - ReadableStreamDefaultReaderRead(reader, readRequest); - return promiseResolvedWith(undefined); - } - function cancel1Algorithm(reason) { - canceled1 = true; - reason1 = reason; - if (canceled2) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function cancel2Algorithm(reason) { - canceled2 = true; - reason2 = reason; - if (canceled1) { - const compositeReason = CreateArrayFromList([reason1, reason2]); - const cancelResult = ReadableStreamCancel(stream, compositeReason); - resolveCancelPromise(cancelResult); - } - return cancelPromise; - } - function startAlgorithm() { - // do nothing - } - branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); - branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); - uponRejection(reader._closedPromise, (r) => { - ReadableStreamDefaultControllerError(branch1._readableStreamController, r); - ReadableStreamDefaultControllerError(branch2._readableStreamController, r); - if (!canceled1 || !canceled2) { - resolveCancelPromise(undefined); - } - }); - return [branch1, branch2]; + +/** + * Implementation of the Trust Packet (Tag 12) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ +class TrustPacket { + static get tag() { + return enums.packet.trust; + } + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + */ + read() { + throw new UnsupportedError('Trust packets are not supported'); + } + + write() { + throw new UnsupportedError('Trust packets are not supported'); + } } -function convertUnderlyingDefaultOrByteSource(source, context) { - assertDictionary(source, context); - const original = source; - const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; - const cancel = original === null || original === void 0 ? void 0 : original.cancel; - const pull = original === null || original === void 0 ? void 0 : original.pull; - const start = original === null || original === void 0 ? void 0 : original.start; - const type = original === null || original === void 0 ? void 0 : original.type; - return { - autoAllocateChunkSize: autoAllocateChunkSize === undefined ? - undefined : - convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), - cancel: cancel === undefined ? - undefined : - convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), - pull: pull === undefined ? - undefined : - convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), - start: start === undefined ? - undefined : - convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), - type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) - }; -} -function convertUnderlyingSourceCancelCallback(fn, original, context) { - assertFunction(fn, context); - return (reason) => promiseCall(fn, original, [reason]); -} -function convertUnderlyingSourcePullCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertUnderlyingSourceStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertReadableStreamType(type, context) { - type = `${type}`; - if (type !== 'bytes') { - throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); - } - return type; +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2022 Proton AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +/** + * Implementation of the Padding Packet + * + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}: + * Padding Packet + */ +class PaddingPacket { + static get tag() { + return enums.packet.padding; + } + + constructor() { + this.padding = null; + } + + /** + * Read a padding packet + * @param {Uint8Array | ReadableStream} bytes + */ + read(bytes) { // eslint-disable-line @typescript-eslint/no-unused-vars + // Padding packets are ignored, so this function is never called. + } + + /** + * Write the padding packet + * @returns {Uint8Array} The padding packet. + */ + write() { + return this.padding; + } + + /** + * Create random padding. + * @param {Number} length - The length of padding to be generated. + * @throws {Error} if padding generation was not successful + * @async + */ + async createPadding(length) { + this.padding = await mod$1.random.getRandomBytes(length); + } } -function convertReaderOptions(options, context) { - assertDictionary(options, context); - const mode = options === null || options === void 0 ? void 0 : options.mode; - return { - mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) - }; -} -function convertReadableStreamReaderMode(mode, context) { - mode = `${mode}`; - if (mode !== 'byob') { - throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); - } - return mode; -} +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -function convertIteratorOptions(options, context) { - assertDictionary(options, context); - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - return { preventCancel: Boolean(preventCancel) }; -} -function convertPipeOptions(options, context) { - assertDictionary(options, context); - const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; - const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; - const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; - const signal = options === null || options === void 0 ? void 0 : options.signal; - if (signal !== undefined) { - assertAbortSignal(signal, `${context} has member 'signal' that`); - } - return { - preventAbort: Boolean(preventAbort), - preventCancel: Boolean(preventCancel), - preventClose: Boolean(preventClose), - signal - }; -} -function assertAbortSignal(signal, context) { - if (!isAbortSignal(signal)) { - throw new TypeError(`${context} is not an AbortSignal.`); - } -} +// A Signature can contain the following packets +const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); + +/** + * Class that represents an OpenPGP signature. + */ +class Signature { + /** + * @param {PacketList} packetlist - The signature packets + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } + + /** + * Returns binary encoded signature + * @returns {ReadableStream} Binary signature. + */ + write() { + return this.packets.write(); + } -function convertReadableWritablePair(pair, context) { - assertDictionary(pair, context); - const readable = pair === null || pair === void 0 ? void 0 : pair.readable; - assertRequiredField(readable, 'readable', 'ReadableWritablePair'); - assertReadableStream(readable, `${context} has member 'readable' that`); - const writable = pair === null || pair === void 0 ? void 0 : pair.writable; - assertRequiredField(writable, 'writable', 'ReadableWritablePair'); - assertWritableStream(writable, `${context} has member 'writable' that`); - return { readable, writable }; + /** + * Returns ASCII armored text of signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1); + } + + /** + * Returns an array of KeyIDs of all of the issuers who created this signature + * @returns {Array} The Key IDs of the signing keys + */ + getSigningKeyIDs() { + return this.packets.map(packet => packet.issuerKeyID); + } } /** - * A readable stream represents a source of data, from which you can read. - * - * @public + * reads an (optionally armored) OpenPGP signature and returns a signature object + * @param {Object} options + * @param {String} [options.armoredSignature] - Armored signature to be parsed + * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New signature object. + * @async + * @static */ -class ReadableStream$1 { - constructor(rawUnderlyingSource = {}, rawStrategy = {}) { - if (rawUnderlyingSource === undefined) { - rawUnderlyingSource = null; - } - else { - assertObject(rawUnderlyingSource, 'First parameter'); - } - const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); - const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); - InitializeReadableStream(this); - if (underlyingSource.type === 'bytes') { - if (strategy.size !== undefined) { - throw new RangeError('The strategy for a byte stream cannot have a size function'); - } - const highWaterMark = ExtractHighWaterMark(strategy, 0); - SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); - } - else { - const sizeAlgorithm = ExtractSizeAlgorithm(strategy); - const highWaterMark = ExtractHighWaterMark(strategy, 1); - SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); - } - } - /** - * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. - */ - get locked() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('locked'); - } - return IsReadableStreamLocked(this); - } - /** - * Cancels the stream, signaling a loss of interest in the stream by a consumer. - * - * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} - * method, which might or might not use it. - */ - cancel(reason = undefined) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('cancel')); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); - } - return ReadableStreamCancel(this, reason); - } - getReader(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('getReader'); - } - const options = convertReaderOptions(rawOptions, 'First parameter'); - if (options.mode === undefined) { - return AcquireReadableStreamDefaultReader(this); - } - return AcquireReadableStreamBYOBReader(this); - } - pipeThrough(rawTransform, rawOptions = {}) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('pipeThrough'); - } - assertRequiredArgument(rawTransform, 1, 'pipeThrough'); - const transform = convertReadableWritablePair(rawTransform, 'First parameter'); - const options = convertPipeOptions(rawOptions, 'Second parameter'); - if (IsReadableStreamLocked(this)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); - } - if (IsWritableStreamLocked(transform.writable)) { - throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); - } - const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - setPromiseIsHandledToTrue(promise); - return transform.readable; - } - pipeTo(destination, rawOptions = {}) { - if (!IsReadableStream(this)) { - return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); - } - if (destination === undefined) { - return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); - } - if (!IsWritableStream(destination)) { - return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); - } - let options; - try { - options = convertPipeOptions(rawOptions, 'Second parameter'); - } - catch (e) { - return promiseRejectedWith(e); - } - if (IsReadableStreamLocked(this)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); - } - if (IsWritableStreamLocked(destination)) { - return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); - } - return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); - } - /** - * Tees this readable stream, returning a two-element array containing the two resulting branches as - * new {@link ReadableStream} instances. - * - * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. - * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be - * propagated to the stream's underlying source. - * - * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, - * this could allow interference between the two branches. - */ - tee() { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('tee'); - } - const branches = ReadableStreamTee(this); - return CreateArrayFromList(branches); +async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredSignature || binarySignature; + if (!input) { + throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`'); + } + if (armoredSignature && !util.isString(armoredSignature)) { + throw new Error('readSignature: options.armoredSignature must be a string'); + } + if (binarySignature && !util.isUint8Array(binarySignature)) { + throw new Error('readSignature: options.binarySignature must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + + if (armoredSignature) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.signature) { + throw new Error('Armored text not of type signature'); } - values(rawOptions = undefined) { - if (!IsReadableStream(this)) { - throw streamBrandCheckException$1('values'); - } - const options = convertIteratorOptions(rawOptions, 'First parameter'); - return AcquireReadableStreamAsyncIterator(this, options.preventCancel); - } -} -Object.defineProperties(ReadableStream$1.prototype, { - cancel: { enumerable: true }, - getReader: { enumerable: true }, - pipeThrough: { enumerable: true }, - pipeTo: { enumerable: true }, - tee: { enumerable: true }, - values: { enumerable: true }, - locked: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'ReadableStream', - configurable: true - }); + input = data; + } + const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1); + return new Signature(packetlist); } -if (typeof SymbolPolyfill.asyncIterator === 'symbol') { - Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, { - value: ReadableStream$1.prototype.values, - writable: true, - configurable: true - }); + +/** + * @fileoverview Provides helpers methods for key module + * @module key/helper + */ + + +async function generateSecretSubkey(options, config) { + const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config); + secretSubkeyPacket.packets = null; + secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretSubkeyPacket.generate(options.rsaBits, options.curve); + await secretSubkeyPacket.computeFingerprintAndKeyID(); + return secretSubkeyPacket; } -// Abstract operations for the ReadableStream. -// Throws if and only if startAlgorithm throws. -function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { - const stream = Object.create(ReadableStream$1.prototype); - InitializeReadableStream(stream); - const controller = Object.create(ReadableStreamDefaultController.prototype); - SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); - return stream; -} -function InitializeReadableStream(stream) { - stream._state = 'readable'; - stream._reader = undefined; - stream._storedError = undefined; - stream._disturbed = false; -} -function IsReadableStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { - return false; - } - return true; + +async function generateSecretKey(options, config) { + const secretKeyPacket = new SecretKeyPacket(options.date, config); + secretKeyPacket.packets = null; + secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm); + await secretKeyPacket.generate(options.rsaBits, options.curve, options.config); + await secretKeyPacket.computeFingerprintAndKeyID(); + return secretKeyPacket; } -function IsReadableStreamLocked(stream) { - if (stream._reader === undefined) { - return false; + +/** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param {Array} signatures - List of signatures + * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature + * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures, + * `enums.signatures.certGeneric` should be given regardless of the actual trust level) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - full configuration + * @returns {Promise} The latest valid signature. + * @async + */ +async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) { + let latestValid; + let exception; + for (let i = signatures.length - 1; i >= 0; i--) { + try { + if ( + (!latestValid || signatures[i].created >= latestValid.created) + ) { + await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config); + latestValid = signatures[i]; + } + } catch (e) { + exception = e; } - return true; + } + if (!latestValid) { + throw util.wrapError( + `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}` + .replace('certGeneric ', 'self-') + .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), + exception); + } + return latestValid; } -// ReadableStream API exposed for controllers. -function ReadableStreamCancel(stream, reason) { - stream._disturbed = true; - if (stream._state === 'closed') { - return promiseResolvedWith(undefined); - } - if (stream._state === 'errored') { - return promiseRejectedWith(stream._storedError); - } - ReadableStreamClose(stream); - const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); - return transformPromiseWith(sourceCancelPromise, noop); + +function isDataExpired(keyPacket, signature, date = new Date()) { + const normDate = util.normalizeDate(date); + if (normDate !== null) { + const expirationTime = getKeyExpirationTime(keyPacket, signature); + return !(keyPacket.created <= normDate && normDate < expirationTime); + } + return false; } -function ReadableStreamClose(stream) { - stream._state = 'closed'; - const reader = stream._reader; - if (reader === undefined) { - return; - } - defaultReaderClosedPromiseResolve(reader); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._closeSteps(); - }); - reader._readRequests = new SimpleQueue(); - } + +/** + * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1} + * @param {SecretSubkeyPacket} subkey - Subkey key packet + * @param {SecretKeyPacket} primaryKey - Primary key packet + * @param {Object} options + * @param {Object} config - Full configuration + */ +async function createBindingSignature(subkey, primaryKey, options, config) { + const dataToSign = {}; + dataToSign.key = primaryKey; + dataToSign.bind = subkey; + const signatureProperties = { signatureType: enums.signature.subkeyBinding }; + if (options.sign) { + signatureProperties.keyFlags = [enums.keyFlags.signData]; + signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, { + signatureType: enums.signature.keyBinding + }, options.date, undefined, undefined, undefined, config); + } else { + signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage]; + } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; + } + const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config); + return subkeySignaturePacket; } -function ReadableStreamError(stream, e) { - stream._state = 'errored'; - stream._storedError = e; - const reader = stream._reader; - if (reader === undefined) { - return; + +/** + * Returns the preferred signature hash algorithm for a set of keys. + * @param {Array} [targetKeys] - The keys to get preferences from + * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from + * @param {Object} config - full configuration + * @returns {Promise} + * @async + */ +async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) { + /** + * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the + * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys). + * if no keys are available, `preferredSenderAlgo` is returned. + * For ECC signing key, the curve preferred hash is taken into account as well (see logic below). + */ + const defaultAlgo = enums.hash.sha256; // MUST implement + const preferredSenderAlgo = config.preferredHashAlgorithm; + + const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => { + const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config); + const targetPrefs = selfCertification.preferredHashAlgorithms; + return targetPrefs; + })); + const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys + for (const supportedAlgos of supportedAlgosPerTarget) { + for (const hashAlgo of supportedAlgos) { + try { + // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on + const supportedAlgo = enums.write(enums.hash, hashAlgo); + supportedAlgosMap.set( + supportedAlgo, + supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1 + ); + } catch {} } - defaultReaderClosedPromiseReject(reader, e); - if (IsReadableStreamDefaultReader(reader)) { - reader._readRequests.forEach(readRequest => { - readRequest._errorSteps(e); - }); - reader._readRequests = new SimpleQueue(); + } + const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo; + const getStrongestSupportedHashAlgo = () => { + if (supportedAlgosMap.size === 0) { + return defaultAlgo; } - else { - reader._readIntoRequests.forEach(readIntoRequest => { - readIntoRequest._errorSteps(e); - }); - reader._readIntoRequests = new SimpleQueue(); + const sortedHashAlgos = Array.from(supportedAlgosMap.keys()) + .filter(hashAlgo => isSupportedHashAlgo(hashAlgo)) + .sort((algoA, algoB) => mod$1.hash.getHashByteLength(algoA) - mod$1.hash.getHashByteLength(algoB)); + const strongestHashAlgo = sortedHashAlgos[0]; + // defaultAlgo is always implicilty supported, and might be stronger than the rest + return mod$1.hash.getHashByteLength(strongestHashAlgo) >= mod$1.hash.getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo; + }; + + const eccAlgos = new Set([ + enums.publicKey.ecdsa, + enums.publicKey.eddsaLegacy, + enums.publicKey.ed25519, + enums.publicKey.ed448 + ]); + + if (eccAlgos.has(signingKeyPacket.algorithm)) { + // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see: + // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5 + // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3 + // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4 + // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4 + // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough; + // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve + // preferred algo, even if not supported by all targets. + const preferredCurveAlgo = mod$1.getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid); + + const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo); + const preferredSenderAlgoStrongerThanCurveAlgo = mod$1.hash.getHashByteLength(preferredSenderAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo); + + if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) { + return preferredSenderAlgo; + } else { + const strongestSupportedAlgo = getStrongestSupportedHashAlgo(); + return mod$1.hash.getHashByteLength(strongestSupportedAlgo) >= mod$1.hash.getHashByteLength(preferredCurveAlgo) ? + strongestSupportedAlgo : + preferredCurveAlgo; } -} -// Helper functions for the ReadableStream. -function streamBrandCheckException$1(name) { - return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); -} + } -function convertQueuingStrategyInit(init, context) { - assertDictionary(init, context); - const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; - assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); - return { - highWaterMark: convertUnrestrictedDouble(highWaterMark) - }; + // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this, + // since it was manually set by the sender. + return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo(); } -const byteLengthSizeFunction = function size(chunk) { - return chunk.byteLength; -}; /** - * A queuing strategy that counts the number of bytes in each chunk. - * - * @public + * Returns the preferred compression algorithm for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Preferred compression algorithm + * @async */ -class ByteLengthQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('highWaterMark'); - } - return this._byteLengthQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by returning the value of its `byteLength` property. - */ - get size() { - if (!IsByteLengthQueuingStrategy(this)) { - throw byteLengthBrandCheckException('size'); - } - return byteLengthSizeFunction; - } -} -Object.defineProperties(ByteLengthQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'ByteLengthQueuingStrategy', - configurable: true - }); -} -// Helper functions for the ByteLengthQueuingStrategy. -function byteLengthBrandCheckException(name) { - return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); -} -function IsByteLengthQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { - return false; - } - return true; +async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const defaultAlgo = enums.compression.uncompressed; + const preferredSenderAlgo = config$1.preferredCompressionAlgorithm; + + // if preferredSenderAlgo appears in the prefs of all recipients, we pick it + // otherwise we use the default algo + // if no keys are available, preferredSenderAlgo is returned + const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) { + const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1); + const recipientPrefs = selfCertification.preferredCompressionAlgorithms; + return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0; + })); + return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo; } -const countSizeFunction = function size() { - return 1; -}; /** - * A queuing strategy that counts the number of chunks. - * - * @public + * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys + * @param {Array} [keys] - Set of keys + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Array} [userIDs] - User IDs + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred + * @async */ -class CountQueuingStrategy { - constructor(options) { - assertRequiredArgument(options, 1, 'CountQueuingStrategy'); - options = convertQueuingStrategyInit(options, 'First parameter'); - this._countQueuingStrategyHighWaterMark = options.highWaterMark; - } - /** - * Returns the high water mark provided to the constructor. - */ - get highWaterMark() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('highWaterMark'); - } - return this._countQueuingStrategyHighWaterMark; - } - /** - * Measures the size of `chunk` by always returning 1. - * This ensures that the total queue size is a count of the number of chunks in the queue. - */ - get size() { - if (!IsCountQueuingStrategy(this)) { - throw countBrandCheckException('size'); - } - return countSizeFunction; - } -} -Object.defineProperties(CountQueuingStrategy.prototype, { - highWaterMark: { enumerable: true }, - size: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { - value: 'CountQueuingStrategy', - configurable: true - }); -} -// Helper functions for the CountQueuingStrategy. -function countBrandCheckException(name) { - return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); -} -function IsCountQueuingStrategy(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { - return false; +async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) { + const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1))); + const withAEAD = keys.length ? + selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) : + config$1.aeadProtect; + + if (withAEAD) { + const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb }; + const desiredCipherSuites = [ + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm }, + { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb }, + { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm } + ]; + for (const desiredCipherSuite of desiredCipherSuites) { + if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some( + cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo + ))) { + return desiredCipherSuite; + } } - return true; + return defaultCipherSuite; + } + const defaultSymAlgo = enums.symmetric.aes128; + const desiredSymAlgo = config$1.preferredSymmetricAlgorithm; + return { + symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ? + desiredSymAlgo : + defaultSymAlgo, + aeadAlgo: undefined + }; } -function convertTransformer(original, context) { - assertDictionary(original, context); - const flush = original === null || original === void 0 ? void 0 : original.flush; - const readableType = original === null || original === void 0 ? void 0 : original.readableType; - const start = original === null || original === void 0 ? void 0 : original.start; - const transform = original === null || original === void 0 ? void 0 : original.transform; - const writableType = original === null || original === void 0 ? void 0 : original.writableType; - return { - flush: flush === undefined ? - undefined : - convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), - readableType, - start: start === undefined ? - undefined : - convertTransformerStartCallback(start, original, `${context} has member 'start' that`), - transform: transform === undefined ? - undefined : - convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), - writableType - }; -} -function convertTransformerFlushCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => promiseCall(fn, original, [controller]); -} -function convertTransformerStartCallback(fn, original, context) { - assertFunction(fn, context); - return (controller) => reflectCall(fn, original, [controller]); -} -function convertTransformerTransformCallback(fn, original, context) { - assertFunction(fn, context); - return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +/** + * Create signature packet + * @param {Object} dataToSign - Contains packets to be signed + * @param {Array} recipientKeys - keys to get preferences from + * @param {SecretKeyPacket| + * SecretSubkeyPacket} signingKeyPacket secret key packet for signing + * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing + * @param {Date} [date] - Override the creationtime of the signature + * @param {Object} [userID] - User ID + * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [detached] - Whether to create a detached signature packet + * @param {Object} config - full configuration + * @returns {Promise} Signature packet. + */ +async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) { + if (signingKeyPacket.isDummy()) { + throw new Error('Cannot sign with a gnu-dummy key.'); + } + if (!signingKeyPacket.isDecrypted()) { + throw new Error('Signing key is not decrypted.'); + } + const signaturePacket = new SignaturePacket(); + Object.assign(signaturePacket, signatureProperties); + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config); + signaturePacket.rawNotations = [...notations]; + await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config); + return signaturePacket; } -// Class TransformStream /** - * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, - * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. - * In a manner specific to the transform stream in question, writes to the writable side result in new data being - * made available for reading from the readable side. - * - * @public + * Merges signatures from source[attr] to dest[attr] + * @param {Object} source + * @param {Object} dest + * @param {String} attr + * @param {Date} [date] - date to use for signature expiration check, instead of the current time + * @param {Function} [checkFn] - signature only merged if true */ -class TransformStream$1 { - constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { - if (rawTransformer === undefined) { - rawTransformer = null; - } - const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); - const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); - const transformer = convertTransformer(rawTransformer, 'First parameter'); - if (transformer.readableType !== undefined) { - throw new RangeError('Invalid readableType specified'); - } - if (transformer.writableType !== undefined) { - throw new RangeError('Invalid writableType specified'); - } - const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); - const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); - const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); - const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); - let startPromise_resolve; - const startPromise = newPromise(resolve => { - startPromise_resolve = resolve; - }); - InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); - if (transformer.start !== undefined) { - startPromise_resolve(transformer.start(this._transformStreamController)); - } - else { - startPromise_resolve(undefined); - } - } - /** - * The readable side of the transform stream. - */ - get readable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('readable'); - } - return this._readable; - } - /** - * The writable side of the transform stream. - */ - get writable() { - if (!IsTransformStream(this)) { - throw streamBrandCheckException('writable'); +async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) { + source = source[attr]; + if (source) { + if (!dest[attr].length) { + dest[attr] = source; + } else { + await Promise.all(source.map(async function(sourceSig) { + if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) && + !dest[attr].some(function(destSig) { + return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams()); + })) { + dest[attr].push(sourceSig); } - return this._writable; - } -} -Object.defineProperties(TransformStream$1.prototype, { - readable: { enumerable: true }, - writable: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStream', - configurable: true - }); -} -function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { - function startAlgorithm() { - return startPromise; - } - function writeAlgorithm(chunk) { - return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); - } - function abortAlgorithm(reason) { - return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); - } - function closeAlgorithm() { - return TransformStreamDefaultSinkCloseAlgorithm(stream); - } - stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); - function pullAlgorithm() { - return TransformStreamDefaultSourcePullAlgorithm(stream); - } - function cancelAlgorithm(reason) { - TransformStreamErrorWritableAndUnblockWrite(stream, reason); - return promiseResolvedWith(undefined); - } - stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); - // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. - stream._backpressure = undefined; - stream._backpressureChangePromise = undefined; - stream._backpressureChangePromise_resolve = undefined; - TransformStreamSetBackpressure(stream, true); - stream._transformStreamController = undefined; -} -function IsTransformStream(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { - return false; - } - return true; -} -// This is a no-op if both sides are already errored. -function TransformStreamError(stream, e) { - ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); - TransformStreamErrorWritableAndUnblockWrite(stream, e); -} -function TransformStreamErrorWritableAndUnblockWrite(stream, e) { - TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); - WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); - if (stream._backpressure) { - // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() - // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time - // _backpressure is set. - TransformStreamSetBackpressure(stream, false); - } -} -function TransformStreamSetBackpressure(stream, backpressure) { - // Passes also when called during construction. - if (stream._backpressureChangePromise !== undefined) { - stream._backpressureChangePromise_resolve(); + })); } - stream._backpressureChangePromise = newPromise(resolve => { - stream._backpressureChangePromise_resolve = resolve; - }); - stream._backpressure = backpressure; + } } -// Class TransformStreamDefaultController + /** - * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. - * - * @public + * Checks if a given certificate or binding signature is revoked + * @param {SecretKeyPacket| + * PublicKeyPacket} primaryKey The primary key packet + * @param {Object} dataToVerify - The data to check + * @param {Array} revocations - The revocation signatures to check + * @param {SignaturePacket} signature - The certificate or signature to check + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the signature revokes the data. + * @async */ -class TransformStreamDefaultController { - constructor() { - throw new TypeError('Illegal constructor'); - } - /** - * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. - */ - get desiredSize() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('desiredSize'); - } - const readableController = this._controlledTransformStream._readable._readableStreamController; - return ReadableStreamDefaultControllerGetDesiredSize(readableController); - } - enqueue(chunk = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('enqueue'); - } - TransformStreamDefaultControllerEnqueue(this, chunk); - } - /** - * Errors both the readable side and the writable side of the controlled transform stream, making all future - * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. - */ - error(reason = undefined) { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('error'); - } - TransformStreamDefaultControllerError(this, reason); - } - /** - * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the - * transformer only needs to consume a portion of the chunks written to the writable side. - */ - terminate() { - if (!IsTransformStreamDefaultController(this)) { - throw defaultControllerBrandCheckException('terminate'); - } - TransformStreamDefaultControllerTerminate(this); - } -} -Object.defineProperties(TransformStreamDefaultController.prototype, { - enqueue: { enumerable: true }, - error: { enumerable: true }, - terminate: { enumerable: true }, - desiredSize: { enumerable: true } -}); -if (typeof SymbolPolyfill.toStringTag === 'symbol') { - Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { - value: 'TransformStreamDefaultController', - configurable: true - }); -} -// Transform Stream Default Controller Abstract Operations -function IsTransformStreamDefaultController(x) { - if (!typeIsObject(x)) { - return false; - } - if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { - return false; - } - return true; -} -function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { - controller._controlledTransformStream = stream; - stream._transformStreamController = controller; - controller._transformAlgorithm = transformAlgorithm; - controller._flushAlgorithm = flushAlgorithm; -} -function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { - const controller = Object.create(TransformStreamDefaultController.prototype); - let transformAlgorithm = (chunk) => { - try { - TransformStreamDefaultControllerEnqueue(controller, chunk); - return promiseResolvedWith(undefined); - } - catch (transformResultE) { - return promiseRejectedWith(transformResultE); - } - }; - let flushAlgorithm = () => promiseResolvedWith(undefined); - if (transformer.transform !== undefined) { - transformAlgorithm = chunk => transformer.transform(chunk, controller); - } - if (transformer.flush !== undefined) { - flushAlgorithm = () => transformer.flush(controller); - } - SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); -} -function TransformStreamDefaultControllerClearAlgorithms(controller) { - controller._transformAlgorithm = undefined; - controller._flushAlgorithm = undefined; -} -function TransformStreamDefaultControllerEnqueue(controller, chunk) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { - throw new TypeError('Readable side is not in a state that permits enqueue'); - } - // We throttle transform invocations based on the backpressure of the ReadableStream, but we still - // accept TransformStreamDefaultControllerEnqueue() calls. +async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) { + key = key || primaryKey; + const revocationKeyIDs = []; + await Promise.all(revocations.map(async function(revocationSignature) { try { - ReadableStreamDefaultControllerEnqueue(readableController, chunk); - } - catch (e) { - // This happens when readableStrategy.size() throws. - TransformStreamErrorWritableAndUnblockWrite(stream, e); - throw stream._readable._storedError; - } - const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); - if (backpressure !== stream._backpressure) { - TransformStreamSetBackpressure(stream, true); - } -} -function TransformStreamDefaultControllerError(controller, e) { - TransformStreamError(controller._controlledTransformStream, e); -} -function TransformStreamDefaultControllerPerformTransform(controller, chunk) { - const transformPromise = controller._transformAlgorithm(chunk); - return transformPromiseWith(transformPromise, undefined, r => { - TransformStreamError(controller._controlledTransformStream, r); - throw r; - }); -} -function TransformStreamDefaultControllerTerminate(controller) { - const stream = controller._controlledTransformStream; - const readableController = stream._readable._readableStreamController; - ReadableStreamDefaultControllerClose(readableController); - const error = new TypeError('TransformStream terminated'); - TransformStreamErrorWritableAndUnblockWrite(stream, error); -} -// TransformStreamDefaultSink Algorithms -function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { - const controller = stream._transformStreamController; - if (stream._backpressure) { - const backpressureChangePromise = stream._backpressureChangePromise; - return transformPromiseWith(backpressureChangePromise, () => { - const writable = stream._writable; - const state = writable._state; - if (state === 'erroring') { - throw writable._storedError; - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); - }); - } - return TransformStreamDefaultControllerPerformTransform(controller, chunk); -} -function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { - // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already - // errored. - TransformStreamError(stream, reason); - return promiseResolvedWith(undefined); -} -function TransformStreamDefaultSinkCloseAlgorithm(stream) { - // stream._readable cannot change after construction, so caching it across a call to user code is safe. - const readable = stream._readable; - const controller = stream._transformStreamController; - const flushPromise = controller._flushAlgorithm(); - TransformStreamDefaultControllerClearAlgorithms(controller); - // Return a promise that is fulfilled with undefined on success. - return transformPromiseWith(flushPromise, () => { - if (readable._state === 'errored') { - throw readable._storedError; - } - ReadableStreamDefaultControllerClose(readable._readableStreamController); - }, r => { - TransformStreamError(stream, r); - throw readable._storedError; - }); -} -// TransformStreamDefaultSource Algorithms -function TransformStreamDefaultSourcePullAlgorithm(stream) { - // Invariant. Enforced by the promises returned by start() and pull(). - TransformStreamSetBackpressure(stream, false); - // Prevent the next pull() call until there is backpressure. - return stream._backpressureChangePromise; -} -// Helper functions for the TransformStreamDefaultController. -function defaultControllerBrandCheckException(name) { - return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + if ( + // Note: a third-party revocation signature could legitimately revoke a + // self-signature if the signature has an authorized revocation key. + // However, we don't support passing authorized revocation keys, nor + // verifying such revocation signatures. Instead, we indicate an error + // when parsing a key with an authorized revocation key, and ignore + // third-party revocation signatures here. (It could also be revoking a + // third-party key certification, which should only affect + // `verifyAllCertifications`.) + !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID) + ) { + const isHardRevocation = ![ + enums.reasonForRevocation.keyRetired, + enums.reasonForRevocation.keySuperseded, + enums.reasonForRevocation.userIDInvalid + ].includes(revocationSignature.reasonForRevocationFlag); + + await revocationSignature.verify( + key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config + ); + + // TODO get an identifier of the revoked object instead + revocationKeyIDs.push(revocationSignature.issuerKeyID); + } + } catch (e) {} + })); + // TODO further verify that this is the signature that should be revoked + if (signature) { + signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true : + signature.revoked || false; + return signature.revoked; + } + return revocationKeyIDs.length > 0; } -// Helper functions for the TransformStream. -function streamBrandCheckException(name) { - return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + +/** + * Returns key expiration time based on the given certification signature. + * The expiration time of the signature is ignored. + * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check + * @param {SignaturePacket} signature - signature to process + * @returns {Date|Infinity} expiration time or infinity if the key does not expire + */ +function getKeyExpirationTime(keyPacket, signature) { + let expirationTime; + // check V4 expiration time + if (signature.keyNeverExpires === false) { + expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000; + } + return expirationTime ? new Date(expirationTime) : Infinity; } -var ponyfill_es6 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, - CountQueuingStrategy: CountQueuingStrategy, - ReadableByteStreamController: ReadableByteStreamController, - ReadableStream: ReadableStream$1, - ReadableStreamBYOBReader: ReadableStreamBYOBReader, - ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, - ReadableStreamDefaultController: ReadableStreamDefaultController, - ReadableStreamDefaultReader: ReadableStreamDefaultReader, - TransformStream: TransformStream$1, - TransformStreamDefaultController: TransformStreamDefaultController, - WritableStream: WritableStream$1, - WritableStreamDefaultController: WritableStreamDefaultController, - WritableStreamDefaultWriter: WritableStreamDefaultWriter -}); +function sanitizeKeyOptions(options, subkeyDefaults = {}) { + options.type = options.type || subkeyDefaults.type; + options.curve = options.curve || subkeyDefaults.curve; + options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits; + options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; + options.sign = options.sign || false; -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + switch (options.type) { + case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve` + try { + options.curve = enums.write(enums.curve, options.curve); + } catch (e) { + throw new Error('Unknown curve'); + } + if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy || + options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now + options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy; + } + if (options.sign) { + options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa; + } else { + options.algorithm = enums.publicKey.ecdh; + } + break; + case 'curve25519': + options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519; + break; + case 'curve448': + options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448; + break; + case 'rsa': + options.algorithm = enums.publicKey.rsaEncryptSign; + break; + default: + throw new Error(`Unsupported key type ${options.type}`); + } + return options; } -function assert$1(test) { - if (!test) { - throw new TypeError('Assertion failed'); - } +function validateSigningKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ed25519: + case enums.publicKey.ed448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + default: + return false; + } } -function noop$1() { - return; -} -function typeIsObject$1(x) { - return (typeof x === 'object' && x !== null) || typeof x === 'function'; +function validateEncryptionKeyPacket(keyPacket, signature, config) { + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; + default: + return false; + } } -function isStreamConstructor(ctor) { - if (typeof ctor !== 'function') { - return false; - } - var startCalled = false; - try { - new ctor({ - start: function () { - startCalled = true; - } - }); - } - catch (e) { - // ignore - } - return startCalled; -} -function isReadableStream(readable) { - if (!typeIsObject$1(readable)) { - return false; - } - if (typeof readable.getReader !== 'function') { - return false; - } - return true; -} -function isReadableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isReadableStream(new ctor())) { - return false; - } - return true; -} -function isWritableStream(writable) { - if (!typeIsObject$1(writable)) { - return false; - } - if (typeof writable.getWriter !== 'function') { - return false; - } - return true; -} -function isWritableStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isWritableStream(new ctor())) { - return false; - } - return true; -} -function isTransformStream(transform) { - if (!typeIsObject$1(transform)) { - return false; - } - if (!isReadableStream(transform.readable)) { - return false; - } - if (!isWritableStream(transform.writable)) { - return false; - } - return true; -} -function isTransformStreamConstructor(ctor) { - if (!isStreamConstructor(ctor)) { - return false; - } - if (!isTransformStream(new ctor())) { - return false; - } - return true; -} -function supportsByobReader(readable) { - try { - var reader = readable.getReader({ mode: 'byob' }); - reader.releaseLock(); - return true; - } - catch (_a) { - return false; - } -} -function supportsByteSource(ctor) { - try { - new ctor({ type: 'bytes' }); +function validateDecryptionKeyPacket(keyPacket, signature, config) { + if (!signature.keyFlags && !config.allowMissingKeyFlags) { + throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`'); + } + + switch (keyPacket.algorithm) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaEncrypt: + case enums.publicKey.elgamal: + case enums.publicKey.ecdh: + case enums.publicKey.x25519: + case enums.publicKey.x448: { + const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0; + if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) { + // This is only relevant for RSA keys, all other signing algorithms cannot decrypt return true; - } - catch (_a) { - return false; - } -} + } -function createReadableStreamWrapper(ctor) { - assert$1(isReadableStreamConstructor(ctor)); - var byteSourceSupported = supportsByteSource(ctor); - return function (readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - type = parseReadableType(type); - if (type === 'bytes' && !byteSourceSupported) { - type = undefined; - } - if (readable.constructor === ctor) { - if (type !== 'bytes' || supportsByobReader(readable)) { - return readable; - } - } - if (type === 'bytes') { - var source = createWrappingReadableSource(readable, { type: type }); - return new ctor(source); - } - else { - var source = createWrappingReadableSource(readable); - return new ctor(source); - } - }; -} -function createWrappingReadableSource(readable, _a) { - var _b = _a === void 0 ? {} : _a, type = _b.type; - assert$1(isReadableStream(readable)); - assert$1(readable.locked === false); - type = parseReadableType(type); - var source; - if (type === 'bytes') { - source = new WrappingReadableByteStreamSource(readable); - } - else { - source = new WrappingReadableStreamDefaultSource(readable); - } - return source; -} -function parseReadableType(type) { - var typeString = String(type); - if (typeString === 'bytes') { - return typeString; - } - else if (type === undefined) { - return type; - } - else { - throw new RangeError('Invalid type is specified'); - } -} -var AbstractWrappingReadableStreamSource = /** @class */ (function () { - function AbstractWrappingReadableStreamSource(underlyingStream) { - this._underlyingReader = undefined; - this._readerMode = undefined; - this._readableStreamController = undefined; - this._pendingRead = undefined; - this._underlyingStream = underlyingStream; - // always keep a reader attached to detect close/error - this._attachDefaultReader(); - } - AbstractWrappingReadableStreamSource.prototype.start = function (controller) { - this._readableStreamController = controller; - }; - AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) { - assert$1(this._underlyingReader !== undefined); - return this._underlyingReader.cancel(reason); - }; - AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () { - if (this._readerMode === "default" /* DEFAULT */) { - return; - } - this._detachReader(); - var reader = this._underlyingStream.getReader(); - this._readerMode = "default" /* DEFAULT */; - this._attachReader(reader); - }; - AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) { - var _this = this; - assert$1(this._underlyingReader === undefined); - this._underlyingReader = reader; - var closed = this._underlyingReader.closed; - if (!closed) { - return; - } - closed - .then(function () { return _this._finishPendingRead(); }) - .then(function () { - if (reader === _this._underlyingReader) { - _this._readableStreamController.close(); - } - }, function (reason) { - if (reader === _this._underlyingReader) { - _this._readableStreamController.error(reason); - } - }) - .catch(noop$1); - }; - AbstractWrappingReadableStreamSource.prototype._detachReader = function () { - if (this._underlyingReader === undefined) { - return; - } - this._underlyingReader.releaseLock(); - this._underlyingReader = undefined; - this._readerMode = undefined; - }; - AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () { - var _this = this; - this._attachDefaultReader(); - // TODO Backpressure? - var read = this._underlyingReader.read() - .then(function (result) { - var controller = _this._readableStreamController; - if (result.done) { - _this._tryClose(); - } - else { - controller.enqueue(result.value); - } - }); - this._setPendingRead(read); - return read; - }; - AbstractWrappingReadableStreamSource.prototype._tryClose = function () { - try { - this._readableStreamController.close(); - } - catch (_a) { - // already errored or closed - } - }; - AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) { - var _this = this; - var pendingRead; - var finishRead = function () { - if (_this._pendingRead === pendingRead) { - _this._pendingRead = undefined; - } - }; - this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead); - }; - AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () { - var _this = this; - if (!this._pendingRead) { - return undefined; - } - var afterRead = function () { return _this._finishPendingRead(); }; - return this._pendingRead.then(afterRead, afterRead); - }; - return AbstractWrappingReadableStreamSource; -}()); -var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) { - __extends(WrappingReadableStreamDefaultSource, _super); - function WrappingReadableStreamDefaultSource() { - return _super !== null && _super.apply(this, arguments) || this; + return !signature.keyFlags || + (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 || + (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0; } - WrappingReadableStreamDefaultSource.prototype.pull = function () { - return this._pullWithDefaultReader(); - }; - return WrappingReadableStreamDefaultSource; -}(AbstractWrappingReadableStreamSource)); -function toUint8Array(view) { - return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); -} -function copyArrayBufferView(from, to) { - var fromArray = toUint8Array(from); - var toArray = toUint8Array(to); - toArray.set(fromArray, 0); -} -var WrappingReadableByteStreamSource = /** @class */ (function (_super) { - __extends(WrappingReadableByteStreamSource, _super); - function WrappingReadableByteStreamSource(underlyingStream) { - var _this = this; - var supportsByob = supportsByobReader(underlyingStream); - _this = _super.call(this, underlyingStream) || this; - _this._supportsByob = supportsByob; - return _this; - } - Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", { - get: function () { - return 'bytes'; - }, - enumerable: false, - configurable: true - }); - WrappingReadableByteStreamSource.prototype._attachByobReader = function () { - if (this._readerMode === "byob" /* BYOB */) { - return; - } - assert$1(this._supportsByob); - this._detachReader(); - var reader = this._underlyingStream.getReader({ mode: 'byob' }); - this._readerMode = "byob" /* BYOB */; - this._attachReader(reader); - }; - WrappingReadableByteStreamSource.prototype.pull = function () { - if (this._supportsByob) { - var byobRequest = this._readableStreamController.byobRequest; - if (byobRequest) { - return this._pullWithByobRequest(byobRequest); - } - } - return this._pullWithDefaultReader(); - }; - WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) { - var _this = this; - this._attachByobReader(); - // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly - // create a separate buffer to read into, then copy that to byobRequest.view - var buffer = new Uint8Array(byobRequest.view.byteLength); - // TODO Backpressure? - var read = this._underlyingReader.read(buffer) - .then(function (result) { - _this._readableStreamController; - if (result.done) { - _this._tryClose(); - byobRequest.respond(0); - } - else { - copyArrayBufferView(result.value, byobRequest.view); - byobRequest.respond(result.value.byteLength); - } - }); - this._setPendingRead(read); - return read; - }; - return WrappingReadableByteStreamSource; -}(AbstractWrappingReadableStreamSource)); - -function createWritableStreamWrapper(ctor) { - assert$1(isWritableStreamConstructor(ctor)); - return function (writable) { - if (writable.constructor === ctor) { - return writable; - } - var sink = createWrappingWritableSink(writable); - return new ctor(sink); - }; + default: + return false; + } } -function createWrappingWritableSink(writable) { - assert$1(isWritableStream(writable)); - assert$1(writable.locked === false); - var writer = writable.getWriter(); - return new WrappingWritableStreamSink(writer); -} -var WrappingWritableStreamSink = /** @class */ (function () { - function WrappingWritableStreamSink(underlyingWriter) { - var _this = this; - this._writableStreamController = undefined; - this._pendingWrite = undefined; - this._state = "writable" /* WRITABLE */; - this._storedError = undefined; - this._underlyingWriter = underlyingWriter; - this._errorPromise = new Promise(function (resolve, reject) { - _this._errorPromiseReject = reject; - }); - this._errorPromise.catch(noop$1); - } - WrappingWritableStreamSink.prototype.start = function (controller) { - var _this = this; - this._writableStreamController = controller; - this._underlyingWriter.closed - .then(function () { - _this._state = "closed" /* CLOSED */; - }) - .catch(function (reason) { return _this._finishErroring(reason); }); - }; - WrappingWritableStreamSink.prototype.write = function (chunk) { - var _this = this; - var writer = this._underlyingWriter; - // Detect past errors - if (writer.desiredSize === null) { - return writer.ready; - } - var writeRequest = writer.write(chunk); - // Detect future errors - writeRequest.catch(function (reason) { return _this._finishErroring(reason); }); - writer.ready.catch(function (reason) { return _this._startErroring(reason); }); - // Reject write when errored - var write = Promise.race([writeRequest, this._errorPromise]); - this._setPendingWrite(write); - return write; - }; - WrappingWritableStreamSink.prototype.close = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return this._underlyingWriter.close(); - } - return this._finishPendingWrite().then(function () { return _this.close(); }); - }; - WrappingWritableStreamSink.prototype.abort = function (reason) { - if (this._state === "errored" /* ERRORED */) { - return undefined; - } - var writer = this._underlyingWriter; - return writer.abort(reason); - }; - WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) { - var _this = this; - var pendingWrite; - var finishWrite = function () { - if (_this._pendingWrite === pendingWrite) { - _this._pendingWrite = undefined; - } - }; - this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite); - }; - WrappingWritableStreamSink.prototype._finishPendingWrite = function () { - var _this = this; - if (this._pendingWrite === undefined) { - return Promise.resolve(); - } - var afterWrite = function () { return _this._finishPendingWrite(); }; - return this._pendingWrite.then(afterWrite, afterWrite); - }; - WrappingWritableStreamSink.prototype._startErroring = function (reason) { - var _this = this; - if (this._state === "writable" /* WRITABLE */) { - this._state = "erroring" /* ERRORING */; - this._storedError = reason; - var afterWrite = function () { return _this._finishErroring(reason); }; - if (this._pendingWrite === undefined) { - afterWrite(); - } - else { - this._finishPendingWrite().then(afterWrite, afterWrite); - } - this._writableStreamController.error(reason); - } - }; - WrappingWritableStreamSink.prototype._finishErroring = function (reason) { - if (this._state === "writable" /* WRITABLE */) { - this._startErroring(reason); - } - if (this._state === "erroring" /* ERRORING */) { - this._state = "errored" /* ERRORED */; - this._errorPromiseReject(this._storedError); - } - }; - return WrappingWritableStreamSink; -}()); -function createTransformStreamWrapper(ctor) { - assert$1(isTransformStreamConstructor(ctor)); - return function (transform) { - if (transform.constructor === ctor) { - return transform; - } - var transformer = createWrappingTransformer(transform); - return new ctor(transformer); - }; -} -function createWrappingTransformer(transform) { - assert$1(isTransformStream(transform)); - var readable = transform.readable, writable = transform.writable; - assert$1(readable.locked === false); - assert$1(writable.locked === false); - var reader = readable.getReader(); - var writer; - try { - writer = writable.getWriter(); - } - catch (e) { - reader.releaseLock(); // do not leak reader - throw e; - } - return new WrappingTransformStreamTransformer(reader, writer); +/** + * Check key against blacklisted algorithms and minimum strength requirements. + * @param {SecretKeyPacket|PublicKeyPacket| + * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket + * @param {Config} config + * @throws {Error} if the key packet does not meet the requirements + */ +function checkKeyRequirements(keyPacket, config) { + const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm); + const algoInfo = keyPacket.getAlgorithmInfo(); + if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) { + throw new Error(`${algoInfo.algorithm} keys are considered too weak.`); + } + switch (keyAlgo) { + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.rsaEncrypt: + if (algoInfo.bits < config.minRSABits) { + throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`); + } + break; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + case enums.publicKey.ecdh: + if (config.rejectCurves.has(algoInfo.curve)) { + throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`); + } + break; + } } -var WrappingTransformStreamTransformer = /** @class */ (function () { - function WrappingTransformStreamTransformer(reader, writer) { - var _this = this; - this._transformStreamController = undefined; - this._onRead = function (result) { - if (result.done) { - return; - } - _this._transformStreamController.enqueue(result.value); - return _this._reader.read().then(_this._onRead); - }; - this._onError = function (reason) { - _this._flushReject(reason); - _this._transformStreamController.error(reason); - _this._reader.cancel(reason).catch(noop$1); - _this._writer.abort(reason).catch(noop$1); - }; - this._onTerminate = function () { - _this._flushResolve(); - _this._transformStreamController.terminate(); - var error = new TypeError('TransformStream terminated'); - _this._writer.abort(error).catch(noop$1); - }; - this._reader = reader; - this._writer = writer; - this._flushPromise = new Promise(function (resolve, reject) { - _this._flushResolve = resolve; - _this._flushReject = reject; - }); - } - WrappingTransformStreamTransformer.prototype.start = function (controller) { - this._transformStreamController = controller; - this._reader.read() - .then(this._onRead) - .then(this._onTerminate, this._onError); - var readerClosed = this._reader.closed; - if (readerClosed) { - readerClosed - .then(this._onTerminate, this._onError); - } - }; - WrappingTransformStreamTransformer.prototype.transform = function (chunk) { - return this._writer.write(chunk); - }; - WrappingTransformStreamTransformer.prototype.flush = function () { - var _this = this; - return this._writer.close() - .then(function () { return _this._flushPromise; }); - }; - return WrappingTransformStreamTransformer; -}()); -var webStreamsAdapter = /*#__PURE__*/Object.freeze({ - __proto__: null, - createReadableStreamWrapper: createReadableStreamWrapper, - createTransformStreamWrapper: createTransformStreamWrapper, - createWrappingReadableSource: createWrappingReadableSource, - createWrappingTransformer: createWrappingTransformer, - createWrappingWritableSink: createWrappingWritableSink, - createWritableStreamWrapper: createWritableStreamWrapper -}); +/** + * @module key/User + */ -var bn = createCommonjsModule(function (module) { -(function (module, exports) { - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); +/** + * Class that represents an user ID or attribute packet and the relevant signatures. + * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info + * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with + */ +class User { + constructor(userPacket, mainKey) { + this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null; + this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null; + this.selfCertifications = []; + this.otherCertifications = []; + this.revocationSignatures = []; + this.mainKey = mainKey; } - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; + /** + * Transforms structured user data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.userID || this.userAttribute); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.selfCertifications); + packetlist.push(...this.otherCertifications); + return packetlist; } - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; + /** + * Shallow clone + * @returns {User} + */ + clone() { + const user = new User(this.userID || this.userAttribute, this.mainKey); + user.selfCertifications = [...this.selfCertifications]; + user.otherCertifications = [...this.otherCertifications]; + user.revocationSignatures = [...this.revocationSignatures]; + return user; + } - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; + /** + * Generate third-party certifications over this user and its primary key + * @param {Array} signingKeys - Decrypted private keys for signing + * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} New user with new certifications. + * @async + */ + async certify(signingKeys, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) { + if (!privateKey.isPrivate()) { + throw new Error('Need private key for signing'); } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; + if (privateKey.hasSameFingerprintAs(primaryKey)) { + throw new Error("The user's own key can only be used for self-certifications"); + } + const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config); + return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, { + // Most OpenPGP implementations use generic certification (0x10) + signatureType: enums.signature.certGeneric, + keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData] + }, date, undefined, undefined, undefined, config); + })); + await user.update(this, date, config); + return user; } - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = void('buffer').Buffer; - } catch (e) { + /** + * Checks if a given certificate of the user is revoked + * @param {SignaturePacket} certificate - The certificate to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked(primaryKey, enums.signature.certRevocation, { + key: primaryKey, + userID: this.userID, + userAttribute: this.userAttribute + }, this.revocationSignatures, certificate, keyPacket, date, config$1); } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; + /** + * Verifies the user certificate. + * @param {SignaturePacket} certificate - A certificate of this user + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate + * @throws if the user certificate is invalid. + * @async + */ + async verifyCertificate(certificate, verificationKeys, date = new Date(), config) { + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const { issuerKeyID } = certificate; + const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0); + if (issuerKeys.length === 0) { + return null; } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } + await Promise.all(issuerKeys.map(async key => { + const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config); + if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) { + throw new Error('User certificate is revoked'); } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } + try { + await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('User certificate is invalid', e); } - } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; + })); + return true; + } - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; + /** + * Verifies all user certificates + * @param {Array} verificationKeys - Array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllCertifications(verificationKeys, date = new Date(), config) { + const that = this; + const certifications = this.selfCertifications.concat(this.otherCertifications); + return Promise.all(certifications.map(async certification => ({ + keyID: certification.issuerKeyID, + valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false) + }))); } - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} config - Full configuration + * @returns {Promise} Status of user. + * @throws {Error} if there are no valid self signatures. + * @async + */ + async verify(date = new Date(), config) { + if (!this.selfCertifications.length) { + throw new Error('No self-certifications found'); + } + const that = this; + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // TODO replace when Promise.some or Promise.any are implemented + let exception; + for (let i = this.selfCertifications.length - 1; i >= 0; i--) { + try { + const selfCertification = this.selfCertifications[i]; + if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) { + throw new Error('Self-certification is revoked'); + } + try { + await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config); + } catch (e) { + throw util.wrapError('Self-certification is invalid', e); + } + return true; + } catch (e) { + exception = e; } } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + throw exception; + } - // '0' - '9' - } else { - r += c; + /** + * Update user with new components from specified user + * @param {User} sourceUser - Source user to merge + * @param {Date} date - Date to verify the validity of signatures + * @param {Object} config - Full configuration + * @returns {Promise} + * @async + */ + async update(sourceUser, date, config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + // self signatures + await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) { + try { + await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config); + return true; + } catch (e) { + return false; } - } - return r; + }); + // other signatures + await mergeSignatures(sourceUser, this, 'otherCertifications', date); + // revocation signatures + await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config); + }); } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + /** + * Revokes the user + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New user with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { + userID: this.userID, + userAttribute: this.userAttribute, + key: primaryKey + }; + const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey); + user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.certRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await user.update(this); + return user; + } +} - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +/** + * @module key/Subkey + */ - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } +/** + * Class that represents a subkey packet and the relevant signatures. + * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID + * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint + * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs + * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo + * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime + * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted + */ +class Subkey { + /** + * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey + * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey + */ + constructor(subkeyPacket, mainKey) { + this.keyPacket = subkeyPacket; + this.bindingSignatures = []; + this.revocationSignatures = []; + this.mainKey = mainKey; + } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + /** + * Transforms structured subkey data to packetlist + * @returns {PacketList} + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.bindingSignatures); + return packetlist; + } - for (i = 0; i < mod; i++) { - pow *= base; - } + /** + * Shallow clone + * @return {Subkey} + */ + clone() { + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.bindingSignatures = [...this.bindingSignatures]; + subkey.revocationSignatures = [...this.revocationSignatures]; + return subkey; + } - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; + /** + * Checks if a binding signature of a subkey is revoked + * @param {SignaturePacket} signature - The binding signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the binding signature is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + return isDataRevoked( + primaryKey, enums.signature.subkeyRevocation, { + key: primaryKey, + bind: this.keyPacket + }, this.revocationSignatures, signature, key, date, config$1 + ); + } - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @throws {Error} if the subkey is invalid. + * @async + */ + async verify(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + // check subkey binding signatures + const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + // check binding signature is not revoked + if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) { + throw new Error('Subkey is revoked'); } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; + // check for expiration time + if (isDataExpired(this.keyPacket, bindingSignature, date)) { + throw new Error('Subkey is expired'); } - return this; - }; + return bindingSignature; + } - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; + /** + * Returns the expiration time of the subkey or Infinity if key does not expire. + * Returns null if the subkey is invalid. + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + const dataToVerify = { key: primaryKey, bind: this.keyPacket }; + let bindingSignature; + try { + bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + } catch (e) { + return null; } - return this._normSign(); - }; + const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature); + const sigExpiry = bindingSignature.getExpirationTime(); + return keyExpiry < sigExpiry ? keyExpiry : sigExpiry; + } - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; + /** + * Update subkey with new components from specified subkey + * @param {Subkey} subkey - Source subkey to merge + * @param {Date} [date] - Date to verify validity of signatures + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if update failed + * @async + */ + async update(subkey, date = new Date(), config$1 = config) { + const primaryKey = this.mainKey.keyPacket; + if (!this.hasSameFingerprintAs(subkey)) { + throw new Error('Subkey update method: fingerprints of subkeys not equal'); } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; + // key packet + if (this.keyPacket.constructor.tag === enums.packet.publicSubkey && + subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) { + this.keyPacket = subkey.keyPacket; } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; + // update missing binding signatures + const that = this; + const dataToVerify = { key: primaryKey, bind: that.keyPacket }; + await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) { + for (let i = 0; i < that.bindingSignatures.length; i++) { + if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) { + if (srcBindSig.created > that.bindingSignatures[i].created) { + that.bindingSignatures[i] = srcBindSig; + } + return false; + } } - if (this.negative !== 0) { - out = '-' + out; + try { + await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1); + return true; + } catch (e) { + return false; } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; + }); + // revocation signatures + await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) { + return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1); + }); + } - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; + /** + * Revokes the subkey + * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New subkey with revocation signature. + * @async + */ + async revoke( + primaryKey, + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + const dataToSign = { key: primaryKey, bind: this.keyPacket }; + const subkey = new Subkey(this.keyPacket, this.mainKey); + subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, { + signatureType: enums.signature.subkeyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, false, config$1)); + await subkey.update(this); + return subkey; + } - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + hasSameFingerprintAs(other) { + return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other); + } +} - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => { + Subkey.prototype[name] = + function() { + return this.keyPacket[name](); + }; +}); - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +// A key revocation certificate can contain the following packets +const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); +const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]); +const keyPacketTags = new Set([ + enums.packet.publicKey, enums.packet.privateKey, + enums.packet.publicSubkey, enums.packet.privateSubkey +]); - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +/** + * Abstract class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + * @borrows PublicKeyPacket#getKeyID as Key#getKeyID + * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint + * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs + * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo + * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime + */ +class Key { + /** + * Transforms packetlist to structured key data + * @param {PacketList} packetlist - The packets that form a key + * @param {Set} disallowedPackets - disallowed packet tags + */ + packetListToStructure(packetlist, disallowedPackets = new Set()) { + let user; + let primaryKeyID; + let subkey; + let ignoreUntil; - res[i] = b; - } + for (const packet of packetlist) { - for (; i < reqLength; i++) { - res[i] = 0; + if (packet instanceof UnparseablePacket) { + const isUnparseableKeyPacket = keyPacketTags.has(packet.tag); + if (isUnparseableKeyPacket && !ignoreUntil) { + // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must + // discard all non-key packets that follow, until another (sub)key packet is found. + if (mainKeyPacketTags.has(packet.tag)) { + ignoreUntil = mainKeyPacketTags; + } else { + ignoreUntil = keyPacketTags; + } + } + continue; } - } - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; + const tag = packet.constructor.tag; + if (ignoreUntil) { + if (!ignoreUntil.has(tag)) continue; + ignoreUntil = null; } - if (t >= 0x8) { - r += 4; - t >>>= 4; + if (disallowedPackets.has(tag)) { + throw new Error(`Unexpected packet type: ${tag}`); } - if (t >= 0x02) { - r += 2; - t >>>= 2; + switch (tag) { + case enums.packet.publicKey: + case enums.packet.secretKey: + if (this.keyPacket) { + throw new Error('Key block contains multiple keys'); + } + this.keyPacket = packet; + primaryKeyID = this.getKeyID(); + if (!primaryKeyID) { + throw new Error('Missing Key ID'); + } + break; + case enums.packet.userID: + case enums.packet.userAttribute: + user = new User(packet, this); + this.users.push(user); + break; + case enums.packet.publicSubkey: + case enums.packet.secretSubkey: + user = null; + subkey = new Subkey(packet, this); + this.subkeys.push(subkey); + break; + case enums.packet.signature: + switch (packet.signatureType) { + case enums.signature.certGeneric: + case enums.signature.certPersona: + case enums.signature.certCasual: + case enums.signature.certPositive: + if (!user) { + util.printDebug('Dropping certification signatures without preceding user packet'); + continue; + } + if (packet.issuerKeyID.equals(primaryKeyID)) { + user.selfCertifications.push(packet); + } else { + user.otherCertifications.push(packet); + } + break; + case enums.signature.certRevocation: + if (user) { + user.revocationSignatures.push(packet); + } else { + this.directSignatures.push(packet); + } + break; + case enums.signature.key: + this.directSignatures.push(packet); + break; + case enums.signature.subkeyBinding: + if (!subkey) { + util.printDebug('Dropping subkey binding signature without preceding subkey packet'); + continue; + } + subkey.bindingSignatures.push(packet); + break; + case enums.signature.keyRevocation: + this.revocationSignatures.push(packet); + break; + case enums.signature.subkeyRevocation: + if (!subkey) { + util.printDebug('Dropping subkey revocation signature without preceding subkey packet'); + continue; + } + subkey.revocationSignatures.push(packet); + break; + } + break; } - return r + t; - }; + } } - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + /** + * Transforms structured key data to packetlist + * @returns {PacketList} The packets that form a key. + */ + toPacketList() { + const packetlist = new PacketList(); + packetlist.push(this.keyPacket); + packetlist.push(...this.revocationSignatures); + packetlist.push(...this.directSignatures); + this.users.map(user => packetlist.push(...user.toPacketList())); + this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList())); + return packetlist; + } - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + /** + * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent. + * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key. + * @returns {Promise} Clone of the key. + */ + clone(clonePrivateParams = false) { + const key = new this.constructor(this.toPacketList()); + if (clonePrivateParams) { + key.getKeys().forEach(k => { + // shallow clone the key packets + k.keyPacket = Object.create( + Object.getPrototypeOf(k.keyPacket), + Object.getOwnPropertyDescriptors(k.keyPacket) + ); + if (!k.keyPacket.isDecrypted()) return; + // deep clone the private params, which are cleared during encryption + const privateParams = {}; + Object.keys(k.keyPacket.privateParams).forEach(name => { + privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]); + }); + k.keyPacket.privateParams = privateParams; + }); } - if ((t & 0x1) === 0) { - r++; + return key; + } + + /** + * Returns an array containing all public or private subkeys matching keyID; + * If no keyID is given, returns all subkeys. + * @param {type/keyID} [keyID] - key ID to look for + * @returns {Array} array of subkeys + */ + getSubkeys(keyID = null) { + const subkeys = this.subkeys.filter(subkey => ( + !keyID || subkey.getKeyID().equals(keyID, true) + )); + return subkeys; + } + + /** + * Returns an array containing all public or private keys matching keyID. + * If no keyID is given, returns all keys, starting with the primary key. + * @param {type/keyid~KeyID} [keyID] - key ID to look for + * @returns {Array} array of keys + */ + getKeys(keyID = null) { + const keys = []; + if (!keyID || this.getKeyID().equals(keyID, true)) { + keys.push(this); } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + return keys.concat(this.getSubkeys(keyID)); + } - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + /** + * Returns key IDs of all keys + * @returns {Array} + */ + getKeyIDs() { + return this.getKeys().map(key => key.getKeyID()); + } - return w; + /** + * Returns userIDs + * @returns {Array} Array of userIDs. + */ + getUserIDs() { + return this.users.map(user => { + return user.userID ? user.userID.userID : null; + }).filter(userID => userID !== null); } - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + /** + * Returns binary encoded key + * @returns {Uint8Array} Binary key. + */ + write() { + return this.toPacketList().write(); + } - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; + /** + * Returns last created key or key by given keyID that is available for signing and verification + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} signing key + * @throws if no valid signing key was found + * @async + */ + async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature( + subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1 + ); + if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + continue; + } + if (!bindingSignature.embeddedSignature) { + throw new Error('Missing embedded signature'); + } + // verify embedded signature + await getLatestValidSignature( + [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1 + ); + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } catch (e) { + exception = e; + } + } } - return this.clone(); - }; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + try { + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateSigningKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception); + } - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; + /** + * Returns last created key or key by given keyID that is available for encryption or decryption + * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve + * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date + * @param {Object} [userID] - filter keys for the given user ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} encryption key + * @throws if no valid encryption key was found + * @async + */ + async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) { + await this.verifyPrimaryKey(date, userID, config$1); + const primaryKey = this.keyPacket; + try { + checkKeyRequirements(primaryKey, config$1); + } catch (err) { + throw util.wrapError('Could not verify primary key', err); } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; + // V4: by convention subkeys are preferred for encryption service + const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created); + let exception; + for (const subkey of subkeys) { + if (!keyID || subkey.getKeyID().equals(keyID)) { + try { + await subkey.verify(date, config$1); + const dataToVerify = { key: primaryKey, bind: subkey.keyPacket }; + const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) { + checkKeyRequirements(subkey.keyPacket, config$1); + return subkey; + } + } catch (e) { + exception = e; + } + } } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + try { + // if no valid subkey for encryption, evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID)) && + validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) { + checkKeyRequirements(primaryKey, config$1); + return this; + } + } catch (e) { + exception = e; } + throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception); + } - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + /** + * Checks if a signature on a key is revoked + * @param {SignaturePacket} signature - The signature to verify + * @param {PublicSubkeyPacket| + * SecretSubkeyPacket| + * PublicKeyPacket| + * SecretKeyPacket} key, optional The key to verify the signature + * @param {Date} [date] - Use the given date for verification, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} True if the certificate is revoked. + * @async + */ + async isRevoked(signature, key, date = new Date(), config$1 = config) { + return isDataRevoked( + this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1 + ); + } - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature. Throws if the primary key is invalid. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} If key verification failed + * @async + */ + async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + // check for key revocation signatures + if (await this.isRevoked(null, null, date, config$1)) { + throw new Error('Primary key is revoked'); } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + // check for valid, unrevoked, unexpired self signature + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + // check for expiration time in binding signatures + if (isDataExpired(primaryKey, selfCertification, date)) { + throw new Error('Primary key is expired'); } + if (primaryKey.version !== 6) { + // check for expiration time in direct signatures (for V6 keys, the above already did so) + const directSignature = await getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + if (directSignature && isDataExpired(primaryKey, directSignature, date)) { + throw new Error('Primary key is expired'); + } + } + } - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; + /** + * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures. + * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid. + * @param {Object} [userID] - User ID to consider instead of the primary user + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} + * @async + */ + async getExpirationTime(userID, config$1 = config) { + let primaryKeyExpiry; + try { + const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1); + const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification); + const selfSigExpiry = selfCertification.getExpirationTime(); + const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature. + await getLatestValidSignature( + this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1 + ).catch(() => {}); + if (directSignature) { + const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature); + // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration, + // causing a discountinous validy period for the key + primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry); + } else { + primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry; + } + } catch (e) { + primaryKeyExpiry = null; + } - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + return util.normalizeDate(primaryKeyExpiry); + } - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + /** + * For V4 keys, returns the self-signature of the primary user. + * For V5 keys, returns the latest valid direct-key self-signature. + * This self-signature is to be used to check the key expiration, + * algorithm preferences, and so on. + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} The primary self-signature + * @async + */ + async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + if (primaryKey.version === 6) { + return getLatestValidSignature( + this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1 + ); } + const { selfCertification } = await this.getPrimaryUser(date, userID, config$1); + return selfCertification; + } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * user: User, + * selfCertification: SignaturePacket + * }>} The primary user and the self signature + * @async + */ + async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const users = []; + let exception; + for (let i = 0; i < this.users.length; i++) { + try { + const user = this.users[i]; + if (!user.userID) { + continue; + } + if ( + (userID.name !== undefined && user.userID.name !== userID.name) || + (userID.email !== undefined && user.userID.email !== userID.email) || + (userID.comment !== undefined && user.userID.comment !== userID.comment) + ) { + throw new Error('Could not find user that matches that user ID'); + } + const dataToVerify = { userID: user.userID, key: primaryKey }; + const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1); + users.push({ index: i, user, selfCertification }); + } catch (e) { + exception = e; } } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; + if (!users.length) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('Could not find primary user'); } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + await Promise.all(users.map(async function (a) { + return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1); + })); + // sort by primary user flag and signature creation time + const primaryUser = users.sort(function(a, b) { + const A = a.selfCertification; + const B = b.selfCertification; + return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created; + }).pop(); + const { user, selfCertification: cert } = primaryUser; + if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) { + throw new Error('Primary user is revoked'); } + return primaryUser; + } - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * + * If the source key is a private key and the destination key is public, + * a private key is returned. + * @param {Key} sourceKey - Source key to merge + * @param {Date} [date] - Date to verify validity of signatures and keys + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} updated key + * @async + */ + async update(sourceKey, date = new Date(), config$1 = config) { + if (!this.hasSameFingerprintAs(sourceKey)) { + throw new Error('Primary key fingerprints must be equal to update the key'); } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (!this.isPrivate() && sourceKey.isPrivate()) { + // check for equal subkey packets + const equal = (this.subkeys.length === sourceKey.subkeys.length) && + (this.subkeys.every(destSubkey => { + return sourceKey.subkeys.some(srcSubkey => { + return destSubkey.hasSameFingerprintAs(srcSubkey); + }); + })); + if (!equal) { + throw new Error('Cannot update public key with private key if subkeys mismatch'); } - } - - return this; - }; - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; + return sourceKey.update(this, config$1); } + // from here on, either: + // - destination key is private, source key is public + // - the keys are of the same type + // hence we don't need to convert the destination key type + const updatedKey = this.clone(); + // revocation signatures + await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => { + return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1); + }); + // direct signatures + await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date); + // update users + await Promise.all(sourceKey.users.map(async srcUser => { + // multiple users with the same ID/attribute are not explicitly disallowed by the spec + // hence we support them, just in case + const usersToUpdate = updatedKey.users.filter(dstUser => ( + (srcUser.userID && srcUser.userID.equals(dstUser.userID)) || + (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) + )); + if (usersToUpdate.length > 0) { + await Promise.all( + usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)) + ); + } else { + const newUser = srcUser.clone(); + newUser.mainKey = updatedKey; + updatedKey.users.push(newUser); + } + })); + // update subkeys + await Promise.all(sourceKey.subkeys.map(async srcSubkey => { + // multiple subkeys with same fingerprint might be preset + const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => ( + dstSubkey.hasSameFingerprintAs(srcSubkey) + )); + if (subkeysToUpdate.length > 0) { + await Promise.all( + subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)) + ); + } else { + const newSubkey = srcSubkey.clone(); + newSubkey.mainKey = updatedKey; + updatedKey.subkeys.push(newSubkey); + } + })); - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; + return updatedKey; + } - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @param {Date} date - Use the given date instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Armored revocation certificate. + * @async + */ + async getRevocationCertificate(date = new Date(), config$1 = config) { + const dataToVerify = { key: this.keyPacket }; + const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1); + const packetlist = new PacketList(); + packetlist.push(revocationSignature); + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1); + } - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param {String} revocationCertificate - armored revocation certificate + * @param {Date} [date] - Date to verify the certificate + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Revoked key. + * @async + */ + async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) { + const input = await unarmor(revocationCertificate); + const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1); + const revocationSignature = packetlist.findPacket(enums.packet.signature); + if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) { + throw new Error('Could not find revocation signature packet'); } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) { + throw new Error('Revocation signature does not match key'); } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + try { + await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1); + } catch (e) { + throw util.wrapError('Could not verify revocation signature', e); } + const key = this.clone(); + key.revocationSignatures.push(revocationSignature); + return key; + } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + /** + * Signs primary user of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signPrimaryUser(privateKeys, date, userID, config$1 = config) { + const { index, user } = await this.getPrimaryUser(date, userID, config$1); + const userSign = await user.certify(privateKeys, date, config$1); + const key = this.clone(); + key.users[index] = userSign; + return key; + } + + /** + * Signs all users of key + * @param {Array} privateKeys - decrypted private keys for signing + * @param {Date} [date] - Use the given date for signing, instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} Key with new certificate signature. + * @async + */ + async signAllUsers(privateKeys, date = new Date(), config$1 = config) { + const key = this.clone(); + key.users = await Promise.all(this.users.map(function(user) { + return user.certify(privateKeys, date, config$1); + })); + return key; + } + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [userID] - User ID to get instead of the primary user, if it exists + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) { + const primaryKey = this.keyPacket; + const { user } = await this.getPrimaryUser(date, userID, config$1); + const results = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; + return results; + } - this.length = Math.max(this.length, i); + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param {Array} [verificationKeys] - array of keys to verify certificate signatures + * @param {Date} [date] - Use the given date for verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} List of userID, signer's keyID and validity of signature. + * Signature validity is null if the verification keys do not correspond to the certificate. + * @async + */ + async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) { + const primaryKey = this.keyPacket; + const results = []; + await Promise.all(this.users.map(async user => { + const signatures = verificationKeys ? + await user.verifyAllCertifications(verificationKeys, date, config$1) : + [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }]; - if (a !== this) { - this.negative = 1; - } + results.push(...signatures.map( + signature => ({ + userID: user.userID ? user.userID.userID : null, + userAttribute: user.userAttribute, + keyID: signature.keyID, + valid: signature.valid + })) + ); + })); + return results; + } +} - return this.strip(); - }; +['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => { + Key.prototype[name] = + Subkey.prototype[name]; +}); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; +/** + * Class that represents an OpenPGP Public Key + */ +class PublicKey extends Key { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.keyPacket = null; + this.revocationSignatures = []; + this.directSignatures = []; + this.users = []; + this.subkeys = []; + if (packetlist) { + this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing public-key packet'); } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; } - - return out.strip(); } - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); + /** + * Returns true if this is a private key + * @returns {false} + */ + isPrivate() { + return false; } - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + return this; } - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } +} - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; +/** + * Class that represents an OpenPGP Private key + */ +class PrivateKey extends PublicKey { + /** + * @param {PacketList} packetlist - The packets that form this key + */ + constructor(packetlist) { + super(); + this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey])); + if (!this.keyPacket) { + throw new Error('Invalid key: missing private-key packet'); } + } - return rb; - }; + /** + * Returns true if this is a private key + * @returns {Boolean} + */ + isPrivate() { + return true; + } - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; + /** + * Returns key as public key (shallow copy) + * @returns {PublicKey} New public Key + */ + toPublic() { + const packetlist = new PacketList(); + const keyPackets = this.toPacketList(); + for (const keyPacket of keyPackets) { + switch (keyPacket.constructor.tag) { + case enums.packet.secretKey: { + const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket); + packetlist.push(pubKeyPacket); + break; + } + case enums.packet.secretSubkey: { + const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket); + packetlist.push(pubSubkeyPacket); + break; + } + default: + packetlist.push(keyPacket); + } } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + return new PublicKey(packetlist); + } - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + /** + * Returns ASCII armored text of key + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer. + const emitChecksum = this.keyPacket.version !== 6; + return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1); + } - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + /** + * Returns all keys that are available for decryption, matching the keyID when given + * This is useful to retrieve keys for session key decryption + * @param {module:type/keyid~KeyID} keyID, optional + * @param {Date} date, optional + * @param {String} userID, optional + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} Array of decryption keys. + * @throws {Error} if no decryption key is found + * @async + */ + async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) { + const primaryKey = this.keyPacket; + const keys = []; + let exception = null; + for (let i = 0; i < this.subkeys.length; i++) { + if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) { + if (this.subkeys[i].keyPacket.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); + continue; + } - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; + try { + const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket }; + const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1); + if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) { + keys.push(this.subkeys[i]); } + } catch (e) { + exception = e; } } } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; + // evaluate primary key + const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1); + if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) { + if (primaryKey.isDummy()) { + exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption'); } else { - carry = w / 0x4000000 | 0; + keys.push(this); } } - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; + if (keys.length === 0) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw exception || new Error('No decryption key packets found'); } - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; + return keys; + } - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + /** + * Returns true if the primary key or any subkey is decrypted. + * A dummy key is considered encrypted. + */ + isDecrypted() { + return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted()); + } - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; + /** + * Check whether the private and public primary key parameters correspond + * Together with verification of binding signatures, this guarantees key integrity + * In case of gnu-dummy primary key, it is enough to validate any signing subkeys + * otherwise all encryption subkeys are validated + * If only gnu-dummy keys are found, we cannot properly validate so we throw an error + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @throws {Error} if validation was not successful and the key cannot be trusted + * @async + */ + async validate(config$1 = config) { + if (!this.isPrivate()) { + throw new Error('Cannot validate a public key'); } - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); + let signingKeyPacket; + if (!this.keyPacket.isDummy()) { + signingKeyPacket = this.keyPacket; + } else { + /** + * It is enough to validate any signing keys + * since its binding signatures are also checked + */ + const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 }); + // This could again be a dummy key + if (signingKey && !signingKey.keyPacket.isDummy()) { + signingKeyPacket = signingKey.keyPacket; } } - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); + if (signingKeyPacket) { + return signingKeyPacket.validate(); + } else { + const keys = this.getKeys(); + const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean); + if (allDummies) { + throw new Error('Cannot validate an all-gnu-dummy key'); } - if (carry) { - this.words[i] = carry; - this.length++; - } + return Promise.all(keys.map(async key => key.keyPacket.validate())); } + } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; + /** + * Clear private key parameters + */ + clearPrivateParams() { + this.getKeys().forEach(({ keyPacket }) => { + if (keyPacket.isDecrypted()) { + keyPacket.clearPrivateParams(); } + }); + } - this.length += s; + /** + * Revokes the key + * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation + * @param {Date} date - optional, override the creationtime of the revocation signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New key with revocation signature. + * @async + */ + async revoke( + { + flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, + string: reasonForRevocationString = '' + } = {}, + date = new Date(), + config$1 = config + ) { + if (!this.isPrivate()) { + throw new Error('Need private key for revoking'); } + const dataToSign = { key: this.keyPacket }; + const key = this.clone(); + key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag), + reasonForRevocationString + }, date, undefined, undefined, undefined, config$1)); + return key; + } - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; + /** + * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added. + * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519. + * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys. + * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format). + * Note: Curve448 and Curve25519 are not widely supported yet. + * @param {String} options.curve (optional) Elliptic curve for ECC keys + * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date (optional) Override the creation date of the key and the key signatures + * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false + * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} + * @async + */ + async addSubkey(options = {}) { + const config$1 = { ...config, ...options.config }; + if (options.passphrase) { + throw new Error('Subkey could not be encrypted here, please encrypt whole key'); } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; + if (options.rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`); } - - if (s === 0) ; else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; + const secretKeyPacket = this.keyPacket; + if (secretKeyPacket.isDummy()) { + throw new Error('Cannot add subkey to gnu-dummy primary key'); } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; + if (!secretKeyPacket.isDecrypted()) { + throw new Error('Key is not decrypted'); } + const defaultOptions = secretKeyPacket.getAlgorithmInfo(); + defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm); + defaultOptions.rsaBits = defaultOptions.bits || 4096; + defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy'; + options = sanitizeKeyOptions(options, defaultOptions); + // Every subkey for a v4 primary key MUST be a v4 subkey. + // Every subkey for a v6 primary key MUST be a v6 subkey. + // For v5 keys, since we dropped generation support, a v4 subkey is added. + // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user. + const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 }); + checkKeyRequirements(keyPacket, config$1); + const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1); + const packetList = this.toPacketList(); + packetList.push(keyPacket, bindingSignature); + return new PrivateKey(packetList); + } +} - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } +function getDefaultSubkeyType(algoName) { + const algo = enums.write(enums.publicKey, algoName); + // NB: no encryption-only algos, since they cannot be in primary keys + switch (algo) { + case enums.publicKey.rsaEncrypt: + case enums.publicKey.rsaEncryptSign: + case enums.publicKey.rsaSign: + case enums.publicKey.dsa: + return 'rsa'; + case enums.publicKey.ecdsa: + case enums.publicKey.eddsaLegacy: + return 'ecc'; + case enums.publicKey.ed25519: + return 'curve25519'; + case enums.publicKey.ed448: + return 'curve448'; + default: + throw new Error('Unsupported algorithm'); + } +} - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - return this.strip(); - }; - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; +// A Key can contain the following packets +const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([ + PublicKeyPacket, + PublicSubkeyPacket, + SecretKeyPacket, + SecretSubkeyPacket, + UserIDPacket, + UserAttributePacket, + SignaturePacket +]); - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; +/** + * Creates a PublicKey or PrivateKey depending on the packetlist in input + * @param {PacketList} - packets to parse + * @return {Key} parsed key + * @throws if no key packet was found + */ +function createKey(packetlist) { + for (const packet of packetlist) { + switch (packet.constructor.tag) { + case enums.packet.secretKey: + return new PrivateKey(packetlist); + case enums.packet.publicKey: + return new PublicKey(packetlist); + } + } + throw new Error('No key packet found'); +} - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; +/** + * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * @param {ecc|rsa|curve448|curve25519} options.type The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format). + * @param {String} options.curve Elliptic curve for ECC keys + * @param {Integer} options.rsaBits Number of bits for RSA keys + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Creation date of the key and the key signatures + * @param {Object} config - Full configuration + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function generate(options, config) { + options.sign = true; // primary key is always a signing key + options = sanitizeKeyOptions(options); + options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options)); + let promises = [generateSecretKey(options, config)]; + promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config))); + const packets = await Promise.all(promises); - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; + const key = await wrapKeyObject(packets[0], packets.slice(1), options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; +} - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; +/** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param {PrivateKey} options.privateKey The private key to reformat + * @param {Array} options.userIDs User IDs as strings or objects: 'Jo Doe ' or { name:'Jo Doe', email:'info@jo.com' } + * @param {String} options.passphrase Passphrase used to encrypt the resulting private key + * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires + * @param {Date} options.date Override the creation date of the key signatures + * @param {Array} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * @param {Object} config - Full configuration + * + * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>} + * @async + * @static + * @private + */ +async function reformat(options, config) { + options = sanitize(options); + const { privateKey } = options; - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; + if (!privateKey.isPrivate()) { + throw new Error('Cannot reformat a public key'); + } - // Check bit and return - var w = this.words[s]; + if (privateKey.keyPacket.isDummy()) { + throw new Error('Cannot reformat a gnu-dummy primary key'); + } - return !!(w & q); - }; + const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted()); + if (!isDecrypted) { + throw new Error('Key is not decrypted'); + } - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + const secretKeyPacket = privateKey.keyPacket; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + if (!options.subkeys) { + options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => { + const secretSubkeyPacket = subkey.keyPacket; + const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket }; + const bindingSignature = await ( + getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config) + ).catch(() => ({})); + return { + sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData) + }; + })); + } - if (this.length <= s) { - return this; - } + const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket); + if (options.subkeys.length !== secretSubkeyPackets.length) { + throw new Error('Number of subkey options does not match number of subkeys'); + } - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); + options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options)); - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config); + const revocationCertificate = await key.getRevocationCertificate(options.date, config); + key.revocationSignatures = []; + return { key, revocationCertificate }; - return this.strip(); - }; + function sanitize(options, subkeyDefaults = {}) { + options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime; + options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase; + options.date = options.date || subkeyDefaults.date; - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + return options; + } +} - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } +/** + * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection + * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked. + * @param {SecretKeyPacket} secretKeyPacket + * @param {SecretSubkeyPacket} secretSubkeyPackets + * @param {Object} options + * @param {Object} config - Full configuration + * @returns {PrivateKey} + */ +async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) { + // set passphrase protection + if (options.passphrase) { + await secretKeyPacket.encrypt(options.passphrase, config); + } - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + await secretSubkeyPacket.encrypt(subkeyPassphrase, config); } + })); - // Add without checks - return this._iaddn(num); - }; + const packetlist = new PacketList(); + packetlist.push(secretKeyPacket); - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + function createPreferredAlgos(algos, preferredAlgo) { + return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)]; + } - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } + function getKeySignatureProperties() { + const signatureProperties = {}; + signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData]; + const symmetricAlgorithms = createPreferredAlgos([ + // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + enums.symmetric.aes256, + enums.symmetric.aes128 + ], config.preferredSymmetricAlgorithm); + signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms; + if (config.aeadProtect) { + const aeadAlgorithms = createPreferredAlgos([ + enums.aead.gcm, + enums.aead.eax, + enums.aead.ocb + ], config.preferredAEADAlgorithm); + signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => { + return symmetricAlgorithms.map(symmetricAlgorithm => { + return [symmetricAlgorithm, aeadAlgorithm]; + }); + }); } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; + signatureProperties.preferredHashAlgorithms = createPreferredAlgos([ + // prefer fast asm.js implementations (SHA-256) + enums.hash.sha256, + enums.hash.sha512, + enums.hash.sha3_256, + enums.hash.sha3_512 + ], config.preferredHashAlgorithm); + signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([ + enums.compression.uncompressed, + enums.compression.zlib, + enums.compression.zip + ], config.preferredCompressionAlgorithm); + // integrity protection always enabled + signatureProperties.features = [0]; + signatureProperties.features[0] |= enums.features.modificationDetection; + if (config.aeadProtect) { + signatureProperties.features[0] |= enums.features.seipdv2; } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } + if (options.keyExpirationTime > 0) { + signatureProperties.keyExpirationTime = options.keyExpirationTime; + signatureProperties.keyNeverExpires = false; } + return signatureProperties; + } - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + if (secretKeyPacket.version === 6) { // add direct key signature with key prefs + const dataToSign = { + key: secretKeyPacket + }; - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + const signatureProperties = getKeySignatureProperties(); + signatureProperties.signatureType = enums.signature.key; - this._expand(len); + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); + packetlist.push(signaturePacket); + } - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; + await Promise.all(options.userIDs.map(async function(userID, index) { + const userIDPacket = UserIDPacket.fromObject(userID); + const dataToSign = { + userID: userIDPacket, + key: secretKeyPacket + }; + const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {}; + signatureProperties.signatureType = enums.signature.certPositive; + if (index === 0) { + signatureProperties.isPrimaryUserID = true; } - if (carry === 0) return this.strip(); + const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config); - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; + return { userIDPacket, signaturePacket }; + })).then(list => { + list.forEach(({ userIDPacket, signaturePacket }) => { + packetlist.push(userIDPacket); + packetlist.push(signaturePacket); + }); + }); - return this.strip(); - }; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyOptions = options.subkeys[index]; + const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config); + return { secretSubkeyPacket, subkeySignaturePacket }; + })).then(packets => { + packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => { + packetlist.push(secretSubkeyPacket); + packetlist.push(subkeySignaturePacket); + }); + }); - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; + // Add revocation signature packet for creating a revocation certificate. + // This packet should be removed before returning the key. + const dataToSign = { key: secretKeyPacket }; + packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, { + signatureType: enums.signature.keyRevocation, + reasonForRevocationFlag: enums.reasonForRevocation.noReason, + reasonForRevocationString: '' + }, options.date, undefined, undefined, undefined, config)); - var a = this.clone(); - var b = num; + if (options.passphrase) { + secretKeyPacket.clearPrivateParams(); + } - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; + await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) { + const subkeyPassphrase = options.subkeys[index].passphrase; + if (subkeyPassphrase) { + secretSubkeyPacket.clearPrivateParams(); } + })); - // Initialize quotient - var m = a.length - b.length; - var q; + return new PrivateKey(packetlist); +} - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } +/** + * Reads an (optionally armored) OpenPGP key and returns a key object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) { + throw new Error('Armored text not of type key'); } + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]); + return createKey(firstKeyPacketList); +} - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); +/** + * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object + * @param {Object} options + * @param {String} [options.armoredKey] - Armored key to be parsed + * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Key object. + * @async + * @static + */ +async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!armoredKey && !binaryKey) { + throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`'); + } + if (armoredKey && !util.isString(armoredKey)) { + throw new Error('readPrivateKey: options.armoredKey must be a string'); + } + if (binaryKey && !util.isUint8Array(binaryKey)) { + throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); + let input; + if (armoredKey) { + const { type, data } = await unarmor(armoredKey); + if (!(type === enums.armor.privateKey)) { + throw new Error('Armored text not of type private key'); } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); + input = data; + } else { + input = binaryKey; + } + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; } + const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + return new PrivateKey(firstPrivateKeyList); + } + throw new Error('No secret key packet found'); +} - return { - div: q || null, - mod: a - }; - }; +/** + * Reads an (optionally armored) OpenPGP key block and returns a list of key objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readKeys: options.binaryKeys must be a Uint8Array'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) { + throw new Error('Armored text not of type key'); + } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + if (keyIndex.length === 0) { + throw new Error('No key packet found'); + } + for (let i = 0; i < keyIndex.length; i++) { + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = createKey(oneKeyList); + keys.push(newKey); + } + return keys; +} - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; +/** + * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects + * @param {Object} options + * @param {String} [options.armoredKeys] - Armored keys to be parsed + * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Key objects. + * @async + * @static + */ +async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) { + config$1 = { ...config, ...config$1 }; + let input = armoredKeys || binaryKeys; + if (!input) { + throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`'); + } + if (armoredKeys && !util.isString(armoredKeys)) { + throw new Error('readPrivateKeys: options.armoredKeys must be a string'); + } + if (binaryKeys && !util.isUint8Array(binaryKeys)) { + throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array'); + } + if (armoredKeys) { + const { type, data } = await unarmor(armoredKeys); + if (type !== enums.armor.privateKey) { + throw new Error('Armored text not of type private key'); } + input = data; + } + const keys = []; + const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1); + const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey); + for (let i = 0; i < keyIndex.length; i++) { + if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) { + continue; + } + const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]); + const newKey = new PrivateKey(oneKeyList); + keys.push(newKey); + } + if (keys.length === 0) { + throw new Error('No secret key packet found'); + } + return keys; +} - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - return { - div: div, - mod: mod - }; - } +// A Message can contain the following packets +const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([ + LiteralDataPacket, + CompressedDataPacket, + AEADEncryptedDataPacket, + SymEncryptedIntegrityProtectedDataPacket, + SymmetricallyEncryptedDataPacket, + PublicKeyEncryptedSessionKeyPacket, + SymEncryptedSessionKeyPacket, + OnePassSignaturePacket, + SignaturePacket +]); +// A SKESK packet can contain the following packets +const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]); +// A detached signature can contain the following packets +const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); +/** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ +class Message { + /** + * @param {PacketList} packetlist - The packets that form this message + */ + constructor(packetlist) { + this.packets = packetlist || new PacketList(); + } - if (mode !== 'mod') { - div = res.div.neg(); - } + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns {Array} Array of keyID objects. + */ + getEncryptionKeyIDs() { + const keyIDs = []; + const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + pkESKeyPacketlist.forEach(function(packet) { + keyIDs.push(packet.publicKeyID); + }); + return keyIDs; + } - return { - div: div, - mod: res.mod - }; + /** + * Returns the key IDs of the keys that signed the message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const msg = this.unwrapCompressed(); + // search for one pass signatures + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature); + if (onePassSigList.length > 0) { + return onePassSigList.map(packet => packet.issuerKeyID); } + // if nothing found look for signature packets + const signatureList = msg.packets.filterByTag(enums.packet.signature); + return signatureList.map(packet => packet.issuerKeyID); + } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {Array} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Date} [date] - Use the given date for key verification instead of the current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with decrypted content. + * @async + */ + async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) { + const symEncryptedPacketlist = this.packets.filterByTag( + enums.packet.symmetricallyEncryptedData, + enums.packet.symEncryptedIntegrityProtectedData, + enums.packet.aeadEncryptedData + ); - return { - div: res.div, - mod: mod - }; + if (symEncryptedPacketlist.length === 0) { + throw new Error('No encrypted data found'); } - // Both numbers are positive at this point + const symEncryptedPacket = symEncryptedPacketlist[0]; + const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm; - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } + const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1); - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; + let exception = null; + const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => { + if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) { + throw new Error('Invalid session key for decryption.'); } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; + try { + const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.decrypt(algo, data, config$1); + } catch (e) { + util.printDebugError(e); + exception = e; } + })); + // We don't await stream.cancel here because it only returns when the other copy is canceled too. + cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory. + symEncryptedPacket.encrypted = null; + await decryptedPromise; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; + if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) { + throw exception || new Error('Decryption failed.'); } - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } + const resultMsg = new Message(symEncryptedPacket.packets); + symEncryptedPacket.packets = new PacketList(); // remove packets after decryption - return this.strip(); - }; + return resultMsg; + } - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param {Array} [decryptionKeys] - Private keys with decrypted secret data + * @param {Array} [passwords] - Passwords used to decrypt + * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable) + * @param {Date} [date] - Use the given date for key verification, instead of current time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * @async + */ + async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) { + let decryptedSessionKeyPackets = []; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + let exception; + if (passwords) { + const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey); + if (skeskPackets.length === 0) { + throw new Error('No symmetrically encrypted session key packet found.'); + } + await Promise.all(passwords.map(async function(password, i) { + let packets; + if (i) { + packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1); + } else { + packets = skeskPackets; + } + await Promise.all(packets.map(async function(skeskPacket) { + try { + await skeskPacket.decrypt(password); + decryptedSessionKeyPackets.push(skeskPacket); + } catch (err) { + util.printDebugError(err); + if (err instanceof Argon2OutOfMemoryError) { + exception = err; + } + } + })); + })); + } else if (decryptionKeys) { + const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey); + if (pkeskPackets.length === 0) { + throw new Error('No public key encrypted session key packet found.'); + } + await Promise.all(pkeskPackets.map(async function(pkeskPacket) { + await Promise.all(decryptionKeys.map(async function(decryptionKey) { + let decryptionKeyPackets; + try { + // do not check key expiration to allow decryption of old messages + decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket); + } catch (err) { + exception = err; + return; + } - var x = this; - var y = p.clone(); + let algos = [ + enums.symmetric.aes256, // Old OpenPGP.js default fallback + enums.symmetric.aes128, // RFC4880bis fallback + enums.symmetric.tripledes, // RFC4880 fallback + enums.symmetric.cast5 // Golang OpenPGP fallback + ]; + try { + const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere. + if (selfCertification.preferredSymmetricAlgorithms) { + algos = algos.concat(selfCertification.preferredSymmetricAlgorithms); + } + } catch (e) {} - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } + await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) { + if (!decryptionKeyPacket.isDecrypted()) { + throw new Error('Decryption key is not decrypted.'); + } - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); + // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set. + const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && ( + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign || + pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal + ); - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + if (doConstantTimeDecryption) { + // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message, + // either with the successfully decrypted session key, or with a randomly generated one. + // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on + // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`: + // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the + // randomly generated keys of the remaining key types. + // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly + // generated session keys. + // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail. - var g = 0; + const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times + await Promise.all(( + expectedSymmetricAlgorithm ? + [expectedSymmetricAlgorithm] : + Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms) + ).map(async sessionKeyAlgorithm => { + const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket(); + pkeskPacketCopy.read(serialisedPKESK); + const randomSessionKey = { + sessionKeyAlgorithm, + sessionKey: mod$1.generateSessionKey(sessionKeyAlgorithm) + }; + try { + await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey); + decryptedSessionKeyPackets.push(pkeskPacketCopy); + } catch (err) { + // `decrypt` can still throw some non-security-sensitive errors + util.printDebugError(err); + exception = err; + } + })); - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + } else { + try { + await pkeskPacket.decrypt(decryptionKeyPacket); + const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm; + if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) { + throw new Error('A non-preferred symmetric algorithm was used.'); + } + decryptedSessionKeyPackets.push(pkeskPacket); + } catch (err) { + util.printDebugError(err); + exception = err; + } + } + })); + })); + cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory. + pkeskPacket.encrypted = null; + })); + } else { + throw new Error('No key or password specified.'); } - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); + if (decryptedSessionKeyPackets.length > 0) { + // Return only unique session keys + if (decryptedSessionKeyPackets.length > 1) { + const seen = new Set(); + decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => { + const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey); + if (seen.has(k)) { + return false; } - - C.iushrn(1); - D.iushrn(1); - } + seen.add(k); + return true; + }); } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } + return decryptedSessionKeyPackets.map(packet => ({ + data: packet.sessionKey, + algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm) + })); } + throw exception || new Error('Session key decryption failed.'); + } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); + /** + * Get literal data that is the body of the message + * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array. + */ + getLiteralData() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getBytes()) || null; + } - var a = this; - var b = p.clone(); + /** + * Get filename from literal data packet + * @returns {(String|null)} Filename of literal data packet as string. + */ + getFilename() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + return (literal && literal.getFilename()) || null; + } - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + /** + * Get literal data as text + * @returns {(String|null)} Literal body of the message interpreted as text. + */ + getText() { + const msg = this.unwrapCompressed(); + const literal = msg.packets.findPacket(enums.packet.literalData); + if (literal) { + return literal.getText(); } + return null; + } - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } + /** + * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any. + * @param {Array} [encryptionKeys] - Public key(s) to select algorithm preferences for + * @param {Date} [date] - Date to select algorithm preferences at + * @param {Array} [userIDs] - User IDs to select algorithm preferences for + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms. + * @async + */ + static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) { + const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1); + const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo); + const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined; - x1.iushrn(1); + await Promise.all(encryptionKeys.map(key => key.getEncryptionKey() + .catch(() => null) // ignore key strength requirements + .then(maybeKey => { + if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) && + !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted + throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.'); } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } + }) + )); - x2.iushrn(1); - } - } + const sessionKeyData = mod$1.generateSessionKey(symmetricAlgo); + return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName }; + } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - Password(s) for message encryption + * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i] + * @param {Date} [date] - Override the creation date of the literal package + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + if (sessionKey) { + if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) { + throw new Error('Invalid session key for encryption.'); } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; + } else if (encryptionKeys && encryptionKeys.length) { + sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1); + } else if (passwords && passwords.length) { + sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1); } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); + throw new Error('No keys, passwords, or session key provided.'); } - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey; - a.isub(b); - } while (true); + const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1); - return b.iushln(shift); - }; + const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({ + version: aeadAlgorithmName ? 2 : 1, + aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null + }); + symEncryptedPacket.packets = this.packets; - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + const algorithm = enums.write(enums.symmetric, algorithmName); + await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1); - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + msg.packets.push(symEncryptedPacket); + symEncryptedPacket.packets = new PacketList(); // remove packets after encryption + return msg; + } - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param {Uint8Array} sessionKey - session key for encryption + * @param {String} algorithmName - session key algorithm + * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {Array} [encryptionKeys] - Public key(s) for message encryption + * @param {Array} [passwords] - For message encryption + * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs + * @param {Array} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [date] - Override the date + * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with encrypted content. + * @async + */ + static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) { + const packetlist = new PacketList(); + const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName); + const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName); - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; + if (encryptionKeys) { + const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) { + const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1); - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } + const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({ + version: aeadAlgorithm ? 6 : 3, + encryptionKeyPacket: encryptionKey.keyPacket, + anonymousRecipient: wildcard, + sessionKey, + sessionKeyAlgorithm: symmetricAlgorithm + }); - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + await pkESKeyPacket.encrypt(encryptionKey.keyPacket); + delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption + return pkESKeyPacket; + })); + packetlist.push(...results); } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + if (passwords) { + const testDecrypt = async function(keyPacket, password) { + try { + await keyPacket.decrypt(password); + return 1; + } catch (e) { + return 0; + } + }; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + const sum = (accumulator, currentValue) => accumulator + currentValue; - this.strip(); + const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) { + const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1); + symEncryptedSessionKeyPacket.sessionKey = sessionKey; + symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm; + if (aeadAlgorithm) { + symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm; + } + await symEncryptedSessionKeyPacket.encrypt(password, config$1); - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + if (config$1.passwordCollisionCheck) { + const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd))); + if (results.reduce(sum) !== 1) { + return encryptPassword(sessionKey, algorithm, password); + } + } - assert(num <= 0x3ffffff, 'Number is too big'); + delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption + return symEncryptedSessionKeyPacket; + }; - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd))); + packetlist.push(...results); } - if (this.negative !== 0) return -res | 0; - return res; - }; - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; + return new Message(packetlist); + } - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; + /** + * Sign the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to add to the message + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New message with signed content. + * @async + */ + async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const packetlist = new PacketList(); - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; + const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well + const onePassSignaturePackets = signaturePackets.map( + (signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0)) + .reverse(); // innermost OPS refers to the first signature packet - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; + packetlist.push(...onePassSignaturePackets); + packetlist.push(literalDataPacket); + packetlist.push(...signaturePackets); - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; + return new Message(packetlist); + } - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param {module:enums.compression} algo - compression algorithm + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Message} New message with compressed content. + */ + compress(algo, config$1 = config) { + if (algo === enums.compression.uncompressed) { + return this; + } - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + const compressed = new CompressedDataPacket(config$1); + compressed.algorithm = algo; + compressed.packets = this.packets; - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + const packetList = new PacketList(); + packetList.push(compressed); - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + return new Message(packetList); + } - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creation time of the signature + * @param {Array} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New detached signature of message content. + * @async + */ + async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], recipientKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) { + const literalDataPacket = this.packets.findPacket(enums.packet.literalData); + if (!literalDataPacket) { + throw new Error('No literal data packet to sign.'); + } + return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, recipientKeyIDs, date, userIDs, notations, true, config$1)); + } - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; + /** + * Verify message signatures + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signatures. + * @async + */ + async verify(verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + if (isArrayStream(msg.packets.stream)) { + msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || [])); + } + const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse(); + const signatureList = msg.packets.filterByTag(enums.packet.signature); + if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) { + await Promise.all(onePassSigList.map(async onePassSig => { + onePassSig.correspondingSig = new Promise((resolve, reject) => { + onePassSig.correspondingSigResolve = resolve; + onePassSig.correspondingSigReject = reject; + }); + onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData); + onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false)); + onePassSig.hashed.catch(() => {}); + })); + msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => { + const reader = getReader(readable); + const writer = getWriter(writable); + try { + for (let i = 0; i < onePassSigList.length; i++) { + const { value: signature } = await reader.read(); + onePassSigList[i].correspondingSigResolve(signature); + } + await reader.readToEnd(); + await writer.ready; + await writer.close(); + } catch (e) { + onePassSigList.forEach(onePassSig => { + onePassSig.correspondingSigReject(e); + }); + await writer.abort(e); + } + }); + return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1); + } + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1); + } - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + /** + * Verify detached message signature + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Signature} signature + * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) { + const msg = this.unwrapCompressed(); + const literalDataList = msg.packets.filterByTag(enums.packet.literalData); + if (literalDataList.length !== 1) { + throw new Error('Can only verify message with one literal data packet.'); + } + const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1); + } - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; + /** + * Unwrap compressed message + * @returns {Message} Message Content of compressed message. + */ + unwrapCompressed() { + const compressed = this.packets.filterByTag(enums.packet.compressedData); + if (compressed.length) { + return new Message(compressed[0].packets); + } return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + } - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + /** + * Append signature to unencrypted message object + * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature + * @param {Object} [config] - Full configuration, defaults to openpgp.config + */ + async appendSignature(detachedSignature, config$1 = config) { + await this.packets.read( + util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, + allowedDetachedSignaturePackets, + config$1 + ); + } - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + /** + * Returns binary encoded message + * @returns {ReadableStream} Binary message. + */ + write() { + return this.packets.write(); + } - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + /** + * Returns ASCII armored text of message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + const trailingPacket = this.packets[this.packets.length - 1]; + // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer. + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ? + trailingPacket.version !== 2 : + this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6); + return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1); + } +} - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; +/** + * Create signature packets for the message + * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign + * @param {Array} [signingKeys] - private keys with decrypted secret key data for signing + * @param {Array} [recipientKeys] - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature to append + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [date] - Override the creationtime of the signature + * @param {Array} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures + * @param {Boolean} [detached] - Whether to create detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} List of signature packets. + * @async + * @private + */ +async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) { + const packetlist = new PacketList(); - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + // If data packet was created from Uint8Array, use binary, otherwise use text + const signatureType = literalDataPacket.text === null ? + enums.signature.binary : enums.signature.text; - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; + await Promise.all(signingKeys.map(async (primaryKey, i) => { + const signingUserID = signingUserIDs[i]; + if (!primaryKey.isPrivate()) { + throw new Error('Need private key for signing'); + } + const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1); + return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1); + })).then(signatureList => { + packetlist.push(...signatureList); + }); - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; + if (signature) { + const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature); + packetlist.push(...existingSigPacketlist); + } + return packetlist; +} - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; +/** + * Create object containing signer's keyID and validity of signature + * @param {SignaturePacket} signature - Signature packet + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} [date] - Check signature validity with respect to the given date + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise<{ + * keyID: module:type/keyid~KeyID, + * signature: Promise, + * verified: Promise + * }>} signer's keyID and validity of signature + * @async + * @private + */ +async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + let primaryKey; + let unverifiedSigningKey; - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + for (const key of verificationKeys) { + const issuerKeys = key.getKeys(signature.issuerKeyID); + if (issuerKeys.length > 0) { + primaryKey = key; + unverifiedSigningKey = issuerKeys[0]; + break; + } + } - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; + const isOnePassSignature = signature instanceof OnePassSignaturePacket; + const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature; - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + const verifiedSig = { + keyID: signature.issuerKeyID, + verified: (async () => { + if (!unverifiedSigningKey) { + throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`); + } - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); + await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1); + const signaturePacket = await signaturePacketPromise; + if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) { + throw new Error('Key is newer than the signature'); + } + // We pass the signature creation time to check whether the key was expired at the time of signing. + // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before + try { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1); + } catch (e) { + // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature, + // making the key invalid at the time of signing. + // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled. + // Note: we do not support the edge case of a key that was reformatted and it has expired. + if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) { + await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1); + } else { + throw e; + } + } + return true; + })(), + signature: (async () => { + const signaturePacket = await signaturePacketPromise; + const packetlist = new PacketList(); + signaturePacket && packetlist.push(signaturePacket); + return new Signature(packetlist); + })() }; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + // Mark potential promise rejections as "handled". This is needed because in + // some cases, we reject them before the user has a reasonable chance to + // handle them (e.g. `await readToEnd(result.data); await result.verified` and + // the data stream errors). + verifiedSig.signature.catch(() => {}); + verifiedSig.verified.catch(() => {}); - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + return verifiedSig; +} - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); +/** + * Create list of objects containing signer's keyID and validity of signature + * @param {Array} signatureList - Array of signature packets + * @param {Array} literalDataList - Array of literal data packets + * @param {Array} verificationKeys - Array of public keys to verify signatures + * @param {Date} date - Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @param {Boolean} [detached] - Whether to verify detached signature packets + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input) + * @async + * @private + */ +async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) { + return Promise.all(signatureList.filter(function(signature) { + return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)); + }).map(async function(signature) { + return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1); + })); +} - this.tmp = this._tmp(); +/** + * Reads an (optionally armored) OpenPGP message and returns a Message object + * @param {Object} options + * @param {String | ReadableStream} [options.armoredMessage] - Armored message to be parsed + * @param {Uint8Array | ReadableStream} [options.binaryMessage] - Binary to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New message object. + * @async + * @static + */ +async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + let input = armoredMessage || binaryMessage; + if (!input) { + throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`'); } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) { + throw new Error('readMessage: options.armoredMessage must be a string or stream'); } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; + if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) { + throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } + const streamType = util.isStream(input); + if (armoredMessage) { + const { type, data } = await unarmor(input); + if (type !== enums.armor.message) { + throw new Error('Armored text not of type message'); } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + input = data; } - inherits(P224, MPrime); + const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1); + const message = new Message(packetlist); + message.fromStream = streamType; + return message; +} - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +/** + * Creates new message object from text or binary data. + * @param {Object} options + * @param {String | ReadableStream} [options.text] - The text message contents + * @param {Uint8Array | ReadableStream} [options.binary] - The binary message contents + * @param {String} [options.filename=""] - Name of the file (if any) + * @param {Date} [options.date=current date] - Date of the message, or modification date of the file + * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type + * @returns {Promise} New message object. + * @async + * @static + */ +async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) { + const input = text !== undefined ? text : binary; + if (input === undefined) { + throw new Error('createMessage: must pass options object containing `text` or `binary`'); } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + if (text && !util.isString(text) && !util.isStream(text)) { + throw new Error('createMessage: options.text must be a string or stream'); + } + if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) { + throw new Error('createMessage: options.binary must be a Uint8Array or stream'); } - inherits(P25519, MPrime); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; + const streamType = util.isStream(input); + const literalDataPacket = new LiteralDataPacket(date); + if (text !== undefined) { + literalDataPacket.setText(input, enums.write(enums.literal, format)); + } else { + literalDataPacket.setBytes(input, enums.write(enums.literal, format)); + } + if (filename !== undefined) { + literalDataPacket.setFilename(filename); + } + const literalDataPacketlist = new PacketList(); + literalDataPacketlist.push(literalDataPacket); + const message = new Message(literalDataPacketlist); + message.fromStream = streamType; + return message; +} - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - return prime; - }; +// A Cleartext message can contain the following packets +const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]); - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; +/** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ +class CleartextMessage { + /** + * @param {String} text - The cleartext of the signed message + * @param {Signature} signature - The detached signature or an empty signature for unsigned messages + */ + constructor(text, signature) { + // remove trailing whitespace and normalize EOL to canonical form + this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n'); + if (signature && !(signature instanceof Signature)) { + throw new Error('Invalid signature input'); } + this.signature = signature || new Signature(new PacketList()); } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns {Array} Array of keyID objects. + */ + getSigningKeyIDs() { + const keyIDs = []; + const signatureList = this.signature.packets; + signatureList.forEach(function(packet) { + keyIDs.push(packet.issuerKeyID); + }); + return keyIDs; + } - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; + /** + * Sign the cleartext message + * @param {Array} signingKeys - private keys with decrypted secret key data for signing + * @param {Array} recipientKeys - recipient keys to get the signing preferences from + * @param {Signature} [signature] - Any existing detached signature + * @param {Array} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i] + * @param {Date} [date] - The creation time of the signature that should be created + * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] + * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from + * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }] + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise} New cleartext message with signed content. + * @async + */ + async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) { + const literalDataPacket = new LiteralDataPacket(); + literalDataPacket.setText(this.text); + const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1)); + return new CleartextMessage(this.text, newSignature); + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; + /** + * Verify signatures of cleartext signed message + * @param {Array} keys - Array of keys to verify signatures + * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {Promise, + * verified: Promise + * }>>} List of signer's keyID and validity of signature. + * @async + */ + verify(keys, date = new Date(), config$1 = config) { + const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets + const literalDataPacket = new LiteralDataPacket(); + // we assume that cleartext signature is generated based on UTF8 cleartext + literalDataPacket.setText(this.text); + return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1); + } - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } + /** + * Get cleartext + * @returns {String} Cleartext of message. + */ + getText() { + // normalize end of line to \n + return this.text.replace(/\r\n/g, '\n'); + } - return this.m.sub(a)._forceRed(this); - }; + /** + * Returns ASCII armored text of cleartext signed message + * @param {Object} [config] - Full configuration, defaults to openpgp.config + * @returns {String | ReadableStream} ASCII armor. + */ + armor(config$1 = config) { + // emit header and checksum if one of the signatures has a version not 6 + const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6); + const hash = emitHeaderAndChecksum ? + Array.from(new Set(this.signature.packets.map( + packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase() + ))).join() : + null; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + const body = { + hash, + text: this.text, + data: this.signature.packets.write() + }; - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; + // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer. + return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1); + } +} - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); +/** + * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param {Object} options + * @param {String} options.cleartextMessage - Text to be parsed + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} New cleartext message object. + * @async + * @static + */ +async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; + if (!cleartextMessage) { + throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`'); + } + if (!util.isString(cleartextMessage)) { + throw new Error('readCleartextMessage: options.cleartextMessage must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + const input = await unarmor(cleartextMessage); + if (input.type !== enums.armor.signed) { + throw new Error('No cleartext signed message.'); + } + const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1); + verifyHeaders(input.headers, packetlist); + const signature = new Signature(packetlist); + return new CleartextMessage(input.text, signature); +} - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); +/** + * Compare hash algorithm specified in the armor header with signatures + * @param {Array} headers - Armor headers + * @param {PacketList} packetlist - The packetlist with signature packets + * @private + */ +function verifyHeaders(headers, packetlist) { + const checkHashAlgos = function(hashAlgos) { + const check = packet => algo => packet.hashAlgorithm === algo; - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + for (let i = 0; i < packetlist.length; i++) { + if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { + return false; + } } - return res._forceRed(this); + return true; }; - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + const hashAlgos = []; + headers.forEach(header => { + const hashHeader = header.match(/^Hash: (.+)$/); // get header value + if (hashHeader) { + const parsedHashIDs = hashHeader[1] + .replace(/\s/g, '') // remove whitespace + .split(',') + .map(hashName => { + try { + return enums.write(enums.hash, hashName.toLowerCase()); + } catch (e) { + throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase()); + } + }); + hashAlgos.push(...parsedHashIDs); + } else { + throw new Error('Only "Hash" header allowed in cleartext signed message'); } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + }); - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { + throw new Error('Hash algorithm mismatch in armor header and signature'); + } +} - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; +/** + * Creates a new CleartextMessage object from text + * @param {Object} options + * @param {String} options.text + * @static + * @async + */ +async function createCleartextMessage({ text, ...rest }) { + if (!text) { + throw new Error('createCleartextMessage: must pass options object containing `text`'); + } + if (!util.isString(text)) { + throw new Error('createCleartextMessage: options.text must be a string'); + } + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + return new CleartextMessage(text); +} - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2016 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } +////////////////////// +// // +// Key handling // +// // +////////////////////// - return r; - }; - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys. + * By default, primary and subkeys will be of same type. + * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated. + * @param {Object} options + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys). + * Note: Curve448 and Curve25519 (new format) are not widely supported yet. + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys + * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys: + * curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1 + * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Array} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]` + * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + if (!type && !curve) { + type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them) + curve = 'curve25519Legacy'; // unused with type != 'ecc' + } else { + type = type || 'ecc'; + curve = curve || 'curve25519Legacy'; + } + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); + if (userIDs.length === 0 && !config$1.v6Keys) { + throw new Error('UserIDs are required for V4 keys'); + } + if (type === 'rsa' && rsaBits < config$1.minRSABits) { + throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`); + } - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } + const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys }; - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } + try { + const { key, revocationCertificate } = await generate(options, config$1); + key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1)); - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } + return { + privateKey: formatObject(key, format, config$1), + publicKey: formatObject(key.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error generating keypair', err); + } +} - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } +/** + * Reformats signature packets for a key and rewraps key object. + * @param {Object} options + * @param {PrivateKey} options.privateKey - Private key to reformat + * @param {Object|Array} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }` + * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted. + * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires + * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended + * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key. + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The generated key object in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String } + * @async + * @static + */ +async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + userIDs = toArray(userIDs); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) { + throw new Error('UserIDs are required for V4 keys'); + } + const options = { privateKey, userIDs, passphrase, keyExpirationTime, date }; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } + try { + const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1); - return res; - }; + return { + privateKey: formatObject(reformattedKey, format, config$1), + publicKey: formatObject(reformattedKey.toPublic(), format, config$1), + revocationCertificate + }; + } catch (err) { + throw util.wrapError('Error reformatting keypair', err); + } +} - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); +/** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored. + * @param {Object} options + * @param {Key} options.key - Public or private key to revoke + * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with + * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation + * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation + * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation + * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature + * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The revoked key in the form: + * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or + * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise + * @async + * @static + */ +async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - return r === num ? r.clone() : r; - }; + try { + const revokedKey = revocationCertificate ? + await key.applyRevocationCertificate(revocationCertificate, date, config$1) : + await key.revoke(reasonForRevocation, date, config$1); - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; + return revokedKey.isPrivate() ? { + privateKey: formatObject(revokedKey, format, config$1), + publicKey: formatObject(revokedKey.toPublic(), format, config$1) + } : { + privateKey: null, + publicKey: formatObject(revokedKey, format, config$1) + }; + } catch (err) { + throw util.wrapError('Error revoking key', err); + } +} - // - // Montgomery method engine - // +/** + * Unlock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to decrypt + * @param {String|Array} options.passphrase - The user's passphrase(s) + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The unlocked key object. + * @async + */ +async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - BN.mont = function mont (num) { - return new Mont(num); - }; + if (!privateKey.isPrivate()) { + throw new Error('Cannot decrypt a public key'); + } + const clonedPrivateKey = privateKey.clone(true); + const passphrases = util.isArray(passphrase) ? passphrase : [passphrase]; - function Mont (m) { - Red.call(this, m); + try { + await Promise.all(clonedPrivateKey.getKeys().map(key => ( + // try to decrypt each key with any of the given passphrases + util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase))) + ))); - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + await clonedPrivateKey.validate(config$1); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error decrypting private key', err); + } +} - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); +/** + * Lock a private key with the given passphrase. + * This method does not change the original key. + * @param {Object} options + * @param {PrivateKey} options.privateKey - The private key to encrypt + * @param {String|Array} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} The locked key object. + * @async + */ +async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); + if (!privateKey.isPrivate()) { + throw new Error('Cannot encrypt a public key'); } - inherits(Mont, Red); + const clonedPrivateKey = privateKey.clone(true); - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + const keys = clonedPrivateKey.getKeys(); + const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase); + if (passphrases.length !== keys.length) { + throw new Error('Invalid number of passphrases given for key encryption'); + } - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + try { + await Promise.all(keys.map(async (key, i) => { + const { keyPacket } = key; + await keyPacket.encrypt(passphrases[i], config$1); + keyPacket.clearPrivateParams(); + })); + return clonedPrivateKey; + } catch (err) { + clonedPrivateKey.clearPrivateParams(); + throw util.wrapError('Error encrypting private key', err); + } +} - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; +/////////////////////////////////////////// +// // +// Message encryption and decryption // +// // +/////////////////////////////////////////// - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - return res._forceRed(this); - }; +/** + * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys` + * must be specified. If signing keys are specified, those will be used to sign the message. + * @param {Object} options + * @param {Message} options.message - Message to be encrypted as created by {@link createMessage} + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message + * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed + * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message + * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }` + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Signature} [options.signature] - A detached signature to add to the encrypted message + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]` + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]` + * @param {Date} [options.date=current date] - Override the creation date of the message signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise|MaybeStream>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); signingKeys = toArray(signingKeys); passwords = toArray(passwords); + signingKeyIDs = toArray(signingKeyIDs); encryptionKeyIDs = toArray(encryptionKeyIDs); signingUserIDs = toArray(signingUserIDs); encryptionUserIDs = toArray(encryptionUserIDs); signatureNotations = toArray(signatureNotations); + if (rest.detached) { + throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well."); + } + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead'); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + if (!signingKeys) { + signingKeys = []; + } - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + try { + if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified + message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1); } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(module, commonjsGlobal); -}); - -var bn$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': bn, - __moduleExports: bn -}); + message = message.compress( + await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), + config$1 + ); + message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + if (format === 'object') return message; + // serialize data + const armor = format === 'armored'; + const data = armor ? message.armor(config$1) : message.write(); + return await convertStream(data); + } catch (err) { + throw util.wrapError('Error encrypting message', err); + } +} /** - * @fileoverview - * BigInteger implementation of basic operations - * Wrapper of bn.js library (wwww.github.com/indutny/bn.js) - * @module biginteger/bn - * @private + * Decrypts a message with the user's private key, a session key or a password. + * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported). + * @param {Object} options + * @param {Message} options.message - The message object with the encrypted data + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key + * @param {String|String[]} [options.passwords] - Passwords to decrypt the message + * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String } + * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing decrypted and verified message in the form: + * + * { + * data: MaybeStream, (if format was 'utf8', the default) + * data: MaybeStream, (if format was 'binary') + * filename: String, + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static */ +async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); verificationKeys = toArray(verificationKeys); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); sessionKeys = toArray(sessionKeys); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead'); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); -/** - * @private - */ -class BigInteger$1 { - /** - * Get a BigInteger (input must be big endian for strings and arrays) - * @param {Number|String|Uint8Array} n - Value to convert - * @throws {Error} on undefined input - */ - constructor(n) { - if (n === undefined) { - throw new Error('Invalid BigInteger input'); + try { + const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1); + if (!verificationKeys) { + verificationKeys = []; } - this.value = new bn(n); + const result = {}; + result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1); + result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText(); + result.filename = decrypted.getFilename(); + linkStreams(result, message); + if (expectSigned) { + if (verificationKeys.length === 0) { + throw new Error('Verification keys are required to verify message signatures'); + } + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error decrypting message', err); } +} - clone() { - const clone = new BigInteger$1(null); - this.value.copy(clone.value); - return clone; - } - /** - * BigInteger increment in place - */ - iinc() { - this.value.iadd(new bn(1)); - return this; - } +////////////////////////////////////////// +// // +// Message signing and verification // +// // +////////////////////////////////////////// - /** - * BigInteger increment - * @returns {BigInteger} this + 1. - */ - inc() { - return this.clone().iinc(); - } - /** - * BigInteger decrement in place - */ - idec() { - this.value.isub(new bn(1)); - return this; - } +/** + * Signs a message. + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed + * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext + * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from + * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message + * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature + * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i] + * @param {Date} [options.date=current date] - Override the creation date of the signature + * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]` + * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys` + * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); checkOutputMessageFormat(format); + signingKeys = toArray(signingKeys); signingKeyIDs = toArray(signingKeyIDs); signingUserIDs = toArray(signingUserIDs); recipientKeys = toArray(recipientKeys); recipientUserIDs = toArray(recipientUserIDs); signatureNotations = toArray(signatureNotations); - /** - * BigInteger decrement - * @returns {BigInteger} this - 1. - */ - dec() { - return this.clone().idec(); - } + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead'); + if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); + if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format'); + if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message'); - /** - * BigInteger addition in place - * @param {BigInteger} x - Value to add - */ - iadd(x) { - this.value.iadd(x.value); - return this; + if (!signingKeys || signingKeys.length === 0) { + throw new Error('No signing keys provided'); } - /** - * BigInteger addition - * @param {BigInteger} x - Value to add - * @returns {BigInteger} this + x. - */ - add(x) { - return this.clone().iadd(x); - } + try { + let signature; + if (detached) { + signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } else { + signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1); + } + if (format === 'object') return signature; - /** - * BigInteger subtraction in place - * @param {BigInteger} x - Value to subtract - */ - isub(x) { - this.value.isub(x.value); - return this; + const armor = format === 'armored'; + signature = armor ? signature.armor(config$1) : signature.write(); + if (detached) { + signature = transformPair(message.packets.write(), async (readable, writable) => { + await Promise.all([ + pipe(signature, writable), + readToEnd(readable).catch(() => {}) + ]); + }); + } + return await convertStream(signature); + } catch (err) { + throw util.wrapError('Error signing message', err); } +} - /** - * BigInteger subtraction - * @param {BigInteger} x - Value to subtract - * @returns {BigInteger} this - x. - */ - sub(x) { - return this.clone().isub(x); - } +/** + * Verifies signatures of cleartext signed message + * @param {Object} options + * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures + * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures + * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys + * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + * @param {Signature} [options.signature] - Detached signature for verification + * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Object containing verified message in the form: + * + * { + * data: MaybeStream, (if `message` was a CleartextMessage) + * data: MaybeStream, (if `message` was a Message) + * signatures: [ + * { + * keyID: module:type/keyid~KeyID, + * verified: Promise, + * signature: Promise + * }, ... + * ] + * } + * + * where `signatures` contains a separate entry for each signature packet found in the input message. + * @async + * @static + */ +async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkCleartextOrMessage(message); verificationKeys = toArray(verificationKeys); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * BigInteger multiplication in place - * @param {BigInteger} x - Value to multiply - */ - imul(x) { - this.value.imul(x.value); - return this; - } + if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary"); + if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature"); - /** - * BigInteger multiplication - * @param {BigInteger} x - Value to multiply - * @returns {BigInteger} this * x. - */ - mul(x) { - return this.clone().imul(x); + try { + const result = {}; + if (signature) { + result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1); + } else { + result.signatures = await message.verify(verificationKeys, date, config$1); + } + result.data = format === 'binary' ? message.getLiteralData() : message.getText(); + if (message.fromStream && !signature) linkStreams(result, message); + if (expectSigned) { + if (result.signatures.length === 0) { + throw new Error('Message is not signed'); + } + result.data = concat([ + result.data, + fromAsync(async () => { + await util.anyPromise(result.signatures.map(sig => sig.verified)); + }) + ]); + } + result.data = await convertStream(result.data); + return result; + } catch (err) { + throw util.wrapError('Error verifying signed message', err); } +} - /** - * Compute value modulo m, in place - * @param {BigInteger} m - Modulo - */ - imod(m) { - this.value = this.value.umod(m.value); - return this; - } - /** - * Compute value modulo m - * @param {BigInteger} m - Modulo - * @returns {BigInteger} this mod m. - */ - mod(m) { - return this.clone().imod(m); - } +/////////////////////////////////////////////// +// // +// Session key encryption and decryption // +// // +/////////////////////////////////////////////// - /** - * Compute modular exponentiation - * Much faster than this.exp(e).mod(n) - * @param {BigInteger} e - Exponent - * @param {BigInteger} n - Modulo - * @returns {BigInteger} this ** e mod n. - */ - modExp(e, n) { - // We use either Montgomery or normal reduction context - // Montgomery requires coprime n and R (montogmery multiplier) - // bn.js picks R as power of 2, so n must be odd - const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value); - const x = this.clone(); - x.value = x.value.toRed(nred).redPow(e.value).fromRed(); - return x; - } +/** + * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any. + * @param {Object} options + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm} + * @param {Date} [options.date=current date] - Date to select algorithm preferences at + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm. + * @async + * @static + */ +async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + encryptionKeys = toArray(encryptionKeys); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Compute the inverse of this value modulo n - * Note: this and and n must be relatively prime - * @param {BigInteger} n - Modulo - * @returns {BigInteger} x such that this*x = 1 mod n - * @throws {Error} if the inverse does not exist - */ - modInv(n) { - // invm returns a wrong result if the inverse does not exist - if (!this.gcd(n).isOne()) { - throw new Error('Inverse does not exist'); - } - return new BigInteger$1(this.value.invm(n.value)); + try { + const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error generating session key', err); } +} - /** - * Compute greatest common divisor between this and n - * @param {BigInteger} n - Operand - * @returns {BigInteger} gcd - */ - gcd(n) { - return new BigInteger$1(this.value.gcd(n.value)); - } +/** + * Encrypt a symmetric session key with public keys, passwords, or both at once. + * At least one of `encryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128) + * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb' + * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key + * @param {String|String[]} [options.passwords] - Passwords for the message + * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value + * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs + * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i] + * @param {Date} [options.date=current date] - Override the date + * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]` + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false). + * @async + * @static + */ +async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format); + encryptionKeys = toArray(encryptionKeys); passwords = toArray(passwords); encryptionKeyIDs = toArray(encryptionKeyIDs); encryptionUserIDs = toArray(encryptionUserIDs); + if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the left by x, in place - * @param {BigInteger} x - Shift value - */ - ileftShift(x) { - this.value.ishln(x.value.toNumber()); - return this; + if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) { + throw new Error('No encryption keys or passwords provided.'); } - /** - * Shift this to the left by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this << x. - */ - leftShift(x) { - return this.clone().ileftShift(x); + try { + const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1); + return formatObject(message, format, config$1); + } catch (err) { + throw util.wrapError('Error encrypting session key', err); } +} - /** - * Shift this to the right by x, in place - * @param {BigInteger} x - Shift value - */ - irightShift(x) { - this.value.ishrn(x.value.toNumber()); - return this; - } +/** + * Decrypt symmetric session keys using private keys or passwords (not both). + * One of `decryptionKeys` or `passwords` must be specified. + * @param {Object} options + * @param {Message} options.message - A message object containing the encrypted session key packets + * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data + * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key + * @param {Date} [options.date] - Date to use for key verification instead of the current time + * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config} + * @returns {Promise} Array of decrypted session key, algorithm pairs in the form: + * { data:Uint8Array, algorithm:String } + * @throws if no session key could be found or decrypted + * @async + * @static + */ +async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) { + config$1 = { ...config, ...config$1 }; checkConfig(config$1); + checkMessage(message); decryptionKeys = toArray(decryptionKeys); passwords = toArray(passwords); + if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead'); + const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`); - /** - * Shift this to the right by x - * @param {BigInteger} x - Shift value - * @returns {BigInteger} this >> x. - */ - rightShift(x) { - return this.clone().irightShift(x); + try { + const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1); + return sessionKeys; + } catch (err) { + throw util.wrapError('Error decrypting session keys', err); } +} - /** - * Whether this value is equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - equal(x) { - return this.value.eq(x.value); - } - /** - * Whether this value is less than x - * @param {BigInteger} x - * @returns {Boolean} - */ - lt(x) { - return this.value.lt(x.value); - } +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// - /** - * Whether this value is less than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - lte(x) { - return this.value.lte(x.value); - } - /** - * Whether this value is greater than x - * @param {BigInteger} x - * @returns {Boolean} - */ - gt(x) { - return this.value.gt(x.value); +/** + * Input validation + * @private + */ +function checkString(data, name) { + if (!util.isString(data)) { + throw new Error('Parameter [' + (name) + '] must be of type String'); } - - /** - * Whether this value is greater than or equal to x - * @param {BigInteger} x - * @returns {Boolean} - */ - gte(x) { - return this.value.gte(x.value); +} +function checkBinary(data, name) { + if (!util.isUint8Array(data)) { + throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array'); } - - isZero() { - return this.value.isZero(); +} +function checkMessage(message) { + if (!(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message'); } - - isOne() { - return this.value.eq(new bn(1)); +} +function checkCleartextOrMessage(message) { + if (!(message instanceof CleartextMessage) && !(message instanceof Message)) { + throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); } - - isNegative() { - return this.value.isNeg(); +} +function checkOutputMessageFormat(format) { + if (format !== 'armored' && format !== 'binary' && format !== 'object') { + throw new Error(`Unsupported format ${format}`); } - - isEven() { - return this.value.isEven(); +} +const defaultConfigPropsCount = Object.keys(config).length; +function checkConfig(config$1) { + const inputConfigProps = Object.keys(config$1); + if (inputConfigProps.length !== defaultConfigPropsCount) { + for (const inputProp of inputConfigProps) { + if (config[inputProp] === undefined) { + throw new Error(`Unknown config property: ${inputProp}`); + } + } } +} - abs() { - const res = this.clone(); - res.value = res.value.abs(); - return res; +/** + * Normalize parameter to an array if it is not undefined. + * @param {Object} param - the parameter to be normalized + * @returns {Array|undefined} The resulting array or undefined. + * @private + */ +function toArray(param) { + if (param && !util.isArray(param)) { + param = [param]; } + return param; +} - /** - * Get this value as a string - * @returns {String} this value. - */ - toString() { - return this.value.toString(); +/** + * Convert data to or from Stream + * @param {Object} data - the data to convert + * @returns {Promise} The data in the respective format. + * @async + * @private + */ +async function convertStream(data) { + const streamType = util.isStream(data); + if (streamType === 'array') { + return readToEnd(data); } + return data; +} - /** - * Get this value as an exact Number (max 53 bits) - * Fails if this value is too large - * @returns {Number} - */ - toNumber() { - return this.value.toNumber(); - } +/** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param {Object} result - the data to convert + * @param {Message} message - message object + * @returns {Object} + * @private + */ +function linkStreams(result, message) { + result.data = transformPair(message.packets.stream, async (readable, writable) => { + await pipe(result.data, writable, { + preventClose: true + }); + const writer = getWriter(writable); + try { + // Forward errors in the message stream to result.data. + await readToEnd(readable, _ => _); + await writer.close(); + } catch (e) { + await writer.abort(e); + } + }); +} - /** - * Get value of i-th bit - * @param {Number} i - Bit index - * @returns {Number} Bit value. - */ - getBit(i) { - return this.value.testn(i) ? 1 : 0; +/** + * Convert the object to the given format + * @param {Key|Message} object + * @param {'armored'|'binary'|'object'} format + * @param {Object} config - Full configuration + * @returns {String|Uint8Array|Object} + */ +function formatObject(object, format, config) { + switch (format) { + case 'object': + return object; + case 'armored': + return object.armor(config); + case 'binary': + return object.write(); + default: + throw new Error(`Unsupported format ${format}`); } +} - /** - * Compute bit length - * @returns {Number} Bit length. - */ - bitLength() { - return this.value.bitLength(); - } +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`positive integer expected, not ${n}`); +} +// copied from utils +function isBytes$1(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes$1(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function hash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(h.outputLen); + number(h.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// The byte swap operation for uint32 +const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +// In place byte swap for Uint32Array +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes$1(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes$1(data); + bytes(data); + return data; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes$1(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + bytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto$1 && typeof crypto$1.randomBytes === 'function') { + return crypto$1.randomBytes(bytesLength); + } + throw new Error('crypto.getRandomValues must be defined'); +} - /** - * Compute byte length - * @returns {Number} Byte length. - */ - byteLength() { - return this.value.byteLength(); - } +/** + * Polyfill for Safari 14 + */ +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +/** + * Choice: a ? b : c + */ +const Chi = (a, b, c) => (a & b) ^ (~a & c); +/** + * Majority function, true if any two inputs is true + */ +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); +/** + * SHA2-224 hash function + */ +const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224()); - /** - * Get Uint8Array representation of this number - * @param {String} endian - Endianess of output array (defaults to 'be') - * @param {Number} length - Of output array - * @returns {Uint8Array} - */ - toUint8Array(endian = 'be', length) { - return this.value.toArrayLike(Uint8Array, endian, length); - } +// HMAC (RFC 2104) +class HMAC extends Hash { + constructor(hash$1, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash$1.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + * @example + * import { hmac } from '@noble/hashes/hmac'; + * import { sha256 } from '@noble/hashes/sha2'; + * const mac1 = hmac(sha256, 'key', 'message'); + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// 100 lines of code in the file are duplicated from noble-hashes (utils). +// This is OK: `abstract` directory does not use noble-hashes. +// User may opt-in into using different hashing library. This way, noble-hashes +// won't be included into their bundle. +const _0n$6 = /* @__PURE__ */ BigInt(0); +const _1n$8 = /* @__PURE__ */ BigInt(1); +const _2n$5 = /* @__PURE__ */ BigInt(2); +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function abool(title, value) { + if (typeof value !== 'boolean') + throw new Error(`${title} must be valid boolean, got "${value}".`); +} +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + abytes(bytes); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + // Big Endian + return BigInt(hex === '' ? '0' : `0x${hex}`); +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; +function asciiToBase16(char) { + if (char >= asciis._0 && char <= asciis._9) + return char - asciis._0; + if (char >= asciis._A && char <= asciis._F) + return char - (asciis._A - 10); + if (char >= asciis._a && char <= asciis._f) + return char - (asciis._a - 10); + return; +} +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +// BE: Big Endian, LE: Little Endian +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +/** + * Takes hex string or Uint8Array, converts to Uint8Array. + * Validates output length. + * Will throw error for other types. + * @param title descriptive title for an error e.g. 'private key' + * @param hex hex string or Uint8Array + * @param expectedLength optional, will compare to result array's length + * @returns + */ +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === 'string') { + try { + res = hexToBytes(hex); + } + catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } + else if (isBytes(hex)) { + // Uint8Array.from() instead of hash.slice() because node.js Buffer + // is instance of Uint8Array, and its slice() creates **mutable** copy + res = Uint8Array.from(hex); + } + else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === 'number' && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +// Compares 2 u8a-s in kinda constant time +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +// Is positive bigint +const isPosBig = (n) => typeof n === 'bigint' && _0n$6 <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +/** + * Asserts min <= n < max. NOTE: It's < max and not <= max. + * @example + * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) + */ +function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + */ +function bitLen(n) { + let len; + for (len = 0; n > _0n$6; n >>= _1n$8, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + */ +function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n$8; +} +/** + * Sets single bit at position. + */ +function bitSet(n, pos, value) { + return n | ((value ? _1n$8 : _0n$6) << BigInt(pos)); +} +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + */ +const bitMask = (n) => (_2n$5 << BigInt(n - 1)) - _1n$8; +// DRBG +const u8n = (data) => new Uint8Array(data); // creates Uint8Array +const u8fr = (arr) => Uint8Array.from(arr); // another shortcut +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @returns function that will call DRBG until 2nd arg returns something meaningful + * @example + * const drbg = createHmacDRBG(32, 32, hmac); + * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined + */ +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + if (typeof hmacFn !== 'function') + throw new Error('hmacFn must be a function'); + // Step B, Step C: set hashLen to 8*ceil(hlen/8) + let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) + const reseed = (seed = u8n()) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= 1000) + throw new Error('drbg: tried 1000 values'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until k is in [1..n-1] + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +// Validating curves and fields +const validatorFns = { + bigint: (val) => typeof val === 'bigint', + function: (val) => typeof val === 'function', + boolean: (val) => typeof val === 'boolean', + string: (val) => typeof val === 'string', + stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), +}; +// type Record = { [P in K]: T; } +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== 'function') + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +// validate type tests +// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; +// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! +// // Should fail type-check +// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); +// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); +// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); +// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); +/** + * throws not implemented error + */ +const notImplemented = () => { + throw new Error('not implemented'); +}; +/** + * Memoizes (caches) computation result. + * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed. + */ +function memoized(fn) { + const map = new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; } -var bn_interface = /*#__PURE__*/Object.freeze({ +var ut = /*#__PURE__*/Object.freeze({ __proto__: null, - 'default': BigInteger$1 + aInRange: aInRange, + abool: abool, + abytes: abytes, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + inRange: inRange, + isBytes: isBytes, + memoized: memoized, + notImplemented: notImplemented, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject }); -var utils_1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Utilities for modular arithmetics and finite fields +// prettier-ignore +const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$4 = BigInt(2), _3n$2 = BigInt(3); +// prettier-ignore +const _4n = BigInt(4), _5n = BigInt(5), _8n$1 = BigInt(8); +// prettier-ignore +BigInt(9); BigInt(16); +// Calculates a modulo b +function mod(a, b) { + const result = a % b; + return result >= _0n$5 ? result : b + result; +} +/** + * Efficiently raise num to power and do modular division. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @example + * pow(2n, 6n, 11n) // 64n % 11n == 9n + */ +// TODO: use field version && remove +function pow(num, power, modulo) { + if (modulo <= _0n$5 || power < _0n$5) + throw new Error('Expected power/modulo > 0'); + if (modulo === _1n$7) + return _0n$5; + let res = _1n$7; + while (power > _0n$5) { + if (power & _1n$7) + res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n$7; + } return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); +} +// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$5) { + res *= res; + res %= modulo; } - } - return res; + return res; } -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; +// Inverses number over modulo +function invert(number, modulo) { + if (number === _0n$5 || modulo <= _0n$5) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n$5, u = _1n$7; + while (a !== _0n$5) { + // JIT applies optimization if those two lines follow each other + const q = b / a; + const r = b % a; + const m = x - u * q; + // prettier-ignore + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$7) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +/** + * Tonelli-Shanks square root search algorithm. + * 1. https://eprint.iacr.org/2012/685.pdf (page 12) + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * Will start an infinite loop if field order P is not prime. + * @param P field order + * @returns function that takes field Fp (created from P) and number n + */ +function tonelliShanks(P) { + // Legendre constant: used to calculate Legendre symbol (a | p), + // which denotes the value of a^((p-1)/2) (mod p). + // (a | p) ≡ 1 if a is a square (mod p) + // (a | p) ≡ -1 if a is not a square (mod p) + // (a | p) ≡ 0 if a ≡ 0 (mod p) + const legendreC = (P - _1n$7) / _2n$4; + let Q, S, Z; + // Step 1: By factoring out powers of 2 from p - 1, + // find q and s such that p - 1 = q*(2^s) with q odd + for (Q = P - _1n$7, S = 0; Q % _2n$4 === _0n$5; Q /= _2n$4, S++) + ; + // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq + for (Z = _2n$4; Z < P && pow(Z, legendreC, P) !== P - _1n$7; Z++) + ; + // Fast-path + if (S === 1) { + const p1div4 = (P + _1n$7) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Slow-path + const Q1div2 = (Q + _1n$7) / _2n$4; + return function tonelliSlow(Fp, n) { + // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error('Cannot find square root'); + let r = S; + // TODO: will fail at Fp2/etc + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b + let x = Fp.pow(n, Q1div2); // first guess at the square root + let b = Fp.pow(n, Q); // first guess at the fudge factor + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) + // Find m such b^(2^m)==1 + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); // t2 *= t2 + } + // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow + const ge = Fp.pow(g, _1n$7 << BigInt(r - m - 1)); // ge = 2^(r-m-1) + g = Fp.sqr(ge); // g = ge * ge + x = Fp.mul(x, ge); // x *= ge + b = Fp.mul(b, g); // b *= g + r = m; + } + return x; + }; +} +function FpSqrt(P) { + // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. + // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). + // P ≡ 3 (mod 4) + // √n = n^((P+1)/4) + if (P % _4n === _3n$2) { + // Not all roots possible! + // const ORDER = + // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; + // const NUM = 72057594037927816n; + const p1div4 = (P + _1n$7) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + // Throw if root**2 != n + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) + if (P % _8n$1 === _5n) { + const c1 = (P - _5n) / _8n$1; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$4); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$4), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error('Cannot find square root'); + return root; + }; + } + // Other cases: Tonelli-Shanks algorithm + return tonelliShanks(P); +} +// prettier-ignore +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +function validateField(field) { + const initial = { + ORDER: 'bigint', + MASK: 'bigint', + BYTES: 'isSafeInteger', + BITS: 'isSafeInteger', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + return validateObject(field, opts); +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + */ +function FpPow(f, num, power) { + // Should have same speed as pow for bigints + // TODO: benchmark! + if (power < _0n$5) + throw new Error('Expected power > 0'); + if (power === _0n$5) + return f.ONE; + if (power === _1n$7) + return num; + let p = f.ONE; + let d = num; + while (power > _0n$5) { + if (power & _1n$7) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$7; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * `inv(0)` will return `undefined` here: make sure to throw an error. + */ +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + // Walk from first to last, multiply them by each other MOD p + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + // Invert last element + const inverted = f.inv(lastMultiplied); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (f.is0(num)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +// CURVE.n lengths +function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +/** + * Initializes a finite field over prime. **Non-primes are not supported.** + * Do not init in loop: slow. Very fragile: always run a benchmark on a change. + * Major performance optimizations: + * * a) denormalized operations like mulN instead of mul + * * b) same object shape: never add or remove keys + * * c) Object.freeze + * NOTE: operations don't check 'isValid' for all elements for performance reasons, + * it is caller responsibility to check this. + * This is low-level code, please make sure you know what you doing. + * @param ORDER prime positive bigint + * @param bitLen how many bits the field consumes + * @param isLE (def: false) if encoding / decoding should be in little-endian + * @param redef optional faster redefinitions of sqrt and other methods + */ +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$5) + throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) + throw new Error('Field lengths over 2048 bytes are not supported'); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$5, + ONE: _1n$7, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== 'bigint') + throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$5 <= num && num < ORDER; // 0 is valid element, but it's not invertible + }, + is0: (num) => num === _0n$5, + isOdd: (num) => (num & _1n$7) === _1n$7, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f, n)), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + }, + }); + return Object.freeze(f); +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of field + */ +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * @param fieldOrder number of field elements, usually CURVE.n + * @returns byte length of target hash + */ +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. + * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ + * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final + * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 + * @param hash hash output from SHA3 or a similar function + * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) + * @param isLE interpret hash bytes as LE num + * @returns valid private scalar + */ +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. + if (len < 16 || len < minLen || len > 1024) + throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n$7) + _1n$7; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Abelian group utilities +const _0n$4 = BigInt(0); +const _1n$6 = BigInt(1); +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside) +// Elliptic curve multiplication of Point by scalar. Fragile. +// Scalars should always be less than curve order: this should be checked inside of a curve itself. +// Creates precomputation tables for fast multiplication: +// - private scalar is split by fixed size windows of W bits +// - every window point is collected from window's table & added to accumulator +// - since windows are different, same point inside tables won't be accessed more than once per calc +// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) +// - +1 window is neccessary for wNAF +// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication +// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow +// windows to be in different memory locations +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const validateW = (W) => { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); + }; + const opts = (W) => { + validateW(W); + const windows = Math.ceil(bits / W) + 1; // +1, because + const windowSize = 2 ** (W - 1); // -1 because we skip zero + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$4) { + if (n & _1n$6) + p = p.add(d); + d = d.double(); + n >>= _1n$6; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // =1, because we skip zero + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise + // But need to carefully remove other checks before wNAF. ORDER == bits here + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + // Extract W bits. + let wbits = Number(n & mask); + // Shift number by W bits. + n >>= shiftBy; + // If the bits are bigger than max size, we'll split those. + // +224 => 256 - 32 + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$6; + } + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + // Check if we're onto Zero point. + // Add random point inside current window to f. + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + // The most important part for const-time getPublicKey + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() + // Even if the variable is still unused, there are some checks which will + // throw an exception, so compiler needs to prove they won't happen, which is hard. + // At this point there is a way to F be infinity-point even if p is not, + // which makes it less const-time: around 1 bigint multiply. + return { p, f }; + }, + wNAFCached(P, n, transform) { + const W = pointWindowSizes.get(P) || 1; + // Calculate precomputes on a first run, reuse them after + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return this.wNAF(W, comp, n); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + }, + }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM). + * MSM is basically (Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster with precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c Curve Point constructor + * @param field field over CURVE.N - important that it's not over CURVE.P + * @param points array of L curve points + * @param scalars array of L scalars (aka private keys / bigints) + */ +function pippenger(c, field, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) + throw new Error('arrays of points and scalars must have equal length'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error(`wrong scalar at index ${i}`); + }); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error(`wrong point at index ${i}`); + }); + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array + const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; + let sum = c.ZERO; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(c.ZERO); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK)); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = c.ZERO; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: 'bigint', + h: 'bigint', + Gx: 'field', + Gy: 'field', + }, { + nBitLength: 'isSafeInteger', + nByteLength: 'isSafeInteger', + }); + // Set defaults + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); } -utils.zero2 = zero2; -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Short Weierstrass curve. The formula is: y² = x³ + ax + b +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool('lowS', opts.lowS); + if (opts.prehash !== undefined) + abool('prehash', opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: 'field', + b: 'field', + }, { + allowedPrivateKeyLengths: 'array', + wrapPrivateKey: 'boolean', + isTorsionFree: 'function', + clearCofactor: 'function', + allowInfinityPoint: 'boolean', + fromBytes: 'function', + toBytes: 'function', + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); + } + if (typeof endo !== 'object' || + typeof endo.beta !== 'bigint' || + typeof endo.splitScalar !== 'function') { + throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); + } + } + return Object.freeze({ ...opts }); +} +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html + */ +const DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = '') { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 128) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : ''; + return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 127; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n$3) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected assertion'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E('Invalid signature integer: negative'); + if (data[0] === 0x00 && !(data[1] & 128)) + throw new E('Invalid signature integer: unnecessary leading zero'); + return b2n(data); + }, + }, + toSig(hex) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === 'string' ? h2b(hex) : hex; + abytes(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('Invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`; + return tlv.encode(0x30, seq); + }, +}; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$3 = BigInt(0), _1n$5 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes = CURVE.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || + ((bytes) => { + // const head = bytes[0]; + const tail = bytes.subarray(1); + // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + /** + * y² = x³ + ax + b: Short weierstrass curve formula + * @returns y² + */ + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x2 * x + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b + } + // Validate whether the passed curve params are valid. + // We check if curve equation works for generator point. + // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. + // ProjectivePoint class has not been initialized yet. + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error('bad generator point: equation left != right'); + // Valid group elements reside in range 1..n-1 + function isWithinCurveOrder(num) { + return inRange(num, _1n$5, CURVE.n); + } + // Validates if priv key is valid and converts it to bigint. + // Supports options allowedPrivateKeyLengths and wrapPrivateKey. + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== 'bigint') { + if (isBytes(key)) + key = bytesToHex(key); + // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes + if (typeof key !== 'string' || !lengths.includes(key.length)) + throw new Error('Invalid key'); + key = key.padStart(nByteLength * 2, '0'); + } + let num; + try { + num = + typeof key === 'bigint' + ? key + : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); + } + catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) + num = mod(num, N); // disabled by default, enabled for BLS + aInRange('private key', num, _1n$5, N); // num in range [1..N-1] + return num; + } + function assertPrjPoint(other) { + if (!(other instanceof Point)) + throw new Error('ProjectivePoint expected'); + } + // Memoized toAffine / validity check. They are heavy. Points are immutable. + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + // Fast-path for normalized points + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + // NOTE: on exception this will crash 'cached' and no value will be set. + // Otherwise true will be return + const assertValidMemo = memoized((p) => { + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // (0, 0, 0) is wrong representation of ZERO and is always invalid. + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + // Check if x, y are valid field elements + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not FE'); + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + if (!Fp.eql(left, right)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + return true; + }); + /** + * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) + * Default Point works in 2d / affine coordinates: (x, y) + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error('x required'); + if (py == null || !Fp.isValid(py)) + throw new Error('y required'); + if (pz == null || !Fp.isValid(pz)) + throw new Error('z required'); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n$1); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + aInRange('scalar', sc, _0n$3, CURVE.n); + const I = Point.ZERO; + if (sc === _0n$3) + return I; + if (sc === _1n$5) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, sc); + // Apply endomorphism + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$3 || k2 > _0n$3) { + if (k1 & _1n$5) + k1p = k1p.add(d); + if (k2 & _1n$5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$5; + k2 >>= _1n$5; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange('scalar', scalar, _1n$5, N); + let point, fake; // Fake point is used to const-time mult + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return Point.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes + const mul = (P, a // Select faster multiply() method + ) => (a === _0n$3 || a === _1n$5 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$5) + return true; // No subgroups, always torsion-free + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error('isTorsionFree() has not been declared for the elliptic curve'); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$5) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool('isCompressed', isCompressed); + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool('isCompressed', isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + // Validate if generator point is on curve + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; } -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; -}); - -var utils_1$1 = createCommonjsModule(function (module, exports) { - -var utils = exports; - - - - -utils.assert = minimalisticAssert; -utils.toArray = utils_1.toArray; -utils.zero2 = utils_1.zero2; -utils.toHex = utils_1.toHex; -utils.encode = utils_1.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; +function validateOpts$2(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: 'hash', + hmac: 'function', + randomBytes: 'function', + }, { + bits2int: 'function', + bits2int_modN: 'function', + lowS: 'boolean', + }); + return Object.freeze({ lowS: true, ...opts }); +} +/** + * Creates short weierstrass curve and ECDSA signature methods for it. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, b, p, n, Gx, Gy + * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n }) + */ +function weierstrass(curveDef) { + const CURVE = validateOpts$2(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 + const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + abool('isCompressed', isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); + } + else { + return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + // this.assertValidity() is done inside of fromHex + if (len === compressedLen && (head === 0x02 || head === 0x03)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n$5, Fp.ORDER)) + throw new Error('Point is not on curve'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('Point is not on curve' + suffix); + } + const isYOdd = (y & _1n$5) === _1n$5; + // ECDSA + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } + else if (len === uncompressedLen && head === 0x04) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } + else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + }, + }); + const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$5; + return number > HALF; } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + // slice bytes num + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + /** + * ECDSA signature with its (r, s) properties. Supports DER & compact representations. + */ + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes('compactSignature', hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes('DER', hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange('r', this.r, _1n$5, CURVE_ORDER); // r in [1..N] + aInRange('s', this.s, _1n$5, CURVE_ORDER); // s in [1..N] + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error('recovery id invalid'); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error('recovery id 2 or 3 invalid'); + const prefix = (rec & 1) === 0 ? '02' : '03'; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); // r^-1 + const u1 = modN(-h * ir); // -hr^-1 + const u2 = modN(s * ir); // sr^-1 + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) + if (!Q) + throw new Error('point at infinify'); // unsafe is fine: no priv data leaked + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } + catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here + return point; + }, + }; + /** + * Computes public key for a private key. Checks for validity of the private key. + * @param privateKey private key + * @param isCompressed whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const arr = isBytes(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) + return true; + return false; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes shared public key from private key and public key. + * Checks: 1) private key validity 2) shared key is on-curve. + * Does NOT hash the result. + * @param privateA private key + * @param publicB different public key + * @param isCompressed whether to return compact (default), or full key + * @returns shared public key + */ + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error('first arg must be private key'); + if (!isProbPub(publicB)) + throw new Error('second arg must be public key'); + const b = Point.fromHex(publicB); // check for being on-curve + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = CURVE.bits2int || + function (bytes) { + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || + function (bytes) { + return modN(bits2int(bytes)); // can't use bytesToNumberBE here + }; + // NOTE: pads output with zero as per spec + const ORDER_MASK = bitMask(CURVE.nBitLength); + /** + * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. + */ + function int2octets(num) { + aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n$3, ORDER_MASK); + // works with order, can have different size than numToField! + return numberToBytesBE(num, CURVE.nByteLength); + } + // Steps A, D of RFC6979 3.2 + // Creates RFC6979 seed; converts msg/privKey to numbers. + // Used only in sign, not in verify. + // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. + // Also it can be bigger for P224 + SHA256 + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (['recovered', 'canonical'].some((k) => k in opts)) + throw new Error('sign() legacy options not supported'); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default + if (lowS == null) + lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash + msgHash = ensureBytes('msgHash', msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); + // We can't later call bits2octets, since nested bits2int is broken for curves + // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (ent != null && ent !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is + seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!isWithinCurveOrder(k)) + return; // Important: all mod() calls here must be done over N + const ik = invN(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = Gk + const r = modN(q.x); // r = q.x mod n + if (r === _0n$3) + return; + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + const s = modN(ik * modN(m + r * d)); // Not using blinding here + if (s === _0n$3) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$5); // recovery bit (2 or 3, when q.x > n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); // if lowS was passed, ensure s is always + recovery ^= 1; // // in the bottom half of N + } + return new Signature(r, normS, recovery); // use normS, not s + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + /** + * Signs message hash with a private key. + * ``` + * sign(m, d, k) where + * (x, y) = G × k + * r = x mod n + * s = (m + dr)/k mod n + * ``` + * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. + * @param privKey private key + * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. + * @returns signature with recovery param + */ + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); // Steps B, C, D, E, F, G + } + // Enable precomputes. Slows down first publicKey computation by 20ms. + Point.BASE._setWindowSize(8); + // utils.precompute(8, ProjectivePoint.BASE) + /** + * Verifies a signature against message hash and public key. + * Rejects lowS signatures by default: to override, + * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * U1 = hs^-1 mod n + * U2 = rs^-1 mod n + * R = U1⋅G - U2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes('msgHash', msgHash); + publicKey = ensureBytes('publicKey', publicKey); + if ('strict' in opts) + throw new Error('options.strict was renamed to lowS'); + validateSigVerOpts(opts); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === 'string' || isBytes(sg)) { + // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). + // Since DER can also be 2*nByteLength bytes, we check for it first. + try { + _sig = Signature.fromDER(sg); + } + catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } + else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { + const { r, s } = sg; + _sig = new Signature(r, s); + } + else { + throw new Error('PARSE'); + } + P = Point.fromHex(publicKey); + } + catch (error) { + if (error.message === 'PARSE') + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element + const is = invN(s); // s^-1 + const u1 = modN(h * is); // u1 = hs^-1 mod n + const u2 = modN(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P + if (!R) + return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils, + }; } -utils.getJSF = getJSF; -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// connects noble-curves to noble-hashes +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), + randomBytes, + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp256r1 aka p256 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256 +const Fp$7 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff')); +const CURVE_A$4 = Fp$7.create(BigInt('-3')); +const CURVE_B$4 = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'); +// prettier-ignore +const p256 = createCurve({ + a: CURVE_A$4, // Equation params: a, b + b: CURVE_B$4, + Fp: Fp$7, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n + // Curve order, total count of valid points in the field + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + // Base (generator) point (x, y) + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), + h: BigInt(1), + lowS: false, +}, sha256); + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); +const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384()); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp384r1 aka p384 +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384 +// Field over which we'll do calculations. +// prettier-ignore +const P$1 = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'); +const Fp$6 = Field(P$1); +const CURVE_A$3 = Fp$6.create(BigInt('-3')); +// prettier-ignore +const CURVE_B$3 = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'); +// prettier-ignore +const p384 = createCurve({ + a: CURVE_A$3, // Equation params: a, b + b: CURVE_B$3, + Fp: Fp$6, // Field: 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n + // Curve order, total count of valid points in the field. + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + // Base (generator) point (x, y) + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), + h: BigInt(1), + lowS: false, +}, sha384); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// NIST secp521r1 aka p521 +// Note that it's 521, which differs from 512 of its hash function. +// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-521 +// Field over which we'll do calculations. +// prettier-ignore +const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const Fp$5 = Field(P); +const CURVE = { + a: Fp$5.create(BigInt('-3')), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Fp: Fp$5, + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), + h: BigInt(1), +}; +// prettier-ignore +const p521 = createCurve({ + a: CURVE.a, // Equation params: a, b + b: CURVE.b, + Fp: Fp$5, // Field: 2n**521n - 1n + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, // Base point (x, y) aka generator point + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b +}, sha512); + +// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. +// It's called a sponge function. +// Various per round constants calculations +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; +const _0n$2 = /* @__PURE__ */ BigInt(0); +const _1n$4 = /* @__PURE__ */ BigInt(1); +const _2n$3 = /* @__PURE__ */ BigInt(2); +const _7n = /* @__PURE__ */ BigInt(7); +const _256n = /* @__PURE__ */ BigInt(256); +const _0x71n = /* @__PURE__ */ BigInt(0x71); +for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n$2; + for (let j = 0; j < 7; j++) { + R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n$3) + t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8); +const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y² +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n$1 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = BigInt(2), _8n = BigInt(8); +// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex: +const VERIFY_DEFAULT = { zip215: true }; +function validateOpts$1(curve) { + const opts = validateBasic(curve); + validateObject(curve, { + hash: 'function', + a: 'bigint', + d: 'bigint', + randomBytes: 'function', + }, { + adjustScalarBytes: 'function', + domain: 'function', + uvRatio: 'function', + mapToCurve: 'function', + }); + // Set defaults + return Object.freeze({ ...opts }); +} +/** + * Creates Twisted Edwards curve with EdDSA signatures. + * @example + * import { Field } from '@noble/curves/abstract/modular'; + * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h + * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h }) + */ +function twistedEdwards(curveDef) { + const CURVE = validateOpts$1(curveDef); + const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE; + const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3); + const modP = Fp.create; // Function overrides + const Fn = Field(CURVE.n, CURVE.nBitLength); + // sqrt(u/v) + const uvRatio = CURVE.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) }; + } + catch (e) { + return { isValid: false, value: _0n$1 }; + } + }); + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP + const domain = CURVE.domain || + ((data, ctx, phflag) => { + abool('phflag', phflag); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + }); // NOOP + // 0 <= n < MASK + // Coordinates larger than Fp.ORDER are allowed for zip215 + function aCoordinate(title, n) { + aInRange('coordinate ' + title, n, _0n$1, MASK); + } + function assertPoint(other) { + if (!(other instanceof Point)) + throw new Error('ExtendedPoint expected'); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + const toAffineMemo = memoized((p, iz) => { + const { ex: x, ey: y, ez: z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily + const ax = modP(x * iz); + const ay = modP(y * iz); + const zz = modP(z * iz); + if (is0) + return { x: _0n$1, y: _1n$3 }; + if (zz !== _1n$3) + throw new Error('invZ was invalid'); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + const { a, d } = CURVE; + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { ex: X, ey: Y, ez: Z, et: T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + return true; + }); + // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + constructor(ex, ey, ez, et) { + this.ex = ex; + this.ey = ey; + this.ez = ez; + this.et = et; + aCoordinate('x', ex); + aCoordinate('y', ey); + aCoordinate('z', ez); + aCoordinate('t', et); + Object.freeze(this); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + aCoordinate('x', x); + aCoordinate('y', y); + return new Point(x, y, _1n$3, modP(x * y)); + } + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.ez)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // Not required for fromHex(), which always creates valid points. + // Could be useful for fromAffine(). + assertValidity() { + assertValidMemo(this); + } + // Compare one point to another. + equals(other) { + assertPoint(other); + const { ex: X1, ey: Y1, ez: Z1 } = this; + const { ex: X2, ey: Y2, ez: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { ex: X1, ey: Y1, ez: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n$2 * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + assertPoint(other); + const { a, d } = CURVE; + const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; + const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other; + // Faster algo for adding 2 Extended Points when curve's a=-1. + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4 + // Cost: 8M + 8add + 2*2. + // Note: It does not check whether the `other` point is valid. + if (a === BigInt(-1)) { + const A = modP((Y1 - X1) * (Y2 + X2)); + const B = modP((Y1 + X1) * (Y2 - X2)); + const F = modP(B - A); + if (F === _0n$1) + return this.double(); // Same point. Tests say it doesn't affect timing + const C = modP(Z1 * _2n$2 * T2); + const D = modP(T1 * _2n$2 * Z2); + const E = D + C; + const G = B + A; + const H = D - C; + const X3 = modP(E * F); + const Y3 = modP(G * H); + const T3 = modP(E * H); + const Z3 = modP(F * G); + return new Point(X3, Y3, Z3, T3); + } + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + // Constant-time multiplication. + multiply(scalar) { + const n = scalar; + aInRange('scalar', n, _1n$3, CURVE_ORDER); // 1 <= scalar < L + const { p, f } = this.wNAF(n); + return Point.normalizeZ([p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Does NOT allow scalars higher than CURVE.n. + multiplyUnsafe(scalar) { + const n = scalar; + aInRange('scalar', n, _0n$1, CURVE_ORDER); // 0 <= scalar < L + if (n === _0n$1) + return I; + if (this.equals(I) || n === _1n$3) + return this; + if (this.equals(G)) + return this.wNAF(n).p; + return wnaf.unsafeLadder(this, n); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Multiplies point by cofactor and checks if the result is 0. + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafeLadder(this, CURVE_ORDER).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(iz) { + return toAffineMemo(this, iz); + } + clearCofactor() { + const { h: cofactor } = CURVE; + if (cofactor === _1n$3) + return this; + return this.multiplyUnsafe(cofactor); + } + // Converts hash string or Uint8Array to Point. + // Uses algo from RFC8032 5.1.3. + static fromHex(hex, zip215 = false) { + const { d, a } = CURVE; + const len = Fp.BYTES; + hex = ensureBytes('pointHex', hex, len); // copy hex to a new array + abool('zip215', zip215); + const normed = hex.slice(); // copy again, we'll manipulate it + const lastByte = hex[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('pointHex.y', y, _0n$1, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n$3); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n$3) === _1n$3; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n$1 && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('Point.fromHex: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromPrivateKey(privKey) { + return getExtendedPublicKey(privKey).point; + } + toRawBytes() { + const { x, y } = this.toAffine(); + const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y) + bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0; // when compressing, it's enough to store y + return bytes; // and use the last byte to encode sign of x + } + toHex() { + return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string. + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy)); + Point.ZERO = new Point(_0n$1, _1n$3, _1n$3, _0n$1); // 0, 1, 1, 0 + const { BASE: G, ZERO: I } = Point; + const wnaf = wNAF(Point, nByteLength * 8); + function modN(a) { + return mod(a, CURVE_ORDER); + } + // Little-endian SHA512 with modulo n + function modN_LE(hash) { + return modN(bytesToNumberLE(hash)); + } + /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */ + function getExtendedPublicKey(key) { + const len = nByteLength; + key = ensureBytes('private key', key, len); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = ensureBytes('hashed private key', cHash(key), 2 * len); + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + const point = G.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toRawBytes(); // Uint8Array representation + return { head, prefix, scalar, point, pointBytes }; + } + // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared + function getPublicKey(privKey) { + return getExtendedPublicKey(privKey).pointBytes; + } + // int('LE', SHA512(dom2(F, C) || msgs)) mod N + function hashDomainToScalar(context = new Uint8Array(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash))); + } + /** Signs message with privateKey. RFC8032 5.1.6 */ + function sign(msg, privKey, options = {}) { + msg = ensureBytes('message', msg); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + const R = G.multiply(r).toRawBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = modN(r + k * scalar); // S = (r + k * s) mod L + aInRange('signature.s', s, _0n$1, CURVE_ORDER); // 0 <= s < l + const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES)); + return ensureBytes('result', res, nByteLength * 2); // 64-byte signature + } + const verifyOpts = VERIFY_DEFAULT; + function verify(sig, msg, publicKey, options = verifyOpts) { + const { context, zip215 } = options; + const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7. + sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked. + msg = ensureBytes('message', msg); + if (zip215 !== undefined) + abool('zip215', zip215); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const s = bytesToNumberLE(sig.slice(len, 2 * len)); + // zip215: true is good for consensus-critical apps and allows points < 2^256 + // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p + let A, R, SB; + try { + A = Point.fromHex(publicKey, zip215); + R = Point.fromHex(sig.slice(0, len), zip215); + SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + if (!zip215 && A.isSmallOrder()) + return false; + const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // [8][S]B = [8]R + [8][k]A' + return RkA.subtract(SB).clearCofactor().equals(Point.ZERO); + } + G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + const utils = { + getExtendedPublicKey, + // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1. + randomPrivateKey: () => randomBytes(Fp.BYTES), + /** + * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT + * values. This slows down first getPublicKey() by milliseconds (see Speed section), + * but allows to speed-up subsequent getPublicKey() calls up to 20x. + * @param windowSize 2, 4, 8, 16 + */ + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + return { + CURVE, + getPublicKey, + sign, + verify, + ExtendedPoint: Point, + utils, + }; } -utils.cachedProperty = cachedProperty; -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const _0n = BigInt(0); +const _1n$2 = BigInt(1); +function validateOpts(curve) { + validateObject(curve, { + a: 'bigint', + }, { + montgomeryBits: 'isSafeInteger', + nByteLength: 'isSafeInteger', + adjustScalarBytes: 'function', + domain: 'function', + powPminus2: 'function', + Gu: 'bigint', + }); + // Set defaults + return Object.freeze({ ...curve }); +} +// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748) +// Uses only one coordinate instead of two +function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P } = CURVE; + const modP = (n) => mod(n, P); + const montgomeryBits = CURVE.montgomeryBits; + const montgomeryBytes = Math.ceil(montgomeryBits / 8); + const fieldLen = CURVE.nByteLength; + const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); + const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P)); + // cswap from RFC7748. But it is not from RFC7748! + /* + cswap(swap, x_2, x_3): + dummy = mask(swap) AND (x_2 XOR x_3) + x_2 = x_2 XOR dummy + x_3 = x_3 XOR dummy + Return (x_2, x_3) + Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + and x_3, computed, e.g., as mask(swap) = 0 - swap. + */ + function cswap(swap, x_2, x_3) { + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); + x_3 = modP(x_3 + dummy); + return [x_2, x_3]; + } + // x25519 from 4 + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 + const a24 = (CURVE.a - BigInt(2)) / BigInt(4); + /** + * + * @param pointU u coordinate (x) on Montgomery Curve 25519 + * @param scalar by which the point would be multiplied + * @returns new Point on Montgomery curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, _0n, P); + // Section 5: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. + const k = scalar; + const x_1 = u; + let x_2 = _1n$2; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n$2; + let swap = _0n; + let sw; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n$2; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + // (x_2, x_3) = cswap(swap, x_2, x_3) + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + // (z_2, z_3) = cswap(swap, z_2, z_3) + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + // z_2^(p - 2) + const z2 = powPminus2(z_2); + // Return x_2 * (z_2^(p - 2)) + return modP(x_2 * z2); + } + function encodeUCoordinate(u) { + return numberToBytesLE(modP(u), montgomeryBytes); + } + function decodeUCoordinate(uEnc) { + // Section 5: When receiving such an array, implementations of X25519 + // MUST mask the most significant bit in the final byte. + const u = ensureBytes('u coordinate', uEnc, montgomeryBytes); + if (fieldLen === 32) + u[31] &= 127; // 0b0111_1111 + return bytesToNumberLE(u); + } + function decodeScalar(n) { + const bytes = ensureBytes('scalar', n); + const len = bytes.length; + if (len !== montgomeryBytes && len !== fieldLen) + throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`); + return bytesToNumberLE(adjustScalarBytes(bytes)); + } + function scalarMult(scalar, u) { + const pointU = decodeUCoordinate(u); + const _scalar = decodeScalar(scalar); + const pu = montgomeryLadder(pointU, _scalar); + // The result was not contributory + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + const GuBytes = encodeUCoordinate(CURVE.Gu); + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + return { + scalarMult, + scalarMultBase, + getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getPublicKey: (privateKey) => scalarMultBase(privateKey), + utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) }, + GuBytes: GuBytes, + }; } -utils.parseBytes = parseBytes; -function intFromLE(bytes) { - return new bn(bytes, 'hex', 'le'); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Edwards448 (not Ed448-Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + */ +const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); +const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439'); +// prettier-ignore +const _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11); +// prettier-ignore +const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448P; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n$1, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n$1, P) * b2) % P; + const b223 = (pow2(b222, _1n$1, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, and the most + // significant bit of the last byte to 1. + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; } -utils.intFromLE = intFromLE; +// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v. +// Uses algo from RFC8032 5.1.3. +function uvRatio(u, v) { + const P = ed448P; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +const Fp$4 = Field(ed448P, 456, true); +const ED448_DEF = { + // Param: a + a: BigInt(1), + // -39081. Negative number is P - number + d: BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358'), + // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n + Fp: Fp$4, + // Subgroup order: how many points curve has; + // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n + n: BigInt('181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779'), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + nBitLength: 456, + // Cofactor + h: BigInt(4), + // Base point (x, y) aka generator point + Gx: BigInt('224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710'), + Gy: BigInt('298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660'), + // SHAKE256(dom4(phflag,context)||x, 114) + hash: shake256_114, + randomBytes, + adjustScalarBytes, + // dom4 + domain: (data, ctx, phflag) => { + if (ctx.length > 255) + throw new Error(`Context is too big: ${ctx.length}`); + return concatBytes$1(utf8ToBytes$1('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + }, + uvRatio, +}; +const ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); +// NOTE: there is no ed448ctx, since ed448 supports ctx by default +/* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); +const x448 = /* @__PURE__ */ (() => montgomery({ + a: BigInt(156326), + // RFC 7748 has 56-byte keys, RFC 8032 has 57-byte keys + montgomeryBits: 448, + nByteLength: 56, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + randomBytes, +}))(); +// TODO: add edwardsToMontgomeryPriv, similar to ed25519 version +// Hash To Curve Elligator2 Map +(Fp$4.ORDER - BigInt(3)) / BigInt(4); // 1. c1 = (q - 3) / 4 # Integer arithmetic +BigInt(156326); +// 1-d +BigInt('39082'); +// 1-2d +BigInt('78163'); +// √(-d) +BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); +const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b) => (a + b / _2n) / b; +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1P; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fp$3.eql(Fp$3.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fp$3 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); +/** + * secp256k1 short weierstrass curve and ECDSA signatures over it. + */ +const secp256k1 = createCurve({ + a: BigInt(0), // equation params: a, b + b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fp$3, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + h: BigInt(1), // Cofactor + lowS: true, // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalar: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, +}, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +BigInt(0); +secp256k1.ProjectivePoint; + +// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4 +// eslint-disable-next-line new-cap +const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377')); +const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9')); +const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'); +// prettier-ignore +const brainpoolP256r1 = createCurve({ + a: CURVE_A$2, // Equation params: a, b + b: CURVE_B$2, + Fp: Fp$2, + // Curve order (q), total count of valid points in the field + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + // Base (generator) point (x, y) + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), + lowS: false +}, sha256); + +// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6 +// eslint-disable-next-line new-cap +const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53')); +const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826')); +const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'); +// prettier-ignore +const brainpoolP384r1 = createCurve({ + a: CURVE_A$1, // Equation params: a, b + b: CURVE_B$1, + Fp: Fp$1, + // Curve order (q), total count of valid points in the field + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + // Base (generator) point (x, y) + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), + lowS: false +}, sha384); + +// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7 +// eslint-disable-next-line new-cap +const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3')); +const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca')); +const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'); +// prettier-ignore +const brainpoolP512r1 = createCurve({ + a: CURVE_A, // Equation params: a, b + b: CURVE_B, + Fp, + // Curve order (q), total count of valid points in the field + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + // Base (generator) point (x, y) + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), + lowS: false +}, sha512); + +/** + * This file is needed to dynamic import the noble-curves. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ + + +const nobleCurves = new Map(Object.entries({ + nistP256: p256, + nistP384: p384, + nistP521: p521, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, + secp256k1, + x448, + ed448 +})); + +var noble_curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleCurves: nobleCurves }); -var r$1; - -var brorand = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -var Rand_1 = Rand; +//Paul Tero, July 2001 +//http://www.tero.co.uk/des/ +// +//Optimised for performance with large blocks by Michael Hayworth, November 2001 +//http://www.netdealing.com +// +// Modified by Recurity Labs GmbH -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; +//THIS SOFTWARE IS PROVIDED "AS IS" AND +//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +//SUCH DAMAGE. -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); +//des +//this takes the key, the message, and whether to encrypt or decrypt - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; +function des(keys, message, encrypt, mode, iv, padding) { + //declaring this locally speeds things up a bit + const spfunction1 = [ + 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, + 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, + 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, + 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, + 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, + 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004 + ]; + const spfunction2 = [ + -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, + -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, + -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, + -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, + -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, + 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, + -0x7fef7fe0, 0x108000 + ]; + const spfunction3 = [ + 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, + 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, + 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, + 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, + 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, + 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200 + ]; + const spfunction4 = [ + 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, + 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, + 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, + 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, + 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080 + ]; + const spfunction5 = [ + 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, + 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, + 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, + 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, + 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, + 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, + 0x40080000, 0x2080100, 0x40000100 + ]; + const spfunction6 = [ + 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, + 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, + 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, + 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, + 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, + 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010 + ]; + const spfunction7 = [ + 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, + 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, + 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, + 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, + 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, + 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002 + ]; + const spfunction8 = [ + 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, + 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, + 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, + 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, + 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, + 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000 + ]; -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; + //create the 16 or 48 subkeys we will need + let m = 0; + let i; + let j; + let temp; + let right1; + let right2; + let left; + let right; + let looping; + let endloop; + let loopinc; + let len = message.length; - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; + //set up the loops for single and triple des + const iterations = keys.length === 32 ? 3 : 9; //single or triple des + if (iterations === 3) { + looping = encrypt ? [0, 32, 2] : [30, -2, -2]; + } else { + looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2]; } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto$2 = void('crypto'); - if (typeof crypto$2.randomBytes !== 'function') - throw new Error('Not supported'); - Rand.prototype._rand = function _rand(n) { - return crypto$2.randomBytes(n); - }; - } catch (e) { + //pad the message depending on the padding parameter + //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt + if (encrypt) { + message = desAddPadding(message); + len = message.length; } -} -brorand.Rand = Rand_1; -var getNAF = utils_1$1.getNAF; -var getJSF = utils_1$1.getJSF; -var assert$2 = utils_1$1.assert; + //store the result here + let result = new Uint8Array(len); + let k = 0; -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); + //loop through each 64 bit chunk of the message + while (m < len) { + left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; + right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++]; - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); + //first each 64 but chunk of the message must be permuted according to IP + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + //do this either 1 or 3 times for each chunk of the message + for (j = 0; j < iterations; j += 3) { + endloop = looping[j + 1]; + loopinc = looping[j + 2]; + //now go through and perform the encryption or decryption + for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency + right1 = right ^ keys[i]; + right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + //the result is attained by passing these bytes through the S selection functions + temp = left; + left = right; + right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> + 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & + 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); + } + temp = left; + left = right; + right = temp; //unreverse left and right + } //for either 1 or 3 iterations - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + //move then each one bit to the right + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -var base = BaseCurve; + //now perform IP-1, which is IP in the opposite direction + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((right >>> 2) ^ left) & 0x33333333; + left ^= temp; + right ^= (temp << 2); + temp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= temp; + left ^= (temp << 16); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; + result[k++] = (left >>> 24); + result[k++] = ((left >>> 16) & 0xff); + result[k++] = ((left >>> 8) & 0xff); + result[k++] = (left & 0xff); + result[k++] = (right >>> 24); + result[k++] = ((right >>> 16) & 0xff); + result[k++] = ((right >>> 8) & 0xff); + result[k++] = (right & 0xff); + } //for every 8 characters, or 64 bits in the message -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; + //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt + if (!encrypt) { + result = desRemovePadding(result); + } -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$2(p.precomputed); - var doubles = p._getDoubles(); + return result; +} //end of des - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } +//desCreateKeys +//this takes as input a 64 bit key (even though only 56 bits are used) +//as an array of 2 integers, and returns 16 48 bit keys - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; +function desCreateKeys(key) { + //declaring this locally speeds things up a bit + const pc2bytes0 = [ + 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, + 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204 + ]; + const pc2bytes1 = [ + 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, + 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101 + ]; + const pc2bytes2 = [ + 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, + 0x1000000, 0x1000008, 0x1000800, 0x1000808 + ]; + const pc2bytes3 = [ + 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, + 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000 + ]; + const pc2bytes4 = [ + 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, + 0x41000, 0x1010, 0x41010 + ]; + const pc2bytes5 = [ + 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, + 0x2000000, 0x2000400, 0x2000020, 0x2000420 + ]; + const pc2bytes6 = [ + 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, + 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002 + ]; + const pc2bytes7 = [ + 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, + 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800 + ]; + const pc2bytes8 = [ + 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, + 0x2000002, 0x2040002, 0x2000002, 0x2040002 + ]; + const pc2bytes9 = [ + 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, + 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408 + ]; + const pc2bytes10 = [ + 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, + 0x102000, 0x102020, 0x102000, 0x102020 + ]; + const pc2bytes11 = [ + 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, + 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200 + ]; + const pc2bytes12 = [ + 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, + 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010 + ]; + const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105]; -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; + //how many iterations (1 for des, 3 for triple des) + const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + //stores the return keys + const keys = new Array(32 * iterations); + //now define the left shifts which need to be done + const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + //other variables + let lefttemp; + let righttemp; + let m = 0; + let n = 0; + let temp; - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations + let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; + let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++]; - // Get NAF form - var naf = getNAF(k, w); + temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= temp; + left ^= (temp << 4); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 2) ^ right) & 0x33333333; + right ^= temp; + left ^= (temp << 2); + temp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= temp; + right ^= (temp << -16); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); + temp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= temp; + right ^= (temp << 8); + temp = ((left >>> 1) ^ right) & 0x55555555; + right ^= temp; + left ^= (temp << 1); - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); + //the right side needs to be shifted and to get the last four bits of the left side + temp = (left << 8) | ((right >>> 20) & 0x000000f0); + //left needs to be put upside down + left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0); + right = temp; - if (i < 0) - break; - var z = naf[i]; - assert$2(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; + //now go through and perform these shifts on the left and right keys + for (let i = 0; i < shifts.length; i++) { + //shift the keys either one or two bits to the left + if (shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; + //now apply PC-2, in such a way that E is easier when encrypting or decrypting + //this conversion will look like PC-2 except only the last 6 bits of each byte are used + //rather than 48 consecutive bits and the order of lines will be according to + //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7 + lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[( + left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & + 0xf]; + righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | + pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]; + temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff; + keys[n++] = lefttemp ^ temp; + keys[n++] = righttemp ^ (temp << 16); } + } //for each iterations + //return the keys we've created + return keys; +} //end of desCreateKeys - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; +function desAddPadding(message, padding) { + const padLength = 8 - (message.length % 8); - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } + let pad; + if ((padLength < 8)) { //pad the message out with null bytes + pad = 0; + } else if (padLength === 8) { + return message; + } else { + throw new Error('des: invalid padding'); } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; + const paddedMessage = new Uint8Array(message.length + padLength); + for (let i = 0; i < message.length; i++) { + paddedMessage[i] = message[i]; + } + for (let j = 0; j < padLength; j++) { + paddedMessage[message.length + j] = pad; + } - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; + return paddedMessage; +} - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); +function desRemovePadding(message, padding) { + let padLength = null; + let pad; + { // null padding + pad = 0; + } - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); + if (!padLength) { + padLength = 1; + while (message[message.length - padLength] === pad) { + padLength++; } + padLength--; } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; + return message.subarray(0, message.length - padLength); } -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert$2(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$2(bytes[bytes.length - 1] % 2 === 1); +// added by Recurity Labs - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); +function TripleDES(key) { + this.key = []; - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + for (let i = 0; i < 3; i++) { + this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8))); } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; -BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null + this.encrypt = function(block) { + return des( + desCreateKeys(this.key[2]), + des( + desCreateKeys(this.key[1]), + des( + desCreateKeys(this.key[0]), + block, true, 0, null, null + ), + false, 0, null, null + ), true); }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; +} - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; +TripleDES.keySize = TripleDES.prototype.keySize = 24; +TripleDES.blockSize = TripleDES.prototype.blockSize = 8; -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; +// Copyright 2010 pjacobs@xeekr.com . All rights reserved. -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; +// Modified by Recurity Labs GmbH -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; +// fixed/modified by Herbert Hanewinkel, www.haneWIN.de +// check www.haneWIN.de for the latest version -var assert$3 = utils_1$1.assert; +// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144. +// CAST-128 is a common OpenPGP cipher. -function ShortCurve(conf) { - base.call(this, 'short', conf); - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); +// CAST5 constructor - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; +function OpenPGPSymEncCAST5() { + this.BlockSize = 8; + this.KeySize = 16; - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits_browser(ShortCurve, base); -var short_1 = ShortCurve; + this.setKey = function(key) { + this.masking = new Array(16); + this.rotate = new Array(16); -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + this.reset(); - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; + if (key.length === this.KeySize) { + this.keySchedule(key); } else { - lambda = lambdas[1]; - assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + throw new Error('CAST-128: keys must be 16 bytes'); } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis + return true; }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + this.reset = function() { + for (let i = 0; i < 16; i++) { + this.masking[i] = 0; + this.rotate[i] = 0; } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; + }; -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + this.getBlockSize = function() { + return this.BlockSize; + }; - var x = point.x; - var y = point.y; + this.encrypt = function(src) { + const dst = new Array(src.length); - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; -function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >>> 16) & 255; + dst[i + 6] = (l >>> 8) & 255; + dst[i + 7] = l & 255; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits_browser(Point, base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + return dst; + }; - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + this.decrypt = function(src) { + const dst = new Array(src.length); - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; + for (let i = 0; i < src.length; i += 8) { + let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3]; + let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7]; + let t; -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + t = r; + r = l ^ f1(r, this.masking[15], this.rotate[15]); + l = t; + t = r; + r = l ^ f3(r, this.masking[14], this.rotate[14]); + l = t; + t = r; + r = l ^ f2(r, this.masking[13], this.rotate[13]); + l = t; + t = r; + r = l ^ f1(r, this.masking[12], this.rotate[12]); + l = t; - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; + t = r; + r = l ^ f3(r, this.masking[11], this.rotate[11]); + l = t; + t = r; + r = l ^ f2(r, this.masking[10], this.rotate[10]); + l = t; + t = r; + r = l ^ f1(r, this.masking[9], this.rotate[9]); + l = t; + t = r; + r = l ^ f3(r, this.masking[8], this.rotate[8]); + l = t; -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; + t = r; + r = l ^ f2(r, this.masking[7], this.rotate[7]); + l = t; + t = r; + r = l ^ f1(r, this.masking[6], this.rotate[6]); + l = t; + t = r; + r = l ^ f3(r, this.masking[5], this.rotate[5]); + l = t; + t = r; + r = l ^ f2(r, this.masking[4], this.rotate[4]); + l = t; - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } + t = r; + r = l ^ f1(r, this.masking[3], this.rotate[3]); + l = t; + t = r; + r = l ^ f3(r, this.masking[2], this.rotate[2]); + l = t; + t = r; + r = l ^ f2(r, this.masking[1], this.rotate[1]); + l = t; + t = r; + r = l ^ f1(r, this.masking[0], this.rotate[0]); + l = t; - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) + dst[i] = (r >>> 24) & 255; + dst[i + 1] = (r >>> 16) & 255; + dst[i + 2] = (r >>> 8) & 255; + dst[i + 3] = r & 255; + dst[i + 4] = (l >>> 24) & 255; + dst[i + 5] = (l >> 16) & 255; + dst[i + 6] = (l >> 8) & 255; + dst[i + 7] = l & 255; } - }; - return res; -}; -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + return dst; + }; + const scheduleA = new Array(4); -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; + scheduleA[0] = new Array(4); + scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8]; + scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; + scheduleA[1] = new Array(4); + scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + O = P - if (p.inf) - return this; + scheduleA[2] = new Array(4); + scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8]; + scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa]; + scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9]; + scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb]; - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); + scheduleA[3] = new Array(4); + scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0]; + scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2]; + scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1]; + scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3]; - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + const scheduleB = new Array(4); - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; + scheduleB[0] = new Array(4); + scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2]; + scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6]; + scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9]; + scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc]; -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; + scheduleB[1] = new Array(4); + scheduleB[1][0] = [3, 2, 0xc, 0xd, 8]; + scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd]; + scheduleB[1][2] = [7, 6, 8, 9, 3]; + scheduleB[1][3] = [5, 4, 0xa, 0xb, 7]; - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - var a = this.curve.a; + scheduleB[2] = new Array(4); + scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9]; + scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc]; + scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2]; + scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6]; - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; + scheduleB[3] = new Array(4); + scheduleB[3][0] = [8, 9, 7, 6, 3]; + scheduleB[3][1] = [0xa, 0xb, 5, 4, 7]; + scheduleB[3][2] = [0xc, 0xd, 3, 2, 8]; + scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd]; -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; + // changed 'in' to 'inn' (in javascript 'in' is a reserved word) + this.keySchedule = function(inn) { + const t = new Array(8); + const k = new Array(32); -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; + let j; -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; + for (let i = 0; i < 4; i++) { + j = i * 4; + t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3]; + } -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; + const x = [6, 7, 4, 5]; + let ki = 0; + let w; -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; + for (let half = 0; half < 2; half++) { + for (let round = 0; round < 4; round++) { + for (j = 0; j < 4; j++) { + const a = scheduleA[round][j]; + w = t[a[1]]; -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; + w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff]; + w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff]; + w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff]; + w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff]; + w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff]; + t[a[0]] = w; + } -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + for (j = 0; j < 4; j++) { + const b = scheduleB[round][j]; + w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff]; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) + w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff]; + w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff]; + w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff]; + w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff]; + k[ki] = w; + ki++; + } } - }; - } - return res; -}; + } -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + for (let i = 0; i < 16; i++) { + this.masking[i] = k[i]; + this.rotate[i] = k[16 + i] & 0x1f; + } + }; - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; + // These are the three 'f' functions. See RFC 2144, section 2.2. -function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); + function f1(d, m, r) { + const t = m + d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits_browser(JPoint, base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; + function f2(d, m, r) { + const t = m ^ d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255]; + } - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); + function f3(d, m, r) { + const t = m - d; + const I = (t << r) | (t >>> (32 - r)); + return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255]; } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + const sBox = new Array(8); + sBox[0] = [ + 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, + 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, + 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, + 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, + 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, + 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, + 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, + 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, + 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, + 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, + 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, + 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, + 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, + 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, + 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, + 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, + 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, + 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, + 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, + 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, + 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, + 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, + 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, + 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, + 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, + 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, + 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, + 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, + 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, + 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, + 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, + 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf + ]; + + sBox[1] = [ + 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, + 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, + 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, + 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, + 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, + 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, + 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, + 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, + 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, + 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, + 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, + 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, + 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, + 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, + 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, + 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, + 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, + 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, + 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, + 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, + 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, + 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, + 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, + 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, + 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, + 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, + 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, + 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, + 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, + 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, + 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, + 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1 + ]; - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); + sBox[2] = [ + 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, + 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, + 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, + 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, + 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, + 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, + 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, + 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, + 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, + 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, + 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, + 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, + 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, + 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, + 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, + 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, + 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, + 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, + 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, + 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, + 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, + 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, + 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, + 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, + 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, + 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, + 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, + 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, + 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, + 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, + 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, + 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783 + ]; - return this.curve.jpoint(nx, ny, nz); -}; + sBox[3] = [ + 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, + 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, + 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, + 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, + 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, + 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, + 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, + 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, + 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, + 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, + 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, + 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, + 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, + 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, + 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, + 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, + 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, + 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, + 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, + 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, + 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, + 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, + 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, + 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, + 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, + 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, + 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, + 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, + 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, + 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, + 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, + 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2 + ]; -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + sBox[4] = [ + 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, + 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, + 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, + 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, + 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, + 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, + 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, + 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, + 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, + 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, + 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, + 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, + 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, + 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, + 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, + 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, + 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, + 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, + 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, + 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, + 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, + 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, + 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, + 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, + 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, + 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, + 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, + 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, + 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, + 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, + 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, + 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4 + ]; - // P + O = P - if (p.isInfinity()) - return this; + sBox[5] = [ + 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, + 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, + 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, + 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, + 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, + 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, + 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, + 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, + 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, + 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, + 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, + 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, + 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, + 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, + 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, + 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, + 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, + 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, + 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, + 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, + 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, + 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, + 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, + 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, + 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, + 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, + 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, + 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, + 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, + 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, + 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, + 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f + ]; - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } + sBox[6] = [ + 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, + 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, + 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, + 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, + 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, + 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, + 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, + 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, + 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, + 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, + 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, + 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, + 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, + 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, + 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, + 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, + 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, + 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, + 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, + 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, + 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, + 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, + 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, + 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, + 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, + 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, + 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, + 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, + 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, + 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, + 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, + 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3 + ]; - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + sBox[7] = [ + 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, + 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, + 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, + 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, + 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, + 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, + 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, + 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, + 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, + 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, + 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, + 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, + 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, + 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, + 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, + 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, + 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, + 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, + 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, + 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, + 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, + 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, + 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, + 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, + 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, + 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, + 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, + 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, + 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, + 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, + 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, + 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e + ]; +} - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); +function CAST5(key) { + this.cast5 = new OpenPGPSymEncCAST5(); + this.cast5.setKey(key); - return this.curve.jpoint(nx, ny, nz); -}; + this.encrypt = function(block) { + return this.cast5.encrypt(block); + }; +} -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); +CAST5.blockSize = CAST5.prototype.blockSize = 8; +CAST5.keySize = CAST5.prototype.keySize = 16; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } +/* eslint-disable no-mixed-operators, no-fallthrough */ - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); +/* Modified by Recurity Labs GmbH + * + * Cipher.js + * A block-cipher algorithm implementation on JavaScript + * See Cipher.readme.txt for further information. + * + * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ] + * This script file is distributed under the LGPL + * + * ACKNOWLEDGMENT + * + * The main subroutines are written by Michiel van Everdingen. + * + * Michiel van Everdingen + * http://home.versatel.nl/MAvanEverdingen/index.html + * + * All rights for these routines are reserved to Michiel van Everdingen. + * + */ - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//Math +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); +const MAXINT = 0xFFFFFFFF; - jx = nx; - jz = nz; - jyd = dny; - } +function rotw(w, n) { + return (w << n | w >>> (32 - n)) & MAXINT; +} - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; +function getW(a, i) { + return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24; +} -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; +function setW(a, i, w) { + a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF); +} - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; +function getB(x, n) { + return (x >>> (n * 8)) & 0xFF; +} -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Twofish +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; +function createTwofish() { + // + let keyBytes = null; + let dataBytes = null; + let dataOffset = -1; + // var dataLength = -1; + // var idx2 = -1; + // -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + let tfsKey = []; + let tfsM = [ + [], + [], + [], + [] + ]; - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + function tfsInit(key) { + keyBytes = key; + let i; + let a; + let b; + let c; + let d; + const meKey = []; + const moKey = []; + const inKey = []; + let kLen; + const sKey = []; + let f01; + let f5b; + let fef; - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + const q0 = [ + [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], + [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5] + ]; + const q1 = [ + [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], + [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8] + ]; + const q2 = [ + [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], + [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15] + ]; + const q3 = [ + [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], + [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10] + ]; + const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; + const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7]; + const q = [ + [], + [] + ]; + const m = [ + [], + [], + [], + [] + ]; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + function ffm5b(x) { + return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3]; + } - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); + function ffmEf(x) { + return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3]; + } - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); + function mdsRem(p, q) { + let i; + let t; + let u; + for (i = 0; i < 8; i++) { + t = q >>> 24; + q = ((q << 8) & MAXINT) | p >>> 24; + p = (p << 8) & MAXINT; + u = t << 1; + if (t & 128) { + u ^= 333; + } + q ^= t ^ (u << 16); + u ^= t >>> 1; + if (t & 1) { + u ^= 166; + } + q ^= u << 24 | u << 8; + } + return q; + } - return this.curve.jpoint(nx, ny, nz); -}; + function qp(n, x) { + const a = x >> 4; + const b = x & 15; + const c = q0[n][a ^ b]; + const d = q1[n][ror4[b] ^ ashx[a]]; + return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; + } -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; + function hFun(x, key) { + let a = getB(x, 0); + let b = getB(x, 1); + let c = getB(x, 2); + let d = getB(x, 3); + switch (kLen) { + case 4: + a = q[1][a] ^ getB(key[3], 0); + b = q[0][b] ^ getB(key[3], 1); + c = q[0][c] ^ getB(key[3], 2); + d = q[1][d] ^ getB(key[3], 3); + case 3: + a = q[1][a] ^ getB(key[2], 0); + b = q[1][b] ^ getB(key[2], 1); + c = q[0][c] ^ getB(key[2], 2); + d = q[0][d] ^ getB(key[2], 3); + case 2: + a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0); + b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1); + c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2); + d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3); + } + return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d]; + } -JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); + keyBytes = keyBytes.slice(0, 32); + i = keyBytes.length; + while (i !== 16 && i !== 24 && i !== 32) { + keyBytes[i++] = 0; + } - return this.curve._wnafMul(this, k); -}; + for (i = 0; i < keyBytes.length; i += 4) { + inKey[i >> 2] = getW(keyBytes, i); + } + for (i = 0; i < 256; i++) { + q[0][i] = qp(0, i); + q[1][i] = qp(1, i); + } + for (i = 0; i < 256; i++) { + f01 = q[1][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + f01 = q[0][i]; + f5b = ffm5b(f01); + fef = ffmEf(f01); + m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + kLen = inKey.length / 2; + for (i = 0; i < kLen; i++) { + a = inKey[i + i]; + meKey[i] = a; + b = inKey[i + i + 1]; + moKey[i] = b; + sKey[kLen - i - 1] = mdsRem(a, b); + } + for (i = 0; i < 40; i += 2) { + a = 0x1010101 * i; + b = a + 0x1010101; + a = hFun(a, meKey); + b = rotw(hFun(b, moKey), 8); + tfsKey[i] = (a + b) & MAXINT; + tfsKey[i + 1] = rotw(a + 2 * b, 9); + } + for (i = 0; i < 256; i++) { + a = b = c = d = i; + switch (kLen) { + case 4: + a = q[1][a] ^ getB(sKey[3], 0); + b = q[0][b] ^ getB(sKey[3], 1); + c = q[0][c] ^ getB(sKey[3], 2); + d = q[1][d] ^ getB(sKey[3], 3); + case 3: + a = q[1][a] ^ getB(sKey[2], 0); + b = q[1][b] ^ getB(sKey[2], 1); + c = q[0][c] ^ getB(sKey[2], 2); + d = q[0][d] ^ getB(sKey[2], 3); + case 2: + tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)]; + tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)]; + tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)]; + tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)]; + } + } + } - if (this === p) - return true; + function tfsG0(x) { + return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)]; + } - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; + function tfsG1(x) { + return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)]; + } - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; + function tfsFrnd(r, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31); + blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT; + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31); + blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT; + } -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; + function tfsIrnd(i, blk) { + let a = tfsG0(blk[0]); + let b = tfsG1(blk[1]); + blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT; + blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31); + a = tfsG0(blk[2]); + b = tfsG1(blk[3]); + blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT; + blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31); + } - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; + function tfsClose() { + tfsKey = []; + tfsM = [ + [], + [], + [], + [] + ]; + } - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; + function tfsEncrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], + getW(dataBytes, dataOffset + 4) ^ tfsKey[1], + getW(dataBytes, dataOffset + 8) ^ tfsKey[2], + getW(dataBytes, dataOffset + 12) ^ tfsKey[3]]; + for (let j = 0; j < 8; j++) { + tfsFrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]); + dataOffset += 16; + return dataBytes; } -}; -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + function tfsDecrypt(data, offset) { + dataBytes = data; + dataOffset = offset; + const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], + getW(dataBytes, dataOffset + 4) ^ tfsKey[5], + getW(dataBytes, dataOffset + 8) ^ tfsKey[6], + getW(dataBytes, dataOffset + 12) ^ tfsKey[7]]; + for (let j = 7; j >= 0; j--) { + tfsIrnd(j, blk); + } + setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]); + setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]); + setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]); + setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]); + dataOffset += 16; + } -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; + // added by Recurity Labs -function MontCurve(conf) { - base.call(this, 'mont', conf); + function tfsFinal() { + return dataBytes; + } - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - // Note: this implementation is according to the original paper - // by P. Montgomery, NOT the one by D. J. Bernstein. - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + return { + name: 'twofish', + blocksize: 128 / 8, + open: tfsInit, + close: tfsClose, + encrypt: tfsEncrypt, + decrypt: tfsDecrypt, + // added by Recurity Labs + finalize: tfsFinal + }; } -inherits_browser(MontCurve, base); -var mont = MontCurve; -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); +// added by Recurity Labs - return y.redSqr().cmp(rhs) === 0; -}; +function TF(key) { + this.tf = createTwofish(); + this.tf.open(Array.from(key), 0); -function Point$1(curve, x, z) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } + this.encrypt = function(block) { + return this.tf.encrypt(Array.from(block), 0); + }; } -inherits_browser(Point$1, base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - var bytes = utils_1$1.toArray(bytes, enc); - - // TODO Curve448 - // Montgomery curve points must be represented in the compressed format - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (bytes.length === 33 && bytes[0] === 0x40) - bytes = bytes.slice(1, 33).reverse(); // point must be little-endian - if (bytes.length !== 32) - throw new Error('Unknown point compression format'); - return this.point(bytes, 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); -}; - -Point$1.prototype.precompute = function precompute() { - // No-op -}; - -Point$1.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - - // Note: the output should always be little-endian - // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B - if (compact) { - return [ 0x40 ].concat(this.getX().toArray('le', len)); - } else { - return this.getX().toArray('be', len); - } -}; - -Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); -}; - -Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; -Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; +TF.keySize = TF.prototype.keySize = 32; +TF.blockSize = TF.prototype.blockSize = 16; -Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; +/* Modified by Recurity Labs GmbH + * + * Originally written by nklein software (nklein.com) + */ -Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; +/* + * Javascript implementation based on Bruce Schneier's reference implementation. + * + * + * The constructor doesn't do much of anything. It's just here + * so we can start defining properties and methods and such. + */ +function Blowfish() {} -Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; +/* + * Declare the block size so that protocols know what size + * Initialization Vector (IV) they will need. + */ +Blowfish.prototype.BLOCKSIZE = 8; -Point$1.prototype.mul = function mul(k) { - k = new bn(k, 16); +/* + * These are the default SBOXES. + */ +Blowfish.prototype.SBOXES = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] +]; - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q +//* +//* This is the default PARRAY +//* +Blowfish.prototype.PARRAY = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b +]; - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); +//* +//* This is the number of rounds the cipher will go +//* +Blowfish.prototype.NN = 16; - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } +//* +//* This function is needed to get rid of problems +//* with the high-bit getting set. If we don't do +//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not +//* equal to ( bb & 0x00FFFFFFFF ) even when they +//* agree bit-for-bit for the first 32 bits. +//* +Blowfish.prototype._clean = function(xx) { + if (xx < 0) { + const yy = xx & 0x7FFFFFFF; + xx = yy + 0x80000000; } - return b; -}; - -Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); + return xx; }; -var assert$4 = utils_1$1.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - base.call(this, 'edwards', conf); - - this.a = new bn(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); +//* +//* This is the mixing function that uses the sboxes +//* +Blowfish.prototype._F = function(xx) { + let yy; - assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits_browser(EdwardsCurve, base); -var edwards = EdwardsCurve; + const dd = xx & 0x00FF; + xx >>>= 8; + const cc = xx & 0x00FF; + xx >>>= 8; + const bb = xx & 0x00FF; + xx >>>= 8; + const aa = xx & 0x00FF; -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; + yy = this.sboxes[0][aa] + this.sboxes[1][bb]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); + return yy; }; -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; +//* +//* This method takes an array with two values, left and right +//* and does NN rounds of Blowfish on them. +//* +Blowfish.prototype._encryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); + let ii; - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + for (ii = 0; ii < this.NN; ++ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; - return this.point(x, y); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new bn(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); +//* +//* This method takes a vector of numbers and turns them +//* into long words so that they can be processed by the +//* real algorithm. +//* +//* Maybe I should make the real algorithm above take a vector +//* instead. That will involve more looping, but it won't require +//* the F() method to deconstruct the vector. +//* +Blowfish.prototype.encryptBlock = function(vector) { + let ii; + const vals = [0, 0]; + const off = this.BLOCKSIZE / 2; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF); + vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF); } - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + this._encryptBlock(vals); - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + const ret = []; + for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { + ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF); + ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF); + // vals[ 0 ] = ( vals[ 0 ] >>> 8 ); + // vals[ 1 ] = ( vals[ 1 ] >>> 8 ); + } - return this.point(x, y); + return ret; }; -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; +//* +//* This method takes an array with two values, left and right +//* and undoes NN rounds of Blowfish on them. +//* +Blowfish.prototype._decryptBlock = function(vals) { + let dataL = vals[0]; + let dataR = vals[1]; -function Point$2(curve, x, y, z, t) { - base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits_browser(Point$2, base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$2.fromJSON(this, obj); -}; + let ii; -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point$2(this, x, y, z, t); -}; + for (ii = this.NN + 1; ii > 1; --ii) { + dataL ^= this.parray[ii]; + dataR = this._F(dataL) ^ dataR; -Point$2.fromJSON = function fromJSON(curve, obj) { - return new Point$2(curve, obj[0], obj[1], obj[2]); -}; + const tmp = dataL; + dataL = dataR; + dataR = tmp; + } -Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; -Point$2.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); + vals[0] = this._clean(dataR); + vals[1] = this._clean(dataL); }; -Point$2.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; +//* +//* This method takes a key array and initializes the +//* sboxes and parray for this encryption. +//* +Blowfish.prototype.init = function(key) { + let ii; + let jj = 0; -Point$2.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); + this.parray = []; + for (ii = 0; ii < this.NN + 2; ++ii) { + let data = 0x00000000; + for (let kk = 0; kk < 4; ++kk) { + data = (data << 8) | (key[jj] & 0x00FF); + if (++jj >= key.length) { + jj = 0; + } } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point$2.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point$2.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point$2.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); + this.parray[ii] = this.PARRAY[ii] ^ data; } - return this.curve.point(nx, ny, nz); -}; -Point$2.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; + this.sboxes = []; + for (ii = 0; ii < 4; ++ii) { + this.sboxes[ii] = []; + for (jj = 0; jj < 256; ++jj) { + this.sboxes[ii][jj] = this.SBOXES[ii][jj]; + } + } -Point$2.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; + const vals = [0x00000000, 0x00000000]; -Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; + for (ii = 0; ii < this.NN + 2; ii += 2) { + this._encryptBlock(vals); + this.parray[ii + 0] = vals[0]; + this.parray[ii + 1] = vals[1]; + } -Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + for (ii = 0; ii < 4; ++ii) { + for (jj = 0; jj < 256; jj += 2) { + this._encryptBlock(vals); + this.sboxes[ii][jj + 0] = vals[0]; + this.sboxes[ii][jj + 1] = vals[1]; + } + } }; -Point$2.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; +// added by Recurity Labs +function BF(key) { + this.bf = new Blowfish(); + this.bf.init(key); -Point$2.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; + this.encrypt = function(block) { + return this.bf.encryptBlock(block); + }; +} -Point$2.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; +BF.keySize = BF.prototype.keySize = 16; +BF.blockSize = BF.prototype.blockSize = 8; -Point$2.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; +/** + * This file is needed to dynamic import the legacy ciphers. + * Separate dynamic imports are not convenient as they result in multiple chunks. + */ -Point$2.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; -Point$2.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; +const legacyCiphers = new Map([ + [enums.symmetric.tripledes, TripleDES], + [enums.symmetric.cast5, CAST5], + [enums.symmetric.blowfish, BF], + [enums.symmetric.twofish, TF] +]); - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; +var legacy_ciphers = /*#__PURE__*/Object.freeze({ + __proto__: null, + legacyCiphers: legacyCiphers +}); - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; +// SHA1 (RFC 3174). It was cryptographically broken: prefer newer algorithms. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA1 (RFC 3174) hash function. + * It was cryptographically broken: prefer newer algorithms. + * @param message - data that would be hashed + */ +const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i)); +const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = /* @__PURE__ */ new Uint32Array([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +const Kr = /* @__PURE__ */ new Uint32Array([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const R_BUF = /* @__PURE__ */ new Uint32Array(16); +class RIPEMD160 extends HashMD { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + R_BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + R_BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); -// Compatibility with BaseCurve -Point$2.prototype.toP = Point$2.prototype.normalize; -Point$2.prototype.mixedAdd = Point$2.prototype.add; +/** + * This file is needed to dynamic import the noble-hashes. + * Separate dynamic imports are not convenient as they result in too many chunks, + * which share a lot of code anyway. + */ -var curve_1 = createCommonjsModule(function (module, exports) { -var curve = exports; +const nobleHashes = new Map(Object.entries({ + sha1, + sha224, + sha256, + sha384, + sha512, + sha3_256, + sha3_512, + ripemd160 +})); -curve.base = base; -curve.short = short_1; -curve.mont = mont; -curve.edwards = edwards; +var noble_hashes = /*#__PURE__*/Object.freeze({ + __proto__: null, + nobleHashes: nobleHashes }); -var rotl32$2 = utils.rotl32; -var sum32$3 = utils.sum32; -var sum32_5$2 = utils.sum32_5; -var ft_1$1 = common$1.ft_1; -var BlockHash$4 = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; +// Adapted from the reference implementation in RFC7693 +// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); +// Uint64 values are represented using two Uint32s, stored as little endian +// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays +// need to be manually handled - BlockHash$4.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); +// 64-bit unsigned addition (little endian, in place) +// Sets a[i,i+1] += b[j,j+1] +// `a` and `b` must be Uint32Array(2) +function ADD64 (a, i, b, j) { + a[i] += b[j]; + a[i+1] += b[j+1] + (a[i] < b[j]); // add carry } -utils.inherits(SHA1, BlockHash$4); -var _1 = SHA1; +// Increment 64-bit little-endian unsigned value by `c` (in place) +// `a` must be Uint32Array(2) +function INC64 (a, c) { + a[0] += c; + a[1] += (a[0] < c); +} -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; +// G Mixing function +// The ROTRs are inlined for speed +function G$1 (v, m, a, b, c, d, ix, iy) { + ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1] + ADD64(v, a, m, ix); // v[a, a+1] += x ... x0 -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + ADD64(v, c, v, d); - for(; i < W.length; i++) - W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor0 >>> 24) ^ (xor1 << 8); + v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; + ADD64(v, a, v, b); + ADD64(v, a, m, iy); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$2(b, 30); - b = a; - a = t; - } + // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = (xor0 >>> 16) ^ (xor1 << 16); + v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); - this.h[0] = sum32$3(this.h[0], a); - this.h[1] = sum32$3(this.h[1], b); - this.h[2] = sum32$3(this.h[2], c); - this.h[3] = sum32$3(this.h[3], d); - this.h[4] = sum32$3(this.h[4], e); -}; + ADD64(v, c, v, d); -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; + // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = (xor1 >>> 31) ^ (xor0 << 1); + v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); +} -var sha1 = _1; -var sha224 = _224; -var sha256 = _256; -var sha384 = _384; -var sha512 = _512; - -var sha = { - sha1: sha1, - sha224: sha224, - sha256: sha256, - sha384: sha384, - sha512: sha512 -}; +// Initialization Vector +const BLAKE2B_IV32 = new Uint32Array([ + 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, + 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, + 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, + 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 +]); -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -var hmac = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; +// These are offsets into a Uint64 buffer. +// Multiply them all by 2 to make them offsets into a Uint32 buffer +const SIGMA = new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 +].map(x => x * 2)); + +// Compression function. 'last' flag indicates last block. +// Note: we're representing 16 uint64s as 32 uint32s +function compress(S, last) { + const v = new Uint32Array(32); + const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32); + + // init work variables + for (let i = 0; i < 16; i++) { + v[i] = S.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + + // low 64 bits of offset + v[24] ^= S.t0[0]; + v[25] ^= S.t0[1]; + // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1 + + // if last block + const f0 = last ? 0xFFFFFFFF : 0; + v[28] ^= f0; + v[29] ^= f0; + + // twelve rounds of mixing + for (let i = 0; i < 12; i++) { + // ROUND(r) + const i16 = i << 4; + G$1(v, m, 0, 8, 16, 24, SIGMA[i16 + 0], SIGMA[i16 + 1]); + G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]); + G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]); + G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]); + G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]); + G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]); + G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]); + G$1(v, m, 6, 8, 18, 28, SIGMA[i16 + 14], SIGMA[i16 + 15]); + } + + for (let i = 0; i < 16; i++) { + S.h[i] ^= v[i] ^ v[i + 16]; + } +} + +// Creates a BLAKE2b hashing context +// Requires an output length between 1 and 64 bytes +// Takes an optional Uint8Array key +class Blake2b { + constructor(outlen, key, salt, personal) { + const params = new Uint8Array(64); + // 0: outlen, keylen, fanout, depth + // 4: leaf length, sequential mode + // 8: node offset + // 12: node offset + // 16: node depth, inner length, rfu + // 20: rfu + // 24: rfu + // 28: rfu + // 32: salt + // 36: salt + // 40: salt + // 44: salt + // 48: personal + // 52: personal + // 56: personal + // 60: personal + + // init internal state + this.S = { + b: new Uint8Array(BLOCKBYTES), + h: new Uint32Array(OUTBYTES_MAX / 4), + t0: new Uint32Array(2), // input counter `t`, lower 64-bits only + c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES` + outlen // output length in bytes + }; -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; + // init parameter block + params[0] = outlen; + if (key) params[1] = key.length; + params[2] = 1; // fanout + params[3] = 1; // depth + if (salt) params.set(salt, 32); + if (personal) params.set(personal, 48); + const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT); -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; + // initialize hash state + for (let i = 0; i < 16; i++) { + this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i]; + } -var hash_1 = createCommonjsModule(function (module, exports) { -var hash = exports; - -hash.utils = utils; -hash.common = common; -hash.sha = sha; -hash.ripemd = ripemd; -hash.hmac = hmac; - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; -}); + // key the hash, if applicable + if (key) { + const block = new Uint8Array(BLOCKBYTES); + block.set(key); + this.update(block); + } + } -var secp256k1 = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] + // Updates a BLAKE2b streaming hash + // Requires Uint8Array (byte array) + update(input) { + if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer') + // for (let i = 0; i < input.length; i++) { + // if (this.S.c === BLOCKBYTES) { // buffer full + // INC64(this.S.t0, this.S.c) // add counters + // compress(this.S, false) + // this.S.c = 0 // empty buffer + // } + // this.S.b[this.S.c++] = input[i] + // } + let i = 0; + while(i < input.length) { + if (this.S.c === BLOCKBYTES) { // buffer full + INC64(this.S.t0, this.S.c); // add counters + compress(this.S, false); + this.S.c = 0; // empty buffer + } + let left = BLOCKBYTES - this.S.c; + this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds + const fill = Math.min(left, input.length - i); + this.S.c += fill; + i += fill; + } + return this } -}; -var curves_1 = createCommonjsModule(function (module, exports) { + /** + * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one + * @param {Uint8Array} [prealloc] - optional preallocated buffer + * @returns {ArrayBuffer} message digest + */ + digest(prealloc) { + INC64(this.S.t0, this.S.c); // mark last block offset + + // final block, padded + this.S.b.fill(0, this.S.c); + this.S.c = BLOCKBYTES; + compress(this.S, true); + + const out = prealloc || new Uint8Array(this.S.outlen); + for (let i = 0; i < this.S.outlen; i++) { + // must be loaded individually since default Uint32 endianness is platform dependant + out[i] = this.S.h[i >> 2] >> (8 * (i & 3)); + } + this.S.h = null; // prevent calling `update` after `digest` + return out.buffer; + } +} -var curves = exports; +function createHash(outlen, key, salt, personal) { + if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`) + return new Blake2b(outlen, key, salt, personal) +} +const OUTBYTES_MAX = 64; +const BLOCKBYTES = 128; +const TYPE = 2; // Argon2id +const VERSION = 0x13; +const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1; +const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; +const SALTBYTES_MIN = 8; +const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const passwordBYTES_MIN = 8; +const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1; +const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional) +const SECRETBYTES_MAX = 32; // key (optional) -var assert = utils_1$1.assert; +const ARGON2_BLOCK_SIZE = 1024; +const ARGON2_PREHASH_DIGEST_LENGTH = 64; -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve_1.short(options); - else if (options.type === 'edwards') - this.curve = new curve_1.edwards(options); - else if (options.type === 'mont') - this.curve = new curve_1.mont(options); - else throw new Error('Unknown curve type.'); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; +const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); +// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3]) +function LE32(buf, n, i) { + buf[i+0] = n; + buf[i+1] = n >> 8; + buf[i+2] = n >> 16; + buf[i+3] = n >> 24; + return buf; } -curves.PresetCurve = PresetCurve; -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); +/** + * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7]) + * @param {Uint8Array} buf + * @param {Number} n + * @param {Number} i + */ +function LE64(buf, n, i) { + if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported"); + // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations + // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps) + // so we manually extract each byte + let remainder = n; + for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER + buf[offset] = remainder; // implicit & 0xff + remainder = (remainder - buf[offset]) / 256; + } + return buf; } -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash_1.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); +/** + * Variable-Length Hash Function H' + * @param {Number} outlen - T + * @param {Uint8Array} X - value to hash + * @param {Uint8Array} res - output buffer, of length `outlength` or larger + */ +function H_(outlen, X, res) { + const V = new Uint8Array(64); // no need to keep around all V_i -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash_1.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); + const V1_in = new Uint8Array(4 + X.length); + LE32(V1_in, outlen, 0); + V1_in.set(X, 4); + if (outlen <= 64) { + // H'^T(A) = H^T(LE32(T)||A) + createHash(outlen).update(V1_in).digest(res); + return res + } -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash_1.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); + const r = Math.ceil(outlen / 32) - 2; -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash_1.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); + // Let V_i be a 64-byte block and W_i be its first 32 bytes. + // V_1 = H^(64)(LE32(T)||A) + // V_2 = H^(64)(V_1) + // ... + // V_r = H^(64)(V_{r-1}) + // V_{r+1} = H^(T-32*r)(V_{r}) + // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1} + for (let i = 0; i < r; i++) { + createHash(64).update(i === 0 ? V1_in : V).digest(V); + // store W_i in result buffer already + res.set(V.subarray(0, 32), i*32); + } + // V_{r+1} + const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest()); + res.set(V_r1, r*32); -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash_1.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); + return res; +} -// https://tools.ietf.org/html/rfc7748#section-4.1 -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '9' - ] -}); +// compute buf = xs ^ ys +function XOR(wasmContext, buf, xs, ys) { + wasmContext.fn.XOR( + buf.byteOffset, + xs.byteOffset, + ys.byteOffset, + ); + return buf +} -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - cofactor: '8', - hash: hash_1.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); +/** + * @param {Uint8Array} X (read-only) + * @param {Uint8Array} Y (read-only) + * @param {Uint8Array} R - output buffer + * @returns + */ +function G(wasmContext, X, Y, R) { + wasmContext.fn.G( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} -// https://tools.ietf.org/html/rfc5639#section-3.4 -defineCurve('brainpoolP256r1', { - type: 'short', - prime: null, - p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377', - a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9', - b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6', - n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7', - hash: hash_1.sha256, // or 384, or 512 - gRed: false, - g: [ - '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262', - '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997' - ] -}); +function G2(wasmContext, X, Y, R) { + wasmContext.fn.G2( + X.byteOffset, + Y.byteOffset, + R.byteOffset, + wasmContext.refs.gZ.byteOffset + ); + return R; +} + +// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values. +function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) { + // For each segment, we do the following. First, we compute the value Z as: + // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) ) + wasmContext.refs.prngTmp.fill(0); + const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8); + LE64(Z, pass, 0); + LE64(Z, lane, 8); + LE64(Z, slice, 16); + LE64(Z, m_, 24); + LE64(Z, totalPasses, 32); + LE64(Z, TYPE, 40); + + // Then we compute q/(128*SL) 1024-byte values + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ), + // ..., + // G( ZERO(1024), + // G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )), + for(let i = 1; i <= segmentLength; i++) { + // tmp.set(Z); // no need to re-copy + LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed + const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR ); + + // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2 + // NB: the first generated pair must be used for the first block of the segment, and so on. + // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset. + for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) { + yield g2.subarray(k, k+8); + } + } + return []; +} + +function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) { + const assertLength = (name, value, min, max) => { + if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); } + }; -// https://tools.ietf.org/html/rfc5639#section-3.6 -defineCurve('brainpoolP384r1', { - type: 'short', - prime: null, - p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' + - 'ACD3A729 901D1A71 87470013 3107EC53', - a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' + - '8AA5814A 503AD4EB 04A8C7DD 22CE2826', - b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' + - '7CB43902 95DBC994 3AB78696 FA504C11', - n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' + - 'CF3AB6AF 6B7FC310 3B883202 E9046565', - hash: hash_1.sha384, // or 512 - gRed: false, - g: [ - '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' + - 'E8E826E03436D646AAEF87B2E247D4AF1E', - '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' + - '280E4646217791811142820341263C5315' - ] -}); + if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version'); + assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX); + assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX); + assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX); + assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX); + // optional fields + ad && assertLength('associated data', ad, 0, ADBYTES_MAX); + secret && assertLength('secret', secret, 0, SECRETBYTES_MAX); -// https://tools.ietf.org/html/rfc5639#section-3.7 -defineCurve('brainpoolP512r1', { - type: 'short', - prime: null, - p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' + - '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3', - a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' + - '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA', - b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' + - '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723', - n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' + - '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069', - hash: hash_1.sha512, - gRed: false, - g: [ - '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' + - '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', - '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' + - '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892' - ] -}); + return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes }; +} -// https://en.bitcoin.it/wiki/Secp256k1 -var pre; -try { - pre = secp256k1; -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash_1.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], +const KB = 1024; +const WASM_PAGE_SIZE = 64 * KB; - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); -}); +function argon2id(params, { memory, instance: wasmInstance }) { + if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + const ctx = validateParams({ type: TYPE, version: VERSION, ...params }); - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports; + const wasmRefs = {}; + const wasmFn = {}; + wasmFn.G = wasmG; + wasmFn.G2 = wasmG2; + wasmFn.XOR = wasmXOR; - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p. + const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes)); + const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references + if (memory.buffer.byteLength < requiredMemory) { + const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE); + // If enough memory is available, the `memory.buffer` is internally detached and the reference updated. + // Otherwise, the operation fails, and the original memory can still be used. + memory.grow(missing); + } - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils_1.toArray(options.pers, options.persEnc || 'hex'); - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -var hmacDrbg = HmacDRBG; + let offset = 0; + // Init wasm memory needed in other functions + wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length; + wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length; + wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length; + wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length; + // Init wasm memory needed locally + const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT; + const wasmContext = { fn: wasmFn, refs: wasmRefs }; + const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length; + const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE); + const allocatedMemory = new Uint8Array(memory.buffer, 0, offset); + + // 1. Establish H_0 + const H0 = getH0(ctx); + + // 2. Allocate the memory as m' 1024-byte blocks + // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns. + const q = m_ / ctx.lanes; + const B = new Array(ctx.lanes).fill(null).map(() => new Array(q)); + const initBlock = (i, j) => { + B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE); + return B[i][j]; + }; -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + for (let i = 0; i < ctx.lanes; i++) { + // const LEi = LE0; // since p = 1 for us + const tmp = new Uint8Array(H0.length + 8); + // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0)); + // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + LE32(tmp, 1, H0.length); + H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1)); + } + + // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2 + // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes + // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc. + const SL = 4; // vertical slices + const segmentLength = q / SL; + for (let pass = 0; pass < ctx.passes; pass++) { + // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel + for (let sl = 0; sl < SL; sl++) { + const isDataIndependent = pass === 0 && sl <= 1; + for (let i = 0; i < ctx.lanes; i++) { // lane + // On the first slice of the first pass, blocks 0 and 1 are already filled + let segmentOffset = sl === 0 && pass === 0 ? 2 : 0; + // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory) + const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null; + for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) { + const j = sl * segmentLength + segmentOffset; + const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q] + + // we can assume the PRNG is never done + const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength); + const l = lz[0]; const z = lz[1]; + // for (let i = 0; i < p; i++ ) + // B[i][j] = G(B[i][j-1], B[l][z]) + // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id. + if (pass === 0) initBlock(i, j); + G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]); + + // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one + if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]); + } + } + } + } + + // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column: + // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1] + const C = B[0][q-1]; + for(let i = 1; i < ctx.lanes; i++) { + XOR(wasmContext, C, C, B[i][q-1]); + } + + const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength)); + // clear memory since the module might be cached + allocatedMemory.fill(0); // clear sensitive contents + memory.grow(0); // allow deallocation + // 8. The output tag is computed as H'^T(C). + return tag; + +} + +function getH0(ctx) { + const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH); + const ZERO32 = new Uint8Array(4); + const params = new Uint8Array(24); + LE32(params, ctx.lanes, 0); + LE32(params, ctx.tagLength, 4); + LE32(params, ctx.memorySize, 8); + LE32(params, ctx.passes, 12); + LE32(params, ctx.version, 16); + LE32(params, ctx.type, 20); + + const toHash = [params]; + if (ctx.password) { + toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0)); + toHash.push(ctx.password); + } else { + toHash.push(ZERO32); // context.password.length + } - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; + if (ctx.salt) { + toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0)); + toHash.push(ctx.salt); + } else { + toHash.push(ZERO32); // context.salt.length } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; + if (ctx.secret) { + toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0)); + toHash.push(ctx.secret); + // todo clear secret? + } else { + toHash.push(ZERO32); // context.secret.length + } -HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); -}; + if (ctx.ad) { + toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0)); + toHash.push(ctx.ad); + } else { + toHash.push(ZERO32); // context.ad.length + } + H.update(concatArrays(toHash)); -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; + const outputBuffer = H.digest(); + return new Uint8Array(outputBuffer); +} - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; +function concatArrays(arrays) { + if (arrays.length === 1) return arrays[0]; -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; + let totalLength = 0; + for (let i = 0; i < arrays.length; i++) { + if (!(arrays[i] instanceof Uint8Array)) { + throw new Error('concatArrays: Data must be in the form of a Uint8Array'); + } + + totalLength += arrays[i].length; } - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); + const result = new Uint8Array(totalLength); + let pos = 0; + arrays.forEach((element) => { + result.set(element, pos); + pos += element.length; + }); + + return result; +} + +let isSIMDSupported; +async function wasmLoader(memory, getSIMD, getNonSIMD) { + const importObject = { env: { memory } }; + if (isSIMDSupported === undefined) { + try { + const loaded = await getSIMD(importObject); + isSIMDSupported = true; + return loaded; + } catch(e) { + isSIMDSupported = false; + } + } - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + const loader = isSIMDSupported ? getSIMD : getNonSIMD; + return loader(importObject); +} - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; +async function setupWasm(getSIMD, getNonSIMD) { + const memory = new WebAssembly.Memory({ + // in pages of 64KiB each + // these values need to be compatible with those declared when building in `build-wasm` + initial: 1040, // 65MB + maximum: 65536, // 4GB + }); + const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD); -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); + /** + * Argon2id hash function + * @callback computeHash + * @param {Object} params + * @param {Uint8Array} params.password - password + * @param {Uint8Array} params.salt - salt + * @param {Integer} params.parallelism + * @param {Integer} params.passes + * @param {Integer} params.memorySize - in kibibytes + * @param {Integer} params.tagLength - output tag length + * @param {Uint8Array} [params.ad] - associated data (optional) + * @param {Uint8Array} [params.secret] - secret data (optional) + * @return {Uint8Array} argon2id hash + */ + const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory }); - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } + return computeHash; +} - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } +function _loadWasmModule (sync, filepath, src, imports) { + function _instantiateOrCompile(source, imports, stream) { + var instantiateFunc = WebAssembly.instantiate; + var compileFunc = WebAssembly.compile; - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); + if (imports) { + return instantiateFunc(source, imports) + } else { + return compileFunc(source) + } } - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils_1.encode(res, enc); -}; + +var buf = null; + + +var raw = globalThis.atob(src); +var rawLength = raw.length; +buf = new Uint8Array(new ArrayBuffer(rawLength)); +for(var i = 0; i < rawLength; i++) { + buf[i] = raw.charCodeAt(i); +} -var assert$5 = utils_1$1.assert; -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); + { + return _instantiateOrCompile(buf, imports) + } } -var key = KeyPair; -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; +function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEUCIG/c4BIAkgCf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAX9USIFQSj9ywEgBUEY/c0B/VA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JCgv93gFBAf3LAf3OASIJ/QsEgAUgACAEIAf9USIFQQH9ywEgBUE//c0B/VAiBSAJIAr9USIEQQH9ywEgBEE//c0B/VAiBCAE/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/QsEgAIgACAEIAUgBf0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eH/0LBIADIBBBAWoiEEEIRw0AC0EAIRADQCACIBBBBHQiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACACIABBEHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBIHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBMHIiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)} - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; +function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)} -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; +const loadWasm = async () => setupWasm( + (instanceObject) => wasmSIMD(instanceObject), + (instanceObject) => wasmNonSIMD(instanceObject), +); - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; +var index$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: loadWasm +}); -// TODO: should not validate for X25519 -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); +/* +node-bzip - a pure-javascript Node.JS module for decoding bzip2 data - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; +Copyright (C) 2012 Eli Skeggs - return { result: true, reason: null }; -}; +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. -KeyPair.prototype.getPublic = function getPublic(enc, compact) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. - if (!enc) - return this.pub; +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html - return this.pub.encode(enc, compact); -}; +Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com). -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; +Based on micro-bunzip by Rob Landley (rob@landley.net). -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new bn(key, enc || 16); - - // For Curve25519/Curve448 we have a specific procedure. - // TODO Curve448 - if (this.ec.curve.type === 'mont') { - var one = this.ec.curve.one; - var mask = one.ushln(255 - 3).sub(one).ushln(3); - this.priv = this.priv.or(one.ushln(255 - 1)); - this.priv = this.priv.and(mask); - } else - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; +var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF]; -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); +// offset in bytes +var BitReader$1 = function(stream) { + this.stream = stream; + this.bitOffset = 0; + this.curByte = 0; + this.hasByte = false; }; -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); +BitReader$1.prototype._ensureByte = function() { + if (!this.hasByte) { + this.curByte = this.stream.readByte(); + this.hasByte = true; + } }; -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); +// reads bits from the buffer +BitReader$1.prototype.read = function(bits) { + var result = 0; + while (bits > 0) { + this._ensureByte(); + var remaining = 8 - this.bitOffset; + // if we're in a byte + if (bits >= remaining) { + result <<= remaining; + result |= BITMASK[remaining] & this.curByte; + this.hasByte = false; + this.bitOffset = 0; + bits -= remaining; + } else { + result <<= bits; + var shift = remaining - bits; + result |= (this.curByte & (BITMASK[bits] << shift)) >> shift; + this.bitOffset += bits; + bits = 0; + } + } + return result; }; -KeyPair.prototype.inspect = function inspect() { - return ''; +// seek to an arbitrary point in the buffer (expressed in bits) +BitReader$1.prototype.seek = function(pos) { + var n_bit = pos % 8; + var n_byte = (pos - n_bit) / 8; + this.bitOffset = n_bit; + this.stream.seek(n_byte); + this.hasByte = false; }; -var assert$6 = utils_1$1.assert; - -function Signature$1(options, enc) { - if (options instanceof Signature$1) - return options; - - if (this._importDER(options, enc)) - return; +// reads 6 bytes worth of data using the read method +BitReader$1.prototype.pi = function() { + var buf = new Uint8Array(6), i; + for (i = 0; i < buf.length; i++) { + buf[i] = this.read(8); + } + return bufToHex(buf); +}; - assert$6(options.r && options.s, 'Signature without r or s'); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; +function bufToHex(buf) { + return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join(''); } -var signature$1 = Signature$1; -function Position() { - this.place = 0; -} +var bitreader = BitReader$1; -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} +/* very simple input/output stream interface */ -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} +var Stream$1 = function() { +}; -Signature$1.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); +// input streams ////////////// +/** Returns the next byte, or -1 for EOF. */ +Stream$1.prototype.readByte = function() { + throw new Error("abstract method readByte() not implemented"); +}; +/** Attempts to fill the buffer; returns number of bytes read, or + * -1 for EOF. */ +Stream$1.prototype.read = function(buffer, bufOffset, length) { + var bytesRead = 0; + while (bytesRead < length) { + var c = this.readByte(); + if (c < 0) { // EOF + return (bytesRead===0) ? -1 : bytesRead; + } + buffer[bufOffset++] = c; + bytesRead++; } - - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - - return true; + return bytesRead; +}; +Stream$1.prototype.seek = function(new_pos) { + throw new Error("abstract method seek() not implemented"); }; -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; +// output streams /////////// +Stream$1.prototype.writeByte = function(_byte) { + throw new Error("abstract method readByte() not implemented"); +}; +Stream$1.prototype.write = function(buffer, bufOffset, length) { + var i; + for (i=0; i>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature$1.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); + return length; +}; +Stream$1.prototype.flush = function() { }; -var assert$7 = utils_1$1.assert; +var stream = Stream$1; +/* CRC32, used in Bzip2 implementation. + * This is a port of CRC32.java from the jbzip2 implementation at + * https://code.google.com/p/jbzip2 + * which is: + * Copyright (c) 2011 Matthew Francis + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * This JavaScript implementation is: + * Copyright (c) 2013 C. Scott Ananian + * with the same licensing terms as Matthew Francis' original implementation. + */ +var crc32 = (function() { + /** + * A static CRC lookup table + */ + var crc32Lookup = new Uint32Array([ + 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, + 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, + 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, + 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, + 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, + 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, + 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, + 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, + 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, + 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, + 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, + 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, + 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, + 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, + 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, + 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, + 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 + ]); -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); + var CRC32 = function() { + /** + * The current CRC + */ + var crc = 0xffffffff; - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options); + /** + * @return The current CRC + */ + this.getCRC = function() { + return (~crc) >>> 0; // return an unsigned value + }; - options = curves_1[options]; - } + /** + * Update the CRC with a single byte + * @param value The value to update the CRC with + */ + this.updateCRC = function(value) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + }; - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves_1.PresetCurve) - options = { curve: options }; + /** + * Update the CRC with a sequence of identical bytes + * @param value The value to update the CRC with + * @param count The number of bytes + */ + this.updateCRCRun = function(value, count) { + while (count-- > 0) { + crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff]; + } + }; + }; + return CRC32; +})(); - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; +/* +seek-bzip - a pure-javascript module for seeking within bzip2 data - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); +Copyright (C) 2013 C. Scott Ananian +Copyright (C) 2012 Eli Skeggs +Copyright (C) 2011 Kevin Kwok - // Hash function for DRBG - this.hash = options.hash || options.curve.hash; -} -var ec = EC; +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. -EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); -}; +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); -}; +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, see +http://www.gnu.org/licenses/lgpl-2.1.html -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); -}; +Adapted from node-bzip, copyright 2012 Eli Skeggs. +Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com). -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); +Based on micro-bunzip by Rob Landley (rob@landley.net). - // Key generation for curve25519 is simpler - if (this.curve.type === 'mont') { - var priv = new bn(drbg.generate(32)); - return this.keyFromPrivate(priv); - } +Based on bzip2 decompression code by Julian R Seward (jseward@acm.org), +which also acknowledges contributions by Mike Burrows, David Wheeler, +Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten, +Robert Sedgewick, and Jon L. Bentley. +*/ - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; +var BitReader = bitreader; +var Stream = stream; +var CRC32 = crc32; - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; +var MAX_HUFCODE_BITS = 20; +var MAX_SYMBOLS = 258; +var SYMBOL_RUNA = 0; +var SYMBOL_RUNB = 1; +var MIN_GROUPS = 2; +var MAX_GROUPS = 6; +var GROUP_SIZE = 50; -EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) { - bitSize = bitSize || msg.byteLength() * 8; - var delta = bitSize - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; +var WHOLEPI = "314159265359"; +var SQRTPI = "177245385090"; -EC.prototype.truncateMsg = function truncateMSG(msg) { - // Bit size is only determined correctly for Uint8Arrays and hex strings - var bitSize; - if (msg instanceof Uint8Array) { - bitSize = msg.byteLength * 8; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else if (typeof msg === 'string') { - bitSize = msg.length * 4; - msg = this._truncateToN(new bn(msg, 16), false, bitSize); - } else { - msg = this._truncateToN(new bn(msg, 16)); +var mtf = function(array, index) { + var src = array[index], i; + for (i = index; i > 0; i--) { + array[i] = array[i-1]; } - return msg; + array[0] = src; + return src; }; -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this.truncateMsg(msg); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); +var Err = { + OK: 0, + LAST_BLOCK: -1, + NOT_BZIP_DATA: -2, + UNEXPECTED_INPUT_EOF: -3, + UNEXPECTED_OUTPUT_EOF: -4, + DATA_ERROR: -5, + OUT_OF_MEMORY: -6, + OBSOLETE_INPUT: -7, + END_OF_BLOCK: -8 +}; +var ErrorMessages = {}; +ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum"; +ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data"; +ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF"; +ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF"; +ErrorMessages[Err.DATA_ERROR] = "Data error"; +ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory"; +ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported."; - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; +var _throw = function(status, optDetail) { + var msg = ErrorMessages[status] || 'unknown error'; + if (optDetail) { msg += ': '+optDetail; } + var e = new TypeError(msg); + e.errorCode = status; + throw e; +}; - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; +var Bunzip = function(inputStream, outputStream) { + this.writePos = this.writeCurrent = this.writeCount = 0; - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + this._start_bunzip(inputStream, outputStream); +}; +Bunzip.prototype._init_block = function() { + var moreBlocks = this._get_next_block(); + if ( !moreBlocks ) { + this.writeCount = -1; + return false; /* no more blocks */ + } + this.blockCRC = new CRC32(); + return true; +}; +/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */ +Bunzip.prototype._start_bunzip = function(inputStream, outputStream) { + /* Ensure that file starts with "BZh['1'-'9']." */ + var buf = new Uint8Array(4); + if (inputStream.read(buf, 0, 4) !== 4 || + String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') + _throw(Err.NOT_BZIP_DATA, 'bad magic'); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + var level = buf[3] - 0x30; + if (level < 1 || level > 9) + _throw(Err.NOT_BZIP_DATA, 'level out of range'); - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + this.reader = new BitReader(inputStream); - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; + /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of + uncompressed data. Allocate intermediate buffer for block. */ + this.dbufSize = 100000 * level; + this.nextoutput = 0; + this.outputStream = outputStream; + this.streamCRC = 0; +}; +Bunzip.prototype._get_next_block = function() { + var i, j, k; + var reader = this.reader; + // this is get_next_block() function from micro-bunzip: + /* Read in header signature and CRC, then validate signature. + (last block signature means CRC is for whole file, return now) */ + var h = reader.pi(); + if (h === SQRTPI) { // last block + return false; /* no more blocks */ + } + if (h !== WHOLEPI) + _throw(Err.NOT_BZIP_DATA); + this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned) + this.streamCRC = (this.targetBlockCRC ^ + ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0; + /* We can add support for blockRandomised if anybody complains. There was + some code for this in busybox 1.0.0-pre3, but nobody ever noticed that + it didn't actually work. */ + if (reader.read(1)) + _throw(Err.OBSOLETE_INPUT); + var origPointer = reader.read(24); + if (origPointer > this.dbufSize) + _throw(Err.DATA_ERROR, 'initial position out of bounds'); + /* mapping table: if some byte values are never used (encoding things + like ascii text), the compression code removes the gaps to have fewer + symbols to deal with, and writes a sparse bitfield indicating which + values were present. We make a translation table to convert the symbols + back to the corresponding bytes. */ + var t = reader.read(16); + var symToByte = new Uint8Array(256), symTotal = 0; + for (i = 0; i < 16; i++) { + if (t & (1 << (0xF - i))) { + var o = i * 16; + k = reader.read(16); + for (j = 0; j < 16; j++) + if (k & (1 << (0xF - j))) + symToByte[symTotal++] = o + j; } - - return new signature$1({ r: r, s: s, recoveryParam: recoveryParam }); } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - key = this.keyFromPublic(key, enc); - signature = new signature$1(signature, 'hex'); - // Fallback to the old code - var ret = this._verify(this.truncateMsg(msg), signature, key) || - this._verify(this._truncateToN(new bn(msg, 16)), signature, key); - return ret; -}; -EC.prototype._verify = function _verify(msg, signature, key) { - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; + /* How many different huffman coding groups does this block use? */ + var groupCount = reader.read(3); + if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) + _throw(Err.DATA_ERROR); + /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding + group. Read in the group selector list, which is stored as MTF encoded + bit runs. (MTF=Move To Front, as each value is used it's moved to the + start of the list.) */ + var nSelectors = reader.read(15); + if (nSelectors === 0) + _throw(Err.DATA_ERROR); - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); + var mtfSymbol = new Uint8Array(256); + for (i = 0; i < groupCount; i++) + mtfSymbol[i] = i; - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + var selectors = new Uint8Array(nSelectors); // was 32768... - return p.getX().umod(this.n).cmp(r) === 0; + for (i = 0; i < nSelectors; i++) { + /* Get next value */ + for (j = 0; reader.read(1); j++) + if (j >= groupCount) _throw(Err.DATA_ERROR); + /* Decode MTF to get the next selector */ + selectors[i] = mtf(mtfSymbol, j); } - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; + /* Read the huffman coding tables for each group, which code for symTotal + literal symbols, plus two run symbols (RUNA, RUNB) */ + var symCount = symTotal + 2; + var groups = [], hufGroup; + for (j = 0; j < groupCount; j++) { + var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1); + /* Read huffman code lengths for each symbol. They're stored in + a way similar to mtf; record a starting value for the first symbol, + and an offset from the previous value for everys symbol after that. */ + t = reader.read(5); // lengths + for (i = 0; i < symCount; i++) { + for (;;) { + if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR); + /* If first bit is 0, stop. Else second bit indicates whether + to increment or decrement the value. */ + if(!reader.read(1)) + break; + if(!reader.read(1)) + t++; + else + t--; + } + length[i] = t; + } -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$7((3 & j) === j, 'The recovery param is more than two bits'); - signature = new signature$1(signature, enc); - - var n = this.n; - var e = new bn(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; + /* Find largest and smallest lengths in this group */ + var minLen, maxLen; + minLen = maxLen = length[0]; + for (i = 1; i < symCount; i++) { + if (length[i] > maxLen) + maxLen = length[i]; + else if (length[i] < minLen) + minLen = length[i]; + } -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new signature$1(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; + /* Calculate permute[], base[], and limit[] tables from length[]. + * + * permute[] is the lookup table for converting huffman coded symbols + * into decoded symbols. base[] is the amount to subtract from the + * value of a huffman symbol of a given length when using permute[]. + * + * limit[] indicates the largest numerical value a symbol with a given + * number of bits can have. This is how the huffman codes can vary in + * length: each code with a value>limit[length] needs another bit. + */ + hufGroup = {}; + groups.push(hufGroup); + hufGroup.permute = new Uint16Array(MAX_SYMBOLS); + hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2); + hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1); + hufGroup.minLen = minLen; + hufGroup.maxLen = maxLen; + /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */ + var pp = 0; + for (i = minLen; i <= maxLen; i++) { + temp[i] = hufGroup.limit[i] = 0; + for (t = 0; t < symCount; t++) + if (length[t] === i) + hufGroup.permute[pp++] = t; + } + /* Count symbols coded for at each bit length */ + for (i = 0; i < symCount; i++) + temp[length[i]]++; + /* Calculate limit[] (the largest symbol-coding value at each bit + * length, which is (previous limit<<1)+symbols at this level), and + * base[] (number of symbols to ignore at each bit length, which is + * limit minus the cumulative count of symbols coded for already). */ + pp = t = 0; + for (i = minLen; i < maxLen; i++) { + pp += temp[i]; + /* We read the largest possible symbol size and then unget bits + after determining how many we need, and those extra bits could + be set to anything. (They're noise from future symbols.) At + each level we're really only interested in the first few bits, + so here we set all the trailing to-be-ignored bits to 1 so they + don't affect the value>limit[length] comparison. */ + hufGroup.limit[i] = pp - 1; + pp <<= 1; + t += temp[i]; + hufGroup.base[i + 1] = pp - t; + } + hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */ + hufGroup.limit[maxLen] = pp + temp[maxLen] - 1; + hufGroup.base[minLen] = 0; + } + /* We've finished reading and digesting the block header. Now read this + block's huffman coded symbols from the file and undo the huffman coding + and run length encoding, saving the result into dbuf[dbufCount++]=uc */ - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { + /* Initialize symbol occurrence counters and symbol Move To Front table */ + var byteCount = new Uint32Array(256); + for (i = 0; i < 256; i++) + mtfSymbol[i] = i; + /* Loop through compressed symbols. */ + var runPos = 0, dbufCount = 0, selector = 0, uc; + var dbuf = this.dbuf = new Uint32Array(this.dbufSize); + symCount = 0; + for (;;) { + /* Determine which huffman coding group to use. */ + if (!(symCount--)) { + symCount = GROUP_SIZE - 1; + if (selector >= nSelectors) { _throw(Err.DATA_ERROR); } + hufGroup = groups[selectors[selector++]]; + } + /* Read next huffman-coded symbol. */ + i = hufGroup.minLen; + j = reader.read(i); + for (;;i++) { + if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); } + if (j <= hufGroup.limit[i]) + break; + j = (j << 1) | reader.read(1); + } + /* Huffman decode value to get nextSym (with bounds checking) */ + j -= hufGroup.base[i]; + if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); } + var nextSym = hufGroup.permute[j]; + /* We have now decoded the symbol, which indicates either a new literal + byte, or a repeated run of the most recent literal byte. First, + check if nextSym indicates a repeated run, and if so loop collecting + how many times to repeat the last literal. */ + if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) { + /* If this is the start of a new run, zero out counter */ + if (!runPos){ + runPos = 1; + t = 0; + } + /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at + each bit position, add 1 or 2 instead. For example, + 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. + You can make any bit pattern that way using 1 less symbol than + the basic or 0/1 method (except all bits 0, which would use no + symbols, but a run of length 0 doesn't mean anything in this + context). Thus space is saved. */ + if (nextSym === SYMBOL_RUNA) + t += runPos; + else + t += 2 * runPos; + runPos <<= 1; continue; } - - if (Qprime.eq(Q)) - return i; + /* When we hit the first non-run symbol after a run, we now know + how many times to repeat the last literal, so append that many + copies to our buffer of decoded symbols (dbuf) now. (The last + literal used is the one at the head of the mtfSymbol array.) */ + if (runPos){ + runPos = 0; + if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); } + uc = symToByte[mtfSymbol[0]]; + byteCount[uc] += t; + while (t--) + dbuf[dbufCount++] = uc; + } + /* Is this the terminating symbol? */ + if (nextSym > symTotal) + break; + /* At this point, nextSym indicates a new literal character. Subtract + one to get the position in the MTF array at which this literal is + currently to be found. (Note that the result can't be -1 or 0, + because 0 and 1 are RUNA and RUNB. But another instance of the + first symbol in the mtf array, position 0, would have been handled + as part of a run above. Therefore 1 unused mtf position minus + 2 non-literal nextSym values equals -1.) */ + if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); } + i = nextSym - 1; + uc = mtf(mtfSymbol, i); + uc = symToByte[uc]; + /* We have our literal byte. Save it into dbuf. */ + byteCount[uc]++; + dbuf[dbufCount++] = uc; } - throw new Error('Unable to find valid recovery factor'); -}; - -var assert$8 = utils_1$1.assert; -var parseBytes = utils_1$1.parseBytes; -var cachedProperty = utils_1$1.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair$1(eddsa, params) { - this.eddsa = eddsa; - if (params.hasOwnProperty('secret')) - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else { - this._pubBytes = parseBytes(params.pub); - if (this._pubBytes && this._pubBytes.length === 33 && - this._pubBytes[0] === 0x40) - this._pubBytes = this._pubBytes.slice(1, 33); - if (this._pubBytes && this._pubBytes.length !== 32) - throw new Error('Unknown point compression format'); - } -} - -KeyPair$1.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$1) - return pub; - return new KeyPair$1(eddsa, { pub: pub }); -}; - -KeyPair$1.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$1) - return secret; - return new KeyPair$1(eddsa, { secret: secret }); -}; - -KeyPair$1.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair$1, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair$1, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair$1, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair$1, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair$1.prototype.sign = function sign(message) { - assert$8(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair$1.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair$1.prototype.getSecret = function getSecret(enc) { - assert$8(this._secret, 'KeyPair is public only'); - return utils_1$1.encode(this.secret(), enc); -}; - -KeyPair$1.prototype.getPublic = function getPublic(enc, compact) { - return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); -}; - -var key$1 = KeyPair$1; - -var assert$9 = utils_1$1.assert; -var cachedProperty$1 = utils_1$1.cachedProperty; -var parseBytes$1 = utils_1$1.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature$2(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; + /* At this point, we've read all the huffman-coded symbols (and repeated + runs) for this block from the input stream, and decoded them into the + intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. + Now undo the Burrows-Wheeler transform on dbuf. + See http://dogma.net/markn/articles/bwt/bwt.htm + */ + if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); } + /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ + j = 0; + for (i = 0; i < 256; i++) { + k = j + byteCount[i]; + byteCount[i] = j; + j = k; } + /* Figure out what order dbuf would be in if we sorted it. */ + for (i = 0; i < dbufCount; i++) { + uc = dbuf[i] & 0xff; + dbuf[byteCount[uc]] |= (i << 8); + byteCount[uc]++; + } + /* Decode first byte by hand to initialize "previous" byte. Note that it + doesn't get output, and if the first three characters are identical + it doesn't qualify as a run (hence writeRunCountdown=5). */ + var pos = 0, current = 0, run = 0; + if (dbufCount) { + pos = dbuf[origPointer]; + current = (pos & 0xff); + pos >>= 8; + run = -1; + } + this.writePos = pos; + this.writeCurrent = current; + this.writeCount = dbufCount; + this.writeRun = run; - assert$9(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof bn) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty$1(Signature$2, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty$1(Signature$2, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature$2.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature$2.prototype.toHex = function toHex() { - return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -var signature$2 = Signature$2; - -var assert$a = utils_1$1.assert; -var parseBytes$2 = utils_1$1.parseBytes; - - - -function EDDSA(curve) { - assert$a(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = curves_1[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash_1.sha512; -} - -var eddsa$1 = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes$2(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); + return true; /* more blocks to come */ }; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message +/* Undo burrows-wheeler transform on intermediate buffer to produce output. + If start_bunzip was initialized with out_fd=-1, then up to len bytes of + data are written to outbuf. Return value is number of bytes written or + error (all errors are negative numbers). If out_fd!=-1, outbuf and len + are ignored, data is written to out_fd and return is RETVAL_OK or error. */ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes$2(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n); -}; +Bunzip.prototype._read_bunzip = function(outputBuffer, len) { + var copies, previous, outbyte; + /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully + decoded, which results in this returning RETVAL_LAST_BLOCK, also + equal to -1... Confusing, I'm returning 0 here to indicate no + bytes written into the buffer */ + if (this.writeCount < 0) { return 0; } + var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent; + var dbufCount = this.writeCount; this.outputsize; + var run = this.writeRun; -EDDSA.prototype.keyPair = function keyPair(options) { - return new key$1(this, options); + while (dbufCount) { + dbufCount--; + previous = current; + pos = dbuf[pos]; + current = pos & 0xff; + pos >>= 8; + if (run++ === 3){ + copies = current; + outbyte = previous; + current = -1; + } else { + copies = 1; + outbyte = current; + } + this.blockCRC.updateCRCRun(outbyte, copies); + while (copies--) { + this.outputStream.writeByte(outbyte); + this.nextoutput++; + } + if (current != previous) + run = 0; + } + this.writeCount = dbufCount; + // check CRC + if (this.blockCRC.getCRC() !== this.targetBlockCRC) { + _throw(Err.DATA_ERROR, "Bad block CRC "+ + "(got "+this.blockCRC.getCRC().toString(16)+ + " expected "+this.targetBlockCRC.toString(16)+")"); + } + return this.nextoutput; }; -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return key$1.fromPublic(this, pub); +var coerceInputStream = function(input) { + if ('readByte' in input) { return input; } + var inputStream = new Stream(); + inputStream.pos = 0; + inputStream.readByte = function() { return input[this.pos++]; }; + inputStream.seek = function(pos) { this.pos = pos; }; + inputStream.eof = function() { return this.pos >= input.length; }; + return inputStream; }; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return key$1.fromSecret(this, secret); +var coerceOutputStream = function(output) { + var outputStream = new Stream(); + var resizeOk = true; + if (output) { + if (typeof(output)==='number') { + outputStream.buffer = new Uint8Array(output); + resizeOk = false; + } else if ('writeByte' in output) { + return output; + } else { + outputStream.buffer = output; + resizeOk = false; + } + } else { + outputStream.buffer = new Uint8Array(16384); + } + outputStream.pos = 0; + outputStream.writeByte = function(_byte) { + if (resizeOk && this.pos >= this.buffer.length) { + var newBuffer = new Uint8Array(this.buffer.length*2); + newBuffer.set(this.buffer); + this.buffer = newBuffer; + } + this.buffer[this.pos++] = _byte; + }; + outputStream.getBuffer = function() { + // trim buffer + if (this.pos !== this.buffer.length) { + if (!resizeOk) + throw new TypeError('outputsize does not match decoded input'); + var newBuffer = new Uint8Array(this.pos); + newBuffer.set(this.buffer.subarray(0, this.pos)); + this.buffer = newBuffer; + } + return this.buffer; + }; + outputStream._coerced = true; + return outputStream; }; -EDDSA.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || brorand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.curve.n.toArray() - }); +/* Static helper functions */ +// 'input' can be a stream or a buffer +// 'output' can be a stream or a buffer or a number (buffer size) +const decode = function(input, output, multistream) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); - return this.keyFromSecret(drbg.generate(32)); + var bz = new Bunzip(inputStream, outputStream); + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; + if (bz._init_block()) { + bz._read_bunzip(); + } else { + var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned) + if (targetStreamCRC !== bz.streamCRC) { + _throw(Err.DATA_ERROR, "Bad stream CRC "+ + "(got "+bz.streamCRC.toString(16)+ + " expected "+targetStreamCRC.toString(16)+")"); + } + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + } else break; + } + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; +const decodeBlock = function(input, pos, output) { + // make a stream from a buffer, if necessary + var inputStream = coerceInputStream(input); + var outputStream = coerceOutputStream(output); + var bz = new Bunzip(inputStream, outputStream); + bz.reader.seek(pos); + /* Fill the decode buffer for the block */ + var moreBlocks = bz._get_next_block(); + if (moreBlocks) { + /* Init the CRC for writing */ + bz.blockCRC = new CRC32(); -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof signature$2) - return sig; - return new signature$2(this, sig); -}; + /* Zero this so the current byte from before the seek is not written */ + bz.writeCopies = 0; -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; + /* Decompress the block and write to stdout */ + bz._read_bunzip(); + // XXX keep writing? + } + if ('getBuffer' in outputStream) + return outputStream.getBuffer(); }; +/* Reads bzip2 file from stream or buffer `input`, and invoke + * `callback(position, size)` once for each bzip2 block, + * where position gives the starting position (in *bits*) + * and size gives uncompressed size of the block (in *bytes*). */ +const table = function(input, callback, multistream) { + // make a stream from a buffer, if necessary + var inputStream = new Stream(); + inputStream.delegate = coerceInputStream(input); + inputStream.pos = 0; + inputStream.readByte = function() { + this.pos++; + return this.delegate.readByte(); + }; + if (inputStream.delegate.eof) { + inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate); + } + var outputStream = new Stream(); + outputStream.pos = 0; + outputStream.writeByte = function() { this.pos++; }; -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils_1$1.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils_1$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; + var bz = new Bunzip(inputStream, outputStream); + var blockSize = bz.dbufSize; + while (true) { + if ('eof' in inputStream && inputStream.eof()) break; -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; + var position = inputStream.pos*8 + bz.reader.bitOffset; + if (bz.reader.hasByte) { position -= 8; } -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils_1$1.intFromLE(bytes); + if (bz._init_block()) { + var start = outputStream.pos; + bz._read_bunzip(); + callback(position, outputStream.pos - start); + } else { + bz.reader.read(32); // (but we ignore the crc) + if (multistream && + 'eof' in inputStream && + !inputStream.eof()) { + // note that start_bunzip will also resync the bit reader to next byte + bz._start_bunzip(inputStream, outputStream); + console.assert(bz.dbufSize === blockSize, + "shouldn't change block size within multistream file"); + } else break; + } + } }; -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; +var lib = { + Bunzip, + Stream, + Err, + decode, + decodeBlock, + table }; -var elliptic_1 = createCommonjsModule(function (module, exports) { - -var elliptic = exports; - -elliptic.utils = utils_1$1; -elliptic.rand = brorand; -elliptic.curve = curve_1; -elliptic.curves = curves_1; - -// Protocols -elliptic.ec = ec; -elliptic.eddsa = eddsa$1; -}); - -var elliptic$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': elliptic_1, - __moduleExports: elliptic_1 -}); +var index = /*#__PURE__*/_mergeNamespaces({ + __proto__: null +}, [lib]); -export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt$5 as decrypt, decryptKey, decryptSessionKeys, encrypt$5 as encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey$1 as generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign$6 as sign, unarmor, verify$6 as verify }; +export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PaddingPacket, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt, decryptKey, decryptSessionKeys, encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign, unarmor, verify }; diff --git a/app/node_modules/openpgp/lightweight/package.json b/app/node_modules/openpgp/lightweight/package.json index 134e03c9c..c141a35d3 100644 --- a/app/node_modules/openpgp/lightweight/package.json +++ b/app/node_modules/openpgp/lightweight/package.json @@ -1,5 +1,5 @@ { "name": "openpgp-lightweight", - "main": "../dist/lightweight/openpgp.min.mjs", + "browser": "../dist/lightweight/openpgp.min.mjs", "types": "../openpgp.d.ts" } diff --git a/app/node_modules/openpgp/openpgp.d.ts b/app/node_modules/openpgp/openpgp.d.ts index 56175b269..b4d54b5b3 100644 --- a/app/node_modules/openpgp/openpgp.d.ts +++ b/app/node_modules/openpgp/openpgp.d.ts @@ -1,3 +1,5 @@ +/* eslint-disable max-lines, @typescript-eslint/indent */ + /** * Type definitions for OpenPGP.js http://openpgpjs.org/ * @@ -7,9 +9,19 @@ * - Errietta Kostala */ -import type { WebStream as GenericWebStream, NodeStream as GenericNodeStream } from '@openpgp/web-stream-tools'; +import type { WebStream as GenericWebStream, NodeWebStream as GenericNodeWebStream } from '@openpgp/web-stream-tools'; + +/* ############## STREAM #################### */ +type Data = Uint8Array | string; +// web-stream-tools might end up supporting additional data types, so we re-declare the types +// to enforce the type contraint that we need. +export type WebStream = GenericWebStream; +export type NodeWebStream = GenericNodeWebStream; +export type Stream = WebStream | NodeWebStream; +export type MaybeStream = T | Stream; +type MaybeArray = T | Array; -/* ############## v5 KEY #################### */ +/* ############## KEY #################### */ // The Key and PublicKey types can be used interchangably since TS cannot detect the difference, as they have the same class properties. // The declared readKey(s) return type is Key instead of a PublicKey since it seems more obvious that a Key can be cast to a PrivateKey. export function readKey(options: { armoredKey: string, config?: PartialConfig }): Promise; @@ -54,8 +66,8 @@ export abstract class Key { // NB: the order of the `update` declarations matters, since PublicKey includes PrivateKey public update(sourceKey: PrivateKey, date?: Date, config?: Config): Promise; public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise; - public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise - public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise + public signPrimaryUser(privateKeys: PrivateKey[], date?: Date, userID?: UserID, config?: Config): Promise; + public signAllUsers(privateKeys: PrivateKey[], date?: Date, config?: Config): Promise; public verifyPrimaryKey(date?: Date, userID?: UserID, config?: Config): Promise; // throws on error public verifyPrimaryUser(publicKeys: PublicKey[], date?: Date, userIDs?: UserID, config?: Config): Promise<{ keyID: KeyID, valid: boolean | null }[]>; public verifyAllUsers(publicKeys?: PublicKey[], date?: Date, config?: Config): Promise<{ userID: string, keyID: KeyID, valid: boolean | null }[]>; @@ -82,7 +94,7 @@ export class PrivateKey extends PublicKey { public revoke(reason?: ReasonForRevocation, date?: Date, config?: Config): Promise; public isDecrypted(): boolean; public addSubkey(options: SubkeyOptions): Promise; - public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise + public getDecryptionKeys(keyID?: KeyID, date?: Date | null, userID?: UserID, config?: Config): Promise; public update(sourceKey: PublicKey, date?: Date, config?: Config): Promise; } @@ -98,9 +110,9 @@ export class Subkey { public getCreationTime(): Date; public getAlgorithmInfo(): AlgorithmInfo; public getKeyID(): KeyID; - public getExpirationTime(date?: Date, config?: Config): Promise + public getExpirationTime(date?: Date, config?: Config): Promise; public isRevoked(signature: SignaturePacket, key: AnyKeyPacket, date?: Date, config?: Config): Promise; - public update(subKey: Subkey, date?: Date, config?: Config): Promise + public update(subKey: Subkey, date?: Date, config?: Config): Promise; public revoke(primaryKey: SecretKeyPacket, reasonForRevocation?: ReasonForRevocation, date?: Date, config?: Config): Promise; } @@ -118,13 +130,13 @@ export interface PrimaryUser { selfCertification: SignaturePacket; } -type AlgorithmInfo = { +export type AlgorithmInfo = { algorithm: enums.publicKeyNames; bits?: number; curve?: EllipticCurveName; }; -/* ############## v5 SIG #################### */ +/* ############## SIG #################### */ export function readSignature(options: { armoredSignature: string, config?: PartialConfig }): Promise; export function readSignature(options: { binarySignature: Uint8Array, config?: PartialConfig }): Promise; @@ -143,7 +155,7 @@ interface VerificationResult { signature: Promise; } -/* ############## v5 CLEARTEXT #################### */ +/* ############## CLEARTEXT #################### */ export function readCleartextMessage(options: { cleartextMessage: string, config?: PartialConfig }): Promise; @@ -176,12 +188,12 @@ export class CleartextMessage { verify(keys: PublicKey[], date?: Date, config?: Config): Promise; } -/* ############## v5 MSG #################### */ +/* ############## MSG #################### */ export function generateSessionKey(options: { encryptionKeys: MaybeArray, date?: Date, encryptionUserIDs?: MaybeArray, config?: PartialConfig }): Promise; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format?: 'armored' }): Promise; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'binary' }): Promise; export function encryptSessionKey(options: EncryptSessionKeyOptions & { format: 'object' }): Promise>; -export function decryptSessionKeys>(options: { message: Message, decryptionKeys?: MaybeArray, passwords?: MaybeArray, date?: Date, config?: PartialConfig }): Promise; +export function decryptSessionKeys>(options: { message: Message, decryptionKeys?: MaybeArray, passwords?: MaybeArray, date?: Date, config?: PartialConfig }): Promise; export function readMessage>(options: { armoredMessage: T, config?: PartialConfig }): Promise>; export function readMessage>(options: { binaryMessage: T, config?: PartialConfig }): Promise>; @@ -190,25 +202,25 @@ export function createMessage>(options: { text: T, export function createMessage>(options: { binary: T, filename?: string, date?: Date, format?: enums.literalFormatNames }): Promise>; export function encrypt>(options: EncryptOptions & { message: Message, format?: 'armored' }): Promise< - T extends WebStream ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : string >; export function encrypt>(options: EncryptOptions & { message: Message, format: 'binary' }): Promise< - T extends WebStream ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : Uint8Array >; export function encrypt>(options: EncryptOptions & { message: Message, format: 'object' }): Promise>; export function sign>(options: SignOptions & { message: Message, format?: 'armored' }): Promise< - T extends WebStream ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : string >; export function sign>(options: SignOptions & { message: Message, format: 'binary' }): Promise< - T extends WebStream ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : Uint8Array >; export function sign>(options: SignOptions & { message: Message, format: 'object' }): Promise>; @@ -217,26 +229,26 @@ export function sign(options: SignOptions & { message: CleartextMessage, format: export function decrypt>(options: DecryptOptions & { message: Message, format: 'binary' }): Promise ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : Uint8Array }>; export function decrypt>(options: DecryptOptions & { message: Message }): Promise ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : string }>; export function verify(options: VerifyOptions & { message: CleartextMessage, format?: 'utf8' }): Promise>; export function verify>(options: VerifyOptions & { message: Message, format: 'binary' }): Promise ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : Uint8Array >>; export function verify>(options: VerifyOptions & { message: Message }): Promise ? WebStream : - T extends NodeStream ? NodeStream : + T extends WebStream ? WebStream : + T extends NodeWebStream ? NodeWebStream : string >>; @@ -263,7 +275,7 @@ export class Message> { /** Encrypt the message @param encryptionKeys array of public keys, used to encrypt the message */ - public encrypt(encryptionKeys?: PublicKey[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], config?: Config): Promise>>; + public encrypt(encryptionKeys?: PublicKey[], passwords?: string[], sessionKeys?: SessionKey[], wildcard?: boolean, encryptionKeyIDs?: KeyID[], date?: Date, userIDs?: UserID[], config?: Config): Promise>>; /** Returns the key IDs of the keys to which the session key is encrypted */ @@ -305,7 +317,7 @@ export class Message> { } -/* ############## v5 CONFIG #################### */ +/* ############## CONFIG #################### */ interface Config { preferredHashAlgorithm: enums.hash; @@ -313,44 +325,44 @@ interface Config { preferredCompressionAlgorithm: enums.compression; showVersion: boolean; showComment: boolean; - deflateLevel: number; aeadProtect: boolean; allowUnauthenticatedMessages: boolean; allowUnauthenticatedStream: boolean; - checksumRequired: boolean; minRSABits: number; passwordCollisionCheck: boolean; - revocationsExpire: boolean; ignoreUnsupportedPackets: boolean; ignoreMalformedPackets: boolean; versionString: string; commentString: string; allowInsecureDecryptionWithSigningKeys: boolean; allowInsecureVerificationWithReformattedKeys: boolean; + allowMissingKeyFlags: boolean; constantTimePKCS1Decryption: boolean; constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: Set; - v5Keys: boolean; + v6Keys: boolean; + enableParsingV5Entities: boolean; preferredAEADAlgorithm: enums.aead; aeadChunkSizeByte: number; + s2kType: enums.s2k.iterated | enums.s2k.argon2; s2kIterationCountByte: number; - minBytesForWebCrypto: number; + s2kArgon2Params: { passes: number, parallelism: number; memoryExponent: number; }; maxUserIDLength: number; knownNotations: string[]; - useIndutnyElliptic: boolean; + useEllipticFallback: boolean; rejectHashAlgorithms: Set; rejectMessageHashAlgorithms: Set; rejectPublicKeyAlgorithms: Set; rejectCurves: Set; } -export var config: Config; +export const config: Config; // PartialConfig has the same properties as Config, but declared as optional. // This interface is relevant for top-level functions, which accept a subset of configuration options -interface PartialConfig extends Partial {} +export interface PartialConfig extends Partial {} -/* ############## v5 PACKET #################### */ +/* ############## PACKET #################### */ -declare abstract class BasePacket { +export declare abstract class BasePacket { static readonly tag: enums.packet; public read(bytes: Uint8Array): void; public write(): Uint8Array; @@ -423,7 +435,7 @@ export class AEADEncryptedDataPacket extends BasePacket { static readonly tag: enums.packet.aeadEncryptedData; private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void; private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void; - private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream): MaybeStream + private crypt(fn: Function, sessionKey: Uint8Array, data: MaybeStream): MaybeStream; } export class PublicKeyEncryptedSessionKeyPacket extends BasePacket { @@ -486,7 +498,8 @@ export class SignaturePacket extends BasePacket { public hashAlgorithm: enums.hash | null; public publicKeyAlgorithm: enums.publicKey | null; public signatureData: null | Uint8Array; - public unhashedSubpackets: null | Uint8Array; + public unhashedSubpackets: RawSubpacket[]; + public unknownSubpackets: RawSubpacket[]; public signedHashValue: null | Uint8Array; public created: Date | null; public signatureExpirationTime: null | number; @@ -530,6 +543,12 @@ export class SignaturePacket extends BasePacket { public getExpirationTime(): Date | typeof Infinity; } +export interface RawSubpacket { + type: number; + critical: boolean; + body: Uint8Array; +} + export interface RawNotation { name: string; value: Uint8Array; @@ -560,16 +579,7 @@ export class PacketList extends Array { public findPacket(tag: enums.packet): T | undefined; } -/* ############## v5 STREAM #################### */ - -type Data = Uint8Array | string; -export interface WebStream extends GenericWebStream {} -export interface NodeStream extends GenericNodeStream {} -export type Stream = WebStream | NodeStream; -export type MaybeStream = T | Stream; - -/* ############## v5 GENERAL #################### */ -type MaybeArray = T | Array; +/* ############## GENERAL #################### */ export interface UserID { name?: string; email?: string; comment?: string; } export interface SessionKey { @@ -578,9 +588,14 @@ export interface SessionKey { aeadAlgorithm?: enums.aeadNames; } +export interface DecryptedSessionKey { + data: Uint8Array; + algorithm: enums.symmetricNames | null; // `null` if the session key is associated with a SEIPDv2 packet +} + export interface ReasonForRevocation { flag?: enums.reasonForRevocation, string?: string } -interface EncryptOptions { +export interface EncryptOptions { /** message to be encrypted as created by createMessage */ message: Message>; /** (optional) array of keys or single key, used to encrypt the message */ @@ -612,7 +627,7 @@ interface EncryptOptions { config?: PartialConfig; } -interface DecryptOptions { +export interface DecryptOptions { /** the message object with the encrypted data */ message: Message>; /** (optional) private keys with decrypted secret key data or session key */ @@ -634,7 +649,7 @@ interface DecryptOptions { config?: PartialConfig; } -interface SignOptions { +export interface SignOptions { message: CleartextMessage | Message>; signingKeys: MaybeArray; format?: 'armored' | 'binary' | 'object'; @@ -646,7 +661,7 @@ interface SignOptions { config?: PartialConfig; } -interface VerifyOptions { +export interface VerifyOptions { /** (cleartext) message object with signatures */ message: CleartextMessage | Message>; /** array of publicKeys or single key, to verify signatures */ @@ -662,7 +677,7 @@ interface VerifyOptions { config?: PartialConfig; } -interface EncryptSessionKeyOptions extends SessionKey { +export interface EncryptSessionKeyOptions extends SessionKey { encryptionKeys?: MaybeArray, passwords?: MaybeArray, format?: 'armored' | 'binary' | 'object', @@ -673,7 +688,7 @@ interface EncryptSessionKeyOptions extends SessionKey { config?: PartialConfig } -interface SerializedKeyPair { +interface SerializedKeyPair { privateKey: T; publicKey: T; } @@ -682,7 +697,7 @@ interface KeyPair { publicKey: PublicKey; } -export type EllipticCurveName = 'ed25519' | 'curve25519' | 'p256' | 'p384' | 'p521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1'; +export type EllipticCurveName = 'ed25519Legacy' | 'curve25519Legacy' | 'nistP256' | 'nistP384' | 'nistP521' | 'secp256k1' | 'brainpoolP256r1' | 'brainpoolP384r1' | 'brainpoolP512r1'; interface GenerateKeyOptions { userIDs: MaybeArray; @@ -698,7 +713,7 @@ interface GenerateKeyOptions { } export type KeyOptions = GenerateKeyOptions; -interface SubkeyOptions { +export interface SubkeyOptions { type?: 'ecc' | 'rsa'; curve?: EllipticCurveName; rsaBits?: number; @@ -708,20 +723,20 @@ interface SubkeyOptions { config?: PartialConfig; } -declare class KeyID { +export declare class KeyID { bytes: string; equals(keyID: KeyID, matchWildcard?: boolean): boolean; toHex(): string; static fromID(hex: string): KeyID; } -interface DecryptMessageResult { +export interface DecryptMessageResult { data: MaybeStream; signatures: VerificationResult[]; filename: string; } -interface VerifyMessageResult = MaybeStream> { +export interface VerifyMessageResult = MaybeStream> { data: T; signatures: VerificationResult[]; } @@ -730,7 +745,7 @@ interface VerifyMessageResult = MaybeStream> { /** * Armor an OpenPGP binary packet block */ -export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, config?: Config): string; +export function armor(messagetype: enums.armor, body: object, partindex?: number, parttotal?: number, customComment?: string, emitChecksum?: boolean, config?: Config): string; /** * DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes @@ -740,44 +755,44 @@ export function unarmor(input: string, config?: Config): Promise<{ text: string, /* ############## v5 ENUMS #################### */ export namespace enums { - function read(type: typeof armor, e: armor): armorNames; - function read(type: typeof compression, e: compression): compressionNames; - function read(type: typeof hash, e: hash): hashNames; - function read(type: typeof packet, e: packet): packetNames; - function read(type: typeof publicKey, e: publicKey): publicKeyNames; - function read(type: typeof symmetric, e: symmetric): symmetricNames; - function read(type: typeof keyStatus, e: keyStatus): keyStatusNames; - function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames; + export function read(type: typeof armor, e: armor): armorNames; + export function read(type: typeof compression, e: compression): compressionNames; + export function read(type: typeof hash, e: hash): hashNames; + export function read(type: typeof packet, e: packet): packetNames; + export function read(type: typeof publicKey, e: publicKey): publicKeyNames; + export function read(type: typeof symmetric, e: symmetric): symmetricNames; + export function read(type: typeof keyStatus, e: keyStatus): keyStatusNames; + export function read(type: typeof keyFlags, e: keyFlags): keyFlagsNames; export type armorNames = 'multipartSection' | 'multipartLast' | 'signed' | 'message' | 'publicKey' | 'privateKey'; - enum armor { + export enum armor { multipartSection = 0, multipartLast = 1, signed = 2, message = 3, publicKey = 4, privateKey = 5, - signature = 6, + signature = 6 } - enum reasonForRevocation { + export enum reasonForRevocation { noReason = 0, // No reason specified (key revocations or cert revocations) keySuperseded = 1, // Key is superseded (key revocations) keyCompromised = 2, // Key material has been compromised (key revocations) keyRetired = 3, // Key is retired and no longer used (key revocations) - userIDInvalid = 32, // User ID information is no longer valid (cert revocations) + userIDInvalid = 32 // User ID information is no longer valid (cert revocations) } export type compressionNames = 'uncompressed' | 'zip' | 'zlib' | 'bzip2'; - enum compression { + export enum compression { uncompressed = 0, zip = 1, zlib = 2, - bzip2 = 3, + bzip2 = 3 } - export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224'; - enum hash { + export type hashNames = 'md5' | 'sha1' | 'ripemd' | 'sha256' | 'sha384' | 'sha512' | 'sha224' | 'sha3_256' | 'sha3_512'; + export enum hash { md5 = 1, sha1 = 2, ripemd = 3, @@ -785,12 +800,14 @@ export namespace enums { sha384 = 9, sha512 = 10, sha224 = 11, + sha3_256 = 12, + sha3_512 = 14 } - export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' - | 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' - | 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket'; - enum packet { + export type packetNames = 'publicKeyEncryptedSessionKey' | 'signature' | 'symEncryptedSessionKey' | 'onePassSignature' | 'secretKey' | 'publicKey' | + 'secretSubkey' | 'compressed' | 'symmetricallyEncrypted' | 'marker' | 'literal' | 'trust' | 'userID' | 'publicSubkey' | 'userAttribute' | + 'symEncryptedIntegrityProtected' | 'modificationDetectionCode' | 'AEADEncryptedDataPacket'; + export enum packet { publicKeyEncryptedSessionKey = 1, signature = 2, symEncryptedSessionKey = 3, @@ -808,11 +825,11 @@ export namespace enums { userAttribute = 17, symEncryptedIntegrityProtectedData = 18, modificationDetectionCode = 19, - aeadEncryptedData = 20, + aeadEncryptedData = 20 } - export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsa' | 'aedh' | 'aedsa'; - enum publicKey { + export type publicKeyNames = 'rsaEncryptSign' | 'rsaEncrypt' | 'rsaSign' | 'elgamal' | 'dsa' | 'ecdh' | 'ecdsa' | 'eddsaLegacy' | 'aedh' | 'aedsa' | 'ed25519' | 'x25519' | 'ed448' | 'x448'; + export enum publicKey { rsaEncryptSign = 1, rsaEncrypt = 2, rsaSign = 3, @@ -820,32 +837,39 @@ export namespace enums { dsa = 17, ecdh = 18, ecdsa = 19, - /** @deprecated use `eddsaLegacy` instead */ - eddsa = 22, eddsaLegacy = 22, aedh = 23, aedsa = 24, + x25519 = 25, + x448 = 26, + ed25519 = 27, + ed448 = 28 } - enum curve { - p256 = 'p256', - p384 = 'p384', - p521 = 'p521', + export enum curve { + /** @deprecated use `nistP256` instead */ + p256 = 'nistP256', + nistP256 = 'nistP256', + /** @deprecated use `nistP384` instead */ + p384 = 'nistP384', + nistP384 = 'nistP384', + /** @deprecated use `nistP521` instead */ + p521 = 'nistP521', + nistP521 = 'nistP521', /** @deprecated use `ed25519Legacy` instead */ - ed25519 = 'ed25519', - ed25519Legacy = 'ed25519', + ed25519 = 'ed25519Legacy', + ed25519Legacy = 'ed25519Legacy', /** @deprecated use `curve25519Legacy` instead */ - curve25519 = 'curve25519', - curve25519Legacy = 'curve25519', + curve25519 = 'curve25519Legacy', + curve25519Legacy = 'curve25519Legacy', secp256k1 = 'secp256k1', brainpoolP256r1 = 'brainpoolP256r1', brainpoolP384r1 = 'brainpoolP384r1', brainpoolP512r1 = 'brainpoolP512r1' } - export type symmetricNames = 'plaintext' | 'idea' | 'tripledes' | 'cast5' | 'blowfish' | 'aes128' | 'aes192' | 'aes256' | 'twofish'; - enum symmetric { - plaintext = 0, + export type symmetricNames = 'idea' | 'tripledes' | 'cast5' | 'blowfish' | 'aes128' | 'aes192' | 'aes256' | 'twofish'; + export enum symmetric { idea = 1, tripledes = 2, cast5 = 3, @@ -853,31 +877,30 @@ export namespace enums { aes128 = 7, aes192 = 8, aes256 = 9, - twofish = 10, + twofish = 10 } export type keyStatusNames = 'invalid' | 'expired' | 'revoked' | 'valid' | 'noSelfCert'; - enum keyStatus { + export enum keyStatus { invalid = 0, expired = 1, revoked = 2, valid = 3, - noSelfCert = 4, + noSelfCert = 4 } - export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication' - | 'sharedPrivateKey'; - enum keyFlags { + export type keyFlagsNames = 'certifyKeys' | 'signData' | 'encryptCommunication' | 'encryptStorage' | 'splitPrivateKey' | 'authentication' | 'sharedPrivateKey'; + export enum keyFlags { certifyKeys = 1, signData = 2, encryptCommunication = 4, encryptStorage = 8, splitPrivateKey = 16, authentication = 32, - sharedPrivateKey = 128, + sharedPrivateKey = 128 } - enum signature { + export enum signature { binary = 0, text = 1, standalone = 2, @@ -896,17 +919,25 @@ export namespace enums { } export type aeadNames = 'eax' | 'ocb' | 'gcm'; - enum aead { + export enum aead { eax = 1, ocb = 2, experimentalGCM = 100 // Private algorithm } - export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime' - enum literal { + export type literalFormatNames = 'utf8' | 'binary' | 'text' | 'mime'; + export enum literal { binary = 98, text = 116, utf8 = 117, mime = 109 } + + export enum s2k { + simple = 0, + salted = 1, + iterated = 3, + argon2 = 4, + gnu = 101 + } } diff --git a/app/node_modules/openpgp/package.json b/app/node_modules/openpgp/package.json index d66004dca..d2a21b578 100644 --- a/app/node_modules/openpgp/package.json +++ b/app/node_modules/openpgp/package.json @@ -1,11 +1,11 @@ { "name": "openpgp", "description": "OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.", - "version": "5.11.2", + "version": "6.0.0", "license": "LGPL-3.0+", "homepage": "https://openpgpjs.org/", "engines": { - "node": ">= 8.0.0" + "node": ">= 18.0.0" }, "keywords": [ "crypto", @@ -13,13 +13,26 @@ "gpg", "openpgp" ], - "main": "dist/node/openpgp.min.js", + "main": "dist/node/openpgp.min.cjs", "module": "dist/node/openpgp.min.mjs", "browser": { - "./dist/node/openpgp.min.js": "./dist/openpgp.min.js", + "./dist/node/openpgp.min.cjs": "./dist/openpgp.min.js", "./dist/node/openpgp.min.mjs": "./dist/openpgp.min.mjs" }, + "exports": { + ".": { + "types": "./openpgp.d.ts", + "import": "./dist/node/openpgp.mjs", + "require": "./dist/node/openpgp.min.cjs", + "browser": "./dist/openpgp.min.mjs" + }, + "./lightweight": { + "types": "./openpgp.d.ts", + "browser": "./dist/lightweight/openpgp.min.mjs" + } + }, "types": "openpgp.d.ts", + "type": "module", "directories": { "lib": "src" }, @@ -28,74 +41,76 @@ "lightweight/", "openpgp.d.ts" ], - "esm": { - "cjs": { - "dedefault": true - } - }, "scripts": { "build": "rollup --config", "build-test": "npm run build --build-only=test", "prepare": "npm run build", - "test": "mocha --require esm --timeout 120000 test/unittests.js", - "test-type-definitions": "tsc test/typescript/definitions.ts && node test/typescript/definitions.js", + "test": "mocha --timeout 120000 test/unittests.js", + "test-type-definitions": "tsx test/typescript/definitions.ts", "benchmark-time": "node test/benchmarks/time.js", - "benchmark-memory-usage": "node --require esm test/benchmarks/memory_usage.js", - "start": "http-server", + "benchmark-memory-usage": "node test/benchmarks/memory_usage.js", "prebrowsertest": "npm run build-test", - "browsertest": "npm start -- -o test/unittests.html", - "test-browser": "karma start test/karma.conf.js", - "test-browserstack": "karma start test/karma.conf.js --browsers bs_safari_latest,bs_ios_14,bs_safari_13_1", - "coverage": "nyc npm test", + "browsertest": "web-test-runner --config test/web-test-runner.config.js --group local --manual --open", + "test-browser": "web-test-runner --config test/web-test-runner.config.js --group local --playwright --browsers chromium firefox webkit", + "test-browser:ci": "web-test-runner --config test/web-test-runner.config.js --group headless:ci", + "test-browserstack": "web-test-runner --config test/web-test-runner.browserstack.config.js", + "coverage": "c8 npm test", "lint": "eslint .", - "docs": "jsdoc --configure .jsdocrc.js --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME", + "docs": "jsdoc --configure .jsdocrc.cjs --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME", "preversion": "rm -rf dist docs node_modules && npm ci && npm test", "version": "npm run docs && git add -A docs", "postversion": "git push && git push --tags && npm publish" }, "devDependencies": { - "@openpgp/asmcrypto.js": "^2.3.2", - "@openpgp/elliptic": "^6.5.1", - "@openpgp/jsdoc": "^3.6.4", - "@openpgp/pako": "^1.0.12", + "@noble/ciphers": "^1.0.0", + "@noble/curves": "^1.6.0", + "@noble/hashes": "^1.5.0", + "@openpgp/jsdoc": "^3.6.11", "@openpgp/seek-bzip": "^1.0.5-git", - "@openpgp/tweetnacl": "^1.0.3", - "@openpgp/web-stream-tools": "0.0.11-patch-1", - "@rollup/plugin-commonjs": "^11.1.0", - "@rollup/plugin-node-resolve": "^7.1.3", - "@rollup/plugin-replace": "^2.3.2", - "@types/chai": "^4.2.14", + "@openpgp/tweetnacl": "^1.0.4-1", + "@openpgp/web-stream-tools": "~0.1.3", + "@rollup/plugin-alias": "^5.1.1", + "@rollup/plugin-commonjs": "^25.0.8", + "@rollup/plugin-node-resolve": "^15.3.0", + "@rollup/plugin-replace": "^5.0.7", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@rollup/plugin-wasm": "^6.2.2", + "@types/chai": "^4.3.19", + "@types/sinon": "^17.0.3", + "@typescript-eslint/parser": "^7.18.0", + "@web/test-runner": "^0.19.0", + "@web/test-runner-browserstack": "^0.7.2", + "@web/test-runner-mocha": "^0.9.0", + "@web/test-runner-playwright": "^0.11.0", + "argon2id": "^1.0.1", "benchmark": "^2.1.4", - "bn.js": "^4.11.8", - "chai": "^4.3.6", - "chai-as-promised": "^7.1.1", - "email-addresses": "3.1.0", - "eslint": "^8.34.0", + "bn.js": "^5.2.1", + "c8": "^8.0.1", + "chai": "^4.4.1", + "chai-as-promised": "^7.1.2", + "eckey-utils": "^0.7.14", + "eslint": "^8.57.1", "eslint-config-airbnb": "^19.0.4", "eslint-config-airbnb-base": "^15.0.0", - "eslint-plugin-chai-friendly": "^0.7.2", - "eslint-plugin-import": "^2.27.5", - "esm": "^3.2.25", - "hash.js": "^1.1.3", - "http-server": "^14.1.1", - "karma": "^6.4.0", - "karma-browserstack-launcher": "^1.6.0", - "karma-chrome-launcher": "^3.1.1", - "karma-firefox-launcher": "^2.1.2", - "karma-mocha": "^2.0.1", - "karma-mocha-reporter": "^2.2.5", - "karma-webkit-launcher": "^2.1.0", - "mocha": "^8.4.0", - "nyc": "^14.1.1", - "playwright": "^1.30.0", - "rollup": "^2.38.5", - "rollup-plugin-terser": "^7.0.2", - "sinon": "^4.3.0", - "typescript": "^4.1.2", - "web-streams-polyfill": "^3.2.0" + "eslint-config-airbnb-typescript": "^18.0.0", + "eslint-import-resolver-typescript": "^3.6.3", + "eslint-plugin-chai-friendly": "^0.7.4", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-unicorn": "^48.0.1", + "fflate": "^0.7.4", + "mocha": "^10.7.3", + "playwright": "^1.48.2", + "rollup": "^4.24.2", + "sinon": "^18.0.1", + "ts-node": "^10.9.2", + "tslib": "^2.8.0", + "tsx": "^4.19.2", + "typescript": "^5.6.3", + "web-streams-polyfill": "^4.0.0" }, - "dependencies": { - "asn1.js": "^5.0.0" + "overrides": { + "@web/dev-server-core": "npm:@openpgp/wtr-dev-server-core@0.7.3-patch.1" }, "repository": { "type": "git", diff --git a/app/node_modules/safer-buffer/LICENSE b/app/node_modules/safer-buffer/LICENSE deleted file mode 100644 index 4fe9e6f10..000000000 --- a/app/node_modules/safer-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Nikita Skovoroda - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/app/node_modules/safer-buffer/Porting-Buffer.md b/app/node_modules/safer-buffer/Porting-Buffer.md deleted file mode 100644 index 68d86bab0..000000000 --- a/app/node_modules/safer-buffer/Porting-Buffer.md +++ /dev/null @@ -1,268 +0,0 @@ -# Porting to the Buffer.from/Buffer.alloc API - - -## Overview - -- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) -- [Variant 2: Use a polyfill](#variant-2) -- [Variant 3: manual detection, with safeguards](#variant-3) - -### Finding problematic bits of code using grep - -Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. - -It will find all the potentially unsafe places in your own code (with some considerably unlikely -exceptions). - -### Finding problematic bits of code using Node.js 8 - -If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: - -- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. -- `--trace-deprecation` does the same thing, but only for deprecation warnings. -- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. - -You can set these flags using an environment variable: - -```console -$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' -$ cat example.js -'use strict'; -const foo = new Buffer('foo'); -$ node example.js -(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. - at showFlaggedDeprecation (buffer.js:127:13) - at new Buffer (buffer.js:148:3) - at Object. (/path/to/example.js:2:13) - [... more stack trace lines ...] -``` - -### Finding problematic bits of code using linters - -Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. - -There is a drawback, though, that it doesn't always -[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is -overriden e.g. with a polyfill, so recommended is a combination of this and some other method -described above. - - -## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. - -This is the recommended solution nowadays that would imply only minimal overhead. - -The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. - -What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: - -- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. -- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). -- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. - -Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than -`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended to avoid accidential unsafe Buffer API usage. - -There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) -for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. -Note that it currently only works with cases where the arguments are literals or where the -constructor is invoked with two arguments. - -_If you currently support those older Node.js versions and dropping them would be a semver-major change -for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) -or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive -the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and -your users will not observe a runtime deprecation warning when running your code on Node.js 10._ - - -## Variant 2: Use a polyfill - -Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older -Node.js versions. - -You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill -`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. - -Make sure that you do not use old `new Buffer` API — in any files where the line above is added, -using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. - -Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or -[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — -those are great, the only downsides being 4 deps in the tree and slightly more code changes to -migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only -`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. - -_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also -provides a polyfill, but takes a different approach which has -[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you -to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as -it is problematic, can cause issues in your code, and will start emitting runtime deprecation -warnings starting with Node.js 10._ - -Note that in either case, it is important that you also remove all calls to the old Buffer -API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides -a polyfill for the new API. I have seen people doing that mistake. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended. - -_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ - - -## Variant 3 — manual detection, with safeguards - -This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own -wrapper around them. - -### Buffer(0) - -This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which -returns the same result all the way down to Node.js 0.8.x. - -### Buffer(notNumber) - -Before: - -```js -var buf = new Buffer(notNumber, encoding); -``` - -After: - -```js -var buf; -if (Buffer.from && Buffer.from !== Uint8Array.from) { - buf = Buffer.from(notNumber, encoding); -} else { - if (typeof notNumber === 'number') - throw new Error('The "size" argument must be of type number.'); - buf = new Buffer(notNumber, encoding); -} -``` - -`encoding` is optional. - -Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not -hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the -Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous -security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create -problems ranging from DoS to leaking sensitive information to the attacker from the process memory. - -When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can -be omitted. - -Also note that using TypeScript does not fix this problem for you — when libs written in -`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as -all type checks are translation-time only and are not present in the actual JS code which TS -compiles to. - -### Buffer(number) - -For Node.js 0.10.x (and below) support: - -```js -var buf; -if (Buffer.alloc) { - buf = Buffer.alloc(number); -} else { - buf = new Buffer(number); - buf.fill(0); -} -``` - -Otherwise (Node.js ≥ 0.12.x): - -```js -const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); -``` - -## Regarding Buffer.allocUnsafe - -Be extra cautious when using `Buffer.allocUnsafe`: - * Don't use it if you don't have a good reason to - * e.g. you probably won't ever see a performance difference for small buffers, in fact, those - might be even faster with `Buffer.alloc()`, - * if your code is not in the hot code path — you also probably won't notice a difference, - * keep in mind that zero-filling minimizes the potential risks. - * If you use it, make sure that you never return the buffer in a partially-filled state, - * if you are writing to it sequentially — always truncate it to the actuall written length - -Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, -ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) -leaking to the remote attacker. - -_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js -version (and lacking type checks also adds DoS to the list of potential problems)._ - - -## FAQ - - -### What is wrong with the `Buffer` constructor? - -The `Buffer` constructor could be used to create a buffer in many different ways: - -- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained - *arbitrary memory* for performance reasons, which could include anything ranging from - program source code to passwords and encryption keys. -- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of - the string `'abc'`. A second argument could specify another encoding: For example, - `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original - sequence of bytes that it represents. -- There are several other combinations of arguments. - -This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell -what exactly the contents of the generated buffer are* without knowing the type of `foo`. - -Sometimes, the value of `foo` comes from an external source. For example, this function -could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: - -``` -function stringToBase64(req, res) { - // The request body should have the format of `{ string: 'foobar' }` - const rawBytes = new Buffer(req.body.string) - const encoded = rawBytes.toString('base64') - res.end({ encoded: encoded }) -} -``` - -Note that this code does *not* validate the type of `req.body.string`: - -- `req.body.string` is expected to be a string. If this is the case, all goes well. -- `req.body.string` is controlled by the client that sends the request. -- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: - - Before Node.js 8, the content would be uninitialized - - After Node.js 8, the content would be `50` bytes with the value `0` - -Because of the missing type check, an attacker could intentionally send a number -as part of the request. Using this, they can either: - -- Read uninitialized memory. This **will** leak passwords, encryption keys and other - kinds of sensitive information. (Information leak) -- Force the program to allocate a large amount of memory. For example, when specifying - `500000000` as the input value, each request will allocate 500MB of memory. - This can be used to either exhaust the memory available of a program completely - and make it crash, or slow it down significantly. (Denial of Service) - -Both of these scenarios are considered serious security issues in a real-world -web server context. - -when using `Buffer.from(req.body.string)` instead, passing a number will always -throw an exception instead, giving a controlled behaviour that can always be -handled by the program. - - -### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? - -Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still -widely used. This includes new code, and overall usage of such code has actually been -*increasing*. diff --git a/app/node_modules/safer-buffer/Readme.md b/app/node_modules/safer-buffer/Readme.md deleted file mode 100644 index 14b082290..000000000 --- a/app/node_modules/safer-buffer/Readme.md +++ /dev/null @@ -1,156 +0,0 @@ -# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] - -[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master -[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer -[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg -[npm-url]: https://npmjs.org/package/safer-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com -[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg -[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md - -Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. - -## How to use? - -First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. - -Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use -`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new -Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ - -Also, see the -[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. - -## Do I need it? - -Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that -is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` -though. - -See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) -for a better description. - -## Why not [safe-buffer](https://npmjs.com/safe-buffer)? - -_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and -itself contains footguns._ - -`safe-buffer` could be used safely to get the new API while still keeping support for older -Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API -I found out that `safe-buffer` is itself causing problems in some cases. - -For example, consider the following snippet: - -```console -$ cat example.unsafe.js -console.log(Buffer(20)) -$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js - -$ standard example.unsafe.js -standard: Use JavaScript Standard Style (https://standardjs.com) - /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. -``` - -This is allocates and writes to console an uninitialized chunk of memory. -[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people -to avoid using unsafe API. - -Let's now throw in `safe-buffer`! - -```console -$ cat example.safe-buffer.js -const Buffer = require('safe-buffer').Buffer -console.log(Buffer(20)) -$ standard example.safe-buffer.js -$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js - -``` - -See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior -remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out -chunks of uninitialized memory. -_And this code will still emit runtime warnings on Node.js 10.x and above._ - -That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or -emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some -discussion, it was decided to move my approach into a separate package, and _this is that separate -package_. - -This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, -«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. - -Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request -can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go -unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even -pass CI. _I also observed that being done in popular packages._ - -Some examples: - * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) - (a module with 548 759 downloads/month), - * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) - (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), - * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) - (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), - * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) - (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), - * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) - (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). - * And there are a lot more over the ecosystem. - -I filed a PR at -[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to -partially fix that (for cases when that lint rule is used), but it is a semver-major change for -linter rules and presets, so it would take significant time for that to reach actual setups. -_It also hasn't been released yet (2018-03-20)._ - -Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. -It still supports it with an explicit concern barier, by placing it under -`require('safer-buffer/dangereous')`. - -## But isn't throwing bad? - -Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like -unguarded `new Buffer()` calls that end up receiving user input can do. - -This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so -it is really simple to keep track of things and make sure that you don't mix old API usage with that. -Also, CI should hint anything that you might have missed. - -New commits, if tested, won't land new usage of unsafe Buffer API this way. -_Node.js 10.x also deals with that by printing a runtime depecation warning._ - -### Would it affect third-party modules? - -No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. -Don't do that. - -### But I don't want throwing… - -That is also fine! - -Also, it could be better in some cases when you don't comprehensive enough test coverage. - -In that case — just don't override `Buffer` and use -`var SaferBuffer = require('safer-buffer').Buffer` instead. - -That way, everything using `Buffer` natively would still work, but there would be two drawbacks: - -* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and - `SaferBuffer.alloc` instead. -* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. - -Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly -recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. - -## «Without footguns»? - -Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property -on older versions and duping things from there. You shouldn't do that in your code, probabably. - -The intention is to remove the most significant footguns that affect lots of packages in the -ecosystem, and to do it in the proper way. - -Also, this package doesn't protect against security issues affecting some Node.js versions, so for -usage in your own production code, it is still recommended to update to a Node.js version -[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/app/node_modules/safer-buffer/dangerous.js b/app/node_modules/safer-buffer/dangerous.js deleted file mode 100644 index ca41fdc54..000000000 --- a/app/node_modules/safer-buffer/dangerous.js +++ /dev/null @@ -1,58 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer -var safer = require('./safer.js') -var Safer = safer.Buffer - -var dangerous = {} - -var key - -for (key in safer) { - if (!safer.hasOwnProperty(key)) continue - dangerous[key] = safer[key] -} - -var Dangereous = dangerous.Buffer = {} - -// Copy Safer API -for (key in Safer) { - if (!Safer.hasOwnProperty(key)) continue - Dangereous[key] = Safer[key] -} - -// Copy those missing unsafe methods, if they are present -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (Dangereous.hasOwnProperty(key)) continue - Dangereous[key] = Buffer[key] -} - -if (!Dangereous.allocUnsafe) { - Dangereous.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return Buffer(size) - } -} - -if (!Dangereous.allocUnsafeSlow) { - Dangereous.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return buffer.SlowBuffer(size) - } -} - -module.exports = dangerous diff --git a/app/node_modules/safer-buffer/package.json b/app/node_modules/safer-buffer/package.json deleted file mode 100644 index d452b04ae..000000000 --- a/app/node_modules/safer-buffer/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "safer-buffer", - "version": "2.1.2", - "description": "Modern Buffer API polyfill without footguns", - "main": "safer.js", - "scripts": { - "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", - "test": "standard && tape tests.js" - }, - "author": { - "name": "Nikita Skovoroda", - "email": "chalkerx@gmail.com", - "url": "https://github.com/ChALkeR" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/ChALkeR/safer-buffer.git" - }, - "bugs": { - "url": "https://github.com/ChALkeR/safer-buffer/issues" - }, - "devDependencies": { - "standard": "^11.0.1", - "tape": "^4.9.0" - }, - "files": [ - "Porting-Buffer.md", - "Readme.md", - "tests.js", - "dangerous.js", - "safer.js" - ] -} diff --git a/app/node_modules/safer-buffer/safer.js b/app/node_modules/safer-buffer/safer.js deleted file mode 100644 index 37c7e1aa6..000000000 --- a/app/node_modules/safer-buffer/safer.js +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer diff --git a/app/node_modules/safer-buffer/tests.js b/app/node_modules/safer-buffer/tests.js deleted file mode 100644 index 7ed2777c9..000000000 --- a/app/node_modules/safer-buffer/tests.js +++ /dev/null @@ -1,406 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var test = require('tape') - -var buffer = require('buffer') - -var index = require('./') -var safer = require('./safer') -var dangerous = require('./dangerous') - -/* Inheritance tests */ - -test('Default is Safer', function (t) { - t.equal(index, safer) - t.notEqual(safer, dangerous) - t.notEqual(index, dangerous) - t.end() -}) - -test('Is not a function', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'object') - }); - [buffer].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'function') - }) - t.end() -}) - -test('Constructor throws', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer() }) - t.throws(function () { impl.Buffer(0) }) - t.throws(function () { impl.Buffer('a') }) - t.throws(function () { impl.Buffer('a', 'utf-8') }) - t.throws(function () { return new impl.Buffer() }) - t.throws(function () { return new impl.Buffer(0) }) - t.throws(function () { return new impl.Buffer('a') }) - t.throws(function () { return new impl.Buffer('a', 'utf-8') }) - }) - t.end() -}) - -test('Safe methods exist', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') - t.equal(typeof impl.Buffer.from, 'function', 'from') - }) - t.end() -}) - -test('Unsafe methods exist only in Dangerous', function (t) { - [index, safer].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') - }); - [dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'function') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') - }) - t.end() -}) - -test('Generic methods/properties are defined and equal', function (t) { - ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in buffer static methods/properties are inherited', function (t) { - Object.keys(buffer).forEach(function (method) { - if (method === 'SlowBuffer' || method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], buffer[method], method) - t.notEqual(typeof impl[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in Buffer static methods/properties are inherited', function (t) { - Object.keys(buffer.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('.prototype property of Buffer is inherited', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') - t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') - }) - t.end() -}) - -test('All Safer methods are present in Dangerous', function (t) { - Object.keys(safer).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], safer[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(safer.Buffer).forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], safer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Safe methods from Dangerous methods are present in Safer', function (t) { - Object.keys(dangerous).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], dangerous[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(dangerous.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], dangerous.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -/* Behaviour tests */ - -test('Methods return Buffers', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) - }) - t.end() -}) - -test('Constructor is buffer.Buffer', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) - t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) - t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) - }); - [0, 10, 100].forEach(function (arg) { - t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) - t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) - }) - t.end() -}) - -test('Invalid calls throw', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer.from(0) }) - t.throws(function () { impl.Buffer.from(10) }) - t.throws(function () { impl.Buffer.from(10, 'utf-8') }) - t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) - t.throws(function () { impl.Buffer.from(-10) }) - t.throws(function () { impl.Buffer.from(1e90) }) - t.throws(function () { impl.Buffer.from(Infinity) }) - t.throws(function () { impl.Buffer.from(-Infinity) }) - t.throws(function () { impl.Buffer.from(NaN) }) - t.throws(function () { impl.Buffer.from(null) }) - t.throws(function () { impl.Buffer.from(undefined) }) - t.throws(function () { impl.Buffer.from() }) - t.throws(function () { impl.Buffer.from({}) }) - t.throws(function () { impl.Buffer.alloc('') }) - t.throws(function () { impl.Buffer.alloc('string') }) - t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) - t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) - t.throws(function () { impl.Buffer.alloc(-10) }) - t.throws(function () { impl.Buffer.alloc(1e90) }) - t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) - t.throws(function () { impl.Buffer.alloc(Infinity) }) - t.throws(function () { impl.Buffer.alloc(-Infinity) }) - t.throws(function () { impl.Buffer.alloc(null) }) - t.throws(function () { impl.Buffer.alloc(undefined) }) - t.throws(function () { impl.Buffer.alloc() }) - t.throws(function () { impl.Buffer.alloc([]) }) - t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) - t.throws(function () { impl.Buffer.alloc({}) }) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.throws(function () { dangerous.Buffer[method]('') }) - t.throws(function () { dangerous.Buffer[method]('string') }) - t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) - t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) - t.throws(function () { dangerous.Buffer[method](Infinity) }) - if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { - t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') - } else { - t.throws(function () { dangerous.Buffer[method](-10) }) - t.throws(function () { dangerous.Buffer[method](-1e90) }) - t.throws(function () { dangerous.Buffer[method](-Infinity) }) - } - t.throws(function () { dangerous.Buffer[method](null) }) - t.throws(function () { dangerous.Buffer[method](undefined) }) - t.throws(function () { dangerous.Buffer[method]() }) - t.throws(function () { dangerous.Buffer[method]([]) }) - t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) - t.throws(function () { dangerous.Buffer[method]({}) }) - }) - t.end() -}) - -test('Buffers have appropriate lengths', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).length, 0) - t.equal(impl.Buffer.alloc(10).length, 10) - t.equal(impl.Buffer.from('').length, 0) - t.equal(impl.Buffer.from('string').length, 6) - t.equal(impl.Buffer.from('string', 'utf-8').length, 6) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) - t.equal(impl.Buffer.from([0, 42, 3]).length, 3) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) - t.equal(impl.Buffer.from([]).length, 0) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.equal(dangerous.Buffer[method](0).length, 0) - t.equal(dangerous.Buffer[method](10).length, 10) - }) - t.end() -}) - -test('Buffers have appropriate lengths (2)', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true; - [ safer.Buffer.alloc, - dangerous.Buffer.allocUnsafe, - dangerous.Buffer.allocUnsafeSlow - ].forEach(function (method) { - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 1e5) - var buf = method(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - } - }) - t.ok(ok) - t.end() -}) - -test('.alloc(size) is zero-filled and has correct length', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = index.Buffer.alloc(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = dangerous.Buffer[method](length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - buf.fill(0, 0, length) - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1, 0, length) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok, method) - }) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) - t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) - - var tmp = new buffer.Buffer(2) - tmp.fill('ok') - if (tmp[1] === tmp[0]) { - // Outdated Node.js - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) - } else { - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) - } - t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) - - t.end() -}) - -test('safer.Buffer.from returns results same as Buffer constructor', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) - t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) - t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) - t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) - t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) - }) - t.end() -}) - -test('safer.Buffer.from returns consistent results', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) - t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) - }) - t.end() -}) diff --git a/app/package-lock.json b/app/package-lock.json index a617f1048..8738ed8f2 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,67 +1,29 @@ { - "name": "site", + "name": "app", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "dependencies": { "humbleicons": "^1.9.0", - "openpgp": "^5.11.2" + "openpgp": "^6.0.0" } }, - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "license": "MIT", - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", - "license": "MIT" - }, "node_modules/humbleicons": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/humbleicons/-/humbleicons-1.10.0.tgz", "integrity": "sha512-+9kIQEa5+aJz+0Aw5gm2hShu59ov9gzT1+x0MZGsDdSlsMeabZ91VBav/zogHA6DywvUDUvXRLn0FOeTnfHyeQ==", "license": "MIT" }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "license": "ISC" - }, "node_modules/openpgp": { - "version": "5.11.2", - "resolved": "https://registry.npmjs.org/openpgp/-/openpgp-5.11.2.tgz", - "integrity": "sha512-f8dJFVLwdkvPvW3VPFs6q9Vs2+HNhdvwls7a/MIFcQUB+XiQzRe7alfa3RtwfGJU7oUDDMAWPZ0nYsHa23Az+A==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/openpgp/-/openpgp-6.0.0.tgz", + "integrity": "sha512-8YMuhOV6bP8+J4bCHltvRwol1sBJhxAcJXvwEKpcK65lKpQ0VUbymQR/EuGrzxYnatNSyMyrMgip4j/F0vhZvg==", "license": "LGPL-3.0+", - "dependencies": { - "asn1.js": "^5.0.0" - }, "engines": { - "node": ">= 8.0.0" + "node": ">= 18.0.0" } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" } } } diff --git a/app/package.json b/app/package.json index e44067ec6..1c591019a 100644 --- a/app/package.json +++ b/app/package.json @@ -1,6 +1,6 @@ { "dependencies": { "humbleicons": "^1.9.0", - "openpgp": "^5.11.2" + "openpgp": "^6.0.0" } }